@kodax-ai/kodax 0.7.97-beta.1 → 0.7.97-beta.2
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 +61 -0
- package/README.md +28 -2
- package/README_CN.md +18 -1
- package/dist/chunks/agent-DS7M57WD.js +2 -0
- package/dist/chunks/agent-adapter-TLWGGK3V.js +2 -0
- package/dist/chunks/argument-completer-OGCXKTRQ.js +2 -0
- package/dist/chunks/{cell-ABNYMGXV.js → cell-LV7MNPNQ.js} +1 -1
- package/dist/chunks/{chunk-KQ3XVHKK.js → chunk-2HH5AS7E.js} +55 -55
- package/dist/chunks/{chunk-6VHO36HK.js → chunk-3CP7AUWY.js} +1 -1
- package/dist/chunks/{chunk-ADIWJDFS.js → chunk-53CJDQS2.js} +1 -1
- package/dist/chunks/{chunk-3ZEJRVNA.js → chunk-5MUVRFMU.js} +1 -1
- package/dist/chunks/{chunk-KJBS6L7Q.js → chunk-6TITQQAI.js} +155 -155
- package/dist/chunks/{chunk-HA4IKFUK.js → chunk-BBZWF2EA.js} +1 -1
- package/dist/chunks/{chunk-W6MHQ7ED.js → chunk-C6JGLEYD.js} +1 -1
- package/dist/chunks/{chunk-NM3AINLH.js → chunk-D36OIMV7.js} +29 -29
- package/dist/chunks/{chunk-LWOGHKTL.js → chunk-D425EZGC.js} +1 -1
- package/dist/chunks/{chunk-7SX7CHYP.js → chunk-DCE7XQUG.js} +1 -1
- package/dist/chunks/{chunk-N2B6A3CX.js → chunk-DV5YPYLW.js} +1 -1
- package/dist/chunks/{chunk-5MDNQCAV.js → chunk-EISRVOBJ.js} +2 -2
- package/dist/chunks/chunk-EPK6EWRI.js +12 -0
- package/dist/chunks/{chunk-G2IMBA3R.js → chunk-F6GJXQNA.js} +5 -5
- package/dist/chunks/chunk-GJXOTOZB.js +465 -0
- package/dist/chunks/{chunk-F7H6CDJN.js → chunk-I325ER7D.js} +1 -1
- package/dist/chunks/{chunk-E2Z754K5.js → chunk-J2L2NK6E.js} +57 -57
- package/dist/chunks/chunk-JAF2YLZO.js +14 -0
- package/dist/chunks/{chunk-A3SLNYBB.js → chunk-KDSO7V4O.js} +1 -1
- package/dist/chunks/{chunk-654JOM24.js → chunk-MCDZNQWD.js} +4 -4
- package/dist/chunks/{chunk-KDRYQKT7.js → chunk-NSR4RW2F.js} +1 -1
- package/dist/chunks/chunk-OGTRDK4Q.js +359 -0
- package/dist/chunks/{chunk-GYNAAIZP.js → chunk-P55RJIOG.js} +1 -1
- package/dist/chunks/chunk-QSZCR5GC.js +190 -0
- package/dist/chunks/chunk-R2HTPDI7.js +2 -0
- package/dist/chunks/chunk-R42S4BLA.js +2 -0
- package/dist/chunks/chunk-RYBUYHDL.js +5 -0
- package/dist/chunks/{chunk-XGUGEVCK.js → chunk-SDPZFH6M.js} +1 -1
- package/dist/chunks/chunk-SK3RRGHJ.js +142 -0
- package/dist/chunks/chunk-TQ475LOI.js +2 -0
- package/dist/chunks/{chunk-ZT2LR3KD.js → chunk-UL6YIT4M.js} +1 -1
- package/dist/chunks/{chunk-7U2BL7CM.js → chunk-V2XJSFFE.js} +1 -1
- package/dist/chunks/{chunk-TXI6SHDO.js → chunk-W2CWO4PQ.js} +1 -1
- package/dist/chunks/{chunk-SCGXZ2QT.js → chunk-WWPVEK6B.js} +1 -1
- package/dist/chunks/{chunk-FMZN5F3Q.js → chunk-X5M7TLJV.js} +1 -1
- package/dist/chunks/{chunk-FZZMHNDB.js → chunk-XDMNJW6J.js} +5 -5
- package/dist/chunks/{chunk-VT35IZEZ.js → chunk-XZSFUGPN.js} +1 -1
- package/dist/chunks/{client-3JEK33QQ.js → client-LTIFNED5.js} +1 -1
- package/dist/chunks/compaction-config-ECMOFP5H.js +2 -0
- package/dist/chunks/{construction-bootstrap-HCRLORKG.js → construction-bootstrap-OAZKGI5Y.js} +1 -1
- package/dist/chunks/dist-5J53DGAO.js +2 -0
- package/dist/chunks/{google-native-45I4S26I.js → google-native-WLL27OV7.js} +1 -1
- package/dist/chunks/host-65E5NM5P.js +2 -0
- package/dist/chunks/model-DZF6URW3.js +2 -0
- package/dist/chunks/{permission-MTSFSB74.js → permission-YVVMLQ5I.js} +1 -1
- package/dist/chunks/readline-helpers-UZXWBRXQ.js +2 -0
- package/dist/chunks/run-manager-ZFACIZM2.js +2 -0
- package/dist/chunks/running-session-Q5Y6A2QV.js +2 -0
- package/dist/chunks/{skills-V7T55I4F.js → skills-TJP6BLZJ.js} +1 -1
- package/dist/chunks/{tool-dispatch-ZVIDGKB4.js → tool-dispatch-MLM3QTSU.js} +1 -1
- package/dist/chunks/{utils-WGRFGT7S.js → utils-2QNMYRGA.js} +1 -1
- package/dist/index.d.ts +18 -18
- package/dist/index.js +2 -2
- package/dist/kodax_bootstrap.js +1 -1
- package/dist/kodax_cli.js +1534 -1532
- package/dist/kodax_doctor.js +1 -1
- package/dist/manual-topics.json +17 -2
- package/dist/native/win32-x64/kodax-windows-sandbox.exe +0 -0
- package/dist/native/win32-x64/kodax-windows-text-transaction.node +0 -0
- package/dist/native/win32-x64/manifest.json +2 -2
- package/dist/one-shot-task.js +1 -1
- package/dist/provider-auth-cli.js +1 -1
- package/dist/runtime-daemon-schema.json +1 -1
- package/dist/sandbox-network-broker.js +77 -77
- package/dist/script-cell.js +1 -1
- package/dist/script-worker.cjs +30 -7
- package/dist/sdk-a2a.d.ts +11 -11
- package/dist/sdk-a2a.js +1 -1
- package/dist/sdk-agent.d.ts +13 -9
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-client.d.ts +5 -5
- package/dist/sdk-client.js +1 -1
- package/dist/sdk-coding.d.ts +57 -16
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-experimental-memory.js +1 -1
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-media.d.ts +11 -11
- package/dist/sdk-media.js +1 -1
- package/dist/sdk-repl.d.ts +15 -15
- package/dist/sdk-repl.js +1 -1
- package/dist/sdk-runtime.d.ts +14 -14
- package/dist/sdk-runtime.js +1 -1
- package/dist/sdk-sandbox.js +1 -1
- package/dist/sdk-session.d.ts +6 -6
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/semantic-worker.js +70 -70
- package/dist/static-text.json +50 -2
- package/dist/storage-repair-cli.js +1 -1
- package/dist/types-chunks/{bash-prefix-extractor.d-RblzA9kO.d.ts → bash-prefix-extractor.d-CJliu5-D.d.ts} +43 -2
- package/dist/types-chunks/{capsule.d-C-saon3X.d.ts → capsule.d-EMwSALqK.d.ts} +3 -3
- package/dist/types-chunks/{client-contract-D8HXN_iu.d.ts → client-contract-B7q69yMA.d.ts} +19 -3
- package/dist/types-chunks/{controller.d-pXik2EIy.d.ts → controller.d-D-hPLKaA.d.ts} +1 -1
- package/dist/types-chunks/{manifest.d-r74es7yq.d.ts → manifest.d-YE3-AIeO.d.ts} +1 -1
- package/dist/types-chunks/{public-api.d-CvDSMmN2.d.ts → public-api.d-BhDU643p.d.ts} +3 -3
- package/dist/types-chunks/{review-packet.d-C0NYHPdq.d.ts → review-packet.d-ChOfJaNI.d.ts} +1 -1
- package/dist/types-chunks/{run-manager.d-COrEJ-hn.d.ts → run-manager.d-ChzguipG.d.ts} +12 -6
- package/dist/types-chunks/{runtime-client-info-DJ9srk4O.d.ts → runtime-client-info-P_mRDG7j.d.ts} +6 -1
- package/dist/types-chunks/{runtime-event-B24TGIxk.d.ts → runtime-event-BW5Pla7a.d.ts} +1 -1
- package/dist/types-chunks/{sdk-runtime-CBPScTNR.d.ts → sdk-runtime-cDe7qmN3.d.ts} +18 -10
- package/dist/types-chunks/{sdk-session-D_bf_sN2.d.ts → sdk-session-D3pcSbnA.d.ts} +1 -1
- package/dist/types-chunks/{skill-invocation-error.d-FJ6ZujRz.d.ts → skill-invocation-error.d-gsNNDnnt.d.ts} +2 -2
- package/dist/types-chunks/{trusted-repl-entry-9i4hUuj-.d.ts → trusted-repl-entry-Bbkd2HlO.d.ts} +6 -6
- package/dist/types-chunks/{types.d-CTo0NiAM.d.ts → types.d-BlXTogOo.d.ts} +2 -0
- package/dist/types-chunks/{utils.d-BhoGV3yv.d.ts → utils.d-CxHyBvO6.d.ts} +5 -5
- package/docs/SDK_MIGRATION.md +264 -1
- package/docs/SPACE_SDK_SEAMS.md +1 -1
- package/package.json +1 -1
- package/public_docs/README.md +8 -3
- package/public_docs/sdk/embedder-guide.md +1 -1
- package/dist/chunks/agent-OY4U4WOU.js +0 -2
- package/dist/chunks/agent-adapter-NDH3DMPG.js +0 -2
- package/dist/chunks/argument-completer-Q6GMPJ74.js +0 -2
- package/dist/chunks/chunk-4KR4VUZK.js +0 -142
- package/dist/chunks/chunk-5WZ5FUUD.js +0 -14
- package/dist/chunks/chunk-7OTOH4PT.js +0 -465
- package/dist/chunks/chunk-BZF7WPRK.js +0 -357
- package/dist/chunks/chunk-ED7D73C3.js +0 -2
- package/dist/chunks/chunk-LPHKXPF7.js +0 -190
- package/dist/chunks/chunk-MJ4IGUD4.js +0 -5
- package/dist/chunks/chunk-NQ4XK3B2.js +0 -2
- package/dist/chunks/chunk-PRH5G5J7.js +0 -12
- package/dist/chunks/chunk-YB24NTBC.js +0 -2
- package/dist/chunks/compaction-config-NKDAUZNH.js +0 -2
- package/dist/chunks/dist-NTS7CJG3.js +0 -2
- package/dist/chunks/host-RHJ3VGYE.js +0 -2
- package/dist/chunks/model-WCSO7VEC.js +0 -2
- package/dist/chunks/readline-helpers-KZQCE3NH.js +0 -2
- package/dist/chunks/run-manager-MWEV42C5.js +0 -2
- package/dist/chunks/running-session-3BYAXGLK.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{a as m}from"./chunk-AGUM5SWX.js";import{b as C}from"./chunk-
|
|
2
|
+
import{a as m}from"./chunk-AGUM5SWX.js";import{b as C}from"./chunk-3CP7AUWY.js";import{B as k,I as O,o as X}from"./chunk-QSZCR5GC.js";import{b as K}from"./chunk-C6JGLEYD.js";import{Db as g,Fb as p}from"./chunk-D36OIMV7.js";import{d as x,za as f}from"./chunk-OGTRDK4Q.js";import{a as s}from"./chunk-V4WSBIXB.js";import{isDeepStrictEqual as R}from"node:util";function y(e,o){let a=e.events,r=new Map;return{...e,guardrails:e.guardrails?.map(t=>{if(t.kind!=="tool"||t.name!=="auto-mode")return t;let n=t.beforeTool;return n?{...t,kind:"tool",async beforeTool(d,i){let T=f(d),c=T?.ok?T.call:d;o.revoke(c.id),r.delete(c.id);let l=await n.call(t,d,i);return l.action==="allow"&&r.set(c.id,structuredClone(c)),l}}:t}),events:{...a,async beforeToolExecute(t,n,d){let i=d?.toolId,T=i===void 0?void 0:r.get(i);i!==void 0&&(o.revoke(i),r.delete(i));let c=await a?.beforeToolExecute?.(t,n,d);if(i!==void 0){let l={id:i,name:t,input:n};(c===!0||c===void 0&&R(l,T))&&o.grant(l)}return c??!0},onToolExecutionEnd(t,n){o.revoke(t.id),a?.onToolExecutionEnd?.(t,n)}}}}s(y,"withDirectTextApprovals");function u(e){if(e.context?.trustedTextMutationHost!==void 0)return e;let o=e.context?.gitRoot??e.context?.executionCwd??process.cwd(),a=e.context?.executionCwd??o,r=m(a,()=>e.context?.resolveShellPermissionMode?.()==="auto"),t=C(()=>[o,a,...e.context?.workspaceSandboxRoots?.list()??[]],n=>x(n,a,[],e.context?.resolveShellPermissionMode?.()==="full-access"),()=>e.context?.resolveShellPermissionMode?.()==="full-access",r.authorize);return y({...e,context:{...e.context,trustedTextMutationHost:t}},r)}s(u,"withTrustedTextMutationHost");function v(e,o){return p(u(e),o)}s(v,"runKodaX");function P(e,o){return K(u(e),o)}s(P,"startKodaX");function S(e,o){return k(u(e),o)}s(S,"runManagedTask");function E(e){let o=e.runAgent??p,a=e.createOptions;return O({...e,createOptions:s((r,t,n)=>u(a?.(r,t,n)??n),"createOptions"),runAgent:s((r,t)=>o(u(r),t),"runAgent")})}s(E,"createKodaXTaskRunner");function D(e={}){let o=g(e),a=o.substrateExecutor;return Object.freeze({...o,substrateExecutor:s(((r,t,n,d)=>{let i=n?.presetOptions??{};return a(r,t,{...n,presetOptions:u(i)},d)}),"substrateExecutor")})}s(D,"createDefaultCodingAgent");var A=class extends X{static{s(this,"KodaXClient")}constructor(o){super(o,v)}};export{u as a,v as b,P as c,S as d,E as e,D as f,A as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{qd as o}from"./chunk-
|
|
2
|
+
import{qd as o}from"./chunk-2HH5AS7E.js";import{c}from"./chunk-J2L2NK6E.js";import{a as n}from"./chunk-V4WSBIXB.js";import{readFile as a}from"fs/promises";var i={enabled:!0,triggerPercent:75};async function s(r){let t=c("config.json");try{let e=await f(t);if(e?.compaction)return o({...i,...e.compaction})}catch{}return o(i)}n(s,"loadCompactionConfig");async function f(r){try{let t=await a(r,"utf-8");return JSON.parse(t)}catch{return null}}n(f,"readConfigFile");export{s as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{a as L,b as ne,o as de,r as X,s as ue,t as le}from"./chunk-
|
|
2
|
+
import{a as L,b as ne,o as de,r as X,s as ue,t as le}from"./chunk-XDMNJW6J.js";import{$b as ie,_b as ae,cc as se,dc as ce}from"./chunk-OGTRDK4Q.js";import{h as J,j as oe}from"./chunk-J2L2NK6E.js";import{a as s}from"./chunk-V4WSBIXB.js";import{execFile as Pe}from"node:child_process";import V from"node:path";import{promisify as Re}from"node:util";var be=Re(Pe),xe=1e4,ke=2,fe=new Set(["write","edit","multi_edit","insert_after_anchor"]),me=new Set(["read"]);function Ce(e,t){if(t.includes("*"))return e;if(e.includes("*"))return t;let r=new Set(t);return e.filter(c=>r.has(c))}s(Ce,"intersectWorkflowToolCeilings");var Se=/^\s*(?:let me|i will|i'll|i am going to)\b[\s\S]{0,120}\b(?:start|create|implement|write|build|plan)\b|^\s*(?:我将|让我|接下来)[\s\S]{0,80}(?:开始|创建|编写|实现|制定)/i;async function ot(e,t,r){let c=e.turn.checkpoint;if(!c||typeof c!="object"||Array.isArray(c)||!("workflow"in c))throw new Error("Workflow generation recovery instructions are missing.");let i=c.workflow;if(!i||i.customExecutor||!i.bundle||!i.input||!i.childOptions||!i.changedPathBaseline||!i.mutation)throw new Error("Workflow generation recovery requires its original executor binding.");let h=De({ctx:t,recovery:{execution:e,snapshot:i},runId:i.runId,childOptions:{...i.childOptions,historyStorage:r.session?.storage,guardrails:t.guardrails,planModeBlockCheck:t.planModeBlockCheck,parentOptions:{...r,extensionRuntime:t.extensionRuntime,events:t.parentEvents}}}),b=await h.spawn(i.input),x=await h.wait(b.taskId);if(x.status!=="completed"&&x.status!=="completed_unverified")throw new Error(x.finalText);return{output:x.finalText,structured:X(JSON.parse(JSON.stringify({workflowRunId:i.runId,taskId:b.taskId,actorPath:e.actor.path,turnId:e.turn.turnId,result:x}))),artifacts:x.artifacts}}s(ot,"resumeWorkflowGenerationTurn");function Ie(e){if(e?.timeoutMs!==void 0){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("workflow wait timeoutMs must be a positive number");return Math.floor(e.timeoutMs)}}s(Ie,"normalizeWaitTimeoutMs");function Z(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}s(Z,"hasVerificationWork");function q(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}s(q,"normalizeWorkspacePath");function Y(e,t){let r=t.gitRoot?V.resolve(t.gitRoot):void 0,c=V.isAbsolute(e)&&r?V.relative(r,V.resolve(e)):e;return q(c)}s(Y,"normalizeRequiredPath");function Fe(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let r={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},c=e.verification.requiredChangedPaths;return{verification:{...r,...c!==void 0&&c.length>0&&r.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}s(Fe,"resolveVerificationForInput");function Ee(e,t){if(t===!0&&e.readOnly===!1)throw new Error(`workflow manifest readOnly=true cannot spawn write-capable child "${e.name}"; set the workflow manifest readOnly=false or use child readOnly:true`);let r=e.readOnly??t??!1;return e.readOnly===r?e:{...e,readOnly:r}}s(Ee,"resolveSpawnAgentInput");function ye(e){let t=e.trim();return t.length>0&&Se.test(t)}s(ye,"isPreparatoryOnlyText");function Ae(e,t){let r=e.trim(),c=t?.trim();return c&&(r.length===0||ye(r))?c:e}s(Ae,"selectWorkflowFinalText");async function G(e,t){return await oe({cwd:t}),(await be("git",[...e],{cwd:t,timeout:xe,windowsHide:!0,maxBuffer:4*1024*1024})).stdout.toString()}s(G,"runGit");async function Me(e){let t=e.gitRoot??e.executionCwd??process.cwd(),r=(await G(["rev-parse","--show-toplevel"],t)).trim(),c=await Promise.all([G(["diff","--name-only","--"],r),G(["diff","--cached","--name-only","--"],r),G(["ls-files","--others","--exclude-standard"],r)]);return[...new Set(c.flatMap(i=>i.split(/\r?\n/)).map(q).filter(i=>i.length>0))]}s(Me,"listGitChangedFiles");async function Q(e,t){try{return{paths:(await t(e)).map(q).filter(c=>c.length>0)}}catch(r){return{paths:[],error:r instanceof Error?r.message:String(r)}}}s(Q,"captureChangedPaths");function Oe(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[],readPathById:new Map,succeededReadPaths:[]}}s(Oe,"createMutationRecorder");function he(e){if(e)for(let t of["path","file_path","target_path"]){let r=e[t];if(typeof r=="string"&&r.trim().length>0)return q(r)}}s(he,"readMutationPath");function Ue(e,t){return{...e??{},onToolUseStart:s((r,c)=>{if(fe.has(r.name)){t.toolNameById.set(r.id,r.name);let i=he(r.input);i!==void 0&&t.toolPathById.set(r.id,i)}if(me.has(r.name)){let i=he(r.input);i!==void 0&&t.readPathById.set(r.id,i)}e?.onToolUseStart?.(r,c)},"onToolUseStart"),onToolResult:s((r,c)=>{let i=t.toolNameById.get(r.id)??r.name;if(fe.has(i)&&!r.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(i);let h=t.toolPathById.get(r.id);h!==void 0&&t.succeededPaths.push(h)}if(me.has(i)&&!r.content.trimStart().startsWith("[Tool Error]")){let h=t.readPathById.get(r.id);h!==void 0&&t.succeededReadPaths.push(h)}e?.onToolResult?.(r,c)},"onToolResult")}}s(Ue,"wrapEventsForMutationRecording");function K(e){return[...new Set(e.filter(t=>t.trim().length>0))]}s(K,"uniqueItems");function pe(e){let t=e.verification;if(!t)return;let r=[],c=new Set(e.before.paths.map(q)),i=K(e.after.paths.map(q)),h=i.filter(y=>!c.has(y)),b=K(e.mutationRecorder.succeededToolCalls),x=e.acceptToolMutationEvidence?b:[],N=e.acceptToolMutationEvidence?K(e.mutationRecorder.succeededPaths.map(q)):[],M=h.length>0||x.length>0,S=t.enforcement??"hard",W=(t.requiredChangedPaths??[]).map(y=>Y(y,e.ctx)),_=K(e.mutationRecorder.succeededReadPaths.map(y=>Y(y,e.ctx))),z=(t.requiredReadPaths??[]).map(y=>Y(y,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?r.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):M||r.push(e.acceptToolMutationEvidence||b.length===0?"expected file mutations, but no new workspace changes or successful write tools were observed":"write tools ran in an isolated worktree, but no main workspace changes were present after cleanup")),e.term.limitReached===!0&&!M&&r.push("workflow child reached its iteration limit before satisfying the task");for(let y of W)!i.includes(y)&&!N.includes(y)&&r.push(`required changed path was not present in workspace changes: ${y}`);for(let y of z)_.includes(y)||r.push(`required review evidence was not read: ${y}`);let B=t.minFinalTextChars;return B!==void 0&&!M&&e.term.finalText.trim().length<B&&r.push(`finalText was shorter than the required ${B} characters`),t.rejectPreparatoryFinalText===!0&&!M&&ye(e.term.finalText)&&r.push("finalText looks preparatory instead of terminal"),{ok:r.length===0,enforcement:S,reasons:r,changedPaths:i,mutationToolCalls:b,mutationEvidence:M,..._.length>0?{readPaths:_}:{}}}s(pe,"evaluateVerification");function ee(e,t){if(t.ok)return e;let c=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(i=>`- ${i}`)].join(`
|
|
3
3
|
`);return e.trim().length>0?`${e}
|
|
4
4
|
|
|
5
5
|
${c}`:c}s(ee,"appendVerificationFailure");function ge(){return{ok:!1,enforcement:"warn",reasons:["workflow child reached its iteration limit before satisfying the task"],mutationEvidence:!1}}s(ge,"limitReachedWarningVerification");function $e(e){return e.entry.bundle.readOnly!==!0&&e.entry.repairAttempts<ke&&e.term.status==="completed"&&e.verification!==void 0&&e.verification.ok!==!0&&e.verification.enforcement!=="warn"}s($e,"shouldRepairVerificationFailure");function qe(e){let t=e.verification.reasons.map(c=>`- ${c}`).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{ja as Ne,la as Te}from"./chunk-NM3AINLH.js";import{Sa as De}from"./chunk-KQ3XVHKK.js";import{b as ke,j as Le}from"./chunk-E2Z754K5.js";import{F as Pe,G as _e,H as Me,I as Oe,J as Ae,K as ae,S as Ie,T as N,X as ce,ga as ue,la as Re,q as xe}from"./chunk-4KR4VUZK.js";import{N as oe,Q as ie,R as Ce,S as se}from"./chunk-KE2NBMAP.js";import{a as o}from"./chunk-V4WSBIXB.js";import g from"fs";import m from"path";import{exec as Vt,spawnSync as Wt}from"child_process";import{promisify as Ht}from"util";import{fileURLToPath as qt}from"url";var le="en";function pt(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}o(pt,"detectSystemLocale");function je(e){if(!e||e==="auto"){le=pt();return}le=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}o(je,"setLocale");var $e={en:{"dialog.confirm":"[Confirm]","dialog.select":"[Select]","dialog.input":"[Input]","confirm.instruction.basic":"Press (y) yes, (n) no","confirm.instruction.always":"Press (y) yes, (a) always yes for this tool, (n) no","confirm.instruction.runtime_session":"Press (y) allow once, (s) allow this Runtime scope for the session, (n) no","confirm.instruction.runtime_persistent":"Press (y) allow once, (s) allow this Runtime scope for the session, (a) always allow this Runtime scope, (n) no","confirm.instruction.protected":"Press (y) to confirm, (n) to cancel (protected path)","confirm.result.approved":"Approved","confirm.result.approved_always":"Approved (always)","confirm.result.approved_session":"Approved (this session)","confirm.result.denied":"Denied","tool.bash.title":"Execute bash command?","tool.shell.title":"Execute shell command?","tool.write.title":"Write to file?","tool.edit.title":"Edit file?","tool.generic.title":"Execute {tool}?","field.reason":"Reason","field.intent":"Intent","field.target":"Target","field.scope":"Scope","field.risk":"Risk","field.summary":"Summary","intent.read":"Read project files","intent.delete":"Delete files","intent.deps":"Modify dependencies or environment","intent.modify":"Modify files","intent.execute":"Execute command","intent.write_file":"Write file","intent.edit_file":"Edit file","intent.use_tool":"Use {tool}","risk.destructive":"Destructive change","risk.deps":"May change dependencies or local tools","risk.modify":"May modify files","risk.unknown":"Command effects depend on its arguments","risk.network":"May access network","scope.outside":"Outside project","scope.protected":"Protected path","waiting.confirm":"Waiting: approval required","waiting.select":"Waiting: choose an option","waiting.input":"Waiting: answer the prompt","placeholder.confirm":"Respond to the approval prompt above...","placeholder.select":"Choose an option above...","placeholder.input":"Answer the prompt above...","placeholder.busy":"Agent is busy...","placeholder.queue":"Queue a follow-up for the next round...","placeholder.idle":"Type a message...","select.choice":"Choice:","select.type_number":"(type a number)","select.more":"{count} more choices...","select.more_above":"\u2191 {count} more above","select.more_below":"\u2193 {count} more below","select.confirm_hint":"Press Enter to confirm, Esc to cancel","select.navigate_hint":"Use \u2191\u2193 to navigate, Enter to confirm, Esc to cancel","select.multiselect_hint":"Use \u2191\u2193 to navigate, Space to toggle, Enter to confirm, Esc to cancel","select.multiselect_empty":"Select at least one option with Space before confirming.","select.multiselect_min":"Select at least {min} option(s) with Space before confirming.","select.multiselect_max":"Select at most {max} option(s) with Space before confirming.","select.back_prev":"\u2190 Back to previous question","input.default":"Default:","input.value":"Value:","input.type_response":"(type your response)","managed.completed":"Task completed","managed.completed.blocked":"Task blocked","managed.completed.continuation":"Task needs continuation","todo.progress":"{completed}/{total} completed","todo.transcript.progress":"Plan {completed}/{total} completed","todo.summary.done":"{count} done","todo.summary.more":"+{count} more",cancelled:"[Cancelled] Operation cancelled by user",cancellationRequested:"[Cancelling] Stop requested for the current reply",cancellationAccepted:"Stop request accepted; waiting for execution to settle.",cancellationConfirmed:"Stop confirmed:",cancellationRejected:"Stop request failed:"},zh:{"dialog.confirm":"[\u786E\u8BA4]","dialog.select":"[\u9009\u62E9]","dialog.input":"[\u8F93\u5165]","confirm.instruction.basic":"\u6309 (y) \u786E\u8BA4, (n) \u62D2\u7EDD","confirm.instruction.always":"\u6309 (y) \u786E\u8BA4, (a) \u59CB\u7EC8\u5141\u8BB8\u6B64\u5DE5\u5177, (n) \u62D2\u7EDD","confirm.instruction.runtime_session":"\u6309 (y) \u4EC5\u5141\u8BB8\u4E00\u6B21, (s) \u672C\u4F1A\u8BDD\u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (n) \u62D2\u7EDD","confirm.instruction.runtime_persistent":"\u6309 (y) \u4EC5\u5141\u8BB8\u4E00\u6B21, (s) \u672C\u4F1A\u8BDD\u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (a) \u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (n) \u62D2\u7EDD","confirm.instruction.protected":"\u6309 (y) \u786E\u8BA4, (n) \u53D6\u6D88 (\u53D7\u4FDD\u62A4\u8DEF\u5F84)","confirm.result.approved":"\u5DF2\u6279\u51C6","confirm.result.approved_always":"\u5DF2\u6279\u51C6 (\u59CB\u7EC8\u5141\u8BB8)","confirm.result.approved_session":"\u5DF2\u6279\u51C6 (\u672C\u4F1A\u8BDD)","confirm.result.denied":"\u5DF2\u62D2\u7EDD","tool.bash.title":"\u6267\u884C bash \u547D\u4EE4\uFF1F","tool.shell.title":"\u6267\u884C shell \u547D\u4EE4\uFF1F","tool.write.title":"\u5199\u5165\u6587\u4EF6\uFF1F","tool.edit.title":"\u7F16\u8F91\u6587\u4EF6\uFF1F","tool.generic.title":"\u6267\u884C {tool}\uFF1F","field.reason":"\u539F\u56E0","field.intent":"\u610F\u56FE","field.target":"\u76EE\u6807","field.scope":"\u8303\u56F4","field.risk":"\u98CE\u9669","field.summary":"\u6458\u8981","intent.read":"\u8BFB\u53D6\u9879\u76EE\u6587\u4EF6","intent.delete":"\u5220\u9664\u6587\u4EF6","intent.deps":"\u4FEE\u6539\u4F9D\u8D56\u6216\u73AF\u5883","intent.modify":"\u4FEE\u6539\u6587\u4EF6","intent.execute":"\u6267\u884C\u547D\u4EE4","intent.write_file":"\u5199\u5165\u6587\u4EF6","intent.edit_file":"\u7F16\u8F91\u6587\u4EF6","intent.use_tool":"\u4F7F\u7528 {tool}","risk.destructive":"\u7834\u574F\u6027\u53D8\u66F4","risk.deps":"\u53EF\u80FD\u4FEE\u6539\u4F9D\u8D56\u6216\u672C\u5730\u5DE5\u5177","risk.modify":"\u53EF\u80FD\u4FEE\u6539\u6587\u4EF6","risk.unknown":"\u547D\u4EE4\u6548\u679C\u53D6\u51B3\u4E8E\u53C2\u6570","risk.network":"\u53EF\u80FD\u8BBF\u95EE\u7F51\u7EDC","scope.outside":"\u9879\u76EE\u5916\u90E8","scope.protected":"\u53D7\u4FDD\u62A4\u8DEF\u5F84","waiting.confirm":"\u7B49\u5F85\u4E2D\uFF1A\u9700\u8981\u5BA1\u6279","waiting.select":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u9009\u62E9","waiting.input":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u56DE\u7B54","placeholder.confirm":"\u8BF7\u56DE\u5E94\u4E0A\u65B9\u7684\u5BA1\u6279\u63D0\u793A...","placeholder.select":"\u8BF7\u5728\u4E0A\u65B9\u9009\u62E9\u4E00\u4E2A\u9009\u9879...","placeholder.input":"\u8BF7\u56DE\u7B54\u4E0A\u65B9\u7684\u63D0\u793A...","placeholder.busy":"\u667A\u80FD\u4F53\u6B63\u5728\u5DE5\u4F5C\u4E2D...","placeholder.queue":"\u6392\u961F\u7B49\u5F85\u4E0B\u4E00\u8F6E\u8DDF\u8FDB...","placeholder.idle":"\u8F93\u5165\u6D88\u606F...","select.choice":"\u9009\u9879\uFF1A","select.type_number":"(\u8F93\u5165\u7F16\u53F7)","select.more":"\u8FD8\u6709 {count} \u4E2A\u9009\u9879...","select.more_above":"\u2191 \u4E0A\u65B9\u8FD8\u6709 {count} \u4E2A","select.more_below":"\u2193 \u4E0B\u65B9\u8FD8\u6709 {count} \u4E2A","select.confirm_hint":"\u6309 Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.navigate_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0C\u7A7A\u683C \u5207\u6362\u9009\u4E2D\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_empty":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u9009\u9879\u3002","select.multiselect_min":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u81F3\u5C11\u9009\u62E9 {min} \u4E2A\u9009\u9879\u3002","select.multiselect_max":"\u6700\u591A\u53EA\u80FD\u9009\u62E9 {max} \u4E2A\u9009\u9879\u3002","select.back_prev":"\u2190 \u8FD4\u56DE\u4E0A\u4E00\u9898","input.default":"\u9ED8\u8BA4\u503C\uFF1A","input.value":"\u503C\uFF1A","input.type_response":"(\u8F93\u5165\u4F60\u7684\u56DE\u7B54)","managed.completed":"\u4EFB\u52A1\u5B8C\u6210","managed.completed.blocked":"\u4EFB\u52A1\u53D7\u963B","managed.completed.continuation":"\u4EFB\u52A1\u9700\u8981\u7EE7\u7EED","todo.progress":"{completed}/{total} \u5DF2\u5B8C\u6210","todo.transcript.progress":"\u8BA1\u5212 {completed}/{total} \u5DF2\u5B8C\u6210","todo.summary.done":"{count} \u9879\u5DF2\u5B8C\u6210","todo.summary.more":"\u53E6\u6709 {count} \u9879",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88",cancellationRequested:"[\u6B63\u5728\u53D6\u6D88] \u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u56DE\u590D",cancellationAccepted:"\u505C\u6B62\u8BF7\u6C42\u5DF2\u63A5\u53D7\uFF0C\u6B63\u5728\u7B49\u5F85\u6267\u884C\u6536\u5C3E\u3002",cancellationConfirmed:"\u505C\u6B62\u5DF2\u786E\u8BA4\uFF1A",cancellationRejected:"\u505C\u6B62\u8BF7\u6C42\u5931\u8D25\uFF1A"}};function Sn(e,t){let r=$e[le][e]??$e.en[e]??e;if(t)for(let[i,s]of Object.entries(t))r=r.replace(`{${i}}`,String(s));return r}o(Sn,"t");import{existsSync as mt,readFileSync as gt}from"node:fs";import T from"node:path";import{fileURLToPath as ht}from"node:url";var Fe=T.dirname(ht(import.meta.url)),Ke=process.env.KODAX_BUNDLED==="true"?[T.join(T.dirname(process.execPath),"generated-config-templates.json")]:[T.join(Fe,"generated-config-templates.json"),T.join(Fe,"..","generated-config-templates.json")],$=JSON.parse(gt(Ke.find(mt)??Ke[0],"utf8"));if(!$||typeof $!="object"||Array.isArray($)||!["core","mcp","a2a","extensions"].every(e=>typeof Reflect.get($,e)=="string"))throw new Error("Invalid package configuration templates.");var Xe=$;function Ue(e){return Xe[e]}o(Ue,"getConfigTemplate");import{closeSync as _t,existsSync as p,fsyncSync as Mt,linkSync as Ot,mkdirSync as ge,openSync as At,readFileSync as tt,renameSync as It,statSync as Rt,unlinkSync as Be,watch as kt,writeFileSync as Dt}from"node:fs";import{createHash as Lt}from"node:crypto";import d from"node:path";import{closeSync as W,mkdirSync as vt,openSync as Ve,rmSync as C,readFileSync as x,writeFileSync as We,fsyncSync as He,linkSync as yt,renameSync as Ge,lstatSync as qe,realpathSync as wt}from"node:fs";import{createHash as Et,randomUUID as J}from"node:crypto";import St from"node:path";var H=class extends Error{static{o(this,"CoreConfigWriteConflictError")}code="conflict";data={source:"configuration",reason:"lock_busy"};constructor(t,n=ze(t)){super(`Core configuration lock is busy or its ownership cannot be safely recovered: ${t}. Retained lock: ${n}. Use kodax doctor for offline recovery guidance; never remove a lock while shared writers may be active.`),this.name="CoreConfigWriteConflictError"}},j=class extends Error{static{o(this,"CoreConfigReadError")}code="internal_error";data={source:"configuration",reason:"read_failed"};constructor(t){super(`Core configuration is unreadable or invalid: ${t}. Retain and repair the original before continuing.`),this.name="CoreConfigReadError"}};function Je(e){try{qe(e)}catch(t){if(v(t)==="ENOENT")return{};throw new j(e)}try{let t=JSON.parse(x(e,"utf8"));if(t===null||typeof t!="object"||Array.isArray(t))throw new j(e);return t}catch{throw new j(e)}}o(Je,"readCoreConfig");var q=new Map;function bt(e){let t=q.get(e);if(t!==void 0){try{x(e,"utf8")===t&&C(e)}catch(n){if(v(n)!=="ENOENT")throw n}q.delete(e)}}o(bt,"retryInactiveRelease");function ze(e){return`${e}.write.lock`}o(ze,"coreConfigWriteLockPath");function P(e,t){let n=!1;try{n=qe(e).isSymbolicLink()}catch(s){if(v(s)!=="ENOENT")throw s}n&&(e=wt(e));let r=`${e}.${J()}.tmp`,i;try{i=Ve(r,"wx",384),We(i,t),He(i);let s=i;i=void 0,W(s),Ct(r,e)}finally{try{i!==void 0&&W(i)}finally{C(r,{force:!0})}}}o(P,"writeCoreConfigAtomically");function Ct(e,t){try{Ge(e,t)}catch(n){if(process.platform!=="win32"||v(n)!=="EPERM")throw n;let r=performance.now()+1e3,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let s=r-performance.now();if(s<=0||(Atomics.wait(i,0,0,Math.min(10,s)),performance.now()>=r))throw n;try{Ge(e,t);return}catch(a){if(v(a)!=="EPERM")throw a}}}}o(Ct,"publishCoreConfigReplacement");function v(e){if(!(!(e instanceof Error)||!("code"in e)))return typeof e.code=="string"?e.code:void 0}o(v,"errorCode");function fe(e,t){let n=`${e}.${J()}.tmp`,r,i=!1,s;try{r=Ve(n,"wx",384),We(r,t),He(r);let a=r;r=void 0,W(a);try{yt(n,e),i=!0}catch(c){if(v(c)!=="EEXIST")throw c}return i}catch(a){throw s=a,a}finally{try{try{r!==void 0&&W(r)}finally{C(n,{force:!0})}}catch(a){if(i&&x(e,"utf8")===t)try{C(e)}catch(c){throw new AggregateError([a,c],"Configuration lock cleanup failed.")}throw s!==void 0?new AggregateError([s,a],"Configuration lock publication and cleanup failed."):new AggregateError([a],a instanceof Error?a.message:"Configuration lock cleanup failed.")}}}o(fe,"publishConfigLock");function xt(e){let t,n;try{t=x(e,"utf8"),n=JSON.parse(t)}catch(r){return v(r)==="ENOENT"}if(!n||n.version!==1||!Number.isSafeInteger(n.pid)||n.pid<=0||typeof n.nonce!="string"||!n.nonce)return!1;try{return process.kill(n.pid,0),!1}catch(r){if(v(r)!=="ESRCH")return!1}return!Pt(e,n.nonce)||x(e,"utf8")!==t?!1:(C(e),!0)}o(xt,"reclaim");function Pt(e,t){let n=`${e}.reclaim.${Et("sha256").update(t).digest("hex")}`;return fe(n,JSON.stringify({pid:process.pid,nonce:J()}))}o(Pt,"claimConfigLockReclamation");function de(e,t,n){vt(St.dirname(t),{recursive:!0,mode:448}),bt(t);let r=JSON.stringify({version:1,pid:process.pid,nonce:J()});if(!fe(t,r)&&(!xt(t)||!fe(t,r)))throw new H(e,t);let i;try{return n()}catch(s){throw i=s,s}finally{try{if(q.set(t,r),x(t,"utf8")!==r)throw new H(e,t);C(t),q.delete(t)}catch(s){throw i!==void 0?new AggregateError([i,s],"Configuration write and lock release failed."):s}}}o(de,"withConfigWriteLock");function S(e,t){return de(e,ze(e),t)}o(S,"withCoreConfigWriteLock");var M=class extends Error{static{o(this,"IntegrationConfigConflictError")}constructor(t,n,r){super(`Integration configuration revision changed for ${d.basename(t)} (expected ${n??"missing"}, actual ${r??"missing"}).`),this.name="IntegrationConfigConflictError"}},Nt={mcp:"mcp.json",a2a:"a2a.json",extensions:"extensions.json"},Tt=new Set(["type","command","args","cwd","env","url","headers","connect","startupTimeoutMs","requestTimeoutMs","auth"]);function _(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(_,"isRecord");function O(e,t){if(!_(e))throw new Error(`${t} must be an object.`);return e}o(O,"requireRecord");function B(e,t,n){let r=Object.keys(e).find(i=>!t.has(i));if(r!==void 0)throw new Error(`${n} has unknown field "${r}".`)}o(B,"assertNoUnknownKeys");function nt(e,t){if(e.version!==1)throw new Error(`${t} version must be 1.`)}o(nt,"requireVersionOne");function Ye(e,t){let n=O(e,t);for(let[r,i]of Object.entries(n))if(r.trim().length===0||typeof i!="string")throw new Error(`${t} must contain non-empty string keys and string values.`);return structuredClone(n)}o(Ye,"requireStringMap");function me(e,t){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`${t} must be an array of non-empty strings.`);return e.map(n=>n.trim())}o(me,"requireStringArray");function pe(e,t){if(e!==void 0&&(!Number.isFinite(e)||Number(e)<=0))throw new Error(`${t} must be a positive number.`)}o(pe,"validatePositiveNumber");function $t(e,t){if(e.trim().length===0)throw new Error("MCP server names must not be empty.");let n=O(t,`MCP server "${e}"`);B(n,Tt,`MCP server "${e}"`);let r=n.type??"stdio";if(!["stdio","sse","streamable-http","http"].includes(String(r)))throw new Error(`MCP server "${e}" has an unsupported transport type.`);if(r==="stdio"){if(typeof n.command!="string"||n.command.trim().length===0)throw new Error(`MCP server "${e}" stdio transport requires command.`)}else if(typeof n.url!="string"||n.url.trim().length===0)throw new Error(`MCP server "${e}" ${String(r)} transport requires url.`);if(n.args!==void 0&&me(n.args,`MCP server "${e}" args`),n.cwd!==void 0&&typeof n.cwd!="string")throw new Error(`MCP server "${e}" cwd must be a string.`);if(n.env!==void 0&&Ye(n.env,`MCP server "${e}" env`),n.headers!==void 0&&Ye(n.headers,`MCP server "${e}" headers`),n.connect!==void 0&&!["lazy","prewarm","disabled"].includes(String(n.connect)))throw new Error(`MCP server "${e}" has an unsupported connect mode.`);if(pe(n.startupTimeoutMs,`MCP server "${e}" startupTimeoutMs`),pe(n.requestTimeoutMs,`MCP server "${e}" requestTimeoutMs`),n.auth!==void 0){let i=O(n.auth,`MCP server "${e}" auth`);if(B(i,new Set(["type","clientId","authorizationUrl","tokenUrl","scopes","redirectPort"]),`MCP server "${e}" auth`),i.type!=="oauth2")throw new Error(`MCP server "${e}" auth type must be oauth2.`);for(let a of["clientId","authorizationUrl","tokenUrl"])if(i[a]!==void 0&&typeof i[a]!="string")throw new Error(`MCP server "${e}" auth.${a} must be a string.`);i.scopes!==void 0&&me(i.scopes,`MCP server "${e}" auth.scopes`),pe(i.redirectPort,`MCP server "${e}" auth.redirectPort`)}return structuredClone(n)}o($t,"parseMcpServer");function A(e){let t=O(e,"MCP integration config");B(t,new Set(["version","servers"]),"MCP integration config"),nt(t,"MCP integration config");let n=O(t.servers,"MCP integration config servers"),r={};for(let[i,s]of Object.entries(n))r[i]=$t(i,s);return{version:1,servers:r}}o(A,"parseMcpIntegrationDocument");function I(e){let t=O(e,"Extensions integration config");B(t,new Set(["version","paths"]),"Extensions integration config"),nt(t,"Extensions integration config");let n=me(t.paths,"Extensions integration config paths");if(new Set(n).size!==n.length)throw new Error("Extensions integration config paths must not contain duplicates.");return{version:1,paths:n}}o(I,"parseExtensionsIntegrationDocument");function R(e,t){return d.join(d.resolve(t),"integrations",Nt[e])}o(R,"resolveIntegrationConfigPath");function D(e){return d.join(d.resolve(e),"config.json")}o(D,"coreConfigPath");function rt(e){return Lt("sha256").update(e).digest("hex")}o(rt,"hashText");function ot(e){let t=tt(e,"utf8");try{return{raw:t,value:JSON.parse(t)}}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`Invalid JSON: ${r}`)}}o(ot,"readJsonFile");function k(e){return{domain:e.domain,source:e.source,path:e.path,revision:rt(e.raw),document:structuredClone(e.document),loadedAt:new Date().toISOString()}}o(k,"snapshot");function Y(e){return Je(D(e))}o(Y,"readCoreConfig");function Q(e){let t=R("mcp",e);if(p(t)){let s=ot(t);return k({domain:"mcp",source:"user",path:t,raw:s.raw,document:A(s.value)})}let n=D(e),r=Y(e).mcpServers,i=A({version:1,servers:r===void 0?{}:r});return k({domain:"mcp",source:r===void 0?"default":"legacy-user",path:r===void 0?t:n,raw:JSON.stringify(i),document:i})}o(Q,"readMcpIntegration");function Z(e){let t=R("extensions",e);if(p(t)){let s=ot(t);return k({domain:"extensions",source:"user",path:t,raw:s.raw,document:I(s.value)})}let n=D(e),r=Y(e).extensions,i=I({version:1,paths:r===void 0?[]:r});return k({domain:"extensions",source:r===void 0?"default":"legacy-user",path:r===void 0?t:n,raw:JSON.stringify(i),document:i})}o(Z,"readExtensionsIntegration");function jt(e){if(!_(e))return[];let t=[],n=/(token|secret|password|api[_-]?key|authorization)/i;for(let[r,i]of Object.entries(e))if(_(i))for(let s of["env","headers"]){let a=i[s];if(_(a))for(let[c,u]of Object.entries(a))n.test(c)&&typeof u=="string"&&!u.startsWith("${env:")&&t.push(`MCP server "${r}" ${s}.${c} may contain a literal secret.`)}return t}o(jt,"likelySecretWarnings");function Ft(e){let t=Y(e),n=R("mcp",e),r=R("extensions",e),i=t.mcpServers,s=t.extensions,a=_(i)?Object.keys(i).length:0,c=Array.isArray(s)?s.length:0,u=o((h,G,V)=>p(h)?{action:"none",entries:G,destination:h,reason:"destination-exists"}:V?{action:"create",entries:G,destination:h}:{action:"none",entries:0,destination:h,reason:"legacy-absent"},"domainPlan");return{mcp:u(n,a,i!==void 0),extensions:u(r,c,s!==void 0),warnings:jt(i)}}o(Ft,"planLegacyIntegrationMigration");function Kt(e,t){let n=D(e);ge(d.dirname(n),{recursive:!0,mode:448});try{P(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
import{ja as Ne,la as Te}from"./chunk-D36OIMV7.js";import{Sa as De}from"./chunk-2HH5AS7E.js";import{b as Ce,j as Le}from"./chunk-J2L2NK6E.js";import{F as _e,G as Me,H as Oe,I as Ae,J as Ie,K as ae,S as Re,T as N,X as ce,ga as ue,la as ke,q as Pe}from"./chunk-SK3RRGHJ.js";import{N as oe,Q as ie,R as xe,S as se}from"./chunk-KE2NBMAP.js";import{a as o}from"./chunk-V4WSBIXB.js";import g from"fs";import m from"path";import{exec as Vt,spawnSync as Wt}from"child_process";import{promisify as Ht}from"util";import{fileURLToPath as qt}from"url";var le="en";function pt(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}o(pt,"detectSystemLocale");function je(e){if(!e||e==="auto"){le=pt();return}le=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}o(je,"setLocale");var $e={en:{"dialog.confirm":"[Confirm]","dialog.select":"[Select]","dialog.input":"[Input]","confirm.instruction.basic":"Press (y) yes, (n) no","confirm.instruction.always":"Press (y) yes, (a) always yes for this tool, (n) no","confirm.instruction.runtime_session":"Press (y) allow once, (s) allow this Runtime scope for the session, (n) no","confirm.instruction.runtime_persistent":"Press (y) allow once, (s) allow this Runtime scope for the session, (a) always allow this Runtime scope, (n) no","confirm.instruction.protected":"Press (y) to confirm, (n) to cancel (protected path)","confirm.result.approved":"Approved","confirm.result.approved_always":"Approved (always)","confirm.result.approved_session":"Approved (this session)","confirm.result.denied":"Denied","tool.bash.title":"Execute bash command?","tool.shell.title":"Execute shell command?","tool.write.title":"Write to file?","tool.edit.title":"Edit file?","tool.generic.title":"Execute {tool}?","field.reason":"Reason","field.intent":"Intent","field.target":"Target","field.scope":"Scope","field.risk":"Risk","field.summary":"Summary","intent.read":"Read project files","intent.delete":"Delete files","intent.deps":"Modify dependencies or environment","intent.modify":"Modify files","intent.execute":"Execute command","intent.write_file":"Write file","intent.edit_file":"Edit file","intent.use_tool":"Use {tool}","risk.destructive":"Destructive change","risk.deps":"May change dependencies or local tools","risk.modify":"May modify files","risk.unknown":"Command effects depend on its arguments","risk.network":"May access network","scope.outside":"Outside project","scope.protected":"Protected path","waiting.confirm":"Waiting: approval required","waiting.select":"Waiting: choose an option","waiting.input":"Waiting: answer the prompt","placeholder.confirm":"Respond to the approval prompt above...","placeholder.select":"Choose an option above...","placeholder.input":"Answer the prompt above...","placeholder.busy":"Agent is busy...","placeholder.queue":"Queue a follow-up for the next round...","placeholder.idle":"Type a message...","select.choice":"Choice:","select.type_number":"(type a number)","select.more":"{count} more choices...","select.more_above":"\u2191 {count} more above","select.more_below":"\u2193 {count} more below","select.confirm_hint":"Press Enter to confirm, Esc to cancel","select.navigate_hint":"Use \u2191\u2193 to navigate, Enter to confirm, Esc to cancel","select.multiselect_hint":"Use \u2191\u2193 to navigate, Space to toggle, Enter to confirm, Esc to cancel","select.multiselect_empty":"Select at least one option with Space before confirming.","select.multiselect_min":"Select at least {min} option(s) with Space before confirming.","select.multiselect_max":"Select at most {max} option(s) with Space before confirming.","select.back_prev":"\u2190 Back to previous question","input.default":"Default:","input.value":"Value:","input.type_response":"(type your response)","managed.completed":"Task completed","managed.completed.blocked":"Task blocked","managed.completed.continuation":"Task needs continuation","todo.progress":"{completed}/{total} completed","todo.transcript.progress":"Plan {completed}/{total} completed","todo.summary.done":"{count} done","todo.summary.more":"+{count} more",cancelled:"[Cancelled] Operation cancelled by user",cancellationRequested:"[Cancelling] Stop requested for the current reply",cancellationAccepted:"Stop request accepted; waiting for execution to settle.",cancellationConfirmed:"Stop confirmed:",cancellationRejected:"Stop request failed:"},zh:{"dialog.confirm":"[\u786E\u8BA4]","dialog.select":"[\u9009\u62E9]","dialog.input":"[\u8F93\u5165]","confirm.instruction.basic":"\u6309 (y) \u786E\u8BA4, (n) \u62D2\u7EDD","confirm.instruction.always":"\u6309 (y) \u786E\u8BA4, (a) \u59CB\u7EC8\u5141\u8BB8\u6B64\u5DE5\u5177, (n) \u62D2\u7EDD","confirm.instruction.runtime_session":"\u6309 (y) \u4EC5\u5141\u8BB8\u4E00\u6B21, (s) \u672C\u4F1A\u8BDD\u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (n) \u62D2\u7EDD","confirm.instruction.runtime_persistent":"\u6309 (y) \u4EC5\u5141\u8BB8\u4E00\u6B21, (s) \u672C\u4F1A\u8BDD\u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (a) \u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (n) \u62D2\u7EDD","confirm.instruction.protected":"\u6309 (y) \u786E\u8BA4, (n) \u53D6\u6D88 (\u53D7\u4FDD\u62A4\u8DEF\u5F84)","confirm.result.approved":"\u5DF2\u6279\u51C6","confirm.result.approved_always":"\u5DF2\u6279\u51C6 (\u59CB\u7EC8\u5141\u8BB8)","confirm.result.approved_session":"\u5DF2\u6279\u51C6 (\u672C\u4F1A\u8BDD)","confirm.result.denied":"\u5DF2\u62D2\u7EDD","tool.bash.title":"\u6267\u884C bash \u547D\u4EE4\uFF1F","tool.shell.title":"\u6267\u884C shell \u547D\u4EE4\uFF1F","tool.write.title":"\u5199\u5165\u6587\u4EF6\uFF1F","tool.edit.title":"\u7F16\u8F91\u6587\u4EF6\uFF1F","tool.generic.title":"\u6267\u884C {tool}\uFF1F","field.reason":"\u539F\u56E0","field.intent":"\u610F\u56FE","field.target":"\u76EE\u6807","field.scope":"\u8303\u56F4","field.risk":"\u98CE\u9669","field.summary":"\u6458\u8981","intent.read":"\u8BFB\u53D6\u9879\u76EE\u6587\u4EF6","intent.delete":"\u5220\u9664\u6587\u4EF6","intent.deps":"\u4FEE\u6539\u4F9D\u8D56\u6216\u73AF\u5883","intent.modify":"\u4FEE\u6539\u6587\u4EF6","intent.execute":"\u6267\u884C\u547D\u4EE4","intent.write_file":"\u5199\u5165\u6587\u4EF6","intent.edit_file":"\u7F16\u8F91\u6587\u4EF6","intent.use_tool":"\u4F7F\u7528 {tool}","risk.destructive":"\u7834\u574F\u6027\u53D8\u66F4","risk.deps":"\u53EF\u80FD\u4FEE\u6539\u4F9D\u8D56\u6216\u672C\u5730\u5DE5\u5177","risk.modify":"\u53EF\u80FD\u4FEE\u6539\u6587\u4EF6","risk.unknown":"\u547D\u4EE4\u6548\u679C\u53D6\u51B3\u4E8E\u53C2\u6570","risk.network":"\u53EF\u80FD\u8BBF\u95EE\u7F51\u7EDC","scope.outside":"\u9879\u76EE\u5916\u90E8","scope.protected":"\u53D7\u4FDD\u62A4\u8DEF\u5F84","waiting.confirm":"\u7B49\u5F85\u4E2D\uFF1A\u9700\u8981\u5BA1\u6279","waiting.select":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u9009\u62E9","waiting.input":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u56DE\u7B54","placeholder.confirm":"\u8BF7\u56DE\u5E94\u4E0A\u65B9\u7684\u5BA1\u6279\u63D0\u793A...","placeholder.select":"\u8BF7\u5728\u4E0A\u65B9\u9009\u62E9\u4E00\u4E2A\u9009\u9879...","placeholder.input":"\u8BF7\u56DE\u7B54\u4E0A\u65B9\u7684\u63D0\u793A...","placeholder.busy":"\u667A\u80FD\u4F53\u6B63\u5728\u5DE5\u4F5C\u4E2D...","placeholder.queue":"\u6392\u961F\u7B49\u5F85\u4E0B\u4E00\u8F6E\u8DDF\u8FDB...","placeholder.idle":"\u8F93\u5165\u6D88\u606F...","select.choice":"\u9009\u9879\uFF1A","select.type_number":"(\u8F93\u5165\u7F16\u53F7)","select.more":"\u8FD8\u6709 {count} \u4E2A\u9009\u9879...","select.more_above":"\u2191 \u4E0A\u65B9\u8FD8\u6709 {count} \u4E2A","select.more_below":"\u2193 \u4E0B\u65B9\u8FD8\u6709 {count} \u4E2A","select.confirm_hint":"\u6309 Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.navigate_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0C\u7A7A\u683C \u5207\u6362\u9009\u4E2D\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_empty":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u9009\u9879\u3002","select.multiselect_min":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u81F3\u5C11\u9009\u62E9 {min} \u4E2A\u9009\u9879\u3002","select.multiselect_max":"\u6700\u591A\u53EA\u80FD\u9009\u62E9 {max} \u4E2A\u9009\u9879\u3002","select.back_prev":"\u2190 \u8FD4\u56DE\u4E0A\u4E00\u9898","input.default":"\u9ED8\u8BA4\u503C\uFF1A","input.value":"\u503C\uFF1A","input.type_response":"(\u8F93\u5165\u4F60\u7684\u56DE\u7B54)","managed.completed":"\u4EFB\u52A1\u5B8C\u6210","managed.completed.blocked":"\u4EFB\u52A1\u53D7\u963B","managed.completed.continuation":"\u4EFB\u52A1\u9700\u8981\u7EE7\u7EED","todo.progress":"{completed}/{total} \u5DF2\u5B8C\u6210","todo.transcript.progress":"\u8BA1\u5212 {completed}/{total} \u5DF2\u5B8C\u6210","todo.summary.done":"{count} \u9879\u5DF2\u5B8C\u6210","todo.summary.more":"\u53E6\u6709 {count} \u9879",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88",cancellationRequested:"[\u6B63\u5728\u53D6\u6D88] \u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u56DE\u590D",cancellationAccepted:"\u505C\u6B62\u8BF7\u6C42\u5DF2\u63A5\u53D7\uFF0C\u6B63\u5728\u7B49\u5F85\u6267\u884C\u6536\u5C3E\u3002",cancellationConfirmed:"\u505C\u6B62\u5DF2\u786E\u8BA4\uFF1A",cancellationRejected:"\u505C\u6B62\u8BF7\u6C42\u5931\u8D25\uFF1A"}};function Sn(e,t){let r=$e[le][e]??$e.en[e]??e;if(t)for(let[i,s]of Object.entries(t))r=r.replace(`{${i}}`,String(s));return r}o(Sn,"t");import{existsSync as mt,readFileSync as gt}from"node:fs";import T from"node:path";import{fileURLToPath as ht}from"node:url";var Fe=T.dirname(ht(import.meta.url)),Ke=process.env.KODAX_BUNDLED==="true"?[T.join(T.dirname(process.execPath),"generated-config-templates.json")]:[T.join(Fe,"generated-config-templates.json"),T.join(Fe,"..","generated-config-templates.json")],$=JSON.parse(gt(Ke.find(mt)??Ke[0],"utf8"));if(!$||typeof $!="object"||Array.isArray($)||!["core","mcp","a2a","extensions"].every(e=>typeof Reflect.get($,e)=="string"))throw new Error("Invalid package configuration templates.");var Xe=$;function Ue(e){return Xe[e]}o(Ue,"getConfigTemplate");import{closeSync as _t,existsSync as p,fsyncSync as Mt,linkSync as Ot,mkdirSync as ge,openSync as At,readFileSync as tt,renameSync as It,statSync as Rt,unlinkSync as Be,watch as kt,writeFileSync as Dt}from"node:fs";import{createHash as Lt}from"node:crypto";import d from"node:path";import{closeSync as W,mkdirSync as vt,openSync as Ve,rmSync as C,readFileSync as x,writeFileSync as We,fsyncSync as He,linkSync as yt,renameSync as Ge,lstatSync as qe,realpathSync as wt}from"node:fs";import{createHash as Et,randomUUID as J}from"node:crypto";import St from"node:path";var H=class extends Error{static{o(this,"CoreConfigWriteConflictError")}code="conflict";data={source:"configuration",reason:"lock_busy"};constructor(t,n=ze(t)){super(`Core configuration lock is busy or its ownership cannot be safely recovered: ${t}. Retained lock: ${n}. Use kodax doctor for offline recovery guidance; never remove a lock while shared writers may be active.`),this.name="CoreConfigWriteConflictError"}},j=class extends Error{static{o(this,"CoreConfigReadError")}code="internal_error";data={source:"configuration",reason:"read_failed"};constructor(t){super(`Core configuration is unreadable or invalid: ${t}. Retain and repair the original before continuing.`),this.name="CoreConfigReadError"}};function Je(e){try{qe(e)}catch(t){if(v(t)==="ENOENT")return{};throw new j(e)}try{let t=JSON.parse(x(e,"utf8"));if(t===null||typeof t!="object"||Array.isArray(t))throw new j(e);return t}catch{throw new j(e)}}o(Je,"readCoreConfig");var q=new Map;function bt(e){let t=q.get(e);if(t!==void 0){try{x(e,"utf8")===t&&C(e)}catch(n){if(v(n)!=="ENOENT")throw n}q.delete(e)}}o(bt,"retryInactiveRelease");function ze(e){return`${e}.write.lock`}o(ze,"coreConfigWriteLockPath");function P(e,t){let n=!1;try{n=qe(e).isSymbolicLink()}catch(s){if(v(s)!=="ENOENT")throw s}n&&(e=wt(e));let r=`${e}.${J()}.tmp`,i;try{i=Ve(r,"wx",384),We(i,t),He(i);let s=i;i=void 0,W(s),Ct(r,e)}finally{try{i!==void 0&&W(i)}finally{C(r,{force:!0})}}}o(P,"writeCoreConfigAtomically");function Ct(e,t){try{Ge(e,t)}catch(n){if(process.platform!=="win32"||v(n)!=="EPERM")throw n;let r=performance.now()+1e3,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let s=r-performance.now();if(s<=0||(Atomics.wait(i,0,0,Math.min(10,s)),performance.now()>=r))throw n;try{Ge(e,t);return}catch(a){if(v(a)!=="EPERM")throw a}}}}o(Ct,"publishCoreConfigReplacement");function v(e){if(!(!(e instanceof Error)||!("code"in e)))return typeof e.code=="string"?e.code:void 0}o(v,"errorCode");function fe(e,t){let n=`${e}.${J()}.tmp`,r,i=!1,s;try{r=Ve(n,"wx",384),We(r,t),He(r);let a=r;r=void 0,W(a);try{yt(n,e),i=!0}catch(c){if(v(c)!=="EEXIST")throw c}return i}catch(a){throw s=a,a}finally{try{try{r!==void 0&&W(r)}finally{C(n,{force:!0})}}catch(a){if(i&&x(e,"utf8")===t)try{C(e)}catch(c){throw new AggregateError([a,c],"Configuration lock cleanup failed.")}throw s!==void 0?new AggregateError([s,a],"Configuration lock publication and cleanup failed."):new AggregateError([a],a instanceof Error?a.message:"Configuration lock cleanup failed.")}}}o(fe,"publishConfigLock");function xt(e){let t,n;try{t=x(e,"utf8"),n=JSON.parse(t)}catch(r){return v(r)==="ENOENT"}if(!n||n.version!==1||!Number.isSafeInteger(n.pid)||n.pid<=0||typeof n.nonce!="string"||!n.nonce)return!1;try{return process.kill(n.pid,0),!1}catch(r){if(v(r)!=="ESRCH")return!1}return!Pt(e,n.nonce)||x(e,"utf8")!==t?!1:(C(e),!0)}o(xt,"reclaim");function Pt(e,t){let n=`${e}.reclaim.${Et("sha256").update(t).digest("hex")}`;return fe(n,JSON.stringify({pid:process.pid,nonce:J()}))}o(Pt,"claimConfigLockReclamation");function de(e,t,n){vt(St.dirname(t),{recursive:!0,mode:448}),bt(t);let r=JSON.stringify({version:1,pid:process.pid,nonce:J()});if(!fe(t,r)&&(!xt(t)||!fe(t,r)))throw new H(e,t);let i;try{return n()}catch(s){throw i=s,s}finally{try{if(q.set(t,r),x(t,"utf8")!==r)throw new H(e,t);C(t),q.delete(t)}catch(s){throw i!==void 0?new AggregateError([i,s],"Configuration write and lock release failed."):s}}}o(de,"withConfigWriteLock");function S(e,t){return de(e,ze(e),t)}o(S,"withCoreConfigWriteLock");var M=class extends Error{static{o(this,"IntegrationConfigConflictError")}constructor(t,n,r){super(`Integration configuration revision changed for ${d.basename(t)} (expected ${n??"missing"}, actual ${r??"missing"}).`),this.name="IntegrationConfigConflictError"}},Nt={mcp:"mcp.json",a2a:"a2a.json",extensions:"extensions.json"},Tt=new Set(["type","command","args","cwd","env","url","headers","connect","startupTimeoutMs","requestTimeoutMs","auth"]);function _(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(_,"isRecord");function O(e,t){if(!_(e))throw new Error(`${t} must be an object.`);return e}o(O,"requireRecord");function B(e,t,n){let r=Object.keys(e).find(i=>!t.has(i));if(r!==void 0)throw new Error(`${n} has unknown field "${r}".`)}o(B,"assertNoUnknownKeys");function nt(e,t){if(e.version!==1)throw new Error(`${t} version must be 1.`)}o(nt,"requireVersionOne");function Ye(e,t){let n=O(e,t);for(let[r,i]of Object.entries(n))if(r.trim().length===0||typeof i!="string")throw new Error(`${t} must contain non-empty string keys and string values.`);return structuredClone(n)}o(Ye,"requireStringMap");function me(e,t){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`${t} must be an array of non-empty strings.`);return e.map(n=>n.trim())}o(me,"requireStringArray");function pe(e,t){if(e!==void 0&&(!Number.isFinite(e)||Number(e)<=0))throw new Error(`${t} must be a positive number.`)}o(pe,"validatePositiveNumber");function $t(e,t){if(e.trim().length===0)throw new Error("MCP server names must not be empty.");let n=O(t,`MCP server "${e}"`);B(n,Tt,`MCP server "${e}"`);let r=n.type??"stdio";if(!["stdio","sse","streamable-http","http"].includes(String(r)))throw new Error(`MCP server "${e}" has an unsupported transport type.`);if(r==="stdio"){if(typeof n.command!="string"||n.command.trim().length===0)throw new Error(`MCP server "${e}" stdio transport requires command.`)}else if(typeof n.url!="string"||n.url.trim().length===0)throw new Error(`MCP server "${e}" ${String(r)} transport requires url.`);if(n.args!==void 0&&me(n.args,`MCP server "${e}" args`),n.cwd!==void 0&&typeof n.cwd!="string")throw new Error(`MCP server "${e}" cwd must be a string.`);if(n.env!==void 0&&Ye(n.env,`MCP server "${e}" env`),n.headers!==void 0&&Ye(n.headers,`MCP server "${e}" headers`),n.connect!==void 0&&!["lazy","prewarm","disabled"].includes(String(n.connect)))throw new Error(`MCP server "${e}" has an unsupported connect mode.`);if(pe(n.startupTimeoutMs,`MCP server "${e}" startupTimeoutMs`),pe(n.requestTimeoutMs,`MCP server "${e}" requestTimeoutMs`),n.auth!==void 0){let i=O(n.auth,`MCP server "${e}" auth`);if(B(i,new Set(["type","clientId","authorizationUrl","tokenUrl","scopes","redirectPort"]),`MCP server "${e}" auth`),i.type!=="oauth2")throw new Error(`MCP server "${e}" auth type must be oauth2.`);for(let a of["clientId","authorizationUrl","tokenUrl"])if(i[a]!==void 0&&typeof i[a]!="string")throw new Error(`MCP server "${e}" auth.${a} must be a string.`);i.scopes!==void 0&&me(i.scopes,`MCP server "${e}" auth.scopes`),pe(i.redirectPort,`MCP server "${e}" auth.redirectPort`)}return structuredClone(n)}o($t,"parseMcpServer");function A(e){let t=O(e,"MCP integration config");B(t,new Set(["version","servers"]),"MCP integration config"),nt(t,"MCP integration config");let n=O(t.servers,"MCP integration config servers"),r={};for(let[i,s]of Object.entries(n))r[i]=$t(i,s);return{version:1,servers:r}}o(A,"parseMcpIntegrationDocument");function I(e){let t=O(e,"Extensions integration config");B(t,new Set(["version","paths"]),"Extensions integration config"),nt(t,"Extensions integration config");let n=me(t.paths,"Extensions integration config paths");if(new Set(n).size!==n.length)throw new Error("Extensions integration config paths must not contain duplicates.");return{version:1,paths:n}}o(I,"parseExtensionsIntegrationDocument");function R(e,t){return d.join(d.resolve(t),"integrations",Nt[e])}o(R,"resolveIntegrationConfigPath");function D(e){return d.join(d.resolve(e),"config.json")}o(D,"coreConfigPath");function rt(e){return Lt("sha256").update(e).digest("hex")}o(rt,"hashText");function ot(e){let t=tt(e,"utf8");try{return{raw:t,value:JSON.parse(t)}}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`Invalid JSON: ${r}`)}}o(ot,"readJsonFile");function k(e){return{domain:e.domain,source:e.source,path:e.path,revision:rt(e.raw),document:structuredClone(e.document),loadedAt:new Date().toISOString()}}o(k,"snapshot");function Y(e){return Je(D(e))}o(Y,"readCoreConfig");function Q(e){let t=R("mcp",e);if(p(t)){let s=ot(t);return k({domain:"mcp",source:"user",path:t,raw:s.raw,document:A(s.value)})}let n=D(e),r=Y(e).mcpServers,i=A({version:1,servers:r===void 0?{}:r});return k({domain:"mcp",source:r===void 0?"default":"legacy-user",path:r===void 0?t:n,raw:JSON.stringify(i),document:i})}o(Q,"readMcpIntegration");function Z(e){let t=R("extensions",e);if(p(t)){let s=ot(t);return k({domain:"extensions",source:"user",path:t,raw:s.raw,document:I(s.value)})}let n=D(e),r=Y(e).extensions,i=I({version:1,paths:r===void 0?[]:r});return k({domain:"extensions",source:r===void 0?"default":"legacy-user",path:r===void 0?t:n,raw:JSON.stringify(i),document:i})}o(Z,"readExtensionsIntegration");function jt(e){if(!_(e))return[];let t=[],n=/(token|secret|password|api[_-]?key|authorization)/i;for(let[r,i]of Object.entries(e))if(_(i))for(let s of["env","headers"]){let a=i[s];if(_(a))for(let[c,u]of Object.entries(a))n.test(c)&&typeof u=="string"&&!u.startsWith("${env:")&&t.push(`MCP server "${r}" ${s}.${c} may contain a literal secret.`)}return t}o(jt,"likelySecretWarnings");function Ft(e){let t=Y(e),n=R("mcp",e),r=R("extensions",e),i=t.mcpServers,s=t.extensions,a=_(i)?Object.keys(i).length:0,c=Array.isArray(s)?s.length:0,u=o((h,G,V)=>p(h)?{action:"none",entries:G,destination:h,reason:"destination-exists"}:V?{action:"create",entries:G,destination:h}:{action:"none",entries:0,destination:h,reason:"legacy-absent"},"domainPlan");return{mcp:u(n,a,i!==void 0),extensions:u(r,c,s!==void 0),warnings:jt(i)}}o(Ft,"planLegacyIntegrationMigration");function Kt(e,t){let n=D(e);ge(d.dirname(n),{recursive:!0,mode:448});try{P(n,`${JSON.stringify(t,null,2)}
|
|
3
3
|
`)}catch(r){throw new Error("Failed to atomically clean legacy integration fields.",{cause:r})}}o(Kt,"writeCoreConfigAtomically");function jn(e){return S(D(e.configHome),()=>Xt(e))}o(jn,"migrateLegacyIntegrationConfig");function Xt(e){let t=Ft(e.configHome),n=Y(e.configHome),r=t.mcp.action==="create"?A({version:1,servers:_(n.mcpServers)?n.mcpServers:{}}):void 0,i=t.extensions.action==="create"?I({version:1,paths:Array.isArray(n.extensions)?n.extensions:[]}):void 0,s=[];if(r)try{F({domain:"mcp",configHome:e.configHome,expectedRevision:null,document:r,validate:A}),s.push("mcp")}catch(c){if(!(c instanceof M))throw c}if(i)try{F({domain:"extensions",configHome:e.configHome,expectedRevision:null,document:i,validate:I}),s.push("extensions")}catch(c){if(!(c instanceof M))throw c}let a=!1;if(e.cleanupLegacy&&p(D(e.configHome))){let c={...n};p(t.mcp.destination)&&delete c.mcpServers,p(t.extensions.destination)&&delete c.extensions,Ut(n,c)||(Kt(e.configHome,c),a=!0)}return{...t,applied:s,cleanedLegacy:a}}o(Xt,"migrateLegacyIntegrationConfigUnlocked");function Ut(e,t){return JSON.stringify(e)===JSON.stringify(t)}o(Ut,"isDeepStrictEqualForConfig");function Qe(e){return p(e)?rt(tt(e,"utf8")):void 0}o(Qe,"currentUserRevision");function F(e){let t=R(e.domain,e.configHome),n=e.validate(e.document);return ge(d.dirname(t),{recursive:!0,mode:448}),de(t,`${t}.lock`,()=>{let r=Qe(t),i=e.expectedRevision===null?void 0:e.expectedRevision;if(e.expectedRevision!==void 0&&r!==i)throw new M(t,i,r);let s=`${JSON.stringify(n,null,2)}
|
|
4
|
-
`,a=`${t}.${process.pid}.${Date.now()}.tmp`,c=At(a,"wx",384);try{Dt(c,s,"utf8"),Mt(c)}finally{_t(c)}try{e.expectedRevision===null?(Ot(a,t),Be(a)):It(a,t)}catch(u){throw p(a)&&Be(a),e.expectedRevision===null&&p(t)?new M(t,void 0,Qe(t)):new Error(`Failed to atomically replace ${d.basename(t)}.`,{cause:u})}return k({domain:e.domain,source:"user",path:t,raw:s,document:n})})}o(F,"writeIntegrationDocument");function Gt(e){if(!p(e))return"missing";let t=Rt(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}o(Gt,"metadataSignature");function Ze(e){return e.map(t=>`${t}:${Gt(t)}`).join("|")}o(Ze,"observationSignature");function z(e,t){return{code:e,message:t,time:new Date().toISOString()}}o(z,"safeDiagnostic");var et=class{static{o(this,"IntegrationConfigController")}#f;#n;#o;#a;#m;#d;#p;#e;#t;#c;#u;#g="";#s=[];#r;#i;#h=Promise.resolve();#l=new Set;constructor(t){this.#f=t.domain,this.#n=R(t.domain,t.configHome),this.#o=t.fallbackPath===void 0?void 0:d.resolve(t.fallbackPath),this.#a=this.#o===void 0?[this.#n]:[this.#n,this.#o],this.#d=t.validate,this.#m=t.read,this.#p=t.coldStartDefault===void 0?void 0:structuredClone(this.#d(t.coldStartDefault))}async initialize(){let t=await this.reload();if(!t.ok&&!this.#e&&this.#p!==void 0){let n=structuredClone(this.#p);this.#e=k({domain:this.#f,source:"default",path:this.#n,raw:JSON.stringify(n),document:n})}if(!this.#e)throw new Error(t.ok?"Integration configuration did not produce a snapshot.":t.error);return structuredClone(this.#e)}snapshot(){return this.#e?structuredClone(this.#e):void 0}status(){let t=this.#t?this.#c:void 0,n=this.#t?this.#u:void 0;return{domain:this.#f,path:t??this.#e?.path??this.#n,...this.#e?{revision:this.#e.revision,lastReloadAt:this.#e.loadedAt}:{},...n??this.#e?.source?{source:n??this.#e?.source}:{},...this.#t?{diagnostic:this.#t}:{},watching:this.#s.length>0}}subscribe(t){return this.#l.add(t),()=>{this.#l.delete(t)}}reload(){let t=this.#h.then(()=>this.#v());return this.#h=t.then(()=>{},()=>{}),t}async#v(){this.#g=Ze(this.#a);let t;try{t=this.#m(),this.#d(t.document)}catch{let r=this.#y();return this.#c=r.path,this.#u=r.source,this.#t=z("invalid-config","Integration configuration is invalid; check the file against its versioned schema."),{ok:!1,error:this.#t.message}}let n=this.#e?structuredClone(this.#e):void 0;try{for(let r of this.#l)await r(structuredClone(t),n)}catch{return this.#c=t.path,this.#u=t.source,this.#t=z("activation-failed","Integration configuration could not be activated; the previous configuration remains active."),{ok:!1,error:this.#t.message}}return this.#e=t,this.#t=void 0,this.#c=void 0,this.#u=void 0,{ok:!0,snapshot:structuredClone(t)}}async ensureCurrent(){return Ze(this.#a)===this.#g&&this.#e?{ok:!0,snapshot:structuredClone(this.#e)}:this.reload()}startWatching(t=100,n=2e3){if(this.#s.length>0||this.#i)return;ge(d.dirname(this.#n),{recursive:!0,mode:448});let r=new Map;for(let i of this.#a){let s=d.dirname(i),a=r.get(s)??new Set;a.add(d.basename(i)),r.set(s,a)}for(let[i,s]of r)try{let a=kt(i,(c,u)=>{u!==null&&!s.has(u.toString())||(this.#r&&clearTimeout(this.#r),this.#r=setTimeout(()=>{this.#r=void 0,this.reload()},t),this.#r.unref?.())});a.unref(),a.on("error",()=>{this.#t=z("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}),this.#s.push(a)}catch{this.#t=z("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}this.#i=setInterval(()=>{this.ensureCurrent()},n),this.#i.unref?.()}close(){this.#r&&clearTimeout(this.#r),this.#r=void 0,this.#i&&clearInterval(this.#i),this.#i=void 0;for(let t of this.#s)t.close();this.#s.length=0,this.#l.clear()}#y(){return p(this.#n)?{path:this.#n,source:"user"}:this.#o&&p(this.#o)?{path:this.#o,source:"legacy-user"}:{path:this.#n,source:"default"}}};var Jt=Ht(Vt),it=2,st=!1,l=ke(),Zn=m.join(l,"sessions"),f=m.join(l,"config.json"),er=60,y=null,ve=!1,zt="dumb";function Bt(e){let t=m.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",r=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",r],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",r]:["-lc",r],sentinel:n}}o(Bt,"buildShellEnvCommand");function Yt(e,t){let n=`${t}\0`,r=e.lastIndexOf(n);if(r===-1)return{};let i=e.slice(r+n.length),s={};for(let a of i.split("\0")){if(!a)continue;let c=a.indexOf("=");c<=0||(s[a.slice(0,c)]=a.slice(c+1))}return s}o(Yt,"parseNullDelimitedShellEnv");function Qt(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let r=e.shell??t.SHELL;if(!r||!m.isAbsolute(r))return!1;let{args:i,sentinel:s}=Bt(r),a=e.run??Wt,c={...t,TERM:zt},u=a(r,i,{encoding:"utf8",env:c,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(u.status!==0||!u.stdout)return!1;let h=typeof u.stdout=="string"?u.stdout:u.stdout.toString("utf8"),G=Yt(h,s),V=!1;for(let[re,dt]of Object.entries(G))re!=="TERM"&&t[re]===void 0&&(t[re]=dt,V=!0);return V}o(Qt,"hydrateProcessEnvFromShell");function Zt(){if(!ve){ve=!0;try{Qt()}catch{}}}o(Zt,"ensureShellEnvironmentHydrated");function tr(){ve=!1}o(tr,"resetShellEnvironmentHydrationForTesting");function en(e){Ie(e.customProviders??[])}o(en,"registerConfiguredCustomProviders");function ye(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:[]}o(ye,"normalizeConfiguredExtensions");function Ee(){let e=g.readFileSync(f,"utf8"),t=JSON.parse(e);if(!(t===null||typeof t!="object"||Array.isArray(t)))return{raw:e,value:t}}o(Ee,"readPersistedCoreConfig");function ut(e){P(f,JSON.stringify(e,null,2))}o(ut,"writePersistedCoreConfig");function tn(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{S(f,()=>{let n=Ee();n?.value.permissionMode==="default"&&ut({...n.value,permissionMode:"accept-edits"})})}catch{}return t}o(tn,"migrateLegacyPermissionModeInConfig");function nn(e){if(e.permissionMode!=="auto-in-project")return e;try{S(f,()=>{let t=Ee();if(t?.value.permissionMode!=="auto-in-project")return;let n=t.raw.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t.raw&&P(f,n)})}catch{}return{...e,permissionMode:"auto"}}o(nn,"migrateAutoInProjectAliasInConfig");function rn(){if(y)return y;let e="0.7.97-beta.1";if(e)return y=e,y;let t=m.join(m.dirname(qt(import.meta.url)),"../../package.json");if(g.existsSync(t))try{return y=JSON.parse(g.readFileSync(t,"utf-8")).version??"0.0.0",y??"0.0.0"}catch{}return y="0.0.0",y}o(rn,"getVersion");var nr=rn();function on(e){return _e(e)}o(on,"getProviderModel");function we(e,t){let n=new Set(e.map(i=>i.toLowerCase())),r=[...e];for(let i of t)n.has(i.toLowerCase())||r.push(i);return r}o(we,"mergeModels");function sn(e,t){t||(t=Se().providerModels);let n=t?.[e];if(n&&n.length>0){try{let r=ae(e);if(r.length>0)return we(n,r)}catch{}try{let r=N(e);if(r)return we(n,r.getAvailableModels())}catch{}return n}try{let r=ae(e);if(r.length>0)return r}catch{}try{let r=N(e);if(r)return r.getAvailableModels()}catch{}return[]}o(sn,"getProviderAvailableModels");function an(e,t){let n=Me(e,t);if(n!=="unknown")return n;try{let r=N(e);if(r)return r.getReasoningCapability(t)}catch{}return"unknown"}o(an,"getProviderReasoningCapability");function cn(e){let t=Oe(e);if(t)return t;try{return ce().find(r=>r.name===e)?.capabilityProfile??null}catch{return null}}o(cn,"getProviderCapabilityProfile");function lt(e,t){let n=cn(e),r=an(e,t);if(n)return{capabilityProfile:n,reasoningCapability:r};try{let i=ue(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}o(lt,"getProviderCapabilityMetadata");function rr(e,t){let n=lt(e,t);return n?Ne({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}o(rr,"getProviderCapabilitySnapshot");function un(e,t,n,r){let i=lt(e,t);return i?Te({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:r}):null}o(un,"getProviderPolicyDecision");function or(e){let t=e.transport==="cli-bridge"?"CLI bridge":"Native API",n=e.conversationSemantics==="last-user-message"?"forwards only the latest user message":"preserves full conversation history",r=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${r}`}o(or,"describeProviderCapabilitySummary");function ir(e){switch(e){case"native-budget":return"B";case"native-effort":return"E";case"native-toggle":return"T";case"native-adaptive":return"A";default:return"-"}}o(ir,"formatReasoningCapabilityShort");function L(e){if(e)return e==="none"?"off":e}o(L,"formatReasoningEffortForDisplay");function ee(e,t){let n=L(t);n&&!e.includes(n)&&e.push(n)}o(ee,"pushUniqueEffortDisplay");function sr(e,t,n){let r=["auto"],i=ne(e,t,n),s=i?.supportedEfforts?.filter(a=>a.isUserVisible!==!1);if(!s||s.length===0){for(let a of["off","low","medium","high"])ee(r,a);return r}for(let a of s)a.value==="none"&&i?.supportsDisabledThinking===!1||ee(r,a.value);return r}o(sr,"getProviderReasoningEffortOptions");function ar(e,t){let n=ne(e,t),r=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(u=>u.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let u of["low","medium","high"])ee(s,u);a=!0}else for(let u of i){if(u.value==="none"){n?.supportsDisabledThinking!==!1&&(a=!0);continue}if(r.has(u.value)){n?.supportsDisabledThinking!==!1&&(a=!0);continue}ee(s,u.value)}let c=[];return a&&c.push("off"),c.push(...s),c.push("auto"),c}o(ar,"getProviderReasoningEffortCycle");function ln(e,t){if(t===!1)return"off";switch(e){case"off":return"off";case"quick":return"low";case"balanced":return"medium";case"deep":return"high";default:return"auto"}}o(ln,"legacyReasoningModeToEffortDisplay");function ne(e,t,n){let r=t??on(e);if(!r)return;let i=Re(e,r)?.reasoningProfile;if(i)return ue(e).usesScopedReasoningLearning?.()?i:xe(i,De(e,r,n))}o(ne,"resolveReasoningProfileForDisplay");function cr(e){let t=L(e.effort)??ln(e.reasoningMode,e.thinking),n=ne(e.provider,e.model);if(!n)return t;try{let r=Ce({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=L(r.configuredEffort)??t,a=r.configuredEffort!==void 0&&n.supportsDisabledThinking!==!1&&n.disabledEfforts?.includes(r.configuredEffort)===!0?"off":L(r.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let r=se({currentEffort:e.effort,capability:n}),i=L(e.effort)??t,s=L(r.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}o(cr,"formatReasoningEffortStatusLabel");function ur(e){let t=wn(e);if(!t)return{preserved:!0};let n=ne(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let r=se({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:r.effectiveEffort,preserved:r.preserved,diagnostic:r.diagnostic}}o(ur,"resolveProviderReasoningRuntimeEffort");function fn(e){switch(e){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";case"native-adaptive":return"adaptive";default:return"none"}}o(fn,"describeReasoningCapabilityControl");function lr(e,t){if(e==="off")return"Reasoning disabled";switch(t){case"native-budget":return"Uses native thinking budget control";case"native-effort":return"Uses native reasoning effort control";case"native-toggle":return"Uses provider-native thinking toggle only";case"native-adaptive":return"Model adaptively decides thinking depth (Opus 4.7+)";case"none":return"Runs without native reasoning parameters";case"prompt-only":return"Uses prompt overlays only; no native reasoning parameter";default:return"Runs without native reasoning parameters"}}o(lr,"describeReasoningExecution");function fr(e){let t=[];e||(e=Se().providerModels);for(let n of Ae())t.push({name:n.name,model:n.model,models:sn(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=ce().map(r=>({...r,models:(()=>{let i=e?.[r.name];return i&&i.length>0?we(i,r.models):r.models})()}));t.push(...n)}catch{}return t}o(fr,"getProviderList");function dr(e){if(Pe(e))return!0;try{return N(e)?.isConfigured()??!1}catch{return!1}}o(dr,"isProviderConfigured");var te=class extends Error{static{o(this,"InvalidAgentModeConfigError")}};function dn(e){let t=e.agentMode;if(t===void 0||t==="ama"||t==="sa")return e;if(t!=="amaw"&&t!=="ama-workflow")throw new te(`Invalid agentMode "${t}" in ${f}. Expected "ama" or "sa".`);let n={...e,agentMode:"ama",schemaVersion:Math.max(e.schemaVersion??0,it)};try{S(f,()=>{let r=Ee();if(!r)return;let i=r.value.agentMode;i!=="amaw"&&i!=="ama-workflow"||ut({...r.value,agentMode:"ama",schemaVersion:Math.max(typeof r.value.schemaVersion=="number"?r.value.schemaVersion:0,it)})})}catch{}return st||(process.emitWarning(`Migrated persisted agentMode "${t}" to "ama". Workflow use is now explicit intent.`,{code:"KODAX_AGENT_MODE_MIGRATED"}),st=!0),n}o(dn,"migrateLegacyAgentModeConfig");function Se(){try{let n=!1;try{g.lstatSync(f),n=!0}catch(r){if(r.code!=="ENOENT")throw r}if(n){let r=JSON.parse(g.readFileSync(f,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid core configuration object.");let i=dn(r),s=i.reasoningCeiling??i.reasoningMode,a=[],c={};try{a=[...Z(l).document.paths]}catch{}try{c=Q(l).document.servers}catch{}let{sandbox:u,...h}=i;return nn(tn({...h,reasoningMode:s,extensions:ye(a),mcpServers:c}))}}catch(n){throw n instanceof te?n:new Error(`Core configuration is unreadable or invalid: ${f}. Repair the retained original before continuing. Use kodax doctor --json for a read-only syntax diagnostic.`)}let e,t;try{let n=Z(l);n.source!=="default"&&(e=ye([...n.document.paths]))}catch{}try{let n=Q(l);n.source!=="default"&&(t=n.document.servers)}catch{}return{...e===void 0?{}:{extensions:e},...t===void 0?{}:{mcpServers:t}}}o(Se,"loadConfig");var pn=m.join(l,"config.example.jsonc"),he={mcp:m.join(l,"integrations","mcp.example.jsonc"),a2a:m.join(l,"integrations","a2a.example.jsonc"),extensions:m.join(l,"integrations","extensions.example.jsonc")},mn=[{name:"core",path:pn},{name:"mcp",path:he.mcp},{name:"a2a",path:he.a2a},{name:"extensions",path:he.extensions}];function gn(){let e=[];for(let t of mn)try{if(g.existsSync(t.path))continue;g.mkdirSync(m.dirname(t.path),{recursive:!0}),g.writeFileSync(t.path,Ue(t.name),"utf8"),e.push(t.path)}catch{}return e}o(gn,"ensureExampleConfigFiles");function pr(){return gn()[0]}o(pr,"ensureExampleConfigFile");var U=new Map;function mr(e){let t=process.env[e];return t===void 0?"unset":U.get(e)===t?"persisted":"environment"}o(mr,"inspectConfigEnvironmentSource");function ft(e,t,n=!1){let r=process.env[e],i=U.get(e),s=i!==void 0&&r===i;if(r!==void 0&&!s&&!n){U.delete(e);return}if(t===void 0){(s||n)&&delete process.env[e],U.delete(e);return}process.env[e]=t,U.set(e,t)}o(ft,"projectConfigEnvironment");var be=[{configPath:"streamIdleTimeoutMs",env:"KODAX_STREAM_IDLE_TIMEOUT_MS",value:o(e=>b(e.streamIdleTimeoutMs),"value")},{configPath:"repoIntelligenceMode",env:"KODAX_REPO_INTELLIGENCE",value:o(e=>e.repoIntelligenceMode,"value")},{configPath:"repoIntelligenceTrace",env:"KODAX_REPO_INTELLIGENCE_TRACE",value:o(e=>K(e.repoIntelligenceTrace),"value")},{configPath:"stallLog",env:"KODAX_STALL_LOG",value:o(e=>K(e.stallLog),"value")},{configPath:"fallbackProviders",env:"KODAX_FALLBACK_PROVIDERS",value:o(e=>vn(e.fallbackProviders),"value")},{configPath:"fastProvider",env:"KODAX_FAST_PROVIDER",value:o(e=>w(e.fastProvider),"value")},{configPath:"fastModel",env:"KODAX_FAST_MODEL",value:o(e=>w(e.fastModel),"value")},{configPath:"deepProvider",env:"KODAX_DEEP_PROVIDER",value:o(e=>w(e.deepProvider),"value")},{configPath:"deepModel",env:"KODAX_DEEP_MODEL",value:o(e=>w(e.deepModel),"value")},{configPath:"provider",env:"KODAX_PROVIDER",value:o(e=>w(e.provider),"value")},{configPath:"effort",env:"KODAX_EFFORT",value:o(e=>w(e.effort),"value")},{configPath:"sessionRetentionDays",env:"KODAX_SESSION_RETENTION_DAYS",value:o(e=>b(e.sessionRetentionDays),"value")},{configPath:"maxOutputTokens",env:"KODAX_MAX_OUTPUT_TOKENS",value:o(e=>b(e.maxOutputTokens),"value")},{configPath:"disablePromptCache",env:"KODAX_DISABLE_PROMPT_CACHE",value:o(e=>K(e.disablePromptCache),"value")},{configPath:"lsp",env:"KODAX_LSP",value:o(e=>K(e.lsp),"value")},{configPath:"lspAutoDownload",env:"KODAX_LSP_DOWNLOAD",value:o(e=>K(e.lspAutoDownload),"value")},{configPath:"acpLogLevel",env:"KODAX_ACP_LOG",value:o(e=>w(e.acpLogLevel),"value")},{configPath:"repoIntelligence.toolWaitMs",env:"KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS",value:o(e=>b(e.repoIntelligence?.toolWaitMs),"value")},{configPath:"repoIntelligence.workerTimeoutMs",env:"KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS",value:o(e=>b(e.repoIntelligence?.workerTimeoutMs),"value")},{configPath:"repoIntelligence.workerOldSpaceMb",env:"KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB",value:o(e=>b(e.repoIntelligence?.workerOldSpaceMb),"value")},{configPath:"repoIntelligence.storageDir",env:"KODAX_REPO_INTELLIGENCE_STORAGE_DIR",value:o(e=>w(e.repoIntelligence?.storageDir),"value")},{configPath:"workflow.maxConcurrency",env:"KODAX_WORKFLOW_MAX_CONCURRENCY",value:o(e=>b(e.workflow?.maxConcurrency),"value")}];function hn(e){for(let t of be)ft(t.env,t.value(e))}o(hn,"applyConfigSurfaceBridges");function w(e){return e?.trim()||void 0}o(w,"normalizedConfigString");function b(e){return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}o(b,"configNumberString");function K(e){return e===void 0?void 0:e?"1":"0"}o(K,"configBooleanString");function vn(e){return e?.filter(t=>t.trim().length>0).join(",")}o(vn,"configStringList");var gr=[...be.map(({configPath:e,env:t})=>({configPath:e,env:t}))];function yn(e){hn(e)}o(yn,"applyConfigEnvironment");function hr(e,t=!1){for(let n of be)["fallbackProviders","stallLog"].includes(n.configPath)&&(t&&!Object.hasOwn(e,n.configPath)||ft(n.env,n.value(e),t))}o(hr,"applyExecutionConfigEnvironment");function vr(){Zt();let e=Se();return yn(e),en(e),je(e.locale),e}o(vr,"prepareRuntimeConfig");function yr(e){let{extensions:t,mcpServers:n,...r}=e;if(S(f,()=>{let i={};if(g.existsSync(f)){let a=g.readFileSync(f,"utf8"),c;try{c=JSON.parse(a)}catch{throw new Error("Core configuration is unreadable; retain and repair the original before saving.")}if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Invalid core configuration; retain and repair the original before saving.");i=c}let s={...i,...r};for(let a of Object.keys(r))r[a]===void 0&&delete s[a];P(f,JSON.stringify(s,null,2))}),t!==void 0){let i=Z(l);F({domain:"extensions",configHome:l,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,paths:ye(t)??[]},validate:I})}if(n!==void 0){let i=Q(l);F({domain:"mcp",configHome:l,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,servers:n},validate:A})}}o(yr,"saveConfig");function wr(e,t,n){return e.effort!==void 0||ie(n).kind==="value"||t.effort!==void 0}o(wr,"resolveInitialEffortOverride");function E(e){return e?.trim()?e:void 0}o(E,"nonEmptySelection");function Er(e){return E(e.explicitProvider)??E(e.environmentProvider)??E(e.configuredProvider)??e.defaultProvider}o(Er,"resolveRuntimeProviderSelection");function Sr(e){let t=E(e.explicitModel);if(t)return t;let n=E(e.configuredModel);if(!n)return;let r=E(e.explicitProvider)??E(e.environmentProvider);return r?E(e.configuredProvider)===r?n:void 0:n}o(Sr,"resolveRuntimeModelSelection");function br(e){if(e.explicitEffort!==void 0)return oe(e.explicitEffort);let t=ie(e.environmentEffort);return t.kind==="value"?t.value:e.configuredEffort===void 0?void 0:oe(e.configuredEffort)}o(br,"resolveRuntimeEffortSelection");function wn(e){return e.permissionMode==="plan"&&e.effortOverride!==!0&&e.planModeEffort!==void 0?e.planModeEffort:e.effort}o(wn,"resolvePermissionModeEffort");async function Cr(e){try{await Le({cwd:e});let{stdout:t}=await Jt("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0});return t.trim()}catch{return null}}o(Cr,"getGitRoot");function En(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}o(En,"formatProviderSourceKind");function xr(e){let t=e.transport==="cli-bridge"?"CLI bridge":"Native API",n=e.conversationSemantics==="last-user-message"?"latest-user-message only":"full conversation history";return[`Source: ${En(e.sourceKind)}`,`Transport: ${t}`,`Conversation semantics: ${n}`,`Context fidelity: ${e.contextFidelity}`,`Tool calling: ${e.toolCallingFidelity}`,`Session behavior: ${e.sessionSupport}`,`Long-running support: ${e.longRunningSupport}`,`Evidence-heavy flows: ${e.evidenceSupport}`,`Multimodal support: ${e.multimodalSupport}`,`MCP support: ${e.mcpSupport}`,`Reasoning control: ${fn(e.reasoningCapability)}`]}o(xr,"formatProviderCapabilityDetailLines");function Pr(e,t,n){return[{label:"General coding",hints:{}},{label:"Evidence-heavy review",hints:{evidenceHeavy:!0}},{label:"Long-running task",hints:{longRunning:!0}}].map(i=>({label:i.label,decision:un(e,t,n,i.hints)})).filter(i=>i.decision!==null)}o(Pr,"getProviderCommonPolicyScenarios");var at=.5,ct=0,X={locked:!1,queue:[]};async function _r(e){for(;X.locked;)await new Promise(t=>X.queue.push(t));X.locked=!0;try{let t=(Date.now()-ct)/1e3;t<at&&await new Promise(r=>setTimeout(r,(at-t)*1e3));let n=await e();return ct=Date.now(),n}finally{X.locked=!1;let t=X.queue.shift();t&&t()}}o(_r,"rateLimitedCall");export{Sn as a,Xe as b,Ue as c,H as d,j as e,Je as f,ze as g,P as h,fe as i,Pt as j,S as k,M as l,A as m,I as n,R as o,Q as p,Z as q,Ft as r,jn as s,F as t,et as u,l as v,Zn as w,f as x,er as y,Qt as z,tr as A,en as B,rn as C,nr as D,on as E,sn as F,an as G,cn as H,rr as I,un as J,or as K,ir as L,L as M,sr as N,ar as O,cr as P,ur as Q,fn as R,lr as S,fr as T,dr as U,Se as V,pn as W,he as X,gn as Y,pr as Z,mr as _,gr as $,yn as aa,hr as ba,vr as ca,yr as da,wr as ea,Er as fa,Sr as ga,br as ha,wn as ia,Cr as ja,En as ka,xr as la,Pr as ma,_r as na};
|
|
4
|
+
`,a=`${t}.${process.pid}.${Date.now()}.tmp`,c=At(a,"wx",384);try{Dt(c,s,"utf8"),Mt(c)}finally{_t(c)}try{e.expectedRevision===null?(Ot(a,t),Be(a)):It(a,t)}catch(u){throw p(a)&&Be(a),e.expectedRevision===null&&p(t)?new M(t,void 0,Qe(t)):new Error(`Failed to atomically replace ${d.basename(t)}.`,{cause:u})}return k({domain:e.domain,source:"user",path:t,raw:s,document:n})})}o(F,"writeIntegrationDocument");function Gt(e){if(!p(e))return"missing";let t=Rt(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}o(Gt,"metadataSignature");function Ze(e){return e.map(t=>`${t}:${Gt(t)}`).join("|")}o(Ze,"observationSignature");function z(e,t){return{code:e,message:t,time:new Date().toISOString()}}o(z,"safeDiagnostic");var et=class{static{o(this,"IntegrationConfigController")}#f;#n;#o;#a;#m;#d;#p;#e;#t;#c;#u;#g="";#s=[];#r;#i;#h=Promise.resolve();#l=new Set;constructor(t){this.#f=t.domain,this.#n=R(t.domain,t.configHome),this.#o=t.fallbackPath===void 0?void 0:d.resolve(t.fallbackPath),this.#a=this.#o===void 0?[this.#n]:[this.#n,this.#o],this.#d=t.validate,this.#m=t.read,this.#p=t.coldStartDefault===void 0?void 0:structuredClone(this.#d(t.coldStartDefault))}async initialize(){let t=await this.reload();if(!t.ok&&!this.#e&&this.#p!==void 0){let n=structuredClone(this.#p);this.#e=k({domain:this.#f,source:"default",path:this.#n,raw:JSON.stringify(n),document:n})}if(!this.#e)throw new Error(t.ok?"Integration configuration did not produce a snapshot.":t.error);return structuredClone(this.#e)}snapshot(){return this.#e?structuredClone(this.#e):void 0}status(){let t=this.#t?this.#c:void 0,n=this.#t?this.#u:void 0;return{domain:this.#f,path:t??this.#e?.path??this.#n,...this.#e?{revision:this.#e.revision,lastReloadAt:this.#e.loadedAt}:{},...n??this.#e?.source?{source:n??this.#e?.source}:{},...this.#t?{diagnostic:this.#t}:{},watching:this.#s.length>0}}subscribe(t){return this.#l.add(t),()=>{this.#l.delete(t)}}reload(){let t=this.#h.then(()=>this.#v());return this.#h=t.then(()=>{},()=>{}),t}async#v(){this.#g=Ze(this.#a);let t;try{t=this.#m(),this.#d(t.document)}catch{let r=this.#y();return this.#c=r.path,this.#u=r.source,this.#t=z("invalid-config","Integration configuration is invalid; check the file against its versioned schema."),{ok:!1,error:this.#t.message}}let n=this.#e?structuredClone(this.#e):void 0;try{for(let r of this.#l)await r(structuredClone(t),n)}catch{return this.#c=t.path,this.#u=t.source,this.#t=z("activation-failed","Integration configuration could not be activated; the previous configuration remains active."),{ok:!1,error:this.#t.message}}return this.#e=t,this.#t=void 0,this.#c=void 0,this.#u=void 0,{ok:!0,snapshot:structuredClone(t)}}async ensureCurrent(){return Ze(this.#a)===this.#g&&this.#e?{ok:!0,snapshot:structuredClone(this.#e)}:this.reload()}startWatching(t=100,n=2e3){if(this.#s.length>0||this.#i)return;ge(d.dirname(this.#n),{recursive:!0,mode:448});let r=new Map;for(let i of this.#a){let s=d.dirname(i),a=r.get(s)??new Set;a.add(d.basename(i)),r.set(s,a)}for(let[i,s]of r)try{let a=kt(i,(c,u)=>{u!==null&&!s.has(u.toString())||(this.#r&&clearTimeout(this.#r),this.#r=setTimeout(()=>{this.#r=void 0,this.reload()},t),this.#r.unref?.())});a.unref(),a.on("error",()=>{this.#t=z("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}),this.#s.push(a)}catch{this.#t=z("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}this.#i=setInterval(()=>{this.ensureCurrent()},n),this.#i.unref?.()}close(){this.#r&&clearTimeout(this.#r),this.#r=void 0,this.#i&&clearInterval(this.#i),this.#i=void 0;for(let t of this.#s)t.close();this.#s.length=0,this.#l.clear()}#y(){return p(this.#n)?{path:this.#n,source:"user"}:this.#o&&p(this.#o)?{path:this.#o,source:"legacy-user"}:{path:this.#n,source:"default"}}};var Jt=Ht(Vt),it=2,st=!1,l=Ce(),Zn=m.join(l,"sessions"),f=m.join(l,"config.json"),er=60,y=null,ve=!1,zt="dumb";function Bt(e){let t=m.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",r=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",r],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",r]:["-lc",r],sentinel:n}}o(Bt,"buildShellEnvCommand");function Yt(e,t){let n=`${t}\0`,r=e.lastIndexOf(n);if(r===-1)return{};let i=e.slice(r+n.length),s={};for(let a of i.split("\0")){if(!a)continue;let c=a.indexOf("=");c<=0||(s[a.slice(0,c)]=a.slice(c+1))}return s}o(Yt,"parseNullDelimitedShellEnv");function Qt(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let r=e.shell??t.SHELL;if(!r||!m.isAbsolute(r))return!1;let{args:i,sentinel:s}=Bt(r),a=e.run??Wt,c={...t,TERM:zt},u=a(r,i,{encoding:"utf8",env:c,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(u.status!==0||!u.stdout)return!1;let h=typeof u.stdout=="string"?u.stdout:u.stdout.toString("utf8"),G=Yt(h,s),V=!1;for(let[re,dt]of Object.entries(G))re!=="TERM"&&t[re]===void 0&&(t[re]=dt,V=!0);return V}o(Qt,"hydrateProcessEnvFromShell");function Zt(){if(!ve){ve=!0;try{Qt()}catch{}}}o(Zt,"ensureShellEnvironmentHydrated");function tr(){ve=!1}o(tr,"resetShellEnvironmentHydrationForTesting");function en(e){Re(e.customProviders??[])}o(en,"registerConfiguredCustomProviders");function ye(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:[]}o(ye,"normalizeConfiguredExtensions");function Ee(){let e=g.readFileSync(f,"utf8"),t=JSON.parse(e);if(!(t===null||typeof t!="object"||Array.isArray(t)))return{raw:e,value:t}}o(Ee,"readPersistedCoreConfig");function ut(e){P(f,JSON.stringify(e,null,2))}o(ut,"writePersistedCoreConfig");function tn(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{S(f,()=>{let n=Ee();n?.value.permissionMode==="default"&&ut({...n.value,permissionMode:"accept-edits"})})}catch{}return t}o(tn,"migrateLegacyPermissionModeInConfig");function nn(e){if(e.permissionMode!=="auto-in-project")return e;try{S(f,()=>{let t=Ee();if(t?.value.permissionMode!=="auto-in-project")return;let n=t.raw.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t.raw&&P(f,n)})}catch{}return{...e,permissionMode:"auto"}}o(nn,"migrateAutoInProjectAliasInConfig");function rn(){if(y)return y;let e="0.7.97-beta.2";if(e)return y=e,y;let t=m.join(m.dirname(qt(import.meta.url)),"../../package.json");if(g.existsSync(t))try{return y=JSON.parse(g.readFileSync(t,"utf-8")).version??"0.0.0",y??"0.0.0"}catch{}return y="0.0.0",y}o(rn,"getVersion");var nr=rn();function on(e){return Me(e)}o(on,"getProviderModel");function we(e,t){let n=new Set(e.map(i=>i.toLowerCase())),r=[...e];for(let i of t)n.has(i.toLowerCase())||r.push(i);return r}o(we,"mergeModels");function sn(e,t){t||(t=Se().providerModels);let n=t?.[e];if(n&&n.length>0){try{let r=ae(e);if(r.length>0)return we(n,r)}catch{}try{let r=N(e);if(r)return we(n,r.getAvailableModels())}catch{}return n}try{let r=ae(e);if(r.length>0)return r}catch{}try{let r=N(e);if(r)return r.getAvailableModels()}catch{}return[]}o(sn,"getProviderAvailableModels");function an(e,t){let n=Oe(e,t);if(n!=="unknown")return n;try{let r=N(e);if(r)return r.getReasoningCapability(t)}catch{}return"unknown"}o(an,"getProviderReasoningCapability");function cn(e){let t=Ae(e);if(t)return t;try{return ce().find(r=>r.name===e)?.capabilityProfile??null}catch{return null}}o(cn,"getProviderCapabilityProfile");function lt(e,t){let n=cn(e),r=an(e,t);if(n)return{capabilityProfile:n,reasoningCapability:r};try{let i=ue(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}o(lt,"getProviderCapabilityMetadata");function rr(e,t){let n=lt(e,t);return n?Ne({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}o(rr,"getProviderCapabilitySnapshot");function un(e,t,n,r){let i=lt(e,t);return i?Te({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:r}):null}o(un,"getProviderPolicyDecision");function or(e){let t=e.transport==="cli-bridge"?"CLI bridge":"Native API",n=e.conversationSemantics==="last-user-message"?"forwards only the latest user message":"preserves full conversation history",r=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${r}`}o(or,"describeProviderCapabilitySummary");function ir(e){switch(e){case"native-budget":return"B";case"native-effort":return"E";case"native-toggle":return"T";case"native-adaptive":return"A";default:return"-"}}o(ir,"formatReasoningCapabilityShort");function L(e){if(e)return e==="none"?"off":e}o(L,"formatReasoningEffortForDisplay");function ee(e,t){let n=L(t);n&&!e.includes(n)&&e.push(n)}o(ee,"pushUniqueEffortDisplay");function sr(e,t,n){let r=["auto"],i=ne(e,t,n),s=i?.supportedEfforts?.filter(a=>a.isUserVisible!==!1);if(!s||s.length===0){for(let a of["off","low","medium","high"])ee(r,a);return r}for(let a of s)a.value==="none"&&i?.supportsDisabledThinking===!1||ee(r,a.value);return r}o(sr,"getProviderReasoningEffortOptions");function ar(e,t){let n=ne(e,t),r=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(u=>u.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let u of["low","medium","high"])ee(s,u);a=!0}else for(let u of i){if(u.value==="none"){n?.supportsDisabledThinking!==!1&&(a=!0);continue}if(r.has(u.value)){n?.supportsDisabledThinking!==!1&&(a=!0);continue}ee(s,u.value)}let c=[];return a&&c.push("off"),c.push(...s),c.push("auto"),c}o(ar,"getProviderReasoningEffortCycle");function ln(e,t){if(t===!1)return"off";switch(e){case"off":return"off";case"quick":return"low";case"balanced":return"medium";case"deep":return"high";default:return"auto"}}o(ln,"legacyReasoningModeToEffortDisplay");function ne(e,t,n){let r=t??on(e);if(!r)return;let i=ke(e,r)?.reasoningProfile;if(i)return ue(e).usesScopedReasoningLearning?.()?i:Pe(i,De(e,r,n))}o(ne,"resolveReasoningProfileForDisplay");function cr(e){let t=L(e.effort)??ln(e.reasoningMode,e.thinking),n=ne(e.provider,e.model);if(!n)return t;try{let r=xe({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=L(r.configuredEffort)??t,a=r.configuredEffort!==void 0&&n.supportsDisabledThinking!==!1&&n.disabledEfforts?.includes(r.configuredEffort)===!0?"off":L(r.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let r=se({currentEffort:e.effort,capability:n}),i=L(e.effort)??t,s=L(r.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}o(cr,"formatReasoningEffortStatusLabel");function ur(e){let t=wn(e);if(!t)return{preserved:!0};let n=ne(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let r=se({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:r.effectiveEffort,preserved:r.preserved,diagnostic:r.diagnostic}}o(ur,"resolveProviderReasoningRuntimeEffort");function fn(e){switch(e){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";case"native-adaptive":return"adaptive";default:return"none"}}o(fn,"describeReasoningCapabilityControl");function lr(e,t){if(e==="off")return"Reasoning disabled";switch(t){case"native-budget":return"Uses native thinking budget control";case"native-effort":return"Uses native reasoning effort control";case"native-toggle":return"Uses provider-native thinking toggle only";case"native-adaptive":return"Model adaptively decides thinking depth (Opus 4.7+)";case"none":return"Runs without native reasoning parameters";case"prompt-only":return"Uses prompt overlays only; no native reasoning parameter";default:return"Runs without native reasoning parameters"}}o(lr,"describeReasoningExecution");function fr(e){let t=[];e||(e=Se().providerModels);for(let n of Ie())t.push({name:n.name,model:n.model,models:sn(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=ce().map(r=>({...r,models:(()=>{let i=e?.[r.name];return i&&i.length>0?we(i,r.models):r.models})()}));t.push(...n)}catch{}return t}o(fr,"getProviderList");function dr(e){if(_e(e))return!0;try{return N(e)?.isConfigured()??!1}catch{return!1}}o(dr,"isProviderConfigured");var te=class extends Error{static{o(this,"InvalidAgentModeConfigError")}};function dn(e){let t=e.agentMode;if(t===void 0||t==="ama"||t==="sa")return e;if(t!=="amaw"&&t!=="ama-workflow")throw new te(`Invalid agentMode "${t}" in ${f}. Expected "ama" or "sa".`);let n={...e,agentMode:"ama",schemaVersion:Math.max(e.schemaVersion??0,it)};try{S(f,()=>{let r=Ee();if(!r)return;let i=r.value.agentMode;i!=="amaw"&&i!=="ama-workflow"||ut({...r.value,agentMode:"ama",schemaVersion:Math.max(typeof r.value.schemaVersion=="number"?r.value.schemaVersion:0,it)})})}catch{}return st||(process.emitWarning(`Migrated persisted agentMode "${t}" to "ama". Workflow use is now explicit intent.`,{code:"KODAX_AGENT_MODE_MIGRATED"}),st=!0),n}o(dn,"migrateLegacyAgentModeConfig");function Se(){try{let n=!1;try{g.lstatSync(f),n=!0}catch(r){if(r.code!=="ENOENT")throw r}if(n){let r=JSON.parse(g.readFileSync(f,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid core configuration object.");let i=dn(r),s=i.reasoningCeiling??i.reasoningMode,a=[],c={};try{a=[...Z(l).document.paths]}catch{}try{c=Q(l).document.servers}catch{}let{sandbox:u,...h}=i;return nn(tn({...h,reasoningMode:s,extensions:ye(a),mcpServers:c}))}}catch(n){throw n instanceof te?n:new Error(`Core configuration is unreadable or invalid: ${f}. Repair the retained original before continuing. Use kodax doctor --json for a read-only syntax diagnostic.`)}let e,t;try{let n=Z(l);n.source!=="default"&&(e=ye([...n.document.paths]))}catch{}try{let n=Q(l);n.source!=="default"&&(t=n.document.servers)}catch{}return{...e===void 0?{}:{extensions:e},...t===void 0?{}:{mcpServers:t}}}o(Se,"loadConfig");var pn=m.join(l,"config.example.jsonc"),he={mcp:m.join(l,"integrations","mcp.example.jsonc"),a2a:m.join(l,"integrations","a2a.example.jsonc"),extensions:m.join(l,"integrations","extensions.example.jsonc")},mn=[{name:"core",path:pn},{name:"mcp",path:he.mcp},{name:"a2a",path:he.a2a},{name:"extensions",path:he.extensions}];function gn(){let e=[];for(let t of mn)try{if(g.existsSync(t.path))continue;g.mkdirSync(m.dirname(t.path),{recursive:!0}),g.writeFileSync(t.path,Ue(t.name),"utf8"),e.push(t.path)}catch{}return e}o(gn,"ensureExampleConfigFiles");function pr(){return gn()[0]}o(pr,"ensureExampleConfigFile");var U=new Map;function mr(e){let t=process.env[e];return t===void 0?"unset":U.get(e)===t?"persisted":"environment"}o(mr,"inspectConfigEnvironmentSource");function ft(e,t,n=!1){let r=process.env[e],i=U.get(e),s=i!==void 0&&r===i;if(r!==void 0&&!s&&!n){U.delete(e);return}if(t===void 0){(s||n)&&delete process.env[e],U.delete(e);return}process.env[e]=t,U.set(e,t)}o(ft,"projectConfigEnvironment");var be=[{configPath:"streamIdleTimeoutMs",env:"KODAX_STREAM_IDLE_TIMEOUT_MS",value:o(e=>b(e.streamIdleTimeoutMs),"value")},{configPath:"repoIntelligenceMode",env:"KODAX_REPO_INTELLIGENCE",value:o(e=>e.repoIntelligenceMode,"value")},{configPath:"repoIntelligenceTrace",env:"KODAX_REPO_INTELLIGENCE_TRACE",value:o(e=>K(e.repoIntelligenceTrace),"value")},{configPath:"stallLog",env:"KODAX_STALL_LOG",value:o(e=>K(e.stallLog),"value")},{configPath:"fallbackProviders",env:"KODAX_FALLBACK_PROVIDERS",value:o(e=>vn(e.fallbackProviders),"value")},{configPath:"fastProvider",env:"KODAX_FAST_PROVIDER",value:o(e=>w(e.fastProvider),"value")},{configPath:"fastModel",env:"KODAX_FAST_MODEL",value:o(e=>w(e.fastModel),"value")},{configPath:"deepProvider",env:"KODAX_DEEP_PROVIDER",value:o(e=>w(e.deepProvider),"value")},{configPath:"deepModel",env:"KODAX_DEEP_MODEL",value:o(e=>w(e.deepModel),"value")},{configPath:"provider",env:"KODAX_PROVIDER",value:o(e=>w(e.provider),"value")},{configPath:"effort",env:"KODAX_EFFORT",value:o(e=>w(e.effort),"value")},{configPath:"sessionRetentionDays",env:"KODAX_SESSION_RETENTION_DAYS",value:o(e=>b(e.sessionRetentionDays),"value")},{configPath:"maxOutputTokens",env:"KODAX_MAX_OUTPUT_TOKENS",value:o(e=>b(e.maxOutputTokens),"value")},{configPath:"disablePromptCache",env:"KODAX_DISABLE_PROMPT_CACHE",value:o(e=>K(e.disablePromptCache),"value")},{configPath:"lsp",env:"KODAX_LSP",value:o(e=>K(e.lsp),"value")},{configPath:"lspAutoDownload",env:"KODAX_LSP_DOWNLOAD",value:o(e=>K(e.lspAutoDownload),"value")},{configPath:"acpLogLevel",env:"KODAX_ACP_LOG",value:o(e=>w(e.acpLogLevel),"value")},{configPath:"repoIntelligence.toolWaitMs",env:"KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS",value:o(e=>b(e.repoIntelligence?.toolWaitMs),"value")},{configPath:"repoIntelligence.workerTimeoutMs",env:"KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS",value:o(e=>b(e.repoIntelligence?.workerTimeoutMs),"value")},{configPath:"repoIntelligence.workerOldSpaceMb",env:"KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB",value:o(e=>b(e.repoIntelligence?.workerOldSpaceMb),"value")},{configPath:"repoIntelligence.storageDir",env:"KODAX_REPO_INTELLIGENCE_STORAGE_DIR",value:o(e=>w(e.repoIntelligence?.storageDir),"value")},{configPath:"workflow.maxConcurrency",env:"KODAX_WORKFLOW_MAX_CONCURRENCY",value:o(e=>b(e.workflow?.maxConcurrency),"value")}];function hn(e){for(let t of be)ft(t.env,t.value(e))}o(hn,"applyConfigSurfaceBridges");function w(e){return e?.trim()||void 0}o(w,"normalizedConfigString");function b(e){return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}o(b,"configNumberString");function K(e){return e===void 0?void 0:e?"1":"0"}o(K,"configBooleanString");function vn(e){return e?.filter(t=>t.trim().length>0).join(",")}o(vn,"configStringList");var gr=[...be.map(({configPath:e,env:t})=>({configPath:e,env:t}))];function yn(e){hn(e)}o(yn,"applyConfigEnvironment");function hr(e,t=!1){for(let n of be)["fallbackProviders","stallLog"].includes(n.configPath)&&(t&&!Object.hasOwn(e,n.configPath)||ft(n.env,n.value(e),t))}o(hr,"applyExecutionConfigEnvironment");function vr(){Zt();let e=Se();return yn(e),en(e),je(e.locale),e}o(vr,"prepareRuntimeConfig");function yr(e){let{extensions:t,mcpServers:n,...r}=e;if(S(f,()=>{let i={};if(g.existsSync(f)){let a=g.readFileSync(f,"utf8"),c;try{c=JSON.parse(a)}catch{throw new Error("Core configuration is unreadable; retain and repair the original before saving.")}if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Invalid core configuration; retain and repair the original before saving.");i=c}let s={...i,...r};for(let a of Object.keys(r))r[a]===void 0&&delete s[a];P(f,JSON.stringify(s,null,2))}),t!==void 0){let i=Z(l);F({domain:"extensions",configHome:l,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,paths:ye(t)??[]},validate:I})}if(n!==void 0){let i=Q(l);F({domain:"mcp",configHome:l,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,servers:n},validate:A})}}o(yr,"saveConfig");function wr(e,t,n){return e.effort!==void 0||ie(n).kind==="value"||t.effort!==void 0}o(wr,"resolveInitialEffortOverride");function E(e){return e?.trim()?e:void 0}o(E,"nonEmptySelection");function Er(e){return E(e.explicitProvider)??E(e.environmentProvider)??E(e.configuredProvider)??e.defaultProvider}o(Er,"resolveRuntimeProviderSelection");function Sr(e){let t=E(e.explicitModel);if(t)return t;let n=E(e.configuredModel);if(!n)return;let r=E(e.explicitProvider)??E(e.environmentProvider);return r?E(e.configuredProvider)===r?n:void 0:n}o(Sr,"resolveRuntimeModelSelection");function br(e){if(e.explicitEffort!==void 0)return oe(e.explicitEffort);let t=ie(e.environmentEffort);return t.kind==="value"?t.value:e.configuredEffort===void 0?void 0:oe(e.configuredEffort)}o(br,"resolveRuntimeEffortSelection");function wn(e){return e.permissionMode==="plan"&&e.effortOverride!==!0&&e.planModeEffort!==void 0?e.planModeEffort:e.effort}o(wn,"resolvePermissionModeEffort");async function Cr(e){try{await Le({cwd:e});let{stdout:t}=await Jt("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0});return t.trim()}catch{return null}}o(Cr,"getGitRoot");function En(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}o(En,"formatProviderSourceKind");function xr(e){let t=e.transport==="cli-bridge"?"CLI bridge":"Native API",n=e.conversationSemantics==="last-user-message"?"latest-user-message only":"full conversation history";return[`Source: ${En(e.sourceKind)}`,`Transport: ${t}`,`Conversation semantics: ${n}`,`Context fidelity: ${e.contextFidelity}`,`Tool calling: ${e.toolCallingFidelity}`,`Session behavior: ${e.sessionSupport}`,`Long-running support: ${e.longRunningSupport}`,`Evidence-heavy flows: ${e.evidenceSupport}`,`Multimodal support: ${e.multimodalSupport}`,`MCP support: ${e.mcpSupport}`,`Reasoning control: ${fn(e.reasoningCapability)}`]}o(xr,"formatProviderCapabilityDetailLines");function Pr(e,t,n){return[{label:"General coding",hints:{}},{label:"Evidence-heavy review",hints:{evidenceHeavy:!0}},{label:"Long-running task",hints:{longRunning:!0}}].map(i=>({label:i.label,decision:un(e,t,n,i.hints)})).filter(i=>i.decision!==null)}o(Pr,"getProviderCommonPolicyScenarios");var at=.5,ct=0,X={locked:!1,queue:[]};async function _r(e){for(;X.locked;)await new Promise(t=>X.queue.push(t));X.locked=!0;try{let t=(Date.now()-ct)/1e3;t<at&&await new Promise(r=>setTimeout(r,(at-t)*1e3));let n=await e();return ct=Date.now(),n}finally{X.locked=!1;let t=X.queue.shift();t&&t()}}o(_r,"rateLimitedCall");export{Sn as a,Xe as b,Ue as c,H as d,j as e,Je as f,ze as g,P as h,fe as i,Pt as j,S as k,M as l,A as m,I as n,R as o,Q as p,Z as q,Ft as r,jn as s,F as t,et as u,l as v,Zn as w,f as x,er as y,Qt as z,tr as A,en as B,rn as C,nr as D,on as E,sn as F,an as G,cn as H,rr as I,un as J,or as K,ir as L,L as M,sr as N,ar as O,cr as P,ur as Q,fn as R,lr as S,fr as T,dr as U,Se as V,pn as W,he as X,gn as Y,pr as Z,mr as _,gr as $,yn as aa,hr as ba,vr as ca,yr as da,wr as ea,Er as fa,Sr as ga,br as ha,wn as ia,Cr as ja,En as ka,xr as la,Pr as ma,_r as na};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
+
import{f as Ee}from"./chunk-ISLK6R2P.js";import{Aa as ue,Ba as le,Ec as U,Fa as B,Fc as xe,Ga as fe,Gc as ge,Id as G,Jd as he,Ma as k,Mb as Te,Sa as me,Td as M,Ud as H,a as F,b as de,ke as q,p as ce,q as v,vc as K,wc as pe,xa as P,xc as j,ya as I,za as W}from"./chunk-OGTRDK4Q.js";import{c as ae}from"./chunk-GZUWQZJD.js";import{a as ne}from"./chunk-65652LR4.js";import{r as y,wa as re,xa as ie}from"./chunk-2HH5AS7E.js";import{h as D}from"./chunk-J2L2NK6E.js";import{b as se}from"./chunk-KDSO7V4O.js";import{a as i}from"./chunk-V4WSBIXB.js";import X from"node:path";function S(e){let t=k(e);return/^\[(?:Tool Error|Cancelled|Blocked|Error)\]/.test(t)||ye(t)!==void 0}i(S,"isToolResultErrorContent");function V(e){return k(e).startsWith(ce)}i(V,"isCancelledToolResultContent");function ke(e){let t=k(e).trim();return/^\[Tool Error\]\s+[^:]+:\s+([A-Z_]+):/.exec(t)?.[1]??ye(t)}i(ke,"extractStructuredToolErrorCode");function ye(e){if(!e.trimStart().startsWith("{"))return;let t;try{t=JSON.parse(e)}catch{return}if(!(t===null||typeof t!="object")){if("ok"in t&&t.ok===!1&&"reason"in t&&typeof t.reason=="string"&&"code"in t&&typeof t.code=="string"&&["todo_invalid_input","todo_unavailable","todo_hook_veto","todo_state_conflict"].includes(t.code))return t.code;if(!(!("retryable"in t)||t.retryable!==!1||!("denialSource"in t)||!("code"in t))&&["explicit_rule","builtin_fallback","policy_configuration"].includes(String(t.denialSource)))return typeof t.code=="string"&&["exec_policy_forbidden","exec_policy_prompt_unavailable","exec_policy_invalid"].includes(t.code)?t.code:void 0}}i(ye,"structuredJsonErrorCode");function je(e,t,o){if(!Array.isArray(e.outputs))return[];let s=new Set(e.outputs.flatMap(r=>!r||typeof r!="object"||!("target"in r)||typeof r.target!="string"?[]:r.target.trim()?[X.resolve(o,r.target.trim())]:[])),n;try{n=JSON.parse(k(t))}catch{return[]}return!n||typeof n!="object"||!("outputs"in n)||!Array.isArray(n.outputs)?[]:n.outputs.flatMap(r=>{if(typeof r!="string"||!r.trim())return[];let a=X.resolve(o,r);return s.has(a)?[a]:[]})}i(je,"skillOutputPaths");function z(e,t,o,s){if(!e||!t.input||S(o))return;let n=t.name;if(n==="run_skill_script"){for(let a of je(t.input,o,s))e.set(a,{path:a,sourceTool:n});return}if(n!=="write"&&n!=="edit"&&n!=="multi_edit"&&n!=="insert_after_anchor"||typeof t.input.path!="string"||!t.input.path.trim())return;let r=X.resolve(s,t.input.path);e.get(r)?.sourceTool!=="run_skill_script"&&e.set(r,{path:r,sourceTool:n})}i(z,"recordWrittenFile");import{randomUUID as L}from"node:crypto";import{randomUUID as Ie}from"node:crypto";function gt(e,t,o,s){let n=Math.min(o,t.capacity.contextWindow??o),r=t.capacity.inputTokens,a=Math.max(0,t.requestInputReliefTokens);return{currentTokens:t.capacity.inputTokensKind==="exact"&&r!==void 0?r+a:Math.max(n+a,(r??0)+a,Re(e,s)),baselineEstimatedTokens:y(e),source:"estimate",capacityWindow:n}}i(gt,"createOverflowContextTokenSnapshot");function R(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}i(R,"isFiniteNonNegative");function ve(e){return!(!e||!R(e.inputTokens)||!R(e.outputTokens)||!R(e.totalTokens)||e.totalTokens<e.inputTokens||e.totalTokens<e.outputTokens||e.cachedReadTokens!==void 0&&!R(e.cachedReadTokens)||e.cachedWriteTokens!==void 0&&!R(e.cachedWriteTokens)||e.thoughtTokens!==void 0&&!R(e.thoughtTokens))}i(ve,"hasValidTokenUsage");function Se(e){let t=y(e);return{currentTokens:t,baselineEstimatedTokens:t,source:"estimate"}}i(Se,"createEstimatedContextTokenSnapshot");function Ge(e,t){let o=y(e);return{currentTokens:t.inputTokens,baselineEstimatedTokens:o,source:"api",usage:t}}i(Ge,"createApiContextTokenSnapshot");function ht(e,t){return ve(t)?{currentTokens:t.totalTokens,baselineEstimatedTokens:y(e),source:"api",usage:t}:Se(e)}i(ht,"createCompletedTurnTokenSnapshot");function Et(e,t){return ve(t)?Ge(e,t):Se(e)}i(Et,"createContextTokenSnapshot");function Re(e,t){let o=y(e);if(!t||!R(t.currentTokens)||!R(t.baselineEstimatedTokens))return o;let s=t.currentTokens+(o-t.baselineEstimatedTokens);return!Number.isFinite(s)||s<0?o:Math.round(s)}i(Re,"resolveContextTokenCount");function be(e,t){return{currentTokens:Re(e,t),baselineEstimatedTokens:y(e),source:t?.source??"estimate",usage:t?.usage}}i(be,"rebaseContextTokenSnapshot");function kt(e,t){let o=y(e);return{currentTokens:o,baselineEstimatedTokens:o,source:t?.source??"estimate"}}i(kt,"recomputeContextTokenSnapshot");var Me=Symbol("KodaXLiveTurnAttributed"),_e=Symbol("KodaXLiveTurnBaseEvents"),we=16,Ce=new Map,b=new Map;function _t(e){let t=e.turnId??`turn_${Ie().replace(/-/g,"").slice(0,we)}`,o=e.deliveryId??`delivery_${Ie().replace(/-/g,"").slice(0,we)}`,s=e.contextId??e.sessionId,n=e.contextKind??"root";return b.has(s)||b.set(s,0),{sessionId:e.sessionId,turnId:t,contextId:s,contextKind:n,parentContextId:e.parentContextId,agentId:e.agentId,deliveryId:o,deliveryKind:e.deliveryKind??"initial",promptId:e.promptId,ownsContextRevision:e.ownsContextRevision??!0,nextMeta(){let r=(Ce.get(e.sessionId)??0)+1;return Ce.set(e.sessionId,r),{sessionId:e.sessionId,seq:r,turnId:t,deliveryId:o,contextId:s,contextKind:n,...e.parentContextId!==void 0?{parentContextId:e.parentContextId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},contextRevision:b.get(s)??0,timestamp:new Date().toISOString()}},advanceContextRevision(){if(e.ownsContextRevision===!1)return b.get(s)??0;let r=(b.get(s)??0)+1;return b.set(s,r),r}}}i(_t,"createLiveTurnScope");function He(e){return e[Me]===!0}i(He,"isAttributedEvents");function J(e){return"current"in e?e.current:e}i(J,"resolveLiveTurnScope");function f(e,t){let o=t?.contextId===void 0||t.contextKind===void 0||t.contextRevision===void 0?{}:{contextId:t.contextId,contextKind:t.contextKind,parentContextId:t.parentContextId,agentId:t.agentId,contextRevision:t.contextRevision,...t.contextKind==="child"&&t.turnId!==void 0?{turnId:t.turnId,deliveryId:t.deliveryId}:{}};return{...t??{},...J(e).nextMeta(),...o}}i(f,"withActivityMeta");function x(e,t){let o=t,s=o.contextId===void 0||o.contextKind===void 0||o.contextRevision===void 0?{}:{contextId:o.contextId,contextKind:o.contextKind,parentContextId:o.parentContextId,agentId:o.agentId,contextRevision:o.contextRevision,...o.contextKind==="child"&&o.turnId!==void 0?{turnId:o.turnId,deliveryId:o.deliveryId}:{}};return{...t,...J(e).nextMeta(),...s}}i(x,"withLiveMeta");function wt(e,t){let o=He(e)?e[_e]:e,s={...o,onSessionStart:i(n=>{o.onSessionStart?.(x(t,n))},"onSessionStart"),onOutputSegmentStart:i((n,r)=>{o.onOutputSegmentStart?.(n,f(t,r))},"onOutputSegmentStart"),onTextDelta:i((n,r)=>{o.onTextDelta?.(n,f(t,r))},"onTextDelta"),onOutputNotice:i((n,r)=>{o.onOutputNotice?.(n,f(t,r))},"onOutputNotice"),onThinkingDelta:i((n,r)=>{o.onThinkingDelta?.(n,f(t,r))},"onThinkingDelta"),onThinkingEnd:i((n,r)=>{o.onThinkingEnd?.(n,f(t,r))},"onThinkingEnd"),onToolUseStart:i((n,r)=>{o.onToolUseStart?.(n,f(t,r))},"onToolUseStart"),onToolInputDelta:i((n,r,a)=>{o.onToolInputDelta?.(n,r,f(t,a))},"onToolInputDelta"),onToolProgress:i((n,r)=>{o.onToolProgress?.(n,f(t,r))},"onToolProgress"),onToolSandboxObservation:i((n,r)=>{o.onToolSandboxObservation?.(n,f(t,r))},"onToolSandboxObservation"),onToolResult:i((n,r)=>{o.onToolResult?.(n,f(t,r))},"onToolResult"),onToolExecutionStart:i((n,r)=>{o.onToolExecutionStart?.(n,f(t,r))},"onToolExecutionStart"),onToolExecutionEnd:i((n,r)=>{o.onToolExecutionEnd?.(n,f(t,r))},"onToolExecutionEnd"),onChildActivityEnd:i(n=>{o.onChildActivityEnd?.(f(t,n))},"onChildActivityEnd"),onStreamEnd:i(n=>{o.onStreamEnd?.(f(t,n))},"onStreamEnd"),onIterationStart:i((n,r,a)=>{o.onIterationStart?.(n,r,f(t,a))},"onIterationStart"),onIterationEnd:i(n=>{o.onIterationEnd?.(x(t,n))},"onIterationEnd"),onCompactStart:i(n=>{o.onCompactStart?.(f(t,n))},"onCompactStart"),onCompact:i((n,r)=>{o.onCompact?.(n,f(t,r))},"onCompact"),onCompactStats:i(n=>{o.onCompactStats?.(x(t,n))},"onCompactStats"),onCompactedMessages:i(async(n,r,a)=>{let c=J(t),u=c.advanceContextRevision();try{await o.onCompactedMessages?.(n,r,f(t,a))}catch(m){throw c.ownsContextRevision&&b.get(c.contextId)===u&&b.set(c.contextId,u-1),m}},"onCompactedMessages"),onContextCompactionFinished:i(n=>{o.onContextCompactionFinished?.(x(t,n))},"onContextCompactionFinished"),onCompactEnd:i((n,r)=>{o.onCompactEnd?.(f(t,n),r)},"onCompactEnd"),onMidTurnUserMessages:i((n,r)=>{o.onMidTurnUserMessages?.(n,f(t,r))},"onMidTurnUserMessages"),onRetry:i((n,r,a,c)=>{o.onRetry?.(n,r,a,f(t,c))},"onRetry"),onProviderRateLimit:i((n,r,a,c)=>{o.onProviderRateLimit?.(n,r,a,f(t,c))},"onProviderRateLimit"),onRetryAfter:i((n,r)=>{o.onRetryAfter?.(n,f(t,r))},"onRetryAfter"),onProviderRecovery:i((n,r)=>{o.onProviderRecovery?.(n,f(t,r))},"onProviderRecovery"),onReasoningEffortRejected:i(n=>{o.onReasoningEffortRejected?.(x(t,n))},"onReasoningEffortRejected"),onReasoningResolved:i(n=>{o.onReasoningResolved?.(x(t,n))},"onReasoningResolved"),onRepoIntelligenceTrace:i(n=>{o.onRepoIntelligenceTrace?.(x(t,n))},"onRepoIntelligenceTrace"),onContextBudgetSnapshot:i(n=>{o.onContextBudgetSnapshot?.(x(t,n))},"onContextBudgetSnapshot"),onPromptCacheDiagnostics:i(n=>{o.onPromptCacheDiagnostics?.(x(t,n))},"onPromptCacheDiagnostics"),onToolExposurePlanned:i(n=>{o.onToolExposurePlanned?.(x(t,n))},"onToolExposurePlanned"),onContextCompactionSkipped:i(n=>{o.onContextCompactionSkipped?.(x(t,n))},"onContextCompactionSkipped"),onTodoUpdate:i((n,r)=>{o.onTodoUpdate?.(n,f(t,r))},"onTodoUpdate"),onTodoDriftWarning:i(n=>{o.onTodoDriftWarning?.(x(t,n))},"onTodoDriftWarning"),onManagedTaskStatus:i(n=>{o.onManagedTaskStatus?.(x(t,n))},"onManagedTaskStatus"),onEffectiveConfig:i(n=>{o.onEffectiveConfig?.(x(t,n))},"onEffectiveConfig"),onWorkflowProcessEvent:i(n=>{o.onWorkflowProcessEvent?.(x(t,n))},"onWorkflowProcessEvent"),onWorkflowAgentDigest:i(n=>{o.onWorkflowAgentDigest?.(x(t,n))},"onWorkflowAgentDigest"),onScoutSuspiciousCompletion:i(n=>{o.onScoutSuspiciousCompletion?.(x(t,n))},"onScoutSuspiciousCompletion"),onComplete:i(n=>{o.onComplete?.(f(t,n))},"onComplete"),onError:i((n,r)=>{o.onError?.(n,f(t,r))},"onError")};return Object.defineProperty(s,Me,{value:!0,enumerable:!1}),Object.defineProperty(s,_e,{value:o,enumerable:!1}),s}i(wt,"withLiveTurnAttribution");function Ct(e,t){let o={...t.nextMeta(),deliveryKind:t.deliveryKind,...t.promptId!==void 0?{promptId:t.promptId}:{}};e.onTurnStarted?.(o)}i(Ct,"emitTurnStarted");function Mt(e,t,o){e.onTurnCompleted?.({...t.nextMeta(),status:o})}i(Mt,"emitTurnCompleted");function At(e,t,o){let s={...t.nextMeta(),error:{name:o.name,message:o.message,...o.stack!==void 0?{stack:o.stack}:{}}};e.onTurnFailed?.(s)}i(At,"emitTurnFailed");var qe=new Set(["todo_update","todo_list","todo_create","todo_get"]);function A(e){return!Ee(e)&&!qe.has(e)}i(A,"isVisibleToolName");function Ot(e,t){return e.hasPendingInputs?.()===!0?!0:se().has({agentId:t,maxPriority:"user",mode:"prompt"})}i(Ot,"hasQueuedFollowUp");function Lt(e,t){e.onSessionStart?.(t)}i(Lt,"emitSessionStart");function Dt(e,t){t===void 0?e.onStreamEnd?.():e.onStreamEnd?.(t)}i(Dt,"emitStreamEnd");function Pt(e){e.onComplete?.()}i(Pt,"emitComplete");function Bt(e,t){e.onError?.(t)}i(Bt,"emitError");function Kt(e,t,o,s,n){if(n!==void 0){e.onProviderRateLimit?.(t,o,s,n);return}e.onProviderRateLimit?.(t,o,s)}i(Kt,"emitProviderRateLimit");function Ut(e,t,o){e.onIterationStart?.(t+1,o)}i(Ut,"emitIterationStart");function Nt(e,t){let o=be(t.messages,t.snapshotOverride??t.currentSnapshot);return e.onIterationEnd?.({iter:t.iter,maxIter:t.maxIter,tokenCount:o.currentTokens,tokenSource:o.source,usage:o.usage,contextTokenSnapshot:o}),o}i(Nt,"emitIterationEnd");async function Q(e,t,o,s,n,r,a){if(e.beforeToolExecute){let u=await e.beforeToolExecute(t,o,{toolId:s});if(u===!1)return a?.denyRead(t,o),v;if(typeof u=="string")return a?.denyRead(t,o),u}let c=await he("tool:before",{name:t,input:o,toolId:s,executionCwd:n,gitRoot:r});return c===!1?(a?.denyRead(t,o),v):(typeof c=="string"&&a?.denyRead(t,o),typeof c=="string"?c:void 0)}i(Q,"getToolExecutionOverride");import Xe from"fs";function Ve(){return process.env.KODAX_DEBUG_STREAM==="1"||process.env.KODAX_DEBUG_RESILIENCE==="1"}i(Ve,"shouldDebugResilience");function N(e,t){Ve()&&D({source:"coding:resilience",level:"debug",message:e,detail:t})}i(N,"emitResilienceDebug");function $(e,t){let o=e.input?.path;if(!(typeof o!="string"||o.trim().length===0))return de(o,t)}i($,"resolveToolTargetPath");function Y(e,t){t&&(e.editRecoveryAttempts.delete(t),e.blockedEditWrites.delete(t))}i(Y,"clearEditRecoveryStateForPath");function Z(e,t,o){if(e.name!=="write")return;let s=$(e,t);if(!(!s||!o.blockedEditWrites.has(s))){if(!Xe.existsSync(s)){o.blockedEditWrites.delete(s);return}return`[Tool Error] write: BLOCKED_AFTER_EDIT_FAILURE: Refusing to rewrite existing file ${s} while edit anchor recovery is in progress. Retry with edit using unique existing text; use an edits array for multiple replacements.`}}i(Z,"maybeBlockExistingFileWrite");async function Ae(e,t,o,s){let n=B(t);if(!n)return;let r=typeof e.input?.path=="string"?e.input.path:void 0,a=$(e,s);if(!r||!a)return;o.blockedEditWrites.add(a);let c=(o.editRecoveryAttempts.get(a)??0)+1;if(o.editRecoveryAttempts.set(a,c),o.lastToolErrorCode=n,n==="EDIT_TOO_LARGE")return N("[edit:recovery]",{code:n,path:a,attempt:c,action:"split-edit"}),[`The previous edit for ${a} failed with ${n}.`,"Do not use write to replace the existing file.","Split the change into smaller replacements in the edits array of one edit call; later anchors must match the result of earlier edits."].join(`
|
|
3
|
+
`);if(c>2)return N("[edit:recovery]",{code:n,path:a,attempt:c,action:"stop-auto-recovery"}),[`The previous edit for ${a} failed with ${n}, and automatic anchor recovery is exhausted.`,"Do not escalate to a whole-file write.","Choose a unique old_string from current file content and retry with edit; preserve the full anchor text when appending."].join(`
|
|
4
|
+
`);let u=c===1?120:400,m=e.input?.edits,d=Array.isArray(m)&&m.length===1?m[0]:void 0,l=e.input?.old_string??(d&&typeof d=="object"&&"old_string"in d?d.old_string:""),T=await fe(r,String(l??""),s,u),g=T.candidates[0],h=T.candidates.slice(1,3);N("[edit:recovery]",{code:n,path:a,attempt:c,windowLines:u,candidateCount:T.candidates.length});let E=[`The previous edit for ${a} failed with ${n}.`,"Do not use write to rewrite the existing file.","Retry with edit using a smaller unique old_string.","For a section append, replace the complete unique heading line with that line plus the new content, preserving line breaks."];if(g&&(E.push(""),E.push(`Best nearby anchor window (${g.startLine}-${g.endLine}):`),E.push("```text"),E.push(g.excerpt),E.push("```")),h.length>0){E.push(""),E.push("Other nearby candidate anchors:");for(let _ of h)E.push(`- lines ${_.startLine}-${_.endLine}: ${_.preview}`)}return E.join(`
|
|
5
|
+
`)}i(Ae,"buildEditRecoveryUserMessage");var ze=new Set(["edit","write","multi_edit","apply_patch","delete","remove","rename"]),Je=3,Qe=100;function Oe(e){return ze.has(e.toLowerCase())}i(Oe,"isMutationTool");function Le(e){return e.files.size>=Je?!0:[...e.files.values()].reduce((o,s)=>o+s,0)>=Qe}i(Le,"isMutationScopeSignificant");function Ye(e){let t=[...e.files.values()].reduce((s,n)=>s+n,0),o=[...e.files.entries()].map(([s,n])=>` - ${s} (~${n} lines)`).join(`
|
|
6
|
+
`);return["",`[Scope: ${e.files.size} files modified, ~${t} lines]`,o].join(`
|
|
7
|
+
`)}i(Ye,"buildMutationScopeReflectionHeader");function De(e){return[Ye(e),ne("t12i.agent-runtime/middleware/mutation-reflection.block.0")].join(`
|
|
8
|
+
`)}i(De,"buildMutationScopeReflection");function Pe(e,t,o,s){let n=$(e,s);if(o.lastToolResultBytes=Buffer.byteLength(k(t),"utf8"),o.lastToolErrorCode=ke(t),e.name==="edit"){B(k(t))||Y(o,n);return}e.name==="insert_after_anchor"&&!S(t)&&Y(o,n)}i(Pe,"updateToolOutcomeTracking");function Ze(e,t,o){return{type:"tool_result",tool_use_id:e,content:t,...S(t)?{is_error:!0}:{},...o||V(t)?{metadata:{...o,...V(t)?{cancelled:!0}:{}}}:{}}}i(Ze,"createToolResultBlock");async function te(e,t,o,s,n,r,a=!0){if(r?.aborted)return v;let c=A(t.name),u=C(e,t.id,p(t).id);c&&(await G("tool:start",{name:t.name,id:t.id,input:t.input}),e.onToolUseStart?.({name:t.name,id:t.id,input:t.input},u));let m=t.name===I||t.name===P;if(!U(t.name,o))return`[Tool Error] ${t.name}: Tool is not active in the current runtime.`;if(!m){let h=await Q(e,t.name,t.input??{},t.id,o.executionCwd,o.gitRoot,o.toolResultRecovery);if(h!==void 0)return h;if(r?.aborted)return v}if(n&&!n.includes(t.name))return`[Tool Error] ${t.name}: Tool is not active in the current runtime.`;if(t.name===P)return et(t.input??{},n,o);if(t.name===I)return ot({events:e,bridgeCall:t,ctx:o,runtimeSessionState:s,activeToolNames:n,abortSignal:r,allowMcpFallback:a});let d=Z(t,o,s);if(d)return d;let l=M(t.name)===void 0?K(o.extensionRuntime,t.name):void 0;if(l===void 0&&M(t.name)===void 0&&n?.includes(t.name))return`[Tool Error] ${t.name}: Host tool lease was revoked or the tool is no longer bound to this run.`;let T=Ne(e,t,o);T.discoveryToolNames=n??o.discoveryToolNames,T.invokeCheckedTool=o.invokeCheckedTool??((h,E)=>te(e,{id:L(),name:h,input:E},o,s,n,r,a)),e.onToolExecutionStart?.({id:t.id,name:t.name},u);let g;try{let h=t,E=i(()=>l===void 0?q(h.name,h.input??{},T):j(T,l,h.input??{}),"executeNative"),_=T.beforeToolInvoke;if(g=await Ue(t,T,r,e,_?async()=>(h={...t,input:structuredClone(t.input??{})},await _({...h,input:h.input??{}}),E()):E),z(o.writtenFiles,h,g,F(o)),a&&k(g).startsWith("[Tool Error]")&&o.extensionRuntime){let oe=await $e(t.name,t.input??{},o);oe!==void 0&&(g=oe)}}finally{e.onToolExecutionEnd?.({id:t.id,name:t.name},u)}return g}i(te,"executeToolCall");function Ue(e,t,o,s,n){if(!t.sessionId||!t.runtimeRunId||!t.invokeCheckedTool)return n();let r={version:1,sessionId:t.sessionId,runId:t.runtimeRunId,invocationId:e.id,extensionId:H(e.name)?.source.id??`tool:${e.name}`};return ge({...r,signal:o??t.abortSignal??new AbortController().signal,actors:t.actorControl,invokeTool:t.invokeCheckedTool,reportProgress:i(a=>{s.onToolProgress?s.onToolProgress({id:e.id,message:a.message,extension:{...r,extensionId:xe()?.extensionId??r.extensionId,data:a.data}},C(s,e.id,p(e).id)):t.reportToolProgress?.(a.message)},"reportProgress")},a=>(t.extensionExecution=a,n()))}i(Ue,"executeInExtensionScope");function C(e,t,o){return{toolId:t,...o===void 0?{}:{executionId:o},...e.workflowCorrelation!==void 0?{workflowCorrelation:e.workflowCorrelation}:{}}}i(C,"createToolEventMeta");function Ne(e,t,o){let s=C(e,t.id,p(t).id);return e.onToolProgress||e.onToolSandboxObservation||e.askUser||e.askUserMulti||e.askUserInput?{...o,toolCallId:t.id,...o.recordToolResultArtifact?{recordToolResultArtifact:i((n,r)=>o.recordToolResultArtifact(n===t.id?p(t).resultKey:n,r),"recordToolResultArtifact")}:{},...e.onToolProgress?{reportToolProgress:i(n=>{e.onToolProgress?.({id:t.id,message:n},s)},"reportToolProgress")}:{},...e.onToolSandboxObservation?{reportToolSandboxObservation:i(n=>{e.onToolSandboxObservation?.({id:t.id,observation:n},s)},"reportToolSandboxObservation")}:{},...e.askUser?{askUser:i(n=>e.askUser(n,s),"askUser")}:{},...e.askUserMulti?{askUserMulti:i(n=>e.askUserMulti(n,s),"askUserMulti")}:{},...e.askUserInput?{askUserInput:i(n=>e.askUserInput(n,s),"askUserInput")}:{}}:{...o,toolCallId:t.id,...o.recordToolResultArtifact?{recordToolResultArtifact:i((n,r)=>o.recordToolResultArtifact(n===t.id?p(t).resultKey:n,r),"recordToolResultArtifact")}:{}}}i(Ne,"createContextForToolCall");function et(e,t,o){let s=tt(e);if(s.length===0)return"[Tool Error] tool_describe: `name` or `names` is required.";let n=t?new Set(t):void 0,r=[];for(let a of s){if(n&&!n.has(a)||!U(a,o)){r.push(`<!-- ${a}: not active in the current runtime -->`);continue}let c=M(a);if(c===void 0){let u=K(o.extensionRuntime,a);u!==void 0&&(c=pe(u))}if(!c){r.push(`<!-- ${a}: not registered -->`);continue}c=ae(c,H(c.name)?.source),r.push(`<function>${JSON.stringify({name:c.name,description:c.description,parameters:c.input_schema})}</function>`)}return r.join(`
|
|
9
|
+
`)}i(et,"describeBridgeTools");function tt(e){let t=[],o=i(s=>{typeof s=="string"&&s.trim().length>0&&t.push(s.trim())},"append");o(e.name),o(e.tool_name);for(let s of["names","tools"]){let n=e[s];if(Array.isArray(n))for(let r of n)o(r)}return[...new Set(t)]}i(tt,"readBridgeToolNames");async function ot(e){let t=W(e.bridgeCall);if(!t?.ok)return`[Tool Error] ${I}: ${t?.error??"invalid bridge call."}`;let o=t.call,s=o.name,n=o.input;if(s===I||s===P)return`[Tool Error] ${I}: bridge meta-tools cannot be called through ${I}.`;if(e.abortSignal?.aborted)return v;if(!U(s,e.ctx))return`[Tool Error] ${s}: Tool is not active in the current runtime.`;let r=await Q(e.events,s,n,o.id,e.ctx.executionCwd,e.ctx.gitRoot,e.ctx.toolResultRecovery);if(r!==void 0)return r;if(e.abortSignal?.aborted)return v;if(e.activeToolNames&&!e.activeToolNames.includes(s))return`[Tool Error] ${s}: Tool is not active in the current runtime.`;let a=Z(o,e.ctx,e.runtimeSessionState);if(a)return a;let c=Ne(e.events,o,e.ctx);c.discoveryToolNames=e.activeToolNames??e.ctx.discoveryToolNames,c.invokeCheckedTool=e.ctx.invokeCheckedTool??((T,g)=>te(e.events,{id:L(),name:T,input:g},e.ctx,e.runtimeSessionState,e.activeToolNames?[...e.activeToolNames]:void 0,e.abortSignal,e.allowMcpFallback));let u=c.recordToolResultArtifact;u!==void 0&&(c.recordToolResultArtifact=(T,g)=>{u(T,g),u(p(e.bridgeCall).resultKey,g)});let m=C(e.events,o.id,p(o).id),d=M(s)===void 0?K(e.ctx.extensionRuntime,s):void 0;e.events.onToolExecutionStart?.({id:o.id,name:s},m);let l;try{if(l=await Ue(o,c,e.abortSignal,e.events,()=>d===void 0?q(s,n,c):j(c,d,n)),z(e.ctx.writtenFiles,o,l,F(e.ctx)),e.allowMcpFallback&&k(l).startsWith("[Tool Error]")&&e.ctx.extensionRuntime){let T=await $e(s,n,e.ctx);T!==void 0&&(l=T)}}finally{e.events.onToolExecutionEnd?.({id:o.id,name:s},m)}return l}i(ot,"executeBridgeToolCall");var nt=new Set(["web_search","web_fetch","glob","grep","read","code_search","semantic_lookup"]);async function $e(e,t,o){if(nt.has(e))try{let s=await o.extensionRuntime.searchCapabilities("mcp",e,{kind:"tool",limit:1});if(s.length===0)return;let n=s[0];if(!n?.id||n.name!==e&&!n.id.endsWith(`:${e}`))return;let r=await o.extensionRuntime.executeCapability("mcp",n.id,t),a=r.content===void 0&&r.structuredContent===void 0?JSON.stringify(r,null,2):"",c=r.structuredContent==null||typeof r.structuredContent=="string"?r.structuredContent:JSON.stringify(r.structuredContent,null,2);return Te({...r,structuredContent:c},u=>`[MCP Fallback via ${n.id}]
|
|
10
|
+
${u??a}`)}catch(s){process.env.KODAX_DEBUG_TOOL_HISTORY&&D({source:"coding:tool-dispatch",level:"debug",message:`MCP fallback failed for ${e}.`,detail:s});return}}i($e,"tryMcpFallback");var O=new WeakMap;function p(e){let t=O.get(e);return t||(t={id:`execution_${L()}`,resultKey:e.id},O.set(e,t)),t}i(p,"toolExecution");async function rt(e){let t=new Map,o=new Map,s=e.toolBlocks.map((d,l)=>({block:d,index:l})).filter(({block:d})=>!w(d)),n=await Promise.all(s.map(({block:d,index:l})=>Be(e,d,l)));for(let d of n)o.set(d.index,d);for(let d=0;d<e.toolBlocks.length;d+=1){let l=e.toolBlocks[d];w(l)&&o.set(d,await Be(e,l,d))}let r=e.toolBlocks.map((d,l)=>{let T=o.get(l);if(!T)throw new Error(`Tool call at index ${l} was not prepared.`);return T});await e.onToolCallsPrepared?.(r.map(d=>Fe(d.call)));for(let d of r)d.blockedContent!==void 0&&(await Ke(e.events,d.call),t.set(p(d.call).resultKey,d.blockedContent));let a=r.filter(d=>ue(d.call));for(let d of a){let l=d.blockedContent??await ee(e,d.call);t.set(p(d.call).resultKey,l)}if(a.length>0){for(let d of r){let l=p(d.call).resultKey;t.has(l)||(await Ke(e.events,d.call),t.set(l,e.abortSignal?.aborted?v:le))}return t}let c=r.filter(d=>d.blockedContent===void 0&&!w(e.toolBlocks[d.index])&&!w(d.call)),u=await Promise.all(c.map(async d=>({id:p(d.call).resultKey,content:await ee(e,d.call)})));for(let d of u)t.set(d.id,d.content);let m=r.filter(d=>d.blockedContent===void 0&&(w(e.toolBlocks[d.index])||w(d.call)));for(let d of m){if(e.abortSignal?.aborted){t.set(p(d.call).resultKey,v);continue}t.set(p(d.call).resultKey,await ee(e,d.call))}return t}i(rt,"runToolDispatch");function w(e){if(e.name==="bash")return!0;let t=W(e);return t?.ok===!0&&t.call.name==="bash"}i(w,"requiresSerialToolExecution");async function Be(e,t,o){let s={id:t.id,name:t.name,input:t.input},n={index:o,call:s};if(!e.abortSignal?.aborted&&e.toolGuardrails?.length){if(!e.guardrailContext)throw new Error("Tool guardrails require a GuardrailContext.");let c=await re(s,e.toolGuardrails,e.guardrailContext,null);n=c.kind==="block"?{index:o,call:c.call,blockedContent:We(c.result.content,!0)}:{index:o,call:c.call}}let r=`execution_${L()}`,a={id:r,resultKey:e.toolBlocks.filter(c=>c.id===t.id).length>1?r:t.id};return O.set(n.call,a),O.set(t,a),e.finalToolBlocks?.set(t.id,Fe(n.call)),n}i(Be,"prepareToolBlock");async function ee(e,t){let o=e.ctx.authorizeShellHostExecution,s={...e.ctx,...o!==void 0&&e.guardrailContext!==void 0?{authorizeShellHostExecution:i(r=>o(r,e.guardrailContext),"authorizeShellHostExecution")}:{},invokeCheckedTool:i(async(r,a)=>{let c=L();return(await rt({...e,toolBlocks:[{type:"tool_use",id:c,name:r,input:a}],finalToolBlocks:void 0,onToolCallsPrepared:void 0})).get(c)??"[Tool Error] Nested tool did not return a result."},"invokeCheckedTool")},n=await te(e.events,t,s,e.runtimeSessionState,e.activeToolNames,e.abortSignal,e.allowMcpFallback);if(e.toolGuardrails?.length&&e.guardrailContext){let r=await ie(t,{content:n,isError:S(n)},e.toolGuardrails,e.getAfterGuardrailContext?.()??e.guardrailContext,null);n=We(r.content,r.isError===!0)}return n}i(ee,"executePreparedToolCall");function Fe(e){let t={id:e.id,name:e.name,type:"tool_use",input:e.input};return O.set(t,p(e)),t}i(Fe,"runnerCallToToolBlock");function We(e,t){return!t||S(e)?e:typeof e=="string"?`[Blocked] ${e}`:[{type:"text",text:"[Blocked]"},...e]}i(We,"normalizeGuardrailResult");async function Ke(e,t){A(t.name)&&(await G("tool:start",{name:t.name,id:t.id,input:t.input}),e.onToolUseStart?.({name:t.name,id:t.id,input:t.input},C(e,t.id,p(t).id)))}i(Ke,"emitToolCallStart");async function Lo(e){let t=[],o=[];for(let n of e.toolBlocks){let r=e.resultMap.get(p(n).resultKey)??"[Error] No result";if(e.mutationScopeReflection!==!1&&e.ctx.mutationTracker&&!e.ctx.mutationTracker.reflectionInjected&&!S(r)&&Oe(n.name)&&Le(e.ctx.mutationTracker)){let a=De(e.ctx.mutationTracker);r=typeof r=="string"?r+a:[...r,{type:"text",text:a}],e.ctx.mutationTracker.reflectionInjected=!0}if(Pe(n,r,e.runtimeSessionState,e.ctx),n.name==="edit"&&S(r)){let a=await Ae(n,k(r),e.runtimeSessionState,e.ctx);a&&o.push(a)}if(A(n.name)){let a=e.toolResultArtifactPaths?.get(p(n).resultKey);t.push(Ze(n.id,r,a?{truncated:!0,capacityFallback:!0,outputPath:a}:void 0))}}return{toolResults:await it(e,t,o),editRecoveryMessages:o}}i(Lo,"applyPostToolProcessing");async function it(e,t,o){let s=e.toolBlocks.filter(u=>A(u.name));t.forEach((u,m)=>{e.ctx.toolResultRecovery?.observeResult(s[m],u.is_error===!0)});let n=o.length>0?y([{role:"user",content:o.join(`
|
|
11
|
+
|
|
12
|
+
`),_synthetic:!0}]):0,r=await me(t.map((u,m)=>({id:p(s[m]).resultKey,toolName:s[m].name,content:u.content,...typeof u.metadata?.outputPath=="string"&&u.metadata.outputPath.length>0?{outputPath:u.metadata.outputPath}:{}})),{...e.ctx,canReadPagedContent:e.runtimeSessionState.activeTools.includes("read")},e.toolResultBudget,n),a=new Map(r.entries.map(u=>[u.id,u])),c=t.map((u,m)=>{let d={...u,is_error:u.is_error===!0},l=a.get(p(s[m]).resultKey);return!l||l.content===d.content?r.capacityDebt?{...d,metadata:{...d.metadata??{},capacityDebt:!0}}:d:{...d,content:l.content,metadata:{...d.metadata??{},truncated:!0,capacityFallback:!0,...r.capacityDebt?{capacityDebt:!0}:{},...l.outputPath?{outputPath:l.outputPath}:{}}}});for(let[u,m]of c.entries()){let d=s[u];if(!d)continue;let l=k(m.content);await e.emitActiveExtensionEvent("tool:result",{id:d.id,name:d.name,content:l}),e.events.onToolResult?.({id:d.id,name:d.name,content:l,toolResult:m},C(e.events,d.id,p(d).id))}return c}i(it,"admitAndEmitVisibleToolResults");export{N as a,S as b,V as c,z as d,gt as e,Se as f,ht as g,Et as h,Re as i,be as j,kt as k,_t as l,wt as m,Ct as n,Mt as o,At as p,A as q,Ot as r,Lt as s,Dt as t,Pt as u,Bt as v,Kt as w,Ut as x,Nt as y,Q as z,Ze as A,te as B,Ue as C,C as D,Ne as E,nt as F,$e as G,p as H,rt as I,Lo as J};
|