aws-runtime-bridge 1.9.141 → 1.9.143
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/dist/adapter/AcodeSdkAdapter.js +2 -2
- package/dist/adapter/ClaudeSdkAdapter.js +2 -2
- package/dist/adapter/CodexSdkAdapter.js +3 -3
- package/dist/adapter/OpencodeSdkAdapter.js +2 -2
- package/dist/adapter/prompts.d.ts +2 -0
- package/dist/adapter/prompts.js +2 -0
- package/dist/routes/terminal.js +21 -21
- package/dist/services/plugin-manager.d.ts +8 -1
- package/dist/services/plugin-manager.js +9 -9
- package/package/acode/dist/ask-user-question-tool.js +1 -1
- package/package/acode/dist/await-complete-tool.js +3 -3
- package/package/acode/dist/background-command-manager.d.ts +22 -4
- package/package/acode/dist/background-command-manager.js +5 -5
- package/package/acode/dist/background-command-tools.js +10 -10
- package/package/acode/dist/background-output-ringbuffer.d.ts +5 -3
- package/package/acode/dist/background-output-ringbuffer.js +2 -2
- package/package/acode/dist/built-in-file-tools.js +2 -2
- package/package/acode/dist/builtins/shellCommandPreparation.js +2 -2
- package/package/acode/dist/plugin-types.d.ts +2 -0
- package/package/acode/dist/runtime.js +8 -8
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +2 -2
- package/package/aws-client-agent-mcp/dist/mcp-server.js +8 -8
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID as
|
|
1
|
+
import{randomUUID as it}from"node:crypto";import{promises as w,createReadStream as X}from"node:fs";import at from"node:os";import m from"node:path";import Y from"node:readline";import{runShellCommand as rt}from"./builtins/shellCommandRunner.js";import{createOutputEventCollector as st}from"./builtins/commandOutputEvents.js";import{buildCommandOutputSpilloverContent as ct,COMMAND_OUTPUT_SPILLOVER_LINE_LIMIT as lt,countOutputLines as H,formatCommandOutputSpilloverStdout as ut,writeCommandArtifactFile as dt}from"./builtins/commandArtifacts.js";import{symbolsTool as mt}from"./built-in-symbols-tool.js";import{createListBackgroundCommandsTool as ht,createKillBackgroundCommandTool as ft,createReadBackgroundOutputTool as pt}from"./background-command-tools.js";import{detectImageFormatFromBuffer as wt,formatBytes as x,imageMediaType as K,readImageDimensions as gt,tryResizeWithSharp as _t}from"./image-utils.js";const yt=2e3,L=2e3,bt=50*1024,V=4096,kt=.3,Tt=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".tiff",".tif",".zip",".gz",".tar",".rar",".7z",".bz2",".xz",".lz",".exe",".dll",".so",".dylib",".bin",".o",".a",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".mp4",".avi",".mov",".wav",".flv",".mkv",".ogg",".woff",".woff2",".ttf",".otf",".eot",".class",".jar",".war",".ear",".pyc",".pyo",".node",".sqlite",".db",".mdb",".wasm"]),Pt=new Set(["png","jpg","jpeg","gif","webp"]),Z=20*1024*1024,A=10*1024*1024,D=Math.floor(3.75*1024*1024),U=2e3,Et=15e3,vt=1e3,xt=1024*1024,$t=256*1024,Rt=1e3,St=new Set([".git","node_modules","dist","build",".next",".nuxt",".cache",".turbo",".output","coverage",".nyc_output"]),re={fileReadOutside:"allow",commandExecution:"allow",fileModification:"allow"};async function B(n,o,e){if(!n)return;const t=n.getLevel(o);if(t==="deny")throw new Error(`Operation blocked by tool permission policy (${o} = deny). Explain this restriction to the user if needed.`);if(t==="ask"&&!await n.requestPermission(o,e))throw new Error(`Operation denied by the user (${o}). Do not retry the same operation without asking the user.`)}function $(n){return n.replace(/\\/g,"/")}async function J(n){try{return await w.access(n),!0}catch{return!1}}function Mt(n,o){if(!o)return 0;let e=0,t=n.indexOf(o);for(;t>=0;)e+=1,t=n.indexOf(o,t+o.length);return e}function S(n,o,e){for(const t of o){const i=n[t];if(typeof i=="string")return i}throw new Error(`${e} is required`)}function I(n,o){for(const e of o){const t=n[e];if(typeof t=="string"&&t.trim())return t}}function C(n,o,e){for(const t of o){const i=n[t],s=typeof i=="number"?i:typeof i=="string"?Number(i):NaN;if(Number.isFinite(s)&&s>0)return Math.floor(s)}return e}async function Q(n){const o=m.extname(n).toLowerCase();if(Tt.has(o))return!0;const e=await w.open(n,"r");try{const t=Buffer.alloc(V),{bytesRead:i}=await e.read(t,0,V,0);if(i===0)return!1;const s=t.subarray(0,i);if(s.includes(0))return!0;let a=0;for(let r=0;r<i;r++){const c=s[r];(c<9||c>13&&c<32)&&a++}return a/i>kt}finally{await e.close()}}function O(n,o){const e=m.resolve(o),t=m.relative(n,e);if(t.startsWith("..")||m.isAbsolute(t))throw new Error(`Target path is outside workspace: ${e}`);return e}function W(n){return n==="~"||n.startsWith("~/")?m.join(at.homedir(),n.slice(1)):n}async function It(n,o){const e=m.resolve(String(n||"").trim()),t=await w.realpath(e);if(!(await w.stat(t)).isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);if(!o?.trim())return{workspaceRoot:t,cwd:t};const s=W(o.trim()),a=m.isAbsolute(s)?m.resolve(s):m.resolve(e,s),r=m.relative(e,a);if(r.startsWith("..")||m.isAbsolute(r))throw new Error(`Command cwd is outside workspace: ${a}`);const c=O(t,await w.realpath(a));if(!(await w.stat(c)).isDirectory())throw new Error(`Command cwd is not a directory: ${c}`);return{workspaceRoot:t,cwd:c}}async function Ot(n,o){const e=await w.realpath(m.dirname(o));O(n,e);try{if((await w.lstat(o)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${o}`)}catch(t){if((typeof t=="object"&&t!==null?Reflect.get(t,"code"):void 0)!=="ENOENT")throw t}}async function F(n,o){const e=m.resolve(String(n||"").trim()),t=await w.realpath(e);if(!(await w.stat(t)).isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);const s=W(o.trim());if(!s)throw new Error("file_path is required");const a=m.isAbsolute(s)?m.resolve(s):m.resolve(e,s),r=m.relative(e,a);if(r.startsWith("..")||m.isAbsolute(r))throw new Error(`Target path is outside workspace: ${a}`);return{workspaceRoot:t,requestedPath:a,targetPath:O(t,m.join(t,r))}}async function tt(n,o,e){const t=m.resolve(String(n||"").trim()),i=await w.realpath(t);if(!(await w.stat(i)).isDirectory())throw new Error(`Workspace path is not a directory: ${t}`);const a=W(o.trim());if(!a)throw new Error("file_path is required");const r=m.isAbsolute(a)?m.resolve(a):m.resolve(t,a),c=m.relative(t,r),u=await w.realpath(r).catch(()=>r),l=m.relative(i,u);if(c.startsWith("..")||m.isAbsolute(c)||l.startsWith("..")||m.isAbsolute(l)){if(!e)throw new Error(`Target path is outside workspace: ${r}`);return await B(e,"fileReadOutside",{path:r}),{workspaceRoot:i,requestedPath:r,targetPath:u}}return{workspaceRoot:i,requestedPath:r,targetPath:O(i,u)}}async function et(n,o,e){const t=await F(n,o),i=m.dirname(t.targetPath),s=!await J(i);await w.mkdir(i,{recursive:!0}),await Ot(t.workspaceRoot,t.targetPath);const a=m.join(i,`.${m.basename(t.targetPath)}.${process.pid}.${it()}.tmp`);try{await w.writeFile(a,e,"utf-8"),await w.rename(a,t.targetPath)}catch(r){throw await w.rm(a,{force:!0}),r}return{workspaceRoot:t.workspaceRoot,targetPath:t.targetPath,bytes:Buffer.byteLength(e,"utf-8"),createdParentDirectory:s}}async function Lt(n,o){const e=await F(n,o),t=O(e.workspaceRoot,await w.realpath(e.targetPath));if(!(await w.stat(t)).isFile())throw new Error(`Path is not a file: ${t}`);return{workspaceRoot:e.workspaceRoot,targetPath:t,content:await w.readFile(t,"utf-8")}}async function At(n,o,e,t,i){const s=await tt(n,o,i),a=s.targetPath;if(!(await w.stat(a)).isFile())throw new Error(`Path is not a file: ${a}`);if(await Q(a))return{workspaceRoot:s.workspaceRoot,targetPath:a,content:"[Binary file, content skipped]",isBinary:!0,truncated:!1,totalLines:0,shownFromLine:0,shownToLine:0};const c=X(a,{encoding:"utf-8"}),u=Y.createInterface({input:c,crlfDelay:1/0});try{const l=[];let g=0,h=0,_=0,d=!1,E=!1;const f=e-1;for await(const p of u){if(h++,g<f){g++;continue}if(l.length>=t){d=!0,g++;continue}let v=p;v.length>L&&(v=v.slice(0,L)+`... (line truncated to ${L} chars)`);const R=`${g+1}: ${v}`,T=Buffer.byteLength(R,"utf-8")+1;if(_+T>bt){E=!0;break}l.push(R),_+=T,g++}if(h>0&&l.length===0&&!d&&!E&&f>=h)throw new Error(`offset ${e} exceeds total line count ${h} in file: ${a}`);const b=l.length>0?e:0,y=l.length>0?e+l.length-1:0;let k;E?k=`Output capped at 50 KB. Showing lines ${b}-${y}. Use offset=${y+1} to continue.`:d?k=`Showing lines ${b}-${y} of ${h}. Use offset=${y+1} to continue.`:k=`End of file - total ${h} lines`;const P=l.length>0?l.join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`+E:E;return{workspaceRoot:s.workspaceRoot,targetPath:a,content:P,isBinary:!1,truncated:h||k,totalLines:k?-1:p,shownFromLine:y,shownToLine:b}}finally{u.close(),c.destroy()}}function W(n){return/^https?:\/\//i.test(n)}async function It(n){let o;try{o=new URL(n)}catch{throw new Error(`Invalid image URL: ${n}`)}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${o.protocol} (only http/https)`);let e;try{e=await fetch(n,{signal:AbortSignal.timeout(yt)})}catch(u){const l=u instanceof Error?u.message:String(u);throw new Error(`Image URL fetch failed: ${n} (${l})`)}if(!e.ok)throw new Error(`Image URL fetch failed: ${n} (HTTP ${e.status})`);const t=(e.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(t&&!t.startsWith("image/"))throw new Error(`URL did not return an image (content-type: ${t}): ${n}`);const i=Number(e.headers.get("content-length")||"");if(Number.isFinite(i)&&i>L)throw new Error(`Image too large to fetch: ${n} (${x(i)} > ${x(L)})`);const s=e.body;if(!s){const u=await e.arrayBuffer();if(u.byteLength>L)throw new Error(`Image too large to fetch: ${n} (${x(u.byteLength)} > ${x(L)})`);return Buffer.from(u)}const a=s.getReader(),r=[];let c=0;for(;;){const{done:u,value:l}=await a.read();if(u)break;if(l){if(c+=l.byteLength,c>L)throw a.cancel().catch(()=>{}),new Error(`Image too large to fetch: ${n} (${x(c)} > ${x(L)})`);r.push(Buffer.from(l))}}return Buffer.concat(r,c)}async function Mt(n,o,e){let t,i;if(W(o))t=await It(o),i=o;else{const b=(await J(n,o,e)).targetPath,E=await m.stat(b);if(!E.isFile())throw new Error(`Path is not a file: ${b}`);if(E.size>K)throw new Error(`Image file too large to read: ${$(b)} (${x(E.size)} > ${x(K)}). Downscale it first.`);t=await m.readFile(b),i=$(b)}if(t.length===0)throw new Error(`Image file is empty: ${i}`);const s=dt(t);if(!s)throw new Error(`Unsupported or corrupt image (unrecognized format): ${i}`);const a=ht(t);let r=s,c=t,u=a?.width,l=a?.height,w=!1;const p=await pt(t,s,{maxWidth:C,maxHeight:C,maxBytes:U});if(p)c=p.buffer,r=p.mediaType,u=p.width,l=p.height,w=p.changed;else if(t.length>U)throw new Error(`Image too large to inline: ${i} (${x(t.length)} > ${x(U)}). Downscale it first, e.g. via Bash: magick "${o}" -resize ${C}x${C} "${o}". Installing sharp enables automatic downscaling.`);const _=u&&l?`${u}x${l}`:"unknown dimensions",h=w&&a&&a.width!==u?` (resized from ${a.width}x${a.height})`:w?" (resized)":"",k=`[Image: ${i}, ${_}${h}, ${x(c.length)}]`,f=W(o)?d.basename(new URL(o).pathname)||"image":d.basename(i);return{ok:!0,filePath:i,content:k,isBinary:!1,image:{mediaType:Y(r),width:u??null,height:l??null,originalWidth:a?.width??null,originalHeight:a?.height??null,resized:w,size:c.length},attachments:[{type:"image",name:f,mediaType:Y(r),base64Data:c.toString("base64")}]}}function tt(n){let o="",e=0;for(;e<n.length;){const t=n[e];if(t==="*")o+="[^/]*";else if(t==="?")o+="[^/]";else if(t==="{"){const i=n.indexOf("}",e);if(i>=0){const s=n.slice(e+1,i);o+=`(${s.split(",").join("|")})`,e=i}else o+="\\{"}else if(t==="["){const i=n.indexOf("]",e);i>=0?(o+=n.slice(e,i+1),e=i):o+="\\["}else"+^$.()|\\".includes(t)?o+="\\"+t:o+=t;e++}return new RegExp(`^${o}$`)}async function Ot(n,o,e,t){const i=[];async function s(a){if(i.length>=t)return;const r=await m.readdir(a,{withFileTypes:!0});for(const c of r){if(i.length>=t)return;if(c.name.startsWith(".")&&c.isDirectory())continue;const u=d.join(a,c.name);if(c.isDirectory()){if(vt.has(c.name))continue;await s(u)}else if(c.isFile()){if(o&&!o.test(c.name)||e&&e.test(c.name))continue;i.push(u)}}}return await s(n),i}async function Lt(n,o,e){if((await m.stat(n)).size>kt)return{matches:[],count:0};if(await Z(n))return{matches:[],count:0};const i=d.relative(o,n).replace(/\\/g,"/"),s=[];let a=0;const r=G(n,{encoding:"utf-8"}),c=X.createInterface({input:r,crlfDelay:1/0});try{let u=0;for await(const l of c)if(u++,e.regex.test(l)){if(a++,e.collectContent){let w=l;if(w.length>O&&(w=w.slice(0,O)+`... (line truncated to ${O} chars)`),s.push({file:i,line:u,content:w}),s.length>=e.maxResults)break}if(e.stopOnFirstMatch)break}}finally{c.close(),r.destroy()}return{matches:s,count:a}}const et=10*6e4,At=et,Ft=6e4,Bt=10*6e4;function Nt(n,o,e){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",description:"Create or overwrite a UTF-8 text file inside the current workspace. Parent directories are created automatically.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to write."},content:{type:"string",description:"Complete UTF-8 file content."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","content"],additionalProperties:!1},async execute(t){const i=R(t,["file_path","filePath"],"file_path"),s=R(t,["content"],"content"),a=I(t,["reason"]),r=await A(n,i);await F(e,"fileModification",{operation:"write",path:r.targetPath});const c=await V(r.targetPath),u=c?await m.readFile(r.targetPath,"utf-8").catch(()=>null):null,l=await Q(n,i,s);if(o){const w=d.relative(l.workspaceRoot,l.targetPath).replace(/\\/g,"/");await o({filePath:w,operation:c?"UPDATE":"CREATE",beforeContent:u,afterContent:s,reason:a})}return{ok:!0,filePath:$(l.targetPath),bytes:l.bytes,createdParentDirectory:l.createdParentDirectory}}}}function Ct(n,o,e){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",description:"Replace exactly one occurrence of old_string with new_string in a UTF-8 workspace text file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to edit."},old_string:{type:"string",description:"Existing text to replace. Must occur exactly once."},new_string:{type:"string",description:"Replacement text."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","old_string","new_string"],additionalProperties:!1},async execute(t){const i=R(t,["file_path","filePath"],"file_path"),s=R(t,["old_string","oldString"],"old_string"),a=R(t,["new_string","newString"],"new_string"),r=I(t,["reason"]);if(!s)throw new Error("old_string must not be empty");const c=await A(n,i);await F(e,"fileModification",{operation:"edit",path:c.targetPath});const u=await Rt(n,i),l=xt(u.content,s);if(l===0)throw new Error("old_string was not found in file");if(l>1)throw new Error(`old_string occurs ${l} times; provide a unique match`);const w=u.content.replace(s,a),p=await Q(n,i,w);if(o){const _=d.relative(p.workspaceRoot,p.targetPath).replace(/\\/g,"/");await o({filePath:_,operation:"UPDATE",beforeContent:u.content,afterContent:w,reason:r})}return{ok:!0,filePath:$(p.targetPath),bytes:p.bytes}}}}function Ut(n,o,e){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",description:"Delete a file inside the current workspace. Returns an error if the file does not exist.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to delete."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path"],additionalProperties:!1},async execute(t){const i=R(t,["file_path","filePath"],"file_path"),s=I(t,["reason"]),a=await A(n,i);await F(e,"fileModification",{operation:"delete",path:a.targetPath});const r=M(a.workspaceRoot,await m.realpath(a.targetPath).catch(()=>a.targetPath)),c=await m.stat(r).catch(()=>null);if(!c)throw new Error(`File does not exist: ${r}`);if(!c.isFile())throw new Error(`Path is not a file: ${r}`);const u=await m.readFile(r,"utf-8").catch(()=>null);if(await m.rm(r,{force:!0}),o){const l=d.relative(a.workspaceRoot,r).replace(/\\/g,"/");await o({filePath:l,operation:"DELETE",beforeContent:u,afterContent:null,reason:s})}return{ok:!0,filePath:$(r),deleted:!0}}}}function Dt(n,o){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",description:"Read a UTF-8 text file inside the current workspace. Returns content with line numbers in the format '<line>: <content>'. Supports offset (1-indexed line number to start from) and limit (max lines to return, default 2000). Output is capped at 2000 lines or 50 KB, whichever is reached first. Individual lines longer than 2000 characters are truncated. Avoid tiny repeated slices (e.g. 30-line chunks); read a larger window if more context is needed. Images (.png/.jpg/.jpeg/.gif/.webp) and http(s) image URLs are also supported: the image is inlined into the conversation so you can see it (requires a model with image input). offset/limit are ignored for images; oversized images are automatically downscaled when sharp is available.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to read. Also accepts an http(s) URL pointing to an image."},offset:{type:"number",description:"Line number to start reading from (1-indexed). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to return. Defaults to 2000."}},required:["file_path"],additionalProperties:!1},async execute(e){const t=R(e,["file_path","filePath"],"file_path"),i=d.extname(t).toLowerCase().slice(1);if(W(t)||_t.has(i))return await Mt(n,t,o);const s=B(e,["offset"],1),a=B(e,["limit"],ft),r=await St(n,t,s,a,o);return{ok:!0,filePath:$(r.targetPath),content:r.content,isBinary:r.isBinary,truncated:r.truncated,totalLines:r.totalLines,shownFromLine:r.shownFromLine,shownToLine:r.shownToLine}}}}function Wt(n,o,e,t){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded timeout and returns stdout, stderr, exit code, and (if interrupted) partial output. By default (wait_seconds omitted or -1) the command runs in the FOREGROUND and streams output in real time; if the 5-minute adapter watchdog fires while it is still running, the command is interrupted and the partial output produced so far is returned (large output is spilled to a file via outputFilePath to avoid context overflow), with watchdogInterrupted=true. For long-running commands use wait_seconds=0 or n>0 to run in the BACKGROUND, then manage them via list_background_commands / read_background_output / kill_background_command / await_complete.",inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},cwd:{type:"string",description:"Optional workspace-relative working directory. Defaults to the workspace root."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds. Defaults to 600000 and is capped at 600000."},inactivity_timeout_ms:{type:"number",description:"Optional no-output timeout in milliseconds. Defaults to 60000 and is capped at 600000."},wait_seconds:{type:"number",description:"How to wait for the command to finish. Omitted values (or -1, the default): run in the FOREGROUND until completion; if the 5-minute adapter watchdog fires first, the command is interrupted and only the partial output already produced is returned (watchdogInterrupted=true; large output spills to outputFilePath). 0: spawn and immediately execute in the background, return task_id. n>0: wait up to n seconds; if still running, move to the background and return task_id. Background commands remain subject to timeout_ms (total upper bound); inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Optional short reason for running the command."}},required:["command"],additionalProperties:!1},async execute(i,s){const a=R(i,["command"],"command").trim();if(!a)throw new Error("command must not be empty");const r=B(i,["timeout_ms","timeoutMs"],At),c=Math.min(r,et),u=B(i,["inactivity_timeout_ms","inactivityTimeoutMs"],Ft),l=Math.min(u,Bt),w=I(i,["cwd"]),p=await Tt(n,w);await F(t,"commandExecution",{command:a,cwd:$(p.cwd)});const _=i.wait_seconds,k=typeof _=="number"&&Number.isFinite(_)?_:-1;if(k!==-1&&e)return await qt({deps:e,command:a,agentId:o,workspaceRoot:p.workspaceRoot,cwd:p.cwd,timeoutMs:c,inactivityTimeoutMs:l,waitSeconds:k,onOutput:s?.onOutput,settleSignal:s?.settleSignal});const f=await at({commandText:a,agentId:o,workspaceRoot:p.workspaceRoot,cwd:p.cwd,timeoutMs:c,inactivityTimeoutMs:l,onOutput:s?.onOutput,watchdogSignal:s?.settleSignal}),y={ok:f.exitCode===0&&!f.timedOut,tool:"Bash",command:a,cwd:$(p.cwd),exitCode:f.exitCode,signal:f.signal,timedOut:f.timedOut,inactivityTimedOut:f.inactivityTimedOut,watchdogInterrupted:f.watchdogInterrupted,timeoutMs:c,inactivityTimeoutMs:l,durationMs:f.durationMs,outputSpilled:f.outputSpilled,outputFilePath:f.outputFilePath,outputLineCount:f.outputLineCount,commandFilePath:f.commandFilePath,commandLineCount:f.commandLineCount,stdout:f.stdout,stderr:f.stderr};return f.watchdogInterrupted?{...y,message:"Command was interrupted by the adapter watchdog after ~5 minutes of synchronous (foreground) execution. Only the partial output produced so far is returned above"+(f.outputFilePath?` (full output spilled to "${f.outputFilePath}"; read it if you need more)`:"")+". For long-running commands, re-run with wait_seconds=0 (or n>0) to execute in the background, then manage via await_complete / list_background_commands / read_background_output / kill_background_command."}:y}}}async function qt(n){const{deps:o,command:e,agentId:t,workspaceRoot:i,cwd:s,timeoutMs:a,inactivityTimeoutMs:r,waitSeconds:c,onOutput:u,settleSignal:l}=n,w=u?rt({cwd:s,commandLineCount:0,onOutput:u}):void 0;let p=!!w;const _=()=>{p&&(p=!1,w?.close())};try{const{taskId:h,completion:k}=o.manager.startCommand({commandText:e,agentId:t,workspaceRoot:i,cwd:s,timeoutMs:a,inactivityTimeoutMs:r,onOutput:p?P=>{p&&w?.push(P.stream,P.text)}:void 0,onCompleted:o.emitCompleted});if(c===0)return o.manager.disableInactivityTimeout(t,h),_(),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:h,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, read_background_output(task_id="${h}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${h}") to stop.`};const f=c===-1?0:Math.max(0,Math.floor(c*1e3));let y,b;c===-1?b=Promise.resolve("__never__"):b=new Promise(P=>{y=setTimeout(()=>P("__timeout__"),f),y.unref?.()});const E=l?l.then(()=>"__settle__"):Promise.resolve("__never__");try{const P=await Promise.race([k,b,E]);if(P==="__settle__")return o.manager.disableInactivityTimeout(t,h),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:h,status:"backgrounded",reason:"watchdog_timeout",waitedMs:f,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, read_background_output(task_id="${h}", mode="tail") to read output, or kill_background_command(task_id="${h}") to stop.`};if(P==="__timeout__")return o.manager.disableInactivityTimeout(t,h),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:h,status:"backgrounded",reason:"timeout",waitedMs:f,message:`Command still running after ${c}s; moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, or read_background_output(task_id="${h}", mode="tail") / kill_background_command(task_id="${h}") to inspect.`};const g=P;return{ok:g.exitCode===0&&!g.timedOut,tool:"Bash",command:e,backgrounded:!1,taskId:h,exitCode:g.exitCode,signal:g.signal,timedOut:g.timedOut,inactivityTimedOut:g.inactivityTimedOut,timeoutMs:g.timeoutMs,inactivityTimeoutMs:g.inactivityTimeoutMs,durationMs:g.durationMs,outputSpilled:g.outputSpilled,outputFilePath:g.outputFilePath,outputLineCount:g.outputLineCount,commandFilePath:g.commandFilePath,commandLineCount:g.commandLineCount,stdout:g.stdout,stderr:g.stderr}}finally{y&&clearTimeout(y),_()}}catch(h){if(h?.code==="too_many_tasks"||h?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:e,backgrounded:!1,status:"not_executed",error:h.code,message:`Command was NOT executed: ${h.message}. Wait for some background tasks to finish/cleanup (per-agent limit 16, global 256), or reduce concurrent background commands, then retry.`};throw h}}function jt(n){return{kind:"builtin",toolName:"grep",exposedName:"grep",description:"Search file contents using regular expressions within the workspace. Returns matched lines with file paths and line numbers. Supports include/exclude glob patterns, case-insensitive matching, and three output modes (content, files_with_matches, count). Searches recursively through directories, skipping binary files, hidden directories, and common build/dependency directories (node_modules, .git, dist, etc.).",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for in file contents."},path:{type:"string",description:"Workspace-relative file or directory path to search in. Defaults to the workspace root."},include:{type:"string",description:"Glob pattern to filter files by name (e.g. '*.ts', '*.{js,ts}'). Only matching files are searched."},exclude:{type:"string",description:"Glob pattern to exclude files by name (e.g. '*.test.ts'). Matching files are skipped."},case_insensitive:{type:"boolean",description:"Case-insensitive matching. Default false."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output format: 'content' returns matched lines with line numbers (default), 'files_with_matches' returns only file paths with matches, 'count' returns match counts per file."},max_results:{type:"number",description:"Maximum number of matched lines to return (content mode). Default 1000."}},required:["pattern"],additionalProperties:!1},async execute(o){const e=R(o,["pattern"],"pattern"),t=I(o,["path"])||".",i=I(o,["include"]),s=I(o,["exclude"]),a=o.case_insensitive===!0,r=(()=>{const v=o.output_mode;return v==="files_with_matches"||v==="count"?v:"content"})(),c=B(o,["max_results"],Pt),u=a?"i":"";let l;try{l=new RegExp(e,u)}catch(v){throw new Error(`Invalid regex pattern: ${v instanceof Error?v.message:String(v)}`)}const w=i?tt(i):null,p=s?tt(s):null,_=await A(n,t),h=M(_.workspaceRoot,await m.realpath(_.targetPath)),k=await m.stat(h);let f;if(k.isFile())f=[h];else if(k.isDirectory())f=await Ot(h,w,p,bt);else throw new Error(`Path is neither a file nor a directory: ${h}`);const y=[],b=[],E=[];let P=0,g=0,T=!1;for(const v of f){if(r==="content"&&y.length>=c){T=!0;break}const ot={regex:l,maxResults:r==="content"?c-y.length:Number.MAX_SAFE_INTEGER,collectContent:r==="content",stopOnFirstMatch:r==="files_with_matches"},N=await Lt(v,_.workspaceRoot,ot);if(N.count>0){const q=d.relative(_.workspaceRoot,v).replace(/\\/g,"/");if(E.push(q),P+=N.count,r==="content"){for(const j of N.matches){const z=Buffer.byteLength(j.content,"utf-8")+64;if(g+z>Et){T=!0;break}g+=z,y.push(j)}if(T)break;if(y.length>=c){T=!0;break}}else r==="count"&&b.push({file:q,count:N.count})}}const S={ok:!0,tool:"grep",pattern:e,searchPath:$(_.targetPath),outputMode:r,filesSearched:f.length,filesMatched:E.length,totalMatches:P,truncated:T};return r==="content"?S.matches=y:r==="files_with_matches"?S.matches=E:S.matches=b,S}}}function ee(n,o,e,t,i){const s=o||"unknown",a=[Dt(n,i),Nt(n,e,i),Ct(n,e,i),Ut(n,e,i),jt(n),Wt(n,s,t,i),st(n)];return t&&a.push(ct(s,t),lt(s,t),ut(s,t)),a}export{te as DEFAULT_TOOL_PERMISSION_POLICY,ee as createBuiltInFileTools,M as ensureInsideWorkspace,A as resolveWorkspaceTarget};
|
|
3
|
+
`+k:k;return{workspaceRoot:s.workspaceRoot,targetPath:a,content:P,isBinary:!1,truncated:d||E,totalLines:E?-1:h,shownFromLine:b,shownToLine:y}}finally{u.close(),c.destroy()}}function q(n){return/^https?:\/\//i.test(n)}async function Ft(n){let o;try{o=new URL(n)}catch{throw new Error(`Invalid image URL: ${n}`)}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${o.protocol} (only http/https)`);let e;try{e=await fetch(n,{signal:AbortSignal.timeout(Et)})}catch(u){const l=u instanceof Error?u.message:String(u);throw new Error(`Image URL fetch failed: ${n} (${l})`)}if(!e.ok)throw new Error(`Image URL fetch failed: ${n} (HTTP ${e.status})`);const t=(e.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(t&&!t.startsWith("image/"))throw new Error(`URL did not return an image (content-type: ${t}): ${n}`);const i=Number(e.headers.get("content-length")||"");if(Number.isFinite(i)&&i>A)throw new Error(`Image too large to fetch: ${n} (${x(i)} > ${x(A)})`);const s=e.body;if(!s){const u=await e.arrayBuffer();if(u.byteLength>A)throw new Error(`Image too large to fetch: ${n} (${x(u.byteLength)} > ${x(A)})`);return Buffer.from(u)}const a=s.getReader(),r=[];let c=0;for(;;){const{done:u,value:l}=await a.read();if(u)break;if(l){if(c+=l.byteLength,c>A)throw a.cancel().catch(()=>{}),new Error(`Image too large to fetch: ${n} (${x(c)} > ${x(A)})`);r.push(Buffer.from(l))}}return Buffer.concat(r,c)}async function Bt(n,o,e){let t,i;if(q(o))t=await Ft(o),i=o;else{const y=(await tt(n,o,e)).targetPath,k=await w.stat(y);if(!k.isFile())throw new Error(`Path is not a file: ${y}`);if(k.size>Z)throw new Error(`Image file too large to read: ${$(y)} (${x(k.size)} > ${x(Z)}). Downscale it first.`);t=await w.readFile(y),i=$(y)}if(t.length===0)throw new Error(`Image file is empty: ${i}`);const s=wt(t);if(!s)throw new Error(`Unsupported or corrupt image (unrecognized format): ${i}`);const a=gt(t);let r=s,c=t,u=a?.width,l=a?.height,g=!1;const h=await _t(t,s,{maxWidth:U,maxHeight:U,maxBytes:D});if(h)c=h.buffer,r=h.mediaType,u=h.width,l=h.height,g=h.changed;else if(t.length>D)throw new Error(`Image too large to inline: ${i} (${x(t.length)} > ${x(D)}). Downscale it first, e.g. via Bash: magick "${o}" -resize ${U}x${U} "${o}". Installing sharp enables automatic downscaling.`);const _=u&&l?`${u}x${l}`:"unknown dimensions",d=g&&a&&a.width!==u?` (resized from ${a.width}x${a.height})`:g?" (resized)":"",E=`[Image: ${i}, ${_}${d}, ${x(c.length)}]`,f=q(o)?m.basename(new URL(o).pathname)||"image":m.basename(i);return{ok:!0,filePath:i,content:E,isBinary:!1,image:{mediaType:K(r),width:u??null,height:l??null,originalWidth:a?.width??null,originalHeight:a?.height??null,resized:g,size:c.length},attachments:[{type:"image",name:f,mediaType:K(r),base64Data:c.toString("base64")}]}}function ot(n){let o="",e=0;for(;e<n.length;){const t=n[e];if(t==="*")o+="[^/]*";else if(t==="?")o+="[^/]";else if(t==="{"){const i=n.indexOf("}",e);if(i>=0){const s=n.slice(e+1,i);o+=`(${s.split(",").join("|")})`,e=i}else o+="\\{"}else if(t==="["){const i=n.indexOf("]",e);i>=0?(o+=n.slice(e,i+1),e=i):o+="\\["}else"+^$.()|\\".includes(t)?o+="\\"+t:o+=t;e++}return new RegExp(`^${o}$`)}async function Ct(n,o,e,t){const i=[];async function s(a){if(i.length>=t)return;const r=await w.readdir(a,{withFileTypes:!0});for(const c of r){if(i.length>=t)return;if(c.name.startsWith(".")&&c.isDirectory())continue;const u=m.join(a,c.name);if(c.isDirectory()){if(St.has(c.name))continue;await s(u)}else if(c.isFile()){if(o&&!o.test(c.name)||e&&e.test(c.name))continue;i.push(u)}}}return await s(n),i}async function Nt(n,o,e){if((await w.stat(n)).size>xt)return{matches:[],count:0};if(await Q(n))return{matches:[],count:0};const i=m.relative(o,n).replace(/\\/g,"/"),s=[];let a=0;const r=X(n,{encoding:"utf-8"}),c=Y.createInterface({input:r,crlfDelay:1/0});try{let u=0;for await(const l of c)if(u++,e.regex.test(l)){if(a++,e.collectContent){let g=l;if(g.length>L&&(g=g.slice(0,L)+`... (line truncated to ${L} chars)`),s.push({file:i,line:u,content:g}),s.length>=e.maxResults)break}if(e.stopOnFirstMatch)break}}finally{c.close(),r.destroy()}return{matches:s,count:a}}const nt=10*6e4,Ut=nt,Dt=6e4,Wt=10*6e4;function qt(n,o,e){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",description:"Create or overwrite a UTF-8 text file inside the current workspace. Parent directories are created automatically.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to write."},content:{type:"string",description:"Complete UTF-8 file content."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","content"],additionalProperties:!1},async execute(t){const i=S(t,["file_path","filePath"],"file_path"),s=S(t,["content"],"content"),a=I(t,["reason"]),r=await F(n,i);await B(e,"fileModification",{operation:"write",path:r.targetPath});const c=await J(r.targetPath),u=c?await w.readFile(r.targetPath,"utf-8").catch(()=>null):null,l=await et(n,i,s);if(o){const g=m.relative(l.workspaceRoot,l.targetPath).replace(/\\/g,"/");await o({filePath:g,operation:c?"UPDATE":"CREATE",beforeContent:u,afterContent:s,reason:a})}return{ok:!0,filePath:$(l.targetPath),bytes:l.bytes,createdParentDirectory:l.createdParentDirectory}}}}function jt(n,o,e){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",description:"Replace exactly one occurrence of old_string with new_string in a UTF-8 workspace text file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to edit."},old_string:{type:"string",description:"Existing text to replace. Must occur exactly once."},new_string:{type:"string",description:"Replacement text."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","old_string","new_string"],additionalProperties:!1},async execute(t){const i=S(t,["file_path","filePath"],"file_path"),s=S(t,["old_string","oldString"],"old_string"),a=S(t,["new_string","newString"],"new_string"),r=I(t,["reason"]);if(!s)throw new Error("old_string must not be empty");const c=await F(n,i);await B(e,"fileModification",{operation:"edit",path:c.targetPath});const u=await Lt(n,i),l=Mt(u.content,s);if(l===0)throw new Error("old_string was not found in file");if(l>1)throw new Error(`old_string occurs ${l} times; provide a unique match`);const g=u.content.replace(s,a),h=await et(n,i,g);if(o){const _=m.relative(h.workspaceRoot,h.targetPath).replace(/\\/g,"/");await o({filePath:_,operation:"UPDATE",beforeContent:u.content,afterContent:g,reason:r})}return{ok:!0,filePath:$(h.targetPath),bytes:h.bytes}}}}function zt(n,o,e){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",description:"Delete a file inside the current workspace. Returns an error if the file does not exist.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to delete."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path"],additionalProperties:!1},async execute(t){const i=S(t,["file_path","filePath"],"file_path"),s=I(t,["reason"]),a=await F(n,i);await B(e,"fileModification",{operation:"delete",path:a.targetPath});const r=O(a.workspaceRoot,await w.realpath(a.targetPath).catch(()=>a.targetPath)),c=await w.stat(r).catch(()=>null);if(!c)throw new Error(`File does not exist: ${r}`);if(!c.isFile())throw new Error(`Path is not a file: ${r}`);const u=await w.readFile(r,"utf-8").catch(()=>null);if(await w.rm(r,{force:!0}),o){const l=m.relative(a.workspaceRoot,r).replace(/\\/g,"/");await o({filePath:l,operation:"DELETE",beforeContent:u,afterContent:null,reason:s})}return{ok:!0,filePath:$(r),deleted:!0}}}}function Gt(n,o){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",description:"Read a UTF-8 text file inside the current workspace. Returns content with line numbers in the format '<line>: <content>'. Supports offset (1-indexed line number to start from) and limit (max lines to return, default 2000). Output is capped at 2000 lines or 50 KB, whichever is reached first. Individual lines longer than 2000 characters are truncated. Avoid tiny repeated slices (e.g. 30-line chunks); read a larger window if more context is needed. Images (.png/.jpg/.jpeg/.gif/.webp) and http(s) image URLs are also supported: the image is inlined into the conversation so you can see it (requires a model with image input). offset/limit are ignored for images; oversized images are automatically downscaled when sharp is available.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to read. Also accepts an http(s) URL pointing to an image."},offset:{type:"number",description:"Line number to start reading from (1-indexed). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to return. Defaults to 2000."}},required:["file_path"],additionalProperties:!1},async execute(e){const t=S(e,["file_path","filePath"],"file_path"),i=m.extname(t).toLowerCase().slice(1);if(q(t)||Pt.has(i))return await Bt(n,t,o);const s=C(e,["offset"],1),a=C(e,["limit"],yt),r=await At(n,t,s,a,o);return{ok:!0,filePath:$(r.targetPath),content:r.content,isBinary:r.isBinary,truncated:r.truncated,totalLines:r.totalLines,shownFromLine:r.shownFromLine,shownToLine:r.shownToLine}}}}function Xt(n,o,e,t){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded foreground wait and returns stdout, stderr, exit code, and (if converted to background) a task_id. By default (wait_seconds omitted or -1) the command runs in the FOREGROUND and streams output in real time; if the 5-minute adapter watchdog or the command total timeout (timeout_ms) fires while it is still running, the command is moved to the BACKGROUND and the tool returns a task_id plus an explanation (backgrounded=true, reason=watchdog_timeout|tool_timeout). The background command has no total timeout and can be managed via await_complete / list_background_commands / read_background_output / kill_background_command. For immediate backgrounding use wait_seconds=0, or wait_seconds=n>0 to wait n seconds then background.",inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},cwd:{type:"string",description:"Optional workspace-relative working directory. Defaults to the workspace root."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds. Defaults to 600000 and is capped at 600000."},inactivity_timeout_ms:{type:"number",description:"Optional no-output timeout in milliseconds. Defaults to 60000 and is capped at 600000."},wait_seconds:{type:"number",description:"How to wait for the command to finish. Omitted values (or -1, the default): run in the FOREGROUND until completion; if the 5-minute adapter watchdog or timeout_ms fires first, the command is moved to the background and a task_id is returned (backgrounded=true, reason=watchdog_timeout|tool_timeout). 0: spawn and immediately execute in the background, return task_id. n>0: wait up to n seconds; if still running, move to the background and return task_id. Background commands have NO total timeout (run until finished or killed); inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Optional short reason for running the command."}},required:["command"],additionalProperties:!1},async execute(i,s){const a=S(i,["command"],"command").trim();if(!a)throw new Error("command must not be empty");const r=C(i,["timeout_ms","timeoutMs"],Ut),c=Math.min(r,nt),u=C(i,["inactivity_timeout_ms","inactivityTimeoutMs"],Dt),l=Math.min(u,Wt),g=I(i,["cwd"]),h=await It(n,g);await B(t,"commandExecution",{command:a,cwd:$(h.cwd)});const _=i.wait_seconds,E=typeof _=="number"&&Number.isFinite(_)?_:-1;if(e)return await Yt({deps:e,command:a,agentId:o,workspaceRoot:h.workspaceRoot,cwd:h.cwd,timeoutMs:c,inactivityTimeoutMs:l,waitSeconds:E,onOutput:s?.onOutput,settleSignal:s?.settleSignal});const f=await rt({commandText:a,agentId:o,workspaceRoot:h.workspaceRoot,cwd:h.cwd,timeoutMs:c,inactivityTimeoutMs:l,onOutput:s?.onOutput,watchdogSignal:s?.settleSignal}),b={ok:f.exitCode===0&&!f.timedOut,tool:"Bash",command:a,cwd:$(h.cwd),exitCode:f.exitCode,signal:f.signal,timedOut:f.timedOut,inactivityTimedOut:f.inactivityTimedOut,watchdogInterrupted:f.watchdogInterrupted,timeoutMs:c,inactivityTimeoutMs:l,durationMs:f.durationMs,outputSpilled:f.outputSpilled,outputFilePath:f.outputFilePath,outputLineCount:f.outputLineCount,commandFilePath:f.commandFilePath,commandLineCount:f.commandLineCount,stdout:f.stdout,stderr:f.stderr};return f.watchdogInterrupted?{...b,message:"Command was interrupted by the adapter watchdog after ~5 minutes of synchronous (foreground) execution. Only the partial output produced so far is returned above"+(f.outputFilePath?` (full output spilled to "${f.outputFilePath}"; read it if you need more)`:"")+". For long-running commands, re-run with wait_seconds=0 (or n>0) to execute in the background, then manage via await_complete / list_background_commands / read_background_output / kill_background_command."}:b}}}async function Yt(n){const{deps:o,command:e,agentId:t,workspaceRoot:i,cwd:s,timeoutMs:a,inactivityTimeoutMs:r,waitSeconds:c,onOutput:u,settleSignal:l}=n,g=u?st({cwd:s,commandLineCount:0,onOutput:u}):void 0;let h=!!g;const _=()=>{h&&(h=!1,g?.close())};try{const{taskId:d,completion:E}=o.manager.startCommand({commandText:e,agentId:t,workspaceRoot:i,cwd:s,timeoutMs:0,inactivityTimeoutMs:r,onOutput:h?P=>{h&&g?.push(P.stream,P.text)}:void 0,onCompleted:o.emitCompleted});if(c===0)return o.manager.disableInactivityTimeout(t,d),_(),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:d,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use await_complete(bg_cmd_ids=["${d}"]) to block until it finishes, read_background_output(task_id="${d}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${d}") to stop.`};const f=c===-1?0:Math.max(0,Math.floor(c*1e3)),b=[E];let y;c!==-1&&b.push(new Promise(P=>{y=setTimeout(()=>P("__timeout__"),f),y.unref?.()}));let k;c===-1&&a>0&&b.push(new Promise(P=>{k=setTimeout(()=>P("__total_timeout__"),a),k.unref?.()})),l&&b.push(l.then(()=>"__settle__"));try{const P=await Promise.race(b);if(P==="__settle__")return o.manager.disableInactivityTimeout(t,d),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:d,status:"backgrounded",reason:"watchdog_timeout",waitedMs:f,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${d}"]) to block until it finishes, read_background_output(task_id="${d}", mode="tail") to read output, or kill_background_command(task_id="${d}") to stop.`};if(P==="__timeout__")return o.manager.disableInactivityTimeout(t,d),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:d,status:"backgrounded",reason:"timeout",waitedMs:f,message:`Command still running after ${c}s; moved to background. Use await_complete(bg_cmd_ids=["${d}"]) to block until it finishes, or read_background_output(task_id="${d}", mode="tail") / kill_background_command(task_id="${d}") to inspect.`};if(P==="__total_timeout__")return o.manager.disableInactivityTimeout(t,d),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:d,status:"backgrounded",reason:"tool_timeout",waitedMs:Math.floor(a/1e3),message:`Command still running after ${Math.floor(a/1e3)}s (total timeout); moved to background. It continues running in the background without a total timeout. Use await_complete(bg_cmd_ids=["${d}"]) to block until it finishes, or read_background_output(task_id="${d}", mode="tail") / kill_background_command(task_id="${d}") to inspect.`};const p=P;let v=p.stdout,R=p.stderr,T=p.outputSpilled,N=p.outputFilePath;if(!T&&H(`${p.stdout}${p.stderr}`)>lt){const M=await dt(t,"cmd","out",ct({commandText:e,commandFilePath:p.commandFilePath,commandLineCount:p.commandLineCount,cwd:s,startedAt:new Date(Date.now()-p.durationMs),endedAt:new Date,exitCode:p.exitCode,signal:p.signal??null,timedOut:p.timedOut,inactivityTimedOut:p.inactivityTimedOut??!1,stdout:v,stderr:R}));v=ut($(M),H(`${p.stdout}${p.stderr}`)),T=!0,N=$(M)}return{ok:p.exitCode===0&&!p.timedOut,tool:"Bash",command:e,backgrounded:!1,taskId:d,exitCode:p.exitCode,signal:p.signal,timedOut:p.timedOut,inactivityTimedOut:p.inactivityTimedOut,timeoutMs:p.timeoutMs||a,inactivityTimeoutMs:p.inactivityTimeoutMs,durationMs:p.durationMs,outputSpilled:T,outputFilePath:N,outputLineCount:p.outputLineCount,commandFilePath:p.commandFilePath,commandLineCount:p.commandLineCount,stdout:v,stderr:R}}finally{y&&clearTimeout(y),k&&clearTimeout(k),_()}}catch(d){if(d?.code==="too_many_tasks"||d?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:e,backgrounded:!1,status:"not_executed",error:d.code,message:`Command was NOT executed: ${d.message}. Wait for some background tasks to finish/cleanup (per-agent limit 16, global 256), or reduce concurrent background commands, then retry.`};throw d}}function Ht(n){return{kind:"builtin",toolName:"grep",exposedName:"grep",description:"Search file contents using regular expressions within the workspace. Returns matched lines with file paths and line numbers. Supports include/exclude glob patterns, case-insensitive matching, and three output modes (content, files_with_matches, count). Searches recursively through directories, skipping binary files, hidden directories, and common build/dependency directories (node_modules, .git, dist, etc.).",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for in file contents."},path:{type:"string",description:"Workspace-relative file or directory path to search in. Defaults to the workspace root."},include:{type:"string",description:"Glob pattern to filter files by name (e.g. '*.ts', '*.{js,ts}'). Only matching files are searched."},exclude:{type:"string",description:"Glob pattern to exclude files by name (e.g. '*.test.ts'). Matching files are skipped."},case_insensitive:{type:"boolean",description:"Case-insensitive matching. Default false."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output format: 'content' returns matched lines with line numbers (default), 'files_with_matches' returns only file paths with matches, 'count' returns match counts per file."},max_results:{type:"number",description:"Maximum number of matched lines to return (content mode). Default 1000."}},required:["pattern"],additionalProperties:!1},async execute(o){const e=S(o,["pattern"],"pattern"),t=I(o,["path"])||".",i=I(o,["include"]),s=I(o,["exclude"]),a=o.case_insensitive===!0,r=(()=>{const T=o.output_mode;return T==="files_with_matches"||T==="count"?T:"content"})(),c=C(o,["max_results"],Rt),u=a?"i":"";let l;try{l=new RegExp(e,u)}catch(T){throw new Error(`Invalid regex pattern: ${T instanceof Error?T.message:String(T)}`)}const g=i?ot(i):null,h=s?ot(s):null,_=await F(n,t),d=O(_.workspaceRoot,await w.realpath(_.targetPath)),E=await w.stat(d);let f;if(E.isFile())f=[d];else if(E.isDirectory())f=await Ct(d,g,h,vt);else throw new Error(`Path is neither a file nor a directory: ${d}`);const b=[],y=[],k=[];let P=0,p=0,v=!1;for(const T of f){if(r==="content"&&b.length>=c){v=!0;break}const N={regex:l,maxResults:r==="content"?c-b.length:Number.MAX_SAFE_INTEGER,collectContent:r==="content",stopOnFirstMatch:r==="files_with_matches"},M=await Nt(T,_.workspaceRoot,N);if(M.count>0){const j=m.relative(_.workspaceRoot,T).replace(/\\/g,"/");if(k.push(j),P+=M.count,r==="content"){for(const z of M.matches){const G=Buffer.byteLength(z.content,"utf-8")+64;if(p+G>$t){v=!0;break}p+=G,b.push(z)}if(v)break;if(b.length>=c){v=!0;break}}else r==="count"&&y.push({file:j,count:M.count})}}const R={ok:!0,tool:"grep",pattern:e,searchPath:$(_.targetPath),outputMode:r,filesSearched:f.length,filesMatched:k.length,totalMatches:P,truncated:v};return r==="content"?R.matches=b:r==="files_with_matches"?R.matches=k:R.matches=y,R}}}function se(n,o,e,t,i){const s=o||"unknown",a=[Gt(n,i),qt(n,e,i),jt(n,e,i),zt(n,e,i),Ht(n),Xt(n,s,t,i),mt(n)];return t&&a.push(ht(s,t),ft(s,t),pt(s,t)),a}export{re as DEFAULT_TOOL_PERMISSION_POLICY,se as createBuiltInFileTools,O as ensureInsideWorkspace,F as resolveWorkspaceTarget};
|
|
4
4
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as o}from"node:fs";import{countOutputLines as c,LONG_COMMAND_LINE_LIMIT as s,toDisplayPath as a,writeCommandArtifactFile as m}from"./commandArtifacts.js";function p(n){return`'${n.replace(/'/g,"'\\''")}'`}function u(n){return`"${n.replace(/"/g,'""')}"`}function l(n=process.env,t=o){return["/bin/bash","/usr/bin/bash",String(n.SHELL||"").trim(),"/bin/sh"].find(r=>r&&t(r))||"/bin/sh"}function x(){if(process.platform==="win32")return{command:process.env.ComSpec||"cmd.exe",argsPrefix:["/d","/c"],scriptExtension:"cmd",scriptInvocation:t=>`call ${u(t)}`};const n=l();return{command:n,argsPrefix:["-lc"],scriptExtension:"sh",scriptInvocation:t=>`${n} ${p(t)}`}}function f(n,t){const i=n.endsWith(`
|
|
2
2
|
`)?n:`${n}
|
|
3
3
|
`;return t==="cmd"?`@echo off\r
|
|
4
|
-
${i}`:i}async function C(n,t,i){const r=c(n);if(r<=s)return{commandText:n,originalCommandText:n,commandLineCount:r};const
|
|
4
|
+
${i}`:i}function d(n){return process.platform!=="win32"?n:n.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g,"_")||"workspace"}async function C(n,t,i){const r=c(n);if(r<=s)return{commandText:n,originalCommandText:n,commandLineCount:r};const e=await m(d(t),"cmd",i.scriptExtension,f(n,i.scriptExtension));return{commandText:i.scriptInvocation(e),originalCommandText:n,commandLineCount:r,commandFilePath:a(e)}}export{C as prepareShellCommand,l as resolveUnixCommandShell,x as shellExecutable};
|
|
5
5
|
|