@kodax-ai/kodax 0.7.59 → 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.
Files changed (62) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +1234 -1228
  3. package/README_CN.md +653 -647
  4. package/dist/chunks/{agent-QQCRBU4C.js → agent-E74WVAFR.js} +1 -1
  5. package/dist/chunks/argument-completer-BBFYCVTM.js +2 -0
  6. package/dist/chunks/{chunk-TBXP7FEG.js → chunk-2OEKUAV4.js} +1 -1
  7. package/dist/chunks/chunk-4NSOBQCU.js +322 -0
  8. package/dist/chunks/{chunk-YADBB5GN.js → chunk-6OZ5KWG3.js} +1 -1
  9. package/dist/chunks/{chunk-SVEJFERZ.js → chunk-7COB3EKF.js} +176 -161
  10. package/dist/chunks/chunk-CGGX3FXE.js +19 -0
  11. package/dist/chunks/{chunk-UXQILGRX.js → chunk-D7CC6YZC.js} +198 -198
  12. package/dist/chunks/{chunk-2UUOFT3Z.js → chunk-KIVYMSRH.js} +1 -1
  13. package/dist/chunks/chunk-NJW2LQOP.js +722 -0
  14. package/dist/chunks/chunk-PJXKBM3Y.js +310 -0
  15. package/dist/chunks/chunk-QCBKLNN5.js +18 -0
  16. package/dist/chunks/{chunk-5GPJ6MB5.js → chunk-XHOPSZVL.js} +120 -120
  17. package/dist/chunks/{chunk-BEXLPFFB.js → chunk-ZL5CEANW.js} +3 -3
  18. package/dist/chunks/compaction-config-GESEZQVA.js +2 -0
  19. package/dist/chunks/{construction-bootstrap-YON4ZEMO.js → construction-bootstrap-OSXHEIBB.js} +1 -1
  20. package/dist/chunks/{dist-EZXBR6NW.js → dist-W3OOJP66.js} +1 -1
  21. package/dist/chunks/host-FRQXOEHH.js +2 -0
  22. package/dist/chunks/{paste-4THGP5XW.js → paste-FDYM7SZX.js} +1 -1
  23. package/dist/chunks/run-manager-FGCG7DFF.js +2 -0
  24. package/dist/chunks/{utils-5XVW33SY.js → utils-47QI5MSP.js} +1 -1
  25. package/dist/index.d.ts +11 -11
  26. package/dist/index.js +1 -1
  27. package/dist/kodax_cli.js +1028 -972
  28. package/dist/sdk-agent.d.ts +24 -13
  29. package/dist/sdk-agent.js +1 -1
  30. package/dist/sdk-coding.d.ts +17 -13
  31. package/dist/sdk-coding.js +1 -1
  32. package/dist/sdk-llm.d.ts +6 -6
  33. package/dist/sdk-mcp.js +1 -1
  34. package/dist/sdk-media.d.ts +1 -1
  35. package/dist/sdk-media.js +1 -1
  36. package/dist/sdk-repl.d.ts +12 -11
  37. package/dist/sdk-repl.js +2 -2
  38. package/dist/sdk-session.d.ts +6 -6
  39. package/dist/sdk-session.js +1 -1
  40. package/dist/sdk-skills.js +1 -1
  41. package/dist/types-chunks/{base.d-BA9Doaj_.d.ts → base.d-DalIRhbb.d.ts} +1 -1
  42. package/dist/types-chunks/{bash-prefix-extractor.d-BNdpV4Cf.d.ts → bash-prefix-extractor.d-e1LD2IRl.d.ts} +70 -27
  43. package/dist/types-chunks/{capability-learning.d-DRV80ISB.d.ts → capability-learning.d-BQB0M70w.d.ts} +1 -1
  44. package/dist/types-chunks/{guardrail.d-CNdKuSD_.d.ts → guardrail.d-CdqJwwN7.d.ts} +3 -3
  45. package/dist/types-chunks/{process.d-BOrAxjvM.d.ts → process.d-C93UMgPK.d.ts} +20 -5
  46. package/dist/types-chunks/{resolver.d-DFAKKUvt.d.ts → resolver.d-CGkfRULj.d.ts} +2 -2
  47. package/dist/types-chunks/{run-manager.d-CsJC9zYf.d.ts → run-manager.d-DHPlNYkK.d.ts} +20 -6
  48. package/dist/types-chunks/{sdk-session-ByZlwgdM.d.ts → sdk-session-DINrM1pF.d.ts} +47 -10
  49. package/dist/types-chunks/{storage.d-DHL3XpAL.d.ts → storage.d-xiw7Vgx0.d.ts} +2 -2
  50. package/dist/types-chunks/{types.d-Ci5YPFEh.d.ts → types.d-Bp4Lm1jv.d.ts} +37 -3
  51. package/dist/types-chunks/{types.d-CE_Ter29.d.ts → types.d-CSZAMmU-.d.ts} +4 -1
  52. package/dist/types-chunks/{utils.d-D9FHU4wB.d.ts → utils.d-Dy19-1XR.d.ts} +5 -5
  53. package/package.json +1 -1
  54. package/dist/chunks/argument-completer-7Q2T4YWA.js +0 -2
  55. package/dist/chunks/chunk-D7RENPQQ.js +0 -322
  56. package/dist/chunks/chunk-PRIBJN5E.js +0 -683
  57. package/dist/chunks/chunk-SDSLWDAZ.js +0 -17
  58. package/dist/chunks/chunk-Z23LK3IV.js +0 -310
  59. package/dist/chunks/chunk-Z3ZXV3DZ.js +0 -18
  60. package/dist/chunks/compaction-config-GQIPCVFD.js +0 -2
  61. package/dist/chunks/host-LO6ZNTMV.js +0 -2
  62. package/dist/chunks/run-manager-HTLXKU66.js +0 -2
package/README.md CHANGED
@@ -1,1228 +1,1234 @@
1
- <p align="center">
2
- <picture>
3
- <source media="(prefers-color-scheme: dark)" srcset="assets/logo-dark.svg">
4
- <source media="(prefers-color-scheme: light)" srcset="assets/logo-light.svg">
5
- <img src="assets/logo-light.svg" alt="KodaX" width="640">
6
- </picture>
7
- </p>
8
-
9
- <p align="center">
10
- <b>Open-source AI coding agent on every LLM you can reach.</b><br>
11
- Anthropic · OpenAI · DeepSeek · Kimi · Zhipu · MiniMax · MiMo · Ark · Qwen · Gemini · Codex.<br>
12
- REPL · CLI · library · Node-free single binary.
13
- </p>
14
-
15
- <p align="center">
16
- <a href="https://www.npmjs.com/package/@kodax-ai/kodax"><img alt="npm version" src="https://img.shields.io/npm/v/@kodax-ai/kodax?style=flat-square&color=cb3837"></a>
17
- <a href="LICENSE"><img alt="license" src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square"></a>
18
- <a href="https://github.com/icetomoyo/KodaX/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/icetomoyo/KodaX?style=flat-square&logo=github&color=f1c40f"></a>
19
- <a href="https://github.com/icetomoyo/KodaX/actions"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/icetomoyo/KodaX/release.yml?style=flat-square&label=release"></a>
20
- <img alt="providers" src="https://img.shields.io/badge/LLMs-14_aliases_+_custom-2ecc71?style=flat-square">
21
- </p>
22
-
23
- <p align="center">
24
- <a href="#install-in-30-seconds">Install</a> ·
25
- <a href="#four-ways-to-use-kodax">Usage</a> ·
26
- <a href="#sdk-usage">SDK</a> ·
27
- <a href="CHANGELOG.md">Changelog</a> ·
28
- <a href="docs/FEATURE_LIST.md">Roadmap</a> ·
29
- <a href="https://github.com/icetomoyo/KodaX/discussions">Discussions</a> ·
30
- <a href="README_CN.md">中文 README</a>
31
- </p>
32
-
33
- <p align="center">
34
- <img src="kodax-hd.gif" alt="KodaX in action" width="880">
35
- </p>
36
-
37
- ---
38
-
39
- ## Install in 30 seconds
40
-
41
- ```bash
42
- npm i -g @kodax-ai/kodax
43
-
44
- # Pick any one you have an API key for:
45
- export ZHIPU_API_KEY=... # or ANTHROPIC_API_KEY / OPENAI_API_KEY / KIMI_API_KEY /
46
- # MINIMAX_API_KEY / MIMO_API_KEY / ARK_API_KEY / QWEN_API_KEY /
47
- # DEEPSEEK_API_KEY / GEMINI_API_KEY
48
-
49
- kodax
50
- ```
51
-
52
- That's it. You're in the REPL — ask anything in natural language.
53
-
54
- > **No-Node target machines:** download a Bun-compiled single binary for Windows / macOS / Linux × x64 + arm64 from the [GitHub Releases](https://github.com/icetomoyo/KodaX/releases) page. See [docs/release.md](docs/release.md) for the build pipeline.
55
-
56
- ---
57
-
58
- ## Four ways to use KodaX
59
-
60
- | Form | Command / Import | When to use it |
61
- |---|---|---|
62
- | **REPL** | `kodax` | Interactive multi-turn coding session with streaming UI, permissions, slash commands |
63
- | **CLI** | `kodax -p "your task"` | One-shot scripted task, CI runs, batch processing |
64
- | **Library** | `import { runKodaX } from '@kodax-ai/kodax'` | Embed in your own tool / agent / web service |
65
- | **Single binary** | `./kodax` | Distribute to machines that don't have Node installed |
66
-
67
- ---
68
-
69
- ## Why KodaX
70
-
71
- <table>
72
- <tr>
73
- <td width="33%" align="center" valign="top">
74
- <h3>🇨🇳 6 China-native LLMs</h3>
75
- <sub>Zhipu · Kimi · MiniMax · MiMo · Ark · Qwen</sub>
76
- <br><br>
77
- First-class adapters with cross-provider <a href="benchmark/EVAL_GUIDELINES.md">prompt-eval calibration</a> on a canonical 5-alias panel — not OpenAI-compat shims.
78
- </td>
79
- <td width="33%" align="center" valign="top">
80
- <h3>📦 Single-file binary</h3>
81
- <sub>Bun --compile · Win / macOS / Linux · x64 + arm64</sub>
82
- <br><br>
83
- No Node required on the target machine. Drop one file, run anywhere — restricted envs, CI runners, air-gapped boxes.
84
- </td>
85
- <td width="33%" align="center" valign="top">
86
- <h3>🌳 Branchable session lineage</h3>
87
- <sub>Fork · rewind · parallel edit</sub>
88
- <br><br>
89
- Conversation history is a DAG, not a list. Powers the upcoming <b>KodaX Space</b> desktop app.
90
- </td>
91
- </tr>
92
- <tr>
93
- <td align="center" valign="top">
94
- <h3>🤖 Multi-agent by default</h3>
95
- <sub>V2 Worker single-loop + Sidecar Verifier + async children</sub>
96
- <br><br>
97
- <code>dispatch_child_task</code>, <code>send_message</code>, <code>task_stop</code>, multi-instance auto-coordination with content-hash safety net.
98
- </td>
99
- <td align="center" valign="top">
100
- <h3>🧩 Skills + self-construction</h3>
101
- <sub>Markdown skills, NL triggers</sub>
102
- <br><br>
103
- 5-stage self-modification staircase (scaffold → validate → stage → test → activate) gated by an 8-invariant admission contract.
104
- </td>
105
- <td align="center" valign="top">
106
- <h3>🛠 50+ built-in tools</h3>
107
- <sub>File · shell · search · MCP · ACP</sub>
108
- <br><br>
109
- Repo intelligence, semantic search, git worktree, web fetch — all addressable through one clean tool surface.
110
- </td>
111
- </tr>
112
- </table>
113
-
114
- ## How KodaX compares
115
-
116
- | Feature | **KodaX** | Claude Code | Aider | Codex CLI | Cursor | Cline |
117
- |---|---|---|---|---|---|---|
118
- | Open source | ✅ Apache&nbsp;2.0 | ❌ Source-available | ✅ Apache&nbsp;2.0 | ✅ Apache&nbsp;2.0 | ❌ Proprietary | ✅ Apache&nbsp;2.0 |
119
- | Node-free single binary | ✅ Bun | ❌ Node | ❌ Python | ✅ Rust | ❌ Electron | ❌ Extension |
120
- | Native China providers<br><sub>(Zhipu · Kimi · MiniMax · MiMo · Ark · Qwen)</sub> | ✅ 6 native | ❌ | ⚠ via LiteLLM | ❌ OpenAI-first | ❌ no provider menu | ⚠ Kimi / Qwen / DeepSeek |
121
- | Branchable session lineage | ✅ fork & rewind | ⚠ routines / sessions | ❌ | ❌ | ❌ | ⚠ checkpoints |
122
- | Multi-agent + MCP + 50+ tools | ✅ all three | ✅ all three | ⚠ tools, no MCP | ✅ all three | ⚠ Composer + MCP | ✅ all three |
123
-
124
- <sub>Data verified May 2026 against public docs ([Claude Code](https://github.com/anthropics/claude-code) · [Aider](https://aider.chat/docs/llms.html) · [Codex CLI](https://github.com/openai/codex) · [Cursor](https://cursor.com) · [Cline](https://github.com/cline/cline)). ⚠ = partial / requires extra setup / not first-class. Corrections welcome via PR.</sub>
125
-
126
- ## Detailed Setup
127
-
128
- > The `npm i -g @kodax-ai/kodax` one-liner above is the fastest path. This section is for building from source, configuring custom providers, or using KodaX as a library.
129
-
130
- ### 1. Build the CLI from source
131
-
132
- ```bash
133
- git clone https://github.com/icetomoyo/KodaX.git
134
- cd KodaX
135
- npm install
136
- npm run build
137
- npm link
138
- ```
139
-
140
- ### 2. Configure a provider
141
-
142
- KodaX reads API keys from environment variables. For built-in providers, the fastest path is:
143
-
144
- ```bash
145
- # macOS / Linux
146
- export ZHIPU_API_KEY=your_api_key
147
-
148
- # PowerShell
149
- $env:ZHIPU_API_KEY="your_api_key"
150
- ```
151
-
152
- For CLI defaults, create `~/.kodax/config.json`:
153
-
154
- ```json
155
- {
156
- "provider": "zhipu-coding",
157
- "effort": "auto"
158
- }
159
- ```
160
-
161
- If you need a custom base URL or an OpenAI/Anthropic-compatible endpoint, define a custom provider in the same config file:
162
-
163
- ```json
164
- {
165
- "provider": "my-openai-compatible",
166
- "customProviders": [
167
- {
168
- "name": "my-openai-compatible",
169
- "protocol": "openai",
170
- "baseUrl": "https://example.com/v1",
171
- "apiKeyEnv": "MY_LLM_API_KEY",
172
- "model": "my-model",
173
- "userAgentMode": "compat",
174
- "reasoning": {
175
- "efforts": ["off", "low", "medium", "high", "max"],
176
- "default": "high"
177
- }
178
- }
179
- ]
180
- }
181
- ```
182
-
183
- `userAgentMode` defaults to `"compat"`, which sends `KodaX` instead of the official SDK User-Agent. Switch it to `"sdk"` only when your gateway expects the upstream SDK header.
184
- For custom reasoning models, `reasoning: { efforts, default }` is the preferred v0.7.57 shape; use `"reasoning": "none"` for models without thinking capability. SDK hosts should render effort pickers from `reasoningProfile.supportedEfforts` / `defaultEffort` rather than assuming a fixed five-option ladder.
185
-
186
- #### OpenAI-compatible reasoning providers
187
-
188
- Some OpenAI-compatible reasoning models require KodaX to replay the previous assistant turn's `reasoning_content` on later requests. DeepSeek V4 thinking mode is the known load-bearing case. Built-in DeepSeek already opts in; custom providers must say so explicitly:
189
-
190
- ```json
191
- {
192
- "customProviders": [
193
- {
194
- "name": "my-deepseek-v4",
195
- "protocol": "openai",
196
- "baseUrl": "https://example.com/v1",
197
- "apiKeyEnv": "MY_DEEPSEEK_API_KEY",
198
- "model": "deepseek-v4-flash",
199
- "reasoningPreset": "deepseek-v4-openai",
200
- "replayReasoningContent": true
201
- }
202
- ]
203
- }
204
- ```
205
-
206
- Keep `replayReasoningContent` unset or `false` for OpenAI proper and gateways that reject unknown assistant-message fields. If one gateway routes mixed models, prefer per-model overrides:
207
-
208
- ```json
209
- {
210
- "models": [
211
- { "id": "deepseek-v4-flash", "replayReasoningContent": true },
212
- { "id": "gpt-5", "replayReasoningContent": false }
213
- ]
214
- }
215
- ```
216
-
217
- Sidecar verifier judge calls use provider-level forced tool choice when supported. If a compatible endpoint rejects the `tool_choice` parameter, KodaX retries that verifier request once without forced tool choice and still fails open rather than blocking the main Worker.
218
-
219
- #### Opting a custom provider into image / vision input (FEATURE_134 v0.7.40)
220
-
221
- If your custom provider's underlying model supports image input (vision), add a `capabilityProfile.multimodalSupport: "image-input"` block so KodaX does not artificially block multimodal requests at the SA-path policy gate. Built-in vision-capable aliases (Anthropic, OpenAI, Anthropic-/OpenAI-compatible aliases such as DeepSeek, Kimi, Qwen, Zhipu, MiniMax, MiMo, Ark, plus Gemini-CLI via the CLI's `@<path>` file-include syntax) already ship with this flag enabled by default; Codex-CLI and custom providers need to opt in when their underlying model supports image input.
222
-
223
- ```json
224
- {
225
- "customProviders": [
226
- {
227
- "name": "my-vision-provider",
228
- "protocol": "openai",
229
- "baseUrl": "https://example.com/v1",
230
- "apiKeyEnv": "MY_LLM_API_KEY",
231
- "model": "my-vision-model",
232
- "capabilityProfile": {
233
- "transport": "native-api",
234
- "conversationSemantics": "full-history",
235
- "mcpSupport": "none",
236
- "contextFidelity": "full",
237
- "toolCallingFidelity": "full",
238
- "sessionSupport": "full",
239
- "longRunningSupport": "full",
240
- "multimodalSupport": "image-input",
241
- "evidenceSupport": "full"
242
- }
243
- }
244
- ]
245
- }
246
- ```
247
-
248
- The serializer layer (`packages/llm/src/providers/anthropic.ts:770` for Anthropic-compat, `openai.ts:904` for OpenAI-compat) forwards image blocks automatically through base-class inheritance. The flag only gates whether KodaX's policy layer pre-rejects multimodal requests — the model-level vision contract remains your upstream provider's responsibility. If the model is actually text-only, you'll see the real upstream API error instead of a KodaX-side rejection.
249
-
250
- ### 3. Start in REPL or run a one-shot task
251
-
252
- ```bash
253
- # Interactive REPL
254
- kodax
255
-
256
- # Then ask naturally inside the REPL
257
- Read package.json and summarize the architecture
258
- /mode
259
- /help
260
-
261
- # One-shot CLI usage
262
- kodax "Review this repository and summarize the architecture"
263
- kodax --session review "Find the riskiest parts of src/"
264
- kodax --session review "Give me concrete fix suggestions"
265
- ```
266
-
267
- ### 4. Use it as a library
268
-
269
- Library usage still expects API keys from environment variables. If you want custom provider names or base URLs in code, register them explicitly:
270
-
271
- ```typescript
272
- import { registerCustomProviders, runKodaX } from '@kodax-ai/kodax';
273
-
274
- registerCustomProviders([
275
- {
276
- name: 'my-openai-compatible',
277
- protocol: 'openai',
278
- baseUrl: 'https://example.com/v1',
279
- apiKeyEnv: 'MY_LLM_API_KEY',
280
- model: 'my-model',
281
- userAgentMode: 'compat',
282
- },
283
- ]);
284
-
285
- const result = await runKodaX(
286
- {
287
- provider: 'my-openai-compatible',
288
- effort: 'auto',
289
- },
290
- 'Explain this codebase'
291
- );
292
- ```
293
-
294
- > **Embedding KodaX inside another app?** (KodaX Space, IDE extensions, custom CLIs)
295
- > See [docs/SDK_EMBEDDER_GUIDE.md](docs/SDK_EMBEDDER_GUIDE.md) for the runtime-mutation
296
- > surface (`startKodaX` + `RunningSession`), MCP popout manager API (`McpManager`),
297
- > Skill `` !`cmd` `` host hook, and per-app data dir namespacing (`getAppDataDir`).
298
-
299
- ## Repo Intelligence
300
-
301
- KodaX ships with built-in repo intelligence (`repo_overview`, `module_context`, `symbol_context`, `process_context`, `impact_estimate`, and related tools) that helps the coding agent understand large codebases without ad-hoc grep/glob exploration.
302
-
303
- Use `/repo-intel status` in the REPL to inspect the active engine. The former standalone `repointel` host skill has been removed; repo intelligence is built into KodaX and requires no external installation.
304
-
305
- ```bash
306
- # Pick a runtime mode (auto | full | light | off)
307
- kodax --repo-intelligence full --repo-intelligence-trace
308
- ```
309
-
310
- ## Architecture
311
-
312
- KodaX uses a **monorepo architecture** with npm workspaces. Source layout currently has 4 workspace packages; published as a single bundled npm package `@kodax-ai/kodax` with 8 SDK subpath exports (`/agent`, `/llm`, `/coding`, `/media`, `/repl`, `/skills`, `/mcp`, `/session`; ADR-024 + ADR-032 + ADR-038, with ADR-036 consolidation):
313
-
314
- ```
315
- KodaX/
316
- ├── packages/ # 4 workspace packages (FEATURE_194 v0.7.43)
317
- │ ├── llm/ # @kodax-ai/llm - LLM abstraction (15 built-in provider aliases)
318
- │ │ └── providers/ # Anthropic, OpenAI, DeepSeek, Kimi, MiMo, MiniMax, Zhipu, Ark, …
319
- │ │
320
- │ ├── agent/ # @kodax-ai/agent - Generic Agent framework
321
- │ │ ├── orchestration/ # Runner, runFanOut, runWithIdleYield, ChildTaskRegistry
322
- │ │ ├── session-lineage/ # branchable session tree (inline v0.7.43)
323
- │ │ ├── capabilities/
324
- │ │ │ ├── mcp/ # MCP integration (inline v0.7.43)
325
- │ │ │ └── skills/ # Skills standard implementation + builtin (inline v0.7.43)
326
- │ │ └── tracing/ # tracing / observability (inline v0.7.43)
327
- │ │
328
- │ ├── coding/ # @kodax-ai/coding - Coding Agent (tools + prompts)
329
- │ │ ├── tools/ # 50+ tools: read, write, edit, bash, glob, grep, undo,
330
- │ │ │ # dispatch_child_task, send_message, task_stop,
331
- │ │ │ # ask_user_question, repo-intelligence, …
332
- │ │ └── repo-intelligence/ # incl. protocol.ts (inline v0.7.43)
333
- │ │
334
- │ └── repl/ # @kodax-ai/repl - Interactive terminal UI (Ink TUI)
335
-
336
- ├── src/ # CLI entry + SDK subpath entries
337
- │ ├── kodax_cli.ts # Main CLI entry point (bin: `kodax`)
338
- │ └── sdk-*.ts # SDK subpath re-exports → @kodax-ai/kodax/{agent,llm,coding,media,repl,skills,mcp,session}
339
-
340
- └── package.json # Root workspace config; release.mjs rewrites name + injects subpath exports
341
- ```
342
-
343
- ### Package Dependencies
344
-
345
- ```
346
- ┌──────────────────┐
347
- │ kodax (root) │
348
- │ CLI Entry │
349
- └────────┬─────────┘
350
-
351
- ┌──────────────┴──────────────┐
352
- │ │
353
- ▼ ▼
354
- ┌──────────────┐ ┌────────────────┐
355
- │@kodax-ai/repl│ │@kodax-ai/coding│
356
- │ UI Layer │ │ Tools+Prompts │
357
- └──────┬───────┘ └──────┬─────────┘
358
- │ │
359
- │ ┌──────────────┴──────────────┐
360
- │ │ │
361
- ▼ ▼ ▼
362
- ┌──────────────┐ ┌──────────────────────────┐ ┌──────────────┐
363
- │@kodax-ai/ │ │@kodax-ai/agent │ │@kodax-ai/llm │
364
- │coding (via │ │Runner + fan-out + │ │LLM Abstract │
365
- │above) │ │idle-yield + session- │ │(15 aliases) │
366
- │ │ │lineage + skills + mcp + │ │ │
367
- │ │ │tracing (FEATURE_194) │ │ │
368
- └──────────────┘ └──────────────────────────┘ └──────────────┘
369
- ```
370
-
371
- ### Package Overview
372
-
373
- Source-side workspace package names (`@kodax-ai/*`). npm consumers install the single bundled `@kodax-ai/kodax` package and import from SDK subpaths — see [Source-side vs npm-published surface](#source-side-vs-npm-published-surface) and [SDK Usage](#sdk-usage) below.
374
-
375
- | Workspace package | Purpose | Key Dependencies |
376
- |---------|---------|------------------|
377
- | `@kodax-ai/llm` | LLM abstraction (15 built-in provider aliases + custom registration) | @anthropic-ai/sdk, openai |
378
- | `@kodax-ai/agent` | Generic Agent framework — Runner, fan-out, idle-yield, media/input artifacts, session-lineage, capabilities (mcp + skills), tracing (ADR-036 v0.7.43 consolidation; subpaths: `/media`, `/session-lineage`, `/capabilities/mcp`, `/capabilities/skills`, `/tracing`) | @kodax-ai/llm, js-tiktoken, fflate, jimp, yaml |
379
- | `@kodax-ai/coding` | Coding Agent — 50+ tools (incl. `dispatch_child_task` / `send_message` / `task_stop`) + role prompts + auto-continue + repo-intelligence protocol | @kodax-ai/llm, @kodax-ai/agent |
380
- | `@kodax-ai/repl` | Complete interactive terminal UI (Ink/React, permission modes, commands, streaming) | @kodax-ai/coding, ink, react |
381
-
382
- ### Source-side vs npm-published surface
383
-
384
- KodaX has two layers that consumers should understand separately:
385
-
386
- - **Source-side**: 4 workspace packages above (what developers see when reading the repo).
387
- - **npm-published**: a single bundled package `@kodax-ai/kodax` with 8 SDK subpaths (what SDK consumers `import` from). The subpaths are split into two roles:
388
- - **Full-package subpaths** (`/agent`, `/llm`, `/coding`, `/repl`) — each one maps 1:1 to a source workspace and exposes its complete public API.
389
- - **Narrow-subset subpaths** (`/media`, `/skills`, `/mcp`, `/session`) — each one exposes only a focused capability slice carved out of `/agent` or `/repl`. This lets consumers who only need (say) the Skills system import a much smaller surface without pulling in the full agent framework.
390
-
391
- | Source package | npm subpath | Type | What you get | Example consumer |
392
- |---|---|---|---|---|
393
- | `packages/llm` | `@kodax-ai/kodax/llm` | Full package | 15-alias LLM abstraction (77 exports) | Standalone LLM clients |
394
- | `packages/agent` | `@kodax-ai/kodax/agent` | Full package | Runner / fan-out / session-lineage / capabilities / tracing (202 exports) | Custom agent frameworks |
395
- | `packages/agent` | `@kodax-ai/kodax/skills` | **Narrow subset** | Skills system only — `SkillRegistry` / `loadFullSkill` / `expandSkillForLLM` / ... (26 exports = pre-v0.7.43 `@kodax-ai/skills` complete API) | Skill loaders, IDE plugins |
396
- | `packages/agent` | `@kodax-ai/kodax/mcp` | **Narrow subset** | MCP only — `McpCapabilityProvider` / `createMcpTransport` / `searchMcpCatalog` / ... (11 exports = pre-v0.7.43 `@kodax-ai/mcp` complete API) | MCP server hosts |
397
- | `packages/coding` | `@kodax-ai/kodax/coding` | Full package | Coding agent + 50+ tools + repo-intelligence (342 exports) | Build a Claude Code-shape product |
398
- | `packages/repl` | `@kodax-ai/kodax/repl` | Full package | Ink TUI + permission modes + commands (193 exports) | Terminal-UI consumers |
399
- | `packages/repl` | `@kodax-ai/kodax/session` | **Narrow subset** | Session management only — `listSessions` / `forkSession` / `watchSessions` / ... (9 exports) | IDE plugins reading session history |
400
-
401
- **Rule of thumb**: if you need Runner / Agent / fan-out, import from `/agent`. If you only need skills or mcp APIs, import from `/skills` or `/mcp` to get a smaller bundle. The narrow subsets are subsets of the full packages — they do **not** expose extra symbols.
402
-
403
- **Dynamic Workflows (FEATURE_217, v0.7.49)**: the domain-neutral workflow runtime is part of `/agent` — `import { createWorkflowRuntime, runWorkflow, WorkflowAbortError, WorkflowLimitError } from '@kodax-ai/kodax/agent'`. The coding-side integration (agent backend + built-in workflows + saved-workflow discovery/generation: `createCodingWorkflowBackend`, `runWorkflowFromOptions`, `parallelInvestigation`, `discoverSavedWorkflows`, `generateWorkflowFromOptions`, …) is part of `/coding`. FEATURE_217 is the v0.7.49 home for the full Dynamic Workflow product loop: `/workflow create <request>` generates restricted scripts, `/workflow save <runId> <name>` stores `.workflow.json` rerunnable workflows, generated/saved scripts coordinate agents through `WorkflowApi`, run lifecycle state stays observable, opt-in `isolation:"worktree"` routes selected children to parent-managed worktrees, and all file/shell effects still pass through agent tools and the existing permission gates. There is **no** separate `@kodax-ai/kodax/agent/workflow` root-package subpath; source-package consumers of `@kodax-ai/agent` can still use that package's `./workflow` subpath.
404
-
405
- **Workflow Process Surface (FEATURE_229, v0.7.50)**: workflow progress is now a reusable Agent-layer process contract rather than private REPL text. SDK hosts can subscribe to `WorkflowProcessEvent`/poll `WorkflowProcessSnapshot`, use `createWorkflowRunManager` and `createWorkflowLifecycleController` for stop/pause/resume/result/artifact/delete/prune/identity/preflight controls, and receive ANSI-free provenance fields (`source`, `sourceRunId`, `sourceWorkflowName`, `savedWorkflowName`, `revisionOf`) plus `resultSummary`. `/coding` owns the coding workflow backend and run graph, `/repl` renders the same snapshots, and the terminal UI is not the hidden source of truth. `KodaXEvents` callbacks also take an optional metadata arg (`KodaXToolEventMeta` / `KodaXActivityEventMeta` / `KodaXWorkflowEventMeta`) so a host can attribute every child-agent tool/thinking/progress event to its workflow run and child id without a second event protocol, and generated/saved workflow scripts pass `validateRestrictedWorkflowSource` (compile + source-policy check) plus a generator repair/smoke loop before they run. See [docs/ADR.md ADR-040](docs/ADR.md) for the layering rationale.
406
-
407
- **Host Reads Persisted History (FEATURE_230 + FEATURE_234, v0.7.51)**: two additive closures for hosts that read persisted state. **Durable tool transcript replay** — a resumed session now replays the tool cards the assistant used instead of degrading to text-only. `messages` / `lineage` stay canonical; `SessionData.uiHistory` becomes a bounded, sanitized, terminal-only replay cache. The SDK transcript contract is explicit: `loadSession()` = active model context, `loadFullTranscript()` = append-order host scrollback, `uiHistory` = optional replay cache, and tool cards can always be reconstructed from canonical messages (replay types exported from `@kodax-ai/kodax/session`). **Workflow run host attribution** — `WorkflowProcessTrackerOptions` / `WorkflowProcessSnapshot` gain a host-owned opaque `hostMetadata?: Record<string, string>` that the SDK stores, persists to `run.json`, and echoes back (including after a restart) without interpreting it, so a host can map a run to the session/surface that launched it with zero side table. Unstamped/legacy runs honestly echo `hostMetadata === undefined`. See [docs/features/v0.7.51.md](docs/features/v0.7.51.md).
408
-
409
- **Inline Workflow Authoring (FEATURE_246, v0.7.58)**: in AMA/AMAW the Worker can now author and run a workflow inline via a model-callable `run_workflow` tool — it scouts the codebase with its own tools first, then bakes concrete findings into each child prompt, and runs the script through the **unchanged** sandbox + static-validation + postcondition-verification pipeline. This replaces the context-blind `sideQuery` generator as the primary interactive path (the generator survives only as a fallback for the explicit `/workflow create` command and non-interactive / CI hosts that have no investigating Worker). It adds structured child output (`outputSchema`), the no-barrier `wf.pipeline` staged primitive, same-session resume (`resumeFromRunId`), nested `wf.workflow(...)`, and a `/workflow create` redirect to Worker-authored scouting; `run_workflow` is async / idle-yield so the turn is not blocked. The neutral run-lifecycle manager (`createWorkflowRunManager` / `getDefaultWorkflowRunManager`) now lives in `@kodax-ai/kodax/agent` for non-coding SDK hosts. See [docs/features/v0.7.58.md](docs/features/v0.7.58.md) and [docs/ADR.md](docs/ADR.md) ADR-044/046/047/048/049.
410
-
411
- ---
412
-
413
- ## Features
414
-
415
- - **Modular Architecture** - Use as CLI, as a library, or as a Node-free single binary
416
- - **15 Built-in Provider Aliases** - Anthropic, OpenAI, DeepSeek, Kimi, Kimi Code, Qwen, Zhipu, Zhipu Coding, Zai Coding, MiniMax Coding, MiMo Coding, MiMo, Ark Coding, Gemini CLI, Codex CLI - plus user-defined OpenAI/Anthropic-compatible providers
417
- - **Dynamic Workflows + SDK Process Surface** - Generate/reuse capability-routed workflows, observe live progress through `WorkflowProcessSnapshot`, and control workflow lifecycle from SDK hosts without parsing REPL output
418
- - **V2 Worker single-loop + Sidecar Verifier (default)** - Single-agent main loop with an out-of-band Sidecar Verifier as Stop-hook (claudecode-shape; FEATURE_184 v0.7.42, ADR-030). Verifier returns accept/revise/blocked verdict on Worker text-only termination. The pre-v0.7.43 V1 chain is retired, `emit_handoff` is deleted, accept-verdict UI silently passes through, and content-aware gating skips trivial-chat sidecar calls. Async child steering uses `dispatch_child_task` + `send_message` + `task_stop` with idle-yield wait; specialist routing uses `subagent_type`.
419
- - **Reasoning Effort** - Effort-first control (`off/auto/low/medium/high` plus model-supported extras) across providers
420
- - **Streaming Output** - Real-time response display
421
- - **Session Management** - JSONL format with branchable session lineage tree
422
- - **Skills System** - Natural language triggering, extensible, role-projected in AMA
423
- - **Repo Intelligence** - Built-in full/light repository intelligence with native KodaX auto-injection lane
424
- - **Rich Tool Surface** - 50+ built-in tools across file ops, shell, search, repo intelligence, MCP capabilities, git worktree, and agent control
425
- - **Permission Control** - 3 permission modes with pattern-based control
426
- - **Standalone Binary** - `bun --compile` releases for Win/macOS/Linux x64+arm64, no Node.js required on target machines
427
- - **Cross-Platform** - Windows/macOS/Linux
428
- - **TypeScript Native** - Full type safety and IDE support
429
-
430
- ---
431
-
432
- ## Installation
433
-
434
- ### As CLI Tool
435
-
436
- ```bash
437
- # Clone repository
438
- git clone https://github.com/icetomoyo/KodaX.git
439
- cd KodaX
440
-
441
- # Install dependencies (includes workspace packages)
442
- npm install
443
-
444
- # Build the monorepo
445
- npm run build
446
-
447
- # Link globally (development mode)
448
- npm link
449
-
450
- # Now you can use 'kodax' anywhere
451
- kodax "your task"
452
- ```
453
-
454
- ### As Standalone Binary (no Node required on target)
455
-
456
- KodaX can be packaged into a single executable + a small `builtin/` sidecar directory using `bun --compile`. The target machine does **not** need Node.js or any other runtime.
457
-
458
- Supported targets: `win-x64`, `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`. Win7 / pre-glibc-2.27 distros / LoongArch are not supported.
459
-
460
- **Build locally**:
461
-
462
- ```bash
463
- # Install Bun once on your build machine
464
- npm i -g bun # or scoop/brew/curl install see docs/release.md
465
-
466
- npm run build:binary # Current host platform (fastest)
467
- npm run build:binary:all # All five targets in sequence
468
- node scripts/build-binary.mjs --target=linux-arm64 # Specific target
469
- ```
470
-
471
- Output lives under `dist/binary/<target>/`:
472
-
473
- ```
474
- dist/binary/linux-x64/
475
- ├── kodax # ~60 MB Bun-compiled executable
476
- └── builtin/ # Sidecar built-in skills
477
- ```
478
-
479
- Smoke-test: `dist/binary/<host>/kodax --version`.
480
-
481
- **Automated release**: pushing a `v*` git tag triggers `.github/workflows/release.yml`, which builds all five targets on native runners, runs smoke tests, and publishes a GitHub Release with archives + SHA256SUMS. Use the `workflow_dispatch` button in the Actions UI to test the pipeline without tagging.
482
-
483
- See [docs/release.md](docs/release.md) for full details on build flags, archive layout, troubleshooting, and the build-time `KODAX_BUNDLED` / `KODAX_VERSION` defines.
484
-
485
- ### As Library
486
-
487
- ```bash
488
- npm install @kodax-ai/kodax
489
- ```
490
-
491
- ```typescript
492
- import { runKodaX } from '@kodax-ai/kodax';
493
-
494
- process.env.ZHIPU_API_KEY = process.env.ZHIPU_API_KEY ?? 'your_api_key';
495
-
496
- const result = await runKodaX({
497
- provider: 'zhipu-coding',
498
- effort: 'auto',
499
- events: {
500
- onTextDelta: (text) => process.stdout.write(text),
501
- onComplete: () => console.log('\nDone!'),
502
- },
503
- }, 'your task');
504
-
505
- console.log(result.lastText);
506
- ```
507
-
508
- #### SDK Subpath Imports (v0.7.39+)
509
-
510
- For smaller surface and tree-shake-friendly imports, the SDK is also exposed via subpath exports — pick only the package(s) you need:
511
-
512
- ```typescript
513
- import { Runner } from '@kodax-ai/kodax/agent'; // agent runtime
514
- import { getProvider } from '@kodax-ai/kodax/llm'; // LLM abstraction (15 aliases)
515
- import { runKodaX } from '@kodax-ai/kodax/coding'; // coding tools + prompts
516
- import { SkillRegistry } from '@kodax-ai/kodax/skills'; // zero-dep skill loader
517
- import { loadConfig } from '@kodax-ai/kodax/repl'; // REPL config / session helpers
518
- import { createMcpManager } from '@kodax-ai/kodax/mcp'; // MCP popout manager (v0.7.42)
519
- import { listSessions } from '@kodax-ai/kodax/session'; // session history helpers
520
- ```
521
-
522
- All 9 SDK entries (root + 8 subpaths) share internal code via ESM chunk splitting — importing from `/agent` does not pull in `/repl`'s Ink + React surface.
523
-
524
- > **ESM-only.** The SDK is published as ES Modules. In a CommonJS context (Electron main process, legacy Webpack CJS bundles, `require()`-based code) you must use `await import(...)` instead of `require()`. See [docs/SDK_EMBEDDER_GUIDE.md §5](docs/SDK_EMBEDDER_GUIDE.md#5-consuming-from-a-commonjs-context-electron-main-cjs-bundles) for the canonical recipe + the technical reason most subpaths cannot ship a dual ESM/CJS build.
525
-
526
- For CLI users, provider defaults live in `~/.kodax/config.json`. For library users, API keys are still read from environment variables; if you need custom base URLs or provider aliases, use `registerCustomProviders()` as shown above.
527
-
528
- ---
529
-
530
- ## Usage
531
-
532
- ### REPL Quickstart
533
-
534
- Running `kodax` with no prompt starts the interactive REPL.
535
-
536
- ```bash
537
- kodax
538
- ```
539
-
540
- Inside the REPL you can type normal requests or slash commands:
541
-
542
- ```text
543
- Read package.json and summarize the architecture
544
- /model
545
- /mode
546
- /help
547
- ```
548
-
549
- ### CLI Quickstart
550
-
551
- ```bash
552
- # Set API key
553
- export ZHIPU_API_KEY=your_api_key
554
-
555
- # Basic usage
556
- kodax "Help me create a TypeScript project"
557
-
558
- # Choose a provider explicitly
559
- kodax --provider openai --model gpt-5.4 "Create a REST API"
560
-
561
- # Use higher reasoning effort
562
- kodax --effort high "Review this architecture"
563
- ```
564
-
565
- ### Session Workflows
566
-
567
- Use a session when you want memory across turns. Without a session, each CLI call is independent.
568
-
569
- ```bash
570
- # No memory: two separate calls
571
- kodax "Read src/auth.ts"
572
- kodax "Summarize it"
573
-
574
- # With memory: same session
575
- kodax --session my-project "Read package.json"
576
- kodax --session my-project "Summarize it"
577
- kodax --session my-project "How should I fix the first issue?"
578
-
579
- # Session management
580
- kodax --session list
581
- kodax --session resume "continue"
582
- ```
583
-
584
- ### Session Patterns
585
-
586
- ```bash
587
- # No memory: two independent calls
588
- kodax "Read src/auth.ts" # Agent reads and responds
589
- kodax "Summarize it" # Agent doesn't know what to summarize
590
-
591
- # ✅ With memory: same session
592
- kodax --session auth-review "Read src/auth.ts"
593
- kodax --session auth-review "Summarize it" # Agent knows to summarize auth.ts
594
- kodax --session auth-review "How to fix first issue" # Agent has context
595
- ```
596
-
597
- ### Workflow Examples
598
-
599
- ```bash
600
- # Code review (multi-turn conversation)
601
- kodax --session review "Review src/ directory"
602
- kodax --session review "Focus on security issues"
603
- kodax --session review "Give me fix suggestions"
604
-
605
- # Project development (continuous session)
606
- kodax --session todo-app "Create a Todo application"
607
- kodax --session todo-app "Add delete functionality"
608
- kodax --session todo-app "Write tests"
609
- ```
610
-
611
- ### CLI Reference
612
-
613
- ```text
614
- kodax Start the interactive REPL
615
- -h, --help [topic] Show help or topic help
616
- -p, --print <text> Run a single task and exit
617
- -c, --continue Continue the most recent conversation in this directory
618
- -r, --resume [id] Resume a session by ID, or the latest session
619
- -m, --provider Provider to use
620
- --model <name> Override the model
621
- --reasoning <mode> off | auto | quick | balanced | deep
622
- -t, --thinking Compatibility alias for --reasoning auto
623
- -s, --session <op> Session ID or legacy session operation
624
- -j, --parallel Enable parallel tool execution
625
- --max-iter <n> Max iterations
626
- ```
627
-
628
- ### Permission Control
629
-
630
- KodaX provides 3 permission modes for fine-grained control:
631
-
632
- | Mode | Description | Tools Need Confirmation |
633
- |------|-------------|------------------------|
634
- | `plan` | Read-only planning mode | All modification tools blocked |
635
- | `accept-edits` | Auto-accept file edits | bash only |
636
- | `auto-in-project` | Full auto within project | None (project-scoped) |
637
-
638
- ```bash
639
- # In REPL, use /mode command
640
- /mode plan # Switch to plan mode (read-only)
641
- /mode accept-edits # Switch to accept-edits mode
642
- /mode auto-in-project # Switch to auto-in-project mode
643
- /auto # Alias for auto-in-project
644
-
645
- # Check current mode
646
- /mode
647
- ```
648
-
649
- **Features:**
650
- - In `accept-edits` mode, choosing "always" can persist safe Bash allow-patterns
651
- - Plan mode includes system prompt context for LLM awareness
652
- - Permanent protection zones: `.kodax/`, `~/.kodax/`, paths outside project
653
- - Pattern-based permission: Allow specific Bash commands (e.g., `Bash(npm install)`)
654
- - Unified diff display for write/edit operations
655
-
656
- ### CLI Help Topics
657
-
658
- Get detailed help for specific topics:
659
-
660
- ```bash
661
- # Basic help
662
- kodax -h
663
- kodax --help
664
-
665
- # Detailed topic help
666
- kodax -h sessions # Session management details
667
- kodax -h init # Long-running project initialization
668
- kodax -h project # Project mode / harness workflow
669
- kodax -h auto # Auto-continue mode
670
- kodax -h provider # LLM provider configuration
671
- kodax -h thinking # Thinking/reasoning effort and compatibility modes
672
- kodax -h team # Multi-agent parallel execution
673
- kodax -h print # Print configuration
674
- ```
675
-
676
- ### Environment Variables
677
-
678
- KodaX recognizes a number of environment variables for tuning runtime behavior. The most commonly used ones are listed below; for the full list, search the repo for `process.env.KODAX_`.
679
-
680
- #### `KODAX_MAX_OUTPUT_TOKENS`
681
-
682
- Overrides the per-turn `max_tokens` value sent to **every** provider (Anthropic, OpenAI, Zhipu, Kimi, MiniMax, Qwen, DeepSeek, MiMo, Gemini, Codex, …). Set to a positive integer; unset or non-numeric values are ignored. This is an **explicit user intent**: when set, it wins over the provider's model descriptor cap, over the provider config default, and over the global `KODAX_MAX_TOKENS` fallback. RST defense is handled at the provider config layer (`streamMaxDurationMs` watchdog + non-streaming fallback in `packages/llm/src/providers/registry.ts`), so this variable is purely an output-budget knob.
683
-
684
- ```bash
685
- # Allow up to 48K output tokens per turn (use a higher cap when generating long files)
686
- export KODAX_MAX_OUTPUT_TOKENS=48000
687
- kodax "generate the full implementation"
688
-
689
- # Unset to restore default behavior
690
- unset KODAX_MAX_OUTPUT_TOKENS
691
- ```
692
-
693
- Precedence used by every provider's `getEffectiveMaxOutputTokens()` (see `packages/llm/src/providers/base.ts`):
694
-
695
- 1. One-shot per-request override (agent-loop escalation / context-overflow recovery — internal)
696
- 2. **`KODAX_MAX_OUTPUT_TOKENS`** (this variable, explicit user intent)
697
- 3. Active model descriptor's `maxOutputTokens` (FEATURE_098 per-model cap)
698
- 4. Provider config default
699
- 5. Global `KODAX_MAX_TOKENS` fallback
700
-
701
- Related variables: `KODAX_MAX_TOKENS` (global fallback when no provider/model cap applies), `KODAX_ESCALATED_MAX_OUTPUT_TOKENS` (escalation budget used by the agent loop when a turn returns `stop_reason: max_tokens`).
702
-
703
- > **Retired in v0.7.42**: `KODAX_RST_PRONE_PROVIDERS` and `KODAX_WRITE_TURN_MAX_TOKENS` (the v0.7.28 P2b write-turn cap mechanism) are no longer recognized. The 2026-04 bench measured RST as time-based (zhipu-coding 308s server kill window), not payload-size-based, so the cap was retired in favor of the per-provider `streamMaxDurationMs` watchdog + non-streaming fallback chain (configured in `registry.ts`). Existing env exports become silent no-ops; remove them from shell profiles when convenient.
704
-
705
- #### Sidecar verifier diagnostics
706
-
707
- Use these when diagnosing Worker text-only completion stalls or custom provider verifier behavior:
708
-
709
- ```bash
710
- export KODAX_VERIFIER_LOG=1
711
- export KODAX_VERIFIER_PROVIDER=anthropic
712
- export KODAX_VERIFIER_MODEL=claude-haiku-4-5-20251001
713
- ```
714
-
715
- - `KODAX_VERIFIER_LOG=1` shows verifier gate/elapsed/trace information and is equivalent to `"verifierLog": true` in `~/.kodax/config.json`.
716
- - `KODAX_VERIFIER_PROVIDER` + `KODAX_VERIFIER_MODEL` route the verifier to a separate provider/model instead of inheriting the main Worker model. Set both together.
717
- - `KODAX_VERIFIER_ALWAYS=1` forces the verifier to fire on every text-only completion for debugging/regression sweeps.
718
-
719
- SDK/headless hosts can observe actionable Sidecar Verifier messages via
720
- `KodaXEvents.onSidecarMessage`; JSONL output emits the same payload as
721
- `sidecar.message`. Only `revise` and `blocked` verdicts are surfaced; `accept`
722
- stays silent.
723
-
724
- ## Advanced Library Usage
725
-
726
- #### Simple Mode (runKodaX)
727
-
728
- ```typescript
729
- import { runKodaX, KodaXEvents } from '@kodax-ai/kodax';
730
-
731
- const events: KodaXEvents = {
732
- onTextDelta: (text) => process.stdout.write(text),
733
- onThinkingDelta: (text) => console.log(`Thinking delta: ${text.length} chars`),
734
- onToolResult: (result) => console.log(`Tool ${result.name}: ${result.content.slice(0, 100)}`),
735
- onSidecarMessage: (event) => console.log(`[sidecar:${event.verdict}] ${event.content}`),
736
- onComplete: () => console.log('\nDone!'),
737
- onError: (e) => console.error(e.message),
738
- };
739
-
740
- const result = await runKodaX({
741
- provider: 'zhipu-coding',
742
- effort: 'auto',
743
- events,
744
- }, 'What is 1+1?');
745
-
746
- console.log(result.lastText);
747
- ```
748
-
749
- #### Continuous Session (KodaXClient)
750
-
751
- ```typescript
752
- import { KodaXClient } from '@kodax-ai/kodax';
753
-
754
- const client = new KodaXClient({
755
- provider: 'zhipu-coding',
756
- effort: 'auto',
757
- events: {
758
- onTextDelta: (t) => process.stdout.write(t),
759
- },
760
- });
761
-
762
- // First message
763
- await client.send('Read package.json');
764
-
765
- // Continue same session
766
- await client.send('Summarize it');
767
-
768
- console.log(client.getSessionId());
769
- ```
770
-
771
- #### Custom Session Storage
772
-
773
- ```typescript
774
- import { runKodaX, KodaXSessionStorage, KodaXMessage } from '@kodax-ai/kodax';
775
-
776
- class MyDatabaseStorage implements KodaXSessionStorage {
777
- async save(id: string, data: { messages: KodaXMessage[]; title: string; gitRoot: string }) {
778
- // Save to your database
779
- }
780
- async load(id: string) {
781
- // Load from your database
782
- return null;
783
- }
784
- }
785
-
786
- await runKodaX({
787
- provider: 'zhipu-coding',
788
- session: {
789
- id: 'my-session-123',
790
- storage: new MyDatabaseStorage(),
791
- },
792
- events: { ... },
793
- }, 'task');
794
- ```
795
-
796
- ### Library Modes Comparison
797
-
798
- | Feature | runKodaX | KodaXClient |
799
- |---------|----------|-------------|
800
- | **Message Memory** | ❌ No | ✅ Yes |
801
- | **Call Style** | Function | Class instance |
802
- | **Context** | Independent each time | Accumulates |
803
- | **Use Case** | Single tasks, batch processing | Interactive dialogue, multi-step tasks |
804
-
805
- ---
806
-
807
- ## SDK Usage
808
-
809
- KodaX ships as a single npm package `@kodax-ai/kodax` with 8 SDK subpath exports (ADR-024 v0.7.39 + ADR-032 v0.7.42 + ADR-038 v0.7.49 + v0.7.56 `/media`). Each subpath is tree-shake-friendly so consumers pull only what they need:
810
-
811
- ```bash
812
- npm install @kodax-ai/kodax
813
- ```
814
-
815
- ```typescript
816
- import { runKodaX } from '@kodax-ai/kodax'; // root: CLI helpers + runKodaX
817
- import { Runner, runFanOut } from '@kodax-ai/kodax/agent'; // generic Agent framework
818
- import { getProvider } from '@kodax-ai/kodax/llm'; // 15-alias LLM abstraction
819
- import { KODAX_TOOLS } from '@kodax-ai/kodax/coding'; // tools + prompts + agent loop
820
- import { createImageArtifactFromPath } from '@kodax-ai/kodax/media'; // input artifact helpers
821
- import { runInkInteractiveMode } from '@kodax-ai/kodax/repl'; // Ink TUI entrypoint
822
- import { SkillRegistry } from '@kodax-ai/kodax/skills'; // zero-dep skill loader
823
- import { createMcpManager } from '@kodax-ai/kodax/mcp'; // MCP popout manager (v0.7.42)
824
- import { listSessions } from '@kodax-ai/kodax/session'; // session history helpers
825
- ```
826
-
827
- > The SDK is **ESM-only**. CommonJS consumers (Electron main / Webpack CJS / `require()` callers) must use `await import('@kodax-ai/kodax/...')` see [docs/SDK_EMBEDDER_GUIDE.md §5](docs/SDK_EMBEDDER_GUIDE.md#5-consuming-from-a-commonjs-context-electron-main-cjs-bundles).
828
-
829
- ### `@kodax-ai/kodax/llm` LLM Abstraction
830
-
831
- 15 built-in provider aliases (Anthropic, OpenAI, DeepSeek, Kimi, Kimi-Code, Qwen, Zhipu, Zhipu-Coding, Zai-Coding, MiniMax-Coding, MiMo, MiMo-Coding, Ark-Coding, Gemini-CLI, Codex-CLI) + custom provider registration.
832
-
833
- ```typescript
834
- import { getProvider, KodaXBaseProvider } from '@kodax-ai/kodax/llm';
835
-
836
- const provider = getProvider('anthropic');
837
- const stream = await provider.streamCompletion(
838
- [{ role: 'user', content: 'Hello!' }],
839
- { onTextDelta: (text) => process.stdout.write(text) }
840
- );
841
-
842
- for await (const result of stream) {
843
- if (result.type === 'text') { /* … */ }
844
- else if (result.type === 'tool_use') { /* … */ }
845
- }
846
- ```
847
-
848
- **Key Features**: unified provider interface · streaming · reasoning effort (`off/auto/low/medium/high` plus model-supported extras) · per-provider retry + error handling · zero business-logic dependencies.
849
-
850
- ### `@kodax-ai/kodax/agent` Agent Framework (standalone-consumable)
851
-
852
- ADR-021 standalone-consumable: `@kodax-ai/agent` has **zero inbound `@kodax-ai/coding` dependency** — you can wire any tool surface on top of it.
853
-
854
- ```typescript
855
- import {
856
- Runner,
857
- runFanOut,
858
- runWithIdleYield,
859
- registerChildTask,
860
- type ChildTaskRegistry,
861
- generateSessionId,
862
- estimateTokens,
863
- DefaultSummaryCompaction,
864
- } from '@kodax-ai/kodax/agent';
865
-
866
- // Bounded-concurrency fan-out with abort + structured progress events (v0.7.39 FEATURE_120)
867
- const result = await runFanOut({
868
- bundles: [{ id: 'a', task: 'audit-foo' }, { id: 'b', task: 'audit-bar' }],
869
- maxParallel: 4,
870
- run: async (bundle) => doWork(bundle),
871
- });
872
-
873
- // Idle-yield wait pause when out of useful work, resume when a wake event arrives
874
- await runWithIdleYield({ runOnce, computeSnapshot, registry, messageQueue, agentId });
875
-
876
- // Pluggable compaction policy (FEATURE_081)
877
- const policy = new DefaultSummaryCompaction({ thresholdRatio: 0.8, keepRecent: 10 });
878
- ```
879
-
880
- **Key Features**: `Runner` + per-step lifecycle · `runFanOut` (bounded-concurrency + abort + progress events) · `runWithIdleYield` (chat-while-waiting) · `ChildTaskRegistry` / `TaskAbortRegistry` · session-id generation · tiktoken-based token estimation · `CompactionPolicy` interface.
881
-
882
- ### `@kodax-ai/kodax/skills` Skills System
883
-
884
- Zero external dependencies. Markdown-based skill files with natural-language triggers and variable resolution.
885
-
886
- ```typescript
887
- import {
888
- SkillRegistry,
889
- discoverSkills,
890
- executeSkill,
891
- type SkillContext,
892
- } from '@kodax-ai/kodax/skills';
893
-
894
- const skills = await discoverSkills(['/path/to/skills']);
895
- const registry = new SkillRegistry();
896
- await registry.registerSkills(skills);
897
-
898
- const result = await executeSkill({
899
- skillId: 'code-review',
900
- arguments: { target: 'src/' },
901
- workingDirectory: process.cwd(),
902
- });
903
- ```
904
-
905
- **Key Features**: zero deps · markdown-based skill files · natural-language triggering · variable resolution · built-in skills included.
906
-
907
- ### `@kodax-ai/kodax/coding` — Coding Agent
908
-
909
- Complete coding agent: 50+ tools (`read`/`write`/`edit`/`bash`/`grep`/`glob`/`dispatch_child_task`/`send_message`/`task_stop`/...) + Worker role prompt + Sidecar Verifier (out-of-band Stop-hook) + agent loop + auto-continue + session management.
910
-
911
- ```typescript
912
- import { runKodaX, KodaXClient, KODAX_TOOLS } from '@kodax-ai/kodax/coding';
913
-
914
- // Single-task helper
915
- const result = await runKodaX({
916
- provider: 'zhipu-coding',
917
- effort: 'auto',
918
- events: { onTextDelta: (text) => process.stdout.write(text) },
919
- }, 'Read package.json and explain the dependencies');
920
-
921
- // Continuous session
922
- const client = new KodaXClient({
923
- provider: 'anthropic',
924
- effort: 'auto',
925
- events: { /* */ },
926
- });
927
- await client.send('Create a new file');
928
- await client.send('Add a function to it'); // Has context from previous message
929
- ```
930
-
931
- **Key Features**: 50+ built-in tools (see [Tools](#tools)) · V2 Worker single-loop + Sidecar Verifier (FEATURE_184 v0.7.42 / V1 chain fully retired by FEATURE_193 v0.7.43) · async child steering via `send_message` / `task_stop` (FEATURE_120, v0.7.39) · idle-yield wait mechanic (FEATURE_155, v0.7.38) · specialist routing via `subagent_type` (FEATURE_191, v0.7.43) · auto-continue · session lineage.
932
-
933
- ### `@kodax-ai/kodax/repl` Interactive Terminal UI
934
-
935
- Ink/React-based interactive REPL. Permission modes, command system, themed streaming display.
936
-
937
- ```typescript
938
- import { runInkInteractiveMode } from '@kodax-ai/kodax/repl';
939
-
940
- // Usually used via the `kodax` bin command; can be embedded:
941
- // - Interactive terminal UI (Ink components)
942
- // - Permission control (auto/plan/accept-edits modes)
943
- // - Command system (/help, /mode, /clear, /status, …)
944
- // - Skills integration
945
- // - Theme support
946
- await runInkInteractiveMode({ provider: 'zhipu-coding', effort: 'auto' });
947
- ```
948
-
949
- **Key Features**: Ink-based React components · 3 permission modes (auto / plan / accept-edits) · built-in commands · real-time streaming display · context-usage indicator.
950
-
951
- ### Package Dependency Graph (workspace internal)
952
-
953
- ```
954
- @kodax-ai/llm (zero business-logic deps)
955
-
956
- @kodax-ai/agent (depends @kodax-ai/llm; ADR-021 standalone-consumable;
957
- inlines session-lineage + capabilities/{mcp,skills} +
958
- tracing per ADR-036 v0.7.43)
959
-
960
- @kodax-ai/coding (depends llm + agent; inlines repo-intelligence/protocol per ADR-036)
961
-
962
- @kodax-ai/repl (depends coding + ink + react)
963
- ```
964
-
965
- **Subpath Recommendations**:
966
-
967
- | Use Case | Subpath | Why |
968
- |----------|---------|-----|
969
- | Only need LLM abstraction | `@kodax-ai/kodax/llm` | Minimal deps; 15 built-in aliases |
970
- | Building custom agent | `@kodax-ai/kodax/agent` | Runner + fan-out + idle-yield + session-lineage + capabilities |
971
- | Coding tasks | `@kodax-ai/kodax/coding` | Complete coding agent + tools |
972
- | Terminal app | `@kodax-ai/kodax/repl` | Full interactive experience |
973
-
974
- ---
975
-
976
- | Provider | Environment Variable | Reasoning Support | Default Model |
977
- |----------|----------------------|-------------------|---------------|
978
- | anthropic | `ANTHROPIC_API_KEY` | Native | claude-sonnet-4-6 (`claude-opus-4-6` / `claude-haiku-4-5` via `/model`) |
979
- | openai | `OPENAI_API_KEY` | Native | gpt-5.3-codex (`gpt-5.4` / `gpt-5.3-codex-spark` via `/model`) |
980
- | kimi | `KIMI_API_KEY` | Native | kimi-k2.6 (`kimi-k2.7-code` 256K / `k2.5` via `/model`) |
981
- | kimi-code | `KIMI_CODE_API_KEY` | Native | kimi-for-coding |
982
- | qwen | `QWEN_API_KEY` | Native | qwen3.5-plus |
983
- | zhipu | `ZHIPU_API_KEY` | Native | glm-5 (`glm-5.2` 1M ctx / `glm-5.1` / `glm-5-turbo` via `/model`) |
984
- | zhipu-coding | `ZHIPU_CODING_API_KEY` | Native | glm-5 (`glm-5.2` 1M ctx / `glm-5.1` / `glm-5-turbo` via `/model`) |
985
- | zai-coding | `ZAI_CODING_API_KEY` | Native | glm-5.2 (Zhipu Coding Plan overseas mirror via `api.z.ai`, Anthropic-compat same model lineup as `zhipu-coding`, served from outside CN) |
986
- | minimax-coding | `MINIMAX_CODING_API_KEY` | Native | MiniMax-M2.7 (`MiniMax-M3` Frontier Coding, native multimodal + 1M ctx, plus `MiniMax-M2.7-highspeed` via `/model`) |
987
- | mimo | `MIMO_API_KEY` | Native | mimo-v2.5-pro (Xiaomi MiMo pay-per-token, Anthropic-compat) |
988
- | mimo-coding | `MIMO_CODING_API_KEY` | Native | mimo-v2.5-pro (Xiaomi Token Plan, Anthropic-compat) |
989
- | ark-coding | `ARK_CODING_API_KEY` | Native | glm-5.2 (Volcengine Ark Coding Plan — GLM-5.2 (alias: `glm-latest`) · Kimi K2.7 Code / K2.6 · MiniMax M3 / M2.7 · DeepSeek V4 Pro / V4 Flash · Doubao Seed 2.0 Code / Pro / Lite · Doubao Seed Code) |
990
- | deepseek | `DEEPSEEK_API_KEY` | Native | deepseek-v4-flash (`deepseek-v4-pro` via `/model`) |
991
- | gemini-cli | `GEMINI_API_KEY` | Prompt-only / CLI bridge | (via gemini CLI) |
992
- | codex-cli | `OPENAI_API_KEY` | Prompt-only / CLI bridge | (via codex CLI) |
993
-
994
- > **Custom providers**: any OpenAI- or Anthropic-compatible endpoint can be added via `customProviders[]` in `~/.kodax/config.json` (CLI) or `registerCustomProviders()` (library). See the [Quick Start](#2-configure-a-provider) for the configuration shape.
995
-
996
- ### Examples
997
-
998
- ```bash
999
- # Use Zhipu Coding
1000
- kodax --provider zhipu-coding --thinking "Help me optimize this code"
1001
-
1002
- # Use OpenAI
1003
- export OPENAI_API_KEY=your_key
1004
- kodax --provider openai "Create a REST API"
1005
-
1006
- # Resume last session
1007
- kodax --session resume
1008
-
1009
- # List all sessions
1010
- kodax --session list
1011
-
1012
- # Parallel tool execution
1013
- kodax --parallel "Read package.json and tsconfig.json"
1014
-
1015
- # Adaptive multi-agent (AMA) mode — V2 Worker single-loop with `dispatch_child_task` fan-out
1016
- kodax --agent-mode ama "Analyze code structure, check test coverage, find bugs"
1017
- ```
1018
-
1019
- ---
1020
-
1021
- ## Tools
1022
-
1023
- KodaX ships 50+ built-in tools, grouped below. They are registered as a single flat tool surface to the LLM; the categories here are just for navigation.
1024
-
1025
- ### File operations
1026
- | Tool | Description |
1027
- |------|-------------|
1028
- | `read` | Read file contents (supports offset/limit) |
1029
- | `write` | Write a new file or fully rewrite an existing one |
1030
- | `edit` | Exact string replacement (supports `replace_all`) |
1031
- | `multi_edit` | Atomic batch of independent edits to one file |
1032
- | `insert_after_anchor` | Insert content after a unique anchor without rewriting the file |
1033
- | `undo` | Revert the last file modification |
1034
-
1035
- ### Shell & search
1036
- | Tool | Description |
1037
- |------|-------------|
1038
- | `bash` | Execute a shell command (supports `run_in_background`, output truncation) |
1039
- | `glob` | Find files by pattern |
1040
- | `grep` | Regex content search (context lines, multiline, file-type filter, pagination) |
1041
- | `code_search` | Lower-noise code search (extension-provider aware) |
1042
- | `semantic_lookup` | Symbol/module/process-aware search backed by repo intelligence |
1043
- | `web_search` | Discovery-oriented web search with trust + freshness signals |
1044
- | `web_fetch` | Fetch a specific URL with provenance hints |
1045
-
1046
- ### Repo Intelligence (working tools)
1047
- | Tool | Description |
1048
- |------|-------------|
1049
- | `repo_overview` | Summarize structure, key areas, entry hints, intelligence snapshot |
1050
- | `changed_scope` | Which files/areas/categories the current diff touches |
1051
- | `changed_diff` | Paged diff slice for a single file |
1052
- | `changed_diff_bundle` | Paged diff slices for multiple files in one call |
1053
- | `module_context` | Module capsule (deps, entries, symbols, tests, docs) |
1054
- | `symbol_context` | Definition + probable callers/callees + alternatives |
1055
- | `process_context` | Approximate static execution capsule for an entry |
1056
- | `impact_estimate` | Blast radius for a symbol/path/module |
1057
-
1058
- ### MCP capabilities (when MCP servers are configured)
1059
- | Tool | Description |
1060
- |------|-------------|
1061
- | `mcp_search` / `mcp_describe` / `mcp_call` | Discover and invoke MCP tools through the shared capability runtime |
1062
- | `mcp_read_resource` / `mcp_get_prompt` | Read MCP resources and prompts |
1063
-
1064
- ### Git worktree
1065
- | Tool | Description |
1066
- |------|-------------|
1067
- | `worktree_create` | Create a new worktree on an isolated branch for safe agent work |
1068
- | `worktree_remove` | Remove a worktree (with safety checks) |
1069
-
1070
- ### Agent control & UX
1071
- | Tool | Description |
1072
- |------|-------------|
1073
- | `dispatch_child_task` | Spawn a sub-agent for an independent investigation/edit task. Optional `model_hint: 'fast' \| 'balanced' \| 'deep'` (advisory; routing no-op until FEATURE_102 v0.7.45). |
1074
- | `send_message` | Append an instruction to an in-flight child's queue — surfaces as `<coordinator-instruction>` at the child's next turn boundary. Coordinator-only. (FEATURE_120, v0.7.39) |
1075
- | `task_stop` | Request graceful exit of a specific child. Current tool finishes atomically, then the child sees a `<coordinator-stop-request>` and emits a final summary. Coordinator-only. (FEATURE_120, v0.7.39) |
1076
- | `ask_user_question` | Single/multi-select or free-text prompt back to the user |
1077
- | `exit_plan_mode` | Present a finalized plan for approval (REPL only) |
1078
- | `run_workflow` | Author and run a workflow script inline (AMAW default). Scouts the codebase first, then bakes findings into child prompts; structured output via `outputSchema`, same-session `resumeFromRunId`, nested `wf.workflow(...)`. Async / idle-yield. (FEATURE_246, v0.7.58) |
1079
- | `emit_managed_protocol` | Internal managed-task protocol side-channel for role payloads (verdict). V2 Worker single-loop + Sidecar Verifier is the default since v0.7.42 (FEATURE_184); V1 chain retired in v0.7.43 (FEATURE_193). |
1080
-
1081
- ---
1082
-
1083
- ## Skills System
1084
-
1085
- KodaX includes a built-in Skills system that can be triggered by natural language:
1086
-
1087
- ```bash
1088
- # Natural language triggering (no explicit /skill needed)
1089
- kodax "帮我审查代码" # Triggers code-review skill
1090
- kodax "写测试用例" # Triggers tdd skill
1091
- kodax "提交代码" # Triggers git-workflow skill
1092
-
1093
- # Explicit skill command
1094
- kodax /skill:code-review
1095
- ```
1096
-
1097
- Built-in skills include:
1098
- - **code-review** - Code review and quality analysis
1099
- - **tdd** - Test-driven development workflow
1100
- - **git-workflow** - Git commit and workflow automation
1101
-
1102
- Skills are stored in `~/.kodax/skills/` and can be extended with custom skills.
1103
-
1104
- ---
1105
-
1106
- ## Commands (CLI)
1107
-
1108
- Commands are `/xxx` shortcuts in CLI:
1109
-
1110
- ```bash
1111
- kodax /review src/auth.ts
1112
- kodax /test
1113
- ```
1114
-
1115
- Commands are stored in `~/.kodax/commands/`:
1116
- - `.md` files → Prompt commands (content used as prompt)
1117
- - `.ts/.js` files → Programmable commands
1118
-
1119
- ---
1120
-
1121
- ## API Exports
1122
-
1123
- ```typescript
1124
- // Main functions
1125
- export { runKodaX, KodaXClient };
1126
-
1127
- // Types
1128
- export type {
1129
- KodaXEvents, KodaXOptions, KodaXResult,
1130
- KodaXMessage, KodaXContentBlock,
1131
- KodaXSessionStorage, KodaXToolDefinition
1132
- };
1133
-
1134
- // Tools
1135
- export { KODAX_TOOLS, KODAX_TOOL_REQUIRED_PARAMS, executeTool };
1136
-
1137
- // Providers
1138
- export { getProvider, KODAX_PROVIDERS, KodaXBaseProvider };
1139
-
1140
- // Utilities
1141
- export {
1142
- estimateTokens,
1143
- getGitRoot, getGitContext, getEnvContext, getProjectSnapshot,
1144
- checkPromiseSignal
1145
- };
1146
- ```
1147
-
1148
- ---
1149
-
1150
- ## Development
1151
-
1152
- ```bash
1153
- # Development mode (using tsx)
1154
- npm run dev "your task"
1155
-
1156
- # Build
1157
- npm run build
1158
-
1159
- # Optional: only build workspace packages
1160
- npm run build:packages
1161
-
1162
- # Build standalone binary (current platform / all platforms)
1163
- npm run build:binary
1164
- npm run build:binary:all
1165
-
1166
- # Run tests
1167
- npm test
1168
-
1169
- # Eval-driven development tests (provider matrices, identity round-trip, etc.)
1170
- npm run test:eval
1171
-
1172
- # Clean
1173
- npm run clean
1174
- ```
1175
-
1176
- ### Repo Intelligence cache directories
1177
-
1178
- KodaX uses one repo-intelligence cache root with separate built-in engine profiles:
1179
-
1180
- - `.agent/repo-intelligence/`
1181
- - Full-engine repo-intelligence artifacts and existing task-engine snapshots.
1182
- - `.agent/repo-intelligence/light/`
1183
- - Light-mode heuristic index artifacts.
1184
-
1185
- They are intentionally separated so:
1186
-
1187
- - full and light profiles can be rebuilt independently.
1188
- - light-mode confidence/capability state cannot be mistaken for full-engine state.
1189
- - future cache migrations can delete one profile without corrupting the other.
1190
-
1191
- `.agent/repo-intelligence/` is local generated state and should not be committed.
1192
-
1193
- ---
1194
-
1195
- ## Code Style
1196
-
1197
- ### Comment Guidelines
1198
-
1199
- KodaX uses an **English-first** comment style with selective Chinese brief notes for complex logic.
1200
-
1201
- | Situation | Style | Example |
1202
- |-----------|-------|---------|
1203
- | Import/Export | English only | `// Import dependencies` |
1204
- | Simple constants | English only | `// Max retry count` |
1205
- | Simple logic | English only | `// Return if null` |
1206
- | **Business rules** | English + Chinese | `// Skip tool_result - 跳过工具结果块` |
1207
- | **Platform compatibility** | English + Chinese | `// Windows path handling - Windows 路径处理` |
1208
- | **Performance optimization** | English + Chinese | `// Debounce to prevent flicker - 防抖避免闪烁` |
1209
-
1210
- ---
1211
-
1212
- ## Documentation
1213
-
1214
- - [README_CN.md](README_CN.md) - Chinese Documentation
1215
- - [docs/release.md](docs/release.md) - Standalone binary build & release pipeline
1216
- - [docs/PRD.md](docs/PRD.md) - Product Requirements
1217
- - [docs/ADR.md](docs/ADR.md) - Architecture Decisions
1218
- - [docs/HLD.md](docs/HLD.md) - High-Level Design
1219
- - [docs/DD.md](docs/DD.md) - Detailed Design
1220
- - [docs/FEATURE_LIST.md](docs/FEATURE_LIST.md) - Feature Tracking
1221
- - [docs/test-guides/](docs/test-guides/) - Feature-specific test guides
1222
- - [CHANGELOG.md](CHANGELOG.md) - Version History (v0.7.0+; [archive](docs/CHANGELOG_ARCHIVE.md) for older)
1223
-
1224
- ---
1225
-
1226
- ## License
1227
-
1228
- [Apache License 2.0](LICENSE) - Copyright 2026 [icetomoyo](mailto:icetomoyo@gmail.com)
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="assets/logo-dark.svg">
4
+ <source media="(prefers-color-scheme: light)" srcset="assets/logo-light.svg">
5
+ <img src="assets/logo-light.svg" alt="KodaX" width="640">
6
+ </picture>
7
+ </p>
8
+
9
+ <p align="center">
10
+ <b>Open-source AI coding agent on every LLM you can reach.</b><br>
11
+ Anthropic · OpenAI · DeepSeek · Kimi · Zhipu · MiniMax · MiMo · Ark · Qwen · Gemini · Codex.<br>
12
+ REPL · CLI · library · Node-free single binary.
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="https://www.npmjs.com/package/@kodax-ai/kodax"><img alt="npm version" src="https://img.shields.io/npm/v/@kodax-ai/kodax?style=flat-square&color=cb3837"></a>
17
+ <a href="LICENSE"><img alt="license" src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square"></a>
18
+ <a href="https://github.com/icetomoyo/KodaX/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/icetomoyo/KodaX?style=flat-square&logo=github&color=f1c40f"></a>
19
+ <a href="https://github.com/icetomoyo/KodaX/actions"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/icetomoyo/KodaX/release.yml?style=flat-square&label=release"></a>
20
+ <img alt="providers" src="https://img.shields.io/badge/LLMs-15_aliases_+_custom-2ecc71?style=flat-square">
21
+ </p>
22
+
23
+ <p align="center">
24
+ <a href="#install-in-30-seconds">Install</a> ·
25
+ <a href="#four-ways-to-use-kodax">Usage</a> ·
26
+ <a href="#sdk-usage">SDK</a> ·
27
+ <a href="CHANGELOG.md">Changelog</a> ·
28
+ <a href="docs/FEATURE_LIST.md">Roadmap</a> ·
29
+ <a href="https://github.com/icetomoyo/KodaX/discussions">Discussions</a> ·
30
+ <a href="README_CN.md">中文 README</a>
31
+ </p>
32
+
33
+ <p align="center">
34
+ <img src="kodax-hd.gif" alt="KodaX in action" width="880">
35
+ </p>
36
+
37
+ ---
38
+
39
+ ## Install in 30 seconds
40
+
41
+ ```bash
42
+ npm i -g @kodax-ai/kodax
43
+
44
+ # Pick any one you have an API key for:
45
+ export ZHIPU_API_KEY=... # or ANTHROPIC_API_KEY / OPENAI_API_KEY / KIMI_API_KEY /
46
+ # MINIMAX_API_KEY / MIMO_API_KEY / ARK_API_KEY / QWEN_API_KEY /
47
+ # DEEPSEEK_API_KEY / GEMINI_API_KEY
48
+
49
+ kodax
50
+ ```
51
+
52
+ That's it. You're in the REPL — ask anything in natural language.
53
+
54
+ > **No-Node target machines:** download a Bun-compiled single binary for Windows / macOS / Linux × x64 + arm64 from the [GitHub Releases](https://github.com/icetomoyo/KodaX/releases) page. See [docs/release.md](docs/release.md) for the build pipeline.
55
+
56
+ ---
57
+
58
+ ## Four ways to use KodaX
59
+
60
+ | Form | Command / Import | When to use it |
61
+ |---|---|---|
62
+ | **REPL** | `kodax` | Interactive multi-turn coding session with streaming UI, permissions, slash commands |
63
+ | **CLI** | `kodax -p "your task"` | One-shot scripted task, CI runs, batch processing |
64
+ | **Library** | `import { runKodaX } from '@kodax-ai/kodax'` | Embed in your own tool / agent / web service |
65
+ | **Single binary** | `./kodax` | Distribute to machines that don't have Node installed |
66
+
67
+ ---
68
+
69
+ ## Why KodaX
70
+
71
+ <table>
72
+ <tr>
73
+ <td width="33%" align="center" valign="top">
74
+ <h3>🇨🇳 6 China-native LLMs</h3>
75
+ <sub>Zhipu · Kimi · MiniMax · MiMo · Ark · Qwen</sub>
76
+ <br><br>
77
+ First-class adapters with cross-provider <a href="benchmark/EVAL_GUIDELINES.md">prompt-eval calibration</a> on a canonical 5-alias panel — not OpenAI-compat shims.
78
+ </td>
79
+ <td width="33%" align="center" valign="top">
80
+ <h3>📦 Single-file binary</h3>
81
+ <sub>Bun --compile · Win / macOS / Linux · x64 + arm64</sub>
82
+ <br><br>
83
+ No Node required on the target machine. Drop one file, run anywhere — restricted envs, CI runners, air-gapped boxes.
84
+ </td>
85
+ <td width="33%" align="center" valign="top">
86
+ <h3>🌳 Branchable session lineage</h3>
87
+ <sub>Fork · rewind · parallel edit</sub>
88
+ <br><br>
89
+ Conversation history is a DAG, not a list. Powers the upcoming <b>KodaX Space</b> desktop app.
90
+ </td>
91
+ </tr>
92
+ <tr>
93
+ <td align="center" valign="top">
94
+ <h3>🤖 Multi-agent by default</h3>
95
+ <sub>V2 Worker single-loop + Sidecar Verifier + async children</sub>
96
+ <br><br>
97
+ <code>dispatch_child_task</code>, <code>send_message</code>, <code>task_stop</code>, multi-instance auto-coordination with content-hash safety net.
98
+ </td>
99
+ <td align="center" valign="top">
100
+ <h3>🧩 Skills + self-construction</h3>
101
+ <sub>Markdown skills, NL triggers</sub>
102
+ <br><br>
103
+ 5-stage self-modification staircase (scaffold → validate → stage → test → activate) gated by an 8-invariant admission contract.
104
+ </td>
105
+ <td align="center" valign="top">
106
+ <h3>🛠 50+ built-in tools</h3>
107
+ <sub>File · shell · search · MCP · ACP</sub>
108
+ <br><br>
109
+ Repo intelligence, semantic search, git worktree, web fetch — all addressable through one clean tool surface.
110
+ </td>
111
+ </tr>
112
+ </table>
113
+
114
+ ## How KodaX compares
115
+
116
+ | Feature | **KodaX** | Claude Code | Aider | Codex CLI | Cursor | Cline |
117
+ |---|---|---|---|---|---|---|
118
+ | Open source | ✅ Apache&nbsp;2.0 | ❌ Source-available | ✅ Apache&nbsp;2.0 | ✅ Apache&nbsp;2.0 | ❌ Proprietary | ✅ Apache&nbsp;2.0 |
119
+ | Node-free single binary | ✅ Bun | ❌ Node | ❌ Python | ✅ Rust | ❌ Electron | ❌ Extension |
120
+ | Native China providers<br><sub>(Zhipu · Kimi · MiniMax · MiMo · Ark · Qwen)</sub> | ✅ 6 native | ❌ | ⚠ via LiteLLM | ❌ OpenAI-first | ❌ no provider menu | ⚠ Kimi / Qwen / DeepSeek |
121
+ | Branchable session lineage | ✅ fork & rewind | ⚠ routines / sessions | ❌ | ❌ | ❌ | ⚠ checkpoints |
122
+ | Multi-agent + MCP + 50+ tools | ✅ all three | ✅ all three | ⚠ tools, no MCP | ✅ all three | ⚠ Composer + MCP | ✅ all three |
123
+
124
+ <sub>Data verified May 2026 against public docs ([Claude Code](https://github.com/anthropics/claude-code) · [Aider](https://aider.chat/docs/llms.html) · [Codex CLI](https://github.com/openai/codex) · [Cursor](https://cursor.com) · [Cline](https://github.com/cline/cline)). ⚠ = partial / requires extra setup / not first-class. Corrections welcome via PR.</sub>
125
+
126
+ ## Detailed Setup
127
+
128
+ > The `npm i -g @kodax-ai/kodax` one-liner above is the fastest path. This section is for building from source, configuring custom providers, or using KodaX as a library.
129
+
130
+ ### 1. Build the CLI from source
131
+
132
+ ```bash
133
+ git clone https://github.com/icetomoyo/KodaX.git
134
+ cd KodaX
135
+ npm install
136
+ npm run build
137
+ npm link
138
+ ```
139
+
140
+ ### 2. Configure a provider
141
+
142
+ KodaX reads API keys from environment variables. For built-in providers, the fastest path is:
143
+
144
+ ```bash
145
+ # macOS / Linux
146
+ export ZHIPU_API_KEY=your_api_key
147
+
148
+ # PowerShell
149
+ $env:ZHIPU_API_KEY="your_api_key"
150
+ ```
151
+
152
+ For CLI defaults, create `~/.kodax/config.json`:
153
+
154
+ ```json
155
+ {
156
+ "provider": "zhipu-coding",
157
+ "effort": "auto"
158
+ }
159
+ ```
160
+
161
+ If you need a custom base URL or an OpenAI/Anthropic-compatible endpoint, define a custom provider in the same config file:
162
+
163
+ ```json
164
+ {
165
+ "provider": "my-openai-compatible",
166
+ "customProviders": [
167
+ {
168
+ "name": "my-openai-compatible",
169
+ "protocol": "openai",
170
+ "baseUrl": "https://example.com/v1",
171
+ "apiKeyEnv": "MY_LLM_API_KEY",
172
+ "model": "my-model",
173
+ "userAgentMode": "compat",
174
+ "reasoning": {
175
+ "efforts": ["off", "low", "medium", "high", "max"],
176
+ "default": "high"
177
+ }
178
+ }
179
+ ]
180
+ }
181
+ ```
182
+
183
+ `userAgentMode` defaults to `"compat"`, which sends `KodaX` instead of the official SDK User-Agent. Switch it to `"sdk"` only when your gateway expects the upstream SDK header.
184
+ For custom reasoning models, `reasoning: { efforts, default }` is the preferred v0.7.57 shape; use `"reasoning": "none"` for models without thinking capability. SDK hosts should render effort pickers from `reasoningProfile.supportedEfforts` / `defaultEffort` rather than assuming a fixed five-option ladder.
185
+
186
+ #### OpenAI-compatible reasoning providers
187
+
188
+ Some OpenAI-compatible reasoning models require KodaX to replay the previous assistant turn's `reasoning_content` on later requests. DeepSeek V4 thinking mode is the known load-bearing case. Built-in DeepSeek already opts in; custom providers must say so explicitly:
189
+
190
+ ```json
191
+ {
192
+ "customProviders": [
193
+ {
194
+ "name": "my-deepseek-v4",
195
+ "protocol": "openai",
196
+ "baseUrl": "https://example.com/v1",
197
+ "apiKeyEnv": "MY_DEEPSEEK_API_KEY",
198
+ "model": "deepseek-v4-flash",
199
+ "reasoningPreset": "deepseek-v4-openai",
200
+ "replayReasoningContent": true
201
+ }
202
+ ]
203
+ }
204
+ ```
205
+
206
+ Keep `replayReasoningContent` unset or `false` for OpenAI proper and gateways that reject unknown assistant-message fields. If one gateway routes mixed models, prefer per-model overrides:
207
+
208
+ ```json
209
+ {
210
+ "models": [
211
+ { "id": "deepseek-v4-flash", "replayReasoningContent": true },
212
+ { "id": "gpt-5", "replayReasoningContent": false }
213
+ ]
214
+ }
215
+ ```
216
+
217
+ Sidecar verifier judge calls use provider-level forced tool choice when supported. If a compatible endpoint rejects the `tool_choice` parameter, KodaX retries that verifier request once without forced tool choice and still fails open rather than blocking the main Worker.
218
+
219
+ #### Opting a custom provider into image / vision input (FEATURE_134 v0.7.40)
220
+
221
+ If your custom provider's underlying model supports image input (vision), add a `capabilityProfile.multimodalSupport: "image-input"` block so KodaX does not artificially block multimodal requests at the SA-path policy gate. Built-in vision-capable aliases (Anthropic, OpenAI, Anthropic-/OpenAI-compatible aliases such as DeepSeek, Kimi, Qwen, Zhipu, MiniMax, MiMo, Ark, plus Gemini-CLI via the CLI's `@<path>` file-include syntax) already ship with this flag enabled by default; Codex-CLI and custom providers need to opt in when their underlying model supports image input.
222
+
223
+ ```json
224
+ {
225
+ "customProviders": [
226
+ {
227
+ "name": "my-vision-provider",
228
+ "protocol": "openai",
229
+ "baseUrl": "https://example.com/v1",
230
+ "apiKeyEnv": "MY_LLM_API_KEY",
231
+ "model": "my-vision-model",
232
+ "capabilityProfile": {
233
+ "transport": "native-api",
234
+ "conversationSemantics": "full-history",
235
+ "mcpSupport": "none",
236
+ "contextFidelity": "full",
237
+ "toolCallingFidelity": "full",
238
+ "sessionSupport": "full",
239
+ "longRunningSupport": "full",
240
+ "multimodalSupport": "image-input",
241
+ "evidenceSupport": "full"
242
+ }
243
+ }
244
+ ]
245
+ }
246
+ ```
247
+
248
+ The serializer layer (`packages/llm/src/providers/anthropic.ts:770` for Anthropic-compat, `openai.ts:904` for OpenAI-compat) forwards image blocks automatically through base-class inheritance. The flag only gates whether KodaX's policy layer pre-rejects multimodal requests — the model-level vision contract remains your upstream provider's responsibility. If the model is actually text-only, you'll see the real upstream API error instead of a KodaX-side rejection.
249
+
250
+ ### 3. Start in REPL or run a one-shot task
251
+
252
+ ```bash
253
+ # Interactive REPL
254
+ kodax
255
+
256
+ # Then ask naturally inside the REPL
257
+ Read package.json and summarize the architecture
258
+ /mode
259
+ /help
260
+
261
+ # One-shot CLI usage
262
+ kodax "Review this repository and summarize the architecture"
263
+ kodax --session review "Find the riskiest parts of src/"
264
+ kodax --session review "Give me concrete fix suggestions"
265
+ ```
266
+
267
+ ### 4. Use it as a library
268
+
269
+ Library usage still expects API keys from environment variables. If you want custom provider names or base URLs in code, register them explicitly:
270
+
271
+ ```typescript
272
+ import { registerCustomProviders, runKodaX } from '@kodax-ai/kodax';
273
+
274
+ registerCustomProviders([
275
+ {
276
+ name: 'my-openai-compatible',
277
+ protocol: 'openai',
278
+ baseUrl: 'https://example.com/v1',
279
+ apiKeyEnv: 'MY_LLM_API_KEY',
280
+ model: 'my-model',
281
+ userAgentMode: 'compat',
282
+ },
283
+ ]);
284
+
285
+ const result = await runKodaX(
286
+ {
287
+ provider: 'my-openai-compatible',
288
+ effort: 'auto',
289
+ },
290
+ 'Explain this codebase'
291
+ );
292
+ ```
293
+
294
+ > **Embedding KodaX inside another app?** (KodaX Space, IDE extensions, custom CLIs)
295
+ > See [docs/SDK_EMBEDDER_GUIDE.md](docs/SDK_EMBEDDER_GUIDE.md) for the runtime-mutation
296
+ > surface (`startKodaX` + `RunningSession`), MCP popout manager API (`McpManager`),
297
+ > Skill `` !`cmd` `` host hook, and per-app data dir namespacing (`getAppDataDir`).
298
+
299
+ ## Repo Intelligence
300
+
301
+ KodaX ships with built-in repo intelligence (`repo_overview`, `module_context`, `symbol_context`, `process_context`, `impact_estimate`, and related tools) that helps the coding agent understand large codebases without ad-hoc grep/glob exploration.
302
+
303
+ Use `/repo-intel status` in the REPL to inspect the active engine. The former standalone `repointel` host skill has been removed; repo intelligence is built into KodaX and requires no external installation.
304
+
305
+ ```bash
306
+ # Pick a runtime mode (auto | full | light | off)
307
+ kodax --repo-intelligence full --repo-intelligence-trace
308
+ ```
309
+
310
+ ## Architecture
311
+
312
+ KodaX uses a **monorepo architecture** with npm workspaces. Source layout currently has 4 workspace packages; published as a single bundled npm package `@kodax-ai/kodax` with 8 SDK subpath exports (`/agent`, `/llm`, `/coding`, `/media`, `/repl`, `/skills`, `/mcp`, `/session`; ADR-024 + ADR-032 + ADR-038, with ADR-036 consolidation):
313
+
314
+ ```
315
+ KodaX/
316
+ ├── packages/ # 4 workspace packages (FEATURE_194 v0.7.43)
317
+ │ ├── llm/ # @kodax-ai/llm - LLM abstraction (15 built-in provider aliases)
318
+ │ │ └── providers/ # Anthropic, OpenAI, DeepSeek, Kimi, MiMo, MiniMax, Zhipu, Ark, …
319
+ │ │
320
+ │ ├── agent/ # @kodax-ai/agent - Generic Agent framework
321
+ │ │ ├── orchestration/ # Runner, runFanOut, runWithIdleYield, ChildTaskRegistry
322
+ │ │ ├── session-lineage/ # branchable session tree (inline v0.7.43)
323
+ │ │ ├── capabilities/
324
+ │ │ │ ├── mcp/ # MCP integration (inline v0.7.43)
325
+ │ │ │ └── skills/ # Skills standard implementation + builtin (inline v0.7.43)
326
+ │ │ └── tracing/ # tracing / observability (inline v0.7.43)
327
+ │ │
328
+ │ ├── coding/ # @kodax-ai/coding - Coding Agent (tools + prompts)
329
+ │ │ ├── tools/ # 50+ tools: read, write, edit, bash, glob, grep, undo,
330
+ │ │ │ # dispatch_child_task, send_message, task_stop,
331
+ │ │ │ # ask_user_question, repo-intelligence, …
332
+ │ │ └── repo-intelligence/ # incl. protocol.ts (inline v0.7.43)
333
+ │ │
334
+ │ └── repl/ # @kodax-ai/repl - Interactive terminal UI (Ink TUI)
335
+
336
+ ├── src/ # CLI entry + SDK subpath entries
337
+ │ ├── kodax_cli.ts # Main CLI entry point (bin: `kodax`)
338
+ │ └── sdk-*.ts # SDK subpath re-exports → @kodax-ai/kodax/{agent,llm,coding,media,repl,skills,mcp,session}
339
+
340
+ └── package.json # Root workspace config; release.mjs rewrites name + injects subpath exports
341
+ ```
342
+
343
+ ### Package Dependencies
344
+
345
+ ```
346
+ ┌──────────────────┐
347
+ │ kodax (root) │
348
+ │ CLI Entry │
349
+ └────────┬─────────┘
350
+
351
+ ┌──────────────┴──────────────┐
352
+ │ │
353
+ ▼ ▼
354
+ ┌──────────────┐ ┌────────────────┐
355
+ │@kodax-ai/repl│ │@kodax-ai/coding│
356
+ │ UI Layer │ │ Tools+Prompts │
357
+ └──────┬───────┘ └──────┬─────────┘
358
+ │ │
359
+ │ ┌──────────────┴──────────────┐
360
+ │ │ │
361
+ ▼ ▼ ▼
362
+ ┌──────────────┐ ┌──────────────────────────┐ ┌──────────────┐
363
+ │@kodax-ai/ │ │@kodax-ai/agent │ │@kodax-ai/llm │
364
+ │coding (via │ │Runner + fan-out + │ │LLM Abstract │
365
+ │above) │ │idle-yield + session- │ │(15 aliases) │
366
+ │ │ │lineage + skills + mcp + │ │ │
367
+ │ │ │tracing (FEATURE_194) │ │ │
368
+ └──────────────┘ └──────────────────────────┘ └──────────────┘
369
+ ```
370
+
371
+ ### Package Overview
372
+
373
+ Source-side workspace package names (`@kodax-ai/*`). npm consumers install the single bundled `@kodax-ai/kodax` package and import from SDK subpaths — see [Source-side vs npm-published surface](#source-side-vs-npm-published-surface) and [SDK Usage](#sdk-usage) below.
374
+
375
+ | Workspace package | Purpose | Key Dependencies |
376
+ |---------|---------|------------------|
377
+ | `@kodax-ai/llm` | LLM abstraction (15 built-in provider aliases + custom registration) | @anthropic-ai/sdk, openai |
378
+ | `@kodax-ai/agent` | Generic Agent framework — Runner, fan-out, idle-yield, media/input artifacts, session-lineage, capabilities (mcp + skills), tracing (ADR-036 v0.7.43 consolidation; subpaths: `/media`, `/session-lineage`, `/capabilities/mcp`, `/capabilities/skills`, `/tracing`) | @kodax-ai/llm, js-tiktoken, fflate, jimp, yaml |
379
+ | `@kodax-ai/coding` | Coding Agent — 50+ tools (incl. `dispatch_child_task` / `send_message` / `task_stop`) + role prompts + auto-continue + repo-intelligence protocol | @kodax-ai/llm, @kodax-ai/agent |
380
+ | `@kodax-ai/repl` | Complete interactive terminal UI (Ink/React, permission modes, commands, streaming) | @kodax-ai/coding, ink, react |
381
+
382
+ ### Source-side vs npm-published surface
383
+
384
+ KodaX has two layers that consumers should understand separately:
385
+
386
+ - **Source-side**: 4 workspace packages above (what developers see when reading the repo).
387
+ - **npm-published**: a single bundled package `@kodax-ai/kodax` with 8 SDK subpaths (what SDK consumers `import` from). The subpaths are split into two roles:
388
+ - **Full-package subpaths** (`/agent`, `/llm`, `/coding`, `/repl`) — each one maps 1:1 to a source workspace and exposes its complete public API.
389
+ - **Narrow-subset subpaths** (`/media`, `/skills`, `/mcp`, `/session`) — each one exposes only a focused capability slice carved out of `/agent` or `/repl`. This lets consumers who only need (say) the Skills system import a much smaller surface without pulling in the full agent framework.
390
+
391
+ | Source package | npm subpath | Type | What you get | Example consumer |
392
+ |---|---|---|---|---|
393
+ | `packages/llm` | `@kodax-ai/kodax/llm` | Full package | 15-alias LLM abstraction (77 exports) | Standalone LLM clients |
394
+ | `packages/agent` | `@kodax-ai/kodax/agent` | Full package | Runner / fan-out / session-lineage / capabilities / tracing (202 exports) | Custom agent frameworks |
395
+ | `packages/agent` | `@kodax-ai/kodax/skills` | **Narrow subset** | Skills system only — `SkillRegistry` / `loadFullSkill` / `expandSkillForLLM` / ... (26 exports = pre-v0.7.43 `@kodax-ai/skills` complete API) | Skill loaders, IDE plugins |
396
+ | `packages/agent` | `@kodax-ai/kodax/mcp` | **Narrow subset** | MCP only — `McpCapabilityProvider` / `createMcpTransport` / `searchMcpCatalog` / ... (11 exports = pre-v0.7.43 `@kodax-ai/mcp` complete API) | MCP server hosts |
397
+ | `packages/coding` | `@kodax-ai/kodax/coding` | Full package | Coding agent + 50+ tools + repo-intelligence (342 exports) | Build a Claude Code-shape product |
398
+ | `packages/repl` | `@kodax-ai/kodax/repl` | Full package | Ink TUI + permission modes + commands (193 exports) | Terminal-UI consumers |
399
+ | `packages/repl` | `@kodax-ai/kodax/session` | **Narrow subset** | Session management only — `listSessions` / `loadFullTranscript` / `appendClientNotice` / `forkSession` / `watchSessions` / ... | IDE plugins and desktop hosts reading session history |
400
+
401
+ **Rule of thumb**: if you need Runner / Agent / fan-out, import from `/agent`. If you only need skills or mcp APIs, import from `/skills` or `/mcp` to get a smaller bundle. The narrow subsets are subsets of the full packages — they do **not** expose extra symbols.
402
+
403
+ **Dynamic Workflows (FEATURE_217, v0.7.49)**: the domain-neutral workflow runtime is part of `/agent` — `import { createWorkflowRuntime, runWorkflow, WorkflowAbortError, WorkflowLimitError } from '@kodax-ai/kodax/agent'`. The coding-side integration (agent backend + built-in workflows + saved-workflow discovery/generation: `createCodingWorkflowBackend`, `runWorkflowFromOptions`, `parallelInvestigation`, `discoverSavedWorkflows`, `generateWorkflowFromOptions`, …) is part of `/coding`. FEATURE_217 is the v0.7.49 home for the full Dynamic Workflow product loop: `/workflow create <request>` generates restricted scripts, `/workflow save <runId> <name>` stores `.workflow.json` rerunnable workflows, generated/saved scripts coordinate agents through `WorkflowApi`, run lifecycle state stays observable, opt-in `isolation:"worktree"` routes selected children to parent-managed worktrees, and all file/shell effects still pass through agent tools and the existing permission gates. There is **no** separate `@kodax-ai/kodax/agent/workflow` root-package subpath; source-package consumers of `@kodax-ai/agent` can still use that package's `./workflow` subpath.
404
+
405
+ **Workflow Process Surface (FEATURE_229, v0.7.50)**: workflow progress is now a reusable Agent-layer process contract rather than private REPL text. SDK hosts can subscribe to `WorkflowProcessEvent`/poll `WorkflowProcessSnapshot`, use `createWorkflowRunManager` and `createWorkflowLifecycleController` for stop/pause/resume/result/artifact/delete/prune/identity/preflight controls, and receive ANSI-free provenance fields (`source`, `sourceRunId`, `sourceWorkflowName`, `savedWorkflowName`, `revisionOf`) plus `resultSummary`. `/coding` owns the coding workflow backend and run graph, `/repl` renders the same snapshots, and the terminal UI is not the hidden source of truth. `KodaXEvents` callbacks also take an optional metadata arg (`KodaXToolEventMeta` / `KodaXActivityEventMeta` / `KodaXWorkflowEventMeta`) so a host can attribute every child-agent tool/thinking/progress event to its workflow run and child id without a second event protocol, and generated/saved workflow scripts pass `validateRestrictedWorkflowSource` (compile + source-policy check) plus a generator repair/smoke loop before they run. See [docs/ADR.md ADR-040](docs/ADR.md) for the layering rationale.
406
+
407
+ **Host Reads Persisted History (FEATURE_230 + FEATURE_234, v0.7.51)**: additive closures for hosts that read persisted state. **Durable tool transcript replay** — a resumed session now replays the tool cards the assistant used instead of degrading to text-only. `messages` / `lineage` stay canonical; `SessionData.uiHistory` becomes a bounded, sanitized, terminal-only replay cache. The SDK transcript contract is explicit: `loadSession()` = active model context, `loadFullTranscript()` = append-order host scrollback with typed entries (`message` / `compaction` / `branch_summary` / `client_notice` / `task_result`) plus clone provenance (`logicalId` / `sourceEntryId`), `uiHistory` = optional replay cache, and tool cards can always be reconstructed from canonical messages. Hosts can persist local slash output with `appendClientNotice()` without entering model context, and workflow/child completions expose structured `taskResults[]` instead of requiring `<task-completed>` parsing. **Workflow run host attribution** — `WorkflowProcessTrackerOptions` / `WorkflowProcessSnapshot` gain a host-owned opaque `hostMetadata?: Record<string, string>` that the SDK stores, persists to `run.json`, and echoes back (including after a restart) without interpreting it, so a host can map a run to the session/surface that launched it with zero side table. Unstamped/legacy runs honestly echo `hostMetadata === undefined`. See [docs/features/v0.7.51.md](docs/features/v0.7.51.md).
408
+
409
+ **Inline Workflow Authoring (FEATURE_246, v0.7.58)**: in AMA/AMAW the Worker can now author and run a workflow inline via a model-callable `run_workflow` tool — it scouts the codebase with its own tools first, then bakes concrete findings into each child prompt, and runs the script through the **unchanged** sandbox + static-validation + postcondition-verification pipeline. This replaces the context-blind `sideQuery` generator as the primary interactive path (the generator survives only as a fallback for the explicit `/workflow create` command and non-interactive / CI hosts that have no investigating Worker). It adds structured child output (`outputSchema`), the no-barrier `wf.pipeline` staged primitive, same-session resume (`resumeFromRunId`), nested `wf.workflow(...)`, and a `/workflow create` redirect to Worker-authored scouting; `run_workflow` is async / idle-yield so the turn is not blocked. The neutral run-lifecycle manager (`createWorkflowRunManager` / `getDefaultWorkflowRunManager`) now lives in `@kodax-ai/kodax/agent` for non-coding SDK hosts. See [docs/features/v0.7.58.md](docs/features/v0.7.58.md) and [docs/ADR.md](docs/ADR.md) ADR-044/046/047/048/049.
410
+
411
+ **Workflow Activation Tiers (FEATURE_248 + FEATURE_249, v0.7.59)**: the three agent modes now have a coherent workflow posture. **AMAW** carries a mode-level `ORCHESTRATION DEFAULT` standing directive (mirroring the reference "ultracode" posture): substantive work — a multi-file investigation, a design decision, anything costly to get wrong — defaults to orchestrating multiple cross-checking agents, with a PLAN-TIME COMMITMENT flow-fix that front-loads the orchestrate-vs-solo call to turn 0. **AMA** hosts the same `run_workflow` tool but with no standing directive — it activates a workflow when you ask for orchestration in natural language, never on complexity alone. **SA** stays solo. The directive is leak-closed via `amawOrchestrationAvailable`, so AMA and SA prompts stay byte-identical. See [docs/features/v0.7.59.md](docs/features/v0.7.59.md).
412
+
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
+
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
+
417
+ ---
418
+
419
+ ## Features
420
+
421
+ - **Modular Architecture** - Use as CLI, as a library, or as a Node-free single binary
422
+ - **15 Built-in Provider Aliases** - Anthropic, OpenAI, DeepSeek, Kimi, Kimi Code, Qwen, Zhipu, Zhipu Coding, Zai Coding, MiniMax Coding, MiMo Coding, MiMo, Ark Coding, Gemini CLI, Codex CLI - plus user-defined OpenAI/Anthropic-compatible providers
423
+ - **Dynamic Workflows + SDK Process Surface** - Generate/reuse capability-routed workflows, observe live progress through `WorkflowProcessSnapshot`, and control workflow lifecycle from SDK hosts without parsing REPL output
424
+ - **V2 Worker single-loop + Sidecar Verifier (default)** - Single-agent main loop with an out-of-band Sidecar Verifier as Stop-hook (claudecode-shape; FEATURE_184 v0.7.42, ADR-030). Verifier returns accept/revise/blocked verdict on Worker text-only termination. The pre-v0.7.43 V1 chain is retired, `emit_handoff` is deleted, accept-verdict UI silently passes through, and content-aware gating skips trivial-chat sidecar calls. Async child steering uses `dispatch_child_task` + `send_message` + `task_stop` with idle-yield wait; specialist routing uses `subagent_type`.
425
+ - **Reasoning Effort** - Effort-first control (`off/auto/low/medium/high` plus model-supported extras) across providers
426
+ - **Streaming Output** - Real-time response display
427
+ - **Session Management** - JSONL format with branchable session lineage tree
428
+ - **Skills System** - Natural language triggering, extensible, role-projected in AMA
429
+ - **Repo Intelligence** - Built-in full/light repository intelligence with native KodaX auto-injection lane
430
+ - **Rich Tool Surface** - 50+ built-in tools across file ops, shell, search, repo intelligence, MCP capabilities, git worktree, and agent control
431
+ - **Permission Control** - 3 permission modes with pattern-based control
432
+ - **Standalone Binary** - `bun --compile` releases for Win/macOS/Linux x64+arm64, no Node.js required on target machines
433
+ - **Cross-Platform** - Windows/macOS/Linux
434
+ - **TypeScript Native** - Full type safety and IDE support
435
+
436
+ ---
437
+
438
+ ## Installation
439
+
440
+ ### As CLI Tool
441
+
442
+ ```bash
443
+ # Clone repository
444
+ git clone https://github.com/icetomoyo/KodaX.git
445
+ cd KodaX
446
+
447
+ # Install dependencies (includes workspace packages)
448
+ npm install
449
+
450
+ # Build the monorepo
451
+ npm run build
452
+
453
+ # Link globally (development mode)
454
+ npm link
455
+
456
+ # Now you can use 'kodax' anywhere
457
+ kodax "your task"
458
+ ```
459
+
460
+ ### As Standalone Binary (no Node required on target)
461
+
462
+ KodaX can be packaged into a single executable + a small `builtin/` sidecar directory using `bun --compile`. The target machine does **not** need Node.js or any other runtime.
463
+
464
+ Supported targets: `win-x64`, `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`. Win7 / pre-glibc-2.27 distros / LoongArch are not supported.
465
+
466
+ **Build locally**:
467
+
468
+ ```bash
469
+ # Install Bun once on your build machine
470
+ npm i -g bun # or scoop/brew/curl install — see docs/release.md
471
+
472
+ npm run build:binary # Current host platform (fastest)
473
+ npm run build:binary:all # All five targets in sequence
474
+ node scripts/build-binary.mjs --target=linux-arm64 # Specific target
475
+ ```
476
+
477
+ Output lives under `dist/binary/<target>/`:
478
+
479
+ ```
480
+ dist/binary/linux-x64/
481
+ ├── kodax # ~60 MB Bun-compiled executable
482
+ └── builtin/ # Sidecar built-in skills
483
+ ```
484
+
485
+ Smoke-test: `dist/binary/<host>/kodax --version`.
486
+
487
+ **Automated release**: pushing a `v*` git tag triggers `.github/workflows/release.yml`, which builds all five targets on native runners, runs smoke tests, and publishes a GitHub Release with archives + SHA256SUMS. Use the `workflow_dispatch` button in the Actions UI to test the pipeline without tagging.
488
+
489
+ See [docs/release.md](docs/release.md) for full details on build flags, archive layout, troubleshooting, and the build-time `KODAX_BUNDLED` / `KODAX_VERSION` defines.
490
+
491
+ ### As Library
492
+
493
+ ```bash
494
+ npm install @kodax-ai/kodax
495
+ ```
496
+
497
+ ```typescript
498
+ import { runKodaX } from '@kodax-ai/kodax';
499
+
500
+ process.env.ZHIPU_API_KEY = process.env.ZHIPU_API_KEY ?? 'your_api_key';
501
+
502
+ const result = await runKodaX({
503
+ provider: 'zhipu-coding',
504
+ effort: 'auto',
505
+ events: {
506
+ onTextDelta: (text) => process.stdout.write(text),
507
+ onComplete: () => console.log('\nDone!'),
508
+ },
509
+ }, 'your task');
510
+
511
+ console.log(result.lastText);
512
+ ```
513
+
514
+ #### SDK Subpath Imports (v0.7.39+)
515
+
516
+ For smaller surface and tree-shake-friendly imports, the SDK is also exposed via subpath exports — pick only the package(s) you need:
517
+
518
+ ```typescript
519
+ import { Runner } from '@kodax-ai/kodax/agent'; // agent runtime
520
+ import { getProvider } from '@kodax-ai/kodax/llm'; // LLM abstraction (15 aliases)
521
+ import { runKodaX } from '@kodax-ai/kodax/coding'; // coding tools + prompts
522
+ import { SkillRegistry } from '@kodax-ai/kodax/skills'; // zero-dep skill loader
523
+ import { loadConfig } from '@kodax-ai/kodax/repl'; // REPL config / session helpers
524
+ import { createMcpManager } from '@kodax-ai/kodax/mcp'; // MCP popout manager (v0.7.42)
525
+ import { listSessions } from '@kodax-ai/kodax/session'; // session history helpers
526
+ ```
527
+
528
+ All 9 SDK entries (root + 8 subpaths) share internal code via ESM chunk splitting — importing from `/agent` does not pull in `/repl`'s Ink + React surface.
529
+
530
+ > **ESM-only.** The SDK is published as ES Modules. In a CommonJS context (Electron main process, legacy Webpack CJS bundles, `require()`-based code) you must use `await import(...)` instead of `require()`. See [docs/SDK_EMBEDDER_GUIDE.md §5](docs/SDK_EMBEDDER_GUIDE.md#5-consuming-from-a-commonjs-context-electron-main-cjs-bundles) for the canonical recipe + the technical reason most subpaths cannot ship a dual ESM/CJS build.
531
+
532
+ For CLI users, provider defaults live in `~/.kodax/config.json`. For library users, API keys are still read from environment variables; if you need custom base URLs or provider aliases, use `registerCustomProviders()` as shown above.
533
+
534
+ ---
535
+
536
+ ## Usage
537
+
538
+ ### REPL Quickstart
539
+
540
+ Running `kodax` with no prompt starts the interactive REPL.
541
+
542
+ ```bash
543
+ kodax
544
+ ```
545
+
546
+ Inside the REPL you can type normal requests or slash commands:
547
+
548
+ ```text
549
+ Read package.json and summarize the architecture
550
+ /model
551
+ /mode
552
+ /help
553
+ ```
554
+
555
+ ### CLI Quickstart
556
+
557
+ ```bash
558
+ # Set API key
559
+ export ZHIPU_API_KEY=your_api_key
560
+
561
+ # Basic usage
562
+ kodax "Help me create a TypeScript project"
563
+
564
+ # Choose a provider explicitly
565
+ kodax --provider openai --model gpt-5.4 "Create a REST API"
566
+
567
+ # Use higher reasoning effort
568
+ kodax --effort high "Review this architecture"
569
+ ```
570
+
571
+ ### Session Workflows
572
+
573
+ Use a session when you want memory across turns. Without a session, each CLI call is independent.
574
+
575
+ ```bash
576
+ # No memory: two separate calls
577
+ kodax "Read src/auth.ts"
578
+ kodax "Summarize it"
579
+
580
+ # With memory: same session
581
+ kodax --session my-project "Read package.json"
582
+ kodax --session my-project "Summarize it"
583
+ kodax --session my-project "How should I fix the first issue?"
584
+
585
+ # Session management
586
+ kodax --session list
587
+ kodax --session resume "continue"
588
+ ```
589
+
590
+ ### Session Patterns
591
+
592
+ ```bash
593
+ # No memory: two independent calls
594
+ kodax "Read src/auth.ts" # Agent reads and responds
595
+ kodax "Summarize it" # Agent doesn't know what to summarize
596
+
597
+ # With memory: same session
598
+ kodax --session auth-review "Read src/auth.ts"
599
+ kodax --session auth-review "Summarize it" # Agent knows to summarize auth.ts
600
+ kodax --session auth-review "How to fix first issue" # Agent has context
601
+ ```
602
+
603
+ ### Workflow Examples
604
+
605
+ ```bash
606
+ # Code review (multi-turn conversation)
607
+ kodax --session review "Review src/ directory"
608
+ kodax --session review "Focus on security issues"
609
+ kodax --session review "Give me fix suggestions"
610
+
611
+ # Project development (continuous session)
612
+ kodax --session todo-app "Create a Todo application"
613
+ kodax --session todo-app "Add delete functionality"
614
+ kodax --session todo-app "Write tests"
615
+ ```
616
+
617
+ ### CLI Reference
618
+
619
+ ```text
620
+ kodax Start the interactive REPL
621
+ -h, --help [topic] Show help or topic help
622
+ -p, --print <text> Run a single task and exit
623
+ -c, --continue Continue the most recent conversation in this directory
624
+ -r, --resume [id] Resume a session by ID, or the latest session
625
+ -m, --provider Provider to use
626
+ --model <name> Override the model
627
+ --reasoning <mode> off | auto | quick | balanced | deep
628
+ -t, --thinking Compatibility alias for --reasoning auto
629
+ -s, --session <op> Session ID or legacy session operation
630
+ -j, --parallel Enable parallel tool execution
631
+ --max-iter <n> Max iterations
632
+ ```
633
+
634
+ ### Permission Control
635
+
636
+ KodaX provides 3 permission modes for fine-grained control:
637
+
638
+ | Mode | Description | Tools Need Confirmation |
639
+ |------|-------------|------------------------|
640
+ | `plan` | Read-only planning mode | All modification tools blocked |
641
+ | `accept-edits` | Auto-accept file edits | bash only |
642
+ | `auto-in-project` | Full auto within project | None (project-scoped) |
643
+
644
+ ```bash
645
+ # In REPL, use /mode command
646
+ /mode plan # Switch to plan mode (read-only)
647
+ /mode accept-edits # Switch to accept-edits mode
648
+ /mode auto-in-project # Switch to auto-in-project mode
649
+ /auto # Alias for auto-in-project
650
+
651
+ # Check current mode
652
+ /mode
653
+ ```
654
+
655
+ **Features:**
656
+ - In `accept-edits` mode, choosing "always" can persist safe Bash allow-patterns
657
+ - Plan mode includes system prompt context for LLM awareness
658
+ - Permanent protection zones: `.kodax/`, `~/.kodax/`, paths outside project
659
+ - Pattern-based permission: Allow specific Bash commands (e.g., `Bash(npm install)`)
660
+ - Unified diff display for write/edit operations
661
+
662
+ ### CLI Help Topics
663
+
664
+ Get detailed help for specific topics:
665
+
666
+ ```bash
667
+ # Basic help
668
+ kodax -h
669
+ kodax --help
670
+
671
+ # Detailed topic help
672
+ kodax -h sessions # Session management details
673
+ kodax -h init # Long-running project initialization
674
+ kodax -h project # Project mode / harness workflow
675
+ kodax -h auto # Auto-continue mode
676
+ kodax -h provider # LLM provider configuration
677
+ kodax -h thinking # Thinking/reasoning effort and compatibility modes
678
+ kodax -h team # Multi-agent parallel execution
679
+ kodax -h print # Print configuration
680
+ ```
681
+
682
+ ### Environment Variables
683
+
684
+ KodaX recognizes a number of environment variables for tuning runtime behavior. The most commonly used ones are listed below; for the full list, search the repo for `process.env.KODAX_`.
685
+
686
+ #### `KODAX_MAX_OUTPUT_TOKENS`
687
+
688
+ Overrides the per-turn `max_tokens` value sent to **every** provider (Anthropic, OpenAI, Zhipu, Kimi, MiniMax, Qwen, DeepSeek, MiMo, Gemini, Codex, …). Set to a positive integer; unset or non-numeric values are ignored. This is an **explicit user intent**: when set, it wins over the provider's model descriptor cap, over the provider config default, and over the global `KODAX_MAX_TOKENS` fallback. RST defense is handled at the provider config layer (`streamMaxDurationMs` watchdog + non-streaming fallback in `packages/llm/src/providers/registry.ts`), so this variable is purely an output-budget knob.
689
+
690
+ ```bash
691
+ # Allow up to 48K output tokens per turn (use a higher cap when generating long files)
692
+ export KODAX_MAX_OUTPUT_TOKENS=48000
693
+ kodax "generate the full implementation"
694
+
695
+ # Unset to restore default behavior
696
+ unset KODAX_MAX_OUTPUT_TOKENS
697
+ ```
698
+
699
+ Precedence used by every provider's `getEffectiveMaxOutputTokens()` (see `packages/llm/src/providers/base.ts`):
700
+
701
+ 1. One-shot per-request override (agent-loop escalation / context-overflow recovery internal)
702
+ 2. **`KODAX_MAX_OUTPUT_TOKENS`** (this variable, explicit user intent)
703
+ 3. Active model descriptor's `maxOutputTokens` (FEATURE_098 per-model cap)
704
+ 4. Provider config default
705
+ 5. Global `KODAX_MAX_TOKENS` fallback
706
+
707
+ Related variables: `KODAX_MAX_TOKENS` (global fallback when no provider/model cap applies), `KODAX_ESCALATED_MAX_OUTPUT_TOKENS` (escalation budget used by the agent loop when a turn returns `stop_reason: max_tokens`).
708
+
709
+ > **Retired in v0.7.42**: `KODAX_RST_PRONE_PROVIDERS` and `KODAX_WRITE_TURN_MAX_TOKENS` (the v0.7.28 P2b write-turn cap mechanism) are no longer recognized. The 2026-04 bench measured RST as time-based (zhipu-coding 308s server kill window), not payload-size-based, so the cap was retired in favor of the per-provider `streamMaxDurationMs` watchdog + non-streaming fallback chain (configured in `registry.ts`). Existing env exports become silent no-ops; remove them from shell profiles when convenient.
710
+
711
+ #### Sidecar verifier diagnostics
712
+
713
+ Use these when diagnosing Worker text-only completion stalls or custom provider verifier behavior:
714
+
715
+ ```bash
716
+ export KODAX_VERIFIER_LOG=1
717
+ export KODAX_VERIFIER_PROVIDER=anthropic
718
+ export KODAX_VERIFIER_MODEL=claude-haiku-4-5-20251001
719
+ ```
720
+
721
+ - `KODAX_VERIFIER_LOG=1` shows verifier gate/elapsed/trace information and is equivalent to `"verifierLog": true` in `~/.kodax/config.json`.
722
+ - `KODAX_VERIFIER_PROVIDER` + `KODAX_VERIFIER_MODEL` route the verifier to a separate provider/model instead of inheriting the main Worker model. Set both together.
723
+ - `KODAX_VERIFIER_ALWAYS=1` forces the verifier to fire on every text-only completion for debugging/regression sweeps.
724
+
725
+ SDK/headless hosts can observe actionable Sidecar Verifier messages via
726
+ `KodaXEvents.onSidecarMessage`; JSONL output emits the same payload as
727
+ `sidecar.message`. Only `revise` and `blocked` verdicts are surfaced; `accept`
728
+ stays silent.
729
+
730
+ ## Advanced Library Usage
731
+
732
+ #### Simple Mode (runKodaX)
733
+
734
+ ```typescript
735
+ import { runKodaX, KodaXEvents } from '@kodax-ai/kodax';
736
+
737
+ const events: KodaXEvents = {
738
+ onTextDelta: (text) => process.stdout.write(text),
739
+ onThinkingDelta: (text) => console.log(`Thinking delta: ${text.length} chars`),
740
+ onToolResult: (result) => console.log(`Tool ${result.name}: ${result.content.slice(0, 100)}`),
741
+ onSidecarMessage: (event) => console.log(`[sidecar:${event.verdict}] ${event.content}`),
742
+ onComplete: () => console.log('\nDone!'),
743
+ onError: (e) => console.error(e.message),
744
+ };
745
+
746
+ const result = await runKodaX({
747
+ provider: 'zhipu-coding',
748
+ effort: 'auto',
749
+ events,
750
+ }, 'What is 1+1?');
751
+
752
+ console.log(result.lastText);
753
+ ```
754
+
755
+ #### Continuous Session (KodaXClient)
756
+
757
+ ```typescript
758
+ import { KodaXClient } from '@kodax-ai/kodax';
759
+
760
+ const client = new KodaXClient({
761
+ provider: 'zhipu-coding',
762
+ effort: 'auto',
763
+ events: {
764
+ onTextDelta: (t) => process.stdout.write(t),
765
+ },
766
+ });
767
+
768
+ // First message
769
+ await client.send('Read package.json');
770
+
771
+ // Continue same session
772
+ await client.send('Summarize it');
773
+
774
+ console.log(client.getSessionId());
775
+ ```
776
+
777
+ #### Custom Session Storage
778
+
779
+ ```typescript
780
+ import { runKodaX, KodaXSessionStorage, KodaXMessage } from '@kodax-ai/kodax';
781
+
782
+ class MyDatabaseStorage implements KodaXSessionStorage {
783
+ async save(id: string, data: { messages: KodaXMessage[]; title: string; gitRoot: string }) {
784
+ // Save to your database
785
+ }
786
+ async load(id: string) {
787
+ // Load from your database
788
+ return null;
789
+ }
790
+ }
791
+
792
+ await runKodaX({
793
+ provider: 'zhipu-coding',
794
+ session: {
795
+ id: 'my-session-123',
796
+ storage: new MyDatabaseStorage(),
797
+ },
798
+ events: { ... },
799
+ }, 'task');
800
+ ```
801
+
802
+ ### Library Modes Comparison
803
+
804
+ | Feature | runKodaX | KodaXClient |
805
+ |---------|----------|-------------|
806
+ | **Message Memory** | ❌ No | ✅ Yes |
807
+ | **Call Style** | Function | Class instance |
808
+ | **Context** | Independent each time | Accumulates |
809
+ | **Use Case** | Single tasks, batch processing | Interactive dialogue, multi-step tasks |
810
+
811
+ ---
812
+
813
+ ## SDK Usage
814
+
815
+ KodaX ships as a single npm package `@kodax-ai/kodax` with 8 SDK subpath exports (ADR-024 v0.7.39 + ADR-032 v0.7.42 + ADR-038 v0.7.49 + v0.7.56 `/media`). Each subpath is tree-shake-friendly so consumers pull only what they need:
816
+
817
+ ```bash
818
+ npm install @kodax-ai/kodax
819
+ ```
820
+
821
+ ```typescript
822
+ import { runKodaX } from '@kodax-ai/kodax'; // root: CLI helpers + runKodaX
823
+ import { Runner, runFanOut } from '@kodax-ai/kodax/agent'; // generic Agent framework
824
+ import { getProvider } from '@kodax-ai/kodax/llm'; // 15-alias LLM abstraction
825
+ import { KODAX_TOOLS } from '@kodax-ai/kodax/coding'; // tools + prompts + agent loop
826
+ import { createImageArtifactFromPath } from '@kodax-ai/kodax/media'; // input artifact helpers
827
+ import { runInkInteractiveMode } from '@kodax-ai/kodax/repl'; // Ink TUI entrypoint
828
+ import { SkillRegistry } from '@kodax-ai/kodax/skills'; // zero-dep skill loader
829
+ import { createMcpManager } from '@kodax-ai/kodax/mcp'; // MCP popout manager (v0.7.42)
830
+ import { listSessions } from '@kodax-ai/kodax/session'; // session history helpers
831
+ ```
832
+
833
+ > The SDK is **ESM-only**. CommonJS consumers (Electron main / Webpack CJS / `require()` callers) must use `await import('@kodax-ai/kodax/...')` — see [docs/SDK_EMBEDDER_GUIDE.md §5](docs/SDK_EMBEDDER_GUIDE.md#5-consuming-from-a-commonjs-context-electron-main-cjs-bundles).
834
+
835
+ ### `@kodax-ai/kodax/llm` — LLM Abstraction
836
+
837
+ 15 built-in provider aliases (Anthropic, OpenAI, DeepSeek, Kimi, Kimi-Code, Qwen, Zhipu, Zhipu-Coding, Zai-Coding, MiniMax-Coding, MiMo, MiMo-Coding, Ark-Coding, Gemini-CLI, Codex-CLI) + custom provider registration.
838
+
839
+ ```typescript
840
+ import { getProvider, KodaXBaseProvider } from '@kodax-ai/kodax/llm';
841
+
842
+ const provider = getProvider('anthropic');
843
+ const stream = await provider.streamCompletion(
844
+ [{ role: 'user', content: 'Hello!' }],
845
+ { onTextDelta: (text) => process.stdout.write(text) }
846
+ );
847
+
848
+ for await (const result of stream) {
849
+ if (result.type === 'text') { /* … */ }
850
+ else if (result.type === 'tool_use') { /* … */ }
851
+ }
852
+ ```
853
+
854
+ **Key Features**: unified provider interface · streaming · reasoning effort (`off/auto/low/medium/high` plus model-supported extras) · per-provider retry + error handling · zero business-logic dependencies.
855
+
856
+ ### `@kodax-ai/kodax/agent` — Agent Framework (standalone-consumable)
857
+
858
+ ADR-021 standalone-consumable: `@kodax-ai/agent` has **zero inbound `@kodax-ai/coding` dependency** — you can wire any tool surface on top of it.
859
+
860
+ ```typescript
861
+ import {
862
+ Runner,
863
+ runFanOut,
864
+ runWithIdleYield,
865
+ registerChildTask,
866
+ type ChildTaskRegistry,
867
+ generateSessionId,
868
+ estimateTokens,
869
+ DefaultSummaryCompaction,
870
+ } from '@kodax-ai/kodax/agent';
871
+
872
+ // Bounded-concurrency fan-out with abort + structured progress events (v0.7.39 FEATURE_120)
873
+ const result = await runFanOut({
874
+ bundles: [{ id: 'a', task: 'audit-foo' }, { id: 'b', task: 'audit-bar' }],
875
+ maxParallel: 4,
876
+ run: async (bundle) => doWork(bundle),
877
+ });
878
+
879
+ // Idle-yield wait — pause when out of useful work, resume when a wake event arrives
880
+ await runWithIdleYield({ runOnce, computeSnapshot, registry, messageQueue, agentId });
881
+
882
+ // Pluggable compaction policy (FEATURE_081)
883
+ const policy = new DefaultSummaryCompaction({ thresholdRatio: 0.8, keepRecent: 10 });
884
+ ```
885
+
886
+ **Key Features**: `Runner` + per-step lifecycle · `runFanOut` (bounded-concurrency + abort + progress events) · `runWithIdleYield` (chat-while-waiting) · `ChildTaskRegistry` / `TaskAbortRegistry` · session-id generation · tiktoken-based token estimation · `CompactionPolicy` interface.
887
+
888
+ ### `@kodax-ai/kodax/skills` — Skills System
889
+
890
+ Zero external dependencies. Markdown-based skill files with natural-language triggers and variable resolution.
891
+
892
+ ```typescript
893
+ import {
894
+ SkillRegistry,
895
+ discoverSkills,
896
+ executeSkill,
897
+ type SkillContext,
898
+ } from '@kodax-ai/kodax/skills';
899
+
900
+ const skills = await discoverSkills(['/path/to/skills']);
901
+ const registry = new SkillRegistry();
902
+ await registry.registerSkills(skills);
903
+
904
+ const result = await executeSkill({
905
+ skillId: 'code-review',
906
+ arguments: { target: 'src/' },
907
+ workingDirectory: process.cwd(),
908
+ });
909
+ ```
910
+
911
+ **Key Features**: zero deps · markdown-based skill files · natural-language triggering · variable resolution · built-in skills included.
912
+
913
+ ### `@kodax-ai/kodax/coding` — Coding Agent
914
+
915
+ Complete coding agent: 50+ tools (`read`/`write`/`edit`/`bash`/`grep`/`glob`/`dispatch_child_task`/`send_message`/`task_stop`/...) + Worker role prompt + Sidecar Verifier (out-of-band Stop-hook) + agent loop + auto-continue + session management.
916
+
917
+ ```typescript
918
+ import { runKodaX, KodaXClient, KODAX_TOOLS } from '@kodax-ai/kodax/coding';
919
+
920
+ // Single-task helper
921
+ const result = await runKodaX({
922
+ provider: 'zhipu-coding',
923
+ effort: 'auto',
924
+ events: { onTextDelta: (text) => process.stdout.write(text) },
925
+ }, 'Read package.json and explain the dependencies');
926
+
927
+ // Continuous session
928
+ const client = new KodaXClient({
929
+ provider: 'anthropic',
930
+ effort: 'auto',
931
+ events: { /* */ },
932
+ });
933
+ await client.send('Create a new file');
934
+ await client.send('Add a function to it'); // Has context from previous message
935
+ ```
936
+
937
+ **Key Features**: 50+ built-in tools (see [Tools](#tools)) · V2 Worker single-loop + Sidecar Verifier (FEATURE_184 v0.7.42 / V1 chain fully retired by FEATURE_193 v0.7.43) · async child steering via `send_message` / `task_stop` (FEATURE_120, v0.7.39) · idle-yield wait mechanic (FEATURE_155, v0.7.38) · specialist routing via `subagent_type` (FEATURE_191, v0.7.43) · auto-continue · session lineage.
938
+
939
+ ### `@kodax-ai/kodax/repl` — Interactive Terminal UI
940
+
941
+ Ink/React-based interactive REPL. Permission modes, command system, themed streaming display.
942
+
943
+ ```typescript
944
+ import { runInkInteractiveMode } from '@kodax-ai/kodax/repl';
945
+
946
+ // Usually used via the `kodax` bin command; can be embedded:
947
+ // - Interactive terminal UI (Ink components)
948
+ // - Permission control (auto/plan/accept-edits modes)
949
+ // - Command system (/help, /mode, /clear, /status, )
950
+ // - Skills integration
951
+ // - Theme support
952
+ await runInkInteractiveMode({ provider: 'zhipu-coding', effort: 'auto' });
953
+ ```
954
+
955
+ **Key Features**: Ink-based React components · 3 permission modes (auto / plan / accept-edits) · built-in commands · real-time streaming display · context-usage indicator.
956
+
957
+ ### Package Dependency Graph (workspace internal)
958
+
959
+ ```
960
+ @kodax-ai/llm (zero business-logic deps)
961
+
962
+ @kodax-ai/agent (depends @kodax-ai/llm; ADR-021 standalone-consumable;
963
+ inlines session-lineage + capabilities/{mcp,skills} +
964
+ tracing per ADR-036 v0.7.43)
965
+
966
+ @kodax-ai/coding (depends llm + agent; inlines repo-intelligence/protocol per ADR-036)
967
+
968
+ @kodax-ai/repl (depends coding + ink + react)
969
+ ```
970
+
971
+ **Subpath Recommendations**:
972
+
973
+ | Use Case | Subpath | Why |
974
+ |----------|---------|-----|
975
+ | Only need LLM abstraction | `@kodax-ai/kodax/llm` | Minimal deps; 15 built-in aliases |
976
+ | Building custom agent | `@kodax-ai/kodax/agent` | Runner + fan-out + idle-yield + session-lineage + capabilities |
977
+ | Coding tasks | `@kodax-ai/kodax/coding` | Complete coding agent + tools |
978
+ | Terminal app | `@kodax-ai/kodax/repl` | Full interactive experience |
979
+
980
+ ---
981
+
982
+ | Provider | Environment Variable | Reasoning Support | Default Model |
983
+ |----------|----------------------|-------------------|---------------|
984
+ | anthropic | `ANTHROPIC_API_KEY` | Native | claude-sonnet-4-6 (`claude-opus-4-6` / `claude-haiku-4-5` via `/model`) |
985
+ | openai | `OPENAI_API_KEY` | Native | gpt-5.3-codex (`gpt-5.4` / `gpt-5.3-codex-spark` via `/model`) |
986
+ | kimi | `KIMI_API_KEY` | Native | kimi-k2.6 (`kimi-k2.7-code` 256K / `k2.5` via `/model`) |
987
+ | kimi-code | `KIMI_CODE_API_KEY` | Native | kimi-for-coding |
988
+ | qwen | `QWEN_API_KEY` | Native | qwen3.5-plus |
989
+ | zhipu | `ZHIPU_API_KEY` | Native | glm-5 (`glm-5.2` 1M ctx / `glm-5.1` / `glm-5-turbo` via `/model`) |
990
+ | zhipu-coding | `ZHIPU_CODING_API_KEY` | Native | glm-5 (`glm-5.2` 1M ctx / `glm-5.1` / `glm-5-turbo` via `/model`) |
991
+ | zai-coding | `ZAI_CODING_API_KEY` | Native | glm-5.2 (Zhipu Coding Plan overseas mirror via `api.z.ai`, Anthropic-compat — same model lineup as `zhipu-coding`, served from outside CN) |
992
+ | minimax-coding | `MINIMAX_CODING_API_KEY` | Native | MiniMax-M2.7 (`MiniMax-M3` Frontier Coding, native multimodal + 1M ctx, plus `MiniMax-M2.7-highspeed` via `/model`) |
993
+ | mimo | `MIMO_API_KEY` | Native | mimo-v2.5-pro (Xiaomi MiMo pay-per-token, Anthropic-compat) |
994
+ | mimo-coding | `MIMO_CODING_API_KEY` | Native | mimo-v2.5-pro (Xiaomi Token Plan, Anthropic-compat) |
995
+ | ark-coding | `ARK_CODING_API_KEY` | Native | glm-5.2 (Volcengine Ark Coding Plan — GLM-5.2 (alias: `glm-latest`) · Kimi K2.7 Code / K2.6 · MiniMax M3 / M2.7 · DeepSeek V4 Pro / V4 Flash · Doubao Seed 2.0 Code / Pro / Lite · Doubao Seed Code) |
996
+ | deepseek | `DEEPSEEK_API_KEY` | Native | deepseek-v4-flash (`deepseek-v4-pro` via `/model`) |
997
+ | gemini-cli | `GEMINI_API_KEY` | Prompt-only / CLI bridge | (via gemini CLI) |
998
+ | codex-cli | `OPENAI_API_KEY` | Prompt-only / CLI bridge | (via codex CLI) |
999
+
1000
+ > **Custom providers**: any OpenAI- or Anthropic-compatible endpoint can be added via `customProviders[]` in `~/.kodax/config.json` (CLI) or `registerCustomProviders()` (library). See the [Quick Start](#2-configure-a-provider) for the configuration shape.
1001
+
1002
+ ### Examples
1003
+
1004
+ ```bash
1005
+ # Use Zhipu Coding
1006
+ kodax --provider zhipu-coding --thinking "Help me optimize this code"
1007
+
1008
+ # Use OpenAI
1009
+ export OPENAI_API_KEY=your_key
1010
+ kodax --provider openai "Create a REST API"
1011
+
1012
+ # Resume last session
1013
+ kodax --session resume
1014
+
1015
+ # List all sessions
1016
+ kodax --session list
1017
+
1018
+ # Parallel tool execution
1019
+ kodax --parallel "Read package.json and tsconfig.json"
1020
+
1021
+ # Adaptive multi-agent (AMA) mode — V2 Worker single-loop with `dispatch_child_task` fan-out
1022
+ kodax --agent-mode ama "Analyze code structure, check test coverage, find bugs"
1023
+ ```
1024
+
1025
+ ---
1026
+
1027
+ ## Tools
1028
+
1029
+ KodaX ships 50+ built-in tools, grouped below. They are registered as a single flat tool surface to the LLM; the categories here are just for navigation.
1030
+
1031
+ ### File operations
1032
+ | Tool | Description |
1033
+ |------|-------------|
1034
+ | `read` | Read file contents (supports offset/limit) |
1035
+ | `write` | Write a new file or fully rewrite an existing one |
1036
+ | `edit` | Exact string replacement (supports `replace_all`) |
1037
+ | `multi_edit` | Atomic batch of independent edits to one file |
1038
+ | `insert_after_anchor` | Insert content after a unique anchor without rewriting the file |
1039
+ | `undo` | Revert the last file modification |
1040
+
1041
+ ### Shell & search
1042
+ | Tool | Description |
1043
+ |------|-------------|
1044
+ | `bash` | Execute a shell command (supports `run_in_background`, output truncation) |
1045
+ | `glob` | Find files by pattern |
1046
+ | `grep` | Regex content search (context lines, multiline, file-type filter, pagination) |
1047
+ | `code_search` | Lower-noise code search (extension-provider aware) |
1048
+ | `semantic_lookup` | Symbol/module/process-aware search backed by repo intelligence |
1049
+ | `web_search` | Discovery-oriented web search with trust + freshness signals |
1050
+ | `web_fetch` | Fetch a specific URL with provenance hints |
1051
+
1052
+ ### Repo Intelligence (working tools)
1053
+ | Tool | Description |
1054
+ |------|-------------|
1055
+ | `repo_overview` | Summarize structure, key areas, entry hints, intelligence snapshot |
1056
+ | `changed_scope` | Which files/areas/categories the current diff touches |
1057
+ | `changed_diff` | Paged diff slice for a single file |
1058
+ | `changed_diff_bundle` | Paged diff slices for multiple files in one call |
1059
+ | `module_context` | Module capsule (deps, entries, symbols, tests, docs) |
1060
+ | `symbol_context` | Definition + probable callers/callees + alternatives |
1061
+ | `process_context` | Approximate static execution capsule for an entry |
1062
+ | `impact_estimate` | Blast radius for a symbol/path/module |
1063
+
1064
+ ### MCP capabilities (when MCP servers are configured)
1065
+ | Tool | Description |
1066
+ |------|-------------|
1067
+ | `mcp_search` / `mcp_describe` / `mcp_call` | Discover and invoke MCP tools through the shared capability runtime |
1068
+ | `mcp_read_resource` / `mcp_get_prompt` | Read MCP resources and prompts |
1069
+
1070
+ ### Git worktree
1071
+ | Tool | Description |
1072
+ |------|-------------|
1073
+ | `worktree_create` | Create a new worktree on an isolated branch for safe agent work |
1074
+ | `worktree_remove` | Remove a worktree (with safety checks) |
1075
+
1076
+ ### Agent control & UX
1077
+ | Tool | Description |
1078
+ |------|-------------|
1079
+ | `dispatch_child_task` | Spawn a sub-agent for an independent investigation/edit task. Optional `model_hint: 'fast' \| 'balanced' \| 'deep'` (advisory; routing no-op until FEATURE_102 v0.7.45). |
1080
+ | `send_message` | Append an instruction to an in-flight child's queue — surfaces as `<coordinator-instruction>` at the child's next turn boundary. Coordinator-only. (FEATURE_120, v0.7.39) |
1081
+ | `task_stop` | Request graceful exit of a specific child. Current tool finishes atomically, then the child sees a `<coordinator-stop-request>` and emits a final summary. Coordinator-only. (FEATURE_120, v0.7.39) |
1082
+ | `ask_user_question` | Single/multi-select or free-text prompt back to the user |
1083
+ | `exit_plan_mode` | Present a finalized plan for approval (REPL only) |
1084
+ | `run_workflow` | Author and run a workflow script inline. Hosted in AMAW (self-activates on complexity via the ORCHESTRATION DEFAULT directive) and AMA (activates on an explicit natural-language request); not in SA. Scouts the codebase first, then bakes findings into child prompts; structured output via `outputSchema`, same-session `resumeFromRunId`, nested `wf.workflow(...)`. Async / idle-yield. (FEATURE_246 v0.7.58; FEATURE_248/249 v0.7.59) |
1085
+ | `emit_managed_protocol` | Internal managed-task protocol side-channel for role payloads (verdict). V2 Worker single-loop + Sidecar Verifier is the default since v0.7.42 (FEATURE_184); V1 chain retired in v0.7.43 (FEATURE_193). |
1086
+
1087
+ ---
1088
+
1089
+ ## Skills System
1090
+
1091
+ KodaX includes a built-in Skills system that can be triggered by natural language:
1092
+
1093
+ ```bash
1094
+ # Natural language triggering (no explicit /skill needed)
1095
+ kodax "帮我审查代码" # Triggers code-review skill
1096
+ kodax "写测试用例" # Triggers tdd skill
1097
+ kodax "提交代码" # Triggers git-workflow skill
1098
+
1099
+ # Explicit skill command
1100
+ kodax /skill:code-review
1101
+ ```
1102
+
1103
+ Built-in skills include:
1104
+ - **code-review** - Code review and quality analysis
1105
+ - **tdd** - Test-driven development workflow
1106
+ - **git-workflow** - Git commit and workflow automation
1107
+
1108
+ Skills are stored in `~/.kodax/skills/` and can be extended with custom skills.
1109
+
1110
+ ---
1111
+
1112
+ ## Commands (CLI)
1113
+
1114
+ Commands are `/xxx` shortcuts in CLI:
1115
+
1116
+ ```bash
1117
+ kodax /review src/auth.ts
1118
+ kodax /test
1119
+ ```
1120
+
1121
+ Commands are stored in `~/.kodax/commands/`:
1122
+ - `.md` files → Prompt commands (content used as prompt)
1123
+ - `.ts/.js` files → Programmable commands
1124
+
1125
+ ---
1126
+
1127
+ ## API Exports
1128
+
1129
+ ```typescript
1130
+ // Main functions
1131
+ export { runKodaX, KodaXClient };
1132
+
1133
+ // Types
1134
+ export type {
1135
+ KodaXEvents, KodaXOptions, KodaXResult,
1136
+ KodaXMessage, KodaXContentBlock,
1137
+ KodaXSessionStorage, KodaXToolDefinition
1138
+ };
1139
+
1140
+ // Tools
1141
+ export { KODAX_TOOLS, KODAX_TOOL_REQUIRED_PARAMS, executeTool };
1142
+
1143
+ // Providers
1144
+ export { getProvider, KODAX_PROVIDERS, KodaXBaseProvider };
1145
+
1146
+ // Utilities
1147
+ export {
1148
+ estimateTokens,
1149
+ getGitRoot, getGitContext, getEnvContext, getProjectSnapshot,
1150
+ checkPromiseSignal
1151
+ };
1152
+ ```
1153
+
1154
+ ---
1155
+
1156
+ ## Development
1157
+
1158
+ ```bash
1159
+ # Development mode (using tsx)
1160
+ npm run dev "your task"
1161
+
1162
+ # Build
1163
+ npm run build
1164
+
1165
+ # Optional: only build workspace packages
1166
+ npm run build:packages
1167
+
1168
+ # Build standalone binary (current platform / all platforms)
1169
+ npm run build:binary
1170
+ npm run build:binary:all
1171
+
1172
+ # Run tests
1173
+ npm test
1174
+
1175
+ # Eval-driven development tests (provider matrices, identity round-trip, etc.)
1176
+ npm run test:eval
1177
+
1178
+ # Clean
1179
+ npm run clean
1180
+ ```
1181
+
1182
+ ### Repo Intelligence cache directories
1183
+
1184
+ KodaX uses one repo-intelligence cache root with separate built-in engine profiles:
1185
+
1186
+ - `.agent/repo-intelligence/`
1187
+ - Full-engine repo-intelligence artifacts and existing task-engine snapshots.
1188
+ - `.agent/repo-intelligence/light/`
1189
+ - Light-mode heuristic index artifacts.
1190
+
1191
+ They are intentionally separated so:
1192
+
1193
+ - full and light profiles can be rebuilt independently.
1194
+ - light-mode confidence/capability state cannot be mistaken for full-engine state.
1195
+ - future cache migrations can delete one profile without corrupting the other.
1196
+
1197
+ `.agent/repo-intelligence/` is local generated state and should not be committed.
1198
+
1199
+ ---
1200
+
1201
+ ## Code Style
1202
+
1203
+ ### Comment Guidelines
1204
+
1205
+ KodaX uses an **English-first** comment style with selective Chinese brief notes for complex logic.
1206
+
1207
+ | Situation | Style | Example |
1208
+ |-----------|-------|---------|
1209
+ | Import/Export | English only | `// Import dependencies` |
1210
+ | Simple constants | English only | `// Max retry count` |
1211
+ | Simple logic | English only | `// Return if null` |
1212
+ | **Business rules** | English + Chinese | `// Skip tool_result - 跳过工具结果块` |
1213
+ | **Platform compatibility** | English + Chinese | `// Windows path handling - Windows 路径处理` |
1214
+ | **Performance optimization** | English + Chinese | `// Debounce to prevent flicker - 防抖避免闪烁` |
1215
+
1216
+ ---
1217
+
1218
+ ## Documentation
1219
+
1220
+ - [README_CN.md](README_CN.md) - Chinese Documentation
1221
+ - [docs/release.md](docs/release.md) - Standalone binary build & release pipeline
1222
+ - [docs/PRD.md](docs/PRD.md) - Product Requirements
1223
+ - [docs/ADR.md](docs/ADR.md) - Architecture Decisions
1224
+ - [docs/HLD.md](docs/HLD.md) - High-Level Design
1225
+ - [docs/DD.md](docs/DD.md) - Detailed Design
1226
+ - [docs/FEATURE_LIST.md](docs/FEATURE_LIST.md) - Feature Tracking
1227
+ - [docs/test-guides/](docs/test-guides/) - Feature-specific test guides
1228
+ - [CHANGELOG.md](CHANGELOG.md) - Version History (v0.7.0+; [archive](docs/CHANGELOG_ARCHIVE.md) for older)
1229
+
1230
+ ---
1231
+
1232
+ ## License
1233
+
1234
+ [Apache License 2.0](LICENSE) - Copyright 2026 [icetomoyo](mailto:icetomoyo@gmail.com)