@openadapter/koda 1.0.0-beta.5 → 1.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,665 +1,87 @@
1
- <p align="center">
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
- ---
1
+ <h1 align="center">Koda</h1>
146
2
 
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.
295
-
296
- Use `--offline` or `PI_OFFLINE=1` to disable all startup network operations described here, including update checks, package update checks, and install/update telemetry.
297
-
298
- ---
3
+ <p align="center"><strong>The coding agent that makes affordable models actually finish the job.</strong></p>
299
4
 
300
- ## Context Files
301
-
302
- Pi loads `AGENTS.md` (or `CLAUDE.md`) at startup from:
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
- ## CLI Reference
493
-
494
- ```bash
495
- pi [options] [@files...] [messages...]
496
- ```
497
-
498
- ### Package Commands
499
-
500
- ```bash
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
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.
514
14
 
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
- In print mode, pi also reads piped stdin and merges it into the initial prompt:
17
+ ## Install
524
18
 
525
19
  ```bash
526
- cat README.md | pi -p "Summarize this text"
20
+ npm i -g @openadapter/koda@beta
21
+ koda
527
22
  ```
528
23
 
529
- ### Model Options
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
- pi @prompt.md "Answer this"
595
- pi -p @screenshot.png "What's in this image?"
596
- pi @code.ts @test.ts "Review these files"
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
- ### Examples
600
-
601
- ```bash
602
- # Interactive with initial prompt
603
- pi "List all .ts files in src/"
34
+ ## What makes Koda different
604
35
 
605
- # Non-interactive
606
- pi -p "Summarize this codebase"
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.
607
37
 
608
- # Non-interactive with piped stdin
609
- cat README.md | pi -p "Summarize this text"
38
+ **Reliability that keeps cheap models honest:**
610
39
 
611
- # Named one-shot session
612
- pi --name "release audit" -p "Audit this repository"
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.
613
45
 
614
- # Different model
615
- pi --provider openai --model gpt-4o "Help me refactor"
46
+ **Features that respect your time:**
616
47
 
617
- # Model with provider prefix (no --provider needed)
618
- pi --model openai/gpt-4o "Help me refactor"
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.
619
55
 
620
- # Model with thinking level shorthand
621
- pi --model sonnet:high "Solve this complex problem"
56
+ ## Common commands
622
57
 
623
- # Limit model cycling
624
- pi --models "claude-*,gpt-4o"
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 |
625
69
 
626
- # Read-only mode
627
- pi --tools read,grep,find,ls -p "Review the code"
70
+ ## Configuration (env flags)
628
71
 
629
- # Disable one extension or built-in tool while keeping the rest available
630
- pi --exclude-tools ask_question
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) |
631
80
 
632
- # High thinking level
633
- pi --thinking high "Solve this complex problem"
634
- ```
81
+ ## Credits
635
82
 
636
- ### Environment Variables
637
-
638
- | Variable | Description |
639
- |----------|-------------|
640
- | `PI_CODING_AGENT_DIR` | Override config directory (default: `~/.pi/agent`) |
641
- | `PI_CODING_AGENT_SESSION_DIR` | Override session storage directory (overridden by `--session-dir`) |
642
- | `PI_PACKAGE_DIR` | Override package directory (useful for Nix/Guix where store paths tokenize poorly) |
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 |
648
-
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
- ---
83
+ Koda is built on **[Pi](https://github.com/earendil-works/pi)** — the excellent open-source terminal coding harness by **Mario Zechner** ([@badlogic](https://github.com/badlogic)). Koda is a fork that rebrands it and adds the OpenAdapter integration and reliability layer described above. Huge thanks to the Pi project and its contributors.
656
84
 
657
85
  ## License
658
86
 
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
87
+ MIT — see [LICENSE](../../LICENSE). Copyright © Mario Zechner (original "pi" project) and OpenAdapter (the "Koda" fork).
@@ -17,6 +17,12 @@
17
17
  export declare function runInteractiveImport(opts?: {
18
18
  auto?: boolean;
19
19
  }): Promise<void>;
20
+ /**
21
+ * Once a day, refresh the OpenAdapter model list from the gateway so users
22
+ * automatically get newly-added models without re-running setup. Best-effort and
23
+ * throttled (24h); KODA_NO_MODEL_REFRESH=1 or KODA_OFFLINE disables.
24
+ */
25
+ export declare function maybeRefreshOpenAdapterModels(agentDir: string): Promise<void>;
20
26
  /** `koda import` — import sessions from other CLIs any time. */
21
27
  export declare function handleImportCommand(args: string[]): Promise<boolean>;
22
28
  /** Run the bundled wizard interactively. Returns true on success. */
@@ -1,3 +1,4 @@
1
- var m=Object.defineProperty;var o=(t,e)=>m(t,"name",{value:e,configurable:!0});import{spawnSync as f}from"node:child_process";import{existsSync as y,readFileSync as p}from"node:fs";import{dirname as h,join as i}from"node:path";import{createInterface as S}from"node:readline/promises";import{fileURLToPath as w}from"node:url";import a from"chalk";import{getPackageDir as C}from"../config.js";import{detectImportable as $,importExternalSessions as g}from"./import-sessions.js";async function I(t,e=!0){const r=S({input:process.stdin,output:process.stdout});try{const n=(await r.question(`${t} ${e?"[Y/n]":"[y/N]"} `)).trim().toLowerCase();return n?n==="y"||n==="yes":e}finally{r.close()}}o(I,"askYesNo");async function c(t){let e;try{e=await $()}catch{return}if(e.claude+e.opencode===0){t?.auto||console.log("No new sessions to import from Claude Code or OpenCode.");return}const n=[e.claude?`${e.claude} from Claude Code`:"",e.opencode?`${e.opencode} from OpenCode`:""].filter(Boolean).join(" and ");if(!await I(a.bold(`Import ${n} into Koda so all your history is here?`)))return;process.stdout.write("Importing\u2026 ");const s=await g({onProgress:o((d,l)=>{process.stdout.write(`\rImporting\u2026 ${d}/${l} `)},"onProgress")});process.stdout.write("\r"),console.log(`\u2713 Imported ${s.imported} session(s) (${s.perSource.claude} Claude Code, ${s.perSource.opencode} OpenCode)${s.errors?`, ${s.errors} skipped`:""}. Find them with \`koda --resume\`.`)}o(c,"runInteractiveImport");async function J(t){return t[0]!=="import"?!1:(await c(),!0)}o(J,"handleImportCommand");function x(){const t=h(w(import.meta.url)),e=[i(C(),"openadapter","setup.mjs"),i(t,"..","..","openadapter","setup.mjs"),i(t,"..","..","..","..","scripts","setup-openadapter.mjs")];for(const r of e)if(y(r))return r;return null}o(x,"findSetupScript");function u(t=[]){const e=x();return e?f(process.execPath,[e,...t],{stdio:"inherit"}).status===0:(console.error(a.red("Koda setup script not found in this install.")),!1)}o(u,"runOpenAdapterSetup");async function L(t){if(t[0]!=="setup")return!1;const e=t.slice(1).find(r=>r.startsWith("sk-"));return u(e?[e]:[]),!0}o(L,"handleSetupCommand");function O(t){try{if(JSON.parse(p(i(t,"settings.json"),"utf-8"))?.defaultProvider==="openadapter")return!1}catch{}try{if(JSON.parse(p(i(t,"models.json"),"utf-8"))?.providers?.openadapter?.apiKey)return!1}catch{}return!0}o(O,"needsOpenAdapterSetup");async function R(t){if(process.env.KODA_SKIP_SETUP!=="1"&&O(t)){console.log(a.bold(`
1
+ var y=Object.defineProperty;var n=(t,e)=>y(t,"name",{value:e,configurable:!0});import{spawnSync as h}from"node:child_process";import{existsSync as S,readFileSync as p,writeFileSync as g}from"node:fs";import{dirname as w,join as i}from"node:path";import{createInterface as O}from"node:readline/promises";import{fileURLToPath as $}from"node:url";import u from"chalk";import{getPackageDir as x}from"../config.js";import{detectImportable as A,importExternalSessions as C}from"./import-sessions.js";async function b(t,e=!0){const r=O({input:process.stdin,output:process.stdout});try{const o=(await r.question(`${t} ${e?"[Y/n]":"[y/N]"} `)).trim().toLowerCase();return o?o==="y"||o==="yes":e}finally{r.close()}}n(b,"askYesNo");async function f(t){let e;try{e=await A()}catch{return}if(e.claude+e.opencode===0){t?.auto||console.log("No new sessions to import from Claude Code or OpenCode.");return}const o=[e.claude?`${e.claude} from Claude Code`:"",e.opencode?`${e.opencode} from OpenCode`:""].filter(Boolean).join(" and ");if(!await b(u.bold(`Import ${o} into Koda so all your history is here?`)))return;process.stdout.write("Importing\u2026 ");const s=await C({onProgress:n((l,c)=>{process.stdout.write(`\rImporting\u2026 ${l}/${c} `)},"onProgress")});process.stdout.write("\r"),console.log(`\u2713 Imported ${s.imported} session(s) (${s.perSource.claude} Claude Code, ${s.perSource.opencode} OpenCode)${s.errors?`, ${s.errors} skipped`:""}. Find them with \`koda --resume\`.`)}n(f,"runInteractiveImport");async function E(t){if(process.env.KODA_NO_MODEL_REFRESH==="1"||process.env.KODA_OFFLINE)return;const e=i(t,"models.json");let r;try{r=JSON.parse(p(e,"utf-8"))}catch{return}const o=r?.providers?.openadapter;if(!o?.apiKey||!o?.baseUrl)return;const d=typeof o.modelsRefreshedAt=="number"?o.modelsRefreshedAt:0;if(!(Date.now()-d<1440*60*1e3))try{const s=await fetch(`${String(o.baseUrl).replace(/\/$/,"")}/models`,{headers:{Authorization:`Bearer ${o.apiKey}`},signal:AbortSignal.timeout(5e3)});if(!s.ok)return;const c=((await s.json()).data??[]).filter(a=>(a.endpoint_format||a.model_type)==="chat");if(c.length===0)return;o.models=c.map(a=>({id:a.id,name:a.id,input:a.supports_vision?["text","image"]:["text"],maxTokens:16e3})),o.modelsRefreshedAt=Date.now(),g(e,`${JSON.stringify(r,null,2)}
2
+ `,"utf-8")}catch{}}n(E,"maybeRefreshOpenAdapterModels");async function J(t){return t[0]!=="import"?!1:(await f(),!0)}n(J,"handleImportCommand");function I(){const t=w($(import.meta.url)),e=[i(x(),"openadapter","setup.mjs"),i(t,"..","..","openadapter","setup.mjs"),i(t,"..","..","..","..","scripts","setup-openadapter.mjs")];for(const r of e)if(S(r))return r;return null}n(I,"findSetupScript");function m(t=[]){const e=I();return e?h(process.execPath,[e,...t],{stdio:"inherit"}).status===0:(console.error(u.red("Koda setup script not found in this install.")),!1)}n(m,"runOpenAdapterSetup");async function L(t){if(t[0]!=="setup")return!1;const e=t.slice(1).find(r=>r.startsWith("sk-"));return m(e?[e]:[]),!0}n(L,"handleSetupCommand");function K(t){try{if(JSON.parse(p(i(t,"settings.json"),"utf-8"))?.defaultProvider==="openadapter")return!1}catch{}try{if(JSON.parse(p(i(t,"models.json"),"utf-8"))?.providers?.openadapter?.apiKey)return!1}catch{}return!0}n(K,"needsOpenAdapterSetup");async function U(t){if(process.env.KODA_SKIP_SETUP!=="1"&&K(t)){console.log(u.bold(`
2
3
  Welcome to Koda \u2014 let's connect it to OpenAdapter (one-time).
3
- `)),u([]),console.log("");try{await c({auto:!0})}catch{}}}o(R,"maybeFirstRunSetup");export{J as handleImportCommand,L as handleSetupCommand,R as maybeFirstRunSetup,O as needsOpenAdapterSetup,c as runInteractiveImport,u as runOpenAdapterSetup};
4
+ `)),m([]),console.log("");try{await f({auto:!0})}catch{}}}n(U,"maybeFirstRunSetup");export{J as handleImportCommand,L as handleSetupCommand,U as maybeFirstRunSetup,E as maybeRefreshOpenAdapterModels,K as needsOpenAdapterSetup,f as runInteractiveImport,m as runOpenAdapterSetup};
package/dist/main.js CHANGED
@@ -1 +1 @@
1
- var ue=Object.defineProperty;var l=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{createInterface as pe}from"node:readline";import{modelsAreEqual as ge}from"@openadapter/koda-ai";import{ProcessTerminal as he,setKeybindings as ve,TUI as Se}from"@openadapter/koda-tui";import c from"chalk";import{parseArgs as we,printHelp as xe}from"./cli/args.js";import{processFileArguments as ye}from"./cli/file-processor.js";import{buildInitialMessage as j}from"./cli/initial-message.js";import{listModels as ke}from"./cli/list-models.js";import{handleImportCommand as Te,handleSetupCommand as Me,maybeFirstRunSetup as Pe}from"./cli/openadapter-setup.js";import{selectSession as Ce}from"./cli/session-picker.js";import{ENV_SESSION_DIR as Ee,expandTildePath as Ie,getAgentDir as D,getPackageDir as Fe,VERSION as Le}from"./config.js";import{createAgentSessionRuntime as be}from"./core/agent-session-runtime.js";import{createAgentSessionFromServices as Ae,createAgentSessionServices as Oe}from"./core/agent-session-services.js";import{formatNoModelsAvailableMessage as $e}from"./core/auth-guidance.js";import{AuthStorage as Re}from"./core/auth-storage.js";import{exportFromFile as Ke}from"./core/export-html/index.js";import{configureHttpDispatcher as _e}from"./core/http-dispatcher.js";import{KeybindingsManager as Ne}from"./core/keybindings.js";import{resolveCliModel as We,resolveModelScope as je}from"./core/model-resolver.js";import{restoreStdout as De,takeOverStdout as He}from"./core/output-guard.js";import{formatMissingSessionCwdPrompt as Be,getMissingSessionCwdIssue as Ve,MissingSessionCwdError as qe}from"./core/session-cwd.js";import{assertValidSessionId as Ue,SessionManager as f}from"./core/session-manager.js";import{SettingsManager as ze}from"./core/settings-manager.js";import{printTimings as C,resetTimings as Ye,time as p}from"./core/timings.js";import{runMigrations as Qe,showDeprecationWarnings as Ge}from"./migrations.js";import{InteractiveMode as Je,runPrintMode as Xe,runRpcMode as Ze}from"./modes/index.js";import{ExtensionSelectorComponent as eo}from"./modes/interactive/components/extension-selector.js";import{initTheme as O,stopThemeWatcher as $}from"./modes/interactive/theme/theme.js";import{handleConfigCommand as oo,handlePackageCommand as to}from"./package-manager-cli.js";import{isLocalPath as no,normalizePath as io,resolvePath as H}from"./utils/paths.js";import{cleanupWindowsSelfUpdateQuarantine as so}from"./utils/windows-self-update.js";async function ro(){if(!process.stdin.isTTY)return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim()||void 0)}),process.stdin.resume()})}l(ro,"readPipedStdin");function B(e,t){return e.drainErrors().map(({scope:n,error:o})=>({type:"warning",message:`(${t}, ${n} settings) ${o.message}`}))}l(B,"collectSettingsDiagnostics");function V(e){for(const t of e){const n=t.type==="error"?c.red:t.type==="warning"?c.yellow:c.dim,o=t.type==="error"?"Error: ":t.type==="warning"?"Warning: ":"";console.error(n(`${o}${t.message}`))}}l(V,"reportDiagnostics");function q(e){return e?e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="yes":!1}l(q,"isTruthyEnvFlag");function ao(e,t){return e.mode==="rpc"?"rpc":e.mode==="json"?"json":e.print||!t?"print":"interactive"}l(ao,"resolveAppMode");function lo(e){return e==="json"?"json":"text"}l(lo,"toPrintOutputMode");async function co(e,t,n){if(e.fileArgs.length===0)return j({parsed:e,stdinContent:n});const{text:o,images:i}=await ye(e.fileArgs,{autoResizeImages:t});return j({parsed:e,fileText:o,fileImages:i,stdinContent:n})}l(co,"prepareInitialMessage");async function U(e,t,n){const i=(await f.list(t,n)).find(s=>s.id===e);return i?{type:"local",path:i.path}:void 0}l(U,"findLocalSessionByExactId");async function z(e,t,n){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:H(e,t)};const o=await f.list(t,n),i=o.find(d=>d.id===e)??o.find(d=>d.id.startsWith(e));if(i)return{type:"local",path:i.path};const s=await f.listAll(n),u=s.find(d=>d.id===e)??s.find(d=>d.id.startsWith(e));return u?{type:"global",path:u.path,cwd:u.cwd}:{type:"not_found",arg:e}}l(z,"resolveSessionPath");async function mo(e){return new Promise(t=>{const n=pe({input:process.stdin,output:process.stdout});n.question(`${e} [y/N] `,o=>{n.close(),t(o.toLowerCase()==="y"||o.toLowerCase()==="yes")})})}l(mo,"promptConfirm");function fo(e){if(!e.fork)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(n=>n!==void 0);t.length>0&&(console.error(c.red(`Error: --fork cannot be combined with ${t.join(", ")}`)),process.exit(1))}l(fo,"validateForkFlags");function uo(e){if(e.sessionId===void 0)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(n=>n!==void 0);t.length>0&&(console.error(c.red(`Error: --session-id cannot be combined with ${t.join(", ")}`)),process.exit(1));try{Ue(e.sessionId)}catch(n){const o=n instanceof Error?n.message:String(n);console.error(c.red(`Error: ${o}`)),process.exit(1)}}l(uo,"validateSessionIdFlags");function Y(e,t,n,o){try{return f.forkFrom(e,t,n,{id:o})}catch(i){const s=i instanceof Error?i.message:String(i);console.error(c.red(`Error: ${s}`)),process.exit(1)}}l(Y,"forkSessionOrExit");async function po(e,t,n,o){if(e.noSession||e.help||e.listModels!==void 0)return f.inMemory(t);if(e.fork){e.sessionId&&await U(e.sessionId,t,n)&&(console.error(c.red(`Session already exists with id '${e.sessionId}'`)),process.exit(1));const i=await z(e.fork,t,n);switch(i.type){case"path":case"local":case"global":return Y(i.path,t,n,e.sessionId);case"not_found":console.error(c.red(`No session found matching '${i.arg}'`)),process.exit(1)}}if(e.session){const i=await z(e.session,t,n);switch(i.type){case"path":case"local":return f.open(i.path,n);case"global":return console.log(c.yellow(`Session found in different project: ${i.cwd}`)),await mo("Fork this session into current directory?")||(console.log(c.dim("Aborted.")),process.exit(0)),Y(i.path,t,n);case"not_found":console.error(c.red(`No session found matching '${i.arg}'`)),process.exit(1)}}if(e.resume){O(o.getTheme(),!0);try{const i=await Ce(s=>f.list(t,n,s),s=>f.listAll(n,s));return i||(console.log(c.dim("No session selected")),process.exit(0)),f.open(i,n)}finally{$()}}if(e.continue)return f.continueRecent(t,n);if(e.sessionId){const i=await U(e.sessionId,t,n);if(i)return f.open(i.path,n)}return f.create(t,n,{id:e.sessionId})}l(po,"createSessionManager");function go(e,t,n,o,i){const s={},u=[];let d=!1;if(e.model){const a=We({cliProvider:e.provider,cliModel:e.model,modelRegistry:o});a.warning&&u.push({type:"warning",message:a.warning}),a.error&&u.push({type:"error",message:a.error}),a.model&&(s.model=a.model,!e.thinking&&a.thinkingLevel&&(s.thinkingLevel=a.thinkingLevel,d=!0))}if(!s.model&&t.length>0&&!n){const a=i.getDefaultProvider(),w=i.getDefaultModel(),h=a&&w?o.find(a,w):void 0,v=h?t.find(y=>ge(y.model,h)):void 0;v?(s.model=v.model,!e.thinking&&v.thinkingLevel&&(s.thinkingLevel=v.thinkingLevel)):(s.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(s.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(s.thinkingLevel=e.thinking),t.length>0&&(s.scopedModels=t.map(a=>({model:a.model,thinkingLevel:a.thinkingLevel}))),e.noTools?s.noTools="all":e.noBuiltinTools&&(s.noTools="builtin"),e.tools&&(s.tools=[...e.tools]),e.excludeTools&&(s.excludeTools=[...e.excludeTools]),{options:s,cliThinkingFromModel:d,diagnostics:u}}l(go,"buildSessionOptions");function E(e,t){return t?.map(n=>no(n)?H(n,e):n)}l(E,"resolveCliPaths");async function ho(e,t){return O(t.getTheme()),ve(Ne.create()),new Promise(n=>{const o=new Se(new he,t.getShowHardwareCursor());o.setClearOnShrink(t.getClearOnShrink());let i=!1;const s=l(d=>{i||(i=!0,o.stop(),n(d))},"finish"),u=new eo(Be(e),["Continue","Cancel"],d=>s(d==="Continue"?e.fallbackCwd:void 0),()=>s(void 0),{tui:o});o.addChild(u),o.setFocus(u),o.start()})}l(ho,"promptForMissingSessionCwd");async function Qo(e,t){if(Ye(),(e.includes("--offline")||q(process.env.KODA_OFFLINE))&&(process.env.KODA_OFFLINE="1",process.env.KODA_SKIP_VERSION_CHECK="1"),process.platform==="win32"&&so(Fe()),await to(e)||await oo(e)||await Me(e)||await Te(e))return;const o=we(e);if(o.diagnostics.length>0){for(const r of o.diagnostics){const m=r.type==="error"?c.red:c.yellow;console.error(m(`${r.type==="error"?"Error":"Warning"}: ${r.message}`))}o.diagnostics.some(r=>r.type==="error")&&process.exit(1)}p("parseArgs");let i=ao(o,process.stdin.isTTY);if(i!=="interactive"&&He(),o.version&&(console.log(Le),process.exit(0)),o.export){let r;try{const m=o.messages.length>0?o.messages[0]:void 0;r=await Ke(o.export,m)}catch(m){const T=m instanceof Error?m.message:"Failed to export session";console.error(c.red(`Error: ${T}`)),process.exit(1)}console.log(`Exported to: ${r}`),process.exit(0)}o.mode==="rpc"&&o.fileArgs.length>0&&(console.error(c.red("Error: @file arguments are not supported in RPC mode")),process.exit(1)),fo(o),uo(o),i==="interactive"&&await Pe(D());const{migratedAuthProviders:u,deprecationWarnings:d}=Qe(process.cwd());p("runMigrations");const a=process.cwd(),w=D(),h=ze.create(a,w);V(B(h,"startup session lookup"));const v=process.env[Ee],y=(o.sessionDir?io(o.sessionDir):void 0)??(v?Ie(v):void 0)??h.getSessionDir();let x=await po(o,a,y,h);const k=Ve(x,a);if(k)if(i==="interactive"){const r=await ho(k,h);r||process.exit(0),x=f.open(k.sessionFile,y,r)}else console.error(c.red(new qe(k).message)),process.exit(1);if(o.name!==void 0){const r=o.name.trim();r||(console.error(c.red("Error: --name requires a non-empty value")),process.exit(1)),x.appendSessionInfo(r)}p("createSessionManager");const Q=E(a,o.extensions),G=E(a,o.skills),J=E(a,o.promptTemplates),X=E(a,o.themes),R=Re.create(),Z=l(async({cwd:r,agentDir:m,sessionManager:T,sessionStartEvent:se})=>{const M=await Oe({cwd:r,agentDir:m,authStorage:R,extensionFlagValues:o.unknownFlags,resourceLoaderOptions:{additionalExtensionPaths:Q,additionalSkillPaths:G,additionalPromptTemplatePaths:J,additionalThemePaths:X,noExtensions:o.noExtensions,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:t?.extensionFactories}}),{settingsManager:L,modelRegistry:W,resourceLoader:re}=M,b=[...M.diagnostics,...B(L,"runtime creation"),...re.getExtensions().errors.map(({path:me,error:fe})=>({type:"error",message:`Failed to load extension "${me}": ${fe}`}))],A=o.models??L.getEnabledModels(),ae=A&&A.length>0?await je(A,W):[],{options:g,cliThinkingFromModel:le,diagnostics:ce}=go(o,ae,T.buildSessionContext().messages.length>0,W,L);b.push(...ce),o.apiKey&&(g.model?R.setRuntimeApiKey(g.model.provider,o.apiKey):b.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"}));const P=await Ae({services:M,sessionManager:T,sessionStartEvent:se,model:g.model,thinkingLevel:g.thinkingLevel,scopedModels:g.scopedModels,tools:g.tools,excludeTools:g.excludeTools,noTools:g.noTools,customTools:g.customTools}),de=o.thinking!==void 0||le;return P.session.model&&de&&P.session.setThinkingLevel(P.session.thinkingLevel),{...P,services:M,diagnostics:b}},"createRuntime");p("createRuntime");const S=await be(Z,{cwd:x.getCwd(),agentDir:w,sessionManager:x});p("createAgentSessionRuntime");const{services:ee,session:oe,modelFallbackMessage:te}=S,{settingsManager:I,modelRegistry:ne,resourceLoader:ie}=ee;if(_e(I.getHttpIdleTimeoutMs()),o.help){const r=ie.getExtensions().extensions.flatMap(m=>Array.from(m.flags.values()));xe(r),process.exit(0)}if(o.listModels!==void 0){const r=typeof o.listModels=="string"?o.listModels:void 0;await ke(ne,r),process.exit(0)}let F;i!=="rpc"&&(F=await ro(),F!==void 0&&i==="interactive"&&(i="print")),p("readPipedStdin");const{initialMessage:K,initialImages:_}=await co(o,I.getImageAutoResize(),F);p("prepareInitialMessage"),O(I.getTheme(),i==="interactive"),p("initTheme"),i==="interactive"&&d.length>0&&await Ge(d),p("resolveModelScope"),V(S.diagnostics),S.diagnostics.some(r=>r.type==="error")&&process.exit(1),p("createAgentSession"),i!=="interactive"&&!oe.model&&(console.error(c.red($e())),process.exit(1));const N=q(process.env.KODA_STARTUP_BENCHMARK);if(N&&i!=="interactive"&&(console.error(c.red("Error: KODA_STARTUP_BENCHMARK only supports interactive mode")),process.exit(1)),i==="rpc")C(),await Ze(S);else if(i==="interactive"){const r=new Je(S,{migratedProviders:u,modelFallbackMessage:te,initialMessage:K,initialImages:_,initialMessages:o.messages,verbose:o.verbose});if(N){await r.init(),p("interactiveMode.init"),C(),r.stop(),$(),process.stdout.writableLength>0&&await new Promise(m=>process.stdout.once("drain",m)),process.stderr.writableLength>0&&await new Promise(m=>process.stderr.once("drain",m));return}C(),await r.run()}else{C();const r=await Xe(S,{mode:lo(i),messages:o.messages,initialMessage:K,initialImages:_});$(),De(),r!==0&&(process.exitCode=r);return}}l(Qo,"main");export{Qo as main};
1
+ var ue=Object.defineProperty;var l=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{createInterface as pe}from"node:readline";import{modelsAreEqual as ge}from"@openadapter/koda-ai";import{ProcessTerminal as he,setKeybindings as ve,TUI as we}from"@openadapter/koda-tui";import c from"chalk";import{parseArgs as Se,printHelp as xe}from"./cli/args.js";import{processFileArguments as ye}from"./cli/file-processor.js";import{buildInitialMessage as D}from"./cli/initial-message.js";import{listModels as ke}from"./cli/list-models.js";import{handleImportCommand as Te,handleSetupCommand as Me,maybeFirstRunSetup as Pe,maybeRefreshOpenAdapterModels as Ce}from"./cli/openadapter-setup.js";import{selectSession as Ee}from"./cli/session-picker.js";import{ENV_SESSION_DIR as Ie,expandTildePath as Fe,getAgentDir as O,getPackageDir as Le,VERSION as be}from"./config.js";import{createAgentSessionRuntime as Ae}from"./core/agent-session-runtime.js";import{createAgentSessionFromServices as Oe,createAgentSessionServices as $e}from"./core/agent-session-services.js";import{formatNoModelsAvailableMessage as Re}from"./core/auth-guidance.js";import{AuthStorage as Ke}from"./core/auth-storage.js";import{exportFromFile as _e}from"./core/export-html/index.js";import{configureHttpDispatcher as Ne}from"./core/http-dispatcher.js";import{KeybindingsManager as We}from"./core/keybindings.js";import{resolveCliModel as je,resolveModelScope as De}from"./core/model-resolver.js";import{restoreStdout as He,takeOverStdout as Be}from"./core/output-guard.js";import{formatMissingSessionCwdPrompt as Ve,getMissingSessionCwdIssue as qe,MissingSessionCwdError as Ue}from"./core/session-cwd.js";import{assertValidSessionId as ze,SessionManager as f}from"./core/session-manager.js";import{SettingsManager as Ye}from"./core/settings-manager.js";import{printTimings as C,resetTimings as Qe,time as p}from"./core/timings.js";import{runMigrations as Ge,showDeprecationWarnings as Je}from"./migrations.js";import{InteractiveMode as Xe,runPrintMode as Ze,runRpcMode as eo}from"./modes/index.js";import{ExtensionSelectorComponent as oo}from"./modes/interactive/components/extension-selector.js";import{initTheme as $,stopThemeWatcher as R}from"./modes/interactive/theme/theme.js";import{handleConfigCommand as to,handlePackageCommand as no}from"./package-manager-cli.js";import{isLocalPath as io,normalizePath as so,resolvePath as H}from"./utils/paths.js";import{cleanupWindowsSelfUpdateQuarantine as ro}from"./utils/windows-self-update.js";async function ao(){if(!process.stdin.isTTY)return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim()||void 0)}),process.stdin.resume()})}l(ao,"readPipedStdin");function B(e,t){return e.drainErrors().map(({scope:n,error:o})=>({type:"warning",message:`(${t}, ${n} settings) ${o.message}`}))}l(B,"collectSettingsDiagnostics");function V(e){for(const t of e){const n=t.type==="error"?c.red:t.type==="warning"?c.yellow:c.dim,o=t.type==="error"?"Error: ":t.type==="warning"?"Warning: ":"";console.error(n(`${o}${t.message}`))}}l(V,"reportDiagnostics");function q(e){return e?e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="yes":!1}l(q,"isTruthyEnvFlag");function lo(e,t){return e.mode==="rpc"?"rpc":e.mode==="json"?"json":e.print||!t?"print":"interactive"}l(lo,"resolveAppMode");function co(e){return e==="json"?"json":"text"}l(co,"toPrintOutputMode");async function mo(e,t,n){if(e.fileArgs.length===0)return D({parsed:e,stdinContent:n});const{text:o,images:i}=await ye(e.fileArgs,{autoResizeImages:t});return D({parsed:e,fileText:o,fileImages:i,stdinContent:n})}l(mo,"prepareInitialMessage");async function U(e,t,n){const i=(await f.list(t,n)).find(s=>s.id===e);return i?{type:"local",path:i.path}:void 0}l(U,"findLocalSessionByExactId");async function z(e,t,n){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:H(e,t)};const o=await f.list(t,n),i=o.find(d=>d.id===e)??o.find(d=>d.id.startsWith(e));if(i)return{type:"local",path:i.path};const s=await f.listAll(n),u=s.find(d=>d.id===e)??s.find(d=>d.id.startsWith(e));return u?{type:"global",path:u.path,cwd:u.cwd}:{type:"not_found",arg:e}}l(z,"resolveSessionPath");async function fo(e){return new Promise(t=>{const n=pe({input:process.stdin,output:process.stdout});n.question(`${e} [y/N] `,o=>{n.close(),t(o.toLowerCase()==="y"||o.toLowerCase()==="yes")})})}l(fo,"promptConfirm");function uo(e){if(!e.fork)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(n=>n!==void 0);t.length>0&&(console.error(c.red(`Error: --fork cannot be combined with ${t.join(", ")}`)),process.exit(1))}l(uo,"validateForkFlags");function po(e){if(e.sessionId===void 0)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(n=>n!==void 0);t.length>0&&(console.error(c.red(`Error: --session-id cannot be combined with ${t.join(", ")}`)),process.exit(1));try{ze(e.sessionId)}catch(n){const o=n instanceof Error?n.message:String(n);console.error(c.red(`Error: ${o}`)),process.exit(1)}}l(po,"validateSessionIdFlags");function Y(e,t,n,o){try{return f.forkFrom(e,t,n,{id:o})}catch(i){const s=i instanceof Error?i.message:String(i);console.error(c.red(`Error: ${s}`)),process.exit(1)}}l(Y,"forkSessionOrExit");async function go(e,t,n,o){if(e.noSession||e.help||e.listModels!==void 0)return f.inMemory(t);if(e.fork){e.sessionId&&await U(e.sessionId,t,n)&&(console.error(c.red(`Session already exists with id '${e.sessionId}'`)),process.exit(1));const i=await z(e.fork,t,n);switch(i.type){case"path":case"local":case"global":return Y(i.path,t,n,e.sessionId);case"not_found":console.error(c.red(`No session found matching '${i.arg}'`)),process.exit(1)}}if(e.session){const i=await z(e.session,t,n);switch(i.type){case"path":case"local":return f.open(i.path,n);case"global":return console.log(c.yellow(`Session found in different project: ${i.cwd}`)),await fo("Fork this session into current directory?")||(console.log(c.dim("Aborted.")),process.exit(0)),Y(i.path,t,n);case"not_found":console.error(c.red(`No session found matching '${i.arg}'`)),process.exit(1)}}if(e.resume){$(o.getTheme(),!0);try{const i=await Ee(s=>f.list(t,n,s),s=>f.listAll(n,s));return i||(console.log(c.dim("No session selected")),process.exit(0)),f.open(i,n)}finally{R()}}if(e.continue)return f.continueRecent(t,n);if(e.sessionId){const i=await U(e.sessionId,t,n);if(i)return f.open(i.path,n)}return f.create(t,n,{id:e.sessionId})}l(go,"createSessionManager");function ho(e,t,n,o,i){const s={},u=[];let d=!1;if(e.model){const a=je({cliProvider:e.provider,cliModel:e.model,modelRegistry:o});a.warning&&u.push({type:"warning",message:a.warning}),a.error&&u.push({type:"error",message:a.error}),a.model&&(s.model=a.model,!e.thinking&&a.thinkingLevel&&(s.thinkingLevel=a.thinkingLevel,d=!0))}if(!s.model&&t.length>0&&!n){const a=i.getDefaultProvider(),S=i.getDefaultModel(),h=a&&S?o.find(a,S):void 0,v=h?t.find(y=>ge(y.model,h)):void 0;v?(s.model=v.model,!e.thinking&&v.thinkingLevel&&(s.thinkingLevel=v.thinkingLevel)):(s.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(s.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(s.thinkingLevel=e.thinking),t.length>0&&(s.scopedModels=t.map(a=>({model:a.model,thinkingLevel:a.thinkingLevel}))),e.noTools?s.noTools="all":e.noBuiltinTools&&(s.noTools="builtin"),e.tools&&(s.tools=[...e.tools]),e.excludeTools&&(s.excludeTools=[...e.excludeTools]),{options:s,cliThinkingFromModel:d,diagnostics:u}}l(ho,"buildSessionOptions");function E(e,t){return t?.map(n=>io(n)?H(n,e):n)}l(E,"resolveCliPaths");async function vo(e,t){return $(t.getTheme()),ve(We.create()),new Promise(n=>{const o=new we(new he,t.getShowHardwareCursor());o.setClearOnShrink(t.getClearOnShrink());let i=!1;const s=l(d=>{i||(i=!0,o.stop(),n(d))},"finish"),u=new oo(Ve(e),["Continue","Cancel"],d=>s(d==="Continue"?e.fallbackCwd:void 0),()=>s(void 0),{tui:o});o.addChild(u),o.setFocus(u),o.start()})}l(vo,"promptForMissingSessionCwd");async function Go(e,t){if(Qe(),(e.includes("--offline")||q(process.env.KODA_OFFLINE))&&(process.env.KODA_OFFLINE="1",process.env.KODA_SKIP_VERSION_CHECK="1"),process.platform==="win32"&&ro(Le()),await no(e)||await to(e)||await Me(e)||await Te(e))return;const o=Se(e);if(o.diagnostics.length>0){for(const r of o.diagnostics){const m=r.type==="error"?c.red:c.yellow;console.error(m(`${r.type==="error"?"Error":"Warning"}: ${r.message}`))}o.diagnostics.some(r=>r.type==="error")&&process.exit(1)}p("parseArgs");let i=lo(o,process.stdin.isTTY);if(i!=="interactive"&&Be(),o.version&&(console.log(be),process.exit(0)),o.export){let r;try{const m=o.messages.length>0?o.messages[0]:void 0;r=await _e(o.export,m)}catch(m){const T=m instanceof Error?m.message:"Failed to export session";console.error(c.red(`Error: ${T}`)),process.exit(1)}console.log(`Exported to: ${r}`),process.exit(0)}o.mode==="rpc"&&o.fileArgs.length>0&&(console.error(c.red("Error: @file arguments are not supported in RPC mode")),process.exit(1)),uo(o),po(o),i==="interactive"&&(await Pe(O()),await Ce(O()));const{migratedAuthProviders:u,deprecationWarnings:d}=Ge(process.cwd());p("runMigrations");const a=process.cwd(),S=O(),h=Ye.create(a,S);V(B(h,"startup session lookup"));const v=process.env[Ie],y=(o.sessionDir?so(o.sessionDir):void 0)??(v?Fe(v):void 0)??h.getSessionDir();let x=await go(o,a,y,h);const k=qe(x,a);if(k)if(i==="interactive"){const r=await vo(k,h);r||process.exit(0),x=f.open(k.sessionFile,y,r)}else console.error(c.red(new Ue(k).message)),process.exit(1);if(o.name!==void 0){const r=o.name.trim();r||(console.error(c.red("Error: --name requires a non-empty value")),process.exit(1)),x.appendSessionInfo(r)}p("createSessionManager");const Q=E(a,o.extensions),G=E(a,o.skills),J=E(a,o.promptTemplates),X=E(a,o.themes),K=Ke.create(),Z=l(async({cwd:r,agentDir:m,sessionManager:T,sessionStartEvent:se})=>{const M=await $e({cwd:r,agentDir:m,authStorage:K,extensionFlagValues:o.unknownFlags,resourceLoaderOptions:{additionalExtensionPaths:Q,additionalSkillPaths:G,additionalPromptTemplatePaths:J,additionalThemePaths:X,noExtensions:o.noExtensions,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:t?.extensionFactories}}),{settingsManager:L,modelRegistry:j,resourceLoader:re}=M,b=[...M.diagnostics,...B(L,"runtime creation"),...re.getExtensions().errors.map(({path:me,error:fe})=>({type:"error",message:`Failed to load extension "${me}": ${fe}`}))],A=o.models??L.getEnabledModels(),ae=A&&A.length>0?await De(A,j):[],{options:g,cliThinkingFromModel:le,diagnostics:ce}=ho(o,ae,T.buildSessionContext().messages.length>0,j,L);b.push(...ce),o.apiKey&&(g.model?K.setRuntimeApiKey(g.model.provider,o.apiKey):b.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"}));const P=await Oe({services:M,sessionManager:T,sessionStartEvent:se,model:g.model,thinkingLevel:g.thinkingLevel,scopedModels:g.scopedModels,tools:g.tools,excludeTools:g.excludeTools,noTools:g.noTools,customTools:g.customTools}),de=o.thinking!==void 0||le;return P.session.model&&de&&P.session.setThinkingLevel(P.session.thinkingLevel),{...P,services:M,diagnostics:b}},"createRuntime");p("createRuntime");const w=await Ae(Z,{cwd:x.getCwd(),agentDir:S,sessionManager:x});p("createAgentSessionRuntime");const{services:ee,session:oe,modelFallbackMessage:te}=w,{settingsManager:I,modelRegistry:ne,resourceLoader:ie}=ee;if(Ne(I.getHttpIdleTimeoutMs()),o.help){const r=ie.getExtensions().extensions.flatMap(m=>Array.from(m.flags.values()));xe(r),process.exit(0)}if(o.listModels!==void 0){const r=typeof o.listModels=="string"?o.listModels:void 0;await ke(ne,r),process.exit(0)}let F;i!=="rpc"&&(F=await ao(),F!==void 0&&i==="interactive"&&(i="print")),p("readPipedStdin");const{initialMessage:_,initialImages:N}=await mo(o,I.getImageAutoResize(),F);p("prepareInitialMessage"),$(I.getTheme(),i==="interactive"),p("initTheme"),i==="interactive"&&d.length>0&&await Je(d),p("resolveModelScope"),V(w.diagnostics),w.diagnostics.some(r=>r.type==="error")&&process.exit(1),p("createAgentSession"),i!=="interactive"&&!oe.model&&(console.error(c.red(Re())),process.exit(1));const W=q(process.env.KODA_STARTUP_BENCHMARK);if(W&&i!=="interactive"&&(console.error(c.red("Error: KODA_STARTUP_BENCHMARK only supports interactive mode")),process.exit(1)),i==="rpc")C(),await eo(w);else if(i==="interactive"){const r=new Xe(w,{migratedProviders:u,modelFallbackMessage:te,initialMessage:_,initialImages:N,initialMessages:o.messages,verbose:o.verbose});if(W){await r.init(),p("interactiveMode.init"),C(),r.stop(),R(),process.stdout.writableLength>0&&await new Promise(m=>process.stdout.once("drain",m)),process.stderr.writableLength>0&&await new Promise(m=>process.stderr.once("drain",m));return}C(),await r.run()}else{C();const r=await Ze(w,{mode:co(i),messages:o.messages,initialMessage:_,initialImages:N});R(),He(),r!==0&&(process.exitCode=r);return}}l(Go,"main");export{Go as main};
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@openadapter/koda",
3
- "version": "1.0.0-beta.5",
3
+ "version": "1.0.0-beta.7",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@openadapter/koda",
9
- "version": "1.0.0-beta.5",
9
+ "version": "1.0.0-beta.7",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
- "@openadapter/koda-agent-core": "1.0.0-beta.5",
13
- "@openadapter/koda-ai": "1.0.0-beta.5",
14
- "@openadapter/koda-tui": "1.0.0-beta.5",
12
+ "@openadapter/koda-agent-core": "1.0.0-beta.7",
13
+ "@openadapter/koda-ai": "1.0.0-beta.7",
14
+ "@openadapter/koda-tui": "1.0.0-beta.7",
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.5",
703
- "resolved": "https://registry.npmjs.org/@openadapter/koda-agent-core/-/koda-agent-core-1.0.0-beta.5.tgz",
702
+ "version": "1.0.0-beta.7",
703
+ "resolved": "https://registry.npmjs.org/@openadapter/koda-agent-core/-/koda-agent-core-1.0.0-beta.7.tgz",
704
704
  "license": "MIT",
705
705
  "dependencies": {
706
- "@openadapter/koda-ai": "1.0.0-beta.5",
706
+ "@openadapter/koda-ai": "1.0.0-beta.7",
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.5",
717
- "resolved": "https://registry.npmjs.org/@openadapter/koda-ai/-/koda-ai-1.0.0-beta.5.tgz",
716
+ "version": "1.0.0-beta.7",
717
+ "resolved": "https://registry.npmjs.org/@openadapter/koda-ai/-/koda-ai-1.0.0-beta.7.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.5",
740
- "resolved": "https://registry.npmjs.org/@openadapter/koda-tui/-/koda-tui-1.0.0-beta.5.tgz",
739
+ "version": "1.0.0-beta.7",
740
+ "resolved": "https://registry.npmjs.org/@openadapter/koda-tui/-/koda-tui-1.0.0-beta.7.tgz",
741
741
  "license": "MIT",
742
742
  "dependencies": {
743
743
  "get-east-asian-width": "1.6.0",
@@ -105,6 +105,8 @@ mergeJson(join(AGENT_DIR, "models.json"), (cfg) => {
105
105
  apiKey: key,
106
106
  api: "openai-completions",
107
107
  models,
108
+ // Stamp so the daily auto-refresh doesn't immediately re-fetch right after setup.
109
+ modelsRefreshedAt: Date.now(),
108
110
  };
109
111
  });
110
112
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openadapter/koda",
3
- "version": "1.0.0-beta.5",
3
+ "version": "1.0.0-beta.7",
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.5",
46
- "@openadapter/koda-ai": "1.0.0-beta.5",
47
- "@openadapter/koda-tui": "1.0.0-beta.5",
45
+ "@openadapter/koda-agent-core": "1.0.0-beta.7",
46
+ "@openadapter/koda-ai": "1.0.0-beta.7",
47
+ "@openadapter/koda-tui": "1.0.0-beta.7",
48
48
  "@silvia-odwyer/photon-node": "0.3.4",
49
49
  "chalk": "5.6.2",
50
50
  "cross-spawn": "7.0.6",