@kodax-ai/kodax 0.7.49 → 0.7.51
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 +1800 -1741
- package/README.md +1215 -1210
- package/README_CN.md +636 -632
- package/dist/chunks/agent-EFA7BSE7.js +2 -0
- package/dist/chunks/argument-completer-MAJVHSE7.js +2 -0
- package/dist/chunks/{chunk-TYZAH3YP.js → chunk-CCZMQE3Q.js} +1 -1
- package/dist/chunks/chunk-E3HENKTX.js +420 -0
- package/dist/chunks/chunk-FAIGYAEX.js +301 -0
- package/dist/chunks/chunk-HMATTIU6.js +574 -0
- package/dist/chunks/{chunk-YW4RQV7U.js → chunk-JJTUBNQX.js} +1 -1
- package/dist/chunks/chunk-ODVA5VTE.js +492 -0
- package/dist/chunks/chunk-PEWH3AAL.js +31 -0
- package/dist/chunks/chunk-WQTVG2T5.js +648 -0
- package/dist/chunks/{compaction-config-BQBYOWX2.js → compaction-config-UBPCNGC2.js} +1 -1
- package/dist/chunks/{construction-bootstrap-5TFGMSWQ.js → construction-bootstrap-WY5MDXRX.js} +1 -1
- package/dist/chunks/{dist-BL7IBQHD.js → dist-B73FQEAA.js} +1 -1
- package/dist/chunks/dist-BTWS2ENP.js +2 -0
- package/dist/chunks/utils-HVOJRR5C.js +2 -0
- package/dist/index.d.ts +11 -11
- package/dist/index.js +4 -4
- package/dist/kodax_cli.js +1091 -984
- package/dist/provider-capabilities.json +2 -0
- package/dist/sdk-agent.d.ts +25 -11
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +160 -34
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-llm.d.ts +3 -5
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-repl.d.ts +38 -727
- package/dist/sdk-repl.js +2 -2
- package/dist/sdk-session.d.ts +8 -200
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/types-chunks/{types.d-rPRl2LSB.d.ts → base.d-GZ6jvICS.d.ts} +270 -3
- package/dist/types-chunks/{bash-prefix-extractor.d-CI_xcPhn.d.ts → bash-prefix-extractor.d-DTOiDMlG.d.ts} +84 -537
- package/dist/types-chunks/{capsule.d-DaPuhyyK.d.ts → capsule.d-CXGdLGAn.d.ts} +6 -3
- package/dist/types-chunks/guardrail.d-D47yu9AO.d.ts +518 -0
- package/dist/types-chunks/{types.d-BR9oNWup.d.ts → process.d-B8kEBnQD.d.ts} +487 -275
- package/dist/types-chunks/{resolver.d-B_wm409c.d.ts → resolver.d-D75XFRH2.d.ts} +23 -6
- package/dist/types-chunks/sdk-session-BKQJN9oH.d.ts +977 -0
- package/dist/types-chunks/{storage.d-J2GqOgaX.d.ts → storage.d-BN1xIn8R.d.ts} +78 -3
- package/dist/types-chunks/types.d-DQ_hdN70.d.ts +273 -0
- package/dist/types-chunks/{utils.d-BJ_-y8gC.d.ts → utils.d-ZfRDo-kX.d.ts} +8 -80
- package/package.json +2 -2
- package/dist/chunks/argument-completer-GDG5OHN7.js +0 -2
- package/dist/chunks/chunk-67SWUEEN.js +0 -1035
- package/dist/chunks/chunk-C5PKZX5Z.js +0 -291
- package/dist/chunks/chunk-ISGHUKRY.js +0 -428
- package/dist/chunks/chunk-JTHMWRXM.js +0 -566
- package/dist/chunks/chunk-YACQ4OST.js +0 -31
- package/dist/chunks/dist-D7HOETCE.js +0 -2
- package/dist/chunks/utils-XWDT3W5X.js +0 -2
- package/dist/types-chunks/base.d-C4jYVjJh.d.ts +0 -270
- package/dist/types-chunks/types.d-BnjX2Gn4.d.ts +0 -297
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{a as i}from"./chunk-V4WSBIXB.js";var H=class extends Error{static{i(this,"KodaXError")}code;constructor(e,o="KODAX_ERROR"){super(e),this.code=o,this.name="KodaXError"}},R=class extends H{static{i(this,"KodaXProviderError")}provider;constructor(e,o){super(e,"PROVIDER_ERROR"),this.provider=o,this.name="KodaXProviderError"}},ye=class extends H{static{i(this,"KodaXRateLimitError")}retryAfter;constructor(e,o){super(e,"RATE_LIMIT_ERROR"),this.retryAfter=o,this.name="KodaXRateLimitError"}},lt=class extends H{static{i(this,"KodaXNetworkError")}isTimeout;constructor(e,o=!1){super(e,"NETWORK_ERROR"),this.isTimeout=o,this.name="KodaXNetworkError"}},ut=class extends H{static{i(this,"KodaXToolCallIdError")}constructor(e){super(e,"TOOL_CALL_ID_ERROR"),this.name="KodaXToolCallIdError"}};var dt=32768,Qo=32e3,Zo=64e3,en=.5;var tn=["off","auto","quick","balanced","deep"],oo={low:6e3,medium:1e4,high:2e4},no=4096;function pt(t){return t.reasoningCapability?t.reasoningCapability:t.supportsThinking?"native-toggle":"prompt-only"}i(pt,"getReasoningCapability");function te(t){return we(t).enabled}i(te,"isReasoningEnabled");function we(t){if(typeof t=="boolean")return{enabled:t,mode:t?"auto":"off",depth:t?"medium":"off",taskType:"unknown",executionMode:"implementation"};let e=t?.mode??"off",o=t?.depth??io(e),n=t?.enabled??(e!=="off"&&o!=="off");return{enabled:n&&e!=="off"&&o!=="off",mode:e,depth:n?o:"off",taskType:t?.taskType??"unknown",executionMode:t?.executionMode??"implementation"}}i(we,"normalizeReasoningRequest");function io(t){switch(t){case"quick":return"low";case"balanced":case"auto":return"medium";case"deep":return"high";default:return"off"}}i(io,"getDefaultThinkingDepthForMode");function oe(t,e,o="unknown"){if(e==="off")return 0;let n={...oo,...t.defaultThinkingBudgets??{}},s=t.taskBudgetOverrides?.[o]?.[e]??n[e];return t.thinkingBudgetCap?Math.min(s,t.thinkingBudgetCap):s}i(oe,"resolveThinkingBudget");function ne(t,e,o=no){let n=Math.max(1024,e-o);return Math.max(1024,Math.min(t,n))}i(ne,"clampThinkingBudget");function ft(t){switch(t){case"low":return"low";case"medium":return"medium";case"high":return"high";default:return}}i(ft,"mapDepthToOpenAIReasoningEffort");import Se from"fs";import on from"os";import ht from"path";var mt=null;function nn(t){return t==="budget"||t==="effort"||t==="toggle"||t==="none"}i(nn,"isReasoningOverride");function rn(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t.providerReasoningOverrides;return e===void 0?!0:!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(nn)}i(rn,"isStoredConfig");function sn(){return process.env.KODAX_HOME??ht.join(on.homedir(),".kodax")}i(sn,"getKodaxDir");function ro(){return process.env.KODAX_CONFIG_FILE??ht.join(sn(),"config.json")}i(ro,"getConfigFilePath");function gt(t,e){return mt={filePath:t,config:e},e}i(gt,"updateStoredConfigCache");function an(t){let e=JSON.parse(Se.readFileSync(t,"utf-8"));return rn(e)?e:{}}i(an,"readStoredConfigFromDisk");function yt(t){switch(t){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";case"none":return"none";default:return}}i(yt,"reasoningCapabilityToOverride");function vt(t){switch(t){case"budget":return"native-budget";case"effort":return"native-effort";case"toggle":return"native-toggle";default:return"none"}}i(vt,"reasoningOverrideToCapability");function ie(t,e,o){return[t,e.baseUrl??"",o??e.model].join("|")}i(ie,"buildReasoningOverrideKey");function kt(){let t=ro();if(mt?.filePath===t)return mt.config;try{if(Se.existsSync(t))return gt(t,an(t))}catch{}return gt(t,{})}i(kt,"loadStoredConfig");function so(t){let e=ro();try{Se.mkdirSync(ht.dirname(e),{recursive:!0}),Se.writeFileSync(e,JSON.stringify(t,null,2)),gt(e,t)}catch(o){process.env.KODAX_DEBUG_OVERRIDES&&console.error("[ReasoningOverride] Failed to save config:",o)}}i(so,"saveStoredConfig");function Re(t,e,o){let n=kt(),r=ie(t,e,o);return n.providerReasoningOverrides?.[r]}i(Re,"loadReasoningOverride");function bt(t,e,o,n){let r=kt(),s=ie(t,e,n);r.providerReasoningOverrides={...r.providerReasoningOverrides??{},[s]:o},so(r)}i(bt,"saveReasoningOverride");function cn(t,e,o){let n=kt(),r=ie(t,e,o);if(!n.providerReasoningOverrides?.[r])return;let s={...n.providerReasoningOverrides};delete s[r],n.providerReasoningOverrides=Object.keys(s).length>0?s:void 0,so(n)}i(cn,"clearReasoningOverride");function ao(t,e){if(!t)return;if(typeof t.get=="function")return t.get(e)??void 0;let o=t,n=e.toLowerCase(),r=o[e]??o[n]??o[n.replace(/\b\w/g,s=>s.toUpperCase())];if(r!==void 0)return Array.isArray(r)?r[0]:r}i(ao,"readHeader");function co(t){if(!t)return;let e=t.trim();if(e.length===0)return;let o=Number(e);if(!(!Number.isFinite(o)||o<=0))return o}i(co,"parsePositiveNumber");function ln(t,e){if(!t)return;let o=t.trim();if(o.length===0)return;let n=Date.parse(o);if(!Number.isFinite(n))return;let r=n-e;return r>0?r:void 0}i(ln,"parseHttpDate");function Ae(t,e){let o=e.baseBackoffMs??1e3,n=e.maxBackoffMs??3e4,r=e.maxHeaderWaitMs??12e4,s=e.now?e.now():Date.now(),a=co(ao(t,"retry-after-ms"));if(a!==void 0){let y=Math.min(a,r);return{type:"header",waitMs:Math.round(y),source:"retry-after-ms",cappedFromHeader:y!==a}}let c=ao(t,"retry-after");if(c!==void 0&&c.trim().length>0){let y=co(c);if(y!==void 0){let b=y*1e3,d=Math.min(b,r);return{type:"header",waitMs:Math.round(d),source:"retry-after-seconds",cappedFromHeader:d!==b}}let h=ln(c,s);if(h!==void 0){let b=Math.min(h,r);return{type:"header",waitMs:Math.round(b),source:"retry-after-date",cappedFromHeader:b!==h}}}let u=o*Math.pow(2,Math.max(0,e.attempt)),p=Math.min(u,n),f=e.withJitter!==!1?Math.random()*.25*p:0;return{type:"backoff",waitMs:Math.round(p+f),source:"exponential-backoff",attempt:e.attempt}}i(Ae,"parseRetryAfter");function Oe(t){if(!t||typeof t!="object")return;let e=t;return e.headers??e.response?.headers??e.cause?.headers??e.cause?.response?.headers}i(Oe,"extractHeadersFromError");var Z={transport:"native-api",conversationSemantics:"full-history",mcpSupport:"none",contextFidelity:"full",toolCallingFidelity:"full",sessionSupport:"full",longRunningSupport:"full",multimodalSupport:"none",evidenceSupport:"full"},lo={...Z,multimodalSupport:"image-input"},ve={transport:"cli-bridge",conversationSemantics:"last-user-message",mcpSupport:"none",contextFidelity:"lossy",toolCallingFidelity:"limited",sessionSupport:"stateless",longRunningSupport:"limited",multimodalSupport:"none",evidenceSupport:"limited"},uo={...ve,multimodalSupport:"image-input"};function De(t){return{transport:t.transport,conversationSemantics:t.conversationSemantics,mcpSupport:t.mcpSupport,contextFidelity:t.contextFidelity??"full",toolCallingFidelity:t.toolCallingFidelity??"full",sessionSupport:t.sessionSupport??"full",longRunningSupport:t.longRunningSupport??"full",multimodalSupport:t.multimodalSupport??"none",evidenceSupport:t.evidenceSupport??"full"}}i(De,"normalizeCapabilityProfile");function W(t){return{...De(t)}}i(W,"cloneCapabilityProfile");function un(t){if(!t)return;let e=parseInt(t,10);return Number.isFinite(e)&&e>0?e:void 0}i(un,"parseEnvInt");function Ie(){return new DOMException("Request aborted","AbortError")}i(Ie,"abortError");function dn(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ie()):new Promise((o,n)=>{let r,s=i(()=>{e&&e.removeEventListener("abort",a)},"cleanup"),a=i(()=>{r&&clearTimeout(r),s(),n(Ie())},"onAbort");e&&e.addEventListener("abort",a,{once:!0}),r=setTimeout(()=>{s(),o()},t)})}i(dn,"waitForRetryDelay");var V=class{static{i(this,"KodaXBaseProvider")}maxOutputTokensOverride;setMaxOutputTokensOverride(e){this.maxOutputTokensOverride=e}getEffectiveMaxOutputTokens(e){if(this.maxOutputTokensOverride!==void 0)return this.maxOutputTokensOverride;let o=un(process.env.KODAX_MAX_OUTPUT_TOKENS);if(o!==void 0)return o;let n=this.getModelDescriptor(e)?.maxOutputTokens;return n!==void 0?n:this.config.maxOutputTokens??32768}getStreamMaxDurationMs(e){let o=this.getModelDescriptor(e)?.streamMaxDurationMs;return o!==void 0?o:this.config.streamMaxDurationMs}getEffectiveReplayReasoningContent(e){let o=this.getModelDescriptor(e)?.replayReasoningContent;return o!==void 0?o:this.config.replayReasoningContent??!1}getEffectiveStrictThinkingSignature(e){let o=this.getModelDescriptor(e)?.strictThinkingSignature;return o!==void 0?o:this.config.strictThinkingSignature??!1}supportsNonStreamingFallback(){return!1}async complete(e,o,n,r,s,a){throw new R(`${this.name} does not support non-streaming fallback`)}isConfigured(){return!!process.env[this.config.apiKeyEnv]}async verifyCredential(e){return{ok:!1,error:"unsupported",strategy:this.config.verifyStrategy??"unsupported",durationMs:0,approxTokensSpent:0,message:`Provider class "${this.name}" does not implement verifyCredential()`}}getModel(){return this.config.model}getAvailableModels(){return this.config.models?.length?[...new Set([this.config.model,...this.config.models.map(e=>e.id)])]:[this.config.model]}getModelDescriptor(e){let o=e??this.config.model,n=this.config.models?.find(r=>r.id===o);if(n)return n;if(o===this.config.model)return{id:this.config.model}}getBaseUrl(){return this.config.baseUrl}getApiKeyEnv(){return this.config.apiKeyEnv}getCapabilityProfile(){return W(this.config.capabilityProfile??Z)}getConfiguredReasoningCapability(e){let o=this.getModelDescriptor(e);return o?.reasoningCapability?o.reasoningCapability:pt(this.config)}getReasoningCapability(e){let o=Re(this.name,this.config,e);return o?vt(o):this.getConfiguredReasoningCapability(e)}getReasoningOverride(e){return Re(this.name,this.config,e)}getReasoningOverrideKey(e){return ie(this.name,this.config,e)}persistReasoningCapabilityOverride(e,o){let n=yt(e);n&&bt(this.name,this.config,n,o)}shouldFallbackForReasoningError(e,...o){let n=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),s=o.map(c=>c.toLowerCase()).some(c=>n.includes(c)),a=n.includes("parameter")||s;return n.includes("unknown parameter")||n.includes("invalid parameter")||n.includes("unsupported")&&a}shouldFallbackForSpecificReasoningError(e,...o){let n=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return o.map(a=>a.toLowerCase()).some(a=>n.includes(a))?n.includes("unknown parameter")||n.includes("invalid parameter")||n.includes("unsupported"):!1}shouldFallbackForForcedToolChoiceError(e){let o=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return o.includes("tool_choice")||o.includes("tool choice")||o.includes("toolchoice")?o.includes("unknown parameter")||o.includes("invalid parameter")||o.includes("unsupported"):!1}getReasoningFallbackChain(e){switch(e){case"native-budget":return["native-budget","native-toggle","none"];case"native-effort":return["native-effort","none"];case"native-toggle":return["native-toggle","none"];default:return["none"]}}getContextWindow(){return this.getEffectiveContextWindow()}getEffectiveContextWindow(e){let o=this.getModelDescriptor(e)?.contextWindow;return o!==void 0?o:this.config.contextWindow??2e5}getApiKey(){let e=process.env[this.config.apiKeyEnv];if(!e)throw new Error(`${this.config.apiKeyEnv} not set`);return e}shouldLogStreamDiagnostics(){return!!process.env.KODAX_DEBUG_STREAM}logStreamDiagnostic(...e){this.shouldLogStreamDiagnostics()&&console.error(...e)}normalizeReasoning(e){return we(e)}onStaleConnection(){}isRateLimitError(e){if(!(e instanceof Error))return!1;let o=e.message.toLowerCase();return["rate","limit","\u901F\u7387","\u9891\u7387","1302","429","too many","overload","overwhelmed","503","529","busy"].some(n=>o.includes(n))}classifyRateLimitReason(e){let o=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return o.includes("overload")||o.includes("overwhelmed")||o.includes("503")||o.includes("529")||o.includes("busy")?"overloaded":"rate-limit"}extractRetryAfterMs(e){let o=Oe(e);if(!o)return;let n=Ae(o,{attempt:0,withJitter:!1});return n.type==="header"?n.waitMs:void 0}parseContextOverflow(e){let o=String(e?.message??""),n=[/(\d[\d,]*)\s*tokens?.*?(\d[\d,]*)\s*(?:maximum|limit|context)/i,/maximum.*?(\d[\d,]*)\s*tokens?.*?requested.*?(\d[\d,]*)/i,/exceeds?\s+.*?(\d[\d,]*)\s*.*?(?:limit|max|上限).*?(\d[\d,]*)/i];for(let r of n){let s=o.match(r);if(s){let a=Number(s[1].replace(/,/g,"")),c=Number(s[2].replace(/,/g,"")),u=Math.min(a,c),p=Math.max(a,c);return Math.max(3e3,p-u-1e3)}}}isContextOverflowError(e){let o=String(e?.message??"").toLowerCase();return o.includes("prompt is too long")||o.includes("prompt too long")||o.includes("context length")||o.includes("context_length_exceeded")||o.includes("context window")||o.includes("\u4E0A\u4E0B\u6587\u957F\u5EA6")}async withRateLimit(e,o,n=3,r,s){for(let a=0;a<n;a++)try{let c=await e();return this.maxOutputTokensOverride=void 0,c}catch(c){if(this.isContextOverflowError(c)&&!this.maxOutputTokensOverride){let u=this.parseContextOverflow(c);if(u){this.maxOutputTokensOverride=u,r?.(a+1,n,0);continue}}if(this.isRateLimitError(c)){if(a===n-1)throw new ye(`API rate limit exceeded after ${n} retries. Please wait and try again later.`,6e4);let u=Oe(c)??{},p=Ae(u,{attempt:a,baseBackoffMs:500,maxBackoffMs:32e3,withJitter:!0}),l=p.waitMs,f=this.classifyRateLimitReason(c);if(s?.({provider:this.name,waitMs:l,reason:f,source:p.source,attempt:a+1,maxAttempts:n}),r?r(a+1,n,l):s||console.log(`[Rate Limit] Retrying in ${l/1e3}s (${a+1}/${n})...`),o?.aborted||(await dn(l,o),o?.aborted))throw Ie();continue}if(c instanceof Error){if((c.name==="AbortError"||c.name==="APIUserAbortError")&&o?.aborted)throw c.name==="AbortError"?c:new DOMException(c.message||"Request aborted","AbortError");let u=c?.cause?.code??c?.code??"";throw(u==="ECONNRESET"||u==="EPIPE")&&this.onStaleConnection(),new R(`${this.name} API error: ${c.message}`,this.name)}throw c}throw new H("Unexpected end of withRateLimit")}};import yn from"@anthropic-ai/sdk";import{parse as pn}from"partial-json";function re(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{}try{let e=pn(t);return process.env.KODAX_DEBUG_TOOL_STREAM&&console.warn("[Tool Block Salvaged] partial JSON recovered, rawLength=",t.length),e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}i(re,"parseToolInputWithSalvage");async function se(t){if(t.strategy==="unsupported")return{ok:!1,error:"unsupported",strategy:"unsupported",durationMs:0,approxTokensSpent:0,message:"Provider does not support credential verification"};let e=t.runners.find(p=>p.strategy===t.strategy);if(!e)return{ok:!1,error:"unsupported",strategy:t.strategy,durationMs:0,approxTokensSpent:0,message:`verifyStrategy="${t.strategy}" is not implemented for this provider's base class`};if(t.signal?.aborted)return{ok:!1,error:"unknown",strategy:t.strategy,durationMs:0,approxTokensSpent:0,message:"caller aborted before verifyCredential started"};let o=new AbortController,n=t.timeoutMs??8e3,r,s=i(p=>{r||(r=p),o.abort()},"recordAbort"),a=setTimeout(()=>s("timeout"),n),c=i(()=>s("parent"),"onParentAbort");t.signal&&t.signal.addEventListener("abort",c,{once:!0});let u=Date.now();try{return await e.run(o.signal),{ok:!0,strategy:t.strategy,durationMs:Date.now()-u,approxTokensSpent:e.approxTokensSpent}}catch(p){return Ct(p,{strategy:t.strategy,durationMs:Date.now()-u,approxTokensSpent:0,abortCause:r,providerName:t.providerName})}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",c)}}i(se,"runVerifyCredential");function fn(t){return t.replace(/\bsk-[A-Za-z0-9_-]{6,}/g,"sk-***")}i(fn,"redactKeyMaterial");function Ct(t,e){let o=t,n=o.status??o.statusCode??o.response?.status,r=fn(String(o.message??t)).slice(0,240),s=o.cause?.code??o.code,a=o.constructor?.name??"",c;return e.abortCause==="timeout"?c="timeout":e.abortCause==="parent"?c="unknown":a==="AuthenticationError"||a==="PermissionDeniedError"||n===401||n===403?c="unauthorized":n===429?c="rate_limited":n===400&&e.strategy==="count-tokens"&&e.providerName==="kimi-code"?c="unauthorized":n!==void 0&&n>=500&&n<600?c="server_error":s!==void 0&&/ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|EPIPE|ETIMEDOUT|ENETUNREACH|ENETDOWN|EHOSTUNREACH/i.test(s)?c="network":/timeout/i.test(r)?c="timeout":c="unknown",{ok:!1,error:c,status:n,message:r,durationMs:e.durationMs,approxTokensSpent:e.approxTokensSpent,strategy:e.strategy}}i(Ct,"classifyVerifyError");function _t(t,e){let o=t[t.length-1];if(o&&ae(o)&&o.hint===e)return t;let n=e?{type:"cache-boundary",hint:e}:{type:"cache-boundary"};return[...t,n]}i(_t,"insertCacheBoundary");function ae(t){if(typeof t!="object"||t===null||t.type!=="cache-boundary")return!1;let e=Object.keys(t);return e.length<=2&&e.every(o=>o==="type"||o==="hint")}i(ae,"isCacheBoundary");function xt(t,e){let o=[];for(let n of t){if(ae(n)){if(e==="attach"&&o.length>0){let r=o[o.length-1];o[o.length-1]={...r,cache_control:{type:"ephemeral"}}}continue}o.push(n)}return o}i(xt,"lowerCacheBoundaries");function ke(t){return t.filter(e=>!ae(e))}i(ke,"stripCacheBoundaries");import{readFile as mn}from"node:fs/promises";import gn from"node:path";var hn={".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"};function Ne(t,e){return e??hn[gn.extname(t).toLowerCase()]??"image/png"}i(Ne,"resolveImageMediaType");async function Le(t){return(await mn(t)).toString("base64")}i(Le,"readImageFileAsBase64");async function po(t,e){let o=Ne(t,e),n=await Le(t);return`data:${o};base64,${n}`}i(po,"buildImageDataUrl");var vn="KodaX";function kn(t){return t.userAgentMode==="sdk"?void 0:{"User-Agent":vn}}i(kn,"getAnthropicCompatDefaultHeaders");function Tt(t,e){if(!t)return e;let o=t.input_tokens!==void 0&&t.input_tokens!==null||t.cache_creation_input_tokens!==void 0&&t.cache_creation_input_tokens!==null||t.cache_read_input_tokens!==void 0&&t.cache_read_input_tokens!==null,n=typeof t.input_tokens=="number"?t.input_tokens:o?0:e?.inputTokens??0,r=typeof t.cache_creation_input_tokens=="number"?t.cache_creation_input_tokens:o?0:e?.cachedWriteTokens??0,s=typeof t.cache_read_input_tokens=="number"?t.cache_read_input_tokens:o?0:e?.cachedReadTokens??0,a=typeof t.output_tokens=="number"?t.output_tokens:e?.outputTokens??0,c=o?n+r+s:e?.inputTokens??0;if(![c,a].some(u=>!Number.isFinite(u)||u<0))return{inputTokens:c,outputTokens:a,totalTokens:c+a,cachedReadTokens:s||void 0,cachedWriteTokens:r||void 0}}i(Tt,"normalizeAnthropicUsage");var I=class extends V{static{i(this,"KodaXAnthropicCompatProvider")}supportsThinking=!0;client;initClient(){let e=kn(this.config);this.client=new yn({apiKey:this.getApiKey(),baseURL:this.config.baseUrl,...e?{defaultHeaders:e}:{}})}onStaleConnection(){this.initClient()}async verifyCredential(e){let o=this.config.model,n=this.client,r=[{strategy:"count-tokens",approxTokensSpent:0,run:i(async s=>{await n.messages.countTokens({model:o,messages:[{role:"user",content:"hi"}]},{signal:s})},"run")},{strategy:"models-list",approxTokensSpent:0,run:i(async s=>{await n.models.list({},{signal:s})},"run")},{strategy:"minimal-message",approxTokensSpent:7,run:i(async s=>{await n.messages.create({model:o,max_tokens:1,messages:[{role:"user",content:"hi"}]},{signal:s})},"run")}];return se({strategy:this.config.verifyStrategy??"count-tokens",runners:r,timeoutMs:e?.timeoutMs,signal:e?.signal,providerName:this.name})}applyCacheControlToSystem(e){if(!e.trim()||process.env.KODAX_DISABLE_PROMPT_CACHE==="1")return e;let o=_t([{type:"text",text:e}],"system");return xt(o,"attach")}applyCacheControlToTools(e){if(e.length===0||process.env.KODAX_DISABLE_PROMPT_CACHE==="1")return e;let o=e.slice(),n=o[o.length-1];return o[o.length-1]={...n,cache_control:{type:"ephemeral"}},o}async stream(e,o,n,r,s,a){return this.withRateLimit(async()=>{let c=this.normalizeReasoning(r),u=s?.modelOverride??this.config.model,p=s?.maxOutputTokensOverride??this.getEffectiveMaxOutputTokens(u),l=await this.convertMessages(e,u),f=c.enabled?this.getReasoningCapability(u):"none",y=c.enabled?this.getReasoningFallbackChain(f).filter(g=>g==="native-budget"||g==="native-toggle"||g==="none"):["none"],h=!!s?.forcedToolName,b=i(g=>{let w={model:u,max_tokens:p,system:this.applyCacheControlToSystem(this.buildSystemPrompt(n,e)),messages:l,tools:this.applyCacheControlToTools(o),stream:!0};if(s?.forcedToolName&&h&&(w.tool_choice={type:"tool",name:s.forcedToolName}),g==="native-budget"){let S=oe(this.config,c.depth,c.taskType);w.thinking={type:"enabled",budget_tokens:ne(S,p)}}else g==="native-toggle"&&(w.thinking={type:"enabled"});return w},"buildRequest");if(a?.aborted)throw new DOMException("Request aborted","AbortError");let d=[],v=[],k=[],x,C=null,m="",T="",P="",L="",N="",j="",B="",J=!1,M,D=Date.now(),z=Date.now(),q,Pe;for(let g of y){for(;!q;)try{q=await this.client.messages.create(b(g),a?{signal:a}:{}),g!==f&&this.persistReasoningCapabilityOverride(g,u)}catch(w){if(Pe=w,h&&this.shouldFallbackForForcedToolChoiceError(w)){h=!1,this.logStreamDiagnostic(`[${this.name}] upstream rejected forced tool_choice; retrying without forced tool choice`);continue}let S=g==="native-budget"?["budget_tokens","thinking"]:g==="native-toggle"?["thinking"]:[];if(!this.shouldFallbackForReasoningError(w,...S))throw w;break}if(q)break}if(!q)throw Pe??new R("All reasoning capability attempts failed without a captured error",this.name);let ge=Date.now(),he=0,E=0,F=3e4;for await(let g of q){if(a?.aborted)throw new DOMException("Request aborted","AbortError");let w=Date.now(),S=w-ge;if(S>F&&(he++,E+=S,this.logStreamDiagnostic(`[Stream] stall detected: ${Math.round(S/1e3)}s gap before ${g.type}`,{stallCount:he,totalStallMs:E,eventType:g.type})),ge=w,g.type==="content_block_start"||g.type==="content_block_stop"?s?.onHeartbeat?.(!0):s?.onHeartbeat?.(),g.type==="content_block_start"){D=Date.now();let _=g.content_block;C=_.type,process.env.KODAX_DEBUG_TOOL_STREAM&&_.type==="tool_use"&&console.error("[ToolStream] content_block_start:",{type:_.type,id:_.id,name:_.name}),_.type==="thinking"?(T="",P=_.signature??""):_.type==="redacted_thinking"?(C="redacted_thinking",L=_.data??""):_.type==="text"?m="":_.type==="tool_use"&&(N=_.id,j=_.name,B="")}else if(g.type==="content_block_delta"){D=Date.now();let _=g.delta;_.type==="thinking_delta"?(T+=_.thinking??"",s?.onThinkingDelta?.(_.thinking??"")):_.type==="text_delta"?(m+=_.text??"",s?.onTextDelta?.(_.text??"")):_.type==="input_json_delta"&&(B+=_.partial_json??"",s?.onToolInputDelta?.(j,_.partial_json??"",N?{toolId:N}:void 0))}else if(g.type==="content_block_stop")D=Date.now(),C==="thinking"?T&&(k.push({type:"thinking",thinking:T,signature:P}),s?.onThinkingEnd?.(T)):C==="redacted_thinking"?(L&&k.push({type:"redacted_thinking",data:L}),L=""):C==="text"?m&&d.push({type:"text",text:m}):C==="tool_use"&&(!N||!j?console.error("[Tool Block Invalid] Missing tool id or name:",{id:JSON.stringify(N),name:JSON.stringify(j),input:B.slice(0,100)}):v.push({type:"tool_use",id:N,name:j,input:re(B)})),C=null;else if(g.type==="message_stop"){if(J=!0,D=Date.now(),process.env.KODAX_DEBUG_STREAM){let _=Date.now()-z;this.logStreamDiagnostic(`[Stream] message_stop received after ${_}ms`)}}else if(g.type==="message_delta"){D=Date.now(),x=Tt(g.usage,x);let _=g.delta;_?.stop_reason&&(M=_.stop_reason,process.env.KODAX_DEBUG_STREAM&&this.logStreamDiagnostic(`[Stream] message_delta with stop_reason: ${M}`))}else g.type==="message_start"&&(D=Date.now(),x=Tt(g.message?.usage,x),process.env.KODAX_DEBUG_STREAM&&this.logStreamDiagnostic("[Stream] message_start received"))}if(!J){let g=Date.now()-z,w=Date.now()-D;if(a?.aborted){let _=a.reason instanceof Error?a.reason.message:typeof a.reason=="string"?a.reason:"Request aborted";throw this.logStreamDiagnostic("[Stream] Stream ended after abort before message_stop:",{duration:g,lastEventAge:w,reason:_,textBlocks:d.length,toolBlocks:v.length,thinkingBlocks:k.length}),new DOMException(_,"AbortError")}let S=new Error(`Stream incomplete: message_stop event not received. Duration: ${g}ms, Last event: ${w}ms ago. This may indicate a network disconnection or API timeout.`);throw S.name="StreamIncompleteError",this.logStreamDiagnostic("[Stream] Incomplete stream detected:",{duration:g,lastEventAge:w,textBlocks:d.length,toolBlocks:v.length,thinkingBlocks:k.length}),S}return{textBlocks:d,toolBlocks:v,thinkingBlocks:k,usage:x,stopReason:M}},a,3,s?.onRateLimit,s?.onRetryAfter)}supportsNonStreamingFallback(){return!0}async complete(e,o,n,r,s,a){return this.withRateLimit(async()=>{let c=this.normalizeReasoning(r),u=s?.modelOverride??this.config.model,p=s?.maxOutputTokensOverride??this.getEffectiveMaxOutputTokens(u),l=await this.convertMessages(e,u),f=c.enabled?this.getReasoningCapability(u):"none",y=c.enabled?this.getReasoningFallbackChain(f).filter(m=>m==="native-budget"||m==="native-toggle"||m==="none"):["none"],h=!!s?.forcedToolName,b=i(m=>{let T={model:u,max_tokens:p,system:this.applyCacheControlToSystem(this.buildSystemPrompt(n,e)),messages:l,tools:this.applyCacheControlToTools(o)};if(s?.forcedToolName&&h&&(T.tool_choice={type:"tool",name:s.forcedToolName}),m==="native-budget"){let P=oe(this.config,c.depth,c.taskType);T.thinking={type:"enabled",budget_tokens:ne(P,p)}}else m==="native-toggle"&&(T.thinking={type:"enabled"});return T},"buildRequest"),d,v;for(let m of y){for(;!d;)try{d=await this.client.messages.create(b(m),a?{signal:a}:{}),m!==f&&this.persistReasoningCapabilityOverride(m,u)}catch(T){if(v=T,h&&this.shouldFallbackForForcedToolChoiceError(T)){h=!1,this.logStreamDiagnostic(`[${this.name}] upstream rejected forced tool_choice; retrying without forced tool choice`);continue}let P=m==="native-budget"?["budget_tokens","thinking"]:m==="native-toggle"?["thinking"]:[];if(!this.shouldFallbackForReasoningError(T,...P))throw T;break}if(d)break}if(!d)throw v??new R("All reasoning capability attempts failed without a captured error",this.name);let k=[],x=[],C=[];for(let m of d.content)m.type==="text"?(k.push({type:"text",text:m.text}),s?.onTextDelta?.(m.text)):m.type==="thinking"?(C.push({type:"thinking",thinking:m.thinking,signature:m.signature??""}),s?.onThinkingDelta?.(m.thinking),s?.onThinkingEnd?.(m.thinking)):m.type==="redacted_thinking"?C.push({type:"redacted_thinking",data:m.data}):m.type==="tool_use"&&x.push({type:"tool_use",id:m.id,name:m.name,input:typeof m.input=="object"&&m.input!==null?m.input:{}});return{textBlocks:k,toolBlocks:x,thinkingBlocks:C,usage:Tt(d.usage),stopReason:d.stop_reason??void 0}},a,3,s?.onRateLimit,s?.onRetryAfter)}serializeSystemMessageContent(e){if(typeof e=="string")return e.trim();for(let o of e)if(ae(o))throw new R("cache-boundary marker reached system message serialization unlowered. Provider base class lowering must run before any wire-level serialization.",this.name);return e.filter(o=>o.type==="text").map(o=>o.text.trim()).filter(Boolean).join(`
|
|
3
|
-
`)}buildSystemPrompt(e,o){let n=o.filter(r=>r.role==="system").map(r=>this.serializeSystemMessageContent(r.content)).filter(Boolean);return[e,...n].filter(r=>typeof r=="string"&&r.trim().length>0).join(`
|
|
4
|
-
|
|
5
|
-
`)}async convertMessages(e,o){let n=[],r=this.getEffectiveStrictThinkingSignature(o);for(let s of e.filter(a=>a.role!=="system")){let a=s.role==="user"?"user":"assistant";if(typeof s.content=="string"){n.push({role:a,content:s.content});continue}let c=[],u=[];for(let l of s.content)l.type==="thinking"?!r||typeof l.signature=="string"&&l.signature.length>0?c.push({type:"thinking",thinking:l.thinking,signature:l.signature??""}):l.thinking&&u.push(l.thinking):l.type==="redacted_thinking"&&(r||c.push({type:"redacted_thinking",data:l.data}));u.length>0&&s.role==="assistant"&&c.push({type:"text",text:`<prior_reasoning>
|
|
6
|
-
${u.join(`
|
|
7
|
-
|
|
8
|
-
`)}
|
|
9
|
-
</prior_reasoning>`});for(let l of s.content)if(l.type==="tool_result"&&s.role==="user"){let f;if(typeof l.content=="string")f=l.content;else{let y=[];for(let h of l.content)h.type==="text"?y.push({type:"text",text:h.text}):h.type==="image"&&y.push({type:"image",source:{type:"base64",media_type:Ne(h.path,h.mediaType),data:await Le(h.path)}});f=y}c.push({type:"tool_result",tool_use_id:l.tool_use_id,content:f,...l.is_error===!0?{is_error:!0}:{}})}for(let l of s.content)l.type==="tool_use"&&s.role==="assistant"&&c.push({type:"tool_use",id:l.id,name:l.name,input:l.input});for(let l of s.content)l.type==="text"?c.push({type:"text",text:l.text}):l.type==="image"&&s.role==="user"&&c.push({type:"image",source:{type:"base64",media_type:Ne(l.path,l.mediaType),data:await Le(l.path)}});if(a==="assistant"&&this.config.supportsThinking&&!r){let l=c.some(y=>y.type==="tool_use"),f=c.some(y=>y.type==="thinking"||y.type==="redacted_thinking");l&&!f&&c.unshift({type:"thinking",thinking:"...",signature:""})}let p=c.length===0||a==="assistant"&&c.every(l=>{let f=l;return f.type==="thinking"&&!f.thinking||f.type==="text"&&!f.text});n.push({role:s.role,content:p?[{type:"text",text:"..."}]:c})}return n}};import bn from"openai";var Cn="KodaX";function _n(t){return t.userAgentMode==="sdk"?void 0:{"User-Agent":Cn}}i(_n,"getOpenAICompatDefaultHeaders");function fo(t){if(!t)return;let e=typeof t.prompt_tokens=="number"?t.prompt_tokens:0,o=typeof t.completion_tokens=="number"?t.completion_tokens:0,n=typeof t.total_tokens=="number"?t.total_tokens:e+o;if([e,o,n].some(s=>!Number.isFinite(s)||s<0)||n<e||n<o)return;let r=typeof t.prompt_tokens_details?.cached_tokens=="number"&&t.prompt_tokens_details.cached_tokens>=0?t.prompt_tokens_details.cached_tokens:typeof t.prompt_cache_hit_tokens=="number"&&t.prompt_cache_hit_tokens>=0?t.prompt_cache_hit_tokens:void 0;return{inputTokens:e,outputTokens:o,totalTokens:n,...r!==void 0?{cachedReadTokens:r}:{}}}i(fo,"normalizeOpenAIUsage");function xn(t){return t?t.type==="function"&&"function"in t:!1}i(xn,"isOpenAIFunctionToolCall");function Tn(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return"";let o=Reflect.get(e,"text");if(typeof o=="string")return o;if(o&&typeof o=="object"){let n=Reflect.get(o,"value");return typeof n=="string"?n:""}return""}).filter(Boolean).join(""):""}i(Tn,"extractOpenAIMessageText");function En(t){if(!t||typeof t!="object")return"";let e=Reflect.get(t,"reasoning_content");return typeof e=="string"?e:Array.isArray(e)?e.map(o=>typeof o=="string"?o:o&&typeof o=="object"&&"text"in o&&typeof o.text=="string"?o.text:"").join(""):""}i(En,"extractOpenAIMessageReasoning");var K=class extends V{static{i(this,"KodaXOpenAICompatProvider")}supportsThinking=!0;client;initClient(){let e=_n(this.config);this.client=new bn({apiKey:this.getApiKey(),baseURL:this.config.baseUrl,...e?{defaultHeaders:e}:{}})}onStaleConnection(){this.initClient()}async verifyCredential(e){let o=this.config.model,n=this.client,r=[{strategy:"models-list",approxTokensSpent:0,run:i(async s=>{await n.models.list({signal:s})},"run")},{strategy:"minimal-message",approxTokensSpent:6,run:i(async s=>{await n.chat.completions.create({model:o,max_tokens:1,messages:[{role:"user",content:"hi"}]},{signal:s})},"run")}];return se({strategy:this.config.verifyStrategy??"models-list",runners:r,timeoutMs:e?.timeoutMs,signal:e?.signal,providerName:this.name})}stripCacheBoundariesFromMessages(e){return e.map(o=>{if(typeof o.content=="string")return o;let n=ke(o.content);return n.length===o.content.length?o:{...o,content:n}})}normalizeSystemForWire(e,o){let n=[];e&&e.trim().length>0&&n.push(e);let r=[];for(let s of o){if(s.role!=="system"){r.push(s);continue}let a=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.filter(c=>typeof c=="object"&&c!==null&&c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
10
|
-
`):"";a.trim().length>0&&n.push(a)}return{system:n.join(`
|
|
11
|
-
|
|
12
|
-
`),rest:r}}appendExtraBody(e,o){let n=typeof e.extra_body=="object"&&e.extra_body!==null?e.extra_body:{};e.extra_body={...n,...o}}resetReasoningCapabilityParams(e){delete e.reasoning_effort,delete e.thinking;let o=typeof e.extra_body=="object"&&e.extra_body!==null?{...e.extra_body}:void 0;if(o){if(delete o.enable_thinking,delete o.thinking_budget,delete o.thinking,Object.keys(o).length===0){delete e.extra_body;return}e.extra_body=o}}applyReasoningCapability(e,o,n){let r=e,s=this.getEffectiveMaxOutputTokens(e.model),a=ne(oe(this.config,n.depth,n.taskType),s);switch(o){case"native-effort":{let c=ft(n.depth);c&&(r.reasoning_effort=c);break}case"native-budget":{this.name==="qwen"?this.appendExtraBody(r,{enable_thinking:!0,thinking_budget:a}):this.name==="zhipu"&&(r.thinking={type:"enabled",budget_tokens:a});break}case"native-toggle":{this.name==="qwen"?this.appendExtraBody(r,{enable_thinking:!0}):this.name==="zhipu"&&(r.thinking={type:"enabled"});break}default:break}}getFallbackTerms(e){switch(e){case"native-budget":return["thinking_budget","budget_tokens","thinking"];case"native-effort":return["reasoning_effort"];case"native-toggle":return["enable_thinking","thinking"];default:return[]}}async stream(e,o,n,r,s,a){return this.withRateLimit(async()=>{let c=this.stripCacheBoundariesFromMessages(e),{system:u,rest:p}=this.normalizeSystemForWire(n,c),l=s?.modelOverride??this.config.model,f=[{role:"system",content:u},...await this.convertMessages(p,l)],y=o.map(E=>({type:"function",function:{name:E.name,description:E.description,parameters:E.input_schema}})),h=s?.forcedToolName,b=!!h;if(a?.aborted)throw new DOMException("Request aborted","AbortError");let d=new Map,v="",k="",x,C=!0,m=null,T=Date.now(),P=this.normalizeReasoning(r),L=te(P)?this.getReasoningCapability(l):"none",N=te(P)?this.getReasoningFallbackChain(L).filter(E=>E==="native-budget"||E==="native-effort"||E==="native-toggle"||E==="none"):["none"],j={model:l,messages:f,tools:y,max_completion_tokens:s?.maxOutputTokensOverride??this.getEffectiveMaxOutputTokens(l),stream:!0};h&&b&&(j.tool_choice={type:"function",function:{name:h}});let B,J;for(let E of N){for(;!B;){let F={...j};C&&(F.stream_options={include_usage:!0}),this.resetReasoningCapabilityParams(F),this.applyReasoningCapability(F,E,P);try{B=await this.client.chat.completions.create(F,a?{signal:a}:{}),E!==L&&this.persistReasoningCapabilityOverride(E,l)}catch(g){if(J=g,b&&this.shouldFallbackForForcedToolChoiceError(g)){b=!1,delete j.tool_choice,this.logStreamDiagnostic(`[${this.name}] upstream rejected forced tool_choice; retrying without forced tool choice`);continue}if(C&&this.shouldFallbackForSpecificReasoningError(g,"stream_options","include_usage")){C=!1;continue}if(!this.shouldFallbackForReasoningError(g,...this.getFallbackTerms(E)))throw g;break}}if(B)break}if(!B)throw J??new R("All reasoning capability attempts failed without a captured error",this.name);let M=Date.now(),D=0,z=0,q=3e4;for await(let E of B){if(a?.aborted)throw new DOMException("Request aborted","AbortError");let F=Date.now(),g=F-M;g>q&&(D++,z+=g,this.logStreamDiagnostic(`[Stream] stall detected: ${Math.round(g/1e3)}s gap`,{stallCount:D,totalStallMs:z})),M=F,s?.onHeartbeat?.(),x=fo(E.usage)??x;let w=E.choices[0],S=w?.delta;if(w?.finish_reason&&(m=w.finish_reason,process.env.KODAX_DEBUG_STREAM)){let X=Date.now()-T;this.logStreamDiagnostic(`[Stream] finish_reason: ${m} after ${X}ms`)}S?.content&&(v+=S.content,s?.onTextDelta?.(S.content));let _=this.extractReasoningDelta(S);if(_&&(k+=_,s?.onThinkingDelta?.(_)),S?.tool_calls)for(let X of S.tool_calls){let Q=d.get(X.index)??{id:"",name:"",arguments:""};X.id&&(Q.id=X.id),X.function?.name&&(Q.name=X.function.name),X.function?.arguments&&(Q.arguments+=X.function.arguments,s?.onToolInputDelta?.(Q.name,X.function.arguments,Q.id?{toolId:Q.id}:void 0)),d.set(X.index,Q)}}if(!m){let E=Date.now()-T;if(a?.aborted){let g=a.reason instanceof Error?a.reason.message:typeof a.reason=="string"?a.reason:"Request aborted";throw this.logStreamDiagnostic("[Stream] Stream ended after abort before finish_reason:",{duration:E,reason:g,textContentLength:v.length,toolCallsCount:d.size}),new DOMException(g,"AbortError")}let F=new Error(`Stream incomplete: finish_reason not received. Duration: ${E}ms. This may indicate a network disconnection or API timeout.`);throw F.name="StreamIncompleteError",this.logStreamDiagnostic("[Stream] Incomplete stream detected:",{duration:E,textContentLength:v.length,toolCallsCount:d.size}),F}let Pe=v?[{type:"text",text:v}]:[],ge=[],he=[];k&&(he.push({type:"thinking",thinking:k}),s?.onThinkingEnd?.(k));for(let[,E]of d)E.id&&E.name&&ge.push({type:"tool_use",id:E.id,name:E.name,input:re(E.arguments)});return{textBlocks:Pe,toolBlocks:ge,thinkingBlocks:he,usage:x,stopReason:m??void 0}},a,3,s?.onRateLimit,s?.onRetryAfter)}supportsNonStreamingFallback(){return!0}async complete(e,o,n,r,s,a){return this.withRateLimit(async()=>{let c=this.stripCacheBoundariesFromMessages(e),{system:u,rest:p}=this.normalizeSystemForWire(n,c),l=s?.modelOverride??this.config.model,f=[{role:"system",content:u},...await this.convertMessages(p,l)],y=o.map(M=>({type:"function",function:{name:M.name,description:M.description,parameters:M.input_schema}})),h=s?.forcedToolName,b=!!h,d=this.normalizeReasoning(r),v=te(d)?this.getReasoningCapability(l):"none",k=te(d)?this.getReasoningFallbackChain(v).filter(M=>M==="native-budget"||M==="native-effort"||M==="native-toggle"||M==="none"):["none"],x={model:l,messages:f,tools:y,max_completion_tokens:s?.maxOutputTokensOverride??this.getEffectiveMaxOutputTokens(l)};h&&b&&(x.tool_choice={type:"function",function:{name:h}});let C,m;for(let M of k){for(;!C;){let D={...x};this.resetReasoningCapabilityParams(D),this.applyReasoningCapability(D,M,d);try{C=await this.client.chat.completions.create(D,a?{signal:a}:{}),M!==v&&this.persistReasoningCapabilityOverride(M,l)}catch(z){if(m=z,b&&this.shouldFallbackForForcedToolChoiceError(z)){b=!1,delete x.tool_choice,this.logStreamDiagnostic(`[${this.name}] upstream rejected forced tool_choice; retrying without forced tool choice`);continue}if(!this.shouldFallbackForReasoningError(z,...this.getFallbackTerms(M)))throw z;break}}if(C)break}if(!C)throw m??new R("All reasoning capability attempts failed without a captured error",this.name);let T=C.choices[0],P=T?.message,L=Tn(P?.content),N=En(P),j=(P?.tool_calls??[]).filter(xn).map(M=>({type:"tool_use",id:M.id,name:M.function.name,input:re(M.function.arguments)}));L&&s?.onTextDelta?.(L);let B=L?[{type:"text",text:L}]:[],J=[];return N&&(J.push({type:"thinking",thinking:N}),s?.onThinkingDelta?.(N),s?.onThinkingEnd?.(N)),{textBlocks:B,toolBlocks:j,thinkingBlocks:J,usage:fo(C.usage),stopReason:T?.finish_reason??void 0}},a,3,s?.onRateLimit,s?.onRetryAfter)}extractReasoningDelta(e){let o=e?.reasoning_content;return typeof o=="string"?o:Array.isArray(o)?o.map(n=>typeof n=="string"?n:typeof n=="object"&&n!==null&&"text"in n&&typeof n.text=="string"?n.text:"").join(""):""}serializeAssistantMessage(e,o){let n=e.filter(p=>p.type==="text").map(p=>p.text).join(`
|
|
13
|
-
`),r=e.filter(p=>p.type==="tool_use").map(p=>({id:p.id,type:"function",function:{name:p.name,arguments:JSON.stringify(p.input??{})}})),s=e.filter(p=>p.type==="thinking"||p.type==="redacted_thinking").map(p=>p.type==="thinking"?p.thinking:"").filter(Boolean).join(`
|
|
14
|
-
|
|
15
|
-
`),a=e.some(p=>p.type==="thinking"||p.type==="redacted_thinking");if(!n&&r.length===0&&!a)return[];let c;n?c=n:r.length>0?c=null:c="...";let u={role:"assistant",content:c};return r.length>0&&(u.tool_calls=r),this.getEffectiveReplayReasoningContent(o)&&(u.reasoning_content=s||""),[u]}async serializeUserMessage(e){let o=[],n=e.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
16
|
-
`),r=e.filter(a=>a.type==="image");for(let a of e)if(a.type==="tool_result"){let c;typeof a.content=="string"?c=a.content:c=a.content.map(u=>u.type==="text"?u.text:`[Image at ${u.path}${u.mediaType?` (${u.mediaType})`:""}] (provider does not support image content in tool_result; if the image was previously visible to you in the conversation, refer to it directly via native vision)`).join(`
|
|
17
|
-
`),o.push({role:"tool",tool_call_id:a.tool_use_id,content:c})}if(r.length===0)return n&&o.push({role:"user",content:n}),o;let s=[];n&&s.push({type:"text",text:n});for(let a of r)s.push({type:"image_url",image_url:{url:await po(a.path,a.mediaType)}});return o.push({role:"user",content:s}),o}serializeSystemMessage(e){if(typeof e=="string")return[{role:"system",content:e}];let o=e.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
18
|
-
`);return o?[{role:"system",content:o}]:[]}async convertMessages(e,o){let n=[];for(let r of e){if(r.role==="system"){n.push(...this.serializeSystemMessage(r.content));continue}if(typeof r.content=="string"){n.push({role:r.role,content:r.content});continue}if(r.role==="assistant"){n.push(...this.serializeAssistantMessage(r.content,o));continue}n.push(...await this.serializeUserMessage(r.content))}return n}};import{spawn as Rn}from"node:child_process";import{Readable as An,Writable as On}from"node:stream";import Be from"node:process";import{ClientSideConnection as Dn,PROTOCOL_VERSION as In,ndJsonStream as Nn}from"@agentclientprotocol/sdk";import{spawn as Mn,spawnSync as vo}from"node:child_process";var wt=2e3,be=2e3;function Mt(t){return t.exitCode!==null||t.signalCode!==null}i(Mt,"isExited");function Et(t,e){return Mt(t)?Promise.resolve(!0):new Promise(o=>{let n=!1,r=i(c=>{n||(n=!0,clearTimeout(a),t.off("exit",s),t.off("error",s),o(c))},"finish"),s=i(()=>r(!0),"onExit"),a=setTimeout(()=>r(!1),e);a.unref?.(),t.once("exit",s),t.once("error",s)})}i(Et,"waitForExit");function mo(t){return new Promise(e=>{let o=Mn("taskkill",["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),n=!1,r=i(()=>{n||(n=!0,clearTimeout(s),e())},"finish"),s=setTimeout(()=>{try{o.kill()}catch{}r()},wt);s.unref?.(),o.once("exit",r),o.once("error",r)})}i(mo,"runTaskkill");function go(t,e){let o=!1;try{process.kill(-t,e),o=!0}catch{}try{process.kill(t,e),o=!0}catch{}return o}i(go,"signalPosixPidTree");function Pt(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}i(Pt,"signalTargetExists");function ho(t){return Pt(-t)||Pt(t)}i(ho,"isPosixPidTreeAlive");async function yo(t,e){let o=Date.now()+e;for(;Date.now()<o;){if(!ho(t))return!0;await new Promise(n=>setTimeout(n,50))}return!ho(t)}i(yo,"waitForPosixPidTreeExit");function Pn(t){let e=t.trim();if(!e)return[];try{let o=JSON.parse(e);return(Array.isArray(o)?o:[o]).map(r=>Number(r)).filter(r=>Number.isFinite(r)&&r>0)}catch{return[]}}i(Pn,"readWindowsPidListJson");function wn(t){let e=vo("wmic",["process","where",`ParentProcessId=${t}`,"get","ProcessId","/format:list"],{encoding:"utf8",timeout:wt,windowsHide:!0});if(e.error||e.status!==0)return[];let o=[],n=/ProcessId=(\d+)/g,r;for(;(r=n.exec(e.stdout))!==null;){let s=Number(r[1]);Number.isFinite(s)&&s>0&&s!==t&&o.push(s)}return o}i(wn,"getWindowsChildPidsViaWmic");function Sn(t){let e=[`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${t}"`,"if ($null -eq $children) { exit 0 }","$children | Select-Object -ExpandProperty ProcessId | ConvertTo-Json -Compress"].join("; "),o=vo("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",timeout:wt,windowsHide:!0});if(!o.error&&o.status===0){let n=Pn(o.stdout);if(n.length>0)return n}return wn(t)}i(Sn,"getWindowsChildPids");function ko(t,e=new Set){let o=[];for(let n of Sn(t))e.has(n)||(e.add(n),o.push(n),o.push(...ko(n,e)));return o}i(ko,"collectWindowsDescendantPids");async function Ce(t){if(process.platform==="win32"&&t.pid!==void 0){let e=ko(t.pid);Mt(t)||await mo(t.pid);for(let o of e.reverse())Pt(o)&&await mo(o);await Et(t,be);return}if(t.pid!==void 0&&process.platform!=="win32"){if(!go(t.pid,"SIGTERM")||await yo(t.pid,be))return;go(t.pid,"SIGKILL"),await yo(t.pid,be);return}if(!Mt(t)){try{t.kill("SIGTERM")}catch{return}if(!await Et(t,be)){try{t.kill("SIGKILL")}catch{}await Et(t,be)}}}i(Ce,"killChildProcessTree");var Fe=class{static{i(this,"AcpClient")}client=null;agentProcess=null;options;constructor(e){this.options=e}async connect(){let e,o;if(this.options.inputStream&&this.options.outputStream)e=this.options.inputStream,o=this.options.outputStream;else if(this.options.command){let s=Be.platform==="win32"&&!this.options.command.endsWith(".cmd")?`${this.options.command}.cmd`:this.options.command;if(this.agentProcess=Rn(s,this.options.args??[],{cwd:this.options.cwd??Be.cwd(),stdio:["pipe","pipe","inherit"],detached:Be.platform!=="win32"}),!this.agentProcess.stdin||!this.agentProcess.stdout)throw new Error("Failed to create ACP stdio pipes");o=On.toWeb(this.agentProcess.stdin),e=An.toWeb(this.agentProcess.stdout)}else throw new Error("AcpClient requires either a command or I/O streams");let n=Nn(o,e);this.client=new Dn(()=>({sessionUpdate:i(async r=>{this.options.onSessionUpdate?.(r)},"sessionUpdate"),requestPermission:i(async r=>{let s=r.options??[],a=s.find(c=>c.kind==="allow_once"||c.kind==="allow_always")??s[0];return a?{outcome:{outcome:"selected",optionId:a.optionId}}:{outcome:{outcome:"cancelled"}}},"requestPermission")}),n),await this.client.initialize({protocolVersion:In,clientCapabilities:{},clientInfo:{name:"kodax-ai-acp-client",version:"1.0.0"}})}async createNewSession(){if(!this.client)throw new Error("Client not connected");return(await this.client.newSession({cwd:this.options.cwd??Be.cwd(),mcpServers:[]})).sessionId}async prompt(e,o,n,r){if(!this.client)throw new Error("Client not connected");let s={sessionId:o,prompt:[{type:"text",text:e}]};r?.model&&(s.model=r.model);let a=this.client.prompt(s);if(n){let c=i(()=>{this.client?.cancel({sessionId:o}).catch(()=>{})},"onAbort");n.addEventListener("abort",c),a=a.finally(()=>{n.removeEventListener("abort",c)})}return await a}disconnect(){this.agentProcess&&Ce(this.agentProcess),this.options.abort?.();try{this.client?.close?.()}catch{}this.client=null,this.agentProcess=null}};function Ln(t){if(!t||typeof t!="object")return;let e=t,o=typeof e.inputTokens=="number"?e.inputTokens:0,n=typeof e.outputTokens=="number"?e.outputTokens:0,r=typeof e.totalTokens=="number"?e.totalTokens:o+n;if(![o,n,r].some(s=>!Number.isFinite(s)||s<0)&&!(r<o||r<n))return{inputTokens:o,outputTokens:n,totalTokens:r,cachedReadTokens:typeof e.cachedReadTokens=="number"?e.cachedReadTokens:void 0,cachedWriteTokens:typeof e.cachedWriteTokens=="number"?e.cachedWriteTokens:void 0,thoughtTokens:typeof e.thoughtTokens=="number"?e.thoughtTokens:void 0}}i(Ln,"normalizeAcpUsage");var ce=class extends V{static{i(this,"KodaXAcpProvider")}_client=null;_sessionMap=new Map;_activeStreams=new Map;isConfigured(){return!0}async verifyCredential(){return{ok:!1,error:"unsupported",strategy:"unsupported",durationMs:0,approxTokensSpent:0,message:`CLI-bridge provider "${this.name}" manages credentials in its CLI binary's token store; not verifiable from the KodaX SDK`}}getCapabilityProfile(){return W(ve)}serializeImageBlockToPromptToken(e){return null}stripCacheBoundariesFromMessages(e){return e.map(o=>{if(typeof o.content=="string")return o;let n=ke(o.content);return n.length===o.content.length?o:{...o,content:n}})}async stream(e,o,n,r,s,a){if(e=this.stripCacheBoundariesFromMessages(e),this.acpClientOptions.executor&&typeof this.acpClientOptions.executor.isInstalled=="function"&&!await this.acpClientOptions.executor.isInstalled())throw new Error(`${this.name} requires a local CLI environment, but the CLI was not found or is not configured correctly.`);let c=[],u=[],p=e[e.length-1],l="";if(p&&typeof p.content=="string")l=p.content;else if(p&&Array.isArray(p.content)){let v=[];for(let k of p.content)if(k.type==="text")v.push(k.text);else if(k.type==="image"){let x=this.serializeImageBlockToPromptToken(k);x&&v.push(x)}l=v.join(`
|
|
19
|
-
`)}let f={...this.acpClientOptions,onSessionUpdate:i(v=>{let k=v.update,x=v.sessionId;if(!("sessionUpdate"in k))return;let C=x?this._activeStreams.get(x):void 0;if(C)switch(k.sessionUpdate){case"agent_message_chunk":if(k.content?.type==="text"){let m=k.content.text;C.output.text+=m,C.streamOptions?.onTextDelta?.(m)}break;case"tool_call":{let m="{}",T=k.arguments??k.parameters;T&&(m=typeof T=="string"?T:JSON.stringify(T)),C.streamOptions?.onToolInputDelta?.(k.title,m);let P=`
|
|
20
|
-
> [Tool Use] ${k.title}: ${m}
|
|
21
|
-
`;C.output.text+=P,C.streamOptions?.onTextDelta?.(P);break}case"tool_call_update":if(k.status){let m=`> [Tool Result] ${k.status}
|
|
22
|
-
|
|
23
|
-
`;C.output.text+=m,C.streamOptions?.onTextDelta?.(m)}break}},"onSessionUpdate")},y=s?.sessionId??"default";this._client||(this._client=new Fe(f),await this._client.connect());let h=this._sessionMap.get(y);h||(h=await this._client.createNewSession(),this._sessionMap.set(y,h));let b={text:""};this._activeStreams.set(h,{streamOptions:s,output:b});let d;try{d=await this._client.prompt(l,h,a,{model:s?.modelOverride})}catch(v){if(!(v instanceof Error&&v.name==="AbortError"))throw v}finally{this._activeStreams.delete(h)}return b.text&&c.push({type:"text",text:b.text}),{textBlocks:c,toolBlocks:u,thinkingBlocks:[],usage:Ln(d?.usage)}}disconnect(){this._client&&(this._client.disconnect(),this._client=null),this._activeStreams.clear(),this._sessionMap.clear()}};import{spawn as Bn}from"node:child_process";import Ke from"node:process";var le=class{static{i(this,"CLIExecutor")}config;_installedCache=null;constructor(e){this.config=e}async isInstalled(){return this._installedCache!==null?this._installedCache:(this._installedCache=await this.checkInstalled(),this._installedCache)}async*execute(e){let o=this.buildArgs(e),n={...Ke.env,...this.config.env},s=Ke.platform==="win32"&&!this.config.command.endsWith(".cmd")?`${this.config.command}.cmd`:this.config.command,a=Bn(s,o,{cwd:this.config.cwd??Ke.cwd(),env:n,stdio:["ignore","pipe","pipe"],detached:Ke.platform!=="win32"}),c="";a.stderr?.on("data",l=>{c+=l.toString()});let u=!1,p=i(()=>{u||Ce(a)},"abortHandler");e.signal?.addEventListener("abort",p),a.on("exit",()=>{u=!0});try{yield*this.parseOutputStream(a.stdout,e.signal),c.trim()&&console.error(`[CLIExecutor] stderr: ${c.trim()}`)}finally{e.signal?.removeEventListener("abort",p),u||await Ce(a)}}async*parseOutputStream(e,o){let n="";for await(let r of e){if(o?.aborted)break;n+=r.toString();let s=n.split(`
|
|
24
|
-
`);n=s.pop()??"";for(let a of s){if(!a.trim())continue;let c=this.parseLine(a.trim());c&&(yield c)}}if(n.trim()&&!o?.aborted){let r=this.parseLine(n.trim());r&&(yield r)}}};import{spawn as Fn}from"node:child_process";import Kn from"node:process";async function $e(t){try{let e=Kn.platform==="win32",o=Fn(e?`${t}.cmd`:t,["--version"]);return await new Promise(n=>{o.on("close",r=>n(r===0)),o.on("error",()=>n(!1))})}catch{return!1}}i($e,"checkCliCommandInstalled");var Ue=class extends le{static{i(this,"GeminiCLIExecutor")}model;constructor(e){super({command:"gemini",baseArgs:["--output-format","stream-json","--approval-mode","yolo"],timeout:3e5,...e}),this.model=e?.model??"gemini-2.5-pro"}async checkInstalled(){return $e("gemini")}buildArgs(e){let o=["-m",e.model??this.model];return e.sessionId?(o.push("-r",e.sessionId),o.push(e.prompt)):o.push("-p",e.prompt),[...o,...this.config.baseArgs]}parseLine(e){if(!e.startsWith("{"))return null;try{let o=JSON.parse(e);return this.convertEvent(o)}catch{return null}}convertEvent(e){let o=e.timestamp?Date.parse(e.timestamp):Date.now();switch(e.type){case"init":return{type:"session_start",timestamp:o,sessionId:e.session_id??"",model:e.model??this.model,raw:e};case"message":return{type:"message",timestamp:o,role:e.role,content:e.content??"",delta:e.delta,raw:e};case"tool_use":return{type:"tool_use",timestamp:o,toolId:e.tool_id??"",toolName:e.tool_name??"",parameters:e.parameters??{},raw:e};case"tool_result":return{type:"tool_result",timestamp:o,toolId:e.tool_id??"",status:e.status==="success"?"success":"error",output:e.output??"",raw:e};case"error":return{type:"error",timestamp:o,errorType:"error",message:e.message??"Unknown error",raw:e};case"result":return{type:"complete",timestamp:o,status:e.status==="success"?"success":"failed",usage:e.stats?{inputTokens:e.stats.input_tokens??0,outputTokens:e.stats.output_tokens??0,totalTokens:e.stats.total_tokens??0}:void 0,raw:e};default:return null}}};import{TransformStream as bo}from"node:stream/web";import{randomUUID as St}from"node:crypto";function je(t){let e=new bo,o=new bo,n=e.readable.getReader(),r=o.writable.getWriter(),s=new TextDecoder,a=new TextEncoder,c="",u=St(),p=new AbortController,l=new Map;(async()=>{try{for(;;){let{done:d,value:v}=await n.read();if(d)break;c+=s.decode(v,{stream:!0});let k=c.split(`
|
|
25
|
-
`);c=k.pop()??"";for(let x of k)if(x.trim())try{let C=JSON.parse(x);y(C).catch(m=>{console.error("[PseudoAcpServer] Failed to handle request:",m)})}catch{console.error("[PseudoAcpServer] Failed to parse message:",x)}}}catch(d){console.error("[PseudoAcpServer] Stream read error:",d)}})();let f=i(async d=>{let v=JSON.stringify(d)+`
|
|
26
|
-
`;await r.write(a.encode(v))},"sendMsg");async function y(d){if(d.method==="initialize")await f({jsonrpc:"2.0",id:d.id,result:{protocolVersion:d.params.protocolVersion,serverInfo:{name:"pseudo-acp-server",version:"1.0.0"},serverCapabilities:{}}});else if(d.method==="session/new"||d.method==="sessions/new")u=d.params?.sessionId??St(),await f({jsonrpc:"2.0",id:d.id,result:{sessionId:u}});else if(d.method==="session/prompt"||d.method==="chat/prompt"){let v=new AbortController,k=d.params.sessionId;l.set(k,v);let x=i(()=>v.abort(),"onGlobalAbort");p.signal.addEventListener("abort",x);let m=await h(k,d.params.prompt,typeof d.params.model=="string"?d.params.model:void 0,v.signal).finally(()=>{l.delete(k),p.signal.removeEventListener("abort",x)});await f({jsonrpc:"2.0",id:d.id,result:m.usage?{stopReason:m.stopReason,usage:m.usage}:{stopReason:m.stopReason}})}else if(d.method==="session/cancel"||d.method==="chat/cancel"){let v=l.get(d.params.sessionId);v&&v.abort(),d.id!==void 0&&await f({jsonrpc:"2.0",id:d.id,result:{}})}else d.id!==void 0&&await f({jsonrpc:"2.0",id:d.id,result:{}})}i(y,"handleRequest");let h=i(async(d,v,k,x)=>{let C=v.find(m=>m.type==="text")?.text??"";try{let m=t.execute({prompt:C,model:k,sessionId:d==="default"?void 0:d,signal:x});for await(let T of m){let P=b(T);if(P&&await f({jsonrpc:"2.0",method:"session/update",params:{sessionId:d,update:P}}),T.type==="complete")return{stopReason:x.aborted?"cancelled":"end_turn",usage:T.usage}}return{stopReason:x.aborted?"cancelled":"end_turn"}}catch(m){return x.aborted||m instanceof Error&&m.name==="AbortError"?{stopReason:"cancelled"}:(console.error("[PseudoAcpServer] Error executing prompt:",m),await f({jsonrpc:"2.0",method:"session/update",params:{sessionId:d,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
27
|
-
[Fatal Error: ${m}]
|
|
28
|
-
`}}}}),{stopReason:"end_turn"})}},"executePrompt"),b=i(d=>{switch(d.type){case"message":if(d.role==="assistant"&&d.content)return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d.content}};break;case"tool_use":return{sessionUpdate:"tool_call",title:d.toolName,arguments:d.parameters,status:"running",toolCallId:d.toolId||St()};case"tool_result":return{sessionUpdate:"tool_call_update",toolCallId:d.toolId,status:d.status};case"error":return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
29
|
-
[Error: ${d.message}]
|
|
30
|
-
`}};case"complete":break}return null},"mapToAcpNotification");return{inputStream:o.readable,outputStream:e.writable,abort:i(()=>{p.abort(),e.readable.cancel().catch(()=>{}),o.writable.abort().catch(()=>{})},"abort"),executor:t}}i(je,"createPseudoAcpServer");import Co from"node:fs";import _o from"node:os";import xo from"node:path";var $n="gpt-5.4",Un="auto-gemini-3",jn=["gpt-5.4","gpt-5.3-codex","gpt-5.3-codex-spark"],Xn=["auto-gemini-3","gemini-3.1-pro-preview","gemini-3-flash-preview","gemini-2.5-pro","gemini-2.5-flash"];function To(t){let e=new Set,o=[];for(let n of t){let r=n.trim();if(!r)continue;let s=r.toLowerCase();e.has(s)||(e.add(s),o.push(r))}return o}i(To,"dedupePreserveOrder");function Wn(){let t=xo.join(_o.homedir(),".codex","config.toml");try{return Co.readFileSync(t,"utf8").match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1]?.trim()||null}catch{return null}}i(Wn,"readCodexConfiguredModel");function zn(){let t=xo.join(_o.homedir(),".gemini","settings.json");try{let e=JSON.parse(Co.readFileSync(t,"utf8")),o=typeof e.model=="string"?e.model.trim():"";return o||(typeof e.general?.model=="string"?e.general.model.trim():"")||null}catch{return null}}i(zn,"readGeminiConfiguredModel");function ue(){return Wn()||$n}i(ue,"getCodexCliDefaultModel");function de(){return zn()||Un}i(de,"getGeminiCliDefaultModel");function _e(){return To([ue(),...jn])}i(_e,"getCodexCliKnownModels");function xe(){return To([de(),...Xn])}i(xe,"getGeminiCliKnownModels");var Rt=de(),Vn=xe(),Gn={transport:"cli-bridge",conversationSemantics:"last-user-message",mcpSupport:"none",contextFidelity:"lossy",toolCallingFidelity:"limited",sessionSupport:"stateless",longRunningSupport:"limited",multimodalSupport:"image-input",evidenceSupport:"limited"},Xe=class extends ce{static{i(this,"KodaXGeminiCliProvider")}name="gemini-cli";supportsThinking=!1;config={apiKeyEnv:"GEMINI_CLI_API_KEY",model:Rt,models:Vn.filter(e=>e!==Rt).map(e=>({id:e,displayName:e})),supportsThinking:!1,reasoningCapability:"prompt-only",contextWindow:1048576};acpClientOptions;constructor(){super();let e=new Ue({model:Rt});this.acpClientOptions=je(e)}getCapabilityProfile(){return W(Gn)}serializeImageBlockToPromptToken(e){return/\s/.test(e.path)?(console.warn(`[gemini-cli] Image path contains whitespace and cannot be safely passed via @<path> syntax \u2014 dropping image block. Path: ${JSON.stringify(e.path)}`),null):`@${e.path}`}};var We=class extends le{static{i(this,"CodexCLIExecutor")}model;constructor(e){super({command:"codex",baseArgs:["exec","--json","--full-auto"],timeout:3e5,...e}),this.model=e?.model??"gpt-5.4"}async checkInstalled(){return $e("codex")}buildArgs(e){this.model=e.model??this.model;let o=e.model?["-m",e.model]:[];return e.sessionId?["exec","resume",e.sessionId,...o,e.prompt,...this.config.baseArgs.filter(n=>n!=="exec")]:[...this.config.baseArgs,...o,e.prompt]}parseLine(e){if(!e.startsWith("{"))return null;try{let o=JSON.parse(e);return this.convertEvent(o)}catch{return null}}convertEvent(e){let o=Date.now();switch(e.type){case"thread.started":return{type:"session_start",timestamp:o,sessionId:e.thread_id??"",model:this.model,raw:e};case"item.completed":return e.item?.type==="agent_message"?{type:"message",timestamp:o,role:"assistant",content:e.item.text??"",raw:e}:e.item?.type==="command_execution"?{type:"tool_use",timestamp:o,toolId:e.item.id,toolName:"Bash",parameters:{command:e.item.command},raw:e}:null;case"turn.completed":return{type:"complete",timestamp:o,status:"success",usage:e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens}:void 0,raw:e};case"error":case"turn.failed":return{type:"error",timestamp:o,errorType:e.type,message:e.message??"Unknown error",raw:e};default:return null}}};var At=ue(),Hn=_e(),ze=class extends ce{static{i(this,"KodaXCodexCliProvider")}name="codex-cli";supportsThinking=!1;config={apiKeyEnv:"CODEX_CLI_API_KEY",model:At,models:Hn.filter(e=>e!==At).map(e=>({id:e,displayName:e})),supportsThinking:!1,reasoningCapability:"prompt-only",contextWindow:128e3};acpClientOptions;constructor(){super();let e=new We({model:At});this.acpClientOptions=je(e)}};import{existsSync as ei,readFileSync as ti}from"node:fs";import pe from"node:path";import{fileURLToPath as oi}from"node:url";var Eo=["none","prompt-only","native-effort","native-budget","native-toggle","unknown"],Mo=["native","image-input-native","cli-bridge","image-input-cli-bridge"],Po=["count-tokens","models-list","minimal-message","unsupported"];function Te(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(Te,"isPlainObject");function Ge(t,e){if(typeof t!="string"||t.length===0)throw new Error(`provider-capabilities.json: ${e} must be a non-empty string`);return t}i(Ge,"requireString");function wo(t,e){if(t!==void 0)return Ge(t,e)}i(wo,"optionalString");function ee(t,e){if(t!==void 0){if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new Error(`provider-capabilities.json: ${e} must be a non-negative finite number`);return t}}i(ee,"optionalNumber");function Ve(t,e){if(t!==void 0){if(typeof t!="boolean")throw new Error(`provider-capabilities.json: ${e} must be a boolean`);return t}}i(Ve,"optionalBoolean");function Ot(t,e){if(typeof t!="string"||!Eo.includes(t))throw new Error(`provider-capabilities.json: ${e} must be one of ${Eo.join(", ")}, got ${JSON.stringify(t)}`);return t}i(Ot,"requireReasoningCapability");function Jn(t,e){if(typeof t!="string"||!Mo.includes(t))throw new Error(`provider-capabilities.json: ${e} must be one of ${Mo.join(", ")}, got ${JSON.stringify(t)}`);return t}i(Jn,"requireProfileName");function Yn(t,e){if(typeof t!="string"||!Po.includes(t))throw new Error(`provider-capabilities.json: ${e} must be one of ${Po.join(", ")}, got ${JSON.stringify(t)}`);return t}i(Yn,"requireVerifyStrategy");function qn(t,e){if(!Te(t))throw new Error(`provider-capabilities.json: ${e} must be an object`);let o=Ge(t.id,`${e}.id`),n=wo(t.displayName,`${e}.displayName`),r=ee(t.contextWindow,`${e}.contextWindow`),s=ee(t.maxOutputTokens,`${e}.maxOutputTokens`),a=ee(t.thinkingBudgetCap,`${e}.thinkingBudgetCap`),c=Ve(t.replayReasoningContent,`${e}.replayReasoningContent`),u=Ve(t.strictThinkingSignature,`${e}.strictThinkingSignature`),p=ee(t.streamMaxDurationMs,`${e}.streamMaxDurationMs`),l=t.reasoningCapability===void 0?void 0:Ot(t.reasoningCapability,`${e}.reasoningCapability`),f={id:o};return n!==void 0&&(f.displayName=n),r!==void 0&&(f.contextWindow=r),s!==void 0&&(f.maxOutputTokens=s),a!==void 0&&(f.thinkingBudgetCap=a),l!==void 0&&(f.reasoningCapability=l),c!==void 0&&(f.replayReasoningContent=c),u!==void 0&&(f.strictThinkingSignature=u),p!==void 0&&(f.streamMaxDurationMs=p),f}i(qn,"validateModelDescriptor");function Qn(t,e){if(t===void 0)return;if(!Te(t))throw new Error(`provider-capabilities.json: ${e} must be an object`);let o={};for(let[n,r]of Object.entries(t))o[n]=Ot(r,`${e}.${n}`);return o}i(Qn,"validateModelReasoningCapabilities");function Zn(t,e){if(!Te(t))throw new Error(`provider-capabilities.json: providers.${e} must be an object`);let o=Ve(t.cliBridge,`providers.${e}.cliBridge`),n=Ge(t.apiKeyEnv,`providers.${e}.apiKeyEnv`),r=Ot(t.reasoningCapability,`providers.${e}.reasoningCapability`),s=Jn(t.capabilityProfile,`providers.${e}.capabilityProfile`),a=Yn(t.verifyStrategy,`providers.${e}.verifyStrategy`);if(o&&a!=="unsupported")throw new Error(`provider-capabilities.json: providers.${e} is a cliBridge entry but verifyStrategy="${a}" \u2014 must be "unsupported" (CLI binary owns credentials)`);let c=ee(t.contextWindow,`providers.${e}.contextWindow`),u=ee(t.maxOutputTokens,`providers.${e}.maxOutputTokens`),p=ee(t.thinkingBudgetCap,`providers.${e}.thinkingBudgetCap`),l=Ve(t.supportsThinking,`providers.${e}.supportsThinking`),f=Qn(t.modelReasoningCapabilities,`providers.${e}.modelReasoningCapabilities`),y=wo(t.model,`providers.${e}.model`);if(o&&(y!==void 0||t.models!==void 0))throw new Error(`provider-capabilities.json: providers.${e} is a cliBridge entry but defines model/models \u2014 must be omitted (filled at load time)`);if(!o&&y===void 0)throw new Error(`provider-capabilities.json: providers.${e}.model is required (only cliBridge entries may omit)`);let h;if(t.models!==void 0){if(!Array.isArray(t.models))throw new Error(`provider-capabilities.json: providers.${e}.models must be an array`);h=t.models.map((d,v)=>qn(d,`providers.${e}.models[${v}]`))}let b={apiKeyEnv:n,reasoningCapability:r,capabilityProfile:s,verifyStrategy:a};return y!==void 0&&(b.model=y),h!==void 0&&(b.models=h),c!==void 0&&(b.contextWindow=c),u!==void 0&&(b.maxOutputTokens=u),p!==void 0&&(b.thinkingBudgetCap=p),l!==void 0&&(b.supportsThinking=l),f!==void 0&&(b.modelReasoningCapabilities=f),o&&(b.cliBridge=!0),b}i(Zn,"validateProviderEntry");function So(t){if(!Te(t))throw new Error("provider-capabilities.json: root must be an object");if(t.version!==1)throw new Error(`provider-capabilities.json: version must be 1, got ${JSON.stringify(t.version)}`);let e=Ge(t.updatedAt,"updatedAt");if(!Te(t.providers))throw new Error("provider-capabilities.json: providers must be an object");let o={};for(let[n,r]of Object.entries(t.providers))o[n]=Zn(r,n);return{version:1,updatedAt:e,providers:o}}i(So,"validateProviderCapabilitiesJson");var ni=Object.freeze({native:Z,"image-input-native":lo,"cli-bridge":ve,"image-input-cli-bridge":uo}),He=null;function ii(){if(process.env.KODAX_BUNDLED==="true")return pe.join(pe.dirname(process.execPath),"provider-capabilities.json");let t=pe.dirname(oi(import.meta.url)),e=[pe.join(t,"provider-capabilities.json"),pe.join(pe.dirname(t),"provider-capabilities.json")];for(let o of e)if(ei(o))return o;return e[0]}i(ii,"resolveJsonPath");function ri(t){if(t.models){for(let e of t.models)Object.freeze(e);Object.freeze(t.models)}return t.modelReasoningCapabilities&&Object.freeze(t.modelReasoningCapabilities),Object.freeze(t)}i(ri,"deepFreezeSnapshot");function si(t){if(t==="gemini-cli"){let e=de();return{model:e,models:xe().filter(o=>o!==e).map(o=>({id:o}))}}if(t==="codex-cli"){let e=ue();return{model:e,models:_e().filter(o=>o!==e).map(o=>({id:o}))}}throw new Error(`provider-capabilities loader: unknown cliBridge provider '${t}'`)}i(si,"resolveCliBridgeModels");function ai(t,e){let o=ni[e.capabilityProfile];if(!o)throw new Error(`provider-capabilities loader: unknown capabilityProfile '${e.capabilityProfile}' for provider '${t}'`);if(e.cliBridge){let r=si(t),s={model:r.model,models:r.models,apiKeyEnv:e.apiKeyEnv,reasoningCapability:e.reasoningCapability,capabilityProfile:o,verifyStrategy:e.verifyStrategy};return e.supportsThinking!==void 0&&(s.supportsThinking=e.supportsThinking),s}let n={model:e.model,apiKeyEnv:e.apiKeyEnv,reasoningCapability:e.reasoningCapability,capabilityProfile:o,verifyStrategy:e.verifyStrategy};return e.models!==void 0&&(n.models=e.models),e.modelReasoningCapabilities!==void 0&&(n.modelReasoningCapabilities=e.modelReasoningCapabilities),e.contextWindow!==void 0&&(n.contextWindow=e.contextWindow),e.maxOutputTokens!==void 0&&(n.maxOutputTokens=e.maxOutputTokens),e.thinkingBudgetCap!==void 0&&(n.thinkingBudgetCap=e.thinkingBudgetCap),e.supportsThinking!==void 0&&(n.supportsThinking=e.supportsThinking),n}i(ai,"buildSnapshot");function Ro(){if(He)return He;let t=ii(),e;try{let r=ti(t,"utf8");e=JSON.parse(r)}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`provider-capabilities loader: failed to read ${t}: ${s}`)}let o=So(e),n={};for(let[r,s]of Object.entries(o.providers))n[r]=ri(ai(r,s));return He=Object.freeze(n),He}i(Ro,"getProviderSnapshots");import ci from"@anthropic-ai/sdk";var A=Ro();function U(t,e={}){let o=A[t];return{apiKeyEnv:o.apiKeyEnv,model:o.model,reasoningCapability:o.reasoningCapability,models:o.models,contextWindow:o.contextWindow,maxOutputTokens:o.maxOutputTokens,thinkingBudgetCap:o.thinkingBudgetCap,supportsThinking:o.supportsThinking??!1,verifyStrategy:o.verifyStrategy,...e}}i(U,"buildProviderConfig");var Dt=class extends I{static{i(this,"AnthropicProvider")}name="anthropic";config=U("anthropic",{strictThinkingSignature:!0});constructor(){super(),this.client=new ci({apiKey:this.getApiKey()})}},It=class extends I{static{i(this,"ZhipuCodingProvider")}name="zhipu-coding";config=U("zhipu-coding",{baseUrl:"https://open.bigmodel.cn/api/anthropic",streamMaxDurationMs:3e5});constructor(){super(),this.initClient()}},Nt=class extends I{static{i(this,"KimiCodeProvider")}name="kimi-code";config=U("kimi-code",{baseUrl:"https://api.kimi.com/coding/"});constructor(){super(),this.initClient()}},Lt=class extends I{static{i(this,"MiniMaxCodingProvider")}name="minimax-coding";config=U("minimax-coding",{baseUrl:"https://api.minimaxi.com/anthropic"});constructor(){super(),this.initClient()}},Bt=class extends I{static{i(this,"MimoCodingProvider")}name="mimo-coding";config=U("mimo-coding",{baseUrl:"https://token-plan-cn.xiaomimimo.com/anthropic"});constructor(){super(),this.initClient()}},Ft=class extends I{static{i(this,"MimoProvider")}name="mimo";config=U("mimo",{baseUrl:"https://api.xiaomimimo.com/anthropic"});constructor(){super(),this.initClient()}},Kt=class extends I{static{i(this,"ArkCodingProvider")}name="ark-coding";config=U("ark-coding",{baseUrl:"https://ark.cn-beijing.volces.com/api/coding"});constructor(){super(),this.initClient()}},$t=class extends K{static{i(this,"OpenAIProvider")}name="openai";config=U("openai");constructor(){super(),this.initClient()}},Ut=class extends K{static{i(this,"DeepSeekProvider")}name="deepseek";config=U("deepseek",{baseUrl:"https://api.deepseek.com",replayReasoningContent:!0});constructor(){super(),this.initClient()}},jt=class extends K{static{i(this,"KimiProvider")}name="kimi";config=U("kimi",{baseUrl:"https://api.moonshot.cn/v1",replayReasoningContent:!0});constructor(){super(),this.initClient()}},Xt=class extends K{static{i(this,"QwenProvider")}name="qwen";config=U("qwen",{baseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",replayReasoningContent:!0});constructor(){super(),this.initClient()}},Wt=class extends K{static{i(this,"ZhipuProvider")}name="zhipu";config=U("zhipu",{baseUrl:"https://open.bigmodel.cn/api/paas/v4",replayReasoningContent:!0});constructor(){super(),this.initClient()}},$={anthropic:i(()=>new Dt,"anthropic"),openai:i(()=>new $t,"openai"),deepseek:i(()=>new Ut,"deepseek"),kimi:i(()=>new jt,"kimi"),"kimi-code":i(()=>new Nt,"kimi-code"),qwen:i(()=>new Xt,"qwen"),zhipu:i(()=>new Wt,"zhipu"),"zhipu-coding":i(()=>new It,"zhipu-coding"),"minimax-coding":i(()=>new Lt,"minimax-coding"),"mimo-coding":i(()=>new Bt,"mimo-coding"),mimo:i(()=>new Ft,"mimo"),"ark-coding":i(()=>new Kt,"ark-coding"),"gemini-cli":i(()=>new Xe,"gemini-cli"),"codex-cli":i(()=>new ze,"codex-cli")},zt=process.env.KODAX_PROVIDER??"zhipu-coding",Ao=new Map;function li(t){if(O(t))return A[t].apiKeyEnv}i(li,"resolveApiKeyEnvForProvider");function Oo(t){let e=t??zt,o=$[e];if(!o)throw new R(`Unknown provider: ${e}. Available: ${Object.keys($).join(", ")}`,e);let n=li(e),r=n?process.env[n]:void 0,s=Ao.get(e);if(s&&s.apiKey===r)return s.instance;let a=o();return Ao.set(e,{apiKey:r,instance:a}),a}i(Oo,"getProvider");function Do(t){return O(t)?!!process.env[A[t].apiKeyEnv]:!1}i(Do,"isProviderConfigured");function Io(t){return O(t)?A[t].model:null}i(Io,"getProviderModel");function No(t,e){if(!O(t))return"unknown";let o=A[t],n=e??o.model;return o.modelReasoningCapabilities?.[n]??o.reasoningCapability}i(No,"getProviderConfiguredReasoningCapability");function Lo(t){return O(t)?W(A[t].capabilityProfile):null}i(Lo,"getProviderConfiguredCapabilityProfile");function Bo(){let t=[];for(let e of Object.keys($)){let o=A[e];t.push({name:e,model:o.model,models:o.models?[o.model,...o.models.map(n=>n.id)]:[o.model],configured:!!process.env[o.apiKeyEnv],reasoningCapability:o.reasoningCapability,capabilityProfile:W(o.capabilityProfile)})}return t}i(Bo,"getProviderList");function Fo(t){let e=A[t];return e?e.models?[e.model,...e.models.map(o=>o.id)]:[e.model]:[]}i(Fo,"getProviderModels");function O(t){return t in $}i(O,"isProviderName");function Vt(t){return{id:t.model}}i(Vt,"makeDefaultDescriptor");function Je(t,e,o){let n=o.id===e.model;return{provider:t,model:o.id,displayName:o.displayName??o.id,supportsThinking:e.supportsThinking??!1,reasoningCapability:o.reasoningCapability??e.reasoningCapability,contextWindow:o.contextWindow??e.contextWindow,maxOutputTokens:o.maxOutputTokens??e.maxOutputTokens,thinkingBudgetCap:o.thinkingBudgetCap??e.thinkingBudgetCap,isDefault:n}}i(Je,"effectiveCapabilities");function Ye(t){let e=A[t];return e?[Vt(e),...e.models??[]]:[]}i(Ye,"getProviderModelDescriptors");function qe(t,e){let o=A[t];if(!o)return;if(e===o.model)return Je(t,o,Vt(o));let n=o.models?.find(r=>r.id===e);if(n)return Je(t,o,n)}i(qe,"getModelCapabilities");function Qe(){let t=[];for(let e of Object.keys($)){let o=A[e];t.push(Je(e,o,Vt(o)));for(let n of o.models??[])t.push(Je(e,o,n))}return t}i(Qe,"listBuiltinModelCapabilities");var ui=new Set(["compat","sdk"]),di=new Set(["count-tokens","models-list","minimal-message","unsupported"]);function pi(t){return t==="anthropic"?"count-tokens":"models-list"}i(pi,"defaultVerifyStrategyForProtocol");function Ee(t){if(!t.name||!t.baseUrl||!t.apiKeyEnv||!t.model)throw new Error(`Custom provider requires name, baseUrl, apiKeyEnv, and model. Got: ${JSON.stringify({name:t.name,baseUrl:t.baseUrl,apiKeyEnv:t.apiKeyEnv,model:t.model})}`);if(t.protocol!=="anthropic"&&t.protocol!=="openai")throw new Error(`Unknown protocol "${t.protocol}" for custom provider "${t.name}". Must be "anthropic" or "openai".`);if(t.userAgentMode!==void 0&&!ui.has(t.userAgentMode))throw new Error(`Unknown userAgentMode "${t.userAgentMode}" for custom provider "${t.name}". Must be "compat" or "sdk".`);if(t.verifyStrategy!==void 0){if(!di.has(t.verifyStrategy))throw new Error(`Unknown verifyStrategy "${t.verifyStrategy}" for custom provider "${t.name}". Must be one of "count-tokens" | "models-list" | "minimal-message" | "unsupported".`);if(t.protocol==="openai"&&t.verifyStrategy==="count-tokens")throw new Error(`Custom provider "${t.name}": verifyStrategy="count-tokens" requires Anthropic protocol; got protocol="openai". Use "models-list" or "minimal-message" for OpenAI-compat.`)}}i(Ee,"validateCustomProviderConfig");function fi(t){let e=t.models?.length?t.models.map(o=>typeof o=="string"?{id:o}:o):void 0;return{apiKeyEnv:t.apiKeyEnv,model:t.model,baseUrl:t.baseUrl,models:e,userAgentMode:t.userAgentMode,supportsThinking:t.supportsThinking??!1,reasoningCapability:t.reasoningCapability??"none",capabilityProfile:t.capabilityProfile,contextWindow:t.contextWindow,maxOutputTokens:t.maxOutputTokens,thinkingBudgetCap:t.thinkingBudgetCap,replayReasoningContent:t.replayReasoningContent??!1,strictThinkingSignature:t.strictThinkingSignature??!1,streamMaxDurationMs:t.streamMaxDurationMs,verifyStrategy:t.verifyStrategy??pi(t.protocol)}}i(fi,"buildProviderConfig");function Ze(t){Ee(t);let e=fi(t);return t.protocol==="anthropic"?new Gt(t.name,e):new Ht(t.name,e)}i(Ze,"createCustomProvider");var Gt=class extends I{static{i(this,"DynamicAnthropicProvider")}name;config;constructor(e,o){super(),this.name=e,this.config=o,this.initClient()}},Ht=class extends K{static{i(this,"DynamicOpenAIProvider")}name;config;constructor(e,o){super(),this.name=e,this.config=o,this.initClient()}};var G=new Map,Jt=new Map;function Ko(t){let e=new Set,o=new Map,n=new Map;for(let r of t){if(Ee(r),e.has(r.name))throw new Error(`Duplicate custom provider name: "${r.name}". Each custom provider must have a unique name.`);r.name in $&&console.warn(`[kodax] Custom provider "${r.name}" shadows a built-in provider. The built-in provider will be used. Choose a different name to use your custom provider.`),e.add(r.name),o.set(r.name,r),n.set(r.name,()=>Ze(r))}G.clear(),Jt.clear();for(let[r,s]of o)G.set(r,s);for(let[r,s]of n)Jt.set(r,s)}i(Ko,"registerCustomProviders");function et(t){let e=Jt.get(t);return e?e():void 0}i(et,"getCustomProvider");function me(t){return G.has(t)}i(me,"isCustomProviderName");function tt(){return[...G.keys()]}i(tt,"getCustomProviderNames");function $o(){let t=[];for(let[e,o]of G){let n=!!process.env[o.apiKeyEnv],r=(o.models??[]).map(a=>typeof a=="string"?a:a.id),s=o.model&&r.length?[...new Set([o.model,...r])]:[o.model];t.push({name:e,model:o.model,models:s,configured:n,reasoningCapability:o.reasoningCapability??"none",capabilityProfile:W(o.capabilityProfile??Z),custom:!0})}return t}i($o,"getCustomProviderList");function Uo(t){let e=G.get(t);if(!e)return;let o=(e.models??[]).map(n=>typeof n=="string"?n:n.id);return e.model&&o.length?[...new Set([e.model,...o])]:[e.model]}i(Uo,"getCustomProviderModels");function jo(t){return typeof t=="string"?{id:t}:t}i(jo,"customDescriptorToFull");function ot(t){let e=G.get(t);if(!e)return;let o={id:e.model},n=(e.models??[]).map(jo).filter(r=>r.id!==e.model);return[o,...n]}i(ot,"getCustomProviderModelDescriptors");function fe(t,e){let o=G.get(t);if(!o)return;let n=e===o.model,r=n?{id:o.model}:(o.models??[]).map(jo).find(s=>s.id===e);if(r)return{provider:t,model:r.id,displayName:r.displayName??r.id,supportsThinking:o.supportsThinking??!1,reasoningCapability:r.reasoningCapability??o.reasoningCapability??"none",contextWindow:r.contextWindow??o.contextWindow,maxOutputTokens:r.maxOutputTokens??o.maxOutputTokens,thinkingBudgetCap:r.thinkingBudgetCap??o.thinkingBudgetCap,isDefault:n}}i(fe,"getCustomModelCapabilities");function Xo(t){let e=G.get(t);if(!e)return;let o=e.verifyStrategy??(e.protocol==="anthropic"?"count-tokens":"models-list");return{apiKeyEnv:e.apiKeyEnv,verifyStrategy:o}}i(Xo,"getCustomProviderVerifyMetadata");function nt(){let t=[];for(let[e,o]of G){let n=fe(e,o.model);n&&t.push(n);for(let r of o.models??[]){let s=typeof r=="string"?r:r.id;if(s===o.model)continue;let a=fe(e,s);a&&t.push(a)}}return t}i(nt,"listCustomProviderModelCapabilities");var Y=new Map,mi=0;function Yt(t){let e=Y.get(t);if(!(!e||e.length===0))return e[e.length-1]}i(Yt,"getActiveRuntimeProviderRegistration");function gi(t){for(let[e,o]of Y){let n=o.filter(r=>r.id!==t);if(n.length!==o.length){n.length===0?Y.delete(e):Y.set(e,n);return}}}i(gi,"removeRuntimeProviderRegistration");function Wo(t,e){let o=t.trim();if(!o)throw new Error("Model provider name cannot be empty.");if(O(o))throw new Error(`Runtime model provider "${o}" conflicts with a built-in provider.`);if(me(o))throw new Error(`Runtime model provider "${o}" conflicts with an existing config-defined custom provider.`);let n={id:`runtime-provider:${++mi}`,name:o,factory:e},r=Y.get(o)??[];return Y.set(o,[...r,n]),()=>{gi(n.id)}}i(Wo,"registerModelProvider");function it(t){let e=Yt(t);return e?e.factory():void 0}i(it,"getRuntimeModelProvider");function Me(t){return Yt(t)!==void 0}i(Me,"isRuntimeModelProviderName");function rt(){return Array.from(Y.keys()).filter(t=>Yt(t)!==void 0)}i(rt,"getRuntimeModelProviderNames");function zo(){Y.clear()}i(zo,"clearRuntimeModelProviders");function qt(t){if(O(t))return $[t]();let e=it(t);if(e)return e;let o=et(t);if(o)return o;let n=at();throw new Error(`Unknown provider: ${t}. Available: ${n.join(", ")}`)}i(qt,"resolveProvider");function st(t){return O(t)||Me(t)||me(t)}i(st,"isKnownProvider");function at(){let t=Object.keys($),e=rt(),o=tt();return[...new Set([...t,...e,...o])]}i(at,"getAvailableProviderNames");function Qt(t){return O(t)?Ye(t):ot(t)??[]}i(Qt,"resolveProviderModelDescriptors");function Vo(t,e){return O(t)?qe(t,e):fe(t,e)}i(Vo,"resolveModelCapabilities");function Go(){return[...Qe(),...nt()]}i(Go,"listAllModelCapabilities");function hi(t){if(O(t)){let e=A[t];return{apiKeyEnv:e.apiKeyEnv,verifyStrategy:e.verifyStrategy}}if(!Me(t))return Xo(t)}i(hi,"getProviderVerifyMetadata");async function Ho(t,e){let o=hi(t);if(!o&&!st(t))return{ok:!1,error:"unsupported",strategy:"unsupported",durationMs:0,approxTokensSpent:0,message:`Unknown provider: "${t}". Available: ${at().join(", ")}`};if(o?.verifyStrategy==="unsupported")return{ok:!1,error:"unsupported",strategy:"unsupported",durationMs:0,approxTokensSpent:0,message:`Provider "${t}" does not support credential verification (cli-bridge or strategy marked unsupported)`};if(o&&!process.env[o.apiKeyEnv])return{ok:!1,error:"unconfigured",strategy:o.verifyStrategy,durationMs:0,approxTokensSpent:0,message:`Environment variable "${o.apiKeyEnv}" is not set for provider "${t}"`};let n;try{n=qt(t)}catch(r){return{ok:!1,error:"unconfigured",strategy:o?.verifyStrategy??"unsupported",durationMs:0,approxTokensSpent:0,message:String(r?.message??r).slice(0,240)}}try{return await n.verifyCredential(e)}catch(r){return{ok:!1,error:"unknown",strategy:o?.verifyStrategy??"unsupported",durationMs:0,approxTokensSpent:0,message:String(r?.message??r).slice(0,240)}}}i(Ho,"verifyProviderCredential");async function Jo(t,e){if(!st(t))return{ok:!1,source:"failed",error:`Unknown provider: "${t}"`,durationMs:0};let o=Qt(t);return o.length===0?{ok:!1,source:"failed",error:`Provider "${t}" has no static model list`,durationMs:0}:{ok:!0,source:"static",models:o.map(r=>r.id),durationMs:0}}i(Jo,"listProviderModels");var Yo={anthropic:{"claude-opus-4-6":{inputPer1M:15,outputPer1M:75,cachePer1M:1.875},"claude-sonnet-4-6":{inputPer1M:3,outputPer1M:15,cachePer1M:.375},"claude-haiku-4-5":{inputPer1M:.8,outputPer1M:4,cachePer1M:.08}},openai:{"gpt-5.4":{inputPer1M:30,outputPer1M:120},"gpt-5.3-codex-spark":{inputPer1M:10,outputPer1M:40}},deepseek:{"deepseek-v4-flash":{inputPer1M:.14,outputPer1M:.28,cachePer1M:.028},"deepseek-v4-pro":{inputPer1M:1.68,outputPer1M:3.36,cachePer1M:.14}},kimi:{"k2.5":{inputPer1M:.005,outputPer1M:.015},"kimi-k2.6":{inputPer1M:.005,outputPer1M:.015}},"kimi-code":{"kimi-for-coding":{inputPer1M:.005,outputPer1M:.015}},qwen:{"qwen3.5-plus":{inputPer1M:.003,outputPer1M:.006}},zhipu:{"glm-5":{inputPer1M:.05,outputPer1M:.1},"glm-5.1":{inputPer1M:.05,outputPer1M:.1},"glm-5-turbo":{inputPer1M:.01,outputPer1M:.03}},"zhipu-coding":{"glm-5":{inputPer1M:.05,outputPer1M:.1},"glm-5.1":{inputPer1M:.05,outputPer1M:.1},"glm-5-turbo":{inputPer1M:.01,outputPer1M:.03}},"minimax-coding":{"MiniMax-M3":{inputPer1M:.01,outputPer1M:.03},"MiniMax-M2.7":{inputPer1M:.01,outputPer1M:.03},"MiniMax-M2.7-highspeed":{inputPer1M:.01,outputPer1M:.03}},"mimo-coding":{"mimo-v2.5-pro":{inputPer1M:.01,outputPer1M:.03},"mimo-v2.5":{inputPer1M:.01,outputPer1M:.03}},mimo:{"mimo-v2.5-pro":{inputPer1M:.01,outputPer1M:.03},"mimo-v2.5":{inputPer1M:.01,outputPer1M:.03}},"ark-coding":{"glm-5.1":{inputPer1M:.005,outputPer1M:.015},"glm-4.7":{inputPer1M:.005,outputPer1M:.015},"kimi-k2.6":{inputPer1M:.005,outputPer1M:.015},"MiniMax-M3":{inputPer1M:.005,outputPer1M:.015},"MiniMax-M2.7":{inputPer1M:.005,outputPer1M:.015},"deepseek-v3.2":{inputPer1M:.005,outputPer1M:.015},"deepseek-v4-pro":{inputPer1M:.005,outputPer1M:.015},"deepseek-v4-flash":{inputPer1M:.005,outputPer1M:.015},"doubao-seed-2.0-code":{inputPer1M:.005,outputPer1M:.015},"doubao-seed-2.0-pro":{inputPer1M:.005,outputPer1M:.015},"doubao-seed-2.0-lite":{inputPer1M:.005,outputPer1M:.015}},"gemini-cli":{},"codex-cli":{}};function Zt(t,e,o){let n=o?.[t]?.[e];return n||Yo[t]?.[e]}i(Zt,"getCostRate");function eo(t,e,o,n=0){let r=e/1e6*t.inputPer1M,s=o/1e6*t.outputPer1M,a=t.cachePer1M?n/1e6*t.cachePer1M:0;return r+s+a}i(eo,"calculateCost");function yi(){return{records:[],retries:[]}}i(yi,"createCostTracker");function vi(t,e){let o={timestamp:Date.now(),provider:e.provider,waitMs:e.waitMs,reason:e.reason,source:e.source};return{records:t.records,retries:[...t.retries,o]}}i(vi,"recordRetry");function to(t,e,o){let n=Zt(e.provider,e.model,o),r=(e.cacheReadTokens??0)+(e.cacheWriteTokens??0),s=n?eo(n,e.inputTokens,e.outputTokens,r):0,a={timestamp:Date.now(),provider:e.provider,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheReadTokens:e.cacheReadTokens??0,cacheWriteTokens:e.cacheWriteTokens??0,cost:s,role:e.role};return{records:[...t.records,a],retries:t.retries}}i(to,"recordUsage");function ki(t){let e=0,o=0,n=0,r=0,s=0,a=0,c={},u={};for(let f of t.records){e+=f.cost,o+=f.inputTokens,n+=f.outputTokens,r+=f.cacheReadTokens+f.cacheWriteTokens,s+=f.cacheReadTokens,a+=f.cacheWriteTokens;let y=c[f.provider];c[f.provider]={cost:(y?.cost??0)+f.cost,calls:(y?.calls??0)+1,inputTokens:(y?.inputTokens??0)+f.inputTokens,outputTokens:(y?.outputTokens??0)+f.outputTokens};let h=f.role??"default",b=u[h];u[h]={cost:(b?.cost??0)+f.cost,calls:(b?.calls??0)+1,inputTokens:(b?.inputTokens??0)+f.inputTokens,outputTokens:(b?.outputTokens??0)+f.outputTokens}}let p=0;for(let f of t.retries)p+=f.waitMs;let l=r>0?s/r:0;return{totalCost:e,totalInputTokens:o,totalOutputTokens:n,totalCacheTokens:r,totalCacheReadTokens:s,totalCacheWriteTokens:a,cacheHitRate:l,callCount:t.records.length,retryCount:t.retries.length,retryWaitMs:p,byProvider:c,byRole:u}}i(ki,"getSummary");function ct(t){return t<.01?`$${t.toFixed(4)}`:t<1?`$${t.toFixed(3)}`:`$${t.toFixed(2)}`}i(ct,"formatCost");function bi(t){let e=[];if(e.push(`Session Cost: ${ct(t.totalCost)} (${t.callCount} calls)`),e.push(`Tokens: ${t.totalInputTokens.toLocaleString()} in / ${t.totalOutputTokens.toLocaleString()} out`),t.totalCacheTokens>0){let r=(t.cacheHitRate*100).toFixed(0);e.push(`Cache: ${t.totalCacheTokens.toLocaleString()} tokens (${t.totalCacheReadTokens.toLocaleString()} read / ${t.totalCacheWriteTokens.toLocaleString()} write, ${r}% hit rate)`)}if(t.retryCount>0){let r=(t.retryWaitMs/1e3).toFixed(1);e.push(`Retries: ${t.retryCount} (${r}s total wait)`)}e.push("");let o=Object.entries(t.byProvider).sort((r,s)=>s[1].cost-r[1].cost);if(o.length>0){e.push("By Provider:");for(let[r,s]of o)e.push(` ${r}: ${ct(s.cost)} (${s.calls} calls, ${s.inputTokens.toLocaleString()} in / ${s.outputTokens.toLocaleString()} out)`);e.push("")}let n=Object.entries(t.byRole).sort((r,s)=>s[1].cost-r[1].cost);if(n.length>1){e.push("By Role:");for(let[r,s]of n)e.push(` ${r}: ${ct(s.cost)} (${s.calls} calls)`)}return e.join(`
|
|
31
|
-
`)}i(bi,"formatCostReport");var qo={inputTokens:0,outputTokens:0,totalTokens:0},Ci=3e4;async function _i(t){let e=new AbortController,o=t.timeoutMs??Ci,n,r=i(c=>{n||(n=c),e.abort()},"recordAbort"),s=setTimeout(()=>r("timeout"),o),a=i(()=>r("parent"),"onParentAbort");t.abortSignal&&(t.abortSignal.aborted?r("parent"):t.abortSignal.addEventListener("abort",a,{once:!0}));try{let c=await t.provider.stream([...t.messages],[],t.system,t.reasoning??{mode:"off"},{modelOverride:t.model},e.signal),u=c.usage??qo,p=c.textBlocks??[],l=c.toolBlocks??[],f=p.map(h=>h.text).join("");if(l.length>0)return{text:f,usage:u,costTracker:t.costTracker,stopReason:"error",error:new Error(`sideQuery: provider returned ${l.length} tool_use block(s); sideQuery expects text-only output`)};let y=t.costTracker;return y&&(y=to(y,{provider:t.provider.name,model:t.model,inputTokens:u.inputTokens,outputTokens:u.outputTokens,cacheReadTokens:u.cachedReadTokens,cacheWriteTokens:u.cachedWriteTokens,role:t.querySource})),{text:f,usage:u,costTracker:y,stopReason:xi(c.stopReason)}}catch(c){let u=c instanceof Error?c:new Error(String(c)),p="error";return e.signal.aborted&&(p=n==="timeout"?"timeout":"aborted"),{text:"",usage:qo,costTracker:t.costTracker,stopReason:p,error:u}}finally{clearTimeout(s),t.abortSignal&&t.abortSignal.removeEventListener("abort",a)}}i(_i,"sideQuery");function xi(t){return t==="max_tokens"?"max_tokens":"end_turn"}i(xi,"mapStopReason");export{H as a,R as b,ye as c,lt as d,ut as e,dt as f,Qo as g,Zo as h,en as i,tn as j,oo as k,no as l,pt as m,te as n,we as o,io as p,oe as q,ne as r,ft as s,yt as t,vt as u,ie as v,Re as w,bt as x,cn as y,Ae as z,Oe as A,De as B,V as C,re as D,se as E,Ct as F,_t as G,ae as H,xt as I,ke as J,I as K,K as L,ue as M,de as N,_e as O,xe as P,A as Q,$ as R,zt as S,Oo as T,Do as U,Io as V,No as W,Lo as X,Bo as Y,Fo as Z,O as _,Ye as $,qe as aa,Qe as ba,Ee as ca,Ze as da,Ko as ea,et as fa,me as ga,tt as ha,$o as ia,Uo as ja,ot as ka,fe as la,nt as ma,Wo as na,it as oa,Me as pa,rt as qa,zo as ra,qt as sa,st as ta,at as ua,Qt as va,Vo as wa,Go as xa,Ho as ya,Jo as za,Yo as Aa,Zt as Ba,eo as Ca,yi as Da,vi as Ea,to as Fa,ki as Ga,ct as Ha,bi as Ia,_i as Ja};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{$ as ec,$a as ed,$b as ee,$c as ef,$d as fg,A as Fb,Aa as Fc,Ab as Fd,Ac as Fe,Ad as Gf,Ae as Gg,B as Gb,Ba as Gc,Bb as Gd,Bc as Ge,Bd as Hf,Be as Hg,C as Hb,Ca as Hc,Cb as Hd,Cc as He,Cd as If,Ce as Ig,D as Ib,Da as Ic,Db as Id,Dc as Ie,Dd as Jf,De as Jg,E as Jb,Ea as Jc,Eb as Jd,Ec as Je,Ed as Kf,Ee as Kg,F as Kb,Fa as Kc,Fb as Kd,Fc as Ke,Fd as Lf,Fe as Lg,G as Lb,Ga as Lc,Gb as Ld,Gc as Le,Gd as Mf,Ge as Mg,H as Mb,Ha as Mc,Hb as Md,Hc as Me,Hd as Nf,He as Ng,I as Nb,Ia as Nc,Ib as Nd,Ic as Ne,Id as Of,Ie as Og,J as Ob,Ja as Oc,Jb as Od,Jc as Oe,Jd as Pf,Je as Pg,K as Pb,Ka as Pc,Kb as Pd,Kc as Pe,Kd as Qf,Ke as Qg,L as Qb,La as Qc,Lb as Qd,Lc as Qe,Ld as Rf,Le as Rg,M as Rb,Ma as Rc,Mb as Rd,Mc as Re,Md as Sf,Me as Sg,N as Sb,Na as Sc,Nb as Sd,Nc as Se,Nd as Tf,Ne as Tg,O as Tb,Oa as Tc,Ob as Td,Oc as Te,Od as Uf,Oe as Ug,P as Ub,Pa as Uc,Pb as Ud,Pc as Ue,Pd as Vf,Pe as Vg,Q as Vb,Qa as Vc,Qb as Vd,Qc as Ve,Qd as Wf,Qe as Wg,R as Wb,Ra as Wc,Rb as Wd,Rc as We,Rd as Xf,Re as Xg,S as Xb,Sa as Xc,Sb as Xd,Sc as Xe,Sd as Yf,Se as Yg,T as Yb,Ta as Yc,Tb as Yd,Tc as Ye,Td as Zf,U as Zb,Ua as Zc,Ub as Zd,Uc as Ze,Ud as _f,V as _b,Va as _c,Vb as _d,Vc as _e,Vd as $f,W as $b,Wa as $c,Wb as $d,Wc as $e,Wd as ag,X as ac,Xa as ad,Xb as ae,Xc as af,Xd as bg,Y as bc,Ya as bd,Yb as be,Yc as bf,Yd as cg,Z as cc,Za as cd,Zb as ce,Zc as cf,Zd as dg,_ as dc,_a as dd,_b as de,_c as df,_d as eg,a as X,aa as fc,ab as fd,ac as fe,ad as ff,ae as gg,b as Y,ba as gc,bb as gd,bc as ge,bd as gf,be as hg,c as Z,ca as hc,cb as hd,cc as he,cd as hf,ce as ig,d as _,da as ic,db as id,dc as ie,dd as jf,de as jg,e as $,ea as jc,eb as jd,ec as je,ed as kf,ee as kg,f as kb,fa as kc,fb as kd,fc as ke,fd as lf,fe as lg,g as lb,ga as lc,gb as ld,gc as le,gd as mf,ge as mg,h as mb,ha as mc,hb as md,hc as me,hd as nf,he as ng,i as nb,ia as nc,ib as nd,ic as ne,id as of,ie as og,j as ob,ja as oc,jb as od,jc as oe,jd as pf,je as pg,k as pb,ka as pc,kb as pd,kc as pe,kd as qf,ke as qg,l as qb,la as qc,lb as qd,lc as qe,ld as rf,le as rg,m as rb,ma as rc,mb as rd,mc as re,md as sf,me as sg,n as sb,na as sc,nb as sd,nc as se,nd as tf,ne as tg,o as tb,oa as tc,ob as td,oc as te,od as uf,oe as ug,p as ub,pa as uc,pb as ud,pc as ue,pd as vf,pe as vg,q as vb,qa as vc,qb as vd,qc as ve,qd as wf,qe as wg,r as wb,ra as wc,rb as wd,rc as we,rd as xf,re as xg,s as xb,sa as xc,sb as xd,sc as xe,sd as yf,se as yg,t as yb,ta as yc,tb as yd,tc as ye,td as zf,te as zg,u as zb,ua as zc,ub as zd,uc as ze,ud as Af,ue as Ag,v as Ab,va as Ac,vb as Ad,vc as Ae,vd as Bf,ve as Bg,w as Bb,wa as Bc,wb as Bd,wc as Be,wd as Cf,we as Cg,x as Cb,xa as Cc,xb as Cd,xc as Ce,xd as Df,xe as Dg,y as Db,ya as Dc,yb as Dd,yc as De,yd as Ef,ye as Eg,z as Eb,za as Ec,zb as Ed,zc as Ee,zd as Ff,ze as Fg}from"./chunk-67SWUEEN.js";import{$ as y,C as k,K as l,L as m,Q as n,R as o,S as p,T as q,U as r,V as s,W as t,X as u,Y as v,Z as w,_ as x,a,aa as z,b,ba as A,c,ca as B,da as C,ea as D,fa as E,ga as F,ha as G,ia as H,j as d,ja as I,ka as J,la as K,ma as L,na as M,oa as N,pa as O,qa as P,ra as Q,sa as R,t as e,ta as S,u as f,ua as T,v as g,va as U,w as h,wa as V,x as i,xa as W,y as j}from"./chunk-YACQ4OST.js";import{Ac as Ta,Bc as Ua,Cb as xa,Cc as Va,Db as ya,Dc as Wa,Eb as za,Fb as Aa,Gb as Ba,Hb as Ca,Ib as Da,Jb as Ea,Kb as Fa,Kc as Xa,Lb as Ga,Lc as Ya,Mb as Ha,Mc as Za,Nb as Ia,Nc as _a,Ob as Ja,Oc as $a,Pb as Ka,Pc as ab,Qb as La,Qc as bb,Rb as Ma,Sb as Na,Sc as cb,Tb as Oa,Tc as db,Ub as Pa,Uc as eb,Vb as Qa,Vc as fb,Wb as Ra,Wc as gb,Xc as hb,a as aa,b as ba,c as ca,cd as ib,d as da,dd as jb,e as ea,f as fa,h as ga,i as ha,j as ia,jb as va,k as ja,ka as pa,kb as wa,l as ka,m as la,n as ma,na as qa,o as na,p as oa,ua as ra,va as sa,wa as ta,xa as ua,zc as Sa}from"./chunk-JTHMWRXM.js";import"./chunk-V4WSBIXB.js";export{Tf as AUTO_MODE_DENIAL_CONSECUTIVE_THRESHOLD,Uf as AUTO_MODE_DENIAL_CUMULATIVE_THRESHOLD,mg as BASH_POLICY_SPEC,hf as BLOCKER_REQUIRED_CONSECUTIVE_TURNS,Zf as BREAKER_ERROR_THRESHOLD,_f as BREAKER_WINDOW_MS,Wg as BUILTIN_WORKFLOWS,lb as CANCELLED_TOOL_RESULT_MESSAGE,kb as CANCELLED_TOOL_RESULT_PREFIX,Jf as CODING_AGENT_MARKER,Ue as CODING_INVARIANTS,Je as CODING_SUMMARY_PROMPT,Ke as CODING_UPDATE_SUMMARY_PROMPT,Yc as CapabilityDeniedError,We as Client,Zc as ConstructionManifestError,Le as DEFAULT_CODING_AGENT_NAME,yf as DEFAULT_DANGEROUS_PATTERNS,Wc as DEFAULT_HANDLER_TIMEOUT_MS,le as DEFAULT_RESILIENCE_CONFIG,xf as DEFAULT_SAFE_PATTERNS,hd as DEFAULT_SELF_MODIFY_BUDGET,ig as DEFAULT_SPECULATIVE_WINDOW_MS,nb as DEFAULT_TOOL_OUTPUT_MAX_BYTES,mb as DEFAULT_TOOL_OUTPUT_MAX_LINES,Lg as DEFAULT_WORKFLOW_GENERATION_TIMEOUT_MS,oa as DefaultSummaryCompaction,Gf as EMIT_VERDICT_TOOL_NAME,_ as ErrorCategory,Cc as GENERATOR_AGENT_NAME,ha as KODAX_API_MIN_INTERVAL,p as KODAX_DEFAULT_PROVIDER,ba as KODAX_DEFAULT_TIMEOUT,ca as KODAX_HARD_TIMEOUT,fa as KODAX_MAX_INCOMPLETE_RETRIES,da as KODAX_MAX_RETRIES,aa as KODAX_MAX_TOKENS,o as KODAX_PROVIDERS,n as KODAX_PROVIDER_SNAPSHOTS,d as KODAX_REASONING_MODE_SEQUENCE,ea as KODAX_RETRY_BASE_DELAY,ga as KODAX_STAGGER_DELAY,Gd as KODAX_TOOLS,l as KodaXAnthropicCompatProvider,k as KodaXBaseProvider,We as KodaXClient,a as KodaXError,Cd as KodaXExtensionRuntime,m as KodaXOpenAICompatProvider,b as KodaXProviderError,c as KodaXRateLimitError,Y as KodaXSessionError,Z as KodaXTerminalError,X as KodaXToolError,Sa as LINEAGE_ENTRY_TYPES,Fe as LSP_SERVERS,Ua as LineageCompaction,Ta as LineageExtension,Ge as LspService,xb as MANUAL_TOPIC_IDS,Da as McpAuthRequiredError,Pa as McpCapabilityProvider,Ca as McpExpiredSessionError,Qa as McpManager,Oa as McpServerRuntime,Bc as PLANNER_AGENT_NAME,ia as PROMISE_PATTERN,Zd as PROMPT_SECTION_REGISTRY,If as PROTOCOL_EMITTER_TOOLS,qe as ProviderRecoveryCoordinator,ob as READ_DEFAULT_LIMIT,qb as READ_MAX_LINE_CHARS,pb as READ_PREFLIGHT_SIZE_BYTES,Wb as REPOINTEL_DEFAULT_ENDPOINT,qa as Runner,Ac as SCOUT_AGENT_NAME,de as SELF_KNOWLEDGE_ROUTING_RULE,Yd as SYSTEM_PROMPT,vg as SYSTEM_WORKFLOW_LIMITS,oe as StableBoundaryTracker,Fc as TASK_ENGINE_ROLE_AGENTS,df as TOOL_RESULT_TRUNCATION_GUARDRAIL_NAME,pg as TRACING_ENV,Dc as WORKER_AGENT_NAME,Kg as WORKFLOW_GENERATION_SYSTEM_PROMPT,od as _resetRuntimeForTesting,rd as activate,Nb as analyzeChangedScope,fd as appendAuditEntry,ab as appendSessionLineageLabel,Oc as applyAccountingDelta,$e as applyFanoutBranchTransition,bb as applySessionCompaction,mc as applyToolResultGuardrail,hb as archiveOldIslands,af as assignFanoutBranchWorker,Yf as autoModeDenialShouldFallback,fg as bashSignalCollector,qg as bootstrapTracing,Qe as boundedRevise,bg as breakerShouldFallback,Re as budgetCeiling,ze as buildAmaControllerDecision,wg as buildApprovalSummary,Rc as buildBlockedGoal,ee as buildCapabilityContextSections,Kf as buildClassifierPrompt,Sc as buildCompleteGoal,Nc as buildCreatedGoal,xe as buildFallbackRoutingDecision,Ye as buildFanoutSchedulerPlan,mf as buildGoalRuntimeBinding,Na as buildInitializeCapabilities,cd as buildLlmReviewPrompt,qf as buildMcpReverseCapabilities,Pc as buildPausedGoal,ie as buildPromptMessageContent,Ae as buildPromptOverlay,be as buildPromptSnapshot,re as buildProviderCapabilitySnapshot,ye as buildProviderPolicyHintsForDecision,se as buildProviderPolicyPromptNotes,g as buildReasoningOverrideKey,Mb as buildRepoIntelligenceContext,$b as buildRepoIntelligenceIndex,Jb as buildRepoOverview,Qc as buildResumedGoal,ce as buildSelfKnowledgeRoutingRule,fb as buildSessionTree,ge as buildSystemPrompt,fe as buildSystemPromptSnapshot,Og as buildWorkflowGenerationUserPrompt,eg as checkAbsoluteDeny,he as checkIncompleteToolCalls,Ce as checkPromiseSignal,xg as clampWorkflowLimits,Mf as classify,Af as classifyBashCommand,$ as classifyError,ne as classifyResilienceError,wa as cleanupIncompleteToolCalls,j as clearReasoningOverride,Q as clearRuntimeModelProviders,hg as collectAllSignals,Cf as computeInputSignature,Nf as computeRulesFingerprint,nd as configureRuntime,qc as convertCapabilityReadResult,pc as convertProviderSearchResults,_e as countActiveFanoutBranches,gb as countActiveLineageMessages,ka as countTokens,la as createAgent,Vf as createAutoModeDenialTracker,lg as createAutoModeToolGuardrail,zf as createBashClassifierConfig,og as createBashPrefixExtractor,Od as createBuiltinToolDefinition,$f as createCircuitBreaker,sg as createCodingWorkflowBackend,_c as createCtxProxy,C as createCustomProvider,Me as createDefaultCodingAgent,Bf as createDenialTracker,Dd as createExtensionRuntime,Xe as createFanoutSchedulerInput,ma as createHandoff,na as createInMemorySession,tf as createKodaXTaskRunner,ya as createMcpCapabilityId,Ra as createMcpManager,Ea as createMcpTransport,_d as createPromptSection,Be as createReasoningPlan,ug as createRunGraphWriter,Oe as createSessionControl,Xa as createSessionLineage,ef as createToolResultTruncationGuardrail,Ug as createWorkflowPatternTemplateModule,Ig as createWorkflowRunManager,Vg as decideWorkflowInvocation,xa as defaultMcpCacheDir,Xc as defaultPolicy,md as disableSelfModify,Ia as discoverAuthorizationServerMetadata,Ad as discoverMarkdownAgents,Ja as discoverOAuthEndpoints,Ha as discoverProtectedResourceMetadata,Ag as discoverSavedWorkflows,Ic as drainPendingSwaps,Hf as emitVerdict,ja as estimateTokens,te as evaluateProviderPolicy,Uc as exec,Xd as executeTool,ib as extractArtifactLedger,ng as extractCommandPrefix,ke as extractComparableUserMessageText,oc as extractHtmlTitle,Ga as extractInsufficientScope,je as extractPromptComparableText,Fa as extractResourceMetadataUrl,Wa as extractTitleFromMessages,gg as fileSignalCollector,sc as finalizeRetrievalResult,xd as findByVersion,cb as findPreviousUserEntryId,eb as forkSessionLineage,zc as formatAgentsForPrompt,vf as formatParallelDispatchResult,rb as formatSize,Va as generateSessionId,Qg as generateWorkflow,Rg as generateWorkflowFromOptions,Fd as getActiveExtensionRuntime,sa as getAgentConfigHome,ta as getAgentConfigPath,Qd as getAllRegisteredTools,ua as getAppDataDir,T as getAvailableProviderNames,Nd as getBuiltinRegisteredToolDefinition,Md as getBuiltinToolDefinition,Xg as getBuiltinWorkflow,K as getCustomModelCapabilities,E as getCustomProvider,H as getCustomProviderList,J as getCustomProviderModelDescriptors,I as getCustomProviderModels,G as getCustomProviderNames,He as getDefaultLspService,Jg as getDefaultWorkflowRunManager,Ff as getDenialContext,Ze as getFanoutBranch,ec as getImpactEstimate,xc as getKodaxGlobalDir,Ba as getMcpCachePaths,z as getModelCapabilities,bc as getModuleContext,dc as getProcessContext,q as getProvider,u as getProviderConfiguredCapabilityProfile,t as getProviderConfiguredReasoningCapability,v as getProviderList,s as getProviderModel,y as getProviderModelDescriptors,w as getProviderModels,Kd as getRegisteredToolDefinition,ac as getRepoIntelligenceIndex,Kb as getRepoOverview,fc as getRepoRoutingSignals,Ud as getRequiredToolParams,N as getRuntimeModelProvider,P as getRuntimeModelProviderNames,Ya as getSessionLineagePath,Za as getSessionMessagesFromLineage,cc as getSymbolContext,Id as getTool,Jd as getToolDefinition,Ld as getToolRegistrations,lc as getToolResultPolicy,Tg as getWorkflowPatternTemplate,Kc as goalTokenDelta,Hc as hasPendingSwap,we as inferTaskType,Cb as inspectEditFailure,Zb as inspectRepoIntelligenceRuntime,F as isCustomProviderName,Ef as isDeniedRecently,S as isKnownProvider,uf as isParallelDispatchDirective,r as isProviderConfigured,x as isProviderName,O as isRuntimeModelProviderName,Sd as isToolFileMutation,Td as isToolMutation,Rd as isToolPlanModeAllowed,Tc as isValidTokenBudget,De as languageIdForPath,yd as listAll,W as listAllModelCapabilities,ud as listArtifacts,A as listBuiltinModelCapabilities,Pd as listBuiltinToolDefinitions,Yg as listBuiltinWorkflows,wd as listConstructed,L as listCustomProviderModelCapabilities,Wd as listToolDefinitions,Vd as listTools,Sg as listWorkflowPatternTemplates,yc as loadAgentsFiles,zd as loadAgentsFromMarkdown,Rf as loadAutoRules,Fg as loadGeneratedWorkflowFromRun,$c as loadHandler,h as loadReasoningOverride,Dg as loadSavedWorkflow,Cg as loadSavedWorkflowCapsule,Ma as loadValidToken,Jc as makeDisabledGoalToolsContext,cf as markFanoutBranchCancelled,bf as markFanoutBranchCompleted,pf as mcpRootsFromWorkspace,jb as mergeArtifactLedger,Bg as normalizeWorkflowModule,$d as orderPromptSections,rg as parallelInvestigation,Qf as parseAutoRules,Lf as parseClassifierOutput,Bb as parseEditToolError,dd as parseLlmReviewVerdict,za as parseMcpCapabilityId,cg as parseModelSpec,Pg as parseWorkflowGeneration,La as performOAuthLogin,vb as persistToolOutput,Hg as preflightWorkflowCapsule,gc as prewarmRepoIntelligenceCaches,vd as readArtifact,gd as readAuditEntries,id as readBudget,ld as readDisableState,jg as readSpeculativeWindowFromEnv,Of as readTrustState,e as reasoningCapabilityToOverride,ve as reasoningModeToDepth,f as reasoningOverrideToCapability,pe as reconstructMessagesWithToolGuard,Xf as recordAutoModeAllow,Wf as recordAutoModeBlock,ff as recordBlockerAttempt,ag as recordBreakerError,Df as recordDenial,Ve as registerCodingInvariants,of as registerConfiguredMcpCapabilityProvider,D as registerCustomProviders,M as registerModelProvider,Ka as registerOAuthClient,rf as registerOfficialSandboxExtension,pa as registerPresetDispatcher,Hd as registerTool,sd as rehydrateActiveArtifacts,jd as remainingSelfModifyBudget,Ob as renderChangedScope,Vb as renderImpactEstimate,Sb as renderModuleContext,Ub as renderProcessContext,ae as renderPromptSections,Lb as renderRepoOverview,rc as renderRetrievalResult,Tb as renderSymbolContext,Ee as reportLspDiagnostics,gf as resetBlockerCounter,kd as resetBudget,dg as resolveClassifierModel,Gc as resolveConstructedAgent,yb as resolveKodaXManual,V as resolveModelCapabilities,R as resolveProvider,U as resolveProviderModelDescriptors,ue as resolveReasoningMode,Yb as resolveRepoIntelligenceMode,Xb as resolveRepoIntelligenceRuntimeConfig,me as resolveResilienceConfig,_a as resolveSessionLineageTarget,Se as resolveToolCapability,Mg as resolveWorkflowGenerationTimeoutMs,td as revoke,db as rewindSessionLineage,Bd as rollbackSelfModify,ad as runAstRules,Ne as runKodaX,ed as runLlmReview,nf as runManagedTask,sf as runOrchestration,zg as runWorkflowFromOptions,yg as runWorkflowModule,tg as safeWorkflowArtifactName,Eg as saveGeneratedWorkflow,Gg as saveGeneratedWorkflowFromRun,i as saveReasoningOverride,Aa as searchMcpCatalog,Ed as setActiveExtensionRuntime,ra as setAgentConfigHome,$a as setSessionLineageActiveEntry,Mc as shouldFlipBudgetLimited,Ie as shutdownDefaultLspService,kg as speculativeRace,pd as stage,Pe as startKodaX,Sf as stripAssistantText,nc as stripHtmlToText,qd as testArtifact,Ib as toolAskUserQuestion,Eb as toolBash,Rb as toolChangedDiff,Qb as toolChangedScope,vc as toolCodeSearch,Ab as toolEdit,Fb as toolGlob,Gb as toolGrep,kc as toolImpactEstimate,Db as toolInsertAfterAnchor,hc as toolModuleContext,Te as toolPermission,jc as toolProcessContext,wb as toolRead,Pb as toolRepoOverview,wc as toolSemanticLookup,ic as toolSymbolContext,Hb as toolUndo,uc as toolWebFetch,tc as toolWebSearch,zb as toolWrite,sb as truncateHead,ub as truncateLine,tb as truncateTail,Pf as trustProjectRules,Lc as turnWallTimeDelta,va as validateAndFixToolHistory,B as validateCustomProviderConfig,Ng as validateGeneratedWorkflowSource,wf as validateSubtaskIndependence,bd as validateToolSchemaForProvider,lf as verifyGoalCompletion,_b as warmRepoIntelligenceRuntime,Vc as webhook,jf as withGoalBeforeNextTurn,kf as withGoalStopHook,Ec as workerAgent};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{A as z,B as A,C as B,D as C,b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"./chunk-TYZAH3YP.js";import"./chunk-67SWUEEN.js";import"./chunk-YACQ4OST.js";import"./chunk-JTHMWRXM.js";import"./chunk-V4WSBIXB.js";export{c as KODAX_CONFIG_FILE,a as KODAX_DIR,b as KODAX_SESSIONS_DIR,i as KODAX_VERSION,d as PREVIEW_MAX_LENGTH,p as describeProviderCapabilitySummary,r as describeReasoningCapabilityControl,s as describeReasoningExecution,A as formatProviderCapabilityDetailLines,z as formatProviderSourceKind,q as formatReasoningCapabilityShort,y as getGitRoot,k as getProviderAvailableModels,m as getProviderCapabilityProfile,n as getProviderCapabilitySnapshot,B as getProviderCommonPolicyScenarios,t as getProviderList,j as getProviderModel,o as getProviderPolicyDecision,l as getProviderReasoningCapability,h as getVersion,e as hydrateProcessEnvFromShell,u as isProviderConfigured,v as loadConfig,w as prepareRuntimeConfig,C as rateLimitedCall,g as registerConfiguredCustomProviders,f as resetShellEnvironmentHydrationForTesting,x as saveConfig};
|
|
@@ -1,270 +0,0 @@
|
|
|
1
|
-
import { s as KodaXProviderConfig, n as KodaXMessage, Y as KodaXToolDefinition, G as KodaXReasoningRequest, A as KodaXProviderStreamOptions, L as KodaXStreamResult, a2 as KodaXVerifyCredentialResult, o as KodaXModelDescriptor, r as KodaXProviderCapabilityProfile, D as KodaXReasoningCapability, F as KodaXReasoningOverride } from './types.d-rPRl2LSB.js';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Retry-After header parsing — FEATURE_130 (v0.7.36).
|
|
5
|
-
*
|
|
6
|
-
* Handles the four forms KodaX's 12 provider adapters encounter when a
|
|
7
|
-
* model returns 429 (rate limit) or 503/529 (overloaded):
|
|
8
|
-
*
|
|
9
|
-
* 1. `Retry-After: 120` — integer seconds (HTTP 7231 standard)
|
|
10
|
-
* 2. `Retry-After: <HTTP-date>` — RFC 7231 IMF-fixdate
|
|
11
|
-
* e.g. "Wed, 21 Oct 2026 07:28:00 GMT"
|
|
12
|
-
* 3. `retry-after-ms: 45000` — Anthropic millisecond extension
|
|
13
|
-
* 4. (no Retry-After header present) — falls back to exponential backoff
|
|
14
|
-
* capped at `maxBackoffMs`, with optional jitter for the
|
|
15
|
-
* "thundering herd" protection.
|
|
16
|
-
*
|
|
17
|
-
* All return values are normalized to whole milliseconds and clamped to
|
|
18
|
-
* a sensible upper bound — never block the user for more than 120s, and
|
|
19
|
-
* never honor a header advertising a wait longer than `maxHeaderWaitMs`
|
|
20
|
-
* (default 120s). Beyond that limit we still extract the header but cap
|
|
21
|
-
* it; the calling provider can check `cappedFromHeader` to decide
|
|
22
|
-
* whether to surface a "rate limit exceeded — please wait" error to the
|
|
23
|
-
* user instead of silently sleeping for two minutes.
|
|
24
|
-
*
|
|
25
|
-
* Pattern-B (FEATURE_119) interaction: the helper is referentially
|
|
26
|
-
* transparent and stateless — it can be invoked concurrently by N
|
|
27
|
-
* parallel children without coordination. The retry loop in each
|
|
28
|
-
* provider holds its own attempt counter; this helper only translates
|
|
29
|
-
* headers/attempts into wait durations.
|
|
30
|
-
*
|
|
31
|
-
* Reference: opencode session/retry.ts:14-123 (4-form coverage).
|
|
32
|
-
*/
|
|
33
|
-
type RetryAfterSource = 'retry-after-seconds' | 'retry-after-date' | 'retry-after-ms' | 'exponential-backoff';
|
|
34
|
-
type RetryAfterResult = {
|
|
35
|
-
readonly type: 'header';
|
|
36
|
-
readonly waitMs: number;
|
|
37
|
-
readonly source: 'retry-after-seconds' | 'retry-after-date' | 'retry-after-ms';
|
|
38
|
-
/** True when the header value exceeded `maxHeaderWaitMs` and was clamped. */
|
|
39
|
-
readonly cappedFromHeader: boolean;
|
|
40
|
-
} | {
|
|
41
|
-
readonly type: 'backoff';
|
|
42
|
-
readonly waitMs: number;
|
|
43
|
-
readonly source: 'exponential-backoff';
|
|
44
|
-
readonly attempt: number;
|
|
45
|
-
};
|
|
46
|
-
interface ParseRetryAfterOptions {
|
|
47
|
-
/** Zero-based attempt index used by the backoff branch (0 = first retry). */
|
|
48
|
-
readonly attempt: number;
|
|
49
|
-
/** Base delay for exponential backoff. Default 1000ms. */
|
|
50
|
-
readonly baseBackoffMs?: number;
|
|
51
|
-
/** Maximum exponential backoff cap. Default 30000ms. */
|
|
52
|
-
readonly maxBackoffMs?: number;
|
|
53
|
-
/** Maximum wait honored from a header. Default 120000ms. */
|
|
54
|
-
readonly maxHeaderWaitMs?: number;
|
|
55
|
-
/**
|
|
56
|
-
* Override the "now" reference used by the HTTP-date branch.
|
|
57
|
-
* Test-only escape hatch — production code should leave this undefined.
|
|
58
|
-
*/
|
|
59
|
-
readonly now?: () => number;
|
|
60
|
-
/**
|
|
61
|
-
* Whether the backoff branch adds 0-25% jitter on top of the base
|
|
62
|
-
* exponential. Default true (matches the legacy `withRateLimit`
|
|
63
|
-
* jitter contract). Tests can pass `false` for deterministic output.
|
|
64
|
-
*/
|
|
65
|
-
readonly withJitter?: boolean;
|
|
66
|
-
}
|
|
67
|
-
type HeadersLike = Headers | Record<string, string | string[] | undefined> | undefined;
|
|
68
|
-
/**
|
|
69
|
-
* Parse rate-limit/overload retry-after headers (4 forms) and decide
|
|
70
|
-
* how long the caller should sleep before retrying. Returns either:
|
|
71
|
-
*
|
|
72
|
-
* - `{type: 'header', ...}` when one of the supported headers was found
|
|
73
|
-
* and converted into a wait duration; OR
|
|
74
|
-
* - `{type: 'backoff', ...}` falling back to exponential backoff for
|
|
75
|
-
* the given `attempt` index when no header is present.
|
|
76
|
-
*/
|
|
77
|
-
declare function parseRetryAfter(headers: HeadersLike, options: ParseRetryAfterOptions): RetryAfterResult;
|
|
78
|
-
/**
|
|
79
|
-
* Pull headers off a thrown error in the various shapes produced across
|
|
80
|
-
* provider SDKs (Anthropic, OpenAI, fetch-based custom providers).
|
|
81
|
-
* Returns `undefined` when no headers can be located — the helper then
|
|
82
|
-
* falls through to exponential backoff.
|
|
83
|
-
*/
|
|
84
|
-
declare function extractHeadersFromError(error: unknown): HeadersLike;
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* KodaX Base Provider
|
|
88
|
-
*
|
|
89
|
-
* Provider 抽象基类 - 所有 Provider 的公共基础
|
|
90
|
-
*/
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* FEATURE_130 (v0.7.36): structured payload fired through
|
|
94
|
-
* `KodaXEvents.onRetryAfter` whenever a provider's `withRateLimit`
|
|
95
|
-
* loop catches a 429 / 503 / 529 response and decides to wait. The
|
|
96
|
-
* `source` field carries which retry-after header form (or fallback)
|
|
97
|
-
* produced the wait duration so UI surfaces can show "provider asked
|
|
98
|
-
* us to wait 45s" vs "no header, exp-backoff guess of 4s".
|
|
99
|
-
*/
|
|
100
|
-
interface KodaXRetryAfterEvent {
|
|
101
|
-
readonly provider: string;
|
|
102
|
-
readonly waitMs: number;
|
|
103
|
-
readonly reason: 'rate-limit' | 'overloaded';
|
|
104
|
-
readonly source: RetryAfterSource;
|
|
105
|
-
readonly attempt: number;
|
|
106
|
-
readonly maxAttempts: number;
|
|
107
|
-
}
|
|
108
|
-
type KodaXOnRetryAfterCallback = (event: KodaXRetryAfterEvent) => void;
|
|
109
|
-
declare abstract class KodaXBaseProvider {
|
|
110
|
-
abstract readonly name: string;
|
|
111
|
-
abstract readonly supportsThinking: boolean;
|
|
112
|
-
protected abstract readonly config: KodaXProviderConfig;
|
|
113
|
-
/**
|
|
114
|
-
* Per-request override for `max_tokens` in the next provider call. Consumed
|
|
115
|
-
* once and cleared in `withRateLimit` after the next successful response.
|
|
116
|
-
* Two callers set this:
|
|
117
|
-
* 1. Context-overflow recovery inside `withRateLimit` (reduces budget
|
|
118
|
-
* when the model reports "prompt too long").
|
|
119
|
-
* 2. The agent loop's max_tokens escalation path, which flips this to
|
|
120
|
-
* `KODAX_ESCALATED_MAX_OUTPUT_TOKENS` when a capped-budget turn
|
|
121
|
-
* returns `stop_reason: max_tokens`. See `coding/src/agent.ts`.
|
|
122
|
-
*/
|
|
123
|
-
protected maxOutputTokensOverride?: number;
|
|
124
|
-
/**
|
|
125
|
-
* Public setter for the one-shot override above. Callers outside the
|
|
126
|
-
* provider package (notably the agent loop's escalation branch) use this
|
|
127
|
-
* to stage a larger budget for the next stream call in the same logical
|
|
128
|
-
* turn. Pass `undefined` to clear a stale override explicitly.
|
|
129
|
-
*/
|
|
130
|
-
setMaxOutputTokensOverride(value: number | undefined): void;
|
|
131
|
-
/**
|
|
132
|
-
* Returns the max_tokens value the provider will currently use on its
|
|
133
|
-
* next request. Precedence (highest to lowest):
|
|
134
|
-
* 1. One-shot override (agent escalation, context-overflow recovery)
|
|
135
|
-
* 2. User env var `KODAX_MAX_OUTPUT_TOKENS` (explicit user intent)
|
|
136
|
-
* 3. Active model descriptor's `maxOutputTokens` (FEATURE_098)
|
|
137
|
-
* 4. Provider config default
|
|
138
|
-
* 5. Global `KODAX_MAX_TOKENS` fallback
|
|
139
|
-
* Used by provider stream() paths and by the agent loop to decide
|
|
140
|
-
* whether escalation is applicable (see `coding/src/agent.ts`).
|
|
141
|
-
*/
|
|
142
|
-
getEffectiveMaxOutputTokens(model?: string): number;
|
|
143
|
-
/**
|
|
144
|
-
* Hard cap on a single streaming request's wall-clock duration (ms).
|
|
145
|
-
* Returns undefined when no cap is configured. Consumed by the
|
|
146
|
-
* resilience layer to abort a doomed stream before the server-side
|
|
147
|
-
* kill window fires; routed through `non_streaming_fallback`.
|
|
148
|
-
*
|
|
149
|
-
* Cascade (highest to lowest):
|
|
150
|
-
* 1. Active model descriptor's `streamMaxDurationMs`
|
|
151
|
-
* 2. Provider config default
|
|
152
|
-
* 3. undefined (watchdog disabled)
|
|
153
|
-
*/
|
|
154
|
-
getStreamMaxDurationMs(model?: string): number | undefined;
|
|
155
|
-
/**
|
|
156
|
-
* Resolves whether OpenAI-compat `reasoning_content` should echo back
|
|
157
|
-
* on replayed assistant messages for the given model. Same cascade as
|
|
158
|
-
* `getStreamMaxDurationMs`. Defaults to false when neither layer sets it.
|
|
159
|
-
*/
|
|
160
|
-
getEffectiveReplayReasoningContent(model?: string): boolean;
|
|
161
|
-
/**
|
|
162
|
-
* Resolves whether Anthropic-style thinking signatures must verify
|
|
163
|
-
* strictly (Anthropic proper only). Same cascade as
|
|
164
|
-
* `getStreamMaxDurationMs`. Defaults to false (lenient) when neither
|
|
165
|
-
* layer sets it — matches third-party Anthropic-compat behavior.
|
|
166
|
-
*/
|
|
167
|
-
getEffectiveStrictThinkingSignature(model?: string): boolean;
|
|
168
|
-
abstract stream(messages: KodaXMessage[], tools: KodaXToolDefinition[], system: string, reasoning?: boolean | KodaXReasoningRequest, streamOptions?: KodaXProviderStreamOptions, signal?: AbortSignal): Promise<KodaXStreamResult>;
|
|
169
|
-
supportsNonStreamingFallback(): boolean;
|
|
170
|
-
complete(_messages: KodaXMessage[], _tools: KodaXToolDefinition[], _system: string, _reasoning?: boolean | KodaXReasoningRequest, _streamOptions?: KodaXProviderStreamOptions, _signal?: AbortSignal): Promise<KodaXStreamResult>;
|
|
171
|
-
isConfigured(): boolean;
|
|
172
|
-
/**
|
|
173
|
-
* FEATURE_216 v0.7.45 — Lightweight credential verification. Returns
|
|
174
|
-
* a never-throws envelope with `ok` + categorized `error`. Concrete
|
|
175
|
-
* compat base classes (`KodaXAnthropicCompatProvider`,
|
|
176
|
-
* `KodaXOpenAICompatProvider`) override this to dispatch by the
|
|
177
|
-
* `verifyStrategy` field. The default here returns `unsupported` so
|
|
178
|
-
* Provider classes that don't extend a compat base — or future ones
|
|
179
|
-
* yet to be wired — fail safely instead of throwing.
|
|
180
|
-
*
|
|
181
|
-
* Distinct from `isConfigured()`: that one is env-only (no network);
|
|
182
|
-
* this one hits the wire (zero or ~7 tokens depending on strategy)
|
|
183
|
-
* and verifies the key is actually accepted by the upstream.
|
|
184
|
-
*/
|
|
185
|
-
verifyCredential(_opts?: {
|
|
186
|
-
timeoutMs?: number;
|
|
187
|
-
signal?: AbortSignal;
|
|
188
|
-
}): Promise<KodaXVerifyCredentialResult>;
|
|
189
|
-
getModel(): string;
|
|
190
|
-
getAvailableModels(): string[];
|
|
191
|
-
getModelDescriptor(modelId?: string): KodaXModelDescriptor | undefined;
|
|
192
|
-
getBaseUrl(): string | undefined;
|
|
193
|
-
getApiKeyEnv(): string;
|
|
194
|
-
getCapabilityProfile(): KodaXProviderCapabilityProfile;
|
|
195
|
-
getConfiguredReasoningCapability(modelOverride?: string): KodaXReasoningCapability;
|
|
196
|
-
getReasoningCapability(modelOverride?: string): KodaXReasoningCapability;
|
|
197
|
-
getReasoningOverride(modelOverride?: string): KodaXReasoningOverride | undefined;
|
|
198
|
-
getReasoningOverrideKey(modelOverride?: string): string;
|
|
199
|
-
protected persistReasoningCapabilityOverride(capability: KodaXReasoningCapability, modelOverride?: string): void;
|
|
200
|
-
protected shouldFallbackForReasoningError(error: unknown, ...terms: string[]): boolean;
|
|
201
|
-
protected shouldFallbackForSpecificReasoningError(error: unknown, ...terms: string[]): boolean;
|
|
202
|
-
protected shouldFallbackForForcedToolChoiceError(error: unknown): boolean;
|
|
203
|
-
protected getReasoningFallbackChain(capability: KodaXReasoningCapability): KodaXReasoningCapability[];
|
|
204
|
-
/**
|
|
205
|
-
* 获取模型的上下文窗口大小
|
|
206
|
-
*
|
|
207
|
-
* Backwards-compatible no-arg form: resolves against the provider's
|
|
208
|
-
* default model descriptor. New call sites that know the active
|
|
209
|
-
* model should use `getEffectiveContextWindow(model)` directly.
|
|
210
|
-
* @returns 上下文窗口大小 (tokens)
|
|
211
|
-
*/
|
|
212
|
-
getContextWindow(): number;
|
|
213
|
-
/**
|
|
214
|
-
* Resolves the context window for a specific model.
|
|
215
|
-
* Precedence (highest to lowest):
|
|
216
|
-
* 1. Active model descriptor's `contextWindow` (FEATURE_098)
|
|
217
|
-
* 2. Provider config default
|
|
218
|
-
* 3. 200_000 fallback
|
|
219
|
-
* The user-level `compaction.contextWindow` is layered on top of
|
|
220
|
-
* this at the call site, so it remains the highest-priority manual
|
|
221
|
-
* override.
|
|
222
|
-
*/
|
|
223
|
-
getEffectiveContextWindow(model?: string): number;
|
|
224
|
-
protected getApiKey(): string;
|
|
225
|
-
protected shouldLogStreamDiagnostics(): boolean;
|
|
226
|
-
protected logStreamDiagnostic(...args: unknown[]): void;
|
|
227
|
-
protected normalizeReasoning(reasoning?: boolean | KodaXReasoningRequest): Required<KodaXReasoningRequest>;
|
|
228
|
-
/**
|
|
229
|
-
* Called when ECONNRESET/EPIPE is detected, indicating a stale keep-alive
|
|
230
|
-
* socket. Subclasses should override to rebuild their HTTP client with a
|
|
231
|
-
* fresh connection pool so the next retry uses a new TCP connection.
|
|
232
|
-
*/
|
|
233
|
-
protected onStaleConnection(): void;
|
|
234
|
-
protected isRateLimitError(error: unknown): boolean;
|
|
235
|
-
/**
|
|
236
|
-
* FEATURE_130: classify a rate-limit error as either a 429-style
|
|
237
|
-
* "rate-limit" or a 503/529-style "overloaded" condition. The
|
|
238
|
-
* distinction matters for UI: "rate-limit" usually surfaces a
|
|
239
|
-
* provider-supplied retry-after window; "overloaded" tends to fall
|
|
240
|
-
* through to exponential backoff with no header. Both flow through
|
|
241
|
-
* the same retry path; this only labels the event.
|
|
242
|
-
*/
|
|
243
|
-
protected classifyRateLimitReason(error: unknown): 'rate-limit' | 'overloaded';
|
|
244
|
-
/**
|
|
245
|
-
* Extract Retry-After delay from error headers (429/529 responses).
|
|
246
|
-
* Returns milliseconds, or undefined when no usable header is present.
|
|
247
|
-
*
|
|
248
|
-
* FEATURE_130 (v0.7.36): now delegates to the shared `parseRetryAfter`
|
|
249
|
-
* helper so all 12 provider adapters get 4-form coverage without each
|
|
250
|
-
* adapter rolling its own parser. The 4 forms supported are:
|
|
251
|
-
* - `Retry-After: <integer-seconds>`
|
|
252
|
-
* - `Retry-After: <HTTP-date>`
|
|
253
|
-
* - `retry-after-ms: <milliseconds>` (Anthropic extension)
|
|
254
|
-
* - exponential-backoff fallback (returned via `withRateLimit`,
|
|
255
|
-
* not through this helper — it is `undefined` here when no
|
|
256
|
-
* header is present, which the caller then resolves to backoff)
|
|
257
|
-
*/
|
|
258
|
-
protected extractRetryAfterMs(error: unknown): number | undefined;
|
|
259
|
-
/**
|
|
260
|
-
* Detect "prompt too long / context window exceeded" errors and compute
|
|
261
|
-
* a reduced max_tokens for retry. Returns undefined if not a context
|
|
262
|
-
* overflow error.
|
|
263
|
-
*/
|
|
264
|
-
protected parseContextOverflow(error: unknown): number | undefined;
|
|
265
|
-
protected isContextOverflowError(error: unknown): boolean;
|
|
266
|
-
protected withRateLimit<T>(fn: () => Promise<T>, signal?: AbortSignal, retries?: number, onRateLimit?: (attempt: number, maxRetries: number, delayMs: number) => void, onRetryAfter?: KodaXOnRetryAfterCallback): Promise<T>;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
export { KodaXBaseProvider as K, extractHeadersFromError as e, parseRetryAfter as p };
|
|
270
|
-
export type { ParseRetryAfterOptions as P, RetryAfterResult as R, KodaXOnRetryAfterCallback as a, KodaXRetryAfterEvent as b, RetryAfterSource as c };
|