aws-runtime-bridge 1.9.126 → 1.9.128
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/routes/pty.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
1
|
+
import O from"node:crypto";import A from"node:fs";import c from"node:path";import{Router as N}from"express";import*as U from"node-pty";import{v4 as D}from"uuid";import M,{WebSocketServer as z}from"ws";import{isRuntimeTokenValid as x,validateToken as h}from"../middleware/auth.js";import{isUpgradeAllowed as R}from"../services/access-control.js";import{createLogger as j}from"../utils/logger.js";const p=j("pty"),W=80,F=24,_=2e5,E=30*60*1e3,b=5*60*1e3,$=60*1e3,v=8,B=new Set(["false","halt","nologin","reboot","shutdown","sync","true"]),H=new Set(["sh","dash","ash"]),u=new Map,w=new Map;function X(e=process.env){const t=String(e.AWS_PTY_IDLE_TTL_MS||"").trim();if(!t)return E;const r=Number(t);return!Number.isFinite(r)||r<1e3?E:r}function Y(e=process.platform,t=process.env,r=A.existsSync){if(e==="win32")return{shell:String(t.ComSpec||t.COMSPEC||"").trim()||"powershell.exe",args:[]};const n=String(t.SHELL||"").trim();return{shell:[...H.has(c.basename(n).toLowerCase())?[]:[n],"/bin/bash","/usr/bin/bash",n,"/bin/sh"].find(a=>J(a,r))||"/bin/sh",args:[]}}function J(e,t){const r=e.trim();if(!r)return!1;const n=c.basename(r).toLowerCase();return B.has(n)?!1:!c.isAbsolute(r)||t(r)}function K(e,t=process.platform,r=process.env){const n=String(e||"auto").trim();if(!n||n==="auto")return Y(t,r);const i=new Set(["bash","sh","zsh","fish","pwsh","pwsh.exe","powershell","powershell.exe","cmd","cmd.exe"]),o=(t==="win32"?c.win32.basename(n):c.basename(n)).toLowerCase();if(!i.has(o))throw new Error(`shell is not allowed: ${n}`);return{shell:/^[A-Za-z]:[\\/]/.test(n)||n.startsWith("\\")||n.startsWith("/")?n:t==="win32"?{cmd:"cmd.exe",powershell:"powershell.exe",pwsh:"pwsh.exe"}[o]??n:n,args:[]}}function V(e,t){const r=c.relative(c.resolve(t),c.resolve(e));return r===""||!r.startsWith("..")&&!c.isAbsolute(r)}function Z(e=process.env){return String(e.AWS_PTY_ALLOWED_ROOTS||"").split(c.delimiter).map(t=>t.trim()).filter(Boolean).map(t=>c.resolve(t))}function q(e,t=process.env){const r=String(e||"").trim();if(!r)throw new Error("workspacePath is required");if(!c.isAbsolute(r))throw new Error("workspacePath must be absolute");const n=c.resolve(r);if(!A.statSync(n).isDirectory())throw new Error("workspacePath must be an existing directory");const o=Z(t);if(o.length>0&&!o.some(a=>V(n,a)))throw new Error("workspacePath is outside allowed roots");return n}function T(e,t){const r=Number(e);return!Number.isInteger(r)||r<=0?t:Math.min(r,500)}function G(e){return{...e,TERM:e.TERM||"xterm-256color",COLORTERM:e.COLORTERM||"truecolor"}}function Q(e,t){e.outputBuffer=`${e.outputBuffer}${t}`,e.outputBuffer.length>_&&(e.outputBuffer=e.outputBuffer.slice(-_))}function g(e){return{id:e.id,title:e.title,workspacePath:e.workspacePath,shell:e.shell,cols:e.cols,rows:e.rows,status:e.status,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,exitCode:e.exitCode,signal:e.signal,attachedClients:e.sockets.size,ownerUserId:e.ownerUserId,tenantId:e.tenantId,projectId:e.projectId}}function I(e,t){e.readyState===M.OPEN&&e.send(JSON.stringify(t))}function k(e,t){for(const r of e.sockets)I(r,t)}function P(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{e.sockets.size===0&&S(e.id,"idle-timeout")},X())}function C(e){e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null)}function ee(e){if(u.size>=se())throw new Error("maximum PTY sessions reached");const t=q(e.workspacePath),r=K(e.shell),n=T(e.cols,W),i=T(e.rows,F),o=`pty_${D()}`,a=new Date().toISOString(),d=String(e.title||"").trim()||`Terminal ${u.size+1}`,l=U.spawn(r.shell,r.args,{name:"xterm-256color",cols:n,rows:i,cwd:t,env:G(process.env)}),s={id:o,title:d,workspacePath:t,shell:r.shell,cols:n,rows:i,status:"running",createdAt:a,lastActiveAt:a,attachedClients:0,ptyProcess:l,sockets:new Set,outputBuffer:"",idleTimer:null,persistent:e.persistent===!0,ownerUserId:String(e.ownerUserId||"").trim()||void 0,tenantId:String(e.tenantId||"").trim()||void 0,projectId:String(e.projectId||"").trim()||void 0};return l.onData(f=>{s.lastActiveAt=new Date().toISOString(),Q(s,f),k(s,{type:"output",data:f})}),l.onExit(({exitCode:f,signal:m})=>{s.status="exited",s.exitCode=f,s.signal=m,s.lastActiveAt=new Date().toISOString(),k(s,{type:"exit",exitCode:f,signal:m}),s.sockets.size===0&&!s.persistent?P(s):s.persistent&&(s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{S(s.id,"exited-timeout")},ne()))}),u.set(o,s),s.persistent||P(s),te(s,e.preCommand),p.info(`created pty session id=${o}, cwd=${t}, shell=${r.shell}`),g(s)}function te(e,t){const r=typeof t=="string"?t:"";if(!r.trim())return;const n=`${r.replace(/\n/g,"\r").replace(/\r+$/g,"")}\r`;try{e.ptyProcess.write(n)}catch(i){const o=i;p.warn(`failed to inject pty pre-command sessionId=${e.id}: ${o.message}`)}}function re(e=process.env){const t=String(e.AWS_PTY_CONNECT_TOKEN_TTL_MS||"").trim();if(!t)return $;const r=Number(t);return!Number.isFinite(r)||r<5e3||r>10*60*1e3?$:r}function ne(e=process.env){const t=String(e.AWS_PTY_EXITED_TTL_MS||"").trim();if(!t)return b;const r=Number(t);return!Number.isFinite(r)||r<1e3?b:r}function se(e=process.env){const t=String(e.AWS_PTY_MAX_SESSIONS||"").trim();if(!t)return v;const r=Number(t);return!Number.isInteger(r)||r<1||r>100?v:r}function oe(e){if(!e||typeof e!="object")return{workspacePath:void 0};const t=e;return{workspacePath:t.workspacePath,title:t.title,shell:t.shell,cols:t.cols,rows:t.rows,persistent:t.persistent,preCommand:t.preCommand,ownerUserId:t.ownerUserId,tenantId:t.tenantId,projectId:t.projectId}}function ie(){return Array.from(u.values()).map(g)}function ae(e){const t=u.get(e);return t?g(t):void 0}function ce(e){if(!u.has(e))return;const t=`ptyws_${O.randomBytes(32).toString("base64url")}`,r=Date.now()+re();return w.set(t,{sessionId:e,expiresAt:r}),{token:t,expiresAt:new Date(r).toISOString()}}function ue(e,t){const r=w.get(t);return r?r.expiresAt<Date.now()?(w.delete(t),p.warn(`[pty-ws] consumePtyConnectToken: token \u5DF2\u8FC7\u671F, sessionId=${e}, expiredAt=${new Date(r.expiresAt).toISOString()}`),!1):r.sessionId!==e?(p.warn(`[pty-ws] consumePtyConnectToken: sessionId \u4E0D\u5339\u914D, expected=${r.sessionId}, actual=${e}`),!1):(w.delete(t),p.info(`[pty-ws] consumePtyConnectToken: \u6210\u529F, sessionId=${e}`),!0):(p.warn(`[pty-ws] consumePtyConnectToken: token \u4E0D\u5B58\u5728, sessionId=${e}, ptyConnectTokens.size=${w.size}`),!1)}function le(e){for(const[t,r]of w.entries())r.sessionId===e&&w.delete(t)}function S(e,t="closed"){const r=u.get(e);if(!r)return!1;C(r),le(e),k(r,{type:"status",status:"closing",reason:t});for(const n of r.sockets)n.close(1e3,t);return r.sockets.clear(),r.status==="running"&&r.ptyProcess.kill(),u.delete(e),p.info(`closed pty session id=${e}, reason=${t}`),!0}function Pe(e="shutdown"){for(const t of Array.from(u.keys()))S(t,e)}const y=N();y.get("/sessions",h,(e,t)=>{t.json({ok:!0,sessions:ie()})}),y.post("/sessions",h,(e,t)=>{try{const r=ee(oe(e.body));t.status(201).json({ok:!0,session:r})}catch(r){const n=r;t.status(400).json({error:n.message})}}),y.get("/sessions/:sessionId",h,(e,t)=>{const r=ae(e.params.sessionId);if(!r){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0,session:r})}),y.delete("/sessions/:sessionId",h,(e,t)=>{if(!S(e.params.sessionId,"explicit-close")){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0})}),y.post("/sessions/:sessionId/connect-token",h,(e,t)=>{const r=ce(e.params.sessionId);if(!r){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0,...r})});function pe(e){const t=e.toString();try{return JSON.parse(t)}catch{return{type:"input",data:t}}}function de(e,t){C(e),e.sockets.add(t),e.lastActiveAt=new Date().toISOString(),I(t,{type:"status",status:e.status,session:g(e)}),e.outputBuffer&&I(t,{type:"output",data:e.outputBuffer,replay:!0}),t.on("message",r=>{const n=pe(r);if(!n||typeof n!="object")return;const i=n,o=String(i.type||"");if(e.lastActiveAt=new Date().toISOString(),o==="input"){e.ptyProcess.write(String(i.data||""));return}if(o==="resize"){const a=T(i.cols,e.cols),d=T(i.rows,e.rows);e.cols=a,e.rows=d,e.ptyProcess.resize(a,d);return}if(o==="close"){S(e.id,"client-close");return}o==="ping"&&I(t,{type:"pong"})}),t.on("close",()=>{e.sockets.delete(t),e.lastActiveAt=new Date().toISOString(),e.sockets.size===0&&e.status==="running"&&!e.persistent&&P(e)})}function fe(e,t){const r=t.searchParams.get("token")||"";if(r.trim())return r.trim();const n=e.headers["x-runtime-token"];return Array.isArray(n)?n[0]?.trim()||"":typeof n=="string"?n.trim():String(e.headers.authorization||"").match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||""}function Ae(e){const t=new z({noServer:!0});e.on("upgrade",(r,n,i)=>{if(!R(r,n))return;const o=r.headers.host||"localhost",a=new URL(r.url||"/",`http://${o}`),d=a.pathname.match(/^\/pty\/sessions\/([^/]+)\/stream$/);if(!d)return;const l=fe(r,a),s=decodeURIComponent(d[1]||""),f=l?l.length>12?l.substring(0,12)+"...":l:"empty";if(p.info(`[pty-ws] upgrade \u8BF7\u6C42: sessionId=${s}, token=${f}, pathname=${a.pathname}`),!x(l)&&!ue(s,l)){p.warn(`[pty-ws] token \u6821\u9A8C\u5931\u8D25: sessionId=${s}, token=${f}, runtimeTokenValid=${x(l)}, ptySessions.size=${u.size}`),n.write(`HTTP/1.1 401 Unauthorized\r
|
|
2
2
|
\r
|
|
3
|
-
`),n.destroy();return}const m=
|
|
3
|
+
`),n.destroy();return}const m=u.get(s);if(!m){p.warn(`[pty-ws] session \u4E0D\u5B58\u5728: sessionId=${s}, ptySessions.size=${u.size}, keys=${Array.from(u.keys()).join(",")}`),n.write(`HTTP/1.1 404 Not Found\r
|
|
4
4
|
\r
|
|
5
|
-
`),n.destroy();return}p.info(`[pty-ws] handleUpgrade: sessionId=${
|
|
5
|
+
`),n.destroy();return}p.info(`[pty-ws] handleUpgrade: sessionId=${s}, status=${m.status}, persistent=${m.persistent}, sockets=${m.sockets.size}`),t.handleUpgrade(r,n,i,L=>{de(m,L)})})}export{Ae as attachPtyWebSocketServer,Pe as closeAllPtySessions,S as closePtySession,ce as createPtyConnectToken,ee as createPtySession,ae as getPtySessionSummary,V as isPathInsideRoot,ie as listPtySessions,y as ptyRouter,u as ptySessions,Y as resolveDefaultShell,se as resolveMaxPtySessions,ne as resolvePtyExitedTtlMs,X as resolvePtyIdleTtlMs,q as resolvePtyWorkspacePath,K as resolveRequestedShell};
|
|
6
6
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID as
|
|
1
|
+
import{randomUUID as K}from"node:crypto";import{promises as u,createReadStream as N}from"node:fs";import H from"node:os";import d from"node:path";import U from"node:readline";import{runShellCommand as V}from"./builtins/shellCommandRunner.js";import{symbolsTool as Z}from"./built-in-symbols-tool.js";import{createListBackgroundCommandsTool as J,createKillBackgroundCommandTool as Q,createReadBackgroundOutputTool as tt}from"./background-command-tools.js";const et=2e3,M=2e3,ot=50*1024,D=4096,nt=.3,it=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"]),rt=1e3,at=1024*1024,st=256*1024,ct=1e3,lt=new Set([".git","node_modules","dist","build",".next",".nuxt",".cache",".turbo",".output","coverage",".nyc_output"]);function b(n){return n.replace(/\\/g,"/")}async function W(n){try{return await u.access(n),!0}catch{return!1}}function ut(n,o){if(!o)return 0;let t=0,e=n.indexOf(o);for(;e>=0;)t+=1,e=n.indexOf(o,e+o.length);return t}function P(n,o,t){for(const e of o){const r=n[e];if(typeof r=="string")return r}throw new Error(`${t} is required`)}function E(n,o){for(const t of o){const e=n[t];if(typeof e=="string"&&e.trim())return e}}function C(n,o,t){for(const e of o){const r=n[e],i=typeof r=="number"?r:typeof r=="string"?Number(r):NaN;if(Number.isFinite(i)&&i>0)return Math.floor(i)}return t}async function j(n){const o=d.extname(n).toLowerCase();if(it.has(o))return!0;const t=await u.open(n,"r");try{const e=Buffer.alloc(D),{bytesRead:r}=await t.read(e,0,D,0);if(r===0)return!1;const i=e.subarray(0,r);if(i.includes(0))return!0;let c=0;for(let a=0;a<r;a++){const l=i[a];(l<9||l>13&&l<32)&&c++}return c/r>nt}finally{await t.close()}}function S(n,o){const t=d.resolve(o),e=d.relative(n,t);if(e.startsWith("..")||d.isAbsolute(e))throw new Error(`Target path is outside workspace: ${t}`);return t}function q(n){return n==="~"||n.startsWith("~/")?d.join(H.homedir(),n.slice(1)):n}async function dt(n,o){const t=d.resolve(String(n||"").trim()),e=await u.realpath(t);if(!(await u.stat(e)).isDirectory())throw new Error(`Workspace path is not a directory: ${t}`);if(!o?.trim())return{workspaceRoot:e,cwd:e};const i=q(o.trim()),c=d.isAbsolute(i)?d.resolve(i):d.resolve(t,i),a=d.relative(t,c);if(a.startsWith("..")||d.isAbsolute(a))throw new Error(`Command cwd is outside workspace: ${c}`);const l=S(e,await u.realpath(c));if(!(await u.stat(l)).isDirectory())throw new Error(`Command cwd is not a directory: ${l}`);return{workspaceRoot:e,cwd:l}}async function pt(n,o){const t=await u.realpath(d.dirname(o));S(n,t);try{if((await u.lstat(o)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${o}`)}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)!=="ENOENT")throw e}}async function O(n,o){const t=d.resolve(String(n||"").trim()),e=await u.realpath(t);if(!(await u.stat(e)).isDirectory())throw new Error(`Workspace path is not a directory: ${t}`);const i=q(o.trim());if(!i)throw new Error("file_path is required");const c=d.isAbsolute(i)?d.resolve(i):d.resolve(t,i),a=d.relative(t,c);if(a.startsWith("..")||d.isAbsolute(a))throw new Error(`Target path is outside workspace: ${c}`);return{workspaceRoot:e,requestedPath:c,targetPath:S(e,d.join(e,a))}}async function G(n,o,t){const e=await O(n,o),r=d.dirname(e.targetPath),i=!await W(r);await u.mkdir(r,{recursive:!0}),await pt(e.workspaceRoot,e.targetPath);const c=d.join(r,`.${d.basename(e.targetPath)}.${process.pid}.${K()}.tmp`);try{await u.writeFile(c,t,"utf-8"),await u.rename(c,e.targetPath)}catch(a){throw await u.rm(c,{force:!0}),a}return{workspaceRoot:e.workspaceRoot,targetPath:e.targetPath,bytes:Buffer.byteLength(t,"utf-8"),createdParentDirectory:i}}async function ft(n,o){const t=await O(n,o),e=S(t.workspaceRoot,await u.realpath(t.targetPath));if(!(await u.stat(e)).isFile())throw new Error(`Path is not a file: ${e}`);return{workspaceRoot:t.workspaceRoot,targetPath:e,content:await u.readFile(e,"utf-8")}}async function mt(n,o,t,e){const r=await O(n,o),i=S(r.workspaceRoot,await u.realpath(r.targetPath));if(!(await u.stat(i)).isFile())throw new Error(`Path is not a file: ${i}`);if(await j(i))return{workspaceRoot:r.workspaceRoot,targetPath:i,content:"[Binary file, content skipped]",isBinary:!0,truncated:!1,totalLines:0,shownFromLine:0,shownToLine:0};const a=N(i,{encoding:"utf-8"}),l=U.createInterface({input:a,crlfDelay:1/0});try{const s=[];let m=0,f=0,g=0,w=!1,p=!1;const _=t-1;for await(const L of l){if(f++,m<_){m++;continue}if(s.length>=e){w=!0,m++;continue}let T=L;T.length>M&&(T=T.slice(0,M)+`... (line truncated to ${M} chars)`);const v=`${m+1}: ${T}`,R=Buffer.byteLength(v,"utf-8")+1;if(g+R>ot){p=!0;break}s.push(v),g+=R,m++}if(f>0&&s.length===0&&!w&&!p&&_>=f)throw new Error(`offset ${t} exceeds total line count ${f} in file: ${i}`);const h=s.length>0?t:0,y=s.length>0?t+s.length-1:0;let x;p?x=`Output capped at 50 KB. Showing lines ${h}-${y}. Use offset=${y+1} to continue.`:w?x=`Showing lines ${h}-${y} of ${f}. Use offset=${y+1} to continue.`:x=`End of file - total ${f} lines`;const B=s.length>0?s.join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`+x:x;return{workspaceRoot:r.workspaceRoot,targetPath:i,content:B,isBinary:!1,truncated:w||d,totalLines:d?-1:f,shownFromLine:h,shownToLine:y}}finally{l.close(),a.destroy()}}function G(n){let o="",t=0;for(;t<n.length;){const e=n[t];if(e==="*")o+="[^/]*";else if(e==="?")o+="[^/]";else if(e==="{"){const r=n.indexOf("}",t);if(r>=0){const i=n.slice(t+1,r);o+=`(${i.split(",").join("|")})`,t=r}else o+="\\{"}else if(e==="["){const r=n.indexOf("]",t);r>=0?(o+=n.slice(t,r+1),t=r):o+="\\["}else"+^$.()|\\".includes(e)?o+="\\"+e:o+=e;t++}return new RegExp(`^${o}$`)}async function ft(n,o,t,e){const r=[];async function i(c){if(r.length>=e)return;const a=await u.readdir(c,{withFileTypes:!0});for(const l of a){if(r.length>=e)return;if(l.name.startsWith(".")&&l.isDirectory())continue;const s=p.join(c,l.name);if(l.isDirectory()){if(st.has(l.name))continue;await i(s)}else if(l.isFile()){if(o&&!o.test(l.name)||t&&t.test(l.name))continue;r.push(s)}}}return await i(n),r}async function mt(n,o,t){if((await u.stat(n)).size>it)return{matches:[],count:0};if(await q(n))return{matches:[],count:0};const r=p.relative(o,n).replace(/\\/g,"/"),i=[];let c=0;const a=N(n,{encoding:"utf-8"}),l=U.createInterface({input:a,crlfDelay:1/0});try{let s=0;for await(const m of l)if(s++,t.regex.test(m)){if(c++,t.collectContent){let f=m;if(f.length>M&&(f=f.slice(0,M)+`... (line truncated to ${M} chars)`),i.push({file:r,line:s,content:f}),i.length>=t.maxResults)break}if(t.stopOnFirstMatch)break}}finally{l.close(),a.destroy()}return{matches:i,count:c}}const X=10*6e4,ht=X,wt=6e4,gt=10*6e4;function _t(n,o){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 e=P(t,["file_path","filePath"],"file_path"),r=P(t,["content"],"content"),i=E(t,["reason"]),c=await O(n,e),a=await W(c.targetPath),l=a?await u.readFile(c.targetPath,"utf-8").catch(()=>null):null,s=await j(n,e,r);if(o){const m=p.relative(s.workspaceRoot,s.targetPath).replace(/\\/g,"/");await o({filePath:m,operation:a?"UPDATE":"CREATE",beforeContent:l,afterContent:r,reason:i})}return{ok:!0,tool:"write_file",workspacePath:b(s.workspaceRoot),filePath:b(s.targetPath),bytes:s.bytes,createdParentDirectory:s.createdParentDirectory}}}}function yt(n,o){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 e=P(t,["file_path","filePath"],"file_path"),r=P(t,["old_string","oldString"],"old_string"),i=P(t,["new_string","newString"],"new_string"),c=E(t,["reason"]);if(!r)throw new Error("old_string must not be empty");const a=await dt(n,e),l=ct(a.content,r);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 s=a.content.replace(r,i),m=await j(n,e,s);if(o){const f=p.relative(m.workspaceRoot,m.targetPath).replace(/\\/g,"/");await o({filePath:f,operation:"UPDATE",beforeContent:a.content,afterContent:s,reason:c})}return{ok:!0,tool:"edit_file",workspacePath:b(m.workspaceRoot),filePath:b(m.targetPath),replacements:1,bytes:m.bytes}}}}function kt(n,o){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 e=P(t,["file_path","filePath"],"file_path"),r=E(t,["reason"]),i=await O(n,e),c=S(i.workspaceRoot,await u.realpath(i.targetPath).catch(()=>i.targetPath)),a=await u.stat(c).catch(()=>null);if(!a)throw new Error(`File does not exist: ${c}`);if(!a.isFile())throw new Error(`Path is not a file: ${c}`);const l=await u.readFile(c,"utf-8").catch(()=>null);if(await u.rm(c,{force:!0}),o){const s=p.relative(i.workspaceRoot,c).replace(/\\/g,"/");await o({filePath:s,operation:"DELETE",beforeContent:l,afterContent:null,reason:r})}return{ok:!0,tool:"delete_file",workspacePath:b(i.workspaceRoot),filePath:b(c),deleted:!0}}}}function bt(n){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.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to read."},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(o){const t=P(o,["file_path","filePath"],"file_path"),e=C(o,["offset"],1),r=C(o,["limit"],Q),i=await pt(n,t,e,r);return{ok:!0,tool:"read_file",workspacePath:b(i.workspaceRoot),filePath:b(i.targetPath),content:i.content,isBinary:i.isBinary,truncated:i.truncated,totalLines:i.totalLines,shownFromLine:i.shownFromLine,shownToLine:i.shownToLine}}}}function Pt(n,o,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, and exit code. Set wait_seconds to 0 or n>0 to move long-running commands to the background and return a task_id immediately (or after n seconds); then use ListBackgroundCommands / ReadBackgroundOutput / KillBackgroundCommand to manage them.",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. Only applies to foreground (wait_seconds=-1); ignored once a command moves to background."},wait_seconds:{type:"number",description:"How long to block waiting for the command to finish. -1 (default): block until completion (current behavior, capped at timeout_ms). 0: spawn and immediately move to background, return task_id. n>0: wait up to n seconds; if still running, move to background and return task_id. Background commands remain subject to timeout_ms (total upper bound); inactivity_timeout_ms is ignored once backgrounded.",default:-1,minimum:-1},description:{type:"string",description:"Optional short reason for running the command."}},required:["command"],additionalProperties:!1},async execute(e,r){const i=P(e,["command"],"command").trim();if(!i)throw new Error("command must not be empty");const c=C(e,["timeout_ms","timeoutMs"],ht),a=Math.min(c,X),l=C(e,["inactivity_timeout_ms","inactivityTimeoutMs"],wt),s=Math.min(l,gt),m=E(e,["cwd"]),f=await lt(n,m),g=e.wait_seconds,w=typeof g=="number"&&Number.isFinite(g)?g:-1;if(w!==-1&&t)return await xt({deps:t,command:i,agentId:o,workspaceRoot:f.workspaceRoot,cwd:f.cwd,timeoutMs:a,waitSeconds:w,settleSignal:r?.settleSignal});const d=await K({commandText:i,agentId:o,workspaceRoot:f.workspaceRoot,cwd:f.cwd,timeoutMs:a,inactivityTimeoutMs:s,onOutput:r?.onOutput});return{ok:d.exitCode===0&&!d.timedOut,tool:"Bash",command:i,cwd:b(f.cwd),exitCode:d.exitCode,signal:d.signal,timedOut:d.timedOut,inactivityTimedOut:d.inactivityTimedOut,timeoutMs:a,inactivityTimeoutMs:s,durationMs:d.durationMs,outputSpilled:d.outputSpilled,outputFilePath:d.outputFilePath,outputLineCount:d.outputLineCount,commandFilePath:d.commandFilePath,commandLineCount:d.commandLineCount,stdout:d.stdout,stderr:d.stderr}}}}async function xt(n){const{deps:o,command:t,agentId:e,workspaceRoot:r,cwd:i,timeoutMs:c,waitSeconds:a,settleSignal:l}=n;try{const{taskId:s,completion:m}=o.manager.startCommand({commandText:t,agentId:e,workspaceRoot:r,cwd:i,timeoutMs:c,onCompleted:o.emitCompleted});if(a===0)return{ok:!0,tool:"Bash",command:t,backgrounded:!0,taskId:s,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use ListBackgroundCommands to view, ReadBackgroundOutput(task_id="${s}", mode="tail") to read output, KillBackgroundCommand(task_id="${s}") to stop.`};const f=Math.max(0,Math.floor(a*1e3));let g;const w=new Promise(_=>{g=setTimeout(()=>_("__timeout__"),f),g.unref?.()}),d=l?l.then(()=>"__settle__"):Promise.resolve("__never__");try{const _=await Promise.race([m,w,d]);if(_==="__settle__")return{ok:!0,tool:"Bash",command:t,backgrounded:!0,taskId:s,status:"backgrounded",reason:"watchdog_timeout",waitedMs:f,message:`Command still running after watchdog timeout; moved to background. Use ListBackgroundCommands / ReadBackgroundOutput(task_id="${s}", mode="tail") to inspect.`};if(_==="__timeout__")return{ok:!0,tool:"Bash",command:t,backgrounded:!0,taskId:s,status:"backgrounded",reason:"timeout",waitedMs:f,message:`Command still running after ${a}s; moved to background. Use ListBackgroundCommands / ReadBackgroundOutput(task_id="${s}", mode="tail") to inspect.`};const h=_;return{ok:h.exitCode===0&&!h.timedOut,tool:"Bash",command:t,backgrounded:!1,taskId:s,exitCode:h.exitCode,signal:h.signal,timedOut:h.timedOut,durationMs:h.durationMs,stdout:h.stdout,stderr:h.stderr}}finally{g&&clearTimeout(g)}}catch(s){if(s?.code==="too_many_tasks"||s?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:t,backgrounded:!1,error:s.code,message:s.message};throw s}}function vt(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 t=P(o,["pattern"],"pattern"),e=E(o,["path"])||".",r=E(o,["include"]),i=E(o,["exclude"]),c=o.case_insensitive===!0,a=(()=>{const k=o.output_mode;return k==="files_with_matches"||k==="count"?k:"content"})(),l=C(o,["max_results"],at),s=c?"i":"";let m;try{m=new RegExp(t,s)}catch(k){throw new Error(`Invalid regex pattern: ${k instanceof Error?k.message:String(k)}`)}const f=r?G(r):null,g=i?G(i):null,w=await O(n,e),d=S(w.workspaceRoot,await u.realpath(w.targetPath)),_=await u.stat(d);let h;if(_.isFile())h=[d];else if(_.isDirectory())h=await ft(d,f,g,nt);else throw new Error(`Path is neither a file nor a directory: ${d}`);const y=[],x=[],B=[];let L=0,T=0,v=!1;for(const k of h){if(a==="content"&&y.length>=l){v=!0;break}const z={regex:m,maxResults:a==="content"?l-y.length:Number.MAX_SAFE_INTEGER,collectContent:a==="content",stopOnFirstMatch:a==="files_with_matches"},A=await mt(k,w.workspaceRoot,z);if(A.count>0){const I=p.relative(w.workspaceRoot,k).replace(/\\/g,"/");if(B.push(I),L+=A.count,a==="content"){for(const $ of A.matches){const F=Buffer.byteLength($.content,"utf-8")+64;if(T+F>rt){v=!0;break}T+=F,y.push($)}if(v)break;if(y.length>=l){v=!0;break}}else a==="count"&&x.push({file:I,count:A.count})}}const R={ok:!0,tool:"grep",pattern:t,searchPath:b(w.targetPath),outputMode:a,filesSearched:h.length,filesMatched:B.length,totalMatches:L,truncated:v};return a==="content"?R.matches=y:a==="files_with_matches"?R.matches=B:R.matches=x,R}}}function Ct(n,o,t,e){const r=o||"unknown",i=[bt(n),_t(n,t),yt(n,t),kt(n,t),vt(n),Pt(n,r,e),H(n)];return e&&i.push(V(r,e),Z(r,e),J(r,e)),i}export{Ct as createBuiltInFileTools,S as ensureInsideWorkspace,O as resolveWorkspaceTarget};
|
|
3
|
+
`+x:x;return{workspaceRoot:r.workspaceRoot,targetPath:i,content:B,isBinary:!1,truncated:w||p,totalLines:p?-1:f,shownFromLine:h,shownToLine:y}}finally{l.close(),a.destroy()}}function X(n){let o="",t=0;for(;t<n.length;){const e=n[t];if(e==="*")o+="[^/]*";else if(e==="?")o+="[^/]";else if(e==="{"){const r=n.indexOf("}",t);if(r>=0){const i=n.slice(t+1,r);o+=`(${i.split(",").join("|")})`,t=r}else o+="\\{"}else if(e==="["){const r=n.indexOf("]",t);r>=0?(o+=n.slice(t,r+1),t=r):o+="\\["}else"+^$.()|\\".includes(e)?o+="\\"+e:o+=e;t++}return new RegExp(`^${o}$`)}async function ht(n,o,t,e){const r=[];async function i(c){if(r.length>=e)return;const a=await u.readdir(c,{withFileTypes:!0});for(const l of a){if(r.length>=e)return;if(l.name.startsWith(".")&&l.isDirectory())continue;const s=d.join(c,l.name);if(l.isDirectory()){if(lt.has(l.name))continue;await i(s)}else if(l.isFile()){if(o&&!o.test(l.name)||t&&t.test(l.name))continue;r.push(s)}}}return await i(n),r}async function wt(n,o,t){if((await u.stat(n)).size>at)return{matches:[],count:0};if(await j(n))return{matches:[],count:0};const r=d.relative(o,n).replace(/\\/g,"/"),i=[];let c=0;const a=N(n,{encoding:"utf-8"}),l=U.createInterface({input:a,crlfDelay:1/0});try{let s=0;for await(const m of l)if(s++,t.regex.test(m)){if(c++,t.collectContent){let f=m;if(f.length>M&&(f=f.slice(0,M)+`... (line truncated to ${M} chars)`),i.push({file:r,line:s,content:f}),i.length>=t.maxResults)break}if(t.stopOnFirstMatch)break}}finally{l.close(),a.destroy()}return{matches:i,count:c}}const z=10*6e4,gt=z,_t=6e4,yt=10*6e4;function kt(n,o){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 e=P(t,["file_path","filePath"],"file_path"),r=P(t,["content"],"content"),i=E(t,["reason"]),c=await O(n,e),a=await W(c.targetPath),l=a?await u.readFile(c.targetPath,"utf-8").catch(()=>null):null,s=await G(n,e,r);if(o){const m=d.relative(s.workspaceRoot,s.targetPath).replace(/\\/g,"/");await o({filePath:m,operation:a?"UPDATE":"CREATE",beforeContent:l,afterContent:r,reason:i})}return{ok:!0,tool:"write_file",workspacePath:b(s.workspaceRoot),filePath:b(s.targetPath),bytes:s.bytes,createdParentDirectory:s.createdParentDirectory}}}}function bt(n,o){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 e=P(t,["file_path","filePath"],"file_path"),r=P(t,["old_string","oldString"],"old_string"),i=P(t,["new_string","newString"],"new_string"),c=E(t,["reason"]);if(!r)throw new Error("old_string must not be empty");const a=await ft(n,e),l=ut(a.content,r);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 s=a.content.replace(r,i),m=await G(n,e,s);if(o){const f=d.relative(m.workspaceRoot,m.targetPath).replace(/\\/g,"/");await o({filePath:f,operation:"UPDATE",beforeContent:a.content,afterContent:s,reason:c})}return{ok:!0,tool:"edit_file",workspacePath:b(m.workspaceRoot),filePath:b(m.targetPath),replacements:1,bytes:m.bytes}}}}function Pt(n,o){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 e=P(t,["file_path","filePath"],"file_path"),r=E(t,["reason"]),i=await O(n,e),c=S(i.workspaceRoot,await u.realpath(i.targetPath).catch(()=>i.targetPath)),a=await u.stat(c).catch(()=>null);if(!a)throw new Error(`File does not exist: ${c}`);if(!a.isFile())throw new Error(`Path is not a file: ${c}`);const l=await u.readFile(c,"utf-8").catch(()=>null);if(await u.rm(c,{force:!0}),o){const s=d.relative(i.workspaceRoot,c).replace(/\\/g,"/");await o({filePath:s,operation:"DELETE",beforeContent:l,afterContent:null,reason:r})}return{ok:!0,tool:"delete_file",workspacePath:b(i.workspaceRoot),filePath:b(c),deleted:!0}}}}function xt(n){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.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to read."},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(o){const t=P(o,["file_path","filePath"],"file_path"),e=C(o,["offset"],1),r=C(o,["limit"],et),i=await mt(n,t,e,r);return{ok:!0,tool:"read_file",workspacePath:b(i.workspaceRoot),filePath:b(i.targetPath),content:i.content,isBinary:i.isBinary,truncated:i.truncated,totalLines:i.totalLines,shownFromLine:i.shownFromLine,shownToLine:i.shownToLine}}}}function vt(n,o,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, and exit code. Set wait_seconds to 0 or n>0 to move long-running commands to the background and return a task_id immediately (or after n seconds); then use ListBackgroundCommands / ReadBackgroundOutput / KillBackgroundCommand to manage them.",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. Only applies to foreground (wait_seconds=-1); ignored once a command moves to background."},wait_seconds:{type:"number",description:"How long to block waiting for the command to finish. -1 (default): block until completion (current behavior, capped at timeout_ms). 0: spawn and immediately move to background, return task_id. n>0: wait up to n seconds; if still running, move to background and return task_id. Background commands remain subject to timeout_ms (total upper bound); inactivity_timeout_ms is ignored once backgrounded.",default:-1,minimum:-1},description:{type:"string",description:"Optional short reason for running the command."}},required:["command"],additionalProperties:!1},async execute(e,r){const i=P(e,["command"],"command").trim();if(!i)throw new Error("command must not be empty");const c=C(e,["timeout_ms","timeoutMs"],gt),a=Math.min(c,z),l=C(e,["inactivity_timeout_ms","inactivityTimeoutMs"],_t),s=Math.min(l,yt),m=E(e,["cwd"]),f=await dt(n,m),g=e.wait_seconds,w=typeof g=="number"&&Number.isFinite(g)?g:-1;if(w!==-1&&t)return await Tt({deps:t,command:i,agentId:o,workspaceRoot:f.workspaceRoot,cwd:f.cwd,timeoutMs:a,waitSeconds:w,settleSignal:r?.settleSignal});const p=await V({commandText:i,agentId:o,workspaceRoot:f.workspaceRoot,cwd:f.cwd,timeoutMs:a,inactivityTimeoutMs:s,onOutput:r?.onOutput});return{ok:p.exitCode===0&&!p.timedOut,tool:"Bash",command:i,cwd:b(f.cwd),exitCode:p.exitCode,signal:p.signal,timedOut:p.timedOut,inactivityTimedOut:p.inactivityTimedOut,timeoutMs:a,inactivityTimeoutMs:s,durationMs:p.durationMs,outputSpilled:p.outputSpilled,outputFilePath:p.outputFilePath,outputLineCount:p.outputLineCount,commandFilePath:p.commandFilePath,commandLineCount:p.commandLineCount,stdout:p.stdout,stderr:p.stderr}}}}async function Tt(n){const{deps:o,command:t,agentId:e,workspaceRoot:r,cwd:i,timeoutMs:c,waitSeconds:a,settleSignal:l}=n;try{const{taskId:s,completion:m}=o.manager.startCommand({commandText:t,agentId:e,workspaceRoot:r,cwd:i,timeoutMs:c,onCompleted:o.emitCompleted});if(a===0)return{ok:!0,tool:"Bash",command:t,backgrounded:!0,taskId:s,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use ListBackgroundCommands to view, ReadBackgroundOutput(task_id="${s}", mode="tail") to read output, KillBackgroundCommand(task_id="${s}") to stop.`};const f=Math.max(0,Math.floor(a*1e3));let g;const w=new Promise(_=>{g=setTimeout(()=>_("__timeout__"),f),g.unref?.()}),p=l?l.then(()=>"__settle__"):Promise.resolve("__never__");try{const _=await Promise.race([m,w,p]);if(_==="__settle__")return{ok:!0,tool:"Bash",command:t,backgrounded:!0,taskId:s,status:"backgrounded",reason:"watchdog_timeout",waitedMs:f,message:`Command still running after watchdog timeout; moved to background. Use ListBackgroundCommands / ReadBackgroundOutput(task_id="${s}", mode="tail") to inspect.`};if(_==="__timeout__")return{ok:!0,tool:"Bash",command:t,backgrounded:!0,taskId:s,status:"backgrounded",reason:"timeout",waitedMs:f,message:`Command still running after ${a}s; moved to background. Use ListBackgroundCommands / ReadBackgroundOutput(task_id="${s}", mode="tail") to inspect.`};const h=_;return{ok:h.exitCode===0&&!h.timedOut,tool:"Bash",command:t,backgrounded:!1,taskId:s,exitCode:h.exitCode,signal:h.signal,timedOut:h.timedOut,durationMs:h.durationMs,stdout:h.stdout,stderr:h.stderr}}finally{g&&clearTimeout(g)}}catch(s){if(s?.code==="too_many_tasks"||s?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:t,backgrounded:!1,error:s.code,message:s.message};throw s}}function Rt(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 t=P(o,["pattern"],"pattern"),e=E(o,["path"])||".",r=E(o,["include"]),i=E(o,["exclude"]),c=o.case_insensitive===!0,a=(()=>{const k=o.output_mode;return k==="files_with_matches"||k==="count"?k:"content"})(),l=C(o,["max_results"],ct),s=c?"i":"";let m;try{m=new RegExp(t,s)}catch(k){throw new Error(`Invalid regex pattern: ${k instanceof Error?k.message:String(k)}`)}const f=r?X(r):null,g=i?X(i):null,w=await O(n,e),p=S(w.workspaceRoot,await u.realpath(w.targetPath)),_=await u.stat(p);let h;if(_.isFile())h=[p];else if(_.isDirectory())h=await ht(p,f,g,rt);else throw new Error(`Path is neither a file nor a directory: ${p}`);const y=[],x=[],B=[];let L=0,T=0,v=!1;for(const k of h){if(a==="content"&&y.length>=l){v=!0;break}const Y={regex:m,maxResults:a==="content"?l-y.length:Number.MAX_SAFE_INTEGER,collectContent:a==="content",stopOnFirstMatch:a==="files_with_matches"},A=await wt(k,w.workspaceRoot,Y);if(A.count>0){const I=d.relative(w.workspaceRoot,k).replace(/\\/g,"/");if(B.push(I),L+=A.count,a==="content"){for(const $ of A.matches){const F=Buffer.byteLength($.content,"utf-8")+64;if(T+F>st){v=!0;break}T+=F,y.push($)}if(v)break;if(y.length>=l){v=!0;break}}else a==="count"&&x.push({file:I,count:A.count})}}const R={ok:!0,tool:"grep",pattern:t,searchPath:b(w.targetPath),outputMode:a,filesSearched:h.length,filesMatched:B.length,totalMatches:L,truncated:v};return a==="content"?R.matches=y:a==="files_with_matches"?R.matches=B:R.matches=x,R}}}function It(n,o,t,e){const r=o||"unknown",i=[xt(n),kt(n,t),bt(n,t),Pt(n,t),Rt(n),vt(n,r,e),Z(n)];return e&&i.push(J(r,e),Q(r,e),tt(r,e)),i}export{It as createBuiltInFileTools,S as ensureInsideWorkspace,O as resolveWorkspaceTarget};
|
|
4
4
|
|
|
@@ -10,5 +10,7 @@ export interface PreparedShellCommand {
|
|
|
10
10
|
readonly commandLineCount: number;
|
|
11
11
|
readonly commandFilePath?: string;
|
|
12
12
|
}
|
|
13
|
+
|
|
14
|
+
export declare function resolveUnixCommandShell(env?: NodeJS.ProcessEnv, exists?: (path: string) => boolean): string;
|
|
13
15
|
export declare function shellExecutable(): ShellExecutable;
|
|
14
16
|
export declare function prepareShellCommand(commandText: string, workspaceRoot: string, shell: ShellExecutable): Promise<PreparedShellCommand>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{countOutputLines as
|
|
1
|
+
import{existsSync as e}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=e){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 d(n,t){const i=n.endsWith(`
|
|
2
2
|
`)?n:`${n}
|
|
3
|
-
`;return
|
|
4
|
-
${
|
|
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 o=await m(t,"cmd",i.scriptExtension,d(n,i.scriptExtension));return{commandText:i.scriptInvocation(o),originalCommandText:n,commandLineCount:r,commandFilePath:a(o)}}export{C as prepareShellCommand,l as resolveUnixCommandShell,x as shellExecutable};
|
|
5
5
|
|