@kodax-ai/kodax 0.7.60 → 0.7.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -1
- package/README.md +2 -0
- package/README_CN.md +2 -0
- package/dist/chunks/{agent-L5FC3YOY.js → agent-E74WVAFR.js} +1 -1
- package/dist/chunks/argument-completer-BBFYCVTM.js +2 -0
- package/dist/chunks/{chunk-5TRQBMPR.js → chunk-2OEKUAV4.js} +1 -1
- package/dist/chunks/{chunk-ZPD7IUKW.js → chunk-4NSOBQCU.js} +1 -1
- package/dist/chunks/{chunk-QFCF3GNT.js → chunk-7COB3EKF.js} +171 -156
- package/dist/chunks/chunk-CGGX3FXE.js +19 -0
- package/dist/chunks/{chunk-6DWXUZMO.js → chunk-D7CC6YZC.js} +198 -198
- package/dist/chunks/{chunk-SGNM3UP6.js → chunk-KIVYMSRH.js} +1 -1
- package/dist/chunks/chunk-NJW2LQOP.js +722 -0
- package/dist/chunks/{chunk-IJN6ZJVI.js → chunk-PJXKBM3Y.js} +4 -4
- package/dist/chunks/{chunk-2RLIKZOZ.js → chunk-QCBKLNN5.js} +2 -2
- package/dist/chunks/{chunk-XULI4U7I.js → chunk-XHOPSZVL.js} +1 -1
- package/dist/chunks/{compaction-config-E4LN3M53.js → compaction-config-GESEZQVA.js} +1 -1
- package/dist/chunks/{construction-bootstrap-GIFDM4L5.js → construction-bootstrap-OSXHEIBB.js} +1 -1
- package/dist/chunks/{dist-7PXDYX2R.js → dist-W3OOJP66.js} +1 -1
- package/dist/chunks/host-FRQXOEHH.js +2 -0
- package/dist/chunks/{run-manager-IU5COC6X.js → run-manager-FGCG7DFF.js} +1 -1
- package/dist/chunks/{utils-NP42DKL3.js → utils-47QI5MSP.js} +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/kodax_cli.js +927 -909
- package/dist/sdk-agent.d.ts +2 -2
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +6 -4
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-repl.d.ts +6 -6
- package/dist/sdk-repl.js +1 -1
- package/dist/sdk-session.d.ts +3 -3
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/types-chunks/{bash-prefix-extractor.d-Ds1THKeH.d.ts → bash-prefix-extractor.d-e1LD2IRl.d.ts} +7 -0
- package/dist/types-chunks/{run-manager.d-DLK3ed-T.d.ts → run-manager.d-DHPlNYkK.d.ts} +16 -2
- package/dist/types-chunks/{sdk-session-CtwN7iBO.d.ts → sdk-session-DINrM1pF.d.ts} +2 -2
- package/dist/types-chunks/{storage.d-DlZS0g8w.d.ts → storage.d-xiw7Vgx0.d.ts} +1 -1
- package/dist/types-chunks/{utils.d-Boz9k2HB.d.ts → utils.d-Dy19-1XR.d.ts} +2 -2
- package/package.json +1 -1
- package/dist/chunks/argument-completer-BQDAYT7W.js +0 -2
- package/dist/chunks/chunk-4K5BDO7S.js +0 -721
- package/dist/chunks/chunk-U6BNMGSK.js +0 -17
- package/dist/chunks/host-FLG7FJZT.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -6,7 +6,32 @@ All notable changes to this project will be documented in this file.
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
-
## [0.7.
|
|
9
|
+
## [0.7.61] - 2026-07-06
|
|
10
|
+
|
|
11
|
+
> Scope note: a token-efficiency + workflow-reliability release. **FEATURE_251** adds command-aware
|
|
12
|
+
> in-tool output compression (an rtk-style Token Killer port) inside KodaX's own `bash` tool layer,
|
|
13
|
+
> so a noisy `git diff` / test run / package-install / docker-build no longer spends thousands of
|
|
14
|
+
> context tokens — the compressed body is what context accounting actually counts, and every lossy
|
|
15
|
+
> summary keeps a raw-recovery path. **FEATURE_252** lands the deterministic half of workflow-quality
|
|
16
|
+
> preflight: a pre-start AST/dataflow lint that hard-fails weak-model authoring contract bugs before
|
|
17
|
+
> a workflow can run. Both are deterministic (no prompt change, no LLM eval). The release also fixes a
|
|
18
|
+
> workflow-start crash: `typescript` is now a runtime dependency of `@kodax-ai/agent` because the
|
|
19
|
+
> quality lint uses the TypeScript compiler API on the workflow hot path. No public runtime type is removed.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- **Tool-output semantic compression — command-aware in-tool Token Killer (FEATURE_251, ADR-050).** A new `packages/coding/src/tools/output-filters/` module compresses bash `stdout`/`stderr` **body** after decode, before the `Command:` / `Exit:` header is assembled, at the single `bash.ts` close-handler integration point (so both the SA and AMA dispatch paths are covered by one change). It ships a lossless generic layer (ANSI strip), compiled stateful filters (`git-diff`, `git-log`, `git-status`, `test-runner` failure-focus, `lint` diagnostic grouping, `json-output` / NDJSON structural summary), and a built-in declarative long-tail table (package-manager / docker / infra CLI progress). Hard constraints: the `Command:` / `Exit:` header is preserved verbatim (FEATURE_185 hits-ledger depends on it); the generic layer is lossless-by-construction with `never_worse` as a size-only backstop; content-signature detection is preferred over command-name matching (robust to compound commands and pipes); and every lossy filter (`lossiness: tail | whole`) first persists the raw decoded body via `persistToolOutput` and appends a recovery hint, falling back to the raw body + existing tail-truncation if the persist fails. `background` / `timeout` / `abort` paths do not reach the completion assembly and are naturally excluded. Isolated Layer-1 measurements (`context-savings.test.ts`) show ~66–99% body-token reduction on high-noise commands (e.g. a 120-file `git diff` 9,960 → 1,344 tokens; a `terraform apply` progress stream 10,617 → 59). Deterministic code — no prompt change, no FEATURE_104 eval. Human test guide: `docs/test-guides/FEATURE_251_v0.7.61_TEST_GUIDE.md`.
|
|
24
|
+
- **Deterministic workflow-quality preflight lint (FEATURE_252).** A new `packages/agent/src/workflow/quality-lint.ts` (`lintRestrictedWorkflowSource` / `assertRestrictedWorkflowQuality`, exported from the workflow package) runs inside restricted workflow module materialization (`script-runner.ts` `createRestrictedWorkflowModule`) and in the coding workflow host with host-policy `maxAgents`, so structural contract violations fail before a run can start — matching the existing inline-smoke hard-fail feedback loop. It hard-fails three deterministic contract classes only: (1) an unawaited workflow-command variable (`wf.runAgent` / `wf.spawnAgent` / `wf.wait` / `wf.synthesize` / `wf.workflow` / `wf.artifact`) used in a boolean position (`if (x)`, `!x`, ternary test, `x && …`, `x || …`, loop test) — a case a runtime Proxy cannot catch because object truthiness has no Proxy trap; (2) top-level structured-output field access (`result.findings`, `result.summary`, …) when the fields belong under `result.structured`; and (3) a literal `[...]`/`[...].map(...)` agent fanout whose static upper bound exceeds `manifest.maxAgents` or a known host cap. Review/verifier/generic quality heuristics are intentionally **not** emitted as model-visible warnings (a lightweight AST pass cannot distinguish a weak workflow from a valid optimized one, and surfacing them causes needless rewrite churn). Human test guide: `docs/test-guides/FEATURE_252_v0.7.61_TEST_GUIDE.md`.
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- **Review/audit workflow templates make adversarial verification explicit (FEATURE_252 Layer 2).** The default generator/authoring fixtures for `adversarial-verification` shapes now use explicit verifier stages and `task_id:` evidence refs, so the desired shape — finders → adversarial verifiers → synthesis of confirmed findings — is stated in the template rather than left to a weak authoring model to infer. This reduces reliance on lint and is robust to capability-limited authors.
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- **Workflow-start crash: `typescript` promoted to a runtime dependency of `@kodax-ai/agent`.** The FEATURE_252 quality lint imports the TypeScript compiler API (`ts.createSourceFile`, …) and runs on every workflow start via `assertRestrictedWorkflowQuality`. With `typescript` only in `devDependencies`, a bundled/published build resolved no `typescript` module at that call site, throwing an uncaught error that crashed the process before the workflow ran (leaving the terminal in a corrupted mouse/alt-screen state). Moving `typescript` to `dependencies` fixes the workflow-front crash.
|
|
33
|
+
|
|
34
|
+
## [0.7.60] - 2026-07-05
|
|
10
35
|
|
|
11
36
|
> Scope note: an F250 refactor + Space SDK rollup. **FEATURE_250** brings the deferred-tool
|
|
12
37
|
> progressive-disclosure mechanism — previously SA-path-only — to the AMA/AMAW **managed** tool
|
package/README.md
CHANGED
|
@@ -412,6 +412,8 @@ KodaX has two layers that consumers should understand separately:
|
|
|
412
412
|
|
|
413
413
|
**Progressive Disclosure on the Managed Tool Path (FEATURE_250, v0.7.60)**: the deferred-tool progressive-disclosure mechanism — previously SA-path-only — now applies to the AMA/AMAW **managed** path too. Cache-cold managed turns carry one-line search hints instead of full descriptions for the 13 non-mcp deferred tools (repo-intelligence + web/code + goal); each tool's `input_schema` is unchanged, so it stays directly callable and the full description is fetched on demand via `tool_search`. `mcp_*` stay resident and `run_workflow` is untouched. Transparent to users; validated by two 5-alias eval panels (DEFER_SAFE 5/5, 0% read/grep fallback). See [docs/features/v0.7.60.md](docs/features/v0.7.60.md).
|
|
414
414
|
|
|
415
|
+
**Tool-Output Compression + Workflow Quality Preflight (FEATURE_251 + FEATURE_252, v0.7.61)**: KodaX's own `bash` tool now compresses noisy command output **inside the tool**, so a big `git diff`, test run, package install, or `docker build` no longer spends thousands of context tokens — command-aware filters (git/test/lint/JSON + a declarative package/docker/infra long-tail) summarize the stdout/stderr body while the `Command:`/`Exit:` header stays verbatim and every lossy summary keeps a raw-recovery path; isolated measurements show ~66–99% body-token reduction. Alongside it, inline `run_workflow` gains a deterministic pre-start quality lint that hard-fails weak-model authoring contract bugs (unawaited workflow-command used as a boolean, top-level access of `result.structured` fields, literal agent fanout above manifest/host caps) before a run starts. Both are deterministic (no prompt change). See [docs/features/v0.7.61.md](docs/features/v0.7.61.md) and [docs/ADR.md ADR-050](docs/ADR.md).
|
|
416
|
+
|
|
415
417
|
---
|
|
416
418
|
|
|
417
419
|
## Features
|
package/README_CN.md
CHANGED
|
@@ -514,6 +514,8 @@ KodaX 有两层结构,SDK 用户需要分开理解:
|
|
|
514
514
|
|
|
515
515
|
**managed 工具路径的渐进披露(FEATURE_250,v0.7.60)**:deferred-tool 渐进披露机制——此前仅 SA path 拥有——现在也应用于 AMA/AMAW 的 **managed** path。缓存冷启的 managed 轮次对 13 个 non-mcp 延迟工具(repo-intelligence + web/code + goal)携带一行 search hint 而非完整描述;每个工具的 `input_schema` 不变,因此仍可直接调用,完整描述按需通过 `tool_search` 拉取。`mcp_*` 保持常驻,`run_workflow` 不动。对用户透明;由两个 5-alias eval panel 验证(DEFER_SAFE 5/5,0% read/grep 回退)。详见 [docs/features/v0.7.60.md](docs/features/v0.7.60.md)。
|
|
516
516
|
|
|
517
|
+
**工具输出压缩 + Workflow 质量预检(FEATURE_251 + FEATURE_252,v0.7.61)**:KodaX 自有的 `bash` 工具现在**在工具内**压缩高噪声命令输出,一次大 `git diff`、测试、包安装或 `docker build` 不再吞掉数千 context token——命令感知过滤器(git/test/lint/JSON + 声明式 package/docker/infra 长尾)摘要 stdout/stderr 正文,`Command:`/`Exit:` 头部逐字保留,所有有损摘要都保留 raw 恢复路径;隔离测量显示正文 token 降幅约 66–99%。同时,inline `run_workflow` 新增确定性启动前质量 lint,在运行前硬失败弱模型的编写合约 bug(未 await 的 workflow-command 用作布尔、顶层访问本应位于 `result.structured` 的字段、字面 agent fanout 超 manifest/host 上限)。二者均为确定性(无 prompt 改动)。详见 [docs/features/v0.7.61.md](docs/features/v0.7.61.md) 与 [docs/ADR.md ADR-050](docs/ADR.md)。
|
|
518
|
+
|
|
517
519
|
```
|
|
518
520
|
KodaX/ # 4 workspace packages(FEATURE_194 v0.7.43)
|
|
519
521
|
├── packages/
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{I as c,J as d,K as e,L as f,Z as g,_ as h,ia as i,oa as j}from"./chunk-
|
|
2
|
+
import{I as c,J as d,K as e,L as f,Z as g,_ as h,ia as i,oa as j}from"./chunk-4NSOBQCU.js";import"./chunk-D6QVXQNI.js";import"./chunk-UA744TZM.js";import"./chunk-7COB3EKF.js";import"./chunk-S4GVQO3W.js";import{mb as a,nb as b}from"./chunk-NJW2LQOP.js";import"./chunk-ZL5CEANW.js";import"./chunk-V4WSBIXB.js";export{d as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,e as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,f as emitResilienceDebug,c as estimateProviderPayloadBytes,j as runKodaX,i as saveSessionSnapshot,a as validateAndFixToolHistory};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
+
import{Aa as b,za as a}from"./chunk-D7CC6YZC.js";import"./chunk-KIVYMSRH.js";import"./chunk-2OEKUAV4.js";import"./chunk-XHOPSZVL.js";import"./chunk-CGGX3FXE.js";import"./chunk-QCBKLNN5.js";import"./chunk-4NSOBQCU.js";import"./chunk-D6QVXQNI.js";import"./chunk-UA744TZM.js";import"./chunk-7COB3EKF.js";import"./chunk-S4GVQO3W.js";import"./chunk-NJW2LQOP.js";import"./chunk-ZL5CEANW.js";import"./chunk-V4WSBIXB.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{w as U,y as $}from"./chunk-ZPD7IUKW.js";import{D as x,E as O,Ja as X,Na as F,ja as I,ka as M,la as D,ma as T,n as k,na as N,oa as S,va as K,wa as g,za as P}from"./chunk-S4GVQO3W.js";import{Ba as j,va as G}from"./chunk-4K5BDO7S.js";import{a as r}from"./chunk-V4WSBIXB.js";import l from"fs";import f from"path";import{exec as ee,spawnSync as te}from"child_process";import{promisify as ne}from"util";import{fileURLToPath as oe}from"url";var C="en";function Z(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}r(Z,"detectSystemLocale");function B(e){if(!e||e==="auto"){C=Z();return}C=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}r(B,"setLocale");var V={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.protected":"Press (y) to confirm, (n) to cancel (protected path)","confirm.result.approved":"Approved","confirm.result.approved_always":"Approved (always)","confirm.result.denied":"Denied","tool.bash.title":"Execute bash command?","tool.shell.title":"Execute shell command?","tool.write.title":"Write to file?","tool.edit.title":"Edit file?","tool.generic.title":"Execute {tool}?","field.reason":"Reason","field.intent":"Intent","field.target":"Target","field.scope":"Scope","field.risk":"Risk","field.summary":"Summary","intent.read":"Read project files","intent.delete":"Delete files","intent.deps":"Modify dependencies or environment","intent.modify":"Modify files","intent.execute":"Execute command","intent.write_file":"Write file","intent.edit_file":"Edit file","intent.use_tool":"Use {tool}","risk.destructive":"Destructive change","risk.deps":"May change dependencies or local tools","risk.modify":"May modify files","risk.unknown":"Command effects depend on its arguments","risk.network":"May access network","scope.outside":"Outside project","scope.protected":"Protected path","waiting.confirm":"Waiting: approval required","waiting.select":"Waiting: choose an option","waiting.input":"Waiting: answer the prompt","placeholder.confirm":"Respond to the approval prompt above...","placeholder.select":"Choose an option above...","placeholder.input":"Answer the prompt above...","placeholder.busy":"Agent is busy...","placeholder.queue":"Queue a follow-up for the next round...","placeholder.idle":"Type a message...","select.choice":"Choice:","select.type_number":"(type a number)","select.more":"{count} more choices...","select.more_above":"\u2191 {count} more above","select.more_below":"\u2193 {count} more below","select.confirm_hint":"Press Enter to confirm, Esc to cancel","select.navigate_hint":"Use \u2191\u2193 to navigate, Enter to confirm, Esc to cancel","select.multiselect_hint":"Use \u2191\u2193 to navigate, Space to toggle, Enter to confirm, Esc to cancel","select.multiselect_empty":"Select at least one option with Space before confirming.","select.multiselect_min":"Select at least {min} option(s) with Space before confirming.","select.multiselect_max":"Select at most {max} option(s) with Space before confirming.","select.back_prev":"\u2190 Back to previous question","input.default":"Default:","input.value":"Value:","input.type_response":"(type your response)","managed.completed":"Task completed","managed.completed.blocked":"Task blocked","managed.completed.continuation":"Task needs continuation",cancelled:"[Cancelled] Operation cancelled by user"},zh:{"dialog.confirm":"[\u786E\u8BA4]","dialog.select":"[\u9009\u62E9]","dialog.input":"[\u8F93\u5165]","confirm.instruction.basic":"\u6309 (y) \u786E\u8BA4, (n) \u62D2\u7EDD","confirm.instruction.always":"\u6309 (y) \u786E\u8BA4, (a) \u59CB\u7EC8\u5141\u8BB8\u6B64\u5DE5\u5177, (n) \u62D2\u7EDD","confirm.instruction.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.denied":"\u5DF2\u62D2\u7EDD","tool.bash.title":"\u6267\u884C bash \u547D\u4EE4\uFF1F","tool.shell.title":"\u6267\u884C shell \u547D\u4EE4\uFF1F","tool.write.title":"\u5199\u5165\u6587\u4EF6\uFF1F","tool.edit.title":"\u7F16\u8F91\u6587\u4EF6\uFF1F","tool.generic.title":"\u6267\u884C {tool}\uFF1F","field.reason":"\u539F\u56E0","field.intent":"\u610F\u56FE","field.target":"\u76EE\u6807","field.scope":"\u8303\u56F4","field.risk":"\u98CE\u9669","field.summary":"\u6458\u8981","intent.read":"\u8BFB\u53D6\u9879\u76EE\u6587\u4EF6","intent.delete":"\u5220\u9664\u6587\u4EF6","intent.deps":"\u4FEE\u6539\u4F9D\u8D56\u6216\u73AF\u5883","intent.modify":"\u4FEE\u6539\u6587\u4EF6","intent.execute":"\u6267\u884C\u547D\u4EE4","intent.write_file":"\u5199\u5165\u6587\u4EF6","intent.edit_file":"\u7F16\u8F91\u6587\u4EF6","intent.use_tool":"\u4F7F\u7528 {tool}","risk.destructive":"\u7834\u574F\u6027\u53D8\u66F4","risk.deps":"\u53EF\u80FD\u4FEE\u6539\u4F9D\u8D56\u6216\u672C\u5730\u5DE5\u5177","risk.modify":"\u53EF\u80FD\u4FEE\u6539\u6587\u4EF6","risk.unknown":"\u547D\u4EE4\u6548\u679C\u53D6\u51B3\u4E8E\u53C2\u6570","risk.network":"\u53EF\u80FD\u8BBF\u95EE\u7F51\u7EDC","scope.outside":"\u9879\u76EE\u5916\u90E8","scope.protected":"\u53D7\u4FDD\u62A4\u8DEF\u5F84","waiting.confirm":"\u7B49\u5F85\u4E2D\uFF1A\u9700\u8981\u5BA1\u6279","waiting.select":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u9009\u62E9","waiting.input":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u56DE\u7B54","placeholder.confirm":"\u8BF7\u56DE\u5E94\u4E0A\u65B9\u7684\u5BA1\u6279\u63D0\u793A...","placeholder.select":"\u8BF7\u5728\u4E0A\u65B9\u9009\u62E9\u4E00\u4E2A\u9009\u9879...","placeholder.input":"\u8BF7\u56DE\u7B54\u4E0A\u65B9\u7684\u63D0\u793A...","placeholder.busy":"\u667A\u80FD\u4F53\u6B63\u5728\u5DE5\u4F5C\u4E2D...","placeholder.queue":"\u6392\u961F\u7B49\u5F85\u4E0B\u4E00\u8F6E\u8DDF\u8FDB...","placeholder.idle":"\u8F93\u5165\u6D88\u606F...","select.choice":"\u9009\u9879\uFF1A","select.type_number":"(\u8F93\u5165\u7F16\u53F7)","select.more":"\u8FD8\u6709 {count} \u4E2A\u9009\u9879...","select.more_above":"\u2191 \u4E0A\u65B9\u8FD8\u6709 {count} \u4E2A","select.more_below":"\u2193 \u4E0B\u65B9\u8FD8\u6709 {count} \u4E2A","select.confirm_hint":"\u6309 Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.navigate_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0C\u7A7A\u683C \u5207\u6362\u9009\u4E2D\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_empty":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u9009\u9879\u3002","select.multiselect_min":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u81F3\u5C11\u9009\u62E9 {min} \u4E2A\u9009\u9879\u3002","select.multiselect_max":"\u6700\u591A\u53EA\u80FD\u9009\u62E9 {max} \u4E2A\u9009\u9879\u3002","select.back_prev":"\u2190 \u8FD4\u56DE\u4E0A\u4E00\u9898","input.default":"\u9ED8\u8BA4\u503C\uFF1A","input.value":"\u503C\uFF1A","input.type_response":"(\u8F93\u5165\u4F60\u7684\u56DE\u7B54)","managed.completed":"\u4EFB\u52A1\u5B8C\u6210","managed.completed.blocked":"\u4EFB\u52A1\u53D7\u963B","managed.completed.continuation":"\u4EFB\u52A1\u9700\u8981\u7EE7\u7EED",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88"}};function Ie(e,t){let o=V[C][e]??V.en[e]??e;if(t)for(let[i,s]of Object.entries(t))o=o.replace(`{${i}}`,String(s));return o}r(Ie,"t");var re=ne(ee),h=G(),Ve=f.join(h,"sessions"),d=f.join(h,"config.json"),Be=60,p=null,L=!1,ie="dumb";function se(e){let t=f.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(se,"buildShellEnvCommand");function ae(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 u=a.indexOf("=");u<=0||(s[a.slice(0,u)]=a.slice(u+1))}return s}r(ae,"parseNullDelimitedShellEnv");function le(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||!f.isAbsolute(o))return!1;let{args:i,sentinel:s}=se(o),a=e.run??te,u={...t,TERM:ie},c=a(o,i,{encoding:"utf8",env:u,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(c.status!==0||!c.stdout)return!1;let J=typeof c.stdout=="string"?c.stdout:c.stdout.toString("utf8"),Y=ae(J,s),A=!1;for(let[_,Q]of Object.entries(Y))_!=="TERM"&&t[_]===void 0&&(t[_]=Q,A=!0);return A}r(le,"hydrateProcessEnvFromShell");function ce(){if(!L){L=!0;try{le()}catch{}}}r(ce,"ensureShellEnvironmentHydrated");function We(){L=!1}r(We,"resetShellEnvironmentHydrationForTesting");function ue(e){K(e.customProviders??[])}r(ue,"registerConfiguredCustomProviders");function z(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(z,"normalizeConfiguredExtensions");function fe(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{l.mkdirSync(f.dirname(d),{recursive:!0}),l.writeFileSync(d,JSON.stringify(t,null,2))}catch{}return t}r(fe,"migrateLegacyPermissionModeInConfig");function de(e){if(e.permissionMode!=="auto-in-project")return e;try{let t=l.readFileSync(d,"utf-8"),n=t.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t&&l.writeFileSync(d,n)}catch{}return{...e,permissionMode:"auto"}}r(de,"migrateAutoInProjectAliasInConfig");function pe(){if(p)return p;let e="0.7.60";if(e)return p=e,p;let t=f.join(f.dirname(oe(import.meta.url)),"../../package.json");if(l.existsSync(t))try{return p=JSON.parse(l.readFileSync(t,"utf-8")).version??"0.0.0",p??"0.0.0"}catch{}return p="0.0.0",p}r(pe,"getVersion");var He=pe();function me(e){return M(e)}r(me,"getProviderModel");function R(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(R,"mergeModels");function ge(e,t){t||(t=b().providerModels);let n=t?.[e];if(n&&n.length>0){try{let o=S(e);if(o.length>0)return R(n,o)}catch{}try{let o=g(e);if(o)return R(n,o.getAvailableModels())}catch{}return n}try{let o=S(e);if(o.length>0)return o}catch{}try{let o=g(e);if(o)return o.getAvailableModels()}catch{}return[]}r(ge,"getProviderAvailableModels");function ve(e,t){let n=D(e,t);if(n!=="unknown")return n;try{let o=g(e);if(o)return o.getReasoningCapability(t)}catch{}return"unknown"}r(ve,"getProviderReasoningCapability");function ye(e){let t=T(e);if(t)return t;try{return P().find(o=>o.name===e)?.capabilityProfile??null}catch{return null}}r(ye,"getProviderCapabilityProfile");function q(e,t){let n=ye(e),o=ve(e,t);if(n)return{capabilityProfile:n,reasoningCapability:o};try{let i=X(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}r(q,"getProviderCapabilityMetadata");function ze(e,t){let n=q(e,t);return n?U({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}r(ze,"getProviderCapabilitySnapshot");function he(e,t,n,o){let i=q(e,t);return i?$({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:o}):null}r(he,"getProviderPolicyDecision");function qe(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(qe,"describeProviderCapabilitySummary");function Je(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(Je,"formatReasoningCapabilityShort");function m(e){if(e)return e==="none"?"off":e}r(m,"formatReasoningEffortForDisplay");function y(e,t){let n=m(t);n&&!e.includes(n)&&e.push(n)}r(y,"pushUniqueEffortDisplay");function Ye(e,t){let n=["auto"],i=E(e,t)?.supportedEfforts?.filter(s=>s.isUserVisible!==!1);if(!i||i.length===0){for(let s of["off","low","medium","high"])y(n,s);return n}for(let s of i)y(n,s.value);return n}r(Ye,"getProviderReasoningEffortOptions");function Qe(e,t){let n=E(e,t),o=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(c=>c.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let c of["low","medium","high"])y(s,c);a=!0}else for(let c of i){if(c.value==="none"){a=!0;continue}if(o.has(c.value)){a=!0;continue}y(s,c.value)}let u=[];return a&&u.push("off"),u.push(...s),u.push("auto"),u}r(Qe,"getProviderReasoningEffortCycle");function Ee(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(Ee,"legacyReasoningModeToEffortDisplay");function E(e,t){let n=t??me(e);if(!n)return;let o=F(e,n)?.reasoningProfile;if(o)return k(o,j(e,n))}r(E,"resolveReasoningProfileForDisplay");function Ze(e){let t=m(e.effort)??Ee(e.reasoningMode,e.thinking),n=E(e.provider,e.model);if(!n)return t;try{let o=x({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=m(o.configuredEffort)??t,a=o.configuredEffort!==void 0&&n.disabledEfforts?.includes(o.configuredEffort)===!0?"off":m(o.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let o=O({currentEffort:e.effort,capability:n}),i=m(e.effort)??t,s=m(o.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}r(Ze,"formatReasoningEffortStatusLabel");function et(e){let t=ke(e);if(!t)return{preserved:!0};let n=E(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let o=O({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:o.effectiveEffort,preserved:o.preserved,diagnostic:o.diagnostic}}r(et,"resolveProviderReasoningRuntimeEffort");function be(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(be,"describeReasoningCapabilityControl");function tt(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(tt,"describeReasoningExecution");function nt(e){let t=[];e||(e=b().providerModels);for(let n of N())t.push({name:n.name,model:n.model,models:ge(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=P().map(o=>({...o,models:(()=>{let i=e?.[o.name];return i&&i.length>0?R(i,o.models):o.models})()}));t.push(...n)}catch{}return t}r(nt,"getProviderList");function ot(e){if(I(e))return!0;try{return g(e)?.isConfigured()??!1}catch{return!1}}r(ot,"isProviderConfigured");function b(){try{if(l.existsSync(d)){let e=JSON.parse(l.readFileSync(d,"utf-8")),t=e.reasoningCeiling??e.reasoningMode;return de(fe({...e,reasoningMode:t,extensions:z(e.extensions)}))}}catch{}return{}}r(b,"loadConfig");var w=f.join(h,"config.example.jsonc"),_e=`// KodaX example configuration \u2014 copy what you need into config.json (in this same
|
|
2
|
+
import{w as U,y as $}from"./chunk-4NSOBQCU.js";import{D as x,E as O,Ja as X,Na as F,ja as I,ka as M,la as D,ma as T,n as k,na as N,oa as S,va as K,wa as g,za as P}from"./chunk-S4GVQO3W.js";import{Ba as j,va as G}from"./chunk-NJW2LQOP.js";import{a as r}from"./chunk-V4WSBIXB.js";import l from"fs";import f from"path";import{exec as ee,spawnSync as te}from"child_process";import{promisify as ne}from"util";import{fileURLToPath as oe}from"url";var C="en";function Z(){return(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").toLowerCase().startsWith("zh")?"zh":"en"}r(Z,"detectSystemLocale");function B(e){if(!e||e==="auto"){C=Z();return}C=e.toLowerCase().replace(/[-_].*/,"")==="zh"?"zh":"en"}r(B,"setLocale");var V={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.protected":"Press (y) to confirm, (n) to cancel (protected path)","confirm.result.approved":"Approved","confirm.result.approved_always":"Approved (always)","confirm.result.denied":"Denied","tool.bash.title":"Execute bash command?","tool.shell.title":"Execute shell command?","tool.write.title":"Write to file?","tool.edit.title":"Edit file?","tool.generic.title":"Execute {tool}?","field.reason":"Reason","field.intent":"Intent","field.target":"Target","field.scope":"Scope","field.risk":"Risk","field.summary":"Summary","intent.read":"Read project files","intent.delete":"Delete files","intent.deps":"Modify dependencies or environment","intent.modify":"Modify files","intent.execute":"Execute command","intent.write_file":"Write file","intent.edit_file":"Edit file","intent.use_tool":"Use {tool}","risk.destructive":"Destructive change","risk.deps":"May change dependencies or local tools","risk.modify":"May modify files","risk.unknown":"Command effects depend on its arguments","risk.network":"May access network","scope.outside":"Outside project","scope.protected":"Protected path","waiting.confirm":"Waiting: approval required","waiting.select":"Waiting: choose an option","waiting.input":"Waiting: answer the prompt","placeholder.confirm":"Respond to the approval prompt above...","placeholder.select":"Choose an option above...","placeholder.input":"Answer the prompt above...","placeholder.busy":"Agent is busy...","placeholder.queue":"Queue a follow-up for the next round...","placeholder.idle":"Type a message...","select.choice":"Choice:","select.type_number":"(type a number)","select.more":"{count} more choices...","select.more_above":"\u2191 {count} more above","select.more_below":"\u2193 {count} more below","select.confirm_hint":"Press Enter to confirm, Esc to cancel","select.navigate_hint":"Use \u2191\u2193 to navigate, Enter to confirm, Esc to cancel","select.multiselect_hint":"Use \u2191\u2193 to navigate, Space to toggle, Enter to confirm, Esc to cancel","select.multiselect_empty":"Select at least one option with Space before confirming.","select.multiselect_min":"Select at least {min} option(s) with Space before confirming.","select.multiselect_max":"Select at most {max} option(s) with Space before confirming.","select.back_prev":"\u2190 Back to previous question","input.default":"Default:","input.value":"Value:","input.type_response":"(type your response)","managed.completed":"Task completed","managed.completed.blocked":"Task blocked","managed.completed.continuation":"Task needs continuation",cancelled:"[Cancelled] Operation cancelled by user"},zh:{"dialog.confirm":"[\u786E\u8BA4]","dialog.select":"[\u9009\u62E9]","dialog.input":"[\u8F93\u5165]","confirm.instruction.basic":"\u6309 (y) \u786E\u8BA4, (n) \u62D2\u7EDD","confirm.instruction.always":"\u6309 (y) \u786E\u8BA4, (a) \u59CB\u7EC8\u5141\u8BB8\u6B64\u5DE5\u5177, (n) \u62D2\u7EDD","confirm.instruction.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.denied":"\u5DF2\u62D2\u7EDD","tool.bash.title":"\u6267\u884C bash \u547D\u4EE4\uFF1F","tool.shell.title":"\u6267\u884C shell \u547D\u4EE4\uFF1F","tool.write.title":"\u5199\u5165\u6587\u4EF6\uFF1F","tool.edit.title":"\u7F16\u8F91\u6587\u4EF6\uFF1F","tool.generic.title":"\u6267\u884C {tool}\uFF1F","field.reason":"\u539F\u56E0","field.intent":"\u610F\u56FE","field.target":"\u76EE\u6807","field.scope":"\u8303\u56F4","field.risk":"\u98CE\u9669","field.summary":"\u6458\u8981","intent.read":"\u8BFB\u53D6\u9879\u76EE\u6587\u4EF6","intent.delete":"\u5220\u9664\u6587\u4EF6","intent.deps":"\u4FEE\u6539\u4F9D\u8D56\u6216\u73AF\u5883","intent.modify":"\u4FEE\u6539\u6587\u4EF6","intent.execute":"\u6267\u884C\u547D\u4EE4","intent.write_file":"\u5199\u5165\u6587\u4EF6","intent.edit_file":"\u7F16\u8F91\u6587\u4EF6","intent.use_tool":"\u4F7F\u7528 {tool}","risk.destructive":"\u7834\u574F\u6027\u53D8\u66F4","risk.deps":"\u53EF\u80FD\u4FEE\u6539\u4F9D\u8D56\u6216\u672C\u5730\u5DE5\u5177","risk.modify":"\u53EF\u80FD\u4FEE\u6539\u6587\u4EF6","risk.unknown":"\u547D\u4EE4\u6548\u679C\u53D6\u51B3\u4E8E\u53C2\u6570","risk.network":"\u53EF\u80FD\u8BBF\u95EE\u7F51\u7EDC","scope.outside":"\u9879\u76EE\u5916\u90E8","scope.protected":"\u53D7\u4FDD\u62A4\u8DEF\u5F84","waiting.confirm":"\u7B49\u5F85\u4E2D\uFF1A\u9700\u8981\u5BA1\u6279","waiting.select":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u9009\u62E9","waiting.input":"\u7B49\u5F85\u4E2D\uFF1A\u8BF7\u56DE\u7B54","placeholder.confirm":"\u8BF7\u56DE\u5E94\u4E0A\u65B9\u7684\u5BA1\u6279\u63D0\u793A...","placeholder.select":"\u8BF7\u5728\u4E0A\u65B9\u9009\u62E9\u4E00\u4E2A\u9009\u9879...","placeholder.input":"\u8BF7\u56DE\u7B54\u4E0A\u65B9\u7684\u63D0\u793A...","placeholder.busy":"\u667A\u80FD\u4F53\u6B63\u5728\u5DE5\u4F5C\u4E2D...","placeholder.queue":"\u6392\u961F\u7B49\u5F85\u4E0B\u4E00\u8F6E\u8DDF\u8FDB...","placeholder.idle":"\u8F93\u5165\u6D88\u606F...","select.choice":"\u9009\u9879\uFF1A","select.type_number":"(\u8F93\u5165\u7F16\u53F7)","select.more":"\u8FD8\u6709 {count} \u4E2A\u9009\u9879...","select.more_above":"\u2191 \u4E0A\u65B9\u8FD8\u6709 {count} \u4E2A","select.more_below":"\u2193 \u4E0B\u65B9\u8FD8\u6709 {count} \u4E2A","select.confirm_hint":"\u6309 Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.navigate_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_hint":"\u4F7F\u7528 \u2191\u2193 \u5BFC\u822A\uFF0C\u7A7A\u683C \u5207\u6362\u9009\u4E2D\uFF0CEnter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88","select.multiselect_empty":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u9009\u62E9\u81F3\u5C11\u4E00\u4E2A\u9009\u9879\u3002","select.multiselect_min":"\u8BF7\u5148\u4F7F\u7528\u7A7A\u683C\u81F3\u5C11\u9009\u62E9 {min} \u4E2A\u9009\u9879\u3002","select.multiselect_max":"\u6700\u591A\u53EA\u80FD\u9009\u62E9 {max} \u4E2A\u9009\u9879\u3002","select.back_prev":"\u2190 \u8FD4\u56DE\u4E0A\u4E00\u9898","input.default":"\u9ED8\u8BA4\u503C\uFF1A","input.value":"\u503C\uFF1A","input.type_response":"(\u8F93\u5165\u4F60\u7684\u56DE\u7B54)","managed.completed":"\u4EFB\u52A1\u5B8C\u6210","managed.completed.blocked":"\u4EFB\u52A1\u53D7\u963B","managed.completed.continuation":"\u4EFB\u52A1\u9700\u8981\u7EE7\u7EED",cancelled:"[\u5DF2\u53D6\u6D88] \u64CD\u4F5C\u5DF2\u88AB\u7528\u6237\u53D6\u6D88"}};function Ie(e,t){let o=V[C][e]??V.en[e]??e;if(t)for(let[i,s]of Object.entries(t))o=o.replace(`{${i}}`,String(s));return o}r(Ie,"t");var re=ne(ee),h=G(),Ve=f.join(h,"sessions"),d=f.join(h,"config.json"),Be=60,p=null,L=!1,ie="dumb";function se(e){let t=f.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(se,"buildShellEnvCommand");function ae(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 u=a.indexOf("=");u<=0||(s[a.slice(0,u)]=a.slice(u+1))}return s}r(ae,"parseNullDelimitedShellEnv");function le(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||!f.isAbsolute(o))return!1;let{args:i,sentinel:s}=se(o),a=e.run??te,u={...t,TERM:ie},c=a(o,i,{encoding:"utf8",env:u,maxBuffer:1024*1024,timeout:5e3,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});if(c.status!==0||!c.stdout)return!1;let J=typeof c.stdout=="string"?c.stdout:c.stdout.toString("utf8"),Y=ae(J,s),A=!1;for(let[_,Q]of Object.entries(Y))_!=="TERM"&&t[_]===void 0&&(t[_]=Q,A=!0);return A}r(le,"hydrateProcessEnvFromShell");function ce(){if(!L){L=!0;try{le()}catch{}}}r(ce,"ensureShellEnvironmentHydrated");function We(){L=!1}r(We,"resetShellEnvironmentHydrationForTesting");function ue(e){K(e.customProviders??[])}r(ue,"registerConfiguredCustomProviders");function z(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(z,"normalizeConfiguredExtensions");function fe(e){if(e.permissionMode!=="default")return e;let t={...e,permissionMode:"accept-edits"};try{l.mkdirSync(f.dirname(d),{recursive:!0}),l.writeFileSync(d,JSON.stringify(t,null,2))}catch{}return t}r(fe,"migrateLegacyPermissionModeInConfig");function de(e){if(e.permissionMode!=="auto-in-project")return e;try{let t=l.readFileSync(d,"utf-8"),n=t.replace(/("permissionMode"\s*:\s*)"auto-in-project"/,'$1"auto"');n!==t&&l.writeFileSync(d,n)}catch{}return{...e,permissionMode:"auto"}}r(de,"migrateAutoInProjectAliasInConfig");function pe(){if(p)return p;let e="0.7.61";if(e)return p=e,p;let t=f.join(f.dirname(oe(import.meta.url)),"../../package.json");if(l.existsSync(t))try{return p=JSON.parse(l.readFileSync(t,"utf-8")).version??"0.0.0",p??"0.0.0"}catch{}return p="0.0.0",p}r(pe,"getVersion");var He=pe();function me(e){return M(e)}r(me,"getProviderModel");function R(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(R,"mergeModels");function ge(e,t){t||(t=b().providerModels);let n=t?.[e];if(n&&n.length>0){try{let o=S(e);if(o.length>0)return R(n,o)}catch{}try{let o=g(e);if(o)return R(n,o.getAvailableModels())}catch{}return n}try{let o=S(e);if(o.length>0)return o}catch{}try{let o=g(e);if(o)return o.getAvailableModels()}catch{}return[]}r(ge,"getProviderAvailableModels");function ve(e,t){let n=D(e,t);if(n!=="unknown")return n;try{let o=g(e);if(o)return o.getReasoningCapability(t)}catch{}return"unknown"}r(ve,"getProviderReasoningCapability");function ye(e){let t=T(e);if(t)return t;try{return P().find(o=>o.name===e)?.capabilityProfile??null}catch{return null}}r(ye,"getProviderCapabilityProfile");function q(e,t){let n=ye(e),o=ve(e,t);if(n)return{capabilityProfile:n,reasoningCapability:o};try{let i=X(e);return{capabilityProfile:i.getCapabilityProfile(),reasoningCapability:i.getReasoningCapability(t)}}catch{return null}}r(q,"getProviderCapabilityMetadata");function ze(e,t){let n=q(e,t);return n?U({providerName:e,model:t,capabilityProfile:n.capabilityProfile,reasoningCapability:n.reasoningCapability==="unknown"?void 0:n.reasoningCapability}):null}r(ze,"getProviderCapabilitySnapshot");function he(e,t,n,o){let i=q(e,t);return i?$({providerName:e,model:t,capabilityProfile:i.capabilityProfile,reasoningCapability:i.reasoningCapability==="unknown"?void 0:i.reasoningCapability,reasoningMode:n,hints:o}):null}r(he,"getProviderPolicyDecision");function qe(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(qe,"describeProviderCapabilitySummary");function Je(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(Je,"formatReasoningCapabilityShort");function m(e){if(e)return e==="none"?"off":e}r(m,"formatReasoningEffortForDisplay");function y(e,t){let n=m(t);n&&!e.includes(n)&&e.push(n)}r(y,"pushUniqueEffortDisplay");function Ye(e,t){let n=["auto"],i=E(e,t)?.supportedEfforts?.filter(s=>s.isUserVisible!==!1);if(!i||i.length===0){for(let s of["off","low","medium","high"])y(n,s);return n}for(let s of i)y(n,s.value);return n}r(Ye,"getProviderReasoningEffortOptions");function Qe(e,t){let n=E(e,t),o=new Set(n?.disabledEfforts??[]),i=n?.supportedEfforts?.filter(c=>c.isUserVisible!==!1),s=[],a=n?.supportsDisabledThinking===!0;if(!i||i.length===0){for(let c of["low","medium","high"])y(s,c);a=!0}else for(let c of i){if(c.value==="none"){a=!0;continue}if(o.has(c.value)){a=!0;continue}y(s,c.value)}let u=[];return a&&u.push("off"),u.push(...s),u.push("auto"),u}r(Qe,"getProviderReasoningEffortCycle");function Ee(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(Ee,"legacyReasoningModeToEffortDisplay");function E(e,t){let n=t??me(e);if(!n)return;let o=F(e,n)?.reasoningProfile;if(o)return k(o,j(e,n))}r(E,"resolveReasoningProfileForDisplay");function Ze(e){let t=m(e.effort)??Ee(e.reasoningMode,e.thinking),n=E(e.provider,e.model);if(!n)return t;try{let o=x({capability:n,explicitEffort:e.effortOverride?e.effort:void 0,sessionEffort:e.effortOverride?void 0:e.effort,legacyReasoningMode:e.reasoningMode,thinking:e.thinking}),i=m(o.configuredEffort)??t,a=o.configuredEffort!==void 0&&n.disabledEfforts?.includes(o.configuredEffort)===!0?"off":m(o.effectiveEffort);return a&&a!==i?`${i}->${a}`:i}catch{if(e.effort)try{let o=O({currentEffort:e.effort,capability:n}),i=m(e.effort)??t,s=m(o.effectiveEffort);return s&&s!==i?`${i}->${s}`:i}catch{return t}return t}}r(Ze,"formatReasoningEffortStatusLabel");function et(e){let t=ke(e);if(!t)return{preserved:!0};let n=E(e.provider,e.model);if(!n)return{configuredEffort:t,runtimeEffort:t,preserved:!0};let o=O({currentEffort:t,capability:n});return{configuredEffort:t,runtimeEffort:o.effectiveEffort,preserved:o.preserved,diagnostic:o.diagnostic}}r(et,"resolveProviderReasoningRuntimeEffort");function be(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(be,"describeReasoningCapabilityControl");function tt(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(tt,"describeReasoningExecution");function nt(e){let t=[];e||(e=b().providerModels);for(let n of N())t.push({name:n.name,model:n.model,models:ge(n.name,e),configured:n.capabilityProfile.transport==="cli-bridge"?!0:n.configured,reasoningCapability:n.reasoningCapability,capabilityProfile:n.capabilityProfile});try{let n=P().map(o=>({...o,models:(()=>{let i=e?.[o.name];return i&&i.length>0?R(i,o.models):o.models})()}));t.push(...n)}catch{}return t}r(nt,"getProviderList");function ot(e){if(I(e))return!0;try{return g(e)?.isConfigured()??!1}catch{return!1}}r(ot,"isProviderConfigured");function b(){try{if(l.existsSync(d)){let e=JSON.parse(l.readFileSync(d,"utf-8")),t=e.reasoningCeiling??e.reasoningMode;return de(fe({...e,reasoningMode:t,extensions:z(e.extensions)}))}}catch{}return{}}r(b,"loadConfig");var w=f.join(h,"config.example.jsonc"),_e=`// KodaX example configuration \u2014 copy what you need into config.json (in this same
|
|
3
3
|
// folder). config.json must be STRICT JSON: no comments, no trailing commas. Most
|
|
4
4
|
// settings also have a KODAX_* env var that overrides the file. Delete anything you
|
|
5
5
|
// don't use; everything here is optional.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{a as Gr}from"./chunk-UA744TZM.js";import{$ as be,$a as Ze,$c as Jr,Ba as vr,Bc as qt,C as Ve,Ca as kr,Cc as Xr,D as fr,Db as Wr,Dc as Yr,Ec as b,Fc as ue,Gc as zr,Hc as Vr,Ic as Qr,Na as wr,O as pr,Qa as Er,U as hr,Va as Rr,Wa as $t,X as gr,Ya as Sr,Za as Cr,_a as _r,_c as Zr,aa as Qe,ab as Mr,bb as Ar,cb as Pr,d as ur,da as yr,db as _,e as W,eb as Ir,f as J,fb as Or,fd as en,g as dr,ga as Tr,gb as Nr,ha as br,hb as Dr,ia as xr,ib as Lr,jb as Fr,kb as z,lb as xe,mb as Ur,nb as ve,ob as Je,pa as Ht,pb as Br,pd as tn,qb as Hr,qd as et,rb as $r,sb as qr,sd as tt,tb as jr,td as on,vd as rn,wd as nn,xc as Kr,y as mr}from"./chunk-QFCF3GNT.js";import{A as ce,B as Do,F as Lo,Ga as Pt,Ja as Te,O as Fo,Q as Uo,Ra as It,T as ye,Va as Bo,Wa as Ho,Xa as $o,Ya as qo,_a as jo,b as _e,c as Me,d as Ae,e as No,pa as Mt,xa as At}from"./chunk-S4GVQO3W.js";import{$c as Lt,Ba as zo,Bd as Ut,Ca as Vo,Eb as Zo,Jd as Bt,Md as nr,Nd as ir,Od as sr,Td as ar,Ud as cr,Wd as lr,ad as Ft,bd as Jo,dd as er,ed as tr,f as Z,fd as or,g as Ye,gd as rr,j as Wo,k as le,m as Ko,mb as Pe,na as Xo,nb as Dt,oa as Nt,vb as ze,wa as Yo,wb as Qo}from"./chunk-4K5BDO7S.js";import{a as Ot,z as Go}from"./chunk-ZL5CEANW.js";import{a as i}from"./chunk-V4WSBIXB.js";import{readFile as ls}from"fs/promises";var sn=75;function us(e){return typeof e!="number"||e<=0?sn:e<=2e5?60:e<=256e3?65:e<=5e5?70:75}i(us,"adaptiveTriggerPercent");var ds={enabled:!0};async function an(e,t){let o=Yo("config.json"),r;try{let a=await ms(o);a?.compaction&&(r=a.compaction)}catch{}let n={...ds,...r,triggerPercent:sn};t?.enabled!==void 0&&(n.enabled=t.enabled),t?.contextWindow!==void 0&&(n.contextWindow=t.contextWindow);let s=n.contextWindow??e;return n.triggerPercent=typeof t?.triggerPercent=="number"?t.triggerPercent:typeof r?.triggerPercent=="number"?r.triggerPercent:us(s),n}i(an,"loadCompactionConfig");async function ms(e){try{let t=await ls(e,"utf-8");return JSON.parse(t)}catch{return null}}i(ms,"readConfigFile");var H;(function(e){e[e.TRANSIENT=0]="TRANSIENT",e[e.PERMANENT=1]="PERMANENT",e[e.TOOL_CALL_ID=2]="TOOL_CALL_ID",e[e.USER_ABORT=3]="USER_ABORT"})(H||(H={}));var fs=[/\bstream incomplete\b/i,/\bstream interrupted\b/i,/\bstream stalled\b/i,/\bdelayed response\b/i,/\btimed out\b/i,/\btimeout\b/i,/\bnetwork\b/i,/\bconnection error\b/i,/\bconnection reset\b/i,/\bconnection closed\b/i,/\bsocket hang up\b/i,/\bfetch failed\b/i,/\beconnrefused\b/i,/\beconnreset\b/i,/\betimedout\b/i,/\benotfound\b/i,/\beai_again\b/i,/\bother side closed\b/i,/\baborted\b/i,/网络错误/,/网络异常/,/连接超时/,/连接错误/,/连接失败/,/连接被拒绝/,/请求超时/,/服务繁忙/,/服务不可用/,/服务器错误/,/服务器内部错误/,/请求过多/,/频率限制/,/限流/,/过载/,/容量不足/];function cn(e){return fs.some(t=>t.test(e))}i(cn,"matchesTransientMessage");function ps(e){if(e.name==="StreamIncompleteError"||e.message.includes("Stream incomplete"))return{category:H.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:2e3,shouldCleanup:!0};if(e.name==="AbortError")return{category:H.USER_ABORT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0};if(e instanceof No||e.message.includes("tool_call_id")||e.message.includes("tool result"))return{category:H.TOOL_CALL_ID,retryable:!0,maxRetries:1,retryDelay:1e3,shouldCleanup:!0};if(e instanceof Me)return{category:H.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:e.retryAfter??6e4,shouldCleanup:!0};if(e instanceof Ae)return{category:H.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:e.isTimeout?5e3:2e3,shouldCleanup:!0};if(e instanceof _e){let o=e.message.toLowerCase();return cn(o)?{category:H.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:2e3,shouldCleanup:!0}:{category:H.PERMANENT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0}}let t=e.message.toLowerCase();return cn(t)?{category:H.TRANSIENT,retryable:!0,maxRetries:2,retryDelay:2e3,shouldCleanup:!0}:{category:H.PERMANENT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0}}i(ps,"classifyError");function jt(e,t){return new Promise((o,r)=>{if(t?.aborted){r(t.reason instanceof Error?t.reason:new DOMException("Request aborted","AbortError"));return}let n,s=t;if(!s){n=setTimeout(()=>{o()},e);return}let a=i(()=>{clearTimeout(n),s.removeEventListener("abort",a),r(s.reason instanceof Error?s.reason:new DOMException("Request aborted","AbortError"))},"onAbort");n=setTimeout(()=>{s.removeEventListener("abort",a),o()},e),s.addEventListener("abort",a,{once:!0})})}i(jt,"waitForRetryDelay");var un={requestTimeoutMs:6e5,streamIdleTimeoutMs:Number(process.env.KODAX_STREAM_IDLE_TIMEOUT_MS)||0,chunkTimeoutMs:3e4,maxRetries:4,maxRetryDelayMs:6e4,enableNonStreamingFallback:!0};function Gt(e,t,o){let r={...un};if(t&&ln(r,t),o&&o.length>0){let n=o.find(s=>s.provider===e);if(n){let{provider:s,...a}=n;ln(r,a)}}return r}i(Gt,"resolveResilienceConfig");function ln(e,t){t.requestTimeoutMs!==void 0&&(e.requestTimeoutMs=t.requestTimeoutMs),t.streamIdleTimeoutMs!==void 0&&(e.streamIdleTimeoutMs=t.streamIdleTimeoutMs),t.chunkTimeoutMs!==void 0&&(e.chunkTimeoutMs=t.chunkTimeoutMs),t.maxRetries!==void 0&&(e.maxRetries=t.maxRetries),t.maxRetryDelayMs!==void 0&&(e.maxRetryDelayMs=t.maxRetryDelayMs),t.enableNonStreamingFallback!==void 0&&(e.enableNonStreamingFallback=t.enableNonStreamingFallback)}i(ln,"mergePartialConfig");var hs=[/\brate.?limit\b/i,/\btoo many requests\b/i,/\b429\b/,/\bquota exceeded\b/i,/\bapi credits?\b/i,/请求过多/,/频率限制/,/限流/,/配额/],dn=[/\boverloaded\b/i,/\bcapacity\b/i,/\bserver (error|busy)\b/i,/\bprovider service error\b/i,/\btry (again )?(a )?moment later\b/i,/\b(api|http|provider|status( code)?)\b[^\n]{0,40}\b5(00|02|03|29)\b/i,/\b5(00|02|03|29)\b[^\n]{0,40}\b(api|http|provider|server|status( code)?)\b/i,/\b503\b/,/\b502\b/,/\binternal server error\b/i,/\bservice unavailable\b/i,/服务繁忙/,/服务不可用/,/服务器错误/,/服务器内部错误/,/过载/,/容量不足/],Wt=[/\bconnection (error|reset|closed|refused|terminated)\b/i,/\bsocket hang up\b/i,/\bsocket closed\b/i,/\bfetch failed\b/i,/\beconnrefused\b/i,/\beconnreset\b/i,/\bepipe\b/i,/\benotfound\b/i,/\beai_again\b/i,/\bother side closed\b/i,/\bnetwork\b/i,/\baborted\b/i,/\bterminated\b/i,/\bpremature close\b/i,/\bund_err_socket\b/i,/\bund_err_closed\b/i,/\bund_err_aborted\b/i,/\bund_err_destroyed\b/i,/网络错误/,/网络异常/,/连接错误/,/连接失败/,/连接被拒绝/,/连接被重置/,/连接被终止/,/连接已终止/,/连接中断/],Kt=[/\btimed? ?out\b/i,/\betimedout\b/i,/\bheaders timeout\b/i,/\bbody timeout\b/i,/\bund_err_headers_timeout\b/i,/\bund_err_body_timeout\b/i,/\bund_err_connect_timeout\b/i,/连接超时/,/请求超时/,/响应超时/],mn=[/\bstream incomplete\b/i,/\bstream interrupted\b/i],gs=[/\bstream stalled or delayed\b/i,/\b60s idle\b/i,/\bidle timeout\b/i],ys=[/\bhard timeout\b/i,/\b10 minutes?\b/i,/\bapi hard timeout\b/i],Ts=[/reasoning_content/i,/thinking.{0,40}signature/i,/signature.{0,40}thinking/i],bs=[/\bcontext too long\b/i,/\bmaximum context\b/i,/\bcontext length\b/i,/\bcontext window\b/i,/\btoo many tokens\b/i],xs=[/\b(401|403)\b/,/\b(auth|unauthorized|forbidden|api key|not configured|permission denied)\b/i];function ot(e,t){let o=fn(e);if(e.name==="AbortError")return{errorClass:"user_abort",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0};if(e instanceof Me||N(o,hs)){let r=e instanceof Me?e.retryAfter:void 0;return{errorClass:"rate_limit",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:r??6e4}}return e instanceof _e&&N(o,dn)?{errorClass:"provider_overloaded",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:e.name==="StreamIncompleteError"||N(o,mn)?{errorClass:"incomplete_stream",failureStage:ks(o,t),retryable:!0,maxRetries:3,baseRetryDelay:2e3}:N(o,gs)?{errorClass:"stream_idle_timeout",failureStage:t??"mid_stream_text",retryable:!0,maxRetries:3,baseRetryDelay:3e3}:N(o,ys)?{errorClass:"request_timeout",failureStage:t??"before_first_delta",retryable:!0,maxRetries:2,baseRetryDelay:5e3}:e instanceof Ae&&e.isTimeout||N(o,Kt)?{errorClass:"request_timeout",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:e instanceof Ae||N(o,Wt)?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:2e3}:e instanceof _e?N(o,[...Wt,...Kt])?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:2e3}:N(o,Ts)?{errorClass:"reasoning_content_required",failureStage:t??"before_first_delta",retryable:!0,maxRetries:1,baseRetryDelay:0}:{errorClass:"non_retryable_provider_error",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0}:N(o,dn)?{errorClass:"provider_overloaded",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:N(o,[...Wt,...Kt,...mn])?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:2,baseRetryDelay:2e3}:{errorClass:"non_retryable_provider_error",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0}}i(ot,"classifyResilienceError");function vs(e,t){if(t<=0)return!1;let o=fn(e);if(N(o,xs))return!1;let r=ot(e);return r.errorClass==="provider_overloaded"||r.errorClass==="reasoning_content_required"||N(o,bs)}i(vs,"isSessionRecoveryCandidateError");function N(e,t){return t.some(o=>o.test(e))}i(N,"matchesAny");function fn(e){let t=[],o=new Set,r=e,n=0,s=5;for(;r!=null&&n<s&&!o.has(r);){if(o.add(r),r instanceof Error){r.message&&t.push(r.message);let a=r.code;typeof a=="string"&&a.length>0&&t.push(a),r=r.cause}else if(typeof r=="string")t.push(r),r=void 0;else if(typeof r=="object"){let a=r.message;typeof a=="string"&&t.push(a);let c=r.code;typeof c=="string"&&t.push(c),r=r.cause}else break;n+=1}return t.join(" | ").toLowerCase()}i(fn,"collectErrorText");function ks(e,t){return t||(/\btool.?input\b/i.test(e)||/\btool.?call\b/i.test(e)?"mid_stream_tool_input":/\bthinking\b/i.test(e)?"mid_stream_thinking":"mid_stream_text")}i(ks,"inferStageForStreamError");var ws=0;function pn(){return`req_${Date.now()}_${++ws}`}i(pn,"nextRequestId");var Ie=class{static{i(this,"StableBoundaryTracker")}state;hasReceivedFirstDelta=!1;currentToolInputId;constructor(){this.state=this.createInitialState()}beginRequest(t,o,r,n=1,s=!1){this.state={requestId:pn(),provider:t,model:o,attempt:n,lastStableMessageIndex:r.length,executedToolCallIds:[...this.state.executedToolCallIds],pendingToolCallIds:[],visibleLiveTextLength:0,visibleThinkingLength:0,fallbackUsed:s,startedAt:Date.now()},this.hasReceivedFirstDelta=!1,this.currentToolInputId=void 0}markFirstDelta(){this.hasReceivedFirstDelta=!0}markTextDelta(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.state.visibleLiveTextLength+=t.length}markThinkingDelta(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.state.visibleThinkingLength+=t.length}markToolInputStart(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.currentToolInputId=t,this.state.pendingToolCallIds.includes(t)||this.state.pendingToolCallIds.push(t)}markToolExecuted(t){this.state.pendingToolCallIds=this.state.pendingToolCallIds.filter(o=>o!==t),this.state.executedToolCallIds.includes(t)||this.state.executedToolCallIds.push(t),this.currentToolInputId===t&&(this.currentToolInputId=void 0)}markAssistantComplete(t){this.state.lastStableMessageIndex=t.length,this.state.visibleLiveTextLength=0,this.state.visibleThinkingLength=0,this.state.pendingToolCallIds=[],this.hasReceivedFirstDelta=!1}inferFailureStage(){return this.hasReceivedFirstDelta?this.currentToolInputId?"mid_stream_tool_input":this.state.visibleThinkingLength>0&&this.state.visibleLiveTextLength===0?"mid_stream_thinking":this.state.executedToolCallIds.length>0?"post_tool_execution_pre_assistant_close":"mid_stream_text":"before_first_delta"}snapshot(){return{...this.state}}get hasReceivedDelta(){return this.hasReceivedFirstDelta}recoverToStableBoundary(t){let o=Math.min(this.state.lastStableMessageIndex,t.length),r=t.slice(0,o),n=[...this.state.pendingToolCallIds],s=[...this.state.executedToolCallIds];return{messages:r,droppedToolCallIds:n,executedToolCallIds:s}}reset(){this.state=this.createInitialState(),this.hasReceivedFirstDelta=!1,this.currentToolInputId=void 0}createInitialState(){return{requestId:pn(),provider:"",model:"",attempt:1,lastStableMessageIndex:0,executedToolCallIds:[],pendingToolCallIds:[],visibleLiveTextLength:0,visibleThinkingLength:0,fallbackUsed:!1,startedAt:Date.now()}}};function rt(e,t,o){if(e.length===0)return[];let r=Es(e,o),n=Rs(r),s=t.filter(a=>!n.includes(a));return s.length>0?Ss(r,s):r}i(rt,"reconstructMessagesWithToolGuard");function Es(e,t){if(t.length===0)return[...e];let o=new Set(t);return e.map(r=>{if(typeof r.content=="string")return r;let n=r.content.filter(s=>s.type==="tool_use"?!o.has(s.id):s.type==="tool_result"?!o.has(s.tool_use_id):!0);return n.length===0?{...r,content:[{type:"text",text:""}]}:{...r,content:n}})}i(Es,"filterIncompleteToolCalls");function Rs(e){let t=[];for(let o of e)if(typeof o.content!="string")for(let r of o.content)r.type==="tool_result"&&t.push(r.tool_use_id);return t}i(Rs,"collectToolResultIds");function Ss(e,t){let o=[...e],r=t.map(n=>({type:"tool_result",tool_use_id:n,content:"[Result preserved from previous attempt - tool already executed]"}));return r.length>0&&o.push({role:"user",content:r}),o}i(Ss,"appendMissingToolResults");var Cs=["before_request_accepted","before_first_delta"],_s=["stream_idle_timeout","chunk_timeout","incomplete_stream","connection_failure"],Oe=class{static{i(this,"ProviderRecoveryCoordinator")}boundaryTracker;config;nonStreamingFallbackUsed=!1;thinkingSanitizationUsed=!1;constructor(t,o){this.boundaryTracker=t,this.config={requestTimeoutMs:o.requestTimeoutMs??6e5,streamIdleTimeoutMs:o.streamIdleTimeoutMs??6e4,chunkTimeoutMs:o.chunkTimeoutMs??3e4,maxRetries:o.maxRetries??4,maxRetryDelayMs:o.maxRetryDelayMs??6e4,enableNonStreamingFallback:o.enableNonStreamingFallback??!0}}decideRecoveryAction(t,o,r){if(!o.retryable)return{action:"manual_continue",ladderStep:4,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};if(o.errorClass==="reasoning_content_required"&&!this.thinkingSanitizationUsed)return this.thinkingSanitizationUsed=!0,{action:"sanitize_thinking_and_retry",ladderStep:2,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};if(r>=this.config.maxRetries)return{action:"manual_continue",ladderStep:4,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};let n=As(o.baseRetryDelay,r,this.config.maxRetryDelayMs),s=Ps(t),a=s!==void 0?Math.min(s,this.config.maxRetryDelayMs):n,{action:c,ladderStep:d,shouldUseNonStreaming:u}=this.selectRecoveryStrategy(o,r);return{action:c,ladderStep:d,delayMs:a,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:u,reasonCode:o.errorClass,failureStage:o.failureStage,serverRetryAfterMs:s}}executeRecovery(t,o){switch(o.action){case"fresh_connection_retry":return this.executeFreshConnectionRetry(t,o);case"stable_boundary_retry":return this.executeStableBoundaryRetry(t,o);case"non_streaming_fallback":return this.executeNonStreamingFallback(t,o);case"manual_continue":return this.executeManualContinue(t,o);case"sanitize_thinking_and_retry":return this.executeSanitizeThinking(t,o)}}selectRecoveryStrategy(t,o){let r=t.failureStage,n=t.errorClass;return _s.includes(n)&&this.config.enableNonStreamingFallback&&!this.nonStreamingFallbackUsed&&o>=2?(this.nonStreamingFallbackUsed=!0,{action:"non_streaming_fallback",ladderStep:3,shouldUseNonStreaming:!0}):Cs.includes(r)?{action:"fresh_connection_retry",ladderStep:1,shouldUseNonStreaming:!1}:{action:"stable_boundary_retry",ladderStep:2,shouldUseNonStreaming:!1}}executeFreshConnectionRetry(t,o){let r=this.boundaryTracker.snapshot();return{messages:[...t],droppedToolCallIds:[],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}executeStableBoundaryRetry(t,o){let r=this.boundaryTracker.recoverToStableBoundary(t);return{messages:rt(r.messages,r.executedToolCallIds,r.droppedToolCallIds),droppedToolCallIds:r.droppedToolCallIds,executedToolCallIds:r.executedToolCallIds,fallbackUsed:this.nonStreamingFallbackUsed}}executeNonStreamingFallback(t,o){let r=this.boundaryTracker.recoverToStableBoundary(t);return{messages:rt(r.messages,r.executedToolCallIds,r.droppedToolCallIds),droppedToolCallIds:r.droppedToolCallIds,executedToolCallIds:r.executedToolCallIds,fallbackUsed:!0}}executeManualContinue(t,o){let r=this.boundaryTracker.snapshot();return{messages:[...t],droppedToolCallIds:[...r.pendingToolCallIds],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}executeSanitizeThinking(t,o){let r=this.boundaryTracker.snapshot();return{messages:Ms(t),droppedToolCallIds:[],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}reset(){this.nonStreamingFallbackUsed=!1,this.thinkingSanitizationUsed=!1}};function Ms(e){return e.map(t=>{if(t.role!=="assistant"||typeof t.content=="string"||!Array.isArray(t.content))return t;let o=t.content.filter(r=>r.type!=="thinking"&&r.type!=="redacted_thinking");return o.length===0?{...t,content:[{type:"text",text:""}]}:{...t,content:o}})}i(Ms,"sanitizeThinkingBlocks");function As(e,t,o){let r=e*Math.pow(2,t-1),n=Math.random()*1e3;return Math.min(r+n,o)}i(As,"calculateRetryDelay");function Ps(e){if("retryAfter"in e&&typeof e.retryAfter=="number")return e.retryAfter*1e3}i(Ps,"extractServerRetryAfter");var nt=process.env.KODAX_DEBUG_STREAM==="1"||process.env.KODAX_DEBUG_RESILIENCE==="1";function Xt(e,t){nt&&console.error("[resilience:classify]",{rawError:e.message,errorClass:t.errorClass,failureStage:t.failureStage,retryable:t.retryable,maxRetries:t.maxRetries})}i(Xt,"telemetryClassify");function Yt(e,t){nt&&console.error("[resilience:decision]",{action:e.action,ladderStep:e.ladderStep,attempt:t,delayMs:e.delayMs,maxDelayMs:e.maxDelayMs,reasonCode:e.reasonCode,failureStage:e.failureStage,shouldUseNonStreaming:e.shouldUseNonStreaming,serverRetryAfterMs:e.serverRetryAfterMs})}i(Yt,"telemetryDecision");function zt(e){nt&&console.error("[resilience:boundary]",{requestId:e.requestId,provider:e.provider,attempt:e.attempt,lastStableMessageIndex:e.lastStableMessageIndex,executedToolCallIds:e.executedToolCallIds,pendingToolCallIds:e.pendingToolCallIds,visibleLiveTextLength:e.visibleLiveTextLength,visibleThinkingLength:e.visibleThinkingLength,fallbackUsed:e.fallbackUsed,failureStage:e.failureStage})}i(zt,"telemetryBoundary");function it(e,t){nt&&console.error("[resilience:recovery]",{action:e,droppedToolCallIds:t.droppedToolCallIds,executedToolCallIds:t.executedToolCallIds,fallbackUsed:t.fallbackUsed})}i(it,"telemetryRecovery");function Ne(e,t){if(!t||t.length===0)return e;let o=[{type:"text",text:e}];for(let r of t){if(r.kind!=="image")throw new Ot("MODEL_INPUT_UNSUPPORTED",`${r.kind} artifacts cannot be attached to the provider prompt yet.`,{detail:"Only image artifacts are currently lowered into provider prompt content."});o.push({type:"image",path:r.path,mediaType:r.mediaType})}return o}i(Ne,"buildPromptMessageContent");function Vt(e){return e._truncated===!0||e._salvaged===!0&&tn(e.name)}i(Vt,"isUntrustedSalvage");function gn(e){let t=[];for(let o of e){if(Vt(o)){t.push(`${o.name}: incomplete input (salvaged from malformed/truncated JSON)`);continue}let r=et(o.name),n=o.input??{};for(let s of r)(n[s]===void 0||n[s]===null||n[s]==="")&&t.push(`${o.name}: missing '${s}'`)}return t}i(gn,"checkIncompleteToolCalls");function pd(e,t=400){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}i(pd,"truncateText");function yn(e){if(!e)return"";if(typeof e.lastText=="string"&&e.lastText.trim())return e.lastText;let t=e.messages?.[e.messages.length-1];return!t||t.role!=="assistant"?"":typeof t.content=="string"?t.content:t.content.map(o=>("text"in o?o.text:"")||"").join("")}i(yn,"extractMessageText");function Is(e){return e==="running"||e==="planned"}i(Is,"isUnconvergedVerdict");function Os(e){let t=e.trim();return t===""||t==="..."}i(Os,"isPlaceholderOnlyAssistantText");function Ns(e){let t=yn(e);return Os(t)?"":t}i(Ns,"extractFinalAssistantText");function kd(e,t,o){if(!e.messages)return e;let r=Ns(e);if(Is(e.managedTask?.verdict?.status)||e.interrupted&&!r)return e;let n=t.context?.inputArtifacts,s=e.artifactLedger??Ut(e.messages),a=Ds(e.messages,o,r,n),c=e.contextTokenSnapshot?Ir(a,e.contextTokenSnapshot):void 0;return{...e,messages:a,artifactLedger:s,contextTokenSnapshot:c}}i(kd,"reshapeToUserConversation");function Ds(e,t,o,r){let n=e,s=n[0];s?.role==="system"&&typeof s.content=="string"&&!s.content.startsWith(Bt)&&(n=n.slice(1)),n=Qt(n);let c=!n.some(u=>u.role==="user"&&st(u)===t);c&&n[0]?.role==="system"&&typeof n[0].content=="string"&&n[0].content.startsWith(Bt)&&n.some(l=>l.role==="user")&&(c=!1),c&&(n=[...n,{role:"user",content:Ne(t,r)}]);let d=n[n.length-1];return d?.role==="assistant"&&typeof d.content=="string"&&d.content===o||(d?.role==="assistant"?n=[...n.slice(0,-1),{role:"assistant",content:o}]:n=[...n,{role:"assistant",content:o}]),[...n]}i(Ds,"preserveTranscriptForRoundExit");function Qt(e){let t=e.length;for(;t>=2;){let o=e[t-2],r=e[t-1];if(o.role==="user"&&r.role==="assistant"&&Fs(o)){t-=2;continue}break}return e.slice(0,t)}i(Qt,"normalizeLoadedSessionMessages");var Ls=/^\s*You are the (Scout|Planner|Generator|Evaluator) role\b/;function Fs(e){if(e.role!=="user")return!1;let t=typeof e.content=="string"?e.content:Us(e.content);return Ls.test(t)}i(Fs,"isRolePromptShapedUser");function Us(e){let t=e[0];return t?.type==="text"&&typeof t.text=="string"?t.text:""}i(Us,"extractLeadingTextBlock");function hn(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
2
|
+
import{a as Gr}from"./chunk-UA744TZM.js";import{$ as be,$a as Ze,$c as Jr,Ba as vr,Bc as qt,C as Ve,Ca as kr,Cc as Xr,D as fr,Db as Wr,Dc as Yr,Ec as b,Fc as ue,Gc as zr,Hc as Vr,Ic as Qr,Na as wr,O as pr,Qa as Er,U as hr,Va as Rr,Wa as $t,X as gr,Ya as Sr,Za as Cr,_a as _r,_c as Zr,aa as Qe,ab as Mr,bb as Ar,cb as Pr,d as ur,da as yr,db as _,e as W,eb as Ir,f as J,fb as Or,fd as en,g as dr,ga as Tr,gb as Nr,ha as br,hb as Dr,ia as xr,ib as Lr,jb as Fr,kb as z,lb as xe,mb as Ur,nb as ve,ob as Je,pa as Ht,pb as Br,pd as tn,qb as Hr,qd as et,rb as $r,sb as qr,sd as tt,tb as jr,td as on,vd as rn,wd as nn,xc as Kr,y as mr}from"./chunk-7COB3EKF.js";import{A as ce,B as Do,F as Lo,Ga as Pt,Ja as Te,O as Fo,Q as Uo,Ra as It,T as ye,Va as Bo,Wa as Ho,Xa as $o,Ya as qo,_a as jo,b as _e,c as Me,d as Ae,e as No,pa as Mt,xa as At}from"./chunk-S4GVQO3W.js";import{$c as Lt,Ba as zo,Bd as Ut,Ca as Vo,Eb as Zo,Jd as Bt,Md as nr,Nd as ir,Od as sr,Td as ar,Ud as cr,Wd as lr,ad as Ft,bd as Jo,dd as er,ed as tr,f as Z,fd as or,g as Ye,gd as rr,j as Wo,k as le,m as Ko,mb as Pe,na as Xo,nb as Dt,oa as Nt,vb as ze,wa as Yo,wb as Qo}from"./chunk-NJW2LQOP.js";import{a as Ot,z as Go}from"./chunk-ZL5CEANW.js";import{a as i}from"./chunk-V4WSBIXB.js";import{readFile as ls}from"fs/promises";var sn=75;function us(e){return typeof e!="number"||e<=0?sn:e<=2e5?60:e<=256e3?65:e<=5e5?70:75}i(us,"adaptiveTriggerPercent");var ds={enabled:!0};async function an(e,t){let o=Yo("config.json"),r;try{let a=await ms(o);a?.compaction&&(r=a.compaction)}catch{}let n={...ds,...r,triggerPercent:sn};t?.enabled!==void 0&&(n.enabled=t.enabled),t?.contextWindow!==void 0&&(n.contextWindow=t.contextWindow);let s=n.contextWindow??e;return n.triggerPercent=typeof t?.triggerPercent=="number"?t.triggerPercent:typeof r?.triggerPercent=="number"?r.triggerPercent:us(s),n}i(an,"loadCompactionConfig");async function ms(e){try{let t=await ls(e,"utf-8");return JSON.parse(t)}catch{return null}}i(ms,"readConfigFile");var H;(function(e){e[e.TRANSIENT=0]="TRANSIENT",e[e.PERMANENT=1]="PERMANENT",e[e.TOOL_CALL_ID=2]="TOOL_CALL_ID",e[e.USER_ABORT=3]="USER_ABORT"})(H||(H={}));var fs=[/\bstream incomplete\b/i,/\bstream interrupted\b/i,/\bstream stalled\b/i,/\bdelayed response\b/i,/\btimed out\b/i,/\btimeout\b/i,/\bnetwork\b/i,/\bconnection error\b/i,/\bconnection reset\b/i,/\bconnection closed\b/i,/\bsocket hang up\b/i,/\bfetch failed\b/i,/\beconnrefused\b/i,/\beconnreset\b/i,/\betimedout\b/i,/\benotfound\b/i,/\beai_again\b/i,/\bother side closed\b/i,/\baborted\b/i,/网络错误/,/网络异常/,/连接超时/,/连接错误/,/连接失败/,/连接被拒绝/,/请求超时/,/服务繁忙/,/服务不可用/,/服务器错误/,/服务器内部错误/,/请求过多/,/频率限制/,/限流/,/过载/,/容量不足/];function cn(e){return fs.some(t=>t.test(e))}i(cn,"matchesTransientMessage");function ps(e){if(e.name==="StreamIncompleteError"||e.message.includes("Stream incomplete"))return{category:H.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:2e3,shouldCleanup:!0};if(e.name==="AbortError")return{category:H.USER_ABORT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0};if(e instanceof No||e.message.includes("tool_call_id")||e.message.includes("tool result"))return{category:H.TOOL_CALL_ID,retryable:!0,maxRetries:1,retryDelay:1e3,shouldCleanup:!0};if(e instanceof Me)return{category:H.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:e.retryAfter??6e4,shouldCleanup:!0};if(e instanceof Ae)return{category:H.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:e.isTimeout?5e3:2e3,shouldCleanup:!0};if(e instanceof _e){let o=e.message.toLowerCase();return cn(o)?{category:H.TRANSIENT,retryable:!0,maxRetries:3,retryDelay:2e3,shouldCleanup:!0}:{category:H.PERMANENT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0}}let t=e.message.toLowerCase();return cn(t)?{category:H.TRANSIENT,retryable:!0,maxRetries:2,retryDelay:2e3,shouldCleanup:!0}:{category:H.PERMANENT,retryable:!1,maxRetries:0,retryDelay:0,shouldCleanup:!0}}i(ps,"classifyError");function jt(e,t){return new Promise((o,r)=>{if(t?.aborted){r(t.reason instanceof Error?t.reason:new DOMException("Request aborted","AbortError"));return}let n,s=t;if(!s){n=setTimeout(()=>{o()},e);return}let a=i(()=>{clearTimeout(n),s.removeEventListener("abort",a),r(s.reason instanceof Error?s.reason:new DOMException("Request aborted","AbortError"))},"onAbort");n=setTimeout(()=>{s.removeEventListener("abort",a),o()},e),s.addEventListener("abort",a,{once:!0})})}i(jt,"waitForRetryDelay");var un={requestTimeoutMs:6e5,streamIdleTimeoutMs:Number(process.env.KODAX_STREAM_IDLE_TIMEOUT_MS)||0,chunkTimeoutMs:3e4,maxRetries:4,maxRetryDelayMs:6e4,enableNonStreamingFallback:!0};function Gt(e,t,o){let r={...un};if(t&&ln(r,t),o&&o.length>0){let n=o.find(s=>s.provider===e);if(n){let{provider:s,...a}=n;ln(r,a)}}return r}i(Gt,"resolveResilienceConfig");function ln(e,t){t.requestTimeoutMs!==void 0&&(e.requestTimeoutMs=t.requestTimeoutMs),t.streamIdleTimeoutMs!==void 0&&(e.streamIdleTimeoutMs=t.streamIdleTimeoutMs),t.chunkTimeoutMs!==void 0&&(e.chunkTimeoutMs=t.chunkTimeoutMs),t.maxRetries!==void 0&&(e.maxRetries=t.maxRetries),t.maxRetryDelayMs!==void 0&&(e.maxRetryDelayMs=t.maxRetryDelayMs),t.enableNonStreamingFallback!==void 0&&(e.enableNonStreamingFallback=t.enableNonStreamingFallback)}i(ln,"mergePartialConfig");var hs=[/\brate.?limit\b/i,/\btoo many requests\b/i,/\b429\b/,/\bquota exceeded\b/i,/\bapi credits?\b/i,/请求过多/,/频率限制/,/限流/,/配额/],dn=[/\boverloaded\b/i,/\bcapacity\b/i,/\bserver (error|busy)\b/i,/\bprovider service error\b/i,/\btry (again )?(a )?moment later\b/i,/\b(api|http|provider|status( code)?)\b[^\n]{0,40}\b5(00|02|03|29)\b/i,/\b5(00|02|03|29)\b[^\n]{0,40}\b(api|http|provider|server|status( code)?)\b/i,/\b503\b/,/\b502\b/,/\binternal server error\b/i,/\bservice unavailable\b/i,/服务繁忙/,/服务不可用/,/服务器错误/,/服务器内部错误/,/过载/,/容量不足/],Wt=[/\bconnection (error|reset|closed|refused|terminated)\b/i,/\bsocket hang up\b/i,/\bsocket closed\b/i,/\bfetch failed\b/i,/\beconnrefused\b/i,/\beconnreset\b/i,/\bepipe\b/i,/\benotfound\b/i,/\beai_again\b/i,/\bother side closed\b/i,/\bnetwork\b/i,/\baborted\b/i,/\bterminated\b/i,/\bpremature close\b/i,/\bund_err_socket\b/i,/\bund_err_closed\b/i,/\bund_err_aborted\b/i,/\bund_err_destroyed\b/i,/网络错误/,/网络异常/,/连接错误/,/连接失败/,/连接被拒绝/,/连接被重置/,/连接被终止/,/连接已终止/,/连接中断/],Kt=[/\btimed? ?out\b/i,/\betimedout\b/i,/\bheaders timeout\b/i,/\bbody timeout\b/i,/\bund_err_headers_timeout\b/i,/\bund_err_body_timeout\b/i,/\bund_err_connect_timeout\b/i,/连接超时/,/请求超时/,/响应超时/],mn=[/\bstream incomplete\b/i,/\bstream interrupted\b/i],gs=[/\bstream stalled or delayed\b/i,/\b60s idle\b/i,/\bidle timeout\b/i],ys=[/\bhard timeout\b/i,/\b10 minutes?\b/i,/\bapi hard timeout\b/i],Ts=[/reasoning_content/i,/thinking.{0,40}signature/i,/signature.{0,40}thinking/i],bs=[/\bcontext too long\b/i,/\bmaximum context\b/i,/\bcontext length\b/i,/\bcontext window\b/i,/\btoo many tokens\b/i],xs=[/\b(401|403)\b/,/\b(auth|unauthorized|forbidden|api key|not configured|permission denied)\b/i];function ot(e,t){let o=fn(e);if(e.name==="AbortError")return{errorClass:"user_abort",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0};if(e instanceof Me||N(o,hs)){let r=e instanceof Me?e.retryAfter:void 0;return{errorClass:"rate_limit",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:r??6e4}}return e instanceof _e&&N(o,dn)?{errorClass:"provider_overloaded",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:e.name==="StreamIncompleteError"||N(o,mn)?{errorClass:"incomplete_stream",failureStage:ks(o,t),retryable:!0,maxRetries:3,baseRetryDelay:2e3}:N(o,gs)?{errorClass:"stream_idle_timeout",failureStage:t??"mid_stream_text",retryable:!0,maxRetries:3,baseRetryDelay:3e3}:N(o,ys)?{errorClass:"request_timeout",failureStage:t??"before_first_delta",retryable:!0,maxRetries:2,baseRetryDelay:5e3}:e instanceof Ae&&e.isTimeout||N(o,Kt)?{errorClass:"request_timeout",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:e instanceof Ae||N(o,Wt)?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:2e3}:e instanceof _e?N(o,[...Wt,...Kt])?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:2e3}:N(o,Ts)?{errorClass:"reasoning_content_required",failureStage:t??"before_first_delta",retryable:!0,maxRetries:1,baseRetryDelay:0}:{errorClass:"non_retryable_provider_error",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0}:N(o,dn)?{errorClass:"provider_overloaded",failureStage:t??"before_first_delta",retryable:!0,maxRetries:3,baseRetryDelay:5e3}:N(o,[...Wt,...Kt,...mn])?{errorClass:"connection_failure",failureStage:t??"before_first_delta",retryable:!0,maxRetries:2,baseRetryDelay:2e3}:{errorClass:"non_retryable_provider_error",failureStage:t??"before_first_delta",retryable:!1,maxRetries:0,baseRetryDelay:0}}i(ot,"classifyResilienceError");function vs(e,t){if(t<=0)return!1;let o=fn(e);if(N(o,xs))return!1;let r=ot(e);return r.errorClass==="provider_overloaded"||r.errorClass==="reasoning_content_required"||N(o,bs)}i(vs,"isSessionRecoveryCandidateError");function N(e,t){return t.some(o=>o.test(e))}i(N,"matchesAny");function fn(e){let t=[],o=new Set,r=e,n=0,s=5;for(;r!=null&&n<s&&!o.has(r);){if(o.add(r),r instanceof Error){r.message&&t.push(r.message);let a=r.code;typeof a=="string"&&a.length>0&&t.push(a),r=r.cause}else if(typeof r=="string")t.push(r),r=void 0;else if(typeof r=="object"){let a=r.message;typeof a=="string"&&t.push(a);let c=r.code;typeof c=="string"&&t.push(c),r=r.cause}else break;n+=1}return t.join(" | ").toLowerCase()}i(fn,"collectErrorText");function ks(e,t){return t||(/\btool.?input\b/i.test(e)||/\btool.?call\b/i.test(e)?"mid_stream_tool_input":/\bthinking\b/i.test(e)?"mid_stream_thinking":"mid_stream_text")}i(ks,"inferStageForStreamError");var ws=0;function pn(){return`req_${Date.now()}_${++ws}`}i(pn,"nextRequestId");var Ie=class{static{i(this,"StableBoundaryTracker")}state;hasReceivedFirstDelta=!1;currentToolInputId;constructor(){this.state=this.createInitialState()}beginRequest(t,o,r,n=1,s=!1){this.state={requestId:pn(),provider:t,model:o,attempt:n,lastStableMessageIndex:r.length,executedToolCallIds:[...this.state.executedToolCallIds],pendingToolCallIds:[],visibleLiveTextLength:0,visibleThinkingLength:0,fallbackUsed:s,startedAt:Date.now()},this.hasReceivedFirstDelta=!1,this.currentToolInputId=void 0}markFirstDelta(){this.hasReceivedFirstDelta=!0}markTextDelta(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.state.visibleLiveTextLength+=t.length}markThinkingDelta(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.state.visibleThinkingLength+=t.length}markToolInputStart(t){this.hasReceivedFirstDelta||this.markFirstDelta(),this.currentToolInputId=t,this.state.pendingToolCallIds.includes(t)||this.state.pendingToolCallIds.push(t)}markToolExecuted(t){this.state.pendingToolCallIds=this.state.pendingToolCallIds.filter(o=>o!==t),this.state.executedToolCallIds.includes(t)||this.state.executedToolCallIds.push(t),this.currentToolInputId===t&&(this.currentToolInputId=void 0)}markAssistantComplete(t){this.state.lastStableMessageIndex=t.length,this.state.visibleLiveTextLength=0,this.state.visibleThinkingLength=0,this.state.pendingToolCallIds=[],this.hasReceivedFirstDelta=!1}inferFailureStage(){return this.hasReceivedFirstDelta?this.currentToolInputId?"mid_stream_tool_input":this.state.visibleThinkingLength>0&&this.state.visibleLiveTextLength===0?"mid_stream_thinking":this.state.executedToolCallIds.length>0?"post_tool_execution_pre_assistant_close":"mid_stream_text":"before_first_delta"}snapshot(){return{...this.state}}get hasReceivedDelta(){return this.hasReceivedFirstDelta}recoverToStableBoundary(t){let o=Math.min(this.state.lastStableMessageIndex,t.length),r=t.slice(0,o),n=[...this.state.pendingToolCallIds],s=[...this.state.executedToolCallIds];return{messages:r,droppedToolCallIds:n,executedToolCallIds:s}}reset(){this.state=this.createInitialState(),this.hasReceivedFirstDelta=!1,this.currentToolInputId=void 0}createInitialState(){return{requestId:pn(),provider:"",model:"",attempt:1,lastStableMessageIndex:0,executedToolCallIds:[],pendingToolCallIds:[],visibleLiveTextLength:0,visibleThinkingLength:0,fallbackUsed:!1,startedAt:Date.now()}}};function rt(e,t,o){if(e.length===0)return[];let r=Es(e,o),n=Rs(r),s=t.filter(a=>!n.includes(a));return s.length>0?Ss(r,s):r}i(rt,"reconstructMessagesWithToolGuard");function Es(e,t){if(t.length===0)return[...e];let o=new Set(t);return e.map(r=>{if(typeof r.content=="string")return r;let n=r.content.filter(s=>s.type==="tool_use"?!o.has(s.id):s.type==="tool_result"?!o.has(s.tool_use_id):!0);return n.length===0?{...r,content:[{type:"text",text:""}]}:{...r,content:n}})}i(Es,"filterIncompleteToolCalls");function Rs(e){let t=[];for(let o of e)if(typeof o.content!="string")for(let r of o.content)r.type==="tool_result"&&t.push(r.tool_use_id);return t}i(Rs,"collectToolResultIds");function Ss(e,t){let o=[...e],r=t.map(n=>({type:"tool_result",tool_use_id:n,content:"[Result preserved from previous attempt - tool already executed]"}));return r.length>0&&o.push({role:"user",content:r}),o}i(Ss,"appendMissingToolResults");var Cs=["before_request_accepted","before_first_delta"],_s=["stream_idle_timeout","chunk_timeout","incomplete_stream","connection_failure"],Oe=class{static{i(this,"ProviderRecoveryCoordinator")}boundaryTracker;config;nonStreamingFallbackUsed=!1;thinkingSanitizationUsed=!1;constructor(t,o){this.boundaryTracker=t,this.config={requestTimeoutMs:o.requestTimeoutMs??6e5,streamIdleTimeoutMs:o.streamIdleTimeoutMs??6e4,chunkTimeoutMs:o.chunkTimeoutMs??3e4,maxRetries:o.maxRetries??4,maxRetryDelayMs:o.maxRetryDelayMs??6e4,enableNonStreamingFallback:o.enableNonStreamingFallback??!0}}decideRecoveryAction(t,o,r){if(!o.retryable)return{action:"manual_continue",ladderStep:4,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};if(o.errorClass==="reasoning_content_required"&&!this.thinkingSanitizationUsed)return this.thinkingSanitizationUsed=!0,{action:"sanitize_thinking_and_retry",ladderStep:2,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};if(r>=this.config.maxRetries)return{action:"manual_continue",ladderStep:4,delayMs:0,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:!1,reasonCode:o.errorClass,failureStage:o.failureStage};let n=As(o.baseRetryDelay,r,this.config.maxRetryDelayMs),s=Ps(t),a=s!==void 0?Math.min(s,this.config.maxRetryDelayMs):n,{action:c,ladderStep:d,shouldUseNonStreaming:u}=this.selectRecoveryStrategy(o,r);return{action:c,ladderStep:d,delayMs:a,maxDelayMs:this.config.maxRetryDelayMs,shouldUseNonStreaming:u,reasonCode:o.errorClass,failureStage:o.failureStage,serverRetryAfterMs:s}}executeRecovery(t,o){switch(o.action){case"fresh_connection_retry":return this.executeFreshConnectionRetry(t,o);case"stable_boundary_retry":return this.executeStableBoundaryRetry(t,o);case"non_streaming_fallback":return this.executeNonStreamingFallback(t,o);case"manual_continue":return this.executeManualContinue(t,o);case"sanitize_thinking_and_retry":return this.executeSanitizeThinking(t,o)}}selectRecoveryStrategy(t,o){let r=t.failureStage,n=t.errorClass;return _s.includes(n)&&this.config.enableNonStreamingFallback&&!this.nonStreamingFallbackUsed&&o>=2?(this.nonStreamingFallbackUsed=!0,{action:"non_streaming_fallback",ladderStep:3,shouldUseNonStreaming:!0}):Cs.includes(r)?{action:"fresh_connection_retry",ladderStep:1,shouldUseNonStreaming:!1}:{action:"stable_boundary_retry",ladderStep:2,shouldUseNonStreaming:!1}}executeFreshConnectionRetry(t,o){let r=this.boundaryTracker.snapshot();return{messages:[...t],droppedToolCallIds:[],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}executeStableBoundaryRetry(t,o){let r=this.boundaryTracker.recoverToStableBoundary(t);return{messages:rt(r.messages,r.executedToolCallIds,r.droppedToolCallIds),droppedToolCallIds:r.droppedToolCallIds,executedToolCallIds:r.executedToolCallIds,fallbackUsed:this.nonStreamingFallbackUsed}}executeNonStreamingFallback(t,o){let r=this.boundaryTracker.recoverToStableBoundary(t);return{messages:rt(r.messages,r.executedToolCallIds,r.droppedToolCallIds),droppedToolCallIds:r.droppedToolCallIds,executedToolCallIds:r.executedToolCallIds,fallbackUsed:!0}}executeManualContinue(t,o){let r=this.boundaryTracker.snapshot();return{messages:[...t],droppedToolCallIds:[...r.pendingToolCallIds],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}executeSanitizeThinking(t,o){let r=this.boundaryTracker.snapshot();return{messages:Ms(t),droppedToolCallIds:[],executedToolCallIds:[...r.executedToolCallIds],fallbackUsed:this.nonStreamingFallbackUsed}}reset(){this.nonStreamingFallbackUsed=!1,this.thinkingSanitizationUsed=!1}};function Ms(e){return e.map(t=>{if(t.role!=="assistant"||typeof t.content=="string"||!Array.isArray(t.content))return t;let o=t.content.filter(r=>r.type!=="thinking"&&r.type!=="redacted_thinking");return o.length===0?{...t,content:[{type:"text",text:""}]}:{...t,content:o}})}i(Ms,"sanitizeThinkingBlocks");function As(e,t,o){let r=e*Math.pow(2,t-1),n=Math.random()*1e3;return Math.min(r+n,o)}i(As,"calculateRetryDelay");function Ps(e){if("retryAfter"in e&&typeof e.retryAfter=="number")return e.retryAfter*1e3}i(Ps,"extractServerRetryAfter");var nt=process.env.KODAX_DEBUG_STREAM==="1"||process.env.KODAX_DEBUG_RESILIENCE==="1";function Xt(e,t){nt&&console.error("[resilience:classify]",{rawError:e.message,errorClass:t.errorClass,failureStage:t.failureStage,retryable:t.retryable,maxRetries:t.maxRetries})}i(Xt,"telemetryClassify");function Yt(e,t){nt&&console.error("[resilience:decision]",{action:e.action,ladderStep:e.ladderStep,attempt:t,delayMs:e.delayMs,maxDelayMs:e.maxDelayMs,reasonCode:e.reasonCode,failureStage:e.failureStage,shouldUseNonStreaming:e.shouldUseNonStreaming,serverRetryAfterMs:e.serverRetryAfterMs})}i(Yt,"telemetryDecision");function zt(e){nt&&console.error("[resilience:boundary]",{requestId:e.requestId,provider:e.provider,attempt:e.attempt,lastStableMessageIndex:e.lastStableMessageIndex,executedToolCallIds:e.executedToolCallIds,pendingToolCallIds:e.pendingToolCallIds,visibleLiveTextLength:e.visibleLiveTextLength,visibleThinkingLength:e.visibleThinkingLength,fallbackUsed:e.fallbackUsed,failureStage:e.failureStage})}i(zt,"telemetryBoundary");function it(e,t){nt&&console.error("[resilience:recovery]",{action:e,droppedToolCallIds:t.droppedToolCallIds,executedToolCallIds:t.executedToolCallIds,fallbackUsed:t.fallbackUsed})}i(it,"telemetryRecovery");function Ne(e,t){if(!t||t.length===0)return e;let o=[{type:"text",text:e}];for(let r of t){if(r.kind!=="image")throw new Ot("MODEL_INPUT_UNSUPPORTED",`${r.kind} artifacts cannot be attached to the provider prompt yet.`,{detail:"Only image artifacts are currently lowered into provider prompt content."});o.push({type:"image",path:r.path,mediaType:r.mediaType})}return o}i(Ne,"buildPromptMessageContent");function Vt(e){return e._truncated===!0||e._salvaged===!0&&tn(e.name)}i(Vt,"isUntrustedSalvage");function gn(e){let t=[];for(let o of e){if(Vt(o)){t.push(`${o.name}: incomplete input (salvaged from malformed/truncated JSON)`);continue}let r=et(o.name),n=o.input??{};for(let s of r)(n[s]===void 0||n[s]===null||n[s]==="")&&t.push(`${o.name}: missing '${s}'`)}return t}i(gn,"checkIncompleteToolCalls");function pd(e,t=400){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}i(pd,"truncateText");function yn(e){if(!e)return"";if(typeof e.lastText=="string"&&e.lastText.trim())return e.lastText;let t=e.messages?.[e.messages.length-1];return!t||t.role!=="assistant"?"":typeof t.content=="string"?t.content:t.content.map(o=>("text"in o?o.text:"")||"").join("")}i(yn,"extractMessageText");function Is(e){return e==="running"||e==="planned"}i(Is,"isUnconvergedVerdict");function Os(e){let t=e.trim();return t===""||t==="..."}i(Os,"isPlaceholderOnlyAssistantText");function Ns(e){let t=yn(e);return Os(t)?"":t}i(Ns,"extractFinalAssistantText");function kd(e,t,o){if(!e.messages)return e;let r=Ns(e);if(Is(e.managedTask?.verdict?.status)||e.interrupted&&!r)return e;let n=t.context?.inputArtifacts,s=e.artifactLedger??Ut(e.messages),a=Ds(e.messages,o,r,n),c=e.contextTokenSnapshot?Ir(a,e.contextTokenSnapshot):void 0;return{...e,messages:a,artifactLedger:s,contextTokenSnapshot:c}}i(kd,"reshapeToUserConversation");function Ds(e,t,o,r){let n=e,s=n[0];s?.role==="system"&&typeof s.content=="string"&&!s.content.startsWith(Bt)&&(n=n.slice(1)),n=Qt(n);let c=!n.some(u=>u.role==="user"&&st(u)===t);c&&n[0]?.role==="system"&&typeof n[0].content=="string"&&n[0].content.startsWith(Bt)&&n.some(l=>l.role==="user")&&(c=!1),c&&(n=[...n,{role:"user",content:Ne(t,r)}]);let d=n[n.length-1];return d?.role==="assistant"&&typeof d.content=="string"&&d.content===o||(d?.role==="assistant"?n=[...n.slice(0,-1),{role:"assistant",content:o}]:n=[...n,{role:"assistant",content:o}]),[...n]}i(Ds,"preserveTranscriptForRoundExit");function Qt(e){let t=e.length;for(;t>=2;){let o=e[t-2],r=e[t-1];if(o.role==="user"&&r.role==="assistant"&&Fs(o)){t-=2;continue}break}return e.slice(0,t)}i(Qt,"normalizeLoadedSessionMessages");var Ls=/^\s*You are the (Scout|Planner|Generator|Evaluator) role\b/;function Fs(e){if(e.role!=="user")return!1;let t=typeof e.content=="string"?e.content:Us(e.content);return Ls.test(t)}i(Fs,"isRolePromptShapedUser");function Us(e){let t=e[0];return t?.type==="text"&&typeof t.text=="string"?t.text:""}i(Us,"extractLeadingTextBlock");function hn(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
3
3
|
`)}i(hn,"extractPromptComparableText");function st(e){if(!(!e||e.role!=="user"))return hn(e.content)}i(st,"extractComparableUserMessageText");async function Tn(e,t){if(e.session?.initialMessages&&e.session.initialMessages.length>0){let o=[...e.session.initialMessages],n=!(e.session.initialExtensionState!==void 0||e.session.initialExtensionRecords!==void 0)&&e.session.storage&&t?await e.session.storage.load(t).catch(()=>null):null;return{messages:o,title:Ft(o),errorMetadata:n?.errorMetadata,loadedExtensionState:e.session.initialExtensionState??n?.extensionState,loadedExtensionRecords:e.session.initialExtensionRecords??n?.extensionRecords}}if(e.session?.storage&&t){let o=await e.session.storage.load(t);if(o)return{messages:Qt(o.messages),title:o.title,errorMetadata:o.errorMetadata,loadedExtensionState:o.extensionState,loadedExtensionRecords:o.extensionRecords}}return{messages:[],title:""}}i(Tn,"resolveInitialMessages");function bn(e,t,o,r){let n=e[e.length-1];return st(n)===t?r!==void 0&&n!==void 0&&n.turnId===void 0?[...e.slice(0,-1),{...n,turnId:r}]:e:[...e,{role:"user",content:Ne(t,o),...r!==void 0?{turnId:r}:{},timestamp:new Date().toISOString()}]}i(bn,"appendPromptIfNotDuplicate");async function xn(e){let t=e.session?.id;if(t)return t;if(!(e.session?.autoResume||e.session?.resume))return;let r=e.session?.storage;if(!r?.list)return;let n=await r.list(e.context?.gitRoot??void 0);return n.length>0?n[0].id:void 0}i(xn,"discoverAutoResumeSessionId");function Bs(e){return Mt(e)?"builtin":Pt(e)?"runtime":At(e)?"custom":"unknown"}i(Bs,"detectProviderSourceKind");function Hs(e,t){return e?e.getCapabilityProfile():t??{transport:"native-api",conversationSemantics:"full-history",mcpSupport:"none"}}i(Hs,"resolveCapabilityProfile");function $s(e,t,o){return e?e.getReasoningCapability(t):o??"unknown"}i($s,"resolveReasoningCapability");function qs(e){let t=Uo(Hs(e.provider,e.capabilityProfile));return{provider:e.providerName,model:e.model,sourceKind:Bs(e.providerName),transport:t.transport,conversationSemantics:t.conversationSemantics,mcpSupport:t.mcpSupport,contextFidelity:t.contextFidelity,toolCallingFidelity:t.toolCallingFidelity,sessionSupport:t.sessionSupport,longRunningSupport:t.longRunningSupport,multimodalSupport:t.multimodalSupport,evidenceSupport:t.evidenceSupport,reasoningCapability:$s(e.provider,e.model,e.reasoningCapability)}}i(qs,"buildProviderCapabilitySnapshot");function js(e){return!!e?.inputArtifacts?.some(t=>t.kind==="image")}i(js,"detectMultimodalContext");function Gs(e){if(!e)return{};let t=e.toLowerCase();return{evidenceHeavy:/merge blocker|review|strict audit|runtime error|stack trace|stderr|failing test|evidence/.test(t)?!0:void 0}}i(Gs,"inferPromptPolicyHints");function ke(...e){return e.find(t=>t!==void 0)}i(ke,"pickBoolean");function Ws(e){let t=e.context??e.options?.context,o=Gs(e.prompt);return{longRunning:ke(e.hints?.longRunning,t?.providerPolicyHints?.longRunning,o.longRunning),harnessProfile:e.hints?.harnessProfile??t?.providerPolicyHints?.harnessProfile,evidenceHeavy:ke(e.hints?.evidenceHeavy,t?.providerPolicyHints?.evidenceHeavy,o.evidenceHeavy),multimodal:ke(e.hints?.multimodal,t?.providerPolicyHints?.multimodal,js(t),o.multimodal),capabilityRuntime:ke(e.hints?.capabilityRuntime,t?.providerPolicyHints?.capabilityRuntime,o.capabilityRuntime),mcpRequired:ke(e.hints?.mcpRequired,t?.providerPolicyHints?.mcpRequired,o.mcpRequired),brainstorm:ke(e.hints?.brainstorm,t?.providerPolicyHints?.brainstorm,o.brainstorm),workIntent:e.hints?.workIntent??t?.providerPolicyHints?.workIntent??o.workIntent}}i(Ws,"resolveProviderPolicyHints");function ee(e,t){e.some(o=>o.code===t.code)||e.push(t)}i(ee,"pushIssue");function Ks(e,t){let o=new Set;e.transport==="cli-bridge"&&o.add("Provider uses a CLI bridge rather than a native API, so semantic parity should not be assumed."),e.conversationSemantics==="last-user-message"&&o.add("Provider forwards only the latest user message instead of preserving full-history semantics.");for(let r of t)o.add(r.detail);return Array.from(o)}i(Ks,"buildRoutingNotes");function Xs(e){return e.length===0?"No provider-policy constraints detected.":e.map(t=>`${t.severity.toUpperCase()}: ${t.summary}`).join(" | ")}i(Xs,"summarizeIssues");function vn(e){return[...[`[Provider Policy] provider=${e.snapshot.provider}${e.snapshot.model?` model=${e.snapshot.model}`:""}; status=${e.status}.`,`[Provider Semantics] transport=${e.snapshot.transport}; context=${e.snapshot.contextFidelity}; toolCalling=${e.snapshot.toolCallingFidelity}; session=${e.snapshot.sessionSupport}; longRunning=${e.snapshot.longRunningSupport}; multimodal=${e.snapshot.multimodalSupport}; evidence=${e.snapshot.evidenceSupport}; mcp=${e.snapshot.mcpSupport}; reasoning=${e.snapshot.reasoningCapability}.`],...e.issues.map(o=>`[Provider Constraint] ${o.severity.toUpperCase()}: ${o.detail}`)]}i(vn,"buildProviderPolicyPromptNotes");function at(e){let t=qs({providerName:e.providerName,model:e.model,provider:e.provider,capabilityProfile:e.capabilityProfile,reasoningCapability:e.reasoningCapability}),o=Ws(e),r=[];return o.multimodal&&t.multimodalSupport==="none"&&ee(r,{code:"multimodal-unsupported",severity:"block",summary:"multimodal requests are unsupported on this provider",detail:"This flow requests multimodal or image semantics, but the selected provider only exposes text-only behavior."}),o.mcpRequired&&t.mcpSupport==="none"?ee(r,{code:"mcp-required",severity:"block",summary:"native MCP semantics are unavailable on this provider",detail:"This flow explicitly requires MCP-native behavior, but the selected provider reports no native MCP support."}):o.capabilityRuntime&&t.mcpSupport==="none"&&ee(r,{code:"capability-runtime-limited",severity:"warn",summary:"capability-oriented flows are constrained by provider semantics",detail:"Capability or MCP-oriented workflows may lose parity because the provider does not expose native MCP semantics."}),o.longRunning&&(t.longRunningSupport==="none"||t.sessionSupport==="stateless"||t.contextFidelity==="lossy"?ee(r,{code:"long-running-blocked",severity:"block",summary:"long-running execution is unsafe on this provider",detail:"Long-running flows require durable session semantics and reliable context fidelity, but this provider reports lossy or stateless behavior."}):(t.longRunningSupport==="limited"||t.sessionSupport==="limited")&&ee(r,{code:"long-running-limited",severity:"warn",summary:"long-running execution is degraded on this provider",detail:"Long-running flows may behave inconsistently because this provider only offers limited session or long-running support."})),(o.evidenceHeavy===!0||e.taskType==="review"||e.taskType==="bugfix"||e.executionMode==="pr-review"||e.executionMode==="strict-audit"||e.executionMode==="investigation")&&(t.contextFidelity==="lossy"&&ee(r,{code:"evidence-context-loss",severity:"warn",summary:"evidence-heavy work is constrained by lossy context semantics",detail:"Evidence-heavy routing remains available, but this provider can lose prior-turn context and should not be treated as equivalent to full-history providers."}),t.evidenceSupport==="limited"&&ee(r,{code:"evidence-support-limited",severity:"warn",summary:"evidence-heavy work may lose fidelity on this provider",detail:"This provider only reports limited evidence support, so review and investigation flows may need extra caution."})),e.reasoningMode!=="off"&&(t.reasoningCapability==="prompt-only"||t.reasoningCapability==="none")&&ee(r,{code:"reasoning-control-limited",severity:"warn",summary:"native reasoning control is unavailable on this provider",detail:"Reasoning remains usable, but the provider cannot enforce native reasoning controls beyond prompt-level guidance."}),{status:r.some(a=>a.severity==="block")?"block":r.length>0?"warn":"allow",snapshot:t,issues:r,routingNotes:Ks(t,r),summary:Xs(r)}}i(at,"evaluateProviderPolicy");var Ys="off",zs=.4,Vs=.42,Qs=.45,kn=.5,Zs=.06,Js=.04,ea=.86,ta=.75,oa=.49,ra=.5;var na=["brainstorm","explore","explore options","option framing","tradeoff","trade-off","safest way","figure out","design first","\u65B9\u6848","\u601D\u8DEF","\u5148\u60F3","\u5148\u8BBE\u8BA1","\u5148\u5206\u6790","\u5148\u8BA8\u8BBA"],ia=["continue","extend","build on","follow up","append","add to","based on the existing","\u63A5\u7740","\u7EE7\u7EED","\u8865\u5145","\u8FFD\u52A0","\u5EF6\u7EED","\u6269\u5C55\u73B0\u6709"],sa=["rewrite","replace","overwrite","from scratch","start over","regenerate","redo","\u91CD\u5199","\u66FF\u6362","\u8986\u76D6","\u63A8\u5012\u91CD\u6765","\u5168\u90E8\u6539\u6389","\u91CD\u65B0\u505A"],Zt={simple:[],moderate:["screen","component","endpoint","service","feature","\u6A21\u5757","\u529F\u80FD","\u9875\u9762"],complex:["migration","architecture","cross-package","multi-step","pipeline","state machine","refactor","monorepo","across packages","integration","\u8FC1\u79FB","\u67B6\u6784","\u8DE8\u5305","\u91CD\u6784","\u6D41\u7A0B"],systemic:["system-wide","orchestrate","multi-agent","control plane","runtime substrate","whole repo","entire repo","across the monorepo","\u5168\u4ED3","\u5168\u5C40","\u6574\u4F53\u67B6\u6784","\u63A7\u5236\u9762","\u591A\u667A\u80FD\u4F53"]},aa=2,ca=4,la=6,ua=10,Jt=1200;var da=30,In=4e3;function On(e){return e.reasoningMode?e.reasoningMode:e.thinking===!0?"auto":e.thinking===!1?"off":Ys}i(On,"resolveReasoningMode");function ma(e){return Lo(e)}i(ma,"reasoningModeToDepth");var wn={none:0,minimal:0,auto:1,low:2,medium:3,high:4,xhigh:5,max:6};function En(e){return wn[e]??wn.medium}i(En,"effortRank");function fa(e,t){let o=En(e),r=En(t);return o<r?-1:o>r?1:0}i(fa,"compareEfforts");function Rn(e,t){return fa(e,t)>0?t:e}i(Rn,"clampEffort");function Fd(e,t){if(e==="none")return"none";if(!t)return e;let o=t.default?ce(t.default):e,r=t.max?Rn(o,ce(t.max)):o;return Rn(r,e)}i(Fd,"resolveRoleEffort");var pa=Object.freeze(["\u4E0D\u5BF9","\u9519\u4E86","\u6709\u95EE\u9898","\u771F\u7684\u5417","\u4F60\u786E\u5B9A","\u4E0D\u662F\u8FD9\u6837","\u5F04\u9519\u4E86","\u641E\u9519\u4E86","\u641E\u53CD\u4E86","\u8FD9\u4E0D\u5BF9","\u4E0D\u6B63\u786E","\u7B54\u9519","\u56DE\u7B54\u9519","that's wrong","that is wrong","that's not right","that is not right","are you sure","not really","this is wrong","this is incorrect","that's incorrect","that is incorrect","you're wrong","you are wrong"]),ha=Object.freeze(["\u4ED4\u7EC6","\u6DF1\u5165","\u8BA4\u771F","\u518D\u770B\u770B","\u518D\u60F3\u60F3","\u60F3\u6E05\u695A","\u7528\u5FC3","\u6DF1\u5EA6\u5206\u6790","\u4ED4\u7EC6\u5206\u6790","\u8BA4\u771F\u5206\u6790","\u5F7B\u5E95","think harder","think more carefully","look more carefully","dig deeper","be thorough","more careful","more carefully","reconsider","reexamine","re-examine"]);function ga(e,t){if(!e)return{category:null,matched:null};let o=e.toLowerCase();if(t)for(let r of pa){let n=r.toLowerCase();if(o.includes(n)||e.includes(r))return{category:"doubt",matched:r}}for(let r of ha){let n=r.toLowerCase();if(o.includes(n)||e.includes(r))return{category:"deepen",matched:r}}return{category:null,matched:null}}i(ga,"detectFollowupSignal");function ya(e){switch(e){case"auto":return"low";case"low":return"medium";case"medium":return"high";default:return e}}i(ya,"escalateEffort");function Ta(e,t,o){let r=ga(t,o);if(r.category===null)return{effective:e,escalated:!1,signal:r};let n=ya(e);return n===e?{effective:e,escalated:!1,signal:r}:{effective:n,escalated:!0,signal:r}}i(Ta,"applyFollowupEscalation");function Nn(e,t){let o=e.effort??ce(On(e)),n=(e.session?.initialMessages??[]).some(a=>a?.role==="assistant"),s=Ta(o,t,n);return s.escalated?{options:{...e,effort:s.effective},escalation:s}:{options:e,escalation:s}}i(Nn,"applyFollowupEscalationToOptions");var ba={conversation:["hello","hi","hey","\u4F60\u597D","\u55E8","\u65E9\u4E0A\u597D","\u4E0B\u5348\u597D","\u665A\u4E0A\u597D"],lookup:["where is","which file","what file","where does","where do","located","defined","\u5728\u54EA\u4E2A\u6587\u4EF6","\u5728\u54EA","\u5728\u54EA\u91CC","\u54EA\u4E2A\u6587\u4EF6","\u54EA\u4E2A\u51FD\u6570","\u54EA\u91CC\u5B9A\u4E49","\u6587\u4EF6\u4F4D\u7F6E","\u5728\u54EA\u7BA1\u7406"],review:["review","code review","pull request","merge blocker","diff","changed files","\u5BA1\u67E5","\u4EE3\u7801\u5BA1\u67E5","review \u4E00\u4E0B","\u770B\u4E0B\u6539\u52A8","\u8BC4\u5BA1","pr"],bugfix:["bug","error","exception","failing","fix","failure","traceback","stack trace","runtime error","\u62A5\u9519","\u9519\u8BEF","\u5F02\u5E38","\u4FEE\u590D","\u5931\u8D25","\u6392\u67E5"],edit:["implement","add ","change ","modify ","update ","create ","write ","\u5B9E\u73B0","\u65B0\u589E","\u4FEE\u6539","\u6539\u4E00\u4E0B","\u521B\u5EFA","\u5199\u4E00\u4E2A"],refactor:["refactor","cleanup","restructure","simplify","decouple","rename","\u91CD\u6784","\u6E05\u7406","\u4F18\u5316","\u7B80\u5316","\u89E3\u8026","\u6574\u7406"],plan:["plan","design","architecture","migration","strategy","roadmap","\u8BA1\u5212","\u8BBE\u8BA1","\u67B6\u6784","\u65B9\u6848","\u7B56\u7565","\u8DEF\u7EBF\u56FE"],qa:["explain","what is","how does","help me understand","\u89E3\u91CA","\u4E3A\u4EC0\u4E48","\u662F\u4EC0\u4E48","\u600E\u4E48\u7406\u89E3","\u4EC0\u4E48\u610F\u601D","\u8BF4\u660E"]};function xa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(xa,"escapeRegExp");function va(e){return/^[a-z0-9][a-z0-9 _-]*$/i.test(e)}i(va,"hasAsciiWordBoundaries");function E(e,t){if(!t)return!1;let o=t.trim();return o?va(o)?new RegExp(`(^|[^a-z0-9])${xa(o)}([^a-z0-9]|$)`,"i").test(e):e.includes(t):!1}i(E,"textHasKeyword");function ka(e,t){let o=0;for(let r of t)r&&E(e,r)&&(o+=r.length>=6||/[^\u0000-\u007f]/.test(r)?2:1);return o}i(ka,"scoreTaskTypeKeywords");var wa=/^(?:\s|[!,.?,。!?])*?(?:hi|hello|hey|yo|你好|嗨|哈喽|早上好|下午好|晚上好)(?:\s|[!,.?,。!?])*$/i,Ea=/\b(where is|which file|what file|where does|where do|defined in|located in|file manages|manages this|which component|which function)\b/i;var Ra=/\b(review|code review|audit|pr|pull request|merge blocker|look at the changes|changed files)\b/i;var Sa=/\b(plan|design|architecture|proposal|strategy|roadmap)\b/i;var Ca=/\b(debug|investigate|root cause|why is|why does|failing|failure|runtime error|stack trace|traceback)\b/i;var _a=/\b(implement|add|change|modify|update|create|write|fix|refactor|rewrite|replace)\b/i;var Ma=/\b(docs?|documentation|readme|changelog|release notes?|spec|proposal|design doc|requirements?|prd|adr|hld|dd|guide|runbook|playbook|feature list|known issues?)\b/i;var Aa=/\b(?:api|backend|frontend|service|module|endpoint|component|architecture|package|migration|schema|database|auth|sdk|cli)\s+(?:docs?|documentation|guide|readme|changelog|spec|proposal|design doc|requirements?|prd|adr|hld|dd|runbook|playbook)\b|\b(?:docs?|documentation|guide|readme|changelog|spec|proposal|design doc|requirements?|prd|adr|hld|dd|runbook|playbook)\s+(?:for|about|on)\s+(?:the\s+)?(?:api|backend|frontend|service|module|endpoint|component|architecture|package|migration|schema|database|auth|sdk|cli)\b/i,Pa=/(?:API|\u540e\u7aef|\u524d\u7aef|\u670d\u52a1|\u6a21\u5757|\u63a5\u53e3|\u7ec4\u4ef6|\u67b6\u6784|\u5305|\u8fc1\u79fb|\u6570\u636e\u5e93|\u8ba4\u8bc1)(?:[\u4e00-\u9fffA-Za-z0-9_\-\/\\.\s]{0,8})(?:\u6587\u6863|\u8bf4\u660e\u6587\u6863|README|CHANGELOG|PRD|ADR|HLD|DD|\u6307\u5357)/u,Ia=/\b(?:implementation|source code|code comments?|function|class|component|bug|script|tests?|ui)\b/i,Oa=/\u4ee3\u7801\u6ce8\u91ca|\u5b9e\u73b0|\u51fd\u6570|\u7c7b|\u7ec4\u4ef6|bug|\u811a\u672c|\u6d4b\u8bd5|\u754c\u9762/u,Na=/\b(?:do not|don't|dont|without|no)\b[\s\S]{0,12}\b(?:change|modify|edit|touch|rewrite|update|mutate)\b[\s\S]{0,8}\bcode\b|\bno code changes?\b/i,Da=/\u4e0d\u6539\u4ee3\u7801|\u4e0d\u8981\u6539\u4ee3\u7801|\u4e0d\u4fee\u6539\u4ee3\u7801|\u4e0d\u8981\u4fee\u6539\u4ee3\u7801|\u53ea\u6539\u6587\u6863|\u53ea\u66f4\u65b0\u6587\u6863|\u4ec5\u6539\u6587\u6863|\u4ec5\u66f4\u65b0\u6587\u6863/u,La=/\b(double[- ]check|re-check|recheck|second pass|second opinion|cross-check|cross check|independently verify|independent review|independent audit|strict audit|extra scrutiny|verify twice)\b/i;var Fa=/\b(code|implementation|function|class|component|module|endpoint|service|repo|repository|file|files|test|bug|feature|script|api|ui|backend|frontend)\b/i;var Ua=/\b(deploy|deployment|restart|reboot|migrate database|run migration|seed database|provision|install dependency|install package|upgrade dependency|kill process|start server|stop server|apply terraform)\b/i;var Ba=/^(?:\s|[!,.?,。!]*)?(?:你好|哈喽|早上好|下午好|晚上好)(?:\s|[!,.?,。!]*)*$/u,Ha=/在哪个文件|哪个文件|在哪定义|定义在|哪个函数|哪个组件|文件位置|在哪里/u,$a=/审查|评审|review一下|看下改动|代码改动|审阅/u,qa=/计划|设计|架构|方案|策略|路线图/u,ja=/排查|定位问题|根因|为什么|报错|错误|异常|失败/u,Ga=/实现|新增|修改|创建|写一个|修复|重构|改一下|替换/u,Wa=/文档|说明文档|设计文档|需求文档|PRD|ADR|HLD|DD|CHANGELOG|README|功能清单|已知问题/u,Ka=/再检查|再审查|双重检查|第二遍|第二轮|二次审查|交叉检查|独立验证|独立审查|更强审查/u,Sn=/代码|实现|函数|类|组件|模块|接口|服务|仓库|文件|测试|bug|功能|脚本|API|界面|后端|前端/u,Xa=/部署|重启|重启服务|迁移数据库|运行迁移|初始化数据库|安装依赖|升级依赖|杀进程|启动服务|停止服务|应用terraform/u,Ya=/代码|实现|函数|类|组件|模块|接口|bug|功能|前端|后端|脚本/u,Cn=/实现|新增|修改|更新|创建|编写|修复|重构|补丁|重写|替换|编辑|重命名/u;function za(e){return wa.test(e)||Ba.test(e)}i(za,"isGreetingOnlyPrompt");function eo(e){let t=e.trim();if(!t)return{primaryTask:"conversation",taskFamily:"conversation",actionability:"non_actionable",executionPattern:"direct",shouldUseRepoSignals:!1,requiresRoutingHeuristics:!1,reason:"Empty input is treated as non-actionable conversation."};if(za(t))return{primaryTask:"conversation",taskFamily:"conversation",actionability:"non_actionable",executionPattern:"direct",shouldUseRepoSignals:!1,requiresRoutingHeuristics:!1,reason:"Pure greeting input should stay conversational and must not be escalated by repository state."};let o=Ea.test(t)||Ha.test(t),r=Ra.test(t)||$a.test(t),n=Sa.test(t)||qa.test(t),s=Ca.test(t)||ja.test(t),a=_a.test(t)||Ga.test(t);return r?{primaryTask:"review",taskFamily:"review",actionability:"actionable",executionPattern:"checked-direct",shouldUseRepoSignals:!0,requiresRoutingHeuristics:!0,reason:"Review work is actionable and benefits from harness assessment for accurate scoping."}:n?{primaryTask:"plan",taskFamily:"planning",actionability:"actionable",executionPattern:"coordinated",shouldUseRepoSignals:!0,requiresRoutingHeuristics:!0,reason:"Planning and design requests may benefit from coordinated execution."}:s?{primaryTask:"bugfix",taskFamily:"investigation",actionability:"actionable",executionPattern:"checked-direct",shouldUseRepoSignals:!0,requiresRoutingHeuristics:!0,reason:"Debugging and root-cause work starts as investigation."}:a?{primaryTask:"edit",taskFamily:"implementation",actionability:"actionable",executionPattern:"checked-direct",shouldUseRepoSignals:!0,requiresRoutingHeuristics:!0,reason:"Implementation and editing work is actionable and may later escalate if the evidence warrants it."}:o?{primaryTask:"lookup",taskFamily:"lookup",actionability:"actionable",executionPattern:"direct",shouldUseRepoSignals:!1,requiresRoutingHeuristics:!0,reason:"Lookup queries are actionable but lightweight \u2014 direct execution unless deeper analysis is requested."}:{primaryTask:"unknown",taskFamily:"ambiguous",actionability:"ambiguous",executionPattern:"direct",shouldUseRepoSignals:!1,requiresRoutingHeuristics:!0,reason:"Ambiguous requests need classification before the work approach is locked in."}}i(eo,"inferIntentGate");function ct(e){switch(e){case"conversation":return"conversation";case"lookup":case"qa":return"lookup";case"review":return"review";case"bugfix":return"investigation";case"plan":return"planning";case"edit":case"refactor":return"implementation";default:return"ambiguous"}}i(ct,"inferTaskFamilyFromPrimaryTask");function Dn(e){switch(e){case"conversation":case"lookup":return"direct";case"review":case"investigation":return"checked-direct";case"planning":case"implementation":return"coordinated";default:return"direct"}}i(Dn,"defaultExecutionPatternForFamily");function Va(e,t){let o=eo(e),r=t.taskFamily??ct(t.primaryTask),n=t.actionability??(r==="conversation"?"non_actionable":r==="ambiguous"?o.actionability:"actionable"),s=t.executionPattern??Dn(r);return{taskFamily:r,actionability:n,executionPattern:s}}i(Va,"deriveIntentFields");function Ln(e,t){let o=` ${e.toLowerCase()} `,r=/[\u3400-\u9fff]/u.test(e),n=Ma.test(e)||r&&Wa.test(e),s=Aa.test(e)||r&&Pa.test(e),a=Ia.test(e)||r&&Oa.test(e),c=Na.test(e)||r&&Da.test(e),d=Ua.test(e)||r&&Xa.test(e),u=Fa.test(o)||r&&Sn.test(e),m=/\b(code|implementation|function|class|component|module|endpoint|service|bug|script|api|ui|backend|frontend)\b/i.test(o)||r&&Sn.test(e),l=/\b(implement|add|modify|update|create|write|fix|refactor|rewrite|replace|edit|patch|rename)\b/i.test(o)||r&&Cn.test(e),g=r&&Ya.test(e),R=r&&Cn.test(e),S=/\b(monorepo|repo|repository|package|packages|architecture|migration)\b/i.test(o),C=/\b(refactor|rewrite|reorganize|migrate|split|merge|consolidate|rename)\b/i.test(o),f=/\b(code|implementation|function|class|component|module|endpoint|service|bug|script|api|ui|backend|frontend)\b/i.test(o)||g,D=/\b(implement|add|modify|update|create|write|fix|refactor|rewrite|replace|edit|patch|rename)\b/i.test(o)||R,w=f&&!s||a,P=S&&!s,p=n&&!d&&c;if(t.primaryTask==="review"&&!D&&!d)return n&&(p||!w)?"docs-only":"read-only";let I=t.primaryTask==="edit"||t.primaryTask==="refactor"||t.taskFamily==="implementation"||t.primaryTask==="bugfix"&&D||D&&w||C&&P;return p&&t.primaryTask!=="refactor"||n&&!d&&!w&&t.primaryTask!=="refactor"?"docs-only":d?"system":I?"code":"read-only"}i(Ln,"deriveMutationSurface");function Qa(e,t){let o=/[\u3400-\u9fff]/u.test(e);return La.test(e)||o&&Ka.test(e)||t.recommendedMode==="strict-audit"?"explicit-check":"default"}i(Qa,"deriveAssuranceIntent");function Fn(e){let t=` ${e.toLowerCase()} `,r=[...Object.entries(ba).map(([c,d])=>({task:c,score:ka(t,d)}))].sort((c,d)=>d.score-c.score),n=r[0],s=r[1];if(!n||n.score===0)return{task:"unknown",confidence:zs,reason:"Fallback task inference did not find enough strong signals, so it kept the task as unknown."};if(s&&n.score===s.score){let c=Za(e,n.task,s.task);return c?{task:c,confidence:kn,reason:`Fallback task inference preferred "${c}" because the request used an explicit directive even though multiple task signals were present.`}:{task:"unknown",confidence:Vs,reason:`Fallback task inference saw competing signals for "${n.task}" and "${s.task}", so it kept the task as unknown.`}}if(n.task==="qa"&&n.score<4)return{task:"unknown",confidence:Qs,reason:"Fallback task inference saw a weak explanation-style signal, but not enough evidence to disable reasoning."};let a=Math.min(ea,kn+n.score*Zs+Math.max(0,(n.score-(s?.score??0))*Js));return{task:n.task,confidence:a,reason:`Fallback task inference selected "${n.task}" from textual signals in the request.`}}i(Fn,"inferTaskSignal");function Za(e,t,o){let r=` ${e.toLowerCase()} `,n=E(r,"review")||E(r,"code review")||E(r,"merge blocker")||E(r,"\u5BA1\u67E5")||E(r,"\u8BC4\u5BA1"),s=E(r,"fix")||E(r,"bug")||E(r,"\u4FEE\u590D")||E(r,"\u62A5\u9519"),a=E(r,"plan")||E(r,"design")||E(r,"\u65B9\u6848")||E(r,"\u8BA1\u5212");return(t==="review"||o==="review")&&n&&!s?"review":(t==="bugfix"||o==="bugfix")&&s&&!n?"bugfix":(t==="plan"||o==="plan")&&a?"plan":null}i(Za,"resolveTiedTask");function Ud(e){return Fn(e).task}i(Ud,"inferTaskType");function lt(e){switch(e){case"simple":return 0;case"moderate":return 1;case"complex":return 2;case"systemic":return 3;default:return 0}}i(lt,"complexityRank");function Ja(e,t){return t&<(t)>lt(e)?t:e}i(Ja,"maxComplexity");function ec(e,t,o){let r=eo(e);if(!r.requiresRoutingHeuristics){let a=r.primaryTask;return Pn(e,{primaryTask:a,confidence:r.actionability==="non_actionable"?.98:.9,riskLevel:"low",recommendedMode:Mn(a),recommendedThinkingDepth:_n(a),complexity:"simple",workIntent:"new",requiresBrainstorm:!1,harnessProfile:"H0_DIRECT",taskFamily:r.taskFamily,actionability:r.actionability,executionPattern:r.executionPattern,routingSource:"fallback",routingAttempts:1,reason:r.reason},t,o)}let n=Fn(e),s=n.task;return Pn(e,{primaryTask:s,taskFamily:ct(s),actionability:s==="unknown"?"ambiguous":"actionable",executionPattern:Dn(ct(s)),confidence:n.confidence,riskLevel:$n(e,s),recommendedMode:Mn(s),recommendedThinkingDepth:_n(s),complexity:"moderate",workIntent:"new",requiresBrainstorm:!1,harnessProfile:"H0_DIRECT",routingSource:"fallback",routingAttempts:1,reason:n.reason},t,o)}i(ec,"buildFallbackRoutingDecision");function Un(e){let t=e.primaryTask==="review"||e.primaryTask==="bugfix"||e.recommendedMode==="pr-review"||e.recommendedMode==="strict-audit"||e.recommendedMode==="investigation";return{harnessProfile:e.harnessProfile,evidenceHeavy:t,brainstorm:e.requiresBrainstorm,workIntent:e.workIntent}}i(Un,"buildProviderPolicyHintsForDecision");async function Bn(e,t,o,r){let n=On(e),s=eo(t),a=at({providerName:o.name,model:e.modelOverride??e.model,provider:o,prompt:t,options:e,reasoningMode:n}),c=ec(t,a,r),d=e.effort??ce(n),u=n==="off"?"off":n==="auto"?c.recommendedThinkingDepth:ma(n),m={...c,recommendedThinkingDepth:u,routingNotes:[...c.routingNotes??[],s.reason,"Heuristic routing only \u2014 LLM router skipped (FEATURE_061 Phase 1; FEATURE_193 retired post-routing calibration)."]};return{effort:d,promptOverlay:"",decision:m,providerPolicy:a}}i(Bn,"createReasoningPlan");function Hn(e,t=.5){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):t}i(Hn,"clampUnitInterval");function tc(e,t){let o=` ${e.toLowerCase()} `;return sa.some(r=>E(o,r))?"overwrite":ia.some(r=>E(o,r))?"append":t}i(tc,"inferWorkIntent");function oc(e,t){let o=` ${e.toLowerCase()} `,r=0;for(let n of Zt.moderate)E(o,n)&&(r+=1);for(let n of Zt.complex)E(o,n)&&(r+=2);for(let n of Zt.systemic)E(o,n)&&(r+=3);return(t.primaryTask==="refactor"||t.primaryTask==="plan")&&(r+=2),t.riskLevel==="high"&&(r+=2),t.workIntent==="overwrite"&&(r+=1),r>=la?"systemic":r>=ca?"complex":r>=aa?"moderate":"simple"}i(oc,"inferComplexity");function rc(e,t,o){let r=` ${e.toLowerCase()} `;return!!(na.some(n=>E(r,n))||t.primaryTask==="plan"||t.primaryTask==="unknown"&&t.confidence<.7||o==="systemic"||t.workIntent==="overwrite"&&(t.primaryTask==="refactor"||t.riskLevel==="high"))}i(rc,"inferRequiresBrainstorm");function nc(e,t){let o=t.taskFamily??ct(t.primaryTask),r=Ln(e,{primaryTask:t.primaryTask,taskFamily:o}),n=[];return(t.complexity==="complex"||t.complexity==="systemic")&&n.push(`Complexity hint: ${t.complexity}. Assess whether the recommended harness fits the task scope.`),t.needsIndependentQA&&n.push("Independent QA was inferred from prompt signals. Verify whether explicit verification artifacts are needed before declaring the task done."),t.requiresBrainstorm&&n.push("Brainstorm/planning signal detected. Judge whether to plan-first via todo_update before executing."),r==="system"&&(t.riskLevel==="high"||t.workIntent==="overwrite")&&n.push("High-risk system mutation detected. Proceed with caution; consider checkpointing intermediate state."),{harnessProfile:"H0_DIRECT",upgradeCeiling:"H0_DIRECT",notes:n}}i(nc,"selectHarnessProfile");function _n(e){switch(e){case"conversation":return"off";case"lookup":return"low";case"review":return"low";case"bugfix":case"edit":return"medium";case"refactor":case"plan":return"high";case"qa":return"off";default:return"medium"}}i(_n,"getDefaultDepthForTask");function Mn(e){switch(e){case"conversation":return"conversation";case"lookup":return"lookup";case"review":return"pr-review";case"bugfix":return"investigation";case"plan":return"planning";default:return"implementation"}}i(Mn,"getExecutionModeForTask");function $n(e,t){let o=e.toLowerCase();return t==="conversation"||t==="lookup"?"low":o.includes("security")||o.includes("auth")||o.includes("migration")||o.includes("database")||o.includes("schema")||o.includes("production")||o.includes("\u5B89\u5168")||o.includes("\u9274\u6743")||o.includes("\u6743\u9650")||o.includes("\u8FC1\u79FB")||o.includes("\u6570\u636E\u5E93")||o.includes("\u751F\u4EA7")?"high":t==="review"||t==="bugfix"||t==="plan"?"medium":"low"}i($n,"getRiskLevel");function ic(e,t,o){let r=.9,n=` ${e.toLowerCase()} `;return t.primaryTask==="review"?(r-=.12,t.reviewScale==="large"?r-=.16:t.reviewScale==="massive"&&(r-=.28)):t.primaryTask==="bugfix"?r-=.08:t.primaryTask==="plan"&&(r-=.24),t.riskLevel==="medium"?r-=.12:t.riskLevel==="high"&&(r-=.26),t.complexity==="moderate"?r-=.12:t.complexity==="complex"?r-=.28:t.complexity==="systemic"&&(r-=.42),t.requiresBrainstorm&&(r-=.18),t.workIntent==="overwrite"&&(r-=.08),/\b(strict review|must[- ]fix|independently verify|browser test|playwright|e2e|frontend verify)\b/.test(n)&&(r-=.2),o&&(o.changedFileCount>=3&&(r-=.12),o.changedLineCount>=Jt&&(r-=.14),o.changedLineCount>=In&&(r-=.14),o.touchedModuleCount>=2&&(r-=.16),(o.impactedModuleCount??0)>=2&&(r-=.14),o.crossModule&&(r-=.2),o.lowConfidence&&(r-=.08)),Hn(r,.5)}i(ic,"computeSoloBoundaryConfidence");function sc(e,t,o){let r=` ${e.toLowerCase()} `;return!!(/\b(must[- ]fix|strict review|audit|independently verify|browser test|playwright|e2e|console errors?|api check|db check)\b/.test(r)||t.primaryTask==="plan"||t.primaryTask==="qa"||t.riskLevel==="high"||t.complexity==="complex"||t.complexity==="systemic"||t.requiresBrainstorm||o&&(o.crossModule||o.lowConfidence||(o.impactedModuleCount??0)>=2||o.touchedModuleCount>=2||o.changedLineCount>=Jt))}i(sc,"computeNeedsIndependentQA");function ac(e,t,o,r){let n=e.recommendedMode,s=e.recommendedThinkingDepth,a=[];return r?(r.suggestedComplexity&<(r.suggestedComplexity)>lt(t)&&a.push(`Repository intelligence elevated task complexity to ${r.suggestedComplexity} (changedFiles=${r.changedFileCount}, touchedModules=${r.touchedModuleCount}, impactedModules=${r.impactedModuleCount??0}).`),r.crossModule&&a.push("Repository intelligence indicates cross-module impact; keep evidence and merge boundaries explicit."),r.lowConfidence&&a.push("Repository intelligence for the active area is low-confidence; re-query `module_context` / `symbol_context` (or `impact_estimate` for blast-radius questions) for a refined capsule before falling back to raw `read`/`grep`. Use direct file evidence only when a specific load-bearing claim needs byte-level verification."),r.investigationBias&&(e.primaryTask==="review"||e.primaryTask==="bugfix")&&n!=="investigation"?(n="investigation",(s==="off"||s==="low")&&(s="medium"),a.push("Repository intelligence shifted execution toward investigation because the active area is low-confidence or high-blast-radius.")):r.plannerBias&&e.primaryTask!=="review"&&e.primaryTask!=="bugfix"&&n==="implementation"&&(o==="complex"||o==="systemic")&&(n="planning",(s==="off"||s==="low")&&(s="medium"),a.push("Repository intelligence shifted execution toward planning because the task spans multiple modules or dependencies.")),{recommendedMode:n,recommendedThinkingDepth:s,repoNotes:a}):{recommendedMode:n,recommendedThinkingDepth:s,repoNotes:a}}i(ac,"applyRepoSignalsToDecision");function An(e,t){let o=t.exec(e);if(!o?.[1])return;let r=o[1].replace(/,/g,"").toLowerCase(),n=r.endsWith("k")?1e3:1,s=r.endsWith("k")?r.slice(0,-1):r,a=Number.parseFloat(s);if(!(!Number.isFinite(a)||a<=0))return Math.round(a*n)}i(An,"parsePromptInteger");function cc(e){let t=An(e,/(?:^|[\s(,])(\d[\d,]*(?:\.\d+)?k?)\s*(?:changed\s+)?files?\b/i),o=An(e,/(?:^|[\s(,])(\d[\d,]*(?:\.\d+)?k?)\s*(?:changed\s+)?lines?\b/i),r;return(t??0)>=da||(o??0)>=In?r="massive":((t??0)>=ua||(o??0)>=Jt)&&(r="large"),{changedFileCount:t,changedLineCount:o,reviewScale:r}}i(cc,"inferPromptReviewScale");function lc(e,t){return e?.reviewScale?e.reviewScale:cc(t??"").reviewScale}i(lc,"deriveReviewScaleFromSignals");function Pn(e,t,o,r){let n=t,s=Va(e,t),a=s.actionability==="actionable"&&s.taskFamily!=="conversation"&&s.taskFamily!=="lookup";t.primaryTask==="unknown"&&s.taskFamily==="ambiguous"&&(n={...t,recommendedMode:"implementation",recommendedThinkingDepth:"medium",reason:`${t.reason} Conservative fallback keeps balanced reasoning for ambiguous tasks.`}),n.primaryTask==="qa"&&n.confidence<ta&&(n={...n,primaryTask:"unknown",confidence:Math.min(n.confidence,oa),riskLevel:$n(e,"unknown"),recommendedMode:"implementation",recommendedThinkingDepth:"medium",reason:`${n.reason} Low-confidence QA routing was downgraded to unknown so reasoning stays available.`}),n.confidence<ra&&n.recommendedThinkingDepth==="off"&&(n={...n,primaryTask:"unknown",recommendedMode:"implementation",recommendedThinkingDepth:"medium",reason:`${n.reason} Low-confidence off-mode routing was upgraded to balanced reasoning for safety.`});let c=tc(e,n.workIntent),d=a?r?.repoSignals:void 0,u=oc(e,{...n,workIntent:c}),m=a?Ja(u,d?.suggestedComplexity):u,l=t.reviewScale??lc(d,e),g=Ln(e,{primaryTask:n.primaryTask,taskFamily:s.taskFamily}),R=Qa(e,n),S="H0_DIRECT",C=rc(e,{...n,workIntent:c,complexity:m,reviewScale:l,mutationSurface:g,assuranceIntent:R,topologyCeiling:S},m)||!!(d?.plannerBias&&(m==="complex"||m==="systemic")),f=Hn(t.soloBoundaryConfidence??ic(e,{primaryTask:n.primaryTask,complexity:m,riskLevel:n.riskLevel,requiresBrainstorm:C,workIntent:c,reviewScale:l},d),.5),D=t.needsIndependentQA??sc(e,{primaryTask:n.primaryTask,complexity:m,riskLevel:n.riskLevel,requiresBrainstorm:C,reviewScale:l},d),w=g==="read-only"||g==="docs-only"?R==="explicit-check":D,P=nc(e,{...n,workIntent:c,complexity:m,requiresBrainstorm:C,reviewScale:l,soloBoundaryConfidence:f,needsIndependentQA:w,mutationSurface:g,assuranceIntent:R,topologyCeiling:S}),{recommendedMode:p,recommendedThinkingDepth:I,repoNotes:re}=ac({...n,taskFamily:s.taskFamily,actionability:s.actionability,executionPattern:s.executionPattern},u,m,d),L=p,M=I,O="direct";return s.taskFamily==="conversation"?(L="conversation",M="off"):s.taskFamily==="lookup"&&(L="lookup",M=I==="high"?"medium":I),{...n,taskFamily:s.taskFamily,actionability:s.actionability,executionPattern:O,mutationSurface:g,assuranceIntent:R,recommendedMode:L,recommendedThinkingDepth:M,workIntent:c,complexity:m,requiresBrainstorm:C,topologyCeiling:S,reviewScale:l,soloBoundaryConfidence:f,needsIndependentQA:w,harnessProfile:P.harnessProfile,upgradeCeiling:P.upgradeCeiling,routingSource:n.routingSource??"fallback",routingAttempts:n.routingAttempts??1,routingNotes:[...n.routingNotes??[],...P.notes,...re,...a?[]:["Intent gate ignored repository scaling signals for this request."]]}}i(Pn,"stabilizeRoutingDecision");function ut(e,t){return Buffer.byteLength(JSON.stringify({systemPrompt:t,messages:e}),"utf8")}i(ut,"estimateProviderPayloadBytes");function dt(e){return e<16*1024?"small":e<64*1024?"medium":e<192*1024?"large":"xlarge"}i(dt,"bucketProviderPayloadSize");function De(e){let t=Wo.exec(e);return t?[t[1].toUpperCase(),t[2]??""]:["",""]}i(De,"checkPromiseSignal");function uc(){return process.env.KODAX_DEBUG_STREAM==="1"||process.env.KODAX_DEBUG_RESILIENCE==="1"}i(uc,"shouldDebugResilience");function te(e,t){uc()&&console.error(e,t)}i(te,"emitResilienceDebug");function qn(e,t,o){let r=e.modelSelection.provider??t.provider,n=e.modelSelection.model??t.modelOverride??t.model,s=e.thinkingLevel,a=Te(r);if(!a.isConfigured())throw new Error(`Provider "${r}" not configured. Set ${a.getApiKeyEnv()}`);let c=lr(o,a,n);return{providerName:r,modelOverride:n,thinkingLevel:s,provider:a,contextWindow:c}}i(qn,"resolvePerTurnProvider");function to(e,t){if(!e.isConfigured())throw new Error(`Provider "${t}" not configured. Set ${e.getApiKeyEnv()}`)}i(to,"assertProviderConfigured");var oo=`You are KodaX, a helpful multi-provider coding agent. You can read, write, and edit files, and execute shell commands.
|
|
4
4
|
|
|
5
5
|
## Error Handling
|