@robota-sdk/agent-cli 3.0.0-beta.79 → 3.0.0-beta.81
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +740 -55
- package/dist/node/bin.js +3 -406
- package/dist/node/bounded-output-DpjpS98g-DFgAppgl.js +2 -0
- package/dist/node/bounded-output-DpjpS98g-DFgAppgl.js.map +1 -0
- package/dist/node/bounded-output-DpjpS98g-DoRuRGhV.js +2 -0
- package/dist/node/bounded-output-DpjpS98g-yPybHprY.cjs +1 -0
- package/dist/node/cli-core-Bah38oug.js +2795 -0
- package/dist/node/command-executor-DV-H2oD6-BfKoGoFw.js +2 -0
- package/dist/node/command-executor-DV-H2oD6-OKy8pwYH.js +2 -0
- package/dist/node/command-executor-DV-H2oD6-OKy8pwYH.js.map +1 -0
- package/dist/node/command-executor-DV-H2oD6-iQAXtTLY.cjs +1 -0
- package/dist/node/headless.js +4 -0
- package/dist/node/http-executor-cWzI2svn-C7F17ZGz.cjs +1 -0
- package/dist/node/http-executor-cWzI2svn-TG_TMYKh.js +2 -0
- package/dist/node/http-executor-cWzI2svn-TG_TMYKh.js.map +1 -0
- package/dist/node/http-executor-cWzI2svn-Ype0naht.js +2 -0
- package/dist/node/index.cjs +2641 -251
- package/dist/node/index.d.cts +3421 -0
- package/dist/node/index.d.cts.map +1 -0
- package/dist/node/index.d.ts +3412 -5
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2641 -251
- package/dist/node/index.js.map +1 -1
- package/dist/node/node-2-nrieFn.js +2 -0
- package/dist/node/node-2-nrieFn.js.map +1 -0
- package/dist/node/node-C-hnFnOP.js +67 -0
- package/dist/node/node-CFTax5Wl.cjs +1 -0
- package/dist/node/node-CJnrbkAS.js +14 -0
- package/dist/node/node-CJnrbkAS.js.map +1 -0
- package/dist/node/node-ChG9Tg1I.js +2 -0
- package/dist/node/node-DDl02brx.cjs +66 -0
- package/dist/node/node-DIRGC_1P.js +67 -0
- package/dist/node/node-DIRGC_1P.js.map +1 -0
- package/dist/node/node-OBnZskvR.cjs +1 -0
- package/dist/node/node-bJ0lEuNF.js +2 -0
- package/dist/node/node-bJ0lEuNF.js.map +1 -0
- package/dist/node/node-tf433Aey.cjs +13 -0
- package/dist/node/node-uwhEt6sT.js +14 -0
- package/dist/node/rolldown-runtime-C9xYM0wc.js +1 -0
- package/dist/node/rolldown-runtime-DK3Fl9T5-BIInC43l.cjs +1 -0
- package/dist/node/rolldown-runtime-DK3Fl9T5-BeX3Bzvn.js +2 -0
- package/dist/node/rolldown-runtime-DK3Fl9T5-DK3Fl9T5.js +2 -0
- package/dist/node/rolldown-runtime-DK3Fl9T5-DK3Fl9T5.js.map +1 -0
- package/dist/node/rolldown-runtime-rs7quPpn.js +2 -0
- package/dist/node/verdict-decoder-Dk_w2NG9-BKWMtxp8.js +2 -0
- package/dist/node/verdict-decoder-Dk_w2NG9-Bka7Cldj.js +2 -0
- package/dist/node/verdict-decoder-Dk_w2NG9-Bka7Cldj.js.map +1 -0
- package/dist/node/verdict-decoder-Dk_w2NG9-DNTeVdQ8.cjs +1 -0
- package/dist/web/assets/index-8_Slbxe7.css +1 -0
- package/dist/web/assets/index-Cgu5C1kn.js +77 -0
- package/dist/web/index.html +3 -3
- package/package.json +106 -39
- package/dist/node/bin.d.ts +0 -2
- package/dist/node/bin.js.map +0 -1
- package/dist/web/assets/index-DiahfakU.css +0 -2
- package/dist/web/assets/index-LMW0IDmj.js +0 -37
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
;(function(){var v=parseInt(process.versions.node.split('.')[0],10);if(v<22){process.stderr.write('\n✗ Node.js 22+ is required (current: '+process.version+')\n\nUpgrade:\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22\n Download: https://nodejs.org/en/download\n\n');process.exit(1);}})();
|
|
2
|
+
import{a as e,i as t,n,r}from"./cli-core-Bah38oug.js";import{z as i}from"zod";var a=class{port;constructor(e){this.port=e.skillPort}async resolvePrompt(n){let r;try{r=this.port.loadCommands()}catch(e){return{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to load skills: ${e instanceof Error?e.message:String(e)}`,!0)}}let i=r.find(e=>e.name===n.skillName);return i?i.context===`fork`?{ok:!1,error:e(`DAG_VALIDATION_SKILL_FORK_UNSUPPORTED`,`Skill "${n.skillName}" uses fork context, which the resolver node does not support (no subagent runtime). Use an inject-context skill.`,{skillName:n.skillName})}:this.resolveInject(i,n):{ok:!1,error:e(`DAG_VALIDATION_SKILL_NOT_FOUND`,`Skill "${n.skillName}" was not found in the injected contribution sources`,{skillName:n.skillName},{action:`set_config`,suggestion:`Set skillName to an available skill`,options:r.map(e=>e.name)})}}async resolveInject(e,n){try{let r=await this.port.resolveSkill(e,n.args,n.sessionId===void 0?void 0:{sessionId:n.sessionId});return typeof r.prompt==`string`?{ok:!0,value:{prompt:r.prompt,mode:r.mode}}:{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Skill "${n.skillName}" did not resolve to an inject prompt`,!1,{skillName:n.skillName,mode:r.mode})}}catch(e){let r=e instanceof Error?e.message:String(e);return{ok:!1,error:t(`DAG_TASK_EXECUTION_SKILL_RESOLVE_FAILED`,`Failed to resolve skill "${n.skillName}": ${r}`,!1,{skillName:n.skillName})}}}};const o=i.object({skillName:i.string().min(1),args:i.string().default(``),sessionId:i.string().optional(),baseCredits:i.number().nonnegative().default(0)}),s=[{key:`args`,label:`Args`,order:0,type:`string`,required:!1}],c=[{key:`prompt`,label:`Prompt`,order:0,type:`string`,required:!0},{key:`mode`,label:`Mode`,order:1,type:`string`,required:!0}];var l=class extends n{nodeType=`skill`;displayName=`Skill`;category=`Integration`;inputs=s;outputs=c;configSchemaDefinition=o;defaultInputPort=`args`;defaultOutputPort=`prompt`;runtime;constructor(e){super(),this.runtime=new a(e)}async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:n.baseCredits}}}async executeWithConfig(t,n,i){let a=new r(t,n.nodeDefinition.nodeId),o=a.getInput(`args`),s=typeof o==`string`&&o.trim().length>0?o:i.args,c=await this.runtime.resolvePrompt({skillName:i.skillName,args:s,...i.sessionId===void 0?{}:{sessionId:i.sessionId}});return c.ok?c.value.prompt.trim().length===0?{ok:!1,error:e(`DAG_VALIDATION_SKILL_EMPTY_PROMPT`,`Skill "${i.skillName}" resolved to an empty prompt`,{skillName:i.skillName})}:(a.setOutput(`prompt`,c.value.prompt),a.setOutput(`mode`,c.value.mode),a.setOutput(`_agentSummary`,`Skill "${i.skillName}" resolved (${c.value.mode}): ${c.value.prompt.length} chars.`),{ok:!0,value:a.toOutput()}):c}};export{l as SkillNodeDefinition};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
const e=require("./node-tf433Aey.cjs"),t=require("./bounded-output-DpjpS98g-yPybHprY.cjs");require("./command-executor-DV-H2oD6-iQAXtTLY.cjs"),require("./http-executor-cWzI2svn-C7F17ZGz.cjs");let n=require("node:crypto"),r=require("node:path"),i=require("node:child_process"),a=require("node:fs/promises"),o=require("node:fs"),s=require("node:os"),c=require("zod"),l=require("node:dns/promises"),u=require("node:net"),d=require("fast-glob");d=e.Rt(d,1);let f=require("p-limit");f=e.Rt(f,1);let p=require("node:events"),m=require("node:worker_threads");const h=process.platform===`win32`;function g(e){return e.exitCode!==null||e.signalCode!==null}function _(e,t,n){if(n&&!h&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function v(e,t){if(h&&typeof e.pid==`number`){(0,i.spawnSync)(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}_(e,`SIGKILL`,t)}async function y(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!g(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(g(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),g(e)){e.removeListener(`exit`,o),t();return}_(e,r,i),a=setTimeout(()=>{g(e)||v(e,i)},n),a.unref?.()})}}function b(e){if(typeof e!=`string`)throw TypeError(`executionRoot must be a string`);if(e.trim().length===0)throw TypeError(`executionRoot must be a non-empty string`);if(!(0,r.isAbsolute)(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=(0,o.realpathSync)(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!(0,o.statSync)(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{(0,o.accessSync)(t,o.constants.R_OK|o.constants.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function x(e){let t=[],n=(0,r.resolve)(e);for(;;)try{return(0,r.join)((0,o.realpathSync)(n),...t)}catch{let i=(0,r.dirname)(n);if(i===n)return(0,r.resolve)(e);t.unshift((0,r.basename)(n)),n=i}}function S(e,t){let n=x(e),i=x(t);return i===n||i.startsWith(n+r.sep)}var ee=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function C(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function te(e,t){let n=(0,r.relative)(e,t);if(n.startsWith(`..`)||(0,r.isAbsolute)(n))throw new ee(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let i=n.split(r.sep).filter(e=>e.length>0),a=[e],o=e;for(let e of i)o=(0,r.join)(o,e),a.push(o);return a}function w(e,t,n={}){if(C()!==`posix-mode`)return;let r=(n.readMode??(e=>(0,o.statSync)(e).mode&4095))(e);if(r&63)throw new ee(`${t} ${e} is mode 0${r.toString(8)} after being set owner-only; group or other permissions survived, so its contents are readable by another account.`)}function T(e,t={}){let n=t.makeDirectory??((e,t)=>{(0,o.mkdirSync)(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>(0,o.chmodSync)(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:te(t.withinRoot,e);for(let e of i)C()===`posix-mode`&&r(e,448),w(e,`directory`,t)}function ne(e,t){T((0,r.dirname)(e));let n=`${e}.${process.pid}.tmp`;(0,o.rmSync)(n,{force:!0}),(0,o.writeFileSync)(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{w(n,`file`),(0,o.renameSync)(n,e)}catch(e){try{(0,o.unlinkSync)(n)}catch{}throw e}w(e,`file`)}function re(e){if(C()!==`posix-mode`)return;let t;try{t=(0,o.statSync)(e).mode&4095}catch{return}t&63&&((0,o.chmodSync)(e,384),w(e,`file`))}function ie(e){let t=(0,u.isIP)(e);return t===4?ae(e.split(`.`).map(Number)):t!==6||oe(e)}function ae(e){let[t=0,n=0,r=0]=e;return t===0||t===10||t===127||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===0&&r===0||t===192&&n===168||t===198&&(n===18||n===19)||t>=224}function oe(e){let t=ce(e);if(t===void 0)return!0;let[n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0]=t;return n===0&&r===0&&i===0&&a===0&&o===0&&s===65535||n===100&&r===65435&&i===0&&a===0&&o===0&&s===0?ae([c>>8,c&255,l>>8,l&255]):n===0&&r===0&&i===0&&a===0&&o===0&&s===0||(n&65024)==64512||(n&65472)==65152||(n&65472)==65216||(n&65280)==65280}function se(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);if(!n.includes(`.`))return e;if(t<0||(0,u.isIP)(n)!==4)return;let[r=0,i=0,a=0,o=0]=n.split(`.`).map(Number),s=(r<<8|i).toString(16),c=(a<<8|o).toString(16);return`${e.slice(0,t+1)}${s}:${c}`}function ce(e){let t=se(e.split(`%`)[0]??e);if(t===void 0)return;let n=t.split(`::`);if(n.length>2)return;let r=e=>e.length===0?[]:e.split(`:`).map(e=>Number.parseInt(e,16)),i=r(n[0]??``),a=n.length===2?r(n[1]??``):[],o=8-i.length-a.length;if(o<0||n.length===1&&o!==0)return;let s=[...i,...Array(o).fill(0),...a];return s.some(e=>Number.isNaN(e)||e<0||e>65535)?void 0:s}const le=3e4,ue=5e6,de=new Set([301,302,303,307,308]),fe=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),E=async e=>(await(0,l.lookup)(e,{all:!0,verbatim:!0})).map(e=>e.address);async function D(e,t={},n=E){let r=e.href;if(e.protocol!==`http:`&&e.protocol!==`https:`)return{reason:`unsupported_scheme`,url:r,message:`Only http(s) URLs may be fetched.`};if(t.allowPrivateAddresses===!0)return;let i=e.hostname.replace(/^\[|\]$/g,``).toLowerCase();if(t.allowedHosts?.includes(i))return;if(fe.has(i)||i.endsWith(`.localhost`))return{reason:`metadata_host`,url:r,message:`Destination "${i}" is a loopback or cloud-metadata host and is not reachable from tools.`};let a=(0,u.isIP)(i)?[i]:await pe(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(ie);if(o!==void 0)return{reason:`private_destination`,url:r,message:`Destination "${i}" resolves to ${o}, a private, loopback or link-local address, and is not reachable from tools.`}}async function pe(e,t){try{return await t(e)}catch{return}}async function me(e,t={},n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=r.lookup??E,o=t.maxResponseBytes??ue,s=n.maxRedirects??5,c=AbortSignal.timeout(t.timeoutMs??le),l=t.signal?AbortSignal.any([c,t.signal]):c,u=new URL(e),d={...t.headers??{}};for(let e=0;;e+=1){let t=await D(u,n,a);if(t!==void 0)return{ok:!1,rejection:t};let r=await i(u.href,{headers:d,signal:l,redirect:`manual`});if(!de.has(r.status))return _e(r,u.href,o,l);let c=r.headers.get(`location`);if(c===null)return{ok:!1,rejection:{reason:`redirect_without_location`,url:u.href,message:`HTTP ${r.status} without a Location header.`}};if(e>=s)return{ok:!1,rejection:{reason:`redirect_limit`,url:u.href,message:`More than ${s} redirects.`}};let f=new URL(c,u);f.origin!==u.origin&&(d=ge(d)),u=f}}async function he(e,t,n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=t.maxResponseBytes??ue,o=AbortSignal.timeout(t.timeoutMs??le),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l=await D(c,n,r.lookup??E);if(l!==void 0)return{ok:!1,rejection:l};let u=await i(c.href,{method:`POST`,headers:{...t.headers??{}},body:t.body,signal:s,redirect:`manual`});return u.status>=300&&u.status<400?(await u.body?.cancel().catch(()=>void 0),{ok:!1,rejection:{reason:`redirect_refused`,url:c.href,message:`HTTP ${u.status}: a POST is never redirected.`}}):_e(u,c.href,a,s)}function ge(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function _e(e,t,n,r){let i=e=>({ok:!1,rejection:{reason:`response_too_large`,url:t,message:`Response exceeds ${n} bytes (${e} seen).`}}),a=Number(e.headers.get(`content-length`));if(Number.isFinite(a)&&a>n)return await e.body?.cancel(),i(a);let o=[],s=0;if(!e.body&&typeof e.arrayBuffer==`function`){let t=new Uint8Array(await e.arrayBuffer());if(t.byteLength>n)return i(t.byteLength);o.push(t),s=t.byteLength}else if(e.body){let t=e.body.getReader();for(;;){r.throwIfAborted();let{done:e,value:a}=await t.read();if(e)break;if(s+=a.byteLength,s>n)return await t.cancel(),i(s);o.push(a)}}let c=new Uint8Array(s),l=0;for(let e of o)c.set(e,l),l+=e.byteLength;return{ok:!0,status:e.status,statusText:e.statusText,headers:e.headers,body:c,finalUrl:t}}function ve(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function ye(e){return ve(e)===`sandbox-separate`}function be(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 xe=/^[A-Za-z]:[\\/]/,Se=/'/g;async function Ce(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);be(t);let r=Ne(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=we(a),s=Pe(r,t);i.push(await Te(e,t,s,r,o,n))}return{entries:i}}function we(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(`\\`)||xe.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 Te(e,t,n,r,i,a){switch(i.type){case`file`:return await ke(e,n,r,i.content),O(t,i.type);case`dir`:return await A(e,n),O(t,i.type);case`localFile`:return await Ee(e,i.src,n,r,a),O(t,i.type);case`localDir`:return await De(e,i.src,n,a),O(t,i.type);case`gitRepo`:return await Oe(e,i,n),O(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 Fe(i)}}function O(e,t){return{path:e,type:t,status:`applied`}}async function Ee(e,t,n,r,i){await ke(e,n,r,await(0,a.readFile)(je(t,i.hostRoot),`utf8`))}async function De(e,t,n,r){await k(e,je(t,r.hostRoot),n)}async function k(e,t,n){await A(e,n);let i=await(0,a.readdir)(t,{withFileTypes:!0});for(let o of i){let i=(0,r.join)(t,o.name),s=Pe(n,o.name);if(o.isDirectory()){await k(e,i,s);continue}if(o.isFile()){let t=await(0,a.readFile)(i,`utf8`);await e.writeFile(s,t)}}}async function Oe(e,t,n){await Ae(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${j(t.ref)}`:``} ${j(t.url)} ${j(n)}`)}async function ke(e,t,n,i){let a=r.posix.dirname(t);a!==n&&await A(e,a),await e.writeFile(t,i)}async function A(e,t){await Ae(e,`mkdir -p ${j(t)}`)}async function Ae(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 je(e,t){return(0,r.isAbsolute)(e)?(0,r.resolve)(e):(0,r.resolve)(t??process.cwd(),e)}function Me(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function Ne(e){let t=Me(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Pe(e,t){let n=Ne(e);return n===`/`?`/${t}`:`${n}/${t}`}function j(e){return`'${e.replace(Se,`'\\''`)}'`}function Fe(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}const M=[`.robota/worktrees`,`.claude/worktrees`];function N(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function P(){return[...e.st,...e.yt]}function Ie(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 P()){let i=N(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of M){let i=N(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=N(i,`${t}/.git`);e.exists(r)&&n.push(`--ro-bind`,r,r)}}}for(let r of t.denyRead)e.exists(r.path)&&(r.directory?n.push(`--tmpfs`,r.path):n.push(`--ro-bind`,`/dev/null`,r.path));if(!t.network){if(e.seccompDescriptor===void 0)throw Error(`A sandbox without network needs the Unix-socket seccomp filter.`);n.push(`--unshare-net`,`--seccomp`,String(e.seccompDescriptor))}return n.push(`--unshare-pid`,`--die-with-parent`,`--new-session`,`--chdir`,e.cwd),n.push(`--`,e.command),[...n,...e.args]}function Le(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function F(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Re(t){let n=[t.root,...t.tempDirectories,...t.allowWrite].map(e=>`(subpath ${F(e)})`).join(` `),r=P().map(n=>{let r=N(t.root,n);return e.yt.includes(n)?`(literal ${F(r)})`:`(subpath ${F(r)})`}),i=M.map(e=>`(subpath ${F(N(t.root,e))})`),a=[`(literal ${F(N(t.root,`.git`))})`,...M.map(e=>`(regex #"^${Le(N(t.root,e))}/[^/]+/\\.git$")`)],o=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${n} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${r.join(` `)})`,`(allow file-write* ${i.join(` `)})`,`(deny file-write* ${a.join(` `)})`];if(t.denyRead.length>0){let e=t.denyRead.map(e=>e.directory?`(subpath ${F(e.path)})`:`(literal ${F(e.path)})`);o.push(`(deny file-read* ${e.join(` `)})`)}return t.network||o.push(`(deny network*)`),o.join(`
|
|
2
|
+
`)}const ze={x64:{audit:3221225534,socket:41,ioUringSetup:425},arm64:{audit:3221225655,socket:198,ioUringSetup:425}};function I(e,t,n,r){return[e,t,n,r]}function Be(e=process.arch){let t=ze[e];if(t===void 0)return;let n=e=>327680|e,r=[I(32,0,0,4),I(21,1,0,t.audit),I(6,0,0,n(1)),I(32,0,0,0),I(69,0,1,1073741824),I(6,0,0,n(1)),I(21,0,1,t.ioUringSetup),I(6,0,0,n(1)),I(21,0,3,t.socket),I(32,0,0,16),I(21,0,1,1),I(6,0,0,n(97)),I(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 Ve=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),He=`/usr/bin/sandbox-exec`;function Ue(e,t){let n=(0,i.spawnSync)(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 We(e={}){let t=e.platform??process.platform,n=e.probe??Ue;if(t===`linux`){if(Be(e.arch??process.arch)===void 0)return{backend:`bubblewrap`,missing:[`a seccomp filter for ${e.arch??process.arch} (x64 and arm64 are supported)`]};let t=n(`bwrap`,[`--ro-bind`,`/`,`/`,`--dev`,`/dev`,`--unshare-pid`,`true`]);return t.ok?{backend:`bubblewrap`,executable:`bwrap`,missing:[]}:{backend:`bubblewrap`,missing:[t.detail?.includes(`ENOENT`)?"bubblewrap (install the `bubblewrap` package)":`bubblewrap cannot create a sandbox here${t.detail?`: ${t.detail}`:``}`]}}if(t===`darwin`){let e=n(He,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:He,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function L(e){try{return(0,o.realpathSync)(e)}catch{return e}}function Ge(e){try{return(0,o.statSync)(e).isDirectory()}catch{return!1}}function Ke(e){let t=(0,o.lstatSync)(e);if(!t.isSymbolicLink()&&((0,o.chmodSync)(e,t.mode|448),t.isDirectory()))for(let t of(0,o.readdirSync)(e))Ke(`${e}/${t}`)}function qe(e){try{return(0,o.lstatSync)(e).isSymbolicLink()}catch{return!1}}function Je(e){return e.trim().split(/\s+/)[0]}var Ye=class{filesystem=`shared`;root;availability;homeDirectory;current;inFlight=0;baseline=[];unresolved=new Map;constructor(e){this.root=L(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??(0,s.homedir)(),this.current={...Ve,...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}}confines(t){if(!this.status().active)return!1;if(e.o(t).length!==1)return!0;let n=Je(t);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`,Re(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:Be();this.protectedEntryStates().some(e=>e.path.endsWith(`/.robota`)&&e.kind===`symlink`)||(0,o.mkdirSync)(`${this.root}/.robota`,{recursive:!0});let a=Ie({policy:n,exists:e=>(0,o.existsSync)(e)&&!qe(e),listDirectory:e=>(0,o.readdirSync)(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 s=!1;return{command:r,args:a,cwd:e.cwd,...i===void 0?{}:{inputDescriptors:[i]},afterExit:()=>{if(!s)return s=!0,--this.inFlight,this.restoreProtectedEntries(this.baseline)}}}protectedEntryStates(){return P().map(e=>{let t=`${this.root}/${e}`;try{return(0,o.lstatSync)(t).isSymbolicLink()?{path:t,kind:`symlink`,target:(0,o.readlinkSync)(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=(0,o.realpathSync)(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()}-${(0,n.randomUUID)()}`,r=[];for(let n of e)if(n.kind!==`present`)try{let e=this.protectedEntryStates().find(e=>e.path===n.path);if(n.kind===`missing`&&e.kind===`missing`){this.unresolved.delete(n.path);continue}if(n.kind===`symlink`&&e.kind===`symlink`&&e.target===n.target){this.unresolved.delete(n.path);continue}e.kind!==`missing`&&r.push(this.setAside(n.path,t)),n.kind===`symlink`&&(0,o.symlinkSync)(n.target,n.path),this.unresolved.delete(n.path)}catch(e){this.unresolved.set(n.path,n),r.push(`could not restore ${n.path} (${e instanceof Error?e.message:String(e)}); commands will ask until it is removed`)}if(r.length!==0)return`[sandbox] A confined command may not create or replace git, agent, MCP or shell configuration: ${r.join(`; `)}.`}quarantineRoot(e){let t=`${this.root}/.robota`;return e.some(e=>e.path===t&&e.kind===`present`)?`${t}/sandbox-quarantine`:`${this.homeDirectory}/.robota/sandbox-quarantine`}setAside(e,t){let n=`${t}/${(0,r.basename)(e)}`;(0,o.mkdirSync)(t,{recursive:!0});try{(0,o.renameSync)(e,n)}catch(t){if(this.inFlight>0)throw t;Ke(e),t.code===`EXDEV`?((0,o.cpSync)(e,n,{recursive:!0,verbatimSymlinks:!0}),(0,o.rmSync)(e,{recursive:!0,force:!0})):(0,o.renameSync)(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return L((0,r.isAbsolute)(t)?t:(0,r.resolve)(this.root,t))},t=[...new Set([(0,s.tmpdir)(),`/tmp`].filter(o.existsSync).map(L))];return{root:this.root,tempDirectories:t,allowWrite:this.current.allowWrite.map(e),denyRead:this.current.denyRead.map(t=>{let n=e(t);return{path:n,directory:Ge(n)}}),network:this.current.network}}run(e,n={}){let r=t.n(),a=n.workingDirectory??this.root,o=this.wrapCommand({command:r.command,args:r.commandArgs(e),cwd:a},e);return new Promise((e,t)=>{let r=o.inputDescriptors??[],a;try{a=(0,i.spawn)(o.command,[...o.args],{cwd:o.cwd,stdio:[`ignore`,`pipe`,`pipe`,...r.map(()=>`pipe`)],...n.timeoutMs===void 0?{}:{timeout:n.timeoutMs}})}catch(e){o.afterExit?.(),t(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 s=``,c=``;a.stdout?.on(`data`,e=>s+=e.toString()),a.stderr?.on(`data`,e=>c+=e.toString()),a.on(`error`,e=>{o.afterExit?.(),t(e)}),a.on(`close`,t=>{let n=o.afterExit?.();e({stdout:n===void 0?s:`${s}\n${n}`,...c?{stderr:c}:{},exitCode:t??1})})})}readFile(e){return Promise.resolve((0,o.readFileSync)(e,`utf8`))}writeFile(e,t){return(0,o.writeFileSync)(e,t,`utf8`),Promise.resolve()}};function R(n,r,i,a,o={}){let s={name:n,description:r,parameters:e.et(i),...o.deferLoading!==void 0&&{deferLoading:o.deferLoading}};return new e.Mt(s,async(e,n)=>{let r=i.safeParse(e);if(!r.success)throw new t.v(`Zod validation failed: ${r.error}`);let o=await a(r.data,n);return typeof o==`string`?o:JSON.stringify(o)})}const Xe={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 Ze(){for(let[t,n]of Object.entries(Xe))e.B(t,n)}Ze();const Qe=1e3,$e=c.z.object({activeFiles:c.z.array(c.z.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:c.z.array(c.z.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:c.z.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Qe}).`)});function et(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
|
|
4
|
+
`)}async function tt(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??Qe});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${et(n.symbols)}`}function nt(e={}){return R(`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.`,$e,async t=>tt(t,e))}const rt=`Computer use is not available in this session (no driver injected).`,it=c.z.enum([`left`,`right`,`middle`]),at=c.z.object({x:c.z.number(),y:c.z.number()}),ot=c.z.object({type:c.z.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:c.z.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:c.z.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:it.optional().describe(`Mouse button (click/double_click/drag).`),text:c.z.string().optional().describe(`Text to type (type).`),keys:c.z.array(c.z.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:c.z.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:c.z.number().optional().describe(`Vertical wheel delta (scroll).`),path:c.z.array(at).optional().describe(`Points to drag through (drag).`),ms:c.z.number().optional().describe(`Milliseconds to wait (wait).`),reason:c.z.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),st=c.z.object({action:ot.describe(`The single mutating action to perform.`)}),ct=c.z.object({});var z=class extends Error{};function B(e,t,n){if(typeof e!=`number`)throw new z(`Action '${n}' requires numeric '${t}'.`);return e}function lt(e){let t=e.button;switch(e.type){case`click`:return{type:`click`,x:B(e.x,`x`,`click`),y:B(e.y,`y`,`click`),...t?{button:t}:{}};case`double_click`:return{type:`double_click`,x:B(e.x,`x`,`double_click`),y:B(e.y,`y`,`double_click`),...t?{button:t}:{}};case`type`:if(typeof e.text!=`string`)throw new z(`Action 'type' requires 'text'.`);return{type:`type`,text:e.text};case`keypress`:if(!e.keys||e.keys.length===0)throw new z(`Action 'keypress' requires non-empty 'keys'.`);return{type:`keypress`,keys:e.keys};case`scroll`:return{type:`scroll`,x:B(e.x,`x`,`scroll`),y:B(e.y,`y`,`scroll`),deltaX:B(e.deltaX,`deltaX`,`scroll`),deltaY:B(e.deltaY,`deltaY`,`scroll`)};case`drag`:if(!e.path||e.path.length<2)throw new z(`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 z(`Unknown action type: ${String(t)}`)}}}async function ut(e){if(!e.driver)return JSON.stringify({success:!1,error:rt});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function dt(e,t){if(!t.driver)return JSON.stringify({success:!1,error:rt});let n;try{n=lt(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 ft(e={}){return R(`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.`,ct,async()=>ut(e))}function pt(e={}){return R(`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.",st,async t=>dt(t,e))}function mt(e={}){return[ft(e),pt(e)]}const ht=[{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 gt(e,t){let n=t?ht.filter(e=>t.includes(e.toolName)):ht,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 V=process.platform!==`win32`,_t=2e6,vt=c.z.object({command:c.z.string().describe(`The shell command to execute`),timeout:c.z.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:c.z.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});async function yt(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 bt(e,n,r,a,o){let{command:s,timeout:c=12e4,workingDirectory:l}=e,u=Math.min(c,6e5),d=l??n.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(n.sandboxClient&&n.sandboxClient.wrapCommand===void 0)return yt(s,u,l??n.cwd,n);let f={command:r.command,args:r.commandArgs(s),cwd:d},p=n.sandboxClient?.wrapCommand?.(f,s)??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 a?.aborted?(h(),JSON.stringify({success:!1,output:``,error:`Aborted before start`})):new Promise(e=>{let n=t.a({maxBytes:_t}),r=t.a({maxBytes:_t}),s=!1,c=!1,l;try{l=(0,i.spawn)(p.command,[...p.args],{cwd:p.cwd,env:o===void 0?process.env:t.s(process.env,o),stdio:[`pipe`,`pipe`,`pipe`,...(p.inputDescriptors??[]).map(()=>`pipe`)],detached:V})}catch(t){let n=h(),r=t instanceof Error?t.message:String(t);e(JSON.stringify({success:!1,output:n??``,error:r}));return}(p.inputDescriptors??[]).forEach((e,t)=>{let n=l.stdio[t+3];n?.on(`error`,()=>void 0),n?.end(Buffer.from(e))}),l.stdin?.end(),l.stdout?.on(`data`,e=>{n.append(e)}),l.stderr?.on(`data`,e=>{r.append(e)});let d=setTimeout(()=>{s=!0,y(l,{processGroup:V}),f({success:!1,output:n.toString(),error:`Command timed out after ${u}ms`})},u);function f(t){c||(c=!0,clearTimeout(d),a?.removeEventListener(`abort`,m),e(JSON.stringify(t)))}function m(){y(l,{processGroup:V}),f({success:!1,output:n.toString(),error:`Aborted`})}a?.addEventListener(`abort`,m,{once:!0}),l.on(`error`,e=>{l.pid===void 0&&h(),f({success:!1,output:``,error:e.message})}),l.on(`close`,e=>{let t=h();if(s){f({success:!1,output:n.toString(),error:`Command timed out after ${u}ms`,exitCode:e??void 0});return}let i=n.toString(),a=r.toString(),o=e??0,c=a?`${i}\nstderr:\n${a}`:i;f({success:!0,output:t===void 0?c:`${c}\n${t}`,exitCode:o})})})}function xt(e,n){let r=t.n({executable:n.shellExecutable});return R(e,n.description??gt(r,n.availableTools),vt,async(e,t)=>bt(e,n,r,t?.signal,t?.shellTraceEnv))}function St(e){return xt(`Shell`,e)}function Ct(e){return xt(`Bash`,e)}function H(e,t){return t!==void 0&&S(t,e)}function U(e,t){return t===void 0?e:(0,r.resolve)(t,e)}function W(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(!H(e,t)){let t={success:!1,output:``,error:`Access denied: "${e}" is outside the working directory`};return JSON.stringify(t)}}function wt(e,t){if(t===void 0)return{root:``,error:W(e??``,void 0)};let n=e?(0,r.resolve)(t,e):t;return{root:n,error:W(n,t)}}const Tt=2e3,G=4*1024*1024;var K=class extends t.d{boundary;constructor(e){super(`Read ${e} exceeds its UTF-8 byte limit`,`Read`),this.boundary=e}},q=class extends t.d{constructor(){super(`Read cancelled`,`Read`)}};const Et=c.z.object({filePath:c.z.string().describe(`The absolute path to the file to read`),offset:c.z.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.z.number().optional().describe(`The number of lines to read (default: ${Tt}). Only provide if the file is too large to read at once`)});function Dt(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function Ot(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 kt(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>G)throw new K(`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>G)throw new K(`output`);let m={success:!0,output:d+Ot(i,n)};return JSON.stringify(m)}async function At(e,t){if(t.signal?.aborted)throw new q;let{offset:n,limit:r=Tt}=e,i=t.sandboxClient?e.filePath:U(e.filePath,t.cwd),o=n!==void 0&&n>0?n:1;if(t.sandboxClient)try{let e=await t.sandboxClient.readFile(i);if(t.signal?.aborted)throw new q;if(Buffer.byteLength(e,`utf8`)>G)throw new K(`input`);return kt(i,e,o,r)}catch(e){if(e instanceof K||e instanceof q)throw e;let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let s=W(i,t.cwd);if(s!==void 0)return s;let c;try{c=await(0,a.stat)(i)}catch{let e={success:!1,output:``,error:`File not found: ${i}`};return JSON.stringify(e)}if(!c.isFile()){let e={success:!1,output:``,error:`Path is not a file: ${i}`};return JSON.stringify(e)}let l=Buffer.alloc(0),u=!1;try{let e=await(0,a.open)(i,`r`);try{let n=[],r=Buffer.allocUnsafe(65536),i=0,a=0;for(;i<=G;){if(t.signal?.aborted)throw new q;let{bytesRead:o}=await e.read(r,0,Math.min(r.length,4194305-i),null);if(o===0)break;let s=Math.min(o,8192-a);if(s>0&&Dt(r.subarray(0,s))){u=!0;break}if(a+=s,i+=o,i>G)throw new K(`input`);n.push(Buffer.from(r.subarray(0,o)))}u||(l=Buffer.concat(n,i))}finally{await e.close()}}catch(e){if(e instanceof K||e instanceof q)throw e;let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}if(t.signal?.aborted)throw new q;if(u){let e={success:!1,output:``,error:`Binary file not supported: ${i}`};return JSON.stringify(e)}return kt(i,l.toString(`utf8`),o,r)}function jt(e){return R(`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.`,Et,async t=>At(t,e))}function Mt(e){let t=(0,r.dirname)(e),i=(0,r.basename)(e),a=(0,n.randomBytes)(6).toString(`hex`);return(0,r.join)(t,`.${i}.atomic-tmp-${process.pid}-${Date.now()}-${a}`)}async function Nt(e){try{return(await(0,a.stat)(e)).mode&4095}catch(e){if(e instanceof Error&&Pt(e,`ENOENT`))return;throw e}}function Pt(e,t){return`code`in e&&e.code===t}async function Ft(e,t){await(0,a.mkdir)((0,r.dirname)(e),{recursive:!0});let n=await Nt(e),i=Mt(e);try{await(0,a.writeFile)(i,t,`utf8`),n!==void 0&&await(0,a.chmod)(i,n),await(0,a.rename)(i,e)}catch(e){throw await(0,a.rm)(i,{force:!0}).catch(()=>void 0),e}}const It=c.z.object({filePath:c.z.string().describe(`The absolute path to the file to write`),content:c.z.string().describe(`The content to write to the file`)});async function Lt(e,t){let{content:n}=e,r=t.sandboxClient?e.filePath:U(e.filePath,t.cwd);if(!t.sandboxClient){let e=W(r,t.cwd);if(e!==void 0)return e}try{t.sandboxClient?await t.sandboxClient.writeFile(r,n):await Ft(r,n);let e={success:!0,output:`Written ${Buffer.byteLength(n,`utf8`)} bytes to ${r}`};return JSON.stringify(e)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}function Rt(e){return R(`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.`,It,async t=>Lt(t,e))}const zt=c.z.object({filePath:c.z.string().describe(`The absolute path to the file to modify`),oldString:c.z.string().describe(`The text to replace (must be an exact match of existing content)`),newString:c.z.string().describe(`The text to replace it with (must be different from oldString)`),replaceAll:c.z.boolean().optional().describe(`Replace all occurrences of oldString (default: false). Useful for renaming variables`)}),J=4*1024*1024;var Y=class extends Error{boundary;constructor(e){super(`Edit ${e} exceeds its ${J}-byte limit`),this.boundary=e}};async function Bt(e,t){let n=(0,o.createReadStream)(e,{highWaterMark:65536}),r=[],i=0;try{for await(let e of n){let n=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=n.length,i>t)throw new Y(`input`);r.push(n)}}finally{n.destroy()}return Buffer.concat(r,i).toString(`utf8`)}async function Vt(e,t){let{oldString:n,newString:r,replaceAll:i=!1}=e,a=t.sandboxClient?e.filePath:U(e.filePath,t.cwd);if(!t.sandboxClient){let e=W(a,t.cwd);if(e!==void 0)return e}let o;try{if(t.sandboxClient){if(o=await t.sandboxClient.readFile(a),Buffer.byteLength(o,`utf8`)>J)throw new Y(`input`)}else o=await Bt(a,J)}catch(e){if(e instanceof Y){let t={success:!1,output:``,error:`${e.message}: ${a}`};return JSON.stringify(t)}let t={success:!1,output:``,error:`File not found: ${a}`};return JSON.stringify(t)}if(!o.includes(n)){let e={success:!1,output:``,error:`oldString not found in file: ${a}`};return JSON.stringify(e)}let s=[];if(i)s=o.split(n);else if(o.indexOf(n)!==o.lastIndexOf(n)){let e={success:!1,output:``,error:`oldString is not unique in file (found ${o.split(n).length-1} occurrences). Provide more context to make it unique, or use replaceAll:true.`};return JSON.stringify(e)}let c=i?s.length-1:1,l=Buffer.byteLength(n,`utf8`),u=Buffer.byteLength(r,`utf8`);if(Buffer.byteLength(o,`utf8`)-c*l+c*u>J){let e={success:!1,output:``,error:`Edit output exceeds its ${J}-byte limit: ${a}`};return JSON.stringify(e)}let d=i?s.join(r):o.slice(0,o.indexOf(n))+r+o.slice(o.indexOf(n)+n.length);try{t.sandboxClient?await t.sandboxClient.writeFile(a,d):await Ft(a,d)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let f=o.indexOf(n),p=f>=0?o.substring(0,f).split(`
|
|
18
|
+
`).length:1,m={success:!0,output:`Replaced ${c} occurrence(s) in ${a}`,startLine:p};return JSON.stringify(m)}function Ht(e){return R(`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.`,zt,async t=>Vt(t,e))}const Ut=c.z.object({pattern:c.z.string().describe(`The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.tsx")`),path:c.z.string().optional().describe(`The directory to search in. Defaults to the current working directory. Must be a valid directory path if provided`),limit:c.z.number().optional().describe(`Maximum number of results to return (default: 1000). Use a smaller limit to save context space`)});async function Wt(e,t,n){let i=(0,f.default)(100);return(await Promise.all(e.map(e=>i(async()=>{let i=(0,r.resolve)(t,e);if(H(i,n))try{return{path:e,mtime:(await(0,a.stat)(i)).mtimeMs}}catch{return{path:e,mtime:0}}})))).filter(e=>e!==void 0).sort((e,t)=>t.mtime-e.mtime)}async function Gt(e,t,n){let r=[],i=!1,a=d.default.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 Kt(e,t,n=5e4){let{pattern:r,path:i}=e,a=t.cwd,{root:o,error:s}=wt(i,a);if(s)return s;let c;try{c=await Gt(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 Wt(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)`;return 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.]`),JSON.stringify({success:!0,output:g})}function qt(e){return R(`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.`,Ut,async t=>Kt(t,e))}function Jt(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`[^/]*`);return RegExp(`^${t}$`)}function Yt(e,t){return t===void 0||Jt(t).test(e)}async function Xt(e,t,n,i=5e4){let o=[],s=0,c=!1;async function l(e){if(c)return;let u;try{u=await(0,a.readdir)(e)}catch{return}for(let d of u){if(c)return;if(d===`node_modules`||d===`.git`)continue;let u=(0,r.join)(e,d);if(!H(u,n))continue;if(s>=i){c=!0;return}s++;let f;try{f=await(0,a.stat)(u)}catch{continue}f.isDirectory()?await l(u):f.isFile()&&Yt(d,t)&&o.push(u)}}return await l(e),{files:o,truncated:c}}function Zt(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 Qt=`
|
|
33
|
+
const { parentPort } = require('node:worker_threads');
|
|
34
|
+
const searchFile = ${Zt.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 $t=class extends p.EventEmitter{child=(0,i.spawn)(process.execPath,[`-e`,`
|
|
47
|
+
const searchFile = ${Zt.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:(0,s.tmpdir)(),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}},en=class{pattern;signal;worker=process.versions.bun?new $t:new m.Worker(Qt,{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 tn=c.z.object({pattern:c.z.string().describe(`The regular expression pattern to search for in file contents`),path:c.z.string().optional().describe(`File or directory to search in. Defaults to the current working directory`),glob:c.z.string().optional().describe(`Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched`),contextLines:c.z.number().optional().describe(`Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0`),outputMode:c.z.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.z.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`)}),nn=4*1024*1024;var X=class extends t.d{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 rn(e,t){let{pattern:n,path:r,glob:i,contextLines:s=0,outputMode:c=`files_with_matches`,headLimit:l}=e,u=t.cwd,{root:d,error:f}=wt(r,u);if(f)return f;try{new RegExp(n)}catch{let e={success:!1,output:``,error:`Invalid regex pattern: ${n}`};return JSON.stringify(e)}let p;try{p=await(0,a.stat)(d)}catch{let e={success:!1,output:``,error:`Path not found: ${d}`};return JSON.stringify(e)}let m,h=!1;if(p.isFile())m=[d];else{let e=await Xt(d,i,u);m=e.files,h=e.truncated}let g=new en(n,t.signal),_=new AbortController,v=()=>_.abort();t.signal?.addEventListener(`abort`,v,{once:!0}),t.signal?.aborted&&v();let y;try{if(_.signal.aborted)throw new X(`cancelled`);let e=Array(m.length),t=0,n,r=async e=>{let t;try{if((await(0,a.stat)(e)).size>nn)throw new X(`limit`);let n=(0,o.createReadStream)(e,{highWaterMark:65536,signal:_.signal}),r=[],i=0;try{for await(let e of n){if(_.signal.aborted)throw new X(`cancelled`);let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=t.length,i>nn)throw new X(`limit`);r.push(t)}}finally{n.destroy()}let s=Buffer.concat(r,i),c=Math.min(s.length,8192),l=!1;for(let e=0;e<c;e++)if(s[e]===0){l=!0;break}if(l)return[];t=s.toString(`utf8`)}catch(e){if(e instanceof X)throw e;if(_.signal.aborted)throw new X(`cancelled`);return[]}return g.search(t,e,s,c)};if(await Promise.all(Array.from({length:Math.min(8,m.length)},async()=>{for(;n===void 0&&t<m.length;){let i=t++;try{e[i]=await r(m[i])}catch(e){n===void 0&&(n=e,_.abort(),g.stop(e instanceof Error?e:Error(`Grep search failed`)))}}})),n!==void 0)throw n;y=e}catch(e){let t=e instanceof Error?e.message:``;throw e instanceof X?e:new X(t.includes(`timed out`)?`timeout`:t.includes(`cancelled`)?`cancelled`:t.includes(`byte limit`)?`limit`:`failed`)}finally{t.signal?.removeEventListener(`abort`,v),await g.stop()}let b=0;for(let e of y)for(let t of e)if(b+=Buffer.byteLength(t,`utf8`)+1,b>4*1024*1024)throw new X(`limit`);let x=y.flat();if(l!==void 0&&x.length>l){let e=x.length-l;x=[...x.slice(0,l),`(+${e} more results truncated by headLimit)`]}h&&(x=[...x,`[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 S={success:!0,output:x.length>0?x.join(`
|
|
64
|
+
`):`(no matches)`};return JSON.stringify(S)}function an(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 on(e){return R(`Grep`,e.description??an(e.shellToolName??`Shell`),tn,async t=>rn(t,e))}const sn=3e4,cn=5e6,ln=c.z.object({url:c.z.string().describe(`The URL to fetch`),headers:c.z.record(c.z.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function Z(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 un(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 dn={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`," ":` `},fn=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function pn(e){return un(Z(Z(e,`script`),`style`)).replace(fn,e=>dn[e]).replace(/\s+/g,` `).trim()}function mn(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${sn/1e3}s. The server did not respond in time.`;let t=e.code;return t===`ENOTFOUND`||t===`EAI_AGAIN`?`Network error: DNS resolution failed for this host. The URL may be incorrect or the host does not exist. Do not retry with the same URL.`:t===`ECONNREFUSED`?`Network error: Connection refused. The server is not accepting connections at this address. Do not retry with the same URL.`:t===`ECONNRESET`?`Network error: Connection was reset by the server. The server may be temporarily unavailable.`:t===`ETIMEDOUT`?`Network error: Connection timed out. The server is not reachable within the expected time.`:t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?`Network error: SSL certificate error (${t}). The server's certificate is invalid. Do not retry with the same URL.`:`Network error: ${e.message} Check that the URL is correct and the server is reachable.`}async function hn(e,t,n){let{url:r,headers:i}=e;try{new URL(r)}catch{let e={success:!1,output:``,error:`Invalid URL: "${r}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=await me(r,{headers:{"User-Agent":`Robota-CLI/3.0`,...i??{}},signal:n,timeoutMs:sn,maxResponseBytes:cn},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 ${cn} bytes). Consider fetching a more specific URL or a paginated endpoint.`:`Blocked by egress policy: ${t.message} Do not retry with the same URL.`};return JSON.stringify(n)}if(e.status<200||e.status>=300){let t=e.status>=500?` The server is temporarily unavailable — retrying may help.`:` Do not retry with the same URL.`,n={success:!1,output:``,error:`HTTP ${e.status} ${e.statusText}.${t}`};return JSON.stringify(n)}let a=e.headers.get(`content-type`)??``,o=new TextDecoder().decode(e.body);return a.includes(`html`)&&(o=pn(o)),JSON.stringify({success:!0,output:o})}catch(e){let t={success:!1,output:``,error:mn(e)};return JSON.stringify(t)}}function gn(e={}){let t=e.egress??{};return R(`WebFetch`,e.description??`Fetch a URL and return its content as text. HTML pages are converted to plain text.`,ln,async(e,n)=>hn(e,t,n?.signal))}const _n=gn();function vn(){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 yn=c.z.object({query:c.z.string().describe(`The search query`),limit:c.z.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function bn(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 xn(e={}){let t=e.provider??vn();return R(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,yn,async(e,n)=>bn(e,t,n?.signal))}const Sn=xn(),Cn=c.z.object({question:c.z.string().min(1).describe(`The complete question to ask the user.`),header:c.z.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:c.z.array(c.z.union([c.z.string().min(1).describe(`Display text of this choice.`),c.z.object({label:c.z.string().min(1).describe(`Display text of this choice.`),description:c.z.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:c.z.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:c.z.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),wn=c.z.object({questions:c.z.array(Cn).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),Tn=[`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 En(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),r=e.multiSelect===!0&&t.length>1;return{id:`ask_${(0,n.randomUUID)()}`,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:r?t.length:1,allowFreeText:e.allowFreeText!==!1||t.length===0}}async function Dn(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(En(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 On(e={}){return R(`AskUserQuestion`,e.description??Tn,wn,async(e,t)=>{let n=e,r=t?.ask,i=r?await Dn(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}On();const kn=1/0;function Q(e,t){e.description!==void 0&&t.push(e.description);for(let[n,r]of Object.entries(e.properties??{}))t.push(n),Q(r,t);e.items!==void 0&&Q(e.items,t);for(let n of e.anyOf??[])Q(n,t)}function An(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 Q(e.parameters,r),r.some(e=>e.toLowerCase().includes(t))?3:kn}function jn(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:An(e,r)})).filter(e=>e.rank!==kn).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const $=e.T,Mn=c.z.object({query:c.z.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.z.array(c.z.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:c.z.number().int().positive().optional().describe(`Maximum tools to load from a query match (default 5).`)}),Nn=[`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 Pn(e){let t=e?.deferredTools;if(!t)throw Error(`${$} 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 Fn(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${$} needs either "query" to search for tools or "names" to load exact ones.`);let n=jn(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function In(e={}){return R($,e.description??Nn,Mn,async(e,t)=>{let n={loaded:Fn(e,Pn(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)})}In(),Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return Sn}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return he}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return 2e3}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return _n}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return Rt}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return We}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return Ct}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return qt}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return on}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return In}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return St}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return mt}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return nt}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return jt}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Ye}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return On}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return Ht}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return ve}});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import{B as e,Mt as t,T as n,et as r,o as i,st as a,yt as o}from"./node-CJnrbkAS.js";import{a as s,d as c,n as l,s as u,v as d}from"./bounded-output-DpjpS98g-DFgAppgl.js";import"./command-executor-DV-H2oD6-OKy8pwYH.js";import"./http-executor-cWzI2svn-TG_TMYKh.js";import{randomBytes as f,randomUUID as p}from"node:crypto";import{basename as m,dirname as h,isAbsolute as g,join as _,posix as v,relative as y,resolve as b,sep as ee}from"node:path";import{spawn as x,spawnSync as te}from"node:child_process";import{chmod as ne,mkdir as re,open as ie,readFile as ae,readdir as oe,rename as se,rm as ce,stat as S,writeFile as le}from"node:fs/promises";import{accessSync as ue,chmodSync as de,constants as fe,cpSync as pe,createReadStream as me,existsSync as he,lstatSync as ge,mkdirSync as C,readFileSync as _e,readdirSync as ve,readlinkSync as ye,realpathSync as w,renameSync as T,rmSync as be,statSync as E,symlinkSync as xe,unlinkSync as Se,writeFileSync as Ce}from"node:fs";import{homedir as we,tmpdir as Te}from"node:os";import{z as D}from"zod";import{lookup as Ee}from"node:dns/promises";import{isIP as De}from"node:net";import Oe from"fast-glob";import ke from"p-limit";import{EventEmitter as Ae}from"node:events";import{Worker as je}from"node:worker_threads";const Me=2e3,Ne=process.platform===`win32`;function O(e){return e.exitCode!==null||e.signalCode!==null}function Pe(e,t,n){if(n&&!Ne&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function Fe(e,t){if(Ne&&typeof e.pid==`number`){te(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Pe(e,`SIGKILL`,t)}async function k(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!O(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(O(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),O(e)){e.removeListener(`exit`,o),t();return}Pe(e,r,i),a=setTimeout(()=>{O(e)||Fe(e,i)},n),a.unref?.()})}}function Ie(e){if(typeof e!=`string`)throw TypeError(`executionRoot must be a string`);if(e.trim().length===0)throw TypeError(`executionRoot must be a non-empty string`);if(!g(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=w(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!E(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{ue(t,fe.R_OK|fe.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function Le(e){let t=[],n=b(e);for(;;)try{return _(w(n),...t)}catch{let r=h(n);if(r===n)return b(e);t.unshift(m(n)),n=r}}function Re(e,t){let n=Le(e),r=Le(t);return r===n||r.startsWith(n+ee)}var ze=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function A(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function Be(e,t){let n=y(e,t);if(n.startsWith(`..`)||g(n))throw new ze(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let r=n.split(ee).filter(e=>e.length>0),i=[e],a=e;for(let e of r)a=_(a,e),i.push(a);return i}function j(e,t,n={}){if(A()!==`posix-mode`)return;let r=(n.readMode??(e=>E(e).mode&4095))(e);if(r&63)throw new ze(`${t} ${e} is mode 0${r.toString(8)} after being set owner-only; group or other permissions survived, so its contents are readable by another account.`)}function Ve(e,t={}){let n=t.makeDirectory??((e,t)=>{C(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>de(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:Be(t.withinRoot,e);for(let e of i)A()===`posix-mode`&&r(e,448),j(e,`directory`,t)}function He(e,t){Ve(h(e));let n=`${e}.${process.pid}.tmp`;be(n,{force:!0}),Ce(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{j(n,`file`),T(n,e)}catch(e){try{Se(n)}catch{}throw e}j(e,`file`)}function Ue(e){if(A()!==`posix-mode`)return;let t;try{t=E(e).mode&4095}catch{return}t&63&&(de(e,384),j(e,`file`))}function We(e){let t=De(e);return t===4?Ge(e.split(`.`).map(Number)):t!==6||Ke(e)}function Ge(e){let[t=0,n=0,r=0]=e;return t===0||t===10||t===127||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===0&&r===0||t===192&&n===168||t===198&&(n===18||n===19)||t>=224}function Ke(e){let t=Je(e);if(t===void 0)return!0;let[n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0]=t;return n===0&&r===0&&i===0&&a===0&&o===0&&s===65535||n===100&&r===65435&&i===0&&a===0&&o===0&&s===0?Ge([c>>8,c&255,l>>8,l&255]):n===0&&r===0&&i===0&&a===0&&o===0&&s===0||(n&65024)==64512||(n&65472)==65152||(n&65472)==65216||(n&65280)==65280}function qe(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);if(!n.includes(`.`))return e;if(t<0||De(n)!==4)return;let[r=0,i=0,a=0,o=0]=n.split(`.`).map(Number),s=(r<<8|i).toString(16),c=(a<<8|o).toString(16);return`${e.slice(0,t+1)}${s}:${c}`}function Je(e){let t=qe(e.split(`%`)[0]??e);if(t===void 0)return;let n=t.split(`::`);if(n.length>2)return;let r=e=>e.length===0?[]:e.split(`:`).map(e=>Number.parseInt(e,16)),i=r(n[0]??``),a=n.length===2?r(n[1]??``):[],o=8-i.length-a.length;if(o<0||n.length===1&&o!==0)return;let s=[...i,...Array(o).fill(0),...a];return s.some(e=>Number.isNaN(e)||e<0||e>65535)?void 0:s}const Ye=3e4,Xe=5e6,Ze=new Set([301,302,303,307,308]),Qe=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),M=async e=>(await Ee(e,{all:!0,verbatim:!0})).map(e=>e.address);async function N(e,t={},n=M){let r=e.href;if(e.protocol!==`http:`&&e.protocol!==`https:`)return{reason:`unsupported_scheme`,url:r,message:`Only http(s) URLs may be fetched.`};if(t.allowPrivateAddresses===!0)return;let i=e.hostname.replace(/^\[|\]$/g,``).toLowerCase();if(t.allowedHosts?.includes(i))return;if(Qe.has(i)||i.endsWith(`.localhost`))return{reason:`metadata_host`,url:r,message:`Destination "${i}" is a loopback or cloud-metadata host and is not reachable from tools.`};let a=De(i)?[i]:await $e(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(We);if(o!==void 0)return{reason:`private_destination`,url:r,message:`Destination "${i}" resolves to ${o}, a private, loopback or link-local address, and is not reachable from tools.`}}async function $e(e,t){try{return await t(e)}catch{return}}async function et(e,t={},n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=r.lookup??M,o=t.maxResponseBytes??Xe,s=n.maxRedirects??5,c=AbortSignal.timeout(t.timeoutMs??Ye),l=t.signal?AbortSignal.any([c,t.signal]):c,u=new URL(e),d={...t.headers??{}};for(let e=0;;e+=1){let t=await N(u,n,a);if(t!==void 0)return{ok:!1,rejection:t};let r=await i(u.href,{headers:d,signal:l,redirect:`manual`});if(!Ze.has(r.status))return rt(r,u.href,o,l);let c=r.headers.get(`location`);if(c===null)return{ok:!1,rejection:{reason:`redirect_without_location`,url:u.href,message:`HTTP ${r.status} without a Location header.`}};if(e>=s)return{ok:!1,rejection:{reason:`redirect_limit`,url:u.href,message:`More than ${s} redirects.`}};let f=new URL(c,u);f.origin!==u.origin&&(d=nt(d)),u=f}}async function tt(e,t,n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=t.maxResponseBytes??Xe,o=AbortSignal.timeout(t.timeoutMs??Ye),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l=await N(c,n,r.lookup??M);if(l!==void 0)return{ok:!1,rejection:l};let u=await i(c.href,{method:`POST`,headers:{...t.headers??{}},body:t.body,signal:s,redirect:`manual`});return u.status>=300&&u.status<400?(await u.body?.cancel().catch(()=>void 0),{ok:!1,rejection:{reason:`redirect_refused`,url:c.href,message:`HTTP ${u.status}: a POST is never redirected.`}}):rt(u,c.href,a,s)}function nt(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function rt(e,t,n,r){let i=e=>({ok:!1,rejection:{reason:`response_too_large`,url:t,message:`Response exceeds ${n} bytes (${e} seen).`}}),a=Number(e.headers.get(`content-length`));if(Number.isFinite(a)&&a>n)return await e.body?.cancel(),i(a);let o=[],s=0;if(!e.body&&typeof e.arrayBuffer==`function`){let t=new Uint8Array(await e.arrayBuffer());if(t.byteLength>n)return i(t.byteLength);o.push(t),s=t.byteLength}else if(e.body){let t=e.body.getReader();for(;;){r.throwIfAborted();let{done:e,value:a}=await t.read();if(e)break;if(s+=a.byteLength,s>n)return await t.cancel(),i(s);o.push(a)}}let c=new Uint8Array(s),l=0;for(let e of o)c.set(e,l),l+=e.byteLength;return{ok:!0,status:e.status,statusText:e.statusText,headers:e.headers,body:c,finalUrl:t}}function it(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function at(e){return it(e)===`sandbox-separate`}function ot(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 st=/^[A-Za-z]:[\\/]/,ct=/'/g;async function lt(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);ot(t);let r=bt(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=ut(a),s=xt(r,t);i.push(await dt(e,t,s,r,o,n))}return{entries:i}}function ut(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(`\\`)||st.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 dt(e,t,n,r,i,a){switch(i.type){case`file`:return await gt(e,n,r,i.content),P(t,i.type);case`dir`:return await F(e,n),P(t,i.type);case`localFile`:return await ft(e,i.src,n,r,a),P(t,i.type);case`localDir`:return await pt(e,i.src,n,a),P(t,i.type);case`gitRepo`:return await ht(e,i,n),P(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 St(i)}}function P(e,t){return{path:e,type:t,status:`applied`}}async function ft(e,t,n,r,i){await gt(e,n,r,await ae(vt(t,i.hostRoot),`utf8`))}async function pt(e,t,n,r){await mt(e,vt(t,r.hostRoot),n)}async function mt(e,t,n){await F(e,n);let r=await oe(t,{withFileTypes:!0});for(let i of r){let r=_(t,i.name),a=xt(n,i.name);if(i.isDirectory()){await mt(e,r,a);continue}if(i.isFile()){let t=await ae(r,`utf8`);await e.writeFile(a,t)}}}async function ht(e,t,n){await _t(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${I(t.ref)}`:``} ${I(t.url)} ${I(n)}`)}async function gt(e,t,n,r){let i=v.dirname(t);i!==n&&await F(e,i),await e.writeFile(t,r)}async function F(e,t){await _t(e,`mkdir -p ${I(t)}`)}async function _t(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 vt(e,t){return g(e)?b(e):b(t??process.cwd(),e)}function yt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function bt(e){let t=yt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function xt(e,t){let n=bt(e);return n===`/`?`/${t}`:`${n}/${t}`}function I(e){return`'${e.replace(ct,`'\\''`)}'`}function St(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}const Ct=[`.robota/worktrees`,`.claude/worktrees`];function L(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function wt(){return[...a,...o]}function Tt(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 wt()){let i=L(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of Ct){let i=L(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=L(i,`${t}/.git`);e.exists(r)&&n.push(`--ro-bind`,r,r)}}}for(let r of t.denyRead)e.exists(r.path)&&(r.directory?n.push(`--tmpfs`,r.path):n.push(`--ro-bind`,`/dev/null`,r.path));if(!t.network){if(e.seccompDescriptor===void 0)throw Error(`A sandbox without network needs the Unix-socket seccomp filter.`);n.push(`--unshare-net`,`--seccomp`,String(e.seccompDescriptor))}return n.push(`--unshare-pid`,`--die-with-parent`,`--new-session`,`--chdir`,e.cwd),n.push(`--`,e.command),[...n,...e.args]}function Et(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function R(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Dt(e){let t=[e.root,...e.tempDirectories,...e.allowWrite].map(e=>`(subpath ${R(e)})`).join(` `),n=wt().map(t=>{let n=L(e.root,t);return o.includes(t)?`(literal ${R(n)})`:`(subpath ${R(n)})`}),r=Ct.map(t=>`(subpath ${R(L(e.root,t))})`),i=[`(literal ${R(L(e.root,`.git`))})`,...Ct.map(t=>`(regex #"^${Et(L(e.root,t))}/[^/]+/\\.git$")`)],a=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${t} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${n.join(` `)})`,`(allow file-write* ${r.join(` `)})`,`(deny file-write* ${i.join(` `)})`];if(e.denyRead.length>0){let t=e.denyRead.map(e=>e.directory?`(subpath ${R(e.path)})`:`(literal ${R(e.path)})`);a.push(`(deny file-read* ${t.join(` `)})`)}return e.network||a.push(`(deny network*)`),a.join(`
|
|
2
|
+
`)}const Ot={x64:{audit:3221225534,socket:41,ioUringSetup:425},arm64:{audit:3221225655,socket:198,ioUringSetup:425}};function z(e,t,n,r){return[e,t,n,r]}function kt(e=process.arch){let t=Ot[e];if(t===void 0)return;let n=e=>327680|e,r=[z(32,0,0,4),z(21,1,0,t.audit),z(6,0,0,n(1)),z(32,0,0,0),z(69,0,1,1073741824),z(6,0,0,n(1)),z(21,0,1,t.ioUringSetup),z(6,0,0,n(1)),z(21,0,3,t.socket),z(32,0,0,16),z(21,0,1,1),z(6,0,0,n(97)),z(6,0,0,2147418112)],i=new Uint8Array(r.length*8),a=new DataView(i.buffer);return r.forEach(([e,t,n,r],i)=>{a.setUint16(i*8,e,!0),a.setUint8(i*8+2,t),a.setUint8(i*8+3,n),a.setUint32(i*8+4,r>>>0,!0)}),i}const At=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),jt=`/usr/bin/sandbox-exec`;function Mt(e,t){let n=te(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 Nt(e={}){let t=e.platform??process.platform,n=e.probe??Mt;if(t===`linux`){if(kt(e.arch??process.arch)===void 0)return{backend:`bubblewrap`,missing:[`a seccomp filter for ${e.arch??process.arch} (x64 and arm64 are supported)`]};let t=n(`bwrap`,[`--ro-bind`,`/`,`/`,`--dev`,`/dev`,`--unshare-pid`,`true`]);return t.ok?{backend:`bubblewrap`,executable:`bwrap`,missing:[]}:{backend:`bubblewrap`,missing:[t.detail?.includes(`ENOENT`)?"bubblewrap (install the `bubblewrap` package)":`bubblewrap cannot create a sandbox here${t.detail?`: ${t.detail}`:``}`]}}if(t===`darwin`){let e=n(jt,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:jt,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function B(e){try{return w(e)}catch{return e}}function Pt(e){try{return E(e).isDirectory()}catch{return!1}}function Ft(e){let t=ge(e);if(!t.isSymbolicLink()&&(de(e,t.mode|448),t.isDirectory()))for(let t of ve(e))Ft(`${e}/${t}`)}function It(e){try{return ge(e).isSymbolicLink()}catch{return!1}}function Lt(e){return e.trim().split(/\s+/)[0]}var Rt=class{filesystem=`shared`;root;availability;homeDirectory;current;inFlight=0;baseline=[];unresolved=new Map;constructor(e){this.root=B(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??we(),this.current={...At,...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}}confines(e){if(!this.status().active)return!1;if(i(e).length!==1)return!0;let t=Lt(e);return t===void 0||!this.current.excludedCommands.includes(t)}autoApproves(e){return!this.current.autoAllowBashIfSandboxed||!this.confines(e)||this.unresolved.size>0?!1:!this.protectedEntryStates().some(e=>e.kind===`symlink`&&!this.resolvesOutsideWritableWorkspace(e.path))}wrapCommand(e,t){if(!this.confines(t))return e;let n=this.policy(),r=this.availability.executable;if(this.availability.backend===`seatbelt`)return{command:r,args:[`-p`,Dt(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:kt();this.protectedEntryStates().some(e=>e.path.endsWith(`/.robota`)&&e.kind===`symlink`)||C(`${this.root}/.robota`,{recursive:!0});let a=Tt({policy:n,exists:e=>he(e)&&!It(e),listDirectory:e=>ve(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 wt().map(e=>{let t=`${this.root}/${e}`;try{return ge(t).isSymbolicLink()?{path:t,kind:`symlink`,target:ye(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=w(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()}-${p()}`,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`&&xe(r.target,r.path),this.unresolved.delete(r.path)}catch(e){this.unresolved.set(r.path,r),n.push(`could not restore ${r.path} (${e instanceof Error?e.message:String(e)}); commands will ask until it is removed`)}if(n.length!==0)return`[sandbox] A confined command may not create or replace git, agent, MCP or shell configuration: ${n.join(`; `)}.`}quarantineRoot(e){let t=`${this.root}/.robota`;return e.some(e=>e.path===t&&e.kind===`present`)?`${t}/sandbox-quarantine`:`${this.homeDirectory}/.robota/sandbox-quarantine`}setAside(e,t){let n=`${t}/${m(e)}`;C(t,{recursive:!0});try{T(e,n)}catch(t){if(this.inFlight>0)throw t;Ft(e),t.code===`EXDEV`?(pe(e,n,{recursive:!0,verbatimSymlinks:!0}),be(e,{recursive:!0,force:!0})):T(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return B(g(t)?t:b(this.root,t))},t=[...new Set([Te(),`/tmp`].filter(he).map(B))];return{root:this.root,tempDirectories:t,allowWrite:this.current.allowWrite.map(e),denyRead:this.current.denyRead.map(t=>{let n=e(t);return{path:n,directory:Pt(n)}}),network:this.current.network}}run(e,t={}){let n=l(),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=x(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(_e(e,`utf8`))}writeFile(e,t){return Ce(e,t,`utf8`),Promise.resolve()}};function V(e,n,i,a,o={}){return new t({name:e,description:n,parameters:r(i),...o.deferLoading!==void 0&&{deferLoading:o.deferLoading}},async(e,t)=>{let n=i.safeParse(e);if(!n.success)throw new d(`Zod validation failed: ${n.error}`);let r=await a(n.data,t);return typeof r==`string`?r:JSON.stringify(r)})}const zt={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 Bt(){for(let[t,n]of Object.entries(zt))e(t,n)}Bt();const Vt=1e3,Ht=D.object({activeFiles:D.array(D.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:D.array(D.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:D.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Vt}).`)});function Ut(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
|
|
4
|
+
`)}async function Wt(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??Vt});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${Ut(n.symbols)}`}function Gt(e={}){return V(`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.`,Ht,async t=>Wt(t,e))}const Kt=`Computer use is not available in this session (no driver injected).`,qt=D.enum([`left`,`right`,`middle`]),Jt=D.object({x:D.number(),y:D.number()}),Yt=D.object({type:D.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:D.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:D.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:qt.optional().describe(`Mouse button (click/double_click/drag).`),text:D.string().optional().describe(`Text to type (type).`),keys:D.array(D.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:D.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:D.number().optional().describe(`Vertical wheel delta (scroll).`),path:D.array(Jt).optional().describe(`Points to drag through (drag).`),ms:D.number().optional().describe(`Milliseconds to wait (wait).`),reason:D.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),Xt=D.object({action:Yt.describe(`The single mutating action to perform.`)}),Zt=D.object({});var H=class extends Error{};function U(e,t,n){if(typeof e!=`number`)throw new H(`Action '${n}' requires numeric '${t}'.`);return e}function Qt(e){let t=e.button;switch(e.type){case`click`:return{type:`click`,x:U(e.x,`x`,`click`),y:U(e.y,`y`,`click`),...t?{button:t}:{}};case`double_click`:return{type:`double_click`,x:U(e.x,`x`,`double_click`),y:U(e.y,`y`,`double_click`),...t?{button:t}:{}};case`type`:if(typeof e.text!=`string`)throw new H(`Action 'type' requires 'text'.`);return{type:`type`,text:e.text};case`keypress`:if(!e.keys||e.keys.length===0)throw new H(`Action 'keypress' requires non-empty 'keys'.`);return{type:`keypress`,keys:e.keys};case`scroll`:return{type:`scroll`,x:U(e.x,`x`,`scroll`),y:U(e.y,`y`,`scroll`),deltaX:U(e.deltaX,`deltaX`,`scroll`),deltaY:U(e.deltaY,`deltaY`,`scroll`)};case`drag`:if(!e.path||e.path.length<2)throw new H(`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 H(`Unknown action type: ${String(t)}`)}}}async function $t(e){if(!e.driver)return JSON.stringify({success:!1,error:Kt});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function en(e,t){if(!t.driver)return JSON.stringify({success:!1,error:Kt});let n;try{n=Qt(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 tn(e={}){return V(`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.`,Zt,async()=>$t(e))}function nn(e={}){return V(`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.",Xt,async t=>en(t,e))}function rn(e={}){return[tn(e),nn(e)]}const an=[{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 on(e,t){let n=t?an.filter(e=>t.includes(e.toolName)):an,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 W=process.platform!==`win32`,sn=2e6,cn=D.object({command:D.string().describe(`The shell command to execute`),timeout:D.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:D.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});async function ln(e,t,n,r){try{let i=await r.sandboxClient.run(e,{timeoutMs:t,workingDirectory:n}),a={success:!0,output:i.stderr?`${i.stdout}\nstderr:\n${i.stderr}`:i.stdout,exitCode:i.exitCode};return JSON.stringify(a)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}async function un(e,t,n,r,i){let{command:a,timeout:o=12e4,workingDirectory:c}=e,l=Math.min(o,6e5),d=c??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 ln(a,l,c??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=s({maxBytes:sn}),n=s({maxBytes:sn}),a=!1,o=!1,c;try{c=x(p.command,[...p.args],{cwd:p.cwd,env:i===void 0?process.env:u(process.env,i),stdio:[`pipe`,`pipe`,`pipe`,...(p.inputDescriptors??[]).map(()=>`pipe`)],detached:W})}catch(t){let n=h(),r=t instanceof Error?t.message:String(t);e(JSON.stringify({success:!1,output:n??``,error:r}));return}(p.inputDescriptors??[]).forEach((e,t)=>{let n=c.stdio[t+3];n?.on(`error`,()=>void 0),n?.end(Buffer.from(e))}),c.stdin?.end(),c.stdout?.on(`data`,e=>{t.append(e)}),c.stderr?.on(`data`,e=>{n.append(e)});let d=setTimeout(()=>{a=!0,k(c,{processGroup:W}),f({success:!1,output:t.toString(),error:`Command timed out after ${l}ms`})},l);function f(t){o||(o=!0,clearTimeout(d),r?.removeEventListener(`abort`,m),e(JSON.stringify(t)))}function m(){k(c,{processGroup:W}),f({success:!1,output:t.toString(),error:`Aborted`})}r?.addEventListener(`abort`,m,{once:!0}),c.on(`error`,e=>{c.pid===void 0&&h(),f({success:!1,output:``,error:e.message})}),c.on(`close`,e=>{let r=h();if(a){f({success:!1,output:t.toString(),error:`Command timed out after ${l}ms`,exitCode:e??void 0});return}let i=t.toString(),o=n.toString(),s=e??0,c=o?`${i}\nstderr:\n${o}`:i;f({success:!0,output:r===void 0?c:`${c}\n${r}`,exitCode:s})})})}function dn(e,t){let n=l({executable:t.shellExecutable});return V(e,t.description??on(n,t.availableTools),cn,async(e,r)=>un(e,t,n,r?.signal,r?.shellTraceEnv))}function fn(e){return dn(`Shell`,e)}function pn(e){return dn(`Bash`,e)}function G(e,t){return t!==void 0&&Re(t,e)}function K(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(!G(e,t)){let t={success:!1,output:``,error:`Access denied: "${e}" is outside the working directory`};return JSON.stringify(t)}}function mn(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 hn=2e3,J=4*1024*1024;var Y=class extends c{boundary;constructor(e){super(`Read ${e} exceeds its UTF-8 byte limit`,`Read`),this.boundary=e}},X=class extends c{constructor(){super(`Read cancelled`,`Read`)}};const gn=D.object({filePath:D.string().describe(`The absolute path to the file to read`),offset:D.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:D.number().optional().describe(`The number of lines to read (default: ${hn}). Only provide if the file is too large to read at once`)});function _n(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function vn(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 yn(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>J)throw new Y(`output`);i.push(e)}if(e===-1)break;s=e+1}let u=i.length,d=u<o?`[File: ${e} (lines ${n}-${n+u-1} of ${o})]\n`:`[File: ${e} (${o} lines)]\n`,f=String(n+u-1).length,p=Buffer.byteLength(d,`utf8`)+Math.max(0,u-1);for(let e of i)p+=f+1+Buffer.byteLength(e,`utf8`);if(p>J)throw new Y(`output`);let m={success:!0,output:d+vn(i,n)};return JSON.stringify(m)}async function bn(e,t){if(t.signal?.aborted)throw new X;let{offset:n,limit:r=hn}=e,i=t.sandboxClient?e.filePath:K(e.filePath,t.cwd),a=n!==void 0&&n>0?n:1;if(t.sandboxClient)try{let e=await t.sandboxClient.readFile(i);if(t.signal?.aborted)throw new X;if(Buffer.byteLength(e,`utf8`)>J)throw new Y(`input`);return yn(i,e,a,r)}catch(e){if(e instanceof Y||e instanceof X)throw e;let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let o=q(i,t.cwd);if(o!==void 0)return o;let s;try{s=await S(i)}catch{let e={success:!1,output:``,error:`File not found: ${i}`};return JSON.stringify(e)}if(!s.isFile()){let e={success:!1,output:``,error:`Path is not a file: ${i}`};return JSON.stringify(e)}let c=Buffer.alloc(0),l=!1;try{let e=await ie(i,`r`);try{let n=[],r=Buffer.allocUnsafe(65536),i=0,a=0;for(;i<=J;){if(t.signal?.aborted)throw new X;let{bytesRead:o}=await e.read(r,0,Math.min(r.length,4194305-i),null);if(o===0)break;let s=Math.min(o,8192-a);if(s>0&&_n(r.subarray(0,s))){l=!0;break}if(a+=s,i+=o,i>J)throw new Y(`input`);n.push(Buffer.from(r.subarray(0,o)))}l||(c=Buffer.concat(n,i))}finally{await e.close()}}catch(e){if(e instanceof Y||e instanceof X)throw e;let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}if(t.signal?.aborted)throw new X;if(l){let e={success:!1,output:``,error:`Binary file not supported: ${i}`};return JSON.stringify(e)}return yn(i,c.toString(`utf8`),a,r)}function xn(e){return V(`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.`,gn,async t=>bn(t,e))}function Sn(e){let t=h(e),n=m(e),r=f(6).toString(`hex`);return _(t,`.${n}.atomic-tmp-${process.pid}-${Date.now()}-${r}`)}async function Cn(e){try{return(await S(e)).mode&4095}catch(e){if(e instanceof Error&&wn(e,`ENOENT`))return;throw e}}function wn(e,t){return`code`in e&&e.code===t}async function Tn(e,t){await re(h(e),{recursive:!0});let n=await Cn(e),r=Sn(e);try{await le(r,t,`utf8`),n!==void 0&&await ne(r,n),await se(r,e)}catch(e){throw await ce(r,{force:!0}).catch(()=>void 0),e}}const En=D.object({filePath:D.string().describe(`The absolute path to the file to write`),content:D.string().describe(`The content to write to the file`)});async function Dn(e,t){let{content:n}=e,r=t.sandboxClient?e.filePath:K(e.filePath,t.cwd);if(!t.sandboxClient){let e=q(r,t.cwd);if(e!==void 0)return e}try{t.sandboxClient?await t.sandboxClient.writeFile(r,n):await Tn(r,n);let e={success:!0,output:`Written ${Buffer.byteLength(n,`utf8`)} bytes to ${r}`};return JSON.stringify(e)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}function On(e){return V(`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.`,En,async t=>Dn(t,e))}const kn=D.object({filePath:D.string().describe(`The absolute path to the file to modify`),oldString:D.string().describe(`The text to replace (must be an exact match of existing content)`),newString:D.string().describe(`The text to replace it with (must be different from oldString)`),replaceAll:D.boolean().optional().describe(`Replace all occurrences of oldString (default: false). Useful for renaming variables`)}),Z=4*1024*1024;var An=class extends Error{boundary;constructor(e){super(`Edit ${e} exceeds its ${Z}-byte limit`),this.boundary=e}};async function jn(e,t){let n=me(e,{highWaterMark:65536}),r=[],i=0;try{for await(let e of n){let n=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=n.length,i>t)throw new An(`input`);r.push(n)}}finally{n.destroy()}return Buffer.concat(r,i).toString(`utf8`)}async function Mn(e,t){let{oldString:n,newString:r,replaceAll:i=!1}=e,a=t.sandboxClient?e.filePath:K(e.filePath,t.cwd);if(!t.sandboxClient){let e=q(a,t.cwd);if(e!==void 0)return e}let o;try{if(t.sandboxClient){if(o=await t.sandboxClient.readFile(a),Buffer.byteLength(o,`utf8`)>Z)throw new An(`input`)}else o=await jn(a,Z)}catch(e){if(e instanceof An){let t={success:!1,output:``,error:`${e.message}: ${a}`};return JSON.stringify(t)}let t={success:!1,output:``,error:`File not found: ${a}`};return JSON.stringify(t)}if(!o.includes(n)){let e={success:!1,output:``,error:`oldString not found in file: ${a}`};return JSON.stringify(e)}let s=[];if(i)s=o.split(n);else if(o.indexOf(n)!==o.lastIndexOf(n)){let e={success:!1,output:``,error:`oldString is not unique in file (found ${o.split(n).length-1} occurrences). Provide more context to make it unique, or use replaceAll:true.`};return JSON.stringify(e)}let c=i?s.length-1:1,l=Buffer.byteLength(n,`utf8`),u=Buffer.byteLength(r,`utf8`);if(Buffer.byteLength(o,`utf8`)-c*l+c*u>Z){let e={success:!1,output:``,error:`Edit output exceeds its ${Z}-byte limit: ${a}`};return JSON.stringify(e)}let d=i?s.join(r):o.slice(0,o.indexOf(n))+r+o.slice(o.indexOf(n)+n.length);try{t.sandboxClient?await t.sandboxClient.writeFile(a,d):await Tn(a,d)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let f=o.indexOf(n),p=f>=0?o.substring(0,f).split(`
|
|
18
|
+
`).length:1,m={success:!0,output:`Replaced ${c} occurrence(s) in ${a}`,startLine:p};return JSON.stringify(m)}function Nn(e){return V(`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.`,kn,async t=>Mn(t,e))}const Pn=D.object({pattern:D.string().describe(`The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.tsx")`),path:D.string().optional().describe(`The directory to search in. Defaults to the current working directory. Must be a valid directory path if provided`),limit:D.number().optional().describe(`Maximum number of results to return (default: 1000). Use a smaller limit to save context space`)});async function Fn(e,t,n){let r=ke(100);return(await Promise.all(e.map(e=>r(async()=>{let r=b(t,e);if(G(r,n))try{return{path:e,mtime:(await S(r)).mtimeMs}}catch{return{path:e,mtime:0}}})))).filter(e=>e!==void 0).sort((e,t)=>t.mtime-e.mtime)}async function In(e,t,n){let r=[],i=!1,a=Oe.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 Ln(e,t,n=5e4){let{pattern:r,path:i}=e,a=t.cwd,{root:o,error:s}=mn(i,a);if(s)return s;let c;try{c=await In(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 Fn(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)`;return 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.]`),JSON.stringify({success:!0,output:g})}function Rn(e){return V(`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.`,Pn,async t=>Ln(t,e))}function zn(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`[^/]*`);return RegExp(`^${t}$`)}function Bn(e,t){return t===void 0||zn(t).test(e)}async function Vn(e,t,n,r=5e4){let i=[],a=0,o=!1;async function s(e){if(o)return;let c;try{c=await oe(e)}catch{return}for(let l of c){if(o)return;if(l===`node_modules`||l===`.git`)continue;let c=_(e,l);if(!G(c,n))continue;if(a>=r){o=!0;return}a++;let u;try{u=await S(c)}catch{continue}u.isDirectory()?await s(c):u.isFile()&&Bn(l,t)&&i.push(c)}}return await s(e),{files:i,truncated:o}}function Hn(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 Un=`
|
|
33
|
+
const { parentPort } = require('node:worker_threads');
|
|
34
|
+
const searchFile = ${Hn.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 Wn=class extends Ae{child=x(process.execPath,[`-e`,`
|
|
47
|
+
const searchFile = ${Hn.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:Te(),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}},Gn=class{pattern;signal;worker=process.versions.bun?new Wn:new je(Un,{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 Kn=D.object({pattern:D.string().describe(`The regular expression pattern to search for in file contents`),path:D.string().optional().describe(`File or directory to search in. Defaults to the current working directory`),glob:D.string().optional().describe(`Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched`),contextLines:D.number().optional().describe(`Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0`),outputMode:D.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:D.number().int().positive().optional().describe(`Maximum number of result lines (file paths, content lines, or count rows) to return. Excess results are truncated with a marker line`)}),qn=4*1024*1024;var Q=class extends c{reason;constructor(e){super(`Grep search ${e===`timeout`?`timed out`:e===`cancelled`?`cancelled`:e===`limit`?`exceeded its byte limit`:`worker failed`}`,`Grep`),this.reason=e}};async function Jn(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}=mn(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 S(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 Vn(l,i,c);f=e.files,p=e.truncated}let m=new Gn(n,t.signal),h=new AbortController,g=()=>h.abort();t.signal?.addEventListener(`abort`,g,{once:!0}),t.signal?.aborted&&g();let _;try{if(h.signal.aborted)throw new Q(`cancelled`);let e=Array(f.length),t=0,n,r=async e=>{let t;try{if((await S(e)).size>qn)throw new Q(`limit`);let n=me(e,{highWaterMark:65536,signal:h.signal}),r=[],i=0;try{for await(let e of n){if(h.signal.aborted)throw new Q(`cancelled`);let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=t.length,i>qn)throw new Q(`limit`);r.push(t)}}finally{n.destroy()}let a=Buffer.concat(r,i),o=Math.min(a.length,8192),s=!1;for(let e=0;e<o;e++)if(a[e]===0){s=!0;break}if(s)return[];t=a.toString(`utf8`)}catch(e){if(e instanceof Q)throw e;if(h.signal.aborted)throw new Q(`cancelled`);return[]}return m.search(t,e,a,o)};if(await Promise.all(Array.from({length:Math.min(8,f.length)},async()=>{for(;n===void 0&&t<f.length;){let i=t++;try{e[i]=await r(f[i])}catch(e){n===void 0&&(n=e,h.abort(),m.stop(e instanceof Error?e:Error(`Grep search failed`)))}}})),n!==void 0)throw n;_=e}catch(e){let t=e instanceof Error?e.message:``;throw e instanceof Q?e:new Q(t.includes(`timed out`)?`timeout`:t.includes(`cancelled`)?`cancelled`:t.includes(`byte limit`)?`limit`:`failed`)}finally{t.signal?.removeEventListener(`abort`,g),await m.stop()}let v=0;for(let e of _)for(let t of e)if(v+=Buffer.byteLength(t,`utf8`)+1,v>4*1024*1024)throw new Q(`limit`);let y=_.flat();if(s!==void 0&&y.length>s){let e=y.length-s;y=[...y.slice(0,s),`(+${e} more results truncated by headLimit)`]}p&&(y=[...y,`[File enumeration stopped early; the search tree has more files than this tool scans in one call. Results may be incomplete — narrow the path or glob.]`]);let b={success:!0,output:y.length>0?y.join(`
|
|
64
|
+
`):`(no matches)`};return JSON.stringify(b)}function Yn(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 Xn(e){return V(`Grep`,e.description??Yn(e.shellToolName??`Shell`),Kn,async t=>Jn(t,e))}const Zn=3e4,Qn=5e6,$n=D.object({url:D.string().describe(`The URL to fetch`),headers:D.record(D.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function er(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 tr(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 nr={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`," ":` `},rr=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function ir(e){return tr(er(er(e,`script`),`style`)).replace(rr,e=>nr[e]).replace(/\s+/g,` `).trim()}function ar(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${Zn/1e3}s. The server did not respond in time.`;let t=e.code;return t===`ENOTFOUND`||t===`EAI_AGAIN`?`Network error: DNS resolution failed for this host. The URL may be incorrect or the host does not exist. Do not retry with the same URL.`:t===`ECONNREFUSED`?`Network error: Connection refused. The server is not accepting connections at this address. Do not retry with the same URL.`:t===`ECONNRESET`?`Network error: Connection was reset by the server. The server may be temporarily unavailable.`:t===`ETIMEDOUT`?`Network error: Connection timed out. The server is not reachable within the expected time.`:t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?`Network error: SSL certificate error (${t}). The server's certificate is invalid. Do not retry with the same URL.`:`Network error: ${e.message} Check that the URL is correct and the server is reachable.`}async function or(e,t,n){let{url:r,headers:i}=e;try{new URL(r)}catch{let e={success:!1,output:``,error:`Invalid URL: "${r}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=await et(r,{headers:{"User-Agent":`Robota-CLI/3.0`,...i??{}},signal:n,timeoutMs:Zn,maxResponseBytes:Qn},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 ${Qn} bytes). Consider fetching a more specific URL or a paginated endpoint.`:`Blocked by egress policy: ${t.message} Do not retry with the same URL.`};return JSON.stringify(n)}if(e.status<200||e.status>=300){let t=e.status>=500?` The server is temporarily unavailable — retrying may help.`:` Do not retry with the same URL.`,n={success:!1,output:``,error:`HTTP ${e.status} ${e.statusText}.${t}`};return JSON.stringify(n)}let a=e.headers.get(`content-type`)??``,o=new TextDecoder().decode(e.body);return a.includes(`html`)&&(o=ir(o)),JSON.stringify({success:!0,output:o})}catch(e){let t={success:!1,output:``,error:ar(e)};return JSON.stringify(t)}}function sr(e={}){let t=e.egress??{};return V(`WebFetch`,e.description??`Fetch a URL and return its content as text. HTML pages are converted to plain text.`,$n,async(e,n)=>or(e,t,n?.signal))}const cr=sr();function lr(){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 ur=D.object({query:D.string().describe(`The search query`),limit:D.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function dr(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 fr(e={}){let t=e.provider??lr();return V(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,ur,async(e,n)=>dr(e,t,n?.signal))}const pr=fr(),mr=D.object({question:D.string().min(1).describe(`The complete question to ask the user.`),header:D.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:D.array(D.union([D.string().min(1).describe(`Display text of this choice.`),D.object({label:D.string().min(1).describe(`Display text of this choice.`),description:D.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:D.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:D.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),hr=D.object({questions:D.array(mr).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),gr=[`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 _r(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),n=e.multiSelect===!0&&t.length>1;return{id:`ask_${p()}`,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 vr(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(_r(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 yr(e={}){return V(`AskUserQuestion`,e.description??gr,hr,async(e,t)=>{let n=e,r=t?.ask,i=r?await vr(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}yr();const br=1/0;function $(e,t){e.description!==void 0&&t.push(e.description);for(let[n,r]of Object.entries(e.properties??{}))t.push(n),$(r,t);e.items!==void 0&&$(e.items,t);for(let n of e.anyOf??[])$(n,t)}function xr(e,t){let n=e.name.toLowerCase();if(n===t)return 0;if(n.includes(t))return 1;if(e.description.toLowerCase().includes(t))return 2;let r=[];return $(e.parameters,r),r.some(e=>e.toLowerCase().includes(t))?3:br}function Sr(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:xr(e,r)})).filter(e=>e.rank!==br).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const Cr=n,wr=D.object({query:D.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:D.array(D.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:D.number().int().positive().optional().describe(`Maximum tools to load from a query match (default 5).`)}),Tr=[`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 Er(e){let t=e?.deferredTools;if(!t)throw Error(`${Cr} 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 Dr(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${Cr} needs either "query" to search for tools or "names" to load exact ones.`);let n=Sr(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Or(e={}){return V(Cr,e.description??Tr,wr,async(e,t)=>{let n={loaded:Dr(e,Er(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)})}Or();export{N as A,pr as C,et as D,A as E,Ie as M,k as N,tt as O,Me as P,cr as S,Re as T,On as _,X as a,Nt as b,pn as c,Rn as d,Xn as f,Or as g,fn as h,Y as i,He as j,Ue as k,rn as l,Gt as m,Q as n,lt as o,xn as p,Rt as r,yr as s,At as t,Nn as u,V as v,Ve as w,at as x,it as y};
|
|
67
|
+
//# sourceMappingURL=node-DIRGC_1P.js.map
|