@kodax-ai/kodax 0.7.62 → 0.7.66
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2300 -2145
- package/README.md +81 -9
- package/README_CN.md +54 -5
- package/dist/chunks/{agent-4ZMCIEGD.js → agent-KER4WDNO.js} +1 -1
- package/dist/chunks/argument-completer-HK3MHA3K.js +2 -0
- package/dist/chunks/{chunk-ARUWXX25.js → chunk-35P7QL2Q.js} +1 -1
- package/dist/chunks/chunk-3HKBBY74.js +339 -0
- package/dist/chunks/chunk-AKBH2EEE.js +8 -0
- package/dist/chunks/{chunk-OGRJQGKO.js → chunk-ALS32RNZ.js} +1 -1
- package/dist/chunks/chunk-MHRN2LQV.js +328 -0
- package/dist/chunks/{chunk-JILSZHCQ.js → chunk-NBQW7PNZ.js} +2 -2
- package/dist/chunks/{chunk-S4GVQO3W.js → chunk-O7N22GJ3.js} +1 -1
- package/dist/chunks/chunk-ONUPGMER.js +2 -0
- package/dist/chunks/{chunk-ZL5CEANW.js → chunk-PZTG2C33.js} +1 -1
- package/dist/chunks/{chunk-AY3BLB4Q.js → chunk-QAQ2HNXD.js} +112 -112
- package/dist/chunks/{chunk-6OZ5KWG3.js → chunk-QJJKMNZF.js} +1 -1
- package/dist/chunks/chunk-QJVZZSEO.js +56 -0
- package/dist/chunks/chunk-TLJGOKBT.js +729 -0
- package/dist/chunks/{chunk-6HTR3GHZ.js → chunk-VS4CDDEF.js} +245 -245
- package/dist/chunks/chunk-WBBEJIAY.js +306 -0
- package/dist/chunks/{chunk-HO6P6CPU.js → chunk-WMIZCY2J.js} +1 -1
- package/dist/chunks/{chunk-UA744TZM.js → chunk-YRBNXFHY.js} +1 -1
- package/dist/chunks/compaction-config-7GMUFNPB.js +2 -0
- package/dist/chunks/{construction-bootstrap-4ZNFZFX2.js → construction-bootstrap-3XDS2D5K.js} +1 -1
- package/dist/chunks/{devtools-4CRULTR2.js → devtools-CD6KSIHE.js} +1 -1
- package/dist/chunks/{devtools-YINBSZC7.js → devtools-XR5F2C6T.js} +1 -1
- package/dist/chunks/{dist-73L4OYPD.js → dist-4PXB7U22.js} +1 -1
- package/dist/chunks/dist-4YAYT2TO.js +2 -0
- package/dist/chunks/host-KG3456QP.js +2 -0
- package/dist/chunks/{paste-FDYM7SZX.js → paste-C33GZQV5.js} +1 -1
- package/dist/chunks/run-manager-6CAH3KTA.js +2 -0
- package/dist/chunks/utils-OT5ENFUL.js +2 -0
- package/dist/constructed-handler-worker.js +2 -0
- package/dist/index.d.ts +22 -11
- package/dist/index.js +6 -6
- package/dist/kodax_cli.js +1117 -1090
- package/dist/runtime-worker.js +2843 -0
- package/dist/sdk-agent.d.ts +29 -10
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +108 -1091
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-mcp.d.ts +2 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-media.js +1 -1
- package/dist/sdk-repl.d.ts +198 -184
- package/dist/sdk-repl.js +2 -2
- package/dist/sdk-runtime.d.ts +982 -0
- package/dist/sdk-runtime.js +2 -0
- package/dist/sdk-session.d.ts +4 -4
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/semantic-worker.js +191 -10
- package/dist/types-chunks/{bash-prefix-extractor.d-Do_TCAmA.d.ts → bash-prefix-extractor.d-BjkITAva.d.ts} +266 -4
- package/dist/types-chunks/{run-manager.d-CYY3pZeJ.d.ts → capsule.d-hVhPNkHd.d.ts} +9 -107
- package/dist/types-chunks/commands.d-C3B1TdGM.d.ts +213 -0
- package/dist/types-chunks/{types.d-DFf4Sfys.d.ts → guardrail.d-C_Siraua.d.ts} +3 -128
- package/dist/types-chunks/{guardrail.d-DRp0Lqvx.d.ts → guardrail.d-wk-s0psS.d.ts} +3 -3
- package/dist/types-chunks/{manager.d-DBD7SOTT.d.ts → manager.d-Zum9cGHU.d.ts} +3 -173
- package/dist/types-chunks/oauth-login.d-Bgb4rdLN.d.ts +174 -0
- package/dist/types-chunks/{process.d-DXkRD7hj.d.ts → process.d-CY2g03Mb.d.ts} +11 -4
- package/dist/types-chunks/public-api.d-jtREVfEq.d.ts +596 -0
- package/dist/types-chunks/run-manager.d-CFknOfo1.d.ts +91 -0
- package/dist/types-chunks/{sdk-session-BGGOC0cT.d.ts → sdk-session-CLqyfAmf.d.ts} +8 -304
- package/dist/types-chunks/types.d-BMLxKV69.d.ts +128 -0
- package/dist/types-chunks/types.d-CUN_bZU7.d.ts +975 -0
- package/dist/types-chunks/{utils.d-ChOEH3NF.d.ts → utils.d-C1rpoeDh.d.ts} +84 -72
- package/package.json +7 -1
- package/dist/chunks/argument-completer-5PWSKFKI.js +0 -2
- package/dist/chunks/chunk-2F4R7WM7.js +0 -52
- package/dist/chunks/chunk-3KD26NCI.js +0 -310
- package/dist/chunks/chunk-E2Q4RIOD.js +0 -731
- package/dist/chunks/chunk-S4ISEA6F.js +0 -341
- package/dist/chunks/chunk-V4WSBIXB.js +0 -2
- package/dist/chunks/chunk-WFE6FBQ2.js +0 -326
- package/dist/chunks/compaction-config-SP3REMFR.js +0 -2
- package/dist/chunks/dist-IKWRJW6J.js +0 -2
- package/dist/chunks/host-XL5CH7QP.js +0 -2
- package/dist/chunks/run-manager-UXIPDVVF.js +0 -2
- package/dist/chunks/utils-XKWEVPE3.js +0 -2
- package/dist/types-chunks/storage.d-C3umBC4g.d.ts +0 -280
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
+
import{a as gn}from"./chunk-YRBNXFHY.js";import{$ as Re,$a as Zr,Bc as Tn,Bd as ht,C as at,Cd as _n,D as Ur,Ea as Xr,Ed as Cn,Fa as Yr,Fc as oo,Fd as ro,Gb as yn,Gc as bn,Hc as xn,Ic as x,Jc as fe,Kc as mt,Lc as $e,Mc as vn,O as Br,Qa as zr,Ta as Vr,U as Hr,X as $r,Ya as Qr,Za as eo,aa as ct,ab as Jr,ad as ft,bb as en,bd as pe,cb as ut,d as Dr,da as jr,db as tn,e as $,eb as on,f as j,fb as to,g as Lr,ga as qr,gb as M,ha as Wr,hb as rn,hd as kn,ia as Gr,ib as nn,id as wn,jb as sn,kb as an,lb as cn,mb as ln,nb as J,nd as Rn,ob as Ee,od as En,pa as Kr,pb as un,qb as Se,rb as dt,sa as lt,sb as dn,tb as mn,ub as fn,vb as pn,wb as hn,y as Fr,yd as Sn,zd as pt}from"./chunk-3HKBBY74.js";import{A as me,B as ir,F as sr,Ga as Gt,Ja as we,O as ar,Q as cr,Ra as Kt,T as ke,Va as lr,Wa as ur,Xa as dr,Ya as mr,_a as fr,b as Le,c as Fe,d as Ue,e as nr,pa as qt,xa as Wt}from"./chunk-O7N22GJ3.js";import{$d as Or,Ab as st,Bb as kr,Ea as xr,Fa as vr,Fb as wr,Id as Zt,Qd as Jt,Td as Mr,Ud as Ar,Vd as Pr,_d as Ir,be as Nr,f as re,g as it,gd as Vt,hd as Qt,id as Rr,j as hr,k as Z,kd as Er,l as gr,ld as Sr,md as _r,n as E,nd as Cr,p as yr,pc as He,qa as Tr,ra as Yt,rb as Be,sb as zt,za as br}from"./chunk-TLJGOKBT.js";import{a as Xt,z as pr}from"./chunk-PZTG2C33.js";import{a as i}from"./chunk-ONUPGMER.js";import{readFile as zs}from"fs/promises";var Mn=75;function Vs(e){return typeof e!="number"||e<=0?Mn:e<=2e5?60:e<=256e3?65:e<=5e5?70:75}i(Vs,"adaptiveTriggerPercent");var Qs={enabled:!0};async function An(e,t){let o=br("config.json"),r;try{let a=await Zs(o);a?.compaction&&(r=a.compaction)}catch{}let n={...Qs,...r,triggerPercent:Mn};t?.enabled!==void 0&&(n.enabled=t.enabled),t?.contextWindow!==void 0&&(n.contextWindow=t.contextWindow);let s=n.contextWindow??e;return n.triggerPercent=typeof t?.triggerPercent=="number"?t.triggerPercent:typeof r?.triggerPercent=="number"?r.triggerPercent:Vs(s),n}i(An,"loadCompactionConfig");async function Zs(e){try{let t=await zs(e,"utf-8");return JSON.parse(t)}catch{return null}}i(Zs,"readConfigFile");var q;(function(e){e[e.TRANSIENT=0]="TRANSIENT",e[e.PERMANENT=1]="PERMANENT",e[e.TOOL_CALL_ID=2]="TOOL_CALL_ID",e[e.USER_ABORT=3]="USER_ABORT"})(q||(q={}));var Js=[/\bstream incomplete\b/i,/\bstream interrupted\b/i,/\bstream stalled\b/i,/\bdelayed response\b/i,/\btimed out\b/i,/\btimeout\b/i,/\bnetwork\b/i,/\bconnection error\b/i,/\bconnection reset\b/i,/\bconnection closed\b/i,/\bsocket hang up\b/i,/\bfetch failed\b/i,/\beconnrefused\b/i,/\beconnreset\b/i,/\betimedout\b/i,/\benotfound\b/i,/\beai_again\b/i,/\bother side closed\b/i,/\baborted\b/i,/网络错误/,/网络异常/,/连接超时/,/连接错误/,/连接失败/,/连接被拒绝/,/请求超时/,/服务繁忙/,/服务不可用/,/服务器错误/,/服务器内部错误/,/请求过多/,/频率限制/,/限流/,/过载/,/容量不足/];function Pn(e){return Js.some(t=>t.test(e))}i(Pn,"matchesTransientMessage");function ea(e){if(e.name==="StreamIncompleteError"||e.message.includes("Stream incomplete"))return{category:q.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:2e3,shouldCleanup:!0};if(e.name==="AbortError")return{category:q.USER_ABORT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0};if(e instanceof nr||e.message.includes("tool_call_id")||e.message.includes("tool result"))return{category:q.TOOL_CALL_ID,retryable:!0,maxRetries:1,retryDelay:1e3,shouldCleanup:!0};if(e instanceof Fe)return{category:q.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:e.retryAfter??6e4,shouldCleanup:!0};if(e instanceof Ue)return{category:q.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:e.isTimeout?5e3:2e3,shouldCleanup:!0};if(e instanceof Le){let o=e.message.toLowerCase();return Pn(o)?{category:q.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:2e3,shouldCleanup:!0}:{category:q.PERMANENT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0}}let t=e.message.toLowerCase();return Pn(t)?{category:q.TRANSIENT,retryable:!0,maxRetries:2,retryDelay:2e3,shouldCleanup:!0}:{category:q.PERMANENT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0}}i(ea,"classifyError");function no(e,t){return new Promise((o,r)=>{if(t?.aborted){r(t.reason instanceof Error?t.reason:new DOMException("Request aborted","AbortError"));return}let n,s=t;if(!s){n=setTimeout(()=>{o()},e);return}let a=i(()=>{clearTimeout(n),s.removeEventListener("abort",a),r(s.reason instanceof Error?s.reason:new DOMException("Request aborted","AbortError"))},"onAbort");n=setTimeout(()=>{s.removeEventListener("abort",a),o()},e),s.addEventListener("abort",a,{once:!0})})}i(no,"waitForRetryDelay");var On={requestTimeoutMs:6e5,streamIdleTimeoutMs:Number(process.env.KODAX_STREAM_IDLE_TIMEOUT_MS)||0,chunkTimeoutMs:3e4,maxRetries:4,maxRetryDelayMs:6e4,enableNonStreamingFallback:!0};function io(e,t,o){let r={...On};if(t&&In(r,t),o&&o.length>0){let n=o.find(s=>s.provider===e);if(n){let{provider:s,...a}=n;In(r,a)}}return r}i(io,"resolveResilienceConfig");function In(e,t){t.requestTimeoutMs!==void 0&&(e.requestTimeoutMs=t.requestTimeoutMs),t.streamIdleTimeoutMs!==void 0&&(e.streamIdleTimeoutMs=t.streamIdleTimeoutMs),t.chunkTimeoutMs!==void 0&&(e.chunkTimeoutMs=t.chunkTimeoutMs),t.maxRetries!==void 0&&(e.maxRetries=t.maxRetries),t.maxRetryDelayMs!==void 0&&(e.maxRetryDelayMs=t.maxRetryDelayMs),t.enableNonStreamingFallback!==void 0&&(e.enableNonStreamingFallback=t.enableNonStreamingFallback)}i(In,"mergePartialConfig");var ta=[/\brate.?limit\b/i,/\btoo many requests\b/i,/\b429\b/,/\bquota exceeded\b/i,/\bapi credits?\b/i,/请求过多/,/频率限制/,/限流/,/配额/],Nn=[/\boverloaded\b/i,/\bcapacity\b/i,/\bserver (error|busy)\b/i,/\bprovider service error\b/i,/\btry (again )?(a )?moment later\b/i,/\b(api|http|provider|status( code)?)\b[^\n]{0,40}\b5(00|02|03|29)\b/i,/\b5(00|02|03|29)\b[^\n]{0,40}\b(api|http|provider|server|status( code)?)\b/i,/\b503\b/,/\b502\b/,/\binternal server error\b/i,/\bservice unavailable\b/i,/服务繁忙/,/服务不可用/,/服务器错误/,/服务器内部错误/,/过载/,/容量不足/],so=[/\bconnection (error|reset|closed|refused|terminated)\b/i,/\bsocket hang up\b/i,/\bsocket closed\b/i,/\bfetch failed\b/i,/\beconnrefused\b/i,/\beconnreset\b/i,/\bepipe\b/i,/\benotfound\b/i,/\beai_again\b/i,/\bother side closed\b/i,/\bnetwork\b/i,/\baborted\b/i,/\bterminated\b/i,/\bpremature close\b/i,/\bund_err_socket\b/i,/\bund_err_closed\b/i,/\bund_err_aborted\b/i,/\bund_err_destroyed\b/i,/网络错误/,/网络异常/,/连接错误/,/连接失败/,/连接被拒绝/,/连接被重置/,/连接被终止/,/连接已终止/,/连接中断/],ao=[/\btimed? ?out\b/i,/\betimedout\b/i,/\bheaders timeout\b/i,/\bbody timeout\b/i,/\bund_err_headers_timeout\b/i,/\bund_err_body_timeout\b/i,/\bund_err_connect_timeout\b/i,/连接超时/,/请求超时/,/响应超时/],Dn=[/\bstream incomplete\b/i,/\bstream interrupted\b/i],oa=[/\bstream stalled or delayed\b/i,/\b60s idle\b/i,/\bidle timeout\b/i],ra=[/\bhard timeout\b/i,/\b10 minutes?\b/i,/\bapi hard timeout\b/i],na=[/reasoning_content/i,/thinking.{0,40}signature/i,/signature.{0,40}thinking/i],ia=[/\bcontext too long\b/i,/\bmaximum context\b/i,/\bcontext length\b/i,/\bcontext window\b/i,/\btoo many tokens\b/i],sa=[/\b(401|403)\b/,/\b(auth|unauthorized|forbidden|api key|not configured|permission denied)\b/i];function gt(e,t){let o=Ln(e);if(e.name==="AbortError")return{errorClass:"user_abort",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0};if(e instanceof Fe||F(o,ta)){let r=e instanceof Fe?e.retryAfter:void 0;return{errorClass:"rate_limit",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:r??6e4}}return e instanceof Le&&F(o,Nn)?{errorClass:"provider_overloaded",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:e.name==="StreamIncompleteError"||F(o,Dn)?{errorClass:"incomplete_stream",failureStage:ca(o,t),retryable:!0,maxRetries:3,baseRetryDelay:2e3}:F(o,oa)?{errorClass:"stream_idle_timeout",failureStage:t??"mid_stream_text",retryable:!0,maxRetries:3,baseRetryDelay:3e3}:F(o,ra)?{errorClass:"request_timeout",failureStage:t??"before_first_delta",retryable:!0,maxRetries:2,baseRetryDelay:5e3}:e instanceof Ue&&e.isTimeout||F(o,ao)?{errorClass:"request_timeout",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:e instanceof Ue||F(o,so)?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:2e3}:e instanceof Le?F(o,[...so,...ao])?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:2e3}:F(o,na)?{errorClass:"reasoning_content_required",failureStage:t??"before_first_delta",retryable:!0,maxRetries:1,baseRetryDelay:0}:{errorClass:"non_retryable_provider_error",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0}:F(o,Nn)?{errorClass:"provider_overloaded",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:F(o,[...so,...ao,...Dn])?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:2,baseRetryDelay:2e3}:{errorClass:"non_retryable_provider_error",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0}}i(gt,"classifyResilienceError");function aa(e,t){if(t<=0)return!1;let o=Ln(e);if(F(o,sa))return!1;let r=gt(e);return r.errorClass==="provider_overloaded"||r.errorClass==="reasoning_content_required"||F(o,ia)}i(aa,"isSessionRecoveryCandidateError");function F(e,t){return t.some(o=>o.test(e))}i(F,"matchesAny");function Ln(e){let t=[],o=new Set,r=e,n=0,s=5;for(;r!=null&&n<s&&!o.has(r);){if(o.add(r),r instanceof Error){r.message&&t.push(r.message);let a=r.code;typeof a=="string"&&a.length>0&&t.push(a),r=r.cause}else if(typeof r=="string")t.push(r),r=void 0;else if(typeof r=="object"){let a=r.message;typeof a=="string"&&t.push(a);let c=r.code;typeof c=="string"&&t.push(c),r=r.cause}else break;n+=1}return t.join(" | ").toLowerCase()}i(Ln,"collectErrorText");function ca(e,t){return t||(/\btool.?input\b/i.test(e)||/\btool.?call\b/i.test(e)?"mid_stream_tool_input":/\bthinking\b/i.test(e)?"mid_stream_thinking":"mid_stream_text")}i(ca,"inferStageForStreamError");var la=0;function Fn(){return`req_${Date.now()}_${++la}`}i(Fn,"nextRequestId");var je=class{static{i(this,"StableBoundaryTracker")}state;hasReceivedFirstDelta=!1;currentToolInputId;constructor(){this.state=this.createInitialState()}beginRequest(t,o,r,n=1,s=!1){this.state={requestId:Fn(),provider:t,model:o,attempt:n,lastStableMessageIndex:r.length,executedToolCallIds:[...this.state.executedToolCallIds],pendingToolCallIds:[],visibleLiveTextLength:0,visibleThinkingLength:0,fallbackUsed:s,startedAt:Date.now()},this.hasReceivedFirstDelta=!1,this.currentToolInputId=void 0}markFirstDelta(){this.hasReceivedFirstDelta=!0}markTextDelta(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.state.visibleLiveTextLength+=t.length}markThinkingDelta(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.state.visibleThinkingLength+=t.length}markToolInputStart(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.currentToolInputId=t,this.state.pendingToolCallIds.includes(t)||this.state.pendingToolCallIds.push(t)}markToolExecuted(t){this.state.pendingToolCallIds=this.state.pendingToolCallIds.filter(o=>o!==t),this.state.executedToolCallIds.includes(t)||this.state.executedToolCallIds.push(t),this.currentToolInputId===t&&(this.currentToolInputId=void 0)}markAssistantComplete(t){this.state.lastStableMessageIndex=t.length,this.state.visibleLiveTextLength=0,this.state.visibleThinkingLength=0,this.state.pendingToolCallIds=[],this.hasReceivedFirstDelta=!1}inferFailureStage(){return this.hasReceivedFirstDelta?this.currentToolInputId?"mid_stream_tool_input":this.state.visibleThinkingLength>0&&this.state.visibleLiveTextLength===0?"mid_stream_thinking":this.state.executedToolCallIds.length>0?"post_tool_execution_pre_assistant_close":"mid_stream_text":"before_first_delta"}snapshot(){return{...this.state}}get hasReceivedDelta(){return this.hasReceivedFirstDelta}recoverToStableBoundary(t){let o=Math.min(this.state.lastStableMessageIndex,t.length),r=t.slice(0,o),n=[...this.state.pendingToolCallIds],s=[...this.state.executedToolCallIds];return{messages:r,droppedToolCallIds:n,executedToolCallIds:s}}reset(){this.state=this.createInitialState(),this.hasReceivedFirstDelta=!1,this.currentToolInputId=void 0}createInitialState(){return{requestId:Fn(),provider:"",model:"",attempt:1,lastStableMessageIndex:0,executedToolCallIds:[],pendingToolCallIds:[],visibleLiveTextLength:0,visibleThinkingLength:0,fallbackUsed:!1,startedAt:Date.now()}}};function yt(e,t,o){if(e.length===0)return[];let r=ua(e,o),n=da(r),s=t.filter(a=>!n.includes(a));return s.length>0?ma(r,s):r}i(yt,"reconstructMessagesWithToolGuard");function ua(e,t){if(t.length===0)return[...e];let o=new Set(t);return e.map(r=>{if(typeof r.content=="string")return r;let n=r.content.filter(s=>s.type==="tool_use"?!o.has(s.id):s.type==="tool_result"?!o.has(s.tool_use_id):!0);return n.length===0?{...r,content:[{type:"text",text:""}]}:{...r,content:n}})}i(ua,"filterIncompleteToolCalls");function da(e){let t=[];for(let o of e)if(typeof o.content!="string")for(let r of o.content)r.type==="tool_result"&&t.push(r.tool_use_id);return t}i(da,"collectToolResultIds");function ma(e,t){let o=[...e],r=t.map(n=>({type:"tool_result",tool_use_id:n,content:"[Result preserved from previous attempt - tool already executed]"}));return r.length>0&&o.push({role:"user",content:r}),o}i(ma,"appendMissingToolResults");var fa=["before_request_accepted","before_first_delta"],pa=["stream_idle_timeout","chunk_timeout","incomplete_stream","connection_failure"],qe=class{static{i(this,"ProviderRecoveryCoordinator")}boundaryTracker;config;nonStreamingFallbackUsed=!1;thinkingSanitizationUsed=!1;constructor(t,o){this.boundaryTracker=t,this.config={requestTimeoutMs:o.requestTimeoutMs??6e5,streamIdleTimeoutMs:o.streamIdleTimeoutMs??6e4,chunkTimeoutMs:o.chunkTimeoutMs??3e4,maxRetries:o.maxRetries??4,maxRetryDelayMs:o.maxRetryDelayMs??6e4,enableNonStreamingFallback:o.enableNonStreamingFallback??!0}}decideRecoveryAction(t,o,r){if(!o.retryable)return{action:"manual_continue",ladderStep:4,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};if(o.errorClass==="reasoning_content_required"&&!this.thinkingSanitizationUsed)return this.thinkingSanitizationUsed=!0,{action:"sanitize_thinking_and_retry",ladderStep:2,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};if(r>=this.config.maxRetries)return{action:"manual_continue",ladderStep:4,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};let n=ga(o.baseRetryDelay,r,this.config.maxRetryDelayMs),s=ya(t),a=s!==void 0?Math.min(s,this.config.maxRetryDelayMs):n,{action:c,ladderStep:d,shouldUseNonStreaming:u}=this.selectRecoveryStrategy(o,r);return{action:c,ladderStep:d,delayMs:a,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:u,reasonCode:o.errorClass,failureStage:o.failureStage,serverRetryAfterMs:s}}executeRecovery(t,o){switch(o.action){case"fresh_connection_retry":return this.executeFreshConnectionRetry(t,o);case"stable_boundary_retry":return this.executeStableBoundaryRetry(t,o);case"non_streaming_fallback":return this.executeNonStreamingFallback(t,o);case"manual_continue":return this.executeManualContinue(t,o);case"sanitize_thinking_and_retry":return this.executeSanitizeThinking(t,o)}}selectRecoveryStrategy(t,o){let r=t.failureStage,n=t.errorClass;return pa.includes(n)&&this.config.enableNonStreamingFallback&&!this.nonStreamingFallbackUsed&&o>=2?(this.nonStreamingFallbackUsed=!0,{action:"non_streaming_fallback",ladderStep:3,shouldUseNonStreaming:!0}):fa.includes(r)?{action:"fresh_connection_retry",ladderStep:1,shouldUseNonStreaming:!1}:{action:"stable_boundary_retry",ladderStep:2,shouldUseNonStreaming:!1}}executeFreshConnectionRetry(t,o){let r=this.boundaryTracker.snapshot();return{messages:[...t],droppedToolCallIds:[],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}executeStableBoundaryRetry(t,o){let r=this.boundaryTracker.recoverToStableBoundary(t);return{messages:yt(r.messages,r.executedToolCallIds,r.droppedToolCallIds),droppedToolCallIds:r.droppedToolCallIds,executedToolCallIds:r.executedToolCallIds,fallbackUsed:this.nonStreamingFallbackUsed}}executeNonStreamingFallback(t,o){let r=this.boundaryTracker.recoverToStableBoundary(t);return{messages:yt(r.messages,r.executedToolCallIds,r.droppedToolCallIds),droppedToolCallIds:r.droppedToolCallIds,executedToolCallIds:r.executedToolCallIds,fallbackUsed:!0}}executeManualContinue(t,o){let r=this.boundaryTracker.snapshot();return{messages:[...t],droppedToolCallIds:[...r.pendingToolCallIds],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}executeSanitizeThinking(t,o){let r=this.boundaryTracker.snapshot();return{messages:ha(t),droppedToolCallIds:[],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}reset(){this.nonStreamingFallbackUsed=!1,this.thinkingSanitizationUsed=!1}};function ha(e){return e.map(t=>{if(t.role!=="assistant"||typeof t.content=="string"||!Array.isArray(t.content))return t;let o=t.content.filter(r=>r.type!=="thinking"&&r.type!=="redacted_thinking");return o.length===0?{...t,content:[{type:"text",text:""}]}:{...t,content:o}})}i(ha,"sanitizeThinkingBlocks");function ga(e,t,o){let r=e*Math.pow(2,t-1),n=Math.random()*1e3;return Math.min(r+n,o)}i(ga,"calculateRetryDelay");function ya(e){if("retryAfter"in e&&typeof e.retryAfter=="number")return e.retryAfter*1e3}i(ya,"extractServerRetryAfter");var Tt=process.env.KODAX_DEBUG_STREAM==="1"||process.env.KODAX_DEBUG_RESILIENCE==="1";function co(e,t){Tt&&E({source:"coding:resilience",level:"debug",message:"classify",detail:{rawError:e.message,errorClass:t.errorClass,failureStage:t.failureStage,retryable:t.retryable,maxRetries:t.maxRetries}})}i(co,"telemetryClassify");function lo(e,t){Tt&&E({source:"coding:resilience",level:"debug",message:"decision",detail:{action:e.action,ladderStep:e.ladderStep,attempt:t,delayMs:e.delayMs,maxDelayMs:e.maxDelayMs,reasonCode:e.reasonCode,failureStage:e.failureStage,shouldUseNonStreaming:e.shouldUseNonStreaming,serverRetryAfterMs:e.serverRetryAfterMs}})}i(lo,"telemetryDecision");function uo(e){Tt&&E({source:"coding:resilience",level:"debug",message:"boundary",detail:{requestId:e.requestId,provider:e.provider,attempt:e.attempt,lastStableMessageIndex:e.lastStableMessageIndex,executedToolCallIds:e.executedToolCallIds,pendingToolCallIds:e.pendingToolCallIds,visibleLiveTextLength:e.visibleLiveTextLength,visibleThinkingLength:e.visibleThinkingLength,fallbackUsed:e.fallbackUsed,failureStage:e.failureStage}})}i(uo,"telemetryBoundary");function bt(e,t){Tt&&E({source:"coding:resilience",level:"debug",message:"recovery",detail:{action:e,droppedToolCallIds:t.droppedToolCallIds,executedToolCallIds:t.executedToolCallIds,fallbackUsed:t.fallbackUsed}})}i(bt,"telemetryRecovery");function We(e,t){if(!t||t.length===0)return e;let o=[{type:"text",text:e}];for(let r of t){if(r.kind!=="image")throw new Xt("MODEL_INPUT_UNSUPPORTED",`${r.kind} artifacts cannot be attached to the provider prompt yet.`,{detail:"Only image artifacts are currently lowered into provider prompt content."});o.push({type:"image",path:r.path,mediaType:r.mediaType})}return o}i(We,"buildPromptMessageContent");function mo(e){return e._truncated===!0||e._salvaged===!0&&Sn(e.name)}i(mo,"isUntrustedSalvage");function Bn(e){let t=[];for(let o of e){if(mo(o)){t.push(`${o.name}: incomplete input (salvaged from malformed/truncated JSON)`);continue}let r=pt(o.name),n=o.input??{};for(let s of r)(n[s]===void 0||n[s]===null||n[s]==="")&&t.push(`${o.name}: missing '${s}'`)}return t}i(Bn,"checkIncompleteToolCalls");function Fm(e,t=400){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}i(Fm,"truncateText");function Hn(e){if(!e)return"";if(typeof e.lastText=="string"&&e.lastText.trim())return e.lastText;let t=e.messages?.[e.messages.length-1];return!t||t.role!=="assistant"?"":typeof t.content=="string"?t.content:t.content.map(o=>("text"in o?o.text:"")||"").join("")}i(Hn,"extractMessageText");function Ta(e){return e==="running"||e==="planned"}i(Ta,"isUnconvergedVerdict");function ba(e){let t=e.trim();return t===""||t==="..."}i(ba,"isPlaceholderOnlyAssistantText");function xa(e){let t=Hn(e);return ba(t)?"":t}i(xa,"extractFinalAssistantText");function Gm(e,t,o){if(!e.messages)return e;let r=xa(e);if(Ta(e.managedTask?.verdict?.status)||e.interrupted&&!r)return e;let n=t.context?.inputArtifacts,s=e.artifactLedger??Zt(e.messages),a=va(e.messages,o,r,n),c=e.contextTokenSnapshot?rn(a,e.contextTokenSnapshot):void 0;return{...e,messages:a,artifactLedger:s,contextTokenSnapshot:c}}i(Gm,"reshapeToUserConversation");function va(e,t,o,r){let n=e,s=n[0];s?.role==="system"&&typeof s.content=="string"&&!s.content.startsWith(Jt)&&(n=n.slice(1)),n=fo(n);let c=!n.some(u=>u.role==="user"&&xt(u)===t);c&&n[0]?.role==="system"&&typeof n[0].content=="string"&&n[0].content.startsWith(Jt)&&n.some(l=>l.role==="user")&&(c=!1),c&&(n=[...n,{role:"user",content:We(t,r)}]);let d=n[n.length-1];return d?.role==="assistant"&&typeof d.content=="string"&&d.content===o||(d?.role==="assistant"?n=[...n.slice(0,-1),{role:"assistant",content:o}]:n=[...n,{role:"assistant",content:o}]),[...n]}i(va,"preserveTranscriptForRoundExit");function fo(e){let t=e.length;for(;t>=2;){let o=e[t-2],r=e[t-1];if(o.role==="user"&&r.role==="assistant"&&wa(o)){t-=2;continue}break}return e.slice(0,t)}i(fo,"normalizeLoadedSessionMessages");var ka=/^\s*You are the (Scout|Planner|Generator|Evaluator) role\b/;function wa(e){if(e.role!=="user")return!1;let t=typeof e.content=="string"?e.content:Ra(e.content);return ka.test(t)}i(wa,"isRolePromptShapedUser");function Ra(e){let t=e[0];return t?.type==="text"&&typeof t.text=="string"?t.text:""}i(Ra,"extractLeadingTextBlock");function Un(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
3
|
+
`)}i(Un,"extractPromptComparableText");function xt(e){if(!(!e||e.role!=="user"))return Un(e.content)}i(xt,"extractComparableUserMessageText");async function $n(e,t){if(e.session?.initialMessages&&e.session.initialMessages.length>0){let o=[...e.session.initialMessages],n=!(e.session.initialExtensionState!==void 0||e.session.initialExtensionRecords!==void 0)&&e.session.storage&&t?await e.session.storage.load(t).catch(()=>null):null;return{messages:o,title:Qt(o),errorMetadata:n?.errorMetadata,loadedExtensionState:e.session.initialExtensionState??n?.extensionState,loadedExtensionRecords:e.session.initialExtensionRecords??n?.extensionRecords}}if(e.session?.storage&&t){let o=await e.session.storage.load(t);if(o)return{messages:fo(o.messages),title:o.title,errorMetadata:o.errorMetadata,loadedExtensionState:o.extensionState,loadedExtensionRecords:o.extensionRecords}}return{messages:[],title:""}}i($n,"resolveInitialMessages");function jn(e,t,o,r){let n=e[e.length-1];return xt(n)===t?r!==void 0&&n!==void 0&&n.turnId===void 0?[...e.slice(0,-1),{...n,turnId:r}]:e:[...e,{role:"user",content:We(t,o),...r!==void 0?{turnId:r}:{},timestamp:new Date().toISOString()}]}i(jn,"appendPromptIfNotDuplicate");async function qn(e){let t=e.session?.id;if(t)return t;if(!(e.session?.autoResume||e.session?.resume))return;let r=e.session?.storage;if(!r?.list)return;let n=await r.list(e.context?.gitRoot??void 0);return n.length>0?n[0].id:void 0}i(qn,"discoverAutoResumeSessionId");function Ea(e){return qt(e)?"builtin":Gt(e)?"runtime":Wt(e)?"custom":"unknown"}i(Ea,"detectProviderSourceKind");function Sa(e,t){return e?e.getCapabilityProfile():t??{transport:"native-api",conversationSemantics:"full-history",mcpSupport:"none"}}i(Sa,"resolveCapabilityProfile");function _a(e,t,o){return e?e.getReasoningCapability(t):o??"unknown"}i(_a,"resolveReasoningCapability");function Ca(e){let t=cr(Sa(e.provider,e.capabilityProfile));return{provider:e.providerName,model:e.model,sourceKind:Ea(e.providerName),transport:t.transport,conversationSemantics:t.conversationSemantics,mcpSupport:t.mcpSupport,contextFidelity:t.contextFidelity,toolCallingFidelity:t.toolCallingFidelity,sessionSupport:t.sessionSupport,longRunningSupport:t.longRunningSupport,multimodalSupport:t.multimodalSupport,evidenceSupport:t.evidenceSupport,reasoningCapability:_a(e.provider,e.model,e.reasoningCapability)}}i(Ca,"buildProviderCapabilitySnapshot");function Ma(e){return!!e?.inputArtifacts?.some(t=>t.kind==="image")}i(Ma,"detectMultimodalContext");function Aa(e){if(!e)return{};let t=e.toLowerCase();return{evidenceHeavy:/merge blocker|review|strict audit|runtime error|stack trace|stderr|failing test|evidence/.test(t)?!0:void 0}}i(Aa,"inferPromptPolicyHints");function _e(...e){return e.find(t=>t!==void 0)}i(_e,"pickBoolean");function Pa(e){let t=e.context??e.options?.context,o=Aa(e.prompt);return{longRunning:_e(e.hints?.longRunning,t?.providerPolicyHints?.longRunning,o.longRunning),harnessProfile:e.hints?.harnessProfile??t?.providerPolicyHints?.harnessProfile,evidenceHeavy:_e(e.hints?.evidenceHeavy,t?.providerPolicyHints?.evidenceHeavy,o.evidenceHeavy),multimodal:_e(e.hints?.multimodal,t?.providerPolicyHints?.multimodal,Ma(t),o.multimodal),capabilityRuntime:_e(e.hints?.capabilityRuntime,t?.providerPolicyHints?.capabilityRuntime,o.capabilityRuntime),mcpRequired:_e(e.hints?.mcpRequired,t?.providerPolicyHints?.mcpRequired,o.mcpRequired),brainstorm:_e(e.hints?.brainstorm,t?.providerPolicyHints?.brainstorm,o.brainstorm),workIntent:e.hints?.workIntent??t?.providerPolicyHints?.workIntent??o.workIntent}}i(Pa,"resolveProviderPolicyHints");function ne(e,t){e.some(o=>o.code===t.code)||e.push(t)}i(ne,"pushIssue");function Ia(e,t){let o=new Set;e.transport==="cli-bridge"&&o.add("Provider uses a CLI bridge rather than a native API, so semantic parity should not be assumed."),e.conversationSemantics==="last-user-message"&&o.add("Provider forwards only the latest user message instead of preserving full-history semantics.");for(let r of t)o.add(r.detail);return Array.from(o)}i(Ia,"buildRoutingNotes");function Oa(e){return e.length===0?"No provider-policy constraints detected.":e.map(t=>`${t.severity.toUpperCase()}: ${t.summary}`).join(" | ")}i(Oa,"summarizeIssues");function Wn(e){return[...[`[Provider Policy] provider=${e.snapshot.provider}${e.snapshot.model?` model=${e.snapshot.model}`:""}; status=${e.status}.`,`[Provider Semantics] transport=${e.snapshot.transport}; context=${e.snapshot.contextFidelity}; toolCalling=${e.snapshot.toolCallingFidelity}; session=${e.snapshot.sessionSupport}; longRunning=${e.snapshot.longRunningSupport}; multimodal=${e.snapshot.multimodalSupport}; evidence=${e.snapshot.evidenceSupport}; mcp=${e.snapshot.mcpSupport}; reasoning=${e.snapshot.reasoningCapability}.`],...e.issues.map(o=>`[Provider Constraint] ${o.severity.toUpperCase()}: ${o.detail}`)]}i(Wn,"buildProviderPolicyPromptNotes");function vt(e){let t=Ca({providerName:e.providerName,model:e.model,provider:e.provider,capabilityProfile:e.capabilityProfile,reasoningCapability:e.reasoningCapability}),o=Pa(e),r=[];return o.multimodal&&t.multimodalSupport==="none"&&ne(r,{code:"multimodal-unsupported",severity:"block",summary:"multimodal requests are unsupported on this provider",detail:"This flow requests multimodal or image semantics, but the selected provider only exposes text-only behavior."}),o.mcpRequired&&t.mcpSupport==="none"?ne(r,{code:"mcp-required",severity:"block",summary:"native MCP semantics are unavailable on this provider",detail:"This flow explicitly requires MCP-native behavior, but the selected provider reports no native MCP support."}):o.capabilityRuntime&&t.mcpSupport==="none"&&ne(r,{code:"capability-runtime-limited",severity:"warn",summary:"capability-oriented flows are constrained by provider semantics",detail:"Capability or MCP-oriented workflows may lose parity because the provider does not expose native MCP semantics."}),o.longRunning&&(t.longRunningSupport==="none"||t.sessionSupport==="stateless"||t.contextFidelity==="lossy"?ne(r,{code:"long-running-blocked",severity:"block",summary:"long-running execution is unsafe on this provider",detail:"Long-running flows require durable session semantics and reliable context fidelity, but this provider reports lossy or stateless behavior."}):(t.longRunningSupport==="limited"||t.sessionSupport==="limited")&&ne(r,{code:"long-running-limited",severity:"warn",summary:"long-running execution is degraded on this provider",detail:"Long-running flows may behave inconsistently because this provider only offers limited session or long-running support."})),(o.evidenceHeavy===!0||e.taskType==="review"||e.taskType==="bugfix"||e.executionMode==="pr-review"||e.executionMode==="strict-audit"||e.executionMode==="investigation")&&(t.contextFidelity==="lossy"&&ne(r,{code:"evidence-context-loss",severity:"warn",summary:"evidence-heavy work is constrained by lossy context semantics",detail:"Evidence-heavy routing remains available, but this provider can lose prior-turn context and should not be treated as equivalent to full-history providers."}),t.evidenceSupport==="limited"&&ne(r,{code:"evidence-support-limited",severity:"warn",summary:"evidence-heavy work may lose fidelity on this provider",detail:"This provider only reports limited evidence support, so review and investigation flows may need extra caution."})),e.reasoningMode!=="off"&&(t.reasoningCapability==="prompt-only"||t.reasoningCapability==="none")&&ne(r,{code:"reasoning-control-limited",severity:"warn",summary:"native reasoning control is unavailable on this provider",detail:"Reasoning remains usable, but the provider cannot enforce native reasoning controls beyond prompt-level guidance."}),{status:r.some(a=>a.severity==="block")?"block":r.length>0?"warn":"allow",snapshot:t,issues:r,routingNotes:Ia(t,r),summary:Oa(r)}}i(vt,"evaluateProviderPolicy");var Na="off",Da=.4,La=.42,Fa=.45,Gn=.5,Ua=.06,Ba=.04,Ha=.86,$a=.75,ja=.49,qa=.5;var Wa=["brainstorm","explore","explore options","option framing","tradeoff","trade-off","safest way","figure out","design first","\u65B9\u6848","\u601D\u8DEF","\u5148\u60F3","\u5148\u8BBE\u8BA1","\u5148\u5206\u6790","\u5148\u8BA8\u8BBA"],Ga=["continue","extend","build on","follow up","append","add to","based on the existing","\u63A5\u7740","\u7EE7\u7EED","\u8865\u5145","\u8FFD\u52A0","\u5EF6\u7EED","\u6269\u5C55\u73B0\u6709"],Ka=["rewrite","replace","overwrite","from scratch","start over","regenerate","redo","\u91CD\u5199","\u66FF\u6362","\u8986\u76D6","\u63A8\u5012\u91CD\u6765","\u5168\u90E8\u6539\u6389","\u91CD\u65B0\u505A"],po={simple:[],moderate:["screen","component","endpoint","service","feature","\u6A21\u5757","\u529F\u80FD","\u9875\u9762"],complex:["migration","architecture","cross-package","multi-step","pipeline","state machine","refactor","monorepo","across packages","integration","\u8FC1\u79FB","\u67B6\u6784","\u8DE8\u5305","\u91CD\u6784","\u6D41\u7A0B"],systemic:["system-wide","orchestrate","multi-agent","control plane","runtime substrate","whole repo","entire repo","across the monorepo","\u5168\u4ED3","\u5168\u5C40","\u6574\u4F53\u67B6\u6784","\u63A7\u5236\u9762","\u591A\u667A\u80FD\u4F53"]},Xa=2,Ya=4,za=6,Va=10,ho=1200;var Qa=30,ti=4e3;function oi(e){return e.reasoningMode?e.reasoningMode:e.thinking===!0?"auto":e.thinking===!1?"off":Na}i(oi,"resolveReasoningMode");function Za(e){return sr(e)}i(Za,"reasoningModeToDepth");var Kn={none:0,minimal:0,auto:1,low:2,medium:3,high:4,xhigh:5,max:6};function Xn(e){return Kn[e]??Kn.medium}i(Xn,"effortRank");function Ja(e,t){let o=Xn(e),r=Xn(t);return o<r?-1:o>r?1:0}i(Ja,"compareEfforts");function Yn(e,t){return Ja(e,t)>0?t:e}i(Yn,"clampEffort");function af(e,t){if(e==="none")return"none";if(!t)return e;let o=t.default?me(t.default):e,r=t.max?Yn(o,me(t.max)):o;return Yn(r,e)}i(af,"resolveRoleEffort");var ec=Object.freeze(["\u4E0D\u5BF9","\u9519\u4E86","\u6709\u95EE\u9898","\u771F\u7684\u5417","\u4F60\u786E\u5B9A","\u4E0D\u662F\u8FD9\u6837","\u5F04\u9519\u4E86","\u641E\u9519\u4E86","\u641E\u53CD\u4E86","\u8FD9\u4E0D\u5BF9","\u4E0D\u6B63\u786E","\u7B54\u9519","\u56DE\u7B54\u9519","that's wrong","that is wrong","that's not right","that is not right","are you sure","not really","this is wrong","this is incorrect","that's incorrect","that is incorrect","you're wrong","you are wrong"]),tc=Object.freeze(["\u4ED4\u7EC6","\u6DF1\u5165","\u8BA4\u771F","\u518D\u770B\u770B","\u518D\u60F3\u60F3","\u60F3\u6E05\u695A","\u7528\u5FC3","\u6DF1\u5EA6\u5206\u6790","\u4ED4\u7EC6\u5206\u6790","\u8BA4\u771F\u5206\u6790","\u5F7B\u5E95","think harder","think more carefully","look more carefully","dig deeper","be thorough","more careful","more carefully","reconsider","reexamine","re-examine"]);function oc(e,t){if(!e)return{category:null,matched:null};let o=e.toLowerCase();if(t)for(let r of ec){let n=r.toLowerCase();if(o.includes(n)||e.includes(r))return{category:"doubt",matched:r}}for(let r of tc){let n=r.toLowerCase();if(o.includes(n)||e.includes(r))return{category:"deepen",matched:r}}return{category:null,matched:null}}i(oc,"detectFollowupSignal");function rc(e){switch(e){case"auto":return"low";case"low":return"medium";case"medium":return"high";default:return e}}i(rc,"escalateEffort");function nc(e,t,o){let r=oc(t,o);if(r.category===null)return{effective:e,escalated:!1,signal:r};let n=rc(e);return n===e?{effective:e,escalated:!1,signal:r}:{effective:n,escalated:!0,signal:r}}i(nc,"applyFollowupEscalation");function ri(e,t){let o=e.effort??me(oi(e)),n=(e.session?.initialMessages??[]).some(a=>a?.role==="assistant"),s=nc(o,t,n);return s.escalated?{options:{...e,effort:s.effective},escalation:s}:{options:e,escalation:s}}i(ri,"applyFollowupEscalationToOptions");var ic={conversation:["hello","hi","hey","\u4F60\u597D","\u55E8","\u65E9\u4E0A\u597D","\u4E0B\u5348\u597D","\u665A\u4E0A\u597D"],lookup:["where is","which file","what file","where does","where do","located","defined","\u5728\u54EA\u4E2A\u6587\u4EF6","\u5728\u54EA","\u5728\u54EA\u91CC","\u54EA\u4E2A\u6587\u4EF6","\u54EA\u4E2A\u51FD\u6570","\u54EA\u91CC\u5B9A\u4E49","\u6587\u4EF6\u4F4D\u7F6E","\u5728\u54EA\u7BA1\u7406"],review:["review","code review","pull request","merge blocker","diff","changed files","\u5BA1\u67E5","\u4EE3\u7801\u5BA1\u67E5","review \u4E00\u4E0B","\u770B\u4E0B\u6539\u52A8","\u8BC4\u5BA1","pr"],bugfix:["bug","error","exception","failing","fix","failure","traceback","stack trace","runtime error","\u62A5\u9519","\u9519\u8BEF","\u5F02\u5E38","\u4FEE\u590D","\u5931\u8D25","\u6392\u67E5"],edit:["implement","add ","change ","modify ","update ","create ","write ","\u5B9E\u73B0","\u65B0\u589E","\u4FEE\u6539","\u6539\u4E00\u4E0B","\u521B\u5EFA","\u5199\u4E00\u4E2A"],refactor:["refactor","cleanup","restructure","simplify","decouple","rename","\u91CD\u6784","\u6E05\u7406","\u4F18\u5316","\u7B80\u5316","\u89E3\u8026","\u6574\u7406"],plan:["plan","design","architecture","migration","strategy","roadmap","\u8BA1\u5212","\u8BBE\u8BA1","\u67B6\u6784","\u65B9\u6848","\u7B56\u7565","\u8DEF\u7EBF\u56FE"],qa:["explain","what is","how does","help me understand","\u89E3\u91CA","\u4E3A\u4EC0\u4E48","\u662F\u4EC0\u4E48","\u600E\u4E48\u7406\u89E3","\u4EC0\u4E48\u610F\u601D","\u8BF4\u660E"]};function sc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(sc,"escapeRegExp");function ac(e){return/^[a-z0-9][a-z0-9 _-]*$/i.test(e)}i(ac,"hasAsciiWordBoundaries");function C(e,t){if(!t)return!1;let o=t.trim();return o?ac(o)?new RegExp(`(^|[^a-z0-9])${sc(o)}([^a-z0-9]|$)`,"i").test(e):e.includes(t):!1}i(C,"textHasKeyword");function cc(e,t){let o=0;for(let r of t)r&&C(e,r)&&(o+=r.length>=6||/[^\u0000-\u007f]/.test(r)?2:1);return o}i(cc,"scoreTaskTypeKeywords");var lc=/^(?:\s|[!,.?,。!?])*?(?:hi|hello|hey|yo|你好|嗨|哈喽|早上好|下午好|晚上好)(?:\s|[!,.?,。!?])*$/i,uc=/\b(where is|which file|what file|where does|where do|defined in|located in|file manages|manages this|which component|which function)\b/i;var dc=/\b(review|code review|audit|pr|pull request|merge blocker|look at the changes|changed files)\b/i;var mc=/\b(plan|design|architecture|proposal|strategy|roadmap)\b/i;var fc=/\b(debug|investigate|root cause|why is|why does|failing|failure|runtime error|stack trace|traceback)\b/i;var pc=/\b(implement|add|change|modify|update|create|write|fix|refactor|rewrite|replace)\b/i;var hc=/\b(docs?|documentation|readme|changelog|release notes?|spec|proposal|design doc|requirements?|prd|adr|hld|dd|guide|runbook|playbook|feature list|known issues?)\b/i;var gc=/\b(?:api|backend|frontend|service|module|endpoint|component|architecture|package|migration|schema|database|auth|sdk|cli)\s+(?:docs?|documentation|guide|readme|changelog|spec|proposal|design doc|requirements?|prd|adr|hld|dd|runbook|playbook)\b|\b(?:docs?|documentation|guide|readme|changelog|spec|proposal|design doc|requirements?|prd|adr|hld|dd|runbook|playbook)\s+(?:for|about|on)\s+(?:the\s+)?(?:api|backend|frontend|service|module|endpoint|component|architecture|package|migration|schema|database|auth|sdk|cli)\b/i,yc=/(?:API|\u540e\u7aef|\u524d\u7aef|\u670d\u52a1|\u6a21\u5757|\u63a5\u53e3|\u7ec4\u4ef6|\u67b6\u6784|\u5305|\u8fc1\u79fb|\u6570\u636e\u5e93|\u8ba4\u8bc1)(?:[\u4e00-\u9fffA-Za-z0-9_\-\/\\.\s]{0,8})(?:\u6587\u6863|\u8bf4\u660e\u6587\u6863|README|CHANGELOG|PRD|ADR|HLD|DD|\u6307\u5357)/u,Tc=/\b(?:implementation|source code|code comments?|function|class|component|bug|script|tests?|ui)\b/i,bc=/\u4ee3\u7801\u6ce8\u91ca|\u5b9e\u73b0|\u51fd\u6570|\u7c7b|\u7ec4\u4ef6|bug|\u811a\u672c|\u6d4b\u8bd5|\u754c\u9762/u,xc=/\b(?:do not|don't|dont|without|no)\b[\s\S]{0,12}\b(?:change|modify|edit|touch|rewrite|update|mutate)\b[\s\S]{0,8}\bcode\b|\bno code changes?\b/i,vc=/\u4e0d\u6539\u4ee3\u7801|\u4e0d\u8981\u6539\u4ee3\u7801|\u4e0d\u4fee\u6539\u4ee3\u7801|\u4e0d\u8981\u4fee\u6539\u4ee3\u7801|\u53ea\u6539\u6587\u6863|\u53ea\u66f4\u65b0\u6587\u6863|\u4ec5\u6539\u6587\u6863|\u4ec5\u66f4\u65b0\u6587\u6863/u,kc=/\b(double[- ]check|re-check|recheck|second pass|second opinion|cross-check|cross check|independently verify|independent review|independent audit|strict audit|extra scrutiny|verify twice)\b/i;var wc=/\b(code|implementation|function|class|component|module|endpoint|service|repo|repository|file|files|test|bug|feature|script|api|ui|backend|frontend)\b/i;var Rc=/\b(deploy|deployment|restart|reboot|migrate database|run migration|seed database|provision|install dependency|install package|upgrade dependency|kill process|start server|stop server|apply terraform)\b/i;var Ec=/^(?:\s|[!,.?,。!]*)?(?:你好|哈喽|早上好|下午好|晚上好)(?:\s|[!,.?,。!]*)*$/u,Sc=/在哪个文件|哪个文件|在哪定义|定义在|哪个函数|哪个组件|文件位置|在哪里/u,_c=/审查|评审|review一下|看下改动|代码改动|审阅/u,Cc=/计划|设计|架构|方案|策略|路线图/u,Mc=/排查|定位问题|根因|为什么|报错|错误|异常|失败/u,Ac=/实现|新增|修改|创建|写一个|修复|重构|改一下|替换/u,Pc=/文档|说明文档|设计文档|需求文档|PRD|ADR|HLD|DD|CHANGELOG|README|功能清单|已知问题/u,Ic=/再检查|再审查|双重检查|第二遍|第二轮|二次审查|交叉检查|独立验证|独立审查|更强审查/u,zn=/代码|实现|函数|类|组件|模块|接口|服务|仓库|文件|测试|bug|功能|脚本|API|界面|后端|前端/u,Oc=/部署|重启|重启服务|迁移数据库|运行迁移|初始化数据库|安装依赖|升级依赖|杀进程|启动服务|停止服务|应用terraform/u,Nc=/代码|实现|函数|类|组件|模块|接口|bug|功能|前端|后端|脚本/u,Vn=/实现|新增|修改|更新|创建|编写|修复|重构|补丁|重写|替换|编辑|重命名/u;function Dc(e){return lc.test(e)||Ec.test(e)}i(Dc,"isGreetingOnlyPrompt");function go(e){let t=e.trim();if(!t)return{primaryTask:"conversation",taskFamily:"conversation",actionability:"non_actionable",executionPattern:"direct",shouldUseRepoSignals:!1,requiresRoutingHeuristics:!1,reason:"Empty input is treated as non-actionable conversation."};if(Dc(t))return{primaryTask:"conversation",taskFamily:"conversation",actionability:"non_actionable",executionPattern:"direct",shouldUseRepoSignals:!1,requiresRoutingHeuristics:!1,reason:"Pure greeting input should stay conversational and must not be escalated by repository state."};let o=uc.test(t)||Sc.test(t),r=dc.test(t)||_c.test(t),n=mc.test(t)||Cc.test(t),s=fc.test(t)||Mc.test(t),a=pc.test(t)||Ac.test(t);return r?{primaryTask:"review",taskFamily:"review",actionability:"actionable",executionPattern:"checked-direct",shouldUseRepoSignals:!0,requiresRoutingHeuristics:!0,reason:"Review work is actionable and benefits from harness assessment for accurate scoping."}:n?{primaryTask:"plan",taskFamily:"planning",actionability:"actionable",executionPattern:"coordinated",shouldUseRepoSignals:!0,requiresRoutingHeuristics:!0,reason:"Planning and design requests may benefit from coordinated execution."}:s?{primaryTask:"bugfix",taskFamily:"investigation",actionability:"actionable",executionPattern:"checked-direct",shouldUseRepoSignals:!0,requiresRoutingHeuristics:!0,reason:"Debugging and root-cause work starts as investigation."}:a?{primaryTask:"edit",taskFamily:"implementation",actionability:"actionable",executionPattern:"checked-direct",shouldUseRepoSignals:!0,requiresRoutingHeuristics:!0,reason:"Implementation and editing work is actionable and may later escalate if the evidence warrants it."}:o?{primaryTask:"lookup",taskFamily:"lookup",actionability:"actionable",executionPattern:"direct",shouldUseRepoSignals:!1,requiresRoutingHeuristics:!0,reason:"Lookup queries are actionable but lightweight \u2014 direct execution unless deeper analysis is requested."}:{primaryTask:"unknown",taskFamily:"ambiguous",actionability:"ambiguous",executionPattern:"direct",shouldUseRepoSignals:!1,requiresRoutingHeuristics:!0,reason:"Ambiguous requests need classification before the work approach is locked in."}}i(go,"inferIntentGate");function kt(e){switch(e){case"conversation":return"conversation";case"lookup":case"qa":return"lookup";case"review":return"review";case"bugfix":return"investigation";case"plan":return"planning";case"edit":case"refactor":return"implementation";default:return"ambiguous"}}i(kt,"inferTaskFamilyFromPrimaryTask");function ni(e){switch(e){case"conversation":case"lookup":return"direct";case"review":case"investigation":return"checked-direct";case"planning":case"implementation":return"coordinated";default:return"direct"}}i(ni,"defaultExecutionPatternForFamily");function Lc(e,t){let o=go(e),r=t.taskFamily??kt(t.primaryTask),n=t.actionability??(r==="conversation"?"non_actionable":r==="ambiguous"?o.actionability:"actionable"),s=t.executionPattern??ni(r);return{taskFamily:r,actionability:n,executionPattern:s}}i(Lc,"deriveIntentFields");function ii(e,t){let o=` ${e.toLowerCase()} `,r=/[\u3400-\u9fff]/u.test(e),n=hc.test(e)||r&&Pc.test(e),s=gc.test(e)||r&&yc.test(e),a=Tc.test(e)||r&&bc.test(e),c=xc.test(e)||r&&vc.test(e),d=Rc.test(e)||r&&Oc.test(e),u=wc.test(o)||r&&zn.test(e),m=/\b(code|implementation|function|class|component|module|endpoint|service|bug|script|api|ui|backend|frontend)\b/i.test(o)||r&&zn.test(e),l=/\b(implement|add|modify|update|create|write|fix|refactor|rewrite|replace|edit|patch|rename)\b/i.test(o)||r&&Vn.test(e),p=r&&Nc.test(e),y=r&&Vn.test(e),w=/\b(monorepo|repo|repository|package|packages|architecture|migration)\b/i.test(o),_=/\b(refactor|rewrite|reorganize|migrate|split|merge|consolidate|rename)\b/i.test(o),f=/\b(code|implementation|function|class|component|module|endpoint|service|bug|script|api|ui|backend|frontend)\b/i.test(o)||p,U=/\b(implement|add|modify|update|create|write|fix|refactor|rewrite|replace|edit|patch|rename)\b/i.test(o)||y,R=f&&!s||a,O=w&&!s,h=n&&!d&&c;if(t.primaryTask==="review"&&!U&&!d)return n&&(h||!R)?"docs-only":"read-only";let N=t.primaryTask==="edit"||t.primaryTask==="refactor"||t.taskFamily==="implementation"||t.primaryTask==="bugfix"&&U||U&&R||_&&O;return h&&t.primaryTask!=="refactor"||n&&!d&&!R&&t.primaryTask!=="refactor"?"docs-only":d?"system":N?"code":"read-only"}i(ii,"deriveMutationSurface");function Fc(e,t){let o=/[\u3400-\u9fff]/u.test(e);return kc.test(e)||o&&Ic.test(e)||t.recommendedMode==="strict-audit"?"explicit-check":"default"}i(Fc,"deriveAssuranceIntent");function si(e){let t=` ${e.toLowerCase()} `,r=[...Object.entries(ic).map(([c,d])=>({task:c,score:cc(t,d)}))].sort((c,d)=>d.score-c.score),n=r[0],s=r[1];if(!n||n.score===0)return{task:"unknown",confidence:Da,reason:"Fallback task inference did not find enough strong signals, so it kept the task as unknown."};if(s&&n.score===s.score){let c=Uc(e,n.task,s.task);return c?{task:c,confidence:Gn,reason:`Fallback task inference preferred "${c}" because the request used an explicit directive even though multiple task signals were present.`}:{task:"unknown",confidence:La,reason:`Fallback task inference saw competing signals for "${n.task}" and "${s.task}", so it kept the task as unknown.`}}if(n.task==="qa"&&n.score<4)return{task:"unknown",confidence:Fa,reason:"Fallback task inference saw a weak explanation-style signal, but not enough evidence to disable reasoning."};let a=Math.min(Ha,Gn+n.score*Ua+Math.max(0,(n.score-(s?.score??0))*Ba));return{task:n.task,confidence:a,reason:`Fallback task inference selected "${n.task}" from textual signals in the request.`}}i(si,"inferTaskSignal");function Uc(e,t,o){let r=` ${e.toLowerCase()} `,n=C(r,"review")||C(r,"code review")||C(r,"merge blocker")||C(r,"\u5BA1\u67E5")||C(r,"\u8BC4\u5BA1"),s=C(r,"fix")||C(r,"bug")||C(r,"\u4FEE\u590D")||C(r,"\u62A5\u9519"),a=C(r,"plan")||C(r,"design")||C(r,"\u65B9\u6848")||C(r,"\u8BA1\u5212");return(t==="review"||o==="review")&&n&&!s?"review":(t==="bugfix"||o==="bugfix")&&s&&!n?"bugfix":(t==="plan"||o==="plan")&&a?"plan":null}i(Uc,"resolveTiedTask");function cf(e){return si(e).task}i(cf,"inferTaskType");function wt(e){switch(e){case"simple":return 0;case"moderate":return 1;case"complex":return 2;case"systemic":return 3;default:return 0}}i(wt,"complexityRank");function Bc(e,t){return t&&wt(t)>wt(e)?t:e}i(Bc,"maxComplexity");function Hc(e,t,o){let r=go(e);if(!r.requiresRoutingHeuristics){let a=r.primaryTask;return ei(e,{primaryTask:a,confidence:r.actionability==="non_actionable"?.98:.9,riskLevel:"low",recommendedMode:Zn(a),recommendedThinkingDepth:Qn(a),complexity:"simple",workIntent:"new",requiresBrainstorm:!1,harnessProfile:"H0_DIRECT",taskFamily:r.taskFamily,actionability:r.actionability,executionPattern:r.executionPattern,routingSource:"fallback",routingAttempts:1,reason:r.reason},t,o)}let n=si(e),s=n.task;return ei(e,{primaryTask:s,taskFamily:kt(s),actionability:s==="unknown"?"ambiguous":"actionable",executionPattern:ni(kt(s)),confidence:n.confidence,riskLevel:ui(e,s),recommendedMode:Zn(s),recommendedThinkingDepth:Qn(s),complexity:"moderate",workIntent:"new",requiresBrainstorm:!1,harnessProfile:"H0_DIRECT",routingSource:"fallback",routingAttempts:1,reason:n.reason},t,o)}i(Hc,"buildFallbackRoutingDecision");function ai(e){let t=e.primaryTask==="review"||e.primaryTask==="bugfix"||e.recommendedMode==="pr-review"||e.recommendedMode==="strict-audit"||e.recommendedMode==="investigation";return{harnessProfile:e.harnessProfile,evidenceHeavy:t,brainstorm:e.requiresBrainstorm,workIntent:e.workIntent}}i(ai,"buildProviderPolicyHintsForDecision");async function ci(e,t,o,r){let n=oi(e),s=go(t),a=vt({providerName:o.name,model:e.modelOverride??e.model,provider:o,prompt:t,options:e,reasoningMode:n}),c=Hc(t,a,r),d=e.effort??me(n),u=n==="off"?"off":n==="auto"?c.recommendedThinkingDepth:Za(n),m={...c,recommendedThinkingDepth:u,routingNotes:[...c.routingNotes??[],s.reason,"Heuristic routing only \u2014 LLM router skipped (FEATURE_061 Phase 1; FEATURE_193 retired post-routing calibration)."]};return{effort:d,promptOverlay:"",decision:m,providerPolicy:a}}i(ci,"createReasoningPlan");function li(e,t=.5){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):t}i(li,"clampUnitInterval");function $c(e,t){let o=` ${e.toLowerCase()} `;return Ka.some(r=>C(o,r))?"overwrite":Ga.some(r=>C(o,r))?"append":t}i($c,"inferWorkIntent");function jc(e,t){let o=` ${e.toLowerCase()} `,r=0;for(let n of po.moderate)C(o,n)&&(r+=1);for(let n of po.complex)C(o,n)&&(r+=2);for(let n of po.systemic)C(o,n)&&(r+=3);return(t.primaryTask==="refactor"||t.primaryTask==="plan")&&(r+=2),t.riskLevel==="high"&&(r+=2),t.workIntent==="overwrite"&&(r+=1),r>=za?"systemic":r>=Ya?"complex":r>=Xa?"moderate":"simple"}i(jc,"inferComplexity");function qc(e,t,o){let r=` ${e.toLowerCase()} `;return!!(Wa.some(n=>C(r,n))||t.primaryTask==="plan"||t.primaryTask==="unknown"&&t.confidence<.7||o==="systemic"||t.workIntent==="overwrite"&&(t.primaryTask==="refactor"||t.riskLevel==="high"))}i(qc,"inferRequiresBrainstorm");function Wc(e,t){let o=t.taskFamily??kt(t.primaryTask),r=ii(e,{primaryTask:t.primaryTask,taskFamily:o}),n=[];return(t.complexity==="complex"||t.complexity==="systemic")&&n.push(`Complexity hint: ${t.complexity}. Assess whether the recommended harness fits the task scope.`),t.needsIndependentQA&&n.push("Independent QA was inferred from prompt signals. Verify whether explicit verification artifacts are needed before declaring the task done."),t.requiresBrainstorm&&n.push("Brainstorm/planning signal detected. Judge whether to plan-first via todo_update before executing."),r==="system"&&(t.riskLevel==="high"||t.workIntent==="overwrite")&&n.push("High-risk system mutation detected. Proceed with caution; consider checkpointing intermediate state."),{harnessProfile:"H0_DIRECT",upgradeCeiling:"H0_DIRECT",notes:n}}i(Wc,"selectHarnessProfile");function Qn(e){switch(e){case"conversation":return"off";case"lookup":return"low";case"review":return"low";case"bugfix":case"edit":return"medium";case"refactor":case"plan":return"high";case"qa":return"off";default:return"medium"}}i(Qn,"getDefaultDepthForTask");function Zn(e){switch(e){case"conversation":return"conversation";case"lookup":return"lookup";case"review":return"pr-review";case"bugfix":return"investigation";case"plan":return"planning";default:return"implementation"}}i(Zn,"getExecutionModeForTask");function ui(e,t){let o=e.toLowerCase();return t==="conversation"||t==="lookup"?"low":o.includes("security")||o.includes("auth")||o.includes("migration")||o.includes("database")||o.includes("schema")||o.includes("production")||o.includes("\u5B89\u5168")||o.includes("\u9274\u6743")||o.includes("\u6743\u9650")||o.includes("\u8FC1\u79FB")||o.includes("\u6570\u636E\u5E93")||o.includes("\u751F\u4EA7")?"high":t==="review"||t==="bugfix"||t==="plan"?"medium":"low"}i(ui,"getRiskLevel");function Gc(e,t,o){let r=.9,n=` ${e.toLowerCase()} `;return t.primaryTask==="review"?(r-=.12,t.reviewScale==="large"?r-=.16:t.reviewScale==="massive"&&(r-=.28)):t.primaryTask==="bugfix"?r-=.08:t.primaryTask==="plan"&&(r-=.24),t.riskLevel==="medium"?r-=.12:t.riskLevel==="high"&&(r-=.26),t.complexity==="moderate"?r-=.12:t.complexity==="complex"?r-=.28:t.complexity==="systemic"&&(r-=.42),t.requiresBrainstorm&&(r-=.18),t.workIntent==="overwrite"&&(r-=.08),/\b(strict review|must[- ]fix|independently verify|browser test|playwright|e2e|frontend verify)\b/.test(n)&&(r-=.2),o&&(o.changedFileCount>=3&&(r-=.12),o.changedLineCount>=ho&&(r-=.14),o.changedLineCount>=ti&&(r-=.14),o.touchedModuleCount>=2&&(r-=.16),(o.impactedModuleCount??0)>=2&&(r-=.14),o.crossModule&&(r-=.2),o.lowConfidence&&(r-=.08)),li(r,.5)}i(Gc,"computeSoloBoundaryConfidence");function Kc(e,t,o){let r=` ${e.toLowerCase()} `;return!!(/\b(must[- ]fix|strict review|audit|independently verify|browser test|playwright|e2e|console errors?|api check|db check)\b/.test(r)||t.primaryTask==="plan"||t.primaryTask==="qa"||t.riskLevel==="high"||t.complexity==="complex"||t.complexity==="systemic"||t.requiresBrainstorm||o&&(o.crossModule||o.lowConfidence||(o.impactedModuleCount??0)>=2||o.touchedModuleCount>=2||o.changedLineCount>=ho))}i(Kc,"computeNeedsIndependentQA");function Xc(e,t,o,r){let n=e.recommendedMode,s=e.recommendedThinkingDepth,a=[];return r?(r.suggestedComplexity&&wt(r.suggestedComplexity)>wt(t)&&a.push(`Repository intelligence elevated task complexity to ${r.suggestedComplexity} (changedFiles=${r.changedFileCount}, touchedModules=${r.touchedModuleCount}, impactedModules=${r.impactedModuleCount??0}).`),r.crossModule&&a.push("Repository intelligence indicates cross-module impact; keep evidence and merge boundaries explicit."),r.lowConfidence&&a.push("Repository intelligence for the active area is low-confidence; re-query `module_context` / `symbol_context` (or `impact_estimate` for blast-radius questions) for a refined capsule before falling back to raw `read`/`grep`. Use direct file evidence only when a specific load-bearing claim needs byte-level verification."),r.investigationBias&&(e.primaryTask==="review"||e.primaryTask==="bugfix")&&n!=="investigation"?(n="investigation",(s==="off"||s==="low")&&(s="medium"),a.push("Repository intelligence shifted execution toward investigation because the active area is low-confidence or high-blast-radius.")):r.plannerBias&&e.primaryTask!=="review"&&e.primaryTask!=="bugfix"&&n==="implementation"&&(o==="complex"||o==="systemic")&&(n="planning",(s==="off"||s==="low")&&(s="medium"),a.push("Repository intelligence shifted execution toward planning because the task spans multiple modules or dependencies.")),{recommendedMode:n,recommendedThinkingDepth:s,repoNotes:a}):{recommendedMode:n,recommendedThinkingDepth:s,repoNotes:a}}i(Xc,"applyRepoSignalsToDecision");function Jn(e,t){let o=t.exec(e);if(!o?.[1])return;let r=o[1].replace(/,/g,"").toLowerCase(),n=r.endsWith("k")?1e3:1,s=r.endsWith("k")?r.slice(0,-1):r,a=Number.parseFloat(s);if(!(!Number.isFinite(a)||a<=0))return Math.round(a*n)}i(Jn,"parsePromptInteger");function Yc(e){let t=Jn(e,/(?:^|[\s(,])(\d[\d,]*(?:\.\d+)?k?)\s*(?:changed\s+)?files?\b/i),o=Jn(e,/(?:^|[\s(,])(\d[\d,]*(?:\.\d+)?k?)\s*(?:changed\s+)?lines?\b/i),r;return(t??0)>=Qa||(o??0)>=ti?r="massive":((t??0)>=Va||(o??0)>=ho)&&(r="large"),{changedFileCount:t,changedLineCount:o,reviewScale:r}}i(Yc,"inferPromptReviewScale");function zc(e,t){return e?.reviewScale?e.reviewScale:Yc(t??"").reviewScale}i(zc,"deriveReviewScaleFromSignals");function ei(e,t,o,r){let n=t,s=Lc(e,t),a=s.actionability==="actionable"&&s.taskFamily!=="conversation"&&s.taskFamily!=="lookup";t.primaryTask==="unknown"&&s.taskFamily==="ambiguous"&&(n={...t,recommendedMode:"implementation",recommendedThinkingDepth:"medium",reason:`${t.reason} Conservative fallback keeps balanced reasoning for ambiguous tasks.`}),n.primaryTask==="qa"&&n.confidence<$a&&(n={...n,primaryTask:"unknown",confidence:Math.min(n.confidence,ja),riskLevel:ui(e,"unknown"),recommendedMode:"implementation",recommendedThinkingDepth:"medium",reason:`${n.reason} Low-confidence QA routing was downgraded to unknown so reasoning stays available.`}),n.confidence<qa&&n.recommendedThinkingDepth==="off"&&(n={...n,primaryTask:"unknown",recommendedMode:"implementation",recommendedThinkingDepth:"medium",reason:`${n.reason} Low-confidence off-mode routing was upgraded to balanced reasoning for safety.`});let c=$c(e,n.workIntent),d=a?r?.repoSignals:void 0,u=jc(e,{...n,workIntent:c}),m=a?Bc(u,d?.suggestedComplexity):u,l=t.reviewScale??zc(d,e),p=ii(e,{primaryTask:n.primaryTask,taskFamily:s.taskFamily}),y=Fc(e,n),w="H0_DIRECT",_=qc(e,{...n,workIntent:c,complexity:m,reviewScale:l,mutationSurface:p,assuranceIntent:y,topologyCeiling:w},m)||!!(d?.plannerBias&&(m==="complex"||m==="systemic")),f=li(t.soloBoundaryConfidence??Gc(e,{primaryTask:n.primaryTask,complexity:m,riskLevel:n.riskLevel,requiresBrainstorm:_,workIntent:c,reviewScale:l},d),.5),U=t.needsIndependentQA??Kc(e,{primaryTask:n.primaryTask,complexity:m,riskLevel:n.riskLevel,requiresBrainstorm:_,reviewScale:l},d),R=p==="read-only"||p==="docs-only"?y==="explicit-check":U,O=Wc(e,{...n,workIntent:c,complexity:m,requiresBrainstorm:_,reviewScale:l,soloBoundaryConfidence:f,needsIndependentQA:R,mutationSurface:p,assuranceIntent:y,topologyCeiling:w}),{recommendedMode:h,recommendedThinkingDepth:N,repoNotes:ae}=Xc({...n,taskFamily:s.taskFamily,actionability:s.actionability,executionPattern:s.executionPattern},u,m,d),B=h,A=N,D="direct";return s.taskFamily==="conversation"?(B="conversation",A="off"):s.taskFamily==="lookup"&&(B="lookup",A=N==="high"?"medium":N),{...n,taskFamily:s.taskFamily,actionability:s.actionability,executionPattern:D,mutationSurface:p,assuranceIntent:y,recommendedMode:B,recommendedThinkingDepth:A,workIntent:c,complexity:m,requiresBrainstorm:_,topologyCeiling:w,reviewScale:l,soloBoundaryConfidence:f,needsIndependentQA:R,harnessProfile:O.harnessProfile,upgradeCeiling:O.upgradeCeiling,routingSource:n.routingSource??"fallback",routingAttempts:n.routingAttempts??1,routingNotes:[...n.routingNotes??[],...O.notes,...ae,...a?[]:["Intent gate ignored repository scaling signals for this request."]]}}i(ei,"stabilizeRoutingDecision");function Rt(e,t){return Buffer.byteLength(JSON.stringify({systemPrompt:t,messages:e}),"utf8")}i(Rt,"estimateProviderPayloadBytes");function Et(e){return e<16*1024?"small":e<64*1024?"medium":e<192*1024?"large":"xlarge"}i(Et,"bucketProviderPayloadSize");function Ge(e){let t=hr.exec(e);return t?[t[1].toUpperCase(),t[2]??""]:["",""]}i(Ge,"checkPromiseSignal");function Vc(){return process.env.KODAX_DEBUG_STREAM==="1"||process.env.KODAX_DEBUG_RESILIENCE==="1"}i(Vc,"shouldDebugResilience");function I(e,t){Vc()&&E({source:"coding:resilience",level:"debug",message:e,detail:t})}i(I,"emitResilienceDebug");function di(e,t,o){let r=e.modelSelection.provider??t.provider,n=e.modelSelection.model??t.modelOverride??t.model,s=e.thinkingLevel,a=we(r);if(!a.isConfigured())throw new Error(`Provider "${r}" not configured. Set ${a.getApiKeyEnv()}`);let c=Nr(o,a,n);return{providerName:r,modelOverride:n,thinkingLevel:s,provider:a,contextWindow:c}}i(di,"resolvePerTurnProvider");function yo(e,t){if(!e.isConfigured())throw new Error(`Provider "${t}" not configured. Set ${e.getApiKeyEnv()}`)}i(yo,"assertProviderConfigured");var To=`You are KodaX, a helpful multi-provider coding agent. You can read, write, and edit files, and execute shell commands.
|
|
4
|
+
|
|
5
|
+
## Error Handling
|
|
6
|
+
|
|
7
|
+
When a tool call returns an error:
|
|
8
|
+
1. STOP and READ the error message carefully
|
|
9
|
+
2. DO NOT repeat the same tool call with the same parameters \u2014 a re-issue with identical params almost always lands in a retry loop that wastes tokens without producing new information. Vary the params or switch to a different tool
|
|
10
|
+
3. Identify what's wrong (missing parameter? wrong type? wrong path?)
|
|
11
|
+
4. Fix the issue BEFORE making another tool call
|
|
12
|
+
5. Common errors:
|
|
13
|
+
- "Missing required parameter 'X'" -> Add the missing parameter to your JSON
|
|
14
|
+
- "File not found" -> Check the path with read or glob first
|
|
15
|
+
- "String not found" -> Read the file again to see exact content
|
|
16
|
+
|
|
17
|
+
When a shell command fails, prefer this recovery order:
|
|
18
|
+
1. Check whether a specialized tool can solve the task directly
|
|
19
|
+
2. Fix the command itself (quoting, workdir, platform-specific command, smaller scope)
|
|
20
|
+
3. Split the task into smaller read/edit/write steps
|
|
21
|
+
4. Only create a helper script when repeated inline commands are clearly less safe or less maintainable
|
|
22
|
+
|
|
23
|
+
## Editing Files
|
|
24
|
+
|
|
25
|
+
- Always read the file first to understand its current content
|
|
26
|
+
- Make precise, targeted edits rather than rewriting entire files
|
|
27
|
+
- Preserve the existing code style and formatting
|
|
28
|
+
- Do not create new files unless the user asks for one or the task genuinely needs one. Prefer editing an existing file to creating a new one, as this prevents file bloat and keeps each tool call small
|
|
29
|
+
- When a modification is scoped to an existing file, ALWAYS prefer \`edit\` over \`write\`. Only fall back to \`write\` when no file exists yet or the user explicitly requested a complete rewrite
|
|
30
|
+
|
|
31
|
+
## Tool Usage
|
|
32
|
+
|
|
33
|
+
Prefer specialized tools over shell for file operations:
|
|
34
|
+
- Use read to view files instead of cat, head, or tail
|
|
35
|
+
- Use edit to modify existing files instead of sed or awk when possible
|
|
36
|
+
- Use write to create new files instead of echo redirection or heredocs
|
|
37
|
+
- Use glob or grep for file discovery and content search before falling back to shell
|
|
38
|
+
- When multiple read-only tool calls are independent, emit them in the same response so parallel mode can run them together
|
|
39
|
+
- Only serialize tool calls when a later call depends on an earlier result
|
|
40
|
+
- Keep parallel batches focused: prefer a few narrow grep/read/diff calls over many tiny sequential probes
|
|
41
|
+
|
|
42
|
+
Read is intentionally bounded:
|
|
43
|
+
- A single read call only returns a limited slice of a file
|
|
44
|
+
- For large files, continue with offset/limit instead of retrying a whole-file read
|
|
45
|
+
- Prefer grep first, then read the specific section you need
|
|
46
|
+
|
|
47
|
+
Tool outputs are also bounded:
|
|
48
|
+
- Large bash output may be truncated to the tail
|
|
49
|
+
- Large grep results and diffs may be summarized
|
|
50
|
+
- When you see a truncation hint, narrow the next tool call instead of repeating the same broad request
|
|
51
|
+
- If edit fails to find a stable anchor, do not rewrite the entire existing file with write; retry with a smaller unique edit anchor or use insert_after_anchor for section appends
|
|
52
|
+
|
|
53
|
+
If you truly need a script:
|
|
54
|
+
- Do NOT create temporary scripts or scratch files in the project root \u2014 they leak into \`git status\` and file listings, confusing the user about what was actually changed
|
|
55
|
+
- Do NOT place them at \`.agent/\` top level \u2014 that directory is reserved for system-managed artifacts (managed-tasks/, project/, repo-intelligence/, etc.)
|
|
56
|
+
- Write them to the Session Scratch Directory when one is shown in the environment
|
|
57
|
+
- If no Session Scratch Directory is shown, write them under a unique session-scoped subdirectory of \`.agent/tmp/sessions/\` (relative to the git root), not directly in the shared \`.agent/tmp/\` root
|
|
58
|
+
- Alternatively, use the system temp directory if the script does not need to be inspectable from the project
|
|
59
|
+
- Treat helper scripts as a last resort, not the default recovery path
|
|
60
|
+
|
|
61
|
+
## Shell Commands
|
|
62
|
+
|
|
63
|
+
- Be careful with destructive operations
|
|
64
|
+
- Reserve shell commands for terminal operations such as git, package managers, builds, tests, and system commands
|
|
65
|
+
- Prefer read-only operations when possible
|
|
66
|
+
- For file edits, prefer read/edit/write over shell transforms unless shell scripting is genuinely more efficient
|
|
67
|
+
|
|
68
|
+
### Cross-Platform Notes
|
|
69
|
+
|
|
70
|
+
Different platforms have different commands:
|
|
71
|
+
- Move: \`move\` (Windows) vs \`mv\` (Unix/Mac)
|
|
72
|
+
- List: \`dir\` (Windows) vs \`ls\` (Unix/Mac)
|
|
73
|
+
- Delete: \`del\` (Windows) vs \`rm\` (Unix/Mac)
|
|
74
|
+
|
|
75
|
+
**IMPORTANT: Directories are created automatically by the \`write\` tool.**
|
|
76
|
+
- NEVER use \`mkdir\` before writing files - the write tool handles directory creation
|
|
77
|
+
- If you truly need an empty directory: \`mkdir dir\` (Windows) or \`mkdir -p dir\` (Unix)
|
|
78
|
+
|
|
79
|
+
If you see "not recognized", "\u4E0D\u662F\u5185\u90E8\u6216\u5916\u90E8\u547D\u4EE4", or a similar shell lookup error, the command does not exist on this platform. Try the platform equivalent.
|
|
80
|
+
|
|
81
|
+
## Multi-step Tasks
|
|
82
|
+
|
|
83
|
+
- Track your progress by listing what you've done and what's next
|
|
84
|
+
- Break complex tasks into smaller steps
|
|
85
|
+
- Summarize progress periodically
|
|
86
|
+
|
|
87
|
+
## Plan Before Action
|
|
88
|
+
|
|
89
|
+
For any non-trivial task (creating files, editing code, running complex commands):
|
|
90
|
+
1. First explain your understanding of the task
|
|
91
|
+
2. Outline your approach (what files, what changes, what order)
|
|
92
|
+
3. Consider potential issues (edge cases, dependencies, conflicts)
|
|
93
|
+
4. Then execute step by step
|
|
94
|
+
|
|
95
|
+
For simple read-only tasks (reading a file, listing directory), just do it directly.
|
|
96
|
+
|
|
97
|
+
If the environment is currently in a read-only planning mode:
|
|
98
|
+
- Do not try to write files or run mutating shell commands during planning
|
|
99
|
+
- Finish the plan first
|
|
100
|
+
- After the plan is complete, use \`ask_user_question\` to ask whether the user wants to proceed with implementation
|
|
101
|
+
- If the user confirms, call \`set_permission_mode\` with \`mode: "accept-edits"\` to switch to implementation mode
|
|
102
|
+
- If the user declines, stay in plan mode \u2014 do NOT call \`set_permission_mode\`
|
|
103
|
+
|
|
104
|
+
## Asking User Questions
|
|
105
|
+
|
|
106
|
+
When you need the user to make decisions, use \`ask_user_question\`.
|
|
107
|
+
- For **multiple independent questions**, use the \`questions\` array (the schema accepts up to 4 items per call \u2014 if you need more, ask the additional ones in a follow-up turn). Each question has its own \`question\`, \`header\`, \`options\`, and optional \`multi_select\`. The user answers each question separately. Do NOT combine multiple questions into a single question string with pre-combined option combinations, because that forces the user to mentally disambiguate combinations and breaks the option-button UI.
|
|
108
|
+
- For a **single question**, use the \`question\` + \`options\` fields as before.
|
|
109
|
+
- For **free-text input**, use \`kind: "input"\`.
|
|
110
|
+
|
|
111
|
+
Always explain what you're doing before taking action.
|
|
112
|
+
|
|
113
|
+
{context}`;import El from"path";import{createHash as Qc}from"crypto";var mi={base:100,"runtime-context":200,"session-context":300,"capability-truth":400,"base-suffix":450,"mode-overlay":500,"project-rules":600,"skill-addendum":700,specialist:800},fi={"base-system":{id:"base-system",title:"Base System Prompt",owner:"prompts",feature:"FEATURE_048",slot:"base",order:100,stability:"stable"},"base-system-suffix":{id:"base-system-suffix",title:"Base System Prompt Suffix",owner:"prompts",feature:"FEATURE_048",slot:"base-suffix",order:200,stability:"stable"},"environment-context":{id:"environment-context",title:"Environment Context",owner:"prompts",feature:"FEATURE_048",slot:"runtime-context",order:100,stability:"dynamic"},"runtime-fact":{id:"runtime-fact",title:"Runtime Fact",owner:"prompts",feature:"FEATURE_048",slot:"runtime-context",order:150,stability:"dynamic"},"working-directory":{id:"working-directory",title:"Working Directory",owner:"prompts",feature:"FEATURE_048",slot:"runtime-context",order:200,stability:"dynamic"},"session-scratch-directory":{id:"session-scratch-directory",title:"Session Scratch Directory",owner:"prompts",feature:"FEATURE_071",slot:"runtime-context",order:250,stability:"dynamic"},"git-context":{id:"git-context",title:"Git Context",owner:"prompts",feature:"FEATURE_048",slot:"session-context",order:100,stability:"dynamic"},"project-snapshot":{id:"project-snapshot",title:"Project Snapshot",owner:"prompts",feature:"FEATURE_048",slot:"session-context",order:200,stability:"dynamic"},"long-running-context":{id:"long-running-context",title:"Long-Running Context",owner:"prompts",feature:"FEATURE_048",slot:"session-context",order:300,stability:"dynamic"},"repo-intelligence-context":{id:"repo-intelligence-context",title:"Repository Intelligence Context",owner:"reasoning",feature:"FEATURE_048",slot:"capability-truth",order:100,stability:"dynamic"},"mcp-capability-context":{id:"mcp-capability-context",title:"MCP Capability Context",owner:"reasoning",feature:"FEATURE_035",slot:"capability-truth",order:200,stability:"dynamic"},"specialist-agents":{id:"specialist-agents",title:"Specialist Agents",owner:"agent",feature:"FEATURE_191",slot:"capability-truth",order:300,stability:"dynamic"},"self-knowledge-routing":{id:"self-knowledge-routing",title:"KodaX Self-Knowledge",owner:"prompts",feature:"FEATURE_218",slot:"capability-truth",order:350,stability:"stable"},"execution-guidance":{id:"execution-guidance",title:"Execution Guidance",owner:"prompts",feature:"FEATURE_048",slot:"capability-truth",order:360,stability:"stable"},"long-running-overlay":{id:"long-running-overlay",title:"Long-Running Overlay",owner:"prompts",feature:"FEATURE_048",slot:"mode-overlay",order:100,stability:"dynamic"},"prompt-overlay":{id:"prompt-overlay",title:"Prompt Overlay",owner:"reasoning",feature:"FEATURE_048",slot:"mode-overlay",order:200,stability:"dynamic"},"project-agents":{id:"project-agents",title:"Project Rules",owner:"project",feature:"FEATURE_048",slot:"project-rules",order:100,stability:"project"},"memory-rules":{id:"memory-rules",title:"Memory Rules",owner:"project",feature:"FEATURE_124",slot:"project-rules",order:150,stability:"project"},"project-memory":{id:"project-memory",title:"Persistent Memory Index",owner:"project",feature:"FEATURE_124",slot:"project-rules",order:200,stability:"project"},"skills-addendum":{id:"skills-addendum",title:"Skills Addendum",owner:"skills",feature:"FEATURE_048",slot:"skill-addendum",order:100,stability:"dynamic"},"tool-construction":{id:"tool-construction",title:"Tool Construction Mode",owner:"agent",feature:"FEATURE_087",slot:"specialist",order:100,stability:"specialist"}};function S(e,t,o){let r=fi[e];if(!r)throw new Error(`Unknown prompt section: ${e}`);return{...r,inclusionReason:o,content:t.trim()}}i(S,"createPromptSection");function bo(e){return[...e].sort((t,o)=>{let r=mi[t.slot]-mi[o.slot];return r!==0?r:t.order-o.order})}i(bo,"orderPromptSections");function pi(e){return bo(e).map(t=>t.content.trim()).filter(Boolean).join(`
|
|
114
|
+
|
|
115
|
+
`).trim()}i(pi,"renderPromptSections");function xo(e,t){let o=bo(e),r=pi(o),n=Qc("sha256").update(JSON.stringify({kind:"system",metadata:t,sections:o.map(s=>({id:s.id,title:s.title,slot:s.slot,order:s.order,owner:s.owner,feature:s.feature,stability:s.stability,inclusionReason:s.inclusionReason,content:s.content}))})).digest("hex");return{kind:"system",sections:o,rendered:r,hash:n,metadata:t}}i(xo,"buildPromptSnapshot");import Ct from"node:path";import{exec as pl}from"node:child_process";import{promisify as hl}from"node:util";import*as hi from"node:path";function gi(e){let t=st(e);return Zc(t).join(`
|
|
116
|
+
`)}i(gi,"buildMemoryRulesSection");function Zc(e){return["# Memory (per-project)","",`You have a persistent, file-based memory system at \`${e.split(hi.sep).join("/")}\`. The directory is created on first write \u2014 you may write to it directly with the Write tool (do not run mkdir or check for its existence first).`,"","You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they would like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.","","If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.","",...Jc,"",...el,"",...tl,"",...ol,"",...rl,"",...nl]}i(Zc,"MEMORY_RULES_LINES");var Jc=["## Types of memory","","There are several discrete types of memory that you can store in your memory system:","","<types>","<type>"," <name>user</name>"," <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>"," <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>"," <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>"," <examples>"," user: I'm a data scientist investigating what logging we have in place"," assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]",""," user: I've been writing Go for ten years but this is my first time touching the React side of this repo"," assistant: [saves user memory: deep Go expertise, new to React and this project's frontend \u2014 frame frontend explanations in terms of backend analogues]"," </examples>","</type>","<type>"," <name>feedback</name>"," <description>Guidance the user has given you about how to approach work \u2014 both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>",` <when_to_save>Any time the user corrects your approach ("no not that", "don't", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter \u2014 watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>`," <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>"," <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave \u2014 often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>"," <examples>"," user: don't mock the database in these tests \u2014 we got burned last quarter when mocked tests passed but the prod migration failed"," assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]",""," user: stop summarizing what you just did at the end of every response, I can read the diff"," assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]",""," user: yeah the single bundled PR was the right call here, splitting this one would've just been churn"," assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach \u2014 a validated judgment call, not a correction]"," </examples>","</type>","<type>"," <name>project</name>"," <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>",' <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" \u2192 "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>'," <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>"," <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation \u2014 often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>"," <examples>"," user: we're freezing all non-critical merges after Thursday \u2014 mobile team is cutting a release branch"," assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]",""," user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements"," assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup \u2014 scope decisions should favor compliance over ergonomics]"," </examples>","</type>","<type>"," <name>reference</name>"," <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>"," <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>"," <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>"," <examples>",` user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs`,' assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]',""," user: the Grafana board at grafana.internal/d/api-latency is what oncall watches \u2014 if you're touching request handling, that's the thing that'll page someone"," assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard \u2014 check it when editing request-path code]"," </examples>","</type>","</types>"],el=["## What NOT to save in memory","","- Code patterns, conventions, architecture, file paths, or project structure \u2014 these can be derived by reading the current project state.","- Git history, recent changes, or who-changed-what \u2014 `git log` / `git blame` are authoritative.","- Debugging solutions or fix recipes \u2014 the fix is in the code; the commit message has the context.","- Anything already documented in `AGENTS.md` or `CLAUDE.md` files in the repo.","- Ephemeral task details: in-progress work, temporary state, current conversation context.","","These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it \u2014 that is the part worth keeping."],tl=["## How to save memories","","Saving a memory is a two-step process:","","**Step 1** \u2014 write the memory to its own file (e.g., `user_role.md`, `feedback_no_mock_db.md`, `project_q2.md`, `reference_grafana.md`) using this frontmatter format:","","```markdown","---","name: {{short title shown in the MEMORY.md index}}","description: {{one-line description \u2014 used to decide relevance in future conversations, so be specific}}","type: {{user, feedback, project, reference}}","---","","{{memory content \u2014 for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}","```","","**Step 2** \u2014 Edit `MEMORY.md` to prepend a one-line entry AT THE TOP of the file:","","`- [<title>](<filename>.md) \u2014 <one-line hook under ~150 chars>`","","`MEMORY.md` is an index, not a memory file. Each entry must be one line. Never write the memory body directly into `MEMORY.md`. The full body lives in the topic file; the index entry is what is loaded into your conversation context.","","Prepending to the top creates a natural-LRU index ordering: recent memories stay visible while older entries sink. The index is capped at 200 lines / 25 KB \u2014 entries below the cap are silently truncated from the context that future sessions see, so keep the index concise.","","## GC responsibilities","","Memory does not auto-expire. You are responsible for keeping it tidy:","","- **Before writing**, check whether an existing memory already covers the topic. If yes, `Edit` it instead of creating a duplicate. Use `Grep` over the memory directory to find existing entries by keyword.","- **Update or remove memories that turn out to be wrong or outdated**:"," - To update: `Edit <file>` and rewrite the body. Update the MEMORY.md index line if the description changed."," - To remove: `Bash rm <file>` then `Edit MEMORY.md` to delete the index line.","- **Stale memory encountered during use** \u2192 do not work around it. Update or delete it on the spot.","","- Keep the `name`, `description`, and `type` fields up to date with the body.","- Organize memory semantically by topic, not chronologically. Two memories about the same topic should be merged into one file."],ol=["## When to access memories","- When memories seem relevant, or the user references prior-conversation work.","- You MUST access memory when the user explicitly asks you to check, recall, or remember.","- If the user says to *ignore* or *not use* memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.","- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now \u2014 and update or remove the stale memory rather than acting on it."],rl=["## Before recommending from memory","","A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:","","- If the memory names a file path: check the file exists.","- If the memory names a function or flag: grep for it.","- If the user is about to act on your recommendation (not just asking about history), verify first.","",'"The memory says X exists" is not the same as "X exists now."',"","A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot."],nl=["## Memory and other forms of persistence","","Memory is one of several persistence mechanisms available to you. The distinction is that memory can be recalled in future conversations, so it should not be used for persisting information that is only useful within the scope of the current conversation.","","- **Plans / todos** instead of memory: when breaking down work into discrete steps for the CURRENT task, use `todo_create` / `todo_update`. Tasks completed in this conversation are not memory-worthy unless they revealed something surprising.","- **AGENTS.md / CLAUDE.md** instead of memory: code conventions, architecture decisions, project-permanent rules go to `<repo>/AGENTS.md` (user-maintained). If the user states a permanent project rule, suggest they add it to `AGENTS.md` instead of saving to memory.","- **Git commits** instead of memory: who changed what, when, and why is in `git log` / `git blame` / commit messages. Memory should not duplicate that record."];import*as ie from"node:fs";import*as _t from"node:path";var vo=60,ko=8e3,St=new Map;function il(e){let t;try{t=ie.statSync(e).mtimeMs}catch{St.delete(e);return}let o=St.get(e);if(o&&o.mtimeMs===t)return o.content;try{let r=ie.readFileSync(e,"utf-8");return St.set(e,{mtimeMs:t,content:r}),r}catch{St.delete(e);return}}i(il,"readEntrypointWithCache");function Ti(e){let t=st(e),o=kr(e),r=il(o),n=r!==void 0;return{content:n?sl(t,r):ll(t),memoryDir:t,entrypointExists:n}}i(Ti,"buildMemorySection");function sl(e,t){let o=al(t),r=ul(e);return["=== Persistent memory (cross-session) ===",`Memory directory: ${e}`,"",o.content,...o.warning===void 0?[]:["",o.warning],...r,"","[Bounded index only - read individual files via the read tool when you need details. See memory rules section above.]"].join(`
|
|
117
|
+
`)}i(sl,"buildBodyWithEntrypoint");function al(e){let t=e.trimEnd(),o=t.length===0?[]:t.split(/\r?\n/),r=o.length,n=Buffer.byteLength(t,"utf8"),s=t,a=!1;return r>vo&&(s=o.slice(0,vo).join(`
|
|
118
|
+
`),a=!0),Buffer.byteLength(s,"utf8")>ko&&(s=cl(s,ko),a=!0),a?{content:s,warning:[`> NOTE: MEMORY.md has ${r} lines / ${yi(n)}.`,`Only a bounded ${vo}-line / ${yi(ko)} index preview is loaded here.`,"Read relevant topic files on demand instead of relying on the prompt to carry every memory."].join(" ")}:{content:s}}i(al,"truncatePromptMemoryIndex");function cl(e,t){let o=0,r=[];for(let a of e){let c=Buffer.byteLength(a,"utf8");if(o+c>t)break;r.push(a),o+=c}let n=r.join(""),s=n.lastIndexOf(`
|
|
119
|
+
`);return(s>0?n.slice(0,s):n).trimEnd()}i(cl,"sliceUtf8ToByteCap");function yi(e){return e<1024?`${e}B`:`${(e/1024).toFixed(1)}KB`}i(yi,"formatBytes");function ll(e){return["=== Persistent memory (cross-session) ===",`Memory directory: ${e}`,"","Your MEMORY.md is currently empty. When you save new memories, they will appear here."].join(`
|
|
120
|
+
`)}i(ll,"buildEmptyFallback");function ul(e){let t=[...dl(e)].sort((o,r)=>r.mtimeMs-o.mtimeMs).slice(0,8);return t.length===0?[]:["","Governed memory hints (deterministic):",...t.map(o=>`- ${o.title}: ${o.hook} (${o.filename})`)]}i(ul,"buildMemoryHintLines");function dl(e){let t;try{t=ie.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let r of t){if(!r.isFile()||r.name==="MEMORY.md"||!r.name.endsWith(".md"))continue;let n=ml(_t.join(e,r.name),r.name);n!==void 0&&o.push(n)}return o}i(dl,"readMemoryHintEntries");function ml(e,t){let o,r;try{o=ie.readFileSync(e,"utf-8"),r=ie.statSync(e).mtimeMs}catch{return}let n=wr(o),s=n.frontmatter.name??_t.basename(t,".md"),a=n.frontmatter.description??fl(n.body)??s;return{filename:t,title:s,hook:a,mtimeMs:r}}i(ml,"readMemoryHintEntry");function fl(e){let t=e.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0);return t===void 0?void 0:t.slice(0,160)}i(fl,"firstBodyLine");function wo(e="KodaX"){let t=e==="KodaX"?[`Claude Code and Codex CLI knowledge that does not match ${e} \u2014 ${e} uses`,"~/.kodax/config.json and KODAX_* env vars, not .claude/settings.json or","config.toml. Only bring up Claude Code or Codex when the user explicitly asks"]:[`Claude Code and Codex CLI knowledge that does not match ${e}.`,"Only bring up Claude Code or Codex when the user explicitly asks"];return[`${e} self-knowledge: when the user asks how to use, install, configure,`,`troubleshoot, or extend ${e} itself \u2014 providers, custom providers, config,`,"permissions, slash commands, tools, custom agents, skills, extensions, MCP, repo","intelligence, sessions, the doctor command, or the SDK \u2014 call the","kodax_manual tool first and answer from it.","",`Treat kodax_manual as the version-bound source of truth for ${e} product`,"behavior. Do not answer these from pretraining, because pretraining mixes in",...t,"to compare. Project AGENTS.md still governs work in the current repo; the",`manual governs questions about ${e} as a product.`].join(`
|
|
121
|
+
`)}i(wo,"buildSelfKnowledgeRoutingRule");var Df=wo();var bi=["EXECUTION GUIDANCE (match your approach to the kind of work \u2014 judge which fits):","- Respond in the primary natural language of the user's request for your user-visible explanations, progress notes, and final answer \u2014 if the user wrote in Chinese, reply in Chinese. Code, identifiers, file paths, tool output, and quoted evidence stay in their source language.","- After you make a change, check the result against what was actually asked before you finalize. Confirm the change does what the request wanted, backed by evidence (a test run, a re-read of the edited region) rather than confidence alone \u2014 because a change that looks right but was never verified is how silent regressions ship.","- When you are reviewing code or a pull request: report only high-confidence issues that materially affect correctness, reliability, security, or merge-readiness. Do not list naming, formatting, or style preferences as findings \u2014 padding a review with nits buries the issues that matter. Lead with the must-fix items, then optional improvements, and for each issue state the concrete consequence it causes.","- When you are doing a broad audit: cover correctness, security, performance, and maintainability together, and keep issues you have confirmed separate from lower-confidence risks so the reader can tell which is which.","- When you are investigating a bug or an unknown: isolate the root cause and validate your assumptions with concrete evidence \u2014 a reproduction, a targeted check \u2014 before making broad changes, because a fix applied before the cause is understood usually treats a symptom.","- When the task is design or planning work: reason through architecture, constraints, sequencing, and risks before writing code.","- When the request is genuinely ambiguous: frame the options briefly and make the path you chose explicit before any irreversible edit, so the user can redirect before the cost is sunk."].join(`
|
|
122
|
+
`);var xi="[Tool Construction Mode]\nYou may build a new tool at runtime when an existing builtin or extension does not solve the user's task and a thin reusable handler would. Walk the five-step staircase in order \u2014 DO NOT skip steps:\n\n 1. scaffold_tool \u2014 emit a fillable artifact JSON skeleton for {name, version, description}.\n 2. (edit the JSON) \u2014 fill in inputSchema, capabilities.tools (whitelist of builtins the handler may call via ctx.tools.<name>), and the handler.code body.\n 3. validate_tool \u2014 dry-run shape + AST + provider-schema checks on the candidate JSON. Fix any errors before staging.\n 4. stage_construction \u2014 persist to .kodax/constructed/tools/<name>/<version>.json (status=staged).\n 5. test_tool \u2014 run the full check pipeline against the staged artifact (shape + AST + schema + handler materialize).\n 6. activate_tool \u2014 register the handler into the live tool registry. The tool is then callable as <name> in subsequent turns.\n\nHard rules the AST stage enforces (failing any of these aborts the staircase):\n - No `eval`, no `new Function(...)`. Constructed handlers are not allowed to evaluate dynamic source.\n - The handler MUST export an `async function handler(input, ctx)` (function decl, arrow, or function expression with at least 2 parameters).\n\nCapability rule: the handler can ONLY invoke tools listed in `capabilities.tools` through `ctx.tools.<name>(...)`. Calls to undeclared tools throw at runtime. Direct `require`, `import()`, `process.env`, network access, and filesystem APIs are not provided \u2014 route all I/O through declared builtin tools (`read` / `write` / `bash` / `grep` / etc.).\n\nVersioning: re-staging an active version is rejected. Bump the semver string when iterating; revoke first if the user wants to replace an in-use handler at the same version. The on-disk artifact is the source of truth \u2014 there is no in-memory cache.";function vi(e){return!!e}i(vi,"shouldIncludeToolConstructionSection");var Ro=hl(pl),Eo="{context}";async function So(e,t,o){let r=o??j(e.context),n=[],{prefix:s,suffix:a}=xl(To);n.push(S("base-system",s,"Always include the stable base identity and safety baseline.")),a&&n.push(S("base-system-suffix",a,"Preserve any trailing stable base prompt instructions that follow the context placeholder.")),n.push(S("environment-context",vl(),"Always disclose runtime platform details so shell guidance stays accurate."));let c=kl(e);c&&n.push(S("runtime-fact",c,"Always disclose the active provider and model so identity questions can be answered truthfully instead of guessed from pretraining.")),n.push(S("working-directory",`Working Directory: ${r}`,"Always disclose the resolved execution directory for deterministic file operations."));let d=hn(e);if(d&&n.push(S("session-scratch-directory",`Session Scratch Directory: ${d}`,"Disclose the per-session scratch directory so temporary helper files never collide across same-directory sessions.")),t){let _=await wl(r);_&&n.push(S("git-context",_,"Include repository state when the session starts so the agent can orient itself quickly."));let f=await Rl(r);f&&n.push(S("project-snapshot",f,"Include a lightweight project snapshot at the start of a session."))}e.context?.repoIntelligenceContext?.trim()&&n.push(S("repo-intelligence-context",e.context.repoIntelligenceContext,"Include repository-intelligence capability truth only when it is active for this runtime."));let u=await e.extensionRuntime?.getCapabilityPromptContext("mcp");u?.trim()&&n.push(S("mcp-capability-context",u,"Include runtime-owned MCP capability truth only when active MCP servers are configured."));let m=bl(e.context?.agentScope);m&&n.push(S("specialist-agents",m,"List registered specialist agents the Worker can dispatch via dispatch_child_task(subagent_type) so curated prompts and tool whitelists get reused instead of duplicated.")),n.push(S("self-knowledge-routing",wo(e.selfManual?.productName),"Route product usage/config/troubleshooting questions to the kodax_manual tool as the version-bound product source of truth.")),n.push(S("execution-guidance",bi,"Match your approach to the kind of work (review / audit / investigation / planning / ambiguity) by self-judgment, not router assignment.")),e.context?.promptOverlay?.trim()&&n.push(S("prompt-overlay",e.context.promptOverlay,"Task-shaping rule for this request plus any caller-supplied context."));let l=Xr({cwd:r,projectRoot:e.context?.gitRoot??void 0}),p=Yr(l);p&&n.push(S("project-agents",p,"Append project-scoped AI rules after runtime truth so local constraints keep higher precedence than skills.")),n.push(S("memory-rules",gi(r),"Teach the agent the 4-type memory taxonomy, save procedure, and recall etiquette so writes are consistent across sessions and providers."));let y=Ti(r),w=await gl(r,e.context?.rawUserInput);return n.push(S("project-memory",yl(y.content,w),"Inject the per-project MEMORY.md index so the agent has cross-session recall without re-asking the user for previously-given context.")),e.context?.skillsPrompt?.trim()&&n.push(S("skills-addendum",e.context.skillsPrompt,"Append skill-specific guidance after project rules as a bounded dynamic addendum.")),vi(e.context?.toolConstructionMode)&&n.push(S("tool-construction",xi,"Append the tool-construction staircase guidance only when self-construction is authorized for this session.")),n}i(So,"buildCapabilityContextSections");async function gl(e,t){let o=t?.trim();if(!(o===void 0||o.length===0))try{return await He({cwd:e,projectDocs:[],discoverSkills:!1}).buildMemoryPack({task:o,maxHints:5,includeSnippets:!1})}catch(r){I("[memory:pack:error]",{cwd:e,error:r instanceof Error?r.message:String(r)});return}}i(gl,"buildTaskMemoryPack");function yl(e,t){return t===void 0?e:t.traceMetadata.suppressed?[e,"","Task-relevant memory hints: suppressed by user request."].join(`
|
|
123
|
+
`):t.hints.length===0?e:[e,"","Task-relevant memory hints (bounded):",...t.hints.map(Tl),"","Use these as pointers, not authority. If a hint matters, read the referenced memory file before relying on details. Current repository files override memory."].join(`
|
|
124
|
+
`)}i(yl,"appendTaskMemoryPack");function Tl(e){return`- ${ki(e.hook)} [${e.ref.id}]: ${ki(e.reason)}`}i(Tl,"formatTaskMemoryHint");function ki(e){return e.replace(/\s+/g," ").trim().slice(0,180)}i(ki,"compactPromptLine");function bl(e){let t=zr(e);return t.length===0?null:["=== Available specialist agents ===",t.map(r=>`- ${r.name}: ${r.description?.trim()||"(no description)"}`).join(`
|
|
125
|
+
`),"",'Dispatch via dispatch_child_task(subagent_type="<name>").'].join(`
|
|
126
|
+
`)}i(bl,"buildSpecialistAgentsBlock");function xl(e){if(!e.includes(Eo))return{prefix:e.trim(),suffix:""};let[t,...o]=e.split(Eo);return{prefix:t.trim(),suffix:o.join(Eo).trim()}}i(xl,"splitSystemPromptTemplate");function vl(){let e=process.platform,t=e==="win32";return`Platform: ${t?"Windows":e==="darwin"?"macOS":"Linux"}
|
|
127
|
+
${t?"Use: dir, move, copy, del":"Use: ls, mv, cp, rm"}
|
|
128
|
+
Node: ${process.version}`}i(vl,"getEnvContext");function kl(e){let t=e.provider?.trim(),o=(e.modelOverride??e.model)?.trim();if(!t&&!o)return null;let r=[];return t&&r.push(`provider=${t}`),o&&r.push(`model=${o}`),`[Runtime] ${r.join("; ")}.`}i(kl,"getRuntimeFact");async function wl(e){try{let{stdout:t}=await Ro("git rev-parse --is-inside-work-tree",{cwd:e});if(!t.trim())return"";let o=[];try{let{stdout:r}=await Ro("git branch --show-current",{cwd:e});r.trim()&&o.push(`Git Branch: ${r.trim()}`)}catch{}try{let{stdout:r}=await Ro("git status --short",{cwd:e});if(r.trim()){let n=r.trim().split(`
|
|
129
|
+
`).slice(0,10);o.push(`Git Status:
|
|
130
|
+
${n.map(a=>` ${a}`).join(`
|
|
131
|
+
`)}`),r.trim().split(`
|
|
132
|
+
`).length>10&&o.push(" ... (more changes)")}}catch{}return o.join(`
|
|
133
|
+
`)}catch{return""}}i(wl,"getGitContext");async function Rl(e,t=2,o=50){let r=await import("fs/promises"),n=new Set([".git","__pycache__","node_modules",".venv","venv","dist","build",".idea",".vscode"]),s=new Set([".pyc",".pyo",".so",".dll",".exe",".bin"]),a=[`Project: ${Ct.basename(e)}`],c=0;async function d(u,m){if(!(m>t||c>=o))try{let l=await r.readdir(u,{withFileTypes:!0}),p=[],y=[];for(let f of l)f.isDirectory()&&!n.has(f.name)&&!f.name.startsWith(".")?p.push(f.name):f.isFile()&&!s.has(Ct.extname(f.name))&&y.push(f.name);let w=" ".repeat(m),_=Ct.relative(e,u);_&&_!=="."&&a.push(`${w}${_}/`);for(let f of y.sort().slice(0,20))if(a.push(`${w} ${f}`),c+=1,c>=o){a.push(" ... (more files)");return}for(let f of p.sort())await d(Ct.join(u,f),m+1)}catch{}}return i(d,"walk"),await d(e,0),a.join(`
|
|
134
|
+
`)}i(Rl,"getProjectSnapshot");async function wi(e,t){let o=j(e.context),r=e.context?.gitRoot?El.resolve(e.context.gitRoot):o,n=await So(e,t,o);return xo(n,{isNewSession:t,executionCwd:o,projectRoot:r,longRunning:!1})}i(wi,"buildSystemPromptSnapshot");async function _o(e,t){return(await wi(e,t)).rendered}i(_o,"buildSystemPrompt");function Ri(e,t,o){if(!t.capability&&!t.trace)return null;let r=[`stage=${e}`,t.capability?`mode=${t.capability.mode}/${t.capability.engine}/${t.capability.status}`:void 0,t.trace?.cacheHit!==void 0?`cache_hit=${t.trace.cacheHit?"yes":"no"}`:void 0,t.trace?.capsuleEstimatedTokens!==void 0?`capsule_tokens=${t.trace.capsuleEstimatedTokens}`:void 0,o].filter(n=>!!n);return{stage:e,summary:r.join(" | "),capability:t.capability,trace:t.trace}}i(Ri,"createRepoIntelligenceTraceEvent");var Sl=2e3,_l=6e4,Ei=64,se=new Map;async function Mt(e){let t,o=new Promise(r=>{t=setTimeout(()=>{r({value:null,timedOut:!0})},Sl),typeof t=="object"&&typeof t.unref=="function"&&t.unref()});try{return await Promise.race([e.then(r=>({value:r,timedOut:!1})),o])}finally{t&&clearTimeout(t)}}i(Mt,"settleWithinAutoContextBudget");function Si(e=Date.now()){for(let[o,r]of se.entries())r.settled&&r.expiresAt<=e&&se.delete(o);if(se.size<=Ei)return;let t=Array.from(se.keys());for(let o of t.slice(0,se.size-Ei))se.delete(o)}i(Si,"pruneAutoContextPreturnStates");function Cl(e,t,o){return JSON.stringify({executionCwd:e.executionCwd??"",gitRoot:e.gitRoot??"",mode:t,targetPath:o??""})}i(Cl,"autoContextPreturnKey");function Ml(e,t){let o=Date.now();Si(o);let r=se.get(e);if(r&&(!r.settled||r.expiresAt>o))return r;let n;return n={promise:t().catch(()=>null).finally(()=>{n.settled=!0,n.expiresAt=Date.now()+_l}),budgetMissed:!1,settled:!1,expiresAt:Number.POSITIVE_INFINITY},se.set(e,n),Si(o),n}i(Ml,"getAutoContextPreturnState");async function Al(e){if(e.budgetMissed&&!e.settled)return{value:null,timedOut:!0};let t=await Mt(e.promise);return t.timedOut&&(e.budgetMissed=!0),t}i(Al,"settleAutoContextPreturn");function Pl(e){return e.context?.repoIntelligenceTrace===!0||process.env.KODAX_REPO_INTELLIGENCE_TRACE==="1"}i(Pl,"shouldEmitRepoIntelligenceTrace");function Ke(e,t,o,r,n){if(!e?.onRepoIntelligenceTrace||!Pl(t)||!r)return;let s=Ri(o,r,n);s&&e.onRepoIntelligenceTrace(s)}i(Ke,"emitRepoIntelligenceTrace");async function Co(e,t,o,r){if(Re(e.context?.repoIntelligenceMode)==="off")return e.context?.repoIntelligenceContext;let s=ct(e.context?.repoIntelligenceMode),a=t.decision,c=o||a.primaryTask==="plan"||a.complexity!=="simple",d=a.primaryTask==="review"||a.primaryTask==="bugfix"||a.primaryTask==="edit"||a.primaryTask==="refactor";if(!c&&!d)return e.context?.repoIntelligenceContext;try{let u=e.context?.executionCwd?".":void 0,m={executionCwd:e.context?.executionCwd,gitRoot:e.context?.gitRoot??void 0},l=a.primaryTask==="review"||a.primaryTask==="bugfix"||a.primaryTask==="edit"||a.primaryTask==="refactor",y=l&&s==="full"?Al(Ml(Cl(m,s,u),()=>Gr(m,{targetPath:u,refresh:!1,mode:s}))):Promise.resolve({value:null,timedOut:!1}),w=Mt(Br({executionCwd:e.context?.executionCwd,gitRoot:e.context?.gitRoot??void 0},{includeRepoOverview:c,includeChangedScope:d,refreshOverview:!1,changedScope:"all"}).catch(()=>null)),[_,f]=await Promise.all([w,y]),U=_.value??"",R=f.value,O="",h="",N="",ae="",B=_.timedOut||f.timedOut,A=null,D=null;if(R&&(Ke(r,e,"preturn",R,R.summary),A=R.moduleContext??null,D=R.impactEstimate??null,ae=R.repoContext??""),l){let V=!B,[Ae,T]=await Promise.all([V&&!A?Mt(jr(m,{targetPath:u,refresh:!1,mode:s}).catch(()=>null)).then(W=>(B=B||W.timedOut,W.value)):Promise.resolve(null),V&&!D?Mt(qr(m,{targetPath:u,refresh:!1,mode:s}).catch(()=>null)).then(W=>(B=B||W.timedOut,W.value)):Promise.resolve(null)]);A=A??Ae,D=D??T,A&&(Ke(r,e,"module",A,`module=${A.module.moduleId}`),O=["## Active Module Intelligence",Hr(A)].join(`
|
|
135
|
+
`)),D&&(Ke(r,e,"impact",D,`target=${D.target.label}`),h=["## Active Impact Intelligence",$r(D)].join(`
|
|
136
|
+
`));let b=(A?.confidence??1)<.72||(D?.confidence??1)<.72;!B&&(b||!A&&!D)&&(N=["## Repo Intelligence Guidance","- Current repository intelligence is low-confidence for this area.","- Validate critical edits with `module_context`, `symbol_context`, `grep`, and `read` before committing to a change."].join(`
|
|
137
|
+
`))}return[e.context?.repoIntelligenceContext,ae,U,O,h,N].filter(V=>typeof V=="string"&&V.trim().length>0).join(`
|
|
138
|
+
|
|
139
|
+
`)}catch{return e.context?.repoIntelligenceContext}}i(Co,"buildAutoRepoIntelligenceContext");async function At(e,t,o){let r=await Co(e,t,o,e.events),n={...e,effort:t.effort,context:{...e.context,executionCwd:j(e.context),repoIntelligenceContext:r,providerPolicyHints:{...e.context?.providerPolicyHints,...ai(t.decision)},promptOverlay:[e.context?.promptOverlay,t.promptOverlay].filter(Boolean).join(`
|
|
140
|
+
|
|
141
|
+
`)}};return{effectiveOptions:n,systemPrompt:e.context?.systemPromptOverride??await _o(n,o),providerReasoning:{enabled:t.effort!=="none",effort:t.effort,taskType:t.decision.primaryTask,executionMode:t.decision.recommendedMode}}}i(At,"buildReasoningExecutionState");function Il(e,t){return t?{...e,effort:t}:e}i(Il,"buildEffectiveReasoningPlan");async function _i(e){let t=Il(e.reasoningPlan,e.thinkingLevel),o=await At({...e.options,provider:e.providerName,modelOverride:e.modelOverride,effort:e.thinkingLevel??e.options.effort},t,e.messages.length===1);return{effectiveReasoningPlan:t,currentExecution:o}}i(_i,"resolvePerTurnReasoning");function Ci(e){let t=new AbortController,o=setTimeout(()=>{t.abort(new Error("API Hard Timeout (10 minutes)"))},e.hardTimeoutMs),r;e.streamMaxDurationMs>0&&(r=setTimeout(()=>{t.abort(new Error(`Stream max duration exceeded (${e.streamMaxDurationMs}ms; provider has known server-side kill window)`))},e.streamMaxDurationMs));let n=e.idleTimeoutMs>0,s;n&&(s=setTimeout(()=>{t.abort(new Error(`Stream stalled or delayed response (${e.idleTimeoutMs}ms idle)`))},e.idleTimeoutMs));let a=i(()=>{n&&(clearTimeout(s),t.signal.aborted||(s=setTimeout(()=>{t.abort(new Error(`Stream stalled or delayed response (${e.idleTimeoutMs}ms idle)`))},e.idleTimeoutMs)))},"resetIdleTimer"),c=i(()=>{n&&(clearTimeout(s),s=void 0)},"clearIdleTimer"),d=e.callerAbortSignal?AbortSignal.any([e.callerAbortSignal,t.signal]):t.signal;return{retryTimeoutController:t,retrySignal:d,resetIdleTimer:a,clearIdleTimer:c,clearAll:i(()=>{clearTimeout(o),clearTimeout(r),clearTimeout(s),o=void 0,r=void 0,s=void 0},"clearAll")}}i(Ci,"buildStreamTimers");function Mi(e){let t=vt({providerName:e.providerName,model:e.model,provider:e.provider,prompt:e.prompt,options:e.effectiveOptions,context:e.effectiveOptions.context,reasoningMode:e.reasoningMode,taskType:e.taskType,executionMode:e.executionMode});if(t.status==="block")throw new Error(`[Provider Policy] ${t.summary}`);return{effectiveSystemPrompt:t.issues.length>0?[e.baseSystemPrompt,Wn(t).join(`
|
|
142
|
+
`)].join(`
|
|
143
|
+
|
|
144
|
+
`):e.baseSystemPrompt,decision:t}}i(Mi,"applyProviderPolicyGate");function Ai(e){let{events:t,boundaryTracker:o,streamTimers:r,emitActiveExtensionEvent:n,providerName:s}=e;return{onTextDelta:i(a=>{r.resetIdleTimer(),o.markTextDelta(a),n("text:delta",{text:a}),t.onTextDelta?.(a)},"onTextDelta"),onThinkingDelta:i(a=>{r.resetIdleTimer(),o.markThinkingDelta(a),n("thinking:delta",{text:a}),t.onThinkingDelta?.(a)},"onThinkingDelta"),onThinkingEnd:i(a=>{r.resetIdleTimer(),n("thinking:end",{thinking:a}),t.onThinkingEnd?.(a)},"onThinkingEnd"),onToolInputDelta:i((a,c,d)=>{r.resetIdleTimer(),o.markToolInputStart(d?.toolId??`pending:${a}`),t.onToolInputDelta?.(a,c,d)},"onToolInputDelta"),onRateLimit:i((a,c,d)=>{r.resetIdleTimer(),n("provider:rate-limit",{provider:s,attempt:a,maxRetries:c,delayMs:d}),mn(t,a,c,d)},"onRateLimit"),onRetryAfter:i(a=>{r.resetIdleTimer(),t.onRetryAfter?.(a)},"onRetryAfter"),onReasoningEffortRejected:i(a=>{vr(a.provider,a.model,a.effort,"observed",new Date().toISOString()),t.onReasoningEffortRejected?.(a)},"onReasoningEffortRejected"),onHeartbeat:i(a=>{a?r.clearIdleTimer():r.resetIdleTimer()},"onHeartbeat")}}i(Ai,"buildStreamHandlers");var Pt=class{static{i(this,"BoundaryTrackerSession")}tracker;constructor(){this.tracker=new je}beginAttempt(t,o,r,n,s){this.tracker.beginRequest(t,o,r,n,s),uo(this.tracker.snapshot())}markTextDelta(t){this.tracker.markTextDelta(t)}markThinkingDelta(t){this.tracker.markThinkingDelta(t)}markToolInputStart(t){this.tracker.markToolInputStart(t)}inferFailureStage(){return this.tracker.inferFailureStage()}snapshot(){return this.tracker.snapshot()}};function Pi(e){let t=e.message.toLowerCase();return e.name==="StreamIncompleteError"||t.includes("stream incomplete")?"Stream interrupted before completion":t.includes("stream stalled")||t.includes("delayed response")||t.includes("60s idle")?"Stream stalled":t.includes("hard timeout")||t.includes("10 minutes")?"Provider response timed out":t.includes("socket hang up")||t.includes("connection error")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("fetch failed")||t.includes("network")?"Provider connection error":t.includes("timed out")||t.includes("timeout")||t.includes("etimedout")?"Provider request timed out":t.includes("aborted")?"Provider stream aborted":"Transient provider error"}i(Pi,"describeTransientProviderRetry");function Ii(e,t,o,r){let n=io(e,gn(r)),s=new qe(o,{...n,enableNonStreamingFallback:n.enableNonStreamingFallback&&t.supportsNonStreamingFallback()});return{resilienceCfg:n,recoveryCoordinator:s}}i(Ii,"buildResilienceSession");async function Oi(e,t,o){if(e.name==="AbortError"&&t.signal.aborted&&!o?.aborted){let r=t.signal.reason?.message??"Stream stalled",{KodaXNetworkError:n}=await import("./dist-4PXB7U22.js");return new n(r,!0)}return e}i(Oi,"translateAbortError");function Ni(e){let t=gt(e.error,e.failureStage);co(e.error,t);let o=e.recoveryCoordinator.decideRecoveryAction(e.error,t,e.attempt);return lo(o,e.attempt),e.events.onProviderRecovery?.({stage:o.failureStage,errorClass:o.reasonCode,attempt:e.attempt,maxAttempts:e.resilienceCfg.maxRetries,delayMs:o.delayMs,recoveryAction:o.action,ladderStep:o.ladderStep,fallbackUsed:o.shouldUseNonStreaming,serverRetryAfterMs:o.serverRetryAfterMs}),!e.events.onProviderRecovery&&o.action!=="manual_continue"&&e.events.onRetry?.(`${Pi(e.error)} \xB7 retry ${e.attempt}/${e.resilienceCfg.maxRetries} in ${Math.round(o.delayMs/1e3)}s`,e.attempt,e.resilienceCfg.maxRetries),{classified:t,decision:o}}i(Ni,"runRecoveryPipeline");async function Di(e){let t=new AbortController,o=e.callerAbortSignal?AbortSignal.any([e.callerAbortSignal,t.signal]):t.signal,r=setTimeout(()=>{t.abort(new Error("API Hard Timeout (10 minutes)"))},e.hardTimeoutMs);try{return e.clearStreamTimers(),e.boundarySession.beginAttempt(e.providerName,e.modelOverride??e.streamProvider.getModel(),e.providerMessages,e.attempt,!0),{ok:!0,result:await e.streamProvider.complete(e.providerMessages,e.activeToolDefinitions,e.effectiveSystemPrompt,e.effectiveProviderReasoning,{onTextDelta:i(s=>{e.boundarySession.markTextDelta(s),e.emitActiveExtensionEvent("text:delta",{text:s}),e.events.onTextDelta?.(s)},"onTextDelta"),onThinkingDelta:i(s=>{e.boundarySession.markThinkingDelta(s),e.emitActiveExtensionEvent("thinking:delta",{text:s}),e.events.onThinkingDelta?.(s)},"onThinkingDelta"),onThinkingEnd:i(s=>{e.emitActiveExtensionEvent("thinking:end",{thinking:s}),e.events.onThinkingEnd?.(s)},"onThinkingEnd"),modelOverride:e.modelOverride,signal:o},o)}}catch(n){return{ok:!1,error:n instanceof Error?n:new Error(String(n))}}finally{clearTimeout(r)}}i(Di,"executeNonStreamingFallback");var Ol={type:"text",text:""};function Li(e){return e.length===0?[Ol]:e}i(Li,"guardEmptyAssistantContent");async function Mo(e,t,o,r,n,s){if(e.beforeToolExecute){let c=await e.beforeToolExecute(t,o,{toolId:r});if(c===!1)return $;if(typeof c=="string")return c}let a=await fe("tool:before",{name:t,input:o,toolId:r,executionCwd:n,gitRoot:s});return a===!1?$:typeof a=="string"?a:void 0}i(Mo,"getToolExecutionOverride");import Nl from"fs";function It(e,t){let o=e.input?.path;if(!(typeof o!="string"||o.trim().length===0))return Lr(o,t)}i(It,"resolveToolTargetPath");function Ao(e,t){t&&(e.editRecoveryAttempts.delete(t),e.blockedEditWrites.delete(t))}i(Ao,"clearEditRecoveryStateForPath");function Po(e,t,o){if(e.name!=="write")return;let r=It(e,t);if(!(!r||!o.blockedEditWrites.has(r))){if(!Nl.existsSync(r)){o.blockedEditWrites.delete(r);return}return`[Tool Error] write: BLOCKED_AFTER_EDIT_FAILURE: Refusing to rewrite existing file ${r} while edit anchor recovery is in progress. Retry with edit using a smaller unique anchor or use insert_after_anchor.`}}i(Po,"maybeBlockExistingFileWrite");async function Fi(e,t,o,r){let n=at(t);if(!n)return;let s=typeof e.input?.path=="string"?e.input.path:void 0,a=It(e,r);if(!s||!a)return;o.blockedEditWrites.add(a);let c=(o.editRecoveryAttempts.get(a)??0)+1;if(o.editRecoveryAttempts.set(a,c),o.lastToolErrorCode=n,n==="EDIT_TOO_LARGE")return I("[edit:recovery]",{code:n,path:a,attempt:c,action:"split-edit"}),[`The previous edit for ${a} failed with ${n}.`,"Do not use write to replace the existing file.","Split the change into smaller edit calls, or use insert_after_anchor when you are appending a new section after a unique heading."].join(`
|
|
145
|
+
`);if(c>2)return I("[edit:recovery]",{code:n,path:a,attempt:c,action:"stop-auto-recovery"}),[`The previous edit for ${a} failed with ${n}, and automatic anchor recovery is exhausted.`,"Do not escalate to a whole-file write.","Choose a smaller unique anchor manually, or switch to insert_after_anchor if this is a section append."].join(`
|
|
146
|
+
`);let d=c===1?120:400,u=await Ur(s,String(e.input?.old_string??""),r,d),m=u.candidates[0],l=u.candidates.slice(1,3);I("[edit:recovery]",{code:n,path:a,attempt:c,windowLines:d,candidateCount:u.candidates.length});let p=[`The previous edit for ${a} failed with ${n}.`,"Do not use write to rewrite the existing file.","Retry with edit using a smaller unique old_string.","When appending a new section after a unique heading, use insert_after_anchor instead."];if(m&&(p.push(""),p.push(`Best nearby anchor window (${m.startLine}-${m.endLine}):`),p.push("```text"),p.push(m.excerpt),p.push("```")),l.length>0){p.push(""),p.push("Other nearby candidate anchors:");for(let y of l)p.push(`- lines ${y.startLine}-${y.endLine}: ${y.preview}`)}return p.join(`
|
|
147
|
+
`)}i(Fi,"buildEditRecoveryUserMessage");function Ce(e){return/^\[(?:Tool Error|Cancelled|Blocked|Error)\]/.test(e)}i(Ce,"isToolResultErrorContent");function Ui(e){return e.startsWith(Dr)}i(Ui,"isCancelledToolResultContent");function Bi(e){return/^\[Tool Error\]\s+[^:]+:\s+([A-Z_]+):/.exec(e.trim())?.[1]}i(Bi,"extractStructuredToolErrorCode");var Dl=new Set(["edit","write","multi_edit","apply_patch","delete","remove","rename"]),Ll=3,Fl=100;function Hi(e){return Dl.has(e.toLowerCase())}i(Hi,"isMutationTool");function $i(e){return e.files.size>=Ll?!0:[...e.files.values()].reduce((o,r)=>o+r,0)>=Fl}i($i,"isMutationScopeSignificant");function Ul(e){let t=[...e.files.values()].reduce((r,n)=>r+n,0),o=[...e.files.entries()].map(([r,n])=>` - ${r} (~${n} lines)`).join(`
|
|
148
|
+
`);return["",`[Scope: ${e.files.size} files modified, ~${t} lines]`,o].join(`
|
|
149
|
+
`)}i(Ul,"buildMutationScopeReflectionHeader");function ji(e){return[Ul(e),"A senior engineer would pause here. SA mode has no Evaluator \u2014 you own the review:","\u2192 Re-read the diff: did each edit land on the intended file/region, and does the change as a whole match the user's intent?","\u2192 Run the project's typecheck/tests if available \u2014 uncaught regressions are your responsibility in SA mode.","\u2192 If this turned into a multi-stage task (plan \u2192 generate \u2192 verify), tell the user it would benefit from a re-run under AMA mode for an independent Evaluator pass."].join(`
|
|
150
|
+
`)}i(ji,"buildMutationScopeReflection");function qi(e,t,o,r){let n=It(e,r);if(o.lastToolResultBytes=Buffer.byteLength(t,"utf8"),o.lastToolErrorCode=Bi(t),e.name==="edit"){at(t)||Ao(o,n);return}e.name==="insert_after_anchor"&&!Ce(t)&&Ao(o,n)}i(qi,"updateToolOutcomeTracking");function Xe(e,t){return{type:"tool_result",tool_use_id:e,content:t,...Ce(t)?{is_error:!0}:{}}}i(Xe,"createToolResultBlock");async function Wi(e,t,o,r,n,s,a){if(s?.aborted)return $;let c=J(t.name),d=he(e,t.id);if(c&&(await x("tool:start",{name:t.name,id:t.id,input:t.input}),e.onToolUseStart?.({name:t.name,id:t.id,input:t.input},d)),!(t.name===pe||t.name===ft)){let y=await Mo(e,t.name,t.input??{},t.id,o.executionCwd,o.gitRoot);if(y!==void 0)return y}if(n&&!n.includes(t.name))return`[Tool Error] ${t.name}: Tool is not active in the current runtime.`;if(t.name===ft)return Bl(t.input??{},n);if(t.name===pe)return $l({events:e,bridgeCall:t,ctx:o,runtimeSessionState:r,activeToolNames:n,abortSignal:s,toolResultBudget:a});let m=Po(t,o,r);if(m)return m;let l=Gi(e,t,o),p=await ro(t.name,t.input??{},l);if(p.startsWith("[Tool Error]")&&o.extensionRuntime){let y=await Ki(t.name,t.input??{},o);if(y!==void 0)return y}return p}i(Wi,"executeToolCall");function he(e,t){return{toolId:t,...e.workflowCorrelation!==void 0?{workflowCorrelation:e.workflowCorrelation}:{}}}i(he,"createToolEventMeta");function Gi(e,t,o){let r=he(e,t.id);return e.onToolProgress||e.askUser||e.askUserMulti||e.askUserInput?{...o,toolCallId:t.id,...e.onToolProgress?{reportToolProgress:i(n=>{e.onToolProgress?.({id:t.id,message:n},r)},"reportToolProgress")}:{},...e.askUser?{askUser:i(n=>e.askUser(n,r),"askUser")}:{},...e.askUserMulti?{askUserMulti:i(n=>e.askUserMulti(n,r),"askUserMulti")}:{},...e.askUserInput?{askUserInput:i(n=>e.askUserInput(n,r),"askUserInput")}:{}}:{...o,toolCallId:t.id}}i(Gi,"createContextForToolCall");function Bl(e,t){let o=Hl(e);if(o.length===0)return"[Tool Error] tool_describe: `name` or `names` is required.";let r=t?new Set(t):void 0,n=[];for(let a of o.slice(0,8)){if(r&&!r.has(a)){n.push(`<!-- ${a}: not active in the current runtime -->`);continue}let c=Rn(a);if(!c){n.push(`<!-- ${a}: not registered -->`);continue}n.push(`<function>${JSON.stringify({name:c.name,description:c.description,parameters:c.input_schema})}</function>`)}let s=n.join(`
|
|
151
|
+
`);return s.length<=16e3?s:`${s.slice(0,16e3)}
|
|
152
|
+
<!-- tool_describe output truncated -->`}i(Bl,"describeBridgeTools");function Hl(e){let t=[],o=i(r=>{typeof r=="string"&&r.trim().length>0&&t.push(r.trim())},"append");o(e.name),o(e.tool_name);for(let r of["names","tools"]){let n=e[r];if(Array.isArray(n))for(let s of n)o(s)}return[...new Set(t)]}i(Hl,"readBridgeToolNames");async function $l(e){let t=jl(e.bridgeCall.input??{});if(!t.ok)return`[Tool Error] ${pe}: ${t.error}`;let o=t.name,r=t.input;if(o===pe||o===ft)return`[Tool Error] ${pe}: bridge meta-tools cannot be called through ${pe}.`;let n={id:`${e.bridgeCall.id}:${o}`,name:o,input:r};if(e.abortSignal?.aborted)return $;let s=await Mo(e.events,o,r,n.id,e.ctx.executionCwd,e.ctx.gitRoot);if(s!==void 0)return s;if(e.activeToolNames&&!e.activeToolNames.includes(o))return`[Tool Error] ${o}: Tool is not active in the current runtime.`;let a=Po(n,e.ctx,e.runtimeSessionState);if(a)return a;let c=Gi(e.events,n,e.ctx),d=await ro(o,r,c);if(d.startsWith("[Tool Error]")&&e.ctx.extensionRuntime){let u=await Ki(o,r,e.ctx);u!==void 0&&(d=u)}return(await lt(o,d,e.ctx,{toolResultBudget:e.toolResultBudget})).content}i($l,"executeBridgeToolCall");function jl(e){let t=typeof e.name=="string"?e.name.trim():typeof e.tool_name=="string"?e.tool_name.trim():"";if(t.length===0)return{ok:!1,error:"`name` is required."};let o=e.input??e.arguments;return!o||typeof o!="object"||Array.isArray(o)?{ok:!1,error:"`input` must be a JSON object."}:{ok:!0,name:t,input:o}}i(jl,"parseBridgeCallInput");var ql=new Set(["web_search","web_fetch","glob","grep","read","code_search","semantic_lookup"]);async function Ki(e,t,o){if(ql.has(e))try{let r=await o.extensionRuntime.searchCapabilities("mcp",e,{kind:"tool",limit:1});if(r.length===0)return;let n=r[0];if(!n?.id||n.name!==e&&!n.id.endsWith(`:${e}`))return;let s=await o.extensionRuntime.executeCapability("mcp",n.id,t),a=typeof s.content=="string"?s.content:JSON.stringify(s.structuredContent??s,null,2);return`[MCP Fallback via ${n.id}]
|
|
153
|
+
${a}`}catch(r){process.env.KODAX_DEBUG_TOOL_HISTORY&&E({source:"coding:tool-dispatch",level:"debug",message:`MCP fallback failed for ${e}.`,detail:r});return}}i(Ki,"tryMcpFallback");async function Xi(e){let t=e.toolBlocks.filter(n=>n.name==="bash"),o=e.toolBlocks.filter(n=>n.name!=="bash"),r=new Map;if(o.length>0){let n=o.map(async a=>({id:a.id,content:(await lt(a.name,await Wi(e.events,{id:a.id,name:a.name,input:a.input},e.ctx,e.runtimeSessionState,e.activeToolNames,e.abortSignal,e.toolResultBudget),e.ctx,{toolResultBudget:e.toolResultBudget})).content})),s=await Promise.all(n);for(let a of s)r.set(a.id,a.content)}for(let n of t){if(e.abortSignal?.aborted){r.set(n.id,$);continue}let s=(await lt(n.name,await Wi(e.events,{id:n.id,name:n.name,input:n.input},e.ctx,e.runtimeSessionState,e.activeToolNames,e.abortSignal,e.toolResultBudget),e.ctx,{toolResultBudget:e.toolResultBudget})).content;r.set(n.id,s)}return r}i(Xi,"runToolDispatch");async function Yi(e){let t=[],o=[];for(let r of e.toolBlocks){let n=e.resultMap.get(r.id)??"[Error] No result";if(e.ctx.mutationTracker&&!e.ctx.mutationTracker.reflectionInjected&&!Ce(n)&&Hi(r.name)&&$i(e.ctx.mutationTracker)&&(n+=ji(e.ctx.mutationTracker),e.ctx.mutationTracker.reflectionInjected=!0),qi(r,n,e.runtimeSessionState,e.ctx),r.name==="edit"&&Ce(n)){let s=await Fi(r,n,e.runtimeSessionState,e.ctx);s&&o.push(s)}J(r.name)&&(await e.emitActiveExtensionEvent("tool:result",{id:r.id,name:r.name,content:n}),e.events.onToolResult?.({id:r.id,name:r.name,content:n},he(e.events,r.id)),t.push(Xe(r.id,n)))}return{toolResults:t,editRecoveryMessages:o}}i(Yi,"applyPostToolProcessing");function Wl(e,t){return t===1?`Your previous response was truncated. Missing required parameters:
|
|
154
|
+
${e.map(o=>`- ${o}`).join(`
|
|
155
|
+
`)}
|
|
156
|
+
|
|
157
|
+
Please provide the complete tool calls with ALL required parameters.
|
|
158
|
+
For large content, keep it concise (under 50 lines for write operations).`:`\u26A0\uFE0F CRITICAL: Your response was TRUNCATED again. This is retry ${t}/${2}.
|
|
159
|
+
|
|
160
|
+
MISSING PARAMETERS:
|
|
161
|
+
${e.map(o=>`- ${o}`).join(`
|
|
162
|
+
`)}
|
|
163
|
+
|
|
164
|
+
YOU MUST:
|
|
165
|
+
1. For 'write' tool: Keep content under 50 lines - write structure first, fill in later with 'edit'
|
|
166
|
+
2. For 'edit' tool: Keep new_string under 30 lines - make smaller, focused changes
|
|
167
|
+
3. Provide ALL required parameters in your tool call
|
|
168
|
+
|
|
169
|
+
If your response is truncated again, the task will FAIL.
|
|
170
|
+
PROVIDE SHORT, COMPLETE PARAMETERS NOW.`}i(Wl,"buildRetryPrompt");function Gl(e,t){return typeof e=="string"?e.trim().length>0?`${e}
|
|
171
|
+
|
|
172
|
+
${t}`:t:[...e,{type:"text",text:t}]}i(Gl,"appendTextToUserContent");function Kl(e){return typeof e=="string"?e.trim().length>0:e.some(t=>t.type==="text"&&(t.text??"").trim().length>0)}i(Kl,"userTurnHasText");async function zi(e){let t=Bn(e.toolBlocks);if(t.length===0)return{outcome:"no_incomplete",nextIncompleteRetryCount:0,nextContextTokenSnapshot:e.completedTurnTokenSnapshot};let o=e.incompleteRetryCount+1;if(o<=2){e.events.onRetry?.(`Incomplete tool calls: ${t.join(", ")}`,o,2),e.messages.pop();let c=Wl(t,o),d=e.messages.length-1,u=d>=0?e.messages[d]:void 0;if(u&&u.role==="user"){let l=!Kl(u.content);e.messages[d]={...u,content:Gl(u.content,c),...l?{_synthetic:!0}:{}}}else e.messages.push({role:"user",content:c,_synthetic:!0});let m=M(e.messages,e.preAssistantTokenSnapshot);return{outcome:"retry",nextIncompleteRetryCount:o,nextContextTokenSnapshot:m}}e.events.onRetry?.(`Max retries exceeded for incomplete tool calls. Skipping: ${t.join(", ")}`,o,2);let r=new Set,n=new Set;for(let c of e.toolBlocks){if(mo(c)){r.add(c.id),n.add(c.id);continue}let d=pt(c.name),u=c.input??{};for(let m of d)if(u[m]===void 0||u[m]===null||u[m]===""){r.add(c.id);break}}let s=[];for(let c of e.toolBlocks){if(!J(c.name))continue;let d=r.has(c.id)?n.has(c.id)?`[Tool Error] ${c.name}: Skipped \u2014 input was truncated or could not be parsed as valid JSON after ${2} retries. Re-send a shorter, complete tool call with valid arguments (e.g. write structure first, fill in with smaller edits).`:`[Tool Error] ${c.name}: Skipped due to missing required parameters after ${2} retries`:`[Tool Error] ${c.name}: Skipped \u2014 a sibling tool call in the same turn was incomplete/truncated, so this turn was abandoned. Re-issue this call if it is still needed.`;await e.emitActiveExtensionEvent("tool:result",{id:c.id,name:c.name,content:d}),e.events.onToolResult?.({id:c.id,name:c.name,content:d},he(e.events,c.id)),s.push(Xe(c.id,d))}return s.length===0?e.messages.push({role:"user",content:`Your previous tool call was incomplete or truncated and was skipped after ${2} retries. Continue without it, or re-issue it with complete, valid arguments.`,_synthetic:!0}):e.messages.push({role:"user",content:s}),{outcome:"maxed_out",nextIncompleteRetryCount:0,nextContextTokenSnapshot:M(e.messages,e.completedTurnTokenSnapshot)}}i(zi,"checkAndRetryIncompleteTools");var Io="Operation cancelled by user";async function Vi(e){if(e.abortSignal?.aborted!==!0)return null;let t=[];for(let o of e.toolBlocks)J(o.name)&&(await e.emitActiveExtensionEvent("tool:result",{id:o.id,name:o.name,content:$}),e.events.onToolResult?.({id:o.id,name:o.name,content:$},he(e.events,o.id)),t.push(Xe(o.id,$)));return t}i(Vi,"checkPreToolAbort");function Qi(e){return e.some(t=>typeof t.content=="string"&&Ui(t.content))}i(Qi,"hasCancelledToolResult");async function Zi(e){let t=Ee(e.events);e.messages.push({role:"user",content:e.toolResults});let o=M(e.messages,e.completedTurnTokenSnapshot);return t&&(o=e.emitIterationEnd(e.iter+1,o)),await e.emitActiveExtensionEvent("turn:end",{sessionId:e.sessionId,iteration:e.iter+1,lastText:Io,hadToolCalls:!0,signal:void 0}),Se(e.events),await e.emitActiveExtensionEvent("stream:end",void 0),{contextTokenSnapshot:o,shouldYieldToQueuedFollowUp:t}}i(Zi,"applyCancellationTerminal");function Ji(e,t){if(!t||t.length===0)return e;let o=new Set(t);return e.filter(r=>!o.has(r))}i(Ji,"filterExcludedTools");function es(e,t){return t?e.filter(o=>{let r=En(o);return r?t({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0}):!1}):e}i(es,"applyToolVisibilityPolicy");function Oo(e,t,o=!1,r){let n=Re(t)==="off"?_n(e):e;return o||(n=Cn(n)),n=kn(n,r),n=wn(n,r),n}i(Oo,"getRuntimeActiveToolNames");function ts(e,t,o=!1,r=!1,n,s,a){let c=ht();if(e.length===0)return[];let d=new Set(Oo(e,t,r,n));return c.filter(u=>d.has(u.name)&&(o||!Qr(u.name))).map(u=>{let m=Fr(u,a);if(!$e(m.name)||s&&s.has(m.name))return m;let l=mt[m.name];return l?{...m,description:l}:m})}i(ts,"getActiveToolDefinitions");function Ye(e,t){return Me(JSON.stringify({name:e.name,description:t??e.description,parameters:e.input_schema}))}i(Ye,"estimateToolSchemaTokens");function is(e){let t=rs(e.contextWindow),o=rs(e.reservedResponseTokens??0),r=Me(e.systemPrompt??""),n=os(e.toolDefinitions??[],Ye),s=Me(e.skillCatalogText??""),a=Me(e.mcpCatalogText??""),c=Z(e.messages??[]),d=Me(e.pendingInput??""),u=os(e.recentToolResults??[],Me),m=r+n+s+a+c+d+u+o,l=t>0?Math.max(0,t-m):0,p=t>0?ns(m/t):1,y=t>0?ns(n/t):0,w=t>0&&t<=32e3,_=Xl({availableTokens:l,contextWindow:t,smallWindow:w,usedRatio:p});return{sessionId:e.sessionId,runId:e.runId,turnId:e.turnId,provider:e.provider,model:e.model,profile:e.profile??"report_only",contextWindow:t,smallWindow:w,pressure:_,tokenBreakdown:{systemPrompt:r,toolSchemas:n,skillCatalog:s,mcpCatalog:a,transcript:c,pendingInput:d,recentToolResults:u,reservedResponse:o,total:m},usedTokens:m,availableTokens:l,usedRatio:p,toolSchemaRatio:y,recommendations:Yl({pressure:_,recentToolResults:u,reservedResponse:o,toolSchemaRatio:y}),createdAt:(e.now?.()??new Date).toISOString()}}i(is,"createRuntimeContextBudgetSnapshot");function Me(e){return e.length===0?0:Math.max(0,gr(e))}i(Me,"estimateStringTokens");function os(e,t){let o=0;for(let r of e)o+=t(r);return o}i(os,"sumTokens");function Xl(e){return e.contextWindow<=0||e.availableTokens<=0||e.usedRatio>=.9||e.availableTokens<=Math.max(1024,e.contextWindow*.05)?"critical":e.usedRatio>=.75||e.availableTokens<=Math.max(2048,e.contextWindow*.15)?"high":e.usedRatio>=.55||e.smallWindow&&e.usedRatio>=.4?"medium":"low"}i(Xl,"classifyContextPressure");function Yl(e){if(e.pressure==="low")return[];let t=[];return e.toolSchemaRatio>=.08&&t.push("prefer_progressive_tool_exposure"),(e.pressure==="high"||e.pressure==="critical")&&t.push("compact_or_summarize_history"),e.recentToolResults>0&&t.push("trim_recent_tool_results"),e.reservedResponse===0&&t.push("reserve_response_budget"),t}i(Yl,"buildRecommendations");function rs(e){return!Number.isFinite(e)||e<=0?0:Math.floor(e)}i(rs,"toNonNegativeInteger");function ns(e){return Number.isFinite(e)?e<0?0:e>1?1:e:1}i(ns,"clampRatio");var zl=new Set(["tool_call","tool_describe","tool_search"]),Vl=new Set(["ask_user_question","bash","dispatch_child_task","edit","exit_plan_mode","glob","grep","insert_after_anchor","multi_edit","read","send_message","task_output","task_stop","todo_create","todo_get","todo_list","todo_update","tool_call","tool_describe","tool_search","undo","worktree_create","worktree_remove","write"]);function as(e){return e.smallWindow&&(e.pressure!=="low"||e.toolSchemaRatio>=.08)?"small_window":e.pressure==="high"||e.pressure==="critical"||e.recommendations.includes("prefer_progressive_tool_exposure")?"balanced":"report_only"}i(as,"selectRuntimeContextOptimizationProfile");function cs(e){let t=new Set(e.map(o=>o.name));for(let o of zl)if(!t.has(o))return!1;return!0}i(cs,"hasPortableToolBridge");function ls(e,t){if(t.reportOnly)return[...e];let o=new Set(t.modelVisibleToolNames);return e.filter(r=>o.has(r.name))}i(ls,"applyToolExposurePlan");function us(e){let t=e.profile??e.budget.profile,o=t==="report_only",r=e.bridgeAvailable===!0,n=e.nativeDeferredAvailable===!0,s=e.tools.map(m=>Ql(m,{bridgeAvailable:r,nativeDeferredAvailable:n,pressure:e.budget.pressure,profile:t,reportOnly:o,unlockedDeferredTools:e.unlockedDeferredTools})),a=s.filter(m=>m.modelVisible).map(m=>m.toolName),c=No(s,"estimatedTokensBefore"),d=No(s,"estimatedTokensAfter"),u=No(s,"estimatedTokensIfApplied");return{profile:t,reportOnly:o,pressure:e.budget.pressure,bridgeAvailable:r,nativeDeferredAvailable:n,decisions:s,modelVisibleToolNames:a,estimatedToolSchemaTokensBefore:c,estimatedToolSchemaTokensAfter:d,estimatedToolSchemaTokensIfApplied:u,estimatedTokensSaved:Math.max(0,c-d),estimatedTokensSavedIfApplied:Math.max(0,c-u),residentToolCount:ze(s,"resident"),hintedToolCount:ze(s,"hint"),bridgeToolCount:ze(s,"bridge"),nativeDeferredToolCount:ze(s,"native_deferred"),hiddenToolCount:ze(s,"hidden")}}i(us,"planToolExposure");function Ql(e,t){let o=Ye(e),r=Zl(e,t.unlockedDeferredTools),n=Jl(e,t),s=t.reportOnly?r:n.mode,a=ss(e,s),c=ss(e,n.mode);return{toolName:e.name,mode:s,recommendedMode:n.mode,reason:n.reason,estimatedTokensBefore:o,estimatedTokensAfter:a,estimatedTokensIfApplied:c,modelVisible:s==="resident"||s==="hint"||s==="native_deferred"}}i(Ql,"planTool");function Zl(e,t){return!$e(e.name)||t?.has(e.name)?"resident":"hint"}i(Zl,"currentExposureMode");function Jl(e,t){return t.profile==="off"?{mode:"resident",reason:"profile_off"}:Vl.has(e.name)?{mode:"resident",reason:"protected_core"}:$e(e.name)?t.unlockedDeferredTools?.has(e.name)?{mode:"resident",reason:"already_unlocked"}:eu(t.profile,t.pressure)?t.bridgeAvailable?{mode:"bridge",reason:"portable_bridge"}:t.nativeDeferredAvailable?{mode:"native_deferred",reason:"native_deferred"}:{mode:"hint",reason:"bridge_unavailable"}:{mode:"hint",reason:"deferred_hint"}:{mode:"resident",reason:"low_pressure"}}i(Jl,"recommendedExposureMode");function eu(e,t){return e==="aggressive"?t!=="low":e==="small_window"?!0:t==="high"||t==="critical"}i(eu,"shouldReduceDeferredToolExposure");function ss(e,t){return t==="bridge"||t==="hidden"?0:t==="hint"?Ye(e,mt[e.name]??e.description):Ye(e)}i(ss,"estimateTokensForMode");function No(e,t){return e.reduce((o,r)=>o+r[t],0)}i(No,"sumDecisionTokens");function ze(e,t){return e.filter(o=>o.mode===t).length}i(ze,"countMode");var ds=`Create a structured summary for the conversation below.
|
|
173
|
+
|
|
174
|
+
This summary will be handed to another coding agent so it can continue the same task with minimal context.
|
|
175
|
+
Keep only information that is still useful for continuing the work.
|
|
176
|
+
|
|
177
|
+
You may drop:
|
|
178
|
+
- completed low-value micro-steps
|
|
179
|
+
- repetitive thinking
|
|
180
|
+
- stale intermediate plans
|
|
181
|
+
- verbose tool output details
|
|
182
|
+
|
|
183
|
+
You must keep:
|
|
184
|
+
- the current goal
|
|
185
|
+
- user constraints and preferences
|
|
186
|
+
- current progress and unfinished work
|
|
187
|
+
- blockers or unresolved questions
|
|
188
|
+
- the most important next steps
|
|
189
|
+
- EXACT file paths, function names, and line numbers referenced
|
|
190
|
+
- EXACT error messages, HTTP status codes, and exception types
|
|
191
|
+
- API endpoints, database tables, env vars, and config values mentioned
|
|
192
|
+
- key decisions WITH reasoning (not just the choice)
|
|
193
|
+
|
|
194
|
+
CRITICAL: Every user REQUEST and DECISION must be preserved verbatim or near-verbatim.
|
|
195
|
+
Never reduce "user asked to fix the 401 error on /api/auth/login by switching to JWT"
|
|
196
|
+
to "user asked to fix an error".
|
|
197
|
+
|
|
198
|
+
Keep the summary concise and high-signal. Do not mechanically preserve every historical detail.
|
|
199
|
+
|
|
200
|
+
First, wrap your analysis in <analysis> tags:
|
|
201
|
+
- Walk through messages chronologically
|
|
202
|
+
- Note exact file paths, function names, error codes, config values
|
|
203
|
+
- Identify user's explicit requests vs inferred intent
|
|
204
|
+
- Flag technical details that MUST survive compression
|
|
205
|
+
|
|
206
|
+
Then output the structured summary in <summary> tags.
|
|
207
|
+
|
|
208
|
+
Output format (strict markdown, inside <summary> tags):
|
|
209
|
+
|
|
210
|
+
## Goal
|
|
211
|
+
[1-2 sentences describing the active goal]
|
|
212
|
+
|
|
213
|
+
## Constraints & Preferences
|
|
214
|
+
- [One item per line]
|
|
215
|
+
- [Write "None" if there are no explicit constraints]
|
|
216
|
+
|
|
217
|
+
## Progress
|
|
218
|
+
### Completed
|
|
219
|
+
- [x] [Completed work that still matters for context]
|
|
220
|
+
|
|
221
|
+
### In Progress
|
|
222
|
+
- [ ] [Current work that is actively underway]
|
|
223
|
+
|
|
224
|
+
### Blockers
|
|
225
|
+
- [Current blockers, or "None"]
|
|
226
|
+
|
|
227
|
+
## Key Decisions
|
|
228
|
+
- **[Decision]**: [Short reason]
|
|
229
|
+
|
|
230
|
+
## Next Steps
|
|
231
|
+
1. [Highest-priority next action]
|
|
232
|
+
|
|
233
|
+
## Key Context
|
|
234
|
+
- [Critical context needed to continue]
|
|
235
|
+
|
|
236
|
+
## Files & Changes
|
|
237
|
+
- **[exact path]**: [what was done and why]
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
<read-files>
|
|
242
|
+
[One path per line, leave empty if none]
|
|
243
|
+
</read-files>
|
|
244
|
+
|
|
245
|
+
<modified-files>
|
|
246
|
+
[One path per line, leave empty if none]
|
|
247
|
+
</modified-files>
|
|
248
|
+
|
|
249
|
+
Conversation:
|
|
250
|
+
`,ms=`Merge the new conversation content above into <previous-summary>.
|
|
251
|
+
|
|
252
|
+
Update the structured summary so another coding agent can continue the task immediately.
|
|
253
|
+
Keep only the information needed to continue the work.
|
|
254
|
+
|
|
255
|
+
You may remove:
|
|
256
|
+
- repetitive or superseded plans
|
|
257
|
+
- completed low-value steps
|
|
258
|
+
- outdated blockers
|
|
259
|
+
- noisy tool output details
|
|
260
|
+
|
|
261
|
+
You must preserve or update:
|
|
262
|
+
- the current goal
|
|
263
|
+
- user constraints and preferences
|
|
264
|
+
- current progress and unfinished work
|
|
265
|
+
- blockers that still matter
|
|
266
|
+
- next steps based on the latest state
|
|
267
|
+
- EXACT file paths, function names, and line numbers
|
|
268
|
+
- EXACT error messages, HTTP status codes, and exception types
|
|
269
|
+
- API endpoints, database tables, env vars, and config values
|
|
270
|
+
- key decisions WITH reasoning
|
|
271
|
+
|
|
272
|
+
CRITICAL: Every user REQUEST and DECISION must be preserved verbatim or near-verbatim.
|
|
273
|
+
|
|
274
|
+
Do not accumulate every past detail. Compress aggressively while keeping continuation-critical context.
|
|
275
|
+
|
|
276
|
+
First, wrap your analysis in <analysis> tags, then output the summary in <summary> tags.
|
|
277
|
+
|
|
278
|
+
Output format (strict markdown, inside <summary> tags):
|
|
279
|
+
|
|
280
|
+
## Goal
|
|
281
|
+
[Updated goal]
|
|
282
|
+
|
|
283
|
+
## Constraints & Preferences
|
|
284
|
+
- [Relevant constraints only]
|
|
285
|
+
|
|
286
|
+
## Progress
|
|
287
|
+
### Completed
|
|
288
|
+
- [x] [Completed work that still matters]
|
|
289
|
+
|
|
290
|
+
### In Progress
|
|
291
|
+
- [ ] [Active work in the latest state]
|
|
292
|
+
|
|
293
|
+
### Blockers
|
|
294
|
+
- [Current blockers, or "None"]
|
|
295
|
+
|
|
296
|
+
## Key Decisions
|
|
297
|
+
- **[Decision]**: [Short reason]
|
|
298
|
+
|
|
299
|
+
## Next Steps
|
|
300
|
+
1. [Most relevant next action]
|
|
301
|
+
|
|
302
|
+
## Key Context
|
|
303
|
+
- [Critical context needed to continue]
|
|
304
|
+
|
|
305
|
+
## Files & Changes
|
|
306
|
+
- **[exact path]**: [what was done and why]
|
|
307
|
+
|
|
308
|
+
---
|
|
309
|
+
|
|
310
|
+
<read-files>
|
|
311
|
+
[One path per line, leave empty if none]
|
|
312
|
+
</read-files>
|
|
313
|
+
|
|
314
|
+
<modified-files>
|
|
315
|
+
[One path per line, leave empty if none]
|
|
316
|
+
</modified-files>
|
|
317
|
+
|
|
318
|
+
Keep every section concise.`;async function fs(e){let t=e.tokensBefore-e.tokensAfter,o=Sr(e.artifactLedger,t),r=Math.min(Math.floor(t*Er.budgetRatio),Rr),n=Math.max(0,r-o.totalTokens),s=n>0?await Cr(e.artifactLedger,n):[],a={...o,fileMessages:s,totalTokens:o.totalTokens+Z(s)};if(a.totalTokens<=0)return{compacted:e.compacted,postCompactAttachmentsForLineage:[]};let c=_r(e.compacted,a),d=[...a.ledgerMessage?[a.ledgerMessage]:[],...a.fileMessages];return{compacted:c,postCompactAttachmentsForLineage:d}}i(fs,"applyPostCompactAttachments");function ge(){return{lowSavingsStreak:0,cooldownTurnsRemaining:0}}i(ge,"createCompactionAntiThrashState");function ps(e){return(e?.cooldownTurnsRemaining??0)>0}i(ps,"shouldSkipLlmCompaction");function hs(e){let t=e??ge();return{lowSavingsStreak:t.lowSavingsStreak,cooldownTurnsRemaining:Math.max(0,t.cooldownTurnsRemaining-1)}}i(hs,"consumeCompactionCooldown");function gs(e,t,o={}){let r=e??ge(),n=o.lowSavingsRatio??.1,s=o.lowSavingsStreakLimit??2,a=o.cooldownTurns??2,c=tu(t);if(!(c<n))return{state:ge(),savingsRatio:c,lowSavings:!1,enteredCooldown:!1};let u=r.lowSavingsStreak+1;return u>=s?{state:{lowSavingsStreak:0,cooldownTurnsRemaining:Math.max(1,a)},savingsRatio:c,lowSavings:!0,enteredCooldown:!0}:{state:{lowSavingsStreak:u,cooldownTurnsRemaining:r.cooldownTurnsRemaining},savingsRatio:c,lowSavings:!0,enteredCooldown:!1}}i(gs,"recordCompactionSavings");function tu(e){return e.tokensBefore<=0?0:Math.max(0,e.tokensBefore-e.tokensAfter)/e.tokensBefore}i(tu,"computeSavingsRatio");var ou=3;async function ru(e){let t=e.circuitBreakerLimit??ou,o=e.compactConsecutiveFailures>=t,r=e.compactionAntiThrash??ge();if(!e.needsCompact||o)return{compacted:e.messages,compactionUpdate:void 0,didCompactMessages:!1,nextCompactConsecutiveFailures:e.compactConsecutiveFailures,nextCompactionAntiThrash:r};if(ps(r)){let u=hs(r);return e.emitCompactionDiagnostics&&e.events.onContextCompactionSkipped?.({reason:"low_savings_cooldown",currentTokens:e.currentTokens,contextWindow:e.contextWindow,triggerPercent:e.compactionConfig.triggerPercent,cooldownTurnsRemaining:u.cooldownTurnsRemaining,lowSavingsStreak:u.lowSavingsStreak}),{compacted:e.messages,compactionUpdate:void 0,didCompactMessages:!1,nextCompactConsecutiveFailures:e.compactConsecutiveFailures,nextCompactionAntiThrash:u}}let n=e.messages,s,a=!1,c=e.compactConsecutiveFailures,d=r;e.events.onCompactStart?.();try{let u=await Mr(e.messages,e.compactionConfig,e.provider,e.contextWindow,void 0,e.systemPrompt,e.currentTokens,ds,ms,e.model);if(u.compacted){n=u.messages;let m=[];if(u.artifactLedger&&u.artifactLedger.length>0){let w=await fs({compacted:n,artifactLedger:u.artifactLedger,tokensBefore:u.tokensBefore,tokensAfter:u.tokensAfter});n=w.compacted,m=w.postCompactAttachmentsForLineage}a=!0;let l=e.contextWindow*(e.compactionConfig.triggerPercent/100),p=Z(n),y=gs(r,{tokensBefore:u.tokensBefore,tokensAfter:u.tokensAfter},e.compactionAntiThrashConfig);d=y.state,process.env.KODAX_DEBUG_COMPACTION&&E({source:"coding:compaction",level:"debug",message:"Compaction triggered.",detail:{contextWindow:e.contextWindow,triggerPercent:e.compactionConfig.triggerPercent,triggerTokens:Math.floor(l),tokensBefore:u.tokensBefore,tokensAfter:p,reduction:u.tokensBefore-p}}),y.enteredCooldown&&process.env.KODAX_DEBUG_COMPACTION&&E({source:"coding:compaction",level:"debug",message:"Compaction low-savings cooldown entered.",detail:{savingsRatio:y.savingsRatio,cooldownTurnsRemaining:y.state.cooldownTurnsRemaining}}),p<l?c=0:(c=e.compactConsecutiveFailures+1,process.env.KODAX_DEBUG_COMPACTION&&E({source:"coding:compaction",level:"debug",message:"Compaction partial success remained above trigger.",detail:{postCompactTokens:p,triggerTokens:Math.floor(l),attempt:c,limit:t}})),s={anchor:u.anchor,artifactLedger:u.artifactLedger,memorySeed:u.memorySeed,postCompactAttachments:m.length>0?m:void 0},e.events.onCompactStats?.({tokensBefore:u.tokensBefore,tokensAfter:p}),e.events.onCompact?.(u.tokensBefore)}else n=u.messages}catch(u){c=e.compactConsecutiveFailures+1,E({source:"coding:compaction",level:"error",message:`Compaction LLM summary failed (attempt ${c}/${t}).`,detail:u}),n=e.messages}finally{e.events.onCompactEnd?.()}return{compacted:n,compactionUpdate:s,didCompactMessages:a,nextCompactConsecutiveFailures:c,nextCompactionAntiThrash:d}}i(ru,"tryIntelligentCompact");function nu(e){if(!e.needsCompact)return{compacted:e.compacted,didCompactMessages:!1};let t=e.contextWindow*(e.compactionConfig.triggerPercent/100),o=e.compactionConfig.pruningGapRatio??.8;if(!(Z(e.compacted)>t*o))return{compacted:e.compacted,didCompactMessages:!1};let n=Or(e.compacted,e.contextWindow,e.compactionConfig);return n===e.compacted?{compacted:e.compacted,didCompactMessages:!1}:(e.events.onCompactStats?.({tokensBefore:e.currentTokens,tokensAfter:Z(n)}),e.events.onCompact?.(Z(n)),{compacted:n,didCompactMessages:!0})}i(nu,"applyGracefulDegradationGate");function iu(e){let t=Be(e.compacted);if(!e.didCompactMessages)return{messages:t,contextTokenSnapshot:void 0};let o=ut(t);return e.events.onCompactedMessages?.(t,e.compactionUpdate),{messages:t,contextTokenSnapshot:o}}i(iu,"commitCompactedHistory");async function ys(e){let t=await ru({messages:e.messages,needsCompact:e.needsCompact,compactConsecutiveFailures:e.compactConsecutiveFailures,compactionConfig:e.compactionConfig,provider:e.provider,model:e.model,contextWindow:e.contextWindow,systemPrompt:e.systemPrompt,currentTokens:e.currentTokens,events:e.events,compactionAntiThrash:e.compactionAntiThrash,compactionAntiThrashConfig:e.compactionAntiThrashConfig,emitCompactionDiagnostics:e.emitCompactionDiagnostics,circuitBreakerLimit:e.circuitBreakerLimit}),o=nu({compacted:t.compacted,needsCompact:e.needsCompact,contextWindow:e.contextWindow,compactionConfig:e.compactionConfig,currentTokens:e.currentTokens,events:e.events}),r=t.didCompactMessages||o.didCompactMessages,n=iu({compacted:o.compacted,didCompactMessages:r,compactionUpdate:t.compactionUpdate,events:e.events});return{messages:n.messages,compactionUpdate:t.compactionUpdate,didCompactMessages:r,nextCompactConsecutiveFailures:t.nextCompactConsecutiveFailures,nextCompactionAntiThrash:t.nextCompactionAntiThrash,contextTokenSnapshot:n.contextTokenSnapshot}}i(ys,"runCompactionLifecycle");function Ts(e){let{result:t,messages:o,maxTokensRetryCount:r,completedTurnTokenSnapshot:n,events:s}=e;if(ke(t.stopReason)!=="truncated"||t.toolBlocks.length!==0)return{outcome:"no_op",nextMaxTokensRetryCount:r};let a=r+1;if(a<=3){s.onTextDelta?.(`
|
|
319
|
+
|
|
320
|
+
[output token limit hit, continuing\u2026]
|
|
321
|
+
|
|
322
|
+
`),o.push({role:"user",content:[{type:"text",text:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."}],_synthetic:!0});let c=M(o,n);return{outcome:"continue",nextMaxTokensRetryCount:a,nextContextTokenSnapshot:c}}return s.onRetry?.(`max_tokens truncation limit reached (${a-1}/${3})`,a-1,3),{outcome:"exhausted",nextMaxTokensRetryCount:a}}i(Ts,"maybeContinueAfterMaxTokens");function bs(e){let{result:t,lastText:o,messages:r,continueAttempted:n,options:s,emittedManagedProtocolPayload:a,completedTurnTokenSnapshot:c}=e,d=s.context?.managedProtocolEmission;if(n||ke(t.stopReason)!=="end"||t.toolBlocks.length!==0||!o||!d?.enabled||d.optional)return{outcome:"no_op",nextContinueAttempted:n};let u=d.role,m=Zr(u);return!m||Jr(a,u)||en(o,m)?{outcome:"no_op",nextContinueAttempted:n}:(r.push({role:"user",content:[{type:"text",text:`Your response is complete but the required protocol was not emitted. Do NOT output any text \u2014 ONLY call the "${Vr}" tool now, or append a \`\`\`${m}\`\`\` fenced block. No other output.`}],_synthetic:!0}),{outcome:"continue",nextContinueAttempted:!0,nextContextTokenSnapshot:M(r,c)})}i(bs,"maybeAutoContinueManagedProtocol");import{exec as cu}from"child_process";import lu from"path";import{promisify as uu}from"util";function su(e){let t=new Map;if(!e)return t;for(let[o,r]of Object.entries(e))t.set(o,new Map(Object.entries(r)));return t}i(su,"createRuntimeExtensionState");function au(e){let t={};for(let[o,r]of e.entries())r.size!==0&&(t[o]=Object.fromEntries(r.entries()));return Object.keys(t).length>0?t:void 0}i(au,"snapshotRuntimeExtensionState");function Ot(e,t={}){let o=t.includeUnchanged??!0,r=au(e.extensionState),n=o||e.extensionStateDirty?r??(e.extensionStateDirty?{}:void 0):void 0,a=o&&e.extensionRecords.length>0||e.extensionRecordsDirty?e.extensionRecords.map(c=>({...c})):void 0;if(!(!n&&!a))return{...n?{extensionState:n}:{},...a?{extensionRecords:a}:{}}}i(Ot,"snapshotRuntimeSessionState");function xs(e,t){let o=e.get(t);if(o)return o;let r=new Map;return e.set(t,r),r}i(xs,"getExtensionStateBucket");function vs(e){return{queuedMessages:[],extensionState:su(e.loadedExtensionState),extensionStateDirty:!1,extensionRecords:e.loadedExtensionRecords?.map(t=>({...t}))??[],extensionRecordsDirty:!1,activeTools:e.activeTools,editRecoveryAttempts:new Map,blockedEditWrites:new Set,modelSelection:e.modelSelection,thinkingLevel:e.thinkingLevel}}i(vs,"buildRuntimeSessionState");function Do(e){return typeof e=="string"?{role:"user",content:e}:e}i(Do,"normalizeQueuedRuntimeMessage");function Lo(e){let t={};return e.provider?.trim()&&(t.provider=e.provider.trim()),e.model?.trim()&&(t.model=e.model.trim()),t}i(Lo,"normalizeRuntimeModelSelection");function ks(){return`extrec_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}i(ks,"createSessionRecordId");var du=uu(cu);async function mu(e){try{let{stdout:t}=await du("git rev-parse --show-toplevel",{cwd:e});return t.trim()}catch{return null}}i(mu,"getGitRoot");function fu(e){if(!(!e||!e.trim()))return lu.resolve(e).replace(/\\/g,"/")}i(fu,"normalizeSnapshotPath");function pu(e,t){return{...e?{canonicalRepoRoot:e,workspaceRoot:e}:{},executionCwd:t,workspaceKind:"detected"}}i(pu,"buildSnapshotRuntimeInfo");var ws=new Set;function qg(e){return Object.defineProperty(e,"__startKodaXGeneratedId",{value:!0,enumerable:!1}),e}i(qg,"markStartKodaXGeneratedSessionId");function hu(e){return e?.__startKodaXGeneratedId===!0}i(hu,"hasStartKodaXGeneratedSessionId");function Rs(e){return Array.isArray(e.content)?e.content:[]}i(Rs,"contentBlocks");function gu(e){return Rs(e).filter(t=>t.type==="tool_use").map(t=>t.id)}i(gu,"collectToolUseIds");function yu(e){return Rs(e).filter(t=>t.type==="tool_result").map(t=>t.tool_use_id)}i(yu,"collectToolResultIds");function Tu(e){let t=e.find(r=>r.role!=="system");if(!t)return e.length===0;if(t.role!=="user")return!1;let o=new Set;for(let r of e){if(r.role==="assistant"){for(let n of gu(r))o.add(n);continue}if(r.role==="user"){for(let n of yu(r))if(!o.delete(n))return!1}}return o.size===0}i(Tu,"isSafeAuthoritativeTranscript");async function ye(e,t,o){if(e.session?.persistedByHost&&!o.errorMetadata)return;if(!e.session?.storage){e.session?.id&&!hu(e.session)&&!ws.has(e.session.id)&&(ws.add(e.session.id),E({source:"coding:session-snapshot",level:"warn",message:`[KodaX SDK] session.id="${e.session.id}" was provided but session.storage is undefined \u2014 session snapshots will NOT be persisted. To persist, pass a storage instance: import { createSessionManager } from '@kodax-ai/kodax/session'; const { storage } = createSessionManager(); runKodaX({ session: { id, storage, ... }, ... }, prompt); See docs/SDK_EMBEDDER_GUIDE.md \xA76.`}));return}let r=o.messages,n,s,a,c=!0;if(o.errorMetadata&&!Tu(o.messages)){c=!1;try{let p=await e.session.storage.load(t);p?(r=p.messages,n=p.lineage,s=p.extensionState?structuredClone(p.extensionState):void 0,a=p.extensionRecords?.map(y=>({...y}))):(r=[],n=void 0,s=void 0,a=void 0)}catch{r=[],n=void 0,s=void 0,a=void 0}}let d=fu(e.context?.executionCwd??e.context?.gitRoot??process.cwd())??process.cwd().replace(/\\/g,"/"),u=o.gitRoot??e.context?.gitRoot??await mu(d)??"",m=pu(u,d),l=o.runtimeSessionState?Ot(o.runtimeSessionState):void 0;c&&(s=l?.extensionState,a=l?.extensionRecords);try{await e.session.storage.save(t,{messages:r,title:o.title,gitRoot:u,runtimeInfo:m,tag:e.session.tag,scope:e.session.scope??"user",errorMetadata:o.errorMetadata,...n!==void 0?{lineage:n}:{},extensionState:s,extensionRecords:a})}catch(p){E({source:"coding:session-snapshot",level:"error",message:"storage.save failed; continuing without snapshot persistence.",detail:p})}}i(ye,"saveSessionSnapshot");async function Nt(e){await ye(e.options,e.sessionId,{messages:e.messages,title:e.title,gitRoot:e.options.context?.gitRoot??void 0,runtimeSessionState:e.runtimeSessionState});let[t,o]=Ge(e.lastText);return{finalSignal:t,finalReason:o}}i(Nt,"applyIterationLimitTerminal");async function Es(e){let t=zt(e.messages);t=Be(t);let o={lastError:e.error.message,lastErrorTime:Date.now(),consecutiveErrors:(e.errorMetadata?.consecutiveErrors??0)+1};await ye(e.options,e.sessionId,{messages:t,title:e.title,gitRoot:e.options.context?.gitRoot??void 0,errorMetadata:o,runtimeSessionState:e.runtimeSessionState});let r=ut(t);return{cleanedMessages:t,updatedErrorMetadata:o,contextTokenSnapshot:r}}i(Es,"runCatchCleanup");async function Ss(e){Se(e.events),await e.emitActiveExtensionEvent("stream:end",void 0)}i(Ss,"applyAbortErrorTerminal");async function _s(e){await e.emitActiveExtensionEvent("error",{error:e.error}),dn(e.events,e.error)}i(_s,"applyGenericErrorTerminal");async function Cs(e){let t={...e};return await fe("provider:before",{provider:t.provider,model:t.model,reasoningMode:t.reasoningMode,systemPrompt:t.systemPrompt,block:i(o=>{t.blockedReason=o},"block"),replaceProvider:i(o=>{t.provider=o},"replaceProvider"),replaceModel:i(o=>{t.model=o},"replaceModel"),replaceSystemPrompt:i(o=>{t.systemPrompt=o},"replaceSystemPrompt"),setThinkingLevel:i(o=>{t.reasoningMode=o},"setThinkingLevel")}),t}i(Cs,"applyProviderPrepareHook");function Ms(e){return e.toLowerCase().replace(/[\s_-]+/g,"")}i(Ms,"normalizeToolNameKey");function bu(e,t){if(t.includes(e))return null;let o=Ms(e);if(!o)return null;let r=t.filter(n=>Ms(n)===o);return r.length===1?r[0]:null}i(bu,"resolveToolNameAlias");function As(e,t){return e.map(o=>{let r=bu(o.name,t);return r?(process.env.KODAX_DEBUG_TOOL_STREAM&&E({source:"coding:tool-name-repair",level:"debug",message:"Tool name repaired.",detail:{from:o.name,to:r}}),{...o,name:r}):o})}i(As,"repairToolBlockNames");function Ve(e,t){return t.queuedMessages.length===0?!1:(e.push(...t.queuedMessages.splice(0)),!0)}i(Ve,"appendQueuedRuntimeMessages");async function Qe(e,t,o,r){await fe("turn:settle",{sessionId:e,lastText:t,hadToolCalls:r.hadToolCalls,success:r.success,signal:r.signal,queueUserMessage:i(n=>{o.queuedMessages.push(Do(n))},"queueUserMessage"),setModelSelection:i(n=>{o.modelSelection=Lo(n)},"setModelSelection"),setThinkingLevel:i(n=>{o.thinkingLevel=n},"setThinkingLevel")})}i(Qe,"settleExtensionTurn");function dy(e){return async t=>{let o=e();return o?await fe("turn:complete",{sessionId:o,lastAssistantText:t.lastAssistantText,signal:t.signal,reanimateCount:t.reanimateCount,reanimateBudget:t.reanimateBudget})??void 0:void 0}}i(dy,"createExtensionTurnCompleteStopHook");function Ps(e){return{queueUserMessage:i(t=>{e.queuedMessages.push(Do(t))},"queueUserMessage"),getSessionState:i((t,o)=>e.extensionState.get(t)?.get(o),"getSessionState"),setSessionState:i((t,o,r)=>{let n=xs(e.extensionState,t);if(e.extensionStateDirty=!0,r===void 0){n.delete(o),n.size===0&&e.extensionState.delete(t);return}n.set(o,r)},"setSessionState"),getSessionStateSnapshot:i(t=>Object.fromEntries((e.extensionState.get(t)??new Map).entries()),"getSessionStateSnapshot"),appendSessionRecord:i((t,o,r,n)=>{let s=o.trim(),a=n?.dedupeKey?.trim()||void 0,c={id:ks(),extensionId:t,type:s,ts:Date.now(),...r===void 0?{}:{data:r},...a?{dedupeKey:a}:{}};if(a){let d=e.extensionRecords.findIndex(u=>u.extensionId===t&&u.type===s&&u.dedupeKey===a);if(d>=0)return e.extensionRecords.splice(d,1,c),e.extensionRecordsDirty=!0,c}return e.extensionRecords.push(c),e.extensionRecordsDirty=!0,c},"appendSessionRecord"),listSessionRecords:i((t,o)=>e.extensionRecords.filter(r=>r.extensionId===t&&(o===void 0||r.type===o)).map(r=>({...r})),"listSessionRecords"),clearSessionRecords:i((t,o)=>{let r=e.extensionRecords.length;e.extensionRecords=e.extensionRecords.filter(s=>s.extensionId!==t||o!==void 0&&s.type!==o);let n=r-e.extensionRecords.length;return n>0&&(e.extensionRecordsDirty=!0),n},"clearSessionRecords"),getActiveTools:i(()=>[...e.activeTools],"getActiveTools"),setActiveTools:i(t=>{e.activeTools=Array.from(new Set(t.map(o=>o.trim()).filter(Boolean)))},"setActiveTools"),getModelSelection:i(()=>({...e.modelSelection}),"getModelSelection"),setModelSelection:i(t=>{e.modelSelection=Lo(t)},"setModelSelection"),getThinkingLevel:i(()=>e.thinkingLevel,"getThinkingLevel"),setThinkingLevel:i(t=>{e.thinkingLevel=t},"setThinkingLevel")}}i(Ps,"createExtensionRuntimeSessionController");async function Is(e){e.messages.push({role:"user",content:[...e.toolResults]}),e.editRecoveryMessages.length>0&&e.messages.push({role:"user",content:e.editRecoveryMessages.join(`
|
|
323
|
+
|
|
324
|
+
`),_synthetic:!0});let t=M(e.messages,e.completedTurnTokenSnapshot);await Qe(e.sessionId,e.lastText,e.runtimeSessionState,{hadToolCalls:!0,success:!0});let o=Ve(e.messages,e.runtimeSessionState);return o&&(t=M(e.messages,t),await e.emitActiveExtensionEvent("turn:end",{sessionId:e.sessionId,iteration:e.iter+1,lastText:e.lastText,hadToolCalls:!0,signal:void 0})),{contextTokenSnapshot:t,drainedQueuedMessages:o}}i(Is,"pushToolResultsAndSettle");function xu(e){return e?me(e)??e:void 0}i(xu,"legacyReasoningModeToRuntimeEffort");async function Os(e,t){let o=bn(),r=e.extensionRuntime??o,n=e.extensionRuntime instanceof Tn?e.extensionRuntime:void 0,s=!!n&&n!==o;s&&n&&oo(n);let a=xn(r),c;try{let d=e.maxIter??200,u=e.events??{},m=r?.getDefaults?.(),l={preAnswerJudgeConsumed:!1,postToolJudgeConsumed:!1,maxTokensRetryCount:0,costTracker:lr(),managedProtocolContinueAttempted:!1,compactConsecutiveFailures:0,compactAntiThrash:ge(),lastText:"",currentProviderName:m?.modelSelection.provider??e.provider,currentModelOverride:m?.modelSelection.model??e.modelOverride??e.model,runtimeThinkingLevel:m?.thinkingLevel},p=we(l.currentProviderName);yo(p,l.currentProviderName);let y=p.getEffectiveContextWindow?.(l.currentModelOverride)??p.getContextWindow(),w=await An(y,e.compaction),f=await qn(e)??await Vt(),U=e.context?.liveTurn,R=nn({sessionId:f,deliveryKind:U?.deliveryKind??"initial",turnId:U?.turnId,deliveryId:U?.deliveryId,promptId:U?.promptId});u=sn(u,R),e={...e,events:u};let O=await $n(e,f),h=jn(O.messages,t,e.context?.inputArtifacts,R.turnId),N=O.title||t.slice(0,50)+(t.length>50?"...":""),ae=O.errorMetadata,B=O.loadedExtensionState,A=O.loadedExtensionRecords,D=j(e.context),V={current:e.context?.managedProtocolEmission?.enabled?eo(void 0,void 0):void 0},Ae=yn({options:e,sessionId:f,runtime:r??void 0,managedProtocolPayloadRef:V}),T=M(h,e.context?.contextTokenSnapshot),b=vs({loadedExtensionState:B,loadedExtensionRecords:A,activeTools:es(Ji(m?.activeTools??ht().map(g=>g.name),e.context?.excludeTools),e.context?.toolVisibilityPolicy),modelSelection:{provider:l.currentProviderName,model:l.currentModelOverride},thinkingLevel:l.runtimeThinkingLevel}),W=!1,Ze=i(g=>{W||(W=!0,cn(u,R,g))},"emitLiveTurnCompletedOnce"),Fo=i(g=>{W||(W=!0,ln(u,R,g))},"emitLiveTurnFailedOnce"),G=i(g=>{g.success?Ze(g.interrupted?"interrupted":"completed"):Fo(new Error(g.errorMetadata?.lastError??"KodaX run failed"));let P=eo(g.managedProtocolPayload,V.current),X=Ot(b,{includeUnchanged:!1});return P||X?{...g,...P?{managedProtocolPayload:P}:{},...X?{runtimeSessionSnapshot:X}:{}}:g},"finalizeManagedProtocolResult");e.sessionControl?._attach({setProvider:i(g=>{b.modelSelection.provider=g},"setProvider"),setModel:i(g=>{b.modelSelection.model=g},"setModel"),setReasoning:i(g=>{b.thinkingLevel=xu(g)},"setReasoning")});let Uo=r?.bindController?.(Ps(b));c=typeof Uo=="function"?Uo:void 0;let $s=Re(e.context?.repoIntelligenceMode),js=ct(e.context?.repoIntelligenceMode),qs=e.context?.repoRoutingSignals?Promise.resolve(e.context.repoRoutingSignals):$s!=="off"&&(e.context?.executionCwd||e.context?.gitRoot)?Wr({executionCwd:D,gitRoot:e.context?.gitRoot??void 0},{mode:js}).catch(()=>null):Promise.resolve(null),[,Je]=await Promise.all([r?.hydrateSession?.(f),qs]);Ke(u,e,"routing",Je,Je?.activeModuleId?`active_module=${Je.activeModuleId}`:void 0);let et=await ci({...e,provider:l.currentProviderName,modelOverride:l.currentModelOverride},t,p,{recentMessages:h.slice(0,-1),sessionErrorMetadata:ae,repoSignals:Je??void 0}),Te=await At({...e,provider:l.currentProviderName,modelOverride:l.currentModelOverride,effort:l.runtimeThinkingLevel??e.effort},l.runtimeThinkingLevel?{...et,effort:l.runtimeThinkingLevel}:et,h.length===1),Bo=0,ee=i((g,P)=>(T=pn(u,{iter:g,maxIter:d,messages:h,currentSnapshot:T,snapshotOverride:P}),T),"emitIterationEnd"),K=i(()=>et.decision,"currentRoutingDecision");un(u,{provider:p.name,sessionId:f}),await x("session:start",{provider:p.name,sessionId:f}),an(u,R),u.getCostReport&&(u.getCostReport.current=()=>fr(mr(l.costTracker)));for(let g=0;g<d;g++)try{let P=di(b,e,w);l.currentProviderName=P.providerName,l.currentModelOverride=P.modelOverride,l.runtimeThinkingLevel=P.thinkingLevel;let X=P.provider,te=P.contextWindow,Pe=await _i({options:e,providerName:l.currentProviderName,modelOverride:l.currentModelOverride,thinkingLevel:l.runtimeThinkingLevel,reasoningPlan:et,messages:h}),ce=Pe.effectiveReasoningPlan;Te=Pe.currentExecution,await x("turn:start",{sessionId:f,iteration:g+1,maxIter:d}),fn(u,g,d),h=Pr(h,Ar);let $o=to(h,T),Ws=Ir({messages:h,compactionConfig:w,contextWindow:te,currentTokens:$o}),Ie=await ys({messages:h,needsCompact:Ws,compactConsecutiveFailures:l.compactConsecutiveFailures,compactionConfig:w,provider:X,model:l.currentModelOverride,contextWindow:te,systemPrompt:Te.systemPrompt,currentTokens:$o,events:u,compactionAntiThrash:l.compactAntiThrash,emitCompactionDiagnostics:e.context?.contextDiagnostics===!0});h=Ie.messages,l.compactConsecutiveFailures=Ie.nextCompactConsecutiveFailures,l.compactAntiThrash=Ie.nextCompactionAntiThrash,Ie.contextTokenSnapshot!==void 0&&(T=Ie.contextTokenSnapshot);let be=await Cs({provider:l.currentProviderName,model:l.currentModelOverride,reasoningMode:ce.effort,systemPrompt:Te.systemPrompt});if(be.blockedReason)throw new Error(be.blockedReason);l.currentProviderName=be.provider,l.currentModelOverride=be.model,b.modelSelection.provider=l.currentProviderName,b.modelSelection.model=l.currentModelOverride,l.runtimeThinkingLevel=be.reasoningMode,b.thinkingLevel=l.runtimeThinkingLevel;let Y=we(l.currentProviderName),le=l.runtimeThinkingLevel??ce.effort,Dt=l.currentModelOverride??Y.getModel(),Lt=xr(l.currentProviderName,Dt);if(le!==void 0&&Lt.length>0){let k=Kt({provider:l.currentProviderName,model:Dt,desiredEffort:le}).effort;k!==void 0&&Lt.includes(k)&&(le=Kt({provider:l.currentProviderName,model:Dt,desiredEffort:le,rejectedEfforts:Lt}).effort??"none")}let jo={...Te.providerReasoning,enabled:le!=="none",effort:le},{effectiveSystemPrompt:Oe}=Mi({providerName:l.currentProviderName,model:l.currentModelOverride,provider:Y,prompt:t,effectiveOptions:Te.effectiveOptions,reasoningMode:ir(le)??"auto",taskType:ce.decision.primaryTask,executionMode:ce.decision.recommendedMode,baseSystemPrompt:be.systemPrompt});pr(Te.effectiveOptions.context?.inputArtifacts??[],{provider:l.currentProviderName,model:l.currentModelOverride}),yo(Y,l.currentProviderName),await x("provider:selected",{provider:l.currentProviderName,model:l.currentModelOverride});let tt=new Pt,qo=tt.tracker,{resilienceCfg:ot,recoveryCoordinator:Ft}=Ii(l.currentProviderName,Y,qo,e.timeouts),Wo=ot.requestTimeoutMs,Gs=ot.streamIdleTimeoutMs,L=h,v,oe=0,Go=vn(Ae),rt=ts(b.activeTools,e.context?.repoIntelligenceMode,e.context?.managedProtocolEmission?.enabled===!0,!!r,e.context?.toolConstructionMode,Go,e.selfManual?.productName),Ko=is({sessionId:f,turnId:R.turnId,provider:l.currentProviderName,model:l.currentModelOverride??Y.getModel(),profile:"report_only",contextWindow:te,systemPrompt:Oe,toolDefinitions:rt,skillCatalogText:e.context?.skillsPrompt,messages:L}),Xo=as(Ko),Yo={...Ko,profile:Xo},zo=us({tools:rt,budget:Yo,profile:Xo,bridgeAvailable:cs(rt),nativeDeferredAvailable:!1,unlockedDeferredTools:Go}),Vo=ls(rt,zo);for(e.context?.contextDiagnostics===!0&&(u.onContextBudgetSnapshot!==void 0||u.onToolExposurePlanned!==void 0)&&(u.onContextBudgetSnapshot?.(Yo),u.onToolExposurePlanned?.(zo));;){oe+=1,tt.beginAttempt(l.currentProviderName,l.currentModelOverride??Y.getModel(),L,oe,!1);let k=Ci({hardTimeoutMs:Wo,idleTimeoutMs:Gs,streamMaxDurationMs:Y.getStreamMaxDurationMs?.(l.currentModelOverride)??0,callerAbortSignal:e.abortSignal}),z=k.retryTimeoutController,Ne=k.retrySignal,$u=k.resetIdleTimer,or=Rt(L,Oe);I("[resilience:request]",{provider:l.currentProviderName,attempt:oe,fallbackActive:!1,payloadBytes:or,payloadBucket:Et(or),lastToolErrorCode:b.lastToolErrorCode,lastToolResultBytes:b.lastToolResultBytes});try{let ve=Ai({events:u,boundaryTracker:qo,streamTimers:k,emitActiveExtensionEvent:x,providerName:l.currentProviderName}),ue=i(de=>{l.costTracker=ur(l.costTracker,{provider:de.provider,waitMs:de.waitMs,reason:de.reason,source:de.source}),ve.onRetryAfter?.(de)},"wrappedRetryAfter");v=await Y.stream(L,Vo,Oe,jo,{...ve,onRetryAfter:ue,modelOverride:l.currentModelOverride,signal:Ne},Ne),h=L;break}catch(ve){let ue=ve instanceof Error?ve:new Error(String(ve));ue=await Oi(ue,z,e.abortSignal);let de=tt.inferFailureStage(),{decision:Q}=Ni({error:ue,failureStage:de,attempt:oe,events:u,resilienceCfg:ot,recoveryCoordinator:Ft});if(Q.shouldUseNonStreaming){let De=Rt(L,Oe);I("[resilience:fallback]",{provider:l.currentProviderName,attempt:oe,payloadBytes:De,payloadBucket:Et(De)});let jt=await Di({events:u,streamProvider:Y,providerMessages:L,activeToolDefinitions:Vo,effectiveSystemPrompt:Oe,effectiveProviderReasoning:jo,callerAbortSignal:e.abortSignal,modelOverride:l.currentModelOverride,hardTimeoutMs:Wo,boundarySession:tt,emitActiveExtensionEvent:x,providerName:l.currentProviderName,attempt:oe,clearStreamTimers:k.clearAll});if(jt.ok){v=jt.result,h=L;break}ue=jt.error}if(Q.action==="sanitize_thinking_and_retry"){let De=Ft.executeRecovery(L,Q);bt(Q.action,De),L=De.messages,k.clearAll(),oe-=1,await no(Q.delayMs,e.abortSignal);continue}if(Q.action==="manual_continue"||oe>=ot.maxRetries)throw h=L,ue;let rr=Ft.executeRecovery(L,Q);bt(Q.action,rr),L=rr.messages,k.clearAll(),await no(Q.delayMs,e.abortSignal);continue}finally{k.clearAll()}}Se(u),await x("stream:end",void 0),v.usage&&(l.costTracker=dr(l.costTracker,{provider:l.currentProviderName,model:l.currentModelOverride??"unknown",inputTokens:v.usage.inputTokens,outputTokens:v.usage.outputTokens,cacheReadTokens:v.usage.cachedReadTokens,cacheWriteTokens:v.usage.cachedWriteTokens})),l.lastText=v.textBlocks.map(k=>k.text).join(" ");let Ut=on(h,v.usage),Qo=Oo(b.activeTools,e.context?.repoIntelligenceMode,!!r,e.context?.toolConstructionMode);v={...v,toolBlocks:As(v.toolBlocks,Qo)};let Ks=v.toolBlocks.filter(k=>J(k.name)),[nt,Bu]=Ge(l.lastText);if(nt){if(await Qe(f,l.lastText,b,{hadToolCalls:!1,success:!0,signal:nt}),Ve(h,b)){T=M(h,Ut),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!1,signal:nt});continue}if(nt==="COMPLETE")return ee(g+1,Ut),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!1,signal:"COMPLETE"}),Ze("completed"),dt(u),await x("complete",{success:!0,signal:"COMPLETE"}),G({success:!0,lastText:l.lastText,signal:"COMPLETE",messages:h,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,limitReached:!1})}let Xs=Li([...v.thinkingBlocks,...v.textBlocks,...Ks]);h.push({role:"assistant",content:Xs,turnId:R.turnId,timestamp:new Date().toISOString()});let H=tn(h,v.usage);T=H;let Bt=Ts({result:v,messages:h,maxTokensRetryCount:l.maxTokensRetryCount,completedTurnTokenSnapshot:H,events:u});if(l.maxTokensRetryCount=Bt.nextMaxTokensRetryCount,Bt.outcome==="continue"){T=Bt.nextContextTokenSnapshot;continue}let Ht=bs({result:v,lastText:l.lastText,messages:h,continueAttempted:l.managedProtocolContinueAttempted,options:e,emittedManagedProtocolPayload:V.current,completedTurnTokenSnapshot:H});if(l.managedProtocolContinueAttempted=Ht.nextContinueAttempted,Ht.outcome==="continue"){T=Ht.nextContextTokenSnapshot;continue}let Zo=ke(v.stopReason);if(Zo==="refused"?u.onTextDelta?.(`
|
|
325
|
+
|
|
326
|
+
[model declined to answer]
|
|
327
|
+
|
|
328
|
+
`):Zo==="unknown"&&typeof v.stopReason=="string"&&E({source:"coding:stop-reason",level:"warn",message:"Provider returned an unknown stop reason.",detail:{rawStopReason:v.stopReason,provider:l.currentProviderName,model:l.currentModelOverride??Y.getModel(),hasToolBlocks:v.toolBlocks.length>0,hasTextBlocks:v.textBlocks.length>0}}),v.toolBlocks.length===0){if(await Qe(f,l.lastText,b,{hadToolCalls:!1,success:!0}),Ve(h,b)){T=M(h,H),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!1,signal:void 0});continue}if(Ee(u))return ee(g+1,H),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!1,signal:void 0}),G({success:!0,lastText:l.lastText,messages:h,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,limitReached:!1});ee(g+1,H),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!1,signal:void 0}),Ze("completed"),dt(u),await x("complete",{success:!0,signal:void 0});{let z=await Nt({options:e,sessionId:f,messages:h,title:N,runtimeSessionState:b,lastText:l.lastText});return G({success:!0,lastText:l.lastText,signal:z.finalSignal,signalReason:z.finalReason,messages:h,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,limitReached:!1})}}let $t=await zi({toolBlocks:v.toolBlocks,events:u,emitActiveExtensionEvent:x,messages:h,incompleteRetryCount:Bo,preAssistantTokenSnapshot:Ut,completedTurnTokenSnapshot:H});if(Bo=$t.nextIncompleteRetryCount,T=$t.nextContextTokenSnapshot,$t.outcome!=="no_incomplete")continue;let xe=[],Jo=[],er=await Vi({toolBlocks:v.toolBlocks,abortSignal:e.abortSignal,events:u,emitActiveExtensionEvent:x});if(er!==null)xe.push(...er);else{let k=Kr({contextWindow:te,currentTokens:to(h,T)}),z=await Xi({toolBlocks:v.toolBlocks,events:u,ctx:Ae,runtimeSessionState:b,activeToolNames:Qo,abortSignal:e.abortSignal,toolResultBudget:k}),Ne=await Yi({toolBlocks:v.toolBlocks,resultMap:z,events:u,emitActiveExtensionEvent:x,ctx:Ae,runtimeSessionState:b});xe=Ne.toolResults,Jo=Ne.editRecoveryMessages}let Ys=Qi(xe);if(xe.length===0){if(await Qe(f,l.lastText,b,{hadToolCalls:!1,success:!0}),Ve(h,b)){T=M(h,H),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!1,signal:void 0});continue}if(Ee(u))return ee(g+1,H),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!1,signal:void 0}),G({success:!0,lastText:l.lastText,messages:h,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,limitReached:!1});ee(g+1,H),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!1,signal:void 0}),Ze("completed"),dt(u),await x("complete",{success:!0,signal:void 0});{let z=await Nt({options:e,sessionId:f,messages:h,title:N,runtimeSessionState:b,lastText:l.lastText});return G({success:!0,lastText:l.lastText,signal:z.finalSignal,signalReason:z.finalReason,messages:h,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,limitReached:!1})}}if(Ys){let k=await Zi({events:u,emitActiveExtensionEvent:x,messages:h,toolResults:xe,completedTurnTokenSnapshot:H,sessionId:f,iter:g,emitIterationEnd:ee});return T=k.contextTokenSnapshot,G({success:!0,lastText:Io,messages:h,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,interrupted:!k.shouldYieldToQueuedFollowUp})}let tr=await Is({messages:h,toolResults:xe,editRecoveryMessages:Jo,completedTurnTokenSnapshot:H,runtimeSessionState:b,emitActiveExtensionEvent:x,sessionId:f,lastText:l.lastText,iter:g});if(T=tr.contextTokenSnapshot,tr.drainedQueuedMessages)continue;if(Ee(u))return ee(g+1,T),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!0,signal:void 0}),G({success:!0,lastText:l.lastText,messages:h,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,limitReached:!1});await ye(e,f,{messages:h,title:N,gitRoot:e.context?.gitRoot??void 0,runtimeSessionState:b}),ee(g+1,T),await x("turn:end",{sessionId:f,iteration:g+1,lastText:l.lastText,hadToolCalls:!0,signal:void 0})}catch(P){let X=P instanceof Error?P:new Error(String(P)),te=await Es({error:X,messages:h,errorMetadata:ae,options:e,sessionId:f,title:N,runtimeSessionState:b}),Pe=te.cleanedMessages,ce=te.updatedErrorMetadata;return T=te.contextTokenSnapshot,X.name==="AbortError"?(await Ss({events:u,emitActiveExtensionEvent:x}),G({success:!0,lastText:l.lastText,messages:Pe,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,interrupted:!0,errorMetadata:ce})):(Fo(X),await _s({error:X,events:u,emitActiveExtensionEvent:x}),G({success:!1,lastText:l.lastText,messages:Pe,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,errorMetadata:ce}))}let Ho=await Nt({options:e,sessionId:f,messages:h,title:N,runtimeSessionState:b,lastText:l.lastText});return G({success:!0,lastText:l.lastText,signal:Ho.finalSignal,signalReason:Ho.finalReason,messages:h,sessionId:f,routingDecision:K(),contextTokenSnapshot:T,limitReached:!0})}finally{c?.(),a(),s&&oo(o)}}i(Os,"runSubstrate");var Ds="kodax/coding/default",vu="KodaX default coding agent.\n\nThis agent is a thin declaration that routes through the built-in `runKodaX`\npipeline. Tools, extensions, reasoning, provider selection, session\npersistence, compaction and harness routing are all driven by the\n`KodaXOptions` forwarded via `Runner.run` `opts.presetOptions`.\n";function ku(e){if(typeof e=="string")return e;for(let t=e.length-1;t>=0;t--){let o=e[t];if(o?.role==="user")return Yt(o)||""}return""}i(ku,"extractPrompt");function Ns(e){let t=e.trim();return t===""||t==="..."}i(Ns,"isPlaceholderOnlyAssistantText");function wu(e){if(e.role!=="user")return!1;let t=e.content;return!Array.isArray(t)||t.length===0?!1:t.every(o=>!!o&&typeof o=="object"&&"type"in o&&o.type==="tool_result")}i(wu,"isPureToolResultUserMessage");function Ru(e){if(e.lastText&&!Ns(e.lastText))return e.lastText;for(let t=e.messages.length-1;t>=0;t--){let o=e.messages[t];if(o){if(o.role==="assistant"){let r=Yt(o);return r&&!Ns(r)?r:""}if(!wu(o))return""}}return""}i(Ru,"extractFinalAssistantText");var Eu=i(async(e,t,o,r)=>{let n=o?.presetOptions??{},s=o?.abortSignal?{...n,abortSignal:o.abortSignal}:n,a=ku(t),c=r?r.agentSpan.addChild("coding:runSubstrate",{kind:"generation",agentName:Ds,provider:s.provider??"unknown",model:s.model??"unknown"}):null,d;try{d=await Os(s,a)}catch(l){throw c&&(c.setError(l instanceof Error?l:new Error(String(l))),c.end()),l}return c&&c.end(),{output:Ru(d),messages:d.messages,sessionId:d.sessionId,data:d}},"codingSubstrate"),Su=Object.freeze([Object.freeze({name:"autoReroute",enabled:!0}),Object.freeze({name:"mutationReflection",enabled:!0}),Object.freeze({name:"preAnswerJudge",enabled:!0}),Object.freeze({name:"postToolJudge",enabled:!0})]),_u=Object.freeze({default:"balanced",max:"deep",escalateOnRevise:!0});function Ls(e={}){return yr({name:Ds,instructions:vu,substrateExecutor:Eu,middleware:Su,reasoning:_u,...e})}i(Ls,"createDefaultCodingAgent");var Cu=/\b(forget|do not remember|don't remember|remove (?:this )?from memory|delete .{0,40}memory)\b/i,Mu=/(?:\u522b\u8bb0|\u4e0d\u8981\u8bb0\u4f4f|\u5fd8\u8bb0|\u5220\u9664.{0,12}\u8bb0\u5fc6|\u4e0d\u8981\u518d\u8bb0)/u,Au=/\b(remember this|please remember|save this to memory|add this to memory)\b/i,Pu=/(?:\u8bb0\u4f4f|\u4fdd\u5b58.{0,12}\u8bb0\u5fc6|\u52a0\u5165\u8bb0\u5fc6)/u,Iu=/\b(memory|remembered|remember|stored|previously saved|memo(?:ry)? note)\b/i,Ou=/\b(wrong|incorrect|outdated|actually|correction|correcting|not .{1,80} but|instead|should be)\b/i,Nu=/(?:\u8bb0\u5fc6|\u8bb0\u4f4f\u7684|\u4e4b\u524d\u8bb0\u7684)/u,Du=/(?:\u4e0d\u662f.{0,24}\u800c\u662f|\u7ea0\u6b63|\u66f4\u6b63|\u5176\u5b9e|\u5e94\u8be5\u662f|\u4e0d\u5bf9)/u;async function Fs(e){if(Bs(e))return;let t=j(e.context);try{let o=await He({cwd:t,projectDocs:[],discoverSkills:!1}).maybeRunAutoCurator();(o.ran||o.skippedReason!=="not_due")&&I("[memory:maintenance]",{cwd:t,ran:o.ran,skippedReason:o.skippedReason??null,reportPath:o.reportPath??null,nextEligibleAt:o.nextEligibleAt??null})}catch(o){I("[memory:maintenance:error]",{cwd:t,error:o instanceof Error?o.message:String(o)})}}i(Fs,"maybeRunMemoryMaintenanceWindow");async function Us(e,t){if(Bs(e))return;let o=e.memoryReviewer;if(o===void 0)return;let r=Lu(t);if(r===void 0)return;let n=j(e.context),s=e.context?.rawUserInput?.trim();try{let a=await He({cwd:n,projectDocs:[],discoverSkills:!1,memoryReviewer:o}).reviewMemoryFeedback({trigger:r,userFeedback:t,...s!==void 0&&s.length>0?{task:s}:{}});e.events?.onMemoryReview?.(a),I("[memory:review]",{cwd:n,trigger:r,actions:a.actions.length,candidates:a.candidateRefs.map(c=>c.ref.id)})}catch(a){I("[memory:review:error]",{cwd:n,error:a instanceof Error?a.message:String(a)})}}i(Us,"maybeReviewMemoryFeedbackFromPrompt");function Lu(e){let t=e.trim();if(t.length!==0){if(Cu.test(t)||Mu.test(t))return"explicit_forget";if(Au.test(t)||Pu.test(t))return"explicit_remember";if(Fu(t))return"user_correction"}}i(Lu,"detectMemoryReviewTrigger");function Fu(e){return Iu.test(e)&&Ou.test(e)||Nu.test(e)&&Du.test(e)}i(Fu,"isMemoryCorrection");function Bs(e){return e.context?.currentAgentId!==void 0||e.context?.parentAgentId!==void 0}i(Bs,"isInternalAgentRun");function Hs(e){return{...e.modelTiers!==void 0?{modelTiers:e.modelTiers}:{},...e.maxOutputTokens!==void 0?{maxOutputTokens:e.maxOutputTokens}:{},...e.disablePromptCache!==void 0?{disablePromptCache:e.disablePromptCache}:{},...e.lsp!==void 0?{lsp:e.lsp}:{},...e.workflow!==void 0?{workflow:e.workflow}:{}}}i(Hs,"deriveRunScopedConfig");async function DT(e,t){let{options:o}=ri(e,t),r=o.context?.agentProfile?.instructions,n=r!==void 0&&o.context?.systemPromptOverride===void 0?{...o,context:{...o.context,systemPromptOverride:r}}:o;return ar(Hs(n),async()=>{await Fs(n),await Us(n,t);let s=await Tr.run(Ls(),t,{presetOptions:n,abortSignal:n.abortSignal,guardrails:n.guardrails});if(!s.data)throw new Error("runKodaX: substrate executor did not lift KodaXResult onto RunResult.data \u2014 verify createDefaultCodingAgent().substrateExecutor in coding-preset.ts");return s.data})}i(DT,"runKodaX");export{q as a,ea as b,An as c,no as d,On as e,io as f,gt as g,aa as h,je as i,yt as j,qe as k,co as l,lo as m,uo as n,bt as o,We as p,Bn as q,Fm as r,Gm as s,Un as t,xt as u,$n as v,Ca as w,Wn as x,vt as y,oi as z,Za as A,af as B,ri as C,go as D,cf as E,Hc as F,ai as G,ci as H,Rt as I,Et as J,Ge as K,I as L,To as M,fi as N,S as O,bo as P,pi as Q,xo as R,wo as S,Df as T,bi as U,So as V,wi as W,_o as X,Ri as Y,Co as Z,Pi as _,Mo as $,Ce as aa,Ji as ba,es as ca,Oo as da,Ye as ea,is as fa,Vl as ga,us as ha,ds as ia,ms as ja,ge as ka,ps as la,hs as ma,gs as na,Ot as oa,vs as pa,qg as qa,ye as ra,dy as sa,Ps as ta,Ds as ua,Ls as va,Fs as wa,Us as xa,Hs as ya,DT as za};
|