@openadapter/koda 1.0.0-beta.6 → 1.0.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -633
- package/dist/core/agent-session.d.ts +1 -0
- package/dist/core/agent-session.js +3 -3
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -1,665 +1,97 @@
|
|
|
1
|
-
<
|
|
2
|
-
<a href="https://pi.dev">
|
|
3
|
-
<img alt="pi logo" src="https://pi.dev/logo-auto.svg" width="128">
|
|
4
|
-
</a>
|
|
5
|
-
</p>
|
|
6
|
-
<p align="center">
|
|
7
|
-
<a href="https://discord.com/invite/3cU7Bz4UPx"><img alt="Discord" src="https://img.shields.io/badge/discord-community-5865F2?style=flat-square&logo=discord&logoColor=white" /></a>
|
|
8
|
-
<a href="https://www.npmjs.com/package/@openadapter/koda"><img alt="npm" src="https://img.shields.io/npm/v/@openadapter/koda?style=flat-square" /></a>
|
|
9
|
-
</p>
|
|
10
|
-
<p align="center">
|
|
11
|
-
<a href="https://pi.dev">pi.dev</a> domain graciously donated by
|
|
12
|
-
<br /><br />
|
|
13
|
-
<a href="https://exe.dev"><img src="docs/images/exy.png" alt="Exy mascot" width="48" /><br />exe.dev</a>
|
|
14
|
-
</p>
|
|
15
|
-
|
|
16
|
-
> New issues and PRs from new contributors are auto-closed by default. Maintainers review auto-closed issues daily. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
|
|
17
|
-
|
|
18
|
-
---
|
|
19
|
-
|
|
20
|
-
Pi is a minimal terminal coding harness. Adapt pi to your workflows, not the other way around, without having to fork and modify pi internals. Extend it with TypeScript [Extensions](#extensions), [Skills](#skills), [Prompt Templates](#prompt-templates), and [Themes](#themes). Put your extensions, skills, prompt templates, and themes in [Pi Packages](#pi-packages) and share them with others via npm or git.
|
|
21
|
-
|
|
22
|
-
Pi ships with powerful defaults but skips features like sub agents and plan mode. Instead, you can ask pi to build what you want or install a third party pi package that matches your workflow.
|
|
23
|
-
|
|
24
|
-
Pi runs in four modes: interactive, print or JSON, RPC for process integration, and an SDK for embedding in your own apps. See [openclaw/openclaw](https://github.com/openclaw/openclaw) for a real-world SDK integration.
|
|
25
|
-
|
|
26
|
-
## Share your OSS coding agent sessions
|
|
27
|
-
|
|
28
|
-
If you use pi for open source work, please share your coding agent sessions.
|
|
29
|
-
|
|
30
|
-
Public OSS session data helps improve models, prompts, tools, and evaluations using real development workflows.
|
|
31
|
-
|
|
32
|
-
For the full explanation, see [this post on X](https://x.com/badlogicgames/status/2037811643774652911).
|
|
33
|
-
|
|
34
|
-
To publish sessions, use [`badlogic/pi-share-hf`](https://github.com/badlogic/pi-share-hf). Read its README.md for setup instructions. All you need is a Hugging Face account, the Hugging Face CLI, and `pi-share-hf`.
|
|
35
|
-
|
|
36
|
-
You can also watch [this video](https://x.com/badlogicgames/status/2041151967695634619), where I show how I publish my `pi-mono` sessions.
|
|
37
|
-
|
|
38
|
-
I regularly publish my own `pi-mono` work sessions here:
|
|
39
|
-
|
|
40
|
-
- [badlogicgames/pi-mono on Hugging Face](https://huggingface.co/datasets/badlogicgames/pi-mono)
|
|
41
|
-
|
|
42
|
-
## Table of Contents
|
|
43
|
-
|
|
44
|
-
- [Quick Start](#quick-start)
|
|
45
|
-
- [Providers & Models](#providers--models)
|
|
46
|
-
- [Interactive Mode](#interactive-mode)
|
|
47
|
-
- [Editor](#editor)
|
|
48
|
-
- [Commands](#commands)
|
|
49
|
-
- [Keyboard Shortcuts](#keyboard-shortcuts)
|
|
50
|
-
- [Message Queue](#message-queue)
|
|
51
|
-
- [Sessions](#sessions)
|
|
52
|
-
- [Branching](#branching)
|
|
53
|
-
- [Compaction](#compaction)
|
|
54
|
-
- [Settings](#settings)
|
|
55
|
-
- [Context Files](#context-files)
|
|
56
|
-
- [Customization](#customization)
|
|
57
|
-
- [Prompt Templates](#prompt-templates)
|
|
58
|
-
- [Skills](#skills)
|
|
59
|
-
- [Extensions](#extensions)
|
|
60
|
-
- [Themes](#themes)
|
|
61
|
-
- [Pi Packages](#pi-packages)
|
|
62
|
-
- [Programmatic Usage](#programmatic-usage)
|
|
63
|
-
- [Philosophy](#philosophy)
|
|
64
|
-
- [CLI Reference](#cli-reference)
|
|
65
|
-
|
|
66
|
-
---
|
|
67
|
-
|
|
68
|
-
## Quick Start
|
|
69
|
-
|
|
70
|
-
```bash
|
|
71
|
-
npm install -g --ignore-scripts @openadapter/koda
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
`--ignore-scripts` disables dependency lifecycle scripts during install. Pi does not require install scripts for normal npm installs.
|
|
75
|
-
|
|
76
|
-
Installer alternative:
|
|
77
|
-
|
|
78
|
-
```bash
|
|
79
|
-
curl -fsSL https://pi.dev/install.sh | sh
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
Authenticate with an API key:
|
|
83
|
-
|
|
84
|
-
```bash
|
|
85
|
-
export ANTHROPIC_API_KEY=sk-ant-...
|
|
86
|
-
pi
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
Or use your existing subscription:
|
|
90
|
-
|
|
91
|
-
```bash
|
|
92
|
-
pi
|
|
93
|
-
/login # Then select provider
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
Then just talk to pi. By default, pi gives the model four tools: `read`, `write`, `edit`, and `bash`. The model uses these to fulfill your requests. Add capabilities via [skills](#skills), [prompt templates](#prompt-templates), [extensions](#extensions), or [pi packages](#pi-packages).
|
|
97
|
-
|
|
98
|
-
**Platform notes:** [Windows](docs/windows.md) | [Termux (Android)](docs/termux.md) | [tmux](docs/tmux.md) | [Terminal setup](docs/terminal-setup.md) | [Shell aliases](docs/shell-aliases.md)
|
|
99
|
-
|
|
100
|
-
---
|
|
101
|
-
|
|
102
|
-
## Providers & Models
|
|
103
|
-
|
|
104
|
-
For each built-in provider, pi maintains a list of tool-capable models, updated with every release. Authenticate via subscription (`/login`) or API key, then select any model from that provider via `/model` (or Ctrl+L).
|
|
105
|
-
|
|
106
|
-
**Subscriptions:**
|
|
107
|
-
- Anthropic Claude Pro/Max
|
|
108
|
-
- OpenAI ChatGPT Plus/Pro (Codex)
|
|
109
|
-
- GitHub Copilot
|
|
110
|
-
|
|
111
|
-
**API keys:**
|
|
112
|
-
- Anthropic
|
|
113
|
-
- OpenAI
|
|
114
|
-
- Azure OpenAI
|
|
115
|
-
- DeepSeek
|
|
116
|
-
- NVIDIA NIM
|
|
117
|
-
- Google Gemini
|
|
118
|
-
- Google Vertex
|
|
119
|
-
- Amazon Bedrock
|
|
120
|
-
- Mistral
|
|
121
|
-
- Groq
|
|
122
|
-
- Cerebras
|
|
123
|
-
- Cloudflare AI Gateway
|
|
124
|
-
- Cloudflare Workers AI
|
|
125
|
-
- xAI
|
|
126
|
-
- OpenRouter
|
|
127
|
-
- Vercel AI Gateway
|
|
128
|
-
- ZAI
|
|
129
|
-
- OpenCode Zen
|
|
130
|
-
- OpenCode Go
|
|
131
|
-
- Hugging Face
|
|
132
|
-
- Fireworks
|
|
133
|
-
- Together AI
|
|
134
|
-
- Kimi For Coding
|
|
135
|
-
- MiniMax
|
|
136
|
-
- Xiaomi MiMo
|
|
137
|
-
- Xiaomi MiMo Token Plan (China)
|
|
138
|
-
- Xiaomi MiMo Token Plan (Amsterdam)
|
|
139
|
-
- Xiaomi MiMo Token Plan (Singapore)
|
|
140
|
-
|
|
141
|
-
See [docs/providers.md](docs/providers.md) for detailed setup instructions.
|
|
142
|
-
|
|
143
|
-
**Custom providers & models:** Add providers via `~/.pi/agent/models.json` if they speak a supported API (OpenAI, Anthropic, Google). For custom APIs or OAuth, use extensions. See [docs/models.md](docs/models.md) and [docs/custom-provider.md](docs/custom-provider.md).
|
|
144
|
-
|
|
145
|
-
---
|
|
146
|
-
|
|
147
|
-
## Interactive Mode
|
|
148
|
-
|
|
149
|
-
<p align="center"><img src="docs/images/interactive-mode.png" alt="Interactive Mode" width="600"></p>
|
|
150
|
-
|
|
151
|
-
The interface from top to bottom:
|
|
152
|
-
|
|
153
|
-
- **Startup header** - Shows shortcuts (`/hotkeys` for all), loaded AGENTS.md files, prompt templates, skills, and extensions
|
|
154
|
-
- **Messages** - Your messages, assistant responses, tool calls and results, notifications, errors, and extension UI
|
|
155
|
-
- **Editor** - Where you type; border color indicates thinking level
|
|
156
|
-
- **Footer** - Working directory, session name, total token/cache usage, cost, context usage, current model
|
|
157
|
-
|
|
158
|
-
The editor can be temporarily replaced by other UI, like built-in `/settings` or custom UI from extensions (e.g., a Q&A tool that lets the user answer model questions in a structured format). [Extensions](#extensions) can also replace the editor, add widgets above/below it, a status line, custom footer, or overlays.
|
|
159
|
-
|
|
160
|
-
### Editor
|
|
161
|
-
|
|
162
|
-
| Feature | How |
|
|
163
|
-
|---------|-----|
|
|
164
|
-
| File reference | Type `@` to fuzzy-search project files |
|
|
165
|
-
| Path completion | Tab to complete paths |
|
|
166
|
-
| Multi-line | Shift+Enter (or Ctrl+Enter on Windows Terminal) |
|
|
167
|
-
| Images | Ctrl+V to paste (Alt+V on Windows), or drag onto terminal |
|
|
168
|
-
| Bash commands | `!command` runs and sends output to LLM, `!!command` runs without sending |
|
|
169
|
-
|
|
170
|
-
Standard editing keybindings for delete word, undo, etc. See [docs/keybindings.md](docs/keybindings.md).
|
|
171
|
-
|
|
172
|
-
### Commands
|
|
173
|
-
|
|
174
|
-
Type `/` in the editor to trigger commands. [Extensions](#extensions) can register custom commands, [skills](#skills) are available as `/skill:name`, and [prompt templates](#prompt-templates) expand via `/templatename`.
|
|
175
|
-
|
|
176
|
-
| Command | Description |
|
|
177
|
-
|---------|-------------|
|
|
178
|
-
| `/login`, `/logout` | OAuth authentication |
|
|
179
|
-
| `/model` | Switch models |
|
|
180
|
-
| `/scoped-models` | Enable/disable models for Ctrl+P cycling |
|
|
181
|
-
| `/settings` | Thinking level, theme, message delivery, transport |
|
|
182
|
-
| `/resume` | Pick from previous sessions |
|
|
183
|
-
| `/new` | Start a new session |
|
|
184
|
-
| `/name <name>` | Set session display name |
|
|
185
|
-
| `/session` | Show session info (file, ID, messages, tokens, cost) |
|
|
186
|
-
| `/tree` | Jump to any point in the session and continue from there |
|
|
187
|
-
| `/fork` | Create a new session from a previous user message |
|
|
188
|
-
| `/clone` | Duplicate the current active branch into a new session |
|
|
189
|
-
| `/compact [prompt]` | Manually compact context, optional custom instructions |
|
|
190
|
-
| `/copy` | Copy last assistant message to clipboard |
|
|
191
|
-
| `/export [file]` | Export session to HTML file |
|
|
192
|
-
| `/share` | Upload as private GitHub gist with shareable HTML link |
|
|
193
|
-
| `/reload` | Reload keybindings, extensions, skills, prompts, and context files (themes hot-reload automatically) |
|
|
194
|
-
| `/hotkeys` | Show all keyboard shortcuts |
|
|
195
|
-
| `/changelog` | Display version history |
|
|
196
|
-
| `/quit` | Quit pi |
|
|
197
|
-
|
|
198
|
-
### Keyboard Shortcuts
|
|
199
|
-
|
|
200
|
-
See `/hotkeys` for the full list. Customize via `~/.pi/agent/keybindings.json`. See [docs/keybindings.md](docs/keybindings.md).
|
|
201
|
-
|
|
202
|
-
**Commonly used:**
|
|
203
|
-
|
|
204
|
-
| Key | Action |
|
|
205
|
-
|-----|--------|
|
|
206
|
-
| Ctrl+C | Clear editor |
|
|
207
|
-
| Ctrl+C twice | Quit |
|
|
208
|
-
| Escape | Cancel/abort |
|
|
209
|
-
| Escape twice | Open `/tree` |
|
|
210
|
-
| Ctrl+L | Open model selector |
|
|
211
|
-
| Ctrl+P / Shift+Ctrl+P | Cycle scoped models forward/backward |
|
|
212
|
-
| Shift+Tab | Cycle thinking level |
|
|
213
|
-
| Ctrl+O | Collapse/expand tool output |
|
|
214
|
-
| Ctrl+T | Collapse/expand thinking blocks |
|
|
215
|
-
|
|
216
|
-
### Message Queue
|
|
217
|
-
|
|
218
|
-
Submit messages while the agent is working:
|
|
219
|
-
|
|
220
|
-
- **Enter** queues a *steering* message, delivered after the current assistant turn finishes executing its tool calls
|
|
221
|
-
- **Alt+Enter** queues a *follow-up* message, delivered only after the agent finishes all work
|
|
222
|
-
- **Escape** aborts and restores queued messages to editor
|
|
223
|
-
- **Alt+Up** retrieves queued messages back to editor
|
|
224
|
-
|
|
225
|
-
On Windows Terminal, `Alt+Enter` is fullscreen by default. Remap it in [docs/terminal-setup.md](docs/terminal-setup.md) so pi can receive the follow-up shortcut.
|
|
226
|
-
|
|
227
|
-
Configure delivery in [settings](docs/settings.md): `steeringMode` and `followUpMode` can be `"one-at-a-time"` (default, waits for response) or `"all"` (delivers all queued at once). `transport` selects provider transport preference (`"sse"`, `"websocket"`, or `"auto"`) for providers that support multiple transports.
|
|
228
|
-
|
|
229
|
-
---
|
|
230
|
-
|
|
231
|
-
## Sessions
|
|
232
|
-
|
|
233
|
-
Sessions are stored as JSONL files with a tree structure. Each entry has an `id` and `parentId`, enabling in-place branching without creating new files. See [docs/session-format.md](docs/session-format.md) for file format.
|
|
234
|
-
|
|
235
|
-
### Management
|
|
236
|
-
|
|
237
|
-
Sessions auto-save to `~/.pi/agent/sessions/` organized by working directory.
|
|
238
|
-
|
|
239
|
-
```bash
|
|
240
|
-
pi -c # Continue most recent session
|
|
241
|
-
pi -r # Browse and select from past sessions
|
|
242
|
-
pi --no-session # Ephemeral mode (don't save)
|
|
243
|
-
pi --name "my task" # Set session display name at startup
|
|
244
|
-
pi --session <path|id> # Use specific session file or ID
|
|
245
|
-
pi --fork <path|id> # Fork specific session file or ID into a new session
|
|
246
|
-
```
|
|
247
|
-
|
|
248
|
-
Use `/session` in interactive mode to see the current session ID before reusing it with `--session <id>` or `--fork <id>`.
|
|
249
|
-
|
|
250
|
-
### Branching
|
|
251
|
-
|
|
252
|
-
**`/tree`** - Navigate the session tree in-place. Select any previous point, continue from there, and switch between branches. All history preserved in a single file.
|
|
253
|
-
|
|
254
|
-
<p align="center"><img src="docs/images/tree-view.png" alt="Tree View" width="600"></p>
|
|
255
|
-
|
|
256
|
-
- Search by typing, fold/unfold and jump between branches with Ctrl+←/Ctrl+→ or Alt+←/Alt+→, page with ←/→
|
|
257
|
-
- Filter modes (Ctrl+O): default → no-tools → user-only → labeled-only → all
|
|
258
|
-
- Press Shift+L to label entries as bookmarks and Shift+T to toggle label timestamps
|
|
259
|
-
|
|
260
|
-
**`/fork`** - Create a new session file from a previous user message on the active branch. Opens a selector, copies the active path up to that point, and places the selected prompt in the editor for modification.
|
|
261
|
-
|
|
262
|
-
**`/clone`** - Duplicate the current active branch into a new session file at the current position. The new session keeps the full active-path history and opens with an empty editor.
|
|
263
|
-
|
|
264
|
-
**`--fork <path|id>`** - Fork an existing session file or partial session UUID directly from the CLI. This copies the full source session into a new session file in the current project.
|
|
265
|
-
|
|
266
|
-
### Compaction
|
|
267
|
-
|
|
268
|
-
Long sessions can exhaust context windows. Compaction summarizes older messages while keeping recent ones.
|
|
269
|
-
|
|
270
|
-
**Manual:** `/compact` or `/compact <custom instructions>`
|
|
271
|
-
|
|
272
|
-
**Automatic:** Enabled by default. Triggers on context overflow (recovers and retries) or when approaching the limit (proactive). Configure via `/settings` or `settings.json`.
|
|
273
|
-
|
|
274
|
-
Compaction is lossy. The full history remains in the JSONL file; use `/tree` to revisit. Customize compaction behavior via [extensions](#extensions). See [docs/compaction.md](docs/compaction.md) for internals.
|
|
275
|
-
|
|
276
|
-
---
|
|
277
|
-
|
|
278
|
-
## Settings
|
|
279
|
-
|
|
280
|
-
Use `/settings` to modify common options, or edit JSON files directly:
|
|
281
|
-
|
|
282
|
-
| Location | Scope |
|
|
283
|
-
|----------|-------|
|
|
284
|
-
| `~/.pi/agent/settings.json` | Global (all projects) |
|
|
285
|
-
| `.pi/settings.json` | Project (overrides global) |
|
|
286
|
-
|
|
287
|
-
See [docs/settings.md](docs/settings.md) for all options.
|
|
288
|
-
|
|
289
|
-
### Telemetry and update checks
|
|
290
|
-
|
|
291
|
-
Pi has two separate startup features:
|
|
292
|
-
|
|
293
|
-
- **Update check:** fetches `https://pi.dev/api/latest-version` to check whether a newer Pi version exists. Disable it with `PI_SKIP_VERSION_CHECK=1`. Disabling update checks only turns off this check.
|
|
294
|
-
- **Install/update telemetry:** after first install or a changelog-detected update, sends an anonymous version ping to `https://pi.dev/api/report-install`. This setting also controls optional provider attribution headers for OpenRouter, Cloudflare, and direct NVIDIA NIM requests. Opt out by setting `enableInstallTelemetry` to `false` in `settings.json`, or by setting `PI_TELEMETRY=0`. This does not disable update checks; Pi may still contact `pi.dev` for the latest version unless update checks are disabled or offline mode is enabled.
|
|
1
|
+
<h1 align="center">Koda</h1>
|
|
295
2
|
|
|
296
|
-
|
|
3
|
+
<p align="center"><strong>The coding agent that makes affordable models actually finish the job.</strong></p>
|
|
297
4
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
- `~/.pi/agent/AGENTS.md` (global)
|
|
304
|
-
- Parent directories (walking up from cwd)
|
|
305
|
-
- Current directory
|
|
306
|
-
|
|
307
|
-
Use for project instructions, conventions, common commands. All matching files are concatenated.
|
|
308
|
-
|
|
309
|
-
Disable context file loading with `--no-context-files` (or `-nc`).
|
|
310
|
-
|
|
311
|
-
### System Prompt
|
|
312
|
-
|
|
313
|
-
Replace the default system prompt with `.pi/SYSTEM.md` (project) or `~/.pi/agent/SYSTEM.md` (global). Append without replacing via `APPEND_SYSTEM.md`.
|
|
314
|
-
|
|
315
|
-
---
|
|
316
|
-
|
|
317
|
-
## Customization
|
|
318
|
-
|
|
319
|
-
### Prompt Templates
|
|
320
|
-
|
|
321
|
-
Reusable prompts as Markdown files. Type `/name` to expand.
|
|
322
|
-
|
|
323
|
-
```markdown
|
|
324
|
-
<!-- ~/.pi/agent/prompts/review.md -->
|
|
325
|
-
Review this code for bugs, security issues, and performance problems.
|
|
326
|
-
Focus on: {{focus}}
|
|
327
|
-
```
|
|
328
|
-
|
|
329
|
-
Place in `~/.pi/agent/prompts/`, `.pi/prompts/`, or a [pi package](#pi-packages) to share with others. See [docs/prompt-templates.md](docs/prompt-templates.md).
|
|
330
|
-
|
|
331
|
-
### Skills
|
|
332
|
-
|
|
333
|
-
On-demand capability packages following the [Agent Skills standard](https://agentskills.io). Invoke via `/skill:name` or let the agent load them automatically.
|
|
334
|
-
|
|
335
|
-
```markdown
|
|
336
|
-
<!-- ~/.pi/agent/skills/my-skill/SKILL.md -->
|
|
337
|
-
# My Skill
|
|
338
|
-
Use this skill when the user asks about X.
|
|
339
|
-
|
|
340
|
-
## Steps
|
|
341
|
-
1. Do this
|
|
342
|
-
2. Then that
|
|
343
|
-
```
|
|
344
|
-
|
|
345
|
-
Place in `~/.pi/agent/skills/`, `~/.agents/skills/`, `.pi/skills/`, or `.agents/skills/` (from `cwd` up through parent directories) or a [pi package](#pi-packages) to share with others. See [docs/skills.md](docs/skills.md).
|
|
346
|
-
|
|
347
|
-
### Extensions
|
|
348
|
-
|
|
349
|
-
<p align="center"><img src="docs/images/doom-extension.png" alt="Doom Extension" width="600"></p>
|
|
350
|
-
|
|
351
|
-
TypeScript modules that extend pi with custom tools, commands, keyboard shortcuts, event handlers, and UI components.
|
|
352
|
-
|
|
353
|
-
```typescript
|
|
354
|
-
export default function (pi: ExtensionAPI) {
|
|
355
|
-
pi.registerTool({ name: "deploy", ... });
|
|
356
|
-
pi.registerCommand("stats", { ... });
|
|
357
|
-
pi.on("tool_call", async (event, ctx) => { ... });
|
|
358
|
-
}
|
|
359
|
-
```
|
|
360
|
-
|
|
361
|
-
The default export can also be `async`. pi waits for async extension factories before startup continues, which is useful for one-time initialization such as fetching remote model lists before calling `pi.registerProvider()`.
|
|
362
|
-
|
|
363
|
-
**What's possible:**
|
|
364
|
-
- Custom tools (or replace built-in tools entirely)
|
|
365
|
-
- Sub-agents and plan mode
|
|
366
|
-
- Custom compaction and summarization
|
|
367
|
-
- Permission gates and path protection
|
|
368
|
-
- Custom editors and UI components
|
|
369
|
-
- Status lines, headers, footers
|
|
370
|
-
- Git checkpointing and auto-commit
|
|
371
|
-
- SSH and sandbox execution
|
|
372
|
-
- MCP server integration
|
|
373
|
-
- Make pi look like Claude Code
|
|
374
|
-
- Games while waiting (yes, Doom runs)
|
|
375
|
-
- ...anything you can dream up
|
|
376
|
-
|
|
377
|
-
Place in `~/.pi/agent/extensions/`, `.pi/extensions/`, or a [pi package](#pi-packages) to share with others. See [docs/extensions.md](docs/extensions.md) and [examples/extensions/](examples/extensions/).
|
|
378
|
-
|
|
379
|
-
### Themes
|
|
380
|
-
|
|
381
|
-
Built-in: `dark`, `light`. Themes hot-reload: modify the active theme file and pi immediately applies changes.
|
|
382
|
-
|
|
383
|
-
Place in `~/.pi/agent/themes/`, `.pi/themes/`, or a [pi package](#pi-packages) to share with others. See [docs/themes.md](docs/themes.md).
|
|
384
|
-
|
|
385
|
-
### Pi Packages
|
|
386
|
-
|
|
387
|
-
Bundle and share extensions, skills, prompts, and themes via npm or git. Find packages on [npmjs.com](https://www.npmjs.com/search?q=keywords%3Api-package) or [Discord](https://discord.com/channels/1456806362351669492/1457744485428629628).
|
|
388
|
-
|
|
389
|
-
> **Security:** Pi packages run with full system access. Extensions execute arbitrary code, and skills can instruct the model to perform any action including running executables. Review source code before installing third-party packages.
|
|
390
|
-
|
|
391
|
-
```bash
|
|
392
|
-
pi install npm:@foo/pi-tools
|
|
393
|
-
pi install npm:@foo/pi-tools@1.2.3 # pinned version
|
|
394
|
-
pi install git:github.com/user/repo
|
|
395
|
-
pi install git:github.com/user/repo@v1 # tag or commit
|
|
396
|
-
pi install git:git@github.com:user/repo
|
|
397
|
-
pi install git:git@github.com:user/repo@v1 # tag or commit
|
|
398
|
-
pi install https://github.com/user/repo
|
|
399
|
-
pi install https://github.com/user/repo@v1 # tag or commit
|
|
400
|
-
pi install ssh://git@github.com/user/repo
|
|
401
|
-
pi install ssh://git@github.com/user/repo@v1 # tag or commit
|
|
402
|
-
pi remove npm:@foo/pi-tools
|
|
403
|
-
pi uninstall npm:@foo/pi-tools # alias for remove
|
|
404
|
-
pi list
|
|
405
|
-
pi update # update pi and packages (skips pinned packages)
|
|
406
|
-
pi update --extensions # update packages only
|
|
407
|
-
pi update --self # update pi only
|
|
408
|
-
pi update --self --force # reinstall pi even if current
|
|
409
|
-
pi update npm:@foo/pi-tools # update one package
|
|
410
|
-
pi config # enable/disable extensions, skills, prompts, themes
|
|
411
|
-
```
|
|
412
|
-
|
|
413
|
-
Packages install to `~/.pi/agent/git/` (git) or `~/.pi/agent/npm/` (npm). Use `-l` for project-local installs (`.pi/git/`, `.pi/npm/`). Git `@ref` values are pinned tags or commits; pinned packages are skipped by `pi update`, so use `pi install git:host/user/repo@new-ref` to move an existing package to a new ref. Git packages install dependencies with `npm install --omit=dev` by default, so runtime deps must be listed under `dependencies`; when `npmCommand` is configured, git packages use plain `install` for compatibility with wrappers. If you use a Node version manager and want package installs to reuse a stable npm context, set `npmCommand` in `settings.json`, for example `["mise", "exec", "node@20", "--", "npm"]`.
|
|
414
|
-
|
|
415
|
-
Create a package by adding a `pi` key to `package.json`:
|
|
416
|
-
|
|
417
|
-
```json
|
|
418
|
-
{
|
|
419
|
-
"name": "my-pi-package",
|
|
420
|
-
"keywords": ["pi-package"],
|
|
421
|
-
"pi": {
|
|
422
|
-
"extensions": ["./extensions"],
|
|
423
|
-
"skills": ["./skills"],
|
|
424
|
-
"prompts": ["./prompts"],
|
|
425
|
-
"themes": ["./themes"]
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
```
|
|
429
|
-
|
|
430
|
-
Without a `pi` manifest, pi auto-discovers from conventional directories (`extensions/`, `skills/`, `prompts/`, `themes/`).
|
|
431
|
-
|
|
432
|
-
See [docs/packages.md](docs/packages.md).
|
|
433
|
-
|
|
434
|
-
---
|
|
435
|
-
|
|
436
|
-
## Programmatic Usage
|
|
437
|
-
|
|
438
|
-
### SDK
|
|
439
|
-
|
|
440
|
-
```typescript
|
|
441
|
-
import { AuthStorage, createAgentSession, ModelRegistry, SessionManager } from "@openadapter/koda";
|
|
442
|
-
|
|
443
|
-
const authStorage = AuthStorage.create();
|
|
444
|
-
const modelRegistry = ModelRegistry.create(authStorage);
|
|
445
|
-
const { session } = await createAgentSession({
|
|
446
|
-
sessionManager: SessionManager.inMemory(),
|
|
447
|
-
authStorage,
|
|
448
|
-
modelRegistry,
|
|
449
|
-
});
|
|
450
|
-
|
|
451
|
-
await session.prompt("What files are in the current directory?");
|
|
452
|
-
```
|
|
453
|
-
|
|
454
|
-
For advanced multi-session runtime replacement, use `createAgentSessionRuntime()` and `AgentSessionRuntime`.
|
|
455
|
-
|
|
456
|
-
See [docs/sdk.md](docs/sdk.md) and [examples/sdk/](examples/sdk/).
|
|
457
|
-
|
|
458
|
-
### RPC Mode
|
|
459
|
-
|
|
460
|
-
For non-Node.js integrations, use RPC mode over stdin/stdout:
|
|
461
|
-
|
|
462
|
-
```bash
|
|
463
|
-
pi --mode rpc
|
|
464
|
-
```
|
|
465
|
-
|
|
466
|
-
RPC mode uses strict LF-delimited JSONL framing. Clients must split records on `\n` only. Do not use generic line readers like Node `readline`, which also split on Unicode separators inside JSON payloads.
|
|
467
|
-
|
|
468
|
-
See [docs/rpc.md](docs/rpc.md) for the protocol.
|
|
469
|
-
|
|
470
|
-
---
|
|
471
|
-
|
|
472
|
-
## Philosophy
|
|
473
|
-
|
|
474
|
-
Pi is aggressively extensible so it doesn't have to dictate your workflow. Features that other tools bake in can be built with [extensions](#extensions), [skills](#skills), or installed from third-party [pi packages](#pi-packages). This keeps the core minimal while letting you shape pi to fit how you work.
|
|
475
|
-
|
|
476
|
-
**No MCP.** Build CLI tools with READMEs (see [Skills](#skills)), or build an extension that adds MCP support. [Why?](https://mariozechner.at/posts/2025-11-02-what-if-you-dont-need-mcp/)
|
|
477
|
-
|
|
478
|
-
**No sub-agents.** There's many ways to do this. Spawn pi instances via tmux, or build your own with [extensions](#extensions), or install a package that does it your way.
|
|
479
|
-
|
|
480
|
-
**No permission popups.** Run in a container, or build your own confirmation flow with [extensions](#extensions) inline with your environment and security requirements.
|
|
481
|
-
|
|
482
|
-
**No plan mode.** Write plans to files, or build it with [extensions](#extensions), or install a package.
|
|
483
|
-
|
|
484
|
-
**No built-in to-dos.** They confuse models. Use a TODO.md file, or build your own with [extensions](#extensions).
|
|
485
|
-
|
|
486
|
-
**No background bash.** Use tmux. Full observability, direct interaction.
|
|
487
|
-
|
|
488
|
-
Read the [blog post](https://mariozechner.at/posts/2025-11-30-pi-coding-agent/) for the full rationale.
|
|
5
|
+
<p align="center">
|
|
6
|
+
<a href="https://www.npmjs.com/package/@openadapter/koda"><img alt="npm" src="https://img.shields.io/npm/v/@openadapter/koda/beta?style=flat-square&label=beta" /></a>
|
|
7
|
+
<a href="https://openadapter.in"><img alt="OpenAdapter" src="https://img.shields.io/badge/built%20for-OpenAdapter-7c3aed?style=flat-square" /></a>
|
|
8
|
+
<img alt="license" src="https://img.shields.io/badge/license-MIT-green?style=flat-square" />
|
|
9
|
+
</p>
|
|
489
10
|
|
|
490
11
|
---
|
|
491
12
|
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
```bash
|
|
495
|
-
pi [options] [@files...] [messages...]
|
|
496
|
-
```
|
|
497
|
-
|
|
498
|
-
### Package Commands
|
|
13
|
+
**Koda** is a terminal coding agent built for [OpenAdapter](https://openadapter.in). One key gives you many models — and Koda wraps a **reliability layer** around them so cheaper, faster models still ship working code: it never idles on rate limits, fails over when a model stalls, verifies its own work, and steps up to a stronger model only when it has to.
|
|
499
14
|
|
|
500
|
-
|
|
501
|
-
pi install <source> [-l] # Install package, -l for project-local
|
|
502
|
-
pi remove <source> [-l] # Remove package
|
|
503
|
-
pi uninstall <source> [-l] # Alias for remove
|
|
504
|
-
pi update [source|self|pi] # Update pi and packages (skips pinned packages)
|
|
505
|
-
pi update --extensions # Update packages only
|
|
506
|
-
pi update --self # Update pi only
|
|
507
|
-
pi update --self --force # Reinstall pi even if current
|
|
508
|
-
pi update --extension <src> # Update one package
|
|
509
|
-
pi list # List installed packages
|
|
510
|
-
pi config # Enable/disable package resources
|
|
511
|
-
```
|
|
512
|
-
|
|
513
|
-
### Modes
|
|
514
|
-
|
|
515
|
-
| Flag | Description |
|
|
516
|
-
|------|-------------|
|
|
517
|
-
| (default) | Interactive mode |
|
|
518
|
-
| `-p`, `--print` | Print response and exit |
|
|
519
|
-
| `--mode json` | Output all events as JSON lines (see [docs/json.md](docs/json.md)) |
|
|
520
|
-
| `--mode rpc` | RPC mode for process integration (see [docs/rpc.md](docs/rpc.md)) |
|
|
521
|
-
| `--export <in> [out]` | Export session to HTML |
|
|
15
|
+
It runs in your terminal like the coding CLIs you already know — just harder to break, and tuned end-to-end for OpenAdapter.
|
|
522
16
|
|
|
523
|
-
|
|
17
|
+
## Install
|
|
524
18
|
|
|
525
19
|
```bash
|
|
526
|
-
|
|
20
|
+
npm i -g @openadapter/koda@beta
|
|
21
|
+
koda
|
|
527
22
|
```
|
|
528
23
|
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
| Option | Description |
|
|
532
|
-
|--------|-------------|
|
|
533
|
-
| `--provider <name>` | Provider (anthropic, openai, google, etc.) |
|
|
534
|
-
| `--model <pattern>` | Model pattern or ID (supports `provider/id` and optional `:<thinking>`) |
|
|
535
|
-
| `--api-key <key>` | API key (overrides env vars) |
|
|
536
|
-
| `--thinking <level>` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh` |
|
|
537
|
-
| `--models <patterns>` | Comma-separated patterns for Ctrl+P cycling |
|
|
538
|
-
| `--list-models [search]` | List available models |
|
|
539
|
-
|
|
540
|
-
### Session Options
|
|
541
|
-
|
|
542
|
-
| Option | Description |
|
|
543
|
-
|--------|-------------|
|
|
544
|
-
| `-c`, `--continue` | Continue most recent session |
|
|
545
|
-
| `-r`, `--resume` | Browse and select session |
|
|
546
|
-
| `--session <path\|id>` | Use specific session file or partial UUID |
|
|
547
|
-
| `--fork <path\|id>` | Fork specific session file or partial UUID into a new session |
|
|
548
|
-
| `--session-dir <dir>` | Custom session storage directory |
|
|
549
|
-
| `--no-session` | Ephemeral mode (don't save) |
|
|
550
|
-
| `--name <name>`, `-n <name>` | Set session display name at startup |
|
|
551
|
-
|
|
552
|
-
### Tool Options
|
|
553
|
-
|
|
554
|
-
| Option | Description |
|
|
555
|
-
|--------|-------------|
|
|
556
|
-
| `--tools <list>`, `-t <list>` | Allowlist specific tool names across built-in, extension, and custom tools |
|
|
557
|
-
| `--exclude-tools <list>`, `-xt <list>` | Disable specific tool names across built-in, extension, and custom tools |
|
|
558
|
-
| `--no-builtin-tools`, `-nbt` | Disable built-in tools by default but keep extension/custom tools enabled |
|
|
559
|
-
| `--no-tools`, `-nt` | Disable all tools by default |
|
|
560
|
-
|
|
561
|
-
Available built-in tools: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`
|
|
562
|
-
|
|
563
|
-
### Resource Options
|
|
564
|
-
|
|
565
|
-
| Option | Description |
|
|
566
|
-
|--------|-------------|
|
|
567
|
-
| `-e`, `--extension <source>` | Load extension from path, npm, or git (repeatable) |
|
|
568
|
-
| `--no-extensions` | Disable extension discovery |
|
|
569
|
-
| `--skill <path>` | Load skill (repeatable) |
|
|
570
|
-
| `--no-skills` | Disable skill discovery |
|
|
571
|
-
| `--prompt-template <path>` | Load prompt template (repeatable) |
|
|
572
|
-
| `--no-prompt-templates` | Disable prompt template discovery |
|
|
573
|
-
| `--theme <path>` | Load theme (repeatable) |
|
|
574
|
-
| `--no-themes` | Disable theme discovery |
|
|
575
|
-
| `--no-context-files`, `-nc` | Disable AGENTS.md and CLAUDE.md context file discovery |
|
|
576
|
-
|
|
577
|
-
Combine `--no-*` with explicit flags to load exactly what you need, ignoring settings.json (e.g., `--no-extensions -e ./my-ext.ts`).
|
|
578
|
-
|
|
579
|
-
### Other Options
|
|
580
|
-
|
|
581
|
-
| Option | Description |
|
|
582
|
-
|--------|-------------|
|
|
583
|
-
| `--system-prompt <text>` | Replace default prompt (context files and skills still appended) |
|
|
584
|
-
| `--append-system-prompt <text>` | Append to system prompt |
|
|
585
|
-
| `--verbose` | Force verbose startup |
|
|
586
|
-
| `-h`, `--help` | Show help |
|
|
587
|
-
| `-v`, `--version` | Show version |
|
|
588
|
-
|
|
589
|
-
### File Arguments
|
|
590
|
-
|
|
591
|
-
Prefix files with `@` to include in the message:
|
|
24
|
+
First launch runs a one-time setup: paste your OpenAdapter API key (`sk-cv-…` from your [dashboard](https://openadapter.in)) and Koda wires up the models, tools, and skills. That's it.
|
|
592
25
|
|
|
593
26
|
```bash
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
27
|
+
koda # start (or resume) in the current folder
|
|
28
|
+
koda --continue # reopen the latest session here
|
|
29
|
+
koda --resume # pick a past session
|
|
30
|
+
koda setup # re-run setup any time
|
|
31
|
+
koda import # pull in past sessions from other CLIs (see below)
|
|
597
32
|
```
|
|
598
33
|
|
|
599
|
-
|
|
34
|
+
## What makes Koda different
|
|
600
35
|
|
|
601
|
-
|
|
602
|
-
# Interactive with initial prompt
|
|
603
|
-
pi "List all .ts files in src/"
|
|
36
|
+
**One key, many models — tiered.** Point Koda at any OpenAdapter model (max / pro / lite). Koda reads live health/latency signals to route well, and you stay on *your* pick.
|
|
604
37
|
|
|
605
|
-
|
|
606
|
-
pi -p "Summarize this codebase"
|
|
38
|
+
**Reliability that keeps cheap models honest:**
|
|
607
39
|
|
|
608
|
-
|
|
609
|
-
|
|
40
|
+
- **Never idle on a rate limit** — `/zenitsu` speed mode instantly reroutes a 429 to a healthy, faster model (no waiting), then snaps back to your preferred one the moment it's free.
|
|
41
|
+
- **Failover, not failure** — provider/model hiccups are retried and routed around; a request rarely dies from a single flake.
|
|
42
|
+
- **Run-it verification** — when code changed, Koda runs your build/tests/lint and treats the **exit code as ground truth**, not the model's opinion.
|
|
43
|
+
- **Overseer + escalation** — a stronger model double-checks "done" on smaller models and, if it's stuck, Koda climbs the tier ladder — capped, then sticks.
|
|
44
|
+
- **Heal, don't crash** — loop/state errors recover instead of killing your session; repetition/garbage output is detected and replaced.
|
|
610
45
|
|
|
611
|
-
|
|
612
|
-
pi --name "release audit" -p "Audit this repository"
|
|
46
|
+
**Features that respect your time:**
|
|
613
47
|
|
|
614
|
-
|
|
615
|
-
|
|
48
|
+
- **Ask & suggest** — on open-ended requests Koda proposes an approach and asks the decisions that matter (framework, storage…) with a clean multiple-choice card, instead of guessing wrong.
|
|
49
|
+
- **Vision on any model** — paste a screenshot even on a non-vision model; Koda reads it with a vision model and passes the details along.
|
|
50
|
+
- **Bring your history** — `koda import` (and a first-run prompt) imports past sessions from **Claude Code** and **OpenCode** into Koda, organized by project. Nothing left behind.
|
|
51
|
+
- **Memory, web, background tasks** — remember/recall with semantic search, web search + fetch, and long-running servers via `run_background`.
|
|
52
|
+
- **Skills & modes** — drop-in Agent Skills (frontend, debugging, code-review), `/plan` and `/build` modes.
|
|
53
|
+
- **Stays current** — checks for updates and updates itself in the background; the model list auto-refreshes daily so you always have the newest models.
|
|
54
|
+
- **Calm, useful UX** — live working indicator, an end-of-task recap, a session-resume hint when you reopen a folder, and contextual tips that surface the right feature exactly when it helps.
|
|
616
55
|
|
|
617
|
-
|
|
618
|
-
pi --model openai/gpt-4o "Help me refactor"
|
|
56
|
+
## Common commands
|
|
619
57
|
|
|
620
|
-
|
|
621
|
-
|
|
58
|
+
| Command | What it does |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `/zenitsu` | Toggle speed mode (never wait on a rate limit) |
|
|
61
|
+
| `/goal` | Set a session goal Koda tracks to completion |
|
|
62
|
+
| `/plan` · `/build` | Switch between plan and build modes |
|
|
63
|
+
| `/resume` · `/continue` | Open a past session |
|
|
64
|
+
| `/memory` · `/todos` | Memory and task list |
|
|
65
|
+
| `/use <skill>` | Keep a skill active for the session |
|
|
66
|
+
| `/trace` | What the harness did (failover / verify / escalate …) |
|
|
67
|
+
| `/settings` | Settings (incl. "Import past sessions") |
|
|
68
|
+
| `/help` | Full help |
|
|
622
69
|
|
|
623
|
-
|
|
624
|
-
pi --models "claude-*,gpt-4o"
|
|
70
|
+
## Configuration (env flags)
|
|
625
71
|
|
|
626
|
-
|
|
627
|
-
|
|
72
|
+
| Flag | Effect |
|
|
73
|
+
|---|---|
|
|
74
|
+
| `KODA_ZENITSU=1` | Start in speed mode |
|
|
75
|
+
| `KODA_NO_AUTO_UPDATE=1` | Notify about updates but don't auto-install |
|
|
76
|
+
| `KODA_NO_MODEL_REFRESH=1` | Don't auto-refresh the model list |
|
|
77
|
+
| `KODA_NO_RESUME_HINT=1` | Hide the "past sessions in this folder" hint |
|
|
78
|
+
| `KODA_TIPS=0` | Disable contextual feature tips |
|
|
79
|
+
| `KODA_OFFLINE=1` | No network calls (version check, model refresh, tool downloads) |
|
|
628
80
|
|
|
629
|
-
|
|
630
|
-
pi --exclude-tools ask_question
|
|
81
|
+
## Built on Pi — credit where it's due
|
|
631
82
|
|
|
632
|
-
|
|
633
|
-
pi --thinking high "Solve this complex problem"
|
|
634
|
-
```
|
|
83
|
+
Koda stands on **[Pi](https://github.com/earendil-works/pi)**, the excellent open-source terminal coding harness by **Mario Zechner** ([@badlogic](https://github.com/badlogic)). A huge amount of what makes Koda pleasant to use is Pi's, and we're grateful for it.
|
|
635
84
|
|
|
636
|
-
|
|
85
|
+
**Pi provides the foundation** — the interactive TUI + editor, sessions & branching, context compaction, the extension / skill / prompt-template / theme system, prompt-template and package management, and the interactive / print / RPC / SDK run modes.
|
|
637
86
|
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
| `PI_OFFLINE` | Disable startup network operations, including update checks, package update checks, and install/update telemetry |
|
|
644
|
-
| `PI_SKIP_VERSION_CHECK` | Skip the Pi version update check at startup. This prevents the `pi.dev` latest-version request |
|
|
645
|
-
| `PI_TELEMETRY` | Override install/update telemetry and provider attribution headers. Use `1`/`true`/`yes` to enable or `0`/`false`/`no` to disable. This does not disable update checks |
|
|
646
|
-
| `PI_CACHE_RETENTION` | Set to `long` for extended prompt cache (Anthropic: 1h, OpenAI: 24h) |
|
|
647
|
-
| `VISUAL`, `EDITOR` | External editor for Ctrl+G |
|
|
87
|
+
**Koda adds, on top of Pi:**
|
|
88
|
+
- OpenAdapter integration (one key → many tiered models) and the first-run setup.
|
|
89
|
+
- The reliability layer — zenitsu never-idle rerouting, model failover, run-it verification, the overseer + escalation, heal-don't-crash, poison guard.
|
|
90
|
+
- Ask & suggest, the vision bridge, session import from Claude Code & OpenCode.
|
|
91
|
+
- Auto-update + daily model refresh, the resume hint, contextual tips, recap, and the live status UX.
|
|
648
92
|
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
## Contributing & Development
|
|
652
|
-
|
|
653
|
-
See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines and [docs/development.md](docs/development.md) for setup, forking, and debugging.
|
|
654
|
-
|
|
655
|
-
---
|
|
93
|
+
Thank you to the Pi project and its contributors.
|
|
656
94
|
|
|
657
95
|
## License
|
|
658
96
|
|
|
659
|
-
MIT
|
|
660
|
-
|
|
661
|
-
## See Also
|
|
662
|
-
|
|
663
|
-
- [@openadapter/koda-ai](https://www.npmjs.com/package/@openadapter/koda-ai): Core LLM toolkit
|
|
664
|
-
- [@openadapter/koda-agent-core](https://www.npmjs.com/package/@openadapter/koda-agent-core): Agent framework
|
|
665
|
-
- [@openadapter/koda-tui](https://www.npmjs.com/package/@openadapter/koda-tui): Terminal UI components
|
|
97
|
+
MIT — see [LICENSE](../../LICENSE). Copyright © Mario Zechner (original "pi" project) and OpenAdapter (the "Koda" fork).
|
|
@@ -376,6 +376,7 @@ export declare class AgentSession {
|
|
|
376
376
|
private _normalizePromptSnippet;
|
|
377
377
|
private _normalizePromptGuidelines;
|
|
378
378
|
private _rebuildSystemPrompt;
|
|
379
|
+
private _continueWithHeal;
|
|
379
380
|
private _runAgentPrompt;
|
|
380
381
|
private _generateRecap;
|
|
381
382
|
private _recapOnce;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var J=Object.defineProperty;var f=(E,e)=>J(E,"name",{value:e,configurable:!0});import{existsSync as k,mkdirSync as D,readFileSync as T,unlinkSync as Q,writeFileSync as L}from"node:fs";import{homedir as Y}from"node:os";import{basename as Z,dirname as U,join as S,relative as X,resolve as K}from"node:path";import{clampThinkingLevel as ee,cleanupSessionResources as te,getSupportedThinkingLevels as se,isContextOverflow as $,modelsAreEqual as C,resetApiProviders as ne,streamSimple as B}from"@openadapter/koda-ai";import{theme as ie}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as F}from"../utils/frontmatter.js";import{resolvePath as re}from"../utils/paths.js";import{sleep as oe}from"../utils/sleep.js";import{formatNoApiKeyFoundMessage as O,formatNoModelSelectedMessage as H}from"./auth-guidance.js";import{executeBashWithOperations as ae}from"./bash-executor.js";import{calculateContextTokens as z,collectEntriesForBranchSummary as le,compact as j,estimateContextTokens as G,generateBranchSummary as ce,prepareCompaction as q,shouldCompact as he}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as de}from"./defaults.js";import{execCommand as ue}from"./exec.js";import{exportSessionToHtml as me}from"./export-html/index.js";import{createToolHtmlRenderer as ge}from"./export-html/tool-renderer.js";import{ExtensionRunner as pe,wrapRegisteredTools as W}from"./extensions/index.js";import{emitSessionShutdownEvent as fe}from"./extensions/runner.js";import{expandPromptTemplate as N}from"./prompt-templates.js";import{CURRENT_SESSION_VERSION as _e,getLatestCompactionEntry as V}from"./session-manager.js";import{createSyntheticSourceInfo as I}from"./source-info.js";import{buildSystemPrompt as ye}from"./system-prompt.js";import{createLocalBashOperations as we}from"./tools/bash.js";import{createAllToolDefinitions as xe}from"./tools/index.js";import{createToolDefinitionFromAgentTool as be}from"./tools/tool-definition-wrapper.js";function Ve(E){const e=E.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}f(Ve,"parseSkillBlock");const ve=["off","minimal","low","medium","high"];class Je{static{f(this,"AgentSession")}agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_branchSummaryAbortController=void 0;_retryAbortController=void 0;_retryAttempt=0;_overseerAbortController=void 0;_failoverTried=new Set;get _zenitsu(){return process.env.KODA_ZENITSU==="1"}_zenitsuPreferred;_zenitsuCooldown=new Map;_zenitsuHealthCache;_overseerRounds=0;_currentGoal;_tierCache;_overseerLastError="";_escalationsDone=0;_escalateTried=new Set;_sessionEscalations=0;_stickyModel;_homeModel;_sessionGoal;_pinnedSkills=new Map;_codeChangedThisTask=!1;_verifyCmd;_taskStartTs=0;_taskHadActivity=!1;_suggestShown=new Set;_suggestedThisTask=!1;_harnessTrace=[];_gatewayCircuit={failures:0,openUntil:0};_bashAbortController=void 0;_pendingBashMessages=[];_extensionRunner;_turnIndex=0;_resourceLoader;_customTools;_baseToolDefinitions=new Map;_cwd;_protectedSnap=new Map;_extensionRunnerRef;_initialActiveToolNames;_allowedToolNames;_excludedToolNames;_baseToolsOverride;_sessionStartEvent;_extensionUIContext;_extensionMode="print";_extensionCommandContextActions;_extensionAbortHandler;_extensionShutdownHandler;_extensionErrorListener;_extensionErrorUnsubscriber;_modelRegistry;_toolRegistry=new Map;_toolDefinitions=new Map;_toolPromptSnippets=new Map;_toolPromptGuidelines=new Map;_baseSystemPrompt="";_baseSystemPromptOptions;constructor(e){this.agent=e.agent,this.sessionManager=e.sessionManager,this.settingsManager=e.settingsManager,this._scopedModels=e.scopedModels??[],this._resourceLoader=e.resourceLoader,this._customTools=e.customTools??[],this._cwd=e.cwd,this._modelRegistry=e.modelRegistry,this._extensionRunnerRef=e.extensionRunnerRef,this._initialActiveToolNames=e.initialActiveToolNames,this._allowedToolNames=e.allowedToolNames?new Set(e.allowedToolNames):void 0,this._excludedToolNames=e.excludedToolNames?new Set(e.excludedToolNames):void 0,this._baseToolsOverride=e.baseToolsOverride,this._sessionStartEvent=e.sessionStartEvent??{type:"session_start",reason:"startup"},this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._installAgentToolHooks(),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0})}get modelRegistry(){return this._modelRegistry}async _getRequiredRequestAuth(e){const t=await this._modelRegistry.getApiKeyAndHeaders(e);if(!t.ok)throw t.error.startsWith("No API key found")?new Error(O(e.provider)):new Error(t.error);if(t.apiKey)return{apiKey:t.apiKey,headers:t.headers};throw this._modelRegistry.isUsingOAuth(e)?new Error(`Authentication failed for "${e.provider}". Credentials may have expired or network is unavailable. Run '/login ${e.provider}' to re-authenticate.`):new Error(O(e.provider))}async _getCompactionRequestAuth(e){if(this.agent.streamFn===B)return this._getRequiredRequestAuth(e);const t=await this._modelRegistry.getApiKeyAndHeaders(e);return t.ok?{apiKey:t.apiKey,headers:t.headers}:{}}_installAgentToolHooks(){const e=process.env.KODA_UNSAFE==="1",t=process.cwd(),s=[/(^|\/)test_[^/]*\.[A-Za-z0-9]+$/,/(^|\/)[^/]*_test\.[A-Za-z0-9]+$/,/\.(test|spec)\.[A-Za-z0-9]+$/,/(^|\/)(tests?|__tests__|spec)\//,/(^|\/)\.git(\/|$)/,/(^|\/)\.env(\.[^/]*)?$/,/(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Cargo\.lock)$/],n=(process.env.KODA_PROTECT||"").split(",").map(g=>g.trim()).filter(Boolean),i=f(g=>{const p=g.replace(/\\/g,"/");return s.some(_=>_.test(p))||n.some(_=>p.includes(_))},"isProtected"),o=f(g=>{for(const p of g.matchAll(/(?:>>?|\btee\s+(?:-a\s+)?)\s*([^\s;|&>]+)/g))if(i(p[1]))return`output redirect onto protected file '${p[1]}'`;return/\brm\s+(?:-\w+\s+)*[^\n;|&]*(?:test_|tests?\/|__tests__|\.git|\.env)/.test(g)?"rm targeting a protected path":/\bgit\s+(?:reset\s+--hard|clean\b|checkout\s+(?:--\s+)?\.)/.test(g)?"destructive git command":null},"dangerousBash"),r=S(process.env.KODA_CODING_AGENT_DIR||S(Y(),".koda","agent"),"checkpoints",String(this.sessionId||"session")),a=new Set,l=f(g=>{if(!a.has(g)){a.add(g);try{D(r,{recursive:!0});const p=S(r,`${g.replace(/[^A-Za-z0-9]/g,"_")}.json`),_=k(g);L(p,JSON.stringify({path:g,existed:_,content:_?T(g,"utf-8"):null}))}catch{}}},"backup");this.agent.beforeToolCall=async({toolCall:g,args:p})=>{if((g.name==="write"||g.name==="edit")&&(this._codeChangedThisTask=!0),this._taskHadActivity=!0,g.name==="bash"){const b=String(p?.command??"");/\b(npm|pnpm|yarn|bun)\s+(run\s+)?(dev|start|serve|preview|watch)\b|\bvite\b|\bnext\s+(dev|start)\b|\bnuxt\s+dev\b|\bnodemon\b|http[-.]server\b|\bserve\b|flask\s+run|rails\s+s(erver)?\b|manage\.py\s+runserver|\b(uvicorn|gunicorn)\b/i.test(b)&&this._suggest("bg","That looks like a long-running server. Use run_background (or /bg) so it keeps running without blocking Koda.")}if(process.env.KODA_MODE==="plan"){const b=p,v=g.name;if(v==="write"||v==="edit")return{block:!0,reason:"Koda is in PLAN MODE \u2014 file changes are disabled. Investigate and present a step-by-step plan instead; the user will run /build to execute it."};if(v==="bash"&&this._isMutatingBash(String(b?.command??"")))return{block:!0,reason:"Koda is in PLAN MODE \u2014 commands that change state are disabled. Use read-only commands to investigate, then present a plan; the user will run /build to execute it."}}if(!e){const b=p,v=g.name;if(v==="write"||v==="edit"){const y=String(b?.path??b?.file_path??"");if(y){const M=K(t,y);if(X(t,M).startsWith(".."))return{block:!0,reason:`Refused: '${y}' is outside the workspace. Only modify files under the project directory.`};if(i(y))return{block:!0,reason:`Refused: '${y}' is a protected file (tests / .git / secrets / lockfiles). Do not modify it \u2014 change the source code instead.`};l(M)}}else if(v==="bash"){const y=o(String(b?.command??""));if(y)return{block:!0,reason:`Refused: ${y}. Use the edit/write tools on source files instead of shell redirects, and never touch tests/.git/secrets.`}}const A=[];if(v==="write"||v==="edit"){const y=String(b?.path??b?.file_path??"");y&&A.push(y)}else if(v==="bash")for(const y of String(b?.command??"").matchAll(/[\w./-]*[\w]\.[A-Za-z0-9]+/g))A.push(y[0]);for(const y of A){if(!i(y))continue;const M=K(t,y);if(!this._protectedSnap.has(M))try{this._protectedSnap.set(M,k(M)?T(M,"utf-8"):null)}catch{}}}const _=this._extensionRunner;if(_.hasHandlers("tool_call"))try{return await _.emitToolCall({type:"tool_call",toolName:g.name,toolCallId:g.id,input:p})}catch(b){throw b instanceof Error?b:new Error(`Extension failed, blocking execution: ${String(b)}`)}};const c=process.env.KODA_CASCADE_MODEL,h=Number(process.env.KODA_CASCADE_ERRORS)||3,u=Number(process.env.KODA_CASCADE_STEPS)||16;let m=0,w=0,d=!1,x;this.agent.afterToolCall=async({toolCall:g,args:p,result:_,isError:b})=>{for(const[y,M]of this._protectedSnap){let P=null;try{P=k(y)?T(y,"utf-8"):null}catch{continue}if(P!==M)try{M===null?k(y)&&Q(y):L(y,M,"utf-8"),console.error(`[koda safety] reverted unauthorized change to protected file ${y}`)}catch{}}if(c&&!d&&(w++,b?m++:m=0,m>=h||w>=u)){const y=this.agent.state.model,[M,P]=c.includes("/")?[c.slice(0,c.indexOf("/")),c.slice(c.indexOf("/")+1)]:[y.provider,c],R=this._modelRegistry.find(M,P);R&&!C(R,y)&&(x=R,this.agent.state.model=R,this.sessionManager.appendModelChange(R.provider,R.id),this._emitModelSelect(R,y,"cycle"),d=!0,console.error(`[koda cascade] escalated ${y.provider}/${y.id} \u2192 ${R.provider}/${R.id} (errors=${m}, toolCalls=${w})`))}const v=this._extensionRunner;if(!v.hasHandlers("tool_result"))return;const A=await v.emitToolResult({type:"tool_result",toolName:g.name,toolCallId:g.id,input:p,content:_.content,details:_.details,isError:b});if(A)return{content:A.content,details:A.details,isError:A.isError??b}},this.agent.prepareNextTurn=async()=>{if(this._zenitsu){const g=await this._zenitsuPickModel();if(g&&!C(g,this.agent.state.model))return{model:g}}return d&&x?{model:x}:void 0}}_emit(e){for(const t of this._eventListeners)t(e)}_emitQueueUpdate(){this._emit({type:"queue_update",steering:[...this._steeringMessages],followUp:[...this._followUpMessages]})}_lastAssistantMessage=void 0;_handleAgentEvent=f(async e=>{if(e.type==="message_start"&&e.message.role==="user"){this._overflowRecoveryAttempted=!1;const t=this._getUserMessageText(e.message);if(t){const s=this._steeringMessages.indexOf(t);if(s!==-1)this._steeringMessages.splice(s,1),this._emitQueueUpdate();else{const n=this._followUpMessages.indexOf(t);n!==-1&&(this._followUpMessages.splice(n,1),this._emitQueueUpdate())}}}if(await this._emitExtensionEvent(e),this._emit(e.type==="agent_end"?{...e,willRetry:this._willRetryAfterAgentEnd(e)}:e),e.type==="message_end"&&(e.message.role==="custom"?this.sessionManager.appendCustomMessageEntry(e.message.customType,e.message.content,e.message.display,e.message.details):(e.message.role==="user"||e.message.role==="assistant"||e.message.role==="toolResult")&&this.sessionManager.appendMessage(e.message),e.message.role==="assistant")){this._lastAssistantMessage=e.message;const t=e.message;t.stopReason!=="error"&&(this._overflowRecoveryAttempted=!1),t.stopReason!=="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!0,attempt:this._retryAttempt}),this._retryAttempt=0)}},"_handleAgentEvent");_willRetryAfterAgentEnd(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled||this._retryAttempt>=t.maxRetries)return!1;for(let s=e.messages.length-1;s>=0;s--){const n=e.messages[s];if(n.role==="assistant")return this._isRetryableError(n)}return!1}_getUserMessageText(e){if(e.role!=="user")return"";const t=e.content;return typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.text).join("")}_findLastAssistantMessage(){const e=this.agent.state.messages;for(let t=e.length-1;t>=0;t--){const s=e[t];if(s.role==="assistant")return s}}_replaceMessageInPlace(e,t){if(e===t)return;const s=e;for(const n of Object.keys(s))delete s[n];Object.assign(s,t)}async _emitExtensionEvent(e){if(e.type==="agent_start")this._turnIndex=0,await this._extensionRunner.emit({type:"agent_start"});else if(e.type==="agent_end")await this._extensionRunner.emit({type:"agent_end",messages:e.messages});else if(e.type==="turn_start"){const t={type:"turn_start",turnIndex:this._turnIndex,timestamp:Date.now()};await this._extensionRunner.emit(t)}else if(e.type==="turn_end"){const t={type:"turn_end",turnIndex:this._turnIndex,message:e.message,toolResults:e.toolResults};await this._extensionRunner.emit(t),this._turnIndex++}else if(e.type==="message_start"){const t={type:"message_start",message:e.message};await this._extensionRunner.emit(t)}else if(e.type==="message_update"){const t={type:"message_update",message:e.message,assistantMessageEvent:e.assistantMessageEvent};await this._extensionRunner.emit(t)}else if(e.type==="message_end"){const t={type:"message_end",message:e.message},s=await this._extensionRunner.emitMessageEnd(t);s&&this._replaceMessageInPlace(e.message,s)}else if(e.type==="tool_execution_start"){const t={type:"tool_execution_start",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_update"){const t={type:"tool_execution_update",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_end"){const t={type:"tool_execution_end",toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError};await this._extensionRunner.emit(t)}}subscribe(e){return this._eventListeners.push(e),()=>{const t=this._eventListeners.indexOf(e);t!==-1&&this._eventListeners.splice(t,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}_reconnectToAgent(){this._unsubscribeAgent||(this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent))}dispose(){try{this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort()}catch{}this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."),this._disconnectFromAgent(),this._eventListeners=[],te(this.sessionId)}get state(){return this.agent.state}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get isStreaming(){return this.agent.state.isStreaming}get systemPrompt(){return this.agent.state.systemPrompt}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}getAllTools(){return Array.from(this._toolDefinitions.values()).map(({definition:e,sourceInfo:t})=>({name:e.name,description:e.description,parameters:e.parameters,promptGuidelines:e.promptGuidelines,sourceInfo:t}))}getToolDefinition(e){return this._toolDefinitions.get(e)?.definition}setActiveToolsByName(e){const t=[],s=[];for(const n of e){const i=this._toolRegistry.get(n);i&&(t.push(i),s.push(n))}this.agent.state.tools=t,this._baseSystemPrompt=this._rebuildSystemPrompt(s),this.agent.state.systemPrompt=this._baseSystemPrompt}get isCompacting(){return this._autoCompactionAbortController!==void 0||this._compactionAbortController!==void 0||this._branchSummaryAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionFile(){return this.sessionManager.getSessionFile()}get sessionId(){return this.sessionManager.getSessionId()}get sessionName(){return this.sessionManager.getSessionName()}get scopedModels(){return this._scopedModels}setScopedModels(e){this._scopedModels=e}get promptTemplates(){return this._resourceLoader.getPrompts().prompts}_normalizePromptSnippet(e){if(!e)return;const t=e.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();return t.length>0?t:void 0}_normalizePromptGuidelines(e){if(!e||e.length===0)return[];const t=new Set;for(const s of e){const n=s.trim();n.length>0&&t.add(n)}return Array.from(t)}_rebuildSystemPrompt(e){const t=e.filter(h=>this._toolRegistry.has(h)),s={},n=[];for(const h of t){const u=this._toolPromptSnippets.get(h);u&&(s[h]=u);const m=this._toolPromptGuidelines.get(h);m&&n.push(...m)}const i=this._resourceLoader.getSystemPrompt(),r=[...this._resourceLoader.getAppendSystemPrompt(),...this._pinnedSkills.values()],a=r.length>0?r.join(`
|
|
1
|
+
var J=Object.defineProperty;var f=(E,e)=>J(E,"name",{value:e,configurable:!0});import{existsSync as k,mkdirSync as D,readFileSync as T,unlinkSync as Q,writeFileSync as L}from"node:fs";import{homedir as Y}from"node:os";import{basename as Z,dirname as U,join as S,relative as X,resolve as K}from"node:path";import{clampThinkingLevel as ee,cleanupSessionResources as te,getSupportedThinkingLevels as se,isContextOverflow as $,modelsAreEqual as C,resetApiProviders as ne,streamSimple as B}from"@openadapter/koda-ai";import{theme as ie}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as F}from"../utils/frontmatter.js";import{resolvePath as re}from"../utils/paths.js";import{sleep as oe}from"../utils/sleep.js";import{formatNoApiKeyFoundMessage as O,formatNoModelSelectedMessage as H}from"./auth-guidance.js";import{executeBashWithOperations as ae}from"./bash-executor.js";import{calculateContextTokens as z,collectEntriesForBranchSummary as le,compact as j,estimateContextTokens as G,generateBranchSummary as ce,prepareCompaction as W,shouldCompact as he}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as de}from"./defaults.js";import{execCommand as ue}from"./exec.js";import{exportSessionToHtml as me}from"./export-html/index.js";import{createToolHtmlRenderer as ge}from"./export-html/tool-renderer.js";import{ExtensionRunner as pe,wrapRegisteredTools as q}from"./extensions/index.js";import{emitSessionShutdownEvent as fe}from"./extensions/runner.js";import{expandPromptTemplate as N}from"./prompt-templates.js";import{CURRENT_SESSION_VERSION as _e,getLatestCompactionEntry as V}from"./session-manager.js";import{createSyntheticSourceInfo as I}from"./source-info.js";import{buildSystemPrompt as ye}from"./system-prompt.js";import{createLocalBashOperations as we}from"./tools/bash.js";import{createAllToolDefinitions as xe}from"./tools/index.js";import{createToolDefinitionFromAgentTool as be}from"./tools/tool-definition-wrapper.js";function Ve(E){const e=E.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}f(Ve,"parseSkillBlock");const ve=["off","minimal","low","medium","high"];class Je{static{f(this,"AgentSession")}agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_branchSummaryAbortController=void 0;_retryAbortController=void 0;_retryAttempt=0;_overseerAbortController=void 0;_failoverTried=new Set;get _zenitsu(){return process.env.KODA_ZENITSU==="1"}_zenitsuPreferred;_zenitsuCooldown=new Map;_zenitsuHealthCache;_overseerRounds=0;_currentGoal;_tierCache;_overseerLastError="";_escalationsDone=0;_escalateTried=new Set;_sessionEscalations=0;_stickyModel;_homeModel;_sessionGoal;_pinnedSkills=new Map;_codeChangedThisTask=!1;_verifyCmd;_taskStartTs=0;_taskHadActivity=!1;_suggestShown=new Set;_suggestedThisTask=!1;_harnessTrace=[];_gatewayCircuit={failures:0,openUntil:0};_bashAbortController=void 0;_pendingBashMessages=[];_extensionRunner;_turnIndex=0;_resourceLoader;_customTools;_baseToolDefinitions=new Map;_cwd;_protectedSnap=new Map;_extensionRunnerRef;_initialActiveToolNames;_allowedToolNames;_excludedToolNames;_baseToolsOverride;_sessionStartEvent;_extensionUIContext;_extensionMode="print";_extensionCommandContextActions;_extensionAbortHandler;_extensionShutdownHandler;_extensionErrorListener;_extensionErrorUnsubscriber;_modelRegistry;_toolRegistry=new Map;_toolDefinitions=new Map;_toolPromptSnippets=new Map;_toolPromptGuidelines=new Map;_baseSystemPrompt="";_baseSystemPromptOptions;constructor(e){this.agent=e.agent,this.sessionManager=e.sessionManager,this.settingsManager=e.settingsManager,this._scopedModels=e.scopedModels??[],this._resourceLoader=e.resourceLoader,this._customTools=e.customTools??[],this._cwd=e.cwd,this._modelRegistry=e.modelRegistry,this._extensionRunnerRef=e.extensionRunnerRef,this._initialActiveToolNames=e.initialActiveToolNames,this._allowedToolNames=e.allowedToolNames?new Set(e.allowedToolNames):void 0,this._excludedToolNames=e.excludedToolNames?new Set(e.excludedToolNames):void 0,this._baseToolsOverride=e.baseToolsOverride,this._sessionStartEvent=e.sessionStartEvent??{type:"session_start",reason:"startup"},this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._installAgentToolHooks(),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0})}get modelRegistry(){return this._modelRegistry}async _getRequiredRequestAuth(e){const t=await this._modelRegistry.getApiKeyAndHeaders(e);if(!t.ok)throw t.error.startsWith("No API key found")?new Error(O(e.provider)):new Error(t.error);if(t.apiKey)return{apiKey:t.apiKey,headers:t.headers};throw this._modelRegistry.isUsingOAuth(e)?new Error(`Authentication failed for "${e.provider}". Credentials may have expired or network is unavailable. Run '/login ${e.provider}' to re-authenticate.`):new Error(O(e.provider))}async _getCompactionRequestAuth(e){if(this.agent.streamFn===B)return this._getRequiredRequestAuth(e);const t=await this._modelRegistry.getApiKeyAndHeaders(e);return t.ok?{apiKey:t.apiKey,headers:t.headers}:{}}_installAgentToolHooks(){const e=process.env.KODA_UNSAFE==="1",t=process.cwd(),s=[/(^|\/)test_[^/]*\.[A-Za-z0-9]+$/,/(^|\/)[^/]*_test\.[A-Za-z0-9]+$/,/\.(test|spec)\.[A-Za-z0-9]+$/,/(^|\/)(tests?|__tests__|spec)\//,/(^|\/)\.git(\/|$)/,/(^|\/)\.env(\.[^/]*)?$/,/(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Cargo\.lock)$/],n=(process.env.KODA_PROTECT||"").split(",").map(g=>g.trim()).filter(Boolean),i=f(g=>{const p=g.replace(/\\/g,"/");return s.some(_=>_.test(p))||n.some(_=>p.includes(_))},"isProtected"),o=f(g=>{for(const p of g.matchAll(/(?:>>?|\btee\s+(?:-a\s+)?)\s*([^\s;|&>]+)/g))if(i(p[1]))return`output redirect onto protected file '${p[1]}'`;return/\brm\s+(?:-\w+\s+)*[^\n;|&]*(?:test_|tests?\/|__tests__|\.git|\.env)/.test(g)?"rm targeting a protected path":/\bgit\s+(?:reset\s+--hard|clean\b|checkout\s+(?:--\s+)?\.)/.test(g)?"destructive git command":null},"dangerousBash"),r=S(process.env.KODA_CODING_AGENT_DIR||S(Y(),".koda","agent"),"checkpoints",String(this.sessionId||"session")),a=new Set,l=f(g=>{if(!a.has(g)){a.add(g);try{D(r,{recursive:!0});const p=S(r,`${g.replace(/[^A-Za-z0-9]/g,"_")}.json`),_=k(g);L(p,JSON.stringify({path:g,existed:_,content:_?T(g,"utf-8"):null}))}catch{}}},"backup");this.agent.beforeToolCall=async({toolCall:g,args:p})=>{if((g.name==="write"||g.name==="edit")&&(this._codeChangedThisTask=!0),this._taskHadActivity=!0,g.name==="bash"){const b=String(p?.command??"");/\b(npm|pnpm|yarn|bun)\s+(run\s+)?(dev|start|serve|preview|watch)\b|\bvite\b|\bnext\s+(dev|start)\b|\bnuxt\s+dev\b|\bnodemon\b|http[-.]server\b|\bserve\b|flask\s+run|rails\s+s(erver)?\b|manage\.py\s+runserver|\b(uvicorn|gunicorn)\b/i.test(b)&&this._suggest("bg","That looks like a long-running server. Use run_background (or /bg) so it keeps running without blocking Koda.")}if(process.env.KODA_MODE==="plan"){const b=p,v=g.name;if(v==="write"||v==="edit")return{block:!0,reason:"Koda is in PLAN MODE \u2014 file changes are disabled. Investigate and present a step-by-step plan instead; the user will run /build to execute it."};if(v==="bash"&&this._isMutatingBash(String(b?.command??"")))return{block:!0,reason:"Koda is in PLAN MODE \u2014 commands that change state are disabled. Use read-only commands to investigate, then present a plan; the user will run /build to execute it."}}if(!e){const b=p,v=g.name;if(v==="write"||v==="edit"){const y=String(b?.path??b?.file_path??"");if(y){const M=K(t,y);if(X(t,M).startsWith(".."))return{block:!0,reason:`Refused: '${y}' is outside the workspace. Only modify files under the project directory.`};if(i(y))return{block:!0,reason:`Refused: '${y}' is a protected file (tests / .git / secrets / lockfiles). Do not modify it \u2014 change the source code instead.`};l(M)}}else if(v==="bash"){const y=o(String(b?.command??""));if(y)return{block:!0,reason:`Refused: ${y}. Use the edit/write tools on source files instead of shell redirects, and never touch tests/.git/secrets.`}}const A=[];if(v==="write"||v==="edit"){const y=String(b?.path??b?.file_path??"");y&&A.push(y)}else if(v==="bash")for(const y of String(b?.command??"").matchAll(/[\w./-]*[\w]\.[A-Za-z0-9]+/g))A.push(y[0]);for(const y of A){if(!i(y))continue;const M=K(t,y);if(!this._protectedSnap.has(M))try{this._protectedSnap.set(M,k(M)?T(M,"utf-8"):null)}catch{}}}const _=this._extensionRunner;if(_.hasHandlers("tool_call"))try{return await _.emitToolCall({type:"tool_call",toolName:g.name,toolCallId:g.id,input:p})}catch(b){throw b instanceof Error?b:new Error(`Extension failed, blocking execution: ${String(b)}`)}};const c=process.env.KODA_CASCADE_MODEL,h=Number(process.env.KODA_CASCADE_ERRORS)||3,u=Number(process.env.KODA_CASCADE_STEPS)||16;let m=0,w=0,d=!1,x;this.agent.afterToolCall=async({toolCall:g,args:p,result:_,isError:b})=>{for(const[y,M]of this._protectedSnap){let P=null;try{P=k(y)?T(y,"utf-8"):null}catch{continue}if(P!==M)try{M===null?k(y)&&Q(y):L(y,M,"utf-8"),console.error(`[koda safety] reverted unauthorized change to protected file ${y}`)}catch{}}if(c&&!d&&(w++,b?m++:m=0,m>=h||w>=u)){const y=this.agent.state.model,[M,P]=c.includes("/")?[c.slice(0,c.indexOf("/")),c.slice(c.indexOf("/")+1)]:[y.provider,c],R=this._modelRegistry.find(M,P);R&&!C(R,y)&&(x=R,this.agent.state.model=R,this.sessionManager.appendModelChange(R.provider,R.id),this._emitModelSelect(R,y,"cycle"),d=!0,console.error(`[koda cascade] escalated ${y.provider}/${y.id} \u2192 ${R.provider}/${R.id} (errors=${m}, toolCalls=${w})`))}const v=this._extensionRunner;if(!v.hasHandlers("tool_result"))return;const A=await v.emitToolResult({type:"tool_result",toolName:g.name,toolCallId:g.id,input:p,content:_.content,details:_.details,isError:b});if(A)return{content:A.content,details:A.details,isError:A.isError??b}},this.agent.prepareNextTurn=async()=>{if(this._zenitsu){const g=await this._zenitsuPickModel();if(g&&!C(g,this.agent.state.model))return{model:g}}return d&&x?{model:x}:void 0}}_emit(e){for(const t of this._eventListeners)t(e)}_emitQueueUpdate(){this._emit({type:"queue_update",steering:[...this._steeringMessages],followUp:[...this._followUpMessages]})}_lastAssistantMessage=void 0;_handleAgentEvent=f(async e=>{if(e.type==="message_start"&&e.message.role==="user"){this._overflowRecoveryAttempted=!1;const t=this._getUserMessageText(e.message);if(t){const s=this._steeringMessages.indexOf(t);if(s!==-1)this._steeringMessages.splice(s,1),this._emitQueueUpdate();else{const n=this._followUpMessages.indexOf(t);n!==-1&&(this._followUpMessages.splice(n,1),this._emitQueueUpdate())}}}if(await this._emitExtensionEvent(e),this._emit(e.type==="agent_end"?{...e,willRetry:this._willRetryAfterAgentEnd(e)}:e),e.type==="message_end"&&(e.message.role==="custom"?this.sessionManager.appendCustomMessageEntry(e.message.customType,e.message.content,e.message.display,e.message.details):(e.message.role==="user"||e.message.role==="assistant"||e.message.role==="toolResult")&&this.sessionManager.appendMessage(e.message),e.message.role==="assistant")){this._lastAssistantMessage=e.message;const t=e.message;t.stopReason!=="error"&&(this._overflowRecoveryAttempted=!1),t.stopReason!=="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!0,attempt:this._retryAttempt}),this._retryAttempt=0)}},"_handleAgentEvent");_willRetryAfterAgentEnd(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled||this._retryAttempt>=t.maxRetries)return!1;for(let s=e.messages.length-1;s>=0;s--){const n=e.messages[s];if(n.role==="assistant")return this._isRetryableError(n)}return!1}_getUserMessageText(e){if(e.role!=="user")return"";const t=e.content;return typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.text).join("")}_findLastAssistantMessage(){const e=this.agent.state.messages;for(let t=e.length-1;t>=0;t--){const s=e[t];if(s.role==="assistant")return s}}_replaceMessageInPlace(e,t){if(e===t)return;const s=e;for(const n of Object.keys(s))delete s[n];Object.assign(s,t)}async _emitExtensionEvent(e){if(e.type==="agent_start")this._turnIndex=0,await this._extensionRunner.emit({type:"agent_start"});else if(e.type==="agent_end")await this._extensionRunner.emit({type:"agent_end",messages:e.messages});else if(e.type==="turn_start"){const t={type:"turn_start",turnIndex:this._turnIndex,timestamp:Date.now()};await this._extensionRunner.emit(t)}else if(e.type==="turn_end"){const t={type:"turn_end",turnIndex:this._turnIndex,message:e.message,toolResults:e.toolResults};await this._extensionRunner.emit(t),this._turnIndex++}else if(e.type==="message_start"){const t={type:"message_start",message:e.message};await this._extensionRunner.emit(t)}else if(e.type==="message_update"){const t={type:"message_update",message:e.message,assistantMessageEvent:e.assistantMessageEvent};await this._extensionRunner.emit(t)}else if(e.type==="message_end"){const t={type:"message_end",message:e.message},s=await this._extensionRunner.emitMessageEnd(t);s&&this._replaceMessageInPlace(e.message,s)}else if(e.type==="tool_execution_start"){const t={type:"tool_execution_start",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_update"){const t={type:"tool_execution_update",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_end"){const t={type:"tool_execution_end",toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError};await this._extensionRunner.emit(t)}}subscribe(e){return this._eventListeners.push(e),()=>{const t=this._eventListeners.indexOf(e);t!==-1&&this._eventListeners.splice(t,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}_reconnectToAgent(){this._unsubscribeAgent||(this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent))}dispose(){try{this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort()}catch{}this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."),this._disconnectFromAgent(),this._eventListeners=[],te(this.sessionId)}get state(){return this.agent.state}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get isStreaming(){return this.agent.state.isStreaming}get systemPrompt(){return this.agent.state.systemPrompt}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}getAllTools(){return Array.from(this._toolDefinitions.values()).map(({definition:e,sourceInfo:t})=>({name:e.name,description:e.description,parameters:e.parameters,promptGuidelines:e.promptGuidelines,sourceInfo:t}))}getToolDefinition(e){return this._toolDefinitions.get(e)?.definition}setActiveToolsByName(e){const t=[],s=[];for(const n of e){const i=this._toolRegistry.get(n);i&&(t.push(i),s.push(n))}this.agent.state.tools=t,this._baseSystemPrompt=this._rebuildSystemPrompt(s),this.agent.state.systemPrompt=this._baseSystemPrompt}get isCompacting(){return this._autoCompactionAbortController!==void 0||this._compactionAbortController!==void 0||this._branchSummaryAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionFile(){return this.sessionManager.getSessionFile()}get sessionId(){return this.sessionManager.getSessionId()}get sessionName(){return this.sessionManager.getSessionName()}get scopedModels(){return this._scopedModels}setScopedModels(e){this._scopedModels=e}get promptTemplates(){return this._resourceLoader.getPrompts().prompts}_normalizePromptSnippet(e){if(!e)return;const t=e.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();return t.length>0?t:void 0}_normalizePromptGuidelines(e){if(!e||e.length===0)return[];const t=new Set;for(const s of e){const n=s.trim();n.length>0&&t.add(n)}return Array.from(t)}_rebuildSystemPrompt(e){const t=e.filter(h=>this._toolRegistry.has(h)),s={},n=[];for(const h of t){const u=this._toolPromptSnippets.get(h);u&&(s[h]=u);const m=this._toolPromptGuidelines.get(h);m&&n.push(...m)}const i=this._resourceLoader.getSystemPrompt(),r=[...this._resourceLoader.getAppendSystemPrompt(),...this._pinnedSkills.values()],a=r.length>0?r.join(`
|
|
2
2
|
|
|
3
|
-
`):void 0,l=this._resourceLoader.getSkills().skills,c=this._resourceLoader.getAgentsFiles().agentsFiles;return this._baseSystemPromptOptions={cwd:this._cwd,skills:l,contextFiles:c,customPrompt:i,appendSystemPrompt:a,selectedTools:t,toolSnippets:s,promptGuidelines:n},ye(this._baseSystemPromptOptions)}async _runAgentPrompt(e){this._failoverTried.clear(),this._overseerRounds=0,this._escalationsDone=0,this._escalateTried.clear(),this._codeChangedThisTask=!1,this._taskStartTs=Date.now(),this._taskHadActivity=!1,this._suggestedThisTask=!1;const t=this._goalFromMessages(e);if(t&&(this._currentGoal=t),!this._homeModel)this._homeModel=this.agent.state.model;else{const s=this._stickyModel??this._homeModel;s.id!==this.agent.state.model.id&&this._modelRegistry.hasConfiguredAuth(s)&&(this.agent.state.model=s,this._zenitsuPreferred=s,this._stickyModel||(this._trace("revert",`\u2192 ${s.id} (new task)`),this._emit({type:"model_switch_notice",message:`\u2190 Back on your pick \u2014 ${s.id}`})))}try{
|
|
3
|
+
`):void 0,l=this._resourceLoader.getSkills().skills,c=this._resourceLoader.getAgentsFiles().agentsFiles;return this._baseSystemPromptOptions={cwd:this._cwd,skills:l,contextFiles:c,customPrompt:i,appendSystemPrompt:a,selectedTools:t,toolSnippets:s,promptGuidelines:n},ye(this._baseSystemPromptOptions)}async _continueWithHeal(){try{return await this.agent.continue(),!0}catch(e){const t=e?.message||String(e);if(this._trace("recover",`continue failed: ${t.slice(0,90)}`),/cannot continue from message role/i.test(t)){this.agent.followUp({role:"user",content:[{type:"text",text:"Continue from where you left off and finish the task."}],timestamp:Date.now()});try{return await this.agent.continue(),!0}catch{}}return this._emit({type:"model_switch_notice",message:`Koda hit a snag and stopped cleanly (${t.slice(0,60)}). Your work is saved \u2014 send another message to continue.`}),!1}}async _runAgentPrompt(e){this._failoverTried.clear(),this._overseerRounds=0,this._escalationsDone=0,this._escalateTried.clear(),this._codeChangedThisTask=!1,this._taskStartTs=Date.now(),this._taskHadActivity=!1,this._suggestedThisTask=!1;const t=this._goalFromMessages(e);if(t&&(this._currentGoal=t),!this._homeModel)this._homeModel=this.agent.state.model;else{const s=this._stickyModel??this._homeModel;s.id!==this.agent.state.model.id&&this._modelRegistry.hasConfiguredAuth(s)&&(this.agent.state.model=s,this._zenitsuPreferred=s,this._stickyModel||(this._trace("revert",`\u2192 ${s.id} (new task)`),this._emit({type:"model_switch_notice",message:`\u2190 Back on your pick \u2014 ${s.id}`})))}try{await this.agent.prompt(e);let s=!0;for(;s&&await this._handlePostAgentRun();)s=await this._continueWithHeal();if(this._taskHadActivity&&process.env.KODA_RECAP!=="0"){const n=await this._generateRecap();this._emit({type:"task_recap",elapsedMs:Date.now()-this._taskStartTs,recap:n||""})}for(this._taskHadActivity&&!this._sessionGoal&&Date.now()-this._taskStartTs>18e4&&this._suggest("goal","Working on something big? Set a goal with /goal \u2014 Koda tracks the milestones and won't stop until they're done.");s&&this.agent.hasQueuedMessages();)for(s=await this._continueWithHeal();s&&await this._handlePostAgentRun();)s=await this._continueWithHeal()}finally{this._flushPendingBashMessages()}}async _generateRecap(){const e=this.agent.state.model,t=process.env.KODA_RECAP_MODEL?[process.env.KODA_RECAP_MODEL]:["free/qwen3-coder","free/qwen3-next-80b-a3b-instruct","GLM-4.7-Flash","GLM-4.7"];for(const s of t){const n=this._modelRegistry.find(e.provider,s);if(!n)continue;const i=await this._recapOnce(n);if(i)return i}return null}async _recapOnce(e){try{if(!e.baseUrl)return null;const t=await this._modelRegistry.getApiKeyAndHeaders(e);if(!t?.apiKey)return null;const s=new AbortController,n=setTimeout(()=>s.abort(),2e4);try{const i=await fetch(`${e.baseUrl.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json",...t.headers||{}},body:JSON.stringify({model:e.id,temperature:.2,max_tokens:150,messages:[{role:"system",content:'Output ONLY a 1-2 sentence, past-tense recap of what was done this turn (and the next step if any). No analysis, no numbered lists, no markdown, no preamble \u2014 just the recap. Example: "Added a /health endpoint to server.ts and confirmed the build passes. Next: add a test for it."'},{role:"user",content:`REQUEST:
|
|
4
4
|
${this._currentGoal||"(none)"}
|
|
5
5
|
|
|
6
6
|
WORK LOG:
|
|
@@ -11,7 +11,7 @@ ${r}
|
|
|
11
11
|
</skill>`;return n?`${a}
|
|
12
12
|
|
|
13
13
|
${n}`:a}catch(o){return this._extensionRunner.emitError({extensionPath:i.filePath,event:"skill_expansion",error:o instanceof Error?o.message:String(o)}),e}}async steer(e,t){e.startsWith("/")&&this._throwIfExtensionCommand(e);let s=this._expandSkillCommand(e);s=N(s,[...this.promptTemplates]),await this._queueSteer(s,t)}async followUp(e,t){e.startsWith("/")&&this._throwIfExtensionCommand(e);let s=this._expandSkillCommand(e);s=N(s,[...this.promptTemplates]),await this._queueFollowUp(s,t)}async _queueSteer(e,t){this._steeringMessages.push(e),this._emitQueueUpdate();const s=[{type:"text",text:e}];t&&s.push(...t),this.agent.steer({role:"user",content:s,timestamp:Date.now()})}async _queueFollowUp(e,t){this._followUpMessages.push(e),this._emitQueueUpdate();const s=[{type:"text",text:e}];t&&s.push(...t),this.agent.followUp({role:"user",content:s,timestamp:Date.now()})}_throwIfExtensionCommand(e){const t=e.indexOf(" "),s=t===-1?e.slice(1):e.slice(1,t);if(this._extensionRunner.getCommand(s))throw new Error(`Extension command "/${s}" cannot be queued. Use prompt() or execute the command when not streaming.`)}async sendCustomMessage(e,t){const s={role:"custom",customType:e.customType,content:e.content,display:e.display,details:e.details,timestamp:Date.now()};t?.deliverAs==="nextTurn"?this._pendingNextTurnMessages.push(s):this.isStreaming?t?.deliverAs==="followUp"?this.agent.followUp(s):this.agent.steer(s):t?.triggerTurn?await this._runAgentPrompt(s):(this.agent.state.messages.push(s),this.sessionManager.appendCustomMessageEntry(e.customType,e.content,e.display,e.details),this._emit({type:"message_start",message:s}),this._emit({type:"message_end",message:s}))}async sendUserMessage(e,t){let s,n;if(typeof e=="string")s=e;else{const i=[];n=[];for(const o of e)o.type==="text"?i.push(o.text):n.push(o);s=i.join(`
|
|
14
|
-
`),n.length===0&&(n=void 0)}await this.prompt(s,{expandPromptTemplates:!1,streamingBehavior:t?.deliverAs,images:n,source:"extension"})}clearQueue(){const e=[...this._steeringMessages],t=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering:e,followUp:t}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(){this.abortRetry(),this.agent.abort(),await this.agent.waitForIdle()}async _emitModelSelect(e,t,s){C(t,e)||await this._extensionRunner.emit({type:"model_select",model:e,previousModel:t,source:s})}async setModel(e){if(!this._modelRegistry.hasConfiguredAuth(e))throw new Error(`No API key for ${e.provider}/${e.id}`);const t=this.model,s=this._getThinkingLevelForModelSwitch();this.agent.state.model=e,this._homeModel=e,this._stickyModel=void 0,this._sessionEscalations=0,this.sessionManager.appendModelChange(e.provider,e.id),this.settingsManager.setDefaultModelAndProvider(e.provider,e.id),this.setThinkingLevel(s),await this._emitModelSelect(e,t,"set")}async cycleModel(e="forward"){return this._scopedModels.length>0?this._cycleScopedModel(e):this._cycleAvailableModel(e)}async _cycleScopedModel(e){const t=this._scopedModels.filter(l=>this._modelRegistry.hasConfiguredAuth(l.model));if(t.length<=1)return;const s=this.model;let n=t.findIndex(l=>C(l.model,s));n===-1&&(n=0);const i=t.length,o=e==="forward"?(n+1)%i:(n-1+i)%i,r=t[o],a=this._getThinkingLevelForModelSwitch(r.thinkingLevel);return this.agent.state.model=r.model,this._homeModel=r.model,this._stickyModel=void 0,this._sessionEscalations=0,this.sessionManager.appendModelChange(r.model.provider,r.model.id),this.settingsManager.setDefaultModelAndProvider(r.model.provider,r.model.id),this.setThinkingLevel(a),await this._emitModelSelect(r.model,s,"cycle"),{model:r.model,thinkingLevel:this.thinkingLevel,isScoped:!0}}async _cycleAvailableModel(e){const t=await this._modelRegistry.getAvailable();if(t.length<=1)return;const s=this.model;let n=t.findIndex(l=>C(l,s));n===-1&&(n=0);const i=t.length,o=e==="forward"?(n+1)%i:(n-1+i)%i,r=t[o],a=this._getThinkingLevelForModelSwitch();return this.agent.state.model=r,this._homeModel=r,this._stickyModel=void 0,this._sessionEscalations=0,this.sessionManager.appendModelChange(r.provider,r.id),this.settingsManager.setDefaultModelAndProvider(r.provider,r.id),this.setThinkingLevel(a),await this._emitModelSelect(r,s,"cycle"),{model:r,thinkingLevel:this.thinkingLevel,isScoped:!1}}setThinkingLevel(e){const t=this.getAvailableThinkingLevels(),s=t.includes(e)?e:this._clampThinkingLevel(e,t),n=this.agent.state.thinkingLevel,i=s!==n;this.agent.state.thinkingLevel=s,i&&(this.sessionManager.appendThinkingLevelChange(s),(this.supportsThinking()||s!=="off")&&this.settingsManager.setDefaultThinkingLevel(s),this._emit({type:"thinking_level_changed",level:s}),this._extensionRunner.emit({type:"thinking_level_select",level:s,previousLevel:n}))}cycleThinkingLevel(){if(!this.supportsThinking())return;const e=this.getAvailableThinkingLevels(),s=(e.indexOf(this.thinkingLevel)+1)%e.length,n=e[s];return this.setThinkingLevel(n),n}getAvailableThinkingLevels(){return this.model?se(this.model):ve}supportsThinking(){return!!this.model?.reasoning}_getThinkingLevelForModelSwitch(e){return e!==void 0?e:this.supportsThinking()?this.thinkingLevel:this.settingsManager.getDefaultThinkingLevel()??de}_clampThinkingLevel(e,t){return this.model?ee(this.model,e):"off"}setSteeringMode(e){this.agent.steeringMode=e,this.settingsManager.setSteeringMode(e)}setFollowUpMode(e){this.agent.followUpMode=e,this.settingsManager.setFollowUpMode(e)}async compact(e){this._disconnectFromAgent(),await this.abort(),this._compactionAbortController=new AbortController,this._emit({type:"compaction_start",reason:"manual"});try{if(!this.model)throw new Error(H());const{apiKey:t,headers:s}=await this._getCompactionRequestAuth(this.model),n=this.sessionManager.getBranch(),i=this.settingsManager.getCompactionSettings(),o=q(n,i);if(!o)throw n[n.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let r,a=!1;if(this._extensionRunner.hasHandlers("session_before_compact")){const g=await this._extensionRunner.emit({type:"session_before_compact",preparation:o,branchEntries:n,customInstructions:e,signal:this._compactionAbortController.signal});if(g?.cancel)throw new Error("Compaction cancelled");g?.compaction&&(r=g.compaction,a=!0)}let l,c,h,u;if(r)l=r.summary,c=r.firstKeptEntryId,h=r.tokensBefore,u=r.details;else{const g=await j(o,this.model,t,s,e,this._compactionAbortController.signal,this.thinkingLevel,this.agent.streamFn);l=g.summary,c=g.firstKeptEntryId,h=g.tokensBefore,u=g.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,c,h,u,a);const m=this.sessionManager.getEntries(),w=this.sessionManager.buildSessionContext();this.agent.state.messages=w.messages;const d=m.find(g=>g.type==="compaction"&&g.summary===l);this._extensionRunner&&d&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:d,fromExtension:a});const x={summary:l,firstKeptEntryId:c,tokensBefore:h,details:u};return this._emit({type:"compaction_end",reason:"manual",result:x,aborted:!1,willRetry:!1}),x}catch(t){const s=t instanceof Error?t.message:String(t),n=s==="Compaction cancelled"||t instanceof Error&&t.name==="AbortError";throw this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:n,willRetry:!1,errorMessage:n?void 0:`Compaction failed: ${s}`}),t}finally{this._compactionAbortController=void 0,this._reconnectToAgent()}}abortCompaction(){this._compactionAbortController?.abort(),this._autoCompactionAbortController?.abort()}abortBranchSummary(){this._branchSummaryAbortController?.abort()}abortOverseer(){this._overseerAbortController?.abort()}async _checkCompaction(e,t=!0){const s=this.settingsManager.getCompactionSettings();if(!s.enabled||t&&e.stopReason==="aborted")return!1;const n=this.model?.contextWindow??0,i=this.model&&e.provider===this.model.provider&&e.model===this.model.id,o=V(this.sessionManager.getBranch());if(o!==null&&e.timestamp<=new Date(o.timestamp).getTime())return!1;if(i&&$(e,n)){if(this._overflowRecoveryAttempted)return this._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model."}),!1;this._overflowRecoveryAttempted=!0;const l=this.agent.state.messages;return l.length>0&&l[l.length-1].role==="assistant"&&(this.agent.state.messages=l.slice(0,-1)),await this._runAutoCompaction("overflow",!0)}let a;if(e.stopReason==="error"){const l=this.agent.state.messages,c=G(l);if(c.lastUsageIndex===null)return!1;const h=l[c.lastUsageIndex];if(o&&h.role==="assistant"&&h.timestamp<=new Date(o.timestamp).getTime())return!1;a=c.tokens}else a=z(e.usage);return he(a,n,s)?await this._runAutoCompaction("threshold",!1):!1}async _runAutoCompaction(e,t){const s=this.settingsManager.getCompactionSettings();this._emit({type:"compaction_start",reason:e}),this._autoCompactionAbortController=new AbortController;try{if(!this.model)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!1,willRetry:!1}),!1;let n,i;if(this.agent.streamFn===B){const p=await this._modelRegistry.getApiKeyAndHeaders(this.model);if(!p.ok||!p.apiKey)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!1,willRetry:!1}),!1;n=p.apiKey,i=p.headers}else({apiKey:n,headers:i}=await this._getCompactionRequestAuth(this.model));const o=this.sessionManager.getBranch(),r=q(o,s);if(!r)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!1,willRetry:!1}),!1;let a,l=!1;if(this._extensionRunner.hasHandlers("session_before_compact")){const p=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:o,customInstructions:void 0,signal:this._autoCompactionAbortController.signal});if(p?.cancel)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!0,willRetry:!1}),!1;p?.compaction&&(a=p.compaction,l=!0)}let c,h,u,m;if(a)c=a.summary,h=a.firstKeptEntryId,u=a.tokensBefore,m=a.details;else{const p=await j(r,this.model,n,i,void 0,this._autoCompactionAbortController.signal,this.thinkingLevel,this.agent.streamFn);c=p.summary,h=p.firstKeptEntryId,u=p.tokensBefore,m=p.details}if(this._autoCompactionAbortController.signal.aborted)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!0,willRetry:!1}),!1;this.sessionManager.appendCompaction(c,h,u,m,l);const w=this.sessionManager.getEntries(),d=this.sessionManager.buildSessionContext();this.agent.state.messages=d.messages;const x=w.find(p=>p.type==="compaction"&&p.summary===c);this._extensionRunner&&x&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:x,fromExtension:l});const g={summary:c,firstKeptEntryId:h,tokensBefore:u,details:m};if(this._emit({type:"compaction_end",reason:e,result:g,aborted:!1,willRetry:t}),t){const p=this.agent.state.messages,_=p[p.length-1];return _?.role==="assistant"&&_.stopReason==="error"&&(this.agent.state.messages=p.slice(0,-1)),!0}return this.agent.hasQueuedMessages()}catch(n){const i=n instanceof Error?n.message:"compaction failed";return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!1,willRetry:!1,errorMessage:e==="overflow"?`Context overflow recovery failed: ${i}`:`Auto-compaction failed: ${i}`}),!1}finally{this._autoCompactionAbortController=void 0}}setAutoCompactionEnabled(e){this.settingsManager.setCompactionEnabled(e)}get autoCompactionEnabled(){return this.settingsManager.getCompactionEnabled()}async bindExtensions(e){e.uiContext!==void 0&&(this._extensionUIContext=e.uiContext),e.mode!==void 0&&(this._extensionMode=e.mode),e.commandContextActions!==void 0&&(this._extensionCommandContextActions=e.commandContextActions),e.abortHandler!==void 0&&(this._extensionAbortHandler=e.abortHandler),e.shutdownHandler!==void 0&&(this._extensionShutdownHandler=e.shutdownHandler),e.onError!==void 0&&(this._extensionErrorListener=e.onError),this._applyExtensionBindings(this._extensionRunner),await this._extensionRunner.emit(this._sessionStartEvent),await this.extendResourcesFromExtensions(this._sessionStartEvent.reason==="reload"?"reload":"startup")}async extendResourcesFromExtensions(e){if(!this._extensionRunner.hasHandlers("resources_discover"))return;const{skillPaths:t,promptPaths:s,themePaths:n}=await this._extensionRunner.emitResourcesDiscover(this._cwd,e);if(t.length===0&&s.length===0&&n.length===0)return;const i={skillPaths:this.buildExtensionResourcePaths(t),promptPaths:this.buildExtensionResourcePaths(s),themePaths:this.buildExtensionResourcePaths(n)};this._resourceLoader.extendResources(i),this._baseSystemPrompt=this._rebuildSystemPrompt(this.getActiveToolNames()),this.agent.state.systemPrompt=this._baseSystemPrompt}buildExtensionResourcePaths(e){return e.map(t=>{const s=this.getExtensionSourceLabel(t.extensionPath),n=t.extensionPath.startsWith("<")?void 0:U(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return e.startsWith("<")?`extension:${e.replace(/[<>]/g,"")}`:`extension:${Z(e).replace(/\.(ts|js)$/,"")}`}_applyExtensionBindings(e){e.setUIContext(this._extensionUIContext,this._extensionMode),e.bindCommandContext(this._extensionCommandContextActions),this._extensionErrorUnsubscriber?.(),this._extensionErrorUnsubscriber=this._extensionErrorListener?e.onError(this._extensionErrorListener):void 0}_refreshCurrentModelFromRegistry(){const e=this.model;if(!e)return;const t=this._modelRegistry.find(e.provider,e.id);!t||t===e||(this.agent.state.model=t)}_bindExtensionCore(e){const t=f(()=>{const s=e.getRegisteredCommands().map(o=>({name:o.invocationName,description:o.description,source:"extension",sourceInfo:o.sourceInfo})),n=this.promptTemplates.map(o=>({name:o.name,description:o.description,source:"prompt",sourceInfo:o.sourceInfo})),i=this._resourceLoader.getSkills().skills.map(o=>({name:`skill:${o.name}`,description:o.description,source:"skill",sourceInfo:o.sourceInfo}));return[...s,...n,...i]},"getCommands");e.bindCore({sendMessage:f((s,n)=>{this.sendCustomMessage(s,n).catch(i=>{e.emitError({extensionPath:"<runtime>",event:"send_message",error:i instanceof Error?i.message:String(i)})})},"sendMessage"),sendUserMessage:f((s,n)=>{this.sendUserMessage(s,n).catch(i=>{e.emitError({extensionPath:"<runtime>",event:"send_user_message",error:i instanceof Error?i.message:String(i)})})},"sendUserMessage"),appendEntry:f((s,n)=>{this.sessionManager.appendCustomEntry(s,n)},"appendEntry"),setSessionName:f(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:f(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:f((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:f(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:f(()=>this.getAllTools(),"getAllTools"),setActiveTools:f(s=>this.setActiveToolsByName(s),"setActiveTools"),refreshTools:f(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:f(async s=>this.modelRegistry.hasConfiguredAuth(s)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:f(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:f(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:f(()=>this.model,"getModel"),isIdle:f(()=>!this.isStreaming,"isIdle"),getSignal:f(()=>this.agent.signal,"getSignal"),abort:f(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:f(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:f(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:f(()=>this.getContextUsage(),"getContextUsage"),compact:f(s=>{(async()=>{try{const n=await this.compact(s?.customInstructions);s?.onComplete?.(n)}catch(n){const i=n instanceof Error?n:new Error(String(n));s?.onError?.(i)}})()},"compact"),getSystemPrompt:f(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:f(()=>this._baseSystemPromptOptions,"getSystemPromptOptions")},{registerProvider:f((s,n)=>{this._modelRegistry.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),unregisterProvider:f(s=>{this._modelRegistry.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider")})}_refreshToolRegistry(e){const t=new Set(this._toolRegistry.keys()),s=this.getActiveToolNames(),n=this._allowedToolNames,i=this._excludedToolNames,o=f(d=>(!n||n.has(d))&&!i?.has(d),"isAllowedTool"),a=[...this._extensionRunner.getAllRegisteredTools(),...this._customTools.map(d=>({definition:d,sourceInfo:I(`<sdk:${d.name}>`,{source:"sdk"})}))].filter(d=>o(d.definition.name)),l=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>o(d)).map(([d,x])=>[d,{definition:x,sourceInfo:I(`<builtin:${d}>`,{source:"builtin"})}]));for(const d of a)l.set(d.definition.name,{definition:d.definition,sourceInfo:d.sourceInfo});this._toolDefinitions=l,this._toolPromptSnippets=new Map(Array.from(l.values()).map(({definition:d})=>{const x=this._normalizePromptSnippet(d.promptSnippet);return x?[d.name,x]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(l.values()).map(({definition:d})=>{const x=this._normalizePromptGuidelines(d.promptGuidelines);return x.length>0?[d.name,x]:void 0}).filter(d=>d!==void 0));const c=this._extensionRunner,h=W(a,c),u=W(Array.from(this._baseToolDefinitions.values()).filter(d=>o(d.name)).map(d=>({definition:d,sourceInfo:I(`<builtin:${d.name}>`,{source:"builtin"})})),c),m=new Map(u.map(d=>[d.name,d]));for(const d of h)m.set(d.name,d);this._toolRegistry=m;const w=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>o(d));if(n)for(const d of this._toolRegistry.keys())n.has(d)&&w.push(d);else if(e?.includeAllExtensionTools)for(const d of h)w.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())t.has(d)||w.push(d);this.setActiveToolsByName([...new Set(w)])}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath(),i=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([l,c])=>[l,be(c)])):xe(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n}});this._baseToolDefinitions=new Map(Object.entries(i).map(([l,c])=>[l,c]));const o=this._resourceLoader.getExtensions();if(e.flagValues)for(const[l,c]of e.flagValues)o.runtime.flagValues.set(l,c);this._extensionRunner=new pe(o.extensions,o.runtime,this._cwd,this.sessionManager,this._modelRegistry),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const r=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],a=e.activeToolNames??r;this._refreshToolRegistry({activeToolNames:a,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(){const e=this._extensionRunner.getFlagValues();await fe(this._extensionRunner,{type:"session_shutdown",reason:"reload"}),await this.settingsManager.reload(),ne(),await this._resourceLoader.reload(),this._buildRuntime({activeToolNames:this.getActiveToolNames(),flagValues:e,includeAllExtensionTools:!0}),(this._extensionUIContext||this._extensionCommandContextActions||this._extensionShutdownHandler||this._extensionErrorListener)&&(await this._extensionRunner.emit({type:"session_start",reason:"reload"}),await this.extendResourcesFromExtensions("reload"))}_isNonRetryableProviderLimitError(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}_isRateLimited(e){return e.stopReason==="error"&&!!e.errorMessage&&/rate.?limit|429|too many requests|retry delay|quota/i.test(e.errorMessage)}_suggest(e,t){process.env.KODA_TIPS!=="0"&&(this._suggestedThisTask||this._suggestShown.has(e)||(this._suggestShown.add(e),this._suggestedThisTask=!0,this._emit({type:"suggest_feature",id:e,message:t})))}_isRetryableError(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;const t=this.model?.contextWindow??0;if($(e,t))return!1;const s=e.errorMessage;return this._isNonRetryableProviderLimitError(s)?!1:/overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|terminated|retry delay/i.test(s)}async _prepareRetry(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled)return!1;if(this._retryAttempt++,this._retryAttempt>t.maxRetries)return this._retryAttempt--,!1;const s=t.baseDelayMs*2**(this._retryAttempt-1);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error"});const n=this.agent.state.messages;n.length>0&&n[n.length-1].role==="assistant"&&(this.agent.state.messages=n.slice(0,-1)),this._retryAbortController=new AbortController;try{await oe(s,this._retryAbortController.signal)}catch{const i=this._retryAttempt;return this._retryAttempt=0,this._emit({type:"auto_retry_end",success:!1,attempt:i,finalError:"Retry cancelled"}),!1}finally{this._retryAbortController=void 0}return!0}async _failoverModel(e){if(e.stopReason!=="error"||$(e,this.model?.contextWindow??0))return!1;const t=this.agent.state.model;this._failoverTried.add(`${t.provider}/${t.id}`);const s=(process.env.KODA_FAILOVER||"openadapter/glm-5.1,openadapter/GLM-5,openadapter/Kimi-K2.6,openadapter/Kimi-K2.5,openadapter/MiniMax-M2.7,openadapter/DeepSeek-V4-Pro").split(",").map(a=>a.trim()).filter(Boolean),n=[];for(const a of s){const l=a.indexOf("/"),[c,h]=l>=0?[a.slice(0,l),a.slice(l+1)]:[t.provider,a];if(this._failoverTried.has(`${c}/${h}`))continue;const u=this._modelRegistry.find(c,h);!u||C(u,t)||n.push({key:`${c}/${h}`,model:u})}if(n.length===0)return!1;const i=await this._fetchModelHealth(n[0].model);if(i){const a=f(c=>c?.health!=null&&c.health<=3,"isHealthy"),l=f(c=>c?.latency??6,"latKey");n.sort((c,h)=>{const u=i[c.model.id],m=i[h.model.id],w=a(u)?1:0,d=a(m)?1:0;return w!==d?d-w:l(u)-l(m)})}const o=n[0].model;this._failoverTried.add(n[0].key);const r=this.agent.state.messages;return r.length>0&&r[r.length-1].role==="assistant"&&(this.agent.state.messages=r.slice(0,-1)),this.agent.state.model=o,this._retryAttempt=0,this.sessionManager.appendModelChange(o.provider,o.id),this._emitModelSelect(o,t,"cycle"),this._trace("failover",`${t.id} \u2192 ${o.id} (provider error)`),this._emit({type:"model_switch_notice",message:`\u2191 ${t.id} hit a wall \u2014 Koda beefed up to ${o.id}`}),!0}async _fetchModelHealth(e){try{if(!e.baseUrl)return null;const t=await this._modelRegistry.getApiKeyAndHeaders(e);if(!t?.apiKey)return null;const s=new AbortController,n=setTimeout(()=>s.abort(),2500);try{const i=await fetch(`${e.baseUrl.replace(/\/$/,"")}/model-health`,{headers:{Authorization:`Bearer ${t.apiKey}`,...t.headers||{}},signal:s.signal});return i.ok?(await i.json())?.models??null:null}finally{clearTimeout(n)}}catch{return null}}async _zenitsuGetHealth(){const e=Date.now();if(this._zenitsuHealthCache&&e-this._zenitsuHealthCache.at<3e4)return this._zenitsuHealthCache.models;const t=this._zenitsuPreferred||this.agent.state.model,s=await this._fetchModelHealth(t);return s&&(this._zenitsuHealthCache={at:e,models:s}),this._zenitsuHealthCache?.models}async _zenitsuPickModel(){this._zenitsuPreferred||(this._zenitsuPreferred=this.agent.state.model);const e=this._zenitsuPreferred,t=e.provider,s=Date.now(),n=await this._zenitsuGetHealth()||{},i=f(m=>this._zenitsuCooldown.get(`${t}/${m}`)??0,"cooldownOf"),o=(process.env.KODA_ZENITSU_LADDER||"glm-5.1,Kimi-K2.6,MiniMax-M2.7,GLM-4.7,GLM-5,Kimi-K2.5,DeepSeek-V4-Pro").split(",").map(m=>m.trim()).filter(Boolean),r=[],a=new Set;for(const m of[e.id,...o]){if(a.has(m)||(a.add(m),i(m)>s))continue;const w=this._modelRegistry.find(t,m);if(!w)continue;const d=n[m]||{};r.push({id:m,model:w,healthy:d.health!=null&&d.health<=3,lat:d.latency??6})}if(r.length===0)return e;const l=i(e.id)<=s,c=r.find(m=>m.id===e.id),h=n[e.id]?.health!=null&&n[e.id].health>3;if(l&&c&&!h){const w=c.lat<=5?r.filter(d=>d.id!==e.id&&d.healthy&&d.lat<c.lat).sort((d,x)=>d.lat-x.lat)[0]:void 0;return w?w.model:e}const u=r.filter(m=>m.healthy).sort((m,w)=>m.lat-w.lat);return u.length?u[0].model:r.sort((m,w)=>m.lat-w.lat)[0].model}_messageText(e){const t=e?.content;return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s?.type==="text").map(s=>s.text).join(`
|
|
14
|
+
`),n.length===0&&(n=void 0)}await this.prompt(s,{expandPromptTemplates:!1,streamingBehavior:t?.deliverAs,images:n,source:"extension"})}clearQueue(){const e=[...this._steeringMessages],t=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering:e,followUp:t}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(){this.abortRetry(),this.agent.abort(),await this.agent.waitForIdle()}async _emitModelSelect(e,t,s){C(t,e)||await this._extensionRunner.emit({type:"model_select",model:e,previousModel:t,source:s})}async setModel(e){if(!this._modelRegistry.hasConfiguredAuth(e))throw new Error(`No API key for ${e.provider}/${e.id}`);const t=this.model,s=this._getThinkingLevelForModelSwitch();this.agent.state.model=e,this._homeModel=e,this._stickyModel=void 0,this._sessionEscalations=0,this.sessionManager.appendModelChange(e.provider,e.id),this.settingsManager.setDefaultModelAndProvider(e.provider,e.id),this.setThinkingLevel(s),await this._emitModelSelect(e,t,"set")}async cycleModel(e="forward"){return this._scopedModels.length>0?this._cycleScopedModel(e):this._cycleAvailableModel(e)}async _cycleScopedModel(e){const t=this._scopedModels.filter(l=>this._modelRegistry.hasConfiguredAuth(l.model));if(t.length<=1)return;const s=this.model;let n=t.findIndex(l=>C(l.model,s));n===-1&&(n=0);const i=t.length,o=e==="forward"?(n+1)%i:(n-1+i)%i,r=t[o],a=this._getThinkingLevelForModelSwitch(r.thinkingLevel);return this.agent.state.model=r.model,this._homeModel=r.model,this._stickyModel=void 0,this._sessionEscalations=0,this.sessionManager.appendModelChange(r.model.provider,r.model.id),this.settingsManager.setDefaultModelAndProvider(r.model.provider,r.model.id),this.setThinkingLevel(a),await this._emitModelSelect(r.model,s,"cycle"),{model:r.model,thinkingLevel:this.thinkingLevel,isScoped:!0}}async _cycleAvailableModel(e){const t=await this._modelRegistry.getAvailable();if(t.length<=1)return;const s=this.model;let n=t.findIndex(l=>C(l,s));n===-1&&(n=0);const i=t.length,o=e==="forward"?(n+1)%i:(n-1+i)%i,r=t[o],a=this._getThinkingLevelForModelSwitch();return this.agent.state.model=r,this._homeModel=r,this._stickyModel=void 0,this._sessionEscalations=0,this.sessionManager.appendModelChange(r.provider,r.id),this.settingsManager.setDefaultModelAndProvider(r.provider,r.id),this.setThinkingLevel(a),await this._emitModelSelect(r,s,"cycle"),{model:r,thinkingLevel:this.thinkingLevel,isScoped:!1}}setThinkingLevel(e){const t=this.getAvailableThinkingLevels(),s=t.includes(e)?e:this._clampThinkingLevel(e,t),n=this.agent.state.thinkingLevel,i=s!==n;this.agent.state.thinkingLevel=s,i&&(this.sessionManager.appendThinkingLevelChange(s),(this.supportsThinking()||s!=="off")&&this.settingsManager.setDefaultThinkingLevel(s),this._emit({type:"thinking_level_changed",level:s}),this._extensionRunner.emit({type:"thinking_level_select",level:s,previousLevel:n}))}cycleThinkingLevel(){if(!this.supportsThinking())return;const e=this.getAvailableThinkingLevels(),s=(e.indexOf(this.thinkingLevel)+1)%e.length,n=e[s];return this.setThinkingLevel(n),n}getAvailableThinkingLevels(){return this.model?se(this.model):ve}supportsThinking(){return!!this.model?.reasoning}_getThinkingLevelForModelSwitch(e){return e!==void 0?e:this.supportsThinking()?this.thinkingLevel:this.settingsManager.getDefaultThinkingLevel()??de}_clampThinkingLevel(e,t){return this.model?ee(this.model,e):"off"}setSteeringMode(e){this.agent.steeringMode=e,this.settingsManager.setSteeringMode(e)}setFollowUpMode(e){this.agent.followUpMode=e,this.settingsManager.setFollowUpMode(e)}async compact(e){this._disconnectFromAgent(),await this.abort(),this._compactionAbortController=new AbortController,this._emit({type:"compaction_start",reason:"manual"});try{if(!this.model)throw new Error(H());const{apiKey:t,headers:s}=await this._getCompactionRequestAuth(this.model),n=this.sessionManager.getBranch(),i=this.settingsManager.getCompactionSettings(),o=W(n,i);if(!o)throw n[n.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let r,a=!1;if(this._extensionRunner.hasHandlers("session_before_compact")){const g=await this._extensionRunner.emit({type:"session_before_compact",preparation:o,branchEntries:n,customInstructions:e,signal:this._compactionAbortController.signal});if(g?.cancel)throw new Error("Compaction cancelled");g?.compaction&&(r=g.compaction,a=!0)}let l,c,h,u;if(r)l=r.summary,c=r.firstKeptEntryId,h=r.tokensBefore,u=r.details;else{const g=await j(o,this.model,t,s,e,this._compactionAbortController.signal,this.thinkingLevel,this.agent.streamFn);l=g.summary,c=g.firstKeptEntryId,h=g.tokensBefore,u=g.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,c,h,u,a);const m=this.sessionManager.getEntries(),w=this.sessionManager.buildSessionContext();this.agent.state.messages=w.messages;const d=m.find(g=>g.type==="compaction"&&g.summary===l);this._extensionRunner&&d&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:d,fromExtension:a});const x={summary:l,firstKeptEntryId:c,tokensBefore:h,details:u};return this._emit({type:"compaction_end",reason:"manual",result:x,aborted:!1,willRetry:!1}),x}catch(t){const s=t instanceof Error?t.message:String(t),n=s==="Compaction cancelled"||t instanceof Error&&t.name==="AbortError";throw this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:n,willRetry:!1,errorMessage:n?void 0:`Compaction failed: ${s}`}),t}finally{this._compactionAbortController=void 0,this._reconnectToAgent()}}abortCompaction(){this._compactionAbortController?.abort(),this._autoCompactionAbortController?.abort()}abortBranchSummary(){this._branchSummaryAbortController?.abort()}abortOverseer(){this._overseerAbortController?.abort()}async _checkCompaction(e,t=!0){const s=this.settingsManager.getCompactionSettings();if(!s.enabled||t&&e.stopReason==="aborted")return!1;const n=this.model?.contextWindow??0,i=this.model&&e.provider===this.model.provider&&e.model===this.model.id,o=V(this.sessionManager.getBranch());if(o!==null&&e.timestamp<=new Date(o.timestamp).getTime())return!1;if(i&&$(e,n)){if(this._overflowRecoveryAttempted)return this._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model."}),!1;this._overflowRecoveryAttempted=!0;const l=this.agent.state.messages;return l.length>0&&l[l.length-1].role==="assistant"&&(this.agent.state.messages=l.slice(0,-1)),await this._runAutoCompaction("overflow",!0)}let a;if(e.stopReason==="error"){const l=this.agent.state.messages,c=G(l);if(c.lastUsageIndex===null)return!1;const h=l[c.lastUsageIndex];if(o&&h.role==="assistant"&&h.timestamp<=new Date(o.timestamp).getTime())return!1;a=c.tokens}else a=z(e.usage);return he(a,n,s)?await this._runAutoCompaction("threshold",!1):!1}async _runAutoCompaction(e,t){const s=this.settingsManager.getCompactionSettings();this._emit({type:"compaction_start",reason:e}),this._autoCompactionAbortController=new AbortController;try{if(!this.model)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!1,willRetry:!1}),!1;let n,i;if(this.agent.streamFn===B){const p=await this._modelRegistry.getApiKeyAndHeaders(this.model);if(!p.ok||!p.apiKey)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!1,willRetry:!1}),!1;n=p.apiKey,i=p.headers}else({apiKey:n,headers:i}=await this._getCompactionRequestAuth(this.model));const o=this.sessionManager.getBranch(),r=W(o,s);if(!r)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!1,willRetry:!1}),!1;let a,l=!1;if(this._extensionRunner.hasHandlers("session_before_compact")){const p=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:o,customInstructions:void 0,signal:this._autoCompactionAbortController.signal});if(p?.cancel)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!0,willRetry:!1}),!1;p?.compaction&&(a=p.compaction,l=!0)}let c,h,u,m;if(a)c=a.summary,h=a.firstKeptEntryId,u=a.tokensBefore,m=a.details;else{const p=await j(r,this.model,n,i,void 0,this._autoCompactionAbortController.signal,this.thinkingLevel,this.agent.streamFn);c=p.summary,h=p.firstKeptEntryId,u=p.tokensBefore,m=p.details}if(this._autoCompactionAbortController.signal.aborted)return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!0,willRetry:!1}),!1;this.sessionManager.appendCompaction(c,h,u,m,l);const w=this.sessionManager.getEntries(),d=this.sessionManager.buildSessionContext();this.agent.state.messages=d.messages;const x=w.find(p=>p.type==="compaction"&&p.summary===c);this._extensionRunner&&x&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:x,fromExtension:l});const g={summary:c,firstKeptEntryId:h,tokensBefore:u,details:m};if(this._emit({type:"compaction_end",reason:e,result:g,aborted:!1,willRetry:t}),t){const p=this.agent.state.messages,_=p[p.length-1];return _?.role==="assistant"&&_.stopReason==="error"&&(this.agent.state.messages=p.slice(0,-1)),!0}return this.agent.hasQueuedMessages()}catch(n){const i=n instanceof Error?n.message:"compaction failed";return this._emit({type:"compaction_end",reason:e,result:void 0,aborted:!1,willRetry:!1,errorMessage:e==="overflow"?`Context overflow recovery failed: ${i}`:`Auto-compaction failed: ${i}`}),!1}finally{this._autoCompactionAbortController=void 0}}setAutoCompactionEnabled(e){this.settingsManager.setCompactionEnabled(e)}get autoCompactionEnabled(){return this.settingsManager.getCompactionEnabled()}async bindExtensions(e){e.uiContext!==void 0&&(this._extensionUIContext=e.uiContext),e.mode!==void 0&&(this._extensionMode=e.mode),e.commandContextActions!==void 0&&(this._extensionCommandContextActions=e.commandContextActions),e.abortHandler!==void 0&&(this._extensionAbortHandler=e.abortHandler),e.shutdownHandler!==void 0&&(this._extensionShutdownHandler=e.shutdownHandler),e.onError!==void 0&&(this._extensionErrorListener=e.onError),this._applyExtensionBindings(this._extensionRunner),await this._extensionRunner.emit(this._sessionStartEvent),await this.extendResourcesFromExtensions(this._sessionStartEvent.reason==="reload"?"reload":"startup")}async extendResourcesFromExtensions(e){if(!this._extensionRunner.hasHandlers("resources_discover"))return;const{skillPaths:t,promptPaths:s,themePaths:n}=await this._extensionRunner.emitResourcesDiscover(this._cwd,e);if(t.length===0&&s.length===0&&n.length===0)return;const i={skillPaths:this.buildExtensionResourcePaths(t),promptPaths:this.buildExtensionResourcePaths(s),themePaths:this.buildExtensionResourcePaths(n)};this._resourceLoader.extendResources(i),this._baseSystemPrompt=this._rebuildSystemPrompt(this.getActiveToolNames()),this.agent.state.systemPrompt=this._baseSystemPrompt}buildExtensionResourcePaths(e){return e.map(t=>{const s=this.getExtensionSourceLabel(t.extensionPath),n=t.extensionPath.startsWith("<")?void 0:U(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return e.startsWith("<")?`extension:${e.replace(/[<>]/g,"")}`:`extension:${Z(e).replace(/\.(ts|js)$/,"")}`}_applyExtensionBindings(e){e.setUIContext(this._extensionUIContext,this._extensionMode),e.bindCommandContext(this._extensionCommandContextActions),this._extensionErrorUnsubscriber?.(),this._extensionErrorUnsubscriber=this._extensionErrorListener?e.onError(this._extensionErrorListener):void 0}_refreshCurrentModelFromRegistry(){const e=this.model;if(!e)return;const t=this._modelRegistry.find(e.provider,e.id);!t||t===e||(this.agent.state.model=t)}_bindExtensionCore(e){const t=f(()=>{const s=e.getRegisteredCommands().map(o=>({name:o.invocationName,description:o.description,source:"extension",sourceInfo:o.sourceInfo})),n=this.promptTemplates.map(o=>({name:o.name,description:o.description,source:"prompt",sourceInfo:o.sourceInfo})),i=this._resourceLoader.getSkills().skills.map(o=>({name:`skill:${o.name}`,description:o.description,source:"skill",sourceInfo:o.sourceInfo}));return[...s,...n,...i]},"getCommands");e.bindCore({sendMessage:f((s,n)=>{this.sendCustomMessage(s,n).catch(i=>{e.emitError({extensionPath:"<runtime>",event:"send_message",error:i instanceof Error?i.message:String(i)})})},"sendMessage"),sendUserMessage:f((s,n)=>{this.sendUserMessage(s,n).catch(i=>{e.emitError({extensionPath:"<runtime>",event:"send_user_message",error:i instanceof Error?i.message:String(i)})})},"sendUserMessage"),appendEntry:f((s,n)=>{this.sessionManager.appendCustomEntry(s,n)},"appendEntry"),setSessionName:f(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:f(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:f((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:f(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:f(()=>this.getAllTools(),"getAllTools"),setActiveTools:f(s=>this.setActiveToolsByName(s),"setActiveTools"),refreshTools:f(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:f(async s=>this.modelRegistry.hasConfiguredAuth(s)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:f(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:f(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:f(()=>this.model,"getModel"),isIdle:f(()=>!this.isStreaming,"isIdle"),getSignal:f(()=>this.agent.signal,"getSignal"),abort:f(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:f(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:f(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:f(()=>this.getContextUsage(),"getContextUsage"),compact:f(s=>{(async()=>{try{const n=await this.compact(s?.customInstructions);s?.onComplete?.(n)}catch(n){const i=n instanceof Error?n:new Error(String(n));s?.onError?.(i)}})()},"compact"),getSystemPrompt:f(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:f(()=>this._baseSystemPromptOptions,"getSystemPromptOptions")},{registerProvider:f((s,n)=>{this._modelRegistry.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),unregisterProvider:f(s=>{this._modelRegistry.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider")})}_refreshToolRegistry(e){const t=new Set(this._toolRegistry.keys()),s=this.getActiveToolNames(),n=this._allowedToolNames,i=this._excludedToolNames,o=f(d=>(!n||n.has(d))&&!i?.has(d),"isAllowedTool"),a=[...this._extensionRunner.getAllRegisteredTools(),...this._customTools.map(d=>({definition:d,sourceInfo:I(`<sdk:${d.name}>`,{source:"sdk"})}))].filter(d=>o(d.definition.name)),l=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>o(d)).map(([d,x])=>[d,{definition:x,sourceInfo:I(`<builtin:${d}>`,{source:"builtin"})}]));for(const d of a)l.set(d.definition.name,{definition:d.definition,sourceInfo:d.sourceInfo});this._toolDefinitions=l,this._toolPromptSnippets=new Map(Array.from(l.values()).map(({definition:d})=>{const x=this._normalizePromptSnippet(d.promptSnippet);return x?[d.name,x]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(l.values()).map(({definition:d})=>{const x=this._normalizePromptGuidelines(d.promptGuidelines);return x.length>0?[d.name,x]:void 0}).filter(d=>d!==void 0));const c=this._extensionRunner,h=q(a,c),u=q(Array.from(this._baseToolDefinitions.values()).filter(d=>o(d.name)).map(d=>({definition:d,sourceInfo:I(`<builtin:${d.name}>`,{source:"builtin"})})),c),m=new Map(u.map(d=>[d.name,d]));for(const d of h)m.set(d.name,d);this._toolRegistry=m;const w=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>o(d));if(n)for(const d of this._toolRegistry.keys())n.has(d)&&w.push(d);else if(e?.includeAllExtensionTools)for(const d of h)w.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())t.has(d)||w.push(d);this.setActiveToolsByName([...new Set(w)])}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath(),i=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([l,c])=>[l,be(c)])):xe(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n}});this._baseToolDefinitions=new Map(Object.entries(i).map(([l,c])=>[l,c]));const o=this._resourceLoader.getExtensions();if(e.flagValues)for(const[l,c]of e.flagValues)o.runtime.flagValues.set(l,c);this._extensionRunner=new pe(o.extensions,o.runtime,this._cwd,this.sessionManager,this._modelRegistry),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const r=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],a=e.activeToolNames??r;this._refreshToolRegistry({activeToolNames:a,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(){const e=this._extensionRunner.getFlagValues();await fe(this._extensionRunner,{type:"session_shutdown",reason:"reload"}),await this.settingsManager.reload(),ne(),await this._resourceLoader.reload(),this._buildRuntime({activeToolNames:this.getActiveToolNames(),flagValues:e,includeAllExtensionTools:!0}),(this._extensionUIContext||this._extensionCommandContextActions||this._extensionShutdownHandler||this._extensionErrorListener)&&(await this._extensionRunner.emit({type:"session_start",reason:"reload"}),await this.extendResourcesFromExtensions("reload"))}_isNonRetryableProviderLimitError(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}_isRateLimited(e){return e.stopReason==="error"&&!!e.errorMessage&&/rate.?limit|429|too many requests|retry delay|quota/i.test(e.errorMessage)}_suggest(e,t){process.env.KODA_TIPS!=="0"&&(this._suggestedThisTask||this._suggestShown.has(e)||(this._suggestShown.add(e),this._suggestedThisTask=!0,this._emit({type:"suggest_feature",id:e,message:t})))}_isRetryableError(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;const t=this.model?.contextWindow??0;if($(e,t))return!1;const s=e.errorMessage;return this._isNonRetryableProviderLimitError(s)?!1:/overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|terminated|retry delay/i.test(s)}async _prepareRetry(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled)return!1;if(this._retryAttempt++,this._retryAttempt>t.maxRetries)return this._retryAttempt--,!1;const s=t.baseDelayMs*2**(this._retryAttempt-1);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error"});const n=this.agent.state.messages;n.length>0&&n[n.length-1].role==="assistant"&&(this.agent.state.messages=n.slice(0,-1)),this._retryAbortController=new AbortController;try{await oe(s,this._retryAbortController.signal)}catch{const i=this._retryAttempt;return this._retryAttempt=0,this._emit({type:"auto_retry_end",success:!1,attempt:i,finalError:"Retry cancelled"}),!1}finally{this._retryAbortController=void 0}return!0}async _failoverModel(e){if(e.stopReason!=="error"||$(e,this.model?.contextWindow??0))return!1;const t=this.agent.state.model;this._failoverTried.add(`${t.provider}/${t.id}`);const s=(process.env.KODA_FAILOVER||"openadapter/glm-5.1,openadapter/GLM-5,openadapter/Kimi-K2.6,openadapter/Kimi-K2.5,openadapter/MiniMax-M2.7,openadapter/DeepSeek-V4-Pro").split(",").map(a=>a.trim()).filter(Boolean),n=[];for(const a of s){const l=a.indexOf("/"),[c,h]=l>=0?[a.slice(0,l),a.slice(l+1)]:[t.provider,a];if(this._failoverTried.has(`${c}/${h}`))continue;const u=this._modelRegistry.find(c,h);!u||C(u,t)||n.push({key:`${c}/${h}`,model:u})}if(n.length===0)return!1;const i=await this._fetchModelHealth(n[0].model);if(i){const a=f(c=>c?.health!=null&&c.health<=3,"isHealthy"),l=f(c=>c?.latency??6,"latKey");n.sort((c,h)=>{const u=i[c.model.id],m=i[h.model.id],w=a(u)?1:0,d=a(m)?1:0;return w!==d?d-w:l(u)-l(m)})}const o=n[0].model;this._failoverTried.add(n[0].key);const r=this.agent.state.messages;return r.length>0&&r[r.length-1].role==="assistant"&&(this.agent.state.messages=r.slice(0,-1)),this.agent.state.model=o,this._retryAttempt=0,this.sessionManager.appendModelChange(o.provider,o.id),this._emitModelSelect(o,t,"cycle"),this._trace("failover",`${t.id} \u2192 ${o.id} (provider error)`),this._emit({type:"model_switch_notice",message:`\u2191 ${t.id} hit a wall \u2014 Koda beefed up to ${o.id}`}),!0}async _fetchModelHealth(e){try{if(!e.baseUrl)return null;const t=await this._modelRegistry.getApiKeyAndHeaders(e);if(!t?.apiKey)return null;const s=new AbortController,n=setTimeout(()=>s.abort(),2500);try{const i=await fetch(`${e.baseUrl.replace(/\/$/,"")}/model-health`,{headers:{Authorization:`Bearer ${t.apiKey}`,...t.headers||{}},signal:s.signal});return i.ok?(await i.json())?.models??null:null}finally{clearTimeout(n)}}catch{return null}}async _zenitsuGetHealth(){const e=Date.now();if(this._zenitsuHealthCache&&e-this._zenitsuHealthCache.at<3e4)return this._zenitsuHealthCache.models;const t=this._zenitsuPreferred||this.agent.state.model,s=await this._fetchModelHealth(t);return s&&(this._zenitsuHealthCache={at:e,models:s}),this._zenitsuHealthCache?.models}async _zenitsuPickModel(){this._zenitsuPreferred||(this._zenitsuPreferred=this.agent.state.model);const e=this._zenitsuPreferred,t=e.provider,s=Date.now(),n=await this._zenitsuGetHealth()||{},i=f(m=>this._zenitsuCooldown.get(`${t}/${m}`)??0,"cooldownOf"),o=(process.env.KODA_ZENITSU_LADDER||"glm-5.1,Kimi-K2.6,MiniMax-M2.7,GLM-4.7,GLM-5,Kimi-K2.5,DeepSeek-V4-Pro").split(",").map(m=>m.trim()).filter(Boolean),r=[],a=new Set;for(const m of[e.id,...o]){if(a.has(m)||(a.add(m),i(m)>s))continue;const w=this._modelRegistry.find(t,m);if(!w)continue;const d=n[m]||{};r.push({id:m,model:w,healthy:d.health!=null&&d.health<=3,lat:d.latency??6})}if(r.length===0)return e;const l=i(e.id)<=s,c=r.find(m=>m.id===e.id),h=n[e.id]?.health!=null&&n[e.id].health>3;if(l&&c&&!h){const w=c.lat<=5?r.filter(d=>d.id!==e.id&&d.healthy&&d.lat<c.lat).sort((d,x)=>d.lat-x.lat)[0]:void 0;return w?w.model:e}const u=r.filter(m=>m.healthy).sort((m,w)=>m.lat-w.lat);return u.length?u[0].model:r.sort((m,w)=>m.lat-w.lat)[0].model}_messageText(e){const t=e?.content;return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s?.type==="text").map(s=>s.text).join(`
|
|
15
15
|
`):""}_goalFromMessages(e){const t=Array.isArray(e)?e:[e];for(let s=t.length-1;s>=0;s--)if(t[s]?.role==="user"){const n=this._messageText(t[s]).trim();if(n)return n}}_overseerContext(){const e=[];for(const t of this.agent.state.messages.slice(-12)){const s=t?.role;if(s==="assistant"){const n=this._messageText(t).trim();n&&e.push(`assistant: ${n.slice(0,600)}`);for(const i of Array.isArray(t.content)?t.content:[])(i?.type==="toolUse"||i?.type==="tool_use")&&e.push(` \u2192 tool ${i.name}(${JSON.stringify(i.input??i.args??{}).slice(0,160)})`)}else(s==="toolResult"||s==="tool")&&e.push(` result(${t.toolName??""}): ${this._messageText(t).slice(0,300)}`)}return e.join(`
|
|
16
16
|
`).slice(-4e3)}async _getModelTier(e){if(!this._tierCache){this._tierCache=new Map;try{if(e.baseUrl){const t=await this._modelRegistry.getApiKeyAndHeaders(e);if(t?.apiKey){const s=new AbortController,n=setTimeout(()=>s.abort(),3e3);try{const i=await fetch(`${e.baseUrl.replace(/\/$/,"")}/models`,{headers:{Authorization:`Bearer ${t.apiKey}`,...t.headers||{}},signal:s.signal});if(i.ok){const o=await i.json();for(const r of o.data??[])r.tier&&this._tierCache.set(r.id,r.tier)}}finally{clearTimeout(n)}}}}catch{}}return this._tierCache.get(e.id)}_isDegenerateOutput(e){const t=this._messageText(e);if(t.length<200)return!1;const s=t.match(/(.{3,60}?)\1{6,}/s);if(s&&s[0].length>150)return!0;const n=t.split(/\s+/).filter(Boolean);return n.length>60&&new Set(n).size/n.length<.15}async _escalate(e,t){if(this._escalationsDone>=2)return!1;const s=this.agent.state.model,n=(process.env.KODA_ESCALATE||"GLM-4.7,glm-5.1").split(",").map(r=>r.trim()).filter(Boolean);let i;for(const r of n){if(r===s.id||this._escalateTried.has(r))continue;const a=this._modelRegistry.find(s.provider,r);if(a){i=a;break}}if(!i)return!1;if(this._escalationsDone++,this._sessionEscalations++,this._escalateTried.add(i.id),this._sessionEscalations>=2&&(this._stickyModel=i),t?.stripLast){const r=this.agent.state.messages;r.length>0&&r[r.length-1].role==="assistant"&&(this.agent.state.messages=r.slice(0,-1))}this.agent.state.model=i,this._retryAttempt=0,this._overseerRounds=0,this.sessionManager.appendModelChange(i.provider,i.id),this._emitModelSelect(i,s,"cycle");const o=this._stickyModel?" (staying on it \u2014 this session needs the muscle)":"";return this._trace("escalate",`${s.id} \u2192 ${i.id}${this._stickyModel?" [sticky]":""} \u2014 ${e}`),this._emit({type:"model_switch_notice",message:`\u25B2 Koda escalated to ${i.id} \u2014 ${e}${o}`}),!0}listSkillNames(){return this._resourceLoader.getSkills().skills.map(e=>e.name)}getPinnedSkills(){return[...this._pinnedSkills.keys()]}pinSkill(e){const t=this._resourceLoader.getSkills().skills.find(s=>s.name===e);if(!t)return!1;try{const s=F(T(t.filePath,"utf-8")).trim();return this._pinnedSkills.set(e,`<active_skill name="${t.name}" location="${t.filePath}">
|
|
17
17
|
References are relative to ${t.baseDir}. Follow these instructions for this session:
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openadapter/koda",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.8",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@openadapter/koda",
|
|
9
|
-
"version": "1.0.0-beta.
|
|
9
|
+
"version": "1.0.0-beta.8",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@openadapter/koda-agent-core": "1.0.0-beta.
|
|
13
|
-
"@openadapter/koda-ai": "1.0.0-beta.
|
|
14
|
-
"@openadapter/koda-tui": "1.0.0-beta.
|
|
12
|
+
"@openadapter/koda-agent-core": "1.0.0-beta.8",
|
|
13
|
+
"@openadapter/koda-ai": "1.0.0-beta.8",
|
|
14
|
+
"@openadapter/koda-tui": "1.0.0-beta.8",
|
|
15
15
|
"@silvia-odwyer/photon-node": "0.3.4",
|
|
16
16
|
"chalk": "5.6.2",
|
|
17
17
|
"cross-spawn": "7.0.6",
|
|
@@ -699,11 +699,11 @@
|
|
|
699
699
|
]
|
|
700
700
|
},
|
|
701
701
|
"node_modules/@openadapter/koda-agent-core": {
|
|
702
|
-
"version": "1.0.0-beta.
|
|
703
|
-
"resolved": "https://registry.npmjs.org/@openadapter/koda-agent-core/-/koda-agent-core-1.0.0-beta.
|
|
702
|
+
"version": "1.0.0-beta.8",
|
|
703
|
+
"resolved": "https://registry.npmjs.org/@openadapter/koda-agent-core/-/koda-agent-core-1.0.0-beta.8.tgz",
|
|
704
704
|
"license": "MIT",
|
|
705
705
|
"dependencies": {
|
|
706
|
-
"@openadapter/koda-ai": "1.0.0-beta.
|
|
706
|
+
"@openadapter/koda-ai": "1.0.0-beta.8",
|
|
707
707
|
"ignore": "7.0.5",
|
|
708
708
|
"typebox": "1.1.38",
|
|
709
709
|
"yaml": "2.9.0"
|
|
@@ -713,8 +713,8 @@
|
|
|
713
713
|
}
|
|
714
714
|
},
|
|
715
715
|
"node_modules/@openadapter/koda-ai": {
|
|
716
|
-
"version": "1.0.0-beta.
|
|
717
|
-
"resolved": "https://registry.npmjs.org/@openadapter/koda-ai/-/koda-ai-1.0.0-beta.
|
|
716
|
+
"version": "1.0.0-beta.8",
|
|
717
|
+
"resolved": "https://registry.npmjs.org/@openadapter/koda-ai/-/koda-ai-1.0.0-beta.8.tgz",
|
|
718
718
|
"license": "MIT",
|
|
719
719
|
"dependencies": {
|
|
720
720
|
"@anthropic-ai/sdk": "0.91.1",
|
|
@@ -736,8 +736,8 @@
|
|
|
736
736
|
}
|
|
737
737
|
},
|
|
738
738
|
"node_modules/@openadapter/koda-tui": {
|
|
739
|
-
"version": "1.0.0-beta.
|
|
740
|
-
"resolved": "https://registry.npmjs.org/@openadapter/koda-tui/-/koda-tui-1.0.0-beta.
|
|
739
|
+
"version": "1.0.0-beta.8",
|
|
740
|
+
"resolved": "https://registry.npmjs.org/@openadapter/koda-tui/-/koda-tui-1.0.0-beta.8.tgz",
|
|
741
741
|
"license": "MIT",
|
|
742
742
|
"dependencies": {
|
|
743
743
|
"get-east-asian-width": "1.6.0",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openadapter/koda",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.8",
|
|
4
4
|
"description": "Coding agent CLI with read, bash, edit, write tools and session management",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"piConfig": {
|
|
@@ -42,9 +42,9 @@
|
|
|
42
42
|
"postbuild": "node ../../scripts/minify-pkg-dist.mjs"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@openadapter/koda-agent-core": "1.0.0-beta.
|
|
46
|
-
"@openadapter/koda-ai": "1.0.0-beta.
|
|
47
|
-
"@openadapter/koda-tui": "1.0.0-beta.
|
|
45
|
+
"@openadapter/koda-agent-core": "1.0.0-beta.8",
|
|
46
|
+
"@openadapter/koda-ai": "1.0.0-beta.8",
|
|
47
|
+
"@openadapter/koda-tui": "1.0.0-beta.8",
|
|
48
48
|
"@silvia-odwyer/photon-node": "0.3.4",
|
|
49
49
|
"chalk": "5.6.2",
|
|
50
50
|
"cross-spawn": "7.0.6",
|