@robota-sdk/agent-cli 3.0.0-beta.99 → 3.0.0
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 +2175 -8
- package/dist/node/bin.js +22 -22
- package/dist/node/cli-core-Bz_5Fzj0.js +2920 -0
- package/dist/node/desktop-host.js +1 -1
- package/dist/node/headless.js +2 -2
- package/dist/node/host.d.ts +1 -1
- package/dist/node/host.js +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.js +2 -2
- package/dist/node/index.js.map +1 -1
- package/dist/node/node-BsDZQcvi.js +67 -0
- package/dist/node/node-Ct446qHg.js +15 -0
- package/dist/node/node-Ct446qHg.js.map +1 -0
- package/dist/node/node-DdB-oeq6.js +100 -0
- package/dist/node/node-DdB-oeq6.js.map +1 -0
- package/dist/node/node-PhNl8kvo.js +15 -0
- package/dist/node/node-gdZ0H7su.js +100 -0
- package/dist/node/node-oHeP4vDn.js +67 -0
- package/dist/node/node-oHeP4vDn.js.map +1 -0
- package/dist/node/product-host-BPPyJk9w.js +2954 -0
- package/dist/node/product-host-BPPyJk9w.js.map +1 -0
- package/dist/node/{product-host-DYR8lHfh.d.ts → product-host-SaMRTzxB.d.ts} +3 -3
- package/dist/node/{product-host-DYR8lHfh.d.ts.map → product-host-SaMRTzxB.d.ts.map} +1 -1
- package/dist/node/src-B9UMvThT-B-MlnUJH.js +2 -0
- package/dist/node/src-B9UMvThT-Cvs0M0_E.js +2 -0
- package/dist/node/src-B9UMvThT-Cvs0M0_E.js.map +1 -0
- package/dist/node/src-BzaNFPZx-CIKPBZac.js +2 -0
- package/dist/node/src-BzaNFPZx-DAgH-EaI.js +2 -0
- package/dist/node/src-BzaNFPZx-DAgH-EaI.js.map +1 -0
- package/dist/node/src-DwAfU-9z-CalH1ynp.js +2 -0
- package/dist/node/{node-BIcfIxK2.js → src-DwAfU-9z-DOErKivb.js} +2 -2
- package/dist/node/src-DwAfU-9z-DOErKivb.js.map +1 -0
- package/dist/node/src-UPsd6jNY-CUahgEdL.js +2 -0
- package/dist/node/src-UPsd6jNY-CgN4wopU.js +2 -0
- package/dist/node/src-UPsd6jNY-CgN4wopU.js.map +1 -0
- package/package.json +43 -43
- package/dist/node/cli-core-CrauPvKn.js +0 -2920
- package/dist/node/node-BIcfIxK2.js.map +0 -1
- package/dist/node/node-BRvqhy29.js +0 -165
- package/dist/node/node-BRvqhy29.js.map +0 -1
- package/dist/node/node-BTKWbzr0.js +0 -15
- package/dist/node/node-BZfTvzcV.js +0 -15
- package/dist/node/node-BZfTvzcV.js.map +0 -1
- package/dist/node/node-CI_NCC-t.js +0 -2
- package/dist/node/node-zABT8WBL.js +0 -165
- package/dist/node/product-host-DmP4TgQl.js +0 -2954
- package/dist/node/product-host-DmP4TgQl.js.map +0 -1
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
;(function(){var v=parseInt(process.versions.node.split('.')[0],10);if(v<22){process.stderr.write('\n✗ Node.js 22+ is required (current: '+process.version+')\n\nUpgrade:\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22\n Download: https://nodejs.org/en/download\n\n');process.exit(1);}})();
|
|
2
|
+
import{Bt as e,N as t,U as n,b as r,jt as i,p as a,rt as o}from"./node-PhNl8kvo.js";import{_ as s,l as c,r as l,s as u,w as d}from"./bounded-output-BdWv9SX3-C4ucXwLR.js";import{l as f,s as p}from"./node-gdZ0H7su.js";import{spawn as m,spawnSync as h}from"node:child_process";import{chmodSync as g,closeSync as _,constants as v,cpSync as y,createReadStream as ee,existsSync as te,fstatSync as ne,fsyncSync as re,lstatSync as ie,mkdirSync as ae,readFileSync as oe,readSync as se,readdirSync as ce,readlinkSync as le,realpathSync as ue,renameSync as de,rmSync as fe,statSync as pe,symlinkSync as me,writeFileSync as he}from"node:fs";import{basename as ge,dirname as _e,isAbsolute as ve,join as ye,posix as be,relative as xe,resolve as b,sep as Se}from"node:path";import{randomBytes as Ce,randomUUID as we}from"node:crypto";import{open as Te,readFile as Ee,readdir as De,readlink as Oe,realpath as ke,stat as x}from"node:fs/promises";import{homedir as Ae,tmpdir as je}from"node:os";import{z as S}from"zod";import{EventEmitter as Me}from"node:events";import{Worker as Ne}from"node:worker_threads";import*as C from"koffi";import Pe from"fast-glob";import Fe from"p-limit";const Ie=2e3,Le=process.platform===`win32`;function w(e){return e.exitCode!==null||e.signalCode!==null}function Re(e,t,n){if(n&&!Le&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function ze(e,t){if(Le&&typeof e.pid==`number`){h(`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(!w(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(w(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),w(e)){e.removeListener(`exit`,o),t();return}Re(e,r,i),a=setTimeout(()=>{w(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(C.os.errno))if(n===e)return t;return`ERRNO_${e}`}function A(e){let t=v.O_CLOEXEC??(process.platform===`darwin`?He:Ue);return v.O_RDONLY|v.O_NOFOLLOW|v.O_NONBLOCK|t|(e?v.O_DIRECTORY:0)}function j(e,t){try{return ne(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=C.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(C.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=C.errno();if(e===C.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,he(c,t,`utf8`),f!==void 0&&this.setMode(c,Number(f.mode&BigInt(4095))),re(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&&C.errno()===C.os.errno.ENOENT){let{mkdirAt:n}=M();if(n(r,t[e],511)<0){let t=C.errno();t!==C.os.errno.EEXIST&&this.throwOpenFailure(t,`create-directory`,e)}o=this.openAt(r,t[e],A(!0),0)}o<0&&this.throwOpenFailure(C.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(C.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=C.errno();if(e===C.os.errno.ENOENT||r&&(e===C.os.errno.ELOOP||e===C.os.errno.ENOTDIR||e===C.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=v.O_CLOEXEC??(process.platform===`darwin`?He:Ue),r=v.O_WRONLY|v.O_CREAT|v.O_EXCL|v.O_NOFOLLOW|n;for(let n=0;n<32;n+=1){let n=`.atomic-tmp-${Ce(16).toString(`hex`)}`,i=this.openAt(e,n,r,t);if(i>=0)return{descriptor:i,name:n};let a=C.errno();a!==C.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(C.errno())})}renameWithoutReplacement(e,t,n){if(M().noReplaceAt(e,t,e,n)>=0)return;let r=C.errno();throw r===C.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(C.errno())})}unlink(e,t,n){if(M().unlinkAt(e,t,0)>=0)return;let r=C.errno();if(!(n&&r===C.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=se(e,a,o,Math.min(1048576,i-o),o);if(t===0)break;o+=t,n.afterReadChunk?.(o)}let s=se(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===C.os.errno.ELOOP||e===C.os.errno.ENOTDIR||e===C.os.errno.EISDIR?E(`UNSAFE_ENTRY`,t,i):E(`HOST_IO`,t,i)}closeDescriptor(e){try{_(e)}catch{}}closeOptionalDescriptor(e){e!==void 0&&this.closeDescriptor(e)}};function Ze(){let e=C.pointer(`ConversationAgentStableFileHandle`,C.opaque()),t=C.struct(`ConversationAgentUnicodeString`,{Length:`uint16_t`,MaximumLength:`uint16_t`,Buffer:C.pointer(`char16_t`)});return{handleType:e,unicodeStringType:t,objectAttributesType:C.struct(`ConversationAgentObjectAttributes`,{Length:`uint32_t`,RootDirectory:e,ObjectName:C.pointer(t),Attributes:`uint32_t`,SecurityDescriptor:`void *`,SecurityQualityOfService:`void *`}),ioStatusBlockType:C.struct(`ConversationAgentIoStatusBlock`,{Status:`intptr_t`,Information:`uintptr_t`}),attributeTagInfoType:C.struct(`ConversationAgentFileAttributeTagInfo`,{FileAttributes:`uint32_t`,ReparseTag:`uint32_t`}),fileIdInfoType:C.struct(`ConversationAgentFileIdInfo`,{VolumeSerialNumber:`uint64_t`,FileId:C.array(`uint8_t`,16,`Typed`)}),standardInfoType:C.struct(`ConversationAgentFileStandardInfo`,{AllocationSize:`int64_t`,EndOfFile:`int64_t`,NumberOfLinks:`uint32_t`,DeletePending:`uint8_t`,Directory:`uint8_t`}),renameInfoType:C.struct(`ConversationAgentFileRenameInfo`,{ReplaceIfExists:`uint8_t`,RootDirectory:e,FileNameLength:`uint32_t`,FileName:C.array(`uint16_t`,256,`Typed`)}),dispositionInfoType:C.struct(`ConversationAgentFileDispositionInfo`,{DeleteFile:`uint8_t`})}}function Qe(e,t){return{createFileW:e.func(`CreateFileW`,t.handleType,[C.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,C.out(C.pointer(`int64_t`))]),readFile:e.func(`ReadFile`,`bool`,[t.handleType,C.out(C.pointer(`uint8_t`)),`uint32_t`,C.out(C.pointer(`uint32_t`)),`void *`]),writeFile:e.func(`WriteFile`,`bool`,[t.handleType,C.pointer(`uint8_t`),`uint32_t`,C.out(C.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`,C.out(C.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`,[C.out(C.pointer(t.handleType)),`uint32_t`,C.pointer(t.objectAttributesType),C.out(C.pointer(t.ioStatusBlockType)),`void *`,`uint32_t`,`uint32_t`,`uint32_t`,`uint32_t`,`void *`,`uint32_t`]),ntClose:e.func(`NtClose`,`int32_t`,[t.handleType])}}let tt;const nt=[];function rt(){if(tt!==void 0)return tt;let e=Ze(),t=C.load(`kernel32.dll`);nt.push(t);let n=C.load(`ntdll.dll`);return nt.push(n),tt={...e,...Qe(t,e),...et(n,e)},tt}const it=BigInt(`0`);function at(e){if(e instanceof Uint8Array||Array.isArray(e))return Buffer.from(e).toString(`hex`);throw E(`UNSUPPORTED_BACKEND`,`decode-file-identity`)}function N(e){return`WIN32_${e.getLastError()}`}function ot(e,t,n){let r={};if(!e.getFileIdInfo(t,18,r,C.sizeof(e.fileIdInfoType)))throw E(`UNSUPPORTED_BACKEND`,n,{hostCode:N(e)});return{volume:BigInt(r.VolumeSerialNumber??it),fileId:at(r.FileId)}}function st(e,t,n,r){let i=lt(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=ct(e,t,o,r),c=[0];if(!e.readFile(t,Buffer.alloc(1),1,c,null))throw E(`HOST_IO`,`probe-file`,{hostCode:N(e)});let l=lt(e,t);if(c[0]!==0&&a>=n)throw E(`OVER_BUDGET`,`read-file`);if(!ut(i,l,s,a,c[0]))throw E(`FILE_CHANGED`,`read-file`);return o}function ct(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:N(e)});if(o[0]===0)break;i+=o[0],r.afterReadChunk?.(i)}return i}function lt(e,t){let n=ot(e,t,`inspect-file`),r=[it];if(!e.getFileSizeEx(t,r))throw E(`HOST_IO`,`inspect-file`,{hostCode:N(e)});return{...n,size:BigInt(r[0])}}function ut(e,t,n,r,i){return n===r&&i===0&&e.volume===t.volume&&e.fileId===t.fileId&&e.size===t.size}const dt=new Set([3221225487,3221225524,3221225530]),ft=new Set([2147483693,3221225658,3221225731,3221226105,3221226763]);function P(e){let t=e>>>0;return{kind:dt.has(t)?`missing`:t===3221225525?`exists`:ft.has(t)?`unsafe`:`host-io`,hostCode:`NTSTATUS_0x${t.toString(16)}`}}const pt=BigInt(`-1`);function mt(e){if(e.length===0||e.length>255)throw E(`INVALID_PATH`,`validate-segments`)}function F(e){return e===null||BigInt.asIntN(64,e)===pt}var ht=class{api;constructor(){try{this.api=rt()}catch{throw E(`UNSUPPORTED_BACKEND`,`load-windows-backend`)}}openRoot(e){let t=this.api.createFileW(e,2147483648,7,null,3,35651584,null);if(F(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(F(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}}F(i)||this.close(i);let o=P(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(F(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}}F(r)||this.close(r);let a=P(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||F(r)){F(r)||this.close(r);let e=P(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(F(n))throw E(`HOST_IO`,`create-temporary`);try{return this.assertSafeHandle(n,!1,`inspect-temporary`),n}catch(e){throw this.close(n),e}}F(n)||this.close(n);let i=P(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=C.alloc(this.api.renameInfoType,1);try{let o={ReplaceIfExists:+!!r,RootDirectory:t,FileNameLength:Buffer.byteLength(n,`utf16le`),FileName:i};if(C.encode(a,this.api.renameInfoType,o),!this.api.setFileInformation(e,3,a,C.sizeof(this.api.renameInfoType)))throw E(`HOST_IO`,`commit-write`,{hostCode:this.lastErrorCode()})}finally{C.free(a)}}markForDeletion(e){let t=C.alloc(this.api.dispositionInfoType,1);try{C.encode(t,this.api.dispositionInfoType,{DeleteFile:1}),this.api.setFileInformation(e,4,t,C.sizeof(this.api.dispositionInfoType))}catch{}finally{C.free(t)}}readFile(e,t,n){return st(this.api,e,t,n)}queryIdentity(e,t){return ot(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){mt(t);let i=C.alloc(this.api.unicodeStringType,1);try{C.encode(i,this.api.unicodeStringType,{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(`${t}\0`,`utf16le`),Buffer:t});let a={Length:C.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{C.free(i)}}issueRelativeCreate(e,t,n,r){mt(t);let i=C.alloc(this.api.unicodeStringType,1);try{C.encode(i,this.api.unicodeStringType,{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(`${t}\0`,`utf16le`),Buffer:t});let a={Length:C.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{C.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,C.sizeof(this.api.attributeTagInfoType))||!this.api.getStandardInfo(e,1,a,C.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 N(this.api)}};function I(e,t){return e.volume===t.volume&&e.fileId===t.fileId}var gt=class{native=new ht;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,m=!1;try{let h=this.openWriteParent(r,i,n);o=h.handle,s=h.owned,d=this.native.openReplacementTarget(o,a,e.length-1),d!==void 0&&(f=this.native.queryIdentity(d,`inspect-existing`));let g=this.createTemporaryFile(o);c=g.handle,l=g.name,this.native.writeUtf8(c,t);let _=this.native.queryIdentity(c,`inspect-temporary`);n.afterTemporaryWritten?.(g.name),this.assertDirectoryChain(r,i,h.identities),n.afterPreCommitValidated?.(),d!==void 0&&f!==void 0&&(p=`.atomic-backup-${Ce(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 v=this.native.openRelative(o,a,!0,e.length-1);if(v===void 0)throw E(`FILE_CHANGED`,`commit-write`);try{if(!I(this.native.queryIdentity(v,`inspect-target`),_))throw E(`FILE_CHANGED`,`commit-write`)}finally{this.native.close(v)}this.assertDirectoryChain(r,i,h.identities),this.assertRootIdentity(r),m=!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&&(m&&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(!I(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-${Ce(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(!I(this.native.queryIdentity(r,`inspect-named-entry`),n))throw E(`FILE_CHANGED`,`inspect-named-entry`)}finally{this.native.close(r)}}assertRootIdentity(e){if(!I(this.native.queryIdentity(e,`inspect-root`),this.rootIdentity))throw E(`ROOT_CHANGED`,`inspect-root`)}};const _t=new Set([`darwin-arm64`,`darwin-x64`,`linux-arm64`,`linux-x64`,`win32-x64`]);function vt(e){let t=`${process.platform}-${process.arch}`;if(!_t.has(t))throw E(`UNSUPPORTED_BACKEND`,`select-backend`,{hostCode:t});return process.platform===`win32`?new gt(e):new Xe(e)}function yt(e){if(typeof e!=`string`||e.trim().length===0||e.includes(`\0`))throw E(`INVALID_PATH`,`validate-root`);return b(e)}function bt(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 xt(e){if(!Number.isSafeInteger(e)||e<0)throw E(`INVALID_PATH`,`validate-budget`)}const St=new FinalizationRegistry(e=>{e.close()});var Ct=class{hooks;backend;finalizerToken={};constructor(e,t){this.hooks=t;let n=vt(yt(e));this.backend=n,St.register(this,n,this.finalizerToken)}writeUtf8(e,t){let n=this.backend;if(n===void 0)throw E(`AUTHORITY_CLOSED`,`write`);if(bt(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,St.unregister(this.finalizerToken);try{e.close()}catch(e){throw e instanceof T?e:E(`HOST_IO`,`close`)}}}[Symbol.dispose](){this.close()}};function wt(e){return new Ct(e,{})}const Tt=new FinalizationRegistry(e=>{e.close()});function Et(e,t){bt(e),xt(t)}var Dt=class{hooks;backend;finalizerToken={};constructor(e,t){this.hooks=t;let n=vt(yt(e));this.backend=n,Tt.register(this,n,this.finalizerToken)}readBytes(e,t){let n=this.backend;if(n===void 0)throw E(`AUTHORITY_CLOSED`,`read`);Et(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,Tt.unregister(this.finalizerToken);try{e.close()}catch(e){throw e instanceof T?e:E(`HOST_IO`,`close`)}}}[Symbol.dispose](){this.close()}};function Ot(e){return new Dt(e,{})}function kt(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 At(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 jt(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 Mt=class{sandbox;generation=0;restoring=!1;connectSandbox;createSandboxFromSnapshot;constructor(e){At(e.sandbox),this.sandbox=e.sandbox,this.connectSandbox=e.connectSandbox,this.createSandboxFromSnapshot=e.createSandboxFromSnapshot}async run(e,t){return jt(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 kt(t.snapshotId??t.id)}let t=kt(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{kt(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(At(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 Nt(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function Pt(e){return Nt(e)===`sandbox-separate`}function Ft(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 It=/^[A-Za-z]:[\\/]/,Lt=/'/g;async function Rt(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);Ft(t);let r=Xt(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=zt(a),s=Zt(r,t);i.push(await Bt(e,t,s,r,o,n))}return{entries:i}}function zt(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(`\\`)||It.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 Bt(e,t,n,r,i,a){switch(i.type){case`file`:return await Gt(e,n,r,i.content),L(t,i.type);case`dir`:return await Kt(e,n),L(t,i.type);case`localFile`:return await Vt(e,i.src,n,r,a),L(t,i.type);case`localDir`:return await Ht(e,i.src,n,a),L(t,i.type);case`gitRepo`:return await Wt(e,i,n),L(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 L(e,t){return{path:e,type:t,status:`applied`}}async function Vt(e,t,n,r,i){await Gt(e,n,r,await Ee(Jt(t,i.hostRoot),`utf8`))}async function Ht(e,t,n,r){await Ut(e,Jt(t,r.hostRoot),n)}async function Ut(e,t,n){await Kt(e,n);let r=await De(t,{withFileTypes:!0});for(let i of r){let r=ye(t,i.name),a=Zt(n,i.name);if(i.isDirectory()){await Ut(e,r,a);continue}if(i.isFile()){let t=await Ee(r,`utf8`);await e.writeFile(a,t)}}}async function Wt(e,t,n){await qt(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${R(t.ref)}`:``} ${R(t.url)} ${R(n)}`)}async function Gt(e,t,n,r){let i=be.dirname(t);i!==n&&await Kt(e,i),await e.writeFile(t,r)}async function Kt(e,t){await qt(e,`mkdir -p ${R(t)}`)}async function qt(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 Jt(e,t){return ve(e)?b(e):b(t??process.cwd(),e)}function Yt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function Xt(e){let t=Yt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Zt(e,t){let n=Xt(e);return n===`/`?`/${t}`:`${n}/${t}`}function R(e){return`'${e.replace(Lt,`'\\''`)}'`}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(`
|
|
3
|
+
`)}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=h(e,[...t],{timeout:5e3,encoding:`utf8`});if(n.error!==void 0)return{ok:!1,detail:n.error.message};let r=(n.stderr??``).trim().split(`
|
|
4
|
+
`)[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 ue(e)}catch{return e}}function fn(e){try{return pe(e).isDirectory()}catch{return!1}}function pn(e){let t=ie(e);if(!t.isSymbolicLink()&&(g(e,t.mode|448),t.isDirectory()))for(let t of ce(e))pn(`${e}/${t}`)}function mn(e){try{return ie(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(!ve(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??Ae(),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`)||ae(`${this.root}/${this.projectStateDirectory}`,{recursive:!0});let a=tn({policy:n,exists:e=>te(e)&&!mn(e),listDirectory:e=>ce(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 ie(t).isSymbolicLink()?{path:t,kind:`symlink`,target:le(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=ue(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()}-${we()}`,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`&&me(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}/${ge(e)}`;ae(t,{recursive:!0});try{de(e,n)}catch(t){if(this.inFlight>0)throw t;pn(e),t.code===`EXDEV`?(y(e,n,{recursive:!0,verbatimSymlinks:!0}),fe(e,{recursive:!0,force:!0})):de(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return dn(ve(t)?t:b(this.root,t))},t=[...new Set([je(),`/tmp`].filter(te).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=m(i.command,[...i.args],{cwd:i.cwd,stdio:[`ignore`,`pipe`,`pipe`,...r.map(()=>`pipe`)],...t.timeoutMs===void 0?{}:{timeout:t.timeoutMs}})}catch(e){i.afterExit?.(),n(e instanceof Error?e:Error(String(e)));return}r.forEach((e,t)=>{let n=a.stdio[t+3];n?.on(`error`,()=>void 0),n?.end(Buffer.from(e))});let o=``,s=``;a.stdout?.on(`data`,e=>o+=e.toString()),a.stderr?.on(`data`,e=>s+=e.toString()),a.on(`error`,e=>{i.afterExit?.(),n(e)}),a.on(`close`,t=>{let n=i.afterExit?.();e({stdout:n===void 0?o:`${o}\n${n}`,...s?{stderr:s}:{},exitCode:t??1})})})}readFile(e){return Promise.resolve(oe(e,`utf8`))}writeFile(e,t){return he(e,t,`utf8`),Promise.resolve()}};const _n=S.discriminatedUnion(`success`,[S.object({success:S.literal(!0),output:S.string()}),S.object({success:S.literal(!1),output:S.string(),error:S.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=S.object({activeFiles:S.array(S.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:S.array(S.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:S.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(`
|
|
5
|
+
`)}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=S.enum([`left`,`right`,`middle`]),Dn=S.object({x:S.number(),y:S.number()}),On=S.object({type:S.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:S.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:S.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:En.optional().describe(`Mouse button (click/double_click/drag).`),text:S.string().optional().describe(`Text to type (type).`),keys:S.array(S.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:S.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:S.number().optional().describe(`Vertical wheel delta (scroll).`),path:S.array(Dn).optional().describe(`Points to drag through (drag).`),ms:S.number().optional().describe(`Milliseconds to wait (wait).`),reason:S.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),kn=S.object({action:On.describe(`The single mutating action to perform.`)}),An=S.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(`
|
|
6
|
+
`)}const G=process.platform!==`win32`,zn=2e6,Bn=e=>`owner_gone=0; trap 'owner_gone=1' TERM; (trap "" TERM; while IFS= read -r line; do :; done; kill -TERM "-$$" 2>/dev/null; sleep 2; kill -KILL "-$$" 2>/dev/null) <&${e} >/dev/null 2>&1 & watcher=$!; (trap - TERM; exec "\$@" </dev/null) & command=\$!; wait "\$command"; status=\$?; if [ "\$owner_gone" -eq 0 ]; then kill -KILL "\$watcher" 2>/dev/null; else wait "\$watcher"; fi; exit "\$status"`,Vn=S.object({command:S.string().describe(`The shell command to execute`),timeout:S.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:S.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});async function Hn(e,t,n,r){try{let i=await r.sandboxClient.run(e,{timeoutMs:t,workingDirectory:n}),a={success:!0,output:i.stderr?`${i.stdout}\nstderr:\n${i.stderr}`:i.stdout,exitCode:i.exitCode};return JSON.stringify(a)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}async function Un(e,t,n,r,i){let{command:a,timeout:o=12e4,workingDirectory:s}=e,c=Math.min(o,6e5),d=s??t.cwd;if(d===void 0)return JSON.stringify({success:!1,output:``,error:"Shell tool has no working directory: it was constructed without a `cwd` (ARCH-010). This is an assembly bug — the tool would otherwise run in whatever directory the host process was started in."});if(t.sandboxClient&&t.sandboxClient.wrapCommand===void 0)return Hn(a,c,s??t.cwd,t);let f={command:n.command,args:n.commandArgs(a),cwd:d},p=t.sandboxClient?.wrapCommand?.(f,a)??f,h=!1,g=()=>{if(!h){h=!0;try{return p.afterExit?.()}catch(e){return`[sandbox] clean-up failed: ${e instanceof Error?e.message:String(e)}`}}};return r?.aborted?(g(),JSON.stringify({success:!1,output:``,error:`Aborted before start`})):new Promise(e=>{let t=l({maxBytes:zn}),n=l({maxBytes:zn}),a=!1,o=!1,s,d=3+(p.inputDescriptors?.length??0);try{s=m(G?`/bin/sh`:p.command,G?[`-c`,Bn(d),`shell-owner-watchdog`,p.command,...p.args]:[...p.args],{cwd:p.cwd,env:i===void 0?process.env:u(process.env,i),stdio:[`pipe`,`pipe`,`pipe`,...(p.inputDescriptors??[]).map(()=>`pipe`),...G?[`pipe`]:[]],detached:G})}catch(t){let n=g(),r=t instanceof Error?t.message:String(t);e(JSON.stringify({success:!1,output:n??``,error:r}));return}let f=G?s.stdio[d]:void 0;f?.on(`error`,()=>void 0),(p.inputDescriptors??[]).forEach((e,t)=>{let n=s.stdio[t+3];n?.on(`error`,()=>void 0),n?.end(Buffer.from(e))}),s.stdin?.end(),s.stdout?.on(`data`,e=>{t.append(e)}),s.stderr?.on(`data`,e=>{n.append(e)});let h=setTimeout(()=>{a=!0,Be(s,{processGroup:G}),_({success:!1,output:t.toString(),error:`Command timed out after ${c}ms`})},c);function _(t){o||(o=!0,clearTimeout(h),r?.removeEventListener(`abort`,v),e(JSON.stringify(t)))}function v(){Be(s,{processGroup:G}),_({success:!1,output:t.toString(),error:`Aborted`})}r?.addEventListener(`abort`,v,{once:!0}),s.on(`error`,e=>{s.pid===void 0&&g(),_({success:!1,output:``,error:e.message})}),s.on(`close`,e=>{s.stdin?.end(),f?.end();let r=g();if(a){_({success:!1,output:t.toString(),error:`Command timed out after ${c}ms`,exitCode:e??void 0});return}let i=t.toString(),o=n.toString(),l=e??0,u=o?`${i}\nstderr:\n${o}`:i;_({success:!0,output:r===void 0?u:`${u}\n${r}`,exitCode:l})})})}function Wn(e,t){let n=d({executable:t.shellExecutable});return H(e,t.description??Rn(n,t.availableTools),Vn,async(e,r)=>Un(e,t,n,r?.signal,r?.shellTraceEnv),{resultMode:`invocation-json`})}function Gn(e){return Wn(`Shell`,e)}function Kn(e){return Wn(`Bash`,e)}function qn(e){let t=e.editorFiles?.();if(t?.pathAuthority===`stable-root`)return t?.readTextFile?.bind(t)}function Jn(e){let t=e.editorFiles?.();if(t?.pathAuthority===`stable-root`)return t?.writeTextFile?.bind(t)}function Yn(...e){let t=e.filter(e=>e!==void 0);return t.length>1?AbortSignal.any(t):t[0]}function K(e,t,n){let r={success:!1,output:``,error:`The editor could not ${e} ${t}: ${n instanceof Error?n.message:String(n)}`};return JSON.stringify(r)}function Xn(e,t){let n=t.editorFiles?.();return n?.readTextFile===void 0&&n?.writeTextFile===void 0?e:`${e}\n\n[Searched the files on disk. The editor may hold changes to them that are not saved yet, which this search does not see.${n.pathAuthority===`stable-root`&&n.readTextFile!==void 0?` Read returns a file as the editor has it.`:``}]`}function Zn(e,t){return t!==void 0&&p(t,e)}function Qn(e,t){return t===void 0?e:b(t,e)}function q(e,t){if(t===void 0){let t={success:!1,output:``,error:`Access denied: "${e}" cannot be checked because no containment root is configured for this tool. This is an assembly bug, not a path problem — the tool was constructed without a \`cwd\`, so it has no boundary to enforce (ARCH-010).`};return JSON.stringify(t)}if(!Zn(e,t)){let t={success:!1,output:``,error:`Access denied: "${e}" is outside the working directory`};return JSON.stringify(t)}}var J=class extends Error{};function $n(e,t){return t===e||t.startsWith(e.endsWith(Se)?e:e+Se)}async function er(e,t,n){let r=()=>new J(`Access denied: "${e}" is outside the working directory`);if(t===void 0)throw r();let i=await ke(t);if(process.platform===`darwin`){let t=await ke(e);if(!$n(i,t))throw r();try{return await Te(t,n|536870912,384)}catch(e){throw e.code===`ELOOP`?r():e}}let a=await Te(e,n,384);if(process.platform!==`linux`)return a;let o;try{o=await Oe(`/proc/self/fd/${a.fd}`)}catch{throw await a.close(),new J(`Access denied: "${e}" cannot be confirmed inside the working directory without /proc`)}if($n(i,o))return a;throw await a.close(),r()}function tr(e,t){if(t===void 0)return{root:``,error:q(e??``,void 0)};let n=e?b(t,e):t;return{root:n,error:q(n,t)}}const nr=2e3,Y=4*1024*1024;var X=class extends c{boundary;constructor(e){super(`Read ${e} exceeds its UTF-8 byte limit`,`Read`),this.boundary=e}},Z=class extends c{constructor(){super(`Read cancelled`,`Read`)}};const rr=S.object({filePath:S.string().describe(`The absolute path to the file to read`),offset:S.number().optional().describe(`The line number to start reading from (1-based). Only provide if the file is too large to read at once`),limit:S.number().optional().describe(`The number of lines to read (default: ${nr}). Only provide if the file is too large to read at once`)});function ir(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function ar(e,t){let n=t+e.length-1,r=String(n).length;return e.map((e,n)=>`${String(t+n).padStart(r,` `)}\t${e}`).join(`
|
|
7
|
+
`)}function or(e,t,n,r){let i=[],a=0,o=0,s=0,c=Math.trunc(n-1),l=Math.trunc(n-1+r);for(;s<t.length;){let e=t.indexOf(`
|
|
8
|
+
`,s),r=e===-1?t.length:e;if(o++,o>c&&o<=l){let e=t.slice(s,r);if(a+=Buffer.byteLength(e,`utf8`)+String(n+i.length).length+1,a>Y)throw new X(`output`);i.push(e)}if(e===-1)break;s=e+1}let u=i.length,d=u<o?`[File: ${e} (lines ${n}-${n+u-1} of ${o})]\n`:`[File: ${e} (${o} lines)]\n`,f=String(n+u-1).length,p=Buffer.byteLength(d,`utf8`)+Math.max(0,u-1);for(let e of i)p+=f+1+Buffer.byteLength(e,`utf8`);if(p>Y)throw new X(`output`);let m={success:!0,output:d+ar(i,n)};return JSON.stringify(m)}async function sr(e,t,n,r,i){let a;try{a=await e(t,i)}catch(e){if(i?.aborted)throw new Z;return K(`read`,t,e)}if(i?.aborted)throw new Z;if(Buffer.byteLength(a,`utf8`)>Y)throw new X(`input`);if(a.slice(0,8192).includes(`\0`)){let e={success:!1,output:``,error:`Binary file not supported: ${t}`};return JSON.stringify(e)}return or(t,a,n,r)}async function cr(e,t,n){if(t.signal?.aborted)throw new Z;let{offset:r,limit:i=nr}=e,a=t.sandboxClient?e.filePath:Qn(e.filePath,t.cwd),o=r!==void 0&&r>0?r:1;if(t.sandboxClient)try{let e=await t.sandboxClient.readFile(a);if(t.signal?.aborted)throw new Z;if(Buffer.byteLength(e,`utf8`)>Y)throw new X(`input`);return or(a,e,o,i)}catch(e){if(e instanceof X||e instanceof Z)throw e;let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let s=q(a,t.cwd);if(s!==void 0)return s;let c=qn(t);if(c!==void 0)return sr(c,a,o,i,Yn(t.signal,n));let l=e=>JSON.stringify({success:!1,output:``,error:e}),u;try{u=await er(a,t.cwd,v.O_RDONLY|v.O_NONBLOCK)}catch(e){if(e instanceof J)return l(e.message);let t=await x(a).catch(()=>void 0);return t===void 0?l(`File not found: ${a}`):t.isFile()?l(e instanceof Error?e.message:String(e)):l(`Path is not a file: ${a}`)}let d=Buffer.alloc(0),f=!1;try{if(!(await u.stat()).isFile())return l(`Path is not a file: ${a}`);let e=[],n=Buffer.allocUnsafe(65536),r=0,i=0;for(;r<=Y;){if(t.signal?.aborted)throw new Z;let{bytesRead:a}=await u.read(n,0,Math.min(n.length,4194305-r),null);if(a===0)break;let o=Math.min(a,8192-i);if(o>0&&ir(n.subarray(0,o))){f=!0;break}if(i+=o,r+=a,r>Y)throw new X(`input`);e.push(Buffer.from(n.subarray(0,a)))}f||(d=Buffer.concat(e,r))}catch(e){if(e instanceof X||e instanceof Z)throw e;return l(e instanceof Error?e.message:String(e))}finally{await u.close()}if(t.signal?.aborted)throw new Z;if(f){let e={success:!1,output:``,error:`Binary file not supported: ${a}`};return JSON.stringify(e)}return or(a,d.toString(`utf8`),o,i)}function lr(e){return H(`Read`,e.description??`Reads a file from the local filesystem.
|
|
9
|
+
|
|
10
|
+
By default, reads up to 2000 lines from the beginning of the file. You can optionally specify offset and limit for partial reads.
|
|
11
|
+
|
|
12
|
+
Results are returned using cat -n format, with line numbers starting at 1.
|
|
13
|
+
|
|
14
|
+
The filePath parameter must be an absolute path, not a relative path.`,rr,async(t,n)=>cr(t,e,n?.signal),{resultMode:`invocation-json`})}function ur(e,t){let n=xe(b(e),b(t));return n.length===0?[]:n.split(Se)}async function dr(e,t,n=_e(e)){let r=wt(n);try{r.writeUtf8(ur(n,e),t)}finally{r.close()}}const fr=S.object({filePath:S.string().describe(`The absolute path to the file to write`),content:S.string().describe(`The content to write to the file`)});async function pr(e,t,n){let r=Yn(t.signal,n);r?.throwIfAborted();let{content:i}=e,a=t.sandboxClient?e.filePath:Qn(e.filePath,t.cwd);if(!t.sandboxClient){let e=q(a,t.cwd);if(e!==void 0)return e}try{let e=t.sandboxClient?void 0:Jn(t);if(e!==void 0)try{await e(a,i,r)}catch(e){return K(`write`,a,e)}else t.sandboxClient?await t.sandboxClient.writeFile(a,i):await dr(a,i,t.cwd);let n={success:!0,output:`Written ${Buffer.byteLength(i,`utf8`)} bytes to ${a}`};return JSON.stringify(n)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}function mr(e){return H(`Write`,e.description??`Writes a file to the local filesystem. This will overwrite an existing file if one exists.
|
|
15
|
+
|
|
16
|
+
Prefer the Edit tool for modifying existing files — it only sends the changed text. Use this tool to create new files or for complete rewrites.
|
|
17
|
+
|
|
18
|
+
Parent directories are created automatically when missing.`,fr,async(t,n)=>pr(t,e,n?.signal),{resultMode:`invocation-json`})}const hr=S.object({filePath:S.string().describe(`The absolute path to the file to modify`),oldString:S.string().describe(`The text to replace (must be an exact match of existing content)`),newString:S.string().describe(`The text to replace it with (must be different from oldString)`),replaceAll:S.boolean().optional().describe(`Replace all occurrences of oldString (default: false). Useful for renaming variables`)}),Q=4*1024*1024,gr=64*1024;var _r=class extends Error{boundary;constructor(e){super(`Edit ${e} exceeds its ${Q}-byte limit`),this.boundary=e}};async function vr(e,t,n){let r=await er(e,t,v.O_RDONLY);try{let e=[],t=0,i=0,a=Buffer.allocUnsafe(Math.min(gr,n+1));for(;;){let{bytesRead:o}=await r.read(a,i,a.length-i,null);if(o===0){i>0&&e.push(a.subarray(0,i));break}if(t+=o,t>n)throw new _r(`input`);i+=o,i===a.length&&(e.push(a),i=0,a=Buffer.allocUnsafe(Math.min(gr,n-t+1)))}return Buffer.concat(e,t).toString(`utf8`)}finally{await r.close()}}async function yr(e,t,n){let r=Yn(t.signal,n);r?.throwIfAborted();let{oldString:i,newString:a,replaceAll:o=!1}=e,s=t.sandboxClient?e.filePath:Qn(e.filePath,t.cwd);if(!t.sandboxClient){let e=q(s,t.cwd);if(e!==void 0)return e}let c=t.sandboxClient?void 0:qn(t),l=t.sandboxClient?void 0:Jn(t),u;try{if(c!==void 0){try{u=await c(s,r)}catch(e){return r?.throwIfAborted(),K(`read`,s,e)}if(Buffer.byteLength(u,`utf8`)>Q)throw new _r(`input`)}else if(t.sandboxClient){if(u=await t.sandboxClient.readFile(s),Buffer.byteLength(u,`utf8`)>Q)throw new _r(`input`)}else u=await vr(s,t.cwd,Q)}catch(e){if(r?.throwIfAborted(),e instanceof _r){let t={success:!1,output:``,error:`${e.message}: ${s}`};return JSON.stringify(t)}if(e instanceof J)return JSON.stringify({success:!1,output:``,error:e.message});let t={success:!1,output:``,error:`File not found: ${s}`};return JSON.stringify(t)}if(r?.throwIfAborted(),!u.includes(i)){let e={success:!1,output:``,error:`oldString not found in file: ${s}`};return JSON.stringify(e)}let d=[];if(o)d=u.split(i);else if(u.indexOf(i)!==u.lastIndexOf(i)){let e={success:!1,output:``,error:`oldString is not unique in file (found ${u.split(i).length-1} occurrences). Provide more context to make it unique, or use replaceAll:true.`};return JSON.stringify(e)}let f=o?d.length-1:1,p=Buffer.byteLength(i,`utf8`),m=Buffer.byteLength(a,`utf8`);if(Buffer.byteLength(u,`utf8`)-f*p+f*m>Q){let e={success:!1,output:``,error:`Edit output exceeds its ${Q}-byte limit: ${s}`};return JSON.stringify(e)}let h=o?d.join(a):u.slice(0,u.indexOf(i))+a+u.slice(u.indexOf(i)+i.length);try{if(l!==void 0)try{await l(s,h,r)}catch(e){return K(`write`,s,e)}else t.sandboxClient?await t.sandboxClient.writeFile(s,h):await dr(s,h,t.cwd)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let g=u.indexOf(i),_=g>=0?u.substring(0,g).split(`
|
|
19
|
+
`).length:1,v={success:!0,output:`Replaced ${f} occurrence(s) in ${s}`,startLine:_};return JSON.stringify(v)}function br(e){return H(`Edit`,e.description??`Performs exact string replacements in files.
|
|
20
|
+
|
|
21
|
+
oldString must exactly match the file's current content, including whitespace and indentation — reading the file first (e.g. with a file-read tool) is the reliable way to copy exact text.
|
|
22
|
+
|
|
23
|
+
The edit will FAIL if oldString is not unique in the file. Either provide more surrounding context to make it unique, or set replaceAll to change every instance.`,hr,async(t,n)=>yr(t,e,n?.signal),{resultMode:`invocation-json`})}const xr=S.object({pattern:S.string().describe(`The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.tsx")`),path:S.string().optional().describe(`The directory to search in. Defaults to the current working directory. Must be a valid directory path if provided`),limit:S.number().optional().describe(`Maximum number of results to return (default: 1000). Use a smaller limit to save context space`)});async function Sr(e,t,n){let r=Fe(100);return(await Promise.all(e.map(e=>r(async()=>{let r=b(t,e);if(Zn(r,n))try{return{path:e,mtime:(await x(r)).mtimeMs}}catch{return{path:e,mtime:0}}})))).filter(e=>e!==void 0).sort((e,t)=>t.mtime-e.mtime)}async function Cr(e,t,n){let r=[],i=!1,a=Pe.stream(e,t);for await(let e of a){if(r.length>=n){i=!0;break}r.push(e)}return{matches:r,truncated:i}}async function wr(e,t,n=5e4){let{pattern:r,path:i}=e,a=t.cwd,{root:o,error:s}=tr(i,a);if(s)return s;let c;try{c=await Cr(r,{cwd:o,ignore:[`**/node_modules/**`,`**/.git/**`],dot:!0,absolute:!1,followSymbolicLinks:!1},n)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let{matches:l,truncated:u}=c,d=await Sr(l,o,a),f=e.limit??1e3,p=d.length,m=p>f,h=(m?d.slice(0,f):d).map(e=>e.path),g=h.length>0?h.join(`
|
|
24
|
+
`):`(no matches)`;m&&(g+=`\n\n[Showing ${f} of ${p} matches. Use limit parameter to see more.]`),u&&(g+=`
|
|
25
|
+
|
|
26
|
+
[Candidate search stopped early; the search tree has more matches than this tool scans in one call. Results are ordered among the scanned candidates only — narrow the pattern or path to see the rest.]`);let _={success:!0,output:Xn(g,t)};return JSON.stringify(_)}function Tr(e){return H(`Glob`,e.description??`Fast file pattern matching tool that works with any codebase size.
|
|
27
|
+
|
|
28
|
+
Supports glob patterns like '**/*.js' or 'src/**/*.ts'. Returns matching file paths sorted by modification time.
|
|
29
|
+
|
|
30
|
+
Use this tool when you need to find files by name patterns.
|
|
31
|
+
|
|
32
|
+
Default limit is 1000 results. Use the limit parameter if you need fewer results to save context space.`,xr,async t=>wr(t,e),{resultMode:`invocation-json`})}function Er(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`[^/]*`);return RegExp(`^${t}$`)}function Dr(e,t){return t===void 0||Er(t).test(e)}async function Or(e,t,n,r=5e4){let i=[],a=0,o=!1;async function s(e){if(o)return;let c;try{c=await De(e)}catch{return}for(let l of c){if(o)return;if(l===`node_modules`||l===`.git`)continue;let c=ye(e,l);if(!Zn(c,n))continue;if(a>=r){o=!0;return}a++;let u;try{u=await x(c)}catch{continue}u.isDirectory()?await s(c):u.isFile()&&Dr(l,t)&&i.push(c)}}return await s(e),{files:i,truncated:o}}function kr(e,t,n,r,i,a){let o=e.split(`
|
|
33
|
+
`),s=[];for(let e=0;e<o.length;e++)n.test(o[e])&&s.push(e);if(s.length===0)return[];if(i===`files_with_matches`)return[t];if(i===`count`)return[`${t}:${s.length}`];let c=new Set;for(let e of s)for(let t=Math.max(0,e-r);t<=Math.min(o.length-1,e+r);t++)c.add(t);let l=[],u=0,d=Array.from(c).sort((e,t)=>e-t),f,p=0;for(let e of d){f!==void 0&&e>f+1&&l.push(`--`);let n=e+1;for(;s[p]<e;)p++;let r=`${t}:${n}${s[p]===e?`:`:`-`}${o[e]}`;if(u+=Buffer.byteLength(r,`utf8`)+1,a!==void 0&&u>a)throw Error(`byte limit`);l.push(r),f=e}return l}const Ar=`
|
|
34
|
+
const { parentPort } = require('node:worker_threads');
|
|
35
|
+
const searchFile = ${kr.toString()};
|
|
36
|
+
let outputBytes = 0;
|
|
37
|
+
parentPort.on('message', (request) => {
|
|
38
|
+
try {
|
|
39
|
+
const regex = new RegExp(request.pattern);
|
|
40
|
+
const matches = searchFile(request.content, request.filePath, regex, request.contextLines, request.outputMode, 4 * 1024 * 1024);
|
|
41
|
+
let bytes = 0;
|
|
42
|
+
for (const match of matches) { bytes += Buffer.byteLength(match, 'utf8') + 1; if (outputBytes + bytes > 4 * 1024 * 1024) throw new Error('byte limit'); }
|
|
43
|
+
outputBytes += bytes;
|
|
44
|
+
parentPort.postMessage({ id: request.id, matches });
|
|
45
|
+
} catch (error) { parentPort.postMessage({ id: request.id, error: error?.message === 'byte limit' ? 'Grep search exceeded its byte limit' : 'Invalid grep regex execution' }); }
|
|
46
|
+
});
|
|
47
|
+
`;var jr=class extends Me{child=m(process.execPath,[`-e`,`
|
|
48
|
+
const searchFile = ${kr.toString()};
|
|
49
|
+
const readline = require('node:readline');
|
|
50
|
+
let outputBytes = 0;
|
|
51
|
+
readline.createInterface({ input: process.stdin }).on('line', line => {
|
|
52
|
+
const request = JSON.parse(line);
|
|
53
|
+
try {
|
|
54
|
+
const regex = new RegExp(request.pattern);
|
|
55
|
+
const matches = searchFile(request.content, request.filePath, regex, request.contextLines, request.outputMode, 4 * 1024 * 1024);
|
|
56
|
+
let bytes = 0;
|
|
57
|
+
for (const match of matches) { bytes += Buffer.byteLength(match, 'utf8') + 1; if (outputBytes + bytes > 4 * 1024 * 1024) throw new Error('byte limit'); }
|
|
58
|
+
outputBytes += bytes;
|
|
59
|
+
process.stdout.write(JSON.stringify({ id: request.id, matches }) + String.fromCharCode(10));
|
|
60
|
+
} catch (error) { process.stdout.write(JSON.stringify({ id: request.id, error: error?.message === 'byte limit' ? 'Grep search exceeded its byte limit' : 'Invalid grep regex execution' }) + String.fromCharCode(10)); }
|
|
61
|
+
});
|
|
62
|
+
`],{env:{BUN_BE_BUN:`1`,...process.env.SystemRoot?{SystemRoot:process.env.SystemRoot}:{}},cwd:je(),stdio:`pipe`});closed;constructor(){super();let e=``;this.child.stdout.setEncoding(`utf8`),this.child.stdout.on(`data`,t=>{if(e+=t,Buffer.byteLength(e,`utf8`)>25166848){this.emit(`error`);return}let n;for(;(n=e.indexOf(`
|
|
63
|
+
`))>=0;){let t=e.slice(0,n);e=e.slice(n+1);try{this.emit(`message`,JSON.parse(t))}catch{this.emit(`error`)}}}),this.child.stderr.resume(),this.child.on(`error`,()=>this.emit(`error`)),this.child.stdin.on(`error`,()=>this.emit(`error`)),this.closed=new Promise(e=>{this.child.once(`close`,()=>{this.emit(`exit`),e()})})}postMessage(e){this.child.stdin.write(JSON.stringify(e)+`
|
|
64
|
+
`)}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 Ne(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=S.object({pattern:S.string().describe(`The regular expression pattern to search for in file contents`),path:S.string().optional().describe(`File or directory to search in. Defaults to the current working directory`),glob:S.string().optional().describe(`Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched`),contextLines:S.number().optional().describe(`Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0`),outputMode:S.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:S.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=ee(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 te={success:!0,output:Xn(y.length>0?y.join(`
|
|
65
|
+
`):`(no matches)`,t)};return JSON.stringify(te)}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=S.object({url:S.string().describe(`The URL to fetch`),headers:S.record(S.string(),S.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=S.object({query:S.string().describe(`The search query`),limit:S.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=S.object({question:S.string().min(1).describe(`The complete question to ask the user.`),header:S.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:S.array(S.union([S.string().min(1).describe(`Display text of this choice.`),S.object({label:S.string().min(1).describe(`Display text of this choice.`),description:S.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:S.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:S.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),ci=S.object({questions:S.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(`
|
|
66
|
+
`);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_${we()}`,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=S.object({query:S.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:S.array(S.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:S.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(`
|
|
67
|
+
`);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{Ie as A,un as C,Ot as D,oi as E,T as O,Nt 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,Be as k,Kn as l,lr as m,Mt as n,Z as o,Lr as p,$ as r,Rt as s,sn as t,In as u,ei as v,Pt as w,H as x,ai as y};
|