@kodax-ai/kodax 0.7.97-alpha.6 → 0.7.97-alpha.7

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 (66) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +21 -1
  3. package/README_CN.md +12 -0
  4. package/dist/chunks/{agent-Z2YSHTJ5.js → agent-EIT4WRTJ.js} +1 -1
  5. package/dist/chunks/argument-completer-N54LWSHY.js +2 -0
  6. package/dist/chunks/{chunk-XEBZJLCW.js → chunk-2EAGDPF4.js} +1 -1
  7. package/dist/chunks/{chunk-NOJ3W5PC.js → chunk-2IRDPHVI.js} +1 -1
  8. package/dist/chunks/{chunk-MWIDZ2GQ.js → chunk-5DF2ZZDA.js} +2 -2
  9. package/dist/chunks/{chunk-XL2N3RDM.js → chunk-5HEBQ4ZF.js} +1 -1
  10. package/dist/chunks/{chunk-SR67IEBP.js → chunk-AJ3VSHGK.js} +1 -1
  11. package/dist/chunks/chunk-BYRPTXH4.js +497 -0
  12. package/dist/chunks/{chunk-DTG3ZF5R.js → chunk-DTJNXVL6.js} +2 -2
  13. package/dist/chunks/{chunk-UGNSAKIT.js → chunk-FX4R5PB3.js} +1 -1
  14. package/dist/chunks/{chunk-VT6MCIE5.js → chunk-HD5BDOPC.js} +1 -1
  15. package/dist/chunks/{chunk-WILX5FJH.js → chunk-J5XBQRJU.js} +4 -4
  16. package/dist/chunks/{chunk-WJL25O6B.js → chunk-JNB2FL6P.js} +1 -1
  17. package/dist/chunks/{chunk-MRZ223W7.js → chunk-L4HSHRFD.js} +1 -1
  18. package/dist/chunks/{chunk-A3YY6JUN.js → chunk-LEON6EFI.js} +1 -1
  19. package/dist/chunks/{chunk-WNSCGMP4.js → chunk-PGT2VSOD.js} +1 -1
  20. package/dist/chunks/{chunk-RLINWRJJ.js → chunk-PRMGOFYX.js} +196 -196
  21. package/dist/chunks/{chunk-PRQEFTX5.js → chunk-PV6DILEK.js} +1 -1
  22. package/dist/chunks/{chunk-RRCIJ234.js → chunk-TXCU25XM.js} +2 -2
  23. package/dist/chunks/{chunk-SQONUELA.js → chunk-VHUCG5YI.js} +1 -1
  24. package/dist/chunks/{chunk-XPEKJKPG.js → chunk-VSOFCKQV.js} +1 -1
  25. package/dist/chunks/{chunk-QFIMF7II.js → chunk-X6BSM54P.js} +2 -2
  26. package/dist/chunks/{chunk-UHC66D7T.js → chunk-XMWTEVFZ.js} +143 -140
  27. package/dist/chunks/{chunk-R7YXI7AB.js → chunk-YHIHYPGQ.js} +3 -3
  28. package/dist/chunks/{client-76JHO3LB.js → client-XFASU74S.js} +1 -1
  29. package/dist/chunks/{compaction-config-HTYGVGD7.js → compaction-config-JZNGDKWW.js} +1 -1
  30. package/dist/chunks/{construction-bootstrap-SW7V7RX6.js → construction-bootstrap-AWOLGJJV.js} +1 -1
  31. package/dist/chunks/{dist-C627SSXJ.js → dist-UG67JCUH.js} +1 -1
  32. package/dist/chunks/host-76O7ZRNA.js +2 -0
  33. package/dist/chunks/readline-helpers-LPPOL5FD.js +2 -0
  34. package/dist/chunks/{run-manager-5O53IGLW.js → run-manager-MPQPULSV.js} +1 -1
  35. package/dist/chunks/{tool-dispatch-FH6TSX64.js → tool-dispatch-K2FJZ5WP.js} +1 -1
  36. package/dist/chunks/{utils-RNKK4N7M.js → utils-KLOVODMA.js} +1 -1
  37. package/dist/index.js +1 -1
  38. package/dist/kodax_bootstrap.js +1 -1
  39. package/dist/kodax_cli.js +1274 -1271
  40. package/dist/native/win32-x64/kodax-windows-sandbox.exe +0 -0
  41. package/dist/native/win32-x64/kodax-windows-text-transaction.node +0 -0
  42. package/dist/native/win32-x64/manifest.json +2 -2
  43. package/dist/sandbox-network-broker.js +9 -9
  44. package/dist/sdk-a2a.js +1 -1
  45. package/dist/sdk-agent.d.ts +6 -1
  46. package/dist/sdk-agent.js +1 -1
  47. package/dist/sdk-client.js +1 -1
  48. package/dist/sdk-coding.js +1 -1
  49. package/dist/sdk-experimental-memory.js +1 -1
  50. package/dist/sdk-mcp.js +1 -1
  51. package/dist/sdk-repl.js +1 -1
  52. package/dist/sdk-runtime.d.ts +14 -3
  53. package/dist/sdk-runtime.js +1 -1
  54. package/dist/sdk-sandbox.js +1 -1
  55. package/dist/sdk-session.js +1 -1
  56. package/dist/sdk-skills.js +1 -1
  57. package/dist/semantic-worker.js +2 -2
  58. package/docs/SDK_MIGRATION.md +1 -1
  59. package/docs/SPACE_SDK_SEAMS.md +1 -1
  60. package/package.json +2 -2
  61. package/public_docs/README.md +2 -2
  62. package/public_docs/sdk/embedder-guide.md +24 -3
  63. package/dist/chunks/argument-completer-MHCQY5C7.js +0 -2
  64. package/dist/chunks/chunk-YXRXHHFQ.js +0 -497
  65. package/dist/chunks/host-LIWMO7QQ.js +0 -2
  66. package/dist/chunks/readline-helpers-WQAT4CAF.js +0 -2
package/CHANGELOG.md CHANGED
@@ -8,6 +8,35 @@ All notable changes to this project will be documented in this file.
8
8
 
9
9
  ---
10
10
 
11
+ ## [0.7.97-alpha.7] - 2026-10-16
12
+
13
+ Seventh alpha of the v0.7.97 line: shared-Session Host ownership resolves
14
+ across daemon profiles — launchers wait for a starting owner's verified
15
+ descriptor within the original startup deadline, reuse compatible Hosts
16
+ without restarting work, and permit only a guarded same-build orphan-exit
17
+ policy refresh — daemon startup and connection timeouts surface as
18
+ structured, retryable failures, idle interactive Hosts retire after a
19
+ bounded 30-second lifetime while explicit daemon/A2A service owners are
20
+ retained, and Windows SDK attachment reads targeted exact identities within
21
+ the original startup controls (Space #222). Every v0.7.96 stable and
22
+ v0.7.97-alpha.1 through alpha.6 contract is retained. npm publication
23
+ remains a manual maintainer action.
24
+
25
+ ### Fixed
26
+
27
+ - Space Issue 222 CI regression: use one conservative process-liveness check for shared storage discovery, daemon health and verified exit, recognizing unreaped Linux zombies while retaining PID generation checks. Release temporary attachments and rediscover current ownership on bounded startup-only retries within the original deadline and cancellation signal; never replay accepted input or tool work. Gate the original crash cases and deterministic zombie/owner-handoff regressions on Linux Node 20/22 before release.
28
+ - Bound Windows startup cleanup of unverifiable historical child records: the automatic historical sweep keeps incomplete Run trees `unknown` instead of launching a PowerShell termination helper per unverified record — a helper storm that invalidated the shared process snapshot and made startup cost grow with history (24-record fixture: 11,069ms and 48 helpers before, 10ms and none after). Exact-handle Run recovery and verified live-descendant cleanup are preserved.
29
+ - Bound Windows SDK attachment work: fresh PID identity checks read targeted exact FILETIME identities instead of repeatedly scanning the full process table, initial Job ownership evidence is collected together, and the original startup deadline passes through readiness and attachment — expired startup stays an expired failure instead of misclassifying the launcher's own new Host as a competitor (nine isolated same-CPU callers reproduced the timeout and now pass without budget increases). Readiness keeps verified-owner status fresh after authenticated OS inspection, checks deadline/cancellation after final owner/build validation, and aborts pending socket/supervisor readiness through existing cleanup paths; discovery that has crossed its boundary no longer opens attachment leases, and the idle inspection cancels when clients attach.
30
+ - Recognize a starting daemon as an existing owner: a concurrent CLI start while initial A2A reconciliation holds the fence before `daemon.json` exists now reports `already_running` against the actual PID/runtimeId instead of claiming a second `started: true` Host.
31
+ - Retire idle interactive Hosts after the accepted 30-second CLI idle lifetime while retaining explicit services: daemon `start` and A2A-serving owners stay in place, explicit/service retention is authenticated separately from default SDK persistence, conflicting orphan-exit requirements are rejected before shutdown, persistent intent survives rebuild refresh, and configured services are re-evaluated in the replacement Host. Idle exit is fenced on pending memory/managed-task maintenance and unknown legacy startup intent; tracked background work blocks automatic idle exit (including the final draining check) without breaking cancellable explicit shutdown, review or compaction contracts; startup admission uses authenticated read-only checks off idle preflight scans without scanning Session history before any real client.
32
+ - Drain a Run queued after its predecessor finishes: admission can retain its queued decision across asynchronous journal binding while the active predecessor completes and drains an empty queue; the existing guarded drain now wakes after queue publication so the queued Run starts exactly once instead of stranding.
33
+ - Keep the preceding turn visible when submitting a new query in a restored Session with legacy display checkpoints. The Host retains its bounded 150-item tail instead of advancing to the next query and collapsing the entire view to the new input; canonical history, full-item reads and input/tool identities are preserved.
34
+ - Keep saved history readable when its final tool call has no result yet: reaching the end of a valid cached revision no longer reports a history-change conflict. Preserve canonical tool timestamps across observed and paged history, and show the session banner only at the beginning of saved history while browsing ordinary chat, avoiding banner flashes at intermediate page boundaries.
35
+ - Space Issue 222: resolve the daemon that owns the canonical Session directory across profiles before startup, and recheck ownership if a peer wins during bootstrap. Wait for a starting owner's descriptor within the original startup deadline and cancellation signal. Reuse compatible Hosts without restarting work. Permit guarded same-build orphan-exit policy refresh, retaining active-work preflight, exact owner identity and process-exit verification. Publish structured owner/profile and upgrade blocker diagnostics; mark transient blockers retryable.
36
+ - Add bundled real-process shared-Host recovery to the continuous `test:bundle` gate.
37
+
38
+ ---
39
+
11
40
  ## [0.7.97-alpha.6] - 2026-10-15
12
41
 
13
42
  Sixth alpha of the v0.7.97 line: shared-Host startup runs historical child
package/README.md CHANGED
@@ -494,6 +494,11 @@ kodax -p "Review this repository"
494
494
  kodax daemon stop --profile default
495
495
  ```
496
496
 
497
+ An ordinary CLI-started Host exits after its last client disconnects and governed
498
+ work has remained idle for 30 seconds. Reconnecting cancels that idle exit.
499
+ `kodax daemon start` retains the current Host (including an existing temporary
500
+ Host); a Host serving configured A2A also stays available without CLI clients.
501
+
497
502
  Tests that start an isolated Host must close that exact Host after its work has
498
503
  settled, before removing its temporary home. Never stop arbitrary Node processes.
499
504
  With no explicit home, CLI and SDK use the resolved `KODAX_HOME`; explicit
@@ -789,6 +794,21 @@ starts, upgrades, or waits. See
789
794
  Every v0.7.96 stable and v0.7.97-alpha.1/alpha.2/alpha.3 contract is
790
795
  retained.
791
796
 
797
+ **v0.7.97-alpha.7 release:** Resolves shared-Session Host ownership across
798
+ daemon profiles (Space #222) — launchers wait for a starting owner's verified
799
+ descriptor within the original startup deadline, reuse compatible Hosts
800
+ without restarting work, and permit only a guarded same-build orphan-exit
801
+ policy refresh. Structured owner/profile and upgrade-blocker diagnostics
802
+ publish, and daemon startup and connection timeouts surface as retryable
803
+ `daemon_startup_failed` and `ETIMEDOUT` failures. Idle interactive Hosts
804
+ retire after a bounded 30-second lifetime while explicit daemon/A2A service
805
+ owners are retained, concurrent CLI starts recognize a starting daemon as
806
+ the existing owner, and Windows SDK attachment reads targeted exact process
807
+ identities within the original startup controls. See the
808
+ [v0.7.97-alpha.7 release notes](docs/release.md#v0797-alpha7-release-preparation).
809
+ Every v0.7.96 stable and v0.7.97-alpha.1 through alpha.6 contract is
810
+ retained.
811
+
792
812
  **v0.7.97-alpha.6 release:** Streamlines shared-Host startup — historical
793
813
  child recovery runs once under the owner fences and preflight projects
794
814
  canonical Actor metadata without loading transcripts — and orders `kodax -r`,
@@ -2074,7 +2094,7 @@ This development tree exposes 13 SDK subpaths plus the root. Shared product
2074
2094
  applications use `@kodax-ai/kodax/client`; independent libraries and trusted Host
2075
2095
  APIs remain available through the other subpaths. See the [Client contract](docs/CLIENT_CONTRACT.md)
2076
2096
  and [SDK migration guide](docs/SDK_MIGRATION.md). This documentation was checked
2077
- against package version `0.7.97-alpha.6`; npm publication is separate from
2097
+ against package version `0.7.97-alpha.7`; npm publication is separate from
2078
2098
  the current development-tree contract.
2079
2099
 
2080
2100
  ```bash
package/README_CN.md CHANGED
@@ -314,6 +314,16 @@ SDK 系统代码契约更新,但没有放宽 shell/sandbox 的 fail-closed 边
314
314
  [v0.7.97-alpha.4 发布清单](docs/release.md#v0797-alpha4-release-preparation)。
315
315
  所有 v0.7.96 稳定与 v0.7.97-alpha.1/alpha.2/alpha.3 契约全部保留。
316
316
 
317
+ **v0.7.97-alpha.7 发布**:跨 daemon profile 解析共享 Session 存储的 Host
318
+ 归属(Space #222)——启动器在原启动期限内等待启动中 owner 的已验证描述符,
319
+ 兼容 Host 直接复用而不重启工作,仅允许受控的同构建 orphan-exit 策略刷新。
320
+ 结构化 owner/profile 与升级阻塞诊断对外发布,daemon 启动与连接超时以可重试的
321
+ `daemon_startup_failed` 与 `ETIMEDOUT` 呈现。空闲的交互式 Host 在 30 秒生命周期后
322
+ 退隐而显式 daemon/A2A 服务 owner 保留;并发 CLI 启动识别启动中的 daemon 为既有
323
+ owner;Windows SDK attach 在原启动控制内读取精确进程身份。
324
+ 详见 [v0.7.97-alpha.7 发布清单](docs/release.md#v0797-alpha7-release-preparation)。
325
+ 所有 v0.7.96 稳定与 v0.7.97-alpha.1 至 alpha.6 契约全部保留。
326
+
317
327
  **v0.7.97-alpha.6 发布**:精简共享 Host 启动——历史子进程恢复在 owner fence
318
328
  下只运行一次,预检投影规范 Actor 元数据而不加载 transcript;`kodax -r`、Host
319
329
  与 SDK 的 Session 列表按真实最近消息活动排序并暴露可选 `lastMessageAt`。
@@ -1125,6 +1135,8 @@ daemon 可承载多个 Session;不同 Session 可以并发,同一 Session
1125
1135
 
1126
1136
  显式独立库嵌入仍可使用 `/runtime` 的 `createKodaXRuntime({mode:'embedded'})`,其 owner 和退出责任属于调用者。这不是 CLI 的可选运行模式,也不是产品客户端的连接失败回退。当前包版本与发布状态见[SDK 迁移指南](docs/SDK_MIGRATION.md)。
1127
1137
 
1138
+ 普通 CLI 自动拉起的 Host 在最后一个客户端断开、后台工作持续空闲 30 秒后退出;重新连接会取消空闲退出。显式 `kodax daemon start` 会保留当前 Host,即使它原先是临时 Host;承载已配置 A2A 服务的 Host 也会在没有 CLI 客户端时继续常驻。
1139
+
1128
1140
  ### 7. 打包成单文件二进制(无需 Node)
1129
1141
 
1130
1142
  KodaX 可以用 `bun --compile` 打包成单可执行文件 + 一个 `builtin/` sidecar 目录,目标机器**不需要安装 Node.js 或任何运行时**。
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Aa as e,Ba as f,Ra as g,Ta as h,mb as i,nb as j,wb as k,za as d}from"./chunk-A3YY6JUN.js";import{a as c}from"./chunk-SQONUELA.js";import"./chunk-V26LAWJY.js";import"./chunk-WILX5FJH.js";import"./chunk-R7YXI7AB.js";import"./chunk-WJL25O6B.js";import"./chunk-UGNSAKIT.js";import{Tb as a,Ub as b}from"./chunk-UHC66D7T.js";import"./chunk-YVBBU6K5.js";import"./chunk-2AM3FRQ7.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,k as runKodaX,j as saveRequiredSessionSnapshot,i as saveSessionSnapshot,a as validateAndFixToolHistory};
2
+ import{Aa as e,Ba as f,Ra as g,Ta as h,mb as i,nb as j,wb as k,za as d}from"./chunk-LEON6EFI.js";import{a as c}from"./chunk-VHUCG5YI.js";import"./chunk-V26LAWJY.js";import"./chunk-J5XBQRJU.js";import"./chunk-YHIHYPGQ.js";import"./chunk-JNB2FL6P.js";import"./chunk-FX4R5PB3.js";import{Ub as a,Vb as b}from"./chunk-XMWTEVFZ.js";import"./chunk-YVBBU6K5.js";import"./chunk-2AM3FRQ7.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,k as runKodaX,j as saveRequiredSessionSnapshot,i as saveSessionSnapshot,a as validateAndFixToolHistory};
@@ -0,0 +1,2 @@
1
+ // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
+ import{$a as a,ab as b}from"./chunk-X6BSM54P.js";import"./chunk-ZQYWDI4O.js";import"./chunk-5DF2ZZDA.js";import"./chunk-HD5BDOPC.js";import"./chunk-TXCU25XM.js";import"./chunk-LEON6EFI.js";import"./chunk-VHUCG5YI.js";import"./chunk-2IRDPHVI.js";import"./chunk-V26LAWJY.js";import"./chunk-DTJNXVL6.js";import"./chunk-J5XBQRJU.js";import"./chunk-YHIHYPGQ.js";import"./chunk-JNB2FL6P.js";import"./chunk-FX4R5PB3.js";import"./chunk-XMWTEVFZ.js";import"./chunk-YVBBU6K5.js";import"./chunk-2AM3FRQ7.js";import"./chunk-ONUPGMER.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Bb as r,Rb as o}from"./chunk-RLINWRJJ.js";import{a as n}from"./chunk-WNSCGMP4.js";import{a as e}from"./chunk-ONUPGMER.js";function u(t){return o(n(t))}e(u,"runInteractiveMode");function a(t){return r(n(t))}e(a,"runInkInteractiveMode");export{u as a,a as b};
2
+ import{Bb as r,Rb as o}from"./chunk-PRMGOFYX.js";import{a as n}from"./chunk-PGT2VSOD.js";import{a as e}from"./chunk-ONUPGMER.js";function u(t){return o(n(t))}e(u,"runInteractiveMode");function a(t){return r(n(t))}e(a,"runInkInteractiveMode");export{u as a,a as b};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{D,J as F}from"./chunk-DTG3ZF5R.js";import{a as q,b as j,c as N,d as P}from"./chunk-WILX5FJH.js";import{ra as C}from"./chunk-R7YXI7AB.js";import{Fg as $,Gg as k,Hg as y,Kg as _,Lg as b,Mg as x,Sd as W,Td as M,Yd as I}from"./chunk-UHC66D7T.js";import{D as v,E as T,Gb as O,mb as E}from"./chunk-2AM3FRQ7.js";import{a as o}from"./chunk-ONUPGMER.js";import{join as Le}from"node:path";var ae=["You generate KodaX Dynamic Workflow scripts.","Return JSON only. Do not wrap the answer in prose.","For simple tasks that do not benefit from multiple agents, return:",'{"action":"decline","reason":"..."}',"For complex tasks, return:",'{"action":"generate","manifest":{...},"source":"async function run(wf, args) { ... }","approvalSummary":"..."}',"Generated source may only coordinate agents through wf and args.","Generated source must return displayable final text for the user.","Never use import, require, process, fs, child_process, network APIs, shell commands, or direct file access."].join(`
2
+ import{D,J as F}from"./chunk-DTJNXVL6.js";import{a as q,b as j,c as N,d as P}from"./chunk-J5XBQRJU.js";import{ra as C}from"./chunk-YHIHYPGQ.js";import{Gg as $,Hg as k,Ig as y,Lg as _,Mg as b,Ng as x,Td as W,Ud as M,Zd as I}from"./chunk-XMWTEVFZ.js";import{D as v,E as T,Gb as O,mb as E}from"./chunk-2AM3FRQ7.js";import{a as o}from"./chunk-ONUPGMER.js";import{join as Le}from"node:path";var ae=["You generate KodaX Dynamic Workflow scripts.","Return JSON only. Do not wrap the answer in prose.","For simple tasks that do not benefit from multiple agents, return:",'{"action":"decline","reason":"..."}',"For complex tasks, return:",'{"action":"generate","manifest":{...},"source":"async function run(wf, args) { ... }","approvalSummary":"..."}',"Generated source may only coordinate agents through wf and args.","Generated source must return displayable final text for the user.","Never use import, require, process, fs, child_process, network APIs, shell commands, or direct file access."].join(`
3
3
  `),G=12e4,le="KODAX_WORKFLOW_GENERATION_TIMEOUT_SEC",ce="KODAX_WORKFLOW_GENERATION_TIMEOUT_MS",ue=64,fe=2,de=2e3,pe=[{name:"default"},{name:"variant-results",finalText:o((e,n)=>`Variant smoke child report from ${e} (${n}).`,"finalText"),synthesizeText:"Variant smoke synthesis report."},{name:"unverified-success",status:o(()=>"completed_unverified","status"),finalText:o(e=>`Smoke result for ${e}: completed with verification warnings.`,"finalText"),synthesizeText:"Smoke synthesis: completed with verification warnings."},{name:"empty-args-rerun",args:o(()=>({}),"args")}],me=[{id:"import",pattern:/\bimport\s*(?:\(|['"*{]|\w+\s+from\b)/},{id:"require",pattern:/\brequire\s*\(/},{id:"process",pattern:/\bprocess\s*(?:\.|\[)/},{id:"fs",pattern:/\b(?:node:)?fs\b/},{id:"child_process",pattern:/\bchild_process\b/},{id:"shell",pattern:/\b(?:exec|spawn|execFile)\s*\(/},{id:"fetch",pattern:/\bfetch\s*\(/},{id:"Deno",pattern:/\bDeno\s*(?:\.|\[)/},{id:"Bun",pattern:/\bBun\s*(?:\.|\[)/},{id:"globalThis-index",pattern:/\bglobalThis\s*\[/}];function we(e=process.env,n){let t=v(n?.workflow?.generationTimeoutSec,"timeouts.workflow.generationTimeoutSec");if(t!==void 0)return t;let r=T(e[le]);if(r!==void 0)return r;let s=e[ce];if(s===void 0||s.trim().length===0)return G;let i=Number(s);return!Number.isFinite(i)||i<=0?G:Math.floor(i)}o(we,"resolveWorkflowGenerationTimeoutMs");function he(e,n){if(typeof e!="object"||e===null)throw new Error(`${n} must be an object`);return e}o(he,"readRecord");function K(e,n){let t=e[n];if(typeof t!="string"||t.trim().length===0)throw new Error(`workflow generation ${n} must be a non-empty string`);return t}o(K,"readNonEmptyString");function ge(e){let n=e.trim(),t=/^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(n);if(t?.[1])return t[1].trim();let r=n.indexOf("{"),s=n.lastIndexOf("}");if(r>=0&&s>r)return n.slice(r,s+1);throw new Error("workflow generation output did not contain a JSON object")}o(ge,"extractJsonText");function ke(e){let n=ge(e);return he(JSON.parse(n),"workflow generation output")}o(ke,"parseGenerationJson");function ye(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(typeof e!="object"||e===null)return;let n=e;for(let t of["name","id","title","phase"]){let r=n[t];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}o(ye,"normalizePhaseEntry");function be(e){return e.split(/(?:->|\u2192|,|\n)/).map(n=>n.trim()).filter(n=>n.length>0)}o(be,"splitPhaseString");function xe(e){if(typeof e!="object"||e===null)return e;let n=e,t=n.phases,r;if(Array.isArray(t)){let s=t.map(ye);s.every(i=>i!==void 0)&&(r=s)}else if(typeof t=="string"){let s=be(t);s.length>0&&(r=s)}return r?{...n,phases:r}:e}o(xe,"normalizeGeneratedManifestCandidate");function ve(e){return e.match(/\bwf\.(?:runAgent|spawnAgent|synthesize)\s*\(/g)?.length??0}o(ve,"estimateDirectAgentCalls");function Se(e,n){let t=e.maxConcurrency*Math.max(1,e.phases.length)+2,r=ve(n)+2,s=Math.min(ue,Math.max(e.maxAgents,t,r));return s>e.maxAgents?{...e,maxAgents:s}:e}o(Se,"reserveGeneratedWorkflowAgentCapacity");function w(e){let n="",t=0,r=["code"],s=[0];for(;t<e.length;){let i=e[t],a=e[t+1];if(r[r.length-1]==="template"){if(i==="\\"){n+=" ",t+=2;continue}if(i==="`"){n+=" ",t+=1,r.pop(),s.pop();continue}if(i==="$"&&a==="{"){n+=" ",t+=2,r.push("code"),s.push(0);continue}n+=i===`
4
4
  `?`
5
5
  `:" ",t+=1;continue}if(i==="/"&&a==="/"){for(n+=" ",t+=2;t<e.length&&e[t]!==`
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{ia as Me,ka as _e}from"./chunk-A3YY6JUN.js";import{Ka as ke,Sa as Se,Wa as Ce}from"./chunk-UHC66D7T.js";import{H as me,Ma as ge,Na as ve,Oa as ye,Pa as we,Qa as xe,Ra as Y,T as z,W as B,X as he,Y as J,Ya as Ee,Za as R,bb as Q,mb as be,rb as Pe}from"./chunk-2AM3FRQ7.js";import{a as r}from"./chunk-ONUPGMER.js";import m from"fs";import h from"path";import{exec as wt,spawnSync as xt}from"child_process";import{promisify as Et}from"util";import{fileURLToPath as bt}from"url";var Z="en";function Ye(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}r(Ye,"detectSystemLocale");function Oe(e){if(!e||e==="auto"){Z=Ye();return}Z=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}r(Oe,"setLocale");var Ae={en:{"dialog.confirm":"[Confirm]","dialog.select":"[Select]","dialog.input":"[Input]","confirm.instruction.basic":"Press (y) yes, (n) no","confirm.instruction.always":"Press (y) yes, (a) always yes for this tool, (n) no","confirm.instruction.runtime_session":"Press (y) allow once, (s) allow this Runtime scope for the session, (n) no","confirm.instruction.runtime_persistent":"Press (y) allow once, (s) allow this Runtime scope for the session, (a) always allow this Runtime scope, (n) no","confirm.instruction.protected":"Press (y) to confirm, (n) to cancel (protected path)","confirm.result.approved":"Approved","confirm.result.approved_always":"Approved (always)","confirm.result.approved_session":"Approved (this session)","confirm.result.denied":"Denied","tool.bash.title":"Execute bash command?","tool.shell.title":"Execute shell command?","tool.write.title":"Write to file?","tool.edit.title":"Edit file?","tool.generic.title":"Execute {tool}?","field.reason":"Reason","field.intent":"Intent","field.target":"Target","field.scope":"Scope","field.risk":"Risk","field.summary":"Summary","intent.read":"Read project files","intent.delete":"Delete files","intent.deps":"Modify dependencies or environment","intent.modify":"Modify files","intent.execute":"Execute command","intent.write_file":"Write file","intent.edit_file":"Edit file","intent.use_tool":"Use {tool}","risk.destructive":"Destructive change","risk.deps":"May change dependencies or local tools","risk.modify":"May modify files","risk.unknown":"Command effects depend on its arguments","risk.network":"May access network","scope.outside":"Outside project","scope.protected":"Protected path","waiting.confirm":"Waiting: approval required","waiting.select":"Waiting: choose an option","waiting.input":"Waiting: answer the prompt","placeholder.confirm":"Respond to the approval prompt above...","placeholder.select":"Choose an option above...","placeholder.input":"Answer the prompt above...","placeholder.busy":"Agent is busy...","placeholder.queue":"Queue a follow-up for the next round...","placeholder.idle":"Type a message...","select.choice":"Choice:","select.type_number":"(type a number)","select.more":"{count} more choices...","select.more_above":"\u2191 {count} more above","select.more_below":"\u2193 {count} more below","select.confirm_hint":"Press Enter to confirm, Esc to cancel","select.navigate_hint":"Use \u2191\u2193 to navigate, Enter to confirm, Esc to cancel","select.multiselect_hint":"Use \u2191\u2193 to navigate, Space to toggle, Enter to confirm, Esc to cancel","select.multiselect_empty":"Select at least one option with Space before confirming.","select.multiselect_min":"Select at least {min} option(s) with Space before confirming.","select.multiselect_max":"Select at most {max} option(s) with Space before confirming.","select.back_prev":"\u2190 Back to previous question","input.default":"Default:","input.value":"Value:","input.type_response":"(type your response)","managed.completed":"Task completed","managed.completed.blocked":"Task blocked","managed.completed.continuation":"Task needs continuation","todo.progress":"{completed}/{total} completed","todo.transcript.progress":"Plan {completed}/{total} completed","todo.summary.done":"{count} done","todo.summary.more":"+{count} more",cancelled:"[Cancelled] Operation cancelled by user",cancellationRequested:"[Cancelling] Stop requested for the current reply",cancellationAccepted:"Stop request accepted; waiting for execution to settle.",cancellationConfirmed:"Stop confirmed:",cancellationRejected:"Stop request failed:"},zh:{"dialog.confirm":"[\u786E\u8BA4]","dialog.select":"[\u9009\u62E9]","dialog.input":"[\u8F93\u5165]","confirm.instruction.basic":"\u6309 (y) \u786E\u8BA4, (n) \u62D2\u7EDD","confirm.instruction.always":"\u6309 (y) \u786E\u8BA4, (a) \u59CB\u7EC8\u5141\u8BB8\u6B64\u5DE5\u5177, (n) \u62D2\u7EDD","confirm.instruction.runtime_session":"\u6309 (y) \u4EC5\u5141\u8BB8\u4E00\u6B21, (s) \u672C\u4F1A\u8BDD\u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (n) \u62D2\u7EDD","confirm.instruction.runtime_persistent":"\u6309 (y) \u4EC5\u5141\u8BB8\u4E00\u6B21, (s) \u672C\u4F1A\u8BDD\u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (a) \u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (n) \u62D2\u7EDD","confirm.instruction.protected":"\u6309 (y) \u786E\u8BA4, (n) \u53D6\u6D88 (\u53D7\u4FDD\u62A4\u8DEF\u5F84)","confirm.result.approved":"\u5DF2\u6279\u51C6","confirm.result.approved_always":"\u5DF2\u6279\u51C6 (\u59CB\u7EC8\u5141\u8BB8)","confirm.result.approved_session":"\u5DF2\u6279\u51C6 (\u672C\u4F1A\u8BDD)","confirm.result.denied":"\u5DF2\u62D2\u7EDD","tool.bash.title":"\u6267\u884C bash \u547D\u4EE4\uFF1F","tool.shell.title":"\u6267\u884C shell \u547D\u4EE4\uFF1F","tool.write.title":"\u5199\u5165\u6587\u4EF6\uFF1F","tool.edit.title":"\u7F16\u8F91\u6587\u4EF6\uFF1F","tool.generic.title":"\u6267\u884C {tool}\uFF1F","field.reason":"\u539F\u56E0","field.intent":"\u610F\u56FE","field.target":"\u76EE\u6807","field.scope":"\u8303\u56F4","field.risk":"\u98CE\u9669","field.summary":"\u6458\u8981","intent.read":"\u8BFB\u53D6\u9879\u76EE\u6587\u4EF6","intent.delete":"\u5220\u9664\u6587\u4EF6","intent.deps":"\u4FEE\u6539\u4F9D\u8D56\u6216\u73AF\u5883","intent.modify":"\u4FEE\u6539\u6587\u4EF6","intent.execute":"\u6267\u884C\u547D\u4EE4","intent.write_file":"\u5199\u5165\u6587\u4EF6","intent.edit_file":"\u7F16\u8F91\u6587\u4EF6","intent.use_tool":"\u4F7F\u7528 {tool}","risk.destructive":"\u7834\u574F\u6027\u53D8\u66F4","risk.deps":"\u53EF\u80FD\u4FEE\u6539\u4F9D\u8D56\u6216\u672C\u5730\u5DE5\u5177","risk.modify":"\u53EF\u80FD\u4FEE\u6539\u6587\u4EF6","risk.unknown":"\u547D\u4EE4\u6548\u679C\u53D6\u51B3\u4E8E\u53C2\u6570","risk.network":"\u53EF\u80FD\u8BBF\u95EE\u7F51\u7EDC","scope.outside":"\u9879\u76EE\u5916\u90E8","scope.protected":"\u53D7\u4FDD\u62A4\u8DEF\u5F84","waiting.confirm":"\u7B49\u5F85\u4E2D\uFF1A\u9700\u8981\u5BA1\u6279","waiting.select":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u9009\u62E9","waiting.input":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u56DE\u7B54","placeholder.confirm":"\u8BF7\u56DE\u5E94\u4E0A\u65B9\u7684\u5BA1\u6279\u63D0\u793A...","placeholder.select":"\u8BF7\u5728\u4E0A\u65B9\u9009\u62E9\u4E00\u4E2A\u9009\u9879...","placeholder.input":"\u8BF7\u56DE\u7B54\u4E0A\u65B9\u7684\u63D0\u793A...","placeholder.busy":"\u667A\u80FD\u4F53\u6B63\u5728\u5DE5\u4F5C\u4E2D...","placeholder.queue":"\u6392\u961F\u7B49\u5F85\u4E0B\u4E00\u8F6E\u8DDF\u8FDB...","placeholder.idle":"\u8F93\u5165\u6D88\u606F...","select.choice":"\u9009\u9879\uFF1A","select.type_number":"(\u8F93\u5165\u7F16\u53F7)","select.more":"\u8FD8\u6709 {count} \u4E2A\u9009\u9879...","select.more_above":"\u2191 \u4E0A\u65B9\u8FD8\u6709 {count} \u4E2A","select.more_below":"\u2193 \u4E0B\u65B9\u8FD8\u6709 {count} \u4E2A","select.confirm_hint":"\u6309 Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.navigate_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0C\u7A7A\u683C \u5207\u6362\u9009\u4E2D\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_empty":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u9009\u9879\u3002","select.multiselect_min":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u81F3\u5C11\u9009\u62E9 {min} \u4E2A\u9009\u9879\u3002","select.multiselect_max":"\u6700\u591A\u53EA\u80FD\u9009\u62E9 {max} \u4E2A\u9009\u9879\u3002","select.back_prev":"\u2190 \u8FD4\u56DE\u4E0A\u4E00\u9898","input.default":"\u9ED8\u8BA4\u503C\uFF1A","input.value":"\u503C\uFF1A","input.type_response":"(\u8F93\u5165\u4F60\u7684\u56DE\u7B54)","managed.completed":"\u4EFB\u52A1\u5B8C\u6210","managed.completed.blocked":"\u4EFB\u52A1\u53D7\u963B","managed.completed.continuation":"\u4EFB\u52A1\u9700\u8981\u7EE7\u7EED","todo.progress":"{completed}/{total} \u5DF2\u5B8C\u6210","todo.transcript.progress":"\u8BA1\u5212 {completed}/{total} \u5DF2\u5B8C\u6210","todo.summary.done":"{count} \u9879\u5DF2\u5B8C\u6210","todo.summary.more":"\u53E6\u6709 {count} \u9879",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88",cancellationRequested:"[\u6B63\u5728\u53D6\u6D88] \u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u56DE\u590D",cancellationAccepted:"\u505C\u6B62\u8BF7\u6C42\u5DF2\u63A5\u53D7\uFF0C\u6B63\u5728\u7B49\u5F85\u6267\u884C\u6536\u5C3E\u3002",cancellationConfirmed:"\u505C\u6B62\u5DF2\u786E\u8BA4\uFF1A",cancellationRejected:"\u505C\u6B62\u8BF7\u6C42\u5931\u8D25\uFF1A"}};function Bt(e,t){let o=Ae[Z][e]??Ae.en[e]??e;if(t)for(let[i,s]of Object.entries(t))o=o.replace(`{${i}}`,String(s));return o}r(Bt,"t");var Re={core:`// Split configs: ~/.kodax/integrations/mcp.json, extensions.json, and a2a.json.
2
+ import{ia as Me,ka as _e}from"./chunk-LEON6EFI.js";import{Ka as ke,Sa as Se,Wa as Ce}from"./chunk-XMWTEVFZ.js";import{H as me,Ma as ge,Na as ve,Oa as ye,Pa as we,Qa as xe,Ra as Y,T as z,W as B,X as he,Y as J,Ya as Ee,Za as R,bb as Q,mb as be,rb as Pe}from"./chunk-2AM3FRQ7.js";import{a as r}from"./chunk-ONUPGMER.js";import m from"fs";import h from"path";import{exec as wt,spawnSync as xt}from"child_process";import{promisify as Et}from"util";import{fileURLToPath as bt}from"url";var Z="en";function Ye(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}r(Ye,"detectSystemLocale");function Oe(e){if(!e||e==="auto"){Z=Ye();return}Z=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}r(Oe,"setLocale");var Ae={en:{"dialog.confirm":"[Confirm]","dialog.select":"[Select]","dialog.input":"[Input]","confirm.instruction.basic":"Press (y) yes, (n) no","confirm.instruction.always":"Press (y) yes, (a) always yes for this tool, (n) no","confirm.instruction.runtime_session":"Press (y) allow once, (s) allow this Runtime scope for the session, (n) no","confirm.instruction.runtime_persistent":"Press (y) allow once, (s) allow this Runtime scope for the session, (a) always allow this Runtime scope, (n) no","confirm.instruction.protected":"Press (y) to confirm, (n) to cancel (protected path)","confirm.result.approved":"Approved","confirm.result.approved_always":"Approved (always)","confirm.result.approved_session":"Approved (this session)","confirm.result.denied":"Denied","tool.bash.title":"Execute bash command?","tool.shell.title":"Execute shell command?","tool.write.title":"Write to file?","tool.edit.title":"Edit file?","tool.generic.title":"Execute {tool}?","field.reason":"Reason","field.intent":"Intent","field.target":"Target","field.scope":"Scope","field.risk":"Risk","field.summary":"Summary","intent.read":"Read project files","intent.delete":"Delete files","intent.deps":"Modify dependencies or environment","intent.modify":"Modify files","intent.execute":"Execute command","intent.write_file":"Write file","intent.edit_file":"Edit file","intent.use_tool":"Use {tool}","risk.destructive":"Destructive change","risk.deps":"May change dependencies or local tools","risk.modify":"May modify files","risk.unknown":"Command effects depend on its arguments","risk.network":"May access network","scope.outside":"Outside project","scope.protected":"Protected path","waiting.confirm":"Waiting: approval required","waiting.select":"Waiting: choose an option","waiting.input":"Waiting: answer the prompt","placeholder.confirm":"Respond to the approval prompt above...","placeholder.select":"Choose an option above...","placeholder.input":"Answer the prompt above...","placeholder.busy":"Agent is busy...","placeholder.queue":"Queue a follow-up for the next round...","placeholder.idle":"Type a message...","select.choice":"Choice:","select.type_number":"(type a number)","select.more":"{count} more choices...","select.more_above":"\u2191 {count} more above","select.more_below":"\u2193 {count} more below","select.confirm_hint":"Press Enter to confirm, Esc to cancel","select.navigate_hint":"Use \u2191\u2193 to navigate, Enter to confirm, Esc to cancel","select.multiselect_hint":"Use \u2191\u2193 to navigate, Space to toggle, Enter to confirm, Esc to cancel","select.multiselect_empty":"Select at least one option with Space before confirming.","select.multiselect_min":"Select at least {min} option(s) with Space before confirming.","select.multiselect_max":"Select at most {max} option(s) with Space before confirming.","select.back_prev":"\u2190 Back to previous question","input.default":"Default:","input.value":"Value:","input.type_response":"(type your response)","managed.completed":"Task completed","managed.completed.blocked":"Task blocked","managed.completed.continuation":"Task needs continuation","todo.progress":"{completed}/{total} completed","todo.transcript.progress":"Plan {completed}/{total} completed","todo.summary.done":"{count} done","todo.summary.more":"+{count} more",cancelled:"[Cancelled] Operation cancelled by user",cancellationRequested:"[Cancelling] Stop requested for the current reply",cancellationAccepted:"Stop request accepted; waiting for execution to settle.",cancellationConfirmed:"Stop confirmed:",cancellationRejected:"Stop request failed:"},zh:{"dialog.confirm":"[\u786E\u8BA4]","dialog.select":"[\u9009\u62E9]","dialog.input":"[\u8F93\u5165]","confirm.instruction.basic":"\u6309 (y) \u786E\u8BA4, (n) \u62D2\u7EDD","confirm.instruction.always":"\u6309 (y) \u786E\u8BA4, (a) \u59CB\u7EC8\u5141\u8BB8\u6B64\u5DE5\u5177, (n) \u62D2\u7EDD","confirm.instruction.runtime_session":"\u6309 (y) \u4EC5\u5141\u8BB8\u4E00\u6B21, (s) \u672C\u4F1A\u8BDD\u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (n) \u62D2\u7EDD","confirm.instruction.runtime_persistent":"\u6309 (y) \u4EC5\u5141\u8BB8\u4E00\u6B21, (s) \u672C\u4F1A\u8BDD\u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (a) \u59CB\u7EC8\u5141\u8BB8\u8FD9\u9879\u7CBE\u786E\u64CD\u4F5C, (n) \u62D2\u7EDD","confirm.instruction.protected":"\u6309 (y) \u786E\u8BA4, (n) \u53D6\u6D88 (\u53D7\u4FDD\u62A4\u8DEF\u5F84)","confirm.result.approved":"\u5DF2\u6279\u51C6","confirm.result.approved_always":"\u5DF2\u6279\u51C6 (\u59CB\u7EC8\u5141\u8BB8)","confirm.result.approved_session":"\u5DF2\u6279\u51C6 (\u672C\u4F1A\u8BDD)","confirm.result.denied":"\u5DF2\u62D2\u7EDD","tool.bash.title":"\u6267\u884C bash \u547D\u4EE4\uFF1F","tool.shell.title":"\u6267\u884C shell \u547D\u4EE4\uFF1F","tool.write.title":"\u5199\u5165\u6587\u4EF6\uFF1F","tool.edit.title":"\u7F16\u8F91\u6587\u4EF6\uFF1F","tool.generic.title":"\u6267\u884C {tool}\uFF1F","field.reason":"\u539F\u56E0","field.intent":"\u610F\u56FE","field.target":"\u76EE\u6807","field.scope":"\u8303\u56F4","field.risk":"\u98CE\u9669","field.summary":"\u6458\u8981","intent.read":"\u8BFB\u53D6\u9879\u76EE\u6587\u4EF6","intent.delete":"\u5220\u9664\u6587\u4EF6","intent.deps":"\u4FEE\u6539\u4F9D\u8D56\u6216\u73AF\u5883","intent.modify":"\u4FEE\u6539\u6587\u4EF6","intent.execute":"\u6267\u884C\u547D\u4EE4","intent.write_file":"\u5199\u5165\u6587\u4EF6","intent.edit_file":"\u7F16\u8F91\u6587\u4EF6","intent.use_tool":"\u4F7F\u7528 {tool}","risk.destructive":"\u7834\u574F\u6027\u53D8\u66F4","risk.deps":"\u53EF\u80FD\u4FEE\u6539\u4F9D\u8D56\u6216\u672C\u5730\u5DE5\u5177","risk.modify":"\u53EF\u80FD\u4FEE\u6539\u6587\u4EF6","risk.unknown":"\u547D\u4EE4\u6548\u679C\u53D6\u51B3\u4E8E\u53C2\u6570","risk.network":"\u53EF\u80FD\u8BBF\u95EE\u7F51\u7EDC","scope.outside":"\u9879\u76EE\u5916\u90E8","scope.protected":"\u53D7\u4FDD\u62A4\u8DEF\u5F84","waiting.confirm":"\u7B49\u5F85\u4E2D\uFF1A\u9700\u8981\u5BA1\u6279","waiting.select":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u9009\u62E9","waiting.input":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u56DE\u7B54","placeholder.confirm":"\u8BF7\u56DE\u5E94\u4E0A\u65B9\u7684\u5BA1\u6279\u63D0\u793A...","placeholder.select":"\u8BF7\u5728\u4E0A\u65B9\u9009\u62E9\u4E00\u4E2A\u9009\u9879...","placeholder.input":"\u8BF7\u56DE\u7B54\u4E0A\u65B9\u7684\u63D0\u793A...","placeholder.busy":"\u667A\u80FD\u4F53\u6B63\u5728\u5DE5\u4F5C\u4E2D...","placeholder.queue":"\u6392\u961F\u7B49\u5F85\u4E0B\u4E00\u8F6E\u8DDF\u8FDB...","placeholder.idle":"\u8F93\u5165\u6D88\u606F...","select.choice":"\u9009\u9879\uFF1A","select.type_number":"(\u8F93\u5165\u7F16\u53F7)","select.more":"\u8FD8\u6709 {count} \u4E2A\u9009\u9879...","select.more_above":"\u2191 \u4E0A\u65B9\u8FD8\u6709 {count} \u4E2A","select.more_below":"\u2193 \u4E0B\u65B9\u8FD8\u6709 {count} \u4E2A","select.confirm_hint":"\u6309 Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.navigate_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0C\u7A7A\u683C \u5207\u6362\u9009\u4E2D\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_empty":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u9009\u9879\u3002","select.multiselect_min":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u81F3\u5C11\u9009\u62E9 {min} \u4E2A\u9009\u9879\u3002","select.multiselect_max":"\u6700\u591A\u53EA\u80FD\u9009\u62E9 {max} \u4E2A\u9009\u9879\u3002","select.back_prev":"\u2190 \u8FD4\u56DE\u4E0A\u4E00\u9898","input.default":"\u9ED8\u8BA4\u503C\uFF1A","input.value":"\u503C\uFF1A","input.type_response":"(\u8F93\u5165\u4F60\u7684\u56DE\u7B54)","managed.completed":"\u4EFB\u52A1\u5B8C\u6210","managed.completed.blocked":"\u4EFB\u52A1\u53D7\u963B","managed.completed.continuation":"\u4EFB\u52A1\u9700\u8981\u7EE7\u7EED","todo.progress":"{completed}/{total} \u5DF2\u5B8C\u6210","todo.transcript.progress":"\u8BA1\u5212 {completed}/{total} \u5DF2\u5B8C\u6210","todo.summary.done":"{count} \u9879\u5DF2\u5B8C\u6210","todo.summary.more":"\u53E6\u6709 {count} \u9879",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88",cancellationRequested:"[\u6B63\u5728\u53D6\u6D88] \u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u56DE\u590D",cancellationAccepted:"\u505C\u6B62\u8BF7\u6C42\u5DF2\u63A5\u53D7\uFF0C\u6B63\u5728\u7B49\u5F85\u6267\u884C\u6536\u5C3E\u3002",cancellationConfirmed:"\u505C\u6B62\u5DF2\u786E\u8BA4\uFF1A",cancellationRejected:"\u505C\u6B62\u8BF7\u6C42\u5931\u8D25\uFF1A"}};function Bt(e,t){let o=Ae[Z][e]??Ae.en[e]??e;if(t)for(let[i,s]of Object.entries(t))o=o.replace(`{${i}}`,String(s));return o}r(Bt,"t");var Re={core:`// Split configs: ~/.kodax/integrations/mcp.json, extensions.json, and a2a.json.
3
3
  // KodaX core configuration template.
4
4
  // Copy only the fields you need to ~/.kodax/config.json (strict JSON).
5
5
  // MCP, A2A, and Extensions live in ~/.kodax/integrations/*.json; use
@@ -257,4 +257,4 @@ import{ia as Me,ka as _e}from"./chunk-A3YY6JUN.js";import{Ka as ke,Sa as Se,Wa a
257
257
  }
258
258
  `};function Ie(e){return Re[e]}r(Ie,"getConfigTemplate");import{closeSync as ne,existsSync as d,fsyncSync as $e,linkSync as it,mkdirSync as re,openSync as ie,readFileSync as je,renameSync as Ke,statSync as st,unlinkSync as K,watch as at,writeFileSync as Fe}from"node:fs";import{createHash as ct}from"node:crypto";import f from"node:path";import{closeSync as Qe,mkdirSync as Ze,openSync as et,rmSync as tt}from"node:fs";import nt from"node:path";var ee=class extends Error{static{r(this,"CoreConfigWriteConflictError")}constructor(t){super(`Core configuration is being changed by another KodaX writer: ${t}`),this.name="CoreConfigWriteConflictError"}};function ot(e){return`${e}.write.lock`}r(ot,"coreConfigWriteLockPath");function rt(e){if(!(!(e instanceof Error)||!("code"in e)))return typeof e.code=="string"?e.code:void 0}r(rt,"errorCode");function x(e,t){Ze(nt.dirname(e),{recursive:!0,mode:448});let n=ot(e),o;try{o=et(n,"wx",384)}catch(i){throw rt(i)==="EEXIST"?new ee(e):new Error(`Failed to acquire the core configuration write lock: ${e}`,{cause:i})}try{return t()}finally{Qe(o),tt(n,{force:!0})}}r(x,"withCoreConfigWriteLock");var k=class extends Error{static{r(this,"IntegrationConfigConflictError")}constructor(t,n,o){super(`Integration configuration revision changed for ${f.basename(t)} (expected ${n??"missing"}, actual ${o??"missing"}).`),this.name="IntegrationConfigConflictError"}},lt={mcp:"mcp.json",a2a:"a2a.json",extensions:"extensions.json"},dt=new Set(["type","command","args","cwd","env","url","headers","connect","startupTimeoutMs","requestTimeoutMs","auth"]);function P(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}r(P,"isRecord");function E(e,t){if(!P(e))throw new Error(`${t} must be an object.`);return e}r(E,"requireRecord");function F(e,t,n){let o=Object.keys(e).find(i=>!t.has(i));if(o!==void 0)throw new Error(`${n} has unknown field "${o}".`)}r(F,"assertNoUnknownKeys");function Xe(e,t){if(e.version!==1)throw new Error(`${t} version must be 1.`)}r(Xe,"requireVersionOne");function Te(e,t){let n=E(e,t);for(let[o,i]of Object.entries(n))if(o.trim().length===0||typeof i!="string")throw new Error(`${t} must contain non-empty string keys and string values.`);return structuredClone(n)}r(Te,"requireStringMap");function oe(e,t){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`${t} must be an array of non-empty strings.`);return e.map(n=>n.trim())}r(oe,"requireStringArray");function te(e,t){if(e!==void 0&&(!Number.isFinite(e)||Number(e)<=0))throw new Error(`${t} must be a positive number.`)}r(te,"validatePositiveNumber");function ut(e,t){if(e.trim().length===0)throw new Error("MCP server names must not be empty.");let n=E(t,`MCP server "${e}"`);F(n,dt,`MCP server "${e}"`);let o=n.type??"stdio";if(!["stdio","sse","streamable-http","http"].includes(String(o)))throw new Error(`MCP server "${e}" has an unsupported transport type.`);if(o==="stdio"){if(typeof n.command!="string"||n.command.trim().length===0)throw new Error(`MCP server "${e}" stdio transport requires command.`)}else if(typeof n.url!="string"||n.url.trim().length===0)throw new Error(`MCP server "${e}" ${String(o)} transport requires url.`);if(n.args!==void 0&&oe(n.args,`MCP server "${e}" args`),n.cwd!==void 0&&typeof n.cwd!="string")throw new Error(`MCP server "${e}" cwd must be a string.`);if(n.env!==void 0&&Te(n.env,`MCP server "${e}" env`),n.headers!==void 0&&Te(n.headers,`MCP server "${e}" headers`),n.connect!==void 0&&!["lazy","prewarm","disabled"].includes(String(n.connect)))throw new Error(`MCP server "${e}" has an unsupported connect mode.`);if(te(n.startupTimeoutMs,`MCP server "${e}" startupTimeoutMs`),te(n.requestTimeoutMs,`MCP server "${e}" requestTimeoutMs`),n.auth!==void 0){let i=E(n.auth,`MCP server "${e}" auth`);if(F(i,new Set(["type","clientId","authorizationUrl","tokenUrl","scopes","redirectPort"]),`MCP server "${e}" auth`),i.type!=="oauth2")throw new Error(`MCP server "${e}" auth type must be oauth2.`);for(let a of["clientId","authorizationUrl","tokenUrl"])if(i[a]!==void 0&&typeof i[a]!="string")throw new Error(`MCP server "${e}" auth.${a} must be a string.`);i.scopes!==void 0&&oe(i.scopes,`MCP server "${e}" auth.scopes`),te(i.redirectPort,`MCP server "${e}" auth.redirectPort`)}return structuredClone(n)}r(ut,"parseMcpServer");function S(e){let t=E(e,"MCP integration config");F(t,new Set(["version","servers"]),"MCP integration config"),Xe(t,"MCP integration config");let n=E(t.servers,"MCP integration config servers"),o={};for(let[i,s]of Object.entries(n))o[i]=ut(i,s);return{version:1,servers:o}}r(S,"parseMcpIntegrationDocument");function C(e){let t=E(e,"Extensions integration config");F(t,new Set(["version","paths"]),"Extensions integration config"),Xe(t,"Extensions integration config");let n=oe(t.paths,"Extensions integration config paths");if(new Set(n).size!==n.length)throw new Error("Extensions integration config paths must not contain duplicates.");return{version:1,paths:n}}r(C,"parseExtensionsIntegrationDocument");function M(e,t){return f.join(f.resolve(t),"integrations",lt[e])}r(M,"resolveIntegrationConfigPath");function A(e){return f.join(f.resolve(e),"config.json")}r(A,"coreConfigPath");function Ue(e){return ct("sha256").update(e).digest("hex")}r(Ue,"hashText");function se(e){let t=je(e,"utf8");try{return{raw:t,value:JSON.parse(t)}}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Invalid JSON: ${o}`)}}r(se,"readJsonFile");function _(e){return{domain:e.domain,source:e.source,path:e.path,revision:Ue(e.raw),document:structuredClone(e.document),loadedAt:new Date().toISOString()}}r(_,"snapshot");function X(e){let t=A(e);return d(t)?E(se(t).value,"Core config"):{}}r(X,"readCoreConfig");function U(e){let t=M("mcp",e);if(d(t)){let s=se(t);return _({domain:"mcp",source:"user",path:t,raw:s.raw,document:S(s.value)})}let n=A(e),o=X(e).mcpServers,i=S({version:1,servers:o===void 0?{}:o});return _({domain:"mcp",source:o===void 0?"default":"legacy-user",path:o===void 0?t:n,raw:JSON.stringify(i),document:i})}r(U,"readMcpIntegration");function q(e){let t=M("extensions",e);if(d(t)){let s=se(t);return _({domain:"extensions",source:"user",path:t,raw:s.raw,document:C(s.value)})}let n=A(e),o=X(e).extensions,i=C({version:1,paths:o===void 0?[]:o});return _({domain:"extensions",source:o===void 0?"default":"legacy-user",path:o===void 0?t:n,raw:JSON.stringify(i),document:i})}r(q,"readExtensionsIntegration");function ft(e){if(!P(e))return[];let t=[],n=/(token|secret|password|api[_-]?key|authorization)/i;for(let[o,i]of Object.entries(e))if(P(i))for(let s of["env","headers"]){let a=i[s];if(P(a))for(let[c,l]of Object.entries(a))n.test(c)&&typeof l=="string"&&!l.startsWith("${env:")&&t.push(`MCP server "${o}" ${s}.${c} may contain a literal secret.`)}return t}r(ft,"likelySecretWarnings");function pt(e){let t=X(e),n=M("mcp",e),o=M("extensions",e),i=t.mcpServers,s=t.extensions,a=P(i)?Object.keys(i).length:0,c=Array.isArray(s)?s.length:0,l=r((g,N,$)=>d(g)?{action:"none",entries:N,destination:g,reason:"destination-exists"}:$?{action:"create",entries:N,destination:g}:{action:"none",entries:0,destination:g,reason:"legacy-absent"},"domainPlan");return{mcp:l(n,a,i!==void 0),extensions:l(o,c,s!==void 0),warnings:ft(i)}}r(pt,"planLegacyIntegrationMigration");function mt(e,t){let n=A(e);re(f.dirname(n),{recursive:!0,mode:448});let o=`${n}.${process.pid}.${Date.now()}.tmp`,i=ie(o,"wx",384);try{Fe(i,`${JSON.stringify(t,null,2)}
259
259
  `,"utf8"),$e(i)}finally{ne(i)}try{Ke(o,n)}catch(s){throw d(o)&&K(o),new Error("Failed to atomically clean legacy integration fields.",{cause:s})}}r(mt,"writeCoreConfigAtomically");function ln(e){return x(A(e.configHome),()=>ht(e))}r(ln,"migrateLegacyIntegrationConfig");function ht(e){let t=pt(e.configHome),n=X(e.configHome),o=t.mcp.action==="create"?S({version:1,servers:P(n.mcpServers)?n.mcpServers:{}}):void 0,i=t.extensions.action==="create"?C({version:1,paths:Array.isArray(n.extensions)?n.extensions:[]}):void 0,s=[];if(o)try{I({domain:"mcp",configHome:e.configHome,expectedRevision:null,document:o,validate:S}),s.push("mcp")}catch(c){if(!(c instanceof k))throw c}if(i)try{I({domain:"extensions",configHome:e.configHome,expectedRevision:null,document:i,validate:C}),s.push("extensions")}catch(c){if(!(c instanceof k))throw c}let a=!1;if(e.cleanupLegacy&&d(A(e.configHome))){let c={...n};d(t.mcp.destination)&&delete c.mcpServers,d(t.extensions.destination)&&delete c.extensions,gt(n,c)||(mt(e.configHome,c),a=!0)}return{...t,applied:s,cleanedLegacy:a}}r(ht,"migrateLegacyIntegrationConfigUnlocked");function gt(e,t){return JSON.stringify(e)===JSON.stringify(t)}r(gt,"isDeepStrictEqualForConfig");function De(e){return d(e)?Ue(je(e,"utf8")):void 0}r(De,"currentUserRevision");function vt(e){let t=`${e}.lock`;try{return{fd:ie(t,"wx",384),path:t}}catch(n){throw new Error(`Integration configuration is busy: ${f.basename(e)}`,{cause:n})}}r(vt,"acquireWriteLock");function I(e){let t=M(e.domain,e.configHome),n=e.validate(e.document);re(f.dirname(t),{recursive:!0,mode:448});let o=vt(t);try{let i=De(t),s=e.expectedRevision===null?void 0:e.expectedRevision;if(e.expectedRevision!==void 0&&i!==s)throw new k(t,s,i);let a=`${JSON.stringify(n,null,2)}
260
- `,c=`${t}.${process.pid}.${Date.now()}.tmp`,l=ie(c,"wx",384);try{Fe(l,a,"utf8"),$e(l)}finally{ne(l)}try{e.expectedRevision===null?(it(c,t),K(c)):Ke(c,t)}catch(g){throw d(c)&&K(c),e.expectedRevision===null&&d(t)?new k(t,void 0,De(t)):new Error(`Failed to atomically replace ${f.basename(t)}.`,{cause:g})}return _({domain:e.domain,source:"user",path:t,raw:a,document:n})}finally{ne(o.fd),d(o.path)&&K(o.path)}}r(I,"writeIntegrationDocument");function yt(e){if(!d(e))return"missing";let t=st(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}r(yt,"metadataSignature");function Le(e){return e.map(t=>`${t}:${yt(t)}`).join("|")}r(Le,"observationSignature");function j(e,t){return{code:e,message:t,time:new Date().toISOString()}}r(j,"safeDiagnostic");var Ne=class{static{r(this,"IntegrationConfigController")}#u;#n;#r;#a;#m;#f;#p;#e;#t;#c;#l;#h="";#s=[];#o;#i;#g=Promise.resolve();#d=new Set;constructor(t){this.#u=t.domain,this.#n=M(t.domain,t.configHome),this.#r=t.fallbackPath===void 0?void 0:f.resolve(t.fallbackPath),this.#a=this.#r===void 0?[this.#n]:[this.#n,this.#r],this.#f=t.validate,this.#m=t.read,this.#p=t.coldStartDefault===void 0?void 0:structuredClone(this.#f(t.coldStartDefault))}async initialize(){let t=await this.reload();if(!t.ok&&!this.#e&&this.#p!==void 0){let n=structuredClone(this.#p);this.#e=_({domain:this.#u,source:"default",path:this.#n,raw:JSON.stringify(n),document:n})}if(!this.#e)throw new Error(t.ok?"Integration configuration did not produce a snapshot.":t.error);return structuredClone(this.#e)}snapshot(){return this.#e?structuredClone(this.#e):void 0}status(){let t=this.#t?this.#c:void 0,n=this.#t?this.#l:void 0;return{domain:this.#u,path:t??this.#e?.path??this.#n,...this.#e?{revision:this.#e.revision,lastReloadAt:this.#e.loadedAt}:{},...n??this.#e?.source?{source:n??this.#e?.source}:{},...this.#t?{diagnostic:this.#t}:{},watching:this.#s.length>0}}subscribe(t){return this.#d.add(t),()=>{this.#d.delete(t)}}reload(){let t=this.#g.then(()=>this.#v());return this.#g=t.then(()=>{},()=>{}),t}async#v(){this.#h=Le(this.#a);let t;try{t=this.#m(),this.#f(t.document)}catch{let o=this.#y();return this.#c=o.path,this.#l=o.source,this.#t=j("invalid-config","Integration configuration is invalid; check the file against its versioned schema."),{ok:!1,error:this.#t.message}}let n=this.#e?structuredClone(this.#e):void 0;try{for(let o of this.#d)await o(structuredClone(t),n)}catch{return this.#c=t.path,this.#l=t.source,this.#t=j("activation-failed","Integration configuration could not be activated; the previous configuration remains active."),{ok:!1,error:this.#t.message}}return this.#e=t,this.#t=void 0,this.#c=void 0,this.#l=void 0,{ok:!0,snapshot:structuredClone(t)}}async ensureCurrent(){return Le(this.#a)===this.#h&&this.#e?{ok:!0,snapshot:structuredClone(this.#e)}:this.reload()}startWatching(t=100,n=2e3){if(this.#s.length>0||this.#i)return;re(f.dirname(this.#n),{recursive:!0,mode:448});let o=new Map;for(let i of this.#a){let s=f.dirname(i),a=o.get(s)??new Set;a.add(f.basename(i)),o.set(s,a)}for(let[i,s]of o)try{let a=at(i,(c,l)=>{l!==null&&!s.has(l.toString())||(this.#o&&clearTimeout(this.#o),this.#o=setTimeout(()=>{this.#o=void 0,this.reload()},t),this.#o.unref?.())});a.unref(),a.on("error",()=>{this.#t=j("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}),this.#s.push(a)}catch{this.#t=j("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}this.#i=setInterval(()=>{this.ensureCurrent()},n),this.#i.unref?.()}close(){this.#o&&clearTimeout(this.#o),this.#o=void 0,this.#i&&clearInterval(this.#i),this.#i=void 0;for(let t of this.#s)t.close();this.#s.length=0,this.#d.clear()}#y(){return d(this.#n)?{path:this.#n,source:"user"}:this.#r&&d(this.#r)?{path:this.#r,source:"legacy-user"}:{path:this.#n,source:"default"}}};var Pt=Et(wt),qe=2,We=!1,u=ke(),kn=h.join(u,"sessions"),p=h.join(u,"config.json"),Sn=60,v=null,ce=!1,kt="dumb";function St(e){let t=h.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",o=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",o],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",o]:["-lc",o],sentinel:n}}r(St,"buildShellEnvCommand");function Ct(e,t){let n=`${t}\0`,o=e.lastIndexOf(n);if(o===-1)return{};let i=e.slice(o+n.length),s={};for(let a of i.split("\0")){if(!a)continue;let c=a.indexOf("=");c<=0||(s[a.slice(0,c)]=a.slice(c+1))}return s}r(Ct,"parseNullDelimitedShellEnv");function Mt(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let o=e.shell??t.SHELL;if(!o||!h.isAbsolute(o))return!1;let{args:i,sentinel:s}=St(o),a=e.run??xt,c={...t,TERM:kt},l=a(o,i,{encoding:"utf8",env:c,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(l.status!==0||!l.stdout)return!1;let g=typeof l.stdout=="string"?l.stdout:l.stdout.toString("utf8"),N=Ct(g,s),$=!1;for(let[V,Je]of Object.entries(N))V!=="TERM"&&t[V]===void 0&&(t[V]=Je,$=!0);return $}r(Mt,"hydrateProcessEnvFromShell");function _t(){if(!ce){ce=!0;try{Mt()}catch{}}}r(_t,"ensureShellEnvironmentHydrated");function Cn(){ce=!1}r(Cn,"resetShellEnvironmentHydrationForTesting");function At(e){Ee(e.customProviders??[])}r(At,"registerConfiguredCustomProviders");function le(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:[]}r(le,"normalizeConfiguredExtensions");function ue(){let e=m.readFileSync(p,"utf8"),t=JSON.parse(e);if(!(t===null||typeof t!="object"||Array.isArray(t)))return{raw:e,value:t}}r(ue,"readPersistedCoreConfig");function Ve(e){m.writeFileSync(p,JSON.stringify(e,null,2))}r(Ve,"writePersistedCoreConfig");function Ot(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{x(p,()=>{let n=ue();n?.value.permissionMode==="default"&&Ve({...n.value,permissionMode:"accept-edits"})})}catch{}return t}r(Ot,"migrateLegacyPermissionModeInConfig");function Rt(e){if(e.permissionMode!=="auto-in-project")return e;try{x(p,()=>{let t=ue();if(t?.value.permissionMode!=="auto-in-project")return;let n=t.raw.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t.raw&&m.writeFileSync(p,n)})}catch{}return{...e,permissionMode:"auto"}}r(Rt,"migrateAutoInProjectAliasInConfig");function It(){if(v)return v;let e="0.7.97-alpha.6";if(e)return v=e,v;let t=h.join(h.dirname(bt(import.meta.url)),"../../package.json");if(m.existsSync(t))try{return v=JSON.parse(m.readFileSync(t,"utf-8")).version??"0.0.0",v??"0.0.0"}catch{}return v="0.0.0",v}r(It,"getVersion");var Mn=It();function Tt(e){return ve(e)}r(Tt,"getProviderModel");function de(e,t){let n=new Set(e.map(i=>i.toLowerCase())),o=[...e];for(let i of t)n.has(i.toLowerCase())||o.push(i);return o}r(de,"mergeModels");function Dt(e,t){t||(t=fe().providerModels);let n=t?.[e];if(n&&n.length>0){try{let o=Y(e);if(o.length>0)return de(n,o)}catch{}try{let o=R(e);if(o)return de(n,o.getAvailableModels())}catch{}return n}try{let o=Y(e);if(o.length>0)return o}catch{}try{let o=R(e);if(o)return o.getAvailableModels()}catch{}return[]}r(Dt,"getProviderAvailableModels");function Lt(e,t){let n=ye(e,t);if(n!=="unknown")return n;try{let o=R(e);if(o)return o.getReasoningCapability(t)}catch{}return"unknown"}r(Lt,"getProviderReasoningCapability");function Nt(e){let t=we(e);if(t)return t;try{return Q().find(o=>o.name===e)?.capabilityProfile??null}catch{return null}}r(Nt,"getProviderCapabilityProfile");function ze(e,t){let n=Nt(e),o=Lt(e,t);if(n)return{capabilityProfile:n,reasoningCapability:o};try{let i=be(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}r(ze,"getProviderCapabilityMetadata");function _n(e,t){let n=ze(e,t);return n?Me({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}r(_n,"getProviderCapabilitySnapshot");function $t(e,t,n,o){let i=ze(e,t);return i?_e({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:o}):null}r($t,"getProviderPolicyDecision");function An(e){let t=e.transport==="cli-bridge"?"CLI bridge":"Native API",n=e.conversationSemantics==="last-user-message"?"forwards only the latest user message":"preserves full conversation history",o=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${o}`}r(An,"describeProviderCapabilitySummary");function On(e){switch(e){case"native-budget":return"B";case"native-effort":return"E";case"native-toggle":return"T";case"native-adaptive":return"A";default:return"-"}}r(On,"formatReasoningCapabilityShort");function O(e){if(e)return e==="none"?"off":e}r(O,"formatReasoningEffortForDisplay");function W(e,t){let n=O(t);n&&!e.includes(n)&&e.push(n)}r(W,"pushUniqueEffortDisplay");function Rn(e,t,n){let o=["auto"],i=H(e,t,n),s=i?.supportedEfforts?.filter(a=>a.isUserVisible!==!1);if(!s||s.length===0){for(let a of["off","low","medium","high"])W(o,a);return o}for(let a of s)a.value==="none"&&i?.supportsDisabledThinking===!1||W(o,a.value);return o}r(Rn,"getProviderReasoningEffortOptions");function In(e,t){let n=H(e,t),o=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(l=>l.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let l of["low","medium","high"])W(s,l);a=!0}else for(let l of i){if(l.value==="none"){n?.supportsDisabledThinking!==!1&&(a=!0);continue}if(o.has(l.value)){n?.supportsDisabledThinking!==!1&&(a=!0);continue}W(s,l.value)}let c=[];return a&&c.push("off"),c.push(...s),c.push("auto"),c}r(In,"getProviderReasoningEffortCycle");function jt(e,t){if(t===!1)return"off";switch(e){case"off":return"off";case"quick":return"low";case"balanced":return"medium";case"deep":return"high";default:return"auto"}}r(jt,"legacyReasoningModeToEffortDisplay");function H(e,t,n){let o=t??Tt(e);if(!o)return;let i=Pe(e,o)?.reasoningProfile;if(i)return me(i,Se(e,o,n))}r(H,"resolveReasoningProfileForDisplay");function Tn(e){let t=O(e.effort)??jt(e.reasoningMode,e.thinking),n=H(e.provider,e.model);if(!n)return t;try{let o=he({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=O(o.configuredEffort)??t,a=o.configuredEffort!==void 0&&n.supportsDisabledThinking!==!1&&n.disabledEfforts?.includes(o.configuredEffort)===!0?"off":O(o.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let o=J({currentEffort:e.effort,capability:n}),i=O(e.effort)??t,s=O(o.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}r(Tn,"formatReasoningEffortStatusLabel");function Dn(e){let t=Vt(e);if(!t)return{preserved:!0};let n=H(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let o=J({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:o.effectiveEffort,preserved:o.preserved,diagnostic:o.diagnostic}}r(Dn,"resolveProviderReasoningRuntimeEffort");function Kt(e){switch(e){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";case"native-adaptive":return"adaptive";default:return"none"}}r(Kt,"describeReasoningCapabilityControl");function Ln(e,t){if(e==="off")return"Reasoning disabled";switch(t){case"native-budget":return"Uses native thinking budget control";case"native-effort":return"Uses native reasoning effort control";case"native-toggle":return"Uses provider-native thinking toggle only";case"native-adaptive":return"Model adaptively decides thinking depth (Opus 4.7+)";case"none":return"Runs without native reasoning parameters";case"prompt-only":return"Uses prompt overlays only; no native reasoning parameter";default:return"Runs without native reasoning parameters"}}r(Ln,"describeReasoningExecution");function Nn(e){let t=[];e||(e=fe().providerModels);for(let n of xe())t.push({name:n.name,model:n.model,models:Dt(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=Q().map(o=>({...o,models:(()=>{let i=e?.[o.name];return i&&i.length>0?de(i,o.models):o.models})()}));t.push(...n)}catch{}return t}r(Nn,"getProviderList");function $n(e){if(ge(e))return!0;try{return R(e)?.isConfigured()??!1}catch{return!1}}r($n,"isProviderConfigured");var G=class extends Error{static{r(this,"InvalidAgentModeConfigError")}};function Ft(e){let t=e.agentMode;if(t===void 0||t==="ama"||t==="sa")return e;if(t!=="amaw"&&t!=="ama-workflow")throw new G(`Invalid agentMode "${t}" in ${p}. Expected "ama" or "sa".`);let n={...e,agentMode:"ama",schemaVersion:Math.max(e.schemaVersion??0,qe)};try{x(p,()=>{let o=ue();if(!o)return;let i=o.value.agentMode;i!=="amaw"&&i!=="ama-workflow"||Ve({...o.value,agentMode:"ama",schemaVersion:Math.max(typeof o.value.schemaVersion=="number"?o.value.schemaVersion:0,qe)})})}catch{}return We||(process.emitWarning(`Migrated persisted agentMode "${t}" to "ama". Workflow use is now explicit intent.`,{code:"KODAX_AGENT_MODE_MIGRATED"}),We=!0),n}r(Ft,"migrateLegacyAgentModeConfig");function fe(){try{if(m.existsSync(p)){let n=JSON.parse(m.readFileSync(p,"utf-8")),o=Ft(n),i=o.reasoningCeiling??o.reasoningMode,s=[],a={};try{s=[...q(u).document.paths]}catch{}try{a=U(u).document.servers}catch{}let{sandbox:c,...l}=o;return Rt(Ot({...l,reasoningMode:i,extensions:le(s),mcpServers:a}))}}catch(n){if(n instanceof G)throw n}let e,t;try{let n=q(u);n.source!=="default"&&(e=le([...n.document.paths]))}catch{}try{let n=U(u);n.source!=="default"&&(t=n.document.servers)}catch{}return{...e===void 0?{}:{extensions:e},...t===void 0?{}:{mcpServers:t}}}r(fe,"loadConfig");var Xt=h.join(u,"config.example.jsonc"),ae={mcp:h.join(u,"integrations","mcp.example.jsonc"),a2a:h.join(u,"integrations","a2a.example.jsonc"),extensions:h.join(u,"integrations","extensions.example.jsonc")},Ut=[{name:"core",path:Xt},{name:"mcp",path:ae.mcp},{name:"a2a",path:ae.a2a},{name:"extensions",path:ae.extensions}];function qt(){let e=[];for(let t of Ut)try{if(m.existsSync(t.path))continue;m.mkdirSync(h.dirname(t.path),{recursive:!0}),m.writeFileSync(t.path,Ie(t.name),"utf8"),e.push(t.path)}catch{}return e}r(qt,"ensureExampleConfigFiles");function jn(){return qt()[0]}r(jn,"ensureExampleConfigFile");var L=new Map;function Kn(e){let t=process.env[e];return t===void 0?"unset":L.get(e)===t?"persisted":"environment"}r(Kn,"inspectConfigEnvironmentSource");function Be(e,t,n=!1){let o=process.env[e],i=L.get(e),s=i!==void 0&&o===i;if(o!==void 0&&!s&&!n){L.delete(e);return}if(t===void 0){(s||n)&&delete process.env[e],L.delete(e);return}process.env[e]=t,L.set(e,t)}r(Be,"projectConfigEnvironment");var pe=[{configPath:"streamIdleTimeoutMs",env:"KODAX_STREAM_IDLE_TIMEOUT_MS",value:r(e=>b(e.streamIdleTimeoutMs),"value")},{configPath:"repoIntelligenceMode",env:"KODAX_REPO_INTELLIGENCE",value:r(e=>e.repoIntelligenceMode,"value")},{configPath:"repoIntelligenceTrace",env:"KODAX_REPO_INTELLIGENCE_TRACE",value:r(e=>T(e.repoIntelligenceTrace),"value")},{configPath:"stallLog",env:"KODAX_STALL_LOG",value:r(e=>T(e.stallLog),"value")},{configPath:"fallbackProviders",env:"KODAX_FALLBACK_PROVIDERS",value:r(e=>Gt(e.fallbackProviders),"value")},{configPath:"fastProvider",env:"KODAX_FAST_PROVIDER",value:r(e=>y(e.fastProvider),"value")},{configPath:"fastModel",env:"KODAX_FAST_MODEL",value:r(e=>y(e.fastModel),"value")},{configPath:"deepProvider",env:"KODAX_DEEP_PROVIDER",value:r(e=>y(e.deepProvider),"value")},{configPath:"deepModel",env:"KODAX_DEEP_MODEL",value:r(e=>y(e.deepModel),"value")},{configPath:"provider",env:"KODAX_PROVIDER",value:r(e=>y(e.provider),"value")},{configPath:"effort",env:"KODAX_EFFORT",value:r(e=>y(e.effort),"value")},{configPath:"sessionRetentionDays",env:"KODAX_SESSION_RETENTION_DAYS",value:r(e=>b(e.sessionRetentionDays),"value")},{configPath:"maxOutputTokens",env:"KODAX_MAX_OUTPUT_TOKENS",value:r(e=>b(e.maxOutputTokens),"value")},{configPath:"disablePromptCache",env:"KODAX_DISABLE_PROMPT_CACHE",value:r(e=>T(e.disablePromptCache),"value")},{configPath:"lsp",env:"KODAX_LSP",value:r(e=>T(e.lsp),"value")},{configPath:"lspAutoDownload",env:"KODAX_LSP_DOWNLOAD",value:r(e=>T(e.lspAutoDownload),"value")},{configPath:"acpLogLevel",env:"KODAX_ACP_LOG",value:r(e=>y(e.acpLogLevel),"value")},{configPath:"repoIntelligence.toolWaitMs",env:"KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS",value:r(e=>b(e.repoIntelligence?.toolWaitMs),"value")},{configPath:"repoIntelligence.workerTimeoutMs",env:"KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS",value:r(e=>b(e.repoIntelligence?.workerTimeoutMs),"value")},{configPath:"repoIntelligence.workerOldSpaceMb",env:"KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB",value:r(e=>b(e.repoIntelligence?.workerOldSpaceMb),"value")},{configPath:"repoIntelligence.storageDir",env:"KODAX_REPO_INTELLIGENCE_STORAGE_DIR",value:r(e=>y(e.repoIntelligence?.storageDir),"value")},{configPath:"workflow.maxConcurrency",env:"KODAX_WORKFLOW_MAX_CONCURRENCY",value:r(e=>b(e.workflow?.maxConcurrency),"value")}];function Wt(e){for(let t of pe)Be(t.env,t.value(e))}r(Wt,"applyConfigSurfaceBridges");function y(e){return e?.trim()||void 0}r(y,"normalizedConfigString");function b(e){return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}r(b,"configNumberString");function T(e){return e===void 0?void 0:e?"1":"0"}r(T,"configBooleanString");function Gt(e){return e?.filter(t=>t.trim().length>0).join(",")}r(Gt,"configStringList");var Fn=[...pe.map(({configPath:e,env:t})=>({configPath:e,env:t}))];function Ht(e){Wt(e)}r(Ht,"applyConfigEnvironment");function Xn(e,t=!1){for(let n of pe)["fallbackProviders","stallLog"].includes(n.configPath)&&(t&&!Object.hasOwn(e,n.configPath)||Be(n.env,n.value(e),t))}r(Xn,"applyExecutionConfigEnvironment");function Un(){_t();let e=fe();return Ht(e),At(e),Oe(e.locale),e}r(Un,"prepareRuntimeConfig");function qn(e){let{extensions:t,mcpServers:n,...o}=e;if(x(p,()=>{let i={};if(m.existsSync(p))try{let a=JSON.parse(m.readFileSync(p,"utf8"));a&&typeof a=="object"&&!Array.isArray(a)&&(i=a)}catch{}let s={...i,...o};for(let a of Object.keys(o))o[a]===void 0&&delete s[a];m.writeFileSync(p,JSON.stringify(s,null,2))}),t!==void 0){let i=q(u);I({domain:"extensions",configHome:u,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,paths:le(t)??[]},validate:C})}if(n!==void 0){let i=U(u);I({domain:"mcp",configHome:u,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,servers:n},validate:S})}}r(qn,"saveConfig");function Wn(e,t,n){return e.effort!==void 0||B(n).kind==="value"||t.effort!==void 0}r(Wn,"resolveInitialEffortOverride");function w(e){return e?.trim()?e:void 0}r(w,"nonEmptySelection");function Gn(e){return w(e.explicitProvider)??w(e.environmentProvider)??w(e.configuredProvider)??e.defaultProvider}r(Gn,"resolveRuntimeProviderSelection");function Hn(e){let t=w(e.explicitModel);if(t)return t;let n=w(e.configuredModel);if(!n)return;let o=w(e.explicitProvider)??w(e.environmentProvider);return o?w(e.configuredProvider)===o?n:void 0:n}r(Hn,"resolveRuntimeModelSelection");function Vn(e){if(e.explicitEffort!==void 0)return z(e.explicitEffort);let t=B(e.environmentEffort);return t.kind==="value"?t.value:e.configuredEffort===void 0?void 0:z(e.configuredEffort)}r(Vn,"resolveRuntimeEffortSelection");function Vt(e){return e.permissionMode==="plan"&&e.effortOverride!==!0&&e.planModeEffort!==void 0?e.planModeEffort:e.effort}r(Vt,"resolvePermissionModeEffort");async function zn(e){try{await Ce({cwd:e});let{stdout:t}=await Pt("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0});return t.trim()}catch{return null}}r(zn,"getGitRoot");function zt(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}r(zt,"formatProviderSourceKind");function Bn(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: ${zt(e.sourceKind)}`,`Transport: ${t}`,`Conversation semantics: ${n}`,`Context fidelity: ${e.contextFidelity}`,`Tool calling: ${e.toolCallingFidelity}`,`Session behavior: ${e.sessionSupport}`,`Long-running support: ${e.longRunningSupport}`,`Evidence-heavy flows: ${e.evidenceSupport}`,`Multimodal support: ${e.multimodalSupport}`,`MCP support: ${e.mcpSupport}`,`Reasoning control: ${Kt(e.reasoningCapability)}`]}r(Bn,"formatProviderCapabilityDetailLines");function Jn(e,t,n){return[{label:"General coding",hints:{}},{label:"Evidence-heavy review",hints:{evidenceHeavy:!0}},{label:"Long-running task",hints:{longRunning:!0}}].map(i=>({label:i.label,decision:$t(e,t,n,i.hints)})).filter(i=>i.decision!==null)}r(Jn,"getProviderCommonPolicyScenarios");var Ge=.5,He=0,D={locked:!1,queue:[]};async function Yn(e){for(;D.locked;)await new Promise(t=>D.queue.push(t));D.locked=!0;try{let t=(Date.now()-He)/1e3;t<Ge&&await new Promise(o=>setTimeout(o,(Ge-t)*1e3));let n=await e();return He=Date.now(),n}finally{D.locked=!1;let t=D.queue.shift();t&&t()}}r(Yn,"rateLimitedCall");export{Bt as a,Re as b,Ie as c,ee as d,ot as e,x as f,k as g,S as h,C as i,M as j,U as k,q as l,pt as m,ln as n,I as o,Ne as p,u as q,kn as r,p as s,Sn as t,Mt as u,Cn as v,At as w,It as x,Mn as y,Tt as z,Dt as A,Lt as B,Nt as C,_n as D,$t as E,An as F,On as G,O as H,Rn as I,In as J,Tn as K,Dn as L,Kt as M,Ln as N,Nn as O,$n as P,fe as Q,Xt as R,ae as S,qt as T,jn as U,Kn as V,Fn as W,Ht as X,Xn as Y,Un as Z,qn as _,Wn as $,Gn as aa,Hn as ba,Vn as ca,Vt as da,zn as ea,zt as fa,Bn as ga,Jn as ha,Yn as ia};
260
+ `,c=`${t}.${process.pid}.${Date.now()}.tmp`,l=ie(c,"wx",384);try{Fe(l,a,"utf8"),$e(l)}finally{ne(l)}try{e.expectedRevision===null?(it(c,t),K(c)):Ke(c,t)}catch(g){throw d(c)&&K(c),e.expectedRevision===null&&d(t)?new k(t,void 0,De(t)):new Error(`Failed to atomically replace ${f.basename(t)}.`,{cause:g})}return _({domain:e.domain,source:"user",path:t,raw:a,document:n})}finally{ne(o.fd),d(o.path)&&K(o.path)}}r(I,"writeIntegrationDocument");function yt(e){if(!d(e))return"missing";let t=st(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}r(yt,"metadataSignature");function Le(e){return e.map(t=>`${t}:${yt(t)}`).join("|")}r(Le,"observationSignature");function j(e,t){return{code:e,message:t,time:new Date().toISOString()}}r(j,"safeDiagnostic");var Ne=class{static{r(this,"IntegrationConfigController")}#u;#n;#r;#a;#m;#f;#p;#e;#t;#c;#l;#h="";#s=[];#o;#i;#g=Promise.resolve();#d=new Set;constructor(t){this.#u=t.domain,this.#n=M(t.domain,t.configHome),this.#r=t.fallbackPath===void 0?void 0:f.resolve(t.fallbackPath),this.#a=this.#r===void 0?[this.#n]:[this.#n,this.#r],this.#f=t.validate,this.#m=t.read,this.#p=t.coldStartDefault===void 0?void 0:structuredClone(this.#f(t.coldStartDefault))}async initialize(){let t=await this.reload();if(!t.ok&&!this.#e&&this.#p!==void 0){let n=structuredClone(this.#p);this.#e=_({domain:this.#u,source:"default",path:this.#n,raw:JSON.stringify(n),document:n})}if(!this.#e)throw new Error(t.ok?"Integration configuration did not produce a snapshot.":t.error);return structuredClone(this.#e)}snapshot(){return this.#e?structuredClone(this.#e):void 0}status(){let t=this.#t?this.#c:void 0,n=this.#t?this.#l:void 0;return{domain:this.#u,path:t??this.#e?.path??this.#n,...this.#e?{revision:this.#e.revision,lastReloadAt:this.#e.loadedAt}:{},...n??this.#e?.source?{source:n??this.#e?.source}:{},...this.#t?{diagnostic:this.#t}:{},watching:this.#s.length>0}}subscribe(t){return this.#d.add(t),()=>{this.#d.delete(t)}}reload(){let t=this.#g.then(()=>this.#v());return this.#g=t.then(()=>{},()=>{}),t}async#v(){this.#h=Le(this.#a);let t;try{t=this.#m(),this.#f(t.document)}catch{let o=this.#y();return this.#c=o.path,this.#l=o.source,this.#t=j("invalid-config","Integration configuration is invalid; check the file against its versioned schema."),{ok:!1,error:this.#t.message}}let n=this.#e?structuredClone(this.#e):void 0;try{for(let o of this.#d)await o(structuredClone(t),n)}catch{return this.#c=t.path,this.#l=t.source,this.#t=j("activation-failed","Integration configuration could not be activated; the previous configuration remains active."),{ok:!1,error:this.#t.message}}return this.#e=t,this.#t=void 0,this.#c=void 0,this.#l=void 0,{ok:!0,snapshot:structuredClone(t)}}async ensureCurrent(){return Le(this.#a)===this.#h&&this.#e?{ok:!0,snapshot:structuredClone(this.#e)}:this.reload()}startWatching(t=100,n=2e3){if(this.#s.length>0||this.#i)return;re(f.dirname(this.#n),{recursive:!0,mode:448});let o=new Map;for(let i of this.#a){let s=f.dirname(i),a=o.get(s)??new Set;a.add(f.basename(i)),o.set(s,a)}for(let[i,s]of o)try{let a=at(i,(c,l)=>{l!==null&&!s.has(l.toString())||(this.#o&&clearTimeout(this.#o),this.#o=setTimeout(()=>{this.#o=void 0,this.reload()},t),this.#o.unref?.())});a.unref(),a.on("error",()=>{this.#t=j("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}),this.#s.push(a)}catch{this.#t=j("watcher-degraded","Integration watcher is degraded; metadata polling remains active.")}this.#i=setInterval(()=>{this.ensureCurrent()},n),this.#i.unref?.()}close(){this.#o&&clearTimeout(this.#o),this.#o=void 0,this.#i&&clearInterval(this.#i),this.#i=void 0;for(let t of this.#s)t.close();this.#s.length=0,this.#d.clear()}#y(){return d(this.#n)?{path:this.#n,source:"user"}:this.#r&&d(this.#r)?{path:this.#r,source:"legacy-user"}:{path:this.#n,source:"default"}}};var Pt=Et(wt),qe=2,We=!1,u=ke(),kn=h.join(u,"sessions"),p=h.join(u,"config.json"),Sn=60,v=null,ce=!1,kt="dumb";function St(e){let t=h.basename(e).toLowerCase(),n="__KODAX_SHELL_ENV_START__",o=`printf '%s\\0' '${n}'; env -0`;return t==="fish"?{args:["-i","-c",o],sentinel:n}:{args:t==="bash"||t==="zsh"?["-ic",o]:["-lc",o],sentinel:n}}r(St,"buildShellEnvCommand");function Ct(e,t){let n=`${t}\0`,o=e.lastIndexOf(n);if(o===-1)return{};let i=e.slice(o+n.length),s={};for(let a of i.split("\0")){if(!a)continue;let c=a.indexOf("=");c<=0||(s[a.slice(0,c)]=a.slice(c+1))}return s}r(Ct,"parseNullDelimitedShellEnv");function Mt(e={}){let t=e.env??process.env;if((e.platform??process.platform)==="win32"||t.KODAX_DISABLE_SHELL_ENV_HYDRATION==="1")return!1;let o=e.shell??t.SHELL;if(!o||!h.isAbsolute(o))return!1;let{args:i,sentinel:s}=St(o),a=e.run??xt,c={...t,TERM:kt},l=a(o,i,{encoding:"utf8",env:c,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(l.status!==0||!l.stdout)return!1;let g=typeof l.stdout=="string"?l.stdout:l.stdout.toString("utf8"),N=Ct(g,s),$=!1;for(let[V,Je]of Object.entries(N))V!=="TERM"&&t[V]===void 0&&(t[V]=Je,$=!0);return $}r(Mt,"hydrateProcessEnvFromShell");function _t(){if(!ce){ce=!0;try{Mt()}catch{}}}r(_t,"ensureShellEnvironmentHydrated");function Cn(){ce=!1}r(Cn,"resetShellEnvironmentHydrationForTesting");function At(e){Ee(e.customProviders??[])}r(At,"registerConfiguredCustomProviders");function le(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:[]}r(le,"normalizeConfiguredExtensions");function ue(){let e=m.readFileSync(p,"utf8"),t=JSON.parse(e);if(!(t===null||typeof t!="object"||Array.isArray(t)))return{raw:e,value:t}}r(ue,"readPersistedCoreConfig");function Ve(e){m.writeFileSync(p,JSON.stringify(e,null,2))}r(Ve,"writePersistedCoreConfig");function Ot(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{x(p,()=>{let n=ue();n?.value.permissionMode==="default"&&Ve({...n.value,permissionMode:"accept-edits"})})}catch{}return t}r(Ot,"migrateLegacyPermissionModeInConfig");function Rt(e){if(e.permissionMode!=="auto-in-project")return e;try{x(p,()=>{let t=ue();if(t?.value.permissionMode!=="auto-in-project")return;let n=t.raw.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t.raw&&m.writeFileSync(p,n)})}catch{}return{...e,permissionMode:"auto"}}r(Rt,"migrateAutoInProjectAliasInConfig");function It(){if(v)return v;let e="0.7.97-alpha.7";if(e)return v=e,v;let t=h.join(h.dirname(bt(import.meta.url)),"../../package.json");if(m.existsSync(t))try{return v=JSON.parse(m.readFileSync(t,"utf-8")).version??"0.0.0",v??"0.0.0"}catch{}return v="0.0.0",v}r(It,"getVersion");var Mn=It();function Tt(e){return ve(e)}r(Tt,"getProviderModel");function de(e,t){let n=new Set(e.map(i=>i.toLowerCase())),o=[...e];for(let i of t)n.has(i.toLowerCase())||o.push(i);return o}r(de,"mergeModels");function Dt(e,t){t||(t=fe().providerModels);let n=t?.[e];if(n&&n.length>0){try{let o=Y(e);if(o.length>0)return de(n,o)}catch{}try{let o=R(e);if(o)return de(n,o.getAvailableModels())}catch{}return n}try{let o=Y(e);if(o.length>0)return o}catch{}try{let o=R(e);if(o)return o.getAvailableModels()}catch{}return[]}r(Dt,"getProviderAvailableModels");function Lt(e,t){let n=ye(e,t);if(n!=="unknown")return n;try{let o=R(e);if(o)return o.getReasoningCapability(t)}catch{}return"unknown"}r(Lt,"getProviderReasoningCapability");function Nt(e){let t=we(e);if(t)return t;try{return Q().find(o=>o.name===e)?.capabilityProfile??null}catch{return null}}r(Nt,"getProviderCapabilityProfile");function ze(e,t){let n=Nt(e),o=Lt(e,t);if(n)return{capabilityProfile:n,reasoningCapability:o};try{let i=be(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}r(ze,"getProviderCapabilityMetadata");function _n(e,t){let n=ze(e,t);return n?Me({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}r(_n,"getProviderCapabilitySnapshot");function $t(e,t,n,o){let i=ze(e,t);return i?_e({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:o}):null}r($t,"getProviderPolicyDecision");function An(e){let t=e.transport==="cli-bridge"?"CLI bridge":"Native API",n=e.conversationSemantics==="last-user-message"?"forwards only the latest user message":"preserves full conversation history",o=e.mcpSupport==="native"?"MCP available":"MCP unavailable";return`${t}; ${n}; ${o}`}r(An,"describeProviderCapabilitySummary");function On(e){switch(e){case"native-budget":return"B";case"native-effort":return"E";case"native-toggle":return"T";case"native-adaptive":return"A";default:return"-"}}r(On,"formatReasoningCapabilityShort");function O(e){if(e)return e==="none"?"off":e}r(O,"formatReasoningEffortForDisplay");function W(e,t){let n=O(t);n&&!e.includes(n)&&e.push(n)}r(W,"pushUniqueEffortDisplay");function Rn(e,t,n){let o=["auto"],i=H(e,t,n),s=i?.supportedEfforts?.filter(a=>a.isUserVisible!==!1);if(!s||s.length===0){for(let a of["off","low","medium","high"])W(o,a);return o}for(let a of s)a.value==="none"&&i?.supportsDisabledThinking===!1||W(o,a.value);return o}r(Rn,"getProviderReasoningEffortOptions");function In(e,t){let n=H(e,t),o=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(l=>l.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let l of["low","medium","high"])W(s,l);a=!0}else for(let l of i){if(l.value==="none"){n?.supportsDisabledThinking!==!1&&(a=!0);continue}if(o.has(l.value)){n?.supportsDisabledThinking!==!1&&(a=!0);continue}W(s,l.value)}let c=[];return a&&c.push("off"),c.push(...s),c.push("auto"),c}r(In,"getProviderReasoningEffortCycle");function jt(e,t){if(t===!1)return"off";switch(e){case"off":return"off";case"quick":return"low";case"balanced":return"medium";case"deep":return"high";default:return"auto"}}r(jt,"legacyReasoningModeToEffortDisplay");function H(e,t,n){let o=t??Tt(e);if(!o)return;let i=Pe(e,o)?.reasoningProfile;if(i)return me(i,Se(e,o,n))}r(H,"resolveReasoningProfileForDisplay");function Tn(e){let t=O(e.effort)??jt(e.reasoningMode,e.thinking),n=H(e.provider,e.model);if(!n)return t;try{let o=he({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=O(o.configuredEffort)??t,a=o.configuredEffort!==void 0&&n.supportsDisabledThinking!==!1&&n.disabledEfforts?.includes(o.configuredEffort)===!0?"off":O(o.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let o=J({currentEffort:e.effort,capability:n}),i=O(e.effort)??t,s=O(o.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}r(Tn,"formatReasoningEffortStatusLabel");function Dn(e){let t=Vt(e);if(!t)return{preserved:!0};let n=H(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let o=J({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:o.effectiveEffort,preserved:o.preserved,diagnostic:o.diagnostic}}r(Dn,"resolveProviderReasoningRuntimeEffort");function Kt(e){switch(e){case"native-budget":return"budget";case"native-effort":return"effort";case"native-toggle":return"toggle";case"native-adaptive":return"adaptive";default:return"none"}}r(Kt,"describeReasoningCapabilityControl");function Ln(e,t){if(e==="off")return"Reasoning disabled";switch(t){case"native-budget":return"Uses native thinking budget control";case"native-effort":return"Uses native reasoning effort control";case"native-toggle":return"Uses provider-native thinking toggle only";case"native-adaptive":return"Model adaptively decides thinking depth (Opus 4.7+)";case"none":return"Runs without native reasoning parameters";case"prompt-only":return"Uses prompt overlays only; no native reasoning parameter";default:return"Runs without native reasoning parameters"}}r(Ln,"describeReasoningExecution");function Nn(e){let t=[];e||(e=fe().providerModels);for(let n of xe())t.push({name:n.name,model:n.model,models:Dt(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=Q().map(o=>({...o,models:(()=>{let i=e?.[o.name];return i&&i.length>0?de(i,o.models):o.models})()}));t.push(...n)}catch{}return t}r(Nn,"getProviderList");function $n(e){if(ge(e))return!0;try{return R(e)?.isConfigured()??!1}catch{return!1}}r($n,"isProviderConfigured");var G=class extends Error{static{r(this,"InvalidAgentModeConfigError")}};function Ft(e){let t=e.agentMode;if(t===void 0||t==="ama"||t==="sa")return e;if(t!=="amaw"&&t!=="ama-workflow")throw new G(`Invalid agentMode "${t}" in ${p}. Expected "ama" or "sa".`);let n={...e,agentMode:"ama",schemaVersion:Math.max(e.schemaVersion??0,qe)};try{x(p,()=>{let o=ue();if(!o)return;let i=o.value.agentMode;i!=="amaw"&&i!=="ama-workflow"||Ve({...o.value,agentMode:"ama",schemaVersion:Math.max(typeof o.value.schemaVersion=="number"?o.value.schemaVersion:0,qe)})})}catch{}return We||(process.emitWarning(`Migrated persisted agentMode "${t}" to "ama". Workflow use is now explicit intent.`,{code:"KODAX_AGENT_MODE_MIGRATED"}),We=!0),n}r(Ft,"migrateLegacyAgentModeConfig");function fe(){try{if(m.existsSync(p)){let n=JSON.parse(m.readFileSync(p,"utf-8")),o=Ft(n),i=o.reasoningCeiling??o.reasoningMode,s=[],a={};try{s=[...q(u).document.paths]}catch{}try{a=U(u).document.servers}catch{}let{sandbox:c,...l}=o;return Rt(Ot({...l,reasoningMode:i,extensions:le(s),mcpServers:a}))}}catch(n){if(n instanceof G)throw n}let e,t;try{let n=q(u);n.source!=="default"&&(e=le([...n.document.paths]))}catch{}try{let n=U(u);n.source!=="default"&&(t=n.document.servers)}catch{}return{...e===void 0?{}:{extensions:e},...t===void 0?{}:{mcpServers:t}}}r(fe,"loadConfig");var Xt=h.join(u,"config.example.jsonc"),ae={mcp:h.join(u,"integrations","mcp.example.jsonc"),a2a:h.join(u,"integrations","a2a.example.jsonc"),extensions:h.join(u,"integrations","extensions.example.jsonc")},Ut=[{name:"core",path:Xt},{name:"mcp",path:ae.mcp},{name:"a2a",path:ae.a2a},{name:"extensions",path:ae.extensions}];function qt(){let e=[];for(let t of Ut)try{if(m.existsSync(t.path))continue;m.mkdirSync(h.dirname(t.path),{recursive:!0}),m.writeFileSync(t.path,Ie(t.name),"utf8"),e.push(t.path)}catch{}return e}r(qt,"ensureExampleConfigFiles");function jn(){return qt()[0]}r(jn,"ensureExampleConfigFile");var L=new Map;function Kn(e){let t=process.env[e];return t===void 0?"unset":L.get(e)===t?"persisted":"environment"}r(Kn,"inspectConfigEnvironmentSource");function Be(e,t,n=!1){let o=process.env[e],i=L.get(e),s=i!==void 0&&o===i;if(o!==void 0&&!s&&!n){L.delete(e);return}if(t===void 0){(s||n)&&delete process.env[e],L.delete(e);return}process.env[e]=t,L.set(e,t)}r(Be,"projectConfigEnvironment");var pe=[{configPath:"streamIdleTimeoutMs",env:"KODAX_STREAM_IDLE_TIMEOUT_MS",value:r(e=>b(e.streamIdleTimeoutMs),"value")},{configPath:"repoIntelligenceMode",env:"KODAX_REPO_INTELLIGENCE",value:r(e=>e.repoIntelligenceMode,"value")},{configPath:"repoIntelligenceTrace",env:"KODAX_REPO_INTELLIGENCE_TRACE",value:r(e=>T(e.repoIntelligenceTrace),"value")},{configPath:"stallLog",env:"KODAX_STALL_LOG",value:r(e=>T(e.stallLog),"value")},{configPath:"fallbackProviders",env:"KODAX_FALLBACK_PROVIDERS",value:r(e=>Gt(e.fallbackProviders),"value")},{configPath:"fastProvider",env:"KODAX_FAST_PROVIDER",value:r(e=>y(e.fastProvider),"value")},{configPath:"fastModel",env:"KODAX_FAST_MODEL",value:r(e=>y(e.fastModel),"value")},{configPath:"deepProvider",env:"KODAX_DEEP_PROVIDER",value:r(e=>y(e.deepProvider),"value")},{configPath:"deepModel",env:"KODAX_DEEP_MODEL",value:r(e=>y(e.deepModel),"value")},{configPath:"provider",env:"KODAX_PROVIDER",value:r(e=>y(e.provider),"value")},{configPath:"effort",env:"KODAX_EFFORT",value:r(e=>y(e.effort),"value")},{configPath:"sessionRetentionDays",env:"KODAX_SESSION_RETENTION_DAYS",value:r(e=>b(e.sessionRetentionDays),"value")},{configPath:"maxOutputTokens",env:"KODAX_MAX_OUTPUT_TOKENS",value:r(e=>b(e.maxOutputTokens),"value")},{configPath:"disablePromptCache",env:"KODAX_DISABLE_PROMPT_CACHE",value:r(e=>T(e.disablePromptCache),"value")},{configPath:"lsp",env:"KODAX_LSP",value:r(e=>T(e.lsp),"value")},{configPath:"lspAutoDownload",env:"KODAX_LSP_DOWNLOAD",value:r(e=>T(e.lspAutoDownload),"value")},{configPath:"acpLogLevel",env:"KODAX_ACP_LOG",value:r(e=>y(e.acpLogLevel),"value")},{configPath:"repoIntelligence.toolWaitMs",env:"KODAX_REPO_INTELLIGENCE_TOOL_WAIT_MS",value:r(e=>b(e.repoIntelligence?.toolWaitMs),"value")},{configPath:"repoIntelligence.workerTimeoutMs",env:"KODAX_REPO_INTELLIGENCE_WORKER_TIMEOUT_MS",value:r(e=>b(e.repoIntelligence?.workerTimeoutMs),"value")},{configPath:"repoIntelligence.workerOldSpaceMb",env:"KODAX_REPO_INTELLIGENCE_WORKER_OLD_SPACE_MB",value:r(e=>b(e.repoIntelligence?.workerOldSpaceMb),"value")},{configPath:"repoIntelligence.storageDir",env:"KODAX_REPO_INTELLIGENCE_STORAGE_DIR",value:r(e=>y(e.repoIntelligence?.storageDir),"value")},{configPath:"workflow.maxConcurrency",env:"KODAX_WORKFLOW_MAX_CONCURRENCY",value:r(e=>b(e.workflow?.maxConcurrency),"value")}];function Wt(e){for(let t of pe)Be(t.env,t.value(e))}r(Wt,"applyConfigSurfaceBridges");function y(e){return e?.trim()||void 0}r(y,"normalizedConfigString");function b(e){return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}r(b,"configNumberString");function T(e){return e===void 0?void 0:e?"1":"0"}r(T,"configBooleanString");function Gt(e){return e?.filter(t=>t.trim().length>0).join(",")}r(Gt,"configStringList");var Fn=[...pe.map(({configPath:e,env:t})=>({configPath:e,env:t}))];function Ht(e){Wt(e)}r(Ht,"applyConfigEnvironment");function Xn(e,t=!1){for(let n of pe)["fallbackProviders","stallLog"].includes(n.configPath)&&(t&&!Object.hasOwn(e,n.configPath)||Be(n.env,n.value(e),t))}r(Xn,"applyExecutionConfigEnvironment");function Un(){_t();let e=fe();return Ht(e),At(e),Oe(e.locale),e}r(Un,"prepareRuntimeConfig");function qn(e){let{extensions:t,mcpServers:n,...o}=e;if(x(p,()=>{let i={};if(m.existsSync(p))try{let a=JSON.parse(m.readFileSync(p,"utf8"));a&&typeof a=="object"&&!Array.isArray(a)&&(i=a)}catch{}let s={...i,...o};for(let a of Object.keys(o))o[a]===void 0&&delete s[a];m.writeFileSync(p,JSON.stringify(s,null,2))}),t!==void 0){let i=q(u);I({domain:"extensions",configHome:u,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,paths:le(t)??[]},validate:C})}if(n!==void 0){let i=U(u);I({domain:"mcp",configHome:u,...i.source==="user"?{expectedRevision:i.revision}:{},document:{version:1,servers:n},validate:S})}}r(qn,"saveConfig");function Wn(e,t,n){return e.effort!==void 0||B(n).kind==="value"||t.effort!==void 0}r(Wn,"resolveInitialEffortOverride");function w(e){return e?.trim()?e:void 0}r(w,"nonEmptySelection");function Gn(e){return w(e.explicitProvider)??w(e.environmentProvider)??w(e.configuredProvider)??e.defaultProvider}r(Gn,"resolveRuntimeProviderSelection");function Hn(e){let t=w(e.explicitModel);if(t)return t;let n=w(e.configuredModel);if(!n)return;let o=w(e.explicitProvider)??w(e.environmentProvider);return o?w(e.configuredProvider)===o?n:void 0:n}r(Hn,"resolveRuntimeModelSelection");function Vn(e){if(e.explicitEffort!==void 0)return z(e.explicitEffort);let t=B(e.environmentEffort);return t.kind==="value"?t.value:e.configuredEffort===void 0?void 0:z(e.configuredEffort)}r(Vn,"resolveRuntimeEffortSelection");function Vt(e){return e.permissionMode==="plan"&&e.effortOverride!==!0&&e.planModeEffort!==void 0?e.planModeEffort:e.effort}r(Vt,"resolvePermissionModeEffort");async function zn(e){try{await Ce({cwd:e});let{stdout:t}=await Pt("git rev-parse --show-toplevel",{cwd:e,windowsHide:!0});return t.trim()}catch{return null}}r(zn,"getGitRoot");function zt(e){switch(e){case"builtin":return"Built-in";case"runtime":return"Runtime extension";case"custom":return"Custom config";default:return"Unknown"}}r(zt,"formatProviderSourceKind");function Bn(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: ${zt(e.sourceKind)}`,`Transport: ${t}`,`Conversation semantics: ${n}`,`Context fidelity: ${e.contextFidelity}`,`Tool calling: ${e.toolCallingFidelity}`,`Session behavior: ${e.sessionSupport}`,`Long-running support: ${e.longRunningSupport}`,`Evidence-heavy flows: ${e.evidenceSupport}`,`Multimodal support: ${e.multimodalSupport}`,`MCP support: ${e.mcpSupport}`,`Reasoning control: ${Kt(e.reasoningCapability)}`]}r(Bn,"formatProviderCapabilityDetailLines");function Jn(e,t,n){return[{label:"General coding",hints:{}},{label:"Evidence-heavy review",hints:{evidenceHeavy:!0}},{label:"Long-running task",hints:{longRunning:!0}}].map(i=>({label:i.label,decision:$t(e,t,n,i.hints)})).filter(i=>i.decision!==null)}r(Jn,"getProviderCommonPolicyScenarios");var Ge=.5,He=0,D={locked:!1,queue:[]};async function Yn(e){for(;D.locked;)await new Promise(t=>D.queue.push(t));D.locked=!0;try{let t=(Date.now()-He)/1e3;t<Ge&&await new Promise(o=>setTimeout(o,(Ge-t)*1e3));let n=await e();return He=Date.now(),n}finally{D.locked=!1;let t=D.queue.shift();t&&t()}}r(Yn,"rateLimitedCall");export{Bt as a,Re as b,Ie as c,ee as d,ot as e,x as f,k as g,S as h,C as i,M as j,U as k,q as l,pt as m,ln as n,I as o,Ne as p,u as q,kn as r,p as s,Sn as t,Mt as u,Cn as v,At as w,It as x,Mn as y,Tt as z,Dt as A,Lt as B,Nt as C,_n as D,$t as E,An as F,On as G,O as H,Rn as I,In as J,Tn as K,Dn as L,Kt as M,Ln as N,Nn as O,$n as P,fe as Q,Xt as R,ae as S,qt as T,jn as U,Kn as V,Fn as W,Ht as X,Xn as Y,Un as Z,qn as _,Wn as $,Gn as aa,Hn as ba,Vn as ca,Vt as da,zn as ea,zt as fa,Bn as ga,Jn as ha,Yn as ia};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{a as hn,b as vn,c as Le,d as xn,e as kn,f as En,g as cr,h as Rn,k as en,l as lr,m as ur,n as fr,o as nn,p as wr}from"./chunk-PRQEFTX5.js";import{Ka as me,Kc as dr,_a as rr,ab as tr,cb as xe,db as or,ib as Sn,kb as ke,nb as De,tb as ir,ub as sr,v as T,wb as ar}from"./chunk-UHC66D7T.js";import{a}from"./chunk-ONUPGMER.js";import{spawn as Xe,spawnSync as we}from"node:child_process";import{createHash as Je,randomInt as jt,randomUUID as B}from"node:crypto";import{once as Ut}from"node:events";import{closeSync as In,constants as dn,existsSync as Kn,fsyncSync as Ft,lstatSync as ae,mkdirSync as qr,openSync as Xr,readFileSync as Oe,readSync as Vt,readdirSync as Jr,realpathSync as K,renameSync as Kt,rmSync as fn,statSync as _e,writeFileSync as Hr,writeSync as qt}from"node:fs";import{copyFile as zr,lstat as Xt,mkdir as ne,readFile as je,realpath as Ue,rm as H,stat as cn,writeFile as Fe}from"node:fs/promises";import{createRequire as Jt}from"node:module";import{createServer as Ht}from"node:net";import U from"node:os";import l from"node:path";import{lstatSync as vt,readFileSync as xt,readdirSync as pr,realpathSync as kt}from"node:fs";import C from"node:path";import{globSync as Et}from"glob";var Rt=[".ssh",".tsh",".brev",".gnupg",".aws",".azure",".kube",".docker",".config",".npm",".pki",".terraform.d"],At=new Set(["certificatefile","controlpath","globalknownhostsfile","identityagent","identityfile","revokedhostkeys","userknownhostsfile"]);function oe(e){try{return kt.native(e).toLowerCase()}catch(r){return["ENOENT","ENOTDIR"].includes(r.code??"")||T({source:"sandbox:ssh-config",level:"warn",message:`Cannot canonicalize SSH ACL path: ${e}`,detail:r}),C.resolve(e).toLowerCase()}}a(oe,"pathKey");function gr(e,r){return r===e||r.startsWith(e.endsWith(C.sep)?e:`${e}${C.sep}`)}a(gr,"inside");function Wt(e){let r=[],n="",t;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="#"&&t===void 0)break;if(i===t){t=void 0;continue}if((i==='"'||i==="'")&&t===void 0){t=i;continue}let s=e[o+1];i==="\\"&&s!==void 0&&(['"',"'","\\"].includes(s)||t===void 0&&s===" ")?(n+=s,o+=1):/\s/.test(i)&&t===void 0?(n&&r.push(n),n=""):n+=i}return n&&r.push(n),r}a(Wt,"sshWords");function Ct(e,r,n){if(e.toLowerCase()==="none")return;if(["~","%d","${HOME}"].includes(e))return r;let t=e.replace(/^(?:~|%d|\$\{HOME\})[/\\]/,`${r}${C.sep}`);return C.isAbsolute(t)?C.resolve(t):n===void 0?void 0:C.resolve(n,t)}a(Ct,"sshPath");function An(e,r,n,t,o=0){let i=oe(e);if(t.has(i))return;if(o>=32){T({source:"sandbox:ssh-config",level:"warn",message:`SSH Include depth limit reached; dependencies beyond this config were not inspected: ${e}`});return}t.add(i);let s;try{s=xt(e,"utf8")}catch(d){if(d.code==="ENOENT")return;T({source:"sandbox:ssh-config",level:"warn",message:`Cannot inspect SSH configuration dependencies: ${e}`,detail:d});return}for(let d of s.split(/\r?\n/)){let c=Wt(d.replace(/^(\s*[^\s=]+)\s*=\s*/,"$1 ")),u=c.shift()?.toLowerCase();if(u!==void 0)for(let f of c){let p=Ct(f,r,u==="include"?C.join(r,".ssh"):void 0);if(p!==void 0)if(u==="include")for(let g of Et(p.replace(/\\/g,"/"),{nodir:!0}))n.push(g),An(g,r,n,t,o+1);else At.has(u)&&n.push(p)}}}a(An,"visitSshConfig");function de(e){let r=[];An(C.join(e,".ssh","config"),e,r,new Set);let n=oe(e),t=Rt.map(o=>C.join(e,o));for(let o of r){let i=C.relative(n,oe(o));i&&!i.startsWith(`..${C.sep}`)&&i!==".."&&!C.isAbsolute(i)&&t.push(C.join(e,i.split(C.sep)[0]))}return[...new Set(t.map(o=>C.resolve(o)))]}a(de,"windowsSandboxAclExclusions");function mr(e){let r=[];An(C.join(e,".ssh","config"),e,r,new Set);let n=[C.join(e,".ssh")];for(;n.length>0;){let t=n.pop();r.push(t);let o;try{if(vt(t).isSymbolicLink())continue;o=pr(t,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")continue;throw i}for(let i of o){if(i.isSymbolicLink())continue;let s=C.join(t,i.name);r.push(s),i.isDirectory()&&n.push(s)}}return[...new Set(r.filter(t=>gr(oe(e),oe(t))))]}a(mr,"windowsSandboxSshCleanupRoots");function Ee(e,r,n){let t=oe(r),o=n.flatMap(s=>[C.resolve(s).toLowerCase(),oe(s)]),i=e.flatMap(s=>oe(s)===t?pr(r,{withFileTypes:!0}).filter(d=>!d.isSymbolicLink()).map(d=>C.join(r,d.name)):[s]);return[...new Set(i)].filter(s=>![C.resolve(s).toLowerCase(),oe(s)].some(c=>o.some(u=>gr(u,c))))}a(Ee,"windowsSandboxAclRoots");import{fileURLToPath as _r,pathToFileURL as Yr}from"node:url";import{realpathSync as Pt,statSync as Nt}from"node:fs";import _t from"node:path";function Wn(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"}a(Wn,"isMissingGitTrustPath");function br(e,r,n){try{let t=r(e).replaceAll("\\","/").replace(/\/+$/,"");return t===""?void 0:/^[A-Za-z]:$/.test(t)?`${t}/`:t}catch(t){if(n(t))return;throw t}}a(br,"normalizeGitSafeDirectoryRootImplementation");function Tt(e){return br(e,Pt,Wn)}a(Tt,"normalizeGitSafeDirectoryRoot");function Sr(e,r,n,t){try{let i=r(n.join(e,".git"));if(i.isDirectory()||i.isFile())return!0}catch(i){if(!t(i))throw i}if(!(n.basename(e).toLowerCase()===".git"||/[/\\]\.git[/\\]modules[/\\]/i.test(e)))return!1;try{return r(n.join(e,"HEAD")).isFile()}catch(i){if(t(i))return!1;throw i}}a(Sr,"isRepoBearingGitReadRootImplementation");function Ot(e){return Sr(e,Nt,_t,Wn)}a(Ot,"isRepoBearingGitReadRoot");function hr(e,r,n,t,o){let i=[];typeof e=="string"&&e!==""&&i.push(e);for(let c of n??[])o(c)&&i.push(c);i.push(...r??[]);let s=[],d=new Set;for(let c of i){if(s.length>=8)break;let u=t(c);if(u===void 0)continue;let f=u.toLowerCase();d.has(f)||(d.add(f),s.push(u))}return s}a(hr,"windowsGitTrustRootsImplementation");function vr(e,r,n){return hr(e,r,n,Tt,Ot)}a(vr,"windowsGitTrustRoots");function xr(e){if(e==="git_config_count")return"count";if(/^git_config_key_\d+$/.test(e))return"key";if(/^git_config_value_\d+$/.test(e))return"value"}a(xr,"gitConfigEnvKind");function It(e,r,n,t,o){let i=new Map,s=[],d,c=!1;for(let u=0;u<r;u+=1){if(e[u]!=="--env"||u+1>=r)continue;let f=e[u+1],p=f.indexOf("="),g=(p<0?f:f.slice(0,p)).toLowerCase(),w=n(g);if(w===void 0)continue;c=!0,s.push(u);let m=p<0?"":f.slice(p+1);if(w==="count"){let W=Number.parseInt(m,10);(d!==void 0||!Number.isSafeInteger(W)||W<0||String(W)!==m)&&t(),d=W;continue}let S=Number.parseInt(g.slice(`git_config_${w}_`.length),10),h=i.get(S)??{};(!Number.isSafeInteger(S)||S<0||h[w]!==void 0)&&t(),h[w]=m,i.set(S,h)}return o(i,s,d,c,t)}a(It,"parseGitConfigEnvironmentImplementation");function rn(){throw new Error("ASRT GIT_CONFIG environment has an unexpected shape.")}a(rn,"throwUnexpectedGitConfigShape");function kr(e,r,n,t,o){!t||n!==void 0&&e.size===n&&[...e].every(([d,c])=>d<n&&c.key!==void 0&&c.value!==void 0)||o();let s=[...e].map(([d,c])=>({slot:d,key:c.key,value:c.value}));return{argumentIndices:r,pairs:s,sawAny:t}}a(kr,"finishParsedGitConfigEnvironment");function Er(e,r){let n=[];for(let o of e)n.push({key:"safe.directory",value:o},{key:"safe.directory",value:`${o}/*`});n.push(...r);let t=n.flatMap((o,i)=>[`GIT_CONFIG_KEY_${i}=${o.key}`,`GIT_CONFIG_VALUE_${i}=${o.value}`]);return t.push(`GIT_CONFIG_COUNT=${n.length}`),t}a(Er,"gitSafeDirectoryAssignments");function yr(e,r){let n=[],t=new Set;for(let[o,i]of Object.entries(e)){if(i===void 0)continue;if(o===""||o.includes("=")||o.includes("\0")||i.includes("\0"))throw new Error(`Invalid ${r} environment entry.`);let s=o.toUpperCase();if(t.has(s))throw new Error(`Ambiguous ${r} environment variable: ${o}.`);t.add(s),n.push([o,i])}return n}a(yr,"validatedEnvironmentEntries");function Dt(e,r){let n=new Map,t=[],o,i=!1;for(let[u,f]of Object.entries(e)){let p=u.toLowerCase(),g=xr(p);if(g===void 0){t.push([u,f]);continue}if(i=!0,g==="count"){let S=Number.parseInt(f,10);(o!==void 0||!Number.isSafeInteger(S)||S<0||String(S)!==f)&&rn(),o=S;continue}let w=Number.parseInt(p.slice(`git_config_${g}_`.length),10),m=n.get(w)??{};(!Number.isSafeInteger(w)||w<0||m[g]!==void 0)&&rn(),m[g]=f,n.set(w,m)}let d=kr(n,[],o,i,rn).pairs.filter(u=>u.key.toLowerCase()!=="safe.directory").sort((u,f)=>u.slot-f.slot),c=Object.fromEntries(t);for(let u of Er(r,d)){let f=u.indexOf("=");c[u.slice(0,f)]=u.slice(f+1)}return c}a(Dt,"rewriteWindowsGitSafeDirectoryEnvironment");function Rr(e,r,n){let t=yr(e,"ASRT-controlled"),o=yr(r,"Windows target"),i=new Map;for(let s of t)i.set(s[0].toUpperCase(),s);for(let s of o){let d=s[0].toUpperCase();i.has(d)&&d!=="PATH"&&d!=="PATHEXT"||i.set(d,s)}return Dt(Object.fromEntries(i.values()),n)}a(Rr,"mergeWindowsSandboxTargetEnvironment");function Lt(e,r,n,t){let o=new Set(n.argumentIndices),i=[],s=!1;for(let d=0;d<e.length;d+=1)if(o.has(d)){if(!s){for(let c of t)i.push("--env",c);s=!0}d+=1}else i.push(e[d]);return n.sawAny||i.splice(r,0,...t.flatMap(d=>["--env",d])),i}a(Lt,"replaceGitConfigEnvironment");function Bt(e,r,n,t,o){let i=e.lastIndexOf("--");if(i<0)throw new Error("ASRT Windows wrapper omitted its child separator.");let s=n(e,i),d=s.pairs.filter(u=>u.key.toLowerCase()!=="safe.directory").sort((u,f)=>u.slot-f.slot),c=t(r,d);return o(e,i,s,c)}a(Bt,"rewriteWindowsGitSafeDirectoryArgvImplementation");function Ar(){return String.raw`
2
+ import{a as hn,b as vn,c as Le,d as xn,e as kn,f as En,g as cr,h as Rn,k as en,l as lr,m as ur,n as fr,o as nn,p as wr}from"./chunk-PV6DILEK.js";import{Ka as me,Lc as dr,_a as rr,ab as tr,cb as xe,db as or,ib as Sn,lb as ke,ob as De,ub as ir,v as T,vb as sr,xb as ar}from"./chunk-XMWTEVFZ.js";import{a}from"./chunk-ONUPGMER.js";import{spawn as Xe,spawnSync as we}from"node:child_process";import{createHash as Je,randomInt as jt,randomUUID as B}from"node:crypto";import{once as Ut}from"node:events";import{closeSync as In,constants as dn,existsSync as Kn,fsyncSync as Ft,lstatSync as ae,mkdirSync as qr,openSync as Xr,readFileSync as Oe,readSync as Vt,readdirSync as Jr,realpathSync as K,renameSync as Kt,rmSync as fn,statSync as _e,writeFileSync as Hr,writeSync as qt}from"node:fs";import{copyFile as zr,lstat as Xt,mkdir as ne,readFile as je,realpath as Ue,rm as H,stat as cn,writeFile as Fe}from"node:fs/promises";import{createRequire as Jt}from"node:module";import{createServer as Ht}from"node:net";import U from"node:os";import l from"node:path";import{lstatSync as vt,readFileSync as xt,readdirSync as pr,realpathSync as kt}from"node:fs";import C from"node:path";import{globSync as Et}from"glob";var Rt=[".ssh",".tsh",".brev",".gnupg",".aws",".azure",".kube",".docker",".config",".npm",".pki",".terraform.d"],At=new Set(["certificatefile","controlpath","globalknownhostsfile","identityagent","identityfile","revokedhostkeys","userknownhostsfile"]);function oe(e){try{return kt.native(e).toLowerCase()}catch(r){return["ENOENT","ENOTDIR"].includes(r.code??"")||T({source:"sandbox:ssh-config",level:"warn",message:`Cannot canonicalize SSH ACL path: ${e}`,detail:r}),C.resolve(e).toLowerCase()}}a(oe,"pathKey");function gr(e,r){return r===e||r.startsWith(e.endsWith(C.sep)?e:`${e}${C.sep}`)}a(gr,"inside");function Wt(e){let r=[],n="",t;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="#"&&t===void 0)break;if(i===t){t=void 0;continue}if((i==='"'||i==="'")&&t===void 0){t=i;continue}let s=e[o+1];i==="\\"&&s!==void 0&&(['"',"'","\\"].includes(s)||t===void 0&&s===" ")?(n+=s,o+=1):/\s/.test(i)&&t===void 0?(n&&r.push(n),n=""):n+=i}return n&&r.push(n),r}a(Wt,"sshWords");function Ct(e,r,n){if(e.toLowerCase()==="none")return;if(["~","%d","${HOME}"].includes(e))return r;let t=e.replace(/^(?:~|%d|\$\{HOME\})[/\\]/,`${r}${C.sep}`);return C.isAbsolute(t)?C.resolve(t):n===void 0?void 0:C.resolve(n,t)}a(Ct,"sshPath");function An(e,r,n,t,o=0){let i=oe(e);if(t.has(i))return;if(o>=32){T({source:"sandbox:ssh-config",level:"warn",message:`SSH Include depth limit reached; dependencies beyond this config were not inspected: ${e}`});return}t.add(i);let s;try{s=xt(e,"utf8")}catch(d){if(d.code==="ENOENT")return;T({source:"sandbox:ssh-config",level:"warn",message:`Cannot inspect SSH configuration dependencies: ${e}`,detail:d});return}for(let d of s.split(/\r?\n/)){let c=Wt(d.replace(/^(\s*[^\s=]+)\s*=\s*/,"$1 ")),u=c.shift()?.toLowerCase();if(u!==void 0)for(let f of c){let p=Ct(f,r,u==="include"?C.join(r,".ssh"):void 0);if(p!==void 0)if(u==="include")for(let g of Et(p.replace(/\\/g,"/"),{nodir:!0}))n.push(g),An(g,r,n,t,o+1);else At.has(u)&&n.push(p)}}}a(An,"visitSshConfig");function de(e){let r=[];An(C.join(e,".ssh","config"),e,r,new Set);let n=oe(e),t=Rt.map(o=>C.join(e,o));for(let o of r){let i=C.relative(n,oe(o));i&&!i.startsWith(`..${C.sep}`)&&i!==".."&&!C.isAbsolute(i)&&t.push(C.join(e,i.split(C.sep)[0]))}return[...new Set(t.map(o=>C.resolve(o)))]}a(de,"windowsSandboxAclExclusions");function mr(e){let r=[];An(C.join(e,".ssh","config"),e,r,new Set);let n=[C.join(e,".ssh")];for(;n.length>0;){let t=n.pop();r.push(t);let o;try{if(vt(t).isSymbolicLink())continue;o=pr(t,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")continue;throw i}for(let i of o){if(i.isSymbolicLink())continue;let s=C.join(t,i.name);r.push(s),i.isDirectory()&&n.push(s)}}return[...new Set(r.filter(t=>gr(oe(e),oe(t))))]}a(mr,"windowsSandboxSshCleanupRoots");function Ee(e,r,n){let t=oe(r),o=n.flatMap(s=>[C.resolve(s).toLowerCase(),oe(s)]),i=e.flatMap(s=>oe(s)===t?pr(r,{withFileTypes:!0}).filter(d=>!d.isSymbolicLink()).map(d=>C.join(r,d.name)):[s]);return[...new Set(i)].filter(s=>![C.resolve(s).toLowerCase(),oe(s)].some(c=>o.some(u=>gr(u,c))))}a(Ee,"windowsSandboxAclRoots");import{fileURLToPath as _r,pathToFileURL as Yr}from"node:url";import{realpathSync as Pt,statSync as Nt}from"node:fs";import _t from"node:path";function Wn(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"}a(Wn,"isMissingGitTrustPath");function br(e,r,n){try{let t=r(e).replaceAll("\\","/").replace(/\/+$/,"");return t===""?void 0:/^[A-Za-z]:$/.test(t)?`${t}/`:t}catch(t){if(n(t))return;throw t}}a(br,"normalizeGitSafeDirectoryRootImplementation");function Tt(e){return br(e,Pt,Wn)}a(Tt,"normalizeGitSafeDirectoryRoot");function Sr(e,r,n,t){try{let i=r(n.join(e,".git"));if(i.isDirectory()||i.isFile())return!0}catch(i){if(!t(i))throw i}if(!(n.basename(e).toLowerCase()===".git"||/[/\\]\.git[/\\]modules[/\\]/i.test(e)))return!1;try{return r(n.join(e,"HEAD")).isFile()}catch(i){if(t(i))return!1;throw i}}a(Sr,"isRepoBearingGitReadRootImplementation");function Ot(e){return Sr(e,Nt,_t,Wn)}a(Ot,"isRepoBearingGitReadRoot");function hr(e,r,n,t,o){let i=[];typeof e=="string"&&e!==""&&i.push(e);for(let c of n??[])o(c)&&i.push(c);i.push(...r??[]);let s=[],d=new Set;for(let c of i){if(s.length>=8)break;let u=t(c);if(u===void 0)continue;let f=u.toLowerCase();d.has(f)||(d.add(f),s.push(u))}return s}a(hr,"windowsGitTrustRootsImplementation");function vr(e,r,n){return hr(e,r,n,Tt,Ot)}a(vr,"windowsGitTrustRoots");function xr(e){if(e==="git_config_count")return"count";if(/^git_config_key_\d+$/.test(e))return"key";if(/^git_config_value_\d+$/.test(e))return"value"}a(xr,"gitConfigEnvKind");function It(e,r,n,t,o){let i=new Map,s=[],d,c=!1;for(let u=0;u<r;u+=1){if(e[u]!=="--env"||u+1>=r)continue;let f=e[u+1],p=f.indexOf("="),g=(p<0?f:f.slice(0,p)).toLowerCase(),w=n(g);if(w===void 0)continue;c=!0,s.push(u);let m=p<0?"":f.slice(p+1);if(w==="count"){let W=Number.parseInt(m,10);(d!==void 0||!Number.isSafeInteger(W)||W<0||String(W)!==m)&&t(),d=W;continue}let S=Number.parseInt(g.slice(`git_config_${w}_`.length),10),h=i.get(S)??{};(!Number.isSafeInteger(S)||S<0||h[w]!==void 0)&&t(),h[w]=m,i.set(S,h)}return o(i,s,d,c,t)}a(It,"parseGitConfigEnvironmentImplementation");function rn(){throw new Error("ASRT GIT_CONFIG environment has an unexpected shape.")}a(rn,"throwUnexpectedGitConfigShape");function kr(e,r,n,t,o){!t||n!==void 0&&e.size===n&&[...e].every(([d,c])=>d<n&&c.key!==void 0&&c.value!==void 0)||o();let s=[...e].map(([d,c])=>({slot:d,key:c.key,value:c.value}));return{argumentIndices:r,pairs:s,sawAny:t}}a(kr,"finishParsedGitConfigEnvironment");function Er(e,r){let n=[];for(let o of e)n.push({key:"safe.directory",value:o},{key:"safe.directory",value:`${o}/*`});n.push(...r);let t=n.flatMap((o,i)=>[`GIT_CONFIG_KEY_${i}=${o.key}`,`GIT_CONFIG_VALUE_${i}=${o.value}`]);return t.push(`GIT_CONFIG_COUNT=${n.length}`),t}a(Er,"gitSafeDirectoryAssignments");function yr(e,r){let n=[],t=new Set;for(let[o,i]of Object.entries(e)){if(i===void 0)continue;if(o===""||o.includes("=")||o.includes("\0")||i.includes("\0"))throw new Error(`Invalid ${r} environment entry.`);let s=o.toUpperCase();if(t.has(s))throw new Error(`Ambiguous ${r} environment variable: ${o}.`);t.add(s),n.push([o,i])}return n}a(yr,"validatedEnvironmentEntries");function Dt(e,r){let n=new Map,t=[],o,i=!1;for(let[u,f]of Object.entries(e)){let p=u.toLowerCase(),g=xr(p);if(g===void 0){t.push([u,f]);continue}if(i=!0,g==="count"){let S=Number.parseInt(f,10);(o!==void 0||!Number.isSafeInteger(S)||S<0||String(S)!==f)&&rn(),o=S;continue}let w=Number.parseInt(p.slice(`git_config_${g}_`.length),10),m=n.get(w)??{};(!Number.isSafeInteger(w)||w<0||m[g]!==void 0)&&rn(),m[g]=f,n.set(w,m)}let d=kr(n,[],o,i,rn).pairs.filter(u=>u.key.toLowerCase()!=="safe.directory").sort((u,f)=>u.slot-f.slot),c=Object.fromEntries(t);for(let u of Er(r,d)){let f=u.indexOf("=");c[u.slice(0,f)]=u.slice(f+1)}return c}a(Dt,"rewriteWindowsGitSafeDirectoryEnvironment");function Rr(e,r,n){let t=yr(e,"ASRT-controlled"),o=yr(r,"Windows target"),i=new Map;for(let s of t)i.set(s[0].toUpperCase(),s);for(let s of o){let d=s[0].toUpperCase();i.has(d)&&d!=="PATH"&&d!=="PATHEXT"||i.set(d,s)}return Dt(Object.fromEntries(i.values()),n)}a(Rr,"mergeWindowsSandboxTargetEnvironment");function Lt(e,r,n,t){let o=new Set(n.argumentIndices),i=[],s=!1;for(let d=0;d<e.length;d+=1)if(o.has(d)){if(!s){for(let c of t)i.push("--env",c);s=!0}d+=1}else i.push(e[d]);return n.sawAny||i.splice(r,0,...t.flatMap(d=>["--env",d])),i}a(Lt,"replaceGitConfigEnvironment");function Bt(e,r,n,t,o){let i=e.lastIndexOf("--");if(i<0)throw new Error("ASRT Windows wrapper omitted its child separator.");let s=n(e,i),d=s.pairs.filter(u=>u.key.toLowerCase()!=="safe.directory").sort((u,f)=>u.slot-f.slot),c=t(r,d);return o(e,i,s,c)}a(Bt,"rewriteWindowsGitSafeDirectoryArgvImplementation");function Ar(){return String.raw`
3
3
  const isMissingGitTrustPath = ${Wn.toString()};
4
4
  const normalizeGitSafeDirectoryRootImplementation = ${br.toString()};
5
5
  const normalizeGitSafeDirectoryRoot = (root) => (
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{K as W,a as c,da as G,z as j}from"./chunk-MWIDZ2GQ.js";import{wa as x,ya as O}from"./chunk-RRCIJ234.js";import{a as o}from"./chunk-ONUPGMER.js";import*as Q from"child_process";import*as v from"path";import*as R from"fs";import*as Z from"os";import h from"chalk";import f from"chalk";var ee=100,te=/\b(curl|wget|invoke-webrequest|invoke-restmethod|iwr|irm)\b/i,U=/\b(rm|del|erase|remove-item|rmdir|rd|git clean)\b/i,Y=/\b(npm|pnpm|yarn|pip|choco|winget)\s+(install|add|remove|uninstall|update|upgrade|ci)\b/i,K=/\b(set-content|add-content|out-file|new-item|copy-item|move-item|rename-item|cp|mv|copy|move|ren|touch)\b/i;function $(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}o($,"readString");function d(e,t,n){n&&e.push({label:t,value:n})}o(d,"pushField");function ne(e){return e.replace(/\s+/g," ").trim()}o(ne,"normalizeWhitespace");function re(e,t){if(e.length<=t)return e;let n=Math.ceil((t-3)/2),r=Math.floor((t-3)/2);return`${e.slice(0,n)}...${e.slice(e.length-r)}`}o(re,"truncateMiddle");function oe(e){let t=e;return t=t.replace(/\b(authorization\s*:\s*bearer\s+)([^\s'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b((?:authorization|cookie)\s*:\s*)([^'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b(bearer\s+)([^\s'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|cookie|session)\b(\s*[:=]\s*)(['"]?)([^'"\s]+)(\3)/gi,(n,r,s,i)=>`${r}${s}${i}[REDACTED]${i}`),t=t.replace(/(--(?:api-key|token|secret|password|cookie)\s+)(\S+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/((?:-u|--user)\s+)(\S+)/gi,(n,r)=>`${r}[REDACTED]`),t}o(oe,"maskSensitiveSegments");function B(e){return re(oe(ne(e)),ee)}o(B,"summarizeCommand");function se(e){return x(e)?c("intent.read"):U.test(e)?c("intent.delete"):Y.test(e)?c("intent.deps"):O(e)||K.test(e)?c("intent.modify"):c("intent.execute")}o(se,"classifyShellIntent");function ie(e){let t=[];return U.test(e)?t.push(c("risk.destructive")):Y.test(e)?t.push(c("risk.deps")):O(e)||K.test(e)?t.push(c("risk.modify")):x(e)||t.push(c("risk.unknown")),te.test(e)&&t.push(c("risk.network")),t}o(ie,"classifyShellRisks");function ce(e){if(Array.isArray(e))return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.kind=="string")}o(ce,"readSignals");function ue(e){if(e){if(e.some(t=>t.kind==="protected_path"))return c("scope.protected");if(e.some(t=>t.kind==="outside_project"||t.kind==="shell_redirect_outside"))return c("scope.outside")}}o(ue,"scopeFromSignals");function ae(e){if(e._outsideProject===!0)return c("scope.outside");if(e._alwaysConfirm===!0)return c("scope.protected")}o(ae,"scopeFromMarkers");function le(e){if(!e)return[];let t=[],n=e.some(s=>s.kind==="dangerous_pattern"&&s.severity==="high"),r=e.some(s=>s.kind==="dangerous_pattern"&&s.severity==="medium");return n?t.push(c("risk.destructive")):r&&t.push(c("risk.modify")),e.some(s=>s.kind==="network")&&t.push(c("risk.network")),e.some(s=>s.kind==="package_install")&&t.push(c("risk.deps")),t}o(le,"risksFromSignals");var de={Reason:"field.reason",Intent:"field.intent",Target:"field.target",Scope:"field.scope",Risk:"field.risk",Summary:"field.summary"};function fe(e){return c(de[e])}o(fe,"localizeFieldLabel");function C(e,t){return{title:e,fields:t,details:t.map(n=>`${fe(n.label)}: ${n.value}`)}}o(C,"buildDisplayFromFields");function A(e,t){if(e==="confirm"){let l=$(t._message);if(l)return C(l,[])}if(e==="exit_plan_mode"){let l=$(t.plan),y="Approve plan? (exits plan mode \u2192 accept-edits)";return l?{title:y,fields:[],details:l.split(`
2
+ import{K as W,a as c,da as G,z as j}from"./chunk-5DF2ZZDA.js";import{wa as x,ya as O}from"./chunk-TXCU25XM.js";import{a as o}from"./chunk-ONUPGMER.js";import*as Q from"child_process";import*as v from"path";import*as R from"fs";import*as Z from"os";import h from"chalk";import f from"chalk";var ee=100,te=/\b(curl|wget|invoke-webrequest|invoke-restmethod|iwr|irm)\b/i,U=/\b(rm|del|erase|remove-item|rmdir|rd|git clean)\b/i,Y=/\b(npm|pnpm|yarn|pip|choco|winget)\s+(install|add|remove|uninstall|update|upgrade|ci)\b/i,K=/\b(set-content|add-content|out-file|new-item|copy-item|move-item|rename-item|cp|mv|copy|move|ren|touch)\b/i;function $(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}o($,"readString");function d(e,t,n){n&&e.push({label:t,value:n})}o(d,"pushField");function ne(e){return e.replace(/\s+/g," ").trim()}o(ne,"normalizeWhitespace");function re(e,t){if(e.length<=t)return e;let n=Math.ceil((t-3)/2),r=Math.floor((t-3)/2);return`${e.slice(0,n)}...${e.slice(e.length-r)}`}o(re,"truncateMiddle");function oe(e){let t=e;return t=t.replace(/\b(authorization\s*:\s*bearer\s+)([^\s'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b((?:authorization|cookie)\s*:\s*)([^'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b(bearer\s+)([^\s'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|cookie|session)\b(\s*[:=]\s*)(['"]?)([^'"\s]+)(\3)/gi,(n,r,s,i)=>`${r}${s}${i}[REDACTED]${i}`),t=t.replace(/(--(?:api-key|token|secret|password|cookie)\s+)(\S+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/((?:-u|--user)\s+)(\S+)/gi,(n,r)=>`${r}[REDACTED]`),t}o(oe,"maskSensitiveSegments");function B(e){return re(oe(ne(e)),ee)}o(B,"summarizeCommand");function se(e){return x(e)?c("intent.read"):U.test(e)?c("intent.delete"):Y.test(e)?c("intent.deps"):O(e)||K.test(e)?c("intent.modify"):c("intent.execute")}o(se,"classifyShellIntent");function ie(e){let t=[];return U.test(e)?t.push(c("risk.destructive")):Y.test(e)?t.push(c("risk.deps")):O(e)||K.test(e)?t.push(c("risk.modify")):x(e)||t.push(c("risk.unknown")),te.test(e)&&t.push(c("risk.network")),t}o(ie,"classifyShellRisks");function ce(e){if(Array.isArray(e))return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.kind=="string")}o(ce,"readSignals");function ue(e){if(e){if(e.some(t=>t.kind==="protected_path"))return c("scope.protected");if(e.some(t=>t.kind==="outside_project"||t.kind==="shell_redirect_outside"))return c("scope.outside")}}o(ue,"scopeFromSignals");function ae(e){if(e._outsideProject===!0)return c("scope.outside");if(e._alwaysConfirm===!0)return c("scope.protected")}o(ae,"scopeFromMarkers");function le(e){if(!e)return[];let t=[],n=e.some(s=>s.kind==="dangerous_pattern"&&s.severity==="high"),r=e.some(s=>s.kind==="dangerous_pattern"&&s.severity==="medium");return n?t.push(c("risk.destructive")):r&&t.push(c("risk.modify")),e.some(s=>s.kind==="network")&&t.push(c("risk.network")),e.some(s=>s.kind==="package_install")&&t.push(c("risk.deps")),t}o(le,"risksFromSignals");var de={Reason:"field.reason",Intent:"field.intent",Target:"field.target",Scope:"field.scope",Risk:"field.risk",Summary:"field.summary"};function fe(e){return c(de[e])}o(fe,"localizeFieldLabel");function C(e,t){return{title:e,fields:t,details:t.map(n=>`${fe(n.label)}: ${n.value}`)}}o(C,"buildDisplayFromFields");function A(e,t){if(e==="confirm"){let l=$(t._message);if(l)return C(l,[])}if(e==="exit_plan_mode"){let l=$(t.plan),y="Approve plan? (exits plan mode \u2192 accept-edits)";return l?{title:y,fields:[],details:l.split(`
3
3
  `)}:C(y,[])}let n=[],r=$(t.path),s=$(t.command),i=$(t._reason)??$(t.justification),u=ce(t._classifierSignals),a=ue(u)??ae(t);switch(d(n,"Reason",i),e){case"bash":case"shell_command":{if(s){d(n,"Intent",se(s)),d(n,"Scope",a);let l=le(u),y=l.length>0?l:ie(s);y.length>0&&d(n,"Risk",y.join("; ")),d(n,"Summary",B(s))}else d(n,"Scope",a);return C(e==="bash"?c("tool.bash.title"):c("tool.shell.title"),n)}case"write":return d(n,"Intent",c("intent.write_file")),d(n,"Target",r),d(n,"Scope",a),C(c("tool.write.title"),n);case"edit":return d(n,"Intent",c("intent.edit_file")),d(n,"Target",r),d(n,"Scope",a),C(c("tool.edit.title"),n);default:return d(n,"Intent",c("intent.use_tool",{tool:e})),d(n,"Target",r),d(n,"Scope",a),s&&d(n,"Summary",B(s)),C(c("tool.generic.title",{tool:e}),n)}}o(A,"buildToolConfirmationDisplay");function Pe(e,t){let n=A(e,t);return n.details.length>0?`${n.title}
4
4
  ${n.details.join(`
5
5
  `)}`:n.title}o(Pe,"buildToolConfirmationPrompt");var z="Runtime state: run active until this approval is resolved.";function Fe(e,t){if(!t.confirmed)return{type:"reject",reason:"User rejected the tool call."};if(t.runtimeGrantKind===void 0)return{type:"allow_once"};let n=e.grantSuggestions?.find(r=>r.kind===t.runtimeGrantKind);return n?t.runtimeGrantKind==="session"?{type:"allow_session",suggestionId:n.id}:{type:"allow_always",suggestionId:n.id}:{type:"reject",reason:"Runtime grant suggestion expired."}}o(Fe,"resolveReplRuntimePermissionDecision");function Le(e){let t=e.classifierModelEnv??e.classifierModel;return{...t!==void 0?{classifierModel:t}:{},...e.reviewPolicy!==void 0?{reviewPolicy:e.reviewPolicy}:{}}}o(Le,"toReplRuntimeAutoModeSettings");import*as H from"child_process";var E;function pe(){if(process.platform!=="win32")return null;if(E!==void 0)return E;try{E=H.execFileSync(process.env.ComSpec??"cmd.exe",["/d","/s","/c","chcp"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).match(/(\d{3,5})/)?.[1]??null}catch{E=null}return E}o(pe,"detectWindowsCodePage");function P(){let e=process.env;return!!(e.COLORTERM==="truecolor"||e.COLORTERM==="24bit"||e.TERM_PROGRAM==="iTerm.app"||e.WT_SESSION||e.TERM==="xterm-kitty"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="gnome-terminal")}o(P,"supportsTrueColor");function me(){if(P())return!0;let e=process.env.TERM||"";return e.includes("256color")||e==="xterm-256color"||e==="screen-256color"||e==="tmux-256color"}o(me,"supports256Colors");function w(){let e=process.env,t=e.LC_ALL||"",n=e.LC_CTYPE||"",r=e.LANG||"";if(t==="C"||t==="POSIX"||n==="C"||n==="POSIX"||r==="C"||r==="POSIX")return!1;let s=`${t}|${n}|${r}`.toLowerCase();return s.includes("utf-8")||s.includes("utf8")?!0:process.platform==="win32"?e.WT_SESSION||e.TERM_PROGRAM==="vscode"?!0:pe()==="65001":!0}o(w,"supportsUnicode");function he(){let e=process.env;return!!(e.TERM_PROGRAM==="iTerm.app"||e.WT_SESSION||e.TERM==="xterm-kitty"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="Apple_Terminal"||e.TERM_PROGRAM==="gnome-terminal"||e.COLORTERM)}o(he,"supportsEmoji");function ye(){if(process.stdout?.columns)return process.stdout.columns;let t=process.env.COLUMNS;if(t){let n=Number.parseInt(t,10);if(!Number.isNaN(n)&&n>0)return n}return 80}o(ye,"getTerminalWidth");function ge(){let e=process.env;return!!(e.NO_COLOR||e.TERM==="dumb"||e.CI)}o(ge,"isScreenReader");function we(){return process.stdout?.isTTY??!1}o(we,"isTTY");function We(){return{trueColor:P(),colors256:me(),unicode:w(),emoji:he(),tty:we(),columns:ye(),screenReader:ge()}}o(We,"detectTerminalCapabilities");var ke=[{key:"y",label:"Yes",description:"Confirm the action",value:"yes"},{key:"n",label:"No",description:"Cancel the action",value:"no"}],be=[{key:"y",label:"Yes",description:"Allow this once",value:"yes"},{key:"n",label:"No",description:"Cancel",value:"no"},{key:"a",label:"Always",description:"Always allow this kind of action",value:"always"}];function Te(e,t=!0){return e.map(n=>{let r=f.dim(`[${n.key}]`);return t?`${r} ${f.cyan(n.label)} ${f.dim(`- ${n.description}`)}`:`${r} ${n.label}`}).join(" ")}o(Te,"formatOptions");function N(){return process.stdout.columns??80}o(N,"getTerminalWidth");function $e(){return w()}o($e,"supportsUnicode");function Ce(){let e=$e();return{success:e?"\u2713":"[OK]",error:e?"\u2717":"[X]",warning:e?"\u26A0":"[!]",info:e?"\u2139":"[i]",arrow:e?"\u2192":"->",bullet:e?"\u2022":"*",check:e?"\u2713":"[v]",cross:e?"\u2717":"[x]"}}o(Ce,"getSymbols");async function Se(e,t){let{message:n,default:r,options:s,showDescription:i=!0,signal:u}=t,a=s??ke,l=Te(a,i);console.log(),console.log(f.cyan(`? ${n}`));let y=N();if(l.length>y-4)for(let p of a){let g=f.dim(` [${p.key}]`);console.log(`${g} ${f.cyan(p.label)}`),i&&console.log(f.dim(` ${p.description}`))}else console.log(f.dim(` ${l}`));return u?.aborted?"no":new Promise(p=>{let g=r?` (${r})`:"",_=!1,k=o(m=>{_||(_=!0,u?.removeEventListener("abort",b),p(m))},"finish"),b=o(()=>k("no"),"onAbort"),T=o(m=>{let S=m.trim().toLowerCase()||r||"",D=a.find(M=>M.key===S||M.value===S||M.label.toLowerCase()===S);k(D?D.value:S===""?"no":S)},"onAnswer");u?.addEventListener("abort",b,{once:!0}),u?e.question(f.dim(` Choose${g}: `),{signal:u},T):e.question(f.dim(` Choose${g}: `),T)})}o(Se,"confirmEnhanced");async function He(e,t,n,r){let{isOutsideProject:s=!1,isProtectedPath:i=!1,permissionMode:u="accept-edits",runtimeGrantSuggestions:a,signal:l}=r??{},y=Ce(),p,g,_={...n,...s?{_outsideProject:!0}:{},...i?{_alwaysConfirm:!0}:{}},k=A(t,_),b=k.details.map(m=>` ${f.dim(m)}`);s||i?(p=`${f.yellow(y.warning)} Safety Warning`,b.length>0&&(p+=`