@geoffai/coder 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,182 @@
1
+ 'use strict';var k=require('fs/promises'),A=require('path'),child_process=require('child_process'),fs=require('fs'),mt=require('openai'),os=require('os');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var k__namespace=/*#__PURE__*/_interopNamespace(k);var A__namespace=/*#__PURE__*/_interopNamespace(A);var mt__default=/*#__PURE__*/_interopDefault(mt);var Ge={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,retryableStatuses:[429,500,502,503,504]},L=class{apiKey;baseUrl;model;retryConfig;constructor(e){this.apiKey=e.apiKey,this.baseUrl=e.baseUrl.replace(/\/$/,""),this.model=e.model,this.retryConfig={...Ge,...e.retryConfig};}async sleep(e){return new Promise(n=>setTimeout(n,e))}calculateBackoff(e,n){if(n)return Math.min(n*1e3,this.retryConfig.maxDelayMs);let t=this.retryConfig.baseDelayMs*Math.pow(2,e),s=Math.random()*.3*t;return Math.min(t+s,this.retryConfig.maxDelayMs)}shouldRetry(e,n){return n<this.retryConfig.maxRetries&&this.retryConfig.retryableStatuses.includes(e)}async createCompletion(e,n,t={}){let s={model:this.model,messages:e,tools:n?.length?n:void 0,tool_choice:n?.length?"auto":void 0,stream:false,max_tokens:t.maxTokens??4096,temperature:t.temperature??.7},o=null;for(let i=0;i<=this.retryConfig.maxRetries;i++)try{let r=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)});if(!r.ok){let a=await r.text();if(this.shouldRetry(r.status,i)){let c=r.headers.get("Retry-After"),u=this.calculateBackoff(i,c?parseInt(c):void 0);console.warn(`\x1B[33m\u26A0 API request failed (${r.status}), retrying in ${Math.round(u/1e3)}s (attempt ${i+1}/${this.retryConfig.maxRetries})\x1B[0m`),await this.sleep(u);continue}throw new Error(`API request failed: ${r.status} - ${a}`)}return r.json()}catch(r){if(o=r,i<this.retryConfig.maxRetries&&r.message.includes("fetch")){let a=this.calculateBackoff(i);console.warn(`\x1B[33m\u26A0 Network error, retrying in ${Math.round(a/1e3)}s (attempt ${i+1}/${this.retryConfig.maxRetries})\x1B[0m`),await this.sleep(a);continue}throw r}throw o??new Error("Max retries exceeded")}async*createStreamingCompletion(e,n,t={}){let s={model:this.model,messages:e,tools:n?.length?n:void 0,tool_choice:n?.length?"auto":void 0,stream:true,max_tokens:t.maxTokens??4096,temperature:t.temperature??.7},o=null;for(let i=0;i<=this.retryConfig.maxRetries;i++)try{let r=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)});if(!r.ok){let d=await r.text();if(this.shouldRetry(r.status,i)){let m=r.headers.get("Retry-After"),h=this.calculateBackoff(i,m?parseInt(m):void 0);console.warn(`\x1B[33m\u26A0 API request failed (${r.status}), retrying in ${Math.round(h/1e3)}s (attempt ${i+1}/${this.retryConfig.maxRetries})\x1B[0m`),await this.sleep(h);continue}throw new Error(`API request failed: ${r.status} - ${d}`)}let a=r.body?.getReader();if(!a)throw new Error("No response body");let c=new TextDecoder,u="";try{for(;;){let{done:d,value:m}=await a.read();if(d)break;u+=c.decode(m,{stream:!0});let h=u.split(`
2
+ `);u=h.pop()??"";for(let g of h){let f=g.trim();if(!(!f||f==="data: [DONE]")&&f.startsWith("data: "))try{yield JSON.parse(f.slice(6));}catch{}}}}finally{a.releaseLock();}return}catch(r){if(o=r,i<this.retryConfig.maxRetries&&(r.message.includes("fetch")||r.message.includes("network"))){let a=this.calculateBackoff(i);console.warn(`\x1B[33m\u26A0 Network error, retrying in ${Math.round(a/1e3)}s (attempt ${i+1}/${this.retryConfig.maxRetries})\x1B[0m`),await this.sleep(a);continue}throw r}throw o??new Error("Max retries exceeded")}async accumulateStream(e,n,t={}){let s="",o=[],i=new Map;for await(let a of this.createStreamingCompletion(e,n,t)){let c=a.choices[0]?.delta;if(c){if(c.content){let u=typeof c.content=="string"?c.content:"";s+=u,t.onToken?.(u);}if(c.tool_calls)for(let u of c.tool_calls){let d=u.index??0;i.has(d)||i.set(d,{id:u.id??"",name:u.function?.name??"",args:""});let m=i.get(d);u.id&&(m.id=u.id),u.function?.name&&(m.name=u.function.name),u.function?.arguments&&(m.args+=u.function.arguments);}}}for(let[a,c]of i)c.id&&c.name&&o.push({id:c.id,type:"function",function:{name:c.name,arguments:c.args}});let r={role:"assistant",content:s||""};return o.length>0&&(r.tool_calls=o),r}};function R(l,e){let n=A.resolve(l),t=A.resolve(l,e);return !t.startsWith(n+"/")&&t!==n?{valid:false,resolvedPath:t,error:`Path "${e}" resolves outside the working directory`}:{valid:true,resolvedPath:t}}var Fe=[/rm\s+(-rf?|--recursive)?\s*[\/~]/i,/rm\s+-rf?\s*\*/i,/>\s*\/dev\/sd/i,/mkfs/i,/dd\s+.*of=\/dev/i,/:(){ :|:& };:/i,/chmod\s+(-R\s+)?777\s+\//i,/chown\s+(-R\s+)?.*\s+\//i,/curl.*\|\s*(ba)?sh/i,/wget.*\|\s*(ba)?sh/i,/eval\s*\(/i,/>\s*\/etc\//i,/rm\s+.*\/\s*$/i],Ue=[/git\s+(reset|clean)\s+--hard/i,/git\s+push\s+.*--force/i,/drop\s+database/i,/truncate\s+table/i,/delete\s+from\s+\w+\s*;?\s*$/i,/npm\s+publish/i,/pip\s+install\s+--user/i];function ke(l){for(let e of Fe)if(e.test(l))return {allowed:false,blocked:`Command contains dangerous pattern: ${e.source}`};for(let e of Ue)if(e.test(l))return {allowed:true,warning:`Command may be destructive: ${e.source}`};return {allowed:true}}var je=[/(?:api[_-]?key|apikey|secret|password|passwd|token|auth)[=:]\s*['"]?[\w\-\.]+['"]?/gi,/Bearer\s+[\w\-\.]+/gi,/ghp_[a-zA-Z0-9]{36}/g,/sk-[a-zA-Z0-9]{48}/g,/-----BEGIN.*PRIVATE KEY-----/gi];function U(l){let e=l;for(let n of je)e=e.replace(n,"[REDACTED]");return e}var ve=".geoff",we="todos";function Pe(l){let e=process.env.HOME||process.env.USERPROFILE||process.cwd(),n=A__namespace.join(e,ve,we),t=`${l||"default"}.json`;return A__namespace.join(n,t)}async function Je(l){try{let e=Pe(l),n=await k__namespace.readFile(e,"utf-8"),t=JSON.parse(n);return Array.isArray(t.todos)?t.todos:[]}catch(e){if(e.code!=="ENOENT")throw e;return []}}async function _e(l,e){let n=Pe(e),t=A__namespace.dirname(n);await k__namespace.mkdir(t,{recursive:true});let s={todos:l,sessionId:e||"default",updatedAt:new Date().toISOString()};await k__namespace.writeFile(n,JSON.stringify(s,null,2),"utf-8");}function Z(l){return async e=>{try{let n=e,{todos:t}=n;if(!Array.isArray(t))return {success:!1,output:"",error:'Parameter "todos" must be an array.'};for(let u of t){if(!u.id||typeof u.id!="string"||u.id.trim()==="")return {success:!1,output:"",error:'Each todo must have a non-empty "id" string.'};if(!u.content||typeof u.content!="string"||u.content.trim()==="")return {success:!1,output:"",error:'Each todo must have a non-empty "content" string.'};if(!["pending","in_progress","completed"].includes(u.status))return {success:!1,output:"",error:'Each todo must have a valid "status" (pending, in_progress, completed).'}}let s=t.map(u=>u.id);if(new Set(s).size!==s.length)return {success:!1,output:"",error:"Todo IDs must be unique."};await _e(t,l);let o=t.filter(u=>u.status==="pending").length,i=t.filter(u=>u.status==="in_progress").length,r=t.filter(u=>u.status==="completed").length,a;t.length===0?a="Todo list cleared.":a=`Todo list updated: ${r} completed, ${i} in progress, ${o} pending.`;let c=JSON.stringify(t);return a+=`
3
+
4
+ <system-reminder>
5
+ Your todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list:
6
+
7
+ ${c}. Continue on with the tasks at hand if applicable.
8
+ </system-reminder>`,{success:!0,output:a}}catch(n){return {success:false,output:"",error:`Failed to write todos: ${n instanceof Error?n.message:String(n)}`}}}}var ee={type:"function",function:{name:"todo_write",description:"Creates and manages a structured task list for your current coding session. This helps track progress, organize complex tasks, and demonstrate thoroughness. Use for complex multi-step tasks (3+ steps), when user provides multiple tasks, or when starting/completing work. Do NOT use for single trivial tasks.",parameters:{type:"object",properties:{todos:{type:"array",description:"The updated todo list"}},required:["todos"]}}};async function ze(){try{let l=process.env.HOME||process.env.USERPROFILE||process.cwd(),e=A__namespace.join(l,ve,we);return (await k__namespace.readdir(e)).filter(t=>t.endsWith(".json")).map(t=>t.replace(".json",""))}catch(l){if(l.code!=="ENOENT")throw l;return []}}var te=new Map;function G(l="default"){return te.has(l)||te.set(l,{enabled:false,awaitingApproval:false,approved:false}),te.get(l)}function Be(l,e){let n=G(l);n.awaitingApproval=false,n.approved=e,e&&(n.enabled=false);}function Re(l="default"){let e=G(l);e.enabled=true,e.approved=false,e.awaitingApproval=false;}function He(l="default"){return G(l).enabled}function ne(l,e){return async n=>{try{let t=n,{plan:s}=t;if(!s||typeof s!="string"||s.trim()==="")return {success:!1,output:"",error:'Parameter "plan" must be a non-empty string.'};let o=G(l||"default");if(o.plan=s,o.awaitingApproval=!0,e){let i={type:"thinking",timestamp:Date.now(),data:{planMode:!0,plan:s,awaitingApproval:!0,sessionId:l||"default"}};e(i);}return o.awaitingApproval=!1,o.approved=!0,o.enabled=!1,{success:!0,output:`Plan presented for approval:
9
+
10
+ ${s}
11
+
12
+ User has approved your plan. You can now start coding. Start with updating your todo list if applicable.`}}catch(t){return {success:false,output:"",error:`Failed to exit plan mode: ${t instanceof Error?t.message:String(t)}`}}}}var se={type:"function",function:{name:"exit_plan_mode",description:"Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to approve the plan. IMPORTANT: Only use this tool when planning implementation steps for coding tasks. For research tasks (searching files, reading code, understanding codebase) - do NOT use this tool.",parameters:{type:"object",properties:{plan:{type:"string",description:"The plan you came up with, that you want the user to approve. Supports markdown. Should be concise but complete."}},required:["plan"]}}};function oe(l,e){return async n=>{try{if(Re(l||"default"),e){let t={type:"thinking",timestamp:Date.now(),data:{planMode:!0,enabled:!0,sessionId:l||"default",message:"Entering plan mode - will create a plan before coding"}};e(t);}return {success:!0,output:"Entered plan mode. Please create a plan before starting implementation."}}catch(t){return {success:false,output:"",error:`Failed to enter plan mode: ${t instanceof Error?t.message:String(t)}`}}}}var re={type:"function",function:{name:"enter_plan_mode",description:"Enter plan mode to create a plan before implementing code changes. Use this when starting a complex task that requires planning. In plan mode, create a clear plan and then use exit_plan_mode to get approval.",parameters:{type:"object",properties:{},required:[]}}};var ie=class{processes=new Map;counter=0;start(e,n,t){let s=`bg_${++this.counter}_${Date.now()}`,o=child_process.spawn("bash",["-c",e],{cwd:n,env:{...process.env,FORCE_COLOR:"0"},detached:false}),i={id:s,pid:o.pid||0,command:e,startTime:Date.now(),output:[],isComplete:false,exitCode:null,process:o};return o.stdout?.on("data",r=>{let a=r.toString();if(i.output.push(a),i.output.length>1e3&&(i.output=i.output.slice(-500)),t){let c={type:"thinking",timestamp:Date.now(),data:{processId:s,type:"stdout",output:a,isBackground:true}};t(c);}}),o.stderr?.on("data",r=>{let a=r.toString();if(i.output.push(`[stderr] ${a}`),t){let c={type:"thinking",timestamp:Date.now(),data:{processId:s,type:"stderr",output:a,isBackground:true}};t(c);}}),o.on("close",r=>{if(i.isComplete=true,i.exitCode=r,t){let a={type:"thinking",timestamp:Date.now(),data:{processId:s,type:"exit",exitCode:r,isBackground:true,message:`Background process ${s} exited with code ${r}`}};t(a);}}),o.on("error",r=>{i.isComplete=true,i.output.push(`[error] ${r.message}`);}),this.processes.set(s,i),i}get(e){return this.processes.get(e)}getAll(){return Array.from(this.processes.values())}kill(e){let n=this.processes.get(e);if(!n)return false;try{return n.process.kill("SIGTERM"),setTimeout(()=>{try{n.process.kill("SIGKILL");}catch{}},1e3),!0}catch{return false}}getOutput(e,n){let t=this.processes.get(e);if(!t)return "";let s=t.output;return n&&n<s.length?s.slice(-n).join(""):s.join("")}cleanup(){for(let[e,n]of this.processes)n.isComplete&&this.processes.delete(e);}},v=new ie;function ae(l,e){return async n=>{try{let t=n.command;if(!t||typeof t!="string")return {success:!1,output:"",error:'Parameter "command" must be a non-empty string.'};let s=v.start(t,l,e);await new Promise(i=>setTimeout(i,500));let o=v.getOutput(s.id,20);return {success:!0,output:`Started background process:
13
+ ID: ${s.id}
14
+ PID: ${s.pid}
15
+ Command: ${t}
16
+
17
+ Initial output:
18
+ ${o||"(no output yet)"}
19
+
20
+ Use get_process_output to check status or kill_process to stop.`}}catch(t){return {success:false,output:"",error:`Failed to start background process: ${t instanceof Error?t.message:String(t)}`}}}}function le(){return async l=>{try{let e=l.process_id,n=l.tail;if(!e||typeof e!="string")return {success:!1,output:"",error:'Parameter "process_id" must be a non-empty string.'};let t=v.get(e);if(!t){let r=v.getAll();if(r.length===0)return {success:!1,output:"",error:`No background processes found. Process ID ${e} is invalid.`};let a=r.map(c=>` ${c.id}: ${c.command.slice(0,50)} (${c.isComplete?"completed":"running"})`).join(`
21
+ `);return {success:!1,output:"",error:`Process ${e} not found. Available processes:
22
+ ${a}`}}let s=v.getOutput(e,n||50),o=Math.round((Date.now()-t.startTime)/1e3),i;return t.isComplete?i=`Completed (exit code: ${t.exitCode})`:i="Running",{success:!0,output:`Process: ${e}
23
+ Status: ${i}
24
+ Duration: ${o}s
25
+ Command: ${t.command}
26
+
27
+ Output:
28
+ ${s||"(no output)"}`}}catch(e){return {success:false,output:"",error:`Failed to get process output: ${e instanceof Error?e.message:String(e)}`}}}}function ce(){return async l=>{try{let e=l.process_id;return !e||typeof e!="string"?{success:!1,output:"",error:'Parameter "process_id" must be a non-empty string.'}:v.kill(e)?{success:!0,output:`Process ${e} has been killed.`}:{success:!1,output:"",error:`Failed to kill process ${e}. It may not exist or already be terminated.`}}catch(e){return {success:false,output:"",error:`Failed to kill process: ${e instanceof Error?e.message:String(e)}`}}}}function ue(){return async l=>{try{let e=v.getAll();return e.length===0?{success:!0,output:"No background processes running."}:{success:!0,output:`Background processes:
29
+
30
+ ${e.map(t=>{let s=Math.round((Date.now()-t.startTime)/1e3),o=t.isComplete?`completed (exit: ${t.exitCode})`:"running";return ` ${t.id}:
31
+ Command: ${t.command.slice(0,60)}${t.command.length>60?"...":""}
32
+ Status: ${o}
33
+ Duration: ${s}s`}).join(`
34
+
35
+ `)}`}}catch(e){return {success:false,output:"",error:`Failed to list processes: ${e instanceof Error?e.message:String(e)}`}}}}var pe={type:"function",function:{name:"run_background",description:"Start a command running in the background. Useful for dev servers, watch processes, or long-running tasks. Returns immediately with a process ID. Use get_process_output to check status.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to run in the background"}},required:["command"]}}},me={type:"function",function:{name:"get_process_output",description:"Get the output from a background process. Returns recent output and status.",parameters:{type:"object",properties:{process_id:{type:"string",description:"The ID of the background process"},tail:{type:"string",description:"Number of recent lines to return (default: 50)"}},required:["process_id"]}}},de={type:"function",function:{name:"kill_process",description:"Kill a background process by ID.",parameters:{type:"object",properties:{process_id:{type:"string",description:"The ID of the background process to kill"}},required:["process_id"]}}},ge={type:"function",function:{name:"list_processes",description:"List all background processes and their status.",parameters:{type:"object",properties:{},required:[]}}};var Ye=[{type:"function",function:{name:"read_file",description:"Read the contents of a file at the specified path. Use this to examine existing code, configuration files, or any text file.",parameters:{type:"object",properties:{path:{type:"string",description:"The path to the file to read (relative to working directory or absolute)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Write content to a file, creating it if it doesn't exist or overwriting if it does. Creates parent directories as needed.",parameters:{type:"object",properties:{path:{type:"string",description:"The path where the file should be written"},content:{type:"string",description:"The content to write to the file"}},required:["path","content"]}}},{type:"function",function:{name:"list_files",description:"List files and directories at the specified path. Returns a tree-like structure showing the contents.",parameters:{type:"object",properties:{path:{type:"string",description:"The directory path to list (defaults to current working directory)"},recursive:{type:"string",description:"Whether to list recursively (true/false, defaults to false)",enum:["true","false"]},max_depth:{type:"string",description:"Maximum depth for recursive listing (default: 3)"}},required:["path"]}}},{type:"function",function:{name:"execute_command",description:"Execute a shell command in the working directory. Use for running scripts, installing packages, git operations, tests, etc. Commands run in bash.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},timeout:{type:"string",description:"Timeout in milliseconds (default: 30000)"}},required:["command"]}}},{type:"function",function:{name:"search_files",description:"Search for files matching a pattern or containing specific text using grep. Returns matching files and lines.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The text pattern or regex to search for"},path:{type:"string",description:"Directory to search in (defaults to working directory)"},file_pattern:{type:"string",description:"Glob pattern to filter files (e.g., '*.ts', '*.py')"}},required:["pattern"]}}},{type:"function",function:{name:"apply_diff",description:"Apply a diff/patch to modify specific parts of a file. Use for precise edits instead of rewriting entire files.",parameters:{type:"object",properties:{path:{type:"string",description:"The path to the file to modify"},original:{type:"string",description:"The exact original text to find and replace"},replacement:{type:"string",description:"The new text to replace the original with"},replace_all:{type:"string",description:"Whether to replace all occurrences (true/false, defaults to false)",enum:["true","false"]}},required:["path","original","replacement"]}}},{type:"function",function:{name:"task_complete",description:"Signal that the task has been completed. Use this when you have finished the user's request and want to present the final result.",parameters:{type:"object",properties:{summary:{type:"string",description:"A brief summary of what was accomplished"},files_modified:{type:"string",description:"Comma-separated list of files that were created or modified"}},required:["summary"]}}},ee,re,se,pe,me,de,ge],Ie=["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".cache",".parcel-cache"];function F(l){let e=typeof l=="string"?l:l.workingDir,n=typeof l=="string"?Ie:l.ignorePatterns??Ie,t=new Map;return t.set("read_file",async s=>{try{let o=R(e,s.path);if(!o.valid)return {success:!1,output:"",error:o.error};if((await k.stat(o.resolvedPath)).isDirectory()){let a=await k.readdir(o.resolvedPath);return {success:!1,output:"",error:`Path is a directory, not a file. Contents: ${a.slice(0,20).join(", ")}${a.length>20?` ... and ${a.length-20} more`:""}`}}let r=await k.readFile(o.resolvedPath,"utf-8");return {success:!0,output:U(r)}}catch(o){return {success:false,output:"",error:`Failed to read file: ${o.message}`}}}),t.set("write_file",async s=>{try{let o=R(e,s.path);return o.valid?(await k.mkdir(A.dirname(o.resolvedPath),{recursive:!0}),await k.writeFile(o.resolvedPath,s.content,"utf-8"),{success:!0,output:`Successfully wrote to ${s.path}`}):{success:!1,output:"",error:o.error}}catch(o){return {success:false,output:"",error:`Failed to write file: ${o.message}`}}}),t.set("list_files",async s=>{try{let o=R(e,s.path||".");if(!o.valid)return {success:!1,output:"",error:o.error};let i=o.resolvedPath,r=s.recursive==="true",a=parseInt(s.max_depth)||3;async function c(d,m,h){if(m>a)return [];let g=await k.readdir(d,{withFileTypes:!0}),f=[];for(let C of g){if(n.some(P=>P.includes("*")?new RegExp("^"+P.replace(/\*/g,".*")+"$").test(C.name):C.name===P))continue;let Q=C.isDirectory();if(f.push(`${h}${Q?"\u{1F4C1} ":"\u{1F4C4} "}${C.name}`),Q&&r&&m<a){let P=await c(A.join(d,C.name),m+1,h+" ");f.push(...P);}}return f}return {success:!0,output:(await c(i,0,"")).join(`
36
+ `)||"(empty directory)"}}catch(o){return {success:false,output:"",error:`Failed to list files: ${o.message}`}}}),t.set("execute_command",async s=>{let o=s.command,i=parseInt(s.timeout)||3e4,r=ke(o);return r.allowed?(r.warning&&console.warn(`\x1B[33m\u26A0 Warning: ${r.warning}\x1B[0m`),new Promise(a=>{let c=child_process.spawn("bash",["-c",o],{cwd:e,timeout:i,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";c.stdout.on("data",m=>{u+=m.toString();}),c.stderr.on("data",m=>{d+=m.toString();}),c.on("close",m=>{let h=U([u,d].filter(Boolean).join(`
37
+ `));a(m===0?{success:true,output:h||"(no output)"}:{success:false,output:h,error:`Command exited with code ${m}`});}),c.on("error",m=>{a({success:false,output:"",error:`Failed to execute command: ${m.message}`});});})):{success:false,output:"",error:`Command blocked: ${r.blocked}`}}),t.set("search_files",async s=>{let o=s.pattern,i=R(e,s.path||".");if(!i.valid)return {success:false,output:"",error:i.error};let r=i.resolvedPath,a=s.file_pattern,c=o.replace(/['"\\]/g,"\\$&"),u=(a||"*").replace(/['"\\]/g,"\\$&"),d=`rg -n --glob '${u}' '${c}' '${r}' 2>/dev/null | head -50`,m=`grep -rn --include='${u}' '${c}' '${r}' 2>/dev/null | head -50`;return new Promise(h=>{let g=child_process.spawn("bash",["-c",`command -v rg >/dev/null && ${d} || ${m}`],{cwd:e}),f="";g.stdout.on("data",C=>{f+=C.toString();}),g.on("close",()=>{if(f){let C=U(f).split(`
38
+ `).map(T=>T.startsWith(e)?T.replace(e+"/",""):T).join(`
39
+ `);h({success:true,output:C});}else h({success:true,output:"No matches found"});});})}),t.set("apply_diff",async s=>{try{let o=R(e,s.path);if(!o.valid)return {success:!1,output:"",error:o.error};let i=o.resolvedPath,r=s.original,a=s.replacement,c=s.replace_all==="true"||s.replace_all===!0,u=await k.readFile(i,"utf-8");if(!u.includes(r))return {success:!1,output:"",error:"Original text not found in file. Please verify the exact text to replace."};let d=u.split(r).length-1,m=c||d===1?u.replaceAll(r,a):u.replace(r,a);return await k.writeFile(i,m,"utf-8"),{success:!0,output:d>1&&!c?`Successfully applied diff to ${s.path} (1 of ${d} occurrences). Use replace_all: true to replace all.`:`Successfully applied diff to ${s.path}${d>1?` (${d} occurrences)`:""}`}}catch(o){return {success:false,output:"",error:`Failed to apply diff: ${o.message}`}}}),t.set("task_complete",async s=>({success:true,output:`\u2705 Task Complete
40
+
41
+ ${s.summary}${s.files_modified?`
42
+
43
+ Modified files: ${s.files_modified}`:""}`})),t.set("todo_write",Z()),t.set("enter_plan_mode",oe()),t.set("exit_plan_mode",ne()),t.set("run_background",ae(e)),t.set("get_process_output",le()),t.set("kill_process",ce()),t.set("list_processes",ue()),{definitions:Ye,handlers:t}}function et(l){let e=[A.join(l,"AGENTS.md"),A.join(l,".agents.md"),A.join(l,"CLAUDE.md"),A.join(l,".claude.md")];for(let n of e)if(fs.existsSync(n))try{return fs.readFileSync(n,"utf-8").trim()}catch{}return null}function z(l){let e=et(l.workingDirectory),n=`You are an AI coding agent operating in a terminal environment. You help users with software engineering tasks by reading, writing, and executing code.
44
+
45
+ ## Your Capabilities
46
+ - Read and analyze files in the codebase
47
+ - Write and modify files with precise edits
48
+ - Execute shell commands (bash) for builds, tests, git, etc.
49
+ - Search through code to find relevant files and patterns
50
+ - Apply targeted diffs for surgical code changes
51
+
52
+ ## Working Directory
53
+ ${l.workingDirectory}
54
+
55
+ ## Operating System
56
+ ${l.osInfo}
57
+
58
+ ## Guidelines
59
+
60
+ ### Task Execution
61
+ - Break complex tasks into steps and execute them methodically
62
+ - Read files before modifying them to understand the context
63
+ - Use apply_diff for small changes; write_file for new files or large rewrites
64
+ - Verify your changes by reading the file after modification when appropriate
65
+ - Run relevant tests or builds after making changes
66
+
67
+ ### Code Quality
68
+ - Follow existing code style and patterns in the project
69
+ - Add appropriate error handling
70
+ - Write clean, maintainable code
71
+ - Include comments for complex logic
72
+
73
+ ### Tool Usage
74
+ - Use the most appropriate tool for each task
75
+ - Prefer apply_diff over write_file for existing files when making small changes
76
+ - Use search_files to find relevant code before making changes
77
+ - Execute commands to verify your work (run tests, check syntax, etc.)
78
+
79
+ ### Communication
80
+ - Explain what you're doing and why
81
+ - Report errors clearly and suggest fixes
82
+ - Summarize your changes when completing a task
83
+ - Ask clarifying questions if the request is ambiguous
84
+
85
+ ### Safety
86
+ - Never execute destructive commands without explicit confirmation
87
+ - Be careful with rm, git reset --hard, and similar operations
88
+ - Don't expose secrets or credentials
89
+ - Respect file permissions and ownership
90
+
91
+ ## Important Rules
92
+ 1. Always verify file paths exist before writing
93
+ 2. Never guess at file contents - read them first
94
+ 3. Keep iterating until the task is fully complete
95
+ 4. Use task_complete when you've finished the user's request
96
+ 5. If stuck, explain the issue and ask for guidance`;return e?`${n}
97
+
98
+ ## Project-Specific Instructions
99
+ The following instructions are specific to this project and should be followed:
100
+
101
+ ${e}`:n}var tt=[{id:"task_focus",content:`<system-reminder>
102
+ Stay focused on the current task. Do what was asked - nothing more, nothing less.
103
+ Do not create unnecessary files or make changes beyond the scope of the request.
104
+ </system-reminder>`,injectionPoint:"pre_user_message",priority:10},{id:"verify_changes",content:`<system-reminder>
105
+ After making file changes, verify they were applied correctly if the task is complex.
106
+ Consider running relevant tests or build commands to catch errors early.
107
+ </system-reminder>`,injectionPoint:"post_tool_result",priority:5,condition:l=>{let e=l.lastToolCalls[0];return e?.function?.name==="write_file"||e?.function?.name==="apply_diff"}},{id:"iteration_warning",content:`<system-reminder>
108
+ You have been running for several iterations. Make sure you are making progress.
109
+ If stuck, consider:
110
+ - Re-reading the original request
111
+ - Checking for errors in your approach
112
+ - Asking the user for clarification
113
+ </system-reminder>`,injectionPoint:"context_refresh",priority:8,condition:l=>l.iteration>5},{id:"complete_task",content:`<system-reminder>
114
+ If you have finished the user's request, use the task_complete tool to signal completion.
115
+ Provide a clear summary of what was accomplished.
116
+ </system-reminder>`,injectionPoint:"task_boundary",priority:7,condition:l=>l.iteration>2},{id:"file_operation_reminder",content:`<system-reminder>
117
+ When modifying existing files:
118
+ - ALWAYS read the file first to understand its current state
119
+ - ALWAYS prefer apply_diff for small, targeted changes
120
+ - Use write_file only for new files or complete rewrites
121
+ </system-reminder>`,injectionPoint:"pre_user_message",priority:6}];function J(l,e){return tt.filter(n=>n.injectionPoint===e).filter(n=>!n.condition||n.condition(l)).sort((n,t)=>t.priority-n.priority).map(n=>n.content)}function B(l,e,n){let t=J(e,"pre_user_message"),s=[];return t.length>0&&s.push(t.join(`
122
+ `)),s.push(l),s.join(`
123
+
124
+ `)}function H(l,e,n){let t=J(e,"post_tool_result"),s=[l];return t.length>0&&s.push(t.join(`
125
+ `)),s.join(`
126
+
127
+ `)}function q(l){return [...J(l,"context_refresh"),...J(l,"task_boundary")].join(`
128
+
129
+ `)}var p={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",clearLine:"\x1B[2K"},x={h:"\u2500",v:"\u2502",tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",hDouble:"\u2550",hHeavy:"\u2501"},y={success:"\u2713",error:"\u2717",warn:"\u26A0",info:"\u2139",tool:"\u{1F527}",user:"\u{1F464}",bot:"\u{1F916}",stats:"\u{1F4CA}",tokens:"\u{1F524}",files:"\u{1F4C1}",code:"\u{1F4DD}",exec:"\u2699\uFE0F",diamond:"\u25C8"},w=class{verbose;currentMetricsLine=null;onLogEvent;constructor(e=false,n){this.verbose=e,this.onLogEvent=n;}setLogEventCallback(e){this.onLogEvent=e;}emit(e,n){this.onLogEvent&&this.onLogEvent({type:e,timestamp:Date.now(),data:n});}timestamp(){return new Date().toISOString().split("T")[1].slice(0,8)}num(e){return e.toLocaleString()}truncate(e,n){return e.length>n?e.slice(0,n)+"...":e}colorize(e,n){return `${n}${e}${p.reset}`}statusIcon(e){return e?this.colorize(y.success,p.green):this.colorize(y.error,p.red)}line(e=x.h,n=60){return this.colorize(e.repeat(n),p.dim)}label(e,n,t=p.cyan){return ` ${e.padEnd(13)}${this.colorize(n,t)}`}section(e,n){this.print(`${p.bright}${n} ${e}${p.reset}`);}clearStatusLine(){this.currentMetricsLine!==null&&process.stdout.write(`\r${p.clearLine}`);}restoreStatusLine(){this.currentMetricsLine!==null&&process.stdout.write(this.currentMetricsLine);}print(e){this.clearStatusLine(),console.log(e),this.restoreStatusLine();}info(e){this.emit("info",{message:e}),this.print(`${this.colorize(y.info,p.blue)} ${e}`);}debug(e){this.verbose&&this.print(this.colorize(`${this.timestamp()} ${e}`,p.gray));}warn(e){this.emit("warn",{message:e}),this.print(`${this.colorize(y.warn,p.yellow)} ${e}`);}error(e){this.emit("error",{message:e}),this.print(`${this.colorize(y.error,p.red)} ${e}`);}success(e){this.emit("success",{message:e}),this.print(`${this.colorize(y.success,p.green)} ${e}`);}tool(e,n){if(this.emit("tool_call",{toolName:e,toolArgs:n}),e==="task_complete")try{let t=JSON.parse(n);this.emit("task_complete",{message:t.summary,toolName:e}),this.clearStatusLine(),console.log(`
130
+ ${this.colorize(`${y.success} Task Complete`,p.green)}`),t.summary&&console.log(this.colorize(t.summary,p.dim)),console.log(),this.restoreStatusLine();return}catch{}this.print(`${this.colorize(`${y.tool} ${e}`,p.cyan)} ${this.colorize(this.truncate(n,200),p.dim)}`);}toolResult(e,n){if(this.emit("tool_result",{toolName:e,success:n.success,output:n.output,error:n.error}),e==="task_complete")return;let t=this.statusIcon(n.success);if(this.verbose){let s=this.truncate(n.output,500);this.print(`${t} ${this.colorize(`${e}:`,p.dim)}`),s&&this.print(this.colorize(s,p.gray)),n.error&&this.print(this.colorize(n.error,p.red));}else {let s=n.output.split(`
131
+ `)[0].slice(0,80)||"(no output)";this.print(`${t} ${this.colorize(s,p.dim)}`);}}assistant(e){this.emit("assistant_message",{message:e}),this.clearStatusLine(),console.log(`
132
+ ${this.colorize(`${y.bot} Geoff:`,p.magenta)}`),console.log(e),console.log(),this.restoreStatusLine();}user(e){this.emit("user_message",{message:e}),this.clearStatusLine(),console.log(`
133
+ ${this.colorize(`${y.user} You:`,p.green)} ${e}
134
+ `),this.restoreStatusLine();}separator(){this.print(this.line());}banner(){let n=(c,u,d="")=>`${p.cyan}${c}${d.padEnd(61)}${u}${p.reset}`,t=c=>n(x.v,x.v,c),s=t(""),o=["\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2591\u2588\u2588\u2588\u2588\u2588\u2557\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2591\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2551\u2591\u2591\u2588\u2588\u2557\u2591\u2588\u2588\u2588\u2588\u2588\u2557\u2591\u2591\u2588\u2588\u2551\u2591\u2591\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2557\u2591\u2591","\u2588\u2588\u2551\u2591\u2591\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u255D\u2591\u2591\u2588\u2588\u2551\u2591\u2591\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D\u2591\u2591\u2588\u2588\u2554\u2550\u2550\u255D\u2591\u2591","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2551\u2591\u2591\u2591\u2591\u2591","\u2591\u255A\u2550\u2550\u2550\u2550\u2550\u255D\u2591\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u2591\u255A\u2550\u2550\u2550\u2550\u255D\u2591\u255A\u2550\u255D\u2591\u2591\u2591\u2591\u2591\u255A\u2550\u255D\u2591\u2591\u2591\u2591\u2591"],i=`${p.dim}${x.hHeavy.repeat(41)}${p.reset}${p.cyan}`,r=`${p.bright}C O D E R V E R S I O N 1 : 1${p.reset}${p.cyan}`,a=[y.diamond,"Reasoning",y.diamond,"Planning",y.diamond,"Execution",y.diamond,"Learning"].map((c,u)=>u%2===0?`${p.yellow}${c}${p.reset}${p.cyan}`:c).join(" ");console.log(),console.log(n(x.tl,x.tr,x.h.repeat(61))),console.log(s),o.forEach(c=>console.log(t(` ${p.bright}${c}${p.reset}${p.cyan} `))),console.log(s),console.log(t(` ${i} `)),console.log(t(` ${r} `)),console.log(t(` ${i} `)),console.log(s),console.log(t(` ${a} `)),console.log(s),console.log(n(x.bl,x.br,x.h.repeat(61))),console.log();}config(e){this.print(this.colorize("Configuration:",p.dim));for(let[n,t]of Object.entries(e)){let s=n==="apiKey"?"***":String(t);this.print(` ${n}: ${this.colorize(s,n==="apiKey"?p.dim:p.cyan)}`);}this.print("");}metricsUpdate(e,n){this.emit("metrics_update",{iteration:n,metrics:e});let t=((Date.now()-e.startTime)/1e3).toFixed(1),s=[`[Iter ${n}]`,`${p.cyan}ctx:${this.num(e.contextSize)}${p.dim}`,`${p.green}+${e.linesAdded}${p.dim}/${p.red}-${e.linesRemoved}${p.dim} lines`,`${p.yellow}${e.filesCreated} new${p.dim}/${p.blue}${e.filesModified} mod${p.dim} files`,`${p.magenta}${this.num(e.tokensUsed)} tok${p.dim}`,`${t}s`];this.currentMetricsLine=`\r${p.dim}${s.join(" | ")}${p.reset}`,process.stdout.write(`\r${p.clearLine}${this.currentMetricsLine}`);}clearMetricsLine(){this.currentMetricsLine=null,process.stdout.write(`\r${p.clearLine}`);}metricsSummary(e,n){this.clearMetricsLine();let t=((Date.now()-e.startTime)/1e3).toFixed(1),s=e.linesAdded-e.linesRemoved,o=s>=0?p.green:p.red,i=s>=0?"+":"";console.log(`
135
+ ${p.bright}${p.cyan}${x.hDouble.repeat(55)}${p.reset}`),console.log(`${p.bright} ${y.stats} Session Summary${p.reset}`),console.log(`${p.cyan}${x.hDouble.repeat(55)}${p.reset}
136
+ `),this.section("Tokens",y.tokens),console.log(this.label("Total:",this.num(e.tokensUsed),p.magenta)),console.log(this.label("Prompt:",this.num(e.promptTokens),p.dim)),console.log(this.label("Completion:",this.num(e.completionTokens),p.dim)),console.log(this.label("Context:",`${this.num(e.contextSize)} (final)`,p.cyan)),console.log(),this.section("Files",y.files),console.log(this.label("Created:",e.filesCreated,p.green));for(let r of e.createdFiles)console.log(this.colorize(` + ${r}`,p.dim));console.log(this.label("Modified:",e.filesModified,p.yellow));for(let r of e.modifiedFiles)console.log(this.colorize(` ~ ${r}`,p.dim));console.log(),this.section("Code Changes",y.code),console.log(this.label("Lines added:",`+${this.num(e.linesAdded)}`,p.green)),console.log(this.label("Lines removed:",`-${this.num(e.linesRemoved)}`,p.red)),console.log(this.label("Net change:",`${i}${this.num(s)}`,o)),console.log(),this.section("Execution",y.exec),console.log(this.label("Iterations:",n,p.blue)),console.log(this.label("API calls:",e.apiCalls,p.dim)),console.log(this.label("Tool calls:",e.toolCallsTotal,p.dim)),console.log(this.label("Commands run:",e.commandsExecuted,p.dim)),console.log(this.label("Duration:",`${t}s`,p.dim)),console.log(`
137
+ ${p.cyan}${x.hDouble.repeat(55)}${p.reset}
138
+ `);}iterationHeader(e,n){this.clearMetricsLine(),console.log(`
139
+ ${this.colorize(`${x.h.repeat(3)} Iteration ${e}/${n} ${x.h.repeat(40)}`,p.dim)}`);}};var W={"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4-turbo":128e3,"gpt-4":8192,"gpt-4-32k":32768,"gpt-3.5-turbo":16385,"gpt-3.5-turbo-16k":16385,"claude-3-opus":2e5,"claude-3-sonnet":2e5,"claude-3-haiku":2e5,"claude-3-5-sonnet":2e5,llama3:8192,"llama3:70b":8192,codellama:16384,mistral:32768,mixtral:32768,"qwen3-coder":131072,"qwen3-coder:30b":131072,"qwen3:30b":131072,"qwen3:8b":131072,qwen3:131072,"qwen2.5-coder":131072,default:32768};function _(l){if(W[l])return W[l];for(let[e,n]of Object.entries(W))if(l.startsWith(e))return n;return W.default}function Ee(l,e){let n=4;return e.includes("claude")?n=3.5:(e.includes("llama")||e.includes("mistral"))&&(n=3.8),Math.ceil(l.length/n)}function X(l,e){let n="";if(typeof l.content=="string")n=l.content;else if(Array.isArray(l.content))for(let o of l.content)o.type==="text"&&o.text&&(n+=o.text);let s=Ee(n,e)+4;if(l.tool_calls)for(let o of l.tool_calls)s+=Ee(o.function.name+o.function.arguments,e);return s}function S(l,e){return l.reduce((n,t)=>n+X(t,e),0)}function K(l,e,n,t=4096){let o=(_(e))-t;if(S(l,e)<=o)return {messages:l,truncated:false,removedCount:0,summarized:false};let r=l[0]?.role==="system"?l[0]:null,a=r?l.slice(1):l,c=-1;for(let g=a.length-1;g>=0;g--)if(a[g].role==="user"){c=g;break}let u=[],d=r?X(r,e):0;if(c>=0){let g=a[c];u.unshift(g),d+=X(g,e);}for(let g=a.length-1;g>=0;g--){if(g===c)continue;let f=a[g],C=X(f,e);if(d+C<=o){let T=u.findIndex((Q,P)=>a.indexOf(u[P])>g);T===-1?u.push(f):u.splice(T,0,f),d+=C;}}u.sort((g,f)=>{let C=a.indexOf(g),T=a.indexOf(f);return C-T});let m=a.length-u.length,h=[];return r&&h.push(r),m>0&&h.push({role:"user",content:`<system-notice>
140
+ Previous conversation context (${m} messages) was truncated to fit within context limits.
141
+ The conversation continues from where relevant context remains.
142
+ </system-notice>`}),h.push(...u),{messages:h,truncated:m>0,removedCount:m,summarized:m>0}}function V(l,e,n=.8){let t=_(e);return S(l,e)/t>=n}function nt(){return `call_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function st(l){let e=[],n=/<function=([^>]+)>([\s\S]*?)<\/function>/g,t=/<parameter=([^>]+)>\n?([\s\S]*?)\n?<\/parameter>/g,s;for(;(s=n.exec(l))!==null;){let o=s[1].trim(),i=s[2],r={},a;for(;(a=t.exec(i))!==null;){let c=a[1].trim(),u=a[2].trim();try{r[c]=JSON.parse(u);}catch{r[c]=u;}}t.lastIndex=0,e.push({name:o,arguments:r});}return e}function ot(l){let e=[],n=/<tool_call>([\s\S]*?)<\/tool_call>/g,t;for(;(t=n.exec(l))!==null;){let s=t[1],o=/<name>([\s\S]*?)<\/name>/i.exec(s);if(!o)continue;let i=o[1].trim(),r=/<arguments>([\s\S]*?)<\/arguments>/i.exec(s);if(!r)continue;let a={},c=r[1].trim();try{a=JSON.parse(c);}catch{let u=/<([^>]+)>([\s\S]*?)<\/\1>/g,d;for(;(d=u.exec(c))!==null;){let m=d[2].trim();try{a[d[1]]=JSON.parse(m);}catch{a[d[1]]=m;}}}e.push({name:i,arguments:a});}return e}function rt(l){let e=[],n=/<invoke\s+name=["']([^"']+)["']>([\s\S]*?)<\/invoke>/g,t=/<parameter\s+name=["']([^"']+)["']>([\s\S]*?)<\/parameter>/g,s;for(;(s=n.exec(l))!==null;){let o=s[1].trim(),i=s[2],r={},a;for(;(a=t.exec(i))!==null;){let c=a[1].trim(),u=a[2].trim();try{r[c]=JSON.parse(u);}catch{r[c]=u;}}t.lastIndex=0,e.push({name:o,arguments:r});}return e}function it(l){let e=[],n=/\{[\s\n]*"name"[\s\n]*:[\s\n]*"([^"]+)"[\s\n]*,[\s\n]*"arguments"[\s\n]*:[\s\n]*(\{[^}]*\}|\{\})\}/g,t;for(;(t=n.exec(l))!==null;)try{let s=t[1],o=t[2];if(s){let i=JSON.parse(o);e.push({name:s,arguments:i});}}catch{}if(e.length===0){let s=/\{[\s\S]{0,500}?"name"[\s\S]{0,50}?:[\s\S]{0,50}?"([^"]+)"[\s\S]{0,50}?,[\s\S]{0,50}?"arguments"[\s\S]{0,50}?:[\s\S]{0,500}?\}/g;for(;(t=s.exec(l))!==null;)try{let o=t[0],i=JSON.parse(o);i.name&&e.push({name:i.name,arguments:i.arguments||{}});}catch{}}return e}function Y(l){return [/<function=[^>]+>/i,/<tool_call>/i,/<invoke\s+name=/i].some(n=>n.test(l))}function at(l){return /\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:/i.test(l)}function lt(l){let e=[];e.push(...st(l)),e.push(...ot(l)),e.push(...rt(l)),e.push(...it(l));let n=new Set;return e.filter(t=>{let s=`${t.name}:${JSON.stringify(t.arguments)}`;return n.has(s)?false:(n.add(s),true)})}function ct(l){return l.map(e=>({id:nt(),type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}function fe(l){let e=l;return e=e.replace(/<function=[^>]+>[\s\S]*?<\/function>/g,""),e=e.replace(/<tool_call>[\s\S]*?<\/tool_call>/g,""),e=e.replace(/<invoke\s+name=["'][^"']+["']>[\s\S]*?<\/invoke>/g,""),e=e.replace(/\n{3,}/g,`
143
+
144
+ `).trim(),e}function Oe(l){let e=Y(l),n=at(l);if(!e&&!n)return null;let t=lt(l);return t.length===0?null:ct(t)}var he=class{client;config;state;tools;logger;aborted=false;constructor(e){this.config=e,this.client=new L({apiKey:e.apiKey,baseUrl:e.baseUrl,model:e.model}),this.tools=F(e.workingDirectory),this.logger=new w(e.verbose),this.state=this.createInitialState();}emit(e,n={}){if(this.config.onEvent){let t={type:e,timestamp:Date.now(),data:n};this.config.onEvent(t);}}createInitialMetrics(){return {tokensUsed:0,promptTokens:0,completionTokens:0,contextSize:0,filesCreated:0,filesModified:0,linesAdded:0,linesRemoved:0,commandsExecuted:0,toolCallsTotal:0,apiCalls:0,startTime:Date.now(),modifiedFiles:new Set,createdFiles:new Set}}createInitialState(){return {messages:[],iteration:0,isRunning:false,lastToolCalls:[],tokensUsed:0,metrics:this.createInitialMetrics()}}getSystemMessage(){return {role:"system",content:z({workingDirectory:this.config.workingDirectory,osInfo:`${process.platform} ${process.arch}`})}}estimateContextSize(){return S(this.state.messages,this.config.model)}manageContextWindow(){let e=K(this.state.messages,this.config.model,void 0,this.config.maxTokens);e.truncated&&(this.logger.warn(`Context truncated: removed ${e.removedCount} messages to fit within ${_(this.config.model)} token limit`),this.state.messages=e.messages);}checkContextLimits(){if(V(this.state.messages,this.config.model,.75)){let e=this.estimateContextSize(),n=_(this.config.model);this.logger.warn(`Context usage: ${e}/${n} tokens (${Math.round(e/n*100)}%)`);}}async run(e){this.state=this.createInitialState(),this.state.isRunning=true,this.aborted=false,this.state.messages=[this.getSystemMessage()];let n=B(e,this.state);this.state.messages.push({role:"user",content:n}),this.logger.info(`Starting agent loop with task: ${e.slice(0,100)}...`),this.emit("thinking",{message:`Starting task: ${e.slice(0,100)}...`,level:"info"});let t="";try{for(;this.state.iteration<this.config.maxIterations&&!this.aborted;){if(this.state.iteration++,this.state.metrics.contextSize=this.estimateContextSize(),this.emit("iteration_start",{iteration:this.state.iteration,maxIterations:this.config.maxIterations,contextSize:this.state.metrics.contextSize}),this.emit("thinking",{message:`Iteration ${this.state.iteration}/${this.config.maxIterations}`,level:"info",icon:"\u2500"}),this.logger.metricsUpdate(this.state.metrics,this.state.iteration),this.manageContextWindow(),this.checkContextLimits(),this.state.iteration>3&&this.state.iteration%3===0){let r=q(this.state);r&&this.state.messages.push({role:"user",content:r});}this.logger.clearMetricsLine(),this.emit("llm_call",{model:this.config.model,messageCount:this.state.messages.length});let s=await this.callLLM();if(!s){this.logger.error("No response from LLM"),this.emit("error",{message:"No response from LLM"});break}let o=typeof s.content=="string"?s.content:s.content?.map(r=>r.type==="text"?r.text:"").join("")||"";this.emit("llm_response",{content:o,hasToolCalls:!!s.tool_calls?.length,toolCallCount:s.tool_calls?.length||0,contentLength:o.length});let i=await this.processXmlToolCalls(s);if(this.state.messages.push(i),i.tool_calls&&i.tool_calls.length>0){this.state.lastToolCalls=i.tool_calls,this.state.metrics.toolCallsTotal+=i.tool_calls.length;let r=await this.handleToolCalls(i.tool_calls);for(let a of i.tool_calls)if(a.function.name==="task_complete")return t=JSON.parse(a.function.arguments).summary,this.state.isRunning=!1,this.emit("task_complete",{summary:t,metrics:{tokensUsed:this.state.metrics.tokensUsed,filesCreated:this.state.metrics.filesCreated,filesModified:this.state.metrics.filesModified,linesAdded:this.state.metrics.linesAdded,linesRemoved:this.state.metrics.linesRemoved,iterations:this.state.iteration,createdFiles:Array.from(this.state.metrics.createdFiles),modifiedFiles:Array.from(this.state.metrics.modifiedFiles)}}),this.emit("thinking",{message:"Task Complete",level:"success",icon:"\u2713",summary:(t||"").slice(0,200)}),t;if(!r)break}else if(i.content){let r=typeof i.content=="string"?i.content:i.content.map(c=>c.type==="text"?c.text:"").join("");if(this.logger.assistant(r),t=r,this.state.lastToolCalls=[],this.shouldStopLoop()||this.looksLikeCompletion(r)){this.emit("task_complete",{summary:r,metrics:{tokensUsed:this.state.metrics.tokensUsed,filesCreated:this.state.metrics.filesCreated,filesModified:this.state.metrics.filesModified,iterations:this.state.iteration,createdFiles:Array.from(this.state.metrics.createdFiles),modifiedFiles:Array.from(this.state.metrics.modifiedFiles)}}),this.emit("thinking",{message:"Task Complete",level:"success",icon:"\u2713",summary:r.slice(0,200)});break}}this.logger.metricsUpdate(this.state.metrics,this.state.iteration);}this.state.iteration>=this.config.maxIterations&&(this.logger.warn(`Reached maximum iterations (${this.config.maxIterations})`),this.emit("thinking",{message:`Reached maximum iterations (${this.config.maxIterations})`,level:"warning",icon:"\u26A0"}));}catch(s){throw this.logger.error(`Agent loop error: ${s.message}`),this.emit("error",{message:s.message,stack:s.stack}),s}finally{this.state.isRunning=false;}return t}async callLLM(){try{if(this.logger.debug("Thinking..."),this.state.metrics.apiCalls++,this.config.verbose){let e=await this.client.accumulateStream(this.state.messages,this.tools.definitions,{maxTokens:this.config.maxTokens,temperature:this.config.temperature,onToken:s=>process.stdout.write(s)});console.log();let n=typeof e.content=="string"?e.content.length:0,t=Math.ceil(n/4);return this.state.metrics.completionTokens+=t,this.state.metrics.tokensUsed+=t,e}else {let e=await this.client.createCompletion(this.state.messages,this.tools.definitions,{maxTokens:this.config.maxTokens,temperature:this.config.temperature});return e.usage&&(this.state.metrics.promptTokens+=e.usage.prompt_tokens,this.state.metrics.completionTokens+=e.usage.completion_tokens,this.state.metrics.tokensUsed+=e.usage.total_tokens,this.state.tokensUsed=this.state.metrics.tokensUsed),e.choices[0]?.message??null}}catch(e){return this.logger.error(`LLM call failed: ${e.message}`),null}}async processXmlToolCalls(e){if(e.tool_calls&&e.tool_calls.length>0)return e;let n=typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(s=>s.type==="text"?s.text:"").join(""):"";if(!n||!Y(n))return e;this.logger.debug("Detected XML-style tool calls in response, parsing...");let t=Oe(n);if(t&&t.length>0){this.logger.info(`Parsed ${t.length} XML tool call(s) to JSON format`);let s=fe(n);return {...e,content:s,tool_calls:t}}if(Y(n)){this.logger.debug("Regex parsing failed, attempting AI-assisted conversion...");try{let s=await this.aiAssistedToolParsing(n);if(s&&s.length>0){this.logger.info(`AI parsed ${s.length} tool call(s) from XML`);let o=fe(n);return {...e,content:o,tool_calls:s}}}catch(s){this.logger.warn(`AI-assisted parsing failed: ${s.message}`);}}return e}async aiAssistedToolParsing(e){let n=`Convert the following XML-style tool calls to JSON format.
145
+
146
+ INPUT:
147
+ ${e}
148
+
149
+ OUTPUT FORMAT:
150
+ Return ONLY a JSON array of tool calls in this exact format:
151
+ [
152
+ {
153
+ "name": "tool_name",
154
+ "arguments": { "param1": "value1", "param2": "value2" }
155
+ }
156
+ ]
157
+
158
+ If there are no valid tool calls, return: []
159
+
160
+ JSON OUTPUT:`;try{let s=(await this.client.createCompletion([{role:"system",content:"You are a tool call parser. Extract tool calls from XML and output them as JSON."},{role:"user",content:n}],void 0,{maxTokens:2048,temperature:0})).choices[0]?.message?.content;if(!s||typeof s!="string")return null;let o=s.match(/\[[\s\S]*\]/);if(!o)return null;let i=JSON.parse(o[0]);return !Array.isArray(i)||i.length===0?null:i.map(r=>({id:`call_${Math.random().toString(36).substring(2,11)}`,type:"function",function:{name:r.name,arguments:JSON.stringify(r.arguments)}}))}catch(t){return this.logger.debug(`AI parsing error: ${t.message}`),null}}async handleToolCalls(e){for(let n of e){let{name:t,arguments:s}=n.function;this.logger.tool(t,s);let o;try{o=JSON.parse(s);}catch{let a={success:false,output:"",error:`Invalid JSON in tool arguments: ${s}`};this.addToolResultMessage(n.id,t,a),this.emit("tool_result",{toolCallId:n.id,toolName:t,success:false,error:a.error});continue}this.emit("tool_call",{toolCallId:n.id,toolName:t,arguments:o});let i=s.length>100?s.slice(0,100)+"...":s;this.emit("thinking",{message:`${t} ${i}`,level:"tool",icon:"\u{1F527}",toolName:t});let r=this.tools.handlers.get(t);if(!r){let a={success:false,output:"",error:`Unknown tool: ${t}`};this.addToolResultMessage(n.id,t,a),this.emit("tool_result",{toolCallId:n.id,toolName:t,success:false,error:a.error});continue}try{let a=await r(o);this.logger.toolResult(t,a),this.trackToolMetrics(t,o,a),this.emit("tool_result",{toolCallId:n.id,toolName:t,success:a.success,output:a.output.slice(0,500),error:a.error});let c=a.success?"\u2713":"\u2717",u=a.success?"success":"error",d=a.success?a.output.split(`
161
+ `)[0].slice(0,80)||"(no output)":a.error||"Unknown error";this.emit("thinking",{message:d,level:u,icon:c,toolName:t,success:a.success});let m=o.path;a.success&&m&&(t==="write_file"?this.emit("file_written",{path:m,sandboxId:this.config.sandboxId,operation:"create"}):t==="apply_diff"&&this.emit("file_modified",{path:m,sandboxId:this.config.sandboxId,operation:"modify"}));let h=H(a.success?a.output:`Error: ${a.error}
162
+ ${a.output}`,this.state,t);this.state.messages.push({role:"tool",tool_call_id:n.id,content:h});}catch(a){let c={success:false,output:"",error:`Tool execution failed: ${a.message}`};this.addToolResultMessage(n.id,t,c),this.emit("tool_result",{toolCallId:n.id,toolName:t,success:false,error:c.error}),this.emit("thinking",{message:c.error,level:"error",icon:"\u2717",toolName:t});}}return true}trackToolMetrics(e,n,t){let s=this.state.metrics,o=n.path;if(t.success)switch(e){case "write_file":if(o){let r=n.content.split(`
163
+ `).length;!s.createdFiles.has(o)&&!s.modifiedFiles.has(o)&&(s.filesCreated++,s.createdFiles.add(o)),s.linesAdded+=r;}break;case "apply_diff":if(o){let i=n.original,r=n.replacement;!s.modifiedFiles.has(o)&&!s.createdFiles.has(o)&&(s.filesModified++,s.modifiedFiles.add(o));let a=i.split(`
164
+ `).length,c=r.split(`
165
+ `).length;s.linesRemoved+=a,s.linesAdded+=c;}break;case "execute_command":s.commandsExecuted++;break}}addToolResultMessage(e,n,t){let s=t.success?t.output:`Error: ${t.error}
166
+ ${t.output}`;this.state.messages.push({role:"tool",tool_call_id:e,content:s});}looksLikeCompletion(e){let n=["let me know if","is there anything else","feel free to ask","hope this helps","task complete","successfully completed","all done","i've created","i've built","i have created","i have built","here's what i","here is what i","i've successfully","i have successfully","the website is ready","the app is ready","the code is ready","implementation is complete","development is complete","ready to use","you can now","you should now","everything is set up","## complete","## summary","## features","## what i've"],t=e.toLowerCase();return n.some(s=>t.includes(s))}shouldStopLoop(){return (this.state.metrics.filesCreated>0||this.state.metrics.filesModified>0)&&this.state.lastToolCalls.length===0?(this.logger.info("Files created/modified and no pending tool calls - stopping loop"),true):false}abort(){this.aborted=true,this.state.isRunning=false,this.logger.warn("Agent loop aborted");}getState(){return {...this.state}}getMetrics(){return {...this.state.metrics}}getTokensUsed(){return this.state.metrics.tokensUsed}};var M=class{candidates;usageMetadata;responseId;createTime;modelVersion;promptFeedback};var Ce="qwen3-coder:30b";function b(l,e={}){if(!l||typeof l!="string")return e;try{return JSON.parse(l)}catch{try{let n=l.trim();return n=n.replace(/,\s*}/g,"}").replace(/,\s*]/g,"]"),n=n.replace(/(\{|,)\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:/g,'$1"$2":'),n=n.replace(/'/g,'"'),JSON.parse(n)}catch{return e}}}var $=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,n,t,s){let o=e;if(t)if(this.idToIndexMap.has(t))o=this.idToIndexMap.get(t);else {if(this.buffers.has(e)){let f=this.buffers.get(e),C=this.depths.get(e),T=this.toolCallMeta.get(e);if(f.trim()&&C===0&&T?.id&&T.id!==t)try{JSON.parse(f),o=this.findNextAvailableIndex();}catch{}}this.idToIndexMap.set(t,o);}else if(this.buffers.has(e)){let f=this.buffers.get(e);if(this.depths.get(e)>0||!f.trim())o=e;else try{JSON.parse(f),o=this.findMostRecentIncompleteIndex();}catch{o=e;}}this.buffers.has(o)||(this.buffers.set(o,""),this.depths.set(o,0),this.inStrings.set(o,false),this.escapes.set(o,false),this.toolCallMeta.set(o,{}));let i=this.toolCallMeta.get(o);t&&(i.id=t),s&&(i.name=s);let r=this.buffers.get(o),a=this.depths.get(o),c=this.inStrings.get(o),u=this.escapes.get(o),d=r+n;this.buffers.set(o,d);let m=a,h=c,g=u;for(let f of n)h||(f==="{"||f==="["?m++:(f==="}"||f==="]")&&m--),f==='"'&&!g&&(h=!h),g=f==="\\"&&!g;if(this.depths.set(o,m),this.inStrings.set(o,h),this.escapes.set(o,g),m===0&&d.trim().length>0)try{return {complete:!0,value:JSON.parse(d)}}catch(f){if(h)try{return {complete:!0,value:JSON.parse(d+'"'),repaired:!0}}catch{}return {complete:false,error:f instanceof Error?f:new Error(String(f))}}return {complete:false}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){let e=[];for(let[n,t]of this.buffers.entries()){let s=this.toolCallMeta.get(n);if(s?.name&&t.trim()){let o={};try{o=JSON.parse(t);}catch{if(this.inStrings.get(n))try{o=JSON.parse(t+'"');}catch{o=b(t,{});}else o=b(t,{});}e.push({id:s.id,name:s.name,args:o,index:n});}}return e}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),n=this.depths.get(this.nextAvailableIndex),t=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||n>0||!t?.id)return this.nextAvailableIndex;try{if(JSON.parse(e),n===0){this.nextAvailableIndex++;continue}}catch{return this.nextAvailableIndex}this.nextAvailableIndex++;}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let e=-1;for(let[n,t]of this.buffers.entries()){let s=this.depths.get(n);if(this.toolCallMeta.get(n)?.id&&(s>0||!t.trim()))e=Math.max(e,n);else if(t.trim())try{JSON.parse(t);}catch{e=Math.max(e,n);}}return e>=0?e:this.findNextAvailableIndex()}resetIndex(e){this.buffers.set(e,""),this.depths.set(e,0),this.inStrings.set(e,false),this.escapes.set(e,false),this.toolCallMeta.set(e,{});}reset(){this.buffers.clear(),this.depths.clear(),this.inStrings.clear(),this.escapes.clear(),this.toolCallMeta.clear(),this.idToIndexMap.clear(),this.nextAvailableIndex=0;}getBuffer(e){return this.buffers.get(e)||""}getState(e){return {depth:this.depths.get(e)||0,inString:this.inStrings.get(e)||false,escape:this.escapes.get(e)||false}}};var I=class{toolCallCounter=0;availableToolNames;constructor(e=[]){this.availableToolNames=new Set(e);}setAvailableTools(e){this.availableToolNames=new Set(e);}generateId(){return `text_call_${Date.now()}_${++this.toolCallCounter}`}isValidTool(e){return this.availableToolNames.size===0?true:this.availableToolNames.has(e)}parse(e){let n=[],t=e,s=this.parseThinkTags(t);t=s.remainingText;let o=s.thinkingContent,i=this.parseXmlStyle(t);n.push(...i.toolCalls),t=i.remainingText;let r=this.parseFunctionCallXml(t);n.push(...r.toolCalls),t=r.remainingText;let a=this.parseLlamaStyleXml(t);n.push(...a.toolCalls),t=a.remainingText;let c=this.parseJsonBlocks(t);n.push(...c.toolCalls),t=c.remainingText;let u=this.parseBracketNotation(t);n.push(...u.toolCalls),t=u.remainingText;let d=this.parseInlineFunctionCalls(t);return n.push(...d.toolCalls),t=d.remainingText,{toolCalls:n,remainingText:t,thinkingContent:o}}parseThinkTags(e){let n=e,t=[],s=/<(think|thinking|reasoning)>([\s\S]*?)<\/\1>/gi,o;for(;(o=s.exec(e))!==null;){let i=o[2].trim();i&&t.push(i),n=n.replace(o[0],"");}return {thinkingContent:t.length>0?t.join(`
167
+
168
+ `):void 0,remainingText:n.trim()}}parseXmlStyle(e){let n=[],t=e,s=/<(tool_call|tool)>([\s\S]*?)<\/\1>/gi,o;for(;(o=s.exec(e))!==null;){let i=o[2].trim(),r=this.parseToolCallJson(i);r&&this.isValidTool(r.name)&&(n.push({id:this.generateId(),name:r.name,args:r.args}),t=t.replace(o[0],""));}return {toolCalls:n,remainingText:t.trim()}}parseFunctionCallXml(e){let n=[],t=e,s=/<function_call>([\s\S]*?)<\/function_call>/gi,o;for(;(o=s.exec(e))!==null;){let i=o[1].trim(),r=this.parseToolCallJson(i);r&&this.isValidTool(r.name)&&(n.push({id:this.generateId(),name:r.name,args:r.args}),t=t.replace(o[0],""));}return {toolCalls:n,remainingText:t.trim()}}parseLlamaStyleXml(e){let n=[],t=e,s=/<function=(\w+)>([\s\S]*?)(?:<\/function>|<\/tool_call>)/gi,o;for(;(o=s.exec(e))!==null;){let i=o[1],r=o[2];if(this.isValidTool(i)){let a={},c=/<parameter=(\w+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=c.exec(r))!==null;){let h=u[1],g=u[2].trim();if(g.startsWith("{")||g.startsWith("["))try{g=JSON.parse(g);}catch{}a[h]=g;}let d=/<parameter=(\w+)>\s*([\s\S]*?)(?=<\/parameter>|<parameter=|$)/gi,m;for(;(m=d.exec(r))!==null;){let h=m[1];if(!a[h]){let g=m[2].trim();if(g.startsWith("{")||g.startsWith("["))try{g=JSON.parse(g);}catch{}a[h]=g;}}n.push({id:this.generateId(),name:i,args:a}),t=t.replace(o[0],"");}}return {toolCalls:n,remainingText:t.trim()}}parseJsonBlocks(e){let n=[],t=e,s=/```(?:json)?\s*\n?([\s\S]*?)\n?```/gi,o;for(;(o=s.exec(e))!==null;){let i=o[1].trim(),r=this.parseToolCallJson(i);r&&this.isValidTool(r.name)&&(n.push({id:this.generateId(),name:r.name,args:r.args}),t=t.replace(o[0],""));}return {toolCalls:n,remainingText:t.trim()}}parseBracketNotation(e){let n=[],t=e,s=/\[(?:tool_call|tool):\s*(\w+)\s*\(\s*(\{[\s\S]*?\})\s*\)\]/gi,o;for(;(o=s.exec(e))!==null;){let i=o[1],r=o[2];if(this.isValidTool(i)){let a=b(r,{});n.push({id:this.generateId(),name:i,args:a}),t=t.replace(o[0],"");}}return {toolCalls:n,remainingText:t.trim()}}parseInlineFunctionCalls(e){let n=[],t=e;if(this.availableToolNames.size===0)return {toolCalls:n,remainingText:t};let s=Array.from(this.availableToolNames).join("|"),o=new RegExp(`\\b(${s})\\s*\\(\\s*(\\{[\\s\\S]*?\\})\\s*\\)`,"gi"),i;for(;(i=o.exec(e))!==null;){let r=i[1],a=i[2],c=b(a,{});(Object.keys(c).length>0||a==="{}")&&(n.push({id:this.generateId(),name:r,args:c}),t=t.replace(i[0],""));}return {toolCalls:n,remainingText:t.trim()}}parseToolCallJson(e){let n=b(e,{});if(!n||typeof n!="object")return null;if(n.name&&typeof n.name=="string"){let t=n.arguments||n.parameters||n.args||{};return {name:n.name,args:t}}if(n.tool&&typeof n.tool=="string"){let t=n.args||n.arguments||n.parameters||{};return {name:n.tool,args:t}}if(n.function&&typeof n.function=="string"){let t=n.parameters||n.arguments||n.args||{};return {name:n.function,args:t}}if(n.type==="function"&&n.function&&typeof n.function=="object"){let t=n.function;if(t.name&&typeof t.name=="string"){let s=t.arguments||t.parameters||{};return {name:t.name,args:s}}}return null}reset(){this.toolCallCounter=0;}};var E=class{model;streamingToolCallParser=new $;textToolCallParser=new I;enableTextToolCallParsing=false;streamingTextAccumulator="";streamingHasNativeToolCalls=false;constructor(e,n=false){this.model=e,this.enableTextToolCallParsing=n;}setAvailableTools(e){this.textToolCallParser.setAvailableTools(e);}setTextToolCallParsing(e){this.enableTextToolCallParsing=e;}resetStreamingToolCalls(){this.streamingToolCallParser.reset(),this.streamingTextAccumulator="",this.streamingHasNativeToolCalls=false;}async convertGeminiToolsToOpenAI(e){let n=[];for(let t of e){let s;if("tool"in t?s=await t.tool():s=t,s.functionDeclarations){for(let o of s.functionDeclarations)if(o.name&&o.description){let i;o.parametersJsonSchema?i={...o.parametersJsonSchema}:o.parameters&&(i=this.convertGeminiToolParametersToOpenAI(o.parameters)),n.push({type:"function",function:{name:o.name,description:o.description,parameters:i}});}}}return n}convertGeminiToolParametersToOpenAI(e){if(!e||typeof e!="object")return e;let n=JSON.parse(JSON.stringify(e)),t=s=>{if(typeof s!="object"||s===null)return s;if(Array.isArray(s))return s.map(t);let o={};for(let[i,r]of Object.entries(s))i==="type"&&typeof r=="string"?o[i]=r.toLowerCase():typeof r=="object"?o[i]=t(r):o[i]=r;return o};return t(n)}convertGeminiRequestToOpenAI(e){let n=[];this.addSystemInstructionMessage(e,n),this.processContents(e.contents,n);let t=this.cleanOrphanedToolCalls(n);return this.mergeConsecutiveAssistantMessages(t)}addSystemInstructionMessage(e,n){if(!e.config?.systemInstruction)return;let t=this.extractTextFromContentUnion(e.config.systemInstruction);t&&n.push({role:"system",content:t});}processContents(e,n){if(typeof e=="string"){n.push({role:"user",content:e});return}if(Array.isArray(e))for(let t of e)this.processContent(t,n);}processContent(e,n){let t=this.parseParts(e.parts||[]);if(t.functionResponses.length>0){for(let i of t.functionResponses)n.push({role:"tool",tool_call_id:i.id||"",content:this.extractFunctionResponseContent(i.response)});return}if(e.role==="model"&&t.functionCalls.length>0){let i=t.functionCalls.map((c,u)=>({id:c.id||`call_${u}`,type:"function",function:{name:c.name||"",arguments:JSON.stringify(c.args||{})}})),r={role:"assistant",content:t.contentParts.join("")||null,tool_calls:i},a=t.thoughtParts.join("");a&&(r.reasoning_content=a),n.push(r);return}let s=e.role==="model"?"assistant":"user",o=this.createMultimodalMessage(s,t);o&&n.push(o);}parseParts(e){let n=[],t=[],s=[],o=[],i=[];for(let r of e)if(r.text&&!r.thought)t.push(r.text);else if(r.text&&r.thought)n.push(r.text);else if(r.functionCall)s.push(r.functionCall);else if(r.functionResponse)o.push(r.functionResponse);else if(r.inlineData){let{data:a,mimeType:c}=r.inlineData;if(a&&c){let u=this.getMediaType(c);i.push({type:u,data:a,mimeType:c});}}return {thoughtParts:n,contentParts:t,functionCalls:s,functionResponses:o,mediaParts:i}}extractFunctionResponseContent(e){if(e==null)return "";if(typeof e=="string")return e;if(typeof e=="object"){let n=e;if(typeof n.output=="string")return n.output;if(typeof n.error=="string")return n.error}try{return JSON.stringify(e)??String(e)}catch{return String(e)}}getMediaType(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":"file"}createMultimodalMessage(e,n){let{contentParts:t,mediaParts:s,thoughtParts:o}=n,i=t.map(a=>({type:"text",text:a}));if(s.length===0){if(i.length===0)return null;let a={role:e,content:i},c=o.join("");return c&&(a.reasoning_content=c),a}if(e==="assistant")return i.length>0?{role:"assistant",content:i}:null;let r=[...i];for(let a of s)if(a.type==="image"&&a.data){let c=`data:${a.mimeType};base64,${a.data}`;r.push({type:"image_url",image_url:{url:c}});}return r.length>0?{role:"user",content:r}:null}extractTextFromContentUnion(e){return typeof e=="string"?e:Array.isArray(e)?e.map(n=>this.extractTextFromContentUnion(n)).filter(Boolean).join(`
169
+ `):typeof e=="object"&&e!==null&&"parts"in e&&e.parts?.map(t=>t.text||"").filter(Boolean).join(`
170
+ `)||""}convertOpenAIResponseToGemini(e){let n=e.choices[0],t=new M,s=[],o=n.message.reasoning_content;o&&s.push({text:o,thought:true});let i=n.message.content||"";if(n.message.tool_calls){for(let r of n.message.tool_calls)if(r.function){let a=b(r.function.arguments,{});s.push({functionCall:{id:r.id,name:r.function.name,args:a}});}}if(!n.message.tool_calls&&this.enableTextToolCallParsing&&i){let r=this.textToolCallParser.parse(i);if(r.thinkingContent&&s.push({text:r.thinkingContent,thought:true}),r.toolCalls.length>0){for(let a of r.toolCalls)s.push({functionCall:{id:a.id,name:a.name,args:a.args}});i=r.remainingText;}else i=r.remainingText;}if(i&&s.push({text:i}),t.responseId=e.id,t.createTime=e.created?e.created.toString():new Date().getTime().toString(),t.candidates=[{content:{parts:s,role:"model"},finishReason:this.mapOpenAIFinishReasonToGemini(n.finish_reason||"stop"),index:0,safetyRatings:[]}],t.modelVersion=this.model,t.promptFeedback={safetyRatings:[]},e.usage){let r=e.usage;t.usageMetadata={promptTokenCount:r.prompt_tokens||0,candidatesTokenCount:r.completion_tokens||0,totalTokenCount:r.total_tokens||0,cachedContentTokenCount:r.prompt_tokens_details?.cached_tokens??r.cached_tokens??0};}return t}convertOpenAIChunkToGemini(e){let n=e.choices?.[0],t=new M;if(n){let s=[],o=n.delta.reasoning_content;if(o&&s.push({text:o,thought:true}),n.delta?.content&&typeof n.delta.content=="string"&&(s.push({text:n.delta.content}),this.enableTextToolCallParsing&&(this.streamingTextAccumulator+=n.delta.content)),n.delta?.tool_calls){this.streamingHasNativeToolCalls=true;for(let r of n.delta.tool_calls){let a=r.index??0;r.function?.arguments?this.streamingToolCallParser.addChunk(a,r.function.arguments,r.id,r.function.name):this.streamingToolCallParser.addChunk(a,"",r.id,r.function?.name);}}if(n.finish_reason){let r=this.streamingToolCallParser.getCompletedToolCalls();for(let a of r)a.name&&s.push({functionCall:{id:a.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:a.name,args:a.args}});if(!this.streamingHasNativeToolCalls&&this.enableTextToolCallParsing&&this.streamingTextAccumulator){let a=this.textToolCallParser.parse(this.streamingTextAccumulator);a.thinkingContent&&s.push({text:a.thinkingContent,thought:true});for(let c of a.toolCalls)s.push({functionCall:{id:c.id,name:c.name,args:c.args}});}this.streamingToolCallParser.reset(),this.streamingTextAccumulator="",this.streamingHasNativeToolCalls=false;}let i={content:{parts:s,role:"model"},index:0,safetyRatings:[]};n.finish_reason&&(i.finishReason=this.mapOpenAIFinishReasonToGemini(n.finish_reason)),t.candidates=[i];}else t.candidates=[];if(t.responseId=e.id,t.createTime=e.created?.toString()||new Date().getTime().toString(),t.modelVersion=this.model,t.promptFeedback={safetyRatings:[]},e.usage){let s=e.usage;t.usageMetadata={promptTokenCount:s.prompt_tokens||0,candidatesTokenCount:s.completion_tokens||0,totalTokenCount:s.total_tokens||0,thoughtsTokenCount:s.completion_tokens_details?.reasoning_tokens||0,cachedContentTokenCount:s.prompt_tokens_details?.cached_tokens??s.cached_tokens??0};}return t}mapOpenAIFinishReasonToGemini(e){return e?{stop:1,length:2,content_filter:3,function_call:1,tool_calls:1}[e]||0:0}cleanOrphanedToolCalls(e){let n=new Set,t=new Set;for(let o of e)if(o.role==="assistant"&&"tool_calls"in o&&o.tool_calls)for(let i of o.tool_calls)i.id&&n.add(i.id);else o.role==="tool"&&"tool_call_id"in o&&o.tool_call_id&&t.add(o.tool_call_id);let s=[];for(let o of e)if(o.role==="assistant"&&"tool_calls"in o&&o.tool_calls){let i=o.tool_calls.filter(r=>r.id&&t.has(r.id));if(i.length>0)s.push({...o,tool_calls:i});else if(typeof o.content=="string"&&o.content.trim()){let{tool_calls:r,...a}=o;s.push(a);}}else o.role==="tool"&&"tool_call_id"in o&&o.tool_call_id?n.has(o.tool_call_id)&&s.push(o):s.push(o);return s}mergeConsecutiveAssistantMessages(e){let n=[];for(let t of e){if(t.role==="assistant"&&n.length>0){let s=n[n.length-1];if(s.role==="assistant"){let o=[typeof s.content=="string"?s.content:"",typeof t.content=="string"?t.content:""].filter(Boolean).join(""),i="tool_calls"in s?s.tool_calls||[]:[],r="tool_calls"in t?t.tool_calls||[]:[],a=[...i,...r];s.content=o||null,a.length>0&&(s.tool_calls=a);continue}}n.push(t);}return n}};var O=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient(),this.converter=new E(this.contentGeneratorConfig.model,this.contentGeneratorConfig.enableTextToolCallParsing??false);}client;converter;contentGeneratorConfig;setAvailableTools(e){this.converter.setAvailableTools(e);}async execute(e,n){let t=await this.buildRequest(e,n,false);try{let s=await this.client.chat.completions.create(t,{signal:e.config?.abortSignal});return this.converter.convertOpenAIResponseToGemini(s)}catch(s){this.handleError(s);}}async executeStream(e,n){let t=await this.buildRequest(e,n,true);try{let s=await this.client.chat.completions.create(t,{signal:e.config?.abortSignal});return this.processStream(s)}catch(s){this.handleError(s);}}async*processStream(e){this.converter.resetStreamingToolCalls();let n=null;try{for await(let t of e){let s=this.converter.convertOpenAIChunkToGemini(t);if(s.candidates?.[0]?.content?.parts?.length===0&&!s.candidates?.[0]?.finishReason&&!s.usageMetadata)continue;if(s.candidates?.[0]?.finishReason){n=s;continue}else n?(s.usageMetadata&&(n.usageMetadata=s.usageMetadata),yield n,n=null):yield s;}n&&(yield n);}catch(t){throw this.converter.resetStreamingToolCalls(),t}}async buildRequest(e,n,t=false){let s=this.converter.convertGeminiRequestToOpenAI(e),o={model:this.contentGeneratorConfig.model,messages:s,...this.buildSamplingParameters(e)};if(t&&(o.stream=true,o.stream_options={include_usage:true}),e.config?.tools&&(o.tools=await this.converter.convertGeminiToolsToOpenAI(e.config.tools),this.contentGeneratorConfig.enableTextToolCallParsing)){let i=o.tools?.map(r=>r.function?.name).filter(r=>!!r);i?.length&&this.converter.setAvailableTools(i);}return this.config.provider.buildRequest(o,n)}buildSamplingParameters(e){let n=this.contentGeneratorConfig.samplingParams,t={},s=n?.temperature??e.config?.temperature;s!==void 0&&(t.temperature=s);let o=n?.top_p??e.config?.topP;o!==void 0&&(t.top_p=o);let i=n?.max_tokens??e.config?.maxOutputTokens;return i!==void 0&&(t.max_tokens=i),n?.top_k!==void 0&&(t.top_k=n.top_k),n?.repetition_penalty!==void 0&&(t.repetition_penalty=n.repetition_penalty),n?.presence_penalty!==void 0&&(t.presence_penalty=n.presence_penalty),n?.frequency_penalty!==void 0&&(t.frequency_penalty=n.frequency_penalty),t}handleError(e){let n=e instanceof Error?e.message:String(e);throw n.toLowerCase().includes("timeout")||n.toLowerCase().includes("timed out")?new Error(`Request timeout: ${n}
171
+
172
+ Troubleshooting tips:
173
+ - Reduce input length or complexity
174
+ - Check network connectivity
175
+ - Increase timeout in config`):e}};var D=class{pipeline;constructor(e,n){let t={provider:n,contentGeneratorConfig:e};this.pipeline=new O(t);}setAvailableTools(e){this.pipeline.setAvailableTools(e);}async generateContent(e,n){return this.pipeline.execute(e,n)}async generateContentStream(e,n){return this.pipeline.executeStream(e,n)}async countTokens(e){let n=JSON.stringify(e.contents);return {totalTokens:Math.ceil(n.length/4)}}async embedContent(e){let n="";typeof e.contents=="string"?n=e.contents:Array.isArray(e.contents)&&(n=e.contents.map(t=>typeof t=="string"?t:"parts"in t&&t.parts?t.parts.map(s=>s.text||"").join(" "):"").join(" "));try{return {embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:n})).data[0].embedding}]}}catch(t){throw console.error("Embedding error:",t),new Error(`Embedding failed: ${t instanceof Error?t.message:String(t)}`)}}};var N=class{contentGeneratorConfig;constructor(e){this.contentGeneratorConfig=e;}buildHeaders(){return {"User-Agent":`GeoffCoder/${process.env.CLI_VERSION||"1.0.0"} (${process.platform}; ${process.arch})`}}buildClient(){let{apiKey:e,baseUrl:n,timeout:t=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders();return new mt__default.default({apiKey:e||"ollama",baseURL:n,timeout:t,maxRetries:s,defaultHeaders:o})}buildRequest(e,n){return {...e}}};function ye(l){let e=new N(l);return new D(l,e)}var xe=class{config;state;tools;logger;aborted=false;contentGenerator;constructor(e){this.config=e,this.tools=F(e.workingDirectory),this.logger=new w(e.verbose),this.state=this.createInitialState();let n={model:e.model||Ce,apiKey:e.apiKey||"ollama",baseUrl:e.baseUrl,enableTextToolCallParsing:e.enableTextToolCallParsing??true,samplingParams:e.samplingParams??{temperature:e.temperature,max_tokens:e.maxTokens}};if(this.contentGenerator=ye(n),this.contentGenerator.setAvailableTools){let t=this.tools.definitions.map(s=>s.function.name);this.contentGenerator.setAvailableTools(t);}}emit(e,n={}){if(this.config.onEvent){let t={type:e,timestamp:Date.now(),data:n};this.config.onEvent(t);}}createInitialMetrics(){return {tokensUsed:0,promptTokens:0,completionTokens:0,contextSize:0,filesCreated:0,filesModified:0,linesAdded:0,linesRemoved:0,commandsExecuted:0,toolCallsTotal:0,apiCalls:0,startTime:Date.now(),modifiedFiles:new Set,createdFiles:new Set}}createInitialState(){return {messages:[],iteration:0,isRunning:false,lastToolCalls:[],tokensUsed:0,metrics:this.createInitialMetrics()}}getSystemMessage(){return {role:"system",content:z({workingDirectory:this.config.workingDirectory,osInfo:`${process.platform} ${process.arch}`})}}estimateContextSize(){return S(this.state.messages,this.config.model)}manageContextWindow(){let e=K(this.state.messages,this.config.model,void 0,this.config.maxTokens);e.truncated&&(this.logger.warn(`Context truncated: removed ${e.removedCount} messages`),this.state.messages=e.messages);}checkContextLimits(){if(V(this.state.messages,this.config.model,.75)){let e=this.estimateContextSize(),n=_(this.config.model);this.logger.warn(`Context usage: ${e}/${n} tokens`);}}messagesToContents(e){let n=[];for(let t of e){if(t.role==="system")continue;let s=typeof t.content=="string"?t.content:t.content?.map(o=>o.type==="text"?o.text:"").join("")||"";if(t.role==="user")n.push({role:"user",parts:[{text:s}]});else if(t.role==="assistant"){let o=[];if(s&&o.push({text:s}),t.tool_calls)for(let i of t.tool_calls)o.push({functionCall:{id:i.id,name:i.function.name,args:JSON.parse(i.function.arguments)}});n.push({role:"model",parts:o});}else t.role==="tool"&&t.tool_call_id&&n.push({role:"user",parts:[{functionResponse:{id:t.tool_call_id,name:t.name||"",response:{output:s}}}]});}return n}toolsToGeminiFormat(){return [{functionDeclarations:this.tools.definitions.map(e=>({name:e.function.name,description:e.function.description,parameters:e.function.parameters}))}]}extractToolCalls(e){let n=[],t=e.candidates?.[0]?.content?.parts||[];for(let s of t)s.functionCall&&n.push({id:s.functionCall.id||`call_${Math.random().toString(36).substring(2,11)}`,type:"function",function:{name:s.functionCall.name||"",arguments:JSON.stringify(s.functionCall.args||{})}});return n}extractTextContent(e){return (e.candidates?.[0]?.content?.parts||[]).filter(t=>t.text&&!t.thought).map(t=>t.text||"").join("")}async run(e){this.state=this.createInitialState(),this.state.isRunning=true,this.aborted=false,this.state.messages=[this.getSystemMessage()];let n=B(e,this.state);this.state.messages.push({role:"user",content:n}),this.logger.info(`Starting agent loop: ${e.slice(0,100)}...`),this.emit("thinking",{message:`Starting task: ${e.slice(0,100)}...`,level:"info"});let t="";try{for(;this.state.iteration<this.config.maxIterations&&!this.aborted;){if(this.state.iteration++,this.state.metrics.contextSize=this.estimateContextSize(),this.emit("iteration_start",{iteration:this.state.iteration,maxIterations:this.config.maxIterations,contextSize:this.state.metrics.contextSize}),this.emit("thinking",{message:`Iteration ${this.state.iteration}/${this.config.maxIterations}`,level:"info",icon:"\u2500"}),this.manageContextWindow(),this.checkContextLimits(),this.state.iteration>3&&this.state.iteration%3===0){let a=q(this.state);a&&this.state.messages.push({role:"user",content:a});}this.emit("llm_call",{model:this.config.model,messageCount:this.state.messages.length});let s=await this.callLLM();if(!s){this.logger.error("No response from LLM"),this.emit("error",{message:"No response from LLM"});break}let o=this.extractTextContent(s),i=this.extractToolCalls(s);this.emit("llm_response",{content:o,hasToolCalls:i.length>0,toolCallCount:i.length,contentLength:o.length});let r={role:"assistant",content:o,tool_calls:i.length>0?i:void 0};if(this.state.messages.push(r),i.length>0){this.state.lastToolCalls=i,this.state.metrics.toolCallsTotal+=i.length,await this.handleToolCalls(i);for(let a of i)if(a.function.name==="task_complete")return t=JSON.parse(a.function.arguments).summary,this.state.isRunning=!1,this.emit("task_complete",{summary:t,metrics:this.serializeMetrics()}),t}else if(o&&(this.logger.assistant(o),t=o,this.state.lastToolCalls=[],this.shouldStopLoop()||this.looksLikeCompletion(o))){this.emit("task_complete",{summary:o,metrics:this.serializeMetrics()});break}}this.state.iteration>=this.config.maxIterations&&(this.logger.warn(`Reached maximum iterations (${this.config.maxIterations})`),this.emit("thinking",{message:"Reached maximum iterations",level:"warning",icon:"\u26A0"}));}catch(s){throw this.logger.error(`Agent loop error: ${s.message}`),this.emit("error",{message:s.message,stack:s.stack}),s}finally{this.state.isRunning=false;}return t}async callLLM(){try{this.logger.debug("Thinking..."),this.state.metrics.apiCalls++;let e=this.state.messages.find(o=>o.role==="system"),n=typeof e?.content=="string"?e.content:"",s={contents:this.messagesToContents(this.state.messages),config:{systemInstruction:n,tools:this.toolsToGeminiFormat(),temperature:this.config.temperature,maxOutputTokens:this.config.maxTokens}};if(this.config.verbose){let o=await this.contentGenerator.generateContentStream(s,`prompt_${Date.now()}`),i=null;for await(let r of o){let a=this.extractTextContent(r);a&&process.stdout.write(a),i=r,r.usageMetadata&&(this.state.metrics.promptTokens+=r.usageMetadata.promptTokenCount||0,this.state.metrics.completionTokens+=r.usageMetadata.candidatesTokenCount||0,this.state.metrics.tokensUsed+=r.usageMetadata.totalTokenCount||0);}return console.log(),i}else {let o=await this.contentGenerator.generateContent(s,`prompt_${Date.now()}`);return o.usageMetadata&&(this.state.metrics.promptTokens+=o.usageMetadata.promptTokenCount||0,this.state.metrics.completionTokens+=o.usageMetadata.candidatesTokenCount||0,this.state.metrics.tokensUsed+=o.usageMetadata.totalTokenCount||0,this.state.tokensUsed=this.state.metrics.tokensUsed),o}}catch(e){return this.logger.error(`LLM call failed: ${e.message}`),null}}async handleToolCalls(e){for(let n of e){let{name:t,arguments:s}=n.function;this.logger.tool(t,s);let o;try{o=JSON.parse(s);}catch{let r={success:false,output:"",error:`Invalid JSON in tool arguments: ${s}`};this.addToolResultMessage(n.id,t,r),this.emit("tool_result",{toolCallId:n.id,toolName:t,success:false,error:r.error});continue}this.emit("tool_call",{toolCallId:n.id,toolName:t,arguments:o}),this.emit("thinking",{message:`${t} ${s.slice(0,100)}...`,level:"tool",icon:"\u{1F527}",toolName:t});let i=this.tools.handlers.get(t);if(!i){let r={success:false,output:"",error:`Unknown tool: ${t}`};this.addToolResultMessage(n.id,t,r),this.emit("tool_result",{toolCallId:n.id,toolName:t,success:false,error:r.error});continue}try{let r=await i(o);this.logger.toolResult(t,r),this.trackToolMetrics(t,o,r),this.emit("tool_result",{toolCallId:n.id,toolName:t,success:r.success,output:r.output.slice(0,500),error:r.error}),this.emit("thinking",{message:r.success?r.output.split(`
176
+ `)[0].slice(0,80):r.error,level:r.success?"success":"error",icon:r.success?"\u2713":"\u2717",toolName:t,success:r.success});let a=o.path;r.success&&a&&(t==="write_file"?this.emit("file_written",{path:a,sandboxId:this.config.sandboxId,operation:"create"}):t==="apply_diff"&&this.emit("file_modified",{path:a,sandboxId:this.config.sandboxId,operation:"modify"}));let c=H(r.success?r.output:`Error: ${r.error}
177
+ ${r.output}`,this.state,t);this.state.messages.push({role:"tool",tool_call_id:n.id,name:t,content:c});}catch(r){let a={success:false,output:"",error:`Tool execution failed: ${r.message}`};this.addToolResultMessage(n.id,t,a),this.emit("tool_result",{toolCallId:n.id,toolName:t,success:false,error:a.error});}}return true}trackToolMetrics(e,n,t){let s=this.state.metrics,o=n.path;if(t.success)switch(e){case "write_file":if(o){let r=n.content.split(`
178
+ `).length;!s.createdFiles.has(o)&&!s.modifiedFiles.has(o)&&(s.filesCreated++,s.createdFiles.add(o)),s.linesAdded+=r;}break;case "apply_diff":if(o){let i=n.original,r=n.replacement;!s.modifiedFiles.has(o)&&!s.createdFiles.has(o)&&(s.filesModified++,s.modifiedFiles.add(o)),s.linesRemoved+=i.split(`
179
+ `).length,s.linesAdded+=r.split(`
180
+ `).length;}break;case "execute_command":s.commandsExecuted++;break}}addToolResultMessage(e,n,t){let s=t.success?t.output:`Error: ${t.error}
181
+ ${t.output}`;this.state.messages.push({role:"tool",tool_call_id:e,name:n,content:s});}looksLikeCompletion(e){let n=["let me know if","is there anything else","feel free to ask","hope this helps","task complete","successfully completed","all done","i've created","i've built","i have created","ready to use","you can now","## complete","## summary"],t=e.toLowerCase();return n.some(s=>t.includes(s))}shouldStopLoop(){return (this.state.metrics.filesCreated>0||this.state.metrics.filesModified>0)&&this.state.lastToolCalls.length===0?(this.logger.info("Files created/modified with no pending tool calls - stopping"),true):false}serializeMetrics(){return {tokensUsed:this.state.metrics.tokensUsed,filesCreated:this.state.metrics.filesCreated,filesModified:this.state.metrics.filesModified,linesAdded:this.state.metrics.linesAdded,linesRemoved:this.state.metrics.linesRemoved,iterations:this.state.iteration,createdFiles:Array.from(this.state.metrics.createdFiles),modifiedFiles:Array.from(this.state.metrics.modifiedFiles)}}abort(){this.aborted=true,this.state.isRunning=false,this.logger.warn("Agent loop aborted");}getState(){return {...this.state}}getMetrics(){return {...this.state.metrics}}getTokensUsed(){return this.state.metrics.tokensUsed}};var gt=["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".cache",".parcel-cache","*.log",".DS_Store"];function ft(){return {model:"qwen3-coder:30b",baseUrl:"https://geoffnet.magma-rpc.com/v1",maxIterations:20,maxTokens:4096,temperature:.7,verbose:false,ignorePatterns:gt,blockedCommands:[],retry:{maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4}}}function ht(l){let n={...ft()},t=A.join(os.homedir(),".geoff.json");if(fs.existsSync(t))try{let o=JSON.parse(fs.readFileSync(t,"utf-8"));n=Le(n,o);}catch(o){console.warn(`Warning: Failed to parse ${t}: ${o.message}`);}let s=[A.join(l,".geoff.json"),A.join(l,"geoff.config.json")];for(let o of s)if(fs.existsSync(o))try{let i=JSON.parse(fs.readFileSync(o,"utf-8"));n=Le(n,i);break}catch(i){console.warn(`Warning: Failed to parse ${o}: ${i.message}`);}return n}function Le(l,e){return {...l,...e,retry:{...l.retry,...e.retry},ignorePatterns:e.ignorePatterns??l.ignorePatterns,blockedCommands:e.blockedCommands??l.blockedCommands}}function Ct(l){let e=[];return l.maxIterations!==void 0&&(l.maxIterations<1||l.maxIterations>100)&&e.push("maxIterations must be between 1 and 100"),l.maxTokens!==void 0&&(l.maxTokens<100||l.maxTokens>32e3)&&e.push("maxTokens must be between 100 and 32000"),l.temperature!==void 0&&(l.temperature<0||l.temperature>2)&&e.push("temperature must be between 0 and 2"),l.retry?.maxRetries!==void 0&&(l.retry.maxRetries<0||l.retry.maxRetries>10)&&e.push("retry.maxRetries must be between 0 and 10"),{valid:e.length===0,errors:e}}
182
+ exports.APIClient=L;exports.AgentLoop=he;exports.ContentGenerationPipeline=O;exports.DEFAULT_QWEN_MODEL=Ce;exports.GenerateContentResponse=M;exports.Logger=w;exports.OpenAIContentConverter=E;exports.OpenAIContentGenerator=D;exports.QwenAgentAdapter=xe;exports.StreamingToolCallParser=$;exports.TextToolCallParser=I;exports.backgroundProcessManager=v;exports.createEnterPlanModeHandler=oe;exports.createExitPlanModeHandler=ne;exports.createGetProcessOutputHandler=le;exports.createKillProcessHandler=ce;exports.createListProcessesHandler=ue;exports.createOpenAIContentGenerator=ye;exports.createRunBackgroundHandler=ae;exports.createTodoWriteHandler=Z;exports.createToolRegistry=F;exports.enterPlanMode=Re;exports.enterPlanModeDefinition=re;exports.exitPlanModeDefinition=se;exports.getPlanModeState=G;exports.getProcessOutputDefinition=me;exports.isPlanModeEnabled=He;exports.killProcessDefinition=de;exports.listProcessesDefinition=ge;exports.listTodoSessions=ze;exports.loadConfig=ht;exports.readTodos=Je;exports.runBackgroundDefinition=pe;exports.setPlanApproval=Be;exports.todoWriteDefinition=ee;exports.validateConfig=Ct;exports.writeTodos=_e;