@kodax-ai/kodax 0.7.75 → 0.7.76

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 (50) hide show
  1. package/CHANGELOG.md +27 -5
  2. package/README.md +7 -1
  3. package/README_CN.md +6 -1
  4. package/dist/chunks/{agent-LVZJB2GQ.js → agent-7X5CFET2.js} +1 -1
  5. package/dist/chunks/argument-completer-3NHIKB4N.js +2 -0
  6. package/dist/chunks/{chunk-SB75RNNR.js → chunk-4PWPNCNK.js} +2 -2
  7. package/dist/chunks/{chunk-737LI7OS.js → chunk-7FJNLJLF.js} +4 -4
  8. package/dist/chunks/chunk-COQYLD4U.js +5 -0
  9. package/dist/chunks/{chunk-Q65EAOX6.js → chunk-D3T24FJW.js} +2 -2
  10. package/dist/chunks/{chunk-F7AIEHSS.js → chunk-EI4JBQKL.js} +2 -2
  11. package/dist/chunks/{chunk-QRBWNYFV.js → chunk-HGT6WQ24.js} +4 -4
  12. package/dist/chunks/{chunk-OJQQRLZJ.js → chunk-HS3XHF3R.js} +2 -2
  13. package/dist/chunks/{chunk-BN3W2DQY.js → chunk-IDCGNQ4H.js} +1 -1
  14. package/dist/chunks/{chunk-6ZMKX3XF.js → chunk-KAY2XLCP.js} +2 -2
  15. package/dist/chunks/{chunk-5WSOB34U.js → chunk-OD6LVXU6.js} +2 -2
  16. package/dist/chunks/{chunk-UJRRZINL.js → chunk-OSF3H4RR.js} +2 -2
  17. package/dist/chunks/{chunk-G5VW55T4.js → chunk-PXKSE54E.js} +1 -1
  18. package/dist/chunks/{chunk-4PVSDE5L.js → chunk-RDXRM3UI.js} +1 -1
  19. package/dist/chunks/{chunk-N6M2LYEP.js → chunk-SMT2JSM3.js} +1 -1
  20. package/dist/chunks/{chunk-DEHOFNQA.js → chunk-TGMBHGZO.js} +2 -2
  21. package/dist/chunks/{chunk-QSMXI4MH.js → chunk-VWSLC2WO.js} +1 -1
  22. package/dist/chunks/{chunk-OGL227XV.js → chunk-Y3AMP22L.js} +1 -1
  23. package/dist/chunks/compaction-config-7J2XE35D.js +2 -0
  24. package/dist/chunks/{construction-bootstrap-3TQWTHSQ.js → construction-bootstrap-5F5KF2BZ.js} +1 -1
  25. package/dist/chunks/{dist-D3EPVAOZ.js → dist-2RA7LSH3.js} +1 -1
  26. package/dist/chunks/{dist-ZJFTZJ55.js → dist-URKXBOC6.js} +1 -1
  27. package/dist/chunks/host-RKZ2OGFT.js +2 -0
  28. package/dist/chunks/run-manager-7RM4HEH6.js +2 -0
  29. package/dist/chunks/{utils-HMVP6XPH.js → utils-X3TEH6IO.js} +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/kodax_cli.js +8 -8
  32. package/dist/provider-capabilities.json +35 -7
  33. package/dist/runtime-worker.js +7 -7
  34. package/dist/sdk-a2a.js +1 -1
  35. package/dist/sdk-agent.js +1 -1
  36. package/dist/sdk-coding.js +1 -1
  37. package/dist/sdk-experimental-memory.js +1 -1
  38. package/dist/sdk-llm.js +1 -1
  39. package/dist/sdk-mcp.js +1 -1
  40. package/dist/sdk-media.js +1 -1
  41. package/dist/sdk-repl.js +1 -1
  42. package/dist/sdk-runtime.js +1 -1
  43. package/dist/sdk-session.js +1 -1
  44. package/dist/sdk-skills.js +1 -1
  45. package/package.json +1 -1
  46. package/dist/chunks/argument-completer-GHWEWPVQ.js +0 -2
  47. package/dist/chunks/chunk-6YUDR7WN.js +0 -5
  48. package/dist/chunks/compaction-config-L2YZK7Q3.js +0 -2
  49. package/dist/chunks/host-KHDXYFVG.js +0 -2
  50. package/dist/chunks/run-manager-CD24OO4V.js +0 -2
package/CHANGELOG.md CHANGED
@@ -6,11 +6,32 @@ All notable changes to this project will be documented in this file.
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.7.76] - 2026-07-25
10
+
11
+ > Git tag and GitHub Release are published by the release workflow. npm
12
+ > publication remains the operator's final manual step.
13
+
14
+ ### Changed
15
+
16
+ - **Kimi Code defaults to the official K3 256K route.** The `kimi-code`
17
+ provider now defaults to `k3-256k` and sends that exact upstream model ID.
18
+ `kimi-for-coding` remains selectable for K2.7 Code, alongside
19
+ `kimi-for-coding-highspeed` and the 1M `k3` tier. K3 now exposes the
20
+ documented `low` / `high` / `max` reasoning levels with `high` as default;
21
+ media metadata marks `k3-256k` as image-capable but not video-capable, and
22
+ nominal subscription accounting reflects the 1M `k3` route's roughly 2x
23
+ quota consumption.
24
+
25
+ ### Verification
26
+
27
+ - Added direct live-wire smoke coverage for all four Kimi Code subscription
28
+ routes: `k3-256k`, `k3`, `kimi-for-coding`, and
29
+ `kimi-for-coding-highspeed`.
30
+
9
31
  ## [0.7.75] - 2026-07-24
10
32
 
11
- > Package, code, tests, and documentation are prepared for SDK/Space validation.
12
- > The `v0.7.75` tag, GitHub Release, and npm publication are intentionally not
13
- > created yet.
33
+ > The npm package was published manually. The `v0.7.75` Git tag and GitHub
34
+ > Release were skipped; the binary-release changes roll into `v0.7.76`.
14
35
 
15
36
  ### Changed
16
37
 
@@ -43,8 +64,9 @@ All notable changes to this project will be documented in this file.
43
64
  - Updated the release guide, current architecture/design baselines, SDK
44
65
  embedder guidance, feature index, roadmap, issue tracker, English/Chinese
45
66
  READMEs, and the v0.7.75 regression guide for the SDK validation candidate.
46
- - Rescheduled FEATURE_263 from v0.7.75 to v0.7.77 and retained v0.7.75 as a
47
- feature-free stabilization release.
67
+ - Rescheduled FEATURE_263 from v0.7.75 to v0.7.77 and then to v0.7.78; moved
68
+ FEATURE_274 from v0.7.76 to v0.7.77. v0.7.75 and v0.7.76 remain feature-free
69
+ stabilization releases.
48
70
 
49
71
  ## [0.7.74] - 2026-07-23
50
72
 
package/README.md CHANGED
@@ -399,6 +399,12 @@ clarification required to finish the current request, emits budget-approval
399
399
  state only for eligible Sidecar revisions, and preserves structured blocked
400
400
  reasons across embedded and daemon Runtime boundaries.
401
401
 
402
+ **v0.7.76 Kimi Code catalog refresh:** `kimi-code` now defaults to the official
403
+ `k3-256k` Model ID and sends it unchanged. `kimi-for-coding` remains selectable
404
+ for K2.7 Code, alongside `kimi-for-coding-highspeed` and the 1M `k3` tier. K3
405
+ supports `low` / `high` / `max` reasoning with `high` as default; the 256K
406
+ route supports image input but not video input.
407
+
402
408
  One daemon owns many sessions. Different sessions may run concurrently; starts
403
409
  within the same session are queued so that only one run is active for that
404
410
  session. Multiple `kodax` processes can attach to the same daemon and open or
@@ -1293,7 +1299,7 @@ await runInkInteractiveMode({ provider: 'zhipu-coding', effort: 'auto' });
1293
1299
  | anthropic | `ANTHROPIC_API_KEY` | Native | claude-sonnet-4-6 (`claude-opus-4-6` / `claude-haiku-4-5` via `/model`) |
1294
1300
  | openai | `OPENAI_API_KEY` | Native | gpt-5.3-codex (`gpt-5.4` / `gpt-5.3-codex-spark` via `/model`) |
1295
1301
  | kimi | `KIMI_API_KEY` | Native | kimi-k2.7-code (262,144-token context; `kimi-k2.7-code-highspeed` / `kimi-k2.6` / `kimi-k2.5` via `/model`) |
1296
- | kimi-code | `KIMI_CODE_API_KEY` | Native | kimi-for-coding (`k3-256k` for Moderato / `k3` 1M for Allegretto+ / `kimi-for-coding-highspeed` via `/model`; both K3 choices use upstream `k3`) |
1302
+ | kimi-code | `KIMI_CODE_API_KEY` | Native | k3-256k (Moderato+, 256K, direct upstream ID; `k3` 1M / `kimi-for-coding` K2.7 Code / `kimi-for-coding-highspeed` via `/model`) |
1297
1303
  | qwen | `QWEN_API_KEY` | Native | qwen3.5-plus |
1298
1304
  | qwen-token-plan | `QWEN_TOKEN_API_KEY` | Native | qwen3.8-max-preview (Anthropic-compat; `qwen3.7-max` / `qwen3.7-plus` / `qwen3.6-flash` / `glm-5.2` / `deepseek-v4-pro` via `/model`; all 1M context; image input on Qwen 3.8 / 3.7 Plus / 3.6 Flash) |
1299
1305
  | zhipu | `ZHIPU_API_KEY` | Native | glm-5 (`glm-5.2` 1M ctx / `glm-5.1` / `glm-5-turbo` via `/model`) |
package/README_CN.md CHANGED
@@ -102,6 +102,11 @@ packaged Electron 回归连续执行 20 次普通查询并检查控制台可见
102
102
  澄清”,只为符合资格的 Sidecar `revise` 发布预算审批状态,并在 embedded 与
103
103
  daemon Runtime 边界保留结构化 blocked 原因。
104
104
 
105
+ **v0.7.76 Kimi Code 模型目录更新**:`kimi-code` 现在默认使用官方
106
+ `k3-256k` Model ID,并直接发送该同名 ID。`kimi-for-coding` 继续作为 K2.7 Code
107
+ 可选模型,同时保留 `kimi-for-coding-highspeed` 与 1M `k3` tier。K3 支持
108
+ `low` / `high` / `max` 思考强度,默认 `high`;256K 路由支持图片但不支持视频输入。
109
+
105
110
  **v0.7.72–v0.7.73 Runtime 权限契约:**Auto Mode 的权限决策由 Runtime Session 持有,
106
111
  不再由 UI hook 抢先决定。Runtime 会跨 turn 复用 LLM/rules guardrail,先分类、
107
112
  仅在 `escalate` 时创建共享 permission 请求,并把自动降级到 rules 的结果持久化到
@@ -509,7 +514,7 @@ dist/binary/linux-x64/
509
514
  | anthropic | `ANTHROPIC_API_KEY` | Native | claude-sonnet-4-6(可 `/model` 切换 `claude-opus-4-6` / `claude-haiku-4-5`) |
510
515
  | openai | `OPENAI_API_KEY` | Native | gpt-5.3-codex(可 `/model` 切换 `gpt-5.4` / `gpt-5.3-codex-spark`) |
511
516
  | kimi | `KIMI_API_KEY` | Native | kimi-k2.7-code(262,144 token;可 `/model` 切换 `kimi-k2.7-code-highspeed` / `kimi-k2.6` / `kimi-k2.5`) |
512
- | kimi-code | `KIMI_CODE_API_KEY` | Native | kimi-for-coding(可 `/model` 切换 `k3-256k`〔Moderato,256K〕/ `k3`〔Allegretto+,1M〕/ `kimi-for-coding-highspeed`;两个 K3 选项均请求上游 `k3`) |
517
+ | kimi-code | `KIMI_CODE_API_KEY` | Native | k3-256k(Moderato+,256K,直接请求同名上游模型;可 `/model` 切换 `k3`〔Allegretto+,1M〕/ `kimi-for-coding`〔K2.7 Code〕/ `kimi-for-coding-highspeed`) |
513
518
  | qwen | `QWEN_API_KEY` | Native | qwen3.5-plus |
514
519
  | qwen-token-plan | `QWEN_TOKEN_API_KEY` | Native | qwen3.8-max-preview(Anthropic 协议;可 `/model` 切换 `qwen3.7-max` / `qwen3.7-plus` / `qwen3.6-flash` / `glm-5.2` / `deepseek-v4-pro`;均为 1M ctx;Qwen 3.8 / 3.7 Plus / 3.6 Flash 支持图片理解) |
515
520
  | zhipu | `ZHIPU_API_KEY` | Native | glm-5(可 `/model` 切换 `glm-5.2` 1M ctx / `glm-5.1` / `glm-5-turbo`) |
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ea as i,Ka as j,da as d,ea as e,fa as f,j as c,ua as g,wa as h}from"./chunk-5WSOB34U.js";import"./chunk-BN3W2DQY.js";import"./chunk-G5VW55T4.js";import"./chunk-737LI7OS.js";import"./chunk-Q65EAOX6.js";import{sb as a,tb as b}from"./chunk-QSMXI4MH.js";import"./chunk-OGL227XV.js";import"./chunk-6YUDR7WN.js";import"./chunk-F7AIEHSS.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,j as runKodaX,i as saveSessionSnapshot,a as validateAndFixToolHistory};
2
+ import{Ea as i,Ka as j,da as d,ea as e,fa as f,j as c,ua as g,wa as h}from"./chunk-OD6LVXU6.js";import"./chunk-IDCGNQ4H.js";import"./chunk-PXKSE54E.js";import"./chunk-7FJNLJLF.js";import"./chunk-D3T24FJW.js";import{sb as a,tb as b}from"./chunk-VWSLC2WO.js";import"./chunk-Y3AMP22L.js";import"./chunk-COQYLD4U.js";import"./chunk-EI4JBQKL.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,j as runKodaX,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{Ja as a,Ka as b}from"./chunk-HS3XHF3R.js";import"./chunk-4PWPNCNK.js";import"./chunk-RDXRM3UI.js";import"./chunk-TGMBHGZO.js";import"./chunk-SMT2JSM3.js";import"./chunk-OSF3H4RR.js";import"./chunk-OD6LVXU6.js";import"./chunk-IDCGNQ4H.js";import"./chunk-PXKSE54E.js";import"./chunk-7FJNLJLF.js";import"./chunk-D3T24FJW.js";import"./chunk-VWSLC2WO.js";import"./chunk-Y3AMP22L.js";import"./chunk-COQYLD4U.js";import"./chunk-EI4JBQKL.js";import"./chunk-ONUPGMER.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{T as xe,V as be}from"./chunk-5WSOB34U.js";import{C as z,Ca as W,F as V,G as ue,H as q,Ma as ve,Qa as ye,ma as de,na as fe,oa as pe,pa as me,q as le,qa as ge,ra as H,ya as he,za as C}from"./chunk-Q65EAOX6.js";import{Fa as Ee}from"./chunk-QSMXI4MH.js";import{e as we}from"./chunk-OGL227XV.js";import{a as o}from"./chunk-ONUPGMER.js";import u from"fs";import p from"path";import{exec as tt,spawnSync as nt}from"child_process";import{promisify as rt}from"util";import{fileURLToPath as ot}from"url";var J="en";function Ue(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}o(Ue,"detectSystemLocale");function Se(e){if(!e||e==="auto"){J=Ue();return}J=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}o(Se,"setLocale");var Pe={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",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",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88"}};function Dt(e,t){let r=Pe[J][e]??Pe.en[e]??e;if(t)for(let[i,s]of Object.entries(t))r=r.replace(`{${i}}`,String(s));return r}o(Dt,"t");var _e={core:`// KodaX core configuration template.
2
+ import{T as xe,V as be}from"./chunk-OD6LVXU6.js";import{C as z,Ca as W,F as V,G as ue,H as q,Ma as ve,Qa as ye,ma as de,na as fe,oa as pe,pa as me,q as le,qa as ge,ra as H,ya as he,za as C}from"./chunk-D3T24FJW.js";import{Fa as Ee}from"./chunk-VWSLC2WO.js";import{e as we}from"./chunk-Y3AMP22L.js";import{a as o}from"./chunk-ONUPGMER.js";import u from"fs";import p from"path";import{exec as tt,spawnSync as nt}from"child_process";import{promisify as rt}from"util";import{fileURLToPath as ot}from"url";var J="en";function Ue(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}o(Ue,"detectSystemLocale");function Se(e){if(!e||e==="auto"){J=Ue();return}J=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}o(Se,"setLocale");var Pe={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",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",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88"}};function Dt(e,t){let r=Pe[J][e]??Pe.en[e]??e;if(t)for(let[i,s]of Object.entries(t))r=r.replace(`{${i}}`,String(s));return r}o(Dt,"t");var _e={core:`// KodaX core configuration template.
3
3
  // Copy only the fields you need to ~/.kodax/config.json (strict JSON).
4
4
  // MCP, A2A, and Extensions live in ~/.kodax/integrations/*.json; use
5
5
  // \`kodax integrations migrate --dry-run\` for legacy declarations.
@@ -155,4 +155,4 @@ import{T as xe,V as be}from"./chunk-5WSOB34U.js";import{C as z,Ca as W,F as V,G
155
155
  }
156
156
  `};function Ce(e){return _e[e]}o(Ce,"getConfigTemplate");import{closeSync as Y,existsSync as m,fsyncSync as Oe,mkdirSync as ee,openSync as te,readFileSync as Ie,renameSync as Re,statSync as Ge,unlinkSync as Q,watch as ze,writeFileSync as De}from"node:fs";import{createHash as Ve}from"node:crypto";import g from"node:path";var qe={mcp:"mcp.json",a2a:"a2a.json",extensions:"extensions.json"},He=new Set(["type","command","args","cwd","env","url","headers","connect","startupTimeoutMs","requestTimeoutMs","auth"]);function w(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(w,"isRecord");function E(e,t){if(!w(e))throw new Error(`${t} must be an object.`);return e}o(E,"requireRecord");function T(e,t,n){let r=Object.keys(e).find(i=>!t.has(i));if(r!==void 0)throw new Error(`${n} has unknown field "${r}".`)}o(T,"assertNoUnknownKeys");function Le(e,t){if(e.version!==1)throw new Error(`${t} version must be 1.`)}o(Le,"requireVersionOne");function ke(e,t){let n=E(e,t);for(let[r,i]of Object.entries(n))if(r.trim().length===0||typeof i!="string")throw new Error(`${t} must contain non-empty string keys and string values.`);return structuredClone(n)}o(ke,"requireStringMap");function Z(e,t){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`${t} must be an array of non-empty strings.`);return e.map(n=>n.trim())}o(Z,"requireStringArray");function B(e,t){if(e!==void 0&&(!Number.isFinite(e)||Number(e)<=0))throw new Error(`${t} must be a positive number.`)}o(B,"validatePositiveNumber");function We(e,t){if(e.trim().length===0)throw new Error("MCP server names must not be empty.");let n=E(t,`MCP server "${e}"`);T(n,He,`MCP server "${e}"`);let r=n.type??"stdio";if(!["stdio","sse","streamable-http","http"].includes(String(r)))throw new Error(`MCP server "${e}" has an unsupported transport type.`);if(r==="stdio"){if(typeof n.command!="string"||n.command.trim().length===0)throw new Error(`MCP server "${e}" stdio transport requires command.`)}else if(typeof n.url!="string"||n.url.trim().length===0)throw new Error(`MCP server "${e}" ${String(r)} transport requires url.`);if(n.args!==void 0&&Z(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&&ke(n.env,`MCP server "${e}" env`),n.headers!==void 0&&ke(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(B(n.startupTimeoutMs,`MCP server "${e}" startupTimeoutMs`),B(n.requestTimeoutMs,`MCP server "${e}" requestTimeoutMs`),n.auth!==void 0){let i=E(n.auth,`MCP server "${e}" auth`);if(T(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&&Z(i.scopes,`MCP server "${e}" auth.scopes`),B(i.redirectPort,`MCP server "${e}" auth.redirectPort`)}return structuredClone(n)}o(We,"parseMcpServer");function k(e){let t=E(e,"MCP integration config");T(t,new Set(["version","servers"]),"MCP integration config"),Le(t,"MCP integration config");let n=E(t.servers,"MCP integration config servers"),r={};for(let[i,s]of Object.entries(n))r[i]=We(i,s);return{version:1,servers:r}}o(k,"parseMcpIntegrationDocument");function M(e){let t=E(e,"Extensions integration config");T(t,new Set(["version","paths"]),"Extensions integration config"),Le(t,"Extensions integration config");let n=Z(t.paths,"Extensions integration config paths");if(new Set(n).size!==n.length)throw new Error("Extensions integration config paths must not contain duplicates.");return{version:1,paths:n}}o(M,"parseExtensionsIntegrationDocument");function P(e,t){return g.join(g.resolve(t),"integrations",qe[e])}o(P,"resolveIntegrationConfigPath");function ne(e){return g.join(g.resolve(e),"config.json")}o(ne,"coreConfigPath");function Te(e){return Ve("sha256").update(e).digest("hex")}o(Te,"hashText");function re(e){let t=Ie(e,"utf8");try{return{raw:t,value:JSON.parse(t)}}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`Invalid JSON: ${r}`)}}o(re,"readJsonFile");function A(e){return{domain:e.domain,source:e.source,path:e.path,revision:Te(e.raw),document:structuredClone(e.document),loadedAt:new Date().toISOString()}}o(A,"snapshot");function N(e){let t=ne(e);return m(t)?E(re(t).value,"Core config"):{}}o(N,"readCoreConfig");function $(e){let t=P("mcp",e);if(m(t)){let i=re(t);return A({domain:"mcp",source:"user",path:t,raw:i.raw,document:k(i.value)})}let n=N(e).mcpServers,r=k({version:1,servers:w(n)?n:{}});return A({domain:"mcp",source:n===void 0?"default":"legacy-user",path:t,raw:JSON.stringify(r),document:r})}o($,"readMcpIntegration");function K(e){let t=P("extensions",e);if(m(t)){let i=re(t);return A({domain:"extensions",source:"user",path:t,raw:i.raw,document:M(i.value)})}let n=N(e).extensions,r=M({version:1,paths:Array.isArray(n)?n:[]});return A({domain:"extensions",source:n===void 0?"default":"legacy-user",path:t,raw:JSON.stringify(r),document:r})}o(K,"readExtensionsIntegration");function Je(e){if(!w(e))return[];let t=[],n=/(token|secret|password|api[_-]?key|authorization)/i;for(let[r,i]of Object.entries(e))if(w(i))for(let s of["env","headers"]){let a=i[s];if(w(a))for(let[l,c]of Object.entries(a))n.test(l)&&typeof c=="string"&&!c.startsWith("${env:")&&t.push(`MCP server "${r}" ${s}.${l} may contain a literal secret.`)}return t}o(Je,"likelySecretWarnings");function Be(e){let t=N(e),n=P("mcp",e),r=P("extensions",e),i=t.mcpServers,s=t.extensions,a=w(i)?Object.keys(i).length:0,l=Array.isArray(s)?s.length:0,c=o((b,R,D)=>m(b)?{action:"none",entries:R,destination:b,reason:"destination-exists"}:D?{action:"create",entries:R,destination:b}:{action:"none",entries:0,destination:b,reason:"legacy-absent"},"domainPlan");return{mcp:c(n,a,i!==void 0),extensions:c(r,l,s!==void 0),warnings:Je(i)}}o(Be,"planLegacyIntegrationMigration");function Ye(e,t){let n=ne(e);ee(g.dirname(n),{recursive:!0,mode:448});let r=`${n}.${process.pid}.${Date.now()}.tmp`,i=te(r,"wx",384);try{De(i,`${JSON.stringify(t,null,2)}
157
157
  `,"utf8"),Oe(i)}finally{Y(i)}try{Re(r,n)}catch(s){throw m(r)&&Q(r),new Error("Failed to atomically clean legacy integration fields.",{cause:s})}}o(Ye,"writeCoreConfigAtomically");function Ft(e){let t=Be(e.configHome),n=N(e.configHome),r=[];t.mcp.action==="create"&&(O({domain:"mcp",configHome:e.configHome,document:{version:1,servers:w(n.mcpServers)?n.mcpServers:{}},validate:k}),r.push("mcp")),t.extensions.action==="create"&&(O({domain:"extensions",configHome:e.configHome,document:{version:1,paths:Array.isArray(n.extensions)?n.extensions:[]},validate:M}),r.push("extensions"));let i=!1;if(e.cleanupLegacy&&m(ne(e.configHome))){let s={...n};m(t.mcp.destination)&&delete s.mcpServers,m(t.extensions.destination)&&delete s.extensions,Qe(n,s)||(Ye(e.configHome,s),i=!0)}return{...t,applied:r,cleanedLegacy:i}}o(Ft,"migrateLegacyIntegrationConfig");function Qe(e,t){return JSON.stringify(e)===JSON.stringify(t)}o(Qe,"isDeepStrictEqualForConfig");function Ze(e){return m(e)?Te(Ie(e,"utf8")):void 0}o(Ze,"currentUserRevision");function et(e){let t=`${e}.lock`;try{return{fd:te(t,"wx",384),path:t}}catch(n){throw new Error(`Integration configuration is busy: ${g.basename(e)}`,{cause:n})}}o(et,"acquireWriteLock");function O(e){let t=P(e.domain,e.configHome),n=e.validate(e.document);ee(g.dirname(t),{recursive:!0,mode:448});let r=et(t);try{let i=Ze(t);if(e.expectedRevision!==void 0&&i!==e.expectedRevision)throw new Error(`Integration configuration revision changed (expected ${e.expectedRevision}, actual ${i??"missing"}).`);let s=`${JSON.stringify(n,null,2)}
158
- `,a=`${t}.${process.pid}.${Date.now()}.tmp`,l=te(a,"wx",384);try{De(l,s,"utf8"),Oe(l)}finally{Y(l)}try{Re(a,t)}catch(c){throw m(a)&&Q(a),new Error(`Failed to atomically replace ${g.basename(t)}.`,{cause:c})}return A({domain:e.domain,source:"user",path:t,raw:s,document:n})}finally{Y(r.fd),m(r.path)&&Q(r.path)}}o(O,"writeIntegrationDocument");function Me(e){if(!m(e))return"missing";let t=Ge(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}o(Me,"metadataSignature");function L(e,t){return{code:e,message:t,time:new Date().toISOString()}}o(L,"safeDiagnostic");var Ae=class{static{o(this,"IntegrationConfigController")}#a;#r;#c;#l;#e;#t;#u="";#o;#n;#i;#d=Promise.resolve();#s=new Set;constructor(t){this.#a=t.domain,this.#r=P(t.domain,t.configHome),this.#l=t.validate,this.#c=t.read}async initialize(){let t=await this.reload();if(!t.ok||!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(){return{domain:this.#a,path:this.#r,...this.#e?{revision:this.#e.revision,source:this.#e.source,lastReloadAt:this.#e.loadedAt}:{},...this.#t?{diagnostic:this.#t}:{},watching:this.#o!==void 0}}subscribe(t){return this.#s.add(t),()=>{this.#s.delete(t)}}reload(){let t=this.#d.then(()=>this.#f());return this.#d=t.then(()=>{},()=>{}),t}async#f(){this.#u=Me(this.#r);let t;try{t=this.#c(),this.#l(t.document)}catch{return this.#t=L("invalid-config","Integration configuration is invalid; check the file against its versioned schema."),{ok:!1,error:this.#t.message}}let n=this.#e?structuredClone(this.#e):void 0;try{for(let r of this.#s)await r(structuredClone(t),n)}catch{return this.#t=L("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,{ok:!0,snapshot:structuredClone(t)}}async ensureCurrent(){return Me(this.#r)===this.#u&&this.#e?{ok:!0,snapshot:structuredClone(this.#e)}:this.reload()}startWatching(t=100,n=2e3){if(!(this.#o||this.#i)){ee(g.dirname(this.#r),{recursive:!0,mode:448});try{this.#o=ze(g.dirname(this.#r),(r,i)=>{i!==null&&i.toString()!==g.basename(this.#r)||(this.#n&&clearTimeout(this.#n),this.#n=setTimeout(()=>{this.#n=void 0,this.reload()},t),this.#n.unref?.())}),this.#o.unref(),this.#o.on("error",()=>{this.#t=L("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")})}catch{this.#t=L("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}this.#i=setInterval(()=>{this.ensureCurrent()},n),this.#i.unref?.()}}close(){this.#n&&clearTimeout(this.#n),this.#n=void 0,this.#i&&clearInterval(this.#i),this.#i=void 0,this.#o?.close(),this.#o=void 0,this.#s.clear()}};var it=rt(tt),st=2,Ne=!1,d=we(),tn=p.join(d,"sessions"),f=p.join(d,"config.json"),nn=60,h=null,ie=!1,at="dumb";function ct(e){let t=p.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",r=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",r],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",r]:["-lc",r],sentinel:n}}o(ct,"buildShellEnvCommand");function lt(e,t){let n=`${t}\0`,r=e.lastIndexOf(n);if(r===-1)return{};let i=e.slice(r+n.length),s={};for(let a of i.split("\0")){if(!a)continue;let l=a.indexOf("=");l<=0||(s[a.slice(0,l)]=a.slice(l+1))}return s}o(lt,"parseNullDelimitedShellEnv");function ut(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let r=e.shell??t.SHELL;if(!r||!p.isAbsolute(r))return!1;let{args:i,sentinel:s}=ct(r),a=e.run??nt,l={...t,TERM:at},c=a(r,i,{encoding:"utf8",env:l,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(c.status!==0||!c.stdout)return!1;let b=typeof c.stdout=="string"?c.stdout:c.stdout.toString("utf8"),R=lt(b,s),D=!1;for(let[G,Fe]of Object.entries(R))G!=="TERM"&&t[G]===void 0&&(t[G]=Fe,D=!0);return D}o(ut,"hydrateProcessEnvFromShell");function dt(){if(!ie){ie=!0;try{ut()}catch{}}}o(dt,"ensureShellEnvironmentHydrated");function rn(){ie=!1}o(rn,"resetShellEnvironmentHydrationForTesting");function ft(e){he(e.customProviders??[])}o(ft,"registerConfiguredCustomProviders");function se(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:[]}o(se,"normalizeConfiguredExtensions");function pt(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{u.mkdirSync(p.dirname(f),{recursive:!0}),u.writeFileSync(f,JSON.stringify(t,null,2))}catch{}return t}o(pt,"migrateLegacyPermissionModeInConfig");function mt(e){if(e.permissionMode!=="auto-in-project")return e;try{let t=u.readFileSync(f,"utf-8"),n=t.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t&&u.writeFileSync(f,n)}catch{}return{...e,permissionMode:"auto"}}o(mt,"migrateAutoInProjectAliasInConfig");function gt(){if(h)return h;let e="0.7.75";if(e)return h=e,h;let t=p.join(p.dirname(ot(import.meta.url)),"../../package.json");if(u.existsSync(t))try{return h=JSON.parse(u.readFileSync(t,"utf-8")).version??"0.0.0",h??"0.0.0"}catch{}return h="0.0.0",h}o(gt,"getVersion");var on=gt();function ht(e){return fe(e)}o(ht,"getProviderModel");function ae(e,t){let n=new Set(e.map(i=>i.toLowerCase())),r=[...e];for(let i of t)n.has(i.toLowerCase())||r.push(i);return r}o(ae,"mergeModels");function vt(e,t){t||(t=ce().providerModels);let n=t?.[e];if(n&&n.length>0){try{let r=H(e);if(r.length>0)return ae(n,r)}catch{}try{let r=C(e);if(r)return ae(n,r.getAvailableModels())}catch{}return n}try{let r=H(e);if(r.length>0)return r}catch{}try{let r=C(e);if(r)return r.getAvailableModels()}catch{}return[]}o(vt,"getProviderAvailableModels");function yt(e,t){let n=pe(e,t);if(n!=="unknown")return n;try{let r=C(e);if(r)return r.getReasoningCapability(t)}catch{}return"unknown"}o(yt,"getProviderReasoningCapability");function wt(e){let t=me(e);if(t)return t;try{return W().find(r=>r.name===e)?.capabilityProfile??null}catch{return null}}o(wt,"getProviderCapabilityProfile");function je(e,t){let n=wt(e),r=yt(e,t);if(n)return{capabilityProfile:n,reasoningCapability:r};try{let i=ve(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}o(je,"getProviderCapabilityMetadata");function sn(e,t){let n=je(e,t);return n?xe({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}o(sn,"getProviderCapabilitySnapshot");function Et(e,t,n,r){let i=je(e,t);return i?be({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:r}):null}o(Et,"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",r=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${r}`}o(an,"describeProviderCapabilitySummary");function cn(e){switch(e){case"native-budget":return"B";case"native-effort":return"E";case"native-toggle":return"T";case"native-adaptive":return"A";default:return"-"}}o(cn,"formatReasoningCapabilityShort");function _(e){if(e)return e==="none"?"off":e}o(_,"formatReasoningEffortForDisplay");function X(e,t){let n=_(t);n&&!e.includes(n)&&e.push(n)}o(X,"pushUniqueEffortDisplay");function ln(e,t){let n=["auto"],i=U(e,t)?.supportedEfforts?.filter(s=>s.isUserVisible!==!1);if(!i||i.length===0){for(let s of["off","low","medium","high"])X(n,s);return n}for(let s of i)X(n,s.value);return n}o(ln,"getProviderReasoningEffortOptions");function un(e,t){let n=U(e,t),r=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(c=>c.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let c of["low","medium","high"])X(s,c);a=!0}else for(let c of i){if(c.value==="none"){a=!0;continue}if(r.has(c.value)){a=!0;continue}X(s,c.value)}let l=[];return a&&l.push("off"),l.push(...s),l.push("auto"),l}o(un,"getProviderReasoningEffortCycle");function xt(e,t){if(t===!1)return"off";switch(e){case"off":return"off";case"quick":return"low";case"balanced":return"medium";case"deep":return"high";default:return"auto"}}o(xt,"legacyReasoningModeToEffortDisplay");function U(e,t){let n=t??ht(e);if(!n)return;let r=ye(e,n)?.reasoningProfile;if(r)return le(r,Ee(e,n))}o(U,"resolveReasoningProfileForDisplay");function dn(e){let t=_(e.effort)??xt(e.reasoningMode,e.thinking),n=U(e.provider,e.model);if(!n)return t;try{let r=ue({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=_(r.configuredEffort)??t,a=r.configuredEffort!==void 0&&n.disabledEfforts?.includes(r.configuredEffort)===!0?"off":_(r.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let r=q({currentEffort:e.effort,capability:n}),i=_(e.effort)??t,s=_(r.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}o(dn,"formatReasoningEffortStatusLabel");function fn(e){let t=It(e);if(!t)return{preserved:!0};let n=U(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let r=q({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:r.effectiveEffort,preserved:r.preserved,diagnostic:r.diagnostic}}o(fn,"resolveProviderReasoningRuntimeEffort");function bt(e){switch(e){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";case"native-adaptive":return"adaptive";default:return"none"}}o(bt,"describeReasoningCapabilityControl");function pn(e,t){if(e==="off")return"Reasoning disabled";switch(t){case"native-budget":return"Uses native thinking budget control";case"native-effort":return"Uses native reasoning effort control";case"native-toggle":return"Uses provider-native thinking toggle only";case"native-adaptive":return"Model adaptively decides thinking depth (Opus 4.7+)";case"none":return"Runs without native reasoning parameters";case"prompt-only":return"Uses prompt overlays only; no native reasoning parameter";default:return"Runs without native reasoning parameters"}}o(pn,"describeReasoningExecution");function mn(e){let t=[];e||(e=ce().providerModels);for(let n of ge())t.push({name:n.name,model:n.model,models:vt(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=W().map(r=>({...r,models:(()=>{let i=e?.[r.name];return i&&i.length>0?ae(i,r.models):r.models})()}));t.push(...n)}catch{}return t}o(mn,"getProviderList");function gn(e){if(de(e))return!0;try{return C(e)?.isConfigured()??!1}catch{return!1}}o(gn,"isProviderConfigured");var F=class extends Error{static{o(this,"InvalidAgentModeConfigError")}};function Pt(e){let t=e.agentMode;if(t===void 0||t==="ama"||t==="sa")return e;if(t!=="amaw"&&t!=="ama-workflow")throw new F(`Invalid agentMode "${t}" in ${f}. Expected "ama" or "sa".`);let n={...e,agentMode:"ama",schemaVersion:Math.max(e.schemaVersion??0,st)},r=`${f}.migrate-${process.pid}.tmp`;try{u.writeFileSync(r,JSON.stringify(n,null,2),{mode:384}),u.renameSync(r,f)}catch{u.rmSync(r,{force:!0})}return Ne||(process.emitWarning(`Migrated persisted agentMode "${t}" to "ama". Workflow use is now explicit intent.`,{code:"KODAX_AGENT_MODE_MIGRATED"}),Ne=!0),n}o(Pt,"migrateLegacyAgentModeConfig");function ce(){try{if(u.existsSync(f)){let n=JSON.parse(u.readFileSync(f,"utf-8")),r=Pt(n),i=r.reasoningCeiling??r.reasoningMode,s=[],a={};try{s=[...K(d).document.paths]}catch{}try{a=$(d).document.servers}catch{}return mt(pt({...r,reasoningMode:i,extensions:se(s),mcpServers:a}))}}catch(n){if(n instanceof F)throw n}let e,t;try{let n=K(d);n.source!=="default"&&(e=se([...n.document.paths]))}catch{}try{let n=$(d);n.source!=="default"&&(t=n.document.servers)}catch{}return{...e===void 0?{}:{extensions:e},...t===void 0?{}:{mcpServers:t}}}o(ce,"loadConfig");var St=p.join(d,"config.example.jsonc"),oe={mcp:p.join(d,"integrations","mcp.example.jsonc"),a2a:p.join(d,"integrations","a2a.example.jsonc"),extensions:p.join(d,"integrations","extensions.example.jsonc")},_t=[{name:"core",path:St},{name:"mcp",path:oe.mcp},{name:"a2a",path:oe.a2a},{name:"extensions",path:oe.extensions}];function Ct(){let e=[];for(let t of _t)try{if(u.existsSync(t.path))continue;u.mkdirSync(p.dirname(t.path),{recursive:!0}),u.writeFileSync(t.path,Ce(t.name),"utf8"),e.push(t.path)}catch{}return e}o(Ct,"ensureExampleConfigFiles");function hn(){return Ct()[0]}o(hn,"ensureExampleConfigFile");var j=new Map;function kt(e,t){let n=process.env[e],r=j.get(e),i=r!==void 0&&n===r;if(n!==void 0&&!i){j.delete(e);return}if(t===void 0){i&&delete process.env[e],j.delete(e);return}process.env[e]=t,j.set(e,t)}o(kt,"projectConfigEnvironment");var Xe=[{configPath:"streamIdleTimeoutMs",env:"KODAX_STREAM_IDLE_TIMEOUT_MS",value:o(e=>x(e.streamIdleTimeoutMs),"value")},{configPath:"repoIntelligenceMode",env:"KODAX_REPO_INTELLIGENCE",value:o(e=>e.repoIntelligenceMode,"value")},{configPath:"repoIntelligenceTrace",env:"KODAX_REPO_INTELLIGENCE_TRACE",value:o(e=>S(e.repoIntelligenceTrace),"value")},{configPath:"verifierLog",env:"KODAX_VERIFIER_LOG",value:o(e=>S(e.verifierLog),"value")},{configPath:"stallLog",env:"KODAX_STALL_LOG",value:o(e=>S(e.stallLog),"value")},{configPath:"fallbackProviders",env:"KODAX_FALLBACK_PROVIDERS",value:o(e=>At(e.fallbackProviders),"value")},{configPath:"fastProvider",env:"KODAX_FAST_PROVIDER",value:o(e=>v(e.fastProvider),"value")},{configPath:"fastModel",env:"KODAX_FAST_MODEL",value:o(e=>v(e.fastModel),"value")},{configPath:"deepProvider",env:"KODAX_DEEP_PROVIDER",value:o(e=>v(e.deepProvider),"value")},{configPath:"deepModel",env:"KODAX_DEEP_MODEL",value:o(e=>v(e.deepModel),"value")},{configPath:"provider",env:"KODAX_PROVIDER",value:o(e=>v(e.provider),"value")},{configPath:"effort",env:"KODAX_EFFORT",value:o(e=>v(e.effort),"value")},{configPath:"runtimeMode",env:"KODAX_RUNTIME_MODE",value:o(e=>e.runtimeMode,"value")},{configPath:"sessionRetentionDays",env:"KODAX_SESSION_RETENTION_DAYS",value:o(e=>x(e.sessionRetentionDays),"value")},{configPath:"maxOutputTokens",env:"KODAX_MAX_OUTPUT_TOKENS",value:o(e=>x(e.maxOutputTokens),"value")},{configPath:"disablePromptCache",env:"KODAX_DISABLE_PROMPT_CACHE",value:o(e=>S(e.disablePromptCache),"value")},{configPath:"lsp",env:"KODAX_LSP",value:o(e=>S(e.lsp),"value")},{configPath:"lspAutoDownload",env:"KODAX_LSP_DOWNLOAD",value:o(e=>S(e.lspAutoDownload),"value")},{configPath:"acpLogLevel",env:"KODAX_ACP_LOG",value:o(e=>v(e.acpLogLevel),"value")},{configPath:"repoIntelligence.toolWaitMs",env:"KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS",value:o(e=>x(e.repoIntelligence?.toolWaitMs),"value")},{configPath:"repoIntelligence.workerTimeoutMs",env:"KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS",value:o(e=>x(e.repoIntelligence?.workerTimeoutMs),"value")},{configPath:"repoIntelligence.workerOldSpaceMb",env:"KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB",value:o(e=>x(e.repoIntelligence?.workerOldSpaceMb),"value")},{configPath:"repoIntelligence.storageDir",env:"KODAX_REPO_INTELLIGENCE_STORAGE_DIR",value:o(e=>v(e.repoIntelligence?.storageDir),"value")},{configPath:"workflow.maxConcurrency",env:"KODAX_WORKFLOW_MAX_CONCURRENCY",value:o(e=>x(e.workflow?.maxConcurrency),"value")}];function Mt(e){for(let t of Xe)kt(t.env,t.value(e))}o(Mt,"applyConfigSurfaceBridges");function v(e){return e?.trim()||void 0}o(v,"normalizedConfigString");function x(e){return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}o(x,"configNumberString");function S(e){return e===void 0?void 0:e?"1":"0"}o(S,"configBooleanString");function At(e){return e?.filter(t=>t.trim().length>0).join(",")}o(At,"configStringList");var vn=[...Xe.map(({configPath:e,env:t})=>({configPath:e,env:t}))];function Ot(e){Mt(e)}o(Ot,"applyConfigEnvironment");function yn(){dt();let e=ce();return Ot(e),ft(e),Se(e.locale),e}o(yn,"prepareRuntimeConfig");function wn(e){let t={};if(u.existsSync(f))try{let a=JSON.parse(u.readFileSync(f,"utf8"));a&&typeof a=="object"&&!Array.isArray(a)&&(t=a)}catch{}let{extensions:n,mcpServers:r,...i}=e,s={...t,...i};for(let a of Object.keys(i))i[a]===void 0&&delete s[a];if(u.mkdirSync(p.dirname(f),{recursive:!0}),u.writeFileSync(f,JSON.stringify(s,null,2)),n!==void 0){let a=K(d);O({domain:"extensions",configHome:d,...a.source==="user"?{expectedRevision:a.revision}:{},document:{version:1,paths:se(n)??[]},validate:M})}if(r!==void 0){let a=$(d);O({domain:"mcp",configHome:d,...a.source==="user"?{expectedRevision:a.revision}:{},document:{version:1,servers:r},validate:k})}}o(wn,"saveConfig");function En(e,t,n){return e.effort!==void 0||V(n).kind==="value"||t.effort!==void 0}o(En,"resolveInitialEffortOverride");function y(e){return e?.trim()?e:void 0}o(y,"nonEmptySelection");function xn(e){return y(e.explicitProvider)??y(e.environmentProvider)??y(e.configuredProvider)??e.defaultProvider}o(xn,"resolveRuntimeProviderSelection");function bn(e){let t=y(e.explicitModel);if(t)return t;let n=y(e.configuredModel);if(!n)return;let r=y(e.explicitProvider)??y(e.environmentProvider);return r?y(e.configuredProvider)===r?n:void 0:n}o(bn,"resolveRuntimeModelSelection");function Pn(e){if(e.explicitEffort!==void 0)return z(e.explicitEffort);let t=V(e.environmentEffort);return t.kind==="value"?t.value:e.configuredEffort===void 0?void 0:z(e.configuredEffort)}o(Pn,"resolveRuntimeEffortSelection");function It(e){return e.permissionMode==="plan"&&e.effortOverride!==!0&&e.planModeEffort!==void 0?e.planModeEffort:e.effort}o(It,"resolvePermissionModeEffort");async function Sn(e){try{let{stdout:t}=await it("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0});return t.trim()}catch{return null}}o(Sn,"getGitRoot");function Rt(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}o(Rt,"formatProviderSourceKind");function _n(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: ${Rt(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: ${bt(e.reasoningCapability)}`]}o(_n,"formatProviderCapabilityDetailLines");function Cn(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:Et(e,t,n,i.hints)})).filter(i=>i.decision!==null)}o(Cn,"getProviderCommonPolicyScenarios");var $e=.5,Ke=0,I={locked:!1,queue:[]};async function kn(e){for(;I.locked;)await new Promise(t=>I.queue.push(t));I.locked=!0;try{let t=(Date.now()-Ke)/1e3;t<$e&&await new Promise(r=>setTimeout(r,($e-t)*1e3));let n=await e();return Ke=Date.now(),n}finally{I.locked=!1;let t=I.queue.shift();t&&t()}}o(kn,"rateLimitedCall");export{Dt as a,_e as b,Ce as c,k as d,M as e,P as f,$ as g,K as h,Be as i,Ft as j,O as k,Ae as l,d as m,tn as n,f as o,nn as p,ut as q,rn as r,ft as s,gt as t,on as u,ht as v,vt as w,yt as x,wt as y,sn as z,Et as A,an as B,cn as C,_ as D,ln as E,un as F,dn as G,fn as H,bt as I,pn as J,mn as K,gn as L,ce as M,St as N,oe as O,Ct as P,hn as Q,vn as R,Ot as S,yn as T,wn as U,En as V,xn as W,bn as X,Pn as Y,It as Z,Sn as _,Rt as $,_n as aa,Cn as ba,kn as ca};
158
+ `,a=`${t}.${process.pid}.${Date.now()}.tmp`,l=te(a,"wx",384);try{De(l,s,"utf8"),Oe(l)}finally{Y(l)}try{Re(a,t)}catch(c){throw m(a)&&Q(a),new Error(`Failed to atomically replace ${g.basename(t)}.`,{cause:c})}return A({domain:e.domain,source:"user",path:t,raw:s,document:n})}finally{Y(r.fd),m(r.path)&&Q(r.path)}}o(O,"writeIntegrationDocument");function Me(e){if(!m(e))return"missing";let t=Ge(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}o(Me,"metadataSignature");function L(e,t){return{code:e,message:t,time:new Date().toISOString()}}o(L,"safeDiagnostic");var Ae=class{static{o(this,"IntegrationConfigController")}#a;#r;#c;#l;#e;#t;#u="";#o;#n;#i;#d=Promise.resolve();#s=new Set;constructor(t){this.#a=t.domain,this.#r=P(t.domain,t.configHome),this.#l=t.validate,this.#c=t.read}async initialize(){let t=await this.reload();if(!t.ok||!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(){return{domain:this.#a,path:this.#r,...this.#e?{revision:this.#e.revision,source:this.#e.source,lastReloadAt:this.#e.loadedAt}:{},...this.#t?{diagnostic:this.#t}:{},watching:this.#o!==void 0}}subscribe(t){return this.#s.add(t),()=>{this.#s.delete(t)}}reload(){let t=this.#d.then(()=>this.#f());return this.#d=t.then(()=>{},()=>{}),t}async#f(){this.#u=Me(this.#r);let t;try{t=this.#c(),this.#l(t.document)}catch{return this.#t=L("invalid-config","Integration configuration is invalid; check the file against its versioned schema."),{ok:!1,error:this.#t.message}}let n=this.#e?structuredClone(this.#e):void 0;try{for(let r of this.#s)await r(structuredClone(t),n)}catch{return this.#t=L("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,{ok:!0,snapshot:structuredClone(t)}}async ensureCurrent(){return Me(this.#r)===this.#u&&this.#e?{ok:!0,snapshot:structuredClone(this.#e)}:this.reload()}startWatching(t=100,n=2e3){if(!(this.#o||this.#i)){ee(g.dirname(this.#r),{recursive:!0,mode:448});try{this.#o=ze(g.dirname(this.#r),(r,i)=>{i!==null&&i.toString()!==g.basename(this.#r)||(this.#n&&clearTimeout(this.#n),this.#n=setTimeout(()=>{this.#n=void 0,this.reload()},t),this.#n.unref?.())}),this.#o.unref(),this.#o.on("error",()=>{this.#t=L("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")})}catch{this.#t=L("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}this.#i=setInterval(()=>{this.ensureCurrent()},n),this.#i.unref?.()}}close(){this.#n&&clearTimeout(this.#n),this.#n=void 0,this.#i&&clearInterval(this.#i),this.#i=void 0,this.#o?.close(),this.#o=void 0,this.#s.clear()}};var it=rt(tt),st=2,Ne=!1,d=we(),tn=p.join(d,"sessions"),f=p.join(d,"config.json"),nn=60,h=null,ie=!1,at="dumb";function ct(e){let t=p.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",r=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",r],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",r]:["-lc",r],sentinel:n}}o(ct,"buildShellEnvCommand");function lt(e,t){let n=`${t}\0`,r=e.lastIndexOf(n);if(r===-1)return{};let i=e.slice(r+n.length),s={};for(let a of i.split("\0")){if(!a)continue;let l=a.indexOf("=");l<=0||(s[a.slice(0,l)]=a.slice(l+1))}return s}o(lt,"parseNullDelimitedShellEnv");function ut(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let r=e.shell??t.SHELL;if(!r||!p.isAbsolute(r))return!1;let{args:i,sentinel:s}=ct(r),a=e.run??nt,l={...t,TERM:at},c=a(r,i,{encoding:"utf8",env:l,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(c.status!==0||!c.stdout)return!1;let b=typeof c.stdout=="string"?c.stdout:c.stdout.toString("utf8"),R=lt(b,s),D=!1;for(let[G,Fe]of Object.entries(R))G!=="TERM"&&t[G]===void 0&&(t[G]=Fe,D=!0);return D}o(ut,"hydrateProcessEnvFromShell");function dt(){if(!ie){ie=!0;try{ut()}catch{}}}o(dt,"ensureShellEnvironmentHydrated");function rn(){ie=!1}o(rn,"resetShellEnvironmentHydrationForTesting");function ft(e){he(e.customProviders??[])}o(ft,"registerConfiguredCustomProviders");function se(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:[]}o(se,"normalizeConfiguredExtensions");function pt(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{u.mkdirSync(p.dirname(f),{recursive:!0}),u.writeFileSync(f,JSON.stringify(t,null,2))}catch{}return t}o(pt,"migrateLegacyPermissionModeInConfig");function mt(e){if(e.permissionMode!=="auto-in-project")return e;try{let t=u.readFileSync(f,"utf-8"),n=t.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t&&u.writeFileSync(f,n)}catch{}return{...e,permissionMode:"auto"}}o(mt,"migrateAutoInProjectAliasInConfig");function gt(){if(h)return h;let e="0.7.76";if(e)return h=e,h;let t=p.join(p.dirname(ot(import.meta.url)),"../../package.json");if(u.existsSync(t))try{return h=JSON.parse(u.readFileSync(t,"utf-8")).version??"0.0.0",h??"0.0.0"}catch{}return h="0.0.0",h}o(gt,"getVersion");var on=gt();function ht(e){return fe(e)}o(ht,"getProviderModel");function ae(e,t){let n=new Set(e.map(i=>i.toLowerCase())),r=[...e];for(let i of t)n.has(i.toLowerCase())||r.push(i);return r}o(ae,"mergeModels");function vt(e,t){t||(t=ce().providerModels);let n=t?.[e];if(n&&n.length>0){try{let r=H(e);if(r.length>0)return ae(n,r)}catch{}try{let r=C(e);if(r)return ae(n,r.getAvailableModels())}catch{}return n}try{let r=H(e);if(r.length>0)return r}catch{}try{let r=C(e);if(r)return r.getAvailableModels()}catch{}return[]}o(vt,"getProviderAvailableModels");function yt(e,t){let n=pe(e,t);if(n!=="unknown")return n;try{let r=C(e);if(r)return r.getReasoningCapability(t)}catch{}return"unknown"}o(yt,"getProviderReasoningCapability");function wt(e){let t=me(e);if(t)return t;try{return W().find(r=>r.name===e)?.capabilityProfile??null}catch{return null}}o(wt,"getProviderCapabilityProfile");function je(e,t){let n=wt(e),r=yt(e,t);if(n)return{capabilityProfile:n,reasoningCapability:r};try{let i=ve(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}o(je,"getProviderCapabilityMetadata");function sn(e,t){let n=je(e,t);return n?xe({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}o(sn,"getProviderCapabilitySnapshot");function Et(e,t,n,r){let i=je(e,t);return i?be({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:r}):null}o(Et,"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",r=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${r}`}o(an,"describeProviderCapabilitySummary");function cn(e){switch(e){case"native-budget":return"B";case"native-effort":return"E";case"native-toggle":return"T";case"native-adaptive":return"A";default:return"-"}}o(cn,"formatReasoningCapabilityShort");function _(e){if(e)return e==="none"?"off":e}o(_,"formatReasoningEffortForDisplay");function X(e,t){let n=_(t);n&&!e.includes(n)&&e.push(n)}o(X,"pushUniqueEffortDisplay");function ln(e,t){let n=["auto"],i=U(e,t)?.supportedEfforts?.filter(s=>s.isUserVisible!==!1);if(!i||i.length===0){for(let s of["off","low","medium","high"])X(n,s);return n}for(let s of i)X(n,s.value);return n}o(ln,"getProviderReasoningEffortOptions");function un(e,t){let n=U(e,t),r=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(c=>c.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let c of["low","medium","high"])X(s,c);a=!0}else for(let c of i){if(c.value==="none"){a=!0;continue}if(r.has(c.value)){a=!0;continue}X(s,c.value)}let l=[];return a&&l.push("off"),l.push(...s),l.push("auto"),l}o(un,"getProviderReasoningEffortCycle");function xt(e,t){if(t===!1)return"off";switch(e){case"off":return"off";case"quick":return"low";case"balanced":return"medium";case"deep":return"high";default:return"auto"}}o(xt,"legacyReasoningModeToEffortDisplay");function U(e,t){let n=t??ht(e);if(!n)return;let r=ye(e,n)?.reasoningProfile;if(r)return le(r,Ee(e,n))}o(U,"resolveReasoningProfileForDisplay");function dn(e){let t=_(e.effort)??xt(e.reasoningMode,e.thinking),n=U(e.provider,e.model);if(!n)return t;try{let r=ue({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=_(r.configuredEffort)??t,a=r.configuredEffort!==void 0&&n.disabledEfforts?.includes(r.configuredEffort)===!0?"off":_(r.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let r=q({currentEffort:e.effort,capability:n}),i=_(e.effort)??t,s=_(r.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}o(dn,"formatReasoningEffortStatusLabel");function fn(e){let t=It(e);if(!t)return{preserved:!0};let n=U(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let r=q({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:r.effectiveEffort,preserved:r.preserved,diagnostic:r.diagnostic}}o(fn,"resolveProviderReasoningRuntimeEffort");function bt(e){switch(e){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";case"native-adaptive":return"adaptive";default:return"none"}}o(bt,"describeReasoningCapabilityControl");function pn(e,t){if(e==="off")return"Reasoning disabled";switch(t){case"native-budget":return"Uses native thinking budget control";case"native-effort":return"Uses native reasoning effort control";case"native-toggle":return"Uses provider-native thinking toggle only";case"native-adaptive":return"Model adaptively decides thinking depth (Opus 4.7+)";case"none":return"Runs without native reasoning parameters";case"prompt-only":return"Uses prompt overlays only; no native reasoning parameter";default:return"Runs without native reasoning parameters"}}o(pn,"describeReasoningExecution");function mn(e){let t=[];e||(e=ce().providerModels);for(let n of ge())t.push({name:n.name,model:n.model,models:vt(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=W().map(r=>({...r,models:(()=>{let i=e?.[r.name];return i&&i.length>0?ae(i,r.models):r.models})()}));t.push(...n)}catch{}return t}o(mn,"getProviderList");function gn(e){if(de(e))return!0;try{return C(e)?.isConfigured()??!1}catch{return!1}}o(gn,"isProviderConfigured");var F=class extends Error{static{o(this,"InvalidAgentModeConfigError")}};function Pt(e){let t=e.agentMode;if(t===void 0||t==="ama"||t==="sa")return e;if(t!=="amaw"&&t!=="ama-workflow")throw new F(`Invalid agentMode "${t}" in ${f}. Expected "ama" or "sa".`);let n={...e,agentMode:"ama",schemaVersion:Math.max(e.schemaVersion??0,st)},r=`${f}.migrate-${process.pid}.tmp`;try{u.writeFileSync(r,JSON.stringify(n,null,2),{mode:384}),u.renameSync(r,f)}catch{u.rmSync(r,{force:!0})}return Ne||(process.emitWarning(`Migrated persisted agentMode "${t}" to "ama". Workflow use is now explicit intent.`,{code:"KODAX_AGENT_MODE_MIGRATED"}),Ne=!0),n}o(Pt,"migrateLegacyAgentModeConfig");function ce(){try{if(u.existsSync(f)){let n=JSON.parse(u.readFileSync(f,"utf-8")),r=Pt(n),i=r.reasoningCeiling??r.reasoningMode,s=[],a={};try{s=[...K(d).document.paths]}catch{}try{a=$(d).document.servers}catch{}return mt(pt({...r,reasoningMode:i,extensions:se(s),mcpServers:a}))}}catch(n){if(n instanceof F)throw n}let e,t;try{let n=K(d);n.source!=="default"&&(e=se([...n.document.paths]))}catch{}try{let n=$(d);n.source!=="default"&&(t=n.document.servers)}catch{}return{...e===void 0?{}:{extensions:e},...t===void 0?{}:{mcpServers:t}}}o(ce,"loadConfig");var St=p.join(d,"config.example.jsonc"),oe={mcp:p.join(d,"integrations","mcp.example.jsonc"),a2a:p.join(d,"integrations","a2a.example.jsonc"),extensions:p.join(d,"integrations","extensions.example.jsonc")},_t=[{name:"core",path:St},{name:"mcp",path:oe.mcp},{name:"a2a",path:oe.a2a},{name:"extensions",path:oe.extensions}];function Ct(){let e=[];for(let t of _t)try{if(u.existsSync(t.path))continue;u.mkdirSync(p.dirname(t.path),{recursive:!0}),u.writeFileSync(t.path,Ce(t.name),"utf8"),e.push(t.path)}catch{}return e}o(Ct,"ensureExampleConfigFiles");function hn(){return Ct()[0]}o(hn,"ensureExampleConfigFile");var j=new Map;function kt(e,t){let n=process.env[e],r=j.get(e),i=r!==void 0&&n===r;if(n!==void 0&&!i){j.delete(e);return}if(t===void 0){i&&delete process.env[e],j.delete(e);return}process.env[e]=t,j.set(e,t)}o(kt,"projectConfigEnvironment");var Xe=[{configPath:"streamIdleTimeoutMs",env:"KODAX_STREAM_IDLE_TIMEOUT_MS",value:o(e=>x(e.streamIdleTimeoutMs),"value")},{configPath:"repoIntelligenceMode",env:"KODAX_REPO_INTELLIGENCE",value:o(e=>e.repoIntelligenceMode,"value")},{configPath:"repoIntelligenceTrace",env:"KODAX_REPO_INTELLIGENCE_TRACE",value:o(e=>S(e.repoIntelligenceTrace),"value")},{configPath:"verifierLog",env:"KODAX_VERIFIER_LOG",value:o(e=>S(e.verifierLog),"value")},{configPath:"stallLog",env:"KODAX_STALL_LOG",value:o(e=>S(e.stallLog),"value")},{configPath:"fallbackProviders",env:"KODAX_FALLBACK_PROVIDERS",value:o(e=>At(e.fallbackProviders),"value")},{configPath:"fastProvider",env:"KODAX_FAST_PROVIDER",value:o(e=>v(e.fastProvider),"value")},{configPath:"fastModel",env:"KODAX_FAST_MODEL",value:o(e=>v(e.fastModel),"value")},{configPath:"deepProvider",env:"KODAX_DEEP_PROVIDER",value:o(e=>v(e.deepProvider),"value")},{configPath:"deepModel",env:"KODAX_DEEP_MODEL",value:o(e=>v(e.deepModel),"value")},{configPath:"provider",env:"KODAX_PROVIDER",value:o(e=>v(e.provider),"value")},{configPath:"effort",env:"KODAX_EFFORT",value:o(e=>v(e.effort),"value")},{configPath:"runtimeMode",env:"KODAX_RUNTIME_MODE",value:o(e=>e.runtimeMode,"value")},{configPath:"sessionRetentionDays",env:"KODAX_SESSION_RETENTION_DAYS",value:o(e=>x(e.sessionRetentionDays),"value")},{configPath:"maxOutputTokens",env:"KODAX_MAX_OUTPUT_TOKENS",value:o(e=>x(e.maxOutputTokens),"value")},{configPath:"disablePromptCache",env:"KODAX_DISABLE_PROMPT_CACHE",value:o(e=>S(e.disablePromptCache),"value")},{configPath:"lsp",env:"KODAX_LSP",value:o(e=>S(e.lsp),"value")},{configPath:"lspAutoDownload",env:"KODAX_LSP_DOWNLOAD",value:o(e=>S(e.lspAutoDownload),"value")},{configPath:"acpLogLevel",env:"KODAX_ACP_LOG",value:o(e=>v(e.acpLogLevel),"value")},{configPath:"repoIntelligence.toolWaitMs",env:"KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS",value:o(e=>x(e.repoIntelligence?.toolWaitMs),"value")},{configPath:"repoIntelligence.workerTimeoutMs",env:"KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS",value:o(e=>x(e.repoIntelligence?.workerTimeoutMs),"value")},{configPath:"repoIntelligence.workerOldSpaceMb",env:"KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB",value:o(e=>x(e.repoIntelligence?.workerOldSpaceMb),"value")},{configPath:"repoIntelligence.storageDir",env:"KODAX_REPO_INTELLIGENCE_STORAGE_DIR",value:o(e=>v(e.repoIntelligence?.storageDir),"value")},{configPath:"workflow.maxConcurrency",env:"KODAX_WORKFLOW_MAX_CONCURRENCY",value:o(e=>x(e.workflow?.maxConcurrency),"value")}];function Mt(e){for(let t of Xe)kt(t.env,t.value(e))}o(Mt,"applyConfigSurfaceBridges");function v(e){return e?.trim()||void 0}o(v,"normalizedConfigString");function x(e){return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}o(x,"configNumberString");function S(e){return e===void 0?void 0:e?"1":"0"}o(S,"configBooleanString");function At(e){return e?.filter(t=>t.trim().length>0).join(",")}o(At,"configStringList");var vn=[...Xe.map(({configPath:e,env:t})=>({configPath:e,env:t}))];function Ot(e){Mt(e)}o(Ot,"applyConfigEnvironment");function yn(){dt();let e=ce();return Ot(e),ft(e),Se(e.locale),e}o(yn,"prepareRuntimeConfig");function wn(e){let t={};if(u.existsSync(f))try{let a=JSON.parse(u.readFileSync(f,"utf8"));a&&typeof a=="object"&&!Array.isArray(a)&&(t=a)}catch{}let{extensions:n,mcpServers:r,...i}=e,s={...t,...i};for(let a of Object.keys(i))i[a]===void 0&&delete s[a];if(u.mkdirSync(p.dirname(f),{recursive:!0}),u.writeFileSync(f,JSON.stringify(s,null,2)),n!==void 0){let a=K(d);O({domain:"extensions",configHome:d,...a.source==="user"?{expectedRevision:a.revision}:{},document:{version:1,paths:se(n)??[]},validate:M})}if(r!==void 0){let a=$(d);O({domain:"mcp",configHome:d,...a.source==="user"?{expectedRevision:a.revision}:{},document:{version:1,servers:r},validate:k})}}o(wn,"saveConfig");function En(e,t,n){return e.effort!==void 0||V(n).kind==="value"||t.effort!==void 0}o(En,"resolveInitialEffortOverride");function y(e){return e?.trim()?e:void 0}o(y,"nonEmptySelection");function xn(e){return y(e.explicitProvider)??y(e.environmentProvider)??y(e.configuredProvider)??e.defaultProvider}o(xn,"resolveRuntimeProviderSelection");function bn(e){let t=y(e.explicitModel);if(t)return t;let n=y(e.configuredModel);if(!n)return;let r=y(e.explicitProvider)??y(e.environmentProvider);return r?y(e.configuredProvider)===r?n:void 0:n}o(bn,"resolveRuntimeModelSelection");function Pn(e){if(e.explicitEffort!==void 0)return z(e.explicitEffort);let t=V(e.environmentEffort);return t.kind==="value"?t.value:e.configuredEffort===void 0?void 0:z(e.configuredEffort)}o(Pn,"resolveRuntimeEffortSelection");function It(e){return e.permissionMode==="plan"&&e.effortOverride!==!0&&e.planModeEffort!==void 0?e.planModeEffort:e.effort}o(It,"resolvePermissionModeEffort");async function Sn(e){try{let{stdout:t}=await it("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0});return t.trim()}catch{return null}}o(Sn,"getGitRoot");function Rt(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}o(Rt,"formatProviderSourceKind");function _n(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: ${Rt(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: ${bt(e.reasoningCapability)}`]}o(_n,"formatProviderCapabilityDetailLines");function Cn(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:Et(e,t,n,i.hints)})).filter(i=>i.decision!==null)}o(Cn,"getProviderCommonPolicyScenarios");var $e=.5,Ke=0,I={locked:!1,queue:[]};async function kn(e){for(;I.locked;)await new Promise(t=>I.queue.push(t));I.locked=!0;try{let t=(Date.now()-Ke)/1e3;t<$e&&await new Promise(r=>setTimeout(r,($e-t)*1e3));let n=await e();return Ke=Date.now(),n}finally{I.locked=!1;let t=I.queue.shift();t&&t()}}o(kn,"rateLimitedCall");export{Dt as a,_e as b,Ce as c,k as d,M as e,P as f,$ as g,K as h,Be as i,Ft as j,O as k,Ae as l,d as m,tn as n,f as o,nn as p,ut as q,rn as r,ft as s,gt as t,on as u,ht as v,vt as w,yt as x,wt as y,sn as z,Et as A,an as B,cn as C,_ as D,ln as E,un as F,dn as G,fn as H,bt as I,pn as J,mn as K,gn as L,ce as M,St as N,oe as O,Ct as P,hn as Q,vn as R,Ot as S,yn as T,wn as U,En as V,xn as W,bn as X,Pn as Y,It as Z,Sn as _,Rt as $,_n as aa,Cn as ba,kn as ca};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{C as Jt,Ha as No,Ma as Do,S as yr,e as Io,f as $o,g as Po,ia as Mo,ka as Lo}from"./chunk-Q65EAOX6.js";import{Ad as Dc,Ce as Fc,Ld as jc,N as Ec,Oa as Tc,Ua as Be,Va as In,Wa as $n,X as Sc,Ya as Ac,Z as _t,Za as Cc,_a as Rc,b as jo,c as Rn,dc as Pe,ec as Lc,kb as Oc,l as B,r as wr,s as xc,va as ae,zd as Nc}from"./chunk-QSMXI4MH.js";import{B as $c,H as Pc,W as br,X as vr,aa as Mc,b as D,e as Qt,f as On,t as Ic}from"./chunk-OGL227XV.js";import{w as tt,y as qe}from"./chunk-6YUDR7WN.js";import{a as i}from"./chunk-ONUPGMER.js";var mA=2,hA=500,gA=500,Fo="[Cancelled]",Uo=`${Fo} Operation cancelled by user`;import Uc from"fs/promises";import qc from"path";var Wc=2e3,Zt=50*1024,Ch=500,kr=2e3,qo=256*1024,Bo=2e3,Rh="KODAX_TOOL_OUTPUT_DIR";function Hc(e){return{maxLines:e.maxLines??Wc,maxBytes:e.maxBytes??Zt}}i(Hc,"getLimits");function Me(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}i(Me,"formatSize");function Pn(e,t={}){let{maxLines:n,maxBytes:r}=Hc(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
2
+ import{C as Jt,Ha as No,Ma as Do,S as yr,e as Io,f as $o,g as Po,ia as Mo,ka as Lo}from"./chunk-D3T24FJW.js";import{Ad as Dc,Ce as Fc,Ld as jc,N as Ec,Oa as Tc,Ua as Be,Va as In,Wa as $n,X as Sc,Ya as Ac,Z as _t,Za as Cc,_a as Rc,b as jo,c as Rn,dc as Pe,ec as Lc,kb as Oc,l as B,r as wr,s as xc,va as ae,zd as Nc}from"./chunk-VWSLC2WO.js";import{B as $c,H as Pc,W as br,X as vr,aa as Mc,b as D,e as Qt,f as On,t as Ic}from"./chunk-Y3AMP22L.js";import{w as tt,y as qe}from"./chunk-COQYLD4U.js";import{a as i}from"./chunk-ONUPGMER.js";var mA=2,hA=500,gA=500,Fo="[Cancelled]",Uo=`${Fo} Operation cancelled by user`;import Uc from"fs/promises";import qc from"path";var Wc=2e3,Zt=50*1024,Ch=500,kr=2e3,qo=256*1024,Bo=2e3,Rh="KODAX_TOOL_OUTPUT_DIR";function Hc(e){return{maxLines:e.maxLines??Wc,maxBytes:e.maxBytes??Zt}}i(Hc,"getLimits");function Me(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}i(Me,"formatSize");function Pn(e,t={}){let{maxLines:n,maxBytes:r}=Hc(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
3
3
  `),a=s.length;if(a<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:a,totalBytes:o,outputLines:a,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let c=s[0]??"";if(Buffer.byteLength(c,"utf-8")>r)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:a,totalBytes:o,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let l=[],d=0,u="lines";for(let p=0;p<s.length&&p<n;p++){let m=s[p]??"",h=Buffer.byteLength(m,"utf-8")+(p>0?1:0);if(d+h>r){u="bytes";break}l.push(m),d+=h}l.length>=n&&d<=r&&(u="lines");let f=l.join(`
4
4
  `);return{content:f,truncated:!0,truncatedBy:u,totalLines:a,totalBytes:o,outputLines:l.length,outputBytes:Buffer.byteLength(f,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}i(Pn,"truncateHead");function Mn(e,t={}){let{maxLines:n,maxBytes:r}=Hc(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
5
5
  `),a=s.length;if(a<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:a,totalBytes:o,outputLines:a,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let c=[],l=0,d="lines",u=!1;for(let p=s.length-1;p>=0&&c.length<n;p--){let m=s[p]??"",h=Buffer.byteLength(m,"utf-8")+(c.length>0?1:0);if(l+h>r){if(d="bytes",c.length===0&&m.length>0){let y=Ih(m,r);c.unshift(y),l=Buffer.byteLength(y,"utf-8"),u=!0}break}c.unshift(m),l+=h}c.length>=n&&l<=r&&(d="lines");let f=c.join(`
@@ -12,7 +12,7 @@ ${t.join(`
12
12
  `),sources:[{label:"README",path:"README.md"}],nextTopics:["license","install","quickstart"]},{id:"license",title:"License & commercial-use boundary",aliases:["licensing","kai-fcl","fair core","commercial use","non-commercial","\u8BB8\u53EF\u8BC1","\u8BB8\u53EF\u534F\u8BAE","\u5546\u4E1A\u4F7F\u7528","\u5546\u7528"],summary:"KAI-FCL from v0.7.70, community use, commercial authorization, and historical Apache copies.",body:["Official KodaX 0.7.70 and later distributions use the KodaX-AI Fair Core","License (KAI-FCL) 1.0 or accompanying KodaX-AI customer terms.","KAI-FCL is source-available / fair-core, not OSI open source.","","Community Use covers individual personal learning, individual non-commercial work,","classroom instruction, non-production research, and contribution development/testing.","Commercial or Managed Use is not granted by the community license. Company, team,","institutional, government, production, intranet, managed-device, paid-service, hosted,","or customer redistribution use requires a Customer Agreement with KodaX-AI and, where","required, a valid License Entitlement.","","This change is not retroactive: historical tags, archives, binaries, npm packages, or","other specific copies already distributed under Apache-2.0 keep that Apache-2.0 grant.","Third-party components remain under their own licenses. The repository LICENSE file is","the governing text; this topic is only a concise product summary."].join(`
13
13
  `),sources:[{label:"license",path:"LICENSE"},{label:"README license summary",path:"README.md"}],nextTopics:["overview","install","sdk"]},{id:"install",title:"Install & start KodaX",aliases:["setup","getting started","\u5B89\u88C5","\u542F\u52A8","\u600E\u4E48\u88C5"],summary:"npm install, Node version, secure first-run setup, updating.",body:["Install (Node >= 20):"," npm install -g @kodax-ai/kodax","Then run `kodax` in any project directory to start the interactive REPL.","","On a bare interactive first launch with no selected provider and no supported","credential, KodaX opens metadata-only provider setup before it starts the Runtime","or REPL. It never asks for or stores an API key: it saves only provider/model","selection (and validated public custom-provider metadata), shows the exact required","environment-variable name, then exits. Set that variable, restart terminal, and run","`kodax` again. Use `kodax setup` to rerun the flow deliberately. An explicitly","configured provider with a missing key stays an actionable credential error; scripts,","JSON/print/ACP modes, resume, and non-TTY runs never open setup automatically.","","Native binaries (no Node needed) are published per release on GitHub Releases","(darwin/linux/win, arm64/x64).","Update: re-run the npm install, or download the new binary."].join(`
14
14
  `),sources:[{label:"package",path:"package.json"}],nextTopics:["quickstart","providers","config"]},{id:"quickstart",title:"Quickstart workflow",aliases:["workflow","first task","\u5FEB\u901F\u5F00\u59CB","\u4E0A\u624B","\u600E\u4E48\u7528"],summary:"Open a project, give a task, review, run tests, continue a session.",body:["1. `cd` into your repo and run `kodax`.","2. Describe the task in plain language; KodaX plans, edits, and runs tools.","3. Review proposed edits (permission mode controls auto-accept vs prompt).","4. Ask it to run tests / build to verify.","5. Continue later: `kodax -c` (continue last) or `kodax -r` (resume a picker)."].join(`
15
- `),sources:[{label:"commands",path:"packages/repl/src/interactive/commands.ts"}],nextTopics:["commands","permissions","sessions"]},{id:"providers",title:"Providers & models",aliases:["provider","model","models","llm","\u4F9B\u5E94\u5546","\u6A21\u578B","\u63D0\u4F9B\u5546"],summary:"Built-in providers, choosing a model, credential check, cross-provider fallback.",body:[`KodaX ships ${Go.length} built-in provider aliases:`,` ${Hh}`,"",`Default provider: ${Lo} (override with KODAX_PROVIDER env or`,'"provider" in ~/.kodax/config.json). Switch model live with the /model command.',"","Public Kimi uses KIMI_API_KEY and defaults to `kimi-k2.7-code`; select","`kimi-k2.7-code-highspeed`, `kimi-k2.6`, or `kimi-k2.5` explicitly. These routes","have a 262,144-token context. K2.7 cannot disable thinking; K2.6 sends its required","wire toggle when thinking is disabled. `kimi-code` is the separate Kimi For Coding","subscription endpoint with KIMI_CODE_API_KEY. It keeps `kimi-for-coding` as default","and offers `k3-256k` (Moderato), Kimi K3 as `k3` (1,048,576 tokens, Allegretto+),","and `kimi-for-coding-highspeed`. Both K3 choices request upstream `k3`; reasoning","uses `thinking.effort`, defaults to max, and supports explicit disable. Public Kimi","and Kimi For Coding credentials are not interchangeable.","","Qwen Token Plan is the separate `qwen-token-plan` alias. It uses","`QWEN_TOKEN_API_KEY`, defaults to `qwen3.8-max-preview`, and speaks the","Anthropic-compatible protocol. `/model` can select `qwen3.7-max`,","`qwen3.7-plus`, `qwen3.6-flash`, `glm-5.2`, or `deepseek-v4-pro`; these Token","Plan routes have a 1M-token context. Qwen 3.8, 3.7 Plus, and 3.6 Flash accept","image input. It is distinct from the standard `qwen` alias and its `QWEN_API_KEY`.","","Check a key works: `verifyCredential` (SDK) / a configured provider is validated via","its verifyStrategy in provider-capabilities.json.","Cross-provider fallback on hard errors: /fallback slash + KODAX_FALLBACK_PROVIDERS.","Cheap/strong tiers for dispatched children: KODAX_FAST_* / KODAX_DEEP_*."].join(`
15
+ `),sources:[{label:"commands",path:"packages/repl/src/interactive/commands.ts"}],nextTopics:["commands","permissions","sessions"]},{id:"providers",title:"Providers & models",aliases:["provider","model","models","llm","\u4F9B\u5E94\u5546","\u6A21\u578B","\u63D0\u4F9B\u5546"],summary:"Built-in providers, choosing a model, credential check, cross-provider fallback.",body:[`KodaX ships ${Go.length} built-in provider aliases:`,` ${Hh}`,"",`Default provider: ${Lo} (override with KODAX_PROVIDER env or`,'"provider" in ~/.kodax/config.json). Switch model live with the /model command.',"","Public Kimi uses KIMI_API_KEY and defaults to `kimi-k2.7-code`; select","`kimi-k2.7-code-highspeed`, `kimi-k2.6`, or `kimi-k2.5` explicitly. These routes","have a 262,144-token context. K2.7 cannot disable thinking; K2.6 sends its required","wire toggle when thinking is disabled. `kimi-code` is the separate Kimi For Coding","subscription endpoint with KIMI_CODE_API_KEY. It defaults to the direct `k3-256k`","Model ID (Moderato+) and offers Kimi K3 as `k3` (1,048,576 tokens, Allegretto+),","`kimi-for-coding` (K2.7 Code), and `kimi-for-coding-highspeed`. K3 reasoning uses","`thinking.effort`, defaults to high, and supports explicit disable. Public Kimi","and Kimi For Coding credentials are not interchangeable.","","Qwen Token Plan is the separate `qwen-token-plan` alias. It uses","`QWEN_TOKEN_API_KEY`, defaults to `qwen3.8-max-preview`, and speaks the","Anthropic-compatible protocol. `/model` can select `qwen3.7-max`,","`qwen3.7-plus`, `qwen3.6-flash`, `glm-5.2`, or `deepseek-v4-pro`; these Token","Plan routes have a 1M-token context. Qwen 3.8, 3.7 Plus, and 3.6 Flash accept","image input. It is distinct from the standard `qwen` alias and its `QWEN_API_KEY`.","","Check a key works: `verifyCredential` (SDK) / a configured provider is validated via","its verifyStrategy in provider-capabilities.json.","Cross-provider fallback on hard errors: /fallback slash + KODAX_FALLBACK_PROVIDERS.","Cheap/strong tiers for dispatched children: KODAX_FAST_* / KODAX_DEEP_*."].join(`
16
16
  `),sources:[{label:"provider capabilities",path:"packages/llm/src/providers/provider-capabilities.json"}],nextTopics:["custom-providers","config","troubleshooting"]},{id:"custom-providers",title:"Custom providers",aliases:["custom provider","baseurl","openai compatible","\u81EA\u5B9A\u4E49\u4F9B\u5E94\u5546","\u81EA\u5B9A\u4E49\u6A21\u578B"],summary:"Point KodaX at an OpenAI/Anthropic-compatible endpoint, incl. thinking config.",body:["Add a `customProviders` entry in ~/.kodax/config.json for an OpenAI/Anthropic-","compatible endpoint: specify the protocol, baseUrl, auth header(s), and model name(s).","KodaX infers a verifyStrategy from the protocol; you can override it explicitly.","Once added, the custom provider is selectable like any built-in one.","","Thinking / reasoning (set on the provider, or per-model in models[]):","- supportsThinking: true is enough for most non-Claude models. With a bare"," supportsThinking: true (no explicit reasoningPreset/reasoningProfile), openai-compat"," stays passive \u2014 KodaX sends no thinking toggle and just surfaces the reasoning the",' model emits; anthropic-compat sends thinking:{type:"enabled"}, which is what the'," Anthropic-compatible endpoints of zhipu / kimi / minimax / deepseek expect. (An"," explicit reasoningPreset/reasoningProfile can send a toggle on openai-compat too.)","- openai-compat multi-turn caveat: some reasoning models (notably DeepSeek V4) reject a"," later turn whose history drops the prior reasoning_content. If thinking shows on the"," first turn but a follow-up errors, also set replayReasoningContent: true (per-provider"," or per-model).",'- reasoning: { efforts: ["low","high"], default: "high" } adds a tunable effort level.'," On openai-compat it sends reasoning_effort; on anthropic-compat it sends",' thinking:{type:"enabled"} + reasoning_effort (the non-Claude dialect). Include "off"'," in efforts to allow disabling thinking.","- Pointing anthropic-compat at REAL Claude (4.6+)? Claude needs adaptive thinking, not",' the enable toggle \u2014 set reasoningCapability: "native-adaptive" (or an explicit',' reasoningProfile with effortStrategy "anthropic-output-effort").',"- reasoningCapability is the low-level override: native-toggle / native-budget /"," native-effort / native-adaptive / none. It is ignored when supportsThinking is false.","If a relay rejects the chosen thinking shape, KodaX retries the turn once without it, so","it still completes (you just see no thinking) instead of erroring."].join(`
17
17
  `),sources:[{label:"config loader",path:"packages/repl/src/common/utils.ts"},{label:"custom provider reasoning",path:"packages/llm/src/providers/custom-provider.ts"}],nextTopics:["providers","config"]},{id:"config",title:"Configuration",aliases:["settings","config.json","env","\u914D\u7F6E","\u8BBE\u7F6E","\u73AF\u5883\u53D8\u91CF"],summary:"Core config, split integration files, migration, and KODAX_* env precedence.",body:["KodaX config is JSON + env vars \u2014 there is no YAML and no single loader entry.","Core file: ~/.kodax/config.json. Common keys: provider, model, effort,","planModeEffort, permissionMode, customProviders, repoIntelligenceMode, compaction,","fallbackProviders, autoMode, verifierLog, stallLog, runtimeMode, and workflow.","`autoMode` configures the Runtime-owned Auto Mode engine, optional classifier model,","timeout, and speculative window. In Auto Mode an omitted engine means `llm`; if no","effective classifier model exists, KodaX reports a recoverable configuration error","before it calls a provider or opens a permission prompt. It never silently falls back","to rules for that error.","","User integration declarations are versioned separately:","- MCP: ~/.kodax/integrations/mcp.json","- A2A: ~/.kodax/integrations/a2a.json","- Extensions: ~/.kodax/integrations/extensions.json","Run `kodax integrations migrate` for a dry run, then","`kodax integrations migrate --apply` to create missing split files. Migration imports","MCP and Extensions from config.json#mcpServers and config.json#extensions; A2A has no","legacy source. It does not overwrite an existing destination. The first MCP/Extension mutation","also stages readable legacy entries before applying the change. Review literal-secret warnings,","then add `--cleanup-legacy` with `--apply` only after the destination validates; cleanup removes","a legacy field only when its split destination exists. Initialize A2A with `a2a add` or an empty",'version-1 `{ "version": 1, "agents": {} }` document.',"Long-lived owners hot-reload","valid changes and retain last-known-good state on failure; inbound A2A execution/store","authority changes are reported as restart-required.","","Env mirrors / extras: KODAX_PROVIDER, KODAX_EFFORT, KODAX_FALLBACK_PROVIDERS, KODAX_FAST_*/KODAX_DEEP_*,","KODAX_REPO_INTELLIGENCE. Env generally overrides file. Project vs user config:","user config is ~/.kodax; project-scoped state lives under <repo>/.kodax/."].join(`
18
18
  `),sources:[{label:"config loader",path:"packages/repl/src/common/utils.ts"},{label:"integration config",path:"packages/repl/src/common/integration-config.ts"},{label:"canonical templates",path:"config-templates/"},{label:"permission config",path:"packages/repl/src/common/permission-config.ts"}],nextTopics:["providers","permissions","mcp","compaction"]},{id:"permissions",title:"Permission modes",aliases:["permission","approval","dangerous","\u6743\u9650","\u5BA1\u6279","\u6743\u9650\u6A21\u5F0F"],summary:"File/command permission modes, Runtime-owned Auto Mode, and exact grants.",body:["permissionMode controls when KodaX asks before file/command actions:","- accept-edits: auto-apply edits, still gate risky commands.","- plan: read-only planning, no mutations until you switch.","- auto: the Runtime-owned LLM/rules guardrail decides per action before it calls"," the shared permission broker. A safe allow creates no prompt; only an escalate does.",'Set via ~/.kodax/config.json "permissionMode" or the relevant slash command.',"","For a Runtime-backed prompt, choose allow once, a session-scoped exact grant, or (when","offered) a persistent exact grant. The Runtime creates the opaque suggestion; never","construct or widen a scope from the displayed input. Exact command grants include the","normalized command, cwd, shell, and background setting; path grants cover one tool and","one normalized absolute path. Dynamic shell commands deliberately do not get a","persistent suggestion. Persistent grants are daemon-owned and revisioned; use the SDK","permission service to inspect or revoke them.","Legacy grants without a Runtime-issued matcher remain visible and revocable but never","authorize a concrete call. A legacy `allow_always.scope` response is mapped only to a","current Runtime-issued concrete candidate; KodaX never persists its coarse scope.","","Auto Mode defaults to the `llm` engine. If no effective classifier model is available,","it fails with a recoverable configuration error before provider access or approval; it","does not quietly downgrade to rules. Classifier context is bounded and redacted before","it reaches a provider.","Shift-Tab cycles Plan -> Edits -> Auto; Shift+Enter inserts a newline. Entering Auto","shows the configured engine immediately as Auto[LLM] or Auto[RULES], while Runtime","settings updates are serialized so rapid cycling cannot let an older mode win. A","session-level LLM-to-rules downgrade remains sticky by design; use `/auto-engine llm`","to opt back into LLM classification.","Threat model: KodaX is a single-user CLI; workspace integrity is the user\u2019s responsibility."].join(`
@@ -334,7 +334,7 @@ LSP errors detected in this file, please fix:
334
334
  ${u}`:""}async getDefinition(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.definition(fe.resolve(t),n).catch(()=>[]);return To(s,"No definition found at that position.")}async getHover(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.hover(fe.resolve(t),n).catch(()=>null);return xm(s)}async getReferences(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.references(fe.resolve(t),n).catch(()=>[]);return To(s,"No references found at that position.")}async getDocumentSymbols(t,n={}){let r=await this.navClient(t,n);if(r.kind!=="client")return r.message;let o=await r.client.documentSymbols(fe.resolve(t)).catch(()=>[]);return Em(o,"No symbols found in this file.")}async getWorkspaceSymbols(t,n={}){let r=await this.workspaceClients(n);if(r.length===0)return"No language server is available for workspace symbol search.";let o=await Promise.all(r.map(s=>s.workspaceSymbols(t).catch(()=>[])));return Sm(o.flat(),"No workspace symbols found for that query.")}async getImplementation(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.implementation(fe.resolve(t),n).catch(()=>[]);return To(s,"No implementation found at that position.")}async getPrepareCallHierarchy(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=await o.client.prepareCallHierarchy(fe.resolve(t),n).catch(()=>[]);return Am(s,"No call hierarchy item found at that position.")}async getIncomingCalls(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=fe.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.incomingCalls(l).catch(()=>[])));return Cm(c.flat(),"No incoming calls found for that symbol.")}async getOutgoingCalls(t,n,r={}){let o=await this.navClient(t,r);if(o.kind!=="client")return o.message;let s=fe.resolve(t),a=await o.client.prepareCallHierarchy(s,n).catch(()=>[]);if(a.length===0)return"No call hierarchy item found at that position.";let c=await Promise.all(a.map(l=>o.client.outgoingCalls(l).catch(()=>[])));return Rm(c.flat(),"No outgoing calls found for that symbol.")}async navClient(t,n){let r=pr(t);if(!r)return{kind:"message",message:`No language server is configured for ${fe.basename(t)}.`};let o=this.servers.filter(c=>c.languageIds.includes(r));if(o.length===0)return{kind:"message",message:`No language server is configured for ${fe.basename(t)}.`};let s=fe.resolve(t),a=n.gitRoot??fe.dirname(s);for(let c of o){let l=rc(s,c.rootMarkers,a),d=await this.getClient(c,l,n);if(d)return await d.notifyOpenOrChange(s).catch(()=>{}),{kind:"client",client:d}}return{kind:"message",message:o.map(c=>c.installGuidance).join(`
335
335
  `)}}async workspaceClients(t){let n=fe.resolve(t.gitRoot??process.cwd()),r=[];for(let o of this.servers){let s=await this.getClient(o,n,t);s&&r.push(s)}return r}async shutdownAll(){this.shuttingDown=!0;try{await Promise.all([...this.spawning.values()].map(n=>n.catch(()=>{})));let t=[...this.clients.values()];this.clients.clear(),this.broken.clear(),await Promise.all(t.map(n=>n.shutdown().catch(()=>{})))}finally{this.shuttingDown=!1}}killAllSync(){for(let t of this.clients.values())t.killSync();this.clients.clear()}resetBroken(t){t?this.broken.delete(t):this.broken.clear()}async getClient(t,n,r){let o=`${$e(n)}|${t.id}`,s=this.clients.get(o);if(s)return s;if(this.broken.has(o))return;let a=this.spawning.get(o);if(a)return a;let c=this.spawnClient(t,n,o,r);this.spawning.set(o,c);try{return await c}finally{this.spawning.delete(o)}}async spawnClient(t,n,r,o){try{let s=t.discover({root:n,moduleUrl:this.config.moduleUrl});if(s||(s=await this.acquireIfEnabled(t,n,o)),!s){this.broken.add(r),this.config.debug?.(`${t.id} not installed at ${n} \u2014 ${t.installGuidance}`);return}o.onProgress?.(`Starting ${t.id} language server\u2026`);let c=await(this.config.createClient??$m)({serverId:t.id,root:n,launch:s,debug:this.config.debug});if(this.shuttingDown){await c.shutdown().catch(()=>{});return}return this.clients.set(r,c),c}catch(s){this.broken.add(r),this.config.debug?.(`${t.id} failed to start at ${n}: ${s.message}`);return}}async acquireIfEnabled(t,n,r){if(!(!t.acquire||!ic()))try{return await t.acquire({root:n,signal:r.signal,onProgress:r.onProgress,debug:this.config.debug})}catch(o){this.config.debug?.(`${t.id} auto-install failed: ${o.message}`);return}}},hr,Pm=!1;function Mm(){let e=yr()?.lsp;if(!(e===!1||e===void 0&&process.env.KODAX_LSP==="0"))return hr||(hr=new dc({moduleUrl:import.meta.url,debug:process.env.KODAX_DEBUG_LSP?t=>D({source:"coding:lsp",level:"debug",message:t}):void 0}),Pm||(Pm=!0,process.once("exit",()=>hr?.killAllSync()))),hr}i(Mm,"getDefaultLspService");async function WU(){await hr?.shutdownAll()}i(WU,"shutdownDefaultLspService");import{createHash as $T}from"node:crypto";import{execFileSync as QS}from"child_process";import{randomUUID as ZS}from"node:crypto";import eT from"fs/promises";import Wm from"os";function Lm(e,t,n){let r=e?.provider?.trim()||process.env[t]?.trim()||void 0,o=e?.model?.trim()||process.env[n]?.trim()||void 0;if(!(!r&&!o))return{provider:r,model:o}}i(Lm,"resolveTier");function uc(e,t){let n=yr()?.modelTiers;if(e==="fast")return t?Lm(n?.fast,"KODAX_FAST_PROVIDER","KODAX_FAST_MODEL"):void 0;if(e==="deep")return Lm(n?.deep,"KODAX_DEEP_PROVIDER","KODAX_DEEP_MODEL")}i(uc,"resolveModelHintTier");function WS(){let e=process.env.KODAX_FALLBACK_PROVIDERS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}i(WS,"resolveFallbackChain");function Nm(e){return e instanceof $o||e instanceof Po||e instanceof Io}i(Nm,"isFallbackEligibleError");function HS(e){return e instanceof $o?"rate-limit exhausted":e instanceof Po?"network error":e instanceof Io?"provider error":e instanceof Error?e.message:String(e)}i(HS,"errorReason");async function fc(e,t,n,r){let o=e.provider??"anthropic";try{return await n(e,t)}catch(s){if(e.abortSignal?.aborted||!Nm(s))throw s;let a=WS().filter(l=>l!==o),c=s;for(let l of a){r?.onFallback?.({fromProvider:o,toProvider:l,reason:HS(c)});try{return await n({...e,provider:l,model:void 0},t)}catch(d){if(e.abortSignal?.aborted||!Nm(d))throw d;c=d}}throw c}}i(fc,"invokeChildWithFallback");function KS(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/skill:([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/skill:${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(KS,"parseInlineSkillReferences");function GS(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/(?!skill:)([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(GS,"parseBareInlineSlashReferences");function Dm(e){return Array.from(new Set(KS(e).map(t=>t.name)))}i(Dm,"uniqueInlineSkillNames");function jm(e){return Array.from(new Set(GS(e).map(t=>t.name)))}i(jm,"uniqueBareInlineSlashNames");function Ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Ue,"isRecord");function zS(e){return e instanceof Error?e.message:String(e)}i(zS,"errorMessage");function Co(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}i(Co,"safeStringify");function Fm(e,t){switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number";case"integer":return typeof e=="number"&&Number.isInteger(e);case"boolean":return typeof e=="boolean";case"object":return Ue(e);case"array":return Array.isArray(e);case"null":return e===null;default:return!0}}i(Fm,"matchesType");function XS(e,t){return e.some(n=>n===t?!0:typeof n!="object"||typeof t!="object"?!1:Co(n)===Co(t))}i(XS,"enumMatches");function Ao(e,t){return e?`${e}.${t}`:t}i(Ao,"joinPath");function pc(e,t,n=""){if(!Ue(t))return[];let r=[],o=n||"(root)",s=t.type;if(typeof s=="string"&&!Fm(e,s))return[`${o}: expected type ${s}`];if(Array.isArray(s)&&!s.some(a=>typeof a=="string"&&Fm(e,a)))return[`${o}: expected one of types ${s.join("|")}`];if(Array.isArray(t.enum)&&!XS(t.enum,e)&&r.push(`${o}: value is not one of the allowed enum values`),Ue(e)){let a=Ue(t.properties)?t.properties:void 0;if(Array.isArray(t.required))for(let c of t.required)typeof c=="string"&&!(c in e)&&r.push(`${Ao(n,c)}: required field is missing`);if(a){for(let[c,l]of Object.entries(e))c in a&&r.push(...pc(l,a[c],Ao(n,c)));if(t.additionalProperties===!1)for(let c of Object.keys(e))c in a||r.push(`${Ao(n,c)}: unexpected property (additionalProperties is false)`)}}return Array.isArray(e)&&Ue(t.items)&&e.forEach((a,c)=>{r.push(...pc(a,t.items,`${o}[${c}]`))}),r}i(pc,"validateAgainstSchema");var YS=["$ref","$defs","definitions","oneOf","allOf","anyOf","not","if","then","else","const","patternProperties","propertyNames","dependencies","dependentSchemas","dependentRequired","contains","unevaluatedProperties","unevaluatedItems","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties"];function mc(e,t,n){if(Ue(e)){for(let r of YS)r in e&&!n.has(r)&&n.set(r,t||"(root)");if(Ue(e.properties))for(let[r,o]of Object.entries(e.properties))mc(o,Ao(t,r),n);Ue(e.items)&&mc(e.items,`${t||"(root)"}[]`,n),Ue(e.additionalProperties)&&!n.has("additionalProperties (schema form)")&&n.set("additionalProperties (schema form)",t||"(root)")}}i(mc,"collectUnsupportedKeywords");function eq(e){if(!Ue(e))return;let t=new Map;if(mc(e,"",t),t.size===0)return;let n=[...t.entries()].map(([r,o])=>`\`${r}\` (at ${o})`).join(", ");throw new Error(`outputSchema uses unsupported JSON-Schema keyword(s): ${n}. The workflow validator supports only type, enum, required, properties, items, and additionalProperties: false (nested object arrays included). Inline the referenced shapes, drop value-constraint keywords, and use that subset.`)}i(eq,"assertSupportedOutputSchema");function VS(e){let t=e.indexOf("{"),n=e.indexOf("[");return t<0?n:n<0?t:Math.min(t,n)}i(VS,"firstStructureStart");function Um(e){let t=VS(e);if(t<0)return;let n=e[t],r=n==="{"?"}":"]",o=0,s=!1,a=!1;for(let c=t;c<e.length;c+=1){let l=e[c];if(s){a?a=!1:l==="\\"?a=!0:l==='"'&&(s=!1);continue}if(l==='"'){s=!0;continue}if(l===n)o+=1;else if(l===r&&(o-=1,o===0))return e.slice(t,c+1)}}i(Um,"balancedStructure");function JS(e){if(typeof e!="string"||e.trim().length===0)return;let t=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(n=t.exec(e))!==null;){let o=n[1]?.trim();o&&(r=o)}return r?Um(r)??r:Um(e)}i(JS,"extractJsonCandidate");function hc(e,t){let n=JS(e);if(n===void 0)return{ok:!1,errors:["no JSON value was found in the output"]};let r;try{r=JSON.parse(n)}catch(s){return{ok:!1,errors:[`output was not valid JSON: ${zS(s)}`]}}let o=pc(r,t);return{ok:o.length===0,value:r,errors:o}}i(hc,"evaluateStructuredOutput");function qm(e){return["## Required Output Format","After your analysis, end your response with a single fenced ```json code block containing ONLY a JSON value that matches the JSON Schema below. Put nothing after the closing fence.","Schema:","```json",Co(e),"```"].join(`
336
336
  `)}i(qm,"buildStructuredOutputInstruction");function Bm(e,t){return["Your previous response did not produce a valid result object for the workflow.","Problems:",...e.map(n=>`- ${n}`),"Re-emit ONLY a single fenced ```json code block containing a JSON value that matches this schema. No prose, nothing after the closing fence.","Schema:","```json",Co(t),"```"].join(`
337
- `)}i(Bm,"buildStructuredOutputRepairPrompt");var gc,Ro;async function Xm(){if(gc)return gc;if(!Ro){let e="./agent.js";Ro=import("./agent-LVZJB2GQ.js").then(t=>{let n=t.runKodaX;if(typeof n!="function")throw new Error("[child-executor] Agent module loaded but `runKodaX` export is missing or not a function. This indicates an API break in packages/coding/src/agent.ts. Check that `export { runKodaX }` is still present.");return gc=n,n}).catch(t=>{if(Ro=void 0,t instanceof Error&&t.message.startsWith("[child-executor]"))throw t;let n=t instanceof Error?t.message:String(t);throw new Error(`[child-executor] Failed to lazy-load agent module (\`${e}\`) for a nested Agent turn. This usually means the @kodax-ai/coding build is broken or out of date. Underlying cause: ${n}`)})}return Ro}i(Xm,"getRunKodaX");var tT=["You are summarizing your own just-completed child-agent report for a parent workflow.","Do not use tools. Do not continue investigation. Produce only the digest."].join(`
337
+ `)}i(Bm,"buildStructuredOutputRepairPrompt");var gc,Ro;async function Xm(){if(gc)return gc;if(!Ro){let e="./agent.js";Ro=import("./agent-7X5CFET2.js").then(t=>{let n=t.runKodaX;if(typeof n!="function")throw new Error("[child-executor] Agent module loaded but `runKodaX` export is missing or not a function. This indicates an API break in packages/coding/src/agent.ts. Check that `export { runKodaX }` is still present.");return gc=n,n}).catch(t=>{if(Ro=void 0,t instanceof Error&&t.message.startsWith("[child-executor]"))throw t;let n=t instanceof Error?t.message:String(t);throw new Error(`[child-executor] Failed to lazy-load agent module (\`${e}\`) for a nested Agent turn. This usually means the @kodax-ai/coding build is broken or out of date. Underlying cause: ${n}`)})}return Ro}i(Xm,"getRunKodaX");var tT=["You are summarizing your own just-completed child-agent report for a parent workflow.","Do not use tools. Do not continue investigation. Produce only the digest."].join(`
338
338
  `),nT=["Create a short user-facing digest of your previous report for the parent workflow.","Return only 2-4 bullet lines.","Each bullet must be concrete: a finding, decision, risk, evidence pointer, unresolved question, or next action.","Use the same natural language as the user request or your report.","Do not include a title, table, generic preamble, or workflow handoff markers."].join(`
339
339
  `),Ym=4,Vm=1e4,rT=45e3,oT=40;function Jm(e,t){return e.historyStorage?{id:`worker-${ZS()}`,scope:"managed-task-worker",storage:e.historyStorage,...t&&t.length>0?{initialMessages:[...t]}:{}}:t&&t.length>0?{initialMessages:[...t]}:void 0}i(Jm,"buildChildRunSession");function Oo(e){let t={};return e.parentOptions.repoIntelligenceMode!==void 0&&(t.repoIntelligenceMode=e.parentOptions.repoIntelligenceMode),e.parentOptions.repoIntelligenceTrace!==void 0&&(t.repoIntelligenceTrace=e.parentOptions.repoIntelligenceTrace),t}i(Oo,"inheritRepoIntelligenceContext");async function Qm(e,t,n){if(e.length===0)return zm;let r=e.filter(f=>f.readOnly),o=e.filter(f=>!f.readOnly),s=IT(o,n.parentRole,n.parentHarness),a=[...r,...s];if(a.length===0)return zm;let c=[],l=[],d=n.onProgress??(()=>{});d(`Starting ${a.length} child tasks in parallel`);let u=await Oc({bundles:a,runOne:i(f=>f.readOnly?vT(f,t,n):_T(f,t,n),"runOne"),maxParallel:n.maxParallel,abortSignal:n.abortSignal,onProgress:i((f,p)=>{f.kind==="start"?d(`[${p.completedCount}/${p.totalCount}] Running: ${f.bundle.id}`):f.kind==="item-done"&&d(`[${p.completedCount}/${p.totalCount}] Done: ${f.bundle.id} \u2192 ${f.result.status}`)},"onProgress")});for(let f of u.results)f.status==="fulfilled"?c.push(f.value):c.push(Vt(f.bundle,`[Crash] ${f.reason.message}`,"failed"));for(let f of u.cancelled)l.push(f.id);return OT(a,c,l)}i(Qm,"executeChildAgents");function Zm(e,t){if(!t)return e;let n=new Set(t.tools),r=n.has("*"),o=new Set(e);for(let s of Gt()){let a=!r&&!n.has(s.name),c=!t.network&&(s.sideEffect==="reads-network"||s.sideEffect==="mutates-network"),l=!t.canAskUser&&s.name==="ask_user_question";(a||c||l)&&o.add(s.name)}return[...o]}i(Zm,"restrictToolsForActor");function iT(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||!("path"in t))throw new Error("worktree_create returned an invalid payload");let n=t.path;if(typeof n!="string"||n.length===0)throw new Error("worktree_create returned an invalid path");return n}i(iT,"readWorktreePath");async function eh(e,t){if(e.isolation!=="worktree")return{ctx:t};let n=await Qn({description:`workflow-${e.id}`,...t.workflowWorktreeBaseDir?{base_dir:t.workflowWorktreeBaseDir}:{}},t),r=iT(n);return{ctx:{...t,gitRoot:r,executionCwd:r},worktreePath:r}}i(eh,"prepareChildIsolationScope");function th(e,t){return t.worktreePath?[`[Workflow worktree: ${t.worktreePath}]`,e].join(`
340
340
  `):e}i(th,"annotateWorktreeSummary");async function Hm(e,t){if(e.worktreePath)try{await Zn({action:"remove",worktree_path:e.worktreePath,discard_changes:!1},t);return}catch(n){return`[Workflow worktree cleanup failed: ${n instanceof Error?n.message:String(n)}]`}}i(Hm,"cleanupChildIsolationScope");function sT(e,t){return t?{...e,summary:`${e.summary}
@@ -366,4 +366,4 @@ ${ge(o)}
366
366
  ${ge(e.content)}
367
367
  </agent-completed>`}return`<agent-message id="${ge(e.messageId)}" from="${ge(e.senderPath)}" classification="${e.classification}">
368
368
  ${ge(e.content)}
369
- </agent-message>`}i(kc,"renderMailboxMessage");function BT(e,t){if(!(!t||e.actor.capabilities.providers.includes("*"))&&!e.actor.capabilities.providers.includes(t))throw new Error(`Actor ${e.actor.path} is not authorized to use provider ${t}.`)}i(BT,"assertProviderAuthority");function ge(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}i(ge,"escapeXml");function WT(e){return{async admit(t){return e.spentBudget+t.units>e.totalBudget?{admitted:!1,fact:{code:"agent_budget_exhausted",retryable:!1,reason:`shared root work budget exhausted (${e.spentBudget}/${e.totalBudget})`}}:(e.spentBudget+=t.units,{admitted:!0})},async refund(){e.spentBudget=Math.max(0,e.spentBudget-1)},snapshot:i(()=>({...e}),"snapshot")}}i(WT,"managedWorkBudgetPort");function HT(e,t){let n=Te(e.specialistName);if(n)return n;let r=Te(e.agentId);if(!(!r||t.actor.kind==="native"))throw new Error(`Agent selector ${r} was not resolved before execution.`)}i(HT,"specialistName");function KT(e){return e==="fast"||e==="balanced"||e==="deep"?e:void 0}i(KT,"modelHint");function GT(e){let t=Te(e);if(!t)return;let n=Jt(t);return n==="auto"?void 0:n}i(GT,"effort");function Te(e){return typeof e=="string"&&e.length>0?e:void 0}i(Te,"metadataString");function bh(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(bh,"metadataStringArray");import _h from"node:path";var zT=80;function XT(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,zT);return!t||t==="."||t===".."?"session":t}i(XT,"sanitizeScratchSessionId");function xh(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?_h.resolve(n):de(e.context);return _h.resolve(r,".agent","tmp","sessions",XT(t))}i(xh,"getSessionScratchDir");var YT="emit_managed_protocol",jq="kodax-task-contract",VT="kodax-task-verdict",Fq="kodax-task-scout",Uq="kodax-task-handoff";function JT(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(JT,"asRecord");function Eh(e){return e.trim().toLowerCase()===YT}i(Eh,"isManagedProtocolToolName");function Sh(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(Sh,"mergeManagedProtocolPayload");function QT(e){let t=e.trim().toLowerCase();if(!t)return;let r=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[_\s-]+/g," ").trim().split(/\s+/,1)[0]??"";if(r){if(/^accept(?:ed|s|ing)?$/.test(r)||r==="approve"||r==="approved")return"accept";if(/^revis(?:e|ed|es|ing)?$/.test(r))return"revise";if(/^block(?:ed|ing)?$/.test(r))return"blocked"}}i(QT,"normalizeManagedVerdictStatus");function ZT(e){let t=e.trim();if(!t)return;let n=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[\s-]+/g,"_").trim().toUpperCase();if(n==="H1_EXECUTE_EVAL"||n==="H1")return"H1_EXECUTE_EVAL";if(n==="H2_PLAN_EXECUTE_EVAL"||n==="H2")return"H2_PLAN_EXECUTE_EVAL"}i(ZT,"normalizeManagedNextHarness");function eA(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"?e.split(/\r?\n/).map(t=>t.replace(/^-+\s*/,"").trim()).filter(Boolean):[]}i(eA,"normalizeStringListValue");function qq(e,t,n=""){let r=JT(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?QT(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:eA(r.followup??r.followups),userFacingText:n,userAnswer:typeof r.user_answer=="string"?r.user_answer.trim()||void 0:typeof r.userAnswer=="string"&&r.userAnswer.trim()||void 0,nextHarness:typeof(r.next_harness??r.nextHarness)=="string"?ZT(String(r.next_harness??r.nextHarness)):void 0,budgetRequest:typeof(r.budget_request??r.budgetRequest)=="string"&&String(r.budget_request??r.budgetRequest).trim()||void 0}}}i(qq,"coerceManagedProtocolToolPayload");function Bq(e){if(e==="evaluator")return VT}i(Bq,"getManagedBlockNameForRole");function Wq(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(Wq,"hasManagedProtocolForRole");function Hq(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i(Hq,"textContainsManagedBlock");function Th(e,t){if(!t||t.length===0)return e;let n=new Set(t);return e.filter(r=>!n.has(r))}i(Th,"filterExcludedTools");function Ah(e,t){return t?e.filter(n=>{let r=_e(n);return r?t({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0}):!1}):e}i(Ah,"applyToolVisibilityPolicy");function tA(e,t,n=!1,r,o=!1){let s=Ji(t)==="off"?Fa(e):e;return n||(s=Ua(s)),s=Aa(s,r),s=La(s,r),o||(s=s.filter(a=>a!=="list_dispatchable_agents")),s}i(tA,"getRuntimeActiveToolNames");function Qq(e,t,n=!1,r=!1,o,s,a,c=!1){let l=ja();if(e.length===0)return[];let d=new Set(tA(e,t,r,o,c));return l.filter(u=>d.has(u.name)&&(n||!Eh(u.name))).map(u=>{let f=Sr(u,a);if(!bo(f.name)||s&&s.has(f.name))return f;let p=zt[f.name];return p?{...f,description:p}:f})}i(Qq,"getActiveToolDefinitions");import{join as nA}from"node:path";function rA(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return nA(e,t)}i(rA,"resolveResumeFromRunDir");function d1(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=de(t.context),c=xh(t),l=Ah(Th([...mt],t.context?.excludeTools),t.context?.toolVisibilityPolicy),d=mt.every(f=>l.includes(f))?bs({sessionId:o,currentAgentId:t.context?.currentAgentId,sessionScope:t.session?.scope,storage:t.session?.storage}):void 0,u={backups:new Map,actorControl:t.context?.actorControl,actorHost:t.context?.actorHost,managedWorkBudget:t.context?.managedWorkBudget,gitRoot:t.context?.gitRoot??void 0,sessionId:o,...d!==void 0?{loadSessionHistory:d}:{},taskSurface:t.context?.taskSurface,agentProfile:t.context?.agentProfile,agentScope:t.context?.agentScope,agentExecutorPlane:t.context?.agentExecutorPlane,selfManual:t.selfManual,skillDynamicContext:t.skillDynamicContext,skillRegistry:t.context?.skillRegistry,skillScriptRunner:t.context?.skillScriptRunner,assertReadablePath:t.context?.assertReadablePath,toolVisibilityPolicy:t.context?.toolVisibilityPolicy,excludeTools:t.context?.excludeTools,lspService:t.context?.lspService??Mm(),executionCwd:a,sessionScratchDir:c,extensionRuntime:n,askUser:s.askUser,askUserMulti:s.askUserMulti,askUserInput:s.askUserInput,exitPlanMode:s.exitPlanMode,abortSignal:t.abortSignal,managedProtocolRole:t.context?.managedProtocolEmission?.enabled?t.context.managedProtocolEmission.role:void 0,emitManagedProtocol:t.context?.managedProtocolEmission?.enabled?f=>{r.current=Sh(r.current,f)}:void 0,mutationTracker:t.context?.mutationTracker,planModeBlockCheck:t.context?.planModeBlockCheck,guardrails:t.guardrails,parentAgentConfig:{provider:t.provider,model:t.modelOverride??t.model,reasoningMode:t.reasoningMode,effort:t.effort,repoIntelligenceMode:t.context?.repoIntelligenceMode,repoIntelligenceTrace:t.context?.repoIntelligenceTrace,...t.compaction!==void 0?{compaction:{...t.compaction}}:{}},parentEvents:s,onChildProgress:void 0,sendMessageTurnCounter:{count:0},goalContext:t.context?.goalRuntime?.goalContext};if(!u.actorControl&&(t.agentMode==="ama"||t.context?.actorSession)){let f=t.context?.actorSession??new gr({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:o});u.actorHost=f,u.actorControl=f.attach(u,t)}return u.workflowHost=iA(t,o,u.actorControl,u.actorHost),u}i(d1,"buildToolExecutionContext");function oA(e,t){return{...t?{sessionId:t}:{},...e.context?.agentProfile?.surface?{surface:e.context.agentProfile.surface}:{},...e.context?.taskSurface?{taskSurface:e.context.taskSurface}:{},...e.context?.gitRoot?{projectRoot:e.context.gitRoot}:{}}}i(oA,"buildWorkflowHostMetadata");function iA(e,t,n,r){let o=e.workflowRunsBaseDir;if(process.env.KODAX_DEBUG_WORKFLOW_GATE){let a=o===void 0?"no-host: workflowRunsBaseDir undefined":e.agentMode!=="ama"?`no-host: agentMode=${String(e.agentMode)} (need ama)`:e.context?.workflowIntent!=="explicit"?"no-host: explicit Workflow intent absent":"host wired";D({source:"coding:workflow-gate",level:"debug",message:"Workflow host gate evaluated.",detail:{agentMode:e.agentMode,runsBaseDir:o,decision:a}})}if(o===void 0||e.agentMode!=="ama"||e.context?.workflowIntent!=="explicit")return;let s=i(async({manifest:a,source:c,args:l,resumeFromRunId:d,signal:u})=>{let[{startManagedWorkflow:f},{getDefaultWorkflowRunManager:p}]=await Promise.all([import("./host-KHDXYFVG.js"),import("./run-manager-CD24OO4V.js")]),m=[e.abortSignal,u].filter(k=>k!==void 0),h=m.length===0?void 0:m.length===1?m[0]:AbortSignal.any(m),y=n&&r?{...e,context:{...e.context,actorControl:n,actorHost:r}}:e,w=await f({source:{kind:"inline",manifest:a,source:c},args:l,options:y,runsBaseDir:o,manager:p(),...(()=>{let k=rA(o,d);return k?{resumeFromRunDir:k}:{}})(),...h?{signal:h}:{},processMetadata:{hostMetadata:oA(e,t)}});if(w.kind==="declined")return{kind:"declined",reason:w.reason};let g=w.qualityWarnings?.map(k=>`${k.code}: ${k.message}`),b=w.managed.done.then(k=>{let v=w.managed.getSnapshot?.(),E=k.kind==="completed"?k.state.events.reduce((S,F)=>{if(F.type==="agent_unverified"){let C=F.data?.name??F.data?.taskId;S.push(typeof C=="string"&&C.length>0?C:"agent")}return S},[]):[];return{kind:"started",runId:w.runId,...v?.status!==void 0?{status:v.status}:{},...v?.resultText!==void 0?{resultText:v.resultText}:{},...v?.error!==void 0?{error:v.error}:{},...E.length>0?{verificationWarnings:E}:{},...g&&g.length>0?{workflowQualityWarnings:g}:{}}});return{kind:"started",runId:w.runId,done:b,...g&&g.length>0?{workflowQualityWarnings:g}:{}}},"startInline");return{startInline:s,runInline:i(async a=>{let c=await s(a);return c.kind==="declined"?{kind:"declined",reason:c.reason}:await c.done},"runInline")}}i(iA,"buildWorkflowToolHost");export{mA as a,hA as b,gA as c,Fo as d,Uo as e,pt as f,ev as g,hs as h,de as i,X as j,dC as k,Wc as l,Zt as m,kr as n,qo as o,Bo as p,Me as q,Pn as r,Mn as s,$h as t,_r as u,xt as v,Ko as w,bu as x,Yn as y,lP as z,dP as A,mP as B,lv as C,hP as D,Xc as E,xC as F,Yc as G,Zc as H,Xo as I,Sr as J,Au as K,xP as L,Cu as M,uv as N,EP as O,DC as P,Vo as Q,Qo as R,_g as S,xg as T,Zo as U,ii as V,si as W,Al as X,Fn as Y,kl as Z,Dn as _,_l as $,xl as aa,fi as ba,pi as ca,Un as da,hi as ea,gi as fa,We as ga,ln as ha,cI as ia,pd as ja,Ti as ka,Ai as la,md as ma,Ci as na,Ri as oa,Oi as pa,Ii as qa,Pi as ra,Mi as sa,Li as ta,Ni as ua,Hn as va,ie as wa,Vw as xa,Ji as ya,r$ as za,o$ as Aa,i$ as Ba,Gn as Ca,Jr as Da,Qr as Ea,zn as Fa,ub as Ga,fb as Ha,s$ as Ia,Qi as Ja,Zi as Ka,es as La,ts as Ma,It as Na,rs as Oa,pn as Pa,os as Qa,lu as Ra,Q as Sa,is as Ta,ss as Ua,as as Va,cs as Wa,Y$ as Xa,V$ as Ya,J$ as Za,Gb as _a,eo as $a,Q$ as ab,nr as bb,Re as cb,V_ as db,J_ as eb,er as fb,cf as gb,BM as hb,bf as ib,vf as jb,zM as kb,kf as lb,QM as mb,ZM as nb,e0 as ob,t0 as pb,n0 as qb,r0 as rb,_f as sb,Tf as tb,Gs as ub,Fk as vb,zt as wb,bo as xb,MD as yb,Dp as zb,jp as Ab,Tx as Bb,Hp as Cb,Kp as Db,dr as Eb,Xx as Fb,za as Gb,Xa as Hb,ZD as Ib,Jx as Jb,Qx as Kb,ej as Lb,tr as Mb,co as Nb,gt as Ob,yt as Pb,Vs as Qb,na as Rb,or as Sb,ir as Tb,Hf as Ub,Kf as Vb,ia as Wb,Xe as Xb,l_ as Yb,ca as Zb,jt as _b,_n as $b,f_ as ac,sr as bc,m_ as cc,v_ as dc,k_ as ec,Ut as fc,ar as gc,cr as hc,C_ as ic,ga as jc,qt as kc,Bt as lc,R_ as mc,O_ as nc,I_ as oc,D_ as pc,F_ as qc,H_ as rc,go as sc,ip as tc,z_ as uc,X_ as vc,Ya as wc,Va as xc,gj as yc,yj as zc,wj as Ac,bj as Bc,vj as Cc,ur as Dc,ko as Ec,em as Fc,rm as Gc,gx as Hc,En as Ic,yx as Jc,Tn as Kc,_e as Lc,Wt as Mc,wx as Nc,Da as Oc,bx as Pc,vx as Qc,Gt as Rc,kx as Sc,_x as Tc,xx as Uc,Ex as Vc,Sx as Wc,Ye as Xc,ja as Yc,CE as Zc,Js as _c,Sp as $c,Tp as ad,ax as bd,cx as cd,ux as dd,fx as ed,px as fd,UE as gd,dm as hd,um as id,xh as jd,YT as kd,jq as ld,VT as md,Fq as nd,Uq as od,Eh as pd,Sh as qd,qq as rd,Bq as sd,Wq as td,Hq as ud,pr as vd,fm as wd,km as xd,dc as yd,Mm as zd,WU as Ad,Dm as Bd,jm as Cd,pc as Dd,eq as Ed,Qm as Fd,kq as Gd,gr as Hd,Rq as Id,Oq as Jd,Th as Kd,Ah as Ld,tA as Md,Qq as Nd,d1 as Od};
369
+ </agent-message>`}i(kc,"renderMailboxMessage");function BT(e,t){if(!(!t||e.actor.capabilities.providers.includes("*"))&&!e.actor.capabilities.providers.includes(t))throw new Error(`Actor ${e.actor.path} is not authorized to use provider ${t}.`)}i(BT,"assertProviderAuthority");function ge(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}i(ge,"escapeXml");function WT(e){return{async admit(t){return e.spentBudget+t.units>e.totalBudget?{admitted:!1,fact:{code:"agent_budget_exhausted",retryable:!1,reason:`shared root work budget exhausted (${e.spentBudget}/${e.totalBudget})`}}:(e.spentBudget+=t.units,{admitted:!0})},async refund(){e.spentBudget=Math.max(0,e.spentBudget-1)},snapshot:i(()=>({...e}),"snapshot")}}i(WT,"managedWorkBudgetPort");function HT(e,t){let n=Te(e.specialistName);if(n)return n;let r=Te(e.agentId);if(!(!r||t.actor.kind==="native"))throw new Error(`Agent selector ${r} was not resolved before execution.`)}i(HT,"specialistName");function KT(e){return e==="fast"||e==="balanced"||e==="deep"?e:void 0}i(KT,"modelHint");function GT(e){let t=Te(e);if(!t)return;let n=Jt(t);return n==="auto"?void 0:n}i(GT,"effort");function Te(e){return typeof e=="string"&&e.length>0?e:void 0}i(Te,"metadataString");function bh(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(bh,"metadataStringArray");import _h from"node:path";var zT=80;function XT(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"").slice(0,zT);return!t||t==="."||t===".."?"session":t}i(XT,"sanitizeScratchSessionId");function xh(e){let t=e.session?.id?.trim();if(!t)return;let n=e.context?.gitRoot?.trim(),r=n?_h.resolve(n):de(e.context);return _h.resolve(r,".agent","tmp","sessions",XT(t))}i(xh,"getSessionScratchDir");var YT="emit_managed_protocol",jq="kodax-task-contract",VT="kodax-task-verdict",Fq="kodax-task-scout",Uq="kodax-task-handoff";function JT(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}i(JT,"asRecord");function Eh(e){return e.trim().toLowerCase()===YT}i(Eh,"isManagedProtocolToolName");function Sh(e,t){if(!(!e&&!t))return{verdict:t?.verdict?{...e?.verdict??{},...t.verdict}:e?.verdict}}i(Sh,"mergeManagedProtocolPayload");function QT(e){let t=e.trim().toLowerCase();if(!t)return;let r=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[_\s-]+/g," ").trim().split(/\s+/,1)[0]??"";if(r){if(/^accept(?:ed|s|ing)?$/.test(r)||r==="approve"||r==="approved")return"accept";if(/^revis(?:e|ed|es|ing)?$/.test(r))return"revise";if(/^block(?:ed|ing)?$/.test(r))return"blocked"}}i(QT,"normalizeManagedVerdictStatus");function ZT(e){let t=e.trim();if(!t)return;let n=t.replace(/[`"'()[\]{}<>]+/g,"").replace(/[.:;!?]+$/g,"").replace(/[\s-]+/g,"_").trim().toUpperCase();if(n==="H1_EXECUTE_EVAL"||n==="H1")return"H1_EXECUTE_EVAL";if(n==="H2_PLAN_EXECUTE_EVAL"||n==="H2")return"H2_PLAN_EXECUTE_EVAL"}i(ZT,"normalizeManagedNextHarness");function eA(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean):typeof e=="string"?e.split(/\r?\n/).map(t=>t.replace(/^-+\s*/,"").trim()).filter(Boolean):[]}i(eA,"normalizeStringListValue");function qq(e,t,n=""){let r=JT(t);if(!r||e!=="evaluator")return;let o=typeof r.status=="string"?QT(r.status):void 0;if(o)return{verdict:{source:"evaluator",status:o,reason:typeof r.reason=="string"&&r.reason.trim()||void 0,followups:eA(r.followup??r.followups),userFacingText:n,userAnswer:typeof r.user_answer=="string"?r.user_answer.trim()||void 0:typeof r.userAnswer=="string"&&r.userAnswer.trim()||void 0,nextHarness:typeof(r.next_harness??r.nextHarness)=="string"?ZT(String(r.next_harness??r.nextHarness)):void 0,budgetRequest:typeof(r.budget_request??r.budgetRequest)=="string"&&String(r.budget_request??r.budgetRequest).trim()||void 0}}}i(qq,"coerceManagedProtocolToolPayload");function Bq(e){if(e==="evaluator")return VT}i(Bq,"getManagedBlockNameForRole");function Wq(e,t){return e&&t==="evaluator"?!!e.verdict:!1}i(Wq,"hasManagedProtocolForRole");function Hq(e,t){return new RegExp(String.raw`\`\`\`${t}\s*[\s\S]*?\`\`\``,"i").test(e)}i(Hq,"textContainsManagedBlock");function Th(e,t){if(!t||t.length===0)return e;let n=new Set(t);return e.filter(r=>!n.has(r))}i(Th,"filterExcludedTools");function Ah(e,t){return t?e.filter(n=>{let r=_e(n);return r?t({name:r.name,sideEffect:r.sideEffect,planModeAllowed:r.planModeAllowed===!0}):!1}):e}i(Ah,"applyToolVisibilityPolicy");function tA(e,t,n=!1,r,o=!1){let s=Ji(t)==="off"?Fa(e):e;return n||(s=Ua(s)),s=Aa(s,r),s=La(s,r),o||(s=s.filter(a=>a!=="list_dispatchable_agents")),s}i(tA,"getRuntimeActiveToolNames");function Qq(e,t,n=!1,r=!1,o,s,a,c=!1){let l=ja();if(e.length===0)return[];let d=new Set(tA(e,t,r,o,c));return l.filter(u=>d.has(u.name)&&(n||!Eh(u.name))).map(u=>{let f=Sr(u,a);if(!bo(f.name)||s&&s.has(f.name))return f;let p=zt[f.name];return p?{...f,description:p}:f})}i(Qq,"getActiveToolDefinitions");import{join as nA}from"node:path";function rA(e,t){if(t&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return nA(e,t)}i(rA,"resolveResumeFromRunDir");function d1(e){let{options:t,runtime:n,managedProtocolPayloadRef:r,sessionId:o}=e,s=t.events??{},a=de(t.context),c=xh(t),l=Ah(Th([...mt],t.context?.excludeTools),t.context?.toolVisibilityPolicy),d=mt.every(f=>l.includes(f))?bs({sessionId:o,currentAgentId:t.context?.currentAgentId,sessionScope:t.session?.scope,storage:t.session?.storage}):void 0,u={backups:new Map,actorControl:t.context?.actorControl,actorHost:t.context?.actorHost,managedWorkBudget:t.context?.managedWorkBudget,gitRoot:t.context?.gitRoot??void 0,sessionId:o,...d!==void 0?{loadSessionHistory:d}:{},taskSurface:t.context?.taskSurface,agentProfile:t.context?.agentProfile,agentScope:t.context?.agentScope,agentExecutorPlane:t.context?.agentExecutorPlane,selfManual:t.selfManual,skillDynamicContext:t.skillDynamicContext,skillRegistry:t.context?.skillRegistry,skillScriptRunner:t.context?.skillScriptRunner,assertReadablePath:t.context?.assertReadablePath,toolVisibilityPolicy:t.context?.toolVisibilityPolicy,excludeTools:t.context?.excludeTools,lspService:t.context?.lspService??Mm(),executionCwd:a,sessionScratchDir:c,extensionRuntime:n,askUser:s.askUser,askUserMulti:s.askUserMulti,askUserInput:s.askUserInput,exitPlanMode:s.exitPlanMode,abortSignal:t.abortSignal,managedProtocolRole:t.context?.managedProtocolEmission?.enabled?t.context.managedProtocolEmission.role:void 0,emitManagedProtocol:t.context?.managedProtocolEmission?.enabled?f=>{r.current=Sh(r.current,f)}:void 0,mutationTracker:t.context?.mutationTracker,planModeBlockCheck:t.context?.planModeBlockCheck,guardrails:t.guardrails,parentAgentConfig:{provider:t.provider,model:t.modelOverride??t.model,reasoningMode:t.reasoningMode,effort:t.effort,repoIntelligenceMode:t.context?.repoIntelligenceMode,repoIntelligenceTrace:t.context?.repoIntelligenceTrace,...t.compaction!==void 0?{compaction:{...t.compaction}}:{}},parentEvents:s,onChildProgress:void 0,sendMessageTurnCounter:{count:0},goalContext:t.context?.goalRuntime?.goalContext};if(!u.actorControl&&(t.agentMode==="ama"||t.context?.actorSession)){let f=t.context?.actorSession??new gr({maxConcurrentThreadsPerSession:t.maxConcurrentThreadsPerSession,sessionId:o});u.actorHost=f,u.actorControl=f.attach(u,t)}return u.workflowHost=iA(t,o,u.actorControl,u.actorHost),u}i(d1,"buildToolExecutionContext");function oA(e,t){return{...t?{sessionId:t}:{},...e.context?.agentProfile?.surface?{surface:e.context.agentProfile.surface}:{},...e.context?.taskSurface?{taskSurface:e.context.taskSurface}:{},...e.context?.gitRoot?{projectRoot:e.context.gitRoot}:{}}}i(oA,"buildWorkflowHostMetadata");function iA(e,t,n,r){let o=e.workflowRunsBaseDir;if(process.env.KODAX_DEBUG_WORKFLOW_GATE){let a=o===void 0?"no-host: workflowRunsBaseDir undefined":e.agentMode!=="ama"?`no-host: agentMode=${String(e.agentMode)} (need ama)`:e.context?.workflowIntent!=="explicit"?"no-host: explicit Workflow intent absent":"host wired";D({source:"coding:workflow-gate",level:"debug",message:"Workflow host gate evaluated.",detail:{agentMode:e.agentMode,runsBaseDir:o,decision:a}})}if(o===void 0||e.agentMode!=="ama"||e.context?.workflowIntent!=="explicit")return;let s=i(async({manifest:a,source:c,args:l,resumeFromRunId:d,signal:u})=>{let[{startManagedWorkflow:f},{getDefaultWorkflowRunManager:p}]=await Promise.all([import("./host-RKZ2OGFT.js"),import("./run-manager-7RM4HEH6.js")]),m=[e.abortSignal,u].filter(k=>k!==void 0),h=m.length===0?void 0:m.length===1?m[0]:AbortSignal.any(m),y=n&&r?{...e,context:{...e.context,actorControl:n,actorHost:r}}:e,w=await f({source:{kind:"inline",manifest:a,source:c},args:l,options:y,runsBaseDir:o,manager:p(),...(()=>{let k=rA(o,d);return k?{resumeFromRunDir:k}:{}})(),...h?{signal:h}:{},processMetadata:{hostMetadata:oA(e,t)}});if(w.kind==="declined")return{kind:"declined",reason:w.reason};let g=w.qualityWarnings?.map(k=>`${k.code}: ${k.message}`),b=w.managed.done.then(k=>{let v=w.managed.getSnapshot?.(),E=k.kind==="completed"?k.state.events.reduce((S,F)=>{if(F.type==="agent_unverified"){let C=F.data?.name??F.data?.taskId;S.push(typeof C=="string"&&C.length>0?C:"agent")}return S},[]):[];return{kind:"started",runId:w.runId,...v?.status!==void 0?{status:v.status}:{},...v?.resultText!==void 0?{resultText:v.resultText}:{},...v?.error!==void 0?{error:v.error}:{},...E.length>0?{verificationWarnings:E}:{},...g&&g.length>0?{workflowQualityWarnings:g}:{}}});return{kind:"started",runId:w.runId,done:b,...g&&g.length>0?{workflowQualityWarnings:g}:{}}},"startInline");return{startInline:s,runInline:i(async a=>{let c=await s(a);return c.kind==="declined"?{kind:"declined",reason:c.reason}:await c.done},"runInline")}}i(iA,"buildWorkflowToolHost");export{mA as a,hA as b,gA as c,Fo as d,Uo as e,pt as f,ev as g,hs as h,de as i,X as j,dC as k,Wc as l,Zt as m,kr as n,qo as o,Bo as p,Me as q,Pn as r,Mn as s,$h as t,_r as u,xt as v,Ko as w,bu as x,Yn as y,lP as z,dP as A,mP as B,lv as C,hP as D,Xc as E,xC as F,Yc as G,Zc as H,Xo as I,Sr as J,Au as K,xP as L,Cu as M,uv as N,EP as O,DC as P,Vo as Q,Qo as R,_g as S,xg as T,Zo as U,ii as V,si as W,Al as X,Fn as Y,kl as Z,Dn as _,_l as $,xl as aa,fi as ba,pi as ca,Un as da,hi as ea,gi as fa,We as ga,ln as ha,cI as ia,pd as ja,Ti as ka,Ai as la,md as ma,Ci as na,Ri as oa,Oi as pa,Ii as qa,Pi as ra,Mi as sa,Li as ta,Ni as ua,Hn as va,ie as wa,Vw as xa,Ji as ya,r$ as za,o$ as Aa,i$ as Ba,Gn as Ca,Jr as Da,Qr as Ea,zn as Fa,ub as Ga,fb as Ha,s$ as Ia,Qi as Ja,Zi as Ka,es as La,ts as Ma,It as Na,rs as Oa,pn as Pa,os as Qa,lu as Ra,Q as Sa,is as Ta,ss as Ua,as as Va,cs as Wa,Y$ as Xa,V$ as Ya,J$ as Za,Gb as _a,eo as $a,Q$ as ab,nr as bb,Re as cb,V_ as db,J_ as eb,er as fb,cf as gb,BM as hb,bf as ib,vf as jb,zM as kb,kf as lb,QM as mb,ZM as nb,e0 as ob,t0 as pb,n0 as qb,r0 as rb,_f as sb,Tf as tb,Gs as ub,Fk as vb,zt as wb,bo as xb,MD as yb,Dp as zb,jp as Ab,Tx as Bb,Hp as Cb,Kp as Db,dr as Eb,Xx as Fb,za as Gb,Xa as Hb,ZD as Ib,Jx as Jb,Qx as Kb,ej as Lb,tr as Mb,co as Nb,gt as Ob,yt as Pb,Vs as Qb,na as Rb,or as Sb,ir as Tb,Hf as Ub,Kf as Vb,ia as Wb,Xe as Xb,l_ as Yb,ca as Zb,jt as _b,_n as $b,f_ as ac,sr as bc,m_ as cc,v_ as dc,k_ as ec,Ut as fc,ar as gc,cr as hc,C_ as ic,ga as jc,qt as kc,Bt as lc,R_ as mc,O_ as nc,I_ as oc,D_ as pc,F_ as qc,H_ as rc,go as sc,ip as tc,z_ as uc,X_ as vc,Ya as wc,Va as xc,gj as yc,yj as zc,wj as Ac,bj as Bc,vj as Cc,ur as Dc,ko as Ec,em as Fc,rm as Gc,gx as Hc,En as Ic,yx as Jc,Tn as Kc,_e as Lc,Wt as Mc,wx as Nc,Da as Oc,bx as Pc,vx as Qc,Gt as Rc,kx as Sc,_x as Tc,xx as Uc,Ex as Vc,Sx as Wc,Ye as Xc,ja as Yc,CE as Zc,Js as _c,Sp as $c,Tp as ad,ax as bd,cx as cd,ux as dd,fx as ed,px as fd,UE as gd,dm as hd,um as id,xh as jd,YT as kd,jq as ld,VT as md,Fq as nd,Uq as od,Eh as pd,Sh as qd,qq as rd,Bq as sd,Wq as td,Hq as ud,pr as vd,fm as wd,km as xd,dc as yd,Mm as zd,WU as Ad,Dm as Bd,jm as Cd,pc as Dd,eq as Ed,Qm as Fd,kq as Gd,gr as Hd,Rq as Id,Oq as Jd,Th as Kd,Ah as Ld,tA as Md,Qq as Nd,d1 as Od};
@@ -0,0 +1,5 @@
1
+ // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
+ import{g as R,h as _}from"./chunk-EI4JBQKL.js";import{a as r}from"./chunk-ONUPGMER.js";var u=class extends Error{static{r(this,"KodaXMediaError")}code;detail;cause;constructor(e,i,o={}){super(i),this.name="KodaXMediaError",this.code=e,this.detail=o.detail,this.cause=o.cause}},p=class extends u{static{r(this,"ImageResizeError")}constructor(e,i={}){super(i.code??"IMAGE_TOO_LARGE",e,i),this.name="ImageResizeError"}};import O from"node:path";var Z={".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"},ee={".3gp":"video/3gpp",".3gpp":"video/3gpp",".avi":"video/x-msvideo",".flv":"video/x-flv",".mov":"video/quicktime",".mp4":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".webm":"video/webm",".wmv":"video/x-ms-wmv"};function N(t){return Z[O.extname(t).toLowerCase()]}r(N,"inferImageMediaType");function $(t){return ee[O.extname(t).toLowerCase()]}r($,"inferVideoMediaType");function te(t,e={}){let i=e.mediaType??N(t);return{kind:"image",path:t,...i?{mediaType:i}:{},...e.source?{source:e.source}:{},...e.description?{description:e.description}:{}}}r(te,"createImageArtifactFromPath");function ie(t,e={}){if(e.mediaType!==void 0&&e.mimeType!==void 0&&e.mediaType!==e.mimeType)throw new u("UNSUPPORTED_MEDIA_TYPE",`File artifact mediaType and mimeType disagree: ${e.mediaType} != ${e.mimeType}.`);return{kind:"file",path:t,...e.mediaType?{mediaType:e.mediaType}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.name?{name:e.name}:{},...e.source?{source:e.source}:{},...e.description?{description:e.description}:{}}}r(ie,"createFileArtifactFromPath");function re(t,e={}){let i=e.mediaType??$(t);if(!i)throw new u("UNSUPPORTED_MEDIA_TYPE",`Cannot infer video media type from path: ${t}.`);return{kind:"video",path:t,mediaType:i,...e.name?{name:e.name}:{},...e.source?{source:e.source}:{},...e.description?{description:e.description}:{}}}r(re,"createVideoArtifactFromPath");import{Jimp as ne}from"jimp";var F=2e3,C=Math.floor(3.75*1024*1024),oe=[80,60,40];async function A(t,e={}){let i=e.maxDimension??F,o=e.targetBytes??C;if(t.length===0)throw new p("Empty image buffer.",{code:"IMAGE_DECODE_FAILED"});let n;try{n=await ne.read(t)}catch(c){let I=c instanceof Error?c.message:String(c);throw new p(`Failed to decode image: ${I}`,{code:"IMAGE_DECODE_FAILED",cause:c})}let{width:a,height:d}=n.bitmap,s=Math.max(a,d);if(s>i){let c=i/s;n.resize({w:Math.max(1,Math.round(a*c)),h:Math.max(1,Math.round(d*c))})}let m=n.bitmap.width,l=n.bitmap.height;if(e.preferMediaType!=="image/jpeg"){let c=await n.getBuffer("image/png");if(c.length<=o)return{buffer:Buffer.from(c),mediaType:"image/png",width:m,height:l}}for(let c of oe){let I=await n.getBuffer("image/jpeg",{quality:c});if(I.length<=o)return{buffer:Buffer.from(I),mediaType:"image/jpeg",width:m,height:l}}if(e.preferMediaType==="image/jpeg"){let c=await n.getBuffer("image/png");if(c.length<=o)return{buffer:Buffer.from(c),mediaType:"image/png",width:m,height:l}}throw new p(`Image still exceeds budget (${o} bytes raw) after PNG and JPEG q40 compression. Try a smaller image or take a fresh screenshot of a smaller region.`,{code:"IMAGE_TOO_LARGE"})}r(A,"normalizePastedImage");import{spawn as L}from"node:child_process";import{mkdtemp as ae,readFile as se,rm as de}from"node:fs/promises";import{tmpdir as me}from"node:os";import U from"node:path";var q=5e3;async function X(){switch(process.platform){case"darwin":return ce();case"win32":return fe();case"linux":return pe();default:throw new u("UNSUPPORTED_PLATFORM",`Clipboard image fallback is not supported on platform "${process.platform}".`)}}r(X,"readClipboardImage");async function ue(t={}){let e=await X();return e?A(e,t):null}r(ue,"readAndNormalizeClipboardImage");async function j(t){let e=await ae(U.join(me(),"kodax-clip-")),i=U.join(e,"clip.png");try{return await t(i)}finally{await de(e,{recursive:!0,force:!0}).catch(o=>{})}}r(j,"runWithTempPng");async function ce(){return j(async t=>{let e=`set png_data to (the clipboard as \xABclass PNGf\xBB)
3
+ set fh to open for access POSIX file "${t.replace(/"/g,'\\"')}" with write permission
4
+ write png_data to fh
5
+ close access fh`;return await G("osascript",["-e",e])?B(t):null})}r(ce,"readMacClipboard");async function fe(){return j(async t=>{let e=["Add-Type -AssemblyName System.Drawing | Out-Null","$img = Get-Clipboard -Format Image","if ($null -eq $img) { exit 1 }",`$img.Save('${t.replace(/'/g,"''")}', [System.Drawing.Imaging.ImageFormat]::Png)`].join("; ");return await G("powershell",["-NoProfile","-Command",e])?B(t):null})}r(fe,"readWinClipboard");async function pe(){return await K("wl-paste",["--type","image/png"])??K("xclip",["-selection","clipboard","-t","image/png","-o"])}r(pe,"readLinuxClipboard");async function B(t){try{let e=await se(t);return e.length>0?e:null}catch(e){return null}}r(B,"readNonEmptyFile");function G(t,e){return new Promise(i=>{let o=!1,n=L(t,[...e],{stdio:"ignore",windowsHide:!0}),a=setTimeout(()=>{o||(o=!0,n.kill(),i(!1))},q);n.once("error",()=>{o||(o=!0,clearTimeout(a),i(!1))}),n.once("exit",d=>{o||(o=!0,clearTimeout(a),i(d===0))})})}r(G,"runCommand");function K(t,e){return new Promise(i=>{let o=!1,n=[],a=L(t,[...e],{stdio:["ignore","pipe","ignore"],windowsHide:!0}),d=setTimeout(()=>{o||(o=!0,a.kill(),i(null))},q);a.stdout?.on("data",s=>n.push(s)),a.once("error",()=>{o||(o=!0,clearTimeout(d),i(null))}),a.once("exit",s=>{if(o)return;if(o=!0,clearTimeout(d),s!==0){i(null);return}let m=Buffer.concat(n);i(m.length>0?m:null)})})}r(K,"collectStdoutBytes");import{createHash as le}from"node:crypto";import{mkdir as ge,readdir as he,stat as Te,unlink as ye,writeFile as Ie}from"node:fs/promises";import{tmpdir as we}from"node:os";import x from"node:path";var Y="KODAX_PASTE_TMP_DIR",z=1440*60*1e3;function Q(){return process.env[Y]??x.join(we(),"kodax-paste")}r(Q,"resolvePasteTmpDir");function Ee(t){let e=t?.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return e&&e.length>0?e:"paste"}r(Ee,"sanitizeFileNamePrefix");async function _e(t,e={}){let i=e.directory??Q();await ge(i,{recursive:!0});let o=t.mediaType==="image/jpeg"?".jpg":".png",n=le("sha256").update(t.buffer).digest("hex").slice(0,16),a=`${Ee(e.fileNamePrefix)}-${n}${o}`,d=x.join(i,a);return await Ie(d,t.buffer),{type:"image",path:d,mediaType:t.mediaType}}r(_e,"persistImageAsBlock");async function Ae(t=Date.now()){let e=Q(),i;try{i=await he(e)}catch(a){return 0}let o=t-z,n=0;return await Promise.all(i.filter(a=>/-[0-9a-f]{16}\.(?:png|jpg)$/.test(a)).map(async a=>{let d=x.join(e,a);try{(await Te(d)).mtimeMs<o&&(await ye(d),n+=1)}catch(s){}})),n}r(Ae,"prunePasteTmpDir");var h=["image/png","image/jpeg","image/webp","image/gif"],T=["video/mp4","video/mpeg","video/quicktime","video/x-msvideo","video/x-flv","video/webm","video/x-ms-wmv","video/3gpp"],xe=[],ke=new Set(["anthropic","openai"]),Me=new Set(["ark-coding/doubao-seed-2.0-code","ark-coding/doubao-seed-2.0-pro","ark-coding/kimi-k2.6","ark-coding/kimi-k2.7-code","ark-coding/minimax-m3","kimi-code/k3-256k","qwen-token-plan/qwen3.8-max-preview","qwen-token-plan/qwen3.7-plus","qwen-token-plan/qwen3.6-flash"]),De=new Set(["kimi-code/kimi-for-coding","kimi-code/kimi-for-coding-highspeed","kimi-code/k3","kimi/kimi-k2.5","kimi/kimi-k2.6","kimi/kimi-k2.7-code","kimi/kimi-k2.7-code-highspeed","minimax-coding/minimax-m3","minimax/minimax-m3","mimo-coding/mimo-v2.5","mimo/mimo-v2.5"]);function k(t){return{nativeSupported:!1,sdkSupported:!1,status:"unsupported",mediaTypes:[],maxCount:0,reason:t}}r(k,"unsupported");function Pe(t){return{nativeSupported:!0,sdkSupported:!0,status:"supported",mediaTypes:h,nativeMediaTypes:h,reason:t}}r(Pe,"supportedImage");function ve(t){return{nativeSupported:!0,sdkSupported:!1,status:"provider-native-unwired",mediaTypes:[],nativeMediaTypes:T,maxCount:0,reason:t}}r(ve,"nativeVideoUnwired");function Se(t){return t.trim().toLowerCase()}r(Se,"normalizeProvider");function be(t){return _[t]?.model}r(be,"resolveProviderDefaultModel");function V(t,e){if(!e)return;let i=e.trim().toLowerCase();if(t==="kimi"){if(i==="k2.5")return"kimi-k2.5";if(i==="k2.6")return"kimi-k2.6";if(i==="k2.7-code")return"kimi-k2.7-code";if(i==="k2.7-code-highspeed")return"kimi-k2.7-code-highspeed"}return(t==="minimax-coding"||t==="minimax")&&i==="minimax-m3"?"minimax-m3":i}r(V,"normalizeModel");function Re(t){if(!ke.has(t))return!1;let e=_[t];return e?R(e.capabilityProfile).multimodalSupport!=="none":!1}r(Re,"hasOfficialImageSupport");function Oe(t,e){let i=V(t,e);if(!i)return!1;let o=`${t}/${i}`;return De.has(o)}r(Oe,"hasSourceBackedNativeMedia");function Ne(t,e){let i=V(t,e);return i?Me.has(`${t}/${i}`):!1}r(Ne,"hasSourceBackedImage");function $e(t,e,i){if(i)return"source-backed";if(e){if(t==="openai")return"openai-official";if(t==="anthropic")return"anthropic-official"}}r($e,"resolveImageCapabilityRoute");function Fe(t){switch(t){case"openai-official":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif, but OpenAI requires non-animated GIF semantics.";case"anthropic-official":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif, but Anthropic uses only the first frame of animated GIFs.";case"source-backed":return"Model route supports KodaX image input. Direct-path image/gif is sent as image/gif; animated-GIF interpretation is provider-owned."}}r(Fe,"imageCapabilityReason");function M(t){let e=Se(t.provider),i=t.model?.trim()||be(e),o=Re(e),n=Oe(e,i),a=n||Ne(e,i),d=$e(e,o,a),s=d!==void 0,m=n;return{text:!0,image:s?Pe(Fe(d)):k("No verified KodaX image-input route for this provider/model."),video:m?ve("Model route is native-video capable, but KodaX SDK video sending is not wired yet. Reject or downgrade before send."):k("No verified native video route for this provider/model."),file:k("File artifact contract is stable, but KodaX SDK file sending/extraction is not wired yet. Reject or downgrade before send.")}}r(M,"getModelInputCapabilities");function Ce(t){return h.includes(t)}r(Ce,"isKnownImageMediaType");function Ue(t){return T.includes(t)}r(Ue,"isKnownVideoMediaType");function D(t){return`${t.provider}${t.model?`/${t.model}`:""}`}r(D,"routeLabel");function P(t){return t.reason?`${t.status}: ${t.reason}`:t.status}r(P,"capabilityDetail");function v(t,e){if(t.length===0)return;let i=M(e);for(let o of t){let n=o;if(n.kind==="image"){if(!i.image.nativeSupported||!i.image.sdkSupported)throw new u("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume image artifacts: ${D(e)}.`,{detail:P(i.image)});if(typeof n.mediaType=="string"&&!Ce(n.mediaType))throw new u("UNSUPPORTED_MEDIA_TYPE",`Unsupported image media type: ${n.mediaType}.`);continue}throw n.kind==="video"?typeof n.mediaType!="string"||!Ue(n.mediaType)?new u("UNSUPPORTED_MEDIA_TYPE",`Unsupported video media type: ${String(n.mediaType)}.`,{detail:`Supported video media types: ${T.join(", ")}`}):new u("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume video artifacts through this SDK runtime: ${D(e)}.`,{detail:P(i.video)}):n.kind==="file"?typeof n.mediaType=="string"&&typeof n.mimeType=="string"&&n.mediaType!==n.mimeType?new u("UNSUPPORTED_MEDIA_TYPE",`File artifact mediaType and mimeType disagree: ${n.mediaType} != ${n.mimeType}.`):new u("MODEL_INPUT_UNSUPPORTED",`Provider/model cannot consume file artifacts through this SDK runtime: ${D(e)}.`,{detail:P(i.file)}):new u("MODEL_INPUT_UNSUPPORTED",`Unsupported input artifact kind: ${String(n.kind)}.`)}}r(v,"validateInputArtifactsForModel");var g={user:0,background:1};function Ke(t,e){return g[t]<=g[e]}r(Ke,"priorityWithinMax");function W(t,e){return!(t.agentId!==e.agentId||!Ke(t.priority,e.maxPriority)||e.mode!==void 0&&t.mode!==e.mode||e.id!==void 0&&t.id!==e.id||e.predicate&&!e.predicate(t))}r(W,"matchesFilter");var E=class{static{r(this,"MessageQueue")}messages=[];nextSeq=1;listeners=new Set;snapshotRef=Object.freeze([]);notify(e){this.snapshotRef=Object.freeze([...this.messages]);for(let i of this.listeners)try{i(e)}catch{}}subscribe=r(e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),"subscribe");getSnapshot=r(()=>this.snapshotRef,"getSnapshot");enqueue(e){let i=`msg-${this.nextSeq++}`,o={id:i,priority:e.priority,mode:e.mode,content:e.content,agentId:e.agentId,inputArtifacts:e.inputArtifacts,taskResult:e.taskResult,enqueuedAt:Date.now()};return this.messages=[...this.messages,o],this.notify({kind:"enqueued",message:o}),i}dequeue(e){let i=[];for(let s=0;s<this.messages.length;s++){let m=this.messages[s];m&&W(m,e)&&i.push({originalIndex:s,message:m})}i.sort((s,m)=>{let l=g[s.message.priority]-g[m.message.priority];return l!==0?l:s.originalIndex-m.originalIndex});let o=e.limit,n=typeof o=="number"&&i.length>o?i.slice(0,o):i;if(n.length===0)return[];let a=new Set(n.map(s=>s.originalIndex));this.messages=this.messages.filter((s,m)=>!a.has(m));let d=n.map(s=>s.message);return this.notify({kind:"dequeued",messages:d}),d}peek(e){let i=[];for(let a=0;a<this.messages.length;a++){let d=this.messages[a];d&&W(d,e)&&i.push({originalIndex:a,message:d})}i.sort((a,d)=>{let s=g[a.message.priority]-g[d.message.priority];return s!==0?s:a.originalIndex-d.originalIndex});let o=e.limit;return(typeof o=="number"&&i.length>o?i.slice(0,o):i).map(a=>a.message)}size(){return this.messages.length}count(e){return this.peek(e).length}has(e){return this.count(e)>0}clear(){if(this.messages.length===0)return;let e=this.messages;this.messages=[],this.notify({kind:"cleared",messages:e})}},w;function y(){return w||(w=new E),w}r(y,"getMessageQueue");function Le(){w=void 0}r(Le,"_resetMessageQueueForTests");function S(t,e){return t?`actor:${t}:${e}`:e==="/root"?void 0:e}r(S,"actorQueueId");var f=new Map;function qe(t){f.set(t,(f.get(t)??0)+1);let e=!1;return()=>{if(e)return;e=!0;let i=f.get(t);i===void 0||i<=1?f.delete(t):f.set(t,i-1)}}r(qe,"registerActiveRootQueueRoute");function b(){if(f.size!==0){if(f.size===1)return f.keys().next().value;throw new Error("Cannot infer queued follow-up target: multiple Actor root sessions are active. Pass sessionId or agentId explicitly.")}}r(b,"resolveActiveRootQueueRoute");function Xe(){f.clear()}r(Xe,"_resetActiveRootQueueRoutesForTests");var H=new Set(["wait_agent"]);function J(t){return t.some(i=>H.has(i))?"background":"user"}r(J,"midTurnDrainPriority");function je(t){let e=J(t.lastTurnToolNames);return y().dequeue({agentId:t.agentId,maxPriority:e,limit:t.limit})}r(je,"maybeDrainMidTurn");function Be(t){if(v(t.inputArtifacts??[],t),t.agentId!==void 0&&t.sessionId!==void 0)throw new Error("enqueueWithArtifacts accepts either agentId or sessionId, not both.");if(t.sessionId!==void 0&&t.sessionId.trim().length===0)throw new Error("enqueueWithArtifacts sessionId must not be empty.");let e=t.agentId??(t.sessionId!==void 0?S(t.sessionId,"/root"):b());return y().enqueue({priority:t.priority??"user",mode:"prompt",content:t.content,agentId:e,inputArtifacts:t.inputArtifacts})}r(Be,"enqueueWithArtifacts");export{u as a,p as b,N as c,$ as d,te as e,ie as f,re as g,F as h,C as i,A as j,X as k,ue as l,Y as m,z as n,_e as o,Ae as p,h as q,T as r,xe as s,M as t,v as u,E as v,y as w,Le as x,S as y,qe as z,b as A,Xe as B,H as C,J as D,je as E,Be as F};