@ywldan/kiro 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +429 -2
  3. package/dist/agent/compact.js +133 -0
  4. package/dist/agent/compact.js.map +1 -0
  5. package/dist/agent/loop.js +253 -0
  6. package/dist/agent/loop.js.map +1 -0
  7. package/dist/agent/prompt.js +53 -0
  8. package/dist/agent/prompt.js.map +1 -0
  9. package/dist/agent/tokens.js +36 -0
  10. package/dist/agent/tokens.js.map +1 -0
  11. package/dist/config.js +382 -0
  12. package/dist/config.js.map +1 -0
  13. package/dist/env.js +203 -0
  14. package/dist/env.js.map +1 -0
  15. package/dist/index.js +272 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/model/cli-ui.js +458 -0
  18. package/dist/model/cli-ui.js.map +1 -0
  19. package/dist/model/cli.js +382 -0
  20. package/dist/model/cli.js.map +1 -0
  21. package/dist/model/contexts.js +61 -0
  22. package/dist/model/contexts.js.map +1 -0
  23. package/dist/model/discovery.js +225 -0
  24. package/dist/model/discovery.js.map +1 -0
  25. package/dist/model/presets.js +60 -0
  26. package/dist/model/presets.js.map +1 -0
  27. package/dist/model/wizard.js +663 -0
  28. package/dist/model/wizard.js.map +1 -0
  29. package/dist/providers/index.js +10 -0
  30. package/dist/providers/index.js.map +1 -0
  31. package/dist/providers/openai.js +422 -0
  32. package/dist/providers/openai.js.map +1 -0
  33. package/dist/providers/types.js +19 -0
  34. package/dist/providers/types.js.map +1 -0
  35. package/dist/secrets.js +63 -0
  36. package/dist/secrets.js.map +1 -0
  37. package/dist/sessions.js +248 -0
  38. package/dist/sessions.js.map +1 -0
  39. package/dist/tools/diff.js +32 -0
  40. package/dist/tools/diff.js.map +1 -0
  41. package/dist/tools/fs.js +524 -0
  42. package/dist/tools/fs.js.map +1 -0
  43. package/dist/tools/glob.js +105 -0
  44. package/dist/tools/glob.js.map +1 -0
  45. package/dist/tools/ignore.js +63 -0
  46. package/dist/tools/ignore.js.map +1 -0
  47. package/dist/tools/index.js +65 -0
  48. package/dist/tools/index.js.map +1 -0
  49. package/dist/tools/patch.js +191 -0
  50. package/dist/tools/patch.js.map +1 -0
  51. package/dist/tools/paths.js +85 -0
  52. package/dist/tools/paths.js.map +1 -0
  53. package/dist/tools/search.js +553 -0
  54. package/dist/tools/search.js.map +1 -0
  55. package/dist/tools/shell.js +189 -0
  56. package/dist/tools/shell.js.map +1 -0
  57. package/dist/tools/types.js +16 -0
  58. package/dist/tools/types.js.map +1 -0
  59. package/dist/ui/App.js +1074 -0
  60. package/dist/ui/App.js.map +1 -0
  61. package/dist/ui/ApprovalPrompt.js +48 -0
  62. package/dist/ui/ApprovalPrompt.js.map +1 -0
  63. package/dist/ui/Input.js +213 -0
  64. package/dist/ui/Input.js.map +1 -0
  65. package/dist/ui/MessageList.js +214 -0
  66. package/dist/ui/MessageList.js.map +1 -0
  67. package/dist/ui/ModelPicker.js +100 -0
  68. package/dist/ui/ModelPicker.js.map +1 -0
  69. package/dist/ui/StatusBar.js +63 -0
  70. package/dist/ui/StatusBar.js.map +1 -0
  71. package/dist/ui/approval-policy.js +22 -0
  72. package/dist/ui/approval-policy.js.map +1 -0
  73. package/dist/ui/commands.js +30 -0
  74. package/dist/ui/commands.js.map +1 -0
  75. package/dist/ui/export.js +65 -0
  76. package/dist/ui/export.js.map +1 -0
  77. package/dist/ui/history.js +86 -0
  78. package/dist/ui/history.js.map +1 -0
  79. package/dist/ui/markdown.js +285 -0
  80. package/dist/ui/markdown.js.map +1 -0
  81. package/dist/ui/model-picker.js +59 -0
  82. package/dist/ui/model-picker.js.map +1 -0
  83. package/dist/ui/mouse.js +36 -0
  84. package/dist/ui/mouse.js.map +1 -0
  85. package/dist/ui/profile-list.js +40 -0
  86. package/dist/ui/profile-list.js.map +1 -0
  87. package/dist/ui/text.js +328 -0
  88. package/dist/ui/text.js.map +1 -0
  89. package/dist/ui/types.js +3 -0
  90. package/dist/ui/types.js.map +1 -0
  91. package/dist/version.js +2 -0
  92. package/dist/version.js.map +1 -0
  93. package/package.json +58 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ywildan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,430 @@
1
- # Temporary Holding Version
1
+ # Kiro
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small terminal-based AI coding agent, in the spirit of Codex CLI and Claude Code. Kiro streams model output into an Ink TUI, calls tools to read, edit, and run code in your working directory, and asks before doing anything destructive.
4
+
5
+ Phase 1 (MVP) supports OpenAI-compatible chat-completions endpoints: OpenAI itself, OpenRouter, Ollama, LM Studio, vLLM, and anything else that speaks `POST {baseUrl}/chat/completions` with SSE streaming and tool calls. A built-in model workflow (`kiro model`) discovers models from the endpoint, tests the connection, and stores keys outside the config file.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js 20 or newer
10
+ - pnpm, only when building from source (npm works too, but the lockfile and scripts assume pnpm)
11
+ - An OpenAI-compatible endpoint and, if the endpoint requires one, an API key
12
+
13
+ ## Install
14
+
15
+ From npm:
16
+
17
+ ```bash
18
+ npm install -g @ywldan/kiro
19
+ ```
20
+
21
+ Then run `kiro` from any project directory.
22
+
23
+ From source:
24
+
25
+ ```bash
26
+ pnpm install
27
+ pnpm build
28
+
29
+ # pnpm 11+
30
+ pnpm add -g .
31
+
32
+ # pnpm 9/10
33
+ # pnpm link --global
34
+ ```
35
+
36
+ If `kiro` is not found after a pnpm global install, pnpm's global bin directory is not on your `PATH`; run `pnpm setup` once, add `~/.local/share/pnpm/bin` to `PATH`, or invoke the binary by its full path.
37
+
38
+ You can also run it without linking:
39
+
40
+ ```bash
41
+ node dist/index.js
42
+ # or, during development:
43
+ pnpm dev
44
+ ```
45
+
46
+ ## Quick start
47
+
48
+ ```bash
49
+ cd ~/src/my-project
50
+ kiro model # choose "Add a new model", pick a provider, paste your key
51
+ kiro # start talking to it
52
+ ```
53
+
54
+ The wizard fetches the endpoint's model list, stores the key in `~/.kiro/.env` (mode `0600`), verifies that a real chat completion works, and can make the new profile active immediately. `~/.kiro/config.json` is created on first use and never contains the key itself.
55
+
56
+ In a terminal the wizard runs on the alternate screen and redraws in place: you always see the current step only, with a breadcrumb of what you already answered (`Choose a provider: Custom endpoint · Base URL: https://…`) across the top. Each entry is labelled with the menu's own title rather than the generic `Choose`, and pressing Enter on a default records the value that was kept instead of `(default)`; `Esc` clears the breadcrumb, and errors from an abandoned step do not follow you into the next one. Long lists are trimmed to the window height so the prompt never scrolls off, and each step replaces the previous menu instead of adding to the scrollback. When a list is longer than the window, a dim indicator shows how much is hidden and you can move through it while the prompt is active: `↑`/`↓` one line, `PgUp`/`PgDn` a page, `Home` the first entry, `End` back to the newest; any new message jumps back to the bottom. When you quit, the screen is restored and the results (saved profile, active profile, where the key went) are printed once. Piped or non-interactive output falls back to plain sequential printing.
57
+
58
+ Prefer no prompts?
59
+
60
+ ```bash
61
+ export OPENROUTER_API_KEY="sk-or-..."
62
+ kiro model add --name openrouter --base-url https://openrouter.ai/api/v1 \
63
+ --model anthropic/claude-sonnet-4 --api-key-env OPENROUTER_API_KEY --set-active
64
+ kiro
65
+ ```
66
+
67
+ Set `KIRO_CONFIG_PATH` to use a different config file (useful for testing).
68
+
69
+ ## Managing models
70
+
71
+ Kiro keeps named connection profiles. `kiro model` opens a guided menu:
72
+
73
+ ```
74
+ Model workflow
75
+ 1. Select the active model
76
+ 2. Add a new model
77
+ 3. Edit a model
78
+ 4. Remove a model
79
+ 5. Quit
80
+ ```
81
+
82
+ ### Adding a model
83
+
84
+ 1. Pick a preset or **Custom endpoint**.
85
+ 2. Confirm or edit the base URL.
86
+ 3. Confirm or edit the environment variable that will hold the key, then paste the key (input is masked). Local presets skip both steps.
87
+ 4. Kiro requests `GET {baseUrl}/models` and shows the result. Enter a number, type part of an id to filter, or enter `0` to type the id manually. If discovery fails or returns an empty list, Kiro explains why and asks for the model id.
88
+ 5. Accept the suggested profile name or type your own. Names use letters, digits, `-`, and `_`, and must be unique.
89
+ 6. Optionally set `temperature`, `maxTokens`, and `contextWindow` (defaults `0.2`, `4096`, and `128000`).
90
+ 7. Kiro sends a tiny non-tool chat completion ("Reply with OK"). It reports success and latency, or the exact error (auth, 404, rate limit, timeout, bad JSON, unreachable host). A failure offers **Retry**, **Edit connection fields**, **Save anyway**, or **Cancel**.
91
+ 8. Confirm **Set as active profile?** (`Y/n`).
92
+
93
+ `Esc` or `Ctrl+C` cancels any step. Cancelling leaves both `config.json` and `.env` untouched.
94
+
95
+ ### Presets
96
+
97
+ | Provider | Base URL | Key variable |
98
+ | --- | --- | --- |
99
+ | OpenRouter | `https://openrouter.ai/api/v1` | `OPENROUTER_API_KEY` |
100
+ | OpenAI | `https://api.openai.com/v1` | `OPENAI_API_KEY` |
101
+ | Groq | `https://api.groq.com/openai/v1` | `GROQ_API_KEY` |
102
+ | DeepSeek | `https://api.deepseek.com/v1` | `DEEPSEEK_API_KEY` |
103
+ | Together | `https://api.together.xyz/v1` | `TOGETHER_API_KEY` |
104
+ | Ollama (local) | `http://localhost:11434/v1` | none |
105
+ | LM Studio (local) | `http://localhost:1234/v1` | none |
106
+ | Custom endpoint | you enter it | optional |
107
+
108
+ Presets only prefill the base URL and the suggested variable name; every field remains editable.
109
+
110
+ ### Scripted commands
111
+
112
+ ```bash
113
+ kiro model # wizard: select / add / edit / remove
114
+ kiro model list # configured profiles, active marked
115
+ kiro model use <name> # make a profile active
116
+ kiro model remove <name> # delete a profile (refuses the last one)
117
+ kiro model test [name] # small chat completion, reports latency or error
118
+
119
+ kiro model add --name <name> --base-url <url> --model <id> \
120
+ [--api-key-env <VAR>] [--api-key <key>] \
121
+ [--temperature <0-2>] [--max-tokens <n>] [--set-active] [--no-test]
122
+ ```
123
+
124
+ `--flag=value` works as well. `add` validates the URL, name, model, and numbers before saving; a failed connection test saves nothing (use `--no-test` to skip the test). Success exits `0`; validation, network, and test failures exit non-zero with a clear message on stderr.
125
+
126
+ Key handling for `kiro model add`:
127
+
128
+ - `--api-key <key>` writes the key to `~/.kiro/.env` under `--api-key-env`, or under a generated `KIRO_<PROFILE_NAME>_API_KEY`.
129
+ - `--api-key-env <VAR>` with no key stores nothing; it references the variable, which must already be set in the environment or in `~/.kiro/.env`.
130
+ - Omitting both creates a profile with no key, suitable for local servers.
131
+
132
+ ### Where keys live
133
+
134
+ The config file contains only `apiKeyEnv`, the *name* of a variable. Values live in the environment or in `~/.kiro/.env`:
135
+
136
+ ```
137
+ # ~/.kiro/.env
138
+ OPENROUTER_API_KEY=sk-or-...
139
+ ```
140
+
141
+ - The file is created on demand with mode `0600`; its directory uses `0700` (best effort on platforms without POSIX modes).
142
+ - At startup Kiro loads `~/.kiro/.env` first, then real environment variables override it.
143
+ - Updating a key rewrites only that line, preserving comments and other variables. Removing a profile leaves its secret in `.env` so another profile can reuse it.
144
+ - Keys are never written to `config.json`, sessions, logs, or the TUI. Kiro shows `set via $VAR`, `missing ($VAR)`, or a mask such as `sk-…abcd`.
145
+ - Values in `.env` and every profile's `apiKeyEnv` are also withheld from the environment of `run_command` and redacted from tool output, so `env`, `printenv`, or `cat ~/.kiro/.env` cannot copy a key into the transcript, the model's context, or a saved session.
146
+
147
+ Set `KIRO_ENV_PATH` to use a different `.env` file (useful for testing).
148
+
149
+ ## Configuration
150
+
151
+ `~/.kiro/config.json`:
152
+
153
+ ```json
154
+ {
155
+ "activeProfile": "openai",
156
+ "profiles": {
157
+ "openai": {
158
+ "type": "openai",
159
+ "baseUrl": "https://api.openai.com/v1",
160
+ "apiKeyEnv": "OPENAI_API_KEY",
161
+ "model": "gpt-4.1",
162
+ "temperature": 0.2,
163
+ "maxTokens": 4096,
164
+ "contextWindow": 128000
165
+ },
166
+ "local": {
167
+ "type": "openai",
168
+ "baseUrl": "http://localhost:11434/v1",
169
+ "model": "qwen2.5-coder:14b",
170
+ "temperature": 0.2
171
+ }
172
+ }
173
+ }
174
+ ```
175
+
176
+ | Field | Required | Meaning |
177
+ | --- | --- | --- |
178
+ | `type` | yes | Provider type. Only `openai` is implemented in Phase 1. |
179
+ | `baseUrl` | yes | API base URL including the version segment, e.g. `https://api.openai.com/v1`. Kiro appends `/chat/completions`. |
180
+ | `apiKeyEnv` | no | Name of the environment variable holding the API key. Omit for local servers that need no auth. |
181
+ | `model` | yes | Model name sent to the endpoint. |
182
+ | `models` | no | Model ids the `/model` picker offers for this profile. Filled by discovery; the model in use is always included. |
183
+ | `temperature` | no | Sampling temperature. |
184
+ | `maxTokens` | no | Maximum response tokens. |
185
+ | `contextWindow` | no | Approximate model context window in tokens, at least 1000. Defaults to `128000`; drives the ctx meter and automatic compaction. |
186
+
187
+ `activeProfile` selects the profile used at startup. `/model <name>` switches at runtime; `--profile` switches per run.
188
+
189
+ ### Example endpoints
190
+
191
+ **OpenRouter** (key from `~/.kiro/.env` or the environment)
192
+
193
+ ```bash
194
+ export OPENROUTER_API_KEY="sk-or-..."
195
+ kiro model add --name openrouter \
196
+ --base-url https://openrouter.ai/api/v1 \
197
+ --model anthropic/claude-sonnet-4 \
198
+ --api-key-env OPENROUTER_API_KEY --set-active
199
+ ```
200
+
201
+ **Ollama** (no key; discovery normally works, but a manually pulled tag can be entered instead)
202
+
203
+ ```bash
204
+ kiro model add --name ollama \
205
+ --base-url http://localhost:11434/v1 \
206
+ --model qwen2.5-coder:14b --set-active
207
+ ```
208
+
209
+ **LM Studio / vLLM / another OpenAI-compatible server**
210
+
211
+ ```bash
212
+ kiro model add --name local \
213
+ --base-url http://localhost:1234/v1 \
214
+ --model local-model --set-active
215
+
216
+ # A server without GET /models: skip discovery by naming the model directly,
217
+ # and skip the test if it is not running yet.
218
+ kiro model add --name vllm \
219
+ --base-url http://gpu-box:8000/v1 \
220
+ --model my-model --no-test
221
+ ```
222
+
223
+ If you prefer hand-editing, the JSON form above is still supported; `kiro model` → **Edit a model** can also update fields afterwards and re-test.
224
+
225
+ ## CLI options
226
+
227
+ ```
228
+ kiro [options]
229
+
230
+ --profile <name> Use a profile from ~/.kiro/config.json
231
+ --base-url <url> Override the active profile's base URL
232
+ --model <name> Override the active profile's model
233
+ -c, --continue Resume the most recent session for this directory
234
+ --resume <id> Resume a specific saved session
235
+ --yolo Skip all approval prompts (use with care)
236
+ --mouse Mouse reporting (on by default): wheel scrolls the transcript
237
+ --no-mouse Disable mouse reporting so plain click-drag selection works
238
+ --no-alt-screen Do not switch to the terminal's alternate screen
239
+ -h, --help Show help
240
+ -v, --version Show version
241
+ ```
242
+
243
+ `--flag=value` works as well. CLI overrides last for the current process only.
244
+
245
+ ## Using the TUI
246
+
247
+ | Key | Action |
248
+ | --- | --- |
249
+ | `Enter` | Send the prompt, or run the highlighted `/` command |
250
+ | `Ctrl+C` | Cancel the running turn; press again to exit |
251
+ | `PgUp` / `PgDn` | Scroll the history (the wheel works too, unless you pass `--no-mouse`) |
252
+ | `Ctrl+O` | Expand or collapse the full output of the most recent tool call |
253
+ | `↑` / `↓` | Move through the `/` command menu |
254
+ | `Tab` | Complete the highlighted `/` command |
255
+ | `Esc` | Clear the input, close the command menu, cancel a model wizard step, or deny a pending approval |
256
+ | `Ctrl+A` / `Ctrl+E` | Move to start / end of input |
257
+ | `Backspace` / `Delete` | Delete before / after the cursor |
258
+ | `Ctrl+U` / `Ctrl+K` | Delete before / after the cursor |
259
+ | `Ctrl+W` | Delete the previous word |
260
+ | Left / Right / Home / End | Move the cursor |
261
+
262
+ The status bar shows the active profile and model, the working directory, the context meter (`ctx 42k/128k`), and the current state (`ready`, `thinking…`, `retrying (n/3)…`, `running <tool>…`, `approval needed`, `cancelling…`). A long profile name is shortened in the middle, so the model and directory stay readable.
263
+
264
+ Assistant replies are rendered as Markdown: headings, bold/italic, inline code, bullet and numbered lists, task checkboxes, blockquotes, links, and fenced code blocks. Unknown or incomplete markers fall back to their literal text, so streaming never breaks the layout.
265
+
266
+ Typing `/` opens a command palette above the input. It filters as you type, `↑`/`↓` select a command, `Enter` runs it, and `Tab` completes it. `Esc` clears the input.
267
+
268
+ On a real TTY, `kiro` switches to the terminal's alternate screen: you get a clean page instead of the TUI drawing underneath the command you just ran. When Kiro exits — `/exit`, `Ctrl+C`, or an error — the terminal restores the previous shell contents and prompt. Redirected output (pipes, CI logs) is left untouched. Pass `--no-alt-screen` to stay on the normal screen instead.
269
+
270
+ Mouse reporting is **on by default**, so the wheel scrolls the transcript. The cost is that the terminal hands clicks to Kiro instead of starting a text selection: to copy text, hold Shift while dragging (or your terminal's equivalent), or run `/mouse` — or start with `--no-mouse` — to get plain click-drag selection back, scrolling with `PgUp`/`PgDn` instead. `/mouse` toggles it at any time.
271
+
272
+ Tool results are shown as a one-line summary. `Ctrl+O` expands the most recent one inline — full text, scrollable with `PgUp`/`PgDn` — and `/export` writes the whole conversation, including complete tool arguments and results, to a Markdown file you can open and copy from.
273
+
274
+ Slash commands:
275
+
276
+ | Command | Action |
277
+ | --- | --- |
278
+ | `/help` | Show commands and keys |
279
+ | `/model` | Open the model picker: profile first, then its stored models |
280
+ | `/model <name>` | Switch profile without restarting |
281
+ | `/model add` | Guided setup; prompts appear in the input box and the key is masked |
282
+ | `/model edit [name]` | Edit fields, replace the key, re-test, and save |
283
+ | `/model remove [name]` | Remove a profile after confirmation (refuses the last one) |
284
+ | `/model test [name]` | Test the active or named profile; prints latency or the exact error |
285
+ | `/model list --remote` | List models offered by the active endpoint's `GET /models` |
286
+ | `/context` | Show approximate context use, broken down by message role |
287
+ | `/compact` | Summarize older turns now, keeping the last four user turns verbatim |
288
+ | `/sessions` | List saved sessions for this working directory |
289
+ | `/resume <n\|id>` | Resume a session by list number or id (prefixes work) |
290
+ | `/clear` | Start a new session, keeping the old one on disk |
291
+ | `/export [file]` | Write the transcript (with full tool output) to a Markdown file |
292
+ | `/mouse` | Toggle mouse reporting: wheel scroll vs normal text selection |
293
+ | `/allow` | List tools that skip approval for this session |
294
+ | `/allow clear` | Ask for approval again for every tool |
295
+ | `/exit` | Quit |
296
+
297
+ `/model` opens a two-step picker. The first step lists profiles grouped by endpoint (the active one is marked `*`); `Enter` opens that profile's models. The second step lists the ids stored in the profile's `models` field with the one in use marked `*`; `Enter` applies it, switches to that profile, and saves the choice to `config.json`. `↑`/`↓` move, `Esc` goes back one step (or closes the picker), and `Ctrl+C` closes it. Press `r` on the model step to refetch `GET /models` from that endpoint and store the result; later switches need no network. A profile with no stored list still shows its current model, and adding a profile through the wizard stores whatever discovery returned for it.
298
+
299
+ ## Sessions
300
+
301
+ Kiro saves the conversation automatically. Each working directory gets its own directory under `~/.kiro/sessions/`, keyed by a hash of the absolute path:
302
+
303
+ ```
304
+ ~/.kiro/sessions/<cwd-hash>/<session-id>.json
305
+ ```
306
+
307
+ A session stores the user, assistant, and tool messages, the title (the first prompt), the creation/update times, and the profile/model in use. System prompts are not stored; they are rebuilt for the current directory on every turn. Writes are atomic (temp file plus rename), the directory is created with mode `0700`, and session files are written with mode `0600`.
308
+
309
+ Saving happens after the user message is accepted and again when a turn finishes, so a crash loses at most the in-flight response. Ctrl+C and `/exit` wait for the pending save before leaving. Set `KIRO_SESSIONS_DIR` to store sessions somewhere other than `~/.kiro/sessions`.
310
+
311
+ Resume with:
312
+
313
+ ```bash
314
+ kiro --continue # most recent session for this directory
315
+ kiro --resume <id> # a specific session
316
+ ```
317
+
318
+ or from inside the TUI with `/sessions` and `/resume <n|id>`. Resuming restores the visible transcript and continues the same conversation; `/clear` starts a fresh session without deleting the old one. There is no auto-resume: without a flag, Kiro always starts a new session.
319
+
320
+ Session files are plaintext and contain your prompts, code snippets returned by tools, and command output. They never contain API keys (keys live only in `~/.kiro/.env` or the environment), but treat them like shell history.
321
+
322
+ ## Context and compaction
323
+
324
+ Kiro tracks how much of the model's context window the conversation is using. The OpenAI provider sends `stream_options: { include_usage: true }` and uses the endpoint's reported `usage` when it arrives. Servers that ignore the option still work: Kiro falls back to an estimate of roughly four characters per token. The status bar shows `ctx <used>/<window>`, and `/context` breaks the total down by message role.
325
+
326
+ Each profile may set `contextWindow` (default `128000`). At about 80% of that window, before the next model request, Kiro compacts the conversation automatically:
327
+
328
+ - the system prompt is kept;
329
+ - the last four user turns, together with their assistant and tool messages, stay verbatim;
330
+ - older turns become a structured summary covering the goal, files touched, decisions, current state, and open TODOs;
331
+ - very large old tool results are replaced by a short placeholder before summarizing, so the summarizer is not flooded;
332
+ - the cut is always made at a user-message boundary, so an assistant tool-call round is never separated from its tool results.
333
+
334
+ Compaction appears as a notice in the transcript and is written into the session, so resuming continues from the compacted history. `/compact` runs the same pass on demand. If the summary request fails, the turn continues with the uncompacted context and an error notice. Counts are approximate; server-reported usage corrects them after each response.
335
+
336
+ ## Tools and safety
337
+
338
+ | Tool | What it does | Approval |
339
+ | --- | --- | --- |
340
+ | `read_file(path, offset?, limit?)` | Reads a file with numbered lines and truncation notes | never |
341
+ | `list_dir(path)` | Lists one directory, with `/` after directories | never |
342
+ | `glob(pattern, path?)` | Finds files by glob, e.g. `src/**/*.ts`. Respects `.gitignore`; skips `node_modules`, `.git`, `dist`, `build`; caps at 200 results | never |
343
+ | `grep(pattern, path?, glob?, ignore_case?, context_lines?, max_results?)` | Regex search returning `file:line: text`. Uses `rg` when installed, otherwise a built-in scanner that skips binary and large files | never |
344
+ | `write_file(path, content)` | Creates or overwrites a file, creating parent directories | always (except `--yolo`) |
345
+ | `edit_file(path, old_string, new_string, replace_all?)` | Exact replacement; `replace_all` replaces every occurrence. Missing text returns a hint with the closest line | always (except `--yolo`) |
346
+ | `multi_edit(path, edits[])` | Several exact replacements in one file, validated together and written once | always (except `--yolo`) |
347
+ | `apply_patch(patch)` | Applies a unified diff to one or more files after validating every hunk | always (except `--yolo`) |
348
+ | `run_command(command, timeout_seconds?)` | Runs a shell command in the working directory | always (except `--yolo`) |
349
+
350
+ Search first, then read: `grep` and `glob` keep large repositories manageable, and `read_file` supports paging for the files that matter. `multi_edit` is the right choice for several changes in one file; `apply_patch` handles coordinated multi-file changes and validates the whole patch before writing anything. `apply_patch` supports creating files but rejects deletions and renames.
351
+
352
+ Approval prompts show a diff for writes, edits, multi-edits, and patches, or the exact command for shell runs, and offer:
353
+
354
+ - `[y]` allow once
355
+ - `[a]` always allow this tool for the rest of the session (the status bar then shows `auto:<tool>`, and `/allow clear` takes it back)
356
+ - `[n]` deny (the denial is returned to the model, which can try another approach)
357
+
358
+ Paths are resolved relative to the working directory. Symlinks and `..` tricks that escape it are detected with `realpath`; reads, listings, searches, and listings outside the workspace are refused, while writes, edits, and patches outside it require an explicit approval warning. `run_command` has a default 60-second timeout (maximum 600), kills the whole process group on timeout or cancel, and truncates output to roughly 20k characters, keeping the head and tail. `read_file` defaults to 400 lines (maximum 2000) and points the model at the next offset when there is more. `glob`/`grep` honour `.gitignore`, always skip `node_modules`, `.git`, `dist`, and `build`, and cap their output with a note telling the model how to narrow the search. As a last resort, every tool result is capped at 60k characters with a note and a hint about narrower requests, so a single call cannot flood the context.
359
+
360
+ Read-only tools (`read_file`, `list_dir`, `glob`, `grep`) that the model requests in one response run in parallel; results are appended in the original call order. Any write, edit, patch, or command breaks the batch and runs sequentially with its approval prompt.
361
+
362
+ `--yolo` skips all approvals: the status bar shows a red `YOLO` badge, the first line of the transcript warns about it, and `/help` reminds you. It cannot be turned off from inside the session — restart without the flag. Use it only in a directory you trust.
363
+
364
+ ## AGENTS.md
365
+
366
+ If an `AGENTS.md` file exists in the working directory, its contents are appended to the system prompt for every turn, so project-specific instructions apply immediately, including after edits.
367
+
368
+ ## How it works
369
+
370
+ - The OpenAI provider posts to `{baseUrl}/chat/completions` with `stream: true`, parses SSE incrementally, and assembles tool-call deltas by index. It also accepts a plain JSON response from servers that ignore streaming, and reads `usage` when the endpoint sends it.
371
+ - Before each model round, Kiro checks the context estimate (corrected by the last reported usage) against the profile's `contextWindow`. At ~80% it replaces older turns with a model-written summary, keeps the last four user turns, and then sends the request.
372
+ - When a profile has no explicit `contextWindow`, Kiro infers one from the model id (a size suffix such as `-32k`, else a family table: `gpt-4o` 128k, `gpt-4` 8k, `o1`/`o3` 200k, `claude-3/4` 200k, `gemini` 1M, `llama-3.1` 128k, …) and falls back to 128k for unknown ids. `/context` says whether the number is inferred; set `contextWindow` in the profile to pin it.
373
+ - If the endpoint still rejects a request as too long (HTTP 400/413 with a context-length message), Kiro forces a compaction and retries that round once instead of ending the turn with a bare error.
374
+ - `finish_reason: length` is reported: a truncated answer, or tool-call arguments cut off by `max_tokens`, produces an explicit notice instead of a confusing tool error.
375
+ - A "cheap" placeholder pass shrinks old tool results before they are summarized; the discarded messages never reach the model again after compaction.
376
+ - The agent loop streams assistant text live, appends the assistant message with its tool calls, executes contiguous read-only calls in parallel and everything else sequentially, appends tool results in call order, and repeats. A turn is capped at 25 tool rounds.
377
+ - Transient failures are retried up to three times with exponential backoff and jitter: network errors, connection drops before any output, HTTP 429, and 5xx. `Retry-After` is honoured (capped at 60 seconds), and the TUI shows `retrying (n/3)…`. A 400/401/403/404, a malformed stream, a cancel, or a failure after partial text is never retried. Set `KIRO_RETRY_BASE_MS` to change the base backoff (default 500ms).
378
+ - Malformed tool-call JSON, unknown tool names, non-zero exits, and timeouts are returned to the model as tool errors rather than crashing the session.
379
+ - Ctrl+C aborts the HTTP stream and any running command; partial assistant text is preserved.
380
+ - Sessions are saved atomically after each user message and completed turn, and are restored by rebuilding the visible transcript from the stored messages.
381
+ - Model discovery calls `GET {baseUrl}/models` with a 10-second timeout; the connection test sends one tiny non-tool chat completion with the same timeout. Both can be cancelled.
382
+ - Config saves are atomic and merge into the file on disk, so fields Kiro does not know about are preserved. Invalid JSON can be backed up and replaced with a fresh template.
383
+ - Keys are never written to `config.json`, sessions, or logs. They live in `~/.kiro/.env` (mode `0600`) or the real environment, and the config stores only `apiKeyEnv`; actual values are never printed, are stripped from `run_command`'s environment, and are redacted from tool output before it reaches the model.
384
+
385
+ ## Testing
386
+
387
+ ```bash
388
+ pnpm test # backend tests against an in-process mock OpenAI-compatible server
389
+ pnpm mock # start the mock server on port 8787 for manual TUI testing
390
+ ```
391
+
392
+ The mock server is scripted: it streams a text response with `write_file` and `list_dir` calls, then a `run_command` call, then a final answer, followed by multi-write and slow-streaming turns for approval and cancellation testing. It can also serve `GET /models` (with a configurable list or a forced `401`/`404`), return HTTP errors with custom headers such as `Retry-After`, drop the connection mid-stream, and records model-discovery and chat requests, including auth headers. Point a test profile at `http://localhost:8787/v1` and any model name; no key is needed.
393
+
394
+ The suite covers streaming, multiple tool calls per response, approvals and denials, malformed tool JSON, the round cap, HTTP errors, malformed SSE, unreachable endpoints, retries for 429/5xx and connection drops, no retry after partial output or a 401, the retry limit, read-only batching and ordered results, the global result cap, abort, workspace escapes, read paging, edit uniqueness, command exit codes and timeouts, output truncation, config validation, missing keys, system-prompt/`AGENTS.md` injection, and session persistence. Search tests cover glob matching, `.gitignore` handling, heavy-directory skips, result caps, ripgrep and the built-in grep fallback, binary/large-file skipping, and invalid regexes. Editing tests cover `replace_all`, near-miss hints, atomic multi-edits, and patch validation for updates, new files, conflicts, and rejected deletions. Context tests cover `stream_options` and usage parsing, token estimates and formatting, the 80% threshold, compaction boundaries, kept tool-call rounds, the old-result placeholder pass, empty-summary rejection, loop-level compaction (once per turn, non-fatal failures), persistence of compacted sessions, the `ctx` status-bar meter, and `contextWindow` config/wizard handling. Session tests cover atomic save/load, file permissions, per-directory isolation, sorting, corrupt-file skipping, id validation, and reconstruction of resumed tool blocks and statuses. TUI unit tests cover Markdown styles and wrapping, slash-command filtering/shared help text, and SGR mouse-wheel parsing; pty runs exercise the command palette, mouse and PgUp/PgDn scrolling, Markdown rendering, approvals, and cancellation.
395
+
396
+ Model workflow tests use a temp `$HOME` so the real `~/.kiro` is never touched. They cover atomic config saves that preserve unknown fields, profile-name and URL validation, corrupt-config backup/recovery, `.env` parsing and real-environment precedence, `0600` writes, masking, the exact preset list, discovery success/401/missing-`/models`/timeout, the connection test, and wizard add/edit/select/remove/last-profile refusal/cancel/manual-model fallback. Scripted `kiro model add`, `list`, `use`, `test`, and `remove` run through the real CLI against the in-process mock; a failed test saves nothing, keys never appear in `config.json`, and generated keys land in `.env`. The wizard screen renderer is unit-tested against a fake stream: alternate-screen enter/leave, a new menu replacing the previous one, the breadcrumb of answered prompts (menu title instead of `Choose`, the value kept by pressing Enter, confirmation of a `Y/n` default, and the reset on Escape or a return to the root menu), stale errors dropped at a step change, log trimming to the terminal height with the prompt always visible, keyboard scrolling of an over-long list (page, top, bottom, clamping, reset on new output), and replaying results after the screen is restored. `/model` groups profiles by endpoint so several models behind one base URL are listed as siblings.
397
+
398
+ ## Project layout
399
+
400
+ ```
401
+ src/
402
+ index.tsx CLI entry point
403
+ config.ts config load/validation/overrides, atomic save, recovery
404
+ env.ts ~/.kiro/.env parser/writer, masking, key status
405
+ secrets.ts credential registry: redaction and child-process env filtering
406
+ sessions.ts atomic session save/load/list
407
+ model/ presets, discovery/test, context-window inference, shared wizard, CLI + screen renderer
408
+ providers/ Provider interface, OpenAI-compatible implementation
409
+ agent/ system prompt, agent loop, token estimates, compaction
410
+ tools/ tool registry, fs/search/patch/shell tools, glob/gitignore matching
411
+ ui/ Ink app, markdown, command palette, scrolling, approvals, status bar, export
412
+ test/
413
+ mock-server.ts scripted OpenAI-compatible SSE server + /models variants
414
+ e2e.ts backend test suite
415
+ ```
416
+
417
+ ## Known limitations
418
+
419
+ - Only the `openai` provider type. Anthropic-style APIs are not supported.
420
+ - Model discovery assumes an OpenAI-compatible `GET /models`. Endpoints without it work, but the model id must be typed manually.
421
+ - Removing a profile leaves its key in `~/.kiro/.env`; there is no command that deletes stored secrets.
422
+ - No sub-agents, MCP, plugins, web search, image input, themes, or git integration.
423
+ - Sessions are single-process and stored as plaintext JSON. There is no delete or rename command and no cross-directory session browser; `/export` writes a Markdown transcript you can keep or copy from.
424
+ - Only contiguous read-only tool calls run in parallel; writes, edits, patches, and commands stay sequential.
425
+ - Context use is approximate when the endpoint does not report usage, and compaction depends on the model producing a usable summary. `/compact` is the manual escape hatch.
426
+ - Markdown support covers the common subset; tables, images, and syntax highlighting are shown as plain text.
427
+ - Mouse reporting is on by default and takes over click-drag selection; use Shift+drag to copy, or `--no-mouse` / `/mouse` to turn it off and scroll with `PgUp`/`PgDn`.
428
+ - The context-window inference is a best-effort guess. For an unusual or self-hosted model, set `contextWindow` explicitly or compaction will trigger too late.
429
+ - The TUI targets Linux, macOS, and Windows Terminal; Windows-specific process-kill behavior is implemented via `taskkill` but has not been exercised on a real Windows machine.
430
+ - Very narrow terminals and unusually long approval previews are clipped rather than paginated.
@@ -0,0 +1,133 @@
1
+ import { estimateMessagesTokens } from './tokens.js';
2
+ export const COMPACT_THRESHOLD = 0.8;
3
+ export const COMPACT_KEEP_USER_TURNS = 4;
4
+ export const PLACEHOLDER_TOOL_RESULT_CHARS = 2_000;
5
+ export const MAX_SUMMARY_INPUT_CHARS = 100_000;
6
+ const MAX_TRANSCRIPT_MESSAGE_CHARS = 4_000;
7
+ const TOOL_ARGS_PREVIEW_CHARS = 500;
8
+ export const SUMMARY_PREFIX = '[Context summary — earlier turns were compacted to save space]';
9
+ export function shouldCompact(usedTokens, contextWindow, threshold = COMPACT_THRESHOLD) {
10
+ return contextWindow > 0 && usedTokens >= Math.floor(contextWindow * threshold);
11
+ }
12
+ function isSummaryMessage(message) {
13
+ return message.role === 'user' && (message.content ?? '').startsWith(SUMMARY_PREFIX);
14
+ }
15
+ /**
16
+ * Index where the last `keepUserTurns` real user turns begin. Everything before
17
+ * it can be summarized. Returns -1 when there is not enough history, or when the
18
+ * boundary would be the first message (nothing older to summarize).
19
+ */
20
+ export function findCompactBoundary(messages, keepUserTurns) {
21
+ const userIndices = [];
22
+ messages.forEach((message, index) => {
23
+ if (message.role === 'user' && !isSummaryMessage(message))
24
+ userIndices.push(index);
25
+ });
26
+ if (userIndices.length <= keepUserTurns)
27
+ return -1;
28
+ const boundary = userIndices[userIndices.length - keepUserTurns];
29
+ return boundary > 0 ? boundary : -1;
30
+ }
31
+ function truncateMiddle(text, max) {
32
+ if (text.length <= max)
33
+ return text;
34
+ const head = Math.floor(max * 0.4);
35
+ const tail = max - head;
36
+ return `${text.slice(0, head)}\n… [${text.length - max} characters omitted] …\n${text.slice(-tail)}`;
37
+ }
38
+ function placeholderForToolResult(message) {
39
+ const size = message.content?.length ?? 0;
40
+ if (size <= PLACEHOLDER_TOOL_RESULT_CHARS)
41
+ return message.content ?? '';
42
+ const name = message.name ?? 'tool';
43
+ return `[${name} result omitted during compaction: ${size.toLocaleString()} characters]`;
44
+ }
45
+ function transcriptLine(message) {
46
+ if (message.role === 'tool') {
47
+ return `TOOL (${message.name ?? 'unknown'}): ${placeholderForToolResult(message)}`;
48
+ }
49
+ if (message.role === 'assistant') {
50
+ const body = truncateMiddle(message.content ?? '', MAX_TRANSCRIPT_MESSAGE_CHARS);
51
+ const calls = message.tool_calls
52
+ ?.map((call) => {
53
+ const args = truncateMiddle(call.function.arguments, TOOL_ARGS_PREVIEW_CHARS);
54
+ return ` -> ${call.function.name}(${args})`;
55
+ })
56
+ .join('\n') ?? '';
57
+ return `ASSISTANT: ${body}${calls ? `\n${calls}` : ''}`.trim();
58
+ }
59
+ if (message.role === 'user') {
60
+ return `USER: ${truncateMiddle(message.content ?? '', MAX_TRANSCRIPT_MESSAGE_CHARS)}`;
61
+ }
62
+ return `SYSTEM: ${truncateMiddle(message.content ?? '', MAX_TRANSCRIPT_MESSAGE_CHARS)}`;
63
+ }
64
+ const SUMMARY_SYSTEM_PROMPT = [
65
+ 'You compress earlier parts of a coding-assistant conversation into a handoff note.',
66
+ 'The assistant will continue the same task after compaction, so preserve facts it needs.',
67
+ 'Write plain text with exactly these headings:',
68
+ 'Goal:',
69
+ 'Files touched:',
70
+ 'Decisions:',
71
+ 'Current state:',
72
+ 'Open TODOs:',
73
+ 'Be concise and specific. Mention file paths, commands, and errors that matter.',
74
+ 'Never invent details that are not in the transcript. If something is unknown, say so.',
75
+ ].join('\n');
76
+ async function summarizeOlderMessages(older, provider, signal) {
77
+ const transcript = truncateMiddle(older.map(transcriptLine).join('\n\n'), MAX_SUMMARY_INPUT_CHARS);
78
+ const request = [
79
+ { role: 'system', content: SUMMARY_SYSTEM_PROMPT },
80
+ {
81
+ role: 'user',
82
+ content: `Summarize this earlier part of the conversation for the next turn.\n\n${transcript}`,
83
+ },
84
+ ];
85
+ let text = '';
86
+ for await (const event of provider.stream(request, [], { signal })) {
87
+ if (event.type === 'text')
88
+ text += event.text;
89
+ }
90
+ const trimmed = text.trim();
91
+ if (!trimmed)
92
+ throw new Error('The model returned an empty compaction summary.');
93
+ return trimmed;
94
+ }
95
+ /**
96
+ * Replaces older turns with a structured model-written summary while keeping
97
+ * the system prompt and the last `keepUserTurns` user turns verbatim.
98
+ * The boundary is always a user message, so assistant tool calls never lose
99
+ * their tool results.
100
+ */
101
+ export async function compactMessages(options) {
102
+ const { messages, provider, signal } = options;
103
+ const keepUserTurns = Math.max(1, options.keepUserTurns ?? COMPACT_KEEP_USER_TURNS);
104
+ const boundary = findCompactBoundary(messages, keepUserTurns);
105
+ if (boundary === -1)
106
+ return null;
107
+ const leadingSystem = [];
108
+ let index = 0;
109
+ while (messages[index]?.role === 'system') {
110
+ leadingSystem.push(messages[index]);
111
+ index++;
112
+ }
113
+ const older = messages.slice(index, boundary);
114
+ if (older.length === 0)
115
+ return null;
116
+ if (signal?.aborted)
117
+ throw new Error('Compaction cancelled.');
118
+ const summary = await summarizeOlderMessages(older, provider, signal);
119
+ const summaryMessage = {
120
+ role: 'user',
121
+ content: `${SUMMARY_PREFIX}\n\n${summary}`,
122
+ };
123
+ const kept = messages.slice(boundary);
124
+ const next = [...leadingSystem, summaryMessage, ...kept];
125
+ return {
126
+ messages: next,
127
+ summary,
128
+ beforeTokens: estimateMessagesTokens(messages),
129
+ afterTokens: estimateMessagesTokens(next),
130
+ summarizedMessages: older.length,
131
+ };
132
+ }
133
+ //# sourceMappingURL=compact.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compact.js","sourceRoot":"","sources":["../../src/agent/compact.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErD,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AACrC,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,6BAA6B,GAAG,KAAK,CAAC;AACnD,MAAM,CAAC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAC/C,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAC3C,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,MAAM,CAAC,MAAM,cAAc,GAAG,gEAAgE,CAAC;AAkB/F,MAAM,UAAU,aAAa,CAC3B,UAAkB,EAClB,aAAqB,EACrB,SAAS,GAAG,iBAAiB;IAE7B,OAAO,aAAa,GAAG,CAAC,IAAI,UAAU,IAAI,IAAI,CAAC,KAAK,CAAC,aAAa,GAAG,SAAS,CAAC,CAAC;AAClF,CAAC;AAED,SAAS,gBAAgB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