aws-runtime-bridge 1.9.171 → 1.9.175

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.
Files changed (74) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/dist/adapter/AcodeSdkAdapter.d.ts +11 -13
  3. package/dist/adapter/AcodeSdkAdapter.js +3 -3
  4. package/dist/adapter/ClaudeSdkAdapter.d.ts +2 -0
  5. package/dist/adapter/ClaudeSdkAdapter.js +3 -3
  6. package/dist/adapter/types.d.ts +6 -7
  7. package/dist/index.js +1 -1
  8. package/dist/routes/bridge-temp-files.d.ts +1 -0
  9. package/dist/routes/bridge-temp-files.js +2 -0
  10. package/dist/routes/dashboard.js +35 -5
  11. package/dist/routes/file-browser.d.ts +4 -10
  12. package/dist/routes/file-browser.js +1 -1
  13. package/dist/routes/git.d.ts +42 -0
  14. package/dist/routes/git.js +34 -34
  15. package/dist/routes/sessions.js +1 -1
  16. package/dist/routes/tech-stack.d.ts +2 -0
  17. package/dist/routes/tech-stack.js +2 -0
  18. package/dist/routes/terminal.d.ts +8 -0
  19. package/dist/routes/terminal.js +27 -27
  20. package/dist/services/agent-pty-manager.d.ts +2 -0
  21. package/dist/services/agent-pty-manager.js +5 -4
  22. package/dist/services/agent-startup-memory.js +4 -4
  23. package/dist/services/bridge-temp-files.d.ts +36 -0
  24. package/dist/services/bridge-temp-files.js +2 -0
  25. package/dist/services/fileSnapshotStore.d.ts +9 -0
  26. package/dist/services/fileSnapshotStore.js +1 -1
  27. package/dist/services/gitignore.d.ts +12 -0
  28. package/dist/services/gitignore.js +2 -0
  29. package/dist/services/log-retention.js +1 -1
  30. package/dist/services/open-doc-events.d.ts +21 -0
  31. package/dist/services/open-doc-events.js +2 -0
  32. package/dist/services/open-doc-registry.d.ts +24 -0
  33. package/dist/services/open-doc-registry.js +2 -0
  34. package/dist/services/request-invalid-dump.js +1 -1
  35. package/dist/services/runtime-resources-snapshot.js +2 -2
  36. package/dist/services/session-output.d.ts +2 -0
  37. package/dist/services/session-output.js +2 -2
  38. package/dist/services/snapshot-retention.d.ts +7 -0
  39. package/dist/services/snapshot-retention.js +2 -0
  40. package/dist/services/tech-stack-scanner.d.ts +31 -0
  41. package/dist/services/tech-stack-scanner.js +2 -0
  42. package/dist/services/tunnel-client.d.ts +42 -0
  43. package/dist/services/tunnel-client.js +1 -1
  44. package/dist/services/workspaceTaskChangeWatcher.js +2 -2
  45. package/package/acode/dist/__tests__/summary-request-helper.d.ts +2 -0
  46. package/package/acode/dist/__tests__/summary-request-helper.js +2 -0
  47. package/package/acode/dist/ask-user-question-tool.d.ts +11 -1
  48. package/package/acode/dist/ask-user-question-tool.js +3 -3
  49. package/package/acode/dist/built-in-file-tools.js +2 -2
  50. package/package/acode/dist/cache-control.d.ts +26 -0
  51. package/package/acode/dist/cache-control.js +2 -0
  52. package/package/acode/dist/compaction.d.ts +174 -32
  53. package/package/acode/dist/compaction.js +22 -6
  54. package/package/acode/dist/microcompact.d.ts +57 -0
  55. package/package/acode/dist/microcompact.js +2 -0
  56. package/package/acode/dist/runtime-environment.js +1 -1
  57. package/package/acode/dist/runtime.d.ts +17 -4
  58. package/package/acode/dist/runtime.js +50 -40
  59. package/package/acode/dist/token-estimator.d.ts +15 -0
  60. package/package/acode/dist/token-estimator.js +2 -0
  61. package/package/acode/dist/types.d.ts +14 -1
  62. package/package/aws-client-agent-mcp/dist/ability-market-tools.js +1 -1
  63. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +15 -2
  64. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  65. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +5 -0
  66. package/package/aws-client-agent-mcp/dist/mcp-server.js +25 -23
  67. package/package/aws-client-agent-mcp/dist/mcp-tools.js +7 -7
  68. package/package/aws-client-agent-mcp/dist/memory-store.d.ts +21 -2
  69. package/package/aws-client-agent-mcp/dist/memory-store.js +27 -2
  70. package/package/aws-client-agent-mcp/dist/memory-tools.js +13 -9
  71. package/package/aws-client-agent-mcp/dist/server-memory-store.d.ts +1 -1
  72. package/package/aws-client-agent-mcp/dist/server-memory-store.js +1 -1
  73. package/package/aws-client-agent-mcp/dist/types.d.ts +51 -0
  74. package/package.json +1 -1
@@ -1,4 +1,4 @@
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(`
1
+ import{randomUUID as pt}from"node:crypto";import{promises as p,createReadStream as Q}from"node:fs";import gt from"node:os";import u from"node:path";import tt from"node:readline";import{runShellCommand as wt}from"./builtins/shellCommandRunner.js";import{createOutputEventCollector as yt}from"./builtins/commandOutputEvents.js";import{buildCommandOutputSpilloverContent as _t,COMMAND_OUTPUT_SPILLOVER_LINE_LIMIT as bt,countOutputLines as et,formatCommandOutputSpilloverStdout as kt,writeCommandArtifactFile as Et}from"./builtins/commandArtifacts.js";import{symbolsTool as vt}from"./built-in-symbols-tool.js";import{buildRevisionId as W,checkFileFreshForWrite as ot,createReadFileEntry as D,STALE_FILE_WRITE_REASON as it,toStateKey as C}from"./read-file-state.js";import{createListBackgroundCommandsTool as Pt,createKillBackgroundCommandTool as St,createReadBackgroundOutputTool as Mt}from"./background-command-tools.js";import{detectImageFormatFromBuffer as xt,formatBytes as M,imageMediaType as at,readImageDimensions as Tt,tryCompressImageWithSharp as Rt,tryResizeWithSharp as $t}from"./image-utils.js";const It=2e3,F=2e3,nt=50*1024,rt=4096,Ot=.3,Lt=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"]),At=new Set(["png","jpg","jpeg","gif","webp"]),st=20*1024*1024,B=10*1024*1024,Y=Math.floor(3.75*1024*1024),z=2e3,Ft=50*1024,Bt=100*1024,ct=15e3,Nt=process.env.ACODE_IMAGE_DEBUG==="1",Ct={Accept:"image/webp,image/png,image/jpeg,image/gif,*/*;q=0.8","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"},Ut=1e3,Wt=1024*1024,Dt=256*1024,zt=1e3,jt=new Set([".git","node_modules","dist","build",".next",".nuxt",".cache",".turbo",".output","coverage",".nyc_output"]),Ie={fileReadOutside:"allow",commandExecution:"allow",fileModification:"allow",fileModificationOutside:"allow"};async function N(t,e,o){if(!t)return;const i=t.getLevel(e);if(i==="deny")throw new Error(`Operation blocked by tool permission policy (${e} = deny). Explain this restriction to the user if needed.`);if(i==="ask"&&!await t.requestPermission(e,o))throw new Error(`Operation denied by the user (${e}). Do not retry the same operation without asking the user.`)}function R(t){return t.replace(/\\/g,"/")}async function G(t){try{return await p.access(t),!0}catch{return!1}}function qt(t,e){if(!e)return 0;let o=0,i=t.indexOf(e);for(;i>=0;)o+=1,i=t.indexOf(e,i+e.length);return o}function O(t,e,o){for(const i of e){const a=t[i];if(typeof a=="string")return a}throw new Error(`${o} is required`)}function L(t,e){for(const o of e){const i=t[o];if(typeof i=="string"&&i.trim())return i}}function j(t,e,o){for(const i of e){const a=t[i],n=typeof a=="number"?a:typeof a=="string"?Number(a):NaN;if(Number.isFinite(n)&&n>0)return Math.floor(n)}return o}function Kt(t,e,o){for(const i of e){const a=t[i],n=typeof a=="number"?a:typeof a=="string"?Number(a):NaN;if(Number.isFinite(n)&&n>0)return Math.floor(n);if(Number.isFinite(n)&&n===0)return 0}return o}function Xt(t){const e=t.compress;if(e==null)return"auto";if(typeof e=="boolean")return e;if(e==="auto")return"auto";if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid compress argument: ${JSON.stringify(e)} (expected true, false, or "auto")`)}async function lt(t){const e=u.extname(t).toLowerCase();if(Lt.has(e))return!0;const o=await p.open(t,"r");try{const i=Buffer.alloc(rt),{bytesRead:a}=await o.read(i,0,rt,0);if(a===0)return!1;const n=i.subarray(0,a);if(n.includes(0))return!0;let r=0;for(let c=0;c<a;c++){const s=n[c];(s<9||s>13&&s<32)&&r++}return r/a>Ot}finally{await o.close()}}function A(t,e){const o=u.resolve(e),i=u.relative(t,o);if(i.startsWith("..")||u.isAbsolute(i))throw new Error(`Target path is outside workspace: ${o}`);return o}function Yt(t,e){const o=u.resolve(String(t||"").trim()),i=U(String(e??"").trim());return`file:${(u.isAbsolute(i)?u.resolve(i):u.resolve(o,i)).replace(/\\/g,"/")}`}function q(t,e,o){return{key:Yt(t,e),access:o}}function K(t){const e=t.file_path??t.filePath;if(typeof e!="string")return null;const o=e.trim();return o.length>0?o:null}function U(t){return t==="~"||t.startsWith("~/")?u.join(gt.homedir(),t.slice(1)):t}async function Gt(t,e){const o=u.resolve(String(t||"").trim()),i=await p.realpath(o);if(!(await p.stat(i)).isDirectory())throw new Error(`Workspace path is not a directory: ${o}`);if(!e?.trim())return{workspaceRoot:i,cwd:i};const n=U(e.trim()),r=u.isAbsolute(n)?u.resolve(n):u.resolve(o,n),c=u.relative(o,r);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Command cwd is outside workspace: ${r}`);const s=A(i,await p.realpath(r));if(!(await p.stat(s)).isDirectory())throw new Error(`Command cwd is not a directory: ${s}`);return{workspaceRoot:i,cwd:s}}async function Ht(t){try{if((await p.lstat(t)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${t}`)}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)!=="ENOENT")throw e}}async function Vt(t,e){const o=await p.realpath(u.dirname(e));A(t,o);try{if((await p.lstat(e)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${e}`)}catch(i){if((typeof i=="object"&&i!==null?Reflect.get(i,"code"):void 0)!=="ENOENT")throw i}}async function ut(t,e){const o=u.resolve(String(t||"").trim()),i=await p.realpath(o);if(!(await p.stat(i)).isDirectory())throw new Error(`Workspace path is not a directory: ${o}`);const n=U(e.trim());if(!n)throw new Error("file_path is required");const r=u.isAbsolute(n)?u.resolve(n):u.resolve(o,n),c=u.relative(o,r);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Target path is outside workspace: ${r}`);return{workspaceRoot:i,requestedPath:r,targetPath:A(i,u.join(i,c))}}async function dt(t,e,o){const i=u.resolve(String(t||"").trim()),a=await p.realpath(i);if(!(await p.stat(a)).isDirectory())throw new Error(`Workspace path is not a directory: ${i}`);const r=U(e.trim());if(!r)throw new Error("file_path is required");const c=u.isAbsolute(r)?u.resolve(r):u.resolve(i,r),s=u.relative(i,c),d=await p.realpath(c).catch(()=>c),l=u.relative(a,d);if(s.startsWith("..")||u.isAbsolute(s)||l.startsWith("..")||u.isAbsolute(l)){if(!o)throw new Error(`Target path is outside workspace: ${c}`);return await N(o,"fileReadOutside",{path:c}),{workspaceRoot:a,requestedPath:c,targetPath:d}}return{workspaceRoot:a,requestedPath:c,targetPath:A(a,d)}}async function Jt(t,e){let o=u.dirname(t);for(;;){const i=u.dirname(o);try{return await p.realpath(o)}catch{if(i===o)return e;o=i}}}async function H(t,e,o,i){const a=u.resolve(String(t||"").trim()),n=await p.realpath(a);if(!(await p.stat(n)).isDirectory())throw new Error(`Workspace path is not a directory: ${a}`);const c=U(e.trim());if(!c)throw new Error("file_path is required");const s=u.isAbsolute(c)?u.resolve(c):u.resolve(a,c),d=u.relative(a,s),l=d.startsWith("..")||u.isAbsolute(d),m=await p.realpath(s).catch(async()=>Jt(s,n)),w=u.relative(n,m),g=w.startsWith("..")||u.isAbsolute(w);if(!l&&!g)return{workspaceRoot:n,requestedPath:s,targetPath:A(n,u.join(n,d))};if(!i)throw new Error(`Target path is outside workspace: ${s}`);await N(i,"fileModificationOutside",{operation:o,path:s});const f=await G(s);return{workspaceRoot:n,requestedPath:s,targetPath:f?m:s,outsideWorkspace:!0}}async function mt(t,e){const o=u.dirname(t.targetPath),i=!await G(o);await p.mkdir(o,{recursive:!0}),t.outsideWorkspace?await Ht(t.targetPath):await Vt(t.workspaceRoot,t.targetPath);const a=u.join(o,`.${u.basename(t.targetPath)}.${process.pid}.${pt()}.tmp`);try{await p.writeFile(a,e,"utf-8"),await p.rename(a,t.targetPath)}catch(n){throw await p.rm(a,{force:!0}),n}return{workspaceRoot:t.workspaceRoot,targetPath:t.targetPath,bytes:Buffer.byteLength(e,"utf-8"),createdParentDirectory:i,outsideWorkspace:t.outsideWorkspace===!0}}async function Zt(t,e){const o=await ut(t,e),i=A(o.workspaceRoot,await p.realpath(o.targetPath)),a=await p.stat(i);if(!a.isFile())throw new Error(`Path is not a file: ${i}`);return{workspaceRoot:o.workspaceRoot,targetPath:i,content:await p.readFile(i,"utf-8"),stat:{mtimeMs:a.mtimeMs,size:a.size}}}async function Qt(t){const e=await p.realpath(t).catch(()=>t),o=await p.stat(e);if(!o.isFile())throw new Error(`Path is not a file: ${e}`);return{workspaceRoot:u.dirname(e),targetPath:e,content:await p.readFile(e,"utf-8"),stat:{mtimeMs:o.mtimeMs,size:o.size}}}async function ht(t,e,o){if(t?.tracker)try{const i=await p.realpath(e),a=await p.stat(i);t.tracker.record(C(i),D(a,o,!1))}catch{}}async function te(t,e,o,i,a){const n=await dt(t,e,a),r=n.targetPath,c=await p.stat(r);if(!c.isFile())throw new Error(`Path is not a file: ${r}`);if(await lt(r))return{workspaceRoot:n.workspaceRoot,targetPath:r,content:"[Binary file, content skipped]",isBinary:!0,truncated:!1,totalLines:0,shownFromLine:0,shownToLine:0,mtimeMs:c.mtimeMs,sizeBytes:c.size};const s=Q(r,{encoding:"utf-8"}),d=tt.createInterface({input:s,crlfDelay:1/0});try{const l=[];let m=0,w=0,g=0,f=!1,h=!1;const k=o-1;for await(const _ of d){if(w++,m<k){m++;continue}if(l.length>=i){f=!0,m++;continue}let P=_;P.length>F&&(P=P.slice(0,F)+`... (line truncated to ${F} chars)`);const x=`${m+1}: ${P}`,b=Buffer.byteLength(x,"utf-8")+1;if(g+b>nt){h=!0;break}l.push(x),g+=b,m++}if(w>0&&l.length===0&&!f&&!h&&k>=w)throw new Error(`offset ${o} exceeds total line count ${w} in file: ${r}`);const y=l.length>0?o:0,E=l.length>0?o+l.length-1:0;let v;h?v=`Output capped at 50 KB. Showing lines ${y}-${E}. Use offset=${E+1} to continue.`:f?v=`Showing lines ${y}-${E} of ${w}. Use offset=${E+1} to continue.`:v=`End of file - total ${w} lines`;const S=l.length>0?l.join(`
2
2
  `)+`
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};
3
+ `+v:v;return{workspaceRoot:n.workspaceRoot,targetPath:r,content:S,isBinary:!1,truncated:f||h,totalLines:h?-1:w,shownFromLine:y,shownToLine:E,mtimeMs:Math.trunc(c.mtimeMs),sizeBytes:c.size}}finally{d.close(),s.destroy()}}function X(t){return/^https?:\/\//i.test(t)}function ee(t){try{const e=new URL(t);return`${e.origin}${e.pathname}`}catch{return"(invalid-url)"}}function I(t,e){if(!Nt)return;const o=e?` ${JSON.stringify(e)}`:"";console.error(`[acode:image] ${t}${o}`)}function oe(t){return!t||t.startsWith("image/")||t==="application/octet-stream"||t==="binary/octet-stream"?!1:t.startsWith("text/")||t==="application/json"||t.endsWith("+json")||t==="application/xml"||t.endsWith("+xml")}async function ie(t){let e;try{e=new URL(t)}catch{throw new Error(`Invalid image URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${e.protocol} (only http/https)`);const o=ee(t),i=Date.now();I("url fetch start",{url:o,timeoutMs:ct});let a;try{a=await fetch(t,{headers:Ct,signal:AbortSignal.timeout(ct)})}catch(m){const w=m instanceof Error?m.message:String(m);throw I("url fetch failed",{url:o,reason:w,elapsedMs:Date.now()-i}),new Error(`Image URL fetch failed: ${t} (${w})`)}if(!a.ok)throw I("url fetch failed",{url:o,status:a.status,elapsedMs:Date.now()-i}),new Error(`Image URL fetch failed: ${t} (HTTP ${a.status})`);const n=(a.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(oe(n))throw I("url fetch rejected: non-image content-type",{url:o,contentType:n,elapsedMs:Date.now()-i}),new Error(`URL did not return an image (content-type: ${n}): ${t}`);const r=Number(a.headers.get("content-length")||"");if(I("url fetch response",{url:o,status:a.status,contentType:n||"(none)",contentLength:Number.isFinite(r)?r:null,elapsedMs:Date.now()-i}),Number.isFinite(r)&&r>B)throw I("url fetch rejected: too large",{url:o,contentLength:r,elapsedMs:Date.now()-i}),new Error(`Image too large to fetch: ${t} (${M(r)} > ${M(B)})`);const c=a.body;if(!c){const m=await a.arrayBuffer();if(m.byteLength>B)throw I("url fetch rejected: too large",{url:o,bytes:m.byteLength,elapsedMs:Date.now()-i}),new Error(`Image too large to fetch: ${t} (${M(m.byteLength)} > ${M(B)})`);return I("url fetch done",{url:o,bytes:m.byteLength,elapsedMs:Date.now()-i}),{buffer:Buffer.from(m),contentType:n}}const s=c.getReader(),d=[];let l=0;for(;;){const{done:m,value:w}=await s.read();if(m)break;if(w){if(l+=w.byteLength,l>B)throw s.cancel().catch(()=>{}),I("url fetch rejected: too large",{url:o,bytes:l,elapsedMs:Date.now()-i}),new Error(`Image too large to fetch: ${t} (${M(l)} > ${M(B)})`);d.push(Buffer.from(w))}}return I("url fetch done",{url:o,bytes:l,elapsedMs:Date.now()-i}),{buffer:Buffer.concat(d,l),contentType:n}}async function ae(t,e,o,i="auto",a){let n,r,c;if(X(e)){const b=await ie(e);n=b.buffer,c=b.contentType,r=e}else{const $=(await dt(t,e,o)).targetPath,T=await p.stat($);if(!T.isFile())throw new Error(`Path is not a file: ${$}`);if(T.size>st)throw new Error(`Image file too large to read: ${R($)} (${M(T.size)} > ${M(st)}). Downscale it first.`);n=await p.readFile($),r=R($),a?.tracker&&a.tracker.record(C($),D(T,null,!0))}if(n.length===0)throw new Error(`Image file is empty: ${r}`);const s=xt(n);if(!s)throw I("image decode failed",{path:r,bytes:n.length,contentType:c||"(local file)"}),new Error(c!==void 0?`URL did not return a supported image (content-type: ${c||"unknown"}, unrecognized format): ${r}`:`Unsupported or corrupt image (unrecognized format): ${r}`);const d=Tt(n);let l=s,m=n,w=d?.width,g=d?.height,f=null;if(i!==!1){const b=await Rt(n,s,{normalMaxBytes:Ft,clearMaxBytes:Bt});b?.compressed&&(m=b.buffer,l=b.mediaType,w=b.width,g=b.height,f={level:b.level,originalSize:b.originalSize})}let h=!1;const k=await $t(m,l,{maxWidth:z,maxHeight:z,maxBytes:Y});if(k)m=k.buffer,l=k.mediaType,w=k.width,g=k.height,h=k.changed;else if(m.length>Y)throw new Error(`Image too large to inline: ${r} (${M(m.length)} > ${M(Y)}). Downscale it first, e.g. via Bash: magick "${e}" -resize ${z}x${z} "${e}". Installing sharp enables automatic downscaling.`);const y=w&&g?`${w}x${g}`:"unknown dimensions",E=h&&d&&d.width!==w?` (resized from ${d.width}x${d.height})`:h?" (resized)":"",v=f!==null?f.level:null,S=f!==null?Math.max(1,Math.round((1-m.length/f.originalSize)*100)):0,_=f!==null?`${M(m.length)} (compressed from ${M(f.originalSize)}, saved ${S}%, ${v} level)`:M(m.length),P=`[Image: ${r}, ${y}${E}, ${_}]`,x=X(e)?u.basename(new URL(e).pathname)||"image":u.basename(r);return{ok:!0,filePath:r,content:P,isBinary:!1,image:{mediaType:at(l),width:w??null,height:g??null,originalWidth:d?.width??null,originalHeight:d?.height??null,resized:h,size:m.length,compressed:f!==null,compressionLevel:v,compressionRatio:f!==null?Math.round((1-m.length/f.originalSize)*100)/100:null,originalSize:n.length},attachments:[{type:"image",name:x,mediaType:at(l),base64Data:m.toString("base64")}]}}function ft(t){let e="",o=0;for(;o<t.length;){const i=t[o];if(i==="*")e+="[^/]*";else if(i==="?")e+="[^/]";else if(i==="{"){const a=t.indexOf("}",o);if(a>=0){const n=t.slice(o+1,a);e+=`(${n.split(",").join("|")})`,o=a}else e+="\\{"}else if(i==="["){const a=t.indexOf("]",o);a>=0?(e+=t.slice(o,a+1),o=a):e+="\\["}else"+^$.()|\\".includes(i)?e+="\\"+i:e+=i;o++}return new RegExp(`^${e}$`)}async function ne(t,e,o,i){const a=[];async function n(r){if(a.length>=i)return;const c=await p.readdir(r,{withFileTypes:!0});for(const s of c){if(a.length>=i)return;if(s.name.startsWith(".")&&s.isDirectory())continue;const d=u.join(r,s.name);if(s.isDirectory()){if(jt.has(s.name))continue;await n(d)}else if(s.isFile()){if(e&&!e.test(s.name)||o&&o.test(s.name))continue;a.push(d)}}}return await n(t),a}async function re(t,e,o){if((await p.stat(t)).size>Wt)return{matches:[],count:0};if(await lt(t))return{matches:[],count:0};const a=u.relative(e,t).replace(/\\/g,"/"),n=[];let r=0;const c=Q(t,{encoding:"utf-8"}),s=tt.createInterface({input:c,crlfDelay:1/0});try{let d=0;for await(const l of s)if(d++,o.regex.test(l)){if(r++,o.collectContent){let m=l;if(m.length>F&&(m=m.slice(0,F)+`... (line truncated to ${F} chars)`),n.push({file:a,line:d,content:m}),n.length>=o.maxResults)break}if(o.stopOnFirstMatch)break}}finally{s.close(),c.destroy()}return{matches:n,count:r}}const se=12*60*6e4,ce=3*6e4,le=6e4,ue=10*6e4;function de(t,e,o,i){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",concurrencyMode:"write",resourceKeys:a=>{const n=K(a);return n?[q(t,n,"write")]:[]},description:"Create or overwrite a UTF-8 text file inside the current workspace. Parent directories are created automatically.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to write."},content:{type:"string",description:"Complete UTF-8 file content."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","content"],additionalProperties:!1},async execute(a){const n=O(a,["file_path","filePath"],"file_path"),r=O(a,["content"],"content"),c=L(a,["reason"]),s=await H(t,n,"write",o);await N(o,"fileModification",{operation:"write",path:s.targetPath});const d=await G(s.targetPath),l=d?await p.readFile(s.targetPath,"utf-8").catch(()=>null):null,m=d?await p.realpath(s.targetPath).catch(()=>s.targetPath):s.targetPath;let w=null;if(i?.enabled&&d){const f=await p.stat(m);w=W(f.mtimeMs,f.size);const h=ot(i.tracker,C(m),f,l);if(!h.ok)throw new Error(h.reason)}if(i?.enabled&&w){const f=await p.stat(m).catch(()=>null);if(!f||W(f.mtimeMs,f.size)!==w)throw new Error(it)}const g=await mt(s,r);if(await ht(i,g.targetPath,r),e&&!g.outsideWorkspace){const f=u.relative(g.workspaceRoot,g.targetPath).replace(/\\/g,"/");await e({filePath:f,operation:d?"UPDATE":"CREATE",beforeContent:l,afterContent:r,reason:c})}return{ok:!0,filePath:R(g.targetPath),bytes:g.bytes,createdParentDirectory:g.createdParentDirectory}}}}const me=15*1024;function Oe(t){if(typeof t!="object"||t===null)return;const e=Reflect.get(t,"editFailureSnapshot");if(typeof e=="object"&&e!==null&&typeof Reflect.get(e,"content")=="string")return e}function he(t,e,o,i){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",concurrencyMode:"write",resourceKeys:a=>{const n=K(a);return n?[q(t,n,"write")]:[]},description:"Replace exactly one occurrence of old_string with new_string in a UTF-8 workspace text file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to edit."},old_string:{type:"string",description:"Existing text to replace. Must occur exactly once."},new_string:{type:"string",description:"Replacement text."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","old_string","new_string"],additionalProperties:!1},async execute(a){const n=O(a,["file_path","filePath"],"file_path"),r=O(a,["old_string","oldString"],"old_string"),c=O(a,["new_string","newString"],"new_string"),s=L(a,["reason"]);if(!r)throw new Error("old_string must not be empty");const d=await H(t,n,"edit",o);await N(o,"fileModification",{operation:"edit",path:d.targetPath});const l=d.outsideWorkspace?await Qt(d.targetPath):await Zt(t,n),m=C(l.targetPath);let w;try{if(i?.enabled){const h=ot(i.tracker,m,l.stat,l.content);if(!h.ok)throw new Error(h.reason)}const f=qt(l.content,r);if(f===0)throw new Error("old_string was not found in file");if(f>1)throw new Error(`old_string occurs ${f} times; provide a unique match`);if(w=l.content.replace(r,c),i?.enabled){const h=await p.stat(l.targetPath).catch(()=>null);if(!h||W(h.mtimeMs,h.size)!==W(l.stat.mtimeMs,l.stat.size))throw new Error(it)}}catch(f){throw f instanceof Error&&l.stat.size<=me&&(i?.tracker.record(m,D(l.stat,l.content,!1)),f.editFailureSnapshot={path:R(l.targetPath),bytes:l.stat.size,content:l.content}),f}const g=await mt(d,w);if(await ht(i,g.targetPath,w),e&&!g.outsideWorkspace){const f=u.relative(g.workspaceRoot,g.targetPath).replace(/\\/g,"/");await e({filePath:f,operation:"UPDATE",beforeContent:l.content,afterContent:w,reason:s})}return{ok:!0,filePath:R(g.targetPath),bytes:g.bytes}}}}function fe(t,e,o){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",concurrencyMode:"write",resourceKeys:i=>{const a=K(i);return a?[q(t,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=O(i,["file_path","filePath"],"file_path"),n=L(i,["reason"]),r=await H(t,a,"delete",o);await N(o,"fileModification",{operation:"delete",path:r.targetPath});const c=r.outsideWorkspace?await p.realpath(r.targetPath).catch(()=>r.targetPath):A(r.workspaceRoot,await p.realpath(r.targetPath).catch(()=>r.targetPath)),s=await p.stat(c).catch(()=>null);if(!s)throw new Error(`File does not exist: ${c}`);if(!s.isFile())throw new Error(`Path is not a file: ${c}`);const d=await p.readFile(c,"utf-8").catch(()=>null);if(await p.rm(c,{force:!0}),e&&!r.outsideWorkspace){const l=u.relative(r.workspaceRoot,c).replace(/\\/g,"/");await e({filePath:l,operation:"DELETE",beforeContent:d,afterContent:null,reason:n})}return{ok:!0,filePath:R(c),deleted:!0}}}}function pe(t,e,o){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",concurrencyMode:"read",resourceKeys:i=>{const a=K(i);return!a||X(a)?[]:[q(t,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). When an image is already available at an http(s) URL (including signed URLs with query strings), pass the URL directly as file_path \u2014 the runtime fetches it in memory and never writes it to disk; do NOT download it with Bash/curl first. 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. For images, also accepts an http(s) URL (including signed URLs with query strings), which is fetched in memory without writing to disk."},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=O(i,["file_path","filePath"],"file_path"),n=u.extname(a).toLowerCase().slice(1);if(X(a)||At.has(n))return await ae(t,a,e,Xt(i),o);const r=j(i,["offset"],1),c=j(i,["limit"],It),s=await te(t,a,r,c,e);if(o?.tracker){let d=null,l=r!==1||s.truncated||s.isBinary;l||(d=await p.readFile(s.targetPath,"utf-8").catch(()=>null),(d==null||d.length>nt)&&(d=null,l=!0)),o.tracker.record(C(s.targetPath),D({mtimeMs:s.mtimeMs,size:s.sizeBytes},d,l))}return{ok:!0,filePath:R(s.targetPath),content:s.content,isBinary:s.isBinary,truncated:s.truncated,totalLines:s.totalLines,shownFromLine:s.shownFromLine,shownToLine:s.shownToLine}}}}function ge(t,e,o,i){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",concurrencyMode:"write",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${u.resolve(String(t||"").trim()).replace(/\\/g,"/")}`,access:"write"}],description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded total timeout (timeout_ms) measured from command start \u2014 by default 3 minutes, after which the process is force-terminated; timeout_ms can raise this (up to 12 hours) or set 0 to disable. The tool returns stdout, stderr, exit code, and (if converted to background) a task_id. By default (wait_seconds omitted or -1) the command runs in the FOREGROUND and streams output in real time; if the 5-minute adapter watchdog fires while it is still running, the command is moved to the BACKGROUND and the tool returns a task_id plus an explanation (backgrounded=true, reason=watchdog_timeout). The background command stays bound by the same total timeout (timeout_ms, default 3 minutes, still measured from command start) and can be managed via await_complete / list_background_commands / read_background_output / kill_background_command. For immediate backgrounding use wait_seconds=0, or wait_seconds=n>0 to wait n seconds then background.",inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},cwd:{type:"string",description:"Optional workspace-relative working directory. Defaults to the workspace root."},timeout_ms:{type:"number",description:"Optional total command timeout in milliseconds, measured from command start. Defaults to 180000 (3 minutes) and is capped at 43200000 (12 hours). Set 0 to disable the timeout entirely (run until finished or killed)."},inactivity_timeout_ms:{type:"number",description:"Optional no-output timeout in milliseconds. Defaults to 60000 and is capped at 600000."},wait_seconds:{type:"number",description:"How to wait for the command to finish. Omitted values (or -1, the default): run in the FOREGROUND until completion; if the 5-minute adapter watchdog fires first, the command is moved to the background and a task_id is returned (backgrounded=true, reason=watchdog_timeout). 0: spawn and immediately execute in the background, return task_id. n>0: wait up to n seconds; if still running, move to the background and return task_id. The command remains bound by the total timeout (timeout_ms, default 3 minutes, measured from command start) whether foreground or background; inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Short reason for running this command (what it does and why it is needed), shown to the user in the background commands panel. Always provide a concise reason, e.g. 'Start local dev server for manual verification'."}},required:["command"],additionalProperties:!1},async execute(a,n){const r=O(a,["command"],"command").trim();if(!r)throw new Error("command must not be empty");const c=Kt(a,["timeout_ms","timeoutMs"],ce),s=c===0?0:Math.min(c,se),d=j(a,["inactivity_timeout_ms","inactivityTimeoutMs"],le),l=Math.min(d,ue),m=L(a,["cwd"]),w=L(a,["description"]),g=await Gt(t,m);await N(i,"commandExecution",{command:r,cwd:R(g.cwd)});const f=a.wait_seconds,k=typeof f=="number"&&Number.isFinite(f)?f:-1;if(o)return await we({deps:o,command:r,agentId:e,workspaceRoot:g.workspaceRoot,cwd:g.cwd,timeoutMs:s,inactivityTimeoutMs:l,waitSeconds:k,description:w,onOutput:n?.onOutput,settleSignal:n?.settleSignal});const y=await wt({commandText:r,agentId:e,workspaceRoot:g.workspaceRoot,cwd:g.cwd,timeoutMs:s,inactivityTimeoutMs:l,onOutput:n?.onOutput,watchdogSignal:n?.settleSignal}),E={ok:y.exitCode===0&&!y.timedOut,tool:"Bash",command:r,cwd:R(g.cwd),exitCode:y.exitCode,signal:y.signal,timedOut:y.timedOut,inactivityTimedOut:y.inactivityTimedOut,watchdogInterrupted:y.watchdogInterrupted,timeoutMs:s,inactivityTimeoutMs:l,durationMs:y.durationMs,outputSpilled:y.outputSpilled,outputFilePath:y.outputFilePath,outputLineCount:y.outputLineCount,commandFilePath:y.commandFilePath,commandLineCount:y.commandLineCount,stdout:y.stdout,stderr:y.stderr};return y.watchdogInterrupted?{...E,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"+(y.outputFilePath?` (full output spilled to "${y.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."}:E}}}async function we(t){const{deps:e,command:o,agentId:i,workspaceRoot:a,cwd:n,timeoutMs:r,inactivityTimeoutMs:c,waitSeconds:s,description:d,onOutput:l,settleSignal:m}=t,w=l?yt({cwd:n,commandLineCount:0,onOutput:l}):void 0;let g=!!w;const f=()=>{g&&(g=!1,w?.close())};try{const{taskId:h,completion:k}=e.manager.startCommand({commandText:o,agentId:i,workspaceRoot:a,cwd:n,description:d,timeoutMs:r,inactivityTimeoutMs:c,onOutput:g?S=>{g&&w?.push(S.stream,S.text)}:void 0,onCompleted:e.emitCompleted});if(s===0)return e.manager.disableInactivityTimeout(i,h),await e.manager.markBackgrounded(i,h).catch(()=>{}),f(),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:h,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, read_background_output(task_id="${h}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${h}") to stop.`};const y=s===-1?0:Math.max(0,Math.floor(s*1e3)),E=[k];let v;s!==-1&&E.push(new Promise(S=>{v=setTimeout(()=>S("__timeout__"),y),v.unref?.()})),m&&E.push(m.then(()=>"__settle__"));try{const S=await Promise.race(E);if(S==="__settle__")return e.manager.disableInactivityTimeout(i,h),await e.manager.markBackgrounded(i,h).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:h,status:"backgrounded",reason:"watchdog_timeout",waitedMs:y,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, read_background_output(task_id="${h}", mode="tail") to read output, or kill_background_command(task_id="${h}") to stop.`};if(S==="__timeout__")return e.manager.disableInactivityTimeout(i,h),await e.manager.markBackgrounded(i,h).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:h,status:"backgrounded",reason:"timeout",waitedMs:y,message:`Command still running after ${s}s; moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, or read_background_output(task_id="${h}", mode="tail") / kill_background_command(task_id="${h}") to inspect.`};const _=S;let P=_.stdout,x=_.stderr,b=_.outputSpilled,$=_.outputFilePath;if(!b&&et(`${_.stdout}${_.stderr}`)>bt){const T=await Et(i,"cmd","out",_t({commandText:o,commandFilePath:_.commandFilePath,commandLineCount:_.commandLineCount,cwd:n,startedAt:new Date(Date.now()-_.durationMs),endedAt:new Date,exitCode:_.exitCode,signal:_.signal??null,timedOut:_.timedOut,inactivityTimedOut:_.inactivityTimedOut??!1,stdout:P,stderr:x}));P=kt(R(T),et(`${_.stdout}${_.stderr}`)),b=!0,$=R(T)}return{ok:_.exitCode===0&&!_.timedOut,tool:"Bash",command:o,backgrounded:!1,taskId:h,exitCode:_.exitCode,signal:_.signal,timedOut:_.timedOut,inactivityTimedOut:_.inactivityTimedOut,timeoutMs:_.timeoutMs,inactivityTimeoutMs:_.inactivityTimeoutMs,durationMs:_.durationMs,outputSpilled:b,outputFilePath:$,outputLineCount:_.outputLineCount,commandFilePath:_.commandFilePath,commandLineCount:_.commandLineCount,stdout:P,stderr:x}}finally{v&&clearTimeout(v),f()}}catch(h){if(h?.code==="too_many_tasks"||h?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:o,backgrounded:!1,status:"not_executed",error:h.code,message:`Command was NOT executed: ${h.message}. Wait for some background tasks to finish/cleanup (per-agent limit 16, global 256), or reduce concurrent background commands, then retry.`};throw h}}function ye(t){return{kind:"builtin",toolName:"grep",exposedName:"grep",concurrencyMode:"read",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${u.resolve(String(t||"").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(e){const o=O(e,["pattern"],"pattern"),i=L(e,["path"])||".",a=L(e,["include"]),n=L(e,["exclude"]),r=e.case_insensitive===!0,c=(()=>{const b=e.output_mode;return b==="files_with_matches"||b==="count"?b:"content"})(),s=j(e,["max_results"],zt),d=r?"i":"";let l;try{l=new RegExp(o,d)}catch(b){throw new Error(`Invalid regex pattern: ${b instanceof Error?b.message:String(b)}`)}const m=a?ft(a):null,w=n?ft(n):null,g=await ut(t,i),f=A(g.workspaceRoot,await p.realpath(g.targetPath)),h=await p.stat(f);let k;if(h.isFile())k=[f];else if(h.isDirectory())k=await ne(f,m,w,Ut);else throw new Error(`Path is neither a file nor a directory: ${f}`);const y=[],E=[],v=[];let S=0,_=0,P=!1;for(const b of k){if(c==="content"&&y.length>=s){P=!0;break}const $={regex:l,maxResults:c==="content"?s-y.length:Number.MAX_SAFE_INTEGER,collectContent:c==="content",stopOnFirstMatch:c==="files_with_matches"},T=await re(b,g.workspaceRoot,$);if(T.count>0){const V=u.relative(g.workspaceRoot,b).replace(/\\/g,"/");if(v.push(V),S+=T.count,c==="content"){for(const J of T.matches){const Z=Buffer.byteLength(J.content,"utf-8")+64;if(_+Z>Dt){P=!0;break}_+=Z,y.push(J)}if(P)break;if(y.length>=s){P=!0;break}}else c==="count"&&E.push({file:V,count:T.count})}}const x={ok:!0,tool:"grep",pattern:o,searchPath:R(g.targetPath),outputMode:c,filesSearched:k.length,filesMatched:v.length,totalMatches:S,truncated:P};return c==="content"?x.matches=y:c==="files_with_matches"?x.matches=v:x.matches=E,x}}}function Le(t,e,o,i,a,n){const r=e||"unknown",c=[pe(t,a,n),de(t,o,a,n),he(t,o,a,n),fe(t,o,a),ye(t),ge(t,r,i,a),vt(t)];return i&&c.push(Pt(r,i),St(r,i),Mt(r,i)),c}export{Ie as DEFAULT_TOOL_PERMISSION_POLICY,me as EDIT_FAILURE_SNAPSHOT_MAX_BYTES,Yt as buildFileResourceKey,Le as createBuiltInFileTools,A as ensureInsideWorkspace,q as fileResourceClaim,Oe as getEditFailureSnapshot,ut as resolveWorkspaceTarget};
4
4
 
@@ -0,0 +1,26 @@
1
+
2
+
3
+ export type CacheControlMode = "off" | "message" | "content-block";
4
+
5
+ export interface CacheControlMessage {
6
+ role: string;
7
+ content?: unknown;
8
+ [key: string]: unknown;
9
+ }
10
+
11
+ export declare function asCacheControlMessages(messages: readonly unknown[]): CacheControlMessage[];
12
+
13
+ export interface CacheControlInjection {
14
+
15
+ index: number;
16
+
17
+ message: CacheControlMessage;
18
+ }
19
+
20
+ export declare function findPreviousNonSystemMessageIndex(messages: readonly CacheControlMessage[], startIndex: number): number | undefined;
21
+
22
+ export declare function clearNonSystemMessageCacheControl(messages: CacheControlMessage[]): void;
23
+
24
+ export declare function injectCacheControl(messages: CacheControlMessage[], mode: CacheControlMode | undefined, options?: {
25
+ skipCacheWrite?: boolean;
26
+ }): CacheControlInjection | undefined;
@@ -0,0 +1,2 @@
1
+ function s(e){return e}function l(e,n){for(let t=Math.min(n,e.length-1);t>=0;t-=1)if(e[t]?.role!=="system")return t}function h(e){for(let n=0;n<e.length;n+=1){const t=e[n];if(t.role==="system"||!("cache_control"in t))continue;const{cache_control:a,...r}=t;e[n]=r}}function x(e,n,t={}){if(!n||n==="off"||e.length===0)return;h(e);const a=l(e,e.length-1);if(a===void 0)return;const r=t.skipCacheWrite===!0?l(e,a-1):a;if(r===void 0)return;const c=e[r],i={type:"ephemeral"};if(n==="message")return{index:r,message:{...c,cache_control:{...i}}};const u=c.content;if(typeof u=="string")return{index:r,message:{...c,content:[{type:"text",text:u,cache_control:{...i}}]}};if(Array.isArray(u)){const o=u.map(d=>({...d}));if(o.length===0)return o.push({type:"text",text:"",cache_control:{...i}}),{index:r,message:{...c,content:o}};const f=o.length-1;return o[f]={...o[f],cache_control:{...i}},{index:r,message:{...c,content:o}}}return{index:r,message:{...c,cache_control:{...i}}}}export{s as asCacheControlMessages,h as clearNonSystemMessageCacheControl,l as findPreviousNonSystemMessageIndex,x as injectCacheControl};
2
+
@@ -10,41 +10,28 @@ export declare const PRUNE_PROTECT = 40000;
10
10
 
11
11
  export declare const PRUNE_MINIMUM = 20000;
12
12
 
13
- export type CompactionPruneCategory = "fileReads" | "fileEdits" | "otherTools" | "commands" | "browser";
13
+ export declare const RUNTIME_RESOURCES_PREFIX = "ACode runtime resources:";
14
14
 
15
- export declare const COMPACTION_PRUNE_CATEGORIES: readonly CompactionPruneCategory[];
15
+ export declare const RUNTIME_INSTRUCTIONS_PREFIX = "[Runtime Instructions]";
16
16
 
17
- export interface CompactionPlan {
18
-
19
- pruneCategories?: CompactionPruneCategory[];
20
-
21
- summarize?: boolean;
22
- }
17
+ export declare const COMPACTION_LLM_PROMPT_TEMPLATE: string;
23
18
 
24
- export declare function pruneCategoryOf(toolName: string): CompactionPruneCategory;
19
+ export { ESTIMATION_CJK_CHARS_PER_TOKEN } from "./token-estimator.js";
25
20
 
26
- export interface CompactionPreview {
27
-
28
- categories: Record<CompactionPruneCategory, {
29
- messages: number;
30
- tokens: number;
31
- }>;
32
-
33
- summarizableMessages: number;
34
-
35
- totalTokens: number;
36
- }
21
+ export { ESTIMATION_ASCII_CHARS_PER_TOKEN } from "./token-estimator.js";
37
22
 
38
- export declare function previewCompaction(messages: readonly ChatMessageLike[]): CompactionPreview;
23
+ export { ESTIMATION_SAFE_PADDING } from "./token-estimator.js";
39
24
 
40
- export declare const RUNTIME_RESOURCES_PREFIX = "ACode runtime resources:";
25
+ export { ESTIMATION_IMAGE_TOKENS } from "./token-estimator.js";
41
26
 
42
- export declare const COMPACTION_LLM_PROMPT_TEMPLATE: string;
27
+ export { ESTIMATION_TOOL_OVERHEAD } from "./token-estimator.js";
43
28
  interface ChatMessageLike {
44
29
  role: "system" | "user" | "assistant" | "tool";
45
30
  content: string | unknown[] | null;
46
31
  tool_call_id?: string;
47
32
  tool_calls?: unknown[];
33
+
34
+ reasoning?: string;
48
35
  }
49
36
 
50
37
  export interface CompactionResult {
@@ -68,10 +55,85 @@ export interface CompactionResult {
68
55
  prunedToolMessages: number;
69
56
 
70
57
  summarizedMessages: number;
58
+
59
+ level?: CompactionLevel;
60
+
61
+ levelLabel?: string;
62
+
63
+ ladderStep?: SummaryLadderStep;
64
+
65
+ summaryChunks?: number;
66
+
67
+ downsampleCount?: number;
68
+
69
+ droppedMessages?: number;
70
+
71
+ noSummary?: boolean;
72
+
73
+ reachedTarget?: boolean;
74
+
75
+ retryAttempts?: number;
76
+
77
+ contextTokensAfter?: number;
78
+ }
79
+
80
+ export type CompactionLevel = 1 | 2 | 3 | 4;
81
+
82
+ export type SummaryLadderStep = "S1" | "S2" | "S3" | "S4" | "S5";
83
+
84
+ export type CompactionReason = "manual" | "threshold" | "overflow" | "byte_cap" | "replay";
85
+
86
+ export interface CompactionBudget {
87
+
88
+ contextLimit: number;
89
+
90
+ maxOutput: number;
91
+
92
+ inputLimit?: number;
93
+
94
+ usableTokens: number;
95
+
96
+ toolsTokens: number;
97
+
98
+ keepRecentTokens: number;
99
+
100
+ summaryInputBudget: number;
101
+
102
+ summaryMaxTokens: number;
103
+
104
+ targetTokens: number;
105
+ }
106
+
107
+ export interface FidelityAnchors {
108
+ filePaths: string[];
109
+ commands: string[];
110
+ errors: string[];
111
+ identifiers: string[];
112
+ numbers: string[];
113
+ }
114
+
115
+ export declare class SummaryOverflowError extends Error {
116
+ readonly marker: string;
117
+ readonly kind: "overflow";
118
+ constructor(marker: string);
119
+ }
120
+
121
+ export declare class SummaryUnavailableError extends Error {
122
+ readonly attempts: number;
123
+ readonly lastError: Error;
124
+ readonly kind: "unavailable";
125
+ constructor(attempts: number, lastError: Error);
126
+ }
127
+
128
+ export interface SummaryRetryPolicy {
129
+ maxAttempts: number;
130
+ baseDelayMs?: number;
131
+ maxDelayMs?: number;
132
+ jitterMs?: number;
71
133
  }
72
134
 
73
135
  export interface CompactionPhaseEvent {
74
- phase: "prune_start" | "prune_end" | "summarize_start" | "summarize_end";
136
+ phase: "prune_start" | "prune_end" | "summarize_start" | "summarize_end" | "degrade";
75
137
 
76
138
  messageCount?: number;
77
139
 
@@ -82,16 +144,68 @@ export interface CompactionPhaseEvent {
82
144
  summarizedCount?: number;
83
145
 
84
146
  usedLLM?: boolean;
147
+
148
+ level?: CompactionLevel;
149
+
150
+ reason?: string;
151
+ }
152
+
153
+ export interface SummaryRequestMessage {
154
+ role: "system" | "user" | "assistant" | "tool";
155
+ content: string | unknown[] | null;
156
+ tool_call_id?: string;
157
+ tool_calls?: unknown[];
85
158
  }
86
159
 
87
160
  export type LLMSummarizer = (input: {
88
- conversationText: string;
161
+
162
+ messages: readonly SummaryRequestMessage[];
163
+
164
+ prefixMessages?: readonly SummaryRequestMessage[];
165
+
89
166
  messageCount: number;
90
167
  contextLimit: number;
168
+
169
+ reasoningText?: string;
170
+
171
+ previousSummary?: string;
172
+
173
+ anchors?: FidelityAnchors;
174
+
175
+ maxTokens?: number;
91
176
  }) => Promise<string>;
92
177
 
93
178
  export declare function calculateCompactionThreshold(contextLimit: number, maxOutput: number, inputLimit?: number): number;
94
179
 
180
+ export declare function calculateCompactionBudget(input: {
181
+ contextLimit: number;
182
+ maxOutput: number;
183
+ inputLimit?: number;
184
+ toolsTokens?: number;
185
+ threshold?: number;
186
+ }): CompactionBudget;
187
+
188
+ export declare function hasReachedTarget(messages: readonly ChatMessageLike[], budget: CompactionBudget): boolean;
189
+
190
+ export declare function fitsHardWindow(messages: readonly ChatMessageLike[], budget: CompactionBudget): boolean;
191
+
192
+ export declare function extractFidelityAnchors(messages: readonly ChatMessageLike[]): FidelityAnchors;
193
+
194
+ export declare function isEmptyAnchors(anchors: FidelityAnchors): boolean;
195
+
196
+ export declare function renderAnchorsForPrompt(anchors: FidelityAnchors): string;
197
+
198
+ export declare function findMissingAnchors(summary: string, anchors: FidelityAnchors): FidelityAnchors;
199
+
200
+ export declare function appendMissingAnchors(summary: string, missing: FidelityAnchors): string;
201
+
202
+ export declare function downsampleToolContent(content: string, cap: number): string;
203
+
204
+ export declare function shrinkRetainedWindow(retained: ChatMessageLike[], tokenBudget: number): {
205
+ downsampleCount: number;
206
+ droppedMessages: number;
207
+ };
208
+
95
209
  export declare function resolveReplayWindow(contextLimit: number, inputLimit?: number): number;
96
210
 
97
211
  export declare function lookupModelLimits(modelName: string, configOverrides?: {
@@ -102,14 +216,14 @@ export declare function lookupModelLimits(modelName: string, configOverrides?: {
102
216
  maxOutput: number;
103
217
  };
104
218
 
105
- export declare function estimateTextTokens(text: string): number;
106
-
107
- export declare function estimateTokens(text: string): number;
219
+ export { estimateTextTokens, estimateTokens } from "./token-estimator.js";
108
220
 
109
221
  export declare function conversationSizeBytes(messages: readonly ChatMessageLike[]): number;
110
222
 
111
223
  export declare function estimateConversationTokens(messages: readonly ChatMessageLike[]): number;
112
224
 
225
+ export declare function estimateContextTokens(messages: readonly ChatMessageLike[], toolsTokens?: number): number;
226
+
113
227
  export declare function conversationSizeKB(messages: readonly ChatMessageLike[]): number;
114
228
 
115
229
  export declare function isOverflow(messages: readonly ChatMessageLike[], contextLimit: number, _maxOutput?: number): boolean;
@@ -117,8 +231,8 @@ export declare function isOverflow(messages: readonly ChatMessageLike[], context
117
231
  export declare function isOverflowByActualUsage(accumulatedInput: number, accumulatedOutput: number, contextLimit: number): boolean;
118
232
 
119
233
  export declare function pruneToolOutputs(messages: ChatMessageLike[], contextLimit?: number, options?: {
120
- categories?: readonly CompactionPruneCategory[];
121
- manual?: boolean;
234
+
235
+ ignoreMinimumGain?: boolean;
122
236
  }): {
123
237
  prunedCount: number;
124
238
  freedTokens: number;
@@ -128,9 +242,28 @@ export declare function isCompactionSummaryMessage(message: ChatMessageLike): bo
128
242
 
129
243
  export declare function isRuntimeResourcesMessage(message: ChatMessageLike): boolean;
130
244
 
245
+ export declare function isRuntimeInstructionsMessage(message: ChatMessageLike): boolean;
246
+
131
247
  export declare function summarizeConversation(messages: ChatMessageLike[], options?: {
132
248
  llmSummarizer?: LLMSummarizer;
133
249
  contextLimit?: number;
250
+
251
+ budget?: CompactionBudget;
252
+
253
+ previousSummary?: string;
254
+
255
+ allowRuleFallback?: boolean;
256
+
257
+ retryPolicy?: SummaryRetryPolicy;
258
+
259
+ includeReasoning?: boolean;
260
+
261
+ prefixMessages?: readonly SummaryRequestMessage[];
262
+
263
+ stats?: {
264
+ downsampleCount: number;
265
+ droppedMessages: number;
266
+ };
134
267
  }): Promise<number>;
135
268
 
136
269
  export declare function snipOldestMessageGroup(messages: ChatMessageLike[]): number;
@@ -143,6 +276,15 @@ export declare function performCompaction(messages: ChatMessageLike[], contextLi
143
276
 
144
277
  force?: boolean;
145
278
 
146
- plan?: CompactionPlan;
279
+ budget?: CompactionBudget;
280
+
281
+ toolsTokens?: number;
282
+
283
+ inputLimit?: number;
284
+
285
+ retryPolicy?: SummaryRetryPolicy;
286
+
287
+ prefixMessages?: readonly SummaryRequestMessage[];
288
+
289
+ allowRuleFallback?: boolean;
147
290
  }): Promise<CompactionResult>;
148
- export {};