aws-runtime-bridge 1.9.162 → 1.9.169
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +324 -0
- package/dist/adapter/AcodeSdkAdapter.d.ts +31 -3
- package/dist/adapter/AcodeSdkAdapter.js +4 -9
- package/dist/adapter/ClaudeSdkAdapter.d.ts +2 -0
- package/dist/adapter/ClaudeSdkAdapter.js +3 -3
- package/dist/adapter/CodexSdkAdapter.d.ts +2 -0
- package/dist/adapter/CodexSdkAdapter.js +3 -3
- package/dist/adapter/OpencodeSdkAdapter.d.ts +2 -0
- package/dist/adapter/OpencodeSdkAdapter.js +3 -3
- package/dist/adapter/prompts.d.ts +1 -1
- package/dist/adapter/prompts.js +1 -1
- package/dist/adapter/types.d.ts +41 -4
- package/dist/adapter/types.js +1 -1
- package/dist/browser/frame-encode.d.ts +25 -0
- package/dist/browser/frame-encode.js +2 -0
- package/dist/browser/screencast-differ.d.ts +2 -3
- package/dist/browser/screencast-differ.js +1 -1
- package/dist/browser/screencast-manager.js +1 -1
- package/dist/browser/types.d.ts +5 -1
- package/dist/browser/types.js +1 -1
- package/dist/desktop/desktop-mcp-client.js +2 -2
- package/dist/routes/background-tasks.js +3 -3
- package/dist/routes/capabilities.js +1 -1
- package/dist/routes/dashboard.d.ts +2 -0
- package/dist/routes/dashboard.js +4 -4
- package/dist/routes/git.js +22 -22
- package/dist/routes/instance.js +1 -1
- package/dist/routes/launch.js +10 -10
- package/dist/routes/mcp-extra.js +2 -2
- package/dist/routes/mcp.d.ts +4 -0
- package/dist/routes/mcp.js +1 -1
- package/dist/routes/plugins.js +1 -1
- package/dist/routes/pty.d.ts +11 -3
- package/dist/routes/pty.js +3 -3
- package/dist/routes/runtime-binding.js +1 -1
- package/dist/routes/sessions.js +1 -1
- package/dist/routes/skills.js +1 -1
- package/dist/routes/sub-agents.js +8 -8
- package/dist/routes/terminal.d.ts +16 -2
- package/dist/routes/terminal.js +34 -36
- package/dist/services/agent-process-manager.js +1 -1
- package/dist/services/agent-pty-manager.js +4 -4
- package/dist/services/aws-client-agent-mcp.js +2 -2
- package/dist/services/capability-config.d.ts +8 -0
- package/dist/services/capability-config.js +2 -2
- package/dist/services/desktop-mcp-manager.d.ts +3 -1
- package/dist/services/desktop-mcp-manager.js +1 -1
- package/dist/services/instance-ai-config-service.js +1 -1
- package/dist/services/instance-features.d.ts +10 -0
- package/dist/services/instance-features.js +1 -1
- package/dist/services/instance-init-service.js +1 -1
- package/dist/services/launch-manager.d.ts +9 -1
- package/dist/services/launch-manager.js +6 -6
- package/dist/services/launch-metrics.d.ts +1 -1
- package/dist/services/launch-metrics.js +4 -3
- package/dist/services/mcp-deploy.d.ts +4 -0
- package/dist/services/mcp-env-injector.d.ts +12 -0
- package/dist/services/mcp-env-injector.js +2 -0
- package/dist/services/mcp-launch-binding-queue.d.ts +8 -0
- package/dist/services/mcp-launch-binding-queue.js +1 -1
- package/dist/services/orphan-monitor.js +1 -1
- package/dist/services/panel-env.d.ts +6 -2
- package/dist/services/panel-env.js +1 -1
- package/dist/services/plugin-manager.js +9 -9
- package/dist/services/process-detector.d.ts +23 -3
- package/dist/services/process-detector.js +13 -13
- package/dist/services/runtime-resources-snapshot.d.ts +3 -0
- package/dist/services/runtime-resources-snapshot.js +3 -0
- package/dist/services/session-output.d.ts +13 -0
- package/dist/services/session-output.js +4 -4
- package/dist/services/tunnel-client.js +1 -1
- package/dist/services/workspace-files.js +1 -1
- package/dist/types.d.ts +4 -0
- package/dist/utils/env-safety.d.ts +15 -0
- package/dist/utils/env-safety.js +2 -0
- package/dist/utils/lifecycle-log.d.ts +2 -0
- package/dist/utils/lifecycle-log.js +3 -0
- package/dist/utils/mcp-utils.js +1 -1
- package/package/acode/dist/background-command-manager.js +4 -4
- package/package/acode/dist/built-in-file-tools.d.ts +13 -0
- package/package/acode/dist/built-in-file-tools.js +2 -2
- package/package/acode/dist/builtins/shellCommandPreparation.d.ts +2 -0
- package/package/acode/dist/builtins/shellCommandPreparation.js +2 -2
- package/package/acode/dist/compaction.d.ts +10 -0
- package/package/acode/dist/compaction.js +6 -6
- package/package/acode/dist/context-overflow.js +1 -1
- package/package/acode/dist/index.d.ts +1 -0
- package/package/acode/dist/index.js +1 -1
- package/package/acode/dist/mcpToolNames.d.ts +4 -0
- package/package/acode/dist/mcpToolNames.js +1 -1
- package/package/acode/dist/runtime-environment.d.ts +2 -0
- package/package/acode/dist/runtime-environment.js +3 -2
- package/package/acode/dist/runtime.d.ts +68 -8
- package/package/acode/dist/runtime.js +28 -27
- package/package/acode/dist/sub-agent-manager.js +1 -1
- package/package/acode/dist/tool-allocation.js +1 -1
- package/package/acode/dist/tool-group-manager.d.ts +12 -0
- package/package/acode/dist/tool-group-manager.js +8 -4
- package/package/acode/dist/types.d.ts +8 -0
- package/package/acode/package.json +1 -1
- package/package/aws-client-agent-mcp/README.md +1 -0
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts +22 -8
- package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +10 -0
- package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/logger.d.ts +2 -1
- package/package/aws-client-agent-mcp/dist/logger.js +2 -2
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +19 -2
- package/package/aws-client-agent-mcp/dist/mcp-server.js +18 -18
- package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +15 -4
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +79 -29
- package/package/aws-client-agent-mcp/dist/memory-store.d.ts +2 -0
- package/package/aws-client-agent-mcp/dist/memory-store.js +3 -3
- package/package/aws-client-agent-mcp/dist/message-buffer.js +1 -1
- package/package/aws-client-agent-mcp/dist/office/office-workspace.d.ts +15 -0
- package/package/aws-client-agent-mcp/dist/office/office-workspace.js +1 -1
- package/package/aws-client-agent-mcp/dist/status-reporter.js +1 -1
- package/package/aws-client-agent-mcp/dist/tool-groups.d.ts +4 -0
- package/package/aws-client-agent-mcp/dist/tool-groups.js +2 -2
- package/package/aws-client-agent-mcp/dist/types.d.ts +52 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.js +1 -1
- package/package/aws-client-agent-mcp/package.json +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import I,{AxiosError as O}from"axios";import p from"ws";import{getActiveBridgeHttpPort as _}from"../config.js";import{logger as i}from"../utils/logger.js";import{loadConfigs as x,loadPrimaryLifecycleConfig as D}from"./auto-register.js";import{getRuntimeAccessToken as L,normalizeSchedulerBaseUrl as S}from"./runtime-binding.js";const W=15e3,P=5e3,$=3e4,k=.2,J=200,q=1*1024*1024,G=4001,H=768*1024,K=384*1024,h=new Map;function X(e){const r=e.serverUrl,n=e.instanceId;if(!r||!n)return null;try{const t=new URL(r),o=t.protocol==="https:"?"wss:":"ws:",c=L(r),l=x().find(m=>S(m.serverUrl)===r)||D(),s=c||l.userKey;if(c?i.debug("[TunnelClient] \u4F7F\u7528 runtime access token \u8FDE\u63A5\u96A7\u9053"):l.userKey&&i.warn("[TunnelClient] getRuntimeAccessToken \u8FD4\u56DE\u7A7A\uFF0C\u56DE\u9000\u5230 userKey\uFF08\u975E runtime token\uFF0C\u9274\u6743\u53EF\u80FD\u5931\u8D25\uFF09: targetUrl=",r),!s)return i.warn("[TunnelClient] \u7F3A\u5C11 runtime token\uFF0C\u65E0\u6CD5\u5EFA\u7ACB\u96A7\u9053: targetUrl=",r),null;const a=new URLSearchParams({instanceId:n});return{url:`${o}//${t.host}/ws/bridge-tunnel?${a.toString()}`,token:s}}catch(t){return i.warn("[TunnelClient] \u65E0\u6CD5\u89E3\u6790 serverUrl:",String(t)),null}}function oe(e,r){const n=S(e);if(!n){i.warn("[TunnelClient] serverUrl \u65E0\u6548\uFF0C\u65E0\u6CD5\u542F\u52A8\u96A7\u9053:",e);return}const t=h.get(n);t&&(t.shuttingDown=!0,C(t),h.delete(n));const o={serverUrl:n,instanceId:r,streams:new Map,shuttingDown:!1};h.set(n,o),A(o)}function se(){for(const e of h.values())e.shuttingDown=!0,C(e);h.clear()}function ie(e){const r=S(e);if(!r)return;const n=h.get(r);n&&(n.shuttingDown=!0,C(n),h.delete(r),i.info(`[TunnelClient] tunnel stopped: ${r}`))}function ce(e){const r=new Set(e.map(n=>S(n)).filter(n=>!!n));for(const[n,t]of h.entries())r.has(n)||(i.info(`[TunnelClient] serverUrl \u5DF2\u4E0D\u5728\u914D\u7F6E\u4E2D\uFF0C\u505C\u6B62\u65E7\u96A7\u9053: ${n}`),t.shuttingDown=!0,C(t),h.delete(n))}function C(e){e.timer&&(clearInterval(e.timer),e.timer=void 0),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0);for(const[r,n]of e.streams.entries()){try{n.ws.close(1e3,"tunnel client stopped")}catch{}e.streams.delete(r)}if(e.ws){e.ws.removeAllListeners();try{e.ws.close(1e3,"tunnel client stopped")}catch{}e.ws=void 0}}function A(e){if(e.shuttingDown)return;const r=e.instanceId;if(!r)return;const n=X(e);if(!n){b(e);return}i.info("[TunnelClient] \u8FDE\u63A5\u96A7\u9053\u670D\u52A1\u7AEF:",n.url);const t=new p(n.url,{handshakeTimeout:15e3,headers:{"X-Runtime-Token":n.token}});e.ws=t,t.on("open",()=>{i.info("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u5DF2\u5EFA\u7ACB: server=",e.serverUrl,"instanceId=",r),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0,e.reconnectAttempts=0,e.timer=setInterval(()=>{t.readyState===p.OPEN&&t.send(JSON.stringify({t:"ping"}))},W)}),t.on("unexpected-response",(o,c)=>{i.error("[TunnelClient] \u670D\u52A1\u7AEF\u62D2\u7EDD\u8FDE\u63A5\uFF08\u975E 101 \u54CD\u5E94\uFF09: server=",e.serverUrl,"statusCode=",c.statusCode,"statusMessage=",c.statusMessage)}),t.on("upgrade",o=>{i.debug("[TunnelClient] \u6536\u5230\u5347\u7EA7\u54CD\u5E94: statusCode=",o.statusCode)}),t.on("message",o=>{let c;typeof o=="string"?c=o:Buffer.isBuffer(o)?c=o.toString("utf-8"):c=Buffer.from(o).toString("utf-8");try{const l=JSON.parse(c);Y(e,l)}catch(l){i.warn("[TunnelClient] \u89E3\u6790\u96A7\u9053\u6D88\u606F\u5931\u8D25:",String(l))}}),t.on("close",(o,c)=>{if(i.warn("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u5173\u95ED: server=",e.serverUrl,"code=",o,"reason=",String(c)),B(e),o===G){i.warn("[TunnelClient] \u9274\u6743\u5931\u8D25\uFF084001\uFF09\uFF0C\u505C\u6B62\u81EA\u52A8\u91CD\u8FDE\uFF1B\u5F85\u91CD\u65B0\u6CE8\u518C\u540E\u518D\u542F\u52A8\u96A7\u9053: server=",e.serverUrl);return}b(e)}),t.on("error",o=>{i.warn("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u9519\u8BEF: server=",e.serverUrl,"err=",o.message,"code=",o.code),B(e),b(e)})}function B(e){e.timer&&(clearInterval(e.timer),e.timer=void 0);for(const[r,n]of e.streams.entries()){try{n.ws.close(1011,"tunnel disconnected")}catch{}e.streams.delete(r)}e.ws=void 0}function b(e){if(e.shuttingDown||e.reconnectTimer)return;const r=(e.reconnectAttempts??0)+1;e.reconnectAttempts=r;const n=Math.min(P*Math.pow(2,r-1),$),t=1-k+Math.random()*k*2,o=Math.round(n*t);i.debug("[TunnelClient] \u8BA1\u5212\u91CD\u8FDE: server=",e.serverUrl,"attempt=",r,"delayMs=",o),e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,A(e)},o)}function Y(e,r){switch(r.t){case"req":j(e,r);break;case"wsopen":z(e,r);break;case"wsmsg":F(e,r);break;case"wsclose":V(e,r);break;case"ping":f(e,{t:"pong"});break;case"pong":break;default:i.debug("[TunnelClient] \u672A\u77E5\u6D88\u606F\u7C7B\u578B: t=",r.t)}}async function j(e,r){const n=r.id,t=r.method||"GET",o=r.path||"/",c=`http://127.0.0.1:${_()}${o}`;try{const l=r.body?Buffer.from(r.body,"base64"):void 0,s={};if(r.headers)for(const[d,u]of Object.entries(r.headers))u&&u.length>0&&(s[d]=u[0]);s["x-bridge-tunnel-source"]=e.serverUrl;const a=await I.request({url:c,method:t,headers:s,data:l,timeout:0,responseType:"stream",validateStatus:()=>!0}),m={};for(const[d,u]of Object.entries(a.headers))u!==void 0&&(m[d]=Array.isArray(u)?u:[String(u)]);const v=a.data,M=String(m["content-type"]?.[0]||"").toLowerCase().includes("text/event-stream"),g=[];let w=0,T=!1,y=!1;try{if(v)for await(const d of v){const u=Buffer.isBuffer(d)?d:Buffer.from(d);if(u.length!==0){if(T){if(!E(e,n,u))return}else if(M){if(T=!0,y=!0,!f(e,{t:"res",id:n,status:a.status,headers:m,body:null,chunked:!0})||!E(e,n,u))return}else if(g.push(u),w+=u.length,w>H){if(T=!0,y=!0,!f(e,{t:"res",id:n,status:a.status,headers:m,body:null,chunked:!0}))return;for(const R of g)if(!E(e,n,R))return;g.length=0,w=0}}}}catch(d){const u=d instanceof Error?d.message:String(d);i.warn("[TunnelClient] \u672C\u5730\u6D41\u8BFB\u53D6\u4E2D\u65AD:",t,o,"->",u),y?f(e,{t:"resend",id:n,error:u}):f(e,{t:"res",id:n,status:502,headers:{"content-type":["text/plain; charset=utf-8"]},body:Buffer.from(u).toString("base64")});return}if(T){f(e,{t:"resend",id:n});return}const N=w>0?Buffer.concat(g).toString("base64"):"";f(e,{t:"res",id:n,status:a.status,headers:m,body:N||null})}catch(l){const s=l instanceof O?l.message:String(l);i.warn("[TunnelClient] \u672C\u5730\u8F6C\u53D1\u5931\u8D25:",t,o,"->",s),f(e,{t:"res",id:n,status:502,headers:{"content-type":["text/plain; charset=utf-8"]},body:Buffer.from(s).toString("base64")})}}function E(e,r,n){let t=0;for(;t<n.length;){const o=n.subarray(t,t+K);if(!f(e,{t:"reschunk",id:r,d:o.toString("base64")}))return!1;t+=o.length}return!0}function z(e,r){const n=r.id,t=r.path||"/",o=`ws://127.0.0.1:${_()}${t}`;let c;try{c=new p(o,{handshakeTimeout:1e4})}catch(s){i.warn("[TunnelClient] \u672C\u5730 WS \u8FDE\u63A5\u5931\u8D25:",String(s)),f(e,{t:"wsclose",id:n,code:1011,reason:"local ws connect failed"});return}const l={ws:c,pending:[]};e.streams.set(n,l),c.on("open",()=>{for(const s of l.pending)U(l,s.data,s.bin);l.pending=[],f(e,{t:"wsopened",id:n})}),c.on("message",(s,a)=>{const m=Buffer.isBuffer(s)?s:Buffer.from(s);a&&e.ws&&e.ws.bufferedAmount>q||f(e,{t:"wsmsg",id:n,bin:a,d:m.toString("base64")})}),c.on("close",(s,a)=>{e.streams.delete(n),f(e,{t:"wsclose",id:n,code:s,reason:String(a)})}),c.on("error",s=>{i.warn("[TunnelClient] \u672C\u5730 WS \u9519\u8BEF: id=",n,"err=",s.message),e.streams.delete(n);try{c.close(1011,s.message)}catch{}f(e,{t:"wsclose",id:n,code:1011,reason:s.message})})}function U(e,r,n){n?e.ws.send(r):e.ws.send(r.toString("utf-8"))}function F(e,r){const n=e.streams.get(r.id);if(!n)return;const t=r.d?Buffer.from(r.d,"base64"):Buffer.alloc(0);if(n.ws.readyState!==p.OPEN){n.pending.length>=J&&(n.pending.shift(),i.warn("[TunnelClient] \u672C\u5730 WS \u672A\u5C31\u7EEA\uFF0C\u6392\u961F\u6D88\u606F\u8D85\u4E0A\u9650\uFF0C\u4E22\u5F03\u6700\u65E7\u4E00\u6761: id=",r.id)),n.pending.push({data:t,bin:!!r.bin});return}U(n,t,!!r.bin)}function V(e,r){const n=e.streams.get(r.id);if(n){e.streams.delete(r.id);try{n.ws.close(r.code??1e3,r.reason||"")}catch{}}}function f(e,r){if(!e.ws||e.ws.readyState!==p.OPEN)return!1;try{return e.ws.send(JSON.stringify(r)),!0}catch(n){return i.warn("[TunnelClient] sendJson \u5931\u8D25:",String(n)),!1}}export{oe as startTunnelClient,se as stopTunnelClient,ie as stopTunnelClientForServer,ce as stopTunnelClientsExcept};
|
|
2
2
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createReadStream as q,createWriteStream as O,promises as s}from"node:fs";import lt from"node:os";import w from"node:path";import{Readable as ht}from"node:stream";import{pipeline as ut}from"node:stream/promises";import{TextDecoder as wt}from"node:util";import{createGunzip as dt}from"node:zlib";import*as ft from"tar";import pt from"unzipper";const{ZipArchive:_}=await import("archiver"),x={maxEntries:1e4,maxFileBytes:512*1024*1024,maxTotalBytes:2*1024*1024*1024,maxPathDepth:64,maxPathLength:4096},mt=new wt("gbk");function u(t){return String(t||"").replace(/\\/g,"/")}function Z(t){const e=w.resolve(String(t||"").trim());if(!e)throw new Error("workspacePath is required");return e}async function yt(t){const e=Z(t),r=await s.realpath(e);if(!(await s.stat(r)).isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);return r}async function v(t){return{requestedRoot:Z(t),workspaceRoot:await yt(t)}}function C(t,e){const r=w.resolve(e),i=w.relative(t,r);if(i.startsWith("..")||w.isAbsolute(i))throw new Error(`Target path is outside workspace: ${r}`);return r}async function D(t){return s.realpath(t)}async function F(t){await s.realpath(w.dirname(t));try{if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${t}`)}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)!=="ENOENT")throw e}}function L(t,e,r){const i=w.resolve(t,r),o=w.relative(t,i);return o.startsWith("..")||w.isAbsolute(o)?i:C(e,w.join(e,o))}async function b({workspacePath:t,targetPath:e=""}){const{requestedRoot:r,workspaceRoot:i}=await v(t),o=String(e||"").trim(),a=o?L(r,i,o):i,c=await D(a);return{workspaceRoot:i,resolvedTargetPath:c}}function $(t){const e=String(t||"").trim();if(!e)throw new Error("entryName is required");if(e==="."||e==="..")throw new Error("entryName is invalid");if(e.includes("/")||e.includes("\\")||w.basename(e)!==e)throw new Error(`entryName must be a plain file or directory name: ${e}`);return e}function G(t){const e=String(t||"");if(!/[\u00c0-\u00ff]/.test(e))return e;const r=Buffer.from(e,"latin1").toString("utf8");return!r||r.includes("\uFFFD")?e:r}function B(t){const e=G(t);return $(w.basename(e.replace(/\\/g,"/")))}function gt(t,e){if(!t)return B(e);const i=G(String(t||e||"")).replace(/\\/g,"/").split("/").filter(Boolean).map(o=>$(o));return i.length===0?B(e):w.join(...i)}function H(t){return(t&4095).toString(8).padStart(4,"0")}function Pt(t){const e=String(t||"").trim();if(!/^[0-7]{3,4}$/.test(e))throw new Error("mode must be a 3 or 4 digit octal string");return Number.parseInt(e,8)}function I(t,e,r,i,o,a,c){const n=t&e?"r":"-",h=t&r?"w":"-",l=(t&i)!==0,d=(t&o)!==0?l?a:c:l?"x":"-";return`${n}${h}${d}`}function kt(t){return[I(t,256,128,64,2048,"s","S"),I(t,32,16,8,1024,"s","S"),I(t,4,2,1,512,"t","T")].join("")}function xt(t){if(!(t.length<24||t.toString("hex",0,8)!=="89504e470d0a1a0a"))return{format:"png",width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}function vt(t){if(!(t.length<10||t.toString("ascii",0,6)!=="GIF87a"&&t.toString("ascii",0,6)!=="GIF89a"))return{format:"gif",width:t.readUInt16LE(6),height:t.readUInt16LE(8)}}function Et(t){if(t.length<4||t[0]!==255||t[1]!==216)return;let e=2;for(;e+9<t.length;){if(t[e]!==255){e+=1;continue}const r=t[e+1],i=t.readUInt16BE(e+2);if(i<2)return;if(r>=192&&r<=207&&![196,200,204].includes(r)&&e+8<t.length)return{format:"jpeg",height:t.readUInt16BE(e+5),width:t.readUInt16BE(e+7)};e+=2+i}}function St(t){if(t.length<30||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WEBP")return;const e=t.toString("ascii",12,16);if(e==="VP8X"&&t.length>=30)return{format:"webp",width:1+t.readUIntLE(24,3),height:1+t.readUIntLE(27,3)};if(e==="VP8 "&&t.length>=30)return{format:"webp",width:t.readUInt16LE(26)&16383,height:t.readUInt16LE(28)&16383};if(e==="VP8L"&&t.length>=25){const r=t.readUInt32LE(21);return{format:"webp",width:(r&16383)+1,height:(r>>14&16383)+1}}}async function K(t,e){if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to change permissions on symbolic link: ${t}`);const i=await s.stat(t);if(!e||!i.isDirectory())return[t];const o=await s.readdir(t),a=await Promise.all(o.map(c=>{const n=w.join(t,c);return K(n,!0)}));return[t,...a.flat()]}async function Rt(t){if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to change permissions on symbolic link: ${t}`);await D(t)}async function Dt(t){const e=await s.open(t,"r");try{const r=Buffer.alloc(512),{bytesRead:i}=await e.read(r,0,r.length,0),o=r.subarray(0,i);return xt(o)||vt(o)||Et(o)||St(o)}finally{await e.close()}}async function T({workspacePath:t,targetPath:e},r={}){const{requestedRoot:i,workspaceRoot:o}=await v(t),a=String(e||"").trim();if(!a)throw new Error("targetPath is required");const c=L(i,o,a),n=await D(c);if(!r.allowWorkspaceRoot&&n===o)throw new Error("Workspace root cannot be modified");return{workspaceRoot:o,resolvedTargetPath:n}}async function X(t){const{requestedRoot:e,workspaceRoot:r}=await v(t.workspacePath),i=String(t.targetPath||"").trim();if(!i)return{workspaceRoot:r,resolvedTargetPath:r};const o=L(e,r,i);return await et(o)?{workspaceRoot:r,resolvedTargetPath:await s.realpath(o)}:(await s.realpath(w.dirname(o)),{workspaceRoot:r,resolvedTargetPath:o})}function V(t){const e=t.toLowerCase();return e.endsWith(".zip")?"zip":e.endsWith(".tar.gz")||e.endsWith(".tgz")?"tgz":e.endsWith(".tar")?"tar":e.endsWith(".gz")?"gz":null}function Y(t){return t.replace(/\.tar\.gz$/i,"").replace(/\.tgz$/i,"").replace(/\.zip$/i,"").replace(/\.tar$/i,"").replace(/\.gz$/i,"")}function Ft(t,e){const r=$(Y(e)||"extracted");return w.join(t,r)}function M(t,e){const r=String(e||"").replace(/\\/g,"/"),i=r.split("/").filter(Boolean);if(!r||r.startsWith("/")||/^[A-Za-z]:/.test(r))throw new Error(`Archive entry path is invalid: ${e}`);if(r.length>x.maxPathLength||i.length>x.maxPathDepth)throw new Error(`Archive entry path is too deep or too long: ${e}`);return C(t,w.join(t,r))}function Tt(t){const e=t.props?.pathBuffer;if(!e||t.props?.flags?.isUnicode)return t.path;const r=mt.decode(e);return!r||r.includes("\uFFFD")?t.path:r}async function J(t){const e=t.autodrain?.();e&&await new Promise((r,i)=>{e.on("close",r),e.on("end",r),e.on("finish",r),e.on("error",i)})}function N(t){if(t.entries+=1,t.entries>x.maxEntries)throw new Error(`Archive contains too many entries. Limit: ${x.maxEntries}`)}function Q(t,e){if(t.totalBytes+=e,e>x.maxFileBytes)throw new Error(`Archive entry exceeds max size. Limit: ${x.maxFileBytes} bytes`);if(t.totalBytes>x.maxTotalBytes)throw new Error(`Archive extraction exceeds total size. Limit: ${x.maxTotalBytes} bytes`)}async function tt(t,e,r){let i=0;t.on("data",o=>{const a=Buffer.isBuffer(o)?o.length:Buffer.byteLength(o);i+=a,(i>x.maxFileBytes||r.totalBytes+i>x.maxTotalBytes)&&t instanceof ht&&t.destroy(new Error("Archive extraction size limit exceeded"))}),await ut(t,O(e)),Q(r,i)}async function et(t){try{return await s.access(t),!0}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)==="ENOENT")return!1;throw e}}async function W({workspacePath:t,filePath:e}){const{requestedRoot:r,workspaceRoot:i}=await v(t),o=String(e||"").trim();if(!o)throw new Error("filePath is required");return{workspaceRoot:i,resolvedFilePath:L(r,i,o)}}async function Gt(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.targetPath||"").trim();if(!r){const{resolvedTargetPath:h}=await b(t);return rt(e,h)}const i=w.resolve(r);let o;try{o=await s.realpath(i)}catch{throw new Error(`Path not found: ${i}`)}if(!(await s.stat(o)).isDirectory())throw new Error(`Path is not a directory: ${i}`);const c=w.relative(e,o),n=c===""||!c.startsWith("..")&&!w.isAbsolute(c);return rt(e,n?o:i)}async function rt(t,e){if(!(await s.stat(e)).isDirectory())throw new Error(`Path is not a directory: ${e}`);const i=await s.readdir(e,{withFileTypes:!0}),o=await Promise.all(i.map(async a=>{const c=w.join(e,a.name),n=a.isFile()?(await s.stat(c)).size:void 0;return{name:a.name,path:u(c),isDirectory:a.isDirectory(),size:n}}));return{currentPath:u(e),workspacePath:u(t),items:o}}async function Ht(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t),i=await D(r),o=await s.stat(i);if(!o.isFile())throw new Error(`Path is not a file: ${i}`);const a=await s.readFile(i,"utf-8");return{workspacePath:u(e),filePath:u(i),content:a,mtimeMs:o.mtimeMs}}const it={maxEntries:1e5,maxDepth:32};async function zt(t){let e=0,r=0;async function i(o,a){if(a>=it.maxDepth)return;let c;try{c=await s.readdir(o,{withFileTypes:!0})}catch{return}for(const n of c){if(r+=1,r>it.maxEntries)return;if(n.isSymbolicLink())continue;const h=w.join(o,n.name);try{if(n.isDirectory())await i(h,a+1);else if(n.isFile()){const l=await s.stat(h);e+=l.size}}catch{}}}return await i(t,0),e}async function Kt(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t,{allowWorkspaceRoot:!0}),[i,o]=await Promise.all([s.stat(r),s.lstat(r)]),a=i.isDirectory(),c=i.isFile()?await Dt(r):void 0,n=a?await zt(r):i.size;return{workspacePath:u(e),targetPath:u(r),name:w.basename(r),isDirectory:i.isDirectory(),isFile:i.isFile(),isSymbolicLink:o.isSymbolicLink(),size:n,mode:i.mode,modeOctal:H(i.mode),permissions:kt(i.mode),uid:i.uid,gid:i.gid,atimeMs:i.atimeMs,mtimeMs:i.mtimeMs,ctimeMs:i.ctimeMs,birthtimeMs:i.birthtimeMs,...c?{image:c}:{}}}async function Xt(t){const e=Pt(t.mode),r=!!t.recursive,{workspaceRoot:i,resolvedTargetPath:o}=await T(t),a=await K(o,r);for(const c of a)await Rt(c),await s.chmod(c,e);return{ok:!0,workspacePath:u(i),targetPath:u(o),mode:e,modeOctal:H(e),recursive:r,changedCount:a.length}}async function Vt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t),i=await D(r),o=await s.stat(i);if(!o.isFile())throw new Error(`Path is not a file: ${i}`);const a=w.extname(i).toLowerCase();if(a===".doc")return{workspacePath:u(e),filePath:u(i),kind:"unsupported",content:"",message:"\u6682\u4E0D\u652F\u6301\u65E7\u7248 .doc \u683C\u5F0F\u9884\u89C8\uFF0C\u8BF7\u53E6\u5B58\u4E3A .docx \u540E\u518D\u6253\u5F00\u3002",size:o.size,mtimeMs:o.mtimeMs};if(a!==".docx")throw new Error("Document preview only supports .docx files");return{workspacePath:u(e),filePath:u(i),kind:"html",content:"",size:o.size,mtimeMs:o.mtimeMs}}async function Yt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t);await s.mkdir(w.dirname(r),{recursive:!0}),await F(r),await s.writeFile(r,String(t.content??""),"utf-8");const i=await s.stat(r);return{ok:!0,workspacePath:u(e),filePath:u(r),mtimeMs:i.mtimeMs}}async function Jt(t){const{workspaceRoot:e,resolvedTargetPath:r}=await b(t),i=$(t.entryName),o=w.join(r,i);if(!(await s.stat(r)).isDirectory())throw new Error(`Path is not a directory: ${r}`);try{throw await s.access(o),new Error(`Path already exists: ${o}`)}catch(c){if((typeof c=="object"&&c!==null?Reflect.get(c,"code"):void 0)!=="ENOENT")throw c}return t.isDirectory?await s.mkdir(o,{recursive:!1}):(await s.mkdir(w.dirname(o),{recursive:!0}),await F(o),await s.writeFile(o,"","utf-8")),{ok:!0,workspacePath:u(e),targetPath:u(o),isDirectory:t.isDirectory}}async function Qt(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t),i=$(t.newName),o=w.join(w.dirname(r),i);if(o===r)return{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(o)};await s.stat(r);try{throw await s.access(o),new Error(`Path already exists: ${o}`)}catch(a){if((typeof a=="object"&&a!==null?Reflect.get(a,"code"):void 0)!=="ENOENT")throw a}return await s.rename(r,o),{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(o)}}async function te(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t),i=await b({workspacePath:t.workspacePath,targetPath:t.destinationPath});if(!(await s.stat(i.resolvedTargetPath)).isDirectory())throw new Error(`Destination is not a directory: ${i.resolvedTargetPath}`);if((await s.stat(r)).isDirectory()){const n=w.relative(r,i.resolvedTargetPath);if(n===""||!n.startsWith("..")&&!w.isAbsolute(n))throw new Error("Cannot move a directory into itself or its descendant")}const c=w.join(i.resolvedTargetPath,w.basename(r));if(c===r)return{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(c),destinationPath:u(i.resolvedTargetPath)};try{throw await s.access(c),new Error(`Path already exists: ${c}`)}catch(n){if((typeof n=="object"&&n!==null?Reflect.get(n,"code"):void 0)!=="ENOENT")throw n}return await s.rename(r,c),{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(c),destinationPath:u(i.resolvedTargetPath)}}async function ee(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t),i=await s.stat(r),o=w.parse(r).root;if(r===o)throw new Error("Filesystem root cannot be deleted");return i.isDirectory()?await s.rm(r,{recursive:!0,force:!1}):await s.unlink(r),{ok:!0,workspacePath:u(e),targetPath:u(r)}}async function re(t){if(!Array.isArray(t.files)||t.files.length===0)throw new Error("files are required");const{workspaceRoot:e,resolvedTargetPath:r}=await X(t);if(!(await s.stat(r)).isDirectory())throw new Error(`Path is not a directory: ${r}`);const o=[];for(const a of t.files){const c=B(a.originalname),n=gt(a.relativePath,a.originalname),h=w.join(r,n);await s.mkdir(w.dirname(h),{recursive:!0}),await F(h),await s.copyFile(a.path,h);let l;t.extractArchives&&V(h)&&(l=await Wt({workspacePath:e,archivePath:h,outputPath:Ft(r,c)})),o.push({fileName:c,targetPath:u(h),size:a.size,extracted:l})}return{ok:!0,workspacePath:u(e),targetPath:u(r),files:o}}async function ie(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t),i=await s.stat(r),o=w.basename(r);return{workspacePath:u(e),targetPath:u(r),resolvedTargetPath:r,fileName:i.isDirectory()?`${o||"workspace"}.zip`:o,contentType:i.isDirectory()?"application/zip":Lt(r),isDirectory:i.isDirectory(),size:i.isDirectory()?void 0:i.size}}function Lt(t){const e=w.extname(t).toLowerCase();return{".svg":"image/svg+xml",".svgz":"image/svg+xml",".ico":"image/x-icon",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".avif":"image/avif",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".xml":"application/xml; charset=utf-8",".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".md":"text/markdown; charset=utf-8",".csv":"text/csv; charset=utf-8",".pdf":"application/pdf",".zip":"application/zip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm"}[e]||"application/octet-stream"}async function oe(t,e){const r=new _({zlib:{level:9}}),i=new Promise((o,a)=>{e.on("close",o),e.on("finish",o),r.on("error",a),e.on("error",a)});r.pipe(e),r.directory(t,!1),await r.finalize(),await i}async function ae(t,e,r,i){const o=w.join(lt.tmpdir(),"agentswork-bridge-downloads");await s.mkdir(o,{recursive:!0});const a=(e||"workspace.zip").replace(/[^\w.-]/g,"_").replace(/\.zip$/i,"")||"workspace",c=w.join(o,`${a}-${Date.now()}-${Math.random().toString(36).slice(2,8)}.zip`),n=new _({zlib:{level:9}}),h=()=>n.pointer(),l=()=>n.abort(),f=O(c),d=new Promise((m,g)=>{f.on("close",m),f.on("finish",m),n.on("error",g),f.on("error",g)});d.catch(()=>{}),n.pipe(f);const y=setInterval(()=>{try{if(i?.()){l();return}r?.(h())}catch{}},200);try{return n.on("progress",()=>{i?.()&&l()}),n.directory(t,!1),i?.()&&l(),await n.finalize(),await d,r?.(h()),c}catch(m){throw await s.rm(c,{force:!0}).catch(()=>{}),m}finally{clearInterval(y)}}async function $t(t,e,r){let i=0,o;const a=q(t),c=a.pipe(pt.Parse({forceStream:!0}));try{for await(const n of c){if(o){await J(n);continue}const h=Tt(n);try{const l=M(e,h);if(N(r),n.type==="Directory"){await s.mkdir(l,{recursive:!0});continue}if(n.type!=="File")throw new Error(`Unsupported archive entry type: ${h}`);await s.mkdir(w.dirname(l),{recursive:!0}),await F(l),await tt(n,l,r),i+=1}catch(l){o=l,await J(n)}}}finally{a.destroy(),c.destroy()}if(o)throw o;return i}async function At(t,e,r,i){let o=0,a;const c=(n,h)=>{if(a)return!1;try{M(e,n),N(i);const l=String(h.type||"").toLowerCase();if(l==="symboliclink"||l==="link")throw new Error(`Archive links are not supported: ${n}`);if(l!=="file"&&l!=="oldfile"&&l!=="contiguousfile"&&l!=="directory")throw new Error(`Unsupported archive entry type: ${n}`);return typeof h.size=="number"&&Q(i,h.size),l!=="directory"&&(o+=1),!0}catch(l){return a=l,!1}};if(await ft.x({file:t,cwd:e,gzip:r,strict:!0,filter:(n,h)=>c(n,h)}),a)throw a;return o}async function Ct(t,e,r){const i=Y(w.basename(t)),o=M(e,i||"decompressed");return N(r),await s.mkdir(w.dirname(o),{recursive:!0}),await F(o),await tt(q(t).pipe(dt()),o,r),1}async function Wt(t){const{requestedRoot:e,workspaceRoot:r}=await v(t.workspacePath),{resolvedTargetPath:i}=await X({workspacePath:t.workspacePath,targetPath:t.outputPath||""}),o=L(e,r,String(t.archivePath||"").trim()),a=await D(o);if(!(await s.stat(a)).isFile())throw new Error(`Archive path is not a file: ${a}`);if(await et(i)||await s.mkdir(i,{recursive:!0}),!(await s.stat(i)).isDirectory())throw new Error(`Output path is not a directory: ${i}`);const h=V(a);if(!h)throw new Error("Unsupported archive type. Supported: .zip, .tar, .tar.gz, .tgz, .gz");let l=0;const f={entries:0,totalBytes:0};return h==="zip"?l=await $t(a,i,f):h==="tar"||h==="tgz"?l=await At(a,i,h==="tgz",f):l=await Ct(a,i,f),{ok:!0,workspacePath:u(r),archivePath:u(a),targetPath:u(i),extractedEntries:l}}function ot(t){const e=t.match(/^(.*?)\{([^}]+)\}(.*)$/);if(!e)return[t];const[,r,i,o]=e;return i.split(",").flatMap(a=>ot(r+a.trim()+o))}function at(t,e){const r=String(e||"").trim();if(!r||r==="*"||r==="*.*")return!0;const i=t.toLowerCase();return ot(r.toLowerCase()).some(a=>{if(a==="*")return!0;const c=a.replace(/\./g,"\\.").replace(/\*\*/g,"<<GLOBSTAR>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<GLOBSTAR>>/g,".*");return new RegExp(`^${c}$`).test(i)})}function j(t){return t===".git"||t==="node_modules"||t===".svn"||t===".hg"}const nt=10*1024*1024,bt=1e3;async function ne(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.keyword||"").trim();if(!r)throw new Error("keyword is required");const i=!!t.ignoreCase,o=String(t.fileMask||"").trim(),a=typeof t.maxResults=="number"&&t.maxResults>0?t.maxResults:bt,c=i?r.toLowerCase():r,h=(t.mode==="filename"?"filename":"content")==="filename",l=[];let f=0,d=!1;async function y(m){if(d)return;let g;try{g=await s.readdir(m,{withFileTypes:!0})}catch{return}for(const p of g){if(d)return;const P=C(e,w.join(m,p.name));if(p.isSymbolicLink())continue;if(p.isDirectory()){if(j(p.name))continue;await y(P);continue}if(!p.isFile()||o&&!at(p.name,o))continue;f+=1;let k;try{k=await s.stat(P)}catch{continue}if(k.size>nt)continue;if(h){const E=(i?p.name.toLowerCase():p.name).indexOf(c);if(E!==-1&&(l.push({filePath:u(P),lineNumber:0,lineContent:p.name,matchStart:E,matchEnd:E+r.length}),l.length>=a)){d=!0;return}continue}let S;try{S=await s.readFile(P,"utf-8")}catch{continue}const z=S.split(/\r?\n/);for(let R=0;R<z.length;R+=1){const E=z[R],ct=i?E.toLowerCase():E;let U=0;for(;;){const A=ct.indexOf(c,U);if(A===-1)break;if(l.push({filePath:u(P),lineNumber:R+1,lineContent:E,matchStart:A,matchEnd:A+r.length}),l.length>=a){d=!0;return}U=A+1}}}}return await y(e),{workspacePath:u(e),keyword:r,totalFiles:f,totalMatches:l.length,matches:l,truncated:d}}const Bt=100,It=120;async function se(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.keyword||"").trim();if(!r)throw new Error("keyword is required");const i=!!t.ignoreCase,o=i?r.toLowerCase():r,a=typeof t.maxResults=="number"&&t.maxResults>0?t.maxResults:Bt,c=typeof t.maxDirectories=="number"&&t.maxDirectories>0?t.maxDirectories:It,n=String(t.rootPath||"").trim(),h=n?w.resolve(/^[A-Za-z]:$/.test(n)?`${n}/`:n):e;let l;try{l=await s.realpath(h)}catch{throw new Error(`Path not found: ${h}`)}if(!(await s.stat(l)).isDirectory())throw new Error(`Path is not a directory: ${h}`);const d=[],y=[l];let m=0,g=!1;for(;y.length>0&&d.length<a&&m<c;){const p=y.shift();m+=1;let P;try{P=await s.readdir(p,{withFileTypes:!0})}catch{continue}for(const k of P){if(d.length>=a){g=!0;break}if(k.isSymbolicLink())continue;const S=w.join(p,k.name);if(k.isDirectory()&&j(k.name))continue;const z=w.relative(l,S).replace(/\\/g,"/");(i?z.toLowerCase():z).includes(o)&&d.push({name:k.name,path:u(S),isDirectory:k.isDirectory()}),k.isDirectory()&&m<c&&y.push(S)}}return(m>=c||d.length>=a)&&(g=!0),d.sort((p,P)=>p.isDirectory===P.isDirectory?p.name.localeCompare(P.name):p.isDirectory?-1:1),{workspacePath:u(e),rootPath:u(l),keyword:r,items:d,truncated:g}}async function st(t,e,r,i){let o;try{o=await s.readFile(t,"utf-8")}catch{return{changed:!1,count:0}}const a=o;let c=0;if(i){const n=e.toLowerCase();let h=0;for(;;){const f=o.toLowerCase().indexOf(n,h);if(f===-1)break;o=o.slice(0,f)+r+o.slice(f+e.length),c+=1;const d=r.length||1;h=f+d}}else{let n=0;for(;;){const h=o.indexOf(e,n);if(h===-1)break;o=o.slice(0,h)+r+o.slice(h+e.length),c+=1;const l=r.length||1;n=h+l}}return o===a?{changed:!1,count:0}:(await F(t),await s.writeFile(t,o,"utf-8"),{changed:!0,count:c})}async function ce(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.keyword||"").trim();if(!r)throw new Error("keyword is required");const i=String(t.replacement??""),o=!!t.ignoreCase,a=String(t.fileMask||"").trim(),c=String(t.filePath||"").trim();let n=0,h=0;if(c){const{resolvedFilePath:f}=await W({workspacePath:t.workspacePath,filePath:c}),d=await st(f,r,i,o);return d.changed&&(n=1,h=d.count),{workspacePath:u(e),keyword:r,replacement:i,changedFiles:n,changedMatches:h}}async function l(f){let d;try{d=await s.readdir(f,{withFileTypes:!0})}catch{return}for(const y of d){const m=C(e,w.join(f,y.name));if(y.isSymbolicLink())continue;if(y.isDirectory()){if(j(y.name))continue;await l(m);continue}if(!y.isFile()||a&&!at(y.name,a))continue;try{if((await s.stat(m)).size>nt)continue}catch{continue}const g=await st(m,r,i,o);g.changed&&(n+=1,h+=g.count)}}return await l(e),{workspacePath:u(e),keyword:r,replacement:i,changedFiles:n,changedMatches:h}}export{Xt as chmodWorkspaceEntry,Jt as createWorkspaceEntry,ee as deleteWorkspaceEntry,Wt as extractWorkspaceArchive,Kt as getWorkspaceEntryProperties,Gt as listWorkspaceDirectory,te as moveWorkspaceEntry,Vt as previewWorkspaceDocument,Ht as readWorkspaceFile,Qt as renameWorkspaceEntry,ce as replaceWorkspaceFiles,ie as resolveWorkspaceDownloadTarget,ne as searchWorkspaceFiles,se as searchWorkspacePaths,oe as streamWorkspaceDirectoryZip,re as uploadWorkspaceFiles,Yt as writeWorkspaceFile,ae as zipWorkspaceDirectoryToTemp};
|
|
1
|
+
import{createReadStream as q,createWriteStream as O,promises as s}from"node:fs";import lt from"node:os";import w from"node:path";import{Readable as ht}from"node:stream";import{pipeline as ut}from"node:stream/promises";import{TextDecoder as wt}from"node:util";import{createGunzip as dt}from"node:zlib";import*as ft from"tar";import pt from"unzipper";const{ZipArchive:_}=await import("archiver"),x={maxEntries:1e4,maxFileBytes:512*1024*1024,maxTotalBytes:2*1024*1024*1024,maxPathDepth:64,maxPathLength:4096},mt=new wt("gbk");function u(t){return String(t||"").replace(/\\/g,"/")}function Z(t){const e=w.resolve(String(t||"").trim());if(!e)throw new Error("workspacePath is required");return e}async function yt(t){const e=Z(t),r=await s.realpath(e);if(!(await s.stat(r)).isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);return r}async function v(t){return{requestedRoot:Z(t),workspaceRoot:await yt(t)}}function C(t,e){const r=w.resolve(e),i=w.relative(t,r);if(i.startsWith("..")||w.isAbsolute(i))throw new Error(`Target path is outside workspace: ${r}`);return r}async function D(t){return s.realpath(t)}async function F(t){await s.realpath(w.dirname(t));try{if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${t}`)}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)!=="ENOENT")throw e}}function L(t,e,r){const i=w.resolve(t,r),o=w.relative(t,i);return o.startsWith("..")||w.isAbsolute(o)?i:C(e,w.join(e,o))}async function b({workspacePath:t,targetPath:e=""}){const{requestedRoot:r,workspaceRoot:i}=await v(t),o=String(e||"").trim(),a=o?L(r,i,o):i,c=await D(a);return{workspaceRoot:i,resolvedTargetPath:c}}function $(t){const e=String(t||"").trim();if(!e)throw new Error("entryName is required");if(e==="."||e==="..")throw new Error("entryName is invalid");if(e.includes("/")||e.includes("\\")||w.basename(e)!==e)throw new Error(`entryName must be a plain file or directory name: ${e}`);return e}function G(t){const e=String(t||"");if(!/[\u00c0-\u00ff]/.test(e))return e;const r=Buffer.from(e,"latin1").toString("utf8");return!r||r.includes("\uFFFD")?e:r}function B(t){const e=G(t);return $(w.basename(e.replace(/\\/g,"/")))}function gt(t,e){if(!t)return B(e);const i=G(String(t||e||"")).replace(/\\/g,"/").split("/").filter(Boolean).map(o=>$(o));return i.length===0?B(e):w.join(...i)}function H(t){return(t&4095).toString(8).padStart(4,"0")}function Pt(t){const e=String(t||"").trim();if(!/^[0-7]{3,4}$/.test(e))throw new Error("mode must be a 3 or 4 digit octal string");return Number.parseInt(e,8)}function I(t,e,r,i,o,a,c){const n=t&e?"r":"-",h=t&r?"w":"-",l=(t&i)!==0,d=(t&o)!==0?l?a:c:l?"x":"-";return`${n}${h}${d}`}function kt(t){return[I(t,256,128,64,2048,"s","S"),I(t,32,16,8,1024,"s","S"),I(t,4,2,1,512,"t","T")].join("")}function xt(t){if(!(t.length<24||t.toString("hex",0,8)!=="89504e470d0a1a0a"))return{format:"png",width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}function vt(t){if(!(t.length<10||t.toString("ascii",0,6)!=="GIF87a"&&t.toString("ascii",0,6)!=="GIF89a"))return{format:"gif",width:t.readUInt16LE(6),height:t.readUInt16LE(8)}}function Et(t){if(t.length<4||t[0]!==255||t[1]!==216)return;let e=2;for(;e+9<t.length;){if(t[e]!==255){e+=1;continue}const r=t[e+1],i=t.readUInt16BE(e+2);if(i<2)return;if(r>=192&&r<=207&&![196,200,204].includes(r)&&e+8<t.length)return{format:"jpeg",height:t.readUInt16BE(e+5),width:t.readUInt16BE(e+7)};e+=2+i}}function St(t){if(t.length<30||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WEBP")return;const e=t.toString("ascii",12,16);if(e==="VP8X"&&t.length>=30)return{format:"webp",width:1+t.readUIntLE(24,3),height:1+t.readUIntLE(27,3)};if(e==="VP8 "&&t.length>=30)return{format:"webp",width:t.readUInt16LE(26)&16383,height:t.readUInt16LE(28)&16383};if(e==="VP8L"&&t.length>=25){const r=t.readUInt32LE(21);return{format:"webp",width:(r&16383)+1,height:(r>>14&16383)+1}}}async function K(t,e){if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to change permissions on symbolic link: ${t}`);const i=await s.stat(t);if(!e||!i.isDirectory())return[t];const o=await s.readdir(t),a=await Promise.all(o.map(c=>{const n=w.join(t,c);return K(n,!0)}));return[t,...a.flat()]}async function Rt(t){if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to change permissions on symbolic link: ${t}`);await D(t)}async function Dt(t){const e=await s.open(t,"r");try{const r=Buffer.alloc(512),{bytesRead:i}=await e.read(r,0,r.length,0),o=r.subarray(0,i);return xt(o)||vt(o)||Et(o)||St(o)}finally{await e.close()}}async function T({workspacePath:t,targetPath:e},r={}){const{requestedRoot:i,workspaceRoot:o}=await v(t),a=String(e||"").trim();if(!a)throw new Error("targetPath is required");const c=L(i,o,a),n=await D(c);if(!r.allowWorkspaceRoot&&n===o)throw new Error("Workspace root cannot be modified");return{workspaceRoot:o,resolvedTargetPath:n}}async function X(t){const{requestedRoot:e,workspaceRoot:r}=await v(t.workspacePath),i=String(t.targetPath||"").trim();if(!i)return{workspaceRoot:r,resolvedTargetPath:r};const o=L(e,r,i);return await et(o)?{workspaceRoot:r,resolvedTargetPath:await s.realpath(o)}:(await s.realpath(w.dirname(o)),{workspaceRoot:r,resolvedTargetPath:o})}function V(t){const e=t.toLowerCase();return e.endsWith(".zip")?"zip":e.endsWith(".tar.gz")||e.endsWith(".tgz")?"tgz":e.endsWith(".tar")?"tar":e.endsWith(".gz")?"gz":null}function Y(t){return t.replace(/\.tar\.gz$/i,"").replace(/\.tgz$/i,"").replace(/\.zip$/i,"").replace(/\.tar$/i,"").replace(/\.gz$/i,"")}function Ft(t,e){const r=$(Y(e)||"extracted");return w.join(t,r)}function M(t,e){const r=String(e||"").replace(/\\/g,"/"),i=r.split("/").filter(Boolean);if(!r||r.startsWith("/")||/^[A-Za-z]:/.test(r))throw new Error(`Archive entry path is invalid: ${e}`);if(r.length>x.maxPathLength||i.length>x.maxPathDepth)throw new Error(`Archive entry path is too deep or too long: ${e}`);return C(t,w.join(t,r))}function Tt(t){const e=t.props?.pathBuffer;if(!e||t.props?.flags?.isUnicode)return t.path;const r=mt.decode(e);return!r||r.includes("\uFFFD")?t.path:r}async function J(t){const e=t.autodrain?.();e&&await new Promise((r,i)=>{e.on("close",r),e.on("end",r),e.on("finish",r),e.on("error",i)})}function N(t){if(t.entries+=1,t.entries>x.maxEntries)throw new Error(`Archive contains too many entries. Limit: ${x.maxEntries}`)}function Q(t,e){if(t.totalBytes+=e,e>x.maxFileBytes)throw new Error(`Archive entry exceeds max size. Limit: ${x.maxFileBytes} bytes`);if(t.totalBytes>x.maxTotalBytes)throw new Error(`Archive extraction exceeds total size. Limit: ${x.maxTotalBytes} bytes`)}async function tt(t,e,r){let i=0;t.on("data",o=>{const a=Buffer.isBuffer(o)?o.length:Buffer.byteLength(o);i+=a,(i>x.maxFileBytes||r.totalBytes+i>x.maxTotalBytes)&&t instanceof ht&&t.destroy(new Error("Archive extraction size limit exceeded"))}),await ut(t,O(e)),Q(r,i)}async function et(t){try{return await s.access(t),!0}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)==="ENOENT")return!1;throw e}}async function W({workspacePath:t,filePath:e}){const{requestedRoot:r,workspaceRoot:i}=await v(t),o=String(e||"").trim();if(!o)throw new Error("filePath is required");return{workspaceRoot:i,resolvedFilePath:L(r,i,o)}}async function Gt(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.targetPath||"").trim();if(!r){const{resolvedTargetPath:h}=await b(t);return rt(e,h)}const i=w.resolve(r);let o;try{o=await s.realpath(i)}catch{throw new Error(`Path not found: ${i}`)}if(!(await s.stat(o)).isDirectory())throw new Error(`Path is not a directory: ${i}`);const c=w.relative(e,o),n=c===""||!c.startsWith("..")&&!w.isAbsolute(c);return rt(e,n?o:i)}async function rt(t,e){if(!(await s.stat(e)).isDirectory())throw new Error(`Path is not a directory: ${e}`);const i=await s.readdir(e,{withFileTypes:!0}),o=await Promise.all(i.map(async a=>{const c=w.join(e,a.name),n=a.isFile()?(await s.stat(c)).size:void 0;return{name:a.name,path:u(c),isDirectory:a.isDirectory(),size:n}}));return{currentPath:u(e),workspacePath:u(t),items:o}}async function Ht(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t),i=await D(r),o=await s.stat(i);if(!o.isFile())throw new Error(`Path is not a file: ${i}`);const a=await s.readFile(i,"utf-8");return{workspacePath:u(e),filePath:u(i),content:a,mtimeMs:o.mtimeMs}}const it={maxEntries:1e5,maxDepth:32};async function zt(t){let e=0,r=0;async function i(o,a){if(a>=it.maxDepth)return;let c;try{c=await s.readdir(o,{withFileTypes:!0})}catch{return}for(const n of c){if(r+=1,r>it.maxEntries)return;if(n.isSymbolicLink())continue;const h=w.join(o,n.name);try{if(n.isDirectory())await i(h,a+1);else if(n.isFile()){const l=await s.stat(h);e+=l.size}}catch{}}}return await i(t,0),e}async function Kt(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t,{allowWorkspaceRoot:!0}),[i,o]=await Promise.all([s.stat(r),s.lstat(r)]),a=i.isDirectory(),c=i.isFile()?await Dt(r):void 0,n=a?await zt(r):i.size;return{workspacePath:u(e),targetPath:u(r),name:w.basename(r),isDirectory:i.isDirectory(),isFile:i.isFile(),isSymbolicLink:o.isSymbolicLink(),size:n,mode:i.mode,modeOctal:H(i.mode),permissions:kt(i.mode),uid:i.uid,gid:i.gid,atimeMs:i.atimeMs,mtimeMs:i.mtimeMs,ctimeMs:i.ctimeMs,birthtimeMs:i.birthtimeMs,...c?{image:c}:{}}}async function Xt(t){const e=Pt(t.mode),r=!!t.recursive,{workspaceRoot:i,resolvedTargetPath:o}=await T(t),a=await K(o,r);for(const c of a)await Rt(c),await s.chmod(c,e);return{ok:!0,workspacePath:u(i),targetPath:u(o),mode:e,modeOctal:H(e),recursive:r,changedCount:a.length}}async function Vt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t),i=await D(r),o=await s.stat(i);if(!o.isFile())throw new Error(`Path is not a file: ${i}`);const a=w.extname(i).toLowerCase();if(a===".doc"||a===".xls"||a===".ppt")return{workspacePath:u(e),filePath:u(i),kind:"unsupported",content:"",message:`\u65E7\u7248 ${a} \u683C\u5F0F\u5C06\u7531\u670D\u52A1\u7AEF\u8F6C\u6362\u4E3A\u73B0\u4EE3\u683C\u5F0F\u540E\u6253\u5F00\uFF08\u539F\u6587\u4EF6\u4E0D\u53D8\uFF09\u3002`,size:o.size,mtimeMs:o.mtimeMs};if(!/\.(docx|docm|xlsx|xlsm|pptx|pptm)$/.test(a))throw new Error("Document preview only supports docx/xlsx/pptx files");return{workspacePath:u(e),filePath:u(i),kind:"html",content:"",size:o.size,mtimeMs:o.mtimeMs}}async function Yt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t);await s.mkdir(w.dirname(r),{recursive:!0}),await F(r),await s.writeFile(r,String(t.content??""),"utf-8");const i=await s.stat(r);return{ok:!0,workspacePath:u(e),filePath:u(r),mtimeMs:i.mtimeMs}}async function Jt(t){const{workspaceRoot:e,resolvedTargetPath:r}=await b(t),i=$(t.entryName),o=w.join(r,i);if(!(await s.stat(r)).isDirectory())throw new Error(`Path is not a directory: ${r}`);try{throw await s.access(o),new Error(`Path already exists: ${o}`)}catch(c){if((typeof c=="object"&&c!==null?Reflect.get(c,"code"):void 0)!=="ENOENT")throw c}return t.isDirectory?await s.mkdir(o,{recursive:!1}):(await s.mkdir(w.dirname(o),{recursive:!0}),await F(o),await s.writeFile(o,"","utf-8")),{ok:!0,workspacePath:u(e),targetPath:u(o),isDirectory:t.isDirectory}}async function Qt(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t),i=$(t.newName),o=w.join(w.dirname(r),i);if(o===r)return{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(o)};await s.stat(r);try{throw await s.access(o),new Error(`Path already exists: ${o}`)}catch(a){if((typeof a=="object"&&a!==null?Reflect.get(a,"code"):void 0)!=="ENOENT")throw a}return await s.rename(r,o),{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(o)}}async function te(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t),i=await b({workspacePath:t.workspacePath,targetPath:t.destinationPath});if(!(await s.stat(i.resolvedTargetPath)).isDirectory())throw new Error(`Destination is not a directory: ${i.resolvedTargetPath}`);if((await s.stat(r)).isDirectory()){const n=w.relative(r,i.resolvedTargetPath);if(n===""||!n.startsWith("..")&&!w.isAbsolute(n))throw new Error("Cannot move a directory into itself or its descendant")}const c=w.join(i.resolvedTargetPath,w.basename(r));if(c===r)return{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(c),destinationPath:u(i.resolvedTargetPath)};try{throw await s.access(c),new Error(`Path already exists: ${c}`)}catch(n){if((typeof n=="object"&&n!==null?Reflect.get(n,"code"):void 0)!=="ENOENT")throw n}return await s.rename(r,c),{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(c),destinationPath:u(i.resolvedTargetPath)}}async function ee(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t),i=await s.stat(r),o=w.parse(r).root;if(r===o)throw new Error("Filesystem root cannot be deleted");return i.isDirectory()?await s.rm(r,{recursive:!0,force:!1}):await s.unlink(r),{ok:!0,workspacePath:u(e),targetPath:u(r)}}async function re(t){if(!Array.isArray(t.files)||t.files.length===0)throw new Error("files are required");const{workspaceRoot:e,resolvedTargetPath:r}=await X(t);if(!(await s.stat(r)).isDirectory())throw new Error(`Path is not a directory: ${r}`);const o=[];for(const a of t.files){const c=B(a.originalname),n=gt(a.relativePath,a.originalname),h=w.join(r,n);await s.mkdir(w.dirname(h),{recursive:!0}),await F(h),await s.copyFile(a.path,h);let l;t.extractArchives&&V(h)&&(l=await Wt({workspacePath:e,archivePath:h,outputPath:Ft(r,c)})),o.push({fileName:c,targetPath:u(h),size:a.size,extracted:l})}return{ok:!0,workspacePath:u(e),targetPath:u(r),files:o}}async function ie(t){const{workspaceRoot:e,resolvedTargetPath:r}=await T(t),i=await s.stat(r),o=w.basename(r);return{workspacePath:u(e),targetPath:u(r),resolvedTargetPath:r,fileName:i.isDirectory()?`${o||"workspace"}.zip`:o,contentType:i.isDirectory()?"application/zip":Lt(r),isDirectory:i.isDirectory(),size:i.isDirectory()?void 0:i.size}}function Lt(t){const e=w.extname(t).toLowerCase();return{".svg":"image/svg+xml",".svgz":"image/svg+xml",".ico":"image/x-icon",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".avif":"image/avif",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".xml":"application/xml; charset=utf-8",".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".md":"text/markdown; charset=utf-8",".csv":"text/csv; charset=utf-8",".pdf":"application/pdf",".zip":"application/zip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm"}[e]||"application/octet-stream"}async function oe(t,e){const r=new _({zlib:{level:9}}),i=new Promise((o,a)=>{e.on("close",o),e.on("finish",o),r.on("error",a),e.on("error",a)});r.pipe(e),r.directory(t,!1),await r.finalize(),await i}async function ae(t,e,r,i){const o=w.join(lt.tmpdir(),"agentswork-bridge-downloads");await s.mkdir(o,{recursive:!0});const a=(e||"workspace.zip").replace(/[^\w.-]/g,"_").replace(/\.zip$/i,"")||"workspace",c=w.join(o,`${a}-${Date.now()}-${Math.random().toString(36).slice(2,8)}.zip`),n=new _({zlib:{level:9}}),h=()=>n.pointer(),l=()=>n.abort(),f=O(c),d=new Promise((m,g)=>{f.on("close",m),f.on("finish",m),n.on("error",g),f.on("error",g)});d.catch(()=>{}),n.pipe(f);const y=setInterval(()=>{try{if(i?.()){l();return}r?.(h())}catch{}},200);try{return n.on("progress",()=>{i?.()&&l()}),n.directory(t,!1),i?.()&&l(),await n.finalize(),await d,r?.(h()),c}catch(m){throw await s.rm(c,{force:!0}).catch(()=>{}),m}finally{clearInterval(y)}}async function $t(t,e,r){let i=0,o;const a=q(t),c=a.pipe(pt.Parse({forceStream:!0}));try{for await(const n of c){if(o){await J(n);continue}const h=Tt(n);try{const l=M(e,h);if(N(r),n.type==="Directory"){await s.mkdir(l,{recursive:!0});continue}if(n.type!=="File")throw new Error(`Unsupported archive entry type: ${h}`);await s.mkdir(w.dirname(l),{recursive:!0}),await F(l),await tt(n,l,r),i+=1}catch(l){o=l,await J(n)}}}finally{a.destroy(),c.destroy()}if(o)throw o;return i}async function At(t,e,r,i){let o=0,a;const c=(n,h)=>{if(a)return!1;try{M(e,n),N(i);const l=String(h.type||"").toLowerCase();if(l==="symboliclink"||l==="link")throw new Error(`Archive links are not supported: ${n}`);if(l!=="file"&&l!=="oldfile"&&l!=="contiguousfile"&&l!=="directory")throw new Error(`Unsupported archive entry type: ${n}`);return typeof h.size=="number"&&Q(i,h.size),l!=="directory"&&(o+=1),!0}catch(l){return a=l,!1}};if(await ft.x({file:t,cwd:e,gzip:r,strict:!0,filter:(n,h)=>c(n,h)}),a)throw a;return o}async function Ct(t,e,r){const i=Y(w.basename(t)),o=M(e,i||"decompressed");return N(r),await s.mkdir(w.dirname(o),{recursive:!0}),await F(o),await tt(q(t).pipe(dt()),o,r),1}async function Wt(t){const{requestedRoot:e,workspaceRoot:r}=await v(t.workspacePath),{resolvedTargetPath:i}=await X({workspacePath:t.workspacePath,targetPath:t.outputPath||""}),o=L(e,r,String(t.archivePath||"").trim()),a=await D(o);if(!(await s.stat(a)).isFile())throw new Error(`Archive path is not a file: ${a}`);if(await et(i)||await s.mkdir(i,{recursive:!0}),!(await s.stat(i)).isDirectory())throw new Error(`Output path is not a directory: ${i}`);const h=V(a);if(!h)throw new Error("Unsupported archive type. Supported: .zip, .tar, .tar.gz, .tgz, .gz");let l=0;const f={entries:0,totalBytes:0};return h==="zip"?l=await $t(a,i,f):h==="tar"||h==="tgz"?l=await At(a,i,h==="tgz",f):l=await Ct(a,i,f),{ok:!0,workspacePath:u(r),archivePath:u(a),targetPath:u(i),extractedEntries:l}}function ot(t){const e=t.match(/^(.*?)\{([^}]+)\}(.*)$/);if(!e)return[t];const[,r,i,o]=e;return i.split(",").flatMap(a=>ot(r+a.trim()+o))}function at(t,e){const r=String(e||"").trim();if(!r||r==="*"||r==="*.*")return!0;const i=t.toLowerCase();return ot(r.toLowerCase()).some(a=>{if(a==="*")return!0;const c=a.replace(/\./g,"\\.").replace(/\*\*/g,"<<GLOBSTAR>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<GLOBSTAR>>/g,".*");return new RegExp(`^${c}$`).test(i)})}function j(t){return t===".git"||t==="node_modules"||t===".svn"||t===".hg"}const nt=10*1024*1024,bt=1e3;async function ne(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.keyword||"").trim();if(!r)throw new Error("keyword is required");const i=!!t.ignoreCase,o=String(t.fileMask||"").trim(),a=typeof t.maxResults=="number"&&t.maxResults>0?t.maxResults:bt,c=i?r.toLowerCase():r,h=(t.mode==="filename"?"filename":"content")==="filename",l=[];let f=0,d=!1;async function y(m){if(d)return;let g;try{g=await s.readdir(m,{withFileTypes:!0})}catch{return}for(const p of g){if(d)return;const P=C(e,w.join(m,p.name));if(p.isSymbolicLink())continue;if(p.isDirectory()){if(j(p.name))continue;await y(P);continue}if(!p.isFile()||o&&!at(p.name,o))continue;f+=1;let k;try{k=await s.stat(P)}catch{continue}if(k.size>nt)continue;if(h){const E=(i?p.name.toLowerCase():p.name).indexOf(c);if(E!==-1&&(l.push({filePath:u(P),lineNumber:0,lineContent:p.name,matchStart:E,matchEnd:E+r.length}),l.length>=a)){d=!0;return}continue}let S;try{S=await s.readFile(P,"utf-8")}catch{continue}const z=S.split(/\r?\n/);for(let R=0;R<z.length;R+=1){const E=z[R],ct=i?E.toLowerCase():E;let U=0;for(;;){const A=ct.indexOf(c,U);if(A===-1)break;if(l.push({filePath:u(P),lineNumber:R+1,lineContent:E,matchStart:A,matchEnd:A+r.length}),l.length>=a){d=!0;return}U=A+1}}}}return await y(e),{workspacePath:u(e),keyword:r,totalFiles:f,totalMatches:l.length,matches:l,truncated:d}}const Bt=100,It=120;async function se(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.keyword||"").trim();if(!r)throw new Error("keyword is required");const i=!!t.ignoreCase,o=i?r.toLowerCase():r,a=typeof t.maxResults=="number"&&t.maxResults>0?t.maxResults:Bt,c=typeof t.maxDirectories=="number"&&t.maxDirectories>0?t.maxDirectories:It,n=String(t.rootPath||"").trim(),h=n?w.resolve(/^[A-Za-z]:$/.test(n)?`${n}/`:n):e;let l;try{l=await s.realpath(h)}catch{throw new Error(`Path not found: ${h}`)}if(!(await s.stat(l)).isDirectory())throw new Error(`Path is not a directory: ${h}`);const d=[],y=[l];let m=0,g=!1;for(;y.length>0&&d.length<a&&m<c;){const p=y.shift();m+=1;let P;try{P=await s.readdir(p,{withFileTypes:!0})}catch{continue}for(const k of P){if(d.length>=a){g=!0;break}if(k.isSymbolicLink())continue;const S=w.join(p,k.name);if(k.isDirectory()&&j(k.name))continue;const z=w.relative(l,S).replace(/\\/g,"/");(i?z.toLowerCase():z).includes(o)&&d.push({name:k.name,path:u(S),isDirectory:k.isDirectory()}),k.isDirectory()&&m<c&&y.push(S)}}return(m>=c||d.length>=a)&&(g=!0),d.sort((p,P)=>p.isDirectory===P.isDirectory?p.name.localeCompare(P.name):p.isDirectory?-1:1),{workspacePath:u(e),rootPath:u(l),keyword:r,items:d,truncated:g}}async function st(t,e,r,i){let o;try{o=await s.readFile(t,"utf-8")}catch{return{changed:!1,count:0}}const a=o;let c=0;if(i){const n=e.toLowerCase();let h=0;for(;;){const f=o.toLowerCase().indexOf(n,h);if(f===-1)break;o=o.slice(0,f)+r+o.slice(f+e.length),c+=1;const d=r.length||1;h=f+d}}else{let n=0;for(;;){const h=o.indexOf(e,n);if(h===-1)break;o=o.slice(0,h)+r+o.slice(h+e.length),c+=1;const l=r.length||1;n=h+l}}return o===a?{changed:!1,count:0}:(await F(t),await s.writeFile(t,o,"utf-8"),{changed:!0,count:c})}async function ce(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.keyword||"").trim();if(!r)throw new Error("keyword is required");const i=String(t.replacement??""),o=!!t.ignoreCase,a=String(t.fileMask||"").trim(),c=String(t.filePath||"").trim();let n=0,h=0;if(c){const{resolvedFilePath:f}=await W({workspacePath:t.workspacePath,filePath:c}),d=await st(f,r,i,o);return d.changed&&(n=1,h=d.count),{workspacePath:u(e),keyword:r,replacement:i,changedFiles:n,changedMatches:h}}async function l(f){let d;try{d=await s.readdir(f,{withFileTypes:!0})}catch{return}for(const y of d){const m=C(e,w.join(f,y.name));if(y.isSymbolicLink())continue;if(y.isDirectory()){if(j(y.name))continue;await l(m);continue}if(!y.isFile()||a&&!at(y.name,a))continue;try{if((await s.stat(m)).size>nt)continue}catch{continue}const g=await st(m,r,i,o);g.changed&&(n+=1,h+=g.count)}}return await l(e),{workspacePath:u(e),keyword:r,replacement:i,changedFiles:n,changedMatches:h}}export{Xt as chmodWorkspaceEntry,Jt as createWorkspaceEntry,ee as deleteWorkspaceEntry,Wt as extractWorkspaceArchive,Kt as getWorkspaceEntryProperties,Gt as listWorkspaceDirectory,te as moveWorkspaceEntry,Vt as previewWorkspaceDocument,Ht as readWorkspaceFile,Qt as renameWorkspaceEntry,ce as replaceWorkspaceFiles,ie as resolveWorkspaceDownloadTarget,ne as searchWorkspaceFiles,se as searchWorkspacePaths,oe as streamWorkspaceDirectoryZip,re as uploadWorkspaceFiles,Yt as writeWorkspaceFile,ae as zipWorkspaceDirectoryToTemp};
|
|
2
2
|
|
package/dist/types.d.ts
CHANGED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
|
|
2
|
+
export declare const BLOCKED_ENV_KEYS: ReadonlySet<string>;
|
|
3
|
+
|
|
4
|
+
export declare const ENV_KEY_PATTERN: RegExp;
|
|
5
|
+
|
|
6
|
+
export declare const SPAWN_ENV_KEY_PATTERN: RegExp;
|
|
7
|
+
|
|
8
|
+
export interface RejectedEnvKey {
|
|
9
|
+
key: string;
|
|
10
|
+
reason: "blocked" | "invalid-name" | "empty-value";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export declare function sanitizeEnvForChild(env: unknown, options?: {
|
|
14
|
+
onReject?: (item: RejectedEnvKey) => void;
|
|
15
|
+
}): Record<string, string>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{logger as O}from"./logger.js";const P=O.child("env-safety"),A=new Set(["NODE_OPTIONS","NODE_PATH","NODE_EXTRA_CA_CERTS","NODE_REPL_HISTORY","LD_PRELOAD","LD_LIBRARY_PATH","LD_AUDIT","DYLD_INSERT_LIBRARIES","DYLD_LIBRARY_PATH","DYLD_FRAMEWORK_PATH","PYTHONPATH","PYTHONSTARTUP","PYTHONHOME","PERL5LIB","PERL5OPT","RUBYOPT","RUBYLIB","BASH_ENV","ENV","SHELLOPTS","BASHOPTS","IFS","PS1","PS4","GIT_SSH","GIT_SSH_COMMAND","GIT_CONFIG","GIT_CONFIG_GLOBAL","PATH","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","TEMP","TMP","LANG","TZ"]),a=/^[A-Za-z_][A-Za-z0-9_]*$/,S=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function L(o,r){const _={};if(!o||typeof o!="object")return _;const t=r?.onReject??(n=>{P.warn(`env key rejected (${n.reason}): ${n.key}`)});for(const[n,T]of Object.entries(o)){const e=n.trim();if(T==null){e&&t({key:e,reason:"empty-value"});continue}const E=String(T).trim();if(!E){t({key:e,reason:"empty-value"});continue}if(!S.test(e)){t({key:e,reason:"invalid-name"});continue}if(A.has(e.toUpperCase())){t({key:e,reason:"blocked"});continue}_[e]=E}return _}export{A as BLOCKED_ENV_KEYS,a as ENV_KEY_PATTERN,S as SPAWN_ENV_KEY_PATTERN,L as sanitizeEnvForChild};
|
|
2
|
+
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{appendFile as f,mkdir as u}from"node:fs/promises";import c from"node:path";import{getBridgeDataHome as a}from"../config.js";const g=process.env.ACODE_LIFECYCLE_LOG!=="0";let l=null,t=null,r=!1;function d(){const e=new Date().toISOString().slice(0,10);return c.join(a(),"log",`lifecycle-${e}.jsonl`)}function m(e){return l===e&&t||(l=e,t=u(e,{recursive:!0}).then(()=>{}).catch(n=>{r||(r=!0,console.warn(`[lifecycle-log] \u65E0\u6CD5\u521B\u5EFA\u8BCA\u65AD\u65E5\u5FD7\u76EE\u5F55\uFF0C\u540E\u7EED\u8BCA\u65AD\u8BB0\u5F55\u5C06\u88AB\u4E22\u5F03: ${n instanceof Error?n.message:String(n)}`))})),t}function D(e,n){if(!g)return;const s={ts:new Date().toISOString(),event:e,...n},o=d();m(c.dirname(o)).then(()=>{f(o,`${JSON.stringify(s)}
|
|
2
|
+
`,"utf8").catch(i=>{r||(r=!0,console.warn(`[lifecycle-log] \u8BCA\u65AD\u65E5\u5FD7\u5199\u5165\u5931\u8D25\uFF0C\u540E\u7EED\u8BB0\u5F55\u5C06\u88AB\u4E22\u5F03: ${i instanceof Error?i.message:String(i)}`))})})}export{D as recordLifecycleEvent};
|
|
3
|
+
|
package/dist/utils/mcp-utils.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{randomUUID as
|
|
1
|
+
import{randomUUID as i}from"node:crypto";import{parseBoolean as o}from"./validation.js";function d(r){if(!r||typeof r!="object")return null;const n=r,t=String(n.name||"").trim();return t?{id:String(n.id||i()),name:t,transport:String(n.transport||"stdio").trim().toLowerCase(),command:n.command===null||n.command===void 0?"":String(n.command),url:n.url===null||n.url===void 0?"":String(n.url),args:Array.isArray(n.args)?n.args.map(e=>String(e)):[],env:n.env&&typeof n.env=="object"?n.env:{},enabled:o(n.enabled,!0),collapsed:n.collapsed===!0,description:String(n.description||"").trim()||void 0,installedAt:n.installedAt||new Date().toISOString()}:null}export{d as normalizeMcpPayload};
|
|
2
2
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{spawn as E}from"node:child_process";import{promises as S}from"node:fs";import{createInterface as
|
|
2
|
-
`),this.finalizeTask(u,-1,null,"spawn_error")}),this.persistTaskSafe(u),{taskId:n,completion:l}}async spawnAndAttach(t,i){const e=
|
|
3
|
-
`),t.finalized||this.finalizeTask(t,-1,null,"child_error")}),s.on("exit",(o,a)=>{if(t.finalized)return;const u=()=>{if(t.finalized||!t.child)return;const l=A(t.stdoutDecoder,void 0,!0),c=A(t.stderrDecoder,void 0,!0);l&&this.onOutput(t,"stdout",l),c&&this.onOutput(t,"stderr",c),t.ringBuffer.flush();const p=t.killedReason??null;this.finalizeTask(t,o,a,p??void 0)};t.exitGraceTimer=setTimeout(u,
|
|
1
|
+
import{spawn as E,spawnSync as R}from"node:child_process";import{promises as S}from"node:fs";import{createInterface as O}from"node:readline";import{randomBytes as M}from"node:crypto";import{prepareShellCommand as D,shellExecutable as G}from"./builtins/shellCommandPreparation.js";import{createShellOutputDecoder as b,decodeShellOutputChunk as A}from"./builtins/shellOutputDecoder.js";import{BackgroundOutputRingBuffer as z}from"./background-output-ringbuffer.js";import{BackgroundCommandStore as F}from"./background-command-store.js";const N=1e3,W=3*60*1e3,$=24*60*60*1e3,k=5*1e3,X=64*1024,q=2e3,C=50*1024*1024,_=16,P=256,K=256*1024,U=100,Y=5e3,H=256,v=20,B=5*60*1e3,L=1024*1024,x=`pid-${process.pid}-${Date.now().toString(36)}`;class V{constructor(){this.tasksByAgent=new Map,this.store=new F}globalCount(){let t=0;for(const i of this.tasksByAgent.values())t+=i.size;return t}startCommand(t){const i=t.agentId,e=this.getOrCreateBucket(i);if(e.size>=_)throw new I("too_many_tasks",`Agent ${i} has ${e.size} background tasks (limit ${_}). Kill or wait for completion first.`);if(this.globalCount()>=P)throw new I("global_limit_reached",`Global background task limit ${P} reached.`);const n=this.generateTaskId(e),r=t.timeoutMs===void 0?W:t.timeoutMs>0?Math.min(t.timeoutMs,$):0,s=typeof t.inactivityTimeoutMs=="number"&&Number.isFinite(t.inactivityTimeoutMs)&&t.inactivityTimeoutMs>0?t.inactivityTimeoutMs:0,o=this.store.outputPathFor(i,n),a=t.commandText.length>80?`${t.commandText.slice(0,77)}...`:t.commandText,u={taskId:n,agentId:i,command:t.commandText,commandPreview:a,description:t.description,cwd:t.cwd,status:"running",startedAt:Date.now(),finishedAt:null,exitCode:null,signal:null,killedReason:null,timeoutMs:r,inactivityTimeoutMs:s,child:null,ringBuffer:new z,outputPath:o,outputWriteChain:Promise.resolve(),outputTruncated:!1,outputLineCount:0,outputBytes:0,notified:!1,completionWaiters:[],onCompleted:t.onCompleted,onOutput:t.onOutput,outputSeq:0,outputSubscribers:new Set,timeoutTimer:null,killEscalationTimer:null,retentionTimer:null,inactivityTimer:null,exitGraceTimer:null,inactivityTimedOut:!1,finalized:!1,stdoutDecoder:b(),stderrDecoder:b(),stdoutText:"",stderrText:"",commandLineCount:0,bootId:x,lastPulseAt:Date.now(),lastPulseBytes:0,backgrounded:!1},l=new Promise(c=>{u.completionResolve=c});return e.set(n,u),r>0&&(u.timeoutTimer=setTimeout(()=>{u.finalized||(u.killedReason="timeout",u.child?this.killProcessGroup(u.child):this.finalizeTask(u,null,null,"timeout"))},r),u.timeoutTimer.unref?.()),this.spawnAndAttach(u,t).catch(c=>{u.ringBuffer.push(`[ACode] spawn failed: ${c?.message??String(c)}
|
|
2
|
+
`),this.finalizeTask(u,-1,null,"spawn_error")}),this.persistTaskSafe(u),{taskId:n,completion:l}}async spawnAndAttach(t,i){const e=G(),n=await D(i.commandText,i.workspaceRoot,e),r=process.platform==="win32",s=E(e.command,[...e.argsPrefix,n.commandText],{cwd:i.cwd,env:process.env,detached:!r,stdio:["ignore","pipe","pipe"],windowsVerbatimArguments:r,windowsHide:!0});t.child=s,t.commandFilePath=n.commandFilePath,t.commandLineCount=n.commandLineCount,t.inactivityTimeoutMs>0&&this.scheduleInactivity(t),s.stdout?.on("data",o=>{const a=A(t.stdoutDecoder,o);this.onOutput(t,"stdout",a)}),s.stderr?.on("data",o=>{const a=A(t.stderrDecoder,o);this.onOutput(t,"stderr",a)}),s.on("error",o=>{this.onOutput(t,"stderr",`[ACode] child error: ${o.message}
|
|
3
|
+
`),t.finalized||this.finalizeTask(t,-1,null,"child_error")}),s.on("exit",(o,a)=>{if(t.finalized)return;const u=()=>{if(t.finalized||!t.child)return;const l=A(t.stdoutDecoder,void 0,!0),c=A(t.stderrDecoder,void 0,!0);l&&this.onOutput(t,"stdout",l),c&&this.onOutput(t,"stderr",c),t.ringBuffer.flush();const p=t.killedReason??null;this.finalizeTask(t,o,a,p??void 0)};t.exitGraceTimer=setTimeout(u,q),t.exitGraceTimer.unref?.()}),s.on("close",(o,a)=>{t.exitGraceTimer&&(clearTimeout(t.exitGraceTimer),t.exitGraceTimer=null);const u=A(t.stdoutDecoder,void 0,!0),l=A(t.stderrDecoder,void 0,!0);if(u&&this.onOutput(t,"stdout",u),l&&this.onOutput(t,"stderr",l),t.ringBuffer.flush(),!t.finalized){const c=t.killedReason??null;this.finalizeTask(t,o,a,c??void 0)}})}disableInactivityTimeout(t,i){const e=this.getTask(t,i);return e?(e.inactivityTimeoutMs=0,e.inactivityTimer&&(clearTimeout(e.inactivityTimer),e.inactivityTimer=null),!0):!1}async markBackgrounded(t,i){const e=this.getTask(t,i);return e?(e.backgrounded=!0,await this.persistTask(e),!0):!1}onOutput(t,i,e){if(!e)return;t.outputSeq++;const n=t.outputSeq;if(t.outputSubscribers.size>0)for(const o of t.outputSubscribers)try{o.onLine({stream:i,text:e,seq:n})}catch{}const r=i==="stdout"?"stdoutText":"stderrText";if(Buffer.byteLength(t[r],"utf-8")<L){const o=L-Buffer.byteLength(t[r],"utf-8");t[r]+=o>0?e.slice(0,o):""}if(t.inactivityTimeoutMs>0&&this.scheduleInactivity(t),t.status==="running"){const o=Date.now(),a=t.outputBytes-t.lastPulseBytes;(o-t.lastPulseAt>=k||a>=X)&&(t.lastPulseAt=o,t.lastPulseBytes=t.outputBytes,this.persistTaskSafe(t))}if(t.outputBytes>=C){if(!t.outputTruncated){t.outputTruncated=!0;const o=`
|
|
4
4
|
[ACode] output truncated at 50MB
|
|
5
5
|
`;t.ringBuffer.push(o),this.appendToFile(t,o)}t.ringBuffer.push(e);return}t.ringBuffer.push(e),t.onOutput?.({stream:i,text:e});const s=(e.match(/\n/g)??[]).length;t.outputLineCount+=s,t.outputBytes+=Buffer.byteLength(e,"utf-8"),this.appendToFile(t,e)}scheduleInactivity(t){t.finalized||t.inactivityTimeoutMs<=0||(t.inactivityTimer&&clearTimeout(t.inactivityTimer),t.inactivityTimer=setTimeout(()=>{t.finalized||!t.child||(t.inactivityTimedOut=!0,t.killedReason="inactivity",this.killProcessGroup(t.child))},t.inactivityTimeoutMs),t.inactivityTimer.unref?.())}appendToFile(t,i){return t.outputBytes>C?Promise.resolve():(t.outputWriteChain=t.outputWriteChain.then(()=>S.appendFile(t.outputPath,i,"utf-8")).catch(e=>{t.ringBuffer.push(`[ACode] output write failed: ${e?.message??e}
|
|
6
|
-
`)}),t.outputWriteChain)}finalizeTask(t,i,e,n){if(t.finalized)return;t.finalized=!0,t.timeoutTimer&&(clearTimeout(t.timeoutTimer),t.timeoutTimer=null),t.killEscalationTimer&&(clearTimeout(t.killEscalationTimer),t.killEscalationTimer=null),t.inactivityTimer&&(clearTimeout(t.inactivityTimer),t.inactivityTimer=null),t.exitGraceTimer&&(clearTimeout(t.exitGraceTimer),t.exitGraceTimer=null),t.child=null,t.finishedAt=Date.now();let r;n?(r="killed",t.killedReason=n):i===0?r="completed":r="failed",t.status=r,t.exitCode=i,t.signal=e;const s=n==="inactivity"||t.inactivityTimedOut,o={taskId:t.taskId,exitCode:i,signal:e,timedOut:n==="timeout"||s,inactivityTimedOut:s,outputFilePath:t.outputPath,outputLineCount:t.outputLineCount,outputSpilled:t.outputTruncated,commandFilePath:t.commandFilePath,commandLineCount:t.commandLineCount,timeoutMs:t.timeoutMs,inactivityTimeoutMs:t.inactivityTimeoutMs,stdout:t.stdoutText,stderr:t.stderrText,durationMs:t.finishedAt-t.startedAt};t.completionResolve?.(o);const a={taskId:t.taskId,status:r,exitCode:i,signal:e,timedOut:n==="timeout"||s,aborted:!1,durationMs:t.finishedAt-t.startedAt},u=t.completionWaiters;t.completionWaiters=[];for(const l of u)l(a);if(this.persistTaskSafe(t),t.onCompleted?.({taskId:t.taskId,agentId:t.agentId,status:r,exitCode:i,signal:e,commandPreview:t.commandPreview,outputLineCount:t.outputLineCount,outputBytes:t.outputBytes,outputPath:t.outputPath,finishedAt:t.finishedAt,killedReason:t.killedReason}),t.outputSubscribers.size>0){const l=Array.from(t.outputSubscribers);t.outputSubscribers.clear();for(const c of l)try{c.onDone({status:r,exitCode:i,signal:e})}catch{}}t.retentionTimer=setTimeout(()=>{this.evictTask(t.agentId,t.taskId)},B),t.retentionTimer.unref?.()}evictTask(t,i){const e=this.tasksByAgent.get(t);if(!e)return;const n=e.get(i);n&&(S.unlink(n.outputPath).catch(()=>{}),e.delete(i),e.size===0&&this.tasksByAgent.delete(t))}listTasks(t,i){const e=this.tasksByAgent.get(t);if(!e)return[];const n=[];for(const r of e.values())i&&i!=="all"&&r.status!==i||n.push(this.toSummary(r));return n.sort((r,s)=>s.startedAt-r.startedAt)}toSummary(t){return{taskId:t.taskId,status:t.status,command:t.command,commandPreview:t.commandPreview,description:t.description,cwd:t.cwd,startedAt:t.startedAt,finishedAt:t.finishedAt,exitCode:t.exitCode,signal:t.signal,outputLineCount:t.outputLineCount,outputBytes:t.outputBytes}}getTaskOutputSnapshot(t,i,e=500){const n=this.getTask(t,i);if(!n)return null;const r=n.ringBuffer.tail(e);return{taskId:n.taskId,status:n.status,exitCode:n.exitCode,signal:n.signal,startedAt:n.startedAt,finishedAt:n.finishedAt,command:n.command,lines:r,nextSeq:n.outputSeq+1,totalLines:n.outputLineCount,totalBytes:n.outputBytes,truncated:n.outputTruncated}}subscribeTaskOutput(t,i,e){const n=this.getTask(t,i);if(!n)return null;n.outputSubscribers.add(e);let r=!0;return()=>{r&&(r=!1,n.outputSubscribers.delete(e))}}async readOutput(t,i){const e=String(i.task_id??""),n=this.getTask(t,e),r=i.mode==="lines"||i.mode==="grep"?i.mode:"tail",s=Math.min(Math.max(1,i.line_size??100),K),o=Number.isFinite(i.start_line)&&(i.start_line??0)>0?Math.floor(i.start_line??0):0;if(!n)return{taskId:e,status:"killed",mode:r,lines:[],lineCount:0,metadata:{totalLines:0,totalBytes:0,returnedBytes:0,truncated:!1,outputTruncated:!1,hasMore:!1,nextStartLine:null,outputFile:""}};let a=[],u=!1,l=null;if(r==="tail"){const m=n.ringBuffer.tail(s),f=Math.max(0,n.outputLineCount-m.length);a=m.map((d,y)=>({line:f+y,text:d})),l=null}else if(r==="lines"){const m=n.ringBuffer.firstLineIndex(),f=m+n.ringBuffer.getLineCount();if(o>=m&&o<f)a=n.ringBuffer.offset(o,s).map((y,T)=>({line:o+T,text:y})),u=o+a.length<f,l=u?o+a.length:null;else if(o<f){const d=await this.readFromFile(n,"lines",o,s,0,0,void 0);a=d.rows,u=d.hasMore,l=d.nextStartLine}}else{const m=String(i.pattern??"");if(!m||m.length>Y)return this._emptyResult(e,n,r);let f;try{f=new RegExp(m,"i")}catch{return this._emptyResult(e,n,r)}const d=Math.min(Math.max(0,i.context_before??0),v),y=Math.min(Math.max(0,i.context_after??0),v),T=await this.readFromFile(n,"grep",o,s,d,y,f);a=T.rows,u=T.hasMore,l=T.nextStartLine}const c=[];let p=0,g=!1;for(const m of a){const f=Buffer.byteLength(m.text,"utf-8")+1;if(c.length>=s||p+f>q){g=!0,u=!0;break}c.push(m),p+=f}const w=i.include_metadata!==!1;return{taskId:e,status:n.status,mode:r,lines:c,lineCount:c.length,metadata:w?{totalLines:n.outputLineCount,totalBytes:n.outputBytes,returnedBytes:p,truncated:g,outputTruncated:n.outputTruncated,hasMore:u,nextStartLine:u?l:null,outputFile:n.outputPath}:void 0}}_emptyResult(t,i,e){return{taskId:t,status:i.status,mode:e,lines:[],lineCount:0,metadata:{totalLines:i.outputLineCount,totalBytes:i.outputBytes,returnedBytes:0,truncated:!1,outputTruncated:i.outputTruncated,hasMore:!1,nextStartLine:null,outputFile:i.outputPath}}}async readFromFile(t,i,e,n,r,s,o){const a=[],u=new Set;let l=0,c=!1;const p=[];let g=-1/0;try{const w=await S.open(t.outputPath,"r"),m=R({input:w.createReadStream({encoding:"utf-8"}),crlfDelay:1/0});for await(const f of m){const d=l;if(l++,i==="grep"&&d-e>=U&&d>=e){c=!0;break}if(d>=e){if(i==="lines"){if(a.length>=n){c=!0;break}u.has(d)||(u.add(d),a.push({line:d,text:f}))}else if(o.test(f)){for(const T of p)T.line>=e&&!u.has(T.line)&&(u.add(T.line),a.push(T));if(u.has(d)||(u.add(d),a.push({line:d,text:f})),g=d,a.length>=n){c=!0;break}}else if(r>0&&(p.push({line:d,text:f}),p.length>r&&p.shift()),g>=e&&d-g<=s&&!u.has(d)&&(u.add(d),a.push({line:d,text:f}),a.length>=n)){c=!0;break}}}m.close(),await w.close()}catch{return{rows:[],hasMore:!1,nextStartLine:null}}return c?{rows:a,hasMore:c,nextStartLine:l}:{rows:a,hasMore:c,nextStartLine:null}}async awaitCompletion(t,i,e){return Promise.all(i.map(n=>this.awaitOne(t,n,e)))}async awaitOne(t,i,e){const n=this.getTask(t,i);if(n)return n.status!=="running"?this.taskToAwaitResult(n):new Promise(o=>{let a=null;const u=l=>{a&&clearTimeout(a),o(l)};n.completionWaiters.push(u),e&&e>0&&(a=setTimeout(()=>{n.completionWaiters=n.completionWaiters.filter(l=>l!==u),o({taskId:i,status:"running",exitCode:null,signal:null,timedOut:!0,aborted:!1,durationMs:Date.now()-n.startedAt})},e),a.unref?.())});const s=(await this.store.readSession(t))?.tasks.find(o=>o.taskId===i);return s?s.status!=="running"?{taskId:i,status:s.status,exitCode:s.exitCode,signal:s.signal,timedOut:s.killedReason==="timeout",aborted:!1,durationMs:(s.finishedAt??Date.now())-s.startedAt,...s.outputPath?{outputFilePath:s.outputPath}:{}}:{taskId:i,status:"killed",exitCode:null,signal:null,timedOut:!1,aborted:!1,durationMs:(s.finishedAt??Date.now())-s.startedAt}:null}taskToAwaitResult(t){return{taskId:t.taskId,status:t.status,exitCode:t.exitCode,signal:t.signal,timedOut:t.killedReason==="timeout",aborted:!1,durationMs:(t.finishedAt??Date.now())-t.startedAt,...t.status!=="running"&&t.outputPath?{outputFilePath:t.outputPath}:{}}}interruptAwaits(t,i){const e=this.tasksByAgent.get(t);if(e)for(const n of i){const r=e.get(n);if(!r)continue;const s=r.completionWaiters;if(s.length===0)continue;r.completionWaiters=[];const o={taskId:n,status:"running",exitCode:null,signal:null,timedOut:!1,aborted:!0,durationMs:Date.now()-r.startedAt};for(const a of s)a(o)}}async killTask(t,i){const e=this.getTask(t,i);return e?e.status!=="running"?{taskId:i,status:e.status,exitCode:e.exitCode??void 0}:e.child?(e.killedReason="user_kill",this.killProcessGroup(e.child)?(e.killEscalationTimer&&clearTimeout(e.killEscalationTimer),e.killEscalationTimer=setTimeout(()=>{e.child&&!e.finalized&&this.killProcessGroup(e.child,!0)},F),e.killEscalationTimer.unref?.(),{taskId:i,status:"killed",signal:"SIGTERM"}):{taskId:i,status:e.status,error:"kill_failed",reason:"permission_denied"}):{taskId:i,status:e.status,error:"kill_failed",reason:"no_child"}:{taskId:i,status:"killed",error:"task_not_found"}}killProcessGroup(t,i=!1){const e=t.pid;if(!e)return!1;try{if(process.platform==="win32"){const n="/F",{spawnSync:r}=require("node:child_process");return r("taskkill",["/PID",String(e),"/T",n],{windowsHide:!0}),!0}try{process.kill(-e,i?"SIGKILL":"SIGTERM")}catch{process.kill(e,i?"SIGKILL":"SIGTERM")}return!0}catch{return!1}}async disposeAgent(t){const i=this.tasksByAgent.get(t);if(i){for(const e of i.values())e.status==="running"&&e.child&&(e.killedReason="session_disposed",this.killProcessGroup(e.child,!0)),e.timeoutTimer&&clearTimeout(e.timeoutTimer),e.killEscalationTimer&&clearTimeout(e.killEscalationTimer),e.retentionTimer&&clearTimeout(e.retentionTimer),e.exitGraceTimer&&clearTimeout(e.exitGraceTimer);this.tasksByAgent.delete(t)}await this.store.deleteAgent(t)}async disposeAll(){for(const[t,i]of this.tasksByAgent){for(const e of i.values())e.status==="running"&&(e.killedReason="process_exit",e.child&&this.killProcessGroup(e.child,!0),e.finalized||this.finalizeTask(e,null,null,"process_exit")),e.timeoutTimer&&clearTimeout(e.timeoutTimer),e.killEscalationTimer&&clearTimeout(e.killEscalationTimer),e.retentionTimer&&clearTimeout(e.retentionTimer),e.exitGraceTimer&&clearTimeout(e.exitGraceTimer);await this.store.updateSession(t,()=>null),this.tasksByAgent.delete(t)}}async reconcileDiskRunning(t){const i=this.tasksByAgent.get(t);let e=0;return await this.store.updateSession(t,n=>{let r=!1;for(const s of n.tasks){if(s.status!=="running")continue;const o=i?.get(s.taskId)?.status==="running",a=s.ownerBootId===x;if(o){a||(s.ownerBootId=x,r=!0);continue}s.status="killed",s.killedReason="runtime_crashed",s.finishedAt=Date.now(),s.notified=!0,e++,r=!0}return r?n.tasks:null}),e}async listTasksWithReconcile(t,i){try{await this.reconcileDiskRunning(t)}catch{}const e=this.tasksByAgent.get(t),n=e?[...e.values()]:[],r=n.filter(o=>o.backgrounded).map(o=>this.toSummary(o)),s=new Set(n.map(o=>o.taskId));try{const o=await this.store.readSession(t);if(o){const a=Date.now();for(const u of o.tasks)s.has(u.taskId)||u.backgrounded===!0&&u.status!=="running"&&(u.finishedAt&&a-u.finishedAt>=B||i&&i!=="all"&&u.status!==i||r.push(V(u)))}}catch{}return i&&i!=="all"?r.filter(o=>o.status===i).sort((o,a)=>a.startedAt-o.startedAt):r.sort((o,a)=>a.startedAt-o.startedAt)}async reconcileAllAgents(){const t=await this.store.listAgents();let i=0;for(const e of t)try{i+=await this.reconcileDiskRunning(e)}catch{}return i}async reconcileOrphans(t){await this.reconcileDiskRunning(t)}async readSessionState(t){return this.store.readSession(t)}async markNotified(t,i){await this.store.markNotified(t,i)}getOrCreateBucket(t){let i=this.tasksByAgent.get(t);return i||(i=new Map,this.tasksByAgent.set(t,i)),i}getTask(t,i){const e=this.tasksByAgent.get(t);if(e&&/^[A-Za-z0-9]{8}$/.test(i))return e.get(i)}generateTaskId(t){for(let i=0;i<3;i++){const e=M(4).toString("hex").slice(0,8);if(!t.has(e))return e}return M(6).toString("hex").slice(0,8)}async persistTask(t){await this.store.updateSession(t.agentId,i=>{const e={taskId:t.taskId,agentId:t.agentId,command:t.command,commandPreview:t.commandPreview,description:t.description,cwd:t.cwd,status:t.status,startedAt:t.startedAt,finishedAt:t.finishedAt,exitCode:t.exitCode,signal:t.signal,outputPath:t.outputPath,outputLineCount:t.outputLineCount,outputBytes:t.outputBytes,notified:t.notified,killedReason:t.killedReason,ownerBootId:t.bootId,lastPulseAt:t.status==="running"?t.lastPulseAt:void 0,backgrounded:t.backgrounded},n=i.tasks.findIndex(s=>s.taskId===t.taskId);n>=0?i.tasks[n]=e:i.tasks.push(e);const r=Date.now();return i.tasks.filter(s=>s.status==="running"||!s.finishedAt||r-s.finishedAt<B)})}persistTaskSafe(t){this.persistTask(t).catch(i=>{console.error(`[BackgroundCommandManager] persist ${t.agentId}/${t.taskId} failed:`,i)})}}class I extends Error{constructor(t,i){super(i),this.name="BackgroundTaskError",this.code=t}}function V(h){return{taskId:h.taskId,status:h.status,command:h.command,commandPreview:h.commandPreview,description:h.description,cwd:h.cwd,startedAt:h.startedAt,finishedAt:h.finishedAt,exitCode:h.exitCode,signal:h.signal,outputLineCount:h.outputLineCount,outputBytes:h.outputBytes}}const ot=new H;export{H as BackgroundCommandManager,I as BackgroundTaskError,ot as backgroundCommandManager};
|
|
6
|
+
`)}),t.outputWriteChain)}finalizeTask(t,i,e,n){if(t.finalized)return;t.finalized=!0,t.timeoutTimer&&(clearTimeout(t.timeoutTimer),t.timeoutTimer=null),t.killEscalationTimer&&(clearTimeout(t.killEscalationTimer),t.killEscalationTimer=null),t.inactivityTimer&&(clearTimeout(t.inactivityTimer),t.inactivityTimer=null),t.exitGraceTimer&&(clearTimeout(t.exitGraceTimer),t.exitGraceTimer=null),t.child=null,t.finishedAt=Date.now();let r;n?(r="killed",t.killedReason=n):i===0?r="completed":r="failed",t.status=r,t.exitCode=i,t.signal=e;const s=n==="inactivity"||t.inactivityTimedOut,o={taskId:t.taskId,exitCode:i,signal:e,timedOut:n==="timeout"||s,inactivityTimedOut:s,outputFilePath:t.outputPath,outputLineCount:t.outputLineCount,outputSpilled:t.outputTruncated,commandFilePath:t.commandFilePath,commandLineCount:t.commandLineCount,timeoutMs:t.timeoutMs,inactivityTimeoutMs:t.inactivityTimeoutMs,stdout:t.stdoutText,stderr:t.stderrText,durationMs:t.finishedAt-t.startedAt};t.completionResolve?.(o);const a={taskId:t.taskId,status:r,exitCode:i,signal:e,timedOut:n==="timeout"||s,aborted:!1,durationMs:t.finishedAt-t.startedAt},u=t.completionWaiters;t.completionWaiters=[];for(const l of u)l(a);if(this.persistTaskSafe(t),t.onCompleted?.({taskId:t.taskId,agentId:t.agentId,status:r,exitCode:i,signal:e,commandPreview:t.commandPreview,outputLineCount:t.outputLineCount,outputBytes:t.outputBytes,outputPath:t.outputPath,finishedAt:t.finishedAt,killedReason:t.killedReason}),t.outputSubscribers.size>0){const l=Array.from(t.outputSubscribers);t.outputSubscribers.clear();for(const c of l)try{c.onDone({status:r,exitCode:i,signal:e})}catch{}}t.retentionTimer=setTimeout(()=>{this.evictTask(t.agentId,t.taskId)},B),t.retentionTimer.unref?.()}evictTask(t,i){const e=this.tasksByAgent.get(t);if(!e)return;const n=e.get(i);n&&(S.unlink(n.outputPath).catch(()=>{}),e.delete(i),e.size===0&&this.tasksByAgent.delete(t))}listTasks(t,i){const e=this.tasksByAgent.get(t);if(!e)return[];const n=[];for(const r of e.values())i&&i!=="all"&&r.status!==i||n.push(this.toSummary(r));return n.sort((r,s)=>s.startedAt-r.startedAt)}toSummary(t){return{taskId:t.taskId,status:t.status,command:t.command,commandPreview:t.commandPreview,description:t.description,cwd:t.cwd,startedAt:t.startedAt,finishedAt:t.finishedAt,exitCode:t.exitCode,signal:t.signal,outputLineCount:t.outputLineCount,outputBytes:t.outputBytes}}getTaskOutputSnapshot(t,i,e=500){const n=this.getTask(t,i);if(!n)return null;const r=n.ringBuffer.tail(e);return{taskId:n.taskId,status:n.status,exitCode:n.exitCode,signal:n.signal,startedAt:n.startedAt,finishedAt:n.finishedAt,command:n.command,lines:r,nextSeq:n.outputSeq+1,totalLines:n.outputLineCount,totalBytes:n.outputBytes,truncated:n.outputTruncated}}subscribeTaskOutput(t,i,e){const n=this.getTask(t,i);if(!n)return null;n.outputSubscribers.add(e);let r=!0;return()=>{r&&(r=!1,n.outputSubscribers.delete(e))}}async readOutput(t,i){const e=String(i.task_id??""),n=this.getTask(t,e),r=i.mode==="lines"||i.mode==="grep"?i.mode:"tail",s=Math.min(Math.max(1,i.line_size??100),U),o=Number.isFinite(i.start_line)&&(i.start_line??0)>0?Math.floor(i.start_line??0):0;if(!n)return{taskId:e,status:"killed",mode:r,lines:[],lineCount:0,metadata:{totalLines:0,totalBytes:0,returnedBytes:0,truncated:!1,outputTruncated:!1,hasMore:!1,nextStartLine:null,outputFile:""}};let a=[],u=!1,l=null;if(r==="tail"){const m=n.ringBuffer.tail(s),f=Math.max(0,n.outputLineCount-m.length);a=m.map((d,y)=>({line:f+y,text:d})),l=null}else if(r==="lines"){const m=n.ringBuffer.firstLineIndex(),f=m+n.ringBuffer.getLineCount();if(o>=m&&o<f)a=n.ringBuffer.offset(o,s).map((y,T)=>({line:o+T,text:y})),u=o+a.length<f,l=u?o+a.length:null;else if(o<f){const d=await this.readFromFile(n,"lines",o,s,0,0,void 0);a=d.rows,u=d.hasMore,l=d.nextStartLine}}else{const m=String(i.pattern??"");if(!m||m.length>H)return this._emptyResult(e,n,r);let f;try{f=new RegExp(m,"i")}catch{return this._emptyResult(e,n,r)}const d=Math.min(Math.max(0,i.context_before??0),v),y=Math.min(Math.max(0,i.context_after??0),v),T=await this.readFromFile(n,"grep",o,s,d,y,f);a=T.rows,u=T.hasMore,l=T.nextStartLine}const c=[];let p=0,g=!1;for(const m of a){const f=Buffer.byteLength(m.text,"utf-8")+1;if(c.length>=s||p+f>K){g=!0,u=!0;break}c.push(m),p+=f}const w=i.include_metadata!==!1;return{taskId:e,status:n.status,mode:r,lines:c,lineCount:c.length,metadata:w?{totalLines:n.outputLineCount,totalBytes:n.outputBytes,returnedBytes:p,truncated:g,outputTruncated:n.outputTruncated,hasMore:u,nextStartLine:u?l:null,outputFile:n.outputPath}:void 0}}_emptyResult(t,i,e){return{taskId:t,status:i.status,mode:e,lines:[],lineCount:0,metadata:{totalLines:i.outputLineCount,totalBytes:i.outputBytes,returnedBytes:0,truncated:!1,outputTruncated:i.outputTruncated,hasMore:!1,nextStartLine:null,outputFile:i.outputPath}}}async readFromFile(t,i,e,n,r,s,o){const a=[],u=new Set;let l=0,c=!1;const p=[];let g=-1/0;try{const w=await S.open(t.outputPath,"r"),m=O({input:w.createReadStream({encoding:"utf-8"}),crlfDelay:1/0});for await(const f of m){const d=l;if(l++,i==="grep"&&d-e>=Y&&d>=e){c=!0;break}if(d>=e){if(i==="lines"){if(a.length>=n){c=!0;break}u.has(d)||(u.add(d),a.push({line:d,text:f}))}else if(o.test(f)){for(const T of p)T.line>=e&&!u.has(T.line)&&(u.add(T.line),a.push(T));if(u.has(d)||(u.add(d),a.push({line:d,text:f})),g=d,a.length>=n){c=!0;break}}else if(r>0&&(p.push({line:d,text:f}),p.length>r&&p.shift()),g>=e&&d-g<=s&&!u.has(d)&&(u.add(d),a.push({line:d,text:f}),a.length>=n)){c=!0;break}}}m.close(),await w.close()}catch{return{rows:[],hasMore:!1,nextStartLine:null}}return c?{rows:a,hasMore:c,nextStartLine:l}:{rows:a,hasMore:c,nextStartLine:null}}async awaitCompletion(t,i,e){return Promise.all(i.map(n=>this.awaitOne(t,n,e)))}async awaitOne(t,i,e){const n=this.getTask(t,i);if(n)return n.status!=="running"?this.taskToAwaitResult(n):new Promise(o=>{let a=null;const u=l=>{a&&clearTimeout(a),o(l)};n.completionWaiters.push(u),e&&e>0&&(a=setTimeout(()=>{n.completionWaiters=n.completionWaiters.filter(l=>l!==u),o({taskId:i,status:"running",exitCode:null,signal:null,timedOut:!0,aborted:!1,durationMs:Date.now()-n.startedAt})},e),a.unref?.())});const s=(await this.store.readSession(t))?.tasks.find(o=>o.taskId===i);return s?s.status!=="running"?{taskId:i,status:s.status,exitCode:s.exitCode,signal:s.signal,timedOut:s.killedReason==="timeout",aborted:!1,durationMs:(s.finishedAt??Date.now())-s.startedAt,...s.outputPath?{outputFilePath:s.outputPath}:{}}:{taskId:i,status:"killed",exitCode:null,signal:null,timedOut:!1,aborted:!1,durationMs:(s.finishedAt??Date.now())-s.startedAt}:null}taskToAwaitResult(t){return{taskId:t.taskId,status:t.status,exitCode:t.exitCode,signal:t.signal,timedOut:t.killedReason==="timeout",aborted:!1,durationMs:(t.finishedAt??Date.now())-t.startedAt,...t.status!=="running"&&t.outputPath?{outputFilePath:t.outputPath}:{}}}interruptAwaits(t,i){const e=this.tasksByAgent.get(t);if(e)for(const n of i){const r=e.get(n);if(!r)continue;const s=r.completionWaiters;if(s.length===0)continue;r.completionWaiters=[];const o={taskId:n,status:"running",exitCode:null,signal:null,timedOut:!1,aborted:!0,durationMs:Date.now()-r.startedAt};for(const a of s)a(o)}}async killTask(t,i){const e=this.getTask(t,i);return e?e.status!=="running"?{taskId:i,status:e.status,exitCode:e.exitCode??void 0}:e.child?(e.killedReason="user_kill",this.killProcessGroup(e.child)?(e.killEscalationTimer&&clearTimeout(e.killEscalationTimer),e.killEscalationTimer=setTimeout(()=>{e.child&&!e.finalized&&this.killProcessGroup(e.child,!0)},N),e.killEscalationTimer.unref?.(),{taskId:i,status:"killed",signal:"SIGTERM"}):{taskId:i,status:e.status,error:"kill_failed",reason:"permission_denied"}):{taskId:i,status:e.status,error:"kill_failed",reason:"no_child"}:{taskId:i,status:"killed",error:"task_not_found"}}killProcessGroup(t,i=!1){const e=t.pid;if(!e)return!1;try{if(process.platform==="win32")return R("taskkill",["/PID",String(e),"/T","/F"],{windowsHide:!0}),!0;try{process.kill(-e,i?"SIGKILL":"SIGTERM")}catch{process.kill(e,i?"SIGKILL":"SIGTERM")}return!0}catch{return!1}}async disposeAgent(t){const i=this.tasksByAgent.get(t);if(i){for(const e of i.values())e.status==="running"&&e.child&&(e.killedReason="session_disposed",this.killProcessGroup(e.child,!0)),e.timeoutTimer&&clearTimeout(e.timeoutTimer),e.killEscalationTimer&&clearTimeout(e.killEscalationTimer),e.retentionTimer&&clearTimeout(e.retentionTimer),e.exitGraceTimer&&clearTimeout(e.exitGraceTimer);this.tasksByAgent.delete(t)}await this.store.deleteAgent(t)}async disposeAll(){for(const[t,i]of this.tasksByAgent){for(const e of i.values())e.status==="running"&&(e.killedReason="process_exit",e.child&&this.killProcessGroup(e.child,!0),e.finalized||this.finalizeTask(e,null,null,"process_exit")),e.timeoutTimer&&clearTimeout(e.timeoutTimer),e.killEscalationTimer&&clearTimeout(e.killEscalationTimer),e.retentionTimer&&clearTimeout(e.retentionTimer),e.exitGraceTimer&&clearTimeout(e.exitGraceTimer);await this.store.updateSession(t,()=>null),this.tasksByAgent.delete(t)}}async reconcileDiskRunning(t){const i=this.tasksByAgent.get(t);let e=0;return await this.store.updateSession(t,n=>{let r=!1;for(const s of n.tasks){if(s.status!=="running")continue;const o=i?.get(s.taskId)?.status==="running",a=s.ownerBootId===x;if(o){a||(s.ownerBootId=x,r=!0);continue}s.status="killed",s.killedReason="runtime_crashed",s.finishedAt=Date.now(),s.notified=!0,e++,r=!0}return r?n.tasks:null}),e}async listTasksWithReconcile(t,i){try{await this.reconcileDiskRunning(t)}catch{}const e=this.tasksByAgent.get(t),n=e?[...e.values()]:[],r=n.filter(o=>o.backgrounded).map(o=>this.toSummary(o)),s=new Set(n.map(o=>o.taskId));try{const o=await this.store.readSession(t);if(o){const a=Date.now();for(const u of o.tasks)s.has(u.taskId)||u.backgrounded===!0&&u.status!=="running"&&(u.finishedAt&&a-u.finishedAt>=B||i&&i!=="all"&&u.status!==i||r.push(Z(u)))}}catch{}return i&&i!=="all"?r.filter(o=>o.status===i).sort((o,a)=>a.startedAt-o.startedAt):r.sort((o,a)=>a.startedAt-o.startedAt)}async reconcileAllAgents(){const t=await this.store.listAgents();let i=0;for(const e of t)try{i+=await this.reconcileDiskRunning(e)}catch{}return i}async reconcileOrphans(t){await this.reconcileDiskRunning(t)}async readSessionState(t){return this.store.readSession(t)}async markNotified(t,i){await this.store.markNotified(t,i)}getOrCreateBucket(t){let i=this.tasksByAgent.get(t);return i||(i=new Map,this.tasksByAgent.set(t,i)),i}getTask(t,i){const e=this.tasksByAgent.get(t);if(e&&/^[A-Za-z0-9]{8}$/.test(i))return e.get(i)}generateTaskId(t){for(let i=0;i<3;i++){const e=M(4).toString("hex").slice(0,8);if(!t.has(e))return e}return M(6).toString("hex").slice(0,8)}async persistTask(t){await this.store.updateSession(t.agentId,i=>{const e={taskId:t.taskId,agentId:t.agentId,command:t.command,commandPreview:t.commandPreview,description:t.description,cwd:t.cwd,status:t.status,startedAt:t.startedAt,finishedAt:t.finishedAt,exitCode:t.exitCode,signal:t.signal,outputPath:t.outputPath,outputLineCount:t.outputLineCount,outputBytes:t.outputBytes,notified:t.notified,killedReason:t.killedReason,ownerBootId:t.bootId,lastPulseAt:t.status==="running"?t.lastPulseAt:void 0,backgrounded:t.backgrounded},n=i.tasks.findIndex(s=>s.taskId===t.taskId);n>=0?i.tasks[n]=e:i.tasks.push(e);const r=Date.now();return i.tasks.filter(s=>s.status==="running"||!s.finishedAt||r-s.finishedAt<B)})}persistTaskSafe(t){this.persistTask(t).catch(i=>{console.error(`[BackgroundCommandManager] persist ${t.agentId}/${t.taskId} failed:`,i)})}}class I extends Error{constructor(t,i){super(i),this.name="BackgroundTaskError",this.code=t}}function Z(h){return{taskId:h.taskId,status:h.status,command:h.command,commandPreview:h.commandPreview,description:h.description,cwd:h.cwd,startedAt:h.startedAt,finishedAt:h.finishedAt,exitCode:h.exitCode,signal:h.signal,outputLineCount:h.outputLineCount,outputBytes:h.outputBytes}}const st=new V;export{V as BackgroundCommandManager,I as BackgroundTaskError,st as backgroundCommandManager};
|
|
7
7
|
|
|
@@ -87,4 +87,17 @@ export declare function buildFileResourceKey(workingDirectory: string, rawFilePa
|
|
|
87
87
|
export declare function fileResourceClaim(workingDirectory: string, rawFilePath: string, access: "read" | "write"): ResourceClaim;
|
|
88
88
|
|
|
89
89
|
export declare function resolveWorkspaceTarget(workingDirectory: string, rawFilePath: string): Promise<ResolvedWorkspaceTarget>;
|
|
90
|
+
|
|
91
|
+
export declare const EDIT_FAILURE_SNAPSHOT_MAX_BYTES: number;
|
|
92
|
+
|
|
93
|
+
export interface EditFailureSnapshot {
|
|
94
|
+
|
|
95
|
+
path: string;
|
|
96
|
+
|
|
97
|
+
bytes: number;
|
|
98
|
+
|
|
99
|
+
content: string;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export declare function getEditFailureSnapshot(error: unknown): EditFailureSnapshot | undefined;
|
|
90
103
|
export declare function createBuiltInFileTools(workingDirectory: string, agentId?: string, onFileChange?: OnAgentFileChange, backgroundDeps?: BackgroundToolDeps, permissionController?: ToolPermissionController, staleGuard?: StaleFileGuardDeps): ACodeBuiltInTool[];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID as ht}from"node:crypto";import{promises as
|
|
1
|
+
import{randomUUID as ht}from"node:crypto";import{promises as f,createReadStream as Z}from"node:fs";import ft from"node:os";import d from"node:path";import Q from"node:readline";import{runShellCommand as pt}from"./builtins/shellCommandRunner.js";import{createOutputEventCollector as wt}from"./builtins/commandOutputEvents.js";import{buildCommandOutputSpilloverContent as gt,COMMAND_OUTPUT_SPILLOVER_LINE_LIMIT as yt,countOutputLines as tt,formatCommandOutputSpilloverStdout as _t,writeCommandArtifactFile as bt}from"./builtins/commandArtifacts.js";import{symbolsTool as kt}from"./built-in-symbols-tool.js";import{buildRevisionId as W,checkFileFreshForWrite as et,createReadFileEntry as U,STALE_FILE_WRITE_REASON as ot,toStateKey as N}from"./read-file-state.js";import{createListBackgroundCommandsTool as vt,createKillBackgroundCommandTool as Pt,createReadBackgroundOutputTool as Et}from"./background-command-tools.js";import{detectImageFormatFromBuffer as St,formatBytes as x,imageMediaType as it,readImageDimensions as Tt,tryCompressImageWithSharp as xt,tryResizeWithSharp as Mt}from"./image-utils.js";const Rt=2e3,L=2e3,at=50*1024,nt=4096,$t=.3,Ot=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"]),It=new Set(["png","jpg","jpeg","gif","webp"]),rt=20*1024*1024,F=10*1024*1024,X=Math.floor(3.75*1024*1024),z=2e3,At=50*1024,Lt=100*1024,Ft=15e3,Bt=1e3,Nt=1024*1024,Ct=256*1024,Wt=1e3,Ut=new Set([".git","node_modules","dist","build",".next",".nuxt",".cache",".turbo",".output","coverage",".nyc_output"]),Te={fileReadOutside:"allow",commandExecution:"allow",fileModification:"allow",fileModificationOutside:"allow"};async function B(e,t,o){if(!e)return;const i=e.getLevel(t);if(i==="deny")throw new Error(`Operation blocked by tool permission policy (${t} = deny). Explain this restriction to the user if needed.`);if(i==="ask"&&!await e.requestPermission(t,o))throw new Error(`Operation denied by the user (${t}). Do not retry the same operation without asking the user.`)}function M(e){return e.replace(/\\/g,"/")}async function Y(e){try{return await f.access(e),!0}catch{return!1}}function zt(e,t){if(!t)return 0;let o=0,i=e.indexOf(t);for(;i>=0;)o+=1,i=e.indexOf(t,i+t.length);return o}function $(e,t,o){for(const i of t){const a=e[i];if(typeof a=="string")return a}throw new Error(`${o} is required`)}function O(e,t){for(const o of t){const i=e[o];if(typeof i=="string"&&i.trim())return i}}function D(e,t,o){for(const i of t){const a=e[i],r=typeof a=="number"?a:typeof a=="string"?Number(a):NaN;if(Number.isFinite(r)&&r>0)return Math.floor(r)}return o}function Dt(e,t,o){for(const i of t){const a=e[i],r=typeof a=="number"?a:typeof a=="string"?Number(a):NaN;if(Number.isFinite(r)&&r>0)return Math.floor(r);if(Number.isFinite(r)&&r===0)return 0}return o}function qt(e){const t=e.compress;if(t==null)return"auto";if(typeof t=="boolean")return t;if(t==="auto")return"auto";if(t==="true")return!0;if(t==="false")return!1;throw new Error(`Invalid compress argument: ${JSON.stringify(t)} (expected true, false, or "auto")`)}async function st(e){const t=d.extname(e).toLowerCase();if(Ot.has(t))return!0;const o=await f.open(e,"r");try{const i=Buffer.alloc(nt),{bytesRead:a}=await o.read(i,0,nt,0);if(a===0)return!1;const r=i.subarray(0,a);if(r.includes(0))return!0;let s=0;for(let c=0;c<a;c++){const n=r[c];(n<9||n>13&&n<32)&&s++}return s/a>$t}finally{await o.close()}}function I(e,t){const o=d.resolve(t),i=d.relative(e,o);if(i.startsWith("..")||d.isAbsolute(i))throw new Error(`Target path is outside workspace: ${o}`);return o}function jt(e,t){const o=d.resolve(String(e||"").trim()),i=C(String(t??"").trim());return`file:${(d.isAbsolute(i)?d.resolve(i):d.resolve(o,i)).replace(/\\/g,"/")}`}function q(e,t,o){return{key:jt(e,t),access:o}}function j(e){const t=e.file_path??e.filePath;if(typeof t!="string")return null;const o=t.trim();return o.length>0?o:null}function C(e){return e==="~"||e.startsWith("~/")?d.join(ft.homedir(),e.slice(1)):e}async function Kt(e,t){const o=d.resolve(String(e||"").trim()),i=await f.realpath(o);if(!(await f.stat(i)).isDirectory())throw new Error(`Workspace path is not a directory: ${o}`);if(!t?.trim())return{workspaceRoot:i,cwd:i};const r=C(t.trim()),s=d.isAbsolute(r)?d.resolve(r):d.resolve(o,r),c=d.relative(o,s);if(c.startsWith("..")||d.isAbsolute(c))throw new Error(`Command cwd is outside workspace: ${s}`);const n=I(i,await f.realpath(s));if(!(await f.stat(n)).isDirectory())throw new Error(`Command cwd is not a directory: ${n}`);return{workspaceRoot:i,cwd:n}}async function Xt(e){try{if((await f.lstat(e)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${e}`)}catch(t){if((typeof t=="object"&&t!==null?Reflect.get(t,"code"):void 0)!=="ENOENT")throw t}}async function Yt(e,t){const o=await f.realpath(d.dirname(t));I(e,o);try{if((await f.lstat(t)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${t}`)}catch(i){if((typeof i=="object"&&i!==null?Reflect.get(i,"code"):void 0)!=="ENOENT")throw i}}async function ct(e,t){const o=d.resolve(String(e||"").trim()),i=await f.realpath(o);if(!(await f.stat(i)).isDirectory())throw new Error(`Workspace path is not a directory: ${o}`);const r=C(t.trim());if(!r)throw new Error("file_path is required");const s=d.isAbsolute(r)?d.resolve(r):d.resolve(o,r),c=d.relative(o,s);if(c.startsWith("..")||d.isAbsolute(c))throw new Error(`Target path is outside workspace: ${s}`);return{workspaceRoot:i,requestedPath:s,targetPath:I(i,d.join(i,c))}}async function lt(e,t,o){const i=d.resolve(String(e||"").trim()),a=await f.realpath(i);if(!(await f.stat(a)).isDirectory())throw new Error(`Workspace path is not a directory: ${i}`);const s=C(t.trim());if(!s)throw new Error("file_path is required");const c=d.isAbsolute(s)?d.resolve(s):d.resolve(i,s),n=d.relative(i,c),u=await f.realpath(c).catch(()=>c),l=d.relative(a,u);if(n.startsWith("..")||d.isAbsolute(n)||l.startsWith("..")||d.isAbsolute(l)){if(!o)throw new Error(`Target path is outside workspace: ${c}`);return await B(o,"fileReadOutside",{path:c}),{workspaceRoot:a,requestedPath:c,targetPath:u}}return{workspaceRoot:a,requestedPath:c,targetPath:I(a,u)}}async function Ht(e,t){let o=d.dirname(e);for(;;){const i=d.dirname(o);try{return await f.realpath(o)}catch{if(i===o)return t;o=i}}}async function H(e,t,o,i){const a=d.resolve(String(e||"").trim()),r=await f.realpath(a);if(!(await f.stat(r)).isDirectory())throw new Error(`Workspace path is not a directory: ${a}`);const c=C(t.trim());if(!c)throw new Error("file_path is required");const n=d.isAbsolute(c)?d.resolve(c):d.resolve(a,c),u=d.relative(a,n),l=u.startsWith("..")||d.isAbsolute(u),w=await f.realpath(n).catch(async()=>Ht(n,r)),_=d.relative(r,w),h=_.startsWith("..")||d.isAbsolute(_);if(!l&&!h)return{workspaceRoot:r,requestedPath:n,targetPath:I(r,d.join(r,u))};if(!i)throw new Error(`Target path is outside workspace: ${n}`);await B(i,"fileModificationOutside",{operation:o,path:n});const p=await Y(n);return{workspaceRoot:r,requestedPath:n,targetPath:p?w:n,outsideWorkspace:!0}}async function ut(e,t){const o=d.dirname(e.targetPath),i=!await Y(o);await f.mkdir(o,{recursive:!0}),e.outsideWorkspace?await Xt(e.targetPath):await Yt(e.workspaceRoot,e.targetPath);const a=d.join(o,`.${d.basename(e.targetPath)}.${process.pid}.${ht()}.tmp`);try{await f.writeFile(a,t,"utf-8"),await f.rename(a,e.targetPath)}catch(r){throw await f.rm(a,{force:!0}),r}return{workspaceRoot:e.workspaceRoot,targetPath:e.targetPath,bytes:Buffer.byteLength(t,"utf-8"),createdParentDirectory:i,outsideWorkspace:e.outsideWorkspace===!0}}async function Gt(e,t){const o=await ct(e,t),i=I(o.workspaceRoot,await f.realpath(o.targetPath)),a=await f.stat(i);if(!a.isFile())throw new Error(`Path is not a file: ${i}`);return{workspaceRoot:o.workspaceRoot,targetPath:i,content:await f.readFile(i,"utf-8"),stat:{mtimeMs:a.mtimeMs,size:a.size}}}async function Vt(e){const t=await f.realpath(e).catch(()=>e),o=await f.stat(t);if(!o.isFile())throw new Error(`Path is not a file: ${t}`);return{workspaceRoot:d.dirname(t),targetPath:t,content:await f.readFile(t,"utf-8"),stat:{mtimeMs:o.mtimeMs,size:o.size}}}async function dt(e,t,o){if(e?.tracker)try{const i=await f.realpath(t),a=await f.stat(i);e.tracker.record(N(i),U(a,o,!1))}catch{}}async function Jt(e,t,o,i,a){const r=await lt(e,t,a),s=r.targetPath,c=await f.stat(s);if(!c.isFile())throw new Error(`Path is not a file: ${s}`);if(await st(s))return{workspaceRoot:r.workspaceRoot,targetPath:s,content:"[Binary file, content skipped]",isBinary:!0,truncated:!1,totalLines:0,shownFromLine:0,shownToLine:0,mtimeMs:c.mtimeMs,sizeBytes:c.size};const n=Z(s,{encoding:"utf-8"}),u=Q.createInterface({input:n,crlfDelay:1/0});try{const l=[];let w=0,_=0,h=0,p=!1,m=!1;const T=o-1;for await(const y of u){if(_++,w<T){w++;continue}if(l.length>=i){p=!0,w++;continue}let E=y;E.length>L&&(E=E.slice(0,L)+`... (line truncated to ${L} chars)`);const k=`${w+1}: ${E}`,b=Buffer.byteLength(k,"utf-8")+1;if(h+b>at){m=!0;break}l.push(k),h+=b,w++}if(_>0&&l.length===0&&!p&&!m&&T>=_)throw new Error(`offset ${o} exceeds total line count ${_} in file: ${s}`);const g=l.length>0?o:0,v=l.length>0?o+l.length-1:0;let P;m?P=`Output capped at 50 KB. Showing lines ${g}-${v}. Use offset=${v+1} to continue.`:p?P=`Showing lines ${g}-${v} of ${_}. Use offset=${v+1} to continue.`:P=`End of file - total ${_} lines`;const S=l.length>0?l.join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`+P:P;return{workspaceRoot:n.workspaceRoot,targetPath:s,content:S,isBinary:!1,truncated:p||m,totalLines:m?-1:_,shownFromLine:g,shownToLine:v,mtimeMs:Math.trunc(c.mtimeMs),sizeBytes:c.size}}finally{u.close(),r.destroy()}}function j(e){return/^https?:\/\//i.test(e)}async function Zt(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid image URL: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${t.protocol} (only http/https)`);let o;try{o=await fetch(e,{signal:AbortSignal.timeout(Ft)})}catch(u){const l=u instanceof Error?u.message:String(u);throw new Error(`Image URL fetch failed: ${e} (${l})`)}if(!o.ok)throw new Error(`Image URL fetch failed: ${e} (HTTP ${o.status})`);const i=(o.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(i&&!i.startsWith("image/"))throw new Error(`URL did not return an image (content-type: ${i}): ${e}`);const a=Number(o.headers.get("content-length")||"");if(Number.isFinite(a)&&a>F)throw new Error(`Image too large to fetch: ${e} (${T(a)} > ${T(F)})`);const n=o.body;if(!n){const u=await o.arrayBuffer();if(u.byteLength>F)throw new Error(`Image too large to fetch: ${e} (${T(u.byteLength)} > ${T(F)})`);return Buffer.from(u)}const s=n.getReader(),c=[];let r=0;for(;;){const{done:u,value:l}=await s.read();if(u)break;if(l){if(r+=l.byteLength,r>F)throw s.cancel().catch(()=>{}),new Error(`Image too large to fetch: ${e} (${T(r)} > ${T(F)})`);c.push(Buffer.from(l))}}return Buffer.concat(c,r)}async function Qt(e,t,o,i="auto",a){let n,s;if(j(t))n=await Zt(t),s=t;else{const b=(await lt(e,t,o)).targetPath,R=await h.stat(b);if(!R.isFile())throw new Error(`Path is not a file: ${b}`);if(R.size>nt)throw new Error(`Image file too large to read: ${M(b)} (${T(R.size)} > ${T(nt)}). Downscale it first.`);n=await h.readFile(b),s=M(b),a?.tracker&&a.tracker.record(N(b),K(R,null,!0))}if(n.length===0)throw new Error(`Image file is empty: ${s}`);const c=St(n);if(!c)throw new Error(`Unsupported or corrupt image (unrecognized format): ${s}`);const r=xt(n);let u=c,l=n,w=r?.width,_=r?.height,f=null;if(i!==!1){const k=await Tt(n,c,{normalMaxBytes:At,clearMaxBytes:Lt});k?.compressed&&(l=k.buffer,u=k.mediaType,w=k.width,_=k.height,f={level:k.level,originalSize:k.originalSize})}let p=!1;const m=await Mt(l,u,{maxWidth:U,maxHeight:U,maxBytes:X});if(m)l=m.buffer,u=m.mediaType,w=m.width,_=m.height,p=m.changed;else if(l.length>X)throw new Error(`Image too large to inline: ${s} (${T(l.length)} > ${T(X)}). Downscale it first, e.g. via Bash: magick "${t}" -resize ${U}x${U} "${t}". Installing sharp enables automatic downscaling.`);const x=w&&_?`${w}x${_}`:"unknown dimensions",g=p&&r&&r.width!==w?` (resized from ${r.width}x${r.height})`:p?" (resized)":"",v=f!==null?f.level:null,P=f!==null?Math.max(1,Math.round((1-l.length/f.originalSize)*100)):0,S=f!==null?`${T(l.length)} (compressed from ${T(f.originalSize)}, saved ${P}%, ${v} level)`:T(l.length),y=`[Image: ${s}, ${x}${g}, ${S}]`,E=j(t)?d.basename(new URL(t).pathname)||"image":d.basename(s);return{ok:!0,filePath:s,content:y,isBinary:!1,image:{mediaType:it(u),width:w??null,height:_??null,originalWidth:r?.width??null,originalHeight:r?.height??null,resized:p,size:l.length,compressed:f!==null,compressionLevel:v,compressionRatio:f!==null?Math.round((1-l.length/f.originalSize)*100)/100:null,originalSize:n.length},attachments:[{type:"image",name:E,mediaType:it(u),base64Data:l.toString("base64")}]}}function mt(e){let t="",o=0;for(;o<e.length;){const i=e[o];if(i==="*")t+="[^/]*";else if(i==="?")t+="[^/]";else if(i==="{"){const a=e.indexOf("}",o);if(a>=0){const n=e.slice(o+1,a);t+=`(${n.split(",").join("|")})`,o=a}else t+="\\{"}else if(i==="["){const a=e.indexOf("]",o);a>=0?(t+=e.slice(o,a+1),o=a):t+="\\["}else"+^$.()|\\".includes(i)?t+="\\"+i:t+=i;o++}return new RegExp(`^${t}$`)}async function te(e,t,o,i){const a=[];async function n(s){if(a.length>=i)return;const c=await h.readdir(s,{withFileTypes:!0});for(const r of c){if(a.length>=i)return;if(r.name.startsWith(".")&&r.isDirectory())continue;const u=d.join(s,r.name);if(r.isDirectory()){if(Ut.has(r.name))continue;await n(u)}else if(r.isFile()){if(t&&!t.test(r.name)||o&&o.test(r.name))continue;a.push(u)}}}return await n(e),a}async function ee(e,t,o){if((await h.stat(e)).size>Nt)return{matches:[],count:0};if(await st(e))return{matches:[],count:0};const a=d.relative(t,e).replace(/\\/g,"/"),n=[];let s=0;const c=Z(e,{encoding:"utf-8"}),r=Q.createInterface({input:c,crlfDelay:1/0});try{let u=0;for await(const l of r)if(u++,o.regex.test(l)){if(s++,o.collectContent){let w=l;if(w.length>L&&(w=w.slice(0,L)+`... (line truncated to ${L} chars)`),n.push({file:a,line:u,content:w}),n.length>=o.maxResults)break}if(o.stopOnFirstMatch)break}}finally{r.close(),c.destroy()}return{matches:n,count:s}}const oe=12*60*6e4,ie=3*6e4,ae=6e4,re=10*6e4;function ne(e,t,o,i){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",concurrencyMode:"write",resourceKeys:a=>{const n=q(a);return n?[D(e,n,"write")]:[]},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(a){const n=$(a,["file_path","filePath"],"file_path"),s=$(a,["content"],"content"),c=O(a,["reason"]),r=await G(e,n,"write",o);await B(o,"fileModification",{operation:"write",path:r.targetPath});const u=await Y(r.targetPath),l=u?await h.readFile(r.targetPath,"utf-8").catch(()=>null):null,w=u?await h.realpath(r.targetPath).catch(()=>r.targetPath):r.targetPath;let _=null;if(i?.enabled&&u){const p=await h.stat(w);_=W(p.mtimeMs,p.size);const m=et(i.tracker,N(w),p,l);if(!m.ok)throw new Error(m.reason)}if(i?.enabled&&_){const p=await h.stat(w).catch(()=>null);if(!p||W(p.mtimeMs,p.size)!==_)throw new Error(ot)}const f=await ut(r,s);if(await dt(i,f.targetPath,s),t&&!f.outsideWorkspace){const p=d.relative(f.workspaceRoot,f.targetPath).replace(/\\/g,"/");await t({filePath:p,operation:u?"UPDATE":"CREATE",beforeContent:l,afterContent:s,reason:c})}return{ok:!0,filePath:M(f.targetPath),bytes:f.bytes,createdParentDirectory:f.createdParentDirectory}}}}function se(e,t,o,i){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",concurrencyMode:"write",resourceKeys:a=>{const n=q(a);return n?[D(e,n,"write")]:[]},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(a){const n=$(a,["file_path","filePath"],"file_path"),s=$(a,["old_string","oldString"],"old_string"),c=$(a,["new_string","newString"],"new_string"),r=O(a,["reason"]);if(!s)throw new Error("old_string must not be empty");const u=await G(e,n,"edit",o);await B(o,"fileModification",{operation:"edit",path:u.targetPath});const l=u.outsideWorkspace?await Vt(u.targetPath):await Ht(e,n),w=N(l.targetPath);if(i?.enabled){const m=et(i.tracker,w,l.stat,l.content);if(!m.ok)throw new Error(m.reason)}const _=zt(l.content,s);if(_===0)throw new Error("old_string was not found in file");if(_>1)throw new Error(`old_string occurs ${_} times; provide a unique match`);const f=l.content.replace(s,c);if(i?.enabled){const m=await h.stat(l.targetPath).catch(()=>null);if(!m||W(m.mtimeMs,m.size)!==W(l.stat.mtimeMs,l.stat.size))throw new Error(ot)}const p=await ut(u,f);if(await dt(i,p.targetPath,f),t&&!p.outsideWorkspace){const m=d.relative(p.workspaceRoot,p.targetPath).replace(/\\/g,"/");await t({filePath:m,operation:"UPDATE",beforeContent:l.content,afterContent:f,reason:r})}return{ok:!0,filePath:M(p.targetPath),bytes:p.bytes}}}}function ce(e,t,o){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",concurrencyMode:"write",resourceKeys:i=>{const a=q(i);return a?[D(e,a,"write")]:[]},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(i){const a=$(i,["file_path","filePath"],"file_path"),n=O(i,["reason"]),s=await G(e,a,"delete",o);await B(o,"fileModification",{operation:"delete",path:s.targetPath});const c=s.outsideWorkspace?await h.realpath(s.targetPath).catch(()=>s.targetPath):I(s.workspaceRoot,await h.realpath(s.targetPath).catch(()=>s.targetPath)),r=await h.stat(c).catch(()=>null);if(!r)throw new Error(`File does not exist: ${c}`);if(!r.isFile())throw new Error(`Path is not a file: ${c}`);const u=await h.readFile(c,"utf-8").catch(()=>null);if(await h.rm(c,{force:!0}),t&&!s.outsideWorkspace){const l=d.relative(s.workspaceRoot,c).replace(/\\/g,"/");await t({filePath:l,operation:"DELETE",beforeContent:u,afterContent:null,reason:n})}return{ok:!0,filePath:M(c),deleted:!0}}}}function le(e,t,o){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",concurrencyMode:"read",resourceKeys:i=>{const a=q(i);return!a||j(a)?[]:[D(e,a,"read")]},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. By default (compress='auto') images are compressed before inlining using a tiered ladder that judges by the compressed result, not the original size: lossless first (pixel-exact, dimensions preserved), then high-quality lossy downscaling only if the lossless result is still over 50 KB (normal level), then more aggressive downscaling if still over 100 KB (clear level). When compression applies, the result reports the compression level, compressed size, and compression ratio (e.g. saved 80%). Pass compress=true to also attempt compression, or compress=false to disable it (images exceeding the hard 2000px / 3.75MB inline limits are still auto-downscaled when sharp is available). You may issue several read_file calls in ONE message; independent reads run in parallel.",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."},compress:{anyOf:[{type:"boolean"},{type:"string",enum:["auto"]}],description:'Image compression mode (ignored for text files). "auto" (default): compress with a tiered ladder driven by the compressed result \u2014 lossless, then high-quality downscale if still >50 KB, then more aggressive if still >100 KB. true: same as auto. false: skip tiered compression entirely (hard inline limits still apply).'}},required:["file_path"],additionalProperties:!1},async execute(i){const a=$(i,["file_path","filePath"],"file_path"),n=d.extname(a).toLowerCase().slice(1);if(j(a)||It.has(n))return await Qt(e,a,t,qt(i),o);const s=z(i,["offset"],1),c=z(i,["limit"],Rt),r=await Jt(e,a,s,c,t);if(o?.tracker){let u=null,l=s!==1||r.truncated||r.isBinary;l||(u=await h.readFile(r.targetPath,"utf-8").catch(()=>null),(u==null||u.length>at)&&(u=null,l=!0)),o.tracker.record(N(r.targetPath),K({mtimeMs:r.mtimeMs,size:r.sizeBytes},u,l))}return{ok:!0,filePath:M(r.targetPath),content:r.content,isBinary:r.isBinary,truncated:r.truncated,totalLines:r.totalLines,shownFromLine:r.shownFromLine,shownToLine:r.shownToLine}}}}function ue(e,t,o,i){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",concurrencyMode:"write",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${d.resolve(String(e||"").trim()).replace(/\\/g,"/")}`,access:"write"}],description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded total timeout (timeout_ms) measured from command start \u2014 by default 3 minutes, after which the process is force-terminated; timeout_ms can raise this (up to 12 hours) or set 0 to disable. The tool 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 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). The background command stays bound by the same total timeout (timeout_ms, default 3 minutes, still measured from command start) 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 total command timeout in milliseconds, measured from command start. Defaults to 180000 (3 minutes) and is capped at 43200000 (12 hours). Set 0 to disable the timeout entirely (run until finished or killed)."},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 moved to the background and a task_id is returned (backgrounded=true, reason=watchdog_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. The command remains bound by the total timeout (timeout_ms, default 3 minutes, measured from command start) whether foreground or background; inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Short reason for running this command (what it does and why it is needed), shown to the user in the background commands panel. Always provide a concise reason, e.g. 'Start local dev server for manual verification'."}},required:["command"],additionalProperties:!1},async execute(a,n){const s=$(a,["command"],"command").trim();if(!s)throw new Error("command must not be empty");const c=Dt(a,["timeout_ms","timeoutMs"],ie),r=c===0?0:Math.min(c,oe),u=z(a,["inactivity_timeout_ms","inactivityTimeoutMs"],ae),l=Math.min(u,re),w=O(a,["cwd"]),_=O(a,["description"]),f=await Kt(e,w);await B(i,"commandExecution",{command:s,cwd:M(f.cwd)});const p=a.wait_seconds,x=typeof p=="number"&&Number.isFinite(p)?p:-1;if(o)return await de({deps:o,command:s,agentId:t,workspaceRoot:f.workspaceRoot,cwd:f.cwd,timeoutMs:r,inactivityTimeoutMs:l,waitSeconds:x,description:_,onOutput:n?.onOutput,settleSignal:n?.settleSignal});const g=await pt({commandText:s,agentId:t,workspaceRoot:f.workspaceRoot,cwd:f.cwd,timeoutMs:r,inactivityTimeoutMs:l,onOutput:n?.onOutput,watchdogSignal:n?.settleSignal}),v={ok:g.exitCode===0&&!g.timedOut,tool:"Bash",command:s,cwd:M(f.cwd),exitCode:g.exitCode,signal:g.signal,timedOut:g.timedOut,inactivityTimedOut:g.inactivityTimedOut,watchdogInterrupted:g.watchdogInterrupted,timeoutMs:r,inactivityTimeoutMs:l,durationMs:g.durationMs,outputSpilled:g.outputSpilled,outputFilePath:g.outputFilePath,outputLineCount:g.outputLineCount,commandFilePath:g.commandFilePath,commandLineCount:g.commandLineCount,stdout:g.stdout,stderr:g.stderr};return g.watchdogInterrupted?{...v,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"+(g.outputFilePath?` (full output spilled to "${g.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."}:v}}}async function de(e){const{deps:t,command:o,agentId:i,workspaceRoot:a,cwd:n,timeoutMs:s,inactivityTimeoutMs:c,waitSeconds:r,description:u,onOutput:l,settleSignal:w}=e,_=l?wt({cwd:n,commandLineCount:0,onOutput:l}):void 0;let f=!!_;const p=()=>{f&&(f=!1,_?.close())};try{const{taskId:m,completion:x}=t.manager.startCommand({commandText:o,agentId:i,workspaceRoot:a,cwd:n,description:u,timeoutMs:s,inactivityTimeoutMs:c,onOutput:f?S=>{f&&_?.push(S.stream,S.text)}:void 0,onCompleted:t.emitCompleted});if(r===0)return t.manager.disableInactivityTimeout(i,m),await t.manager.markBackgrounded(i,m).catch(()=>{}),p(),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:m,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use await_complete(bg_cmd_ids=["${m}"]) to block until it finishes, read_background_output(task_id="${m}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${m}") to stop.`};const g=r===-1?0:Math.max(0,Math.floor(r*1e3)),v=[x];let P;r!==-1&&v.push(new Promise(S=>{P=setTimeout(()=>S("__timeout__"),g),P.unref?.()})),w&&v.push(w.then(()=>"__settle__"));try{const S=await Promise.race(v);if(S==="__settle__")return t.manager.disableInactivityTimeout(i,m),await t.manager.markBackgrounded(i,m).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:m,status:"backgrounded",reason:"watchdog_timeout",waitedMs:g,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${m}"]) to block until it finishes, read_background_output(task_id="${m}", mode="tail") to read output, or kill_background_command(task_id="${m}") to stop.`};if(S==="__timeout__")return t.manager.disableInactivityTimeout(i,m),await t.manager.markBackgrounded(i,m).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:m,status:"backgrounded",reason:"timeout",waitedMs:g,message:`Command still running after ${r}s; moved to background. Use await_complete(bg_cmd_ids=["${m}"]) to block until it finishes, or read_background_output(task_id="${m}", mode="tail") / kill_background_command(task_id="${m}") to inspect.`};const y=S;let E=y.stdout,k=y.stderr,b=y.outputSpilled,R=y.outputFilePath;if(!b&&tt(`${y.stdout}${y.stderr}`)>yt){const A=await bt(i,"cmd","out",gt({commandText:o,commandFilePath:y.commandFilePath,commandLineCount:y.commandLineCount,cwd:n,startedAt:new Date(Date.now()-y.durationMs),endedAt:new Date,exitCode:y.exitCode,signal:y.signal??null,timedOut:y.timedOut,inactivityTimedOut:y.inactivityTimedOut??!1,stdout:E,stderr:k}));E=_t(M(A),tt(`${y.stdout}${y.stderr}`)),b=!0,R=M(A)}return{ok:y.exitCode===0&&!y.timedOut,tool:"Bash",command:o,backgrounded:!1,taskId:m,exitCode:y.exitCode,signal:y.signal,timedOut:y.timedOut,inactivityTimedOut:y.inactivityTimedOut,timeoutMs:y.timeoutMs,inactivityTimeoutMs:y.inactivityTimeoutMs,durationMs:y.durationMs,outputSpilled:b,outputFilePath:R,outputLineCount:y.outputLineCount,commandFilePath:y.commandFilePath,commandLineCount:y.commandLineCount,stdout:E,stderr:k}}finally{P&&clearTimeout(P),p()}}catch(m){if(m?.code==="too_many_tasks"||m?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:o,backgrounded:!1,status:"not_executed",error:m.code,message:`Command was NOT executed: ${m.message}. Wait for some background tasks to finish/cleanup (per-agent limit 16, global 256), or reduce concurrent background commands, then retry.`};throw m}}function me(e){return{kind:"builtin",toolName:"grep",exposedName:"grep",concurrencyMode:"read",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${d.resolve(String(e||"").trim()).replace(/\\/g,"/")}`,access:"read"}],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.). You may issue several grep/read_file calls in ONE message; independent searches run in parallel.",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(t){const o=$(t,["pattern"],"pattern"),i=O(t,["path"])||".",a=O(t,["include"]),n=O(t,["exclude"]),s=t.case_insensitive===!0,c=(()=>{const b=t.output_mode;return b==="files_with_matches"||b==="count"?b:"content"})(),r=z(t,["max_results"],Wt),u=s?"i":"";let l;try{l=new RegExp(o,u)}catch(b){throw new Error(`Invalid regex pattern: ${b instanceof Error?b.message:String(b)}`)}const w=a?mt(a):null,_=n?mt(n):null,f=await ct(e,i),p=I(f.workspaceRoot,await h.realpath(f.targetPath)),m=await h.stat(p);let x;if(m.isFile())x=[p];else if(m.isDirectory())x=await te(p,w,_,Bt);else throw new Error(`Path is neither a file nor a directory: ${p}`);const g=[],v=[],P=[];let S=0,y=0,E=!1;for(const b of x){if(c==="content"&&g.length>=r){E=!0;break}const R={regex:l,maxResults:c==="content"?r-g.length:Number.MAX_SAFE_INTEGER,collectContent:c==="content",stopOnFirstMatch:c==="files_with_matches"},A=await ee(b,f.workspaceRoot,R);if(A.count>0){const H=d.relative(f.workspaceRoot,b).replace(/\\/g,"/");if(P.push(H),S+=A.count,c==="content"){for(const V of A.matches){const J=Buffer.byteLength(V.content,"utf-8")+64;if(y+J>Ct){E=!0;break}y+=J,g.push(V)}if(E)break;if(g.length>=r){E=!0;break}}else c==="count"&&v.push({file:H,count:A.count})}}const k={ok:!0,tool:"grep",pattern:o,searchPath:M(f.targetPath),outputMode:c,filesSearched:x.length,filesMatched:P.length,totalMatches:S,truncated:E};return c==="content"?k.matches=g:c==="files_with_matches"?k.matches=P:k.matches=v,k}}}function xe(e,t,o,i,a,n){const s=t||"unknown",c=[le(e,a,n),ne(e,o,a,n),se(e,o,a,n),ce(e,o,a),me(e),ue(e,s,i,a),kt(e)];return i&&c.push(vt(s,i),Pt(s,i),Et(s,i)),c}export{Se as DEFAULT_TOOL_PERMISSION_POLICY,jt as buildFileResourceKey,xe as createBuiltInFileTools,I as ensureInsideWorkspace,D as fileResourceClaim,ct as resolveWorkspaceTarget};
|
|
3
|
+
`+P:P;return{workspaceRoot:r.workspaceRoot,targetPath:s,content:S,isBinary:!1,truncated:p||m,totalLines:m?-1:_,shownFromLine:g,shownToLine:v,mtimeMs:Math.trunc(c.mtimeMs),sizeBytes:c.size}}finally{u.close(),n.destroy()}}function K(e){return/^https?:\/\//i.test(e)}async function Zt(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid image URL: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${t.protocol} (only http/https)`);let o;try{o=await fetch(e,{signal:AbortSignal.timeout(Ft)})}catch(u){const l=u instanceof Error?u.message:String(u);throw new Error(`Image URL fetch failed: ${e} (${l})`)}if(!o.ok)throw new Error(`Image URL fetch failed: ${e} (HTTP ${o.status})`);const i=(o.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(i&&!i.startsWith("image/"))throw new Error(`URL did not return an image (content-type: ${i}): ${e}`);const a=Number(o.headers.get("content-length")||"");if(Number.isFinite(a)&&a>F)throw new Error(`Image too large to fetch: ${e} (${x(a)} > ${x(F)})`);const r=o.body;if(!r){const u=await o.arrayBuffer();if(u.byteLength>F)throw new Error(`Image too large to fetch: ${e} (${x(u.byteLength)} > ${x(F)})`);return Buffer.from(u)}const s=r.getReader(),c=[];let n=0;for(;;){const{done:u,value:l}=await s.read();if(u)break;if(l){if(n+=l.byteLength,n>F)throw s.cancel().catch(()=>{}),new Error(`Image too large to fetch: ${e} (${x(n)} > ${x(F)})`);c.push(Buffer.from(l))}}return Buffer.concat(c,n)}async function Qt(e,t,o,i="auto",a){let r,s;if(K(t))r=await Zt(t),s=t;else{const b=(await lt(e,t,o)).targetPath,R=await f.stat(b);if(!R.isFile())throw new Error(`Path is not a file: ${b}`);if(R.size>rt)throw new Error(`Image file too large to read: ${M(b)} (${x(R.size)} > ${x(rt)}). Downscale it first.`);r=await f.readFile(b),s=M(b),a?.tracker&&a.tracker.record(N(b),U(R,null,!0))}if(r.length===0)throw new Error(`Image file is empty: ${s}`);const c=St(r);if(!c)throw new Error(`Unsupported or corrupt image (unrecognized format): ${s}`);const n=Tt(r);let u=c,l=r,w=n?.width,_=n?.height,h=null;if(i!==!1){const k=await xt(r,c,{normalMaxBytes:At,clearMaxBytes:Lt});k?.compressed&&(l=k.buffer,u=k.mediaType,w=k.width,_=k.height,h={level:k.level,originalSize:k.originalSize})}let p=!1;const m=await Mt(l,u,{maxWidth:z,maxHeight:z,maxBytes:X});if(m)l=m.buffer,u=m.mediaType,w=m.width,_=m.height,p=m.changed;else if(l.length>X)throw new Error(`Image too large to inline: ${s} (${x(l.length)} > ${x(X)}). Downscale it first, e.g. via Bash: magick "${t}" -resize ${z}x${z} "${t}". Installing sharp enables automatic downscaling.`);const T=w&&_?`${w}x${_}`:"unknown dimensions",g=p&&n&&n.width!==w?` (resized from ${n.width}x${n.height})`:p?" (resized)":"",v=h!==null?h.level:null,P=h!==null?Math.max(1,Math.round((1-l.length/h.originalSize)*100)):0,S=h!==null?`${x(l.length)} (compressed from ${x(h.originalSize)}, saved ${P}%, ${v} level)`:x(l.length),y=`[Image: ${s}, ${T}${g}, ${S}]`,E=K(t)?d.basename(new URL(t).pathname)||"image":d.basename(s);return{ok:!0,filePath:s,content:y,isBinary:!1,image:{mediaType:it(u),width:w??null,height:_??null,originalWidth:n?.width??null,originalHeight:n?.height??null,resized:p,size:l.length,compressed:h!==null,compressionLevel:v,compressionRatio:h!==null?Math.round((1-l.length/h.originalSize)*100)/100:null,originalSize:r.length},attachments:[{type:"image",name:E,mediaType:it(u),base64Data:l.toString("base64")}]}}function mt(e){let t="",o=0;for(;o<e.length;){const i=e[o];if(i==="*")t+="[^/]*";else if(i==="?")t+="[^/]";else if(i==="{"){const a=e.indexOf("}",o);if(a>=0){const r=e.slice(o+1,a);t+=`(${r.split(",").join("|")})`,o=a}else t+="\\{"}else if(i==="["){const a=e.indexOf("]",o);a>=0?(t+=e.slice(o,a+1),o=a):t+="\\["}else"+^$.()|\\".includes(i)?t+="\\"+i:t+=i;o++}return new RegExp(`^${t}$`)}async function te(e,t,o,i){const a=[];async function r(s){if(a.length>=i)return;const c=await f.readdir(s,{withFileTypes:!0});for(const n of c){if(a.length>=i)return;if(n.name.startsWith(".")&&n.isDirectory())continue;const u=d.join(s,n.name);if(n.isDirectory()){if(Ut.has(n.name))continue;await r(u)}else if(n.isFile()){if(t&&!t.test(n.name)||o&&o.test(n.name))continue;a.push(u)}}}return await r(e),a}async function ee(e,t,o){if((await f.stat(e)).size>Nt)return{matches:[],count:0};if(await st(e))return{matches:[],count:0};const a=d.relative(t,e).replace(/\\/g,"/"),r=[];let s=0;const c=Z(e,{encoding:"utf-8"}),n=Q.createInterface({input:c,crlfDelay:1/0});try{let u=0;for await(const l of n)if(u++,o.regex.test(l)){if(s++,o.collectContent){let w=l;if(w.length>L&&(w=w.slice(0,L)+`... (line truncated to ${L} chars)`),r.push({file:a,line:u,content:w}),r.length>=o.maxResults)break}if(o.stopOnFirstMatch)break}}finally{n.close(),c.destroy()}return{matches:r,count:s}}const oe=12*60*6e4,ie=3*6e4,ae=6e4,ne=10*6e4;function re(e,t,o,i){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",concurrencyMode:"write",resourceKeys:a=>{const r=j(a);return r?[q(e,r,"write")]:[]},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(a){const r=$(a,["file_path","filePath"],"file_path"),s=$(a,["content"],"content"),c=O(a,["reason"]),n=await H(e,r,"write",o);await B(o,"fileModification",{operation:"write",path:n.targetPath});const u=await Y(n.targetPath),l=u?await f.readFile(n.targetPath,"utf-8").catch(()=>null):null,w=u?await f.realpath(n.targetPath).catch(()=>n.targetPath):n.targetPath;let _=null;if(i?.enabled&&u){const p=await f.stat(w);_=W(p.mtimeMs,p.size);const m=et(i.tracker,N(w),p,l);if(!m.ok)throw new Error(m.reason)}if(i?.enabled&&_){const p=await f.stat(w).catch(()=>null);if(!p||W(p.mtimeMs,p.size)!==_)throw new Error(ot)}const h=await ut(n,s);if(await dt(i,h.targetPath,s),t&&!h.outsideWorkspace){const p=d.relative(h.workspaceRoot,h.targetPath).replace(/\\/g,"/");await t({filePath:p,operation:u?"UPDATE":"CREATE",beforeContent:l,afterContent:s,reason:c})}return{ok:!0,filePath:M(h.targetPath),bytes:h.bytes,createdParentDirectory:h.createdParentDirectory}}}}const se=15*1024;function xe(e){if(typeof e!="object"||e===null)return;const t=Reflect.get(e,"editFailureSnapshot");if(typeof t=="object"&&t!==null&&typeof Reflect.get(t,"content")=="string")return t}function ce(e,t,o,i){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",concurrencyMode:"write",resourceKeys:a=>{const r=j(a);return r?[q(e,r,"write")]:[]},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(a){const r=$(a,["file_path","filePath"],"file_path"),s=$(a,["old_string","oldString"],"old_string"),c=$(a,["new_string","newString"],"new_string"),n=O(a,["reason"]);if(!s)throw new Error("old_string must not be empty");const u=await H(e,r,"edit",o);await B(o,"fileModification",{operation:"edit",path:u.targetPath});const l=u.outsideWorkspace?await Vt(u.targetPath):await Gt(e,r),w=N(l.targetPath);let _;try{if(i?.enabled){const m=et(i.tracker,w,l.stat,l.content);if(!m.ok)throw new Error(m.reason)}const p=zt(l.content,s);if(p===0)throw new Error("old_string was not found in file");if(p>1)throw new Error(`old_string occurs ${p} times; provide a unique match`);if(_=l.content.replace(s,c),i?.enabled){const m=await f.stat(l.targetPath).catch(()=>null);if(!m||W(m.mtimeMs,m.size)!==W(l.stat.mtimeMs,l.stat.size))throw new Error(ot)}}catch(p){throw p instanceof Error&&l.stat.size<=se&&(i?.tracker.record(w,U(l.stat,l.content,!1)),p.editFailureSnapshot={path:M(l.targetPath),bytes:l.stat.size,content:l.content}),p}const h=await ut(u,_);if(await dt(i,h.targetPath,_),t&&!h.outsideWorkspace){const p=d.relative(h.workspaceRoot,h.targetPath).replace(/\\/g,"/");await t({filePath:p,operation:"UPDATE",beforeContent:l.content,afterContent:_,reason:n})}return{ok:!0,filePath:M(h.targetPath),bytes:h.bytes}}}}function le(e,t,o){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",concurrencyMode:"write",resourceKeys:i=>{const a=j(i);return a?[q(e,a,"write")]:[]},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(i){const a=$(i,["file_path","filePath"],"file_path"),r=O(i,["reason"]),s=await H(e,a,"delete",o);await B(o,"fileModification",{operation:"delete",path:s.targetPath});const c=s.outsideWorkspace?await f.realpath(s.targetPath).catch(()=>s.targetPath):I(s.workspaceRoot,await f.realpath(s.targetPath).catch(()=>s.targetPath)),n=await f.stat(c).catch(()=>null);if(!n)throw new Error(`File does not exist: ${c}`);if(!n.isFile())throw new Error(`Path is not a file: ${c}`);const u=await f.readFile(c,"utf-8").catch(()=>null);if(await f.rm(c,{force:!0}),t&&!s.outsideWorkspace){const l=d.relative(s.workspaceRoot,c).replace(/\\/g,"/");await t({filePath:l,operation:"DELETE",beforeContent:u,afterContent:null,reason:r})}return{ok:!0,filePath:M(c),deleted:!0}}}}function ue(e,t,o){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",concurrencyMode:"read",resourceKeys:i=>{const a=j(i);return!a||K(a)?[]:[q(e,a,"read")]},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. By default (compress='auto') images are compressed before inlining using a tiered ladder that judges by the compressed result, not the original size: lossless first (pixel-exact, dimensions preserved), then high-quality lossy downscaling only if the lossless result is still over 50 KB (normal level), then more aggressive downscaling if still over 100 KB (clear level). When compression applies, the result reports the compression level, compressed size, and compression ratio (e.g. saved 80%). Pass compress=true to also attempt compression, or compress=false to disable it (images exceeding the hard 2000px / 3.75MB inline limits are still auto-downscaled when sharp is available). You may issue several read_file calls in ONE message; independent reads run in parallel.",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."},compress:{anyOf:[{type:"boolean"},{type:"string",enum:["auto"]}],description:'Image compression mode (ignored for text files). "auto" (default): compress with a tiered ladder driven by the compressed result \u2014 lossless, then high-quality downscale if still >50 KB, then more aggressive if still >100 KB. true: same as auto. false: skip tiered compression entirely (hard inline limits still apply).'}},required:["file_path"],additionalProperties:!1},async execute(i){const a=$(i,["file_path","filePath"],"file_path"),r=d.extname(a).toLowerCase().slice(1);if(K(a)||It.has(r))return await Qt(e,a,t,qt(i),o);const s=D(i,["offset"],1),c=D(i,["limit"],Rt),n=await Jt(e,a,s,c,t);if(o?.tracker){let u=null,l=s!==1||n.truncated||n.isBinary;l||(u=await f.readFile(n.targetPath,"utf-8").catch(()=>null),(u==null||u.length>at)&&(u=null,l=!0)),o.tracker.record(N(n.targetPath),U({mtimeMs:n.mtimeMs,size:n.sizeBytes},u,l))}return{ok:!0,filePath:M(n.targetPath),content:n.content,isBinary:n.isBinary,truncated:n.truncated,totalLines:n.totalLines,shownFromLine:n.shownFromLine,shownToLine:n.shownToLine}}}}function de(e,t,o,i){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",concurrencyMode:"write",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${d.resolve(String(e||"").trim()).replace(/\\/g,"/")}`,access:"write"}],description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded total timeout (timeout_ms) measured from command start \u2014 by default 3 minutes, after which the process is force-terminated; timeout_ms can raise this (up to 12 hours) or set 0 to disable. The tool 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 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). The background command stays bound by the same total timeout (timeout_ms, default 3 minutes, still measured from command start) 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 total command timeout in milliseconds, measured from command start. Defaults to 180000 (3 minutes) and is capped at 43200000 (12 hours). Set 0 to disable the timeout entirely (run until finished or killed)."},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 moved to the background and a task_id is returned (backgrounded=true, reason=watchdog_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. The command remains bound by the total timeout (timeout_ms, default 3 minutes, measured from command start) whether foreground or background; inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Short reason for running this command (what it does and why it is needed), shown to the user in the background commands panel. Always provide a concise reason, e.g. 'Start local dev server for manual verification'."}},required:["command"],additionalProperties:!1},async execute(a,r){const s=$(a,["command"],"command").trim();if(!s)throw new Error("command must not be empty");const c=Dt(a,["timeout_ms","timeoutMs"],ie),n=c===0?0:Math.min(c,oe),u=D(a,["inactivity_timeout_ms","inactivityTimeoutMs"],ae),l=Math.min(u,ne),w=O(a,["cwd"]),_=O(a,["description"]),h=await Kt(e,w);await B(i,"commandExecution",{command:s,cwd:M(h.cwd)});const p=a.wait_seconds,T=typeof p=="number"&&Number.isFinite(p)?p:-1;if(o)return await me({deps:o,command:s,agentId:t,workspaceRoot:h.workspaceRoot,cwd:h.cwd,timeoutMs:n,inactivityTimeoutMs:l,waitSeconds:T,description:_,onOutput:r?.onOutput,settleSignal:r?.settleSignal});const g=await pt({commandText:s,agentId:t,workspaceRoot:h.workspaceRoot,cwd:h.cwd,timeoutMs:n,inactivityTimeoutMs:l,onOutput:r?.onOutput,watchdogSignal:r?.settleSignal}),v={ok:g.exitCode===0&&!g.timedOut,tool:"Bash",command:s,cwd:M(h.cwd),exitCode:g.exitCode,signal:g.signal,timedOut:g.timedOut,inactivityTimedOut:g.inactivityTimedOut,watchdogInterrupted:g.watchdogInterrupted,timeoutMs:n,inactivityTimeoutMs:l,durationMs:g.durationMs,outputSpilled:g.outputSpilled,outputFilePath:g.outputFilePath,outputLineCount:g.outputLineCount,commandFilePath:g.commandFilePath,commandLineCount:g.commandLineCount,stdout:g.stdout,stderr:g.stderr};return g.watchdogInterrupted?{...v,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"+(g.outputFilePath?` (full output spilled to "${g.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."}:v}}}async function me(e){const{deps:t,command:o,agentId:i,workspaceRoot:a,cwd:r,timeoutMs:s,inactivityTimeoutMs:c,waitSeconds:n,description:u,onOutput:l,settleSignal:w}=e,_=l?wt({cwd:r,commandLineCount:0,onOutput:l}):void 0;let h=!!_;const p=()=>{h&&(h=!1,_?.close())};try{const{taskId:m,completion:T}=t.manager.startCommand({commandText:o,agentId:i,workspaceRoot:a,cwd:r,description:u,timeoutMs:s,inactivityTimeoutMs:c,onOutput:h?S=>{h&&_?.push(S.stream,S.text)}:void 0,onCompleted:t.emitCompleted});if(n===0)return t.manager.disableInactivityTimeout(i,m),await t.manager.markBackgrounded(i,m).catch(()=>{}),p(),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:m,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use await_complete(bg_cmd_ids=["${m}"]) to block until it finishes, read_background_output(task_id="${m}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${m}") to stop.`};const g=n===-1?0:Math.max(0,Math.floor(n*1e3)),v=[T];let P;n!==-1&&v.push(new Promise(S=>{P=setTimeout(()=>S("__timeout__"),g),P.unref?.()})),w&&v.push(w.then(()=>"__settle__"));try{const S=await Promise.race(v);if(S==="__settle__")return t.manager.disableInactivityTimeout(i,m),await t.manager.markBackgrounded(i,m).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:m,status:"backgrounded",reason:"watchdog_timeout",waitedMs:g,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${m}"]) to block until it finishes, read_background_output(task_id="${m}", mode="tail") to read output, or kill_background_command(task_id="${m}") to stop.`};if(S==="__timeout__")return t.manager.disableInactivityTimeout(i,m),await t.manager.markBackgrounded(i,m).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:m,status:"backgrounded",reason:"timeout",waitedMs:g,message:`Command still running after ${n}s; moved to background. Use await_complete(bg_cmd_ids=["${m}"]) to block until it finishes, or read_background_output(task_id="${m}", mode="tail") / kill_background_command(task_id="${m}") to inspect.`};const y=S;let E=y.stdout,k=y.stderr,b=y.outputSpilled,R=y.outputFilePath;if(!b&&tt(`${y.stdout}${y.stderr}`)>yt){const A=await bt(i,"cmd","out",gt({commandText:o,commandFilePath:y.commandFilePath,commandLineCount:y.commandLineCount,cwd:r,startedAt:new Date(Date.now()-y.durationMs),endedAt:new Date,exitCode:y.exitCode,signal:y.signal??null,timedOut:y.timedOut,inactivityTimedOut:y.inactivityTimedOut??!1,stdout:E,stderr:k}));E=_t(M(A),tt(`${y.stdout}${y.stderr}`)),b=!0,R=M(A)}return{ok:y.exitCode===0&&!y.timedOut,tool:"Bash",command:o,backgrounded:!1,taskId:m,exitCode:y.exitCode,signal:y.signal,timedOut:y.timedOut,inactivityTimedOut:y.inactivityTimedOut,timeoutMs:y.timeoutMs,inactivityTimeoutMs:y.inactivityTimeoutMs,durationMs:y.durationMs,outputSpilled:b,outputFilePath:R,outputLineCount:y.outputLineCount,commandFilePath:y.commandFilePath,commandLineCount:y.commandLineCount,stdout:E,stderr:k}}finally{P&&clearTimeout(P),p()}}catch(m){if(m?.code==="too_many_tasks"||m?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:o,backgrounded:!1,status:"not_executed",error:m.code,message:`Command was NOT executed: ${m.message}. Wait for some background tasks to finish/cleanup (per-agent limit 16, global 256), or reduce concurrent background commands, then retry.`};throw m}}function he(e){return{kind:"builtin",toolName:"grep",exposedName:"grep",concurrencyMode:"read",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${d.resolve(String(e||"").trim()).replace(/\\/g,"/")}`,access:"read"}],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.). You may issue several grep/read_file calls in ONE message; independent searches run in parallel.",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(t){const o=$(t,["pattern"],"pattern"),i=O(t,["path"])||".",a=O(t,["include"]),r=O(t,["exclude"]),s=t.case_insensitive===!0,c=(()=>{const b=t.output_mode;return b==="files_with_matches"||b==="count"?b:"content"})(),n=D(t,["max_results"],Wt),u=s?"i":"";let l;try{l=new RegExp(o,u)}catch(b){throw new Error(`Invalid regex pattern: ${b instanceof Error?b.message:String(b)}`)}const w=a?mt(a):null,_=r?mt(r):null,h=await ct(e,i),p=I(h.workspaceRoot,await f.realpath(h.targetPath)),m=await f.stat(p);let T;if(m.isFile())T=[p];else if(m.isDirectory())T=await te(p,w,_,Bt);else throw new Error(`Path is neither a file nor a directory: ${p}`);const g=[],v=[],P=[];let S=0,y=0,E=!1;for(const b of T){if(c==="content"&&g.length>=n){E=!0;break}const R={regex:l,maxResults:c==="content"?n-g.length:Number.MAX_SAFE_INTEGER,collectContent:c==="content",stopOnFirstMatch:c==="files_with_matches"},A=await ee(b,h.workspaceRoot,R);if(A.count>0){const G=d.relative(h.workspaceRoot,b).replace(/\\/g,"/");if(P.push(G),S+=A.count,c==="content"){for(const V of A.matches){const J=Buffer.byteLength(V.content,"utf-8")+64;if(y+J>Ct){E=!0;break}y+=J,g.push(V)}if(E)break;if(g.length>=n){E=!0;break}}else c==="count"&&v.push({file:G,count:A.count})}}const k={ok:!0,tool:"grep",pattern:o,searchPath:M(h.targetPath),outputMode:c,filesSearched:T.length,filesMatched:P.length,totalMatches:S,truncated:E};return c==="content"?k.matches=g:c==="files_with_matches"?k.matches=P:k.matches=v,k}}}function Me(e,t,o,i,a,r){const s=t||"unknown",c=[ue(e,a,r),re(e,o,a,r),ce(e,o,a,r),le(e,o,a),he(e),de(e,s,i,a),kt(e)];return i&&c.push(vt(s,i),Pt(s,i),Et(s,i)),c}export{Te as DEFAULT_TOOL_PERMISSION_POLICY,se as EDIT_FAILURE_SNAPSHOT_MAX_BYTES,jt as buildFileResourceKey,Me as createBuiltInFileTools,I as ensureInsideWorkspace,q as fileResourceClaim,xe as getEditFailureSnapshot,ct as resolveWorkspaceTarget};
|
|
4
4
|
|
|
@@ -13,4 +13,6 @@ export interface PreparedShellCommand {
|
|
|
13
13
|
|
|
14
14
|
export declare function resolveUnixCommandShell(env?: NodeJS.ProcessEnv, exists?: (path: string) => boolean): string;
|
|
15
15
|
export declare function shellExecutable(): ShellExecutable;
|
|
16
|
+
|
|
17
|
+
export declare function escapeMisquotedWindowsCmdMetachars(commandText: string): string;
|
|
16
18
|
export declare function prepareShellCommand(commandText: string, workspaceRoot: string, shell: ShellExecutable): Promise<PreparedShellCommand>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as a}from"node:fs";import{countOutputLines as m,LONG_COMMAND_LINE_LIMIT as u,toDisplayPath as d,writeCommandArtifactFile as p}from"./commandArtifacts.js";function f(n){return`'${n.replace(/'/g,"'\\''")}'`}function l(n){return`"${n.replace(/"/g,'""')}"`}function h(n=process.env,t=a){return["/bin/bash","/usr/bin/bash",String(n.SHELL||"").trim(),"/bin/sh"].find(i=>i&&t(i))||"/bin/sh"}function w(){if(process.platform==="win32")return{command:process.env.ComSpec||"cmd.exe",argsPrefix:["/d","/c"],scriptExtension:"cmd",scriptInvocation:t=>`call ${l(t)}`};const n=h();return{command:n,argsPrefix:["-lc"],scriptExtension:"sh",scriptInvocation:t=>`${n} ${f(t)}`}}function x(n){const t=new Set(["^","&","|","<",">"]);let e=!1,i=!1,o=0,r="";for(const c of n){if(c==='"'){const s=o%2===1;e=!e,s||(i=!i),o=0,r+=c;continue}if(c==="\\"){o+=1,r+=c;continue}o=0,!e&&i&&t.has(c)&&(r+="^"),r+=c}return r}function C(n,t){const e=n.endsWith(`
|
|
2
2
|
`)?n:`${n}
|
|
3
3
|
`;return t==="cmd"?`@echo off\r
|
|
4
|
-
${
|
|
4
|
+
${e}`:e}function g(n){return process.platform!=="win32"?n:n.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g,"_")||"workspace"}async function E(n,t,e){const i=e.scriptExtension==="cmd"?x(n):n,o=m(i);if(o<=u)return{commandText:i,originalCommandText:n,commandLineCount:o};const r=await p(g(t),"cmd",e.scriptExtension,C(i,e.scriptExtension));return{commandText:e.scriptInvocation(r),originalCommandText:n,commandLineCount:o,commandFilePath:d(r)}}export{x as escapeMisquotedWindowsCmdMetachars,E as prepareShellCommand,h as resolveUnixCommandShell,w as shellExecutable};
|
|
5
5
|
|