@kodax-ai/kodax 0.7.89 → 0.7.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +8 -0
  3. package/README_CN.md +2 -0
  4. package/dist/chunks/{agent-AKCXT573.js → agent-W35WYLTH.js} +1 -1
  5. package/dist/chunks/argument-completer-SRCHPEMA.js +2 -0
  6. package/dist/chunks/{chunk-4Y6OSDZE.js → chunk-4KJQ7QGO.js} +1 -1
  7. package/dist/chunks/{chunk-W5RPVR3O.js → chunk-6FLHNFYV.js} +1 -1
  8. package/dist/chunks/{chunk-BOMSVUJS.js → chunk-7KPBUO2F.js} +2 -2
  9. package/dist/chunks/{chunk-SOIIBADK.js → chunk-DBFWNUGB.js} +2 -2
  10. package/dist/chunks/{chunk-IFD6TUQU.js → chunk-JNBAIFJR.js} +1 -1
  11. package/dist/chunks/{chunk-CQHLFQSU.js → chunk-KG3QIIDU.js} +2 -2
  12. package/dist/chunks/{chunk-W2LRTZBJ.js → chunk-KINDGE7G.js} +40 -40
  13. package/dist/chunks/{chunk-5UBP47VJ.js → chunk-NCK7ASJL.js} +57 -57
  14. package/dist/chunks/{chunk-72H6JNPN.js → chunk-R3BXINQ2.js} +124 -124
  15. package/dist/chunks/{chunk-S74F7MFN.js → chunk-T256QEDN.js} +1 -1
  16. package/dist/chunks/{chunk-QQBFQCMF.js → chunk-TDSTNXNR.js} +9 -9
  17. package/dist/chunks/{chunk-A63MGLH6.js → chunk-ZACJCRHT.js} +1 -1
  18. package/dist/chunks/{chunk-GL6GVYF4.js → chunk-ZDOLJSTE.js} +4 -4
  19. package/dist/chunks/{chunk-PROPMIT4.js → chunk-ZVICRZVA.js} +1 -1
  20. package/dist/chunks/{client-ZXBSEDS4.js → client-RWXK22GN.js} +1 -1
  21. package/dist/chunks/{compaction-config-HVHPJ6CS.js → compaction-config-MD2PQSAM.js} +1 -1
  22. package/dist/chunks/{construction-bootstrap-WF6KQ7XV.js → construction-bootstrap-KB6GB6IY.js} +1 -1
  23. package/dist/chunks/{dist-BCT3UNMA.js → dist-2NRXEHLI.js} +1 -1
  24. package/dist/chunks/host-JAXBBRCV.js +2 -0
  25. package/dist/chunks/{run-manager-ZOV7EKTZ.js → run-manager-EI264JTO.js} +1 -1
  26. package/dist/chunks/{utils-BEWYGEMB.js → utils-SDMYKIZG.js} +1 -1
  27. package/dist/index.d.ts +14 -14
  28. package/dist/index.js +1 -1
  29. package/dist/kodax_bootstrap.js +1 -1
  30. package/dist/kodax_cli.js +927 -927
  31. package/dist/runtime-worker.js +679 -679
  32. package/dist/sandbox-workspace-session.js +61 -61
  33. package/dist/sdk-a2a.d.ts +8 -8
  34. package/dist/sdk-a2a.js +1 -1
  35. package/dist/sdk-agent.d.ts +12 -12
  36. package/dist/sdk-agent.js +1 -1
  37. package/dist/sdk-coding.d.ts +13 -13
  38. package/dist/sdk-coding.js +1 -1
  39. package/dist/sdk-experimental-memory.d.ts +3 -3
  40. package/dist/sdk-experimental-memory.js +1 -1
  41. package/dist/sdk-mcp.js +1 -1
  42. package/dist/sdk-repl.d.ts +9 -9
  43. package/dist/sdk-repl.js +1 -1
  44. package/dist/sdk-runtime.d.ts +2 -2
  45. package/dist/sdk-runtime.js +1 -1
  46. package/dist/sdk-sandbox.js +1 -1
  47. package/dist/sdk-session.d.ts +5 -5
  48. package/dist/sdk-session.js +1 -1
  49. package/dist/sdk-skills.js +1 -1
  50. package/dist/types-chunks/{bash-prefix-extractor.d-BLlhCRI-.d.ts → bash-prefix-extractor.d-DBxWweqC.d.ts} +2 -2
  51. package/dist/types-chunks/{capsule.d-Cw4UlPTC.d.ts → capsule.d-Bc1-UYaj.d.ts} +2 -2
  52. package/dist/types-chunks/{controller.d-BvwWz6yP.d.ts → controller.d-CTvvOy_V.d.ts} +1 -1
  53. package/dist/types-chunks/{controller.d-1tydJm7c.d.ts → controller.d-CnQqfSI5.d.ts} +1 -1
  54. package/dist/types-chunks/{guardrail.d-DqWHIgt6.d.ts → guardrail.d-DqP4s46f.d.ts} +2 -2
  55. package/dist/types-chunks/{history-retrieval.d-ia-4iJpw.d.ts → history-retrieval.d-D0LNyBED.d.ts} +1 -1
  56. package/dist/types-chunks/{public-api.d-CMZa4JPa.d.ts → public-api.d-CrBB7m8F.d.ts} +4 -4
  57. package/dist/types-chunks/{repl.d-Byu2osV-.d.ts → repl.d-qijzfmA1.d.ts} +5 -5
  58. package/dist/types-chunks/{review-inbox.d-D3T-RxRs.d.ts → review-inbox.d-dAtGH3g2.d.ts} +1 -1
  59. package/dist/types-chunks/{run-manager.d-D0aKe12e.d.ts → run-manager.d-PEct-5KE.d.ts} +1 -1
  60. package/dist/types-chunks/{sdk-session-BEM7yvJB.d.ts → sdk-session-BIeiLU8G.d.ts} +2 -2
  61. package/dist/types-chunks/{shell-command-sets.d-_SHjU3KP.d.ts → shell-command-sets.d-RvEIrqHQ.d.ts} +1 -1
  62. package/dist/types-chunks/{types.d-B_IFJlti.d.ts → types.d-B9Fhknxd.d.ts} +1 -1
  63. package/dist/types-chunks/{types.d-BqK7eZ5u.d.ts → types.d-Do_AsIIs.d.ts} +2 -2
  64. package/dist/types-chunks/{types.d-DeokRBs7.d.ts → types.d-EjZTEEVu.d.ts} +2 -1
  65. package/dist/types-chunks/{utils.d-0h1NTEsX.d.ts → utils.d-BvayexqQ.d.ts} +5 -5
  66. package/package.json +1 -1
  67. package/dist/chunks/argument-completer-BJGY57H2.js +0 -2
  68. package/dist/chunks/host-V6ENYZAQ.js +0 -2
package/CHANGELOG.md CHANGED
@@ -6,6 +6,45 @@ All notable changes to this project will be documented in this file.
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.7.90] - 2026-08-17
10
+
11
+ ### Fixed
12
+
13
+ - Workspace session RPC timeouts no longer force-kill the shared ASRT session:
14
+ a timed-out wrap/cleanup now fails its pending requests and retires the
15
+ session through the orderly close path (lease drain + Windows reset grace),
16
+ so a slow shared-queue cleanup can no longer poison the durable Windows ACL
17
+ owner marker as `unconfirmed-owner-*` for the rest of the boot.
18
+ - Workspace session cleanup RPCs use the 130s Windows reset-grace budget
19
+ instead of the generic 30s RPC deadline on every platform, since cleanup
20
+ resets shared ACL/WFP state and may wait behind in-flight wraps on the
21
+ session's serial queue.
22
+ - Daemon log diagnostics keep Error details diagnosable: `detail` payloads
23
+ serialize `name`/`message` plus `AggregateError.errors[]` and `cause` chains
24
+ instead of collapsing to `{}`.
25
+ - Run-scoped tool materialization normalizes open lease/embedder input schemas to
26
+ the provider contract (`type: object`, `properties`, and valid string
27
+ `required` entries), so Anthropic-compatible requests cannot be rejected by a
28
+ missing schema type. Archive markers also stay attached to a retained direct
29
+ predecessor when one-hop clone retention keeps that predecessor alive.
30
+ - Chained-compaction clone provenance now addresses the direct physical
31
+ predecessor copy instead of the transitive root source, and archive
32
+ collection never removes an entry that a retained clone physically
33
+ references. Together these eliminate the double-booked `logicalId` shape
34
+ that could make repeated compaction resolve as ambiguous history;
35
+ `sourceEntryId` semantics for hosts change from "root physical source" to
36
+ "direct physical predecessor" (see the SDK embedder guide).
37
+
38
+ ### Documentation
39
+
40
+ - Synchronized package metadata, release notes, architecture/product/design
41
+ baselines, feature tracking, public SDK guidance, `kodax_manual`, and
42
+ regression coverage for the v0.7.90 stabilization release.
43
+
44
+ > v0.7.90 intentionally includes Runtime/sandbox, Agent lineage, Coding
45
+ > runtime, and REPL persistence system-code fixes. npm publication remains a
46
+ > separate manual operator step.
47
+
9
48
  ---
10
49
 
11
50
  ## [0.7.89] - 2026-08-16
package/README.md CHANGED
@@ -701,6 +701,14 @@ never enter the global registry or unrelated CLI runs. The web-search custom
701
701
  endpoint remains isolated, and no shell/sandbox system code changed in this
702
702
  release. See the [v0.7.89 release checklist](docs/release.md#v0789-release-preparation).
703
703
 
704
+ **v0.7.90 release:** this stabilization release keeps the v0.7.89 contracts
705
+ while fixing workspace-session timeout retirement and daemon Error diagnostics,
706
+ direct clone-predecessor lineage/archive-marker topology, and provider-valid
707
+ schemas for run-scoped tools. These are intentional Runtime/sandbox, Agent,
708
+ Coding runtime, and REPL persistence system-code fixes; the fail-closed safety
709
+ boundaries remain unchanged. See the
710
+ [v0.7.90 release checklist](docs/release.md#v0790-release-preparation).
711
+
704
712
  **v0.7.87 GLM provider release:** `zhipu-coding` defaults to `glm-5.3` and
705
713
  retains `glm-5.2` as an explicit rollback route. `zai-coding` retained both
706
714
  models but defaulted to `glm-5.2` until the overseas Coding Plan rollout
package/README_CN.md CHANGED
@@ -251,6 +251,8 @@ v0.7.93。详见 [v0.7.83 发布清单](docs/release.md#v0783-release-preparatio
251
251
 
252
252
  **v0.7.89 发布**:本版本包含 Issue 293 的 managed context 拓扑透明投影与 v4 conversation page cache、FEATURE_293 的有界零服务 web search fallback(DuckDuckGo HTML → Bing RSS → Bing HTML),以及 FEATURE_294 的 run-scoped Host Tools。绑定到 Run 的 Host Tools 会出现在该 Run 的模型工具表和 capability catalog 中,按 registry-first 规则 dispatch,撤销后 fail-closed,不进入全局 registry,也不会泄漏到其他 CLI Run。自定义 web-search endpoint 仍保持隔离;本版本没有修改 shell/sandbox 系统代码。详见 [v0.7.89 发布清单](docs/release.md#v0789-release-preparation)。
253
253
 
254
+ **v0.7.90 发布**:本稳定性版本保留 v0.7.89 的契约,并修复 workspace session RPC 超时后的有序退役与 daemon Error/AggregateError/cause 诊断、链式 compaction 的 direct physical predecessor 与 archive marker 拓扑,以及 run-scoped tool 在 provider 边界的 object schema 规范化。它包含明确的 Runtime/sandbox、Agent lineage、Coding runtime 与 REPL 持久化系统代码修复,但没有放宽 fail-closed 安全边界。详见 [v0.7.90 发布清单](docs/release.md#v0790-release-preparation)。
255
+
254
256
  **v0.7.87 GLM Provider 发布**:`zhipu-coding` 默认使用 `glm-5.3`,并保留 `glm-5.2` 作为显式回退路由。`zai-coding` 当时保留两个模型但默认使用 `glm-5.2`,直到 v0.7.88 的海外 Coding Plan 路由切换。Coding Plan model ID 原样发送,不附加 context 后缀。GLM-5.3 的思考不可关闭,因此 `off` / `none` 会降级为 `low`,不会发送上游不支持的 disabled-thinking 请求。Issue 256 剩余的 Worker owner lease 边界在 v0.7.87 后仍保持 Open,且本版本不指定新的替代目标。详见 [v0.7.87 发布清单](docs/release.md#v0787-release-preparation)。
255
257
 
256
258
  Windows workspace Shell 还会保留大小写不敏感的 `PATH`/`Path` 与 `PATHEXT` 约定,
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ka as g,Ma as h,Za as i,_a as j,a as c,sa as d,ta as e,ua as f,yc as k}from"./chunk-A63MGLH6.js";import"./chunk-O2ZV775M.js";import"./chunk-5UBP47VJ.js";import"./chunk-W5RPVR3O.js";import"./chunk-PROPMIT4.js";import"./chunk-UNEC2WXJ.js";import{Jb as a,Kb as b}from"./chunk-72H6JNPN.js";import"./chunk-5247AKGN.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,k as runKodaX,j as saveRequiredSessionSnapshot,i as saveSessionSnapshot,a as validateAndFixToolHistory};
2
+ import{Ka as g,Ma as h,Za as i,_a as j,a as c,sa as d,ta as e,ua as f,yc as k}from"./chunk-ZACJCRHT.js";import"./chunk-O2ZV775M.js";import"./chunk-NCK7ASJL.js";import"./chunk-6FLHNFYV.js";import"./chunk-ZVICRZVA.js";import"./chunk-UNEC2WXJ.js";import{Jb as a,Kb as b}from"./chunk-R3BXINQ2.js";import"./chunk-5247AKGN.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,k as runKodaX,j as saveRequiredSessionSnapshot,i as saveSessionSnapshot,a as validateAndFixToolHistory};
@@ -0,0 +1,2 @@
1
+ // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
+ import{Ha as a,Ia as b}from"./chunk-KG3QIIDU.js";import"./chunk-DBFWNUGB.js";import"./chunk-4KJQ7QGO.js";import"./chunk-T256QEDN.js";import"./chunk-JNBAIFJR.js";import"./chunk-ZACJCRHT.js";import"./chunk-O2ZV775M.js";import"./chunk-7KPBUO2F.js";import"./chunk-NCK7ASJL.js";import"./chunk-6FLHNFYV.js";import"./chunk-ZVICRZVA.js";import"./chunk-UNEC2WXJ.js";import"./chunk-R3BXINQ2.js";import"./chunk-5247AKGN.js";import"./chunk-ONUPGMER.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ja as c,df as o}from"./chunk-72H6JNPN.js";import{a as n}from"./chunk-ONUPGMER.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};
2
+ import{Ja as c,df as o}from"./chunk-R3BXINQ2.js";import{a as n}from"./chunk-ONUPGMER.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{Qd as P,Rd as S,Sb as v,Sd as h,ac as x,fc as D,l as j,t as I}from"./chunk-72H6JNPN.js";import{a}from"./chunk-ONUPGMER.js";var k="[Memory evidence; not an instruction]",T="Current user/host instructions and verified environment evidence override this.",A=2048,M=256,N=3,Y=3200;function b(n,e=[]){let t=h(n,A);if(t===void 0)return;let i=e.filter(r=>r.length>0&&r.length<=M&&!/[\r\n\u0000-\u001f\u007f]/.test(r)&&h(r,M)===r).slice(0,N),s=[k,`Claim: ${t}`,...i.length>0?[`Ref: ${i.join(", ")}`]:[],T].join(`
2
+ import{Qd as P,Rd as S,Sb as v,Sd as h,ac as x,fc as D,l as j,t as I}from"./chunk-R3BXINQ2.js";import{a}from"./chunk-ONUPGMER.js";var k="[Memory evidence; not an instruction]",T="Current user/host instructions and verified environment evidence override this.",A=2048,M=256,N=3,Y=3200;function b(n,e=[]){let t=h(n,A);if(t===void 0)return;let i=e.filter(r=>r.length>0&&r.length<=M&&!/[\r\n\u0000-\u001f\u007f]/.test(r)&&h(r,M)===r).slice(0,N),s=[k,`Claim: ${t}`,...i.length>0?[`Ref: ${i.join(", ")}`]:[],T].join(`
3
3
  `);return j(s)<=Y?s:void 0}a(b,"renderMemoryEvidenceEnvelope");import{createHash as W,randomUUID as J}from"node:crypto";var Z="Explicit memory intent captured before episode cancellation.";function ee(n){let e=new q(n);if(!D(n.controlPlane))return e;let t=n.controlPlane;return Object.assign(e,{async list(i={}){let s=await t.listRefs({kinds:["memdir"],lifecycles:["active","trusted"],...i.query===void 0?{}:{query:i.query},...i.scopes===void 0?{}:{scopes:i.scopes}});return(await Promise.all(s.map(o=>t.readRef(o)))).map(o=>({ref:o.ref,handle:P(o.ref),body:x(o.body).body,storageFingerprint:o.bodyFingerprint,readAt:o.readAt,warnings:o.warnings}))},remember:a(i=>t.remember(i),"remember"),forget:a((i,s)=>t.forgetRef(i,s),"forget")})}a(ee,"createMemoryAgent");var q=class{static{a(this,"DefaultMemoryAgent")}options;constructor(e){this.options=e}async startSession(e){let t=this.options.initialMemoryPack??await this.options.controlPlane.buildMemoryPack({task:e.objective,identity:e.identity,maxCandidates:12,maxHints:5});return new C({...e,episodeId:e.episodeId??`episode_${J()}`},t.memoryRevision,t.candidates,this.options)}},C=class{static{a(this,"DefaultMemorySession")}input;memoryRevision;candidates;options;observations=new Map;consumedReminderKeys=new Set;interventionEpochs=new Set;lastSequence=0;closed=!1;completion;activeIntervention=!1;interventionRunnerCalls=0;queryByEpoch=new Map;injectedReceiptIds=[];constructor(e,t,i,s){this.input=e,this.memoryRevision=t,this.candidates=i,this.options=s}observe(e){if(this.assertOpen(),S(e.summary))return;let t=de(e,this.options.sourcePolicy),i=this.observations.get(e.id);if(i!==void 0){if(i.sequence===t.sequence&&F(i)===F(t))return;throw new Error(`conflicting duplicate memory observation: ${e.id}`)}if(!Number.isSafeInteger(e.sequence)||e.sequence<=this.lastSequence)throw new Error(`memory observation sequence must be strictly monotonic after ${this.lastSequence}`);if(e.summary.trim().length===0)throw new Error("memory observation summary must not be empty");this.observations.set(e.id,t),this.lastSequence=e.sequence}recall(e){this.assertOpen();let t=[...this.observations.values()].filter(f=>f.sequence<=e.throughSequence).filter(V).filter(f=>ne(f,e)).sort((f,l)=>l.sequence-f.sequence).map($),i=this.candidates.filter(H).filter(f=>te(f,e)).map(_),s=E([...t,...i]).slice(0,3);if(s.length===0){this.emitDecisionReceipt(e,[],[],[],[]);return}let r=s.map(f=>f.refId),o=p(s.flatMap(f=>f.evidenceRefs??[])),u=g(`${r.join("\0")}\0${e.actionSignature??e.decisionIntent}`);if(this.consumedReminderKeys.has(u)){this.emitDecisionReceipt(e,s,r,[],["exact"]);return}this.consumedReminderKeys.add(u);let m=w(s.map(f=>f.claim),o);return this.emitDecisionReceipt(e,s,r,m?.evidenceRefs??[],["exact"]),m}async intervene(e){if(this.assertOpen(),e.triggers.length===0||e.signal?.aborted)return;let t=L(e);if(this.interventionEpochs.has(t)||this.activeIntervention)return;this.interventionEpochs.add(t),this.activeIntervention=!0;let i=this.lastSequence;try{let s=await this.buildInterventionCandidates(e);if(e.signal?.aborted)return;if(this.lastSequence!==i||e.throughSequence!==i){this.options.onTrace?.({type:"recall.intervention.discarded",key:t,detail:"state_revision_changed"});return}if(s.length===0){this.emitDecisionReceipt(e,[],[],[],[],e.triggers);return}let r=p([...e.triggers.includes("context_compacted")?s.filter(c=>c.source==="current").filter(c=>c.claimKind==="objective").slice(0,1).map(c=>c.refId):[],...s.filter(c=>c.source!=="current").filter(c=>K(c,e)).map(c=>c.refId)]).slice(0,3),o=r.length>=3?[]:await this.selectInterventionCandidates(e,s,t);if(e.signal?.aborted)return;if(this.lastSequence!==i){this.options.onTrace?.({type:"recall.intervention.discarded",key:t,detail:"state_revision_changed"});return}let u=p([...r,...o]).slice(0,3),m=u.map(c=>s.find(U=>U.refId===c)).filter(c=>c!==void 0),f=p(m.flatMap(c=>c.evidenceRefs??[])),l=[...r.length>0?["exact"]:[],...o.length>0?["semantic_intervention"]:[]];if(m.length===0){this.emitDecisionReceipt(e,s,[],[],l,e.triggers);return}let d=g([t,...u].join("\0"));if(this.consumedReminderKeys.has(d)){this.emitDecisionReceipt(e,s,u,[],l,e.triggers);return}this.consumedReminderKeys.add(d);let y=w(m.map(c=>c.claim),f);return this.emitDecisionReceipt(e,s,u,y?.evidenceRefs??[],l,e.triggers),y}finally{this.activeIntervention=!1}}query(e){this.assertOpen();let t=R(e.decisionRevision,e.throughSequence),i=ce(e.need),s=g([t,this.memoryRevision,i??"",e.actionSignature??"",v].join("\0")),r=this.queryByEpoch.get(t);if(r!==void 0)return r.key===s?r.result:Promise.resolve(void 0);let o=i===void 0?Promise.resolve(void 0):this.queryOnce(e,i);return this.queryByEpoch.set(t,{key:s,result:o}),i===void 0&&this.emitDecisionReceipt(e,[],[],[],["deliberate_query"]),o}rewind(e){if(this.assertOpen(),!Number.isSafeInteger(e.throughSequence)||e.throughSequence<0)throw new Error("rewind sequence must be a non-negative safe integer");for(let[t,i]of this.observations)i.sequence>e.throughSequence&&this.observations.delete(t);for(this.lastSequence=e.throughSequence,this.consumedReminderKeys.clear(),this.interventionEpochs.clear(),this.queryByEpoch.clear();this.injectedReceiptIds.length>0;)this.injectedReceiptIds.pop()}complete(e){return this.assertOpen(),this.completion!==void 0?this.completion:(this.completion=this.completeOnce(e),this.completion)}async close(e={}){e.drain!==!1&&this.completion!==void 0&&await this.completion,this.closed=!0}async completeOnce(e){let t=e.evidence.map(c=>Q(c,this.options.sourcePolicy)),i=e.memoryIntent===void 0?void 0:h(e.memoryIntent.candidateStatement,512),s=e.memoryIntent===void 0?void 0:h(e.memoryIntent.userQuote,512),r=e.memoryIntent!==void 0&&i!==void 0&&s!==void 0&&t.some(c=>c.ref===e.memoryIntent?.evidenceRef&&c.requestedGrade==="authoritative"&&c.source==="user")?{operation:e.memoryIntent.operation,evidenceRef:e.memoryIntent.evidenceRef,candidateStatement:i,userQuote:s}:void 0,o=oe(e.handledMemoryOperations??[]),u=e.status==="cancelled";if(u&&r===void 0)return;let m=u?r?.candidateStatement:this.input.objective;if(m===void 0)return;let f=h(m,512),l=h(u?Z:e.summary,512);if(f===void 0||l===void 0)return;let d=u&&r!==void 0?t.filter(c=>c.ref===r.evidenceRef&&c.requestedGrade==="authoritative"&&c.source==="user").slice(0,1):t,y=se({...this.input,objective:f},[...this.observations.values()],{status:e.status,summary:l,evidence:d,...r===void 0?{}:{memoryIntent:r},...o.length===0?{}:{handledMemoryOperations:o}},this.options.now?.()??new Date().toISOString(),this.injectedReceiptIds);if(await this.options.persistOutcomeDigest?.(y),e.status==="cancelled"){this.reviewDetached(y);return}await this.reviewWithTimeout(y)}reviewDetached(e){this.reviewWithTimeout(e,{unrefTimeout:!0}).catch(t=>{let i=t instanceof Error?t.message:String(t);I({source:"memory.agent",level:"warn",message:"Detached episode review failed.",detail:{reviewKey:e.reviewKey,error:i}});try{this.options.onTrace?.({type:"review.failed",key:e.reviewKey,detail:i})}catch(s){I({source:"memory.agent",level:"warn",message:"Detached episode review trace callback failed.",detail:{reviewKey:e.reviewKey,error:s instanceof Error?s.message:String(s)}})}})}async reviewWithTimeout(e,t={}){let i=this.options.reviewEpisode;if(i===void 0)return;let s=new AbortController,r=Math.max(1,this.options.reviewTimeoutMs??3e4),o,u=await Promise.race([i(e,s.signal).then(()=>!1),new Promise(m=>{o=setTimeout(()=>{s.abort(),m(!0)},r),t.unrefTimeout&&o.unref()})]);o!==void 0&&clearTimeout(o),u&&this.options.onTrace?.({type:"review.timed_out",key:e.reviewKey,detail:`${r}ms`})}assertOpen(){if(this.closed)throw new Error("memory session is closed")}async buildInterventionCandidates(e){let t=e.currentCandidates.map(ie).filter(r=>r!==void 0),i=z([...this.observations.values()].filter(r=>r.sequence<=e.throughSequence).filter(V).sort((r,o)=>o.sequence-r.sequence).map($),e),s=[];try{let r=await this.options.controlPlane.buildMemoryPack({task:this.input.objective,identity:this.input.identity,decisionIntent:e.decisionIntent,...e.actionSignature!==void 0?{actionSignature:e.actionSignature}:{},maxCandidates:12,maxHints:12,includeSnippets:!0,purpose:"intervention"});s=z(r.promptHints.filter(H).map(_),e)}catch(r){this.options.onTrace?.({type:"recall.intervention.failed",key:L(e),detail:r instanceof Error?r.message:String(r)})}return re(t,i,s)}async selectInterventionCandidates(e,t,i){let s=this.options.recallRunner;if(s===void 0||this.interventionRunnerCalls>=3)return[];this.interventionRunnerCalls+=1;let r=new AbortController,o=a(()=>r.abort(e.signal?.reason),"forwardAbort");e.signal?.addEventListener("abort",o,{once:!0}),e.signal?.aborted&&o();let u=t.map((f,l)=>({alias:`candidate:${l+1}`,candidate:{...f,refId:`candidate:${l+1}`,evidenceRefs:[]}})),m;try{let f=await Promise.race([s({objective:O(e.objective),decisionContext:O(e.decisionContext,2048),decisionIntent:O(e.decisionIntent),triggers:e.triggers,candidates:u.map(({candidate:d})=>d),signal:r.signal}),new Promise(d=>{m=setTimeout(()=>{r.abort(),d({selectedRefIds:[]})},5e3)})]),l=new Map(u.map(({alias:d},y)=>[d,t[y].refId]));return p(f.selectedRefIds.map(d=>l.get(d)).filter(d=>d!==void 0)).slice(0,3)}catch(f){return this.options.onTrace?.({type:"recall.intervention.failed",key:i,detail:f instanceof Error?f.message:String(f)}),[]}finally{m!==void 0&&clearTimeout(m),e.signal?.removeEventListener("abort",o)}}async queryOnce(e,t){try{let i=await this.options.controlPlane.buildMemoryPack({task:this.input.objective,identity:this.input.identity,decisionIntent:t,...e.actionSignature!==void 0?{actionSignature:e.actionSignature}:{},maxCandidates:3,maxHints:3,includeSnippets:!0,purpose:"deliberate_query"}),s=i.promptHints.filter(X).map(l=>({hint:l,claim:h(l.bodySnippet??"")})).filter(l=>l.claim!==void 0).slice(0,3),r=s.map(({hint:l})=>l.ref.id),o=w(s.map(({claim:l})=>l),r),u=o?.content??"",m=o?.evidenceRefs??[],f=i.candidates.map(_);return this.emitDecisionReceipt(e,f,r,m,["deliberate_query"]),o}catch(i){this.emitDecisionReceipt(e,[],[],[],["deliberate_query"]),this.options.onTrace?.({type:"query.failed",key:R(e.decisionRevision,e.throughSequence),detail:i instanceof Error?i.message:String(i)});return}}emitDecisionReceipt(e,t,i,s,r,o){let u=R(e.decisionRevision,e.throughSequence),m=t.map(c=>c.refId),f=new Set(i),l=p(t.filter(c=>f.has(c.refId)).flatMap(c=>c.evidenceRefs).filter(B)),d=g(t.map(c=>[c.refId,c.source??"",c.claim,...c.evidenceRefs??[]].join("\0")).join(`
4
4
  `)),y={id:`memory-decision:${g([u,v,d,i.join(","),s.join(","),r.join(","),o?.join(",")??""].join("\0")).slice(0,24)}`,decisionEpoch:u,decisionRevision:e.decisionRevision,policyVersion:v,candidateSetFingerprint:d,candidateIds:[...m],selectedCandidateIds:[...i],injectedEvidenceRefs:[...s],...o!==void 0&&o.length>0?{triggers:[...o]}:{},candidateRefs:[...m],selectedRefs:[...l],injectedRefs:[...s],selectionModes:[...r],...e.actionSignature!==void 0?{actionSignature:e.actionSignature}:{},throughSequence:e.throughSequence};s.length>0&&!this.injectedReceiptIds.includes(y.id)&&this.injectedReceiptIds.push(y.id),this.options.onTrace?.({type:"memory.decision",receipt:y})}};function ne(n,e){return n.actionSignature!==void 0&&e.actionSignature!==void 0?n.actionSignature===e.actionSignature:n.claimKey!==void 0&&n.claimKey===e.decisionIntent}a(ne,"exactObservationMatch");function te(n,e){return n.ref.actionSignature!==void 0&&e.actionSignature!==void 0?n.ref.actionSignature===e.actionSignature:n.ref.claimKey!==void 0&&n.ref.claimKey===e.decisionIntent}a(te,"exactCandidateMatch");function ie(n){let e=h(n.claim);if(e!==void 0)return{...n,claim:e,source:"current",evidenceRefs:p(n.evidenceRefs??[n.refId])}}a(ie,"currentCandidate");function $(n){let e=h(n.summary)??`Prior observation is available at ${n.evidence[0]?.ref??n.id}.`;return{refId:`observation:${n.id}`,claim:e,claimKind:n.kind,source:"session",evidenceRefs:p(n.evidence.map(t=>t.ref)),...n.actionSignature!==void 0?{actionSignature:n.actionSignature}:{},...n.claimKey!==void 0?{claimKey:n.claimKey}:{}}}a($,"observationCandidate");function _(n){let e=h(n.bodySnippet??n.hook)??`Governed memory is available at ${n.ref.id}.`;return{refId:n.ref.id,claim:e,...n.ref.claimKind!==void 0?{claimKind:n.ref.claimKind}:{},source:"durable",evidenceRefs:[n.ref.id],...n.ref.actionSignature!==void 0?{actionSignature:n.ref.actionSignature}:{},...n.ref.claimKey!==void 0?{claimKey:n.ref.claimKey}:{}}}a(_,"durableCandidate");function V(n){return n.visibility!=="prompt_safe"||h(n.summary)===void 0?!1:n.evidence.some(e=>e.source!=="agent")}a(V,"isAutomaticObservation");function H(n){return X(n)&&h(n.bodySnippet??n.hook)!==void 0}a(H,"isGovernedHint");function K(n,e){return n.actionSignature!==void 0&&e.actionSignature!==void 0?n.actionSignature===e.actionSignature:n.claimKey!==void 0&&n.claimKey===e.decisionIntent}a(K,"candidateMatchesInput");function z(n,e){return[...n.filter(t=>K(t,e)),...n.filter(t=>!K(t,e))]}a(z,"prioritizeExactCandidates");function re(n,e,t){let i=n.filter(u=>u.claimKind==="objective").slice(0,1),s=n.filter(u=>u.claimKind==="todo"),r=E([...i,...s.slice(0,3),...e.slice(0,4),...t.slice(0,4)]),o=E([...s.slice(3),...e.slice(4),...t.slice(4)]);return E([...r,...o]).slice(0,12)}a(re,"admitInterventionCandidates");function E(n){let e=new Set;return n.filter(t=>e.has(t.refId)?!1:(e.add(t.refId),!0))}a(E,"uniqueCandidates");function se(n,e,t,i,s){let r=t.status==="cancelled"?void 0:[...e].reverse().find(d=>d.kind==="outcome"),o=typeof r?.metadata?.reusableLesson=="string"?h(r.metadata.reusableLesson,512):void 0,u=t.status==="cancelled"?[]:e.filter(d=>d.metadata?.verification===!0).flatMap(d=>d.evidence).filter(d=>d.verdict==="passed"||d.verdict==="failed").filter(d=>!t.evidence.some(y=>y.ref===d.ref)),m=[...t.evidence,...u],f=e.at(-1)?.sequence??0,l=g([n.identity.sessionId,n.episodeId,String(f),t.status,t.summary].join("\0"));return{id:`memory-outcome:${l.slice(0,24)}`,reviewKey:l,episodeId:n.episodeId,sessionId:n.identity.sessionId,branchId:n.identity.sessionId,sequence:f,objective:n.objective,...r?.actionSignature!==void 0?{actionSignature:r.actionSignature}:{},...o===void 0?{}:{lesson:o},approach:r?.summary??"episode completion",outcome:t.status,summary:t.summary.trim(),evidenceRefs:p(m.map(d=>d.ref)),evidence:m.map(d=>({ref:d.ref,grade:d.requestedGrade,source:d.source,...d.verdict!==void 0?{verdict:d.verdict}:{},observedAt:d.observedAt})),...t.memoryIntent===void 0?{}:{memoryIntent:t.memoryIntent},...t.handledMemoryOperations===void 0?{}:{handledMemoryOperations:t.handledMemoryOperations},...t.status!=="cancelled"&&s.length>0?{memoryInfluence:p(s).map(d=>({decisionReceiptRef:d,grade:"exposed"}))}:{},visibility:r?.visibility??"prompt_safe",createdAt:i}}a(se,"buildOutcomeDigest");function oe(n){return n.slice(-20).flatMap(e=>{let t=e.statement===void 0?void 0:h(e.statement,1024),i=e.claimKey?.trim(),s=p(e.targetRefIds).map(o=>h(o,256)).filter(o=>o!==void 0),r=i!==void 0&&/^[a-z0-9._:-]{1,160}$/i.test(i)?i:void 0;return t===void 0&&r===void 0&&s.length===0?[]:[{operation:e.operation,...e.disposition===void 0?{}:{disposition:e.disposition},...t===void 0?{}:{statement:t},...r===void 0?{}:{claimKey:r},targetRefIds:s}]})}a(oe,"sanitizeHandledMemoryOperations");function ce(n){let e=n.replace(/\s+/g," ").trim();if(!(e.length===0||G(e)>512||S(e))&&!/^(?:list|show|dump|enumerate)\s+(?:all|every)\s+(?:the\s+)?memor(?:y|ies)\b/i.test(e)&&!/\b(?:all|every)\s+(?:project|workspace|tenant|user|agent)(?:s|'s)?\b/i.test(e))return e}a(ce,"normalizeQueryNeed");function G(n){let e=0,t=0;for(let i of n)i.codePointAt(0)<=127?e+=1:t+=1;return Math.ceil(e/4)+t}a(G,"estimateMemoryTokens");function X(n){return n.ref.visibility==="prompt_safe"&&n.ref.authority!=="proposal_only"&&(n.ref.lifecycle==="active"||n.ref.lifecycle==="trusted"||n.ref.lifecycle==="readonly")}a(X,"isGovernedQueryHint");function w(n,e){let t=n.map(r=>h(r,512)).filter(r=>r!==void 0),i=t.join(`
5
5
  `).slice(0,2048);if(t.length!==n.length||h(i,2048)===void 0||G(i)>512)return;let s={content:i,evidenceRefs:p(e.filter(B)).slice(0,3)};return b(s.content,s.evidenceRefs)===void 0?void 0:s}a(w,"buildSafeReminder");function O(n,e=512){return h(n,e)??"[withheld by prompt-safety policy]"}a(O,"promptSafeSelectorText");function B(n){return n.length>0&&n.length<=256&&!/[\r\n\u0000-\u001f\u007f]/.test(n)&&h(n,256)===n}a(B,"isSafeEvidenceRef");function R(n,e){return g(`${n}\0${e}`).slice(0,24)}a(R,"decisionEpoch");function L(n){return g([R(n.decisionRevision,n.throughSequence),...n.triggers].join("\0")).slice(0,24)}a(L,"interventionEpoch");function de(n,e){return Object.freeze({...n,evidence:Object.freeze(n.evidence.map(t=>Object.freeze(Q(t,e)))),...n.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{}})}a(de,"freezeObservation");function Q(n,e){let t=e?.(n)??"inferred";return{...n,requestedGrade:ae(n.requestedGrade,t)}}a(Q,"applySourcePolicy");function ae(n,e){let t=["inferred","observed","corroborated","verified","authoritative"];return t[Math.min(t.indexOf(n),t.indexOf(e))]??"inferred"}a(ae,"lowerEvidenceGrade");function F(n){return JSON.stringify(n)}a(F,"stableObservation");function p(n){return[...new Set(n)]}a(p,"unique");function g(n){return W("sha256").update(n).digest("hex")}a(g,"digest");export{k as a,T as b,A as c,M as d,N as e,Y as f,b as g,ee as h};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Eb as Ke,Fb as Le,Ib as ze,Jb as Je,ke as ge,le as Ge,ne as Xe,oe as Ye,pe as Ze,we as Qe}from"./chunk-5UBP47VJ.js";import{Q as Ne}from"./chunk-UNEC2WXJ.js";import{Ag as B,Bg as we,Cg as Ue,Jg as Ve,Kg as Be,Lg as He,jg as re,mg as De,ng as je,pg as Z,t as fe,tg as me,zg as pe}from"./chunk-72H6JNPN.js";import{a as i}from"./chunk-ONUPGMER.js";import{basename as kr,dirname as vr}from"node:path";import{execFile as Qt}from"node:child_process";import oe from"node:path";import{promisify as en}from"node:util";var tn=en(Qt),nn=1e4,at=2,et=new Set(["write","edit","multi_edit","insert_after_anchor"]),tt=new Set(["read"]);function rn(e,t){if(t.includes("*"))return e;if(e.includes("*"))return t;let n=new Set(t);return e.filter(r=>n.has(r))}i(rn,"intersectWorkflowToolCeilings");var on=/^\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;function an(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)}}i(an,"normalizeWaitTimeoutMs");function he(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}i(he,"hasVerificationWork");function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}i(H,"normalizeWorkspacePath");function ye(e,t){let n=t.gitRoot?oe.resolve(t.gitRoot):void 0,r=oe.isAbsolute(e)&&n?oe.relative(n,oe.resolve(e)):e;return H(r)}i(ye,"normalizeRequiredPath");function sn(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let n={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},r=e.verification.requiredChangedPaths;return{verification:{...n,...r!==void 0&&r.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}i(sn,"resolveVerificationForInput");function cn(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 n=e.readOnly??t??!1;return e.readOnly===n?e:{...e,readOnly:n}}i(cn,"resolveSpawnAgentInput");function st(e){let t=e.trim();return t.length>0&&on.test(t)}i(st,"isPreparatoryOnlyText");function dn(e,t){let n=e.trim(),r=t?.trim();return r&&(n.length===0||st(n))?r:e}i(dn,"selectWorkflowFinalText");async function ie(e,t){return(await tn("git",[...e],{cwd:t,timeout:nn,windowsHide:!0,maxBuffer:4194304})).stdout.toString()}i(ie,"runGit");async function un(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await ie(["rev-parse","--show-toplevel"],t)).trim(),r=await Promise.all([ie(["diff","--name-only","--"],n),ie(["diff","--cached","--name-only","--"],n),ie(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(r.flatMap(a=>a.split(/\r?\n/)).map(H).filter(a=>a.length>0))]}i(un,"listGitChangedFiles");async function ke(e,t){try{return{paths:(await t(e)).map(H).filter(r=>r.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}i(ke,"captureChangedPaths");function ln(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[],readPathById:new Map,succeededReadPaths:[]}}i(ln,"createMutationRecorder");function nt(e){if(e)for(let t of["path","file_path","target_path"]){let n=e[t];if(typeof n=="string"&&n.trim().length>0)return H(n)}}i(nt,"readMutationPath");function fn(e,t){return{...e??{},onToolUseStart:i((n,r)=>{if(et.has(n.name)){t.toolNameById.set(n.id,n.name);let a=nt(n.input);a!==void 0&&t.toolPathById.set(n.id,a)}if(tt.has(n.name)){let a=nt(n.input);a!==void 0&&t.readPathById.set(n.id,a)}e?.onToolUseStart?.(n,r)},"onToolUseStart"),onToolResult:i((n,r)=>{let a=t.toolNameById.get(n.id)??n.name;if(et.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(a);let o=t.toolPathById.get(n.id);o!==void 0&&t.succeededPaths.push(o)}if(tt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){let o=t.readPathById.get(n.id);o!==void 0&&t.succeededReadPaths.push(o)}e?.onToolResult?.(n,r)},"onToolResult")}}i(fn,"wrapEventsForMutationRecording");function ae(e){return[...new Set(e.filter(t=>t.trim().length>0))]}i(ae,"uniqueItems");function rt(e){let t=e.verification;if(!t)return;let n=[],r=new Set(e.before.paths.map(H)),a=ae(e.after.paths.map(H)),o=a.filter(m=>!r.has(m)),s=ae(e.mutationRecorder.succeededToolCalls),d=e.acceptToolMutationEvidence?s:[],g=e.acceptToolMutationEvidence?ae(e.mutationRecorder.succeededPaths.map(H)):[],h=o.length>0||d.length>0,y=t.enforcement??"hard",p=(t.requiredChangedPaths??[]).map(m=>ye(m,e.ctx)),b=ae(e.mutationRecorder.succeededReadPaths.map(m=>ye(m,e.ctx))),v=(t.requiredReadPaths??[]).map(m=>ye(m,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?n.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):h||n.push(e.acceptToolMutationEvidence||s.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&&!h&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of p)!a.includes(m)&&!g.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);for(let m of v)b.includes(m)||n.push(`required review evidence was not read: ${m}`);let W=t.minFinalTextChars;return W!==void 0&&!h&&e.term.finalText.trim().length<W&&n.push(`finalText was shorter than the required ${W} characters`),t.rejectPreparatoryFinalText===!0&&!h&&st(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:y,reasons:n,changedPaths:a,mutationToolCalls:s,mutationEvidence:h,...b.length>0?{readPaths:b}:{}}}i(rt,"evaluateVerification");function ve(e,t){if(t.ok)return e;let r=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(a=>`- ${a}`)].join(`
2
+ import{Eb as Ke,Fb as Le,Ib as ze,Jb as Je,ke as ge,le as Ge,ne as Xe,oe as Ye,pe as Ze,we as Qe}from"./chunk-NCK7ASJL.js";import{Q as Ne}from"./chunk-UNEC2WXJ.js";import{Ag as B,Bg as we,Cg as Ue,Jg as Ve,Kg as Be,Lg as He,jg as re,mg as De,ng as je,pg as Z,t as fe,tg as me,zg as pe}from"./chunk-R3BXINQ2.js";import{a as i}from"./chunk-ONUPGMER.js";import{basename as kr,dirname as vr}from"node:path";import{execFile as Qt}from"node:child_process";import oe from"node:path";import{promisify as en}from"node:util";var tn=en(Qt),nn=1e4,at=2,et=new Set(["write","edit","multi_edit","insert_after_anchor"]),tt=new Set(["read"]);function rn(e,t){if(t.includes("*"))return e;if(e.includes("*"))return t;let n=new Set(t);return e.filter(r=>n.has(r))}i(rn,"intersectWorkflowToolCeilings");var on=/^\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;function an(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)}}i(an,"normalizeWaitTimeoutMs");function he(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}i(he,"hasVerificationWork");function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}i(H,"normalizeWorkspacePath");function ye(e,t){let n=t.gitRoot?oe.resolve(t.gitRoot):void 0,r=oe.isAbsolute(e)&&n?oe.relative(n,oe.resolve(e)):e;return H(r)}i(ye,"normalizeRequiredPath");function sn(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let n={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},r=e.verification.requiredChangedPaths;return{verification:{...n,...r!==void 0&&r.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}i(sn,"resolveVerificationForInput");function cn(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 n=e.readOnly??t??!1;return e.readOnly===n?e:{...e,readOnly:n}}i(cn,"resolveSpawnAgentInput");function st(e){let t=e.trim();return t.length>0&&on.test(t)}i(st,"isPreparatoryOnlyText");function dn(e,t){let n=e.trim(),r=t?.trim();return r&&(n.length===0||st(n))?r:e}i(dn,"selectWorkflowFinalText");async function ie(e,t){return(await tn("git",[...e],{cwd:t,timeout:nn,windowsHide:!0,maxBuffer:4194304})).stdout.toString()}i(ie,"runGit");async function un(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await ie(["rev-parse","--show-toplevel"],t)).trim(),r=await Promise.all([ie(["diff","--name-only","--"],n),ie(["diff","--cached","--name-only","--"],n),ie(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(r.flatMap(a=>a.split(/\r?\n/)).map(H).filter(a=>a.length>0))]}i(un,"listGitChangedFiles");async function ke(e,t){try{return{paths:(await t(e)).map(H).filter(r=>r.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}i(ke,"captureChangedPaths");function ln(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[],readPathById:new Map,succeededReadPaths:[]}}i(ln,"createMutationRecorder");function nt(e){if(e)for(let t of["path","file_path","target_path"]){let n=e[t];if(typeof n=="string"&&n.trim().length>0)return H(n)}}i(nt,"readMutationPath");function fn(e,t){return{...e??{},onToolUseStart:i((n,r)=>{if(et.has(n.name)){t.toolNameById.set(n.id,n.name);let a=nt(n.input);a!==void 0&&t.toolPathById.set(n.id,a)}if(tt.has(n.name)){let a=nt(n.input);a!==void 0&&t.readPathById.set(n.id,a)}e?.onToolUseStart?.(n,r)},"onToolUseStart"),onToolResult:i((n,r)=>{let a=t.toolNameById.get(n.id)??n.name;if(et.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(a);let o=t.toolPathById.get(n.id);o!==void 0&&t.succeededPaths.push(o)}if(tt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){let o=t.readPathById.get(n.id);o!==void 0&&t.succeededReadPaths.push(o)}e?.onToolResult?.(n,r)},"onToolResult")}}i(fn,"wrapEventsForMutationRecording");function ae(e){return[...new Set(e.filter(t=>t.trim().length>0))]}i(ae,"uniqueItems");function rt(e){let t=e.verification;if(!t)return;let n=[],r=new Set(e.before.paths.map(H)),a=ae(e.after.paths.map(H)),o=a.filter(m=>!r.has(m)),s=ae(e.mutationRecorder.succeededToolCalls),d=e.acceptToolMutationEvidence?s:[],g=e.acceptToolMutationEvidence?ae(e.mutationRecorder.succeededPaths.map(H)):[],h=o.length>0||d.length>0,y=t.enforcement??"hard",p=(t.requiredChangedPaths??[]).map(m=>ye(m,e.ctx)),b=ae(e.mutationRecorder.succeededReadPaths.map(m=>ye(m,e.ctx))),v=(t.requiredReadPaths??[]).map(m=>ye(m,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?n.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):h||n.push(e.acceptToolMutationEvidence||s.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&&!h&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of p)!a.includes(m)&&!g.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);for(let m of v)b.includes(m)||n.push(`required review evidence was not read: ${m}`);let W=t.minFinalTextChars;return W!==void 0&&!h&&e.term.finalText.trim().length<W&&n.push(`finalText was shorter than the required ${W} characters`),t.rejectPreparatoryFinalText===!0&&!h&&st(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:y,reasons:n,changedPaths:a,mutationToolCalls:s,mutationEvidence:h,...b.length>0?{readPaths:b}:{}}}i(rt,"evaluateVerification");function ve(e,t){if(t.ok)return e;let r=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(a=>`- ${a}`)].join(`
3
3
  `);return e.trim().length>0?`${e}
4
4
 
5
5
  ${r}`:r}i(ve,"appendVerificationFailure");function ot(){return{ok:!1,enforcement:"warn",reasons:["workflow child reached its iteration limit before satisfying the task"],mutationEvidence:!1}}i(ot,"limitReachedWarningVerification");function mn(e){return e.entry.bundle.readOnly!==!0&&e.entry.repairAttempts<at&&e.term.status==="completed"&&e.verification!==void 0&&e.verification.ok!==!0&&e.verification.enforcement!=="warn"}i(mn,"shouldRepairVerificationFailure");function pn(e){let t=e.verification.reasons.map(r=>`- ${r}`).join(`
@@ -13,7 +13,7 @@ ${s.text}`),rubric:t.rubric??vn}))).text,findings:r,degraded:a}}i(Pn,"runParalle
13
13
  `).trim().replace(/[\t\n\f\r ]+/g," ")}i(j,"normalizeText");function lt(e){return j(e).replace(/\\/g,"/")}i(lt,"normalizeLocation");function se(e){return[...new Set(e.map(j).filter(Boolean))].sort((t,n)=>t<n?-1:t>n?1:0)}i(se,"uniqueSorted");function An(e,t,n){return Mn("sha256").update(`${e}\0${lt(t)}\0${j(n)}`,"utf8").digest("hex")}i(An,"findingId");function ft(e,t,n){if(!t&&n.specVerdict!=="not-verifiable")throw new Error('review result must use specVerdict "not-verifiable" when requirements are absent');return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,findings:n.findings.map(r=>{let a=lt(r.location),o=j(r.claim),s=j(r.evidence);return{findingId:An(e,a,o),severity:r.severity,location:a,claim:o,evidence:s,...r.suggestedFix?{suggestedFix:j(r.suggestedFix)}:{}}}).sort((r,a)=>r.findingId<a.findingId?-1:r.findingId>a.findingId?1:0),unverifiedRequirements:se(n.unverifiedRequirements)}}i(ft,"normalizeScopedReviewResult");var ut={low:0,medium:1,high:2,critical:3};function En(e){return e.reduce((t,n)=>ut[n]>ut[t]?n:t,"low")}i(En,"maxSeverity");function mt(e){if(e.length===0)throw new Error("at least one primary review result is required");let t=new Map;for(let a of e)for(let o of a.findings)t.set(o.findingId,[...t.get(o.findingId)??[],o]);let n=[...t.entries()].map(([a,o])=>({findingId:a,severity:En(o.map(s=>s.severity)),location:o[0].location,claim:o[0].claim,evidence:se(o.map(s=>s.evidence)),suggestedFixes:se(o.flatMap(s=>s.suggestedFix?[s.suggestedFix]:[]))})).sort((a,o)=>a.findingId<o.findingId?-1:a.findingId>o.findingId?1:0);return{specVerdict:e.some(a=>a.specVerdict==="issues")?"issues":e.some(a=>a.specVerdict==="not-verifiable")?"not-verifiable":"compliant",qualityVerdict:e.some(a=>a.qualityVerdict==="needs-fixes")?"needs-fixes":"approved",findings:n,unverifiedRequirements:se(e.flatMap(a=>a.unverifiedRequirements))}}i(mt,"mergeScopedReviewResults");function pt(e,t){let n=new Set(e.findings.map(s=>s.findingId)),r=new Set;for(let s of t.findings){if(!n.has(s.findingId)||r.has(s.findingId))throw new Error("verifier must return every input findingId exactly once");r.add(s.findingId)}if(r.size!==n.size)throw new Error("verifier must return every input findingId exactly once");let a=new Map(t.findings.map(s=>[s.findingId,s])),o=e.findings.flatMap(s=>{let d=a.get(s.findingId);if(d.disposition==="refuted")return[];let g=d.severityReason?.trim(),h=d.effectiveSeverity!==void 0&&!!g;return[{...s,disposition:d.disposition,severity:h?d.effectiveSeverity:s.severity,verificationEvidence:j(d.evidence),...g?{severityReason:j(g)}:{}}]});return{specVerdict:e.specVerdict,qualityVerdict:e.qualityVerdict,unverifiedRequirements:e.unverifiedRequirements,actionable:o,audit:t,unqualifiedApprovalAllowed:o.length===0&&e.unverifiedRequirements.length===0&&e.specVerdict==="compliant"&&e.qualityVerdict==="approved"}}i(pt,"applyFindingVerification");var Wn={type:"object",additionalProperties:!1,required:["summary"],properties:{summary:{type:"string"}}};function gt(e){return[e.packetPath,...e.evidenceChunks.map(t=>t.path)]}i(gt,"evidencePaths");function Fn(e){let t=ge(e,Se);if(t.length>0)throw new Error(`primary reviewer structured result is invalid: ${t.join("; ")}`);return e}i(Fn,"rawReview");function On(e){let t=ge(e,Re);if(t.length>0)throw new Error(`finding verifier structured result is invalid: ${t.join("; ")}`);return e}i(On,"rawVerification");function be(e,t){if(e===null||e.status!=="completed")throw new Error(`${t} did not complete; no verdict was accepted`);if(e.verification!==void 0&&!e.verification.ok)throw new Error(`${t} did not read every required packet path; no verdict was accepted`);return e}i(be,"resultOrThrow");function qn(e,t,n){return["Review one immutable KodaX packet as an independent third-party reviewer.",`Packet manifest: ${e.packetPath}`,...e.evidenceChunks.map(r=>`Evidence chunk: ${r.path}`),`This packet has binding requirements: ${e.requirementsPresent?"yes":"no"}.`,t?"This is the additional high-risk primary. Actively seek a disagreement with the first reader; do not assume it was correct.":"Own both specification and implementation-quality verdicts for this scope.",n.lean?"Also identify unnecessary additions, but never remove validation, security, data-loss protection, accessibility, or requested behavior.":"",n.reviewFocus?`Additional user focus: ${n.reviewFocus}`:"","Read the manifest and every listed chunk with the read tool before deciding.","Begin with the required JSON result. No preamble or process narration.","The findings array contains only actionable defects, never approval evidence or positive observations.","When the scope is compliant and approved with no actionable defect, findings must be empty.","If a named requirement cannot be proven compliant or violated from surfaced evidence, use specVerdict not-verifiable, list it in unverifiedRequirements, and emit no finding for that uncertainty; absence of evidence is not proof of a defect.","If requirements are absent, specVerdict must be not-verifiable."].filter(Boolean).join(`
14
14
  `)}i(qn,"buildScopedReviewPrimaryPrompt");function Cn(e,t){return["Independently attempt to refute every candidate finding in this batch.",`Packet manifest: ${e.packetPath}`,...e.evidenceChunks.map(n=>`Evidence chunk: ${n.path}`),`Canonical candidates: ${JSON.stringify(t.findings)}`,"Read the packet evidence. You may run one focused check after naming the concrete doubt.","Return every findingId exactly once. A severity change requires severityReason.","Begin with the required JSON result; no preamble."].join(`
15
15
  `)}i(Cn,"buildScopedReviewVerificationPrompt");function $n(e){return["Synthesize the structured review results below without rereading packet bodies.","Lead with confirmed findings, keep unresolved findings visibly unresolved, omit refuted findings from the actionable list, and never silently downgrade severity.","Cite locations and state explicitly when no actionable issue was confirmed.",JSON.stringify(e)].join(`
16
- `)}i($n,"buildScopedReviewFinalPrompt");async function wt(e,t,n,r){let a=be(await e.runAgent({name:`${n?"high-risk-":""}primary-${t.partitionKey}`,phase:"primary-review",prompt:qn(t,n,r),scopeSummary:`${t.partitionKey}: ${t.scopePaths.join(", ")}`,constraints:["read every required packet path","return both verdicts","cite evidence at each finding"],readOnly:!0,modelHint:n?"deep":"balanced",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Se,terseResult:!0}),"primary reviewer");return e.log({message:`primary read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"primary",contentHash:t.contentHash}}),Fn(a.structured)}i(wt,"runPrimary");async function _n(e,t,n){if(n.findings.length===0)return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,unverifiedRequirements:n.unverifiedRequirements,actionable:[],audit:{findings:[]},unqualifiedApprovalAllowed:n.unverifiedRequirements.length===0&&n.specVerdict==="compliant"&&n.qualityVerdict==="approved"};let r=be(await e.runAgent({name:`verify-${t.partitionKey}`,phase:"verifier",prompt:Cn(t,n),scopeSummary:`verify ${n.findings.length} candidate finding(s) in ${t.partitionKey}`,constraints:["fresh context","attempt refutation","one disposition per findingId"],readOnly:!0,modelHint:"deep",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Re,terseResult:!0}),"finding verifier");return e.log({message:`verification read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"verification",contentHash:t.contentHash,reason:"candidate findings"}}),pt(n,On(r.structured))}i(_n,"verifyFindings");async function Nn(e,t,n){let r=[await wt(e,t,!1,n)];t.riskFlags.includes("routing-high")&&r.push(await wt(e,t,!0,n));let a=r.map(d=>ft(t.contentHash,t.requirementsPresent,d)),o=mt(a),s=await _n(e,t,o);return e.log({message:`quality gate completed for ${t.partitionKey}`,data:{kind:"review_quality_gate",contentHash:t.contentHash,actionableFindings:s.actionable.length,unresolvedFindings:s.actionable.filter(d=>d.disposition==="unresolved").length,unqualifiedApprovalAllowed:s.unqualifiedApprovalAllowed}}),{contentHash:t.contentHash,result:s}}i(Nn,"reviewPacket");async function Dn(e,t){if(!Array.isArray(t.packets)||t.packets.length===0)throw new Error("scoped-review requires at least one review packet");let n=await e.parallel(t.packets.map(d=>()=>Nn(e,d,t)),{concurrency:4});if(n.some(d=>d===null))throw new Error("one or more scope packets failed review; no final verdict was accepted");let r=n.filter(d=>d!==null);await e.artifact("scoped-review-audit",r);let a=be(await e.runAgent({name:"final-review-synthesis",phase:"final-synthesis",prompt:$n(r),scopeSummary:`cross-scope synthesis for ${r.length} packet(s)`,constraints:["preserve severity","preserve unresolved uncertainty","do not invent evidence"],readOnly:!0,modelHint:"deep",outputSchema:Wn,terseResult:!0}),"final synthesis"),o=a.structured;return{summary:typeof o?.summary=="string"?o.summary:a.finalText,packetResults:r}}i(Dn,"runScopedReview");var ht={meta:{name:"scoped-review",description:"Review immutable scope packets once, verify only candidate findings, then synthesize.",readOnly:!0,phases:["primary-review","verifier","final-synthesis"],maxAgents:64,maxConcurrency:4},run:Dn};function yt(e){return{meta:e.meta,run:i((t,n)=>e.run(t,n),"run")}}i(yt,"erase");var kt=[yt(dt),yt(ht)];function vt(e){return kt.find(t=>t.meta.name===e)}i(vt,"getBuiltinWorkflow");function no(){return kt.map(e=>e.meta)}i(no,"listBuiltinWorkflows");import{mkdir as Tt,readdir as jn,readFile as Q,rename as Un,unlink as Pe,writeFile as Me}from"node:fs/promises";import{basename as Vn,dirname as Ie,join as K}from"node:path";import{pathToFileURL as Bn}from"node:url";var It=[".workflow.json",".ts",".mjs",".js"],ee="0.7.49";function Pt(){return"0.7.89"}i(Pt,"currentKodaxWorkflowVersion");function Hn(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}i(Hn,"executionForPath");function Kn(e){let t=It.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}i(Kn,"stripWorkflowSuffix");function Ae(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,80);if(!t||t==="."||t==="..")throw new Error("workflow name must contain at least one safe filename character");return t}i(Ae,"safeWorkflowName");function Ee(e){return typeof e=="object"&&e!==null}i(Ee,"isRecord");function xt(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}i(xt,"readRequiredString");async function St(e,t){if(!e)return[];let n;try{n=await jn(e)}catch{return[]}let r=new Map;for(let a of It)for(let o of n){if(!o.endsWith(a))continue;let s=Kn(o);if(!s||s.length===0||r.has(s))continue;let d=K(e,o);r.set(s,{name:s,path:d,source:t,execution:Hn(d)})}return[...r.values()]}i(St,"scanDir");async function te(e){let t=await St(e.personal,"personal"),n=await St(e.project,"project"),r=new Map;for(let a of t)r.set(a.name,a);for(let a of n)r.set(a.name,a);return[...r.values()].sort((a,o)=>a.name.localeCompare(o.name))}i(te,"discoverSavedWorkflows");function Ln(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}i(Ln,"isWorkflowModule");function zn(e){let t=e.default;if(Ln(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}i(zn,"normalizeWorkflowModule");function Jn(e){let t=JSON.parse(e);if(!Ee(t))throw new Error("generated workflow file must be an object");if(t.format!==void 0&&t.format!=="kodax.workflow")throw new Error(`unsupported workflow capsule format: ${String(t.format)}`);if(t.format==="kodax.workflow"){let a=pe(t);return{manifest:a.manifest,source:a.source,capsule:a,legacy:!1}}let n=t.source;if(typeof n!="string"||n.trim().length===0)throw new Error("generated workflow file source must be a non-empty string");let r=Z(t.manifest);return{manifest:r,source:n,capsule:B({minKodaxVersion:ee,manifest:r,source:n}),legacy:!0}}i(Jn,"parseGeneratedWorkflowFile");async function We(e){let t=Jn(await Q(e,"utf8"));return t.capsule??B({minKodaxVersion:ee,manifest:t.manifest,source:t.source})}i(We,"loadSavedWorkflowCapsule");async function Mt(e){if(e.endsWith(".workflow.json"))return we(await We(e));let t=await import(Bn(e).href);return zn(t)}i(Mt,"loadSavedWorkflow");function Fe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}i(Fe,"deriveRequirements");function ce(e,t){me(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}i(ce,"assertGeneratedCapsuleSource");async function Gn(e){let t=Ae(e.name),n=Z(e.manifest);ce(n,e.source);let r=e.requires??Fe(n),a=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await Tt(e.dir,{recursive:!0});let o=K(e.dir,`${t}.workflow.json`);return await Me(o,`${JSON.stringify(a,null,2)}
16
+ `)}i($n,"buildScopedReviewFinalPrompt");async function wt(e,t,n,r){let a=be(await e.runAgent({name:`${n?"high-risk-":""}primary-${t.partitionKey}`,phase:"primary-review",prompt:qn(t,n,r),scopeSummary:`${t.partitionKey}: ${t.scopePaths.join(", ")}`,constraints:["read every required packet path","return both verdicts","cite evidence at each finding"],readOnly:!0,modelHint:n?"deep":"balanced",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Se,terseResult:!0}),"primary reviewer");return e.log({message:`primary read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"primary",contentHash:t.contentHash}}),Fn(a.structured)}i(wt,"runPrimary");async function _n(e,t,n){if(n.findings.length===0)return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,unverifiedRequirements:n.unverifiedRequirements,actionable:[],audit:{findings:[]},unqualifiedApprovalAllowed:n.unverifiedRequirements.length===0&&n.specVerdict==="compliant"&&n.qualityVerdict==="approved"};let r=be(await e.runAgent({name:`verify-${t.partitionKey}`,phase:"verifier",prompt:Cn(t,n),scopeSummary:`verify ${n.findings.length} candidate finding(s) in ${t.partitionKey}`,constraints:["fresh context","attempt refutation","one disposition per findingId"],readOnly:!0,modelHint:"deep",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Re,terseResult:!0}),"finding verifier");return e.log({message:`verification read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"verification",contentHash:t.contentHash,reason:"candidate findings"}}),pt(n,On(r.structured))}i(_n,"verifyFindings");async function Nn(e,t,n){let r=[await wt(e,t,!1,n)];t.riskFlags.includes("routing-high")&&r.push(await wt(e,t,!0,n));let a=r.map(d=>ft(t.contentHash,t.requirementsPresent,d)),o=mt(a),s=await _n(e,t,o);return e.log({message:`quality gate completed for ${t.partitionKey}`,data:{kind:"review_quality_gate",contentHash:t.contentHash,actionableFindings:s.actionable.length,unresolvedFindings:s.actionable.filter(d=>d.disposition==="unresolved").length,unqualifiedApprovalAllowed:s.unqualifiedApprovalAllowed}}),{contentHash:t.contentHash,result:s}}i(Nn,"reviewPacket");async function Dn(e,t){if(!Array.isArray(t.packets)||t.packets.length===0)throw new Error("scoped-review requires at least one review packet");let n=await e.parallel(t.packets.map(d=>()=>Nn(e,d,t)),{concurrency:4});if(n.some(d=>d===null))throw new Error("one or more scope packets failed review; no final verdict was accepted");let r=n.filter(d=>d!==null);await e.artifact("scoped-review-audit",r);let a=be(await e.runAgent({name:"final-review-synthesis",phase:"final-synthesis",prompt:$n(r),scopeSummary:`cross-scope synthesis for ${r.length} packet(s)`,constraints:["preserve severity","preserve unresolved uncertainty","do not invent evidence"],readOnly:!0,modelHint:"deep",outputSchema:Wn,terseResult:!0}),"final synthesis"),o=a.structured;return{summary:typeof o?.summary=="string"?o.summary:a.finalText,packetResults:r}}i(Dn,"runScopedReview");var ht={meta:{name:"scoped-review",description:"Review immutable scope packets once, verify only candidate findings, then synthesize.",readOnly:!0,phases:["primary-review","verifier","final-synthesis"],maxAgents:64,maxConcurrency:4},run:Dn};function yt(e){return{meta:e.meta,run:i((t,n)=>e.run(t,n),"run")}}i(yt,"erase");var kt=[yt(dt),yt(ht)];function vt(e){return kt.find(t=>t.meta.name===e)}i(vt,"getBuiltinWorkflow");function no(){return kt.map(e=>e.meta)}i(no,"listBuiltinWorkflows");import{mkdir as Tt,readdir as jn,readFile as Q,rename as Un,unlink as Pe,writeFile as Me}from"node:fs/promises";import{basename as Vn,dirname as Ie,join as K}from"node:path";import{pathToFileURL as Bn}from"node:url";var It=[".workflow.json",".ts",".mjs",".js"],ee="0.7.49";function Pt(){return"0.7.90"}i(Pt,"currentKodaxWorkflowVersion");function Hn(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}i(Hn,"executionForPath");function Kn(e){let t=It.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}i(Kn,"stripWorkflowSuffix");function Ae(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,80);if(!t||t==="."||t==="..")throw new Error("workflow name must contain at least one safe filename character");return t}i(Ae,"safeWorkflowName");function Ee(e){return typeof e=="object"&&e!==null}i(Ee,"isRecord");function xt(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}i(xt,"readRequiredString");async function St(e,t){if(!e)return[];let n;try{n=await jn(e)}catch{return[]}let r=new Map;for(let a of It)for(let o of n){if(!o.endsWith(a))continue;let s=Kn(o);if(!s||s.length===0||r.has(s))continue;let d=K(e,o);r.set(s,{name:s,path:d,source:t,execution:Hn(d)})}return[...r.values()]}i(St,"scanDir");async function te(e){let t=await St(e.personal,"personal"),n=await St(e.project,"project"),r=new Map;for(let a of t)r.set(a.name,a);for(let a of n)r.set(a.name,a);return[...r.values()].sort((a,o)=>a.name.localeCompare(o.name))}i(te,"discoverSavedWorkflows");function Ln(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}i(Ln,"isWorkflowModule");function zn(e){let t=e.default;if(Ln(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}i(zn,"normalizeWorkflowModule");function Jn(e){let t=JSON.parse(e);if(!Ee(t))throw new Error("generated workflow file must be an object");if(t.format!==void 0&&t.format!=="kodax.workflow")throw new Error(`unsupported workflow capsule format: ${String(t.format)}`);if(t.format==="kodax.workflow"){let a=pe(t);return{manifest:a.manifest,source:a.source,capsule:a,legacy:!1}}let n=t.source;if(typeof n!="string"||n.trim().length===0)throw new Error("generated workflow file source must be a non-empty string");let r=Z(t.manifest);return{manifest:r,source:n,capsule:B({minKodaxVersion:ee,manifest:r,source:n}),legacy:!0}}i(Jn,"parseGeneratedWorkflowFile");async function We(e){let t=Jn(await Q(e,"utf8"));return t.capsule??B({minKodaxVersion:ee,manifest:t.manifest,source:t.source})}i(We,"loadSavedWorkflowCapsule");async function Mt(e){if(e.endsWith(".workflow.json"))return we(await We(e));let t=await import(Bn(e).href);return zn(t)}i(Mt,"loadSavedWorkflow");function Fe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}i(Fe,"deriveRequirements");function ce(e,t){me(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}i(ce,"assertGeneratedCapsuleSource");async function Gn(e){let t=Ae(e.name),n=Z(e.manifest);ce(n,e.source);let r=e.requires??Fe(n),a=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await Tt(e.dir,{recursive:!0});let o=K(e.dir,`${t}.workflow.json`);return await Me(o,`${JSON.stringify(a,null,2)}
17
17
  `,"utf8"),{name:t,path:o,source:"project",execution:"capability-generated"}}i(Gn,"saveGeneratedWorkflow");async function Rt(e,t){await Me(e,`${JSON.stringify(t,null,2)}
18
18
  `,"utf8")}i(Rt,"writeCapsuleFile");async function Xn(e){try{return await Q(e,"utf8"),!0}catch{return!1}}i(Xn,"fileExists");async function uo(e){let t=(await te(e.dirs)).filter(d=>d.name===e.name).filter(d=>e.source===void 0||d.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be renamed");let r=Ae(e.newName),a=K(Ie(n.path),`${r}.workflow.json`);if(a!==n.path&&await Xn(a))throw new Error(`saved workflow already exists: ${r}`);let o=await We(n.path);ce(o.manifest,o.source);let s=B({minKodaxVersion:o.minKodaxVersion,manifest:{...o.manifest,name:r},source:o.source,...o.intent!==void 0?{intent:o.intent}:{},...o.inputs!==void 0?{inputs:o.inputs}:{},...o.requires!==void 0?{requires:o.requires}:{},...o.provenance!==void 0?{provenance:o.provenance}:{}});return await Me(a,`${JSON.stringify(s,null,2)}
19
19
  `,"utf8"),a!==n.path&&await Pe(n.path),{name:r,path:a,source:n.source,execution:"capability-generated"}}i(uo,"renameSavedWorkflow");async function lo(e){let t=(await te(e.dirs)).filter(r=>r.name===e.name).filter(r=>e.source===void 0||r.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be deleted");return await Pe(n.path),n}i(lo,"deleteSavedWorkflow");async function fo(e){let t=Ae(e.name),n=(await te(e.dirs)).filter(v=>v.name===t).filter(v=>e.savedSource===void 0||v.source===e.savedSource);if(n.length===0)throw new Error(`saved workflow not found: ${t}`);if(n.length>1)throw new Error(`ambiguous saved workflow name: ${t}`);let r=n[0];if(!r.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be replaced");let a=Z({...e.manifest,name:t});ce(a,e.source);let o=e.requires??Fe(a),s=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:a,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...o!==void 0?{requires:o}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}}),d=await We(r.path),g=new Date().toISOString().replace(/[:.]/g,"-"),h=K(Ie(r.path),".revisions",t),y=`${g}-${process.hrtime.bigint().toString(36)}`,p=K(h,`${t}-${y}.workflow.json`),b=K(Ie(r.path),`.${t}.${process.pid}.${Date.now().toString(36)}.tmp`);await Tt(h,{recursive:!0}),await Rt(p,d);try{await Rt(b,s),await Un(b,r.path)}catch(v){try{await Pe(b)}catch{}throw v}return{name:t,path:r.path,source:r.source,execution:"capability-generated",previousPath:p}}i(fo,"replaceSavedWorkflow");function Yn(e){if(!Ee(e))return;let t=e.request;if(typeof t=="string"&&t.trim().length>0)return t;let n=e.question;if(typeof n=="string"&&n.trim().length>0)return n}i(Yn,"readOptionalOriginalRequest");function At(e){return Zn(e)}i(At,"buildCapsuleFromRun");async function Zn(e){let t=JSON.parse(await Q(K(e.runDir,"run.json"),"utf8"));if(!Ee(t))throw new Error("workflow run.json must be an object");let n=xt(t,"scriptSnapshotPath"),r=xt(t,"manifestSnapshotPath"),a=await Q(n,"utf8"),o=Z(JSON.parse(await Q(r,"utf8")));ce(o,a);let s=typeof t.runId=="string"&&t.runId.length>0?t.runId:Vn(e.runDir),d=Yn(t.args),g=Fe(o),h=Ue(o,d!==void 0?{originalRequest:d}:{}),y={description:"Provide new workflow args matching the generated request shape.",..."args"in t?{examples:[t.args]}:{}};return B({minKodaxVersion:ee,manifest:o,source:a,intent:h,inputs:y,...g!==void 0?{requires:g}:{},provenance:{fromRunId:s,createdAt:new Date().toISOString(),kodaxVersion:Pt()}})}i(Zn,"readCapsuleFromRun");async function mo(e){let t=await At(e);return{capsule:t,module:we(t)}}i(mo,"loadGeneratedWorkflowFromRun");async function po(e){let t=await At(e);return Gn({dir:e.targetDir,name:e.name,manifest:t.manifest,source:t.source,...t.intent!==void 0?{intent:t.intent}:{},...t.inputs!==void 0?{inputs:t.inputs}:{},...t.requires!==void 0?{requires:t.requires}:{},...t.provenance!==void 0?{provenance:t.provenance}:{},minKodaxVersion:t.minKodaxVersion})}i(po,"saveGeneratedWorkflowFromRun");function U(e,t,n,r){e.push({severity:t,requirement:n,message:r})}i(U,"addRequirementIssue");function bt(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e.trim());if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}i(bt,"parseSemver");function Qn(e,t){for(let n=0;n<3;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}i(Qn,"compareSemver");function er(e,t,n){let r=bt(t),a=bt(n);if(!r){U(e,"error","kodax:min-version",`workflow minKodaxVersion is not valid semver: ${t}`);return}if(!a){U(e,"warning","kodax:min-version",`cannot verify workflow minKodaxVersion ${t}; current version is unknown`);return}Qn(a,r)<0&&U(e,"error","kodax:min-version",`workflow requires KodaX >= ${t}, current version is ${n}`)}i(er,"addMinVersionIssue");function Te(e,t,n,r){if(!n)return;if(!r){for(let o of n)U(e,"warning",`${t}:${o}`,`workflow requires ${t}:${o}, but no ${t} inventory was provided`);return}let a=new Set(r);for(let o of n)a.has(o)||U(e,"error",`${t}:${o}`,`missing required workflow ${t}: ${o}`)}i(Te,"addMissingItems");function wo(e,t={}){let n=pe(e),r=[],a=n.requires;er(r,n.minKodaxVersion,t.kodaxVersion??Pt()),a?.environment?.includes("git-repo")&&t.isGitRepo===!1&&U(r,"error","environment:git-repo","workflow requires a git repository"),a?.environment?.includes("worktree-capable")&&t.worktreeCapable===!1&&U(r,"error","environment:worktree-capable","workflow may request git worktree isolation");try{me(n.source,{filename:`${n.manifest.name}.workflow.js`,requireAsyncRun:!0})}catch(o){let s=o instanceof Error?o.message:String(o);U(r,"error","workflow:source",s)}return Te(r,"tools",a?.tools,t.availableTools),Te(r,"mcp",a?.mcp,t.availableMcp),Te(r,"skills",a?.skills,t.availableSkills),{ok:!r.some(o=>o.severity==="error"),issues:r}}i(wo,"preflightWorkflowCapsule");function nr(e){return{project:Et(e,".kodax","workflows"),personal:Et(tr(),".kodax","workflows")}}i(nr,"defaultSavedWorkflowDirs");async function rr(e,t){let r=(await te(t)).find(a=>a.name===e);if(r)return Mt(r.path)}i(rr,"resolveSavedByName");function Wt(e){let t=nr(e);return async n=>vt(n)??await rr(n,t)}i(Wt,"createNestedWorkflowResolver");import{existsSync as or,mkdirSync as ir,readFileSync as ar,writeFileSync as Ft}from"node:fs";import{join as ne}from"node:path";var Ot="results";function qt(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}i(qt,"safeKey");function Ct(e,t){let n=ne(e,t);if(or(n))try{return JSON.parse(ar(n,"utf8"))}catch{return}}i(Ct,"readResult");function $t(e,t={}){let n=ne(e,Ot);ir(n,{recursive:!0});let r=t.readFrom?ne(t.readFrom,Ot):void 0;return{get:i(a=>{let o=`${qt(a)}.json`,s=Ct(n,o);if(s!==void 0)return s;if(r===void 0)return;let d=Ct(r,o);if(d!==void 0){try{Ft(ne(n,o),JSON.stringify(d),"utf8")}catch{}return d}},"get"),set:i((a,o)=>{try{Ft(ne(n,`${qt(a)}.json`),JSON.stringify(o),"utf8")}catch{}},"set")}}i($t,"createFsResultCache");import{mkdirSync as sr,appendFileSync as cr,writeFileSync as ue}from"node:fs";import{join as J}from"node:path";function de(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}i(de,"record");function F(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0}i(F,"finiteNumber");function _t(e){let t=new Map,n=new Set,r=[],a=[],o=new Set,s=[],d=[],g=0,h=0,y=0,p=0,b=0,v=0,W=0,m=0,T={},$=[];for(let C of e){let M=C.data??{};if(C.type==="agent_spawned"){let u=typeof M.taskId=="string"?M.taskId:void 0;u&&t.set(u,M),M.role==="primary-review"&&(v+=1);let w=typeof M.role=="string"?M.role:"agent",S=typeof M.requestedTier=="string"?M.requestedTier:"inherited",I=`${w}/${S}`;T[I]=(T[I]??0)+1;continue}if(C.type==="agent_completed"||C.type==="agent_unverified"||C.type==="agent_failed"){let u=typeof M.taskId=="string"?M.taskId:void 0;if(!u||n.has(u))continue;n.add(u);let w=de(M.usage);!w||typeof w.totalTokens!="number"?typeof t.get(u)?.externalTarget=="string"?a.push(u):r.push(u):(g+=F(w.totalTokens),h+=F(w.inputTokens),y+=F(w.cacheReadTokens??w.cachedReadTokens),p+=F(w.outputTokens));let S=de(M.digestUsage);b+=F(S?.totalTokens),h+=F(S?.inputTokens),p+=F(S?.outputTokens),y+=F(S?.cacheReadTokens??S?.cachedReadTokens),W+=F(M.iterations);continue}if(C.type==="agent_summary_updated"){let u=de(M.usage),w=M.summaryKind;if((w==="digest"||w==="digest-failed")&&u){let S=F(u.totalTokens);g+=S,b+=S,h+=F(u.inputTokens),p+=F(u.outputTokens),y+=F(u.cacheReadTokens??u.cachedReadTokens)}continue}if(C.type!=="workflow_log")continue;let f=de(M.data);if(f?.kind==="review_quality_gate"&&typeof f.contentHash=="string"){$.push({contentHash:f.contentHash,actionableFindings:F(f.actionableFindings),unresolvedFindings:F(f.unresolvedFindings),unqualifiedApprovalAllowed:f.unqualifiedApprovalAllowed===!0});continue}if(f?.kind!=="review_packet_read"||typeof f.contentHash!="string")continue;let l={contentHash:f.contentHash,...typeof f.reason=="string"?{reason:f.reason}:{}};f.role==="primary"?(o.has(f.contentHash)&&(m+=1),o.add(f.contentHash)):f.role==="verification"?s.push(l):f.role==="synthesis"&&d.push(l)}for(let C of t.keys())n.has(C)||r.push(C);let G=[...new Set(r)].sort();return{totalModelTokens:g,inputTokens:h,cacheReadTokens:y,outputTokens:p,digestTokens:b,agentStarts:t.size,childTurns:W,agentStartsByRoleTier:T,primaryReviewStarts:v,duplicatePrimaryPacketReads:m,verificationPacketReads:s,synthesisPacketReads:d,reviewWaves:v>0?1:0,fixWaves:0,rereviewWaves:0,qualityGateOutcomes:$,tokenCoverage:{ok:G.length===0,missingTaskIds:G},excludedExternalTaskIds:[...new Set(a)].sort()}}i(_t,"buildWorkflowCostReport");function dr(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120);return t.length>0?t:"artifact"}i(dr,"safeWorkflowArtifactName");function Nt(e,t={}){let n=t.now??(()=>Date.now()),r=J(e,"artifacts");sr(r,{recursive:!0});let a=J(e,"events.jsonl");return{runDir:e,onEvent:i(o=>{cr(a,`${JSON.stringify({...o,ts:n()})}
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{ga as Se,ia as Ce}from"./chunk-A63MGLH6.js";import{Aa as Ee,Ba as R,C as B,Ea as Z,F as q,G as me,H as J,Pa as be,Ua as xe,oa as he,pa as ge,q as pe,qa as ve,ra as ye,sa as we,ta as Y}from"./chunk-UNEC2WXJ.js";import{Ia as Pe,Qa as ke}from"./chunk-72H6JNPN.js";import{a as r}from"./chunk-ONUPGMER.js";import m from"fs";import h from"path";import{exec as yt,spawnSync as wt}from"child_process";import{promisify as Et}from"util";import{fileURLToPath as bt}from"url";var Q="en";function Je(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}r(Je,"detectSystemLocale");function Me(e){if(!e||e==="auto"){Q=Je();return}Q=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}r(Me,"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"},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"}};function qt(e,t){let o=_e[Q][e]??_e.en[e]??e;if(t)for(let[i,s]of Object.entries(t))o=o.replace(`{${i}}`,String(s));return o}r(qt,"t");var Ae={core:`// Split configs: ~/.kodax/integrations/mcp.json, extensions.json, and a2a.json.
2
+ import{ga as Se,ia as Ce}from"./chunk-ZACJCRHT.js";import{Aa as Ee,Ba as R,C as B,Ea as Z,F as q,G as me,H as J,Pa as be,Ua as xe,oa as he,pa as ge,q as pe,qa as ve,ra as ye,sa as we,ta as Y}from"./chunk-UNEC2WXJ.js";import{Ia as Pe,Qa as ke}from"./chunk-R3BXINQ2.js";import{a as r}from"./chunk-ONUPGMER.js";import m from"fs";import h from"path";import{exec as yt,spawnSync as wt}from"child_process";import{promisify as Et}from"util";import{fileURLToPath as bt}from"url";var Q="en";function Je(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}r(Je,"detectSystemLocale");function Me(e){if(!e||e==="auto"){Q=Je();return}Q=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}r(Me,"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"},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"}};function qt(e,t){let o=_e[Q][e]??_e.en[e]??e;if(t)for(let[i,s]of Object.entries(t))o=o.replace(`{${i}}`,String(s));return o}r(qt,"t");var Ae={core:`// Split configs: ~/.kodax/integrations/mcp.json, extensions.json, and a2a.json.
3
3
  // KodaX core configuration template.
4
4
  // Copy only the fields you need to ~/.kodax/config.json (strict JSON).
5
5
  // MCP, A2A, and Extensions live in ~/.kodax/integrations/*.json; use
@@ -275,4 +275,4 @@ import{ga as Se,ia as Ce}from"./chunk-A63MGLH6.js";import{Aa as Ee,Ba as R,C as
275
275
  }
276
276
  `};function Oe(e){return Ae[e]}r(Oe,"getConfigTemplate");import{closeSync as ne,existsSync as d,fsyncSync as Le,linkSync as rt,mkdirSync as re,openSync as ie,readFileSync as Ne,renameSync as $e,statSync as it,unlinkSync as j,watch as st,writeFileSync as je}from"node:fs";import{createHash as at}from"node:crypto";import f from"node:path";import{closeSync as Ye,mkdirSync as Ze,openSync as Qe,rmSync as et}from"node:fs";import tt from"node:path";var ee=class extends Error{static{r(this,"CoreConfigWriteConflictError")}constructor(t){super(`Core configuration is being changed by another KodaX writer: ${t}`),this.name="CoreConfigWriteConflictError"}};function nt(e){return`${e}.write.lock`}r(nt,"coreConfigWriteLockPath");function ot(e){if(!(!(e instanceof Error)||!("code"in e)))return typeof e.code=="string"?e.code:void 0}r(ot,"errorCode");function E(e,t){Ze(tt.dirname(e),{recursive:!0,mode:448});let n=nt(e),o;try{o=Qe(n,"wx",384)}catch(i){throw ot(i)==="EEXIST"?new ee(e):new Error(`Failed to acquire the core configuration write lock: ${e}`,{cause:i})}try{return t()}finally{Ye(o),et(n,{force:!0})}}r(E,"withCoreConfigWriteLock");var k=class extends Error{static{r(this,"IntegrationConfigConflictError")}constructor(t,n,o){super(`Integration configuration revision changed for ${f.basename(t)} (expected ${n??"missing"}, actual ${o??"missing"}).`),this.name="IntegrationConfigConflictError"}},ct={mcp:"mcp.json",a2a:"a2a.json",extensions:"extensions.json"},lt=new Set(["type","command","args","cwd","env","url","headers","connect","startupTimeoutMs","requestTimeoutMs","auth"]);function P(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}r(P,"isRecord");function b(e,t){if(!P(e))throw new Error(`${t} must be an object.`);return e}r(b,"requireRecord");function K(e,t,n){let o=Object.keys(e).find(i=>!t.has(i));if(o!==void 0)throw new Error(`${n} has unknown field "${o}".`)}r(K,"assertNoUnknownKeys");function Ke(e,t){if(e.version!==1)throw new Error(`${t} version must be 1.`)}r(Ke,"requireVersionOne");function Ie(e,t){let n=b(e,t);for(let[o,i]of Object.entries(n))if(o.trim().length===0||typeof i!="string")throw new Error(`${t} must contain non-empty string keys and string values.`);return structuredClone(n)}r(Ie,"requireStringMap");function oe(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())}r(oe,"requireStringArray");function te(e,t){if(e!==void 0&&(!Number.isFinite(e)||Number(e)<=0))throw new Error(`${t} must be a positive number.`)}r(te,"validatePositiveNumber");function dt(e,t){if(e.trim().length===0)throw new Error("MCP server names must not be empty.");let n=b(t,`MCP server "${e}"`);K(n,lt,`MCP server "${e}"`);let o=n.type??"stdio";if(!["stdio","sse","streamable-http","http"].includes(String(o)))throw new Error(`MCP server "${e}" has an unsupported transport type.`);if(o==="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(o)} transport requires url.`);if(n.args!==void 0&&oe(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&&Ie(n.env,`MCP server "${e}" env`),n.headers!==void 0&&Ie(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(te(n.startupTimeoutMs,`MCP server "${e}" startupTimeoutMs`),te(n.requestTimeoutMs,`MCP server "${e}" requestTimeoutMs`),n.auth!==void 0){let i=b(n.auth,`MCP server "${e}" auth`);if(K(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&&oe(i.scopes,`MCP server "${e}" auth.scopes`),te(i.redirectPort,`MCP server "${e}" auth.redirectPort`)}return structuredClone(n)}r(dt,"parseMcpServer");function S(e){let t=b(e,"MCP integration config");K(t,new Set(["version","servers"]),"MCP integration config"),Ke(t,"MCP integration config");let n=b(t.servers,"MCP integration config servers"),o={};for(let[i,s]of Object.entries(n))o[i]=dt(i,s);return{version:1,servers:o}}r(S,"parseMcpIntegrationDocument");function C(e){let t=b(e,"Extensions integration config");K(t,new Set(["version","paths"]),"Extensions integration config"),Ke(t,"Extensions integration config");let n=oe(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}}r(C,"parseExtensionsIntegrationDocument");function _(e,t){return f.join(f.resolve(t),"integrations",ct[e])}r(_,"resolveIntegrationConfigPath");function A(e){return f.join(f.resolve(e),"config.json")}r(A,"coreConfigPath");function Xe(e){return at("sha256").update(e).digest("hex")}r(Xe,"hashText");function se(e){let t=Ne(e,"utf8");try{return{raw:t,value:JSON.parse(t)}}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Invalid JSON: ${o}`)}}r(se,"readJsonFile");function M(e){return{domain:e.domain,source:e.source,path:e.path,revision:Xe(e.raw),document:structuredClone(e.document),loadedAt:new Date().toISOString()}}r(M,"snapshot");function X(e){let t=A(e);return d(t)?b(se(t).value,"Core config"):{}}r(X,"readCoreConfig");function F(e){let t=_("mcp",e);if(d(t)){let s=se(t);return M({domain:"mcp",source:"user",path:t,raw:s.raw,document:S(s.value)})}let n=A(e),o=X(e).mcpServers,i=S({version:1,servers:o===void 0?{}:o});return M({domain:"mcp",source:o===void 0?"default":"legacy-user",path:o===void 0?t:n,raw:JSON.stringify(i),document:i})}r(F,"readMcpIntegration");function U(e){let t=_("extensions",e);if(d(t)){let s=se(t);return M({domain:"extensions",source:"user",path:t,raw:s.raw,document:C(s.value)})}let n=A(e),o=X(e).extensions,i=C({version:1,paths:o===void 0?[]:o});return M({domain:"extensions",source:o===void 0?"default":"legacy-user",path:o===void 0?t:n,raw:JSON.stringify(i),document:i})}r(U,"readExtensionsIntegration");function ut(e){if(!P(e))return[];let t=[],n=/(token|secret|password|api[_-]?key|authorization)/i;for(let[o,i]of Object.entries(e))if(P(i))for(let s of["env","headers"]){let a=i[s];if(P(a))for(let[c,l]of Object.entries(a))n.test(c)&&typeof l=="string"&&!l.startsWith("${env:")&&t.push(`MCP server "${o}" ${s}.${c} may contain a literal secret.`)}return t}r(ut,"likelySecretWarnings");function ft(e){let t=X(e),n=_("mcp",e),o=_("extensions",e),i=t.mcpServers,s=t.extensions,a=P(i)?Object.keys(i).length:0,c=Array.isArray(s)?s.length:0,l=r((g,L,N)=>d(g)?{action:"none",entries:L,destination:g,reason:"destination-exists"}:N?{action:"create",entries:L,destination:g}:{action:"none",entries:0,destination:g,reason:"legacy-absent"},"domainPlan");return{mcp:l(n,a,i!==void 0),extensions:l(o,c,s!==void 0),warnings:ut(i)}}r(ft,"planLegacyIntegrationMigration");function pt(e,t){let n=A(e);re(f.dirname(n),{recursive:!0,mode:448});let o=`${n}.${process.pid}.${Date.now()}.tmp`,i=ie(o,"wx",384);try{je(i,`${JSON.stringify(t,null,2)}
277
277
  `,"utf8"),Le(i)}finally{ne(i)}try{$e(o,n)}catch(s){throw d(o)&&j(o),new Error("Failed to atomically clean legacy integration fields.",{cause:s})}}r(pt,"writeCoreConfigAtomically");function ln(e){return E(A(e.configHome),()=>mt(e))}r(ln,"migrateLegacyIntegrationConfig");function mt(e){let t=ft(e.configHome),n=X(e.configHome),o=t.mcp.action==="create"?S({version:1,servers:P(n.mcpServers)?n.mcpServers:{}}):void 0,i=t.extensions.action==="create"?C({version:1,paths:Array.isArray(n.extensions)?n.extensions:[]}):void 0,s=[];if(o)try{T({domain:"mcp",configHome:e.configHome,expectedRevision:null,document:o,validate:S}),s.push("mcp")}catch(c){if(!(c instanceof k))throw c}if(i)try{T({domain:"extensions",configHome:e.configHome,expectedRevision:null,document:i,validate:C}),s.push("extensions")}catch(c){if(!(c instanceof k))throw c}let a=!1;if(e.cleanupLegacy&&d(A(e.configHome))){let c={...n};d(t.mcp.destination)&&delete c.mcpServers,d(t.extensions.destination)&&delete c.extensions,ht(n,c)||(pt(e.configHome,c),a=!0)}return{...t,applied:s,cleanedLegacy:a}}r(mt,"migrateLegacyIntegrationConfigUnlocked");function ht(e,t){return JSON.stringify(e)===JSON.stringify(t)}r(ht,"isDeepStrictEqualForConfig");function Re(e){return d(e)?Xe(Ne(e,"utf8")):void 0}r(Re,"currentUserRevision");function gt(e){let t=`${e}.lock`;try{return{fd:ie(t,"wx",384),path:t}}catch(n){throw new Error(`Integration configuration is busy: ${f.basename(e)}`,{cause:n})}}r(gt,"acquireWriteLock");function T(e){let t=_(e.domain,e.configHome),n=e.validate(e.document);re(f.dirname(t),{recursive:!0,mode:448});let o=gt(t);try{let i=Re(t),s=e.expectedRevision===null?void 0:e.expectedRevision;if(e.expectedRevision!==void 0&&i!==s)throw new k(t,s,i);let a=`${JSON.stringify(n,null,2)}
278
- `,c=`${t}.${process.pid}.${Date.now()}.tmp`,l=ie(c,"wx",384);try{je(l,a,"utf8"),Le(l)}finally{ne(l)}try{e.expectedRevision===null?(rt(c,t),j(c)):$e(c,t)}catch(g){throw d(c)&&j(c),e.expectedRevision===null&&d(t)?new k(t,void 0,Re(t)):new Error(`Failed to atomically replace ${f.basename(t)}.`,{cause:g})}return M({domain:e.domain,source:"user",path:t,raw:a,document:n})}finally{ne(o.fd),d(o.path)&&j(o.path)}}r(T,"writeIntegrationDocument");function vt(e){if(!d(e))return"missing";let t=it(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}r(vt,"metadataSignature");function Te(e){return e.map(t=>`${t}:${vt(t)}`).join("|")}r(Te,"observationSignature");function $(e,t){return{code:e,message:t,time:new Date().toISOString()}}r($,"safeDiagnostic");var De=class{static{r(this,"IntegrationConfigController")}#u;#n;#r;#a;#m;#f;#p;#e;#t;#c;#l;#h="";#s=[];#o;#i;#g=Promise.resolve();#d=new Set;constructor(t){this.#u=t.domain,this.#n=_(t.domain,t.configHome),this.#r=t.fallbackPath===void 0?void 0:f.resolve(t.fallbackPath),this.#a=this.#r===void 0?[this.#n]:[this.#n,this.#r],this.#f=t.validate,this.#m=t.read,this.#p=t.coldStartDefault===void 0?void 0:structuredClone(this.#f(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=M({domain:this.#u,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.#l:void 0;return{domain:this.#u,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.#d.add(t),()=>{this.#d.delete(t)}}reload(){let t=this.#g.then(()=>this.#v());return this.#g=t.then(()=>{},()=>{}),t}async#v(){this.#h=Te(this.#a);let t;try{t=this.#m(),this.#f(t.document)}catch{let o=this.#y();return this.#c=o.path,this.#l=o.source,this.#t=$("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 o of this.#d)await o(structuredClone(t),n)}catch{return this.#c=t.path,this.#l=t.source,this.#t=$("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.#l=void 0,{ok:!0,snapshot:structuredClone(t)}}async ensureCurrent(){return Te(this.#a)===this.#h&&this.#e?{ok:!0,snapshot:structuredClone(this.#e)}:this.reload()}startWatching(t=100,n=2e3){if(this.#s.length>0||this.#i)return;re(f.dirname(this.#n),{recursive:!0,mode:448});let o=new Map;for(let i of this.#a){let s=f.dirname(i),a=o.get(s)??new Set;a.add(f.basename(i)),o.set(s,a)}for(let[i,s]of o)try{let a=st(i,(c,l)=>{l!==null&&!s.has(l.toString())||(this.#o&&clearTimeout(this.#o),this.#o=setTimeout(()=>{this.#o=void 0,this.reload()},t),this.#o.unref?.())});a.unref(),a.on("error",()=>{this.#t=$("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}),this.#s.push(a)}catch{this.#t=$("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}this.#i=setInterval(()=>{this.ensureCurrent()},n),this.#i.unref?.()}close(){this.#o&&clearTimeout(this.#o),this.#o=void 0,this.#i&&clearInterval(this.#i),this.#i=void 0;for(let t of this.#s)t.close();this.#s.length=0,this.#d.clear()}#y(){return d(this.#n)?{path:this.#n,source:"user"}:this.#r&&d(this.#r)?{path:this.#r,source:"legacy-user"}:{path:this.#n,source:"default"}}};var xt=Et(yt),Fe=2,Ue=!1,u=Pe(),kn=h.join(u,"sessions"),p=h.join(u,"config.json"),Sn=60,v=null,ce=!1,Pt="dumb";function kt(e){let t=h.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",o=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",o],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",o]:["-lc",o],sentinel:n}}r(kt,"buildShellEnvCommand");function St(e,t){let n=`${t}\0`,o=e.lastIndexOf(n);if(o===-1)return{};let i=e.slice(o+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}r(St,"parseNullDelimitedShellEnv");function Ct(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let o=e.shell??t.SHELL;if(!o||!h.isAbsolute(o))return!1;let{args:i,sentinel:s}=kt(o),a=e.run??wt,c={...t,TERM:Pt},l=a(o,i,{encoding:"utf8",env:c,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(l.status!==0||!l.stdout)return!1;let g=typeof l.stdout=="string"?l.stdout:l.stdout.toString("utf8"),L=St(g,s),N=!1;for(let[z,qe]of Object.entries(L))z!=="TERM"&&t[z]===void 0&&(t[z]=qe,N=!0);return N}r(Ct,"hydrateProcessEnvFromShell");function _t(){if(!ce){ce=!0;try{Ct()}catch{}}}r(_t,"ensureShellEnvironmentHydrated");function Cn(){ce=!1}r(Cn,"resetShellEnvironmentHydrationForTesting");function Mt(e){Ee(e.customProviders??[])}r(Mt,"registerConfiguredCustomProviders");function le(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:[]}r(le,"normalizeConfiguredExtensions");function At(e){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return;let t=e.envPass;if(!Array.isArray(t))return;let n=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o));return{envPass:[...new Set(n)]}}r(At,"normalizeSandboxConfig");function ue(){let e=m.readFileSync(p,"utf8"),t=JSON.parse(e);if(!(t===null||typeof t!="object"||Array.isArray(t)))return{raw:e,value:t}}r(ue,"readPersistedCoreConfig");function Ve(e){m.writeFileSync(p,JSON.stringify(e,null,2))}r(Ve,"writePersistedCoreConfig");function Ot(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{E(p,()=>{let n=ue();n?.value.permissionMode==="default"&&Ve({...n.value,permissionMode:"accept-edits"})})}catch{}return t}r(Ot,"migrateLegacyPermissionModeInConfig");function It(e){if(e.permissionMode!=="auto-in-project")return e;try{E(p,()=>{let t=ue();if(t?.value.permissionMode!=="auto-in-project")return;let n=t.raw.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t.raw&&m.writeFileSync(p,n)})}catch{}return{...e,permissionMode:"auto"}}r(It,"migrateAutoInProjectAliasInConfig");function Rt(){if(v)return v;let e="0.7.89";if(e)return v=e,v;let t=h.join(h.dirname(bt(import.meta.url)),"../../package.json");if(m.existsSync(t))try{return v=JSON.parse(m.readFileSync(t,"utf-8")).version??"0.0.0",v??"0.0.0"}catch{}return v="0.0.0",v}r(Rt,"getVersion");var _n=Rt();function Tt(e){return ge(e)}r(Tt,"getProviderModel");function de(e,t){let n=new Set(e.map(i=>i.toLowerCase())),o=[...e];for(let i of t)n.has(i.toLowerCase())||o.push(i);return o}r(de,"mergeModels");function Dt(e,t){t||(t=fe().providerModels);let n=t?.[e];if(n&&n.length>0){try{let o=Y(e);if(o.length>0)return de(n,o)}catch{}try{let o=R(e);if(o)return de(n,o.getAvailableModels())}catch{}return n}try{let o=Y(e);if(o.length>0)return o}catch{}try{let o=R(e);if(o)return o.getAvailableModels()}catch{}return[]}r(Dt,"getProviderAvailableModels");function Lt(e,t){let n=ve(e,t);if(n!=="unknown")return n;try{let o=R(e);if(o)return o.getReasoningCapability(t)}catch{}return"unknown"}r(Lt,"getProviderReasoningCapability");function Nt(e){let t=ye(e);if(t)return t;try{return Z().find(o=>o.name===e)?.capabilityProfile??null}catch{return null}}r(Nt,"getProviderCapabilityProfile");function ze(e,t){let n=Nt(e),o=Lt(e,t);if(n)return{capabilityProfile:n,reasoningCapability:o};try{let i=be(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}r(ze,"getProviderCapabilityMetadata");function Mn(e,t){let n=ze(e,t);return n?Se({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}r(Mn,"getProviderCapabilitySnapshot");function $t(e,t,n,o){let i=ze(e,t);return i?Ce({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:o}):null}r($t,"getProviderPolicyDecision");function An(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",o=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${o}`}r(An,"describeProviderCapabilitySummary");function On(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"-"}}r(On,"formatReasoningCapabilityShort");function I(e){if(e)return e==="none"?"off":e}r(I,"formatReasoningEffortForDisplay");function G(e,t){let n=I(t);n&&!e.includes(n)&&e.push(n)}r(G,"pushUniqueEffortDisplay");function In(e,t){let n=["auto"],o=V(e,t),i=o?.supportedEfforts?.filter(s=>s.isUserVisible!==!1);if(!i||i.length===0){for(let s of["off","low","medium","high"])G(n,s);return n}for(let s of i)s.value==="none"&&o?.supportsDisabledThinking===!1||G(n,s.value);return n}r(In,"getProviderReasoningEffortOptions");function Rn(e,t){let n=V(e,t),o=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(l=>l.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let l of["low","medium","high"])G(s,l);a=!0}else for(let l of i){if(l.value==="none"){n?.supportsDisabledThinking!==!1&&(a=!0);continue}if(o.has(l.value)){n?.supportsDisabledThinking!==!1&&(a=!0);continue}G(s,l.value)}let c=[];return a&&c.push("off"),c.push(...s),c.push("auto"),c}r(Rn,"getProviderReasoningEffortCycle");function jt(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"}}r(jt,"legacyReasoningModeToEffortDisplay");function V(e,t){let n=t??Tt(e);if(!n)return;let o=xe(e,n)?.reasoningProfile;if(o)return pe(o,ke(e,n))}r(V,"resolveReasoningProfileForDisplay");function Tn(e){let t=I(e.effort)??jt(e.reasoningMode,e.thinking),n=V(e.provider,e.model);if(!n)return t;try{let o=me({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=I(o.configuredEffort)??t,a=o.configuredEffort!==void 0&&n.supportsDisabledThinking!==!1&&n.disabledEfforts?.includes(o.configuredEffort)===!0?"off":I(o.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let o=J({currentEffort:e.effort,capability:n}),i=I(e.effort)??t,s=I(o.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}r(Tn,"formatReasoningEffortStatusLabel");function Dn(e){let t=zt(e);if(!t)return{preserved:!0};let n=V(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let o=J({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:o.effectiveEffort,preserved:o.preserved,diagnostic:o.diagnostic}}r(Dn,"resolveProviderReasoningRuntimeEffort");function Kt(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"}}r(Kt,"describeReasoningCapabilityControl");function Ln(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"}}r(Ln,"describeReasoningExecution");function Nn(e){let t=[];e||(e=fe().providerModels);for(let n of we())t.push({name:n.name,model:n.model,models:Dt(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=Z().map(o=>({...o,models:(()=>{let i=e?.[o.name];return i&&i.length>0?de(i,o.models):o.models})()}));t.push(...n)}catch{}return t}r(Nn,"getProviderList");function $n(e){if(he(e))return!0;try{return R(e)?.isConfigured()??!1}catch{return!1}}r($n,"isProviderConfigured");var H=class extends Error{static{r(this,"InvalidAgentModeConfigError")}};function Xt(e){let t=e.agentMode;if(t===void 0||t==="ama"||t==="sa")return e;if(t!=="amaw"&&t!=="ama-workflow")throw new H(`Invalid agentMode "${t}" in ${p}. Expected "ama" or "sa".`);let n={...e,agentMode:"ama",schemaVersion:Math.max(e.schemaVersion??0,Fe)};try{E(p,()=>{let o=ue();if(!o)return;let i=o.value.agentMode;i!=="amaw"&&i!=="ama-workflow"||Ve({...o.value,agentMode:"ama",schemaVersion:Math.max(typeof o.value.schemaVersion=="number"?o.value.schemaVersion:0,Fe)})})}catch{}return Ue||(process.emitWarning(`Migrated persisted agentMode "${t}" to "ama". Workflow use is now explicit intent.`,{code:"KODAX_AGENT_MODE_MIGRATED"}),Ue=!0),n}r(Xt,"migrateLegacyAgentModeConfig");function fe(){try{if(m.existsSync(p)){let n=JSON.parse(m.readFileSync(p,"utf-8")),o=Xt(n),i=o.reasoningCeiling??o.reasoningMode,s=[],a={};try{s=[...U(u).document.paths]}catch{}try{a=F(u).document.servers}catch{}return It(Ot({...o,reasoningMode:i,extensions:le(s),mcpServers:a,sandbox:At(o.sandbox)}))}}catch(n){if(n instanceof H)throw n}let e,t;try{let n=U(u);n.source!=="default"&&(e=le([...n.document.paths]))}catch{}try{let n=F(u);n.source!=="default"&&(t=n.document.servers)}catch{}return{...e===void 0?{}:{extensions:e},...t===void 0?{}:{mcpServers:t}}}r(fe,"loadConfig");var Ft=h.join(u,"config.example.jsonc"),ae={mcp:h.join(u,"integrations","mcp.example.jsonc"),a2a:h.join(u,"integrations","a2a.example.jsonc"),extensions:h.join(u,"integrations","extensions.example.jsonc")},Ut=[{name:"core",path:Ft},{name:"mcp",path:ae.mcp},{name:"a2a",path:ae.a2a},{name:"extensions",path:ae.extensions}];function Wt(){let e=[];for(let t of Ut)try{if(m.existsSync(t.path))continue;m.mkdirSync(h.dirname(t.path),{recursive:!0}),m.writeFileSync(t.path,Oe(t.name),"utf8"),e.push(t.path)}catch{}return e}r(Wt,"ensureExampleConfigFiles");function jn(){return Wt()[0]}r(jn,"ensureExampleConfigFile");var W=new Map;function Gt(e,t){let n=process.env[e],o=W.get(e),i=o!==void 0&&n===o;if(n!==void 0&&!i){W.delete(e);return}if(t===void 0){i&&delete process.env[e],W.delete(e);return}process.env[e]=t,W.set(e,t)}r(Gt,"projectConfigEnvironment");var Be=[{configPath:"streamIdleTimeoutMs",env:"KODAX_STREAM_IDLE_TIMEOUT_MS",value:r(e=>x(e.streamIdleTimeoutMs),"value")},{configPath:"repoIntelligenceMode",env:"KODAX_REPO_INTELLIGENCE",value:r(e=>e.repoIntelligenceMode,"value")},{configPath:"repoIntelligenceTrace",env:"KODAX_REPO_INTELLIGENCE_TRACE",value:r(e=>O(e.repoIntelligenceTrace),"value")},{configPath:"verifierLog",env:"KODAX_VERIFIER_LOG",value:r(e=>O(e.verifierLog),"value")},{configPath:"stallLog",env:"KODAX_STALL_LOG",value:r(e=>O(e.stallLog),"value")},{configPath:"fallbackProviders",env:"KODAX_FALLBACK_PROVIDERS",value:r(e=>We(e.fallbackProviders),"value")},{configPath:"fastProvider",env:"KODAX_FAST_PROVIDER",value:r(e=>y(e.fastProvider),"value")},{configPath:"fastModel",env:"KODAX_FAST_MODEL",value:r(e=>y(e.fastModel),"value")},{configPath:"deepProvider",env:"KODAX_DEEP_PROVIDER",value:r(e=>y(e.deepProvider),"value")},{configPath:"deepModel",env:"KODAX_DEEP_MODEL",value:r(e=>y(e.deepModel),"value")},{configPath:"provider",env:"KODAX_PROVIDER",value:r(e=>y(e.provider),"value")},{configPath:"effort",env:"KODAX_EFFORT",value:r(e=>y(e.effort),"value")},{configPath:"runtimeMode",env:"KODAX_RUNTIME_MODE",value:r(e=>e.runtimeMode,"value")},{configPath:"sessionRetentionDays",env:"KODAX_SESSION_RETENTION_DAYS",value:r(e=>x(e.sessionRetentionDays),"value")},{configPath:"maxOutputTokens",env:"KODAX_MAX_OUTPUT_TOKENS",value:r(e=>x(e.maxOutputTokens),"value")},{configPath:"disablePromptCache",env:"KODAX_DISABLE_PROMPT_CACHE",value:r(e=>O(e.disablePromptCache),"value")},{configPath:"lsp",env:"KODAX_LSP",value:r(e=>O(e.lsp),"value")},{configPath:"lspAutoDownload",env:"KODAX_LSP_DOWNLOAD",value:r(e=>O(e.lspAutoDownload),"value")},{configPath:"acpLogLevel",env:"KODAX_ACP_LOG",value:r(e=>y(e.acpLogLevel),"value")},{configPath:"repoIntelligence.toolWaitMs",env:"KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS",value:r(e=>x(e.repoIntelligence?.toolWaitMs),"value")},{configPath:"repoIntelligence.workerTimeoutMs",env:"KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS",value:r(e=>x(e.repoIntelligence?.workerTimeoutMs),"value")},{configPath:"repoIntelligence.workerOldSpaceMb",env:"KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB",value:r(e=>x(e.repoIntelligence?.workerOldSpaceMb),"value")},{configPath:"repoIntelligence.storageDir",env:"KODAX_REPO_INTELLIGENCE_STORAGE_DIR",value:r(e=>y(e.repoIntelligence?.storageDir),"value")},{configPath:"workflow.maxConcurrency",env:"KODAX_WORKFLOW_MAX_CONCURRENCY",value:r(e=>x(e.workflow?.maxConcurrency),"value")},{configPath:"sandbox.envPass",env:"KODAX_SANDBOX_ENV_PASS",value:r(e=>We(e.sandbox?.envPass)||void 0,"value")}];function Ht(e){for(let t of Be)Gt(t.env,t.value(e))}r(Ht,"applyConfigSurfaceBridges");function y(e){return e?.trim()||void 0}r(y,"normalizedConfigString");function x(e){return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}r(x,"configNumberString");function O(e){return e===void 0?void 0:e?"1":"0"}r(O,"configBooleanString");function We(e){return e?.filter(t=>t.trim().length>0).join(",")}r(We,"configStringList");var Kn=[...Be.map(({configPath:e,env:t})=>({configPath:e,env:t}))];function Vt(e){Ht(e)}r(Vt,"applyConfigEnvironment");function Xn(){_t();let e=fe();return Vt(e),Mt(e),Me(e.locale),e}r(Xn,"prepareRuntimeConfig");function Fn(e){let{extensions:t,mcpServers:n,...o}=e;if(E(p,()=>{let i={};if(m.existsSync(p))try{let a=JSON.parse(m.readFileSync(p,"utf8"));a&&typeof a=="object"&&!Array.isArray(a)&&(i=a)}catch{}let s={...i,...o};for(let a of Object.keys(o))o[a]===void 0&&delete s[a];m.writeFileSync(p,JSON.stringify(s,null,2))}),t!==void 0){let i=U(u);T({domain:"extensions",configHome:u,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,paths:le(t)??[]},validate:C})}if(n!==void 0){let i=F(u);T({domain:"mcp",configHome:u,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,servers:n},validate:S})}}r(Fn,"saveConfig");function Un(e,t,n){return e.effort!==void 0||q(n).kind==="value"||t.effort!==void 0}r(Un,"resolveInitialEffortOverride");function w(e){return e?.trim()?e:void 0}r(w,"nonEmptySelection");function Wn(e){return w(e.explicitProvider)??w(e.environmentProvider)??w(e.configuredProvider)??e.defaultProvider}r(Wn,"resolveRuntimeProviderSelection");function Gn(e){let t=w(e.explicitModel);if(t)return t;let n=w(e.configuredModel);if(!n)return;let o=w(e.explicitProvider)??w(e.environmentProvider);return o?w(e.configuredProvider)===o?n:void 0:n}r(Gn,"resolveRuntimeModelSelection");function Hn(e){if(e.explicitEffort!==void 0)return B(e.explicitEffort);let t=q(e.environmentEffort);return t.kind==="value"?t.value:e.configuredEffort===void 0?void 0:B(e.configuredEffort)}r(Hn,"resolveRuntimeEffortSelection");function zt(e){return e.permissionMode==="plan"&&e.effortOverride!==!0&&e.planModeEffort!==void 0?e.planModeEffort:e.effort}r(zt,"resolvePermissionModeEffort");async function Vn(e){try{let{stdout:t}=await xt("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0});return t.trim()}catch{return null}}r(Vn,"getGitRoot");function Bt(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}r(Bt,"formatProviderSourceKind");function zn(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: ${Bt(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: ${Kt(e.reasoningCapability)}`]}r(zn,"formatProviderCapabilityDetailLines");function Bn(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:$t(e,t,n,i.hints)})).filter(i=>i.decision!==null)}r(Bn,"getProviderCommonPolicyScenarios");var Ge=.5,He=0,D={locked:!1,queue:[]};async function qn(e){for(;D.locked;)await new Promise(t=>D.queue.push(t));D.locked=!0;try{let t=(Date.now()-He)/1e3;t<Ge&&await new Promise(o=>setTimeout(o,(Ge-t)*1e3));let n=await e();return He=Date.now(),n}finally{D.locked=!1;let t=D.queue.shift();t&&t()}}r(qn,"rateLimitedCall");export{qt as a,Ae as b,Oe as c,ee as d,nt as e,E as f,k as g,S as h,C as i,_ as j,F as k,U as l,ft as m,ln as n,T as o,De as p,u as q,kn as r,p as s,Sn as t,Ct as u,Cn as v,Mt as w,Rt as x,_n as y,Tt as z,Dt as A,Lt as B,Nt as C,Mn as D,$t as E,An as F,On as G,I as H,In as I,Rn as J,Tn as K,Dn as L,Kt as M,Ln as N,Nn as O,$n as P,fe as Q,Ft as R,ae as S,Wt as T,jn as U,Kn as V,Vt as W,Xn as X,Fn as Y,Un as Z,Wn as _,Gn as $,Hn as aa,zt as ba,Vn as ca,Bt as da,zn as ea,Bn as fa,qn as ga};
278
+ `,c=`${t}.${process.pid}.${Date.now()}.tmp`,l=ie(c,"wx",384);try{je(l,a,"utf8"),Le(l)}finally{ne(l)}try{e.expectedRevision===null?(rt(c,t),j(c)):$e(c,t)}catch(g){throw d(c)&&j(c),e.expectedRevision===null&&d(t)?new k(t,void 0,Re(t)):new Error(`Failed to atomically replace ${f.basename(t)}.`,{cause:g})}return M({domain:e.domain,source:"user",path:t,raw:a,document:n})}finally{ne(o.fd),d(o.path)&&j(o.path)}}r(T,"writeIntegrationDocument");function vt(e){if(!d(e))return"missing";let t=it(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}r(vt,"metadataSignature");function Te(e){return e.map(t=>`${t}:${vt(t)}`).join("|")}r(Te,"observationSignature");function $(e,t){return{code:e,message:t,time:new Date().toISOString()}}r($,"safeDiagnostic");var De=class{static{r(this,"IntegrationConfigController")}#u;#n;#r;#a;#m;#f;#p;#e;#t;#c;#l;#h="";#s=[];#o;#i;#g=Promise.resolve();#d=new Set;constructor(t){this.#u=t.domain,this.#n=_(t.domain,t.configHome),this.#r=t.fallbackPath===void 0?void 0:f.resolve(t.fallbackPath),this.#a=this.#r===void 0?[this.#n]:[this.#n,this.#r],this.#f=t.validate,this.#m=t.read,this.#p=t.coldStartDefault===void 0?void 0:structuredClone(this.#f(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=M({domain:this.#u,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.#l:void 0;return{domain:this.#u,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.#d.add(t),()=>{this.#d.delete(t)}}reload(){let t=this.#g.then(()=>this.#v());return this.#g=t.then(()=>{},()=>{}),t}async#v(){this.#h=Te(this.#a);let t;try{t=this.#m(),this.#f(t.document)}catch{let o=this.#y();return this.#c=o.path,this.#l=o.source,this.#t=$("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 o of this.#d)await o(structuredClone(t),n)}catch{return this.#c=t.path,this.#l=t.source,this.#t=$("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.#l=void 0,{ok:!0,snapshot:structuredClone(t)}}async ensureCurrent(){return Te(this.#a)===this.#h&&this.#e?{ok:!0,snapshot:structuredClone(this.#e)}:this.reload()}startWatching(t=100,n=2e3){if(this.#s.length>0||this.#i)return;re(f.dirname(this.#n),{recursive:!0,mode:448});let o=new Map;for(let i of this.#a){let s=f.dirname(i),a=o.get(s)??new Set;a.add(f.basename(i)),o.set(s,a)}for(let[i,s]of o)try{let a=st(i,(c,l)=>{l!==null&&!s.has(l.toString())||(this.#o&&clearTimeout(this.#o),this.#o=setTimeout(()=>{this.#o=void 0,this.reload()},t),this.#o.unref?.())});a.unref(),a.on("error",()=>{this.#t=$("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}),this.#s.push(a)}catch{this.#t=$("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}this.#i=setInterval(()=>{this.ensureCurrent()},n),this.#i.unref?.()}close(){this.#o&&clearTimeout(this.#o),this.#o=void 0,this.#i&&clearInterval(this.#i),this.#i=void 0;for(let t of this.#s)t.close();this.#s.length=0,this.#d.clear()}#y(){return d(this.#n)?{path:this.#n,source:"user"}:this.#r&&d(this.#r)?{path:this.#r,source:"legacy-user"}:{path:this.#n,source:"default"}}};var xt=Et(yt),Fe=2,Ue=!1,u=Pe(),kn=h.join(u,"sessions"),p=h.join(u,"config.json"),Sn=60,v=null,ce=!1,Pt="dumb";function kt(e){let t=h.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",o=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",o],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",o]:["-lc",o],sentinel:n}}r(kt,"buildShellEnvCommand");function St(e,t){let n=`${t}\0`,o=e.lastIndexOf(n);if(o===-1)return{};let i=e.slice(o+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}r(St,"parseNullDelimitedShellEnv");function Ct(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let o=e.shell??t.SHELL;if(!o||!h.isAbsolute(o))return!1;let{args:i,sentinel:s}=kt(o),a=e.run??wt,c={...t,TERM:Pt},l=a(o,i,{encoding:"utf8",env:c,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(l.status!==0||!l.stdout)return!1;let g=typeof l.stdout=="string"?l.stdout:l.stdout.toString("utf8"),L=St(g,s),N=!1;for(let[z,qe]of Object.entries(L))z!=="TERM"&&t[z]===void 0&&(t[z]=qe,N=!0);return N}r(Ct,"hydrateProcessEnvFromShell");function _t(){if(!ce){ce=!0;try{Ct()}catch{}}}r(_t,"ensureShellEnvironmentHydrated");function Cn(){ce=!1}r(Cn,"resetShellEnvironmentHydrationForTesting");function Mt(e){Ee(e.customProviders??[])}r(Mt,"registerConfiguredCustomProviders");function le(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:[]}r(le,"normalizeConfiguredExtensions");function At(e){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return;let t=e.envPass;if(!Array.isArray(t))return;let n=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o));return{envPass:[...new Set(n)]}}r(At,"normalizeSandboxConfig");function ue(){let e=m.readFileSync(p,"utf8"),t=JSON.parse(e);if(!(t===null||typeof t!="object"||Array.isArray(t)))return{raw:e,value:t}}r(ue,"readPersistedCoreConfig");function Ve(e){m.writeFileSync(p,JSON.stringify(e,null,2))}r(Ve,"writePersistedCoreConfig");function Ot(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{E(p,()=>{let n=ue();n?.value.permissionMode==="default"&&Ve({...n.value,permissionMode:"accept-edits"})})}catch{}return t}r(Ot,"migrateLegacyPermissionModeInConfig");function It(e){if(e.permissionMode!=="auto-in-project")return e;try{E(p,()=>{let t=ue();if(t?.value.permissionMode!=="auto-in-project")return;let n=t.raw.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t.raw&&m.writeFileSync(p,n)})}catch{}return{...e,permissionMode:"auto"}}r(It,"migrateAutoInProjectAliasInConfig");function Rt(){if(v)return v;let e="0.7.90";if(e)return v=e,v;let t=h.join(h.dirname(bt(import.meta.url)),"../../package.json");if(m.existsSync(t))try{return v=JSON.parse(m.readFileSync(t,"utf-8")).version??"0.0.0",v??"0.0.0"}catch{}return v="0.0.0",v}r(Rt,"getVersion");var _n=Rt();function Tt(e){return ge(e)}r(Tt,"getProviderModel");function de(e,t){let n=new Set(e.map(i=>i.toLowerCase())),o=[...e];for(let i of t)n.has(i.toLowerCase())||o.push(i);return o}r(de,"mergeModels");function Dt(e,t){t||(t=fe().providerModels);let n=t?.[e];if(n&&n.length>0){try{let o=Y(e);if(o.length>0)return de(n,o)}catch{}try{let o=R(e);if(o)return de(n,o.getAvailableModels())}catch{}return n}try{let o=Y(e);if(o.length>0)return o}catch{}try{let o=R(e);if(o)return o.getAvailableModels()}catch{}return[]}r(Dt,"getProviderAvailableModels");function Lt(e,t){let n=ve(e,t);if(n!=="unknown")return n;try{let o=R(e);if(o)return o.getReasoningCapability(t)}catch{}return"unknown"}r(Lt,"getProviderReasoningCapability");function Nt(e){let t=ye(e);if(t)return t;try{return Z().find(o=>o.name===e)?.capabilityProfile??null}catch{return null}}r(Nt,"getProviderCapabilityProfile");function ze(e,t){let n=Nt(e),o=Lt(e,t);if(n)return{capabilityProfile:n,reasoningCapability:o};try{let i=be(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}r(ze,"getProviderCapabilityMetadata");function Mn(e,t){let n=ze(e,t);return n?Se({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}r(Mn,"getProviderCapabilitySnapshot");function $t(e,t,n,o){let i=ze(e,t);return i?Ce({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:o}):null}r($t,"getProviderPolicyDecision");function An(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",o=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${o}`}r(An,"describeProviderCapabilitySummary");function On(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"-"}}r(On,"formatReasoningCapabilityShort");function I(e){if(e)return e==="none"?"off":e}r(I,"formatReasoningEffortForDisplay");function G(e,t){let n=I(t);n&&!e.includes(n)&&e.push(n)}r(G,"pushUniqueEffortDisplay");function In(e,t){let n=["auto"],o=V(e,t),i=o?.supportedEfforts?.filter(s=>s.isUserVisible!==!1);if(!i||i.length===0){for(let s of["off","low","medium","high"])G(n,s);return n}for(let s of i)s.value==="none"&&o?.supportsDisabledThinking===!1||G(n,s.value);return n}r(In,"getProviderReasoningEffortOptions");function Rn(e,t){let n=V(e,t),o=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(l=>l.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let l of["low","medium","high"])G(s,l);a=!0}else for(let l of i){if(l.value==="none"){n?.supportsDisabledThinking!==!1&&(a=!0);continue}if(o.has(l.value)){n?.supportsDisabledThinking!==!1&&(a=!0);continue}G(s,l.value)}let c=[];return a&&c.push("off"),c.push(...s),c.push("auto"),c}r(Rn,"getProviderReasoningEffortCycle");function jt(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"}}r(jt,"legacyReasoningModeToEffortDisplay");function V(e,t){let n=t??Tt(e);if(!n)return;let o=xe(e,n)?.reasoningProfile;if(o)return pe(o,ke(e,n))}r(V,"resolveReasoningProfileForDisplay");function Tn(e){let t=I(e.effort)??jt(e.reasoningMode,e.thinking),n=V(e.provider,e.model);if(!n)return t;try{let o=me({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=I(o.configuredEffort)??t,a=o.configuredEffort!==void 0&&n.supportsDisabledThinking!==!1&&n.disabledEfforts?.includes(o.configuredEffort)===!0?"off":I(o.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let o=J({currentEffort:e.effort,capability:n}),i=I(e.effort)??t,s=I(o.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}r(Tn,"formatReasoningEffortStatusLabel");function Dn(e){let t=zt(e);if(!t)return{preserved:!0};let n=V(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let o=J({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:o.effectiveEffort,preserved:o.preserved,diagnostic:o.diagnostic}}r(Dn,"resolveProviderReasoningRuntimeEffort");function Kt(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"}}r(Kt,"describeReasoningCapabilityControl");function Ln(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"}}r(Ln,"describeReasoningExecution");function Nn(e){let t=[];e||(e=fe().providerModels);for(let n of we())t.push({name:n.name,model:n.model,models:Dt(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=Z().map(o=>({...o,models:(()=>{let i=e?.[o.name];return i&&i.length>0?de(i,o.models):o.models})()}));t.push(...n)}catch{}return t}r(Nn,"getProviderList");function $n(e){if(he(e))return!0;try{return R(e)?.isConfigured()??!1}catch{return!1}}r($n,"isProviderConfigured");var H=class extends Error{static{r(this,"InvalidAgentModeConfigError")}};function Xt(e){let t=e.agentMode;if(t===void 0||t==="ama"||t==="sa")return e;if(t!=="amaw"&&t!=="ama-workflow")throw new H(`Invalid agentMode "${t}" in ${p}. Expected "ama" or "sa".`);let n={...e,agentMode:"ama",schemaVersion:Math.max(e.schemaVersion??0,Fe)};try{E(p,()=>{let o=ue();if(!o)return;let i=o.value.agentMode;i!=="amaw"&&i!=="ama-workflow"||Ve({...o.value,agentMode:"ama",schemaVersion:Math.max(typeof o.value.schemaVersion=="number"?o.value.schemaVersion:0,Fe)})})}catch{}return Ue||(process.emitWarning(`Migrated persisted agentMode "${t}" to "ama". Workflow use is now explicit intent.`,{code:"KODAX_AGENT_MODE_MIGRATED"}),Ue=!0),n}r(Xt,"migrateLegacyAgentModeConfig");function fe(){try{if(m.existsSync(p)){let n=JSON.parse(m.readFileSync(p,"utf-8")),o=Xt(n),i=o.reasoningCeiling??o.reasoningMode,s=[],a={};try{s=[...U(u).document.paths]}catch{}try{a=F(u).document.servers}catch{}return It(Ot({...o,reasoningMode:i,extensions:le(s),mcpServers:a,sandbox:At(o.sandbox)}))}}catch(n){if(n instanceof H)throw n}let e,t;try{let n=U(u);n.source!=="default"&&(e=le([...n.document.paths]))}catch{}try{let n=F(u);n.source!=="default"&&(t=n.document.servers)}catch{}return{...e===void 0?{}:{extensions:e},...t===void 0?{}:{mcpServers:t}}}r(fe,"loadConfig");var Ft=h.join(u,"config.example.jsonc"),ae={mcp:h.join(u,"integrations","mcp.example.jsonc"),a2a:h.join(u,"integrations","a2a.example.jsonc"),extensions:h.join(u,"integrations","extensions.example.jsonc")},Ut=[{name:"core",path:Ft},{name:"mcp",path:ae.mcp},{name:"a2a",path:ae.a2a},{name:"extensions",path:ae.extensions}];function Wt(){let e=[];for(let t of Ut)try{if(m.existsSync(t.path))continue;m.mkdirSync(h.dirname(t.path),{recursive:!0}),m.writeFileSync(t.path,Oe(t.name),"utf8"),e.push(t.path)}catch{}return e}r(Wt,"ensureExampleConfigFiles");function jn(){return Wt()[0]}r(jn,"ensureExampleConfigFile");var W=new Map;function Gt(e,t){let n=process.env[e],o=W.get(e),i=o!==void 0&&n===o;if(n!==void 0&&!i){W.delete(e);return}if(t===void 0){i&&delete process.env[e],W.delete(e);return}process.env[e]=t,W.set(e,t)}r(Gt,"projectConfigEnvironment");var Be=[{configPath:"streamIdleTimeoutMs",env:"KODAX_STREAM_IDLE_TIMEOUT_MS",value:r(e=>x(e.streamIdleTimeoutMs),"value")},{configPath:"repoIntelligenceMode",env:"KODAX_REPO_INTELLIGENCE",value:r(e=>e.repoIntelligenceMode,"value")},{configPath:"repoIntelligenceTrace",env:"KODAX_REPO_INTELLIGENCE_TRACE",value:r(e=>O(e.repoIntelligenceTrace),"value")},{configPath:"verifierLog",env:"KODAX_VERIFIER_LOG",value:r(e=>O(e.verifierLog),"value")},{configPath:"stallLog",env:"KODAX_STALL_LOG",value:r(e=>O(e.stallLog),"value")},{configPath:"fallbackProviders",env:"KODAX_FALLBACK_PROVIDERS",value:r(e=>We(e.fallbackProviders),"value")},{configPath:"fastProvider",env:"KODAX_FAST_PROVIDER",value:r(e=>y(e.fastProvider),"value")},{configPath:"fastModel",env:"KODAX_FAST_MODEL",value:r(e=>y(e.fastModel),"value")},{configPath:"deepProvider",env:"KODAX_DEEP_PROVIDER",value:r(e=>y(e.deepProvider),"value")},{configPath:"deepModel",env:"KODAX_DEEP_MODEL",value:r(e=>y(e.deepModel),"value")},{configPath:"provider",env:"KODAX_PROVIDER",value:r(e=>y(e.provider),"value")},{configPath:"effort",env:"KODAX_EFFORT",value:r(e=>y(e.effort),"value")},{configPath:"runtimeMode",env:"KODAX_RUNTIME_MODE",value:r(e=>e.runtimeMode,"value")},{configPath:"sessionRetentionDays",env:"KODAX_SESSION_RETENTION_DAYS",value:r(e=>x(e.sessionRetentionDays),"value")},{configPath:"maxOutputTokens",env:"KODAX_MAX_OUTPUT_TOKENS",value:r(e=>x(e.maxOutputTokens),"value")},{configPath:"disablePromptCache",env:"KODAX_DISABLE_PROMPT_CACHE",value:r(e=>O(e.disablePromptCache),"value")},{configPath:"lsp",env:"KODAX_LSP",value:r(e=>O(e.lsp),"value")},{configPath:"lspAutoDownload",env:"KODAX_LSP_DOWNLOAD",value:r(e=>O(e.lspAutoDownload),"value")},{configPath:"acpLogLevel",env:"KODAX_ACP_LOG",value:r(e=>y(e.acpLogLevel),"value")},{configPath:"repoIntelligence.toolWaitMs",env:"KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS",value:r(e=>x(e.repoIntelligence?.toolWaitMs),"value")},{configPath:"repoIntelligence.workerTimeoutMs",env:"KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS",value:r(e=>x(e.repoIntelligence?.workerTimeoutMs),"value")},{configPath:"repoIntelligence.workerOldSpaceMb",env:"KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB",value:r(e=>x(e.repoIntelligence?.workerOldSpaceMb),"value")},{configPath:"repoIntelligence.storageDir",env:"KODAX_REPO_INTELLIGENCE_STORAGE_DIR",value:r(e=>y(e.repoIntelligence?.storageDir),"value")},{configPath:"workflow.maxConcurrency",env:"KODAX_WORKFLOW_MAX_CONCURRENCY",value:r(e=>x(e.workflow?.maxConcurrency),"value")},{configPath:"sandbox.envPass",env:"KODAX_SANDBOX_ENV_PASS",value:r(e=>We(e.sandbox?.envPass)||void 0,"value")}];function Ht(e){for(let t of Be)Gt(t.env,t.value(e))}r(Ht,"applyConfigSurfaceBridges");function y(e){return e?.trim()||void 0}r(y,"normalizedConfigString");function x(e){return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}r(x,"configNumberString");function O(e){return e===void 0?void 0:e?"1":"0"}r(O,"configBooleanString");function We(e){return e?.filter(t=>t.trim().length>0).join(",")}r(We,"configStringList");var Kn=[...Be.map(({configPath:e,env:t})=>({configPath:e,env:t}))];function Vt(e){Ht(e)}r(Vt,"applyConfigEnvironment");function Xn(){_t();let e=fe();return Vt(e),Mt(e),Me(e.locale),e}r(Xn,"prepareRuntimeConfig");function Fn(e){let{extensions:t,mcpServers:n,...o}=e;if(E(p,()=>{let i={};if(m.existsSync(p))try{let a=JSON.parse(m.readFileSync(p,"utf8"));a&&typeof a=="object"&&!Array.isArray(a)&&(i=a)}catch{}let s={...i,...o};for(let a of Object.keys(o))o[a]===void 0&&delete s[a];m.writeFileSync(p,JSON.stringify(s,null,2))}),t!==void 0){let i=U(u);T({domain:"extensions",configHome:u,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,paths:le(t)??[]},validate:C})}if(n!==void 0){let i=F(u);T({domain:"mcp",configHome:u,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,servers:n},validate:S})}}r(Fn,"saveConfig");function Un(e,t,n){return e.effort!==void 0||q(n).kind==="value"||t.effort!==void 0}r(Un,"resolveInitialEffortOverride");function w(e){return e?.trim()?e:void 0}r(w,"nonEmptySelection");function Wn(e){return w(e.explicitProvider)??w(e.environmentProvider)??w(e.configuredProvider)??e.defaultProvider}r(Wn,"resolveRuntimeProviderSelection");function Gn(e){let t=w(e.explicitModel);if(t)return t;let n=w(e.configuredModel);if(!n)return;let o=w(e.explicitProvider)??w(e.environmentProvider);return o?w(e.configuredProvider)===o?n:void 0:n}r(Gn,"resolveRuntimeModelSelection");function Hn(e){if(e.explicitEffort!==void 0)return B(e.explicitEffort);let t=q(e.environmentEffort);return t.kind==="value"?t.value:e.configuredEffort===void 0?void 0:B(e.configuredEffort)}r(Hn,"resolveRuntimeEffortSelection");function zt(e){return e.permissionMode==="plan"&&e.effortOverride!==!0&&e.planModeEffort!==void 0?e.planModeEffort:e.effort}r(zt,"resolvePermissionModeEffort");async function Vn(e){try{let{stdout:t}=await xt("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0});return t.trim()}catch{return null}}r(Vn,"getGitRoot");function Bt(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}r(Bt,"formatProviderSourceKind");function zn(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: ${Bt(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: ${Kt(e.reasoningCapability)}`]}r(zn,"formatProviderCapabilityDetailLines");function Bn(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:$t(e,t,n,i.hints)})).filter(i=>i.decision!==null)}r(Bn,"getProviderCommonPolicyScenarios");var Ge=.5,He=0,D={locked:!1,queue:[]};async function qn(e){for(;D.locked;)await new Promise(t=>D.queue.push(t));D.locked=!0;try{let t=(Date.now()-He)/1e3;t<Ge&&await new Promise(o=>setTimeout(o,(Ge-t)*1e3));let n=await e();return He=Date.now(),n}finally{D.locked=!1;let t=D.queue.shift();t&&t()}}r(qn,"rateLimitedCall");export{qt as a,Ae as b,Oe as c,ee as d,nt as e,E as f,k as g,S as h,C as i,_ as j,F as k,U as l,ft as m,ln as n,T as o,De as p,u as q,kn as r,p as s,Sn as t,Ct as u,Cn as v,Mt as w,Rt as x,_n as y,Tt as z,Dt as A,Lt as B,Nt as C,Mn as D,$t as E,An as F,On as G,I as H,In as I,Rn as J,Tn as K,Dn as L,Kt as M,Ln as N,Nn as O,$n as P,fe as Q,Ft as R,ae as S,Wt as T,jn as U,Kn as V,Vt as W,Xn as X,Fn as Y,Un as Z,Wn as _,Gn as $,Hn as aa,zt as ba,Vn as ca,Bt as da,zn as ea,Bn as fa,qn as ga};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{D as N,J as C}from"./chunk-BOMSVUJS.js";import{ie as q,je as j,na as _}from"./chunk-5UBP47VJ.js";import{Pa as E,gb as T,m as x,n as R}from"./chunk-UNEC2WXJ.js";import{Fd as O,Gd as W,Ld as M,og as $,pg as g,qg as k,tg as I,ug as y,vg as b}from"./chunk-72H6JNPN.js";import{a as o}from"./chunk-ONUPGMER.js";import{join as Pe}from"node:path";var ne=["You generate KodaX Dynamic Workflow scripts.","Return JSON only. Do not wrap the answer in prose.","For simple tasks that do not benefit from multiple agents, return:",'{"action":"decline","reason":"..."}',"For complex tasks, return:",'{"action":"generate","manifest":{...},"source":"async function run(wf, args) { ... }","approvalSummary":"..."}',"Generated source may only coordinate agents through wf and args.","Generated source must return displayable final text for the user.","Never use import, require, process, fs, child_process, network APIs, shell commands, or direct file access."].join(`
2
+ import{D as N,J as C}from"./chunk-7KPBUO2F.js";import{ie as q,je as j,na as _}from"./chunk-NCK7ASJL.js";import{Pa as E,gb as T,m as x,n as R}from"./chunk-UNEC2WXJ.js";import{Fd as O,Gd as W,Ld as M,og as $,pg as g,qg as k,tg as I,ug as y,vg as b}from"./chunk-R3BXINQ2.js";import{a as o}from"./chunk-ONUPGMER.js";import{join as Pe}from"node:path";var ne=["You generate KodaX Dynamic Workflow scripts.","Return JSON only. Do not wrap the answer in prose.","For simple tasks that do not benefit from multiple agents, return:",'{"action":"decline","reason":"..."}',"For complex tasks, return:",'{"action":"generate","manifest":{...},"source":"async function run(wf, args) { ... }","approvalSummary":"..."}',"Generated source may only coordinate agents through wf and args.","Generated source must return displayable final text for the user.","Never use import, require, process, fs, child_process, network APIs, shell commands, or direct file access."].join(`
3
3
  `),P=12e4,re="KODAX_WORKFLOW_GENERATION_TIMEOUT_SEC",se="KODAX_WORKFLOW_GENERATION_TIMEOUT_MS",oe=64,ie=2,ae=2e3,le=[{name:"default"},{name:"variant-results",finalText:o((e,n)=>`Variant smoke child report from ${e} (${n}).`,"finalText"),synthesizeText:"Variant smoke synthesis report."},{name:"unverified-success",status:o(()=>"completed_unverified","status"),finalText:o(e=>`Smoke result for ${e}: completed with verification warnings.`,"finalText"),synthesizeText:"Smoke synthesis: completed with verification warnings."},{name:"empty-args-rerun",args:o(()=>({}),"args")}],ce=[{id:"import",pattern:/\bimport\s*(?:\(|['"*{]|\w+\s+from\b)/},{id:"require",pattern:/\brequire\s*\(/},{id:"process",pattern:/\bprocess\s*(?:\.|\[)/},{id:"fs",pattern:/\b(?:node:)?fs\b/},{id:"child_process",pattern:/\bchild_process\b/},{id:"shell",pattern:/\b(?:exec|spawn|execFile)\s*\(/},{id:"fetch",pattern:/\bfetch\s*\(/},{id:"Deno",pattern:/\bDeno\s*(?:\.|\[)/},{id:"Bun",pattern:/\bBun\s*(?:\.|\[)/},{id:"globalThis-index",pattern:/\bglobalThis\s*\[/}];function ue(e=process.env,n){let t=x(n?.workflow?.generationTimeoutSec,"timeouts.workflow.generationTimeoutSec");if(t!==void 0)return t;let r=R(e[re]);if(r!==void 0)return r;let s=e[se];if(s===void 0||s.trim().length===0)return P;let i=Number(s);return!Number.isFinite(i)||i<=0?P:Math.floor(i)}o(ue,"resolveWorkflowGenerationTimeoutMs");function fe(e,n){if(typeof e!="object"||e===null)throw new Error(`${n} must be an object`);return e}o(fe,"readRecord");function D(e,n){let t=e[n];if(typeof t!="string"||t.trim().length===0)throw new Error(`workflow generation ${n} must be a non-empty string`);return t}o(D,"readNonEmptyString");function de(e){let n=e.trim(),t=/^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(n);if(t?.[1])return t[1].trim();let r=n.indexOf("{"),s=n.lastIndexOf("}");if(r>=0&&s>r)return n.slice(r,s+1);throw new Error("workflow generation output did not contain a JSON object")}o(de,"extractJsonText");function pe(e){let n=de(e);return fe(JSON.parse(n),"workflow generation output")}o(pe,"parseGenerationJson");function me(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(typeof e!="object"||e===null)return;let n=e;for(let t of["name","id","title","phase"]){let r=n[t];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}o(me,"normalizePhaseEntry");function we(e){return e.split(/(?:->|\u2192|,|\n)/).map(n=>n.trim()).filter(n=>n.length>0)}o(we,"splitPhaseString");function he(e){if(typeof e!="object"||e===null)return e;let n=e,t=n.phases,r;if(Array.isArray(t)){let s=t.map(me);s.every(i=>i!==void 0)&&(r=s)}else if(typeof t=="string"){let s=we(t);s.length>0&&(r=s)}return r?{...n,phases:r}:e}o(he,"normalizeGeneratedManifestCandidate");function ge(e){return e.match(/\bwf\.(?:runAgent|spawnAgent|synthesize)\s*\(/g)?.length??0}o(ge,"estimateDirectAgentCalls");function ke(e,n){let t=e.maxConcurrency*Math.max(1,e.phases.length)+2,r=ge(n)+2,s=Math.min(oe,Math.max(e.maxAgents,t,r));return s>e.maxAgents?{...e,maxAgents:s}:e}o(ke,"reserveGeneratedWorkflowAgentCapacity");function w(e){let n="",t=0,r=["code"],s=[0];for(;t<e.length;){let i=e[t],a=e[t+1];if(r[r.length-1]==="template"){if(i==="\\"){n+=" ",t+=2;continue}if(i==="`"){n+=" ",t+=1,r.pop(),s.pop();continue}if(i==="$"&&a==="{"){n+=" ",t+=2,r.push("code"),s.push(0);continue}n+=i===`
4
4
  `?`
5
5
  `:" ",t+=1;continue}if(i==="/"&&a==="/"){for(n+=" ",t+=2;t<e.length&&e[t]!==`