aws-runtime-bridge 1.9.153 → 1.9.168
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 +766 -0
- package/dist/adapter/AcodeSdkAdapter.d.ts +57 -6
- package/dist/adapter/AcodeSdkAdapter.js +4 -8
- 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 -20
- 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/acode-todos.js +1 -1
- 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/ltr.js +1 -1
- 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.d.ts +18 -74
- 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 +24 -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 +26 -2
- 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/services/workspace-watch.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/ask-user-question-tool.js +1 -1
- package/package/acode/dist/await-complete-tool.js +1 -1
- package/package/acode/dist/background-command-manager.js +4 -4
- package/package/acode/dist/background-command-tools.js +1 -1
- package/package/acode/dist/built-in-file-tools.d.ts +31 -2
- package/package/acode/dist/built-in-file-tools.js +2 -2
- package/package/acode/dist/built-in-symbols-tool.js +1 -1
- 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.d.ts +19 -0
- package/package/acode/dist/context-overflow.js +2 -0
- package/package/acode/dist/grammars/grammars/tree-sitter-lua.wasm +0 -0
- package/package/acode/dist/index.d.ts +4 -1
- 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/parsers/ast-cache.d.ts +12 -1
- package/package/acode/dist/parsers/ast-cache.js +1 -1
- package/package/acode/dist/parsers/language-queries.js +1 -1
- package/package/acode/dist/parsers/symbol-extractor.js +2 -2
- package/package/acode/dist/parsers/tree-sitter-loader.d.ts +1 -1
- package/package/acode/dist/parsers/tree-sitter-loader.js +1 -1
- package/package/acode/dist/plugin-types.d.ts +5 -0
- package/package/acode/dist/plugin-types.js +1 -0
- package/package/acode/dist/read-file-state.d.ts +48 -0
- package/package/acode/dist/read-file-state.js +2 -0
- 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 +124 -10
- package/package/acode/dist/runtime.js +27 -23
- package/package/acode/dist/skill-tool.js +3 -3
- package/package/acode/dist/sub-agent-manager.js +1 -1
- package/package/acode/dist/sub-agent-tools.js +5 -5
- package/package/acode/dist/todo-tool.js +3 -3
- package/package/acode/dist/tool-allocation.js +1 -1
- package/package/acode/dist/tool-concurrency/index.d.ts +5 -0
- package/package/acode/dist/tool-concurrency/index.js +2 -0
- package/package/acode/dist/tool-concurrency/observability.d.ts +46 -0
- package/package/acode/dist/tool-concurrency/observability.js +3 -0
- package/package/acode/dist/tool-concurrency/resource-lock.d.ts +25 -0
- package/package/acode/dist/tool-concurrency/resource-lock.js +2 -0
- package/package/acode/dist/tool-concurrency/scheduler.d.ts +30 -0
- package/package/acode/dist/tool-concurrency/scheduler.js +2 -0
- package/package/acode/dist/tool-concurrency/types.d.ts +80 -0
- package/package/acode/dist/tool-concurrency/types.js +2 -0
- package/package/acode/dist/tool-group-manager.d.ts +128 -0
- package/package/acode/dist/tool-group-manager.js +18 -0
- package/package/acode/dist/types.d.ts +20 -2
- package/package/acode/package.json +3 -3
- package/package/aws-client-agent-mcp/README.md +1 -0
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts +20 -32
- 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 +65 -10
- package/package/aws-client-agent-mcp/dist/mcp-server.js +30 -30
- package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +42 -7
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +196 -21
- 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-equation.d.ts +5 -0
- package/package/aws-client-agent-mcp/dist/office/office-equation.js +2 -0
- package/package/aws-client-agent-mcp/dist/office/office-image.d.ts +12 -0
- package/package/aws-client-agent-mcp/dist/office/office-image.js +2 -0
- package/package/aws-client-agent-mcp/dist/office/office-workspace.d.ts +40 -0
- package/package/aws-client-agent-mcp/dist/office/office-workspace.js +2 -0
- 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 +56 -3
- package/package/aws-client-agent-mcp/dist/websocket-client.js +1 -1
- package/package/aws-client-agent-mcp/package.json +2 -1
- package/package.json +1 -1
- package/package/acode/dist/capability-prompt.d.ts +0 -16
- package/package/acode/dist/capability-prompt.js +0 -3
- package/package/acode/dist/plugin-tools.d.ts +0 -14
- package/package/acode/dist/plugin-tools.js +0 -9
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID 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
|
-
`+E:E;return{workspaceRoot:a.workspaceRoot,targetPath:s,content:T,isBinary:!1,truncated:y||m,totalLines:m?-1:g,shownFromLine:h,shownToLine:v}}finally{l.close(),c.destroy()}}function z(n){return/^https?:\/\//i.test(n)}async function Ut(n){let e;try{e=new URL(n)}catch{throw new Error(`Invalid image URL: ${n}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${e.protocol} (only http/https)`);let o;try{o=await fetch(n,{signal:AbortSignal.timeout(Pt)})}catch(l){const u=l instanceof Error?l.message:String(l);throw new Error(`Image URL fetch failed: ${n} (${u})`)}if(!o.ok)throw new Error(`Image URL fetch failed: ${n} (HTTP ${o.status})`);const t=(o.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(t&&!t.startsWith("image/"))throw new Error(`URL did not return an image (content-type: ${t}): ${n}`);const i=Number(o.headers.get("content-length")||"");if(Number.isFinite(i)&&i>A)throw new Error(`Image too large to fetch: ${n} (${S(i)} > ${S(A)})`);const a=o.body;if(!a){const l=await o.arrayBuffer();if(l.byteLength>A)throw new Error(`Image too large to fetch: ${n} (${S(l.byteLength)} > ${S(A)})`);return Buffer.from(l)}const s=a.getReader(),r=[];let c=0;for(;;){const{done:l,value:u}=await s.read();if(l)break;if(u){if(c+=u.byteLength,c>A)throw s.cancel().catch(()=>{}),new Error(`Image too large to fetch: ${n} (${S(c)} > ${S(A)})`);r.push(Buffer.from(u))}}return Buffer.concat(r,c)}async function Dt(n,e,o,t="auto"){let i,a;if(z(e))i=await Ut(e),a=e;else{const x=(await tt(n,e,o)).targetPath,k=await p.stat(x);if(!k.isFile())throw new Error(`Path is not a file: ${x}`);if(k.size>J)throw new Error(`Image file too large to read: ${$(x)} (${S(k.size)} > ${S(J)}). Downscale it first.`);i=await p.readFile(x),a=$(x)}if(i.length===0)throw new Error(`Image file is empty: ${a}`);const s=pt(i);if(!s)throw new Error(`Unsupported or corrupt image (unrecognized format): ${a}`);const r=gt(i);let c=s,l=i,u=r?.width,w=r?.height,g=null;if(t!==!1){const b=await wt(i,s,{normalMaxBytes:xt,clearMaxBytes:Tt});b?.compressed&&(l=b.buffer,c=b.mediaType,u=b.width,w=b.height,g={level:b.level,originalSize:b.originalSize})}let _=!1;const y=await _t(l,c,{maxWidth:C,maxHeight:C,maxBytes:D});if(y)l=y.buffer,c=y.mediaType,u=y.width,w=y.height,_=y.changed;else if(l.length>D)throw new Error(`Image too large to inline: ${a} (${S(l.length)} > ${S(D)}). Downscale it first, e.g. via Bash: magick "${e}" -resize ${C}x${C} "${e}". Installing sharp enables automatic downscaling.`);const m=u&&w?`${u}x${w}`:"unknown dimensions",P=_&&r&&r.width!==u?` (resized from ${r.width}x${r.height})`:_?" (resized)":"",h=g!==null?g.level:null,v=g!==null?Math.max(1,Math.round((1-l.length/g.originalSize)*100)):0,E=g!==null?`${S(l.length)} (compressed from ${S(g.originalSize)}, saved ${v}%, ${h} level)`:S(l.length),T=`[Image: ${a}, ${m}${P}, ${E}]`,f=z(e)?d.basename(new URL(e).pathname)||"image":d.basename(a);return{ok:!0,filePath:a,content:T,isBinary:!1,image:{mediaType:K(c),width:u??null,height:w??null,originalWidth:r?.width??null,originalHeight:r?.height??null,resized:_,size:l.length,compressed:g!==null,compressionLevel:h,compressionRatio:g!==null?Math.round((1-l.length/g.originalSize)*100)/100:null,originalSize:i.length},attachments:[{type:"image",name:f,mediaType:K(c),base64Data:l.toString("base64")}]}}function ot(n){let e="",o=0;for(;o<n.length;){const t=n[o];if(t==="*")e+="[^/]*";else if(t==="?")e+="[^/]";else if(t==="{"){const i=n.indexOf("}",o);if(i>=0){const a=n.slice(o+1,i);e+=`(${a.split(",").join("|")})`,o=i}else e+="\\{"}else if(t==="["){const i=n.indexOf("]",o);i>=0?(e+=n.slice(o,i+1),o=i):e+="\\["}else"+^$.()|\\".includes(t)?e+="\\"+t:e+=t;o++}return new RegExp(`^${e}$`)}async function Wt(n,e,o,t){const i=[];async function a(s){if(i.length>=t)return;const r=await p.readdir(s,{withFileTypes:!0});for(const c of r){if(i.length>=t)return;if(c.name.startsWith(".")&&c.isDirectory())continue;const l=d.join(s,c.name);if(c.isDirectory()){if(It.has(c.name))continue;await a(l)}else if(c.isFile()){if(e&&!e.test(c.name)||o&&o.test(c.name))continue;i.push(l)}}}return await a(n),i}async function zt(n,e,o){if((await p.stat(n)).size>$t)return{matches:[],count:0};if(await Q(n))return{matches:[],count:0};const i=d.relative(e,n).replace(/\\/g,"/"),a=[];let s=0;const r=X(n,{encoding:"utf-8"}),c=Y.createInterface({input:r,crlfDelay:1/0});try{let l=0;for await(const u of c)if(l++,o.regex.test(u)){if(s++,o.collectContent){let w=u;if(w.length>L&&(w=w.slice(0,L)+`... (line truncated to ${L} chars)`),a.push({file:i,line:l,content:w}),a.length>=o.maxResults)break}if(o.stopOnFirstMatch)break}}finally{c.close(),r.destroy()}return{matches:a,count:s}}const qt=12*60*6e4,jt=30*6e4,Gt=6e4,Xt=10*6e4;function Yt(n,e,o){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",description:"Create or overwrite a UTF-8 text file inside the current workspace. Parent directories are created automatically.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to write."},content:{type:"string",description:"Complete UTF-8 file content."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","content"],additionalProperties:!1},async execute(t){const i=M(t,["file_path","filePath"],"file_path"),a=M(t,["content"],"content"),s=R(t,["reason"]),r=await B(n,i);await N(o,"fileModification",{operation:"write",path:r.targetPath});const c=await Z(r.targetPath),l=c?await p.readFile(r.targetPath,"utf-8").catch(()=>null):null,u=await et(n,i,a);if(e){const w=d.relative(u.workspaceRoot,u.targetPath).replace(/\\/g,"/");await e({filePath:w,operation:c?"UPDATE":"CREATE",beforeContent:l,afterContent:a,reason:s})}return{ok:!0,filePath:$(u.targetPath),bytes:u.bytes,createdParentDirectory:u.createdParentDirectory}}}}function Ht(n,e,o){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",description:"Replace exactly one occurrence of old_string with new_string in a UTF-8 workspace text file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to edit."},old_string:{type:"string",description:"Existing text to replace. Must occur exactly once."},new_string:{type:"string",description:"Replacement text."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","old_string","new_string"],additionalProperties:!1},async execute(t){const i=M(t,["file_path","filePath"],"file_path"),a=M(t,["old_string","oldString"],"old_string"),s=M(t,["new_string","newString"],"new_string"),r=R(t,["reason"]);if(!a)throw new Error("old_string must not be empty");const c=await B(n,i);await N(o,"fileModification",{operation:"edit",path:c.targetPath});const l=await Ft(n,i),u=Ot(l.content,a);if(u===0)throw new Error("old_string was not found in file");if(u>1)throw new Error(`old_string occurs ${u} times; provide a unique match`);const w=l.content.replace(a,s),g=await et(n,i,w);if(e){const _=d.relative(g.workspaceRoot,g.targetPath).replace(/\\/g,"/");await e({filePath:_,operation:"UPDATE",beforeContent:l.content,afterContent:w,reason:r})}return{ok:!0,filePath:$(g.targetPath),bytes:g.bytes}}}}function Kt(n,e,o){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",description:"Delete a file inside the current workspace. Returns an error if the file does not exist.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to delete."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path"],additionalProperties:!1},async execute(t){const i=M(t,["file_path","filePath"],"file_path"),a=R(t,["reason"]),s=await B(n,i);await N(o,"fileModification",{operation:"delete",path:s.targetPath});const r=O(s.workspaceRoot,await p.realpath(s.targetPath).catch(()=>s.targetPath)),c=await p.stat(r).catch(()=>null);if(!c)throw new Error(`File does not exist: ${r}`);if(!c.isFile())throw new Error(`Path is not a file: ${r}`);const l=await p.readFile(r,"utf-8").catch(()=>null);if(await p.rm(r,{force:!0}),e){const u=d.relative(s.workspaceRoot,r).replace(/\\/g,"/");await e({filePath:u,operation:"DELETE",beforeContent:l,afterContent:null,reason:a})}return{ok:!0,filePath:$(r),deleted:!0}}}}function Vt(n,e){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",description:"Read a UTF-8 text file inside the current workspace. Returns content with line numbers in the format '<line>: <content>'. Supports offset (1-indexed line number to start from) and limit (max lines to return, default 2000). Output is capped at 2000 lines or 50 KB, whichever is reached first. Individual lines longer than 2000 characters are truncated. Avoid tiny repeated slices (e.g. 30-line chunks); read a larger window if more context is needed. Images (.png/.jpg/.jpeg/.gif/.webp) and http(s) image URLs are also supported: the image is inlined into the conversation so you can see it (requires a model with image input). offset/limit are ignored for images. 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).",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(o){const t=M(o,["file_path","filePath"],"file_path"),i=d.extname(t).toLowerCase().slice(1);if(z(t)||Et.has(i))return await Dt(n,t,e,At(o));const a=U(o,["offset"],1),s=U(o,["limit"],yt),r=await Ct(n,t,a,s,e);return{ok:!0,filePath:$(r.targetPath),content:r.content,isBinary:r.isBinary,truncated:r.truncated,totalLines:r.totalLines,shownFromLine:r.shownFromLine,shownToLine:r.shownToLine}}}}function Jt(n,e,o,t){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded total timeout (timeout_ms) measured from command start \u2014 by default 30 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 30 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 1800000 (30 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 30 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(i,a){const s=M(i,["command"],"command").trim();if(!s)throw new Error("command must not be empty");const r=Lt(i,["timeout_ms","timeoutMs"],jt),c=r===0?0:Math.min(r,qt),l=U(i,["inactivity_timeout_ms","inactivityTimeoutMs"],Gt),u=Math.min(l,Xt),w=R(i,["cwd"]),g=R(i,["description"]),_=await Bt(n,w);await N(t,"commandExecution",{command:s,cwd:$(_.cwd)});const y=i.wait_seconds,P=typeof y=="number"&&Number.isFinite(y)?y:-1;if(o)return await Zt({deps:o,command:s,agentId:e,workspaceRoot:_.workspaceRoot,cwd:_.cwd,timeoutMs:c,inactivityTimeoutMs:u,waitSeconds:P,description:g,onOutput:a?.onOutput,settleSignal:a?.settleSignal});const h=await at({commandText:s,agentId:e,workspaceRoot:_.workspaceRoot,cwd:_.cwd,timeoutMs:c,inactivityTimeoutMs:u,onOutput:a?.onOutput,watchdogSignal:a?.settleSignal}),v={ok:h.exitCode===0&&!h.timedOut,tool:"Bash",command:s,cwd:$(_.cwd),exitCode:h.exitCode,signal:h.signal,timedOut:h.timedOut,inactivityTimedOut:h.inactivityTimedOut,watchdogInterrupted:h.watchdogInterrupted,timeoutMs:c,inactivityTimeoutMs:u,durationMs:h.durationMs,outputSpilled:h.outputSpilled,outputFilePath:h.outputFilePath,outputLineCount:h.outputLineCount,commandFilePath:h.commandFilePath,commandLineCount:h.commandLineCount,stdout:h.stdout,stderr:h.stderr};return h.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"+(h.outputFilePath?` (full output spilled to "${h.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 Zt(n){const{deps:e,command:o,agentId:t,workspaceRoot:i,cwd:a,timeoutMs:s,inactivityTimeoutMs:r,waitSeconds:c,description:l,onOutput:u,settleSignal:w}=n,g=u?rt({cwd:a,commandLineCount:0,onOutput:u}):void 0;let _=!!g;const y=()=>{_&&(_=!1,g?.close())};try{const{taskId:m,completion:P}=e.manager.startCommand({commandText:o,agentId:t,workspaceRoot:i,cwd:a,description:l,timeoutMs:s,inactivityTimeoutMs:r,onOutput:_?T=>{_&&g?.push(T.stream,T.text)}:void 0,onCompleted:e.emitCompleted});if(c===0)return e.manager.disableInactivityTimeout(t,m),await e.manager.markBackgrounded(t,m).catch(()=>{}),y(),{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 h=c===-1?0:Math.max(0,Math.floor(c*1e3)),v=[P];let E;c!==-1&&v.push(new Promise(T=>{E=setTimeout(()=>T("__timeout__"),h),E.unref?.()})),w&&v.push(w.then(()=>"__settle__"));try{const T=await Promise.race(v);if(T==="__settle__")return e.manager.disableInactivityTimeout(t,m),await e.manager.markBackgrounded(t,m).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:m,status:"backgrounded",reason:"watchdog_timeout",waitedMs:h,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(T==="__timeout__")return e.manager.disableInactivityTimeout(t,m),await e.manager.markBackgrounded(t,m).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:m,status:"backgrounded",reason:"timeout",waitedMs:h,message:`Command still running after ${c}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 f=T;let b=f.stdout,x=f.stderr,k=f.outputSpilled,F=f.outputFilePath;if(!k&&H(`${f.stdout}${f.stderr}`)>ct){const I=await ut(t,"cmd","out",st({commandText:o,commandFilePath:f.commandFilePath,commandLineCount:f.commandLineCount,cwd:a,startedAt:new Date(Date.now()-f.durationMs),endedAt:new Date,exitCode:f.exitCode,signal:f.signal??null,timedOut:f.timedOut,inactivityTimedOut:f.inactivityTimedOut??!1,stdout:b,stderr:x}));b=lt($(I),H(`${f.stdout}${f.stderr}`)),k=!0,F=$(I)}return{ok:f.exitCode===0&&!f.timedOut,tool:"Bash",command:o,backgrounded:!1,taskId:m,exitCode:f.exitCode,signal:f.signal,timedOut:f.timedOut,inactivityTimedOut:f.inactivityTimedOut,timeoutMs:f.timeoutMs,inactivityTimeoutMs:f.inactivityTimeoutMs,durationMs:f.durationMs,outputSpilled:k,outputFilePath:F,outputLineCount:f.outputLineCount,commandFilePath:f.commandFilePath,commandLineCount:f.commandLineCount,stdout:b,stderr:x}}finally{E&&clearTimeout(E),y()}}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 Qt(n){return{kind:"builtin",toolName:"grep",exposedName:"grep",description:"Search file contents using regular expressions within the workspace. Returns matched lines with file paths and line numbers. Supports include/exclude glob patterns, case-insensitive matching, and three output modes (content, files_with_matches, count). Searches recursively through directories, skipping binary files, hidden directories, and common build/dependency directories (node_modules, .git, dist, etc.).",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for in file contents."},path:{type:"string",description:"Workspace-relative file or directory path to search in. Defaults to the workspace root."},include:{type:"string",description:"Glob pattern to filter files by name (e.g. '*.ts', '*.{js,ts}'). Only matching files are searched."},exclude:{type:"string",description:"Glob pattern to exclude files by name (e.g. '*.test.ts'). Matching files are skipped."},case_insensitive:{type:"boolean",description:"Case-insensitive matching. Default false."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output format: 'content' returns matched lines with line numbers (default), 'files_with_matches' returns only file paths with matches, 'count' returns match counts per file."},max_results:{type:"number",description:"Maximum number of matched lines to return (content mode). Default 1000."}},required:["pattern"],additionalProperties:!1},async execute(e){const o=M(e,["pattern"],"pattern"),t=R(e,["path"])||".",i=R(e,["include"]),a=R(e,["exclude"]),s=e.case_insensitive===!0,r=(()=>{const k=e.output_mode;return k==="files_with_matches"||k==="count"?k:"content"})(),c=U(e,["max_results"],Rt),l=s?"i":"";let u;try{u=new RegExp(o,l)}catch(k){throw new Error(`Invalid regex pattern: ${k instanceof Error?k.message:String(k)}`)}const w=i?ot(i):null,g=a?ot(a):null,_=await B(n,t),y=O(_.workspaceRoot,await p.realpath(_.targetPath)),m=await p.stat(y);let P;if(m.isFile())P=[y];else if(m.isDirectory())P=await Wt(y,w,g,St);else throw new Error(`Path is neither a file nor a directory: ${y}`);const h=[],v=[],E=[];let T=0,f=0,b=!1;for(const k of P){if(r==="content"&&h.length>=c){b=!0;break}const F={regex:u,maxResults:r==="content"?c-h.length:Number.MAX_SAFE_INTEGER,collectContent:r==="content",stopOnFirstMatch:r==="files_with_matches"},I=await zt(k,_.workspaceRoot,F);if(I.count>0){const q=d.relative(_.workspaceRoot,k).replace(/\\/g,"/");if(E.push(q),T+=I.count,r==="content"){for(const j of I.matches){const G=Buffer.byteLength(j.content,"utf-8")+64;if(f+G>Mt){b=!0;break}f+=G,h.push(j)}if(b)break;if(h.length>=c){b=!0;break}}else r==="count"&&v.push({file:q,count:I.count})}}const x={ok:!0,tool:"grep",pattern:o,searchPath:$(_.targetPath),outputMode:r,filesSearched:P.length,filesMatched:E.length,totalMatches:T,truncated:b};return r==="content"?x.matches=h:r==="files_with_matches"?x.matches=E:x.matches=v,x}}}function me(n,e,o,t,i){const a=e||"unknown",s=[Vt(n,i),Yt(n,o,i),Ht(n,o,i),Kt(n,o,i),Qt(n),Jt(n,a,t,i),dt(n)];return t&&s.push(mt(a,t),ht(a,t),ft(a,t)),s}export{de as DEFAULT_TOOL_PERMISSION_POLICY,me as createBuiltInFileTools,O as ensureInsideWorkspace,B 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
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{buildFileResourceKey as a}from"./built-in-file-tools.js";import{extractSymbols as l}from"./parsers/symbol-extractor.js";const u="Query code symbols (definitions, references, outline) by parsing file AST via tree-sitter. Unlike grep (text matching), this tool understands syntax structure \u2014 no false positives from comments/strings, and it knows whether 'foo' is a function, class, variable, or method. Supports 13 languages: TypeScript, JavaScript, Python, Go, Rust, Java, C, C++, C#, Ruby, PHP, Lua, Bash. Single-file scope (no cross-file reference resolution). Falls back to grep for files in unsupported languages.\n\nWhen to use `symbols` vs `grep`:\n- Use `symbols` when you need to find function/class/method **declarations** or their **type-aware usages** in supported languages. It avoids false positives from comments/strings.\n- Use `grep` for: cross-file text search, unsupported languages (e.g., Markdown, YAML), searching non-symbol patterns (TODOs, log strings, config values), or when `symbols` returns \"unsupported language\".";function h(t){return{kind:"builtin",toolName:"symbols",exposedName:"symbols",concurrencyMode:"read",resourceKeys:e=>{const n=e.path;return typeof n!="string"||n.trim().length===0?[]:[{key:a(t,n.trim()),access:"read"}]},description:u,inputSchema:{type:"object",properties:{path:{type:"string",description:"Workspace-relative file path to analyze. Must be a single file (not a directory)."},mode:{type:"string",enum:["definitions","references","outline"],description:"Query mode: 'definitions' finds symbol declarations matching pattern/kind (e.g., function/class/method declarations); 'references' finds all usages of symbols matching pattern (e.g., calls, type annotations, assignments); 'outline' returns the full symbol structure of the file (ignores pattern/kind filters)."},pattern:{type:"string",description:"Optional regex to filter symbol names (case-sensitive by default; use (?i) prefix for case-insensitive). In 'outline' mode this is ignored. Example: '^getUser' matches getUserById, getUserByEmail."},kind:{type:"string",enum:["function","class","method","variable","import","all"],description:"Symbol kind filter. 'all' (default) returns all kinds. Note: not all languages distinguish all kinds (e.g., Bash has no 'class')."},max_results:{type:"number",description:"Maximum number of symbols to return. Default 100."}},required:["path","mode"],additionalProperties:!1},async execute(e){const n=c(e,["path"],"path"),s=d(e),r=f(e,["pattern"]),o=m(e),i=p(e,["max_results"],100);return l(t,n,s,{pattern:r,kind:o,maxResults:i})}}}function c(t,e,n){for(const s of e){const r=t[s];if(typeof r=="string")return r}throw new Error(`${n} is required`)}function f(t,e){for(const n of e){const s=t[n];if(typeof s=="string"&&s.trim())return s}}function d(t){const e=t.mode;if(e==="definitions"||e==="references"||e==="outline")return e;throw new Error("mode must be one of: definitions, references, outline")}function m(t){const e=t.kind;if(e==null||e==="all")return"all";if(e==="function"||e==="class"||e==="method"||e==="variable"||e==="import"||e==="error")return e;throw new Error("kind must be one of: function, class, method, variable, import, all")}function p(t,e,n){for(const s of e){const r=t[s],o=typeof r=="number"?r:typeof r=="string"?Number(r):NaN;if(Number.isFinite(o)&&o>0)return Math.floor(o)}return n}export{h as symbolsTool};
|
|
2
2
|
|
|
@@ -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
|
|
|
@@ -10,6 +10,8 @@ export declare const PRUNE_PROTECT = 40000;
|
|
|
10
10
|
|
|
11
11
|
export declare const PRUNE_MINIMUM = 20000;
|
|
12
12
|
|
|
13
|
+
export declare const RUNTIME_RESOURCES_PREFIX = "ACode runtime resources:";
|
|
14
|
+
|
|
13
15
|
export declare const COMPACTION_LLM_PROMPT_TEMPLATE: string;
|
|
14
16
|
interface ChatMessageLike {
|
|
15
17
|
role: "system" | "user" | "assistant" | "tool";
|
|
@@ -63,6 +65,8 @@ export type LLMSummarizer = (input: {
|
|
|
63
65
|
|
|
64
66
|
export declare function calculateCompactionThreshold(contextLimit: number, maxOutput: number, inputLimit?: number): number;
|
|
65
67
|
|
|
68
|
+
export declare function resolveReplayWindow(contextLimit: number, inputLimit?: number): number;
|
|
69
|
+
|
|
66
70
|
export declare function lookupModelLimits(modelName: string, configOverrides?: {
|
|
67
71
|
contextLimit?: number;
|
|
68
72
|
maxOutput?: number;
|
|
@@ -75,6 +79,8 @@ export declare function estimateTextTokens(text: string): number;
|
|
|
75
79
|
|
|
76
80
|
export declare function estimateTokens(text: string): number;
|
|
77
81
|
|
|
82
|
+
export declare function conversationSizeBytes(messages: readonly ChatMessageLike[]): number;
|
|
83
|
+
|
|
78
84
|
export declare function estimateConversationTokens(messages: readonly ChatMessageLike[]): number;
|
|
79
85
|
|
|
80
86
|
export declare function conversationSizeKB(messages: readonly ChatMessageLike[]): number;
|
|
@@ -88,6 +94,10 @@ export declare function pruneToolOutputs(messages: ChatMessageLike[], contextLim
|
|
|
88
94
|
freedTokens: number;
|
|
89
95
|
};
|
|
90
96
|
|
|
97
|
+
export declare function isCompactionSummaryMessage(message: ChatMessageLike): boolean;
|
|
98
|
+
|
|
99
|
+
export declare function isRuntimeResourcesMessage(message: ChatMessageLike): boolean;
|
|
100
|
+
|
|
91
101
|
export declare function summarizeConversation(messages: ChatMessageLike[], options?: {
|
|
92
102
|
llmSummarizer?: LLMSummarizer;
|
|
93
103
|
contextLimit?: number;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
const
|
|
2
|
-
`)
|
|
3
|
-
`);
|
|
4
|
-
`)});else{const
|
|
5
|
-
`).slice(0,
|
|
6
|
-
`)})}return t.push(...i),
|
|
1
|
+
const st=2e4,lt=.55,B=[[32e3,.7],[128e3,.75],[512e3,.8],[Number.POSITIVE_INFINITY,.85]];function T(t){if(t<=0)return .55;for(const[e,o]of B)if(t<e)return o;return .85}const j=4e4,F=2e4,G=.5,K=.1,W=new Set(["skill","todo_write","todo_read"]),y={read_file:0,Read:0,grep:0,Grep:0,glob:0,Glob:0,"contextweaver_codebase-retrieval":0,Edit:1,edit:1,Write:1,write:1,write_file:1,webfetch:2,WebFetch:2,WebSearch:2,websearch_web_search_exa:2,bash:3,Bash:3,run_terminal_command:3,playwright_browser_:4},k=2;function D(t){if(!t)return k;if(y[t]!==void 0)return y[t];const e=Object.keys(y).filter(o=>t.startsWith(o)).sort((o,n)=>n.length-o.length);return e.length>0?y[e[0]]:k}const M=128e3,C=8192,$=8,X=6e3,b=500,L="ACode context compaction summary:",J="ACode runtime resources:",ct=["Please summarize the conversation above using the following structured format.","Keep each section concise but preserve all actionable details.","Omit any section that has no relevant content.","","## Goal","The user's primary objective in this conversation (1-2 sentences).","","## Known Facts","Key facts already established: decisions, findings, errors, constraints, and user-stated preferences.","","## Done","Tasks that have been completed (do not redo these).","","## In Progress","What is currently being worked on but not yet finished: which step it stopped at and any partial results.","","## Next Steps","The immediate next actions to take to continue the work.","","## Files","Files read, modified, or created with brief context.","","Output only the summary, no preamble."].join(`
|
|
2
|
+
`),H=1.5,R=4,q=1.15,V=2e3,Y=8;function at(t,e,o){const n=Math.floor(t*T(t)),s=o??t,l=Math.min(2e4,e),i=s-l;return Math.min(n,i)}function ut(t,e){const o=e&&e>0?e:t;return o>0?o:t}const g={"claude-4":{contextLimit:2e5,maxOutput:8192},"claude-sonnet-4":{contextLimit:2e5,maxOutput:8192},"claude-3-5-sonnet":{contextLimit:2e5,maxOutput:8192},"claude-3-opus":{contextLimit:2e5,maxOutput:8192},"claude-3-haiku":{contextLimit:2e5,maxOutput:8192},"claude-2":{contextLimit:1e5,maxOutput:4096},"gpt-4o":{contextLimit:128e3,maxOutput:16384},"gpt-4-turbo":{contextLimit:128e3,maxOutput:4096},"gpt-4":{contextLimit:8192,maxOutput:4096},"gpt-3.5-turbo":{contextLimit:16384,maxOutput:4096},o1:{contextLimit:2e5,maxOutput:1e5},"o3-mini":{contextLimit:2e5,maxOutput:1e5},"gemini-2.0-flash":{contextLimit:1048576,maxOutput:8192},"gemini-2.5-pro":{contextLimit:1048576,maxOutput:8192},"gemini-1.5-pro":{contextLimit:2097152,maxOutput:8192},"gemini-1.5-flash":{contextLimit:1048576,maxOutput:8192},deepseek:{contextLimit:64e3,maxOutput:8192},"deepseek-chat":{contextLimit:64e3,maxOutput:8192},"deepseek-reasoner":{contextLimit:64e3,maxOutput:8192},"qwen-max":{contextLimit:32e3,maxOutput:8192},"qwen-plus":{contextLimit:128e3,maxOutput:8192},"qwen-turbo":{contextLimit:1e6,maxOutput:8192},"glm-4":{contextLimit:128e3,maxOutput:4096},"yi-":{contextLimit:2e5,maxOutput:4096},"llama-3":{contextLimit:8192,maxOutput:4096},"llama-2":{contextLimit:4096,maxOutput:4096},mistral:{contextLimit:32e3,maxOutput:4096},mixtral:{contextLimit:32e3,maxOutput:4096},codestral:{contextLimit:256e3,maxOutput:8192},grok:{contextLimit:131072,maxOutput:4096},"nova-":{contextLimit:2e5,maxOutput:8192}};function ft(t,e){if(e?.contextLimit&&e.contextLimit>0)return{contextLimit:e.contextLimit,maxOutput:e.maxOutput??C};if(!t)return{contextLimit:M,maxOutput:C};const o=t.toLowerCase().trim();if(g[o])return g[o];const n=Object.keys(g).filter(s=>o.startsWith(s)).sort((s,l)=>l.length-s.length);return n.length>0?g[n[0]]:{contextLimit:M,maxOutput:C}}function Q(t){if(!t)return 0;let e=0,o=0;for(const n of t)n>"\xFF"?e++:o++;return Math.ceil(e/H+o/R)}function A(t){return t?Math.ceil(Q(t)*q):0}function Z(t){if(typeof t=="object"&&t!==null){const e=t;return e.type==="text"&&typeof e.text=="string"?A(e.text):e.type==="image_url"||e.type==="document"?V:Math.ceil(JSON.stringify(t).length/R)}return typeof t=="string"?A(t):0}function I(t){return Buffer.byteLength(t,"utf8")}function N(t){let e=16;if(typeof t.content=="string")e+=I(t.content);else if(Array.isArray(t.content))for(const o of t.content)typeof o=="object"&&o!==null&&(e+=I(JSON.stringify(o)));return t.tool_calls&&(e+=I(JSON.stringify(t.tool_calls))),t.tool_call_id&&(e+=I(t.tool_call_id)),e}function _t(t){let e=0;for(const o of t)e+=N(o);return e}function x(t){let e=0;for(const o of t){if(typeof o.content=="string")e+=A(o.content);else if(Array.isArray(o.content))for(const n of o.content)e+=Z(n);o.tool_calls&&(e+=Y+Math.ceil(JSON.stringify(o.tool_calls).length/R))}return e}function v(t){let e=0;for(const o of t)e+=N(o);return Math.round(e/1024*10)/10}function mt(t,e,o){if(e<=0)return!1;const n=x(t),s=Math.floor(e*T(e));return n>=s}function pt(t,e,o){if(o<=0)return!1;const n=t+e,s=Math.floor(o*T(o));return n>=s}function tt(t){return t.role==="tool"}function et(t,e,o){if(!(t.role!=="tool"||!t.tool_call_id))for(let n=o-1;n>=0;n--){const s=e[n];if(s&&s.role==="assistant"&&Array.isArray(s.tool_calls)){for(const l of s.tool_calls)if(typeof l=="object"&&l!==null&&"id"in l&&l.id===t.tool_call_id){const i=l.function;return i?String(i.name??""):void 0}}}}function ot(t,e=M){if(t.length===0)return{prunedCount:0,freedTokens:0};const o=Math.min(j,Math.floor(e*G)),n=Math.min(F,Math.floor(e*K));let s=0;const l=[],i=[];let a=0;for(let r=t.length-1;r>=0;r--){const c=t[r];if(c.role==="user"&&a++,a<2||!tt(c))continue;const _=et(c,t,r);if(_&&W.has(_))continue;const u=typeof c.content=="string"?c.content:"",p=A(u);if(s+=p,s>o){const h=_?D(_):k,d={msg:c,tokens:p,name:_??""};h<=1?i.push(d):l.push(d)}}l.sort((r,c)=>c.tokens-r.tokens),i.sort((r,c)=>r.tokens-c.tokens);const f=[];let m=0;for(const r of l){if(m>=n)break;m+=r.tokens,f.push(r.msg)}if(m<n){for(const r of i)if(m+=r.tokens,f.push(r.msg),m>=n)break}if(m<n)return{prunedCount:0,freedTokens:0};for(const r of f)r.content="[Old tool result content cleared]";return{prunedCount:f.length,freedTokens:m}}function z(t){return t.role==="system"&&typeof t.content=="string"&&t.content.startsWith(L)}function nt(t){return t.role==="system"&&typeof t.content=="string"&&t.content.startsWith(J)}function U(t,e){const o=typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l)).join(" "):"",n=o.length>b?`${o.slice(0,b)}\u2026`:o,s=[`${e+1}. ${t.role}`];if(t.tool_calls&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0){const l=t.tool_calls.map(i=>{if(typeof i=="object"&&i!==null){const a=i.function;return a?String(a.name??""):""}return""}).filter(Boolean).join(", ");l&&s.push(`tool_calls=${l}`)}return t.tool_call_id&&s.push(`tool_call_id=${t.tool_call_id}`),n&&s.push(`content=${n}`),s.join(" | ")}async function rt(t,e){const o=t.filter(r=>r.role==="system"&&!z(r)&&!nt(r)),n=t.filter(r=>r.role!=="system"||z(r)),s=Math.max(0,n.length-$);if(s===0)return 0;const l=n.slice(0,s);let i=n.slice(s);const a=new Set;for(const r of i)if(r.role==="assistant"&&r.tool_calls?.length)for(const c of r.tool_calls)typeof c=="object"&&c!==null&&typeof c.id=="string"&&a.add(c.id);i=i.filter(r=>{if(r.role==="tool"){const c=typeof r.tool_call_id=="string"?r.tool_call_id.trim():"";return c!==""&&a.has(c)}return!0});let f=!0;for(;f;){f=!1;const r=new Set;for(const u of i)if(u.role==="assistant"&&u.tool_calls?.length)for(const p of u.tool_calls)typeof p=="object"&&p!==null&&typeof p.id=="string"&&r.add(p.id);const c=new Set;for(const u of i)u.role==="tool"&&u.tool_call_id&&c.add(u.tool_call_id);const _=i.filter(u=>{if(u.role==="tool"){const p=typeof u.tool_call_id=="string"?u.tool_call_id.trim():"";return p!==""&&r.has(p)}if(u.role==="assistant"&&u.tool_calls?.length){const p=new Set;for(const d of u.tool_calls)typeof d=="object"&&d!==null&&typeof d.id=="string"&&p.add(d.id);if(p.size===0)return!0;let h=!0;for(const d of p)if(!c.has(d)){h=!1;break}return h}return!0});_.length!==i.length&&(f=!0,i=_)}if(i.length===0)return 0;let m=null;if(e?.llmSummarizer)try{const r=l.map((c,_)=>U(c,_)).join(`
|
|
3
|
+
`);m=await e.llmSummarizer({conversationText:r,messageCount:s,contextLimit:e.contextLimit??M})}catch{m=null}if(t.length=0,t.push(...o),m!==null)t.push({role:"system",content:[L,`${s} earlier conversation messages were summarized by LLM to free context space.`,"Preserve the user's goal, known facts, completed work, in-progress work, next steps, file paths, and errors from this summary.","Continue from where the work left off \u2014 do not redo completed tasks.","Recent messages below remain authoritative.","",m].join(`
|
|
4
|
+
`)});else{const c=l.map((_,u)=>U(_,u)).join(`
|
|
5
|
+
`).slice(0,X);t.push({role:"system",content:[L,`${s} earlier conversation messages were summarized to free context space.`,"Preserve the user's goal, known facts, completed work, in-progress work, next steps, file paths, and errors from this summary.","Continue from where the work left off \u2014 do not redo completed tasks.","Recent messages below remain authoritative.","",c].join(`
|
|
6
|
+
`)})}return t.push(...i),s}function it(t){if(t.length<=1)return 0;let e=0;for(;e<t.length&&t[e].role==="system";)e++;if(e>=t.length)return 0;let o=t.length;for(let i=e+1;i<t.length;i++)if(t[i].role==="user"){o=i;break}if(o>=t.length)return 0;const n=new Set;for(let i=e;i<o;i++){const a=t[i];if(a.role==="assistant"&&Array.isArray(a.tool_calls))for(const f of a.tool_calls)typeof f=="object"&&f!==null&&typeof f.id=="string"&&n.add(f.id)}const s=o-e;t.splice(e,s);let l=0;for(let i=t.length-1;i>=e;i--){const a=t[i];if(a.role!=="tool")continue;const f=typeof a.tool_call_id=="string"?a.tool_call_id.trim():"";(f===""||n.has(f))&&(t.splice(i,1),l++)}return s+l}async function dt(t,e,o=C,n){const s=v(t),l=t.length,i=x(t);let a="none",f=0,m=0,r=0,c=!1;n?.onPhase&&n.onPhase({phase:"prune_start",messageCount:t.length});const _=ot(t,e);_.prunedCount>0&&(a="prune",f=_.prunedCount,r+=_.freedTokens),n?.onPhase&&n.onPhase({phase:"prune_end",prunedCount:_.prunedCount,freedTokens:_.freedTokens});const u=x(t);if((n?.actualUsedTokens?Math.max(u,Math.max(n.actualUsedTokens,i)-r):u)>=Math.floor(e*T(e))){n?.onPhase&&n.onPhase({phase:"summarize_start",messageCount:t.length});const w=await rt(t,{llmSummarizer:n?.llmSummarizer,contextLimit:e});if(w>0){a=a==="prune"?"prune+summarize":"summarize",m=w;const O=x(t);r=Math.max(r,i-O),c=!!t.find(E=>E.role==="system"&&typeof E.content=="string"&&E.content.includes("summarized by LLM"))}else{const O=it(t);if(O>0){a=a==="prune"?"prune+summarize":"summarize",m=O;const P=x(t);r=Math.max(r,i-P)}}n?.onPhase&&n.onPhase({phase:"summarize_end",summarizedCount:m,usedLLM:c})}const h=v(t),d=t.length,S=x(t);return a==="none"?{strategy:"none",freedTokens:0,sizeBeforeKB:s,sizeAfterKB:s,tokensBefore:i,tokensAfter:S,messageCountBefore:l,messageCountAfter:d,prunedToolMessages:0,summarizedMessages:0}:{strategy:a,freedTokens:r,sizeBeforeKB:s,sizeAfterKB:h,tokensBefore:i,tokensAfter:S,messageCountBefore:l,messageCountAfter:d,prunedToolMessages:f,summarizedMessages:m}}export{st as COMPACTION_BUFFER,ct as COMPACTION_LLM_PROMPT_TEMPLATE,lt as COMPACTION_TRIGGER_RATIO,F as PRUNE_MINIMUM,j as PRUNE_PROTECT,J as RUNTIME_RESOURCES_PREFIX,at as calculateCompactionThreshold,_t as conversationSizeBytes,v as conversationSizeKB,x as estimateConversationTokens,Q as estimateTextTokens,A as estimateTokens,T as getCompactionTriggerRatio,z as isCompactionSummaryMessage,mt as isOverflow,pt as isOverflowByActualUsage,nt as isRuntimeResourcesMessage,ft as lookupModelLimits,dt as performCompaction,ot as pruneToolOutputs,ut as resolveReplayWindow,it as snipOldestMessageGroup,rt as summarizeConversation};
|
|
7
7
|
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
export type FinishReasonOverflowDecision = {
|
|
4
|
+
kind: "none";
|
|
5
|
+
} | {
|
|
6
|
+
kind: "output_limit";
|
|
7
|
+
marker: string;
|
|
8
|
+
} | {
|
|
9
|
+
kind: "context_overflow";
|
|
10
|
+
marker: string;
|
|
11
|
+
source: "finish_reason" | "stop_reason";
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export declare function resolveFinishReasonOverflow(input: {
|
|
15
|
+
finishReason?: string | null;
|
|
16
|
+
stopReason?: string | null;
|
|
17
|
+
}): FinishReasonOverflowDecision;
|
|
18
|
+
|
|
19
|
+
export declare function isContextOverflowError(error: unknown): boolean;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const x=new Set(["length","max_tokens","max_output_tokens","max_completion_tokens","max_tokens_reached","output_limit","output_token_limit","token_limit"]),f=new Set(["context_exceeded","context_length_exceeded","context_window_exceeded","model_context_window_exceeded","max_context_length_exceeded","context_overflow","prompt_too_long","input_too_long","payload_too_large","request_entity_too_large"]),p=["context_length_exceeded","context length","maximum context","max context","token limit","tokens exceed","too many tokens","input is too long","prompt is too long","request too large","payload too large","entity too large","413"],g=6,_=["type","code","reason","stopReason","stop_reason","name"];function R(e){const t=[{source:"finish_reason",value:e.finishReason},{source:"stop_reason",value:e.stopReason}];for(const n of t){const o=i(n.value);if(o&&x.has(o))return{kind:"output_limit",marker:o}}for(const n of t){const o=i(n.value);if(o&&f.has(o))return{kind:"context_overflow",marker:o,source:n.source}}return{kind:"none"}}function h(e){let t=e;const n=new WeakSet;for(let o=0;o<=g;o+=1){if(t==null)return!1;if(typeof t=="string")return!!l(t);if(typeof t!="object"||n.has(t))return!1;n.add(t);const r=t;for(const c of _){const s=i(a(r[c]));if(s&&f.has(s))return!0}if(u(r.statusCode)||u(r.status))return!0;for(const c of["context","error","details"]){const s=r[c];if(k(s)){for(const m of _){const d=i(a(s[m]));if(d&&f.has(d))return!0}if(u(s.statusCode)||u(s.status))return!0}}if(l(a(r.message)))return!0;t=r.cause??r.lastError??r.error}return!1}function i(e){if(e==null)return;const t=e.trim().toLowerCase();return t.length>0?t:void 0}function a(e){if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e))return String(e)}function l(e){if(!e)return!1;const t=e.toLowerCase();return p.some(n=>t.includes(n))}function u(e){return a(e)==="413"}function k(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}export{h as isContextOverflowError,R as resolveFinishReasonOverflow};
|
|
2
|
+
|
|
Binary file
|
|
@@ -4,15 +4,18 @@ export * from './commands/commandParser.js';
|
|
|
4
4
|
export * from './config.js';
|
|
5
5
|
export * from './hooks/hookBus.js';
|
|
6
6
|
export * from './runtime.js';
|
|
7
|
+
export * from './runtime-environment.js';
|
|
7
8
|
export * from './types.js';
|
|
8
9
|
export * from './sub-agent-types.js';
|
|
9
10
|
export * from './sub-agent-store.js';
|
|
10
11
|
export * from './sub-agent-manager.js';
|
|
11
12
|
export * from './sub-agent-tools.js';
|
|
12
13
|
export * from './built-in-file-tools.js';
|
|
14
|
+
export * from './read-file-state.js';
|
|
15
|
+
export * from './tool-concurrency/index.js';
|
|
13
16
|
export * from './terminal-types.js';
|
|
14
17
|
export * from './plugin-types.js';
|
|
15
|
-
export * from './
|
|
18
|
+
export * from './tool-group-manager.js';
|
|
16
19
|
export * from './parsers/types.js';
|
|
17
20
|
export * from './parsers/tree-sitter-loader.js';
|
|
18
21
|
export * from './parsers/ast-cache.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export*from"./commands/commandRegistry.js";export*from"./commands/commandLoader.js";export*from"./commands/commandParser.js";export*from"./config.js";export*from"./hooks/hookBus.js";export*from"./runtime.js";export*from"./types.js";export*from"./sub-agent-types.js";export*from"./sub-agent-store.js";export*from"./sub-agent-manager.js";export*from"./sub-agent-tools.js";export*from"./built-in-file-tools.js";export*from"./terminal-types.js";export*from"./plugin-types.js";export*from"./
|
|
1
|
+
export*from"./commands/commandRegistry.js";export*from"./commands/commandLoader.js";export*from"./commands/commandParser.js";export*from"./config.js";export*from"./hooks/hookBus.js";export*from"./runtime.js";export*from"./runtime-environment.js";export*from"./types.js";export*from"./sub-agent-types.js";export*from"./sub-agent-store.js";export*from"./sub-agent-manager.js";export*from"./sub-agent-tools.js";export*from"./built-in-file-tools.js";export*from"./read-file-state.js";export*from"./tool-concurrency/index.js";export*from"./terminal-types.js";export*from"./plugin-types.js";export*from"./tool-group-manager.js";export*from"./parsers/types.js";export*from"./parsers/tree-sitter-loader.js";export*from"./parsers/ast-cache.js";export*from"./parsers/language-detector.js";export*from"./parsers/language-queries.js";export*from"./parsers/symbol-extractor.js";export*from"./built-in-symbols-tool.js";
|
|
2
2
|
|
|
@@ -4,3 +4,7 @@ export declare function getSemanticToolName(toolName: string): string;
|
|
|
4
4
|
export declare function isMcpPollingToolName(toolName: string): boolean;
|
|
5
5
|
|
|
6
6
|
export declare function isMcpBlockingToolName(toolName: string): boolean;
|
|
7
|
+
|
|
8
|
+
export declare function isMcpIndefinitelyBlockingToolName(toolName: string): boolean;
|
|
9
|
+
|
|
10
|
+
export declare function isMcpBatchExcludedToolName(toolName: string): boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
1
|
+
const s=new Set(["poll_message","get_message","send_private"]),i=new Set(["create_meeting"]),o=new Set(["poll_message","create_meeting"]);function t(e){const n=e.trim().toLowerCase();return n.split(/__|[./]/).filter(Boolean).at(-1)??n}function a(e){return s.has(t(e))}function c(e){return i.has(t(e))}function l(e){return o.has(t(e))}function m(e){return o.has(t(e))}export{t as getSemanticToolName,m as isMcpBatchExcludedToolName,c as isMcpBlockingToolName,l as isMcpIndefinitelyBlockingToolName,a as isMcpPollingToolName};
|
|
2
2
|
|
|
@@ -1,11 +1,22 @@
|
|
|
1
1
|
import type { Tree } from "web-tree-sitter";
|
|
2
2
|
|
|
3
|
+
export interface AcquiredTree {
|
|
4
|
+
readonly tree: Tree;
|
|
5
|
+
release(): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
3
8
|
export declare class AstCache {
|
|
4
9
|
private map;
|
|
5
10
|
private readonly capacity;
|
|
6
11
|
constructor(capacity?: number);
|
|
7
12
|
|
|
8
|
-
|
|
13
|
+
private dispose;
|
|
14
|
+
|
|
15
|
+
acquire(absolutePath: string, mtimeMs: number, size: number, language?: string): AcquiredTree | null;
|
|
16
|
+
|
|
17
|
+
store(absolutePath: string, tree: Tree, language: string, mtimeMs: number, size: number): AcquiredTree | null;
|
|
18
|
+
|
|
19
|
+
get(absolutePath: string, mtimeMs: number, size: number, language?: string): Tree | null;
|
|
9
20
|
|
|
10
21
|
set(absolutePath: string, tree: Tree, language: string, mtimeMs: number, size: number): void;
|
|
11
22
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class
|
|
1
|
+
class f{constructor(e=100){if(this.map=new Map,e<1)throw new Error(`capacity must be >= 1, got ${e}`);this.capacity=e}dispose(e){if(e.refs>0){e.pendingDelete=!0;return}e.tree.delete(),e.pendingDelete=!0}acquire(e,i,n,s){const t=this.map.get(e);if(!t)return null;if(t.mtimeMs!==i||t.size!==n||s!==void 0&&t.language!==s)return this.dispose(t),this.map.delete(e),null;this.map.delete(e),this.map.set(e,t),t.refs+=1;let r=!1;return{tree:t.tree,release:()=>{r||(r=!0,t.refs-=1,t.refs<=0&&t.pendingDelete&&t.tree.delete())}}}store(e,i,n,s,t){const r=this.map.get(e);return r&&r.mtimeMs===s&&r.size===t&&r.language===n?null:(this.set(e,i,n,s,t),this.acquire(e,s,t,n))}get(e,i,n,s){const t=this.map.get(e);return t?t.mtimeMs!==i||t.size!==n||s!==void 0&&t.language!==s?(this.dispose(t),this.map.delete(e),null):(this.map.delete(e),this.map.set(e,t),t.tree):null}set(e,i,n,s,t){const r=this.map.get(e);for(r&&(this.dispose(r),this.map.delete(e)),this.map.set(e,{tree:i,language:n,mtimeMs:s,size:t,refs:0,pendingDelete:!1});this.map.size>this.capacity;){const p=this.map.keys().next().value;if(p===void 0)break;const d=this.map.get(p);d&&this.dispose(d),this.map.delete(p)}}invalidate(e){const i=this.map.get(e);i&&(this.dispose(i),this.map.delete(e))}clear(){for(const e of this.map.values())this.dispose(e);this.map.clear()}size(){return this.map.size}}const l=new f(100);export{f as AstCache,l as astCache};
|
|
2
2
|
|
|
@@ -46,5 +46,5 @@ const e={definitions:[{kind:"function",hasEndLine:!0,query:"(function_declaratio
|
|
|
46
46
|
`},{kind:"variable",query:"(identifier) @name @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class_declaration name: (identifier) @name) @node"}]},i={definitions:[{kind:"function",hasEndLine:!0,query:"(function_definition name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class_definition name: (identifier) @name) @node"},{kind:"import",query:"(import_statement name: (dotted_name) @name) @node"},{kind:"import",query:`
|
|
47
47
|
(import_from_statement
|
|
48
48
|
module_name: (dotted_name) @name) @node
|
|
49
|
-
`}],references:[{kind:"function",query:"(call function: (identifier) @name) @node"},{kind:"variable",query:"(identifier) @name @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_definition name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class_definition name: (identifier) @name) @node"}]},a={definitions:[{kind:"function",hasEndLine:!0,query:"(function_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(type_declaration (type_spec name: (type_identifier) @name) @node)"},{kind:"method",hasEndLine:!0,query:"(method_declaration name: (field_identifier) @name) @node"},{kind:"import",query:"(import_declaration (import_spec path: (interpreted_string_literal) @name) @node)"}],references:[{kind:"function",query:"(call_expression function: (identifier) @name) @node"},{kind:"function",query:"(call_expression function: (selector_expression field: (field_identifier) @name) @node)"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(type_declaration (type_spec name: (type_identifier) @name) @node)"}]},
|
|
49
|
+
`}],references:[{kind:"function",query:"(call function: (identifier) @name) @node"},{kind:"variable",query:"(identifier) @name @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_definition name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class_definition name: (identifier) @name) @node"}]},a={definitions:[{kind:"function",hasEndLine:!0,query:"(function_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(type_declaration (type_spec name: (type_identifier) @name) @node)"},{kind:"method",hasEndLine:!0,query:"(method_declaration name: (field_identifier) @name) @node"},{kind:"import",query:"(import_declaration (import_spec path: (interpreted_string_literal) @name) @node)"}],references:[{kind:"function",query:"(call_expression function: (identifier) @name) @node"},{kind:"function",query:"(call_expression function: (selector_expression field: (field_identifier) @name) @node)"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(type_declaration (type_spec name: (type_identifier) @name) @node)"}]},d={definitions:[{kind:"function",hasEndLine:!0,query:"(function_item name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(struct_item name: (type_identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(trait_item name: (type_identifier) @name) @node"},{kind:"function",hasEndLine:!0,query:"(impl_item body: (declaration_list (function_item name: (identifier) @name) @node))"},{kind:"import",query:"(use_declaration argument: [(identifier) (scoped_identifier)] @name) @node"}],references:[{kind:"function",query:"(call_expression function: (identifier) @name) @node"},{kind:"function",query:"(call_expression function: (field_expression field: (field_identifier) @name) @node)"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_item name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(struct_item name: (type_identifier) @name) @node"}]},t={definitions:[{kind:"function",hasEndLine:!0,query:"(method_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(interface_declaration name: (identifier) @name) @node"},{kind:"import",query:"(import_declaration [(scoped_identifier) (identifier)] @name) @node"}],references:[{kind:"function",query:"(method_invocation name: (identifier) @name) @node"},{kind:"variable",query:"(identifier) @name @node"}],outline:[{kind:"class",hasEndLine:!0,query:"(class_declaration name: (identifier) @name) @node"},{kind:"function",hasEndLine:!0,query:"(method_declaration name: (identifier) @name) @node"}]},r={definitions:[{kind:"function",hasEndLine:!0,query:"(function_definition declarator: (function_declarator declarator: (identifier) @name) @node)"},{kind:"variable",hasEndLine:!0,query:"(declaration declarator: (init_declarator declarator: (identifier) @name) @node)"}],references:[{kind:"function",query:"(call_expression function: (identifier) @name) @node"},{kind:"variable",query:"(identifier) @name @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_definition declarator: (function_declarator declarator: (identifier) @name) @node)"}]},o={definitions:[{kind:"function",hasEndLine:!0,query:"(function_definition declarator: (function_declarator declarator: (identifier) @name) @node)"},{kind:"class",hasEndLine:!0,query:"(class_specifier name: (type_identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(struct_specifier name: (type_identifier) @name) @node"},{kind:"function",hasEndLine:!0,query:"(declaration declarator: (function_declarator declarator: (identifier) @name) @node)"}],references:[{kind:"function",query:"(call_expression function: (identifier) @name) @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_definition declarator: (function_declarator declarator: (identifier) @name) @node)"},{kind:"class",hasEndLine:!0,query:"(class_specifier name: (type_identifier) @name) @node"}]},s={definitions:[{kind:"function",hasEndLine:!0,query:"(method_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class_declaration name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(interface_declaration name: (identifier) @name) @node"},{kind:"import",query:"(using_directive [(qualified_name) (identifier)] @name) @node"}],references:[{kind:"function",query:"(invocation_expression function: (identifier) @name) @node"}],outline:[{kind:"class",hasEndLine:!0,query:"(class_declaration name: (identifier) @name) @node"},{kind:"function",hasEndLine:!0,query:"(method_declaration name: (identifier) @name) @node"}]},u={definitions:[{kind:"function",hasEndLine:!0,query:"(method name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class name: (constant) @name) @node"},{kind:"class",hasEndLine:!0,query:"(module name: (constant) @name) @node"}],references:[{kind:"function",query:"(call method: (identifier) @name) @node"},{kind:"variable",query:"(identifier) @name @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(method name: (identifier) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class name: (constant) @name) @node"}]},c={definitions:[{kind:"function",hasEndLine:!0,query:"(function_definition name: (name) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class_declaration name: (name) @name) @node"},{kind:"method",hasEndLine:!0,query:"(method_declaration name: (name) @name) @node"}],references:[{kind:"function",query:"(function_call_expression function: (name) @name) @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_definition name: (name) @name) @node"},{kind:"class",hasEndLine:!0,query:"(class_declaration name: (name) @name) @node"}]},m={definitions:[{kind:"function",hasEndLine:!0,query:"(function_declaration name: (identifier) @name) @node"},{kind:"method",hasEndLine:!0,query:"(function_declaration name: (dot_index_expression field: (identifier) @name)) @node"},{kind:"variable",query:"(variable_declaration (assignment_statement (variable_list name: (identifier) @name))) @node"}],references:[{kind:"function",query:"(function_call name: (identifier) @name) @node"},{kind:"method",query:"(function_call name: (dot_index_expression field: (identifier) @name)) @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_declaration name: (identifier) @name) @node"},{kind:"method",hasEndLine:!0,query:"(function_declaration name: (dot_index_expression field: (identifier) @name)) @node"}]},f={definitions:[{kind:"function",hasEndLine:!0,query:"(function_definition name: (word) @name) @node"},{kind:"variable",query:"(variable_assignment name: (variable_name) @name) @node"}],references:[{kind:"function",query:"(command name: (command_name) @name) @node"},{kind:"variable",query:"(simple_expansion (variable_name) @name) @node"}],outline:[{kind:"function",hasEndLine:!0,query:"(function_definition name: (word) @name) @node"}]},l={typescript:e,tsx:e,javascript:n,jsx:n,python:i,go:a,rust:d,java:t,c:r,cpp:o,"c-sharp":s,ruby:u,php:c,lua:m,bash:f},_=Object.keys(l);export{l as LANGUAGE_QUERIES,_ as SUPPORTED_LANGUAGES};
|
|
50
50
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{promises as
|
|
2
|
-
`);let
|
|
1
|
+
import{promises as b}from"node:fs";import{resolveWorkspaceTarget as F,ensureInsideWorkspace as O}from"../built-in-file-tools.js";import{astCache as U}from"./ast-cache.js";import{detectLanguage as I}from"./language-detector.js";import{LANGUAGE_QUERIES as N}from"./language-queries.js";import{getParserForLanguage as P,loadLanguage as X}from"./tree-sitter-loader.js";const $=1024*1024,z=256*1024,Q=100,W=500,B=new WeakMap;function Y(r){let e=0;for(let t=0;t<r.length;t++)e=(e<<5)-e+r.charCodeAt(t)|0;return e.toString(16)}async function v(r,e,t){let o=B.get(r);o||(o=new Map,B.set(r,o));const n=`${e}:${Y(t)}`,a=o.get(n);if(a)return a;const{Query:d}=await import("web-tree-sitter"),i=new d(r,t);return o.set(n,i),i}function m(r){return r.replace(/\\/g,"/")}function D(r,e,t,o){const n={kind:t.kind,name:e,line:r.startPosition.row+1};if(t.hasEndLine&&(n.endLine=r.endPosition.row+1),n.column=r.startPosition.column+1,t.hasEndLine||t.kind==="import"){const a=o[r.startPosition.row]??"";n.signature=a.trim()}if(!t.hasEndLine&&t.kind!=="import"){const a=o[r.startPosition.row]??"";n.context=a}return n}async function tt(r,e,t,o){const n=Math.min(o.maxResults??Q,W),a=o.kind??"all",d=await F(r,e),i=O(d.workspaceRoot,await b.realpath(d.targetPath)),l=await b.stat(i);if(!l.isFile())throw new Error(`Path is not a file: ${e}`);if(l.size>$)return{ok:!0,tool:"symbols",path:m(e),mode:t,language:"unknown",symbols:[],truncated:!1,error:"file too large"};const s=I(i);if(!s)return{ok:!0,tool:"symbols",path:m(e),mode:t,language:"unknown",symbols:[],truncated:!1,error:"unsupported language"};const L=await X(s);if(!L)return{ok:!0,tool:"symbols",path:m(e),mode:t,language:s,symbols:[],truncated:!1,error:"grammar load failed"};const h=U.acquire(i,l.mtimeMs,l.size,s);let S=!1,p;if(h)p=h.tree;else{const y=await P(s);if(!y)return{ok:!0,tool:"symbols",path:m(e),mode:t,language:s,symbols:[],truncated:!1,error:"grammar load failed"};const u=await b.readFile(i,"utf-8"),g=y.parse(u);if(!g)return{ok:!0,tool:"symbols",path:m(e),mode:t,language:s,symbols:[],truncated:!1,error:"parse failed"};const f=U.store(i,g,s,l.mtimeMs,l.size);p=g,S=f===null}const C=()=>{S?p.delete():h?.release()};try{const y=N[s]?.[t]??[],u=[],g=p.rootNode.text.split(`
|
|
2
|
+
`);let f=!1,E=0,w=null;if(o.pattern)try{w=new RegExp(o.pattern)}catch(c){throw new Error(`Invalid pattern regex: ${c instanceof Error?c.message:String(c)}`)}for(const c of y){if(u.length>=n){f=!0;break}if(a!=="all"&&c.kind!==a)continue;const q=(await v(L,t,c.query)).matches(p.rootNode);for(const M of q){if(u.length>=n){f=!0;break}const _=M.captures.find(k=>k.name==="name"),x=M.captures.find(k=>k.name==="node");if(!_||!x)continue;const T=_.node.text;if(w&&!w.test(T))continue;const A=D(x.node,T,c,g),R=Buffer.byteLength(JSON.stringify(A),"utf-8")+64;if(E+R>z){f=!0;break}E+=R,u.push(A)}}return{ok:!0,tool:"symbols",path:m(e),mode:t,language:s,symbols:u,truncated:f}}finally{C()}}export{tt as extractSymbols};
|
|
3
3
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Parser, Language } from "web-tree-sitter";
|
|
2
2
|
|
|
3
|
-
export declare function
|
|
3
|
+
export declare function getParserForLanguage(language: string): Promise<Parser | null>;
|
|
4
4
|
|
|
5
5
|
export declare function loadLanguage(language: string): Promise<Language | null>;
|
|
6
6
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{promises as
|
|
1
|
+
import{existsSync as l,promises as d}from"node:fs";import e from"node:path";import{fileURLToPath as g}from"node:url";import{Parser as m,Language as p}from"web-tree-sitter";let i=null;const c=new Map,u=new Map;async function f(){return i||(i=m.init().catch(t=>{throw i=null,t})),i}async function j(t){const a=c.get(t);if(a)return a;const n=await h(t);if(!n)return null;await f();const r=new m;r.setLanguage(n);const s=c.get(t);return s?(r.delete(),s):(c.set(t,r),r)}function L(t){return e.basename(e.dirname(t))==="dist"?[e.resolve(t,"../grammars"),e.resolve(t,"../../grammars")]:[e.resolve(t,"../../grammars"),e.resolve(t,"../grammars")]}function w(t){const a=e.dirname(g(import.meta.url)),n=`tree-sitter-${t}.wasm`,r=L(a);for(const s of r){const o=e.join(s,n);if(l(o))return o}return e.join(r[0],n)}async function h(t){const a=u.get(t);if(a)return a;const n=w(t);try{await f();const r=await d.readFile(n),s=await p.load(r),o=u.get(t);return o||(u.set(t,s),s)}catch{return null}}function F(t){return u.has(t)}async function G(){for(const t of c.values())t.delete();c.clear(),u.clear(),i=null}export{j as getParserForLanguage,F as isLanguageLoaded,h as loadLanguage,G as resetLoader};
|
|
2
2
|
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
|
|
2
2
|
import type { JsonObject } from "./built-in-file-tools.js";
|
|
3
3
|
|
|
4
|
+
export declare function splitQualifiedToolName(qualifiedName: string): {
|
|
5
|
+
plugin: string;
|
|
6
|
+
tool: string;
|
|
7
|
+
} | null;
|
|
8
|
+
|
|
4
9
|
export type PluginStatus = "enabled" | "disabled" | "error";
|
|
5
10
|
|
|
6
11
|
export interface PluginCatalogTool {
|