@robota-sdk/agent-cli 3.0.4 → 3.0.6

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.
Files changed (28) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/node/bin.js +1 -1
  3. package/dist/node/{cli-core-BGjt7AbU.js → cli-core-CcG7HrJg.js} +40 -40
  4. package/dist/node/desktop-host.js +1 -1
  5. package/dist/node/headless.js +1 -1
  6. package/dist/node/host.js +1 -1
  7. package/dist/node/index.js +1 -1
  8. package/dist/node/{node-TUI6iwZA.js → node-CrF8rjSF.js} +21 -21
  9. package/dist/node/node-D_40SJP5.js +67 -0
  10. package/dist/node/node-D_40SJP5.js.map +1 -0
  11. package/dist/node/{product-host-C221Kqok.js → product-host-B2jYVaCe.js} +42 -42
  12. package/dist/node/{product-host-C221Kqok.js.map → product-host-B2jYVaCe.js.map} +1 -1
  13. package/dist/node/product-host-SaMRTzxB.d.ts.map +1 -1
  14. package/dist/node/{src-B9UMvThT-BFjrAV4G.js → src-B9UMvThT-CH8RbDyz.js} +1 -1
  15. package/dist/node/{src-B9UMvThT-Lb4lcGsM.js → src-B9UMvThT-Mipp-Spb.js} +2 -2
  16. package/dist/node/{src-B9UMvThT-Lb4lcGsM.js.map → src-B9UMvThT-Mipp-Spb.js.map} +1 -1
  17. package/dist/node/{src-BzaNFPZx-BvEx8PFT.js → src-BzaNFPZx-0zlY87KO.js} +2 -2
  18. package/dist/node/{src-BzaNFPZx-BvEx8PFT.js.map → src-BzaNFPZx-0zlY87KO.js.map} +1 -1
  19. package/dist/node/{src-BzaNFPZx-lSSo4vg-.js → src-BzaNFPZx-DdIEi4rg.js} +1 -1
  20. package/dist/node/{src-DwAfU-9z-wiH2j4Vl.js → src-DwAfU-9z-B3bEabDl.js} +1 -1
  21. package/dist/node/{src-DwAfU-9z-DHXK7gXT.js → src-DwAfU-9z-DDIgZhiP.js} +2 -2
  22. package/dist/node/{src-DwAfU-9z-DHXK7gXT.js.map → src-DwAfU-9z-DDIgZhiP.js.map} +1 -1
  23. package/dist/node/{src-UPsd6jNY-DWV8HeyO.js → src-UPsd6jNY-CpXUNTpA.js} +1 -1
  24. package/dist/node/{src-UPsd6jNY-CtQwNoeL.js → src-UPsd6jNY-XM9nqZGs.js} +2 -2
  25. package/dist/node/{src-UPsd6jNY-CtQwNoeL.js.map → src-UPsd6jNY-XM9nqZGs.js.map} +1 -1
  26. package/package.json +37 -37
  27. package/dist/node/node-DwQY2ITL.js +0 -67
  28. package/dist/node/node-DwQY2ITL.js.map +0 -1
@@ -0,0 +1,67 @@
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 T(e){return e.exitCode!==null||e.signalCode!==null}function Le(e,t,n){if(n&&!Ie&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function Re(e,t){if(Ie&&typeof e.pid==`number`){ie(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Le(e,`SIGKILL`,t)}async function ze(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!T(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(T(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),T(e)){e.removeListener(`exit`,o),t();return}Le(e,r,i),a=setTimeout(()=>{T(e)||Re(e,i)},n),a.unref?.()})}}const Be={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 E=class extends Error{code;context;constructor(e,t){super(Be[e]),this.name=`StableFileAuthorityError`,this.code=e,this.context=Object.freeze({...t})}};function D(e,t,n={}){return new E(e,{operation:t,...n})}const Ve=16777216,He=524288;function O(e){return{device:e.dev,inode:e.ino,mode:e.mode}}function Ue(e){return{...O(e),size:e.size,modified:e.mtimeNs,changed:e.ctimeNs}}function We(e,t){return e.device===t.device&&e.inode===t.inode&&e.mode===t.mode}function k(e,t){return e.device===t.device&&e.inode===t.inode}function Ge(e,t){return We(e,t)&&e.size===t.size&&e.modified===t.modified&&e.changed===t.changed}function A(e){for(let[t,n]of Object.entries(w.os.errno))if(n===e)return t;return`ERRNO_${e}`}function j(e){let t=S.O_CLOEXEC??(process.platform===`darwin`?Ve:He);return S.O_RDONLY|S.O_NOFOLLOW|S.O_NONBLOCK|t|(e?S.O_DIRECTORY:0)}function M(e,t){try{return he(e,{bigint:!0})}catch(e){let n=Ke(typeof e==`object`?e:null);throw D(`HOST_IO`,t,n===void 0?{}:{hostCode:n})}}function Ke(e){if(!(e===null||!(`code`in e)))return typeof e.code==`string`?e.code:void 0}let qe;const Je=[];function N(){if(!qe){let e=w.load(process.platform===`darwin`?`/usr/lib/libSystem.B.dylib`:`libc.so.6`);Je.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, ...)`);qe={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 qe}var Ye=class{openAt;rootIdentity;rootDescriptor;constructor(e){try{let{open:t,openAt:n}=N();this.openAt=n;let r=t(e,j(!0));r<0&&this.throwOpenFailure(w.errno(),`open-root`),this.rootDescriptor=r;let i=M(r,`inspect-root`);if(!i.isDirectory())throw D(`UNSAFE_ENTRY`,`open-root`);this.rootIdentity=O(i)}catch(e){throw this.rootDescriptor!==void 0&&(this.closeDescriptor(this.rootDescriptor),this.rootDescriptor=void 0),e instanceof E?e:D(`UNSUPPORTED_BACKEND`,`load-posix-backend`)}}assertNamedRoot(e){if(this.rootDescriptor===void 0)throw D(`AUTHORITY_CLOSED`,`inspect-root`);this.assertRootIdentity(this.rootDescriptor);let t=N().open(e,j(!0));if(t<0)throw D(`ROOT_CHANGED`,`inspect-named-root`);try{let e=M(t,`inspect-named-root`);if(!e.isDirectory()||!k(this.rootIdentity,O(e)))throw D(`ROOT_CHANGED`,`inspect-named-root`)}finally{this.closeDescriptor(t)}}readBytes(e,t,n){let r=this.rootDescriptor;if(r===void 0)throw D(`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],j(!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(!M(s,`inspect-directory`).isDirectory())throw this.closeDescriptor(s),D(`UNSAFE_ENTRY`,`inspect-directory`,{segmentIndex:t});a&&this.closeDescriptor(i),i=s,a=!0,n.afterDirectoryOpened?.(t)}if(o===void 0)throw D(`HOST_IO`,`open-file`);let s=this.readFile(o,t,n);return this.assertRootIdentity(r),s}catch(e){if(e instanceof E)throw e;let t=Ke(typeof e==`object`?e:null);throw D(`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 D(`AUTHORITY_CLOSED`,`write`);this.assertRootIdentity(r);let i=e.slice(0,-1),a=e.at(-1);if(a===void 0)throw D(`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=O(M(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||!k(t,m))throw D(`FILE_CHANGED`,`commit-write`);if(d){if(f===void 0)throw D(`HOST_IO`,`commit-write`);let e=this.readNamedIdentity(o,h,`inspect-displaced`,!0);if(e===void 0||!k(e,f))throw D(`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 E)throw e;let t=Ke(typeof e==`object`?e:null);throw D(`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],j(!0),0);if(o<0&&w.errno()===w.os.errno.ENOENT){let{mkdirAt:n}=N();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],j(!0),0)}o<0&&this.throwOpenFailure(w.errno(),`open-directory`,e);let s=M(o,`inspect-directory`);if(!s.isDirectory())throw this.closeDescriptor(o),D(`UNSAFE_ENTRY`,`inspect-directory`,{segmentIndex:e});i&&this.closeDescriptor(r),r=o,i=!0,a.push(O(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],j(!0),0);a<0&&this.throwOpenFailure(w.errno(),`reopen-directory`,e);let o=M(a,`reinspect-directory`);if(!o.isDirectory()||!We(n[e],O(o)))throw this.closeDescriptor(a),D(`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,j(!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=M(i,n);if(!e.isFile()){if(r)return;throw D(`UNSAFE_ENTRY`,n)}return O(e)}finally{this.closeDescriptor(i)}}createTemporaryFile(e,t){let n=S.O_CLOEXEC??(process.platform===`darwin`?Ve:He),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 D(`HOST_IO`,`create-temporary`,{hostCode:`EEXIST`})}assertNamedIdentity(e,t,n,r){let i=this.readNamedIdentity(e,t,`inspect-${r}`);if(i===void 0||!k(i,n))throw D(`FILE_CHANGED`,`inspect-${r}`)}setMode(e,t){if(N().fchmod(e,t)<0)throw D(`HOST_IO`,`set-temporary-mode`,{hostCode:A(w.errno())})}renameWithoutReplacement(e,t,n){if(N().noReplaceAt(e,t,e,n)>=0)return;let r=w.errno();throw r===w.os.errno.EEXIST?D(`FILE_CHANGED`,`commit-write`):D(`HOST_IO`,`commit-write`,{hostCode:A(r)})}exchange(e,t,n){if(N().exchangeAt(e,t,e,n)<0)throw D(`HOST_IO`,`commit-write`,{hostCode:A(w.errno())})}unlink(e,t,n){if(N().unlinkAt(e,t,0)>=0)return;let r=w.errno();if(!(n&&r===w.os.errno.ENOENT)&&!n)throw D(`HOST_IO`,`remove-temporary`,{hostCode:A(r)})}rollbackCommittedWrite(e,t,n,r,i,a){try{let o=this.readNamedIdentity(e,n,`inspect-rollback-target`,!0);if(o===void 0||!k(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||!k(s,i)?!1:(this.exchange(e,t,n),!0)}catch{return!1}}readFile(e,t,n){let r=M(e,`inspect-file`);if(!r.isFile())throw D(`UNSAFE_ENTRY`,`inspect-file`);if(r.size>BigInt(t))throw D(`OVER_BUDGET`,`read-file`);let i=Number(r.size),a;try{a=Buffer.alloc(i)}catch{throw D(`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=M(e,`reinspect-file`);if(s&&i>=t)throw D(`OVER_BUDGET`,`read-file`);if(o!==i||s||!Ge(Ue(r),Ue(c)))throw D(`FILE_CHANGED`,`read-file`);return a}assertRootIdentity(e){let t=M(e,`inspect-root`);if(!t.isDirectory()||!We(this.rootIdentity,O(t)))throw D(`ROOT_CHANGED`,`inspect-root`)}throwOpenFailure(e,t,n){let r=A(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?D(`UNSAFE_ENTRY`,t,i):D(`HOST_IO`,t,i)}closeDescriptor(e){try{de(e)}catch{}}closeOptionalDescriptor(e){e!==void 0&&this.closeDescriptor(e)}};function Xe(){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 Ze(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]),...Qe(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 Qe(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 $e(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`]),ntSetInformationFile:e.func(`NtSetInformationFile`,`int32_t`,[t.handleType,w.out(w.pointer(t.ioStatusBlockType)),`void *`,`uint32_t`,`int32_t`]),ntClose:e.func(`NtClose`,`int32_t`,[t.handleType])}}let et;const tt=[];function nt(){if(et!==void 0)return et;let e=Xe(),t=w.load(`kernel32.dll`);tt.push(t);let n=w.load(`ntdll.dll`);return tt.push(n),et={...e,...Ze(t,e),...$e(n,e)},et}const rt=BigInt(`0`);function it(e){if(e instanceof Uint8Array||Array.isArray(e))return Buffer.from(e).toString(`hex`);throw D(`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 D(`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 D(`OVER_BUDGET`,`read-file`);let a=Number(i.size),o;try{o=Buffer.alloc(a)}catch{throw D(`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 D(`HOST_IO`,`probe-file`,{hostCode:P(e)});let l=ct(e,t);if(c[0]!==0&&a>=n)throw D(`OVER_BUDGET`,`read-file`);if(!lt(i,l,s,a,c[0]))throw D(`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 D(`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 D(`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 ft(e){return`NTSTATUS_0x${(e>>>0).toString(16)}`}function pt(e){let t=e>>>0;return{kind:ut.has(t)?`missing`:t===3221225525?`exists`:dt.has(t)?`unsafe`:`host-io`,hostCode:ft(e)}}const mt=BigInt(`-1`);function ht(e){if(e.length===0||e.length>255)throw D(`INVALID_PATH`,`validate-segments`)}function F(e){return e===null||BigInt.asIntN(64,e)===mt}var gt=class{api;constructor(){try{this.api=nt()}catch{throw D(`UNSUPPORTED_BACKEND`,`load-windows-backend`)}}openRoot(e){let t=this.api.createFileW(e,2147483648,7,null,3,35651584,null);if(F(t))throw D(`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){return this.completeRelativeOpen(this.issueRelativeOpen(e,t,n,!1),n,r)}openIdentity(e,t,n){return this.completeRelativeOpen(this.issueRelativeOpen(e,t,!0,!1,!0),!0,n)}completeRelativeOpen({handle:e,status:t},n,r){if(t>=0){if(F(e))throw D(`HOST_IO`,`open-relative`);try{return this.assertSafeHandle(e,!n,n?`inspect-file`:`inspect-directory`,r),e}catch(t){throw this.close(e),t}}F(e)||this.close(e);let i=pt(t);if(i.kind===`missing`)return;let a={segmentIndex:r,hostCode:i.hostCode};throw i.kind===`unsafe`?D(`UNSAFE_ENTRY`,n?`open-file`:`open-directory`,a):D(`HOST_IO`,n?`open-file`:`open-directory`,a)}openReplacementTarget(e,t,n){let{handle:r,status:i}=this.issueRelativeOpen(e,t,!0,!0);if(i>=0){if(F(r))throw D(`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=pt(i);if(a.kind===`missing`)return;let o={segmentIndex:n,hostCode:a.hostCode};throw a.kind===`unsafe`?D(`UNSAFE_ENTRY`,`open-replacement-target`,o):D(`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=pt(i),t={segmentIndex:n,hostCode:e.hostCode};throw e.kind===`unsafe`?D(`UNSAFE_ENTRY`,`open-directory`,t):D(`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 D(`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=pt(r);if(i.kind!==`exists`)throw i.kind===`unsafe`?D(`UNSAFE_ENTRY`,`create-temporary`,{hostCode:i.hostCode}):D(`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 D(`HOST_IO`,`write-temporary`,{hostCode:this.lastErrorCode()});if(i[0]<=0||i[0]>t.length)throw D(`HOST_IO`,`write-temporary`);r+=i[0]}if(!this.api.flushFileBuffers(e))throw D(`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};w.encode(a,this.api.renameInfoType,o);let s=this.api.ntSetInformationFile(e,{Status:0,Information:0},a,w.sizeof(this.api.renameInfoType),10);if(s<0)throw D(`HOST_IO`,`commit-write`,{hostCode:ft(s)})}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,i=!1){ht(t);let a=w.alloc(this.api.unicodeStringType,1);try{w.encode(a,this.api.unicodeStringType,{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(`${t}\0`,`utf16le`),Buffer:t});let o={Length:w.sizeof(this.api.objectAttributesType),RootDirectory:e,ObjectName:a,Attributes:4160,SecurityDescriptor:null,SecurityQualityOfService:null},s=[null],c={Status:0,Information:0},l=n&&!i?5:7,u=n?i?0:1|(r?65536:0):1,d=this.api.ntCreateFile(s,u|1048704,o,c,null,0,l,1,(n?64:1)|2097184,null,0);return{handle:s[0],status:d}}finally{w.free(a)}}issueRelativeCreate(e,t,n,r){ht(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 D(`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 D(`HOST_IO`,n,{hostCode:this.lastErrorCode()});if((i.FileAttributes??0)&1024||!!a.Directory!==t)throw D(`UNSAFE_ENTRY`,n,r===void 0?{}:{segmentIndex:r})}lastErrorCode(){return P(this.api)}};function I(e,t){return e.volume===t.volume&&e.fileId===t.fileId}var _t=class{native=new gt;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 E?e:D(`UNSUPPORTED_BACKEND`,`load-windows-backend`)}}readBytes(e,t,n){let r=this.rootHandle;if(r===void 0)throw D(`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 D(`HOST_IO`,`open-file`);let s=this.native.readFile(o,t,n);return this.assertRootIdentity(r),s}catch(e){throw e instanceof E?e:D(`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 D(`AUTHORITY_CLOSED`,`write`);this.assertRootIdentity(r);let i=e.slice(0,-1),a=e.at(-1);if(a===void 0)throw D(`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.openIdentity(o,a,e.length-1);if(y===void 0)throw D(`FILE_CHANGED`,`commit-write`);try{if(!I(this.native.queryIdentity(y,`inspect-target`),v))throw D(`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 E?e:D(`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 D(`FILE_CHANGED`,`reopen-directory`,{segmentIndex:e});if(!I(this.native.queryIdentity(a,`reinspect-directory`),n[e]))throw this.native.close(a),D(`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 D(`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 D(`FILE_CHANGED`,`inspect-named-entry`);try{if(!I(this.native.queryIdentity(r,`inspect-named-entry`),n))throw D(`FILE_CHANGED`,`inspect-named-entry`)}finally{this.native.close(r)}}assertRootIdentity(e){if(!I(this.native.queryIdentity(e,`inspect-root`),this.rootIdentity))throw D(`ROOT_CHANGED`,`inspect-root`)}};const vt=new Set([`darwin-arm64`,`darwin-x64`,`linux-arm64`,`linux-x64`,`win32-x64`]);function yt(e){let t=`${process.platform}-${process.arch}`;if(!vt.has(t))throw D(`UNSUPPORTED_BACKEND`,`select-backend`,{hostCode:t});return process.platform===`win32`?new _t(e):new Ye(e)}function bt(e){if(typeof e!=`string`||e.trim().length===0||e.includes(`\0`))throw D(`INVALID_PATH`,`validate-root`);return b(e)}function xt(e){if(!Array.isArray(e)||e.length===0)throw D(`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 D(`INVALID_PATH`,`validate-segments`,{segmentIndex:t})}}function St(e){if(!Number.isSafeInteger(e)||e<0)throw D(`INVALID_PATH`,`validate-budget`)}const Ct=new FinalizationRegistry(e=>{e.close()});var wt=class{rootDirectory;hooks;backend;finalizerToken={};constructor(e,t){this.rootDirectory=e,this.hooks=t;let n=yt(bt(e));this.backend=n,Ct.register(this,n,this.finalizerToken)}assertNamedRoot(){let e=this.backend;if(e===void 0)throw D(`AUTHORITY_CLOSED`,`inspect-root`);if(e.assertNamedRoot===void 0)throw D(`UNSUPPORTED_BACKEND`,`inspect-root`);e.assertNamedRoot(this.rootDirectory)}writeUtf8WhileNamed(e,t){let n=this.backend;if(n===void 0)throw D(`AUTHORITY_CLOSED`,`write`);if(xt(e),typeof t!=`string`)throw D(`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 D(`AUTHORITY_CLOSED`,`write`);if(xt(e),typeof t!=`string`)throw D(`INVALID_PATH`,`validate-content`);try{n.writeUtf8(e,t,this.hooks)}catch(e){throw e instanceof E?e:D(`HOST_IO`,`write`)}}close(){let e=this.backend;if(e!==void 0){this.backend=void 0,Ct.unregister(this.finalizerToken);try{e.close()}catch(e){throw e instanceof E?e:D(`HOST_IO`,`close`)}}}[Symbol.dispose](){this.close()}};function Tt(e){return new wt(e,{})}const Et=new FinalizationRegistry(e=>{e.close()});function Dt(e,t){xt(e),St(t)}var Ot=class{hooks;backend;finalizerToken={};constructor(e,t){this.hooks=t;let n=yt(bt(e));this.backend=n,Et.register(this,n,this.finalizerToken)}readBytes(e,t){let n=this.backend;if(n===void 0)throw D(`AUTHORITY_CLOSED`,`read`);Dt(e,t);try{return n.readBytes(e,t,this.hooks)}catch(e){throw e instanceof E?e:D(`HOST_IO`,`read`)}}close(){let e=this.backend;if(e!==void 0){this.backend=void 0,Et.unregister(this.finalizerToken);try{e.close()}catch(e){throw e instanceof E?e:D(`HOST_IO`,`close`)}}}[Symbol.dispose](){this.close()}};function kt(e){return new Ot(e,{})}function At(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 jt(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 Mt(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 Nt=class{sandbox;generation=0;restoring=!1;connectSandbox;createSandboxFromSnapshot;constructor(e){jt(e.sandbox),this.sandbox=e.sandbox,this.connectSandbox=e.connectSandbox,this.createSandboxFromSnapshot=e.createSandboxFromSnapshot}async run(e,t){return Mt(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 At(t.snapshotId??t.id)}let t=At(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{At(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(jt(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 Pt(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function Ft(e){return Pt(e)===`sandbox-separate`}function It(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 Lt=/^[A-Za-z]:[\\/]/,Rt=/'/g;async function zt(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);It(t);let r=Zt(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=Bt(a),s=Qt(r,t);i.push(await Vt(e,t,s,r,o,n))}return{entries:i}}function Bt(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(`\\`)||Lt.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 Vt(e,t,n,r,i,a){switch(i.type){case`file`:return await Kt(e,n,r,i.content),L(t,i.type);case`dir`:return await qt(e,n),L(t,i.type);case`localFile`:return await Ht(e,i.src,n,r,a),L(t,i.type);case`localDir`:return await Ut(e,i.src,n,a),L(t,i.type);case`gitRepo`:return await Gt(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 $t(i)}}function L(e,t){return{path:e,type:t,status:`applied`}}async function Ht(e,t,n,r,i){await Kt(e,n,r,await oe(Yt(t,i.hostRoot),`utf8`))}async function Ut(e,t,n,r){await Wt(e,Yt(t,r.hostRoot),n)}async function Wt(e,t,n){await qt(e,n);let r=await se(t,{withFileTypes:!0});for(let i of r){let r=y(t,i.name),a=Qt(n,i.name);if(i.isDirectory()){await Wt(e,r,a);continue}if(i.isFile()){let t=await oe(r,`utf8`);await e.writeFile(a,t)}}}async function Gt(e,t,n){await Jt(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${R(t.ref)}`:``} ${R(t.url)} ${R(n)}`)}async function Kt(e,t,n,r){let i=ee.dirname(t);i!==n&&await qt(e,i),await e.writeFile(t,r)}async function qt(e,t){await Jt(e,`mkdir -p ${R(t)}`)}async function Jt(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 Yt(e,t){return v(e)?b(e):b(t??process.cwd(),e)}function Xt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function Zt(e){let t=Xt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Qt(e,t){let n=Zt(e);return n===`/`?`/${t}`:`${n}/${t}`}function R(e){return`'${e.replace(Rt,`'\\''`)}'`}function $t(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}function en(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 tn(t){return[...new Set([...n,...t?.protectedDirectoryNames??[],...e])]}function nn(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 tn(t.pathProtection)){let i=z(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of en(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 rn(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function B(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function an(t){let n=[t.root,...t.tempDirectories,...t.allowWrite].map(e=>`(subpath ${B(e)})`).join(` `),r=tn(t.pathProtection).map(n=>{let r=z(t.root,n);return e.includes(n)?`(literal ${B(r)})`:`(subpath ${B(r)})`}),i=en(t.pathProtection).map(e=>`(subpath ${B(z(t.root,e))})`),a=[`(literal ${B(z(t.root,`.git`))})`,...en(t.pathProtection).map(e=>`(regex #"^${rn(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
+ `)}const on={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 sn(e=process.arch){let t=on[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 cn=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),ln=`/usr/bin/sandbox-exec`;function un(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
+ `)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function dn(e={}){let t=e.platform??process.platform,n=e.probe??un;if(t===`linux`){if(sn(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(ln,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:ln,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function fn(e){try{return Ce(e)}catch{return e}}function pn(e){try{return Ee(e).isDirectory()}catch{return!1}}function mn(e){let t=_e(e);if(!t.isSymbolicLink()&&(ue(e,t.mode|448),t.isDirectory()))for(let t of xe(e))mn(`${e}/${t}`)}function hn(e){try{return _e(e).isSymbolicLink()}catch{return!1}}function gn(e){return e.trim().split(/\s+/)[0]}var _n=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=fn(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??ke(),this.hiddenPaths=Object.freeze([...e.hiddenPaths??[]]),this.current={...cn,...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=gn(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`,an(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:sn();this.protectedEntryStates().some(e=>e.path===`${this.root}/${this.projectStateDirectory}`&&e.kind===`symlink`)||ve(`${this.root}/${this.projectStateDirectory}`,{recursive:!0});let a=nn({policy:n,exists:e=>me(e)&&!hn(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 tn(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;mn(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 fn(v(t)?t:b(this.root,t))},t=[...new Set([Ae(),`/tmp`].filter(me).map(fn))];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:pn(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 vn=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=vn.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 yn={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 bn(){for(let[e,t]of Object.entries(yn))i(e,t)}bn();const xn=1e3,Sn=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 ${xn}).`)});function Cn(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
4
+ `)}async function wn(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??xn});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${Cn(n.symbols)}`}function Tn(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.`,Sn,async t=>wn(t,e))}const En=`Computer use is not available in this session (no driver injected).`,Dn=C.enum([`left`,`right`,`middle`]),On=C.object({x:C.number(),y:C.number()}),kn=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:Dn.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(On).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).`)}),An=C.object({action:kn.describe(`The single mutating action to perform.`)}),jn=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 Mn(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 Nn(e){if(!e.driver)return JSON.stringify({success:!1,error:En});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function Pn(e,t){if(!t.driver)return JSON.stringify({success:!1,error:En});let n;try{n=Mn(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 Fn(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.`,jn,async()=>Nn(e))}function In(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.",An,async t=>Pn(t,e))}function Ln(e={}){return[Fn(e),In(e)]}const Rn=[{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 zn(e,t){let n=t?Rn.filter(e=>t.includes(e.toolName)):Rn,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(`
5
+ `)}const G=process.platform!==`win32`,Bn=2e6,Vn=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"`,Hn=C.object({command:C.string().describe(`The shell command to execute`),timeout:C.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:C.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});async function Un(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 Wn(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 Un(a,c,s??t.cwd,t);let f={command:n.command,args:n.commandArgs(a),cwd:d},p=t.sandboxClient?.wrapCommand?.(f,a)??f,m=!1,h=()=>{if(!m){m=!0;try{return p.afterExit?.()}catch(e){return`[sandbox] clean-up failed: ${e instanceof Error?e.message:String(e)}`}}};return r?.aborted?(h(),JSON.stringify({success:!1,output:``,error:`Aborted before start`})):new Promise(e=>{let t=l({maxBytes:Bn}),n=l({maxBytes:Bn}),a=!1,o=!1,s,d=3+(p.inputDescriptors?.length??0);try{s=re(G?`/bin/sh`:p.command,G?[`-c`,Vn(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=h(),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 m=setTimeout(()=>{a=!0,ze(s,{processGroup:G}),g({success:!1,output:t.toString(),error:`Command timed out after ${c}ms`})},c);function g(t){o||(o=!0,clearTimeout(m),r?.removeEventListener(`abort`,_),e(JSON.stringify(t)))}function _(){ze(s,{processGroup:G}),g({success:!1,output:t.toString(),error:`Aborted`})}r?.addEventListener(`abort`,_,{once:!0}),s.on(`error`,e=>{s.pid===void 0&&h(),g({success:!1,output:``,error:e.message})}),s.on(`close`,e=>{s.stdin?.end(),f?.end();let r=h();if(a){g({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;g({success:!0,output:r===void 0?u:`${u}\n${r}`,exitCode:l})})})}function Gn(e,t){let n=d({executable:t.shellExecutable});return H(e,t.description??zn(n,t.availableTools),Hn,async(e,r)=>Wn(e,t,n,r?.signal,r?.shellTraceEnv),{resultMode:`invocation-json`})}function Kn(e){return Gn(`Shell`,e)}function qn(e){return Gn(`Bash`,e)}function Jn(e){let t=e.editorFiles?.();if(t?.pathAuthority===`stable-root`)return t?.readTextFile?.bind(t)}function Yn(e){let t=e.editorFiles?.();if(t?.pathAuthority===`stable-root`)return t?.writeTextFile?.bind(t)}function Xn(...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 Zn(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 Qn(e,t){return t!==void 0&&p(t,e)}function $n(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(!Qn(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 er(e,t){return t===e||t.startsWith(e.endsWith(ne)?e:e+ne)}async function tr(e,t,n){let r=()=>new J(`Access denied: "${e}" is outside the working directory`);if(t===void 0)throw r();let i=await le(t);if(process.platform===`darwin`){let t=await le(e);if(!er(i,t))throw r();try{return await ae(t,n|536870912,384)}catch(e){throw e.code===`ELOOP`?r():e}}let a=await ae(e,n,384);if(process.platform!==`linux`)return a;let o;try{o=await ce(`/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(er(i,o))return a;throw await a.close(),r()}function nr(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 rr=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 ir=C.object({filePath:C.string().describe(`The absolute path to the file to read`),offset:C.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:C.number().optional().describe(`The number of lines to read (default: ${rr}). Only provide if the file is too large to read at once`)});function ar(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function or(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(`
6
+ `)}function sr(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(`
7
+ `,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+or(i,n)};return JSON.stringify(m)}async function cr(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 sr(t,a,n,r)}async function lr(e,t,n){if(t.signal?.aborted)throw new Z;let{offset:r,limit:i=rr}=e,a=t.sandboxClient?e.filePath:$n(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 sr(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=Jn(t);if(c!==void 0)return cr(c,a,o,i,Xn(t.signal,n));let l=e=>JSON.stringify({success:!1,output:``,error:e}),u;try{u=await tr(a,t.cwd,S.O_RDONLY|S.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&&ar(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 sr(a,d.toString(`utf8`),o,i)}function ur(e){return H(`Read`,e.description??`Reads a file from the local filesystem.
8
+
9
+ By default, reads up to 2000 lines from the beginning of the file. You can optionally specify offset and limit for partial reads.
10
+
11
+ Results are returned using cat -n format, with line numbers starting at 1.
12
+
13
+ The filePath parameter must be an absolute path, not a relative path.`,ir,async(t,n)=>lr(t,e,n?.signal),{resultMode:`invocation-json`})}function dr(e,t){let n=te(b(e),b(t));return n.length===0?[]:n.split(ne)}async function fr(e,t,n=_(e)){let r=Tt(n);try{r.writeUtf8(dr(n,e),t)}finally{r.close()}}const pr=C.object({filePath:C.string().describe(`The absolute path to the file to write`),content:C.string().describe(`The content to write to the file`)});async function mr(e,t,n){let r=Xn(t.signal,n);r?.throwIfAborted();let{content:i}=e,a=t.sandboxClient?e.filePath:$n(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:Yn(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 fr(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 hr(e){return H(`Write`,e.description??`Writes a file to the local filesystem. This will overwrite an existing file if one exists.
14
+
15
+ 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.
16
+
17
+ Parent directories are created automatically when missing.`,pr,async(t,n)=>mr(t,e,n?.signal),{resultMode:`invocation-json`})}const gr=C.object({filePath:C.string().describe(`The absolute path to the file to modify`),oldString:C.string().describe(`The text to replace (must be an exact match of existing content)`),newString:C.string().describe(`The text to replace it with (must be different from oldString)`),replaceAll:C.boolean().optional().describe(`Replace all occurrences of oldString (default: false). Useful for renaming variables`)}),Q=4*1024*1024,_r=64*1024;var vr=class extends Error{boundary;constructor(e){super(`Edit ${e} exceeds its ${Q}-byte limit`),this.boundary=e}};async function yr(e,t,n){let r=await tr(e,t,S.O_RDONLY);try{let e=[],t=0,i=0,a=Buffer.allocUnsafe(Math.min(_r,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 vr(`input`);i+=o,i===a.length&&(e.push(a),i=0,a=Buffer.allocUnsafe(Math.min(_r,n-t+1)))}return Buffer.concat(e,t).toString(`utf8`)}finally{await r.close()}}async function br(e,t,n){let r=Xn(t.signal,n);r?.throwIfAborted();let{oldString:i,newString:a,replaceAll:o=!1}=e,s=t.sandboxClient?e.filePath:$n(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:Jn(t),l=t.sandboxClient?void 0:Yn(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 vr(`input`)}else if(t.sandboxClient){if(u=await t.sandboxClient.readFile(s),Buffer.byteLength(u,`utf8`)>Q)throw new vr(`input`)}else u=await yr(s,t.cwd,Q)}catch(e){if(r?.throwIfAborted(),e instanceof vr){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 fr(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(`
18
+ `).length:1,v={success:!0,output:`Replaced ${f} occurrence(s) in ${s}`,startLine:_};return JSON.stringify(v)}function xr(e){return H(`Edit`,e.description??`Performs exact string replacements in files.
19
+
20
+ 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.
21
+
22
+ 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.`,gr,async(t,n)=>br(t,e,n?.signal),{resultMode:`invocation-json`})}const Sr=C.object({pattern:C.string().describe(`The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.tsx")`),path:C.string().optional().describe(`The directory to search in. Defaults to the current working directory. Must be a valid directory path if provided`),limit:C.number().optional().describe(`Maximum number of results to return (default: 1000). Use a smaller limit to save context space`)});async function Cr(e,t,n){let r=Pe(100);return(await Promise.all(e.map(e=>r(async()=>{let r=b(t,e);if(Qn(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 wr(e,t,n){let r=[],i=!1,a=Ne.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 Tr(e,t,n=5e4){let{pattern:r,path:i}=e,a=t.cwd,{root:o,error:s}=nr(i,a);if(s)return s;let c;try{c=await wr(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 Cr(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(`
23
+ `):`(no matches)`;m&&(g+=`\n\n[Showing ${f} of ${p} matches. Use limit parameter to see more.]`),u&&(g+=`
24
+
25
+ [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:Zn(g,t)};return JSON.stringify(_)}function Er(e){return H(`Glob`,e.description??`Fast file pattern matching tool that works with any codebase size.
26
+
27
+ Supports glob patterns like '**/*.js' or 'src/**/*.ts'. Returns matching file paths sorted by modification time.
28
+
29
+ Use this tool when you need to find files by name patterns.
30
+
31
+ Default limit is 1000 results. Use the limit parameter if you need fewer results to save context space.`,Sr,async t=>Tr(t,e),{resultMode:`invocation-json`})}function Dr(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`[^/]*`);return RegExp(`^${t}$`)}function Or(e,t){return t===void 0||Dr(t).test(e)}async function kr(e,t,n,r=5e4){let i=[],a=0,o=!1;async function s(e){if(o)return;let c;try{c=await se(e)}catch{return}for(let l of c){if(o)return;if(l===`node_modules`||l===`.git`)continue;let c=y(e,l);if(!Qn(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()&&Or(l,t)&&i.push(c)}}return await s(e),{files:i,truncated:o}}function Ar(e,t,n,r,i,a){let o=e.split(`
32
+ `),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 jr=`
33
+ const { parentPort } = require('node:worker_threads');
34
+ const searchFile = ${Ar.toString()};
35
+ let outputBytes = 0;
36
+ parentPort.on('message', (request) => {
37
+ try {
38
+ const regex = new RegExp(request.pattern);
39
+ const matches = searchFile(request.content, request.filePath, regex, request.contextLines, request.outputMode, 4 * 1024 * 1024);
40
+ let bytes = 0;
41
+ for (const match of matches) { bytes += Buffer.byteLength(match, 'utf8') + 1; if (outputBytes + bytes > 4 * 1024 * 1024) throw new Error('byte limit'); }
42
+ outputBytes += bytes;
43
+ parentPort.postMessage({ id: request.id, matches });
44
+ } catch (error) { parentPort.postMessage({ id: request.id, error: error?.message === 'byte limit' ? 'Grep search exceeded its byte limit' : 'Invalid grep regex execution' }); }
45
+ });
46
+ `;var Mr=class extends je{child=re(process.execPath,[`-e`,`
47
+ const searchFile = ${Ar.toString()};
48
+ const readline = require('node:readline');
49
+ let outputBytes = 0;
50
+ readline.createInterface({ input: process.stdin }).on('line', line => {
51
+ const request = JSON.parse(line);
52
+ try {
53
+ const regex = new RegExp(request.pattern);
54
+ const matches = searchFile(request.content, request.filePath, regex, request.contextLines, request.outputMode, 4 * 1024 * 1024);
55
+ let bytes = 0;
56
+ for (const match of matches) { bytes += Buffer.byteLength(match, 'utf8') + 1; if (outputBytes + bytes > 4 * 1024 * 1024) throw new Error('byte limit'); }
57
+ outputBytes += bytes;
58
+ process.stdout.write(JSON.stringify({ id: request.id, matches }) + String.fromCharCode(10));
59
+ } 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)); }
60
+ });
61
+ `],{env:{BUN_BE_BUN:`1`,...process.env.SystemRoot?{SystemRoot:process.env.SystemRoot}:{}},cwd:Ae(),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(`
62
+ `))>=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)+`
63
+ `)}async terminate(){this.child.exitCode===null&&this.child.signalCode===null&&this.child.kill(`SIGKILL`),await this.closed}},Nr=class{pattern;signal;worker=process.versions.bun?new Mr:new Me(jr,{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 Pr=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`)}),Fr=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 Ir(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}=nr(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 kr(l,i,c);f=e.files,p=e.truncated}let m=new Nr(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>Fr)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>Fr)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:Zn(y.length>0?y.join(`
64
+ `):`(no matches)`,t)};return JSON.stringify(ee)}function Lr(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 Rr(e){return H(`Grep`,e.description??Lr(e.shellToolName??`Shell`),Pr,async t=>Ir(t,e),{resultMode:`invocation-json`})}const zr=3e4,Br=5e6,Vr=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 Hr(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 Ur(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 Wr={"&amp;":`&`,"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&#39;":`'`,"&nbsp;":` `},Gr=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function Kr(e){return Ur(Hr(Hr(e,`script`),`style`)).replace(Gr,e=>Wr[e]).replace(/\s+/g,` `).trim()}function qr(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${zr/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 Jr(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 Yr(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:Jr(e.headers.get(`content-type`)??``,e.body)?i:void 0}catch{return}}function Xr(e){return`\n\nThis site publishes an LLM index at ${e} (llms.txt); fetch it for a curated map of the docs.`}async function Zr(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:zr,maxResponseBytes:Br},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 ${Br} 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=Yr(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=Kr(c);let s=await o;s!==void 0&&(c+=Xr(s))}return JSON.stringify({success:!0,output:c})}catch(e){let t={success:!1,output:``,error:qr(e)};return JSON.stringify(t)}}const Qr=`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)`,$r=`${Qr}; when a fetched page's site has one, the result points to it.`,ei=`${Qr}.`;function ti(e={}){let t=e.egress??{},n=e.llmsTxtProbe===!1?void 0:new Map;return H(`WebFetch`,e.description??(n?$r:ei),Vr,async(r,i)=>Zr(r,t,e.userAgent,n,i?.signal),{resultMode:`invocation-json`})}const ni=ti();function ri(){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 ii=C.object({query:C.string().describe(`The search query`),limit:C.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function ai(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 oi(e={}){let t=e.provider??ri();return H(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,ii,async(e,n)=>ai(e,t,n?.signal),{resultMode:`invocation-json`})}const si=oi(),ci=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).`)}),li=C.object({questions:C.array(ci).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),ui=[`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
+ `);function di(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 fi(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(di(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 pi(e={}){return H(`AskUserQuestion`,e.description??ui,li,async(e,t)=>{let n=e,r=t?.ask,i=r?await fi(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)},{resultMode:`invocation-json`})}pi();const mi=1/0;function hi(e,t){e.description!==void 0&&t.push(e.description);for(let[n,r]of Object.entries(e.properties??{}))t.push(n),hi(r,t);e.items!==void 0&&hi(e.items,t);for(let n of e.anyOf??[])hi(n,t)}function gi(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 hi(e.parameters,r),r.some(e=>e.toLowerCase().includes(t))?3:mi}function _i(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:gi(e,r)})).filter(e=>e.rank!==mi).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const vi=a,yi=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).`)}),bi=[`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 xi(e){let t=e?.deferredTools;if(!t)throw Error(`${vi} 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 Si(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${vi} needs either "query" to search for tools or "names" to load exact ones.`);let n=_i(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Ci(e={}){return H(vi,e.description??bi,yi,async(e,t)=>{let n={loaded:Si(e,xi(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`})}Ci();export{ze as A,dn as C,kt as D,si as E,Tt as O,Pt as S,ni as T,Ci as _,X as a,hr as b,pi as c,xr as d,Er as f,Kn as g,Tn as h,_n as i,Fe as j,E as k,qn as l,ur as m,Nt as n,Z as o,Rr as p,$ as r,zt as s,cn as t,Ln as u,ti as v,Ft as w,H as x,oi as y};
67
+ //# sourceMappingURL=node-D_40SJP5.js.map