aws-runtime-bridge 1.9.170 → 1.9.172

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 (38) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/dist/adapter/AcodeSdkAdapter.d.ts +6 -12
  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 +4 -7
  7. package/dist/index.js +1 -1
  8. package/dist/routes/terminal.d.ts +8 -0
  9. package/dist/routes/terminal.js +27 -33
  10. package/dist/services/agent-startup-memory.d.ts +11 -0
  11. package/dist/services/agent-startup-memory.js +8 -0
  12. package/dist/services/log-retention.d.ts +37 -0
  13. package/dist/services/log-retention.js +2 -0
  14. package/dist/services/request-invalid-dump.d.ts +21 -0
  15. package/dist/services/request-invalid-dump.js +2 -0
  16. package/dist/services/session-output.d.ts +2 -0
  17. package/dist/services/session-output.js +2 -2
  18. package/dist/utils/lifecycle-log.d.ts +2 -0
  19. package/dist/utils/lifecycle-log.js +2 -2
  20. package/package/acode/dist/ask-user-question-tool.d.ts +11 -1
  21. package/package/acode/dist/ask-user-question-tool.js +3 -3
  22. package/package/acode/dist/built-in-file-tools.js +2 -2
  23. package/package/acode/dist/compaction.d.ts +143 -31
  24. package/package/acode/dist/compaction.js +20 -6
  25. package/package/acode/dist/image-utils.js +1 -1
  26. package/package/acode/dist/runtime-environment.js +1 -1
  27. package/package/acode/dist/runtime.d.ts +13 -4
  28. package/package/acode/dist/runtime.js +31 -28
  29. package/package/acode/dist/types.d.ts +1 -1
  30. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +2 -0
  31. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  32. package/package/aws-client-agent-mcp/dist/mcp-server.js +1 -1
  33. package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +4 -0
  34. package/package/aws-client-agent-mcp/dist/mcp-tools.js +32 -18
  35. package/package/aws-client-agent-mcp/dist/status-reporter.js +1 -1
  36. package/package/aws-client-agent-mcp/dist/tool-groups.js +2 -2
  37. package/package/aws-client-agent-mcp/dist/types.d.ts +15 -1
  38. package/package.json +1 -1
@@ -4,8 +4,16 @@ export interface AcodeAskUserQuestionDeps {
4
4
 
5
5
  onQuestion(toolCallId: string, questions: AcodeQuestionItem[]): void;
6
6
 
7
- waitForAnswer(toolCallId: string, contextVersion: number): Promise<Record<string, string>>;
7
+ waitForAnswer(toolCallId: string, contextVersion: number): Promise<AcodeQuestionAnswerOutcome>;
8
8
  }
9
+
10
+ export type AcodeQuestionAnswerOutcome = {
11
+ answers: Record<string, string>;
12
+ cancelled?: false;
13
+ } | {
14
+ cancelled: true;
15
+ reason?: string;
16
+ };
9
17
  export interface AcodeQuestionOption {
10
18
  label: string;
11
19
  description?: string;
@@ -22,6 +30,8 @@ export interface AcodeAskUserQuestionResult {
22
30
  tool: "ask_user_question";
23
31
  answers: Record<string, string>;
24
32
  summary: string;
33
+ cancelled?: boolean;
34
+ reason?: string;
25
35
  }
26
36
 
27
37
  export declare const ASK_USER_QUESTION_TOOL_NAME = "ask_user_question";
@@ -1,4 +1,4 @@
1
- const c="ask_user_question",f=["\u5411\u7528\u6237\u63D0\u51FA\u95EE\u9898\uFF0C\u6536\u96C6\u66F4\u591A\u4FE1\u606F\u4E3A\u505A\u51B3\u7B56\u63D0\u4F9B\u66F4\u591A\u7684\u65B9\u5411\u9009\u62E9\uFF0C\u6BCF\u4E2A\u95EE\u9898\u4F1A\u81EA\u52A8\u8FFD\u52A0\u201C\u5176\u5B83\u201D\u9009\u9879\u4F9B\u7528\u6237\u81EA\u5B9A\u4E49\u8F93\u5165\u3002","\u591A\u4E2A\u95EE\u9898\u65F6\u4E0D\u5F97\u4F9D\u8D56\u524D\u9762\u95EE\u9898\u7684\u7B54\u6848\uFF0C\u82E5\u67D0\u95EE\u9898\u4F9D\u8D56\u53E6\u4E00\u95EE\u9898\u7684\u7B54\u6848\uFF0C\u5E94\u62C6\u6210\u591A\u8F6E\u5206\u522B\u8C03\u7528\u672C\u5DE5\u5177\u3002","\u63D0\u4EA4\u540E\u8FDB\u5165\u7528\u6237\u5BA1\u6279\uFF0C\u5BA1\u6279\u901A\u8FC7\u7684\u9879\u4F1A\u76F4\u63A5\u521B\u5EFA\uFF08\u7ED3\u679C\u968F\u5DE5\u5177\u8FD4\u56DE\uFF09\u3002","\u5982\u679C\u63A8\u8350\u67D0\u4E2A\u9009\u9879\uFF0C\u628A\u5B83\u653E\u5728\u7B2C\u4E00\u4F4D\u5E76\u5728 label \u672B\u5C3E\u52A0\u201C\uFF08\u63A8\u8350\uFF09\u201D\u3002"].join(`
2
- `);function I(o,e){return{kind:"builtin",toolName:c,exposedName:c,concurrencyMode:"blocking",description:f,inputSchema:m(),async execute(n,t){const r=t?.toolCallId;if(!r)return{ok:!1,tool:c,error:"missing toolCallId in execution context"};const s=y(n.questions);if(s.length===0)return{ok:!1,tool:c,error:"questions must be a non-empty array"};o.onQuestion(r,s);const u=e();let i;try{i=await o.waitForAnswer(r,u)}catch(p){const a=p instanceof Error?p.message:String(p);return{ok:!1,tool:c,error:a}}const l=b(s,i);return{ok:!0,tool:c,answers:i,summary:l}}}}function m(){return{type:"object",properties:{questions:{type:"array",description:"\u8981\u63D0\u95EE\u7684\u95EE\u9898\u5217\u8868\uFF08\u81F3\u5C11 1 \u4E2A\uFF0C\u6570\u91CF\u4E0D\u8BBE\u4E0A\u9650\uFF09\uFF1B\u591A\u4E2A\u95EE\u9898\u65F6\u5FC5\u987B\u76F8\u4E92\u72EC\u7ACB\u3001\u5E76\u5217\u63D0\u95EE\uFF0C\u540E\u7EED\u95EE\u9898\u4E0D\u5F97\u4F9D\u8D56\u524D\u9762\u95EE\u9898\u7684\u7B54\u6848\uFF0C\u6709\u4F9D\u8D56\u5173\u7CFB\u65F6\u5E94\u62C6\u6210\u591A\u6B21\u8C03\u7528",minItems:1,items:{type:"object",properties:{question:{type:"string",description:"\u5B8C\u6574\u95EE\u9898\u6587\u672C\uFF0C\u5EFA\u8BAE\u4EE5\u95EE\u53F7\u7ED3\u5C3E"},header:{type:"string",description:"\u226412 \u5B57\u7B26\u7684\u7B80\u77ED\u6807\u7B7E\uFF0C\u7528\u4E8E UI chip \u663E\u793A"},options:{type:"array",description:"2-4 \u4E2A\u4E92\u65A5\u9009\u9879\uFF08multiSelect=true \u65F6\u53EF\u4E0D\u4E92\u65A5\uFF09",minItems:2,maxItems:4,items:{type:"object",properties:{label:{type:"string",description:"1-5 \u8BCD\u7684\u7B80\u77ED\u6807\u7B7E"},description:{type:"string",description:"\u9009\u9879\u542B\u4E49\u6216\u6743\u8861\u8BF4\u660E"},requiresCustomInput:{type:"boolean",description:"\u9009\u4E2D\u6B64\u9879\u65F6 UI \u663E\u793A\u81EA\u5B9A\u4E49\u8F93\u5165\u6846"}},required:["label"]}},multiple:{type:"boolean",description:"\u662F\u5426\u5141\u8BB8\u591A\u9009\uFF1B\u9ED8\u8BA4 false"}},required:["question","options"]}},custom:{type:"boolean",description:"\u662F\u5426\u5141\u8BB8\u7528\u6237\u8865\u5145\u81EA\u5B9A\u4E49\u8F93\u5165\uFF1B\u9ED8\u8BA4 true"}},required:["questions"]}}function y(o){if(!Array.isArray(o)||o.length===0)return[];const e=[];for(const n of o){if(!n||typeof n!="object")continue;const t=n,r=typeof t.question=="string"?t.question.trim():"";if(!r)continue;const s=d(t.options);if(s.length<2)continue;const u=typeof t.header=="string"&&t.header.trim()?t.header.trim():void 0,i=t.multiple===!0||t.multiSelect===!0;e.push({question:r,header:u,options:s,multiple:i})}return e}function d(o){if(!Array.isArray(o))return[];const e=[];for(const n of o){if(typeof n=="string"){const i=n.trim();i&&e.push({label:i});continue}if(!n||typeof n!="object")continue;const t=n,r=typeof t.label=="string"?t.label.trim():typeof t.value=="string"?t.value.trim():typeof t.text=="string"?t.text.trim():"";if(!r)continue;const s=typeof t.description=="string"&&t.description.trim()?t.description.trim():void 0,u=t.requiresCustomInput===!0||t.requireCustomInput===!0||t.allowCustomInput===!0;if(e.push({label:r,...s?{description:s}:{},...u?{requiresCustomInput:u}:{}}),e.length>=4)break}return e}function b(o,e){const n=["\u7528\u6237\u5DF2\u56DE\u7B54\u4E86\u60A8\u7684\u95EE\u9898\uFF1A"];return o.forEach((t,r)=>{const s=String(r),u=e[s]||(t.header?e[t.header]:"")||e[t.question]||"\uFF08\u672A\u586B\u5199\uFF09",i=t.header||t.question;n.push(`\u2022 ${i}\uFF1A${u}`)}),n.join(`
3
- `)}function q(o){if(!o||typeof o!="object")return!1;const e=o;return e.ok===!0&&e.tool===c&&typeof e.answers=="object"&&e.answers!==null&&typeof e.summary=="string"}function j(o){const e={ok:!0,tool:c,answers:g(o.answers),summary:o.summary};return JSON.stringify(e)}function g(o){const e={};for(const[n,t]of Object.entries(o))e[n]=t;return e}export{c as ASK_USER_QUESTION_TOOL_NAME,I as createAskUserQuestionTool,q as isAskUserQuestionResult,j as serializeAskUserQuestionResult};
1
+ const u="ask_user_question",f=["\u5411\u7528\u6237\u63D0\u51FA\u95EE\u9898\uFF0C\u6536\u96C6\u66F4\u591A\u4FE1\u606F\u4E3A\u505A\u51B3\u7B56\u63D0\u4F9B\u66F4\u591A\u7684\u65B9\u5411\u9009\u62E9\uFF0C\u6BCF\u4E2A\u95EE\u9898\u4F1A\u81EA\u52A8\u8FFD\u52A0\u201C\u5176\u5B83\u201D\u9009\u9879\u4F9B\u7528\u6237\u81EA\u5B9A\u4E49\u8F93\u5165\u3002","\u591A\u4E2A\u95EE\u9898\u65F6\u4E0D\u5F97\u4F9D\u8D56\u524D\u9762\u95EE\u9898\u7684\u7B54\u6848\uFF0C\u82E5\u67D0\u95EE\u9898\u4F9D\u8D56\u53E6\u4E00\u95EE\u9898\u7684\u7B54\u6848\uFF0C\u5E94\u62C6\u6210\u591A\u8F6E\u5206\u522B\u8C03\u7528\u672C\u5DE5\u5177\u3002","\u63D0\u4EA4\u540E\u8FDB\u5165\u7528\u6237\u5BA1\u6279\uFF0C\u5BA1\u6279\u901A\u8FC7\u7684\u9879\u4F1A\u76F4\u63A5\u521B\u5EFA\uFF08\u7ED3\u679C\u968F\u5DE5\u5177\u8FD4\u56DE\uFF09\u3002","\u5982\u679C\u63A8\u8350\u67D0\u4E2A\u9009\u9879\uFF0C\u628A\u5B83\u653E\u5728\u7B2C\u4E00\u4F4D\u5E76\u5728 label \u672B\u5C3E\u52A0\u201C\uFF08\u63A8\u8350\uFF09\u201D\u3002"].join(`
2
+ `);function q(t,o){return{kind:"builtin",toolName:u,exposedName:u,concurrencyMode:"blocking",description:f,inputSchema:d(),async execute(n,e){const r=e?.toolCallId;if(!r)return{ok:!1,tool:u,error:"missing toolCallId in execution context"};const s=b(n.questions);if(s.length===0)return{ok:!1,tool:u,error:"questions must be a non-empty array"};t.onQuestion(r,s);const c=o();let i;try{i=await t.waitForAnswer(r,c)}catch(a){const m=a instanceof Error?a.message:String(a);return{ok:!1,tool:u,error:m}}if(i.cancelled){const a=i.reason?.trim();return{ok:!0,tool:u,answers:{},summary:y(a),cancelled:!0,...a?{reason:a}:{}}}const l=i.answers,p=h(s,l);return{ok:!0,tool:u,answers:l,summary:p}}}}function y(t){return t?`\u7528\u6237\u53D6\u6D88\u4E86\u672C\u6B21\u4F5C\u7B54\u3002\u539F\u56E0\uFF1A${t}`:"\u7528\u6237\u53D6\u6D88\u4E86\u672C\u6B21\u4F5C\u7B54\uFF0C\u672A\u63D0\u4F9B\u539F\u56E0\u3002"}function d(){return{type:"object",properties:{questions:{type:"array",description:"\u8981\u63D0\u95EE\u7684\u95EE\u9898\u5217\u8868\uFF08\u81F3\u5C11 1 \u4E2A\uFF0C\u6570\u91CF\u4E0D\u8BBE\u4E0A\u9650\uFF09\uFF1B\u591A\u4E2A\u95EE\u9898\u65F6\u5FC5\u987B\u76F8\u4E92\u72EC\u7ACB\u3001\u5E76\u5217\u63D0\u95EE\uFF0C\u540E\u7EED\u95EE\u9898\u4E0D\u5F97\u4F9D\u8D56\u524D\u9762\u95EE\u9898\u7684\u7B54\u6848\uFF0C\u6709\u4F9D\u8D56\u5173\u7CFB\u65F6\u5E94\u62C6\u6210\u591A\u6B21\u8C03\u7528",minItems:1,items:{type:"object",properties:{question:{type:"string",description:"\u5B8C\u6574\u95EE\u9898\u6587\u672C\uFF0C\u5EFA\u8BAE\u4EE5\u95EE\u53F7\u7ED3\u5C3E"},header:{type:"string",description:"\u226412 \u5B57\u7B26\u7684\u7B80\u77ED\u6807\u7B7E\uFF0C\u7528\u4E8E UI chip \u663E\u793A"},options:{type:"array",description:"2-4 \u4E2A\u4E92\u65A5\u9009\u9879\uFF08multiSelect=true \u65F6\u53EF\u4E0D\u4E92\u65A5\uFF09",minItems:2,maxItems:4,items:{type:"object",properties:{label:{type:"string",description:"1-5 \u8BCD\u7684\u7B80\u77ED\u6807\u7B7E"},description:{type:"string",description:"\u9009\u9879\u542B\u4E49\u6216\u6743\u8861\u8BF4\u660E"},requiresCustomInput:{type:"boolean",description:"\u9009\u4E2D\u6B64\u9879\u65F6 UI \u663E\u793A\u81EA\u5B9A\u4E49\u8F93\u5165\u6846"}},required:["label"]}},multiple:{type:"boolean",description:"\u662F\u5426\u5141\u8BB8\u591A\u9009\uFF1B\u9ED8\u8BA4 false"}},required:["question","options"]}},custom:{type:"boolean",description:"\u662F\u5426\u5141\u8BB8\u7528\u6237\u8865\u5145\u81EA\u5B9A\u4E49\u8F93\u5165\uFF1B\u9ED8\u8BA4 true"}},required:["questions"]}}function b(t){if(!Array.isArray(t)||t.length===0)return[];const o=[];for(const n of t){if(!n||typeof n!="object")continue;const e=n,r=typeof e.question=="string"?e.question.trim():"";if(!r)continue;const s=g(e.options);if(s.length<2)continue;const c=typeof e.header=="string"&&e.header.trim()?e.header.trim():void 0,i=e.multiple===!0||e.multiSelect===!0;o.push({question:r,header:c,options:s,multiple:i})}return o}function g(t){if(!Array.isArray(t))return[];const o=[];for(const n of t){if(typeof n=="string"){const i=n.trim();i&&o.push({label:i});continue}if(!n||typeof n!="object")continue;const e=n,r=typeof e.label=="string"?e.label.trim():typeof e.value=="string"?e.value.trim():typeof e.text=="string"?e.text.trim():"";if(!r)continue;const s=typeof e.description=="string"&&e.description.trim()?e.description.trim():void 0,c=e.requiresCustomInput===!0||e.requireCustomInput===!0||e.allowCustomInput===!0;if(o.push({label:r,...s?{description:s}:{},...c?{requiresCustomInput:c}:{}}),o.length>=4)break}return o}function h(t,o){const n=["\u7528\u6237\u5DF2\u56DE\u7B54\u4E86\u60A8\u7684\u95EE\u9898\uFF1A"];return t.forEach((e,r)=>{const s=String(r),c=o[s]||(e.header?o[e.header]:"")||o[e.question]||"\uFF08\u672A\u586B\u5199\uFF09",i=e.header||e.question;n.push(`\u2022 ${i}\uFF1A${c}`)}),n.join(`
3
+ `)}function j(t){if(!t||typeof t!="object")return!1;const o=t;return o.ok===!0&&o.tool===u&&typeof o.answers=="object"&&o.answers!==null&&typeof o.summary=="string"&&(o.cancelled===void 0||typeof o.cancelled=="boolean")}function x(t){const o={ok:!0,tool:u,answers:I(t.answers),summary:t.summary,...t.cancelled?{cancelled:!0}:{},...t.reason?{reason:t.reason}:{}};return JSON.stringify(o)}function I(t){const o={};for(const[n,e]of Object.entries(t))o[n]=e;return o}export{u as ASK_USER_QUESTION_TOOL_NAME,q as createAskUserQuestionTool,j as isAskUserQuestionResult,x as serializeAskUserQuestionResult};
4
4
 
@@ -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
 
@@ -10,41 +10,18 @@ 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";
14
-
15
- export declare const COMPACTION_PRUNE_CATEGORIES: readonly CompactionPruneCategory[];
16
-
17
- export interface CompactionPlan {
18
-
19
- pruneCategories?: CompactionPruneCategory[];
20
-
21
- summarize?: boolean;
22
- }
23
-
24
- export declare function pruneCategoryOf(toolName: string): CompactionPruneCategory;
25
-
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
- }
37
-
38
- export declare function previewCompaction(messages: readonly ChatMessageLike[]): CompactionPreview;
39
-
40
13
  export declare const RUNTIME_RESOURCES_PREFIX = "ACode runtime resources:";
41
14
 
15
+ export declare const RUNTIME_INSTRUCTIONS_PREFIX = "[Runtime Instructions]";
16
+
42
17
  export declare const COMPACTION_LLM_PROMPT_TEMPLATE: string;
43
18
  interface ChatMessageLike {
44
19
  role: "system" | "user" | "assistant" | "tool";
45
20
  content: string | unknown[] | null;
46
21
  tool_call_id?: string;
47
22
  tool_calls?: unknown[];
23
+
24
+ reasoning?: string;
48
25
  }
49
26
 
50
27
  export interface CompactionResult {
@@ -68,10 +45,81 @@ export interface CompactionResult {
68
45
  prunedToolMessages: number;
69
46
 
70
47
  summarizedMessages: number;
48
+
49
+ level?: CompactionLevel;
50
+
51
+ levelLabel?: string;
52
+
53
+ ladderStep?: SummaryLadderStep;
54
+
55
+ summaryChunks?: number;
56
+
57
+ downsampleCount?: number;
58
+
59
+ noSummary?: boolean;
60
+
61
+ reachedTarget?: boolean;
62
+
63
+ retryAttempts?: number;
64
+ }
65
+
66
+ export type CompactionLevel = 1 | 2 | 3 | 4;
67
+
68
+ export type SummaryLadderStep = "S1" | "S2" | "S3" | "S4" | "S5";
69
+
70
+ export type CompactionReason = "manual" | "threshold" | "overflow" | "byte_cap" | "replay";
71
+
72
+ export interface CompactionBudget {
73
+
74
+ contextLimit: number;
75
+
76
+ maxOutput: number;
77
+
78
+ inputLimit?: number;
79
+
80
+ usableTokens: number;
81
+
82
+ toolsTokens: number;
83
+
84
+ keepRecentTokens: number;
85
+
86
+ summaryInputBudget: number;
87
+
88
+ summaryMaxTokens: number;
89
+
90
+ targetTokens: number;
91
+ }
92
+
93
+ export interface FidelityAnchors {
94
+ filePaths: string[];
95
+ commands: string[];
96
+ errors: string[];
97
+ identifiers: string[];
98
+ numbers: string[];
99
+ }
100
+
101
+ export declare class SummaryOverflowError extends Error {
102
+ readonly marker: string;
103
+ readonly kind: "overflow";
104
+ constructor(marker: string);
105
+ }
106
+
107
+ export declare class SummaryUnavailableError extends Error {
108
+ readonly attempts: number;
109
+ readonly lastError: Error;
110
+ readonly kind: "unavailable";
111
+ constructor(attempts: number, lastError: Error);
112
+ }
113
+
114
+ export interface SummaryRetryPolicy {
115
+ maxAttempts: number;
116
+ baseDelayMs?: number;
117
+ maxDelayMs?: number;
118
+ jitterMs?: number;
71
119
  }
72
120
 
73
121
  export interface CompactionPhaseEvent {
74
- phase: "prune_start" | "prune_end" | "summarize_start" | "summarize_end";
122
+ phase: "prune_start" | "prune_end" | "summarize_start" | "summarize_end" | "degrade";
75
123
 
76
124
  messageCount?: number;
77
125
 
@@ -82,16 +130,55 @@ export interface CompactionPhaseEvent {
82
130
  summarizedCount?: number;
83
131
 
84
132
  usedLLM?: boolean;
133
+
134
+ level?: CompactionLevel;
135
+
136
+ reason?: string;
85
137
  }
86
138
 
87
139
  export type LLMSummarizer = (input: {
88
140
  conversationText: string;
89
141
  messageCount: number;
90
142
  contextLimit: number;
143
+
144
+ previousSummary?: string;
145
+
146
+ anchors?: FidelityAnchors;
147
+
148
+ maxTokens?: number;
91
149
  }) => Promise<string>;
92
150
 
93
151
  export declare function calculateCompactionThreshold(contextLimit: number, maxOutput: number, inputLimit?: number): number;
94
152
 
153
+ export declare function calculateCompactionBudget(input: {
154
+ contextLimit: number;
155
+ maxOutput: number;
156
+ inputLimit?: number;
157
+ toolsTokens?: number;
158
+ threshold?: number;
159
+ }): CompactionBudget;
160
+
161
+ export declare function hasReachedTarget(messages: readonly ChatMessageLike[], budget: CompactionBudget): boolean;
162
+
163
+ export declare function fitsHardWindow(messages: readonly ChatMessageLike[], budget: CompactionBudget): boolean;
164
+
165
+ export declare function extractFidelityAnchors(messages: readonly ChatMessageLike[]): FidelityAnchors;
166
+
167
+ export declare function isEmptyAnchors(anchors: FidelityAnchors): boolean;
168
+
169
+ export declare function renderAnchorsForPrompt(anchors: FidelityAnchors): string;
170
+
171
+ export declare function findMissingAnchors(summary: string, anchors: FidelityAnchors): FidelityAnchors;
172
+
173
+ export declare function appendMissingAnchors(summary: string, missing: FidelityAnchors): string;
174
+
175
+ export declare function downsampleToolContent(content: string, cap: number): string;
176
+
177
+ export declare function shrinkRetainedWindow(retained: ChatMessageLike[], tokenBudget: number): {
178
+ downsampleCount: number;
179
+ droppedMessages: number;
180
+ };
181
+
95
182
  export declare function resolveReplayWindow(contextLimit: number, inputLimit?: number): number;
96
183
 
97
184
  export declare function lookupModelLimits(modelName: string, configOverrides?: {
@@ -117,8 +204,8 @@ export declare function isOverflow(messages: readonly ChatMessageLike[], context
117
204
  export declare function isOverflowByActualUsage(accumulatedInput: number, accumulatedOutput: number, contextLimit: number): boolean;
118
205
 
119
206
  export declare function pruneToolOutputs(messages: ChatMessageLike[], contextLimit?: number, options?: {
120
- categories?: readonly CompactionPruneCategory[];
121
- manual?: boolean;
207
+
208
+ ignoreMinimumGain?: boolean;
122
209
  }): {
123
210
  prunedCount: number;
124
211
  freedTokens: number;
@@ -128,9 +215,26 @@ export declare function isCompactionSummaryMessage(message: ChatMessageLike): bo
128
215
 
129
216
  export declare function isRuntimeResourcesMessage(message: ChatMessageLike): boolean;
130
217
 
218
+ export declare function isRuntimeInstructionsMessage(message: ChatMessageLike): boolean;
219
+
131
220
  export declare function summarizeConversation(messages: ChatMessageLike[], options?: {
132
221
  llmSummarizer?: LLMSummarizer;
133
222
  contextLimit?: number;
223
+
224
+ budget?: CompactionBudget;
225
+
226
+ previousSummary?: string;
227
+
228
+ allowRuleFallback?: boolean;
229
+
230
+ retryPolicy?: SummaryRetryPolicy;
231
+
232
+ includeReasoning?: boolean;
233
+
234
+ stats?: {
235
+ downsampleCount: number;
236
+ droppedMessages: number;
237
+ };
134
238
  }): Promise<number>;
135
239
 
136
240
  export declare function snipOldestMessageGroup(messages: ChatMessageLike[]): number;
@@ -143,6 +247,14 @@ export declare function performCompaction(messages: ChatMessageLike[], contextLi
143
247
 
144
248
  force?: boolean;
145
249
 
146
- plan?: CompactionPlan;
250
+ budget?: CompactionBudget;
251
+
252
+ toolsTokens?: number;
253
+
254
+ inputLimit?: number;
255
+
256
+ retryPolicy?: SummaryRetryPolicy;
257
+
258
+ allowRuleFallback?: boolean;
147
259
  }): Promise<CompactionResult>;
148
260
  export {};