@ywldan/kiro 0.1.1 → 0.2.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 (62) hide show
  1. package/README.md +46 -4
  2. package/dist/agent/loop.js +3 -0
  3. package/dist/headless.js +219 -0
  4. package/dist/index.js +56 -7
  5. package/dist/providers/openai.js +101 -4
  6. package/dist/tools/checkpoint.js +158 -0
  7. package/dist/tools/fs.js +4 -0
  8. package/dist/tools/patch.js +2 -0
  9. package/dist/ui/App.js +128 -14
  10. package/dist/ui/Input.js +42 -1
  11. package/dist/ui/MessageList.js +26 -1
  12. package/dist/ui/StatusBar.js +3 -2
  13. package/dist/ui/commands.js +1 -0
  14. package/dist/ui/prompt-history.js +69 -0
  15. package/dist/ui/types.js +2 -0
  16. package/dist/version.js +1 -1
  17. package/package.json +2 -1
  18. package/dist/agent/compact.js.map +0 -1
  19. package/dist/agent/loop.js.map +0 -1
  20. package/dist/agent/prompt.js.map +0 -1
  21. package/dist/agent/tokens.js.map +0 -1
  22. package/dist/config.js.map +0 -1
  23. package/dist/env.js.map +0 -1
  24. package/dist/index.js.map +0 -1
  25. package/dist/model/cli-ui.js.map +0 -1
  26. package/dist/model/cli.js.map +0 -1
  27. package/dist/model/contexts.js.map +0 -1
  28. package/dist/model/discovery.js.map +0 -1
  29. package/dist/model/presets.js.map +0 -1
  30. package/dist/model/wizard.js.map +0 -1
  31. package/dist/providers/index.js.map +0 -1
  32. package/dist/providers/openai.js.map +0 -1
  33. package/dist/providers/types.js.map +0 -1
  34. package/dist/secrets.js.map +0 -1
  35. package/dist/sessions.js.map +0 -1
  36. package/dist/tools/diff.js.map +0 -1
  37. package/dist/tools/fs.js.map +0 -1
  38. package/dist/tools/glob.js.map +0 -1
  39. package/dist/tools/ignore.js.map +0 -1
  40. package/dist/tools/index.js.map +0 -1
  41. package/dist/tools/patch.js.map +0 -1
  42. package/dist/tools/paths.js.map +0 -1
  43. package/dist/tools/search.js.map +0 -1
  44. package/dist/tools/shell.js.map +0 -1
  45. package/dist/tools/types.js.map +0 -1
  46. package/dist/ui/App.js.map +0 -1
  47. package/dist/ui/ApprovalPrompt.js.map +0 -1
  48. package/dist/ui/Input.js.map +0 -1
  49. package/dist/ui/MessageList.js.map +0 -1
  50. package/dist/ui/ModelPicker.js.map +0 -1
  51. package/dist/ui/StatusBar.js.map +0 -1
  52. package/dist/ui/approval-policy.js.map +0 -1
  53. package/dist/ui/commands.js.map +0 -1
  54. package/dist/ui/export.js.map +0 -1
  55. package/dist/ui/history.js.map +0 -1
  56. package/dist/ui/markdown.js.map +0 -1
  57. package/dist/ui/model-picker.js.map +0 -1
  58. package/dist/ui/mouse.js.map +0 -1
  59. package/dist/ui/profile-list.js.map +0 -1
  60. package/dist/ui/text.js.map +0 -1
  61. package/dist/ui/types.js.map +0 -1
  62. package/dist/version.js.map +0 -1
package/README.md CHANGED
@@ -232,6 +232,9 @@ kiro [options]
232
232
  --model <name> Override the active profile's model
233
233
  -c, --continue Resume the most recent session for this directory
234
234
  --resume <id> Resume a specific saved session
235
+ -p, --prompt <text>
236
+ Run one turn without a TUI ("-" or no text reads the
237
+ prompt from stdin); replies stream to stdout
235
238
  --yolo Skip all approval prompts (use with care)
236
239
  --mouse Mouse reporting (on by default): wheel scrolls the transcript
237
240
  --no-mouse Disable mouse reporting so plain click-drag selection works
@@ -242,6 +245,24 @@ kiro [options]
242
245
 
243
246
  `--flag=value` works as well. CLI overrides last for the current process only.
244
247
 
248
+ ## Headless mode
249
+
250
+ `kiro -p "…"` runs a single turn without Ink, for scripts, cron jobs, and CI:
251
+
252
+ ```bash
253
+ kiro -p "explain what this repo does" # read-only answers work immediately
254
+ kiro -p "add the missing tests" --yolo # let it write and run commands
255
+ git diff | kiro -p "review this patch" # pipe the prompt
256
+ kiro -p "continue" --continue # continue this directory's session
257
+ echo "summarize README.md" | kiro -p - > summary.md # "-" reads stdin
258
+ ```
259
+
260
+ Assistant text goes to **stdout**; tool calls, reasoning, compaction notices, and errors go to **stderr**, so `kiro -p … > out.md` stays clean. The turn uses the same provider, tools, system prompt, compaction, and session store as the TUI, and the session is saved when it finishes.
261
+
262
+ Approvals are denied in headless mode unless you pass `--yolo`: a piped run never performs an unsupervised write or command. When a read-only tool is enough, leave `--yolo` off.
263
+
264
+ Exit codes: `0` success, `1` model/tool/session error, `2` usage error (including a missing prompt), `130` cancelled with Ctrl+C. Prompt history is not recorded for headless runs. Set `KIRO_STREAM_IDLE_MS` to change the stall timeout (default 120000 ms; `0` disables it).
265
+
245
266
  ## Using the TUI
246
267
 
247
268
  | Key | Action |
@@ -250,7 +271,7 @@ kiro [options]
250
271
  | `Ctrl+C` | Cancel the running turn; press again to exit |
251
272
  | `PgUp` / `PgDn` | Scroll the history (the wheel works too, unless you pass `--no-mouse`) |
252
273
  | `Ctrl+O` | Expand or collapse the full output of the most recent tool call |
253
- | `↑` / `↓` | Move through the `/` command menu |
274
+ | `↑` / `↓` | Move through the `/` command menu; with an empty input, recall prompt history |
254
275
  | `Tab` | Complete the highlighted `/` command |
255
276
  | `Esc` | Clear the input, close the command menu, cancel a model wizard step, or deny a pending approval |
256
277
  | `Ctrl+A` / `Ctrl+E` | Move to start / end of input |
@@ -259,7 +280,13 @@ kiro [options]
259
280
  | `Ctrl+W` | Delete the previous word |
260
281
  | Left / Right / Home / End | Move the cursor |
261
282
 
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.
283
+ The status bar shows the active profile and model, the working directory, the context meter (`ctx 42k/128k`), the number of queued messages, 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.
284
+
285
+ The input stays enabled while the agent works: type the next prompt and press Enter to queue it, and it runs as soon as the current turn ends. Queued prompts appear in the transcript right away, the status bar shows `N queued`, and Ctrl+C clears the queue together with the running turn. Slash commands typed while busy are queued the same way.
286
+
287
+ Prompt history is stored per working directory in `~/.kiro/history/` (mode `0600`, up to 200 entries). With an empty input, `↑` recalls the most recent prompt, `↓` walks forward again, and editing the recalled text leaves history mode. Registered API-key values are redacted before a prompt is written. Set `KIRO_HISTORY_DIR` to store the files elsewhere.
288
+
289
+ Reasoning models stream their thinking traces live as a dim `thinking…` block. Once the visible answer starts, the trace collapses to a single `reasoning (done, not saved)` line: traces are display-only and are never written to sessions or `/export`.
263
290
 
264
291
  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
292
 
@@ -287,6 +314,7 @@ Slash commands:
287
314
  | `/compact` | Summarize older turns now, keeping the last four user turns verbatim |
288
315
  | `/sessions` | List saved sessions for this working directory |
289
316
  | `/resume <n\|id>` | Resume a session by list number or id (prefixes work) |
317
+ | `/undo` | Revert the most recent write, edit, or patch (repeat to step further back) |
290
318
  | `/clear` | Start a new session, keeping the old one on disk |
291
319
  | `/export [file]` | Write the transcript (with full tool output) to a Markdown file |
292
320
  | `/mouse` | Toggle mouse reporting: wheel scroll vs normal text selection |
@@ -361,6 +389,12 @@ Read-only tools (`read_file`, `list_dir`, `glob`, `grep`) that the model request
361
389
 
362
390
  `--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
391
 
392
+ ### Undo and checkpoints
393
+
394
+ Before every `write_file`, `edit_file`, `multi_edit`, or `apply_patch`, Kiro copies the affected files into `~/.kiro/checkpoints/<cwd-hash>/` (mode `0700`, backups `0600`). `/undo` restores the most recent call: edited files get their previous bytes back, and files the call created are deleted. Running `/undo` again steps further back through the 30 most recent calls.
395
+
396
+ Checkpoints are best effort: if a snapshot cannot be taken, the tool still runs. `run_command` is **not** checkpointed, because a shell command can touch anything; commit before letting Kiro run destructive commands. Set `KIRO_CHECKPOINTS_DIR` to store snapshots elsewhere. The manifest records backup paths, not file contents, so it stays small even in large repositories.
397
+
364
398
  ## AGENTS.md
365
399
 
366
400
  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.
@@ -368,6 +402,8 @@ If an `AGENTS.md` file exists in the working directory, its contents are appende
368
402
  ## How it works
369
403
 
370
404
  - 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.
405
+ - OpenAI reasoning models (`o1`/`o3`/`o4`, `gpt-5`) automatically switch from `max_tokens` to `max_completion_tokens` and omit a custom temperature. If any other endpoint rejects `max_tokens` with a 400/422 that names `max_completion_tokens`, Kiro retries once with the new parameter without consuming a retry slot. Thinking deltas from `reasoning_content`, `reasoning`, and OpenRouter's `reasoning_details` are streamed to the TUI and never persisted.
406
+ - A stream with no bytes for `KIRO_STREAM_IDLE_MS` (default 120 seconds, `0` disables) is cancelled and retried like a dropped connection, instead of hanging the TUI forever.
371
407
  - 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
408
  - 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
409
  - 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.
@@ -377,6 +413,7 @@ If an `AGENTS.md` file exists in the working directory, its contents are appende
377
413
  - 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
414
  - 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
415
  - Ctrl+C aborts the HTTP stream and any running command; partial assistant text is preserved.
416
+ - `kiro -p` runs the same agent loop without Ink, streams assistant text to stdout and diagnostics to stderr, denies tool calls unless `--yolo` is given, and saves the session like the TUI.
380
417
  - Sessions are saved atomically after each user message and completed turn, and are restored by rebuilding the visible transcript from the stored messages.
381
418
  - 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
419
  - 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.
@@ -395,11 +432,14 @@ The suite covers streaming, multiple tool calls per response, approvals and deni
395
432
 
396
433
  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
434
 
435
+ The newer paths have their own coverage: `max_completion_tokens` selection for reasoning models and recovery from a `max_tokens` rejection, `reasoning_content` deltas reaching the agent and collapsing in the renderer, the stream idle timeout, checkpoint edit/create undo with backup files outside the manifest, and prompt-history dedupe/capping/redaction. A spawned `kiro -p` test runs a tool with `--yolo`, checks the reply and saved session, feeds a piped prompt through `-p -`, and verifies the non-TTY hint without `-p`.
436
+
398
437
  ## Project layout
399
438
 
400
439
  ```
401
440
  src/
402
441
  index.tsx CLI entry point
442
+ headless.ts one-shot -p runner (stdout text, stderr diagnostics)
403
443
  config.ts config load/validation/overrides, atomic save, recovery
404
444
  env.ts ~/.kiro/.env parser/writer, masking, key status
405
445
  secrets.ts credential registry: redaction and child-process env filtering
@@ -407,8 +447,8 @@ src/
407
447
  model/ presets, discovery/test, context-window inference, shared wizard, CLI + screen renderer
408
448
  providers/ Provider interface, OpenAI-compatible implementation
409
449
  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
450
+ tools/ tool registry, fs/search/patch/shell tools, checkpoints, glob/gitignore matching
451
+ ui/ Ink app, markdown, command palette, prompt history, scrolling, approvals, status bar, export
412
452
  test/
413
453
  mock-server.ts scripted OpenAI-compatible SSE server + /models variants
414
454
  e2e.ts backend test suite
@@ -421,6 +461,8 @@ test/
421
461
  - Removing a profile leaves its key in `~/.kiro/.env`; there is no command that deletes stored secrets.
422
462
  - No sub-agents, MCP, plugins, web search, image input, themes, or git integration.
423
463
  - 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.
464
+ - `/undo` covers `write_file`, `edit_file`, `multi_edit`, and `apply_patch` only. It keeps the last 30 calls, and `run_command` changes are outside its reach; use Git for a complete safety net.
465
+ - Prompt history is plaintext, capped at 200 entries per directory, and only recalled in the TUI (not in `-p` mode).
424
466
  - Only contiguous read-only tool calls run in parallel; writes, edits, patches, and commands stay sequential.
425
467
  - 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
468
  - Markdown support covers the common subset; tables, images, and syntax highlighting are shown as plain text.
@@ -90,6 +90,9 @@ export async function* runAgentTurn(options) {
90
90
  else if (event.type === 'usage') {
91
91
  yield { type: 'usage', usage: event.usage };
92
92
  }
93
+ else if (event.type === 'reasoning') {
94
+ yield { type: 'reasoning', text: event.text };
95
+ }
93
96
  else if (event.type === 'finish') {
94
97
  finishReason = event.reason;
95
98
  }
@@ -0,0 +1,219 @@
1
+ import { buildSystemPrompt } from './agent/prompt.js';
2
+ import { runAgentTurn } from './agent/loop.js';
3
+ import { COMPACT_KEEP_USER_TURNS, COMPACT_THRESHOLD, compactMessages, shouldCompact, } from './agent/compact.js';
4
+ import { contextWindowFor } from './config.js';
5
+ import { estimateMessagesTokens } from './agent/tokens.js';
6
+ import { createProvider } from './providers/index.js';
7
+ import { dropIncompleteToolCalls, latestSession, loadSession, newSessionId, saveSession, titleFromMessages, } from './sessions.js';
8
+ import { redactSecrets } from './secrets.js';
9
+ /**
10
+ * One-shot agent run without a TUI: `kiro -p "fix the tests"`.
11
+ * Text streams to stdout; notices, tool calls, and reasoning go to stderr, so
12
+ * `kiro -p … > out.md` stays clean for scripting. Same session store, system
13
+ * prompt, compaction, and tools as the TUI. Approvals are denied outside
14
+ * --yolo mode — a piped run never performs an unsupervised mutation.
15
+ */
16
+ export async function runHeadless(options) {
17
+ const { config, cwd, yolo } = options;
18
+ const stderr = process.stderr;
19
+ const writeOut = process.stdout.write.bind(process.stdout);
20
+ const prompt = (options.prompt ?? (await readStdinPrompt())).trim();
21
+ if (!prompt) {
22
+ stderr.write('Kiro: no prompt given. Pass one with -p "…", or pipe text into stdin.\n');
23
+ return 2;
24
+ }
25
+ let session = null;
26
+ try {
27
+ if (options.resumeId) {
28
+ session = await loadSession(cwd, options.resumeId);
29
+ if (!session) {
30
+ stderr.write(`Kiro: session "${options.resumeId}" was not found for this directory.\n`);
31
+ return 1;
32
+ }
33
+ }
34
+ else if (options.continueLatest) {
35
+ session = await latestSession(cwd);
36
+ }
37
+ }
38
+ catch (error) {
39
+ stderr.write(`Kiro: ${error instanceof Error ? error.message : String(error)}\n`);
40
+ return 1;
41
+ }
42
+ const profile = config.profiles[config.activeProfile];
43
+ if (!profile) {
44
+ stderr.write(`Kiro: config has no profile "${config.activeProfile}".\n`);
45
+ return 1;
46
+ }
47
+ const apiKey = profile.apiKeyEnv ? process.env[profile.apiKeyEnv] : undefined;
48
+ if (profile.apiKeyEnv && !apiKey) {
49
+ stderr.write(`Kiro: API key is missing: $${profile.apiKeyEnv} is not set (profile "${config.activeProfile}").\n`);
50
+ return 1;
51
+ }
52
+ let provider;
53
+ try {
54
+ provider = createProvider(profile, apiKey);
55
+ }
56
+ catch (error) {
57
+ stderr.write(`Kiro: ${error instanceof Error ? error.message : String(error)}\n`);
58
+ return 1;
59
+ }
60
+ const warnedTools = new Set();
61
+ const ctx = {
62
+ cwd,
63
+ signal: options.signal,
64
+ approve: yolo
65
+ ? () => Promise.resolve('allow')
66
+ : (request) => {
67
+ if (!warnedTools.has(request.tool)) {
68
+ warnedTools.add(request.tool);
69
+ stderr.write(`# ${request.tool} denied: headless runs never approve tool calls. ` +
70
+ `Run Kiro interactively, or pass --yolo to allow every tool.\n`);
71
+ }
72
+ return Promise.resolve('deny');
73
+ },
74
+ };
75
+ const notice = (line) => {
76
+ stderr.write(`# ${redactSecrets(line).replace(/\s+/g, ' ')}\n`);
77
+ };
78
+ try {
79
+ const systemPrompt = await buildSystemPrompt(cwd);
80
+ const working = [
81
+ { role: 'system', content: systemPrompt },
82
+ ...((session?.messages ?? []).filter((message) => message.role !== 'system')),
83
+ ];
84
+ working.push({ role: 'user', content: prompt });
85
+ const record = session
86
+ ? session
87
+ : {
88
+ version: 1,
89
+ id: newSessionId(),
90
+ cwd: cwd,
91
+ profile: config.activeProfile,
92
+ model: profile.model,
93
+ title: titleFromMessages(working),
94
+ createdAt: new Date().toISOString(),
95
+ updatedAt: new Date().toISOString(),
96
+ messages: [],
97
+ };
98
+ const window = contextWindowFor(profile);
99
+ const compactContext = async (items, signal, compactOptions) => {
100
+ const used = estimateMessagesTokens(items);
101
+ if (!compactOptions?.force && !shouldCompact(used, window, COMPACT_THRESHOLD))
102
+ return null;
103
+ try {
104
+ const result = await compactMessages({
105
+ messages: items,
106
+ provider,
107
+ signal,
108
+ keepUserTurns: COMPACT_KEEP_USER_TURNS,
109
+ });
110
+ if (result) {
111
+ notice(`context compacted (~${result.beforeTokens.toLocaleString()} → ` +
112
+ `~${result.afterTokens.toLocaleString()} tokens)`);
113
+ }
114
+ return result;
115
+ }
116
+ catch (error) {
117
+ notice(`could not compact: ${error instanceof Error ? error.message : String(error)}`);
118
+ return null;
119
+ }
120
+ };
121
+ let exitCode = 0;
122
+ let lastTextChar = '';
123
+ let reasoning = '';
124
+ // Reasoning is live-only in the TUI; headless runs collapse each block to one
125
+ // bounded stderr line so CI logs stay readable and never get key material.
126
+ const flushReasoning = () => {
127
+ if (!reasoning)
128
+ return;
129
+ const text = redactSecrets(reasoning).replace(/\s+/g, ' ').trim();
130
+ reasoning = '';
131
+ if (!text)
132
+ return;
133
+ const cap = 4_000;
134
+ stderr.write(`# reasoning: ${text.length > cap ? `${text.slice(0, cap)}…` : text}\n`);
135
+ };
136
+ for await (const event of runAgentTurn({
137
+ provider,
138
+ messages: working,
139
+ ctx,
140
+ compactContext,
141
+ })) {
142
+ if (event.type === 'text') {
143
+ flushReasoning();
144
+ if (event.text) {
145
+ writeOut(event.text);
146
+ lastTextChar = event.text.at(-1) ?? lastTextChar;
147
+ }
148
+ }
149
+ else if (event.type === 'reasoning') {
150
+ reasoning += event.text;
151
+ }
152
+ else if (event.type === 'tool-start') {
153
+ flushReasoning();
154
+ stderr.write(`# ${toolCallLine(event.toolCall)}\n`);
155
+ }
156
+ else if (event.type === 'notice') {
157
+ flushReasoning();
158
+ notice(event.message);
159
+ }
160
+ else if (event.type === 'done') {
161
+ flushReasoning();
162
+ if (event.reason === 'aborted') {
163
+ notice('turn cancelled');
164
+ exitCode = 130;
165
+ }
166
+ else if (event.reason === 'error')
167
+ exitCode = 1;
168
+ else if (event.reason === 'max-iterations') {
169
+ notice('the turn stopped at the tool-round cap; send another -p message to continue');
170
+ }
171
+ else if (event.reason !== 'complete') {
172
+ exitCode = 1;
173
+ }
174
+ }
175
+ }
176
+ flushReasoning();
177
+ // Keep shell prompts and piped files tidy without altering the model's text.
178
+ if (lastTextChar && lastTextChar !== '\n')
179
+ writeOut('\n');
180
+ const cleaned = dropIncompleteToolCalls(working.filter((message) => message.role !== 'system'));
181
+ if (cleaned.length > 0) {
182
+ await saveSession({
183
+ id: record.id,
184
+ cwd,
185
+ profile: config.activeProfile,
186
+ model: profile.model,
187
+ title: record.title || titleFromMessages(cleaned),
188
+ createdAt: record.createdAt,
189
+ messages: cleaned,
190
+ });
191
+ }
192
+ return exitCode;
193
+ }
194
+ catch (error) {
195
+ stderr.write(`Kiro: ${error instanceof Error ? error.message : String(error)}\n`);
196
+ return 1;
197
+ }
198
+ }
199
+ function toolCallLine(call) {
200
+ let args = call.function.arguments;
201
+ try {
202
+ args = JSON.stringify(JSON.parse(args));
203
+ }
204
+ catch {
205
+ // Keep raw arguments; parsing is a nicety for alignment only.
206
+ }
207
+ return `${call.function.name}(${redactSecrets(args.length > 200 ? `${args.slice(0, 200)}…` : args)})`;
208
+ }
209
+ /** Reads a piped prompt until EOF; no-op on an interactive terminal. */
210
+ async function readStdinPrompt() {
211
+ if (process.stdin.isTTY)
212
+ return '';
213
+ const chunks = [];
214
+ for await (const chunk of process.stdin) {
215
+ chunks.push(chunk);
216
+ }
217
+ return Buffer.concat(chunks).toString('utf8');
218
+ }
219
+ //# sourceMappingURL=headless.js.map
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { applyOverrides, configPath, ConfigError, loadConfig, recoverConfig, } f
5
5
  import { loadEnvFile } from './env.js';
6
6
  import { runModelCli } from './model/cli.js';
7
7
  import { readLine } from './model/cli-ui.js';
8
+ import { runHeadless } from './headless.js';
8
9
  import { registerSecretEnv } from './secrets.js';
9
10
  import { latestSession, loadSession } from './sessions.js';
10
11
  import { MOUSE_OFF } from './ui/mouse.js';
@@ -21,6 +22,10 @@ Options:
21
22
  --model <name> Override the active profile's model name
22
23
  -c, --continue Resume the most recent session for this directory
23
24
  --resume <id> Resume a specific saved session
25
+ -p, --prompt <text>
26
+ Run one turn without a TUI ("-" or no text reads the
27
+ prompt from stdin); replies stream to stdout, notices
28
+ and reasoning to stderr
24
29
  --yolo Skip all approval prompts (use with care)
25
30
  --mouse Mouse reporting is on by default: the wheel scrolls the
26
31
  transcript, Shift+drag selects text for copying.
@@ -111,20 +116,32 @@ function parseArgs(argv) {
111
116
  }
112
117
  const equals = arg.indexOf('=');
113
118
  const flag = equals === -1 ? arg : arg.slice(0, equals);
114
- if (flag === '--profile' || flag === '--base-url' || flag === '--model' || flag === '--resume') {
119
+ if (flag === '--profile' ||
120
+ flag === '--base-url' ||
121
+ flag === '--model' ||
122
+ flag === '--resume' ||
123
+ flag === '--prompt' ||
124
+ flag === '-p') {
125
+ const isPrompt = flag === '--prompt' || flag === '-p';
115
126
  let value;
116
127
  if (equals !== -1) {
117
128
  value = arg.slice(equals + 1);
118
129
  }
119
130
  else {
120
- value = argv[index + 1];
121
- if (value !== undefined && !value.startsWith('-'))
131
+ const next = argv[index + 1];
132
+ if (next !== undefined && (!next.startsWith('-') || (isPrompt && next === '-'))) {
133
+ value = next;
122
134
  index++;
123
- else
124
- value = undefined;
135
+ }
125
136
  }
126
- if (!value)
137
+ if (isPrompt) {
138
+ // Bare -p, -p with an empty value, and -p - all read the prompt from stdin.
139
+ options.prompt = value === undefined || value === '' || value === '-' ? '' : value;
140
+ continue;
141
+ }
142
+ if (value === undefined || value === '') {
127
143
  throw new UsageError(`Option ${flag} requires a value.`);
144
+ }
128
145
  if (flag === '--profile')
129
146
  options.profile = value;
130
147
  else if (flag === '--base-url')
@@ -180,8 +197,10 @@ async function main() {
180
197
  process.stdout.write(`Kiro ${VERSION}\n`);
181
198
  return;
182
199
  }
183
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
200
+ const headless = options.prompt !== undefined;
201
+ if (!headless && (!process.stdin.isTTY || !process.stdout.isTTY)) {
184
202
  console.error('Kiro needs an interactive terminal (stdin and stdout must be TTYs).');
203
+ console.error('For scripts and CI, run one turn with: kiro -p "your prompt"');
185
204
  process.exitCode = 2;
186
205
  return;
187
206
  }
@@ -215,8 +234,38 @@ async function main() {
215
234
  registerSecretEnv(profile.apiKeyEnv, process.env[profile.apiKeyEnv], true);
216
235
  }
217
236
  }
237
+ if (headless) {
238
+ if (options.resume && options.continueSession) {
239
+ console.error('Kiro: both --resume and --continue were given with -p; --resume wins.');
240
+ }
241
+ const controller = new AbortController();
242
+ const onInterrupt = () => controller.abort();
243
+ process.once('SIGINT', onInterrupt);
244
+ try {
245
+ process.exitCode = await runHeadless({
246
+ config,
247
+ cwd: process.cwd(),
248
+ // An empty -p value means "read the prompt from stdin".
249
+ prompt: options.prompt || undefined,
250
+ yolo: options.yolo,
251
+ resumeId: options.resume,
252
+ continueLatest: !options.resume && options.continueSession,
253
+ signal: controller.signal,
254
+ });
255
+ }
256
+ finally {
257
+ process.off('SIGINT', onInterrupt);
258
+ }
259
+ return;
260
+ }
218
261
  let initialSession = null;
219
262
  const startupNotices = [];
263
+ if (options.resume && options.continueSession) {
264
+ startupNotices.push({
265
+ level: 'info',
266
+ text: 'Both --resume and --continue were given; resuming the requested session.',
267
+ });
268
+ }
220
269
  if (backup) {
221
270
  startupNotices.push({
222
271
  level: 'info',
@@ -3,6 +3,7 @@ import { ProviderError } from './types.js';
3
3
  const MAX_RETRIES = 3;
4
4
  const DEFAULT_RETRY_BASE_MS = 500;
5
5
  const MAX_RETRY_DELAY_MS = 60_000;
6
+ const DEFAULT_STREAM_IDLE_MS = 120_000;
6
7
  function isRecord(value) {
7
8
  return typeof value === 'object' && value !== null && !Array.isArray(value);
8
9
  }
@@ -74,6 +75,29 @@ const OVERFLOW_PATTERN = /(maximum context|context (?:window|length)|too many to
74
75
  export function isOverflowMessage(message) {
75
76
  return OVERFLOW_PATTERN.test(message);
76
77
  }
78
+ /** Reasoning-tuned models that only accept max_completion_tokens and default temperature. */
79
+ export function reasoningModel(model) {
80
+ return /^(o[134](-|$)|o\d{3,}|gpt-5)/i.test(model);
81
+ }
82
+ /** Matches endpoints whose 4xx error explicitly names the required parameter. */
83
+ export function rejectsMaxTokens(message) {
84
+ return /max_completion_tokens/.test(message) && /max_tokens/.test(message);
85
+ }
86
+ /** Reads the standard reasoning fields used by R1-style and OpenRouter endpoints. */
87
+ function extractReasoning(source) {
88
+ if (!isRecord(source))
89
+ return '';
90
+ if (typeof source.reasoning_content === 'string')
91
+ return source.reasoning_content;
92
+ if (typeof source.reasoning === 'string')
93
+ return source.reasoning;
94
+ if (Array.isArray(source.reasoning_details)) {
95
+ return source.reasoning_details
96
+ .map((detail) => (isRecord(detail) && typeof detail.text === 'string' ? detail.text : ''))
97
+ .join('');
98
+ }
99
+ return '';
100
+ }
77
101
  function toToolCall(pending) {
78
102
  return {
79
103
  id: pending.id,
@@ -116,12 +140,19 @@ export class OpenAIProvider {
116
140
  apiKey;
117
141
  temperature;
118
142
  maxTokens;
143
+ /**
144
+ * Reasoning-tuned OpenAI models (o1/o3/o4, gpt-5) reject `max_tokens` and
145
+ * non-default `temperature`; they take `max_completion_tokens` instead.
146
+ * Guessed from the model id, then renegotiated on the endpoint's own error.
147
+ */
148
+ completionTokenStyle;
119
149
  constructor(profile, apiKey) {
120
150
  this.baseUrl = profile.baseUrl;
121
151
  this.model = profile.model;
122
152
  this.apiKey = apiKey;
123
153
  this.temperature = profile.temperature;
124
154
  this.maxTokens = profile.maxTokens;
155
+ this.completionTokenStyle = reasoningModel(profile.model) ? 'completion' : 'chat';
125
156
  }
126
157
  async *stream(messages, tools, options = {}) {
127
158
  const endpoint = endpointFor(this.baseUrl);
@@ -157,10 +188,18 @@ export class OpenAIProvider {
157
188
  body.tools = tools;
158
189
  body.tool_choice = 'auto';
159
190
  }
160
- if (this.temperature !== undefined)
191
+ if (this.temperature !== undefined && this.completionTokenStyle === 'chat') {
161
192
  body.temperature = this.temperature;
162
- if (this.maxTokens !== undefined)
163
- body.max_tokens = this.maxTokens;
193
+ }
194
+ if (this.maxTokens !== undefined) {
195
+ if (this.completionTokenStyle === 'completion') {
196
+ body.max_completion_tokens = this.maxTokens;
197
+ }
198
+ else {
199
+ body.max_tokens = this.maxTokens;
200
+ }
201
+ }
202
+ let renegotiatedTokenStyle = false;
164
203
  for (let attempt = 0;; attempt++) {
165
204
  let emitted = 0;
166
205
  try {
@@ -174,6 +213,26 @@ export class OpenAIProvider {
174
213
  catch (error) {
175
214
  if (isAbortError(error) || options.signal?.aborted)
176
215
  throw error;
216
+ // Some endpoints reject the legacy max_tokens parameter: switch the key
217
+ // once and retry immediately without consuming a retry slot.
218
+ if (!renegotiatedTokenStyle &&
219
+ error instanceof ProviderError &&
220
+ (error.status === 400 || error.status === 422) &&
221
+ rejectsMaxTokens(error.message)) {
222
+ renegotiatedTokenStyle = true;
223
+ this.completionTokenStyle = 'completion';
224
+ delete body.max_tokens;
225
+ if (this.maxTokens !== undefined)
226
+ body.max_completion_tokens = this.maxTokens;
227
+ if (body.temperature !== undefined) {
228
+ delete body.temperature;
229
+ }
230
+ yield {
231
+ type: 'notice',
232
+ message: 'The endpoint rejected max_tokens; retrying with max_completion_tokens.',
233
+ };
234
+ continue;
235
+ }
177
236
  if (!(error instanceof ProviderError) ||
178
237
  !error.retryable ||
179
238
  emitted > 0 ||
@@ -257,6 +316,9 @@ export class OpenAIProvider {
257
316
  yield { type: 'finish', reason: choice.finish_reason };
258
317
  }
259
318
  const content = extractText(message.content);
319
+ const reasoning = extractReasoning(message);
320
+ if (reasoning)
321
+ yield { type: 'reasoning', text: reasoning };
260
322
  if (content)
261
323
  yield { type: 'text', text: content };
262
324
  if (Array.isArray(message.tool_calls)) {
@@ -316,6 +378,9 @@ export class OpenAIProvider {
316
378
  }
317
379
  if (!isRecord(choice.delta))
318
380
  return events;
381
+ const reasoning = extractReasoning(choice.delta);
382
+ if (reasoning)
383
+ events.push({ type: 'reasoning', text: reasoning });
319
384
  const text = extractText(choice.delta.content);
320
385
  if (text)
321
386
  events.push({ type: 'text', text });
@@ -337,9 +402,36 @@ export class OpenAIProvider {
337
402
  }
338
403
  return dataLines.length > 0 ? handleData(dataLines.join('\n')) : [];
339
404
  };
405
+ // The chat stream has no connect timeout: an endpoint that stalls without
406
+ // closing the socket would otherwise hang the TUI until Ctrl+C. The idle
407
+ // guard aborts the read when no byte arrives for KIRO_STREAM_IDLE_MS.
408
+ const idleMs = streamIdleMs();
409
+ const idleRead = async () => {
410
+ if (idleMs <= 0)
411
+ return reader.read();
412
+ let inactivity = null;
413
+ try {
414
+ return await Promise.race([
415
+ reader.read(),
416
+ new Promise((_, reject) => {
417
+ inactivity = setTimeout(() => {
418
+ // Reject before cancelling: cancel() resolves the pending read with
419
+ // done, and settling that first would swallow the timeout.
420
+ reject(new ProviderError(`The model stream was idle for more than ${Math.round(idleMs / 1000)}s. The endpoint stalled without sending data.\n` +
421
+ 'Adjust KIRO_STREAM_IDLE_MS (milliseconds, 0 disables) if this is expected.', undefined, { retryable: true }));
422
+ void reader.cancel().catch(() => undefined);
423
+ }, idleMs);
424
+ }),
425
+ ]);
426
+ }
427
+ finally {
428
+ if (inactivity)
429
+ clearTimeout(inactivity);
430
+ }
431
+ };
340
432
  try {
341
433
  while (!finished) {
342
- const { value, done } = await reader.read();
434
+ const { value, done } = await idleRead();
343
435
  if (done)
344
436
  break;
345
437
  buffer += decoder.decode(value, { stream: true });
@@ -398,6 +490,11 @@ function retryBaseMs() {
398
490
  const raw = Number(process.env.KIRO_RETRY_BASE_MS ?? '');
399
491
  return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_RETRY_BASE_MS;
400
492
  }
493
+ /** Kill a stalled stream after this many milliseconds without a byte. 0 disables. */
494
+ function streamIdleMs() {
495
+ const raw = Number(process.env.KIRO_STREAM_IDLE_MS ?? '');
496
+ return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_STREAM_IDLE_MS;
497
+ }
401
498
  /** Honors Retry-After (seconds or HTTP date), capped so a bad header cannot stall the TUI. */
402
499
  function parseRetryAfter(value) {
403
500
  if (!value)