@ywldan/kiro 0.2.2 → 0.2.4

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
@@ -280,7 +280,7 @@ Exit codes: `0` success, `1` model/tool/session error, `2` usage error (includin
280
280
  | `Ctrl+W` | Delete the previous word |
281
281
  | Left / Right / Home / End | Move the cursor |
282
282
 
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…`, `replying…`, `running <tool>…`, `approval needed`, `cancelling…`) with a spinner and the elapsed seconds for the current turn (`replying… · 12s`). 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…`, `replying…`, `running <tool>…`, `approval needed`, `cancelling…`) with a spinner and the elapsed seconds for the current turn (`replying… · 12s`). A long profile name is shortened in the middle, so the model and directory stay readable. On a wide terminal the context meter moves into the Usage card described below, leaving more room for the profile and path.
284
284
 
285
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
286
 
@@ -290,9 +290,11 @@ Reasoning models stream their thinking traces live as a dim `thinking…` block.
290
290
 
291
291
  Each finished assistant round shows how long it took and, when the endpoint reports usage, its output throughput: `· 8.4s · 23 tok/s`. The countdown in the status bar and the per-reply timing are wall-clock (including network time), are display-only, and are not stored in saved sessions; resumed replies and replies from servers without usage simply omit them.
292
292
 
293
- 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.
293
+ When the terminal is at least 110 columns wide and the transcript has room for 9 rows, a **Usage card** sits in its own column to the right of the conversation and stays there while you chat. It shows the session's token totals (`↑` sent, `↓` received) and API request count, a context gauge with the current window, and the duration and throughput of the last timed reply. Totals come from endpoint `usage` reports, accumulate across tool rounds, are saved with the session, and continue after `/resume`; compaction requests are not counted. A `~` before the context number means it is estimated because no usage has been reported since the last resume or compaction. Below 110 columns the card hides so the transcript keeps its width and the `ctx` meter returns to the status bar; `/context` prints the session totals at any width. `/usage` toggles the card; while it is hidden the transcript gets the full width.
294
294
 
295
- 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.
295
+ Assistant replies are rendered as Markdown: headings, bold/italic, inline code, bullet and numbered lists, task checkboxes, blockquotes, links, fenced code blocks, and tables. Table columns are sized to their contents, honour `:---`/`---:`/`:---:` alignment, and wrap cells inside the available width; a table too wide to be readable falls back to its plain rows. Unknown or incomplete markers fall back to their literal text, so streaming never breaks the layout.
296
+
297
+ Typing `/` opens a command palette. It is drawn over the bottom of the transcript instead of resizing it, so the conversation does not jump when the menu opens or closes. It filters as you type, `↑`/`↓` select a command, `Enter` runs it, and `Tab` completes it. `Esc` clears the input.
296
298
 
297
299
  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.
298
300
 
@@ -305,14 +307,15 @@ Slash commands:
305
307
  | Command | Action |
306
308
  | --- | --- |
307
309
  | `/help` | Show commands and keys |
308
- | `/model` | Open the model picker: profile first, then its stored models |
310
+ | `/model` | Open the model picker: profile first, then searchable stored models |
309
311
  | `/model <name>` | Switch profile without restarting |
310
312
  | `/model add` | Guided setup; prompts appear in the input box and the key is masked |
311
313
  | `/model edit [name]` | Edit fields, replace the key, re-test, and save |
312
314
  | `/model remove [name]` | Remove a profile after confirmation (refuses the last one) |
313
315
  | `/model test [name]` | Test the active or named profile; prints latency or the exact error |
314
316
  | `/model list --remote` | List models offered by the active endpoint's `GET /models` |
315
- | `/context` | Show approximate context use, broken down by message role |
317
+ | `/context` | Show approximate context use by message role plus session token totals |
318
+ | `/usage` | Show or hide the Usage card, giving the transcript the full width |
316
319
  | `/compact` | Summarize older turns now, keeping the last four user turns verbatim |
317
320
  | `/sessions` | List saved sessions for this working directory |
318
321
  | `/resume <n\|id>` | Resume a session by list number or id (prefixes work) |
@@ -324,7 +327,7 @@ Slash commands:
324
327
  | `/allow clear` | Ask for approval again for every tool |
325
328
  | `/exit` | Quit |
326
329
 
327
- `/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.
330
+ `/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`. On the model step, type to filter (case-insensitive; space-separated terms must all match), `Backspace` edits the query, `Esc` clears the query first and then goes back, and `↑`/`↓` move through the filtered list. `Ctrl+R` refetches `GET /models` from that endpoint and stores the result; later switches need no network. `Ctrl+C` closes the picker. A profile with no stored list still shows its current model, and adding a profile through the wizard stores whatever discovery returned for it.
328
331
 
329
332
  ## Sessions
330
333
 
@@ -351,7 +354,7 @@ Session files are plaintext and contain your prompts, code snippets returned by
351
354
 
352
355
  ## Context and compaction
353
356
 
354
- 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.
357
+ 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>` (or the Usage card on a wide terminal), and `/context` breaks the total down by message role and prints the session's cumulative token totals.
355
358
 
356
359
  Each profile may set `contextWindow` (default `128000`). At about 80% of that window, before the next model request, Kiro compacts the conversation automatically:
357
360
 
@@ -417,7 +420,7 @@ If an `AGENTS.md` file exists in the working directory, its contents are appende
417
420
  - Ctrl+C aborts the HTTP stream and any running command; partial assistant text is preserved.
418
421
  - `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.
419
422
  - Sessions are saved atomically after each user message and completed turn, and are restored by rebuilding the visible transcript from the stored messages.
420
- - Reply timing is measured per model round (request start to finished reply) and includes network latency. Token throughput uses the endpoint's completion-token usage; both are shown only in the live TUI and are not persisted.
423
+ - Reply timing is measured per model round (request start to finished reply) and includes network latency. Token throughput uses the endpoint's completion-token usage; both are shown only in the live TUI and are not persisted. Session token totals are persisted separately in the session file.
421
424
  - 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.
422
425
  - 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.
423
426
  - 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.
@@ -431,7 +434,7 @@ pnpm mock # start the mock server on port 8787 for manual TUI testing
431
434
 
432
435
  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.
433
436
 
434
- 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.
437
+ 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, usage totals, 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, wrapping, and table alignment, slash-command filtering/shared help text, the Usage card and its width collapse, and SGR mouse-wheel parsing; pty runs exercise the command palette, mouse and PgUp/PgDn scrolling, Markdown rendering, approvals, cancellation, and the `/usage` toggle.
435
438
 
436
439
  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.
437
440
 
@@ -468,7 +471,7 @@ test/
468
471
  - Prompt history is plaintext, capped at 200 entries per directory, and only recalled in the TUI (not in `-p` mode).
469
472
  - Only contiguous read-only tool calls run in parallel; writes, edits, patches, and commands stay sequential.
470
473
  - 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.
471
- - Markdown support covers the common subset; tables, images, and syntax highlighting are shown as plain text.
474
+ - Markdown support covers the common subset; images and syntax highlighting are shown as plain text.
472
475
  - 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`.
473
476
  - 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.
474
477
  - 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.
package/dist/headless.js CHANGED
@@ -6,6 +6,7 @@ import { estimateMessagesTokens } from './agent/tokens.js';
6
6
  import { createProvider } from './providers/index.js';
7
7
  import { dropIncompleteToolCalls, latestSession, loadSession, newSessionId, saveSession, titleFromMessages, } from './sessions.js';
8
8
  import { redactSecrets } from './secrets.js';
9
+ import { addUsage, normalizeUsage } from './usage.js';
9
10
  /**
10
11
  * One-shot agent run without a TUI: `kiro -p "fix the tests"`.
11
12
  * Text streams to stdout; notices, tool calls, and reasoning go to stderr, so
@@ -95,6 +96,7 @@ export async function runHeadless(options) {
95
96
  updatedAt: new Date().toISOString(),
96
97
  messages: [],
97
98
  };
99
+ let usage = normalizeUsage(record.usage);
98
100
  const window = contextWindowFor(profile);
99
101
  const compactContext = async (items, signal, compactOptions) => {
100
102
  const used = estimateMessagesTokens(items);
@@ -153,6 +155,9 @@ export async function runHeadless(options) {
153
155
  flushReasoning();
154
156
  stderr.write(`# ${toolCallLine(event.toolCall)}\n`);
155
157
  }
158
+ else if (event.type === 'usage') {
159
+ usage = addUsage(usage, event.usage);
160
+ }
156
161
  else if (event.type === 'notice') {
157
162
  flushReasoning();
158
163
  notice(event.message);
@@ -187,6 +192,7 @@ export async function runHeadless(options) {
187
192
  title: record.title || titleFromMessages(cleaned),
188
193
  createdAt: record.createdAt,
189
194
  messages: cleaned,
195
+ usage,
190
196
  });
191
197
  }
192
198
  return exitCode;
package/dist/index.js CHANGED
File without changes
package/dist/sessions.js CHANGED
@@ -2,6 +2,7 @@ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { chmod, mkdir, readFile, readdir, rename, unlink, writeFile } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
4
  import path from 'node:path';
5
+ import { normalizeUsage } from './usage.js';
5
6
  export const SESSION_VERSION = 1;
6
7
  export class SessionError extends Error {
7
8
  constructor(message) {
@@ -136,6 +137,7 @@ export async function saveSession(input) {
136
137
  createdAt: input.createdAt ?? now,
137
138
  updatedAt: now,
138
139
  messages,
140
+ usage: normalizeUsage(input.usage),
139
141
  };
140
142
  const dir = projectSessionsDir(input.cwd);
141
143
  await mkdir(dir, { recursive: true, mode: 0o700 });
@@ -196,6 +198,7 @@ export async function loadSession(cwd, id) {
196
198
  createdAt,
197
199
  updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : createdAt,
198
200
  messages,
201
+ usage: normalizeUsage(parsed.usage),
199
202
  };
200
203
  }
201
204
  function summarize(record) {
package/dist/ui/App.js CHANGED
@@ -26,8 +26,10 @@ import { formatProfileList } from './profile-list.js';
26
26
  import { loadPromptHistory, recordPrompt } from './prompt-history.js';
27
27
  import { StatusBar } from './StatusBar.js';
28
28
  import { summarizeToolArgs } from './text.js';
29
+ import { UsageCard, USAGE_CARD_GAP, USAGE_CARD_WIDTH, shouldShowUsageCard, } from './UsageCard.js';
30
+ import { addUsage, EMPTY_USAGE } from '../usage.js';
29
31
  import { undoLastCheckpoint } from '../tools/checkpoint.js';
30
- import { MAX_EXPANDED_TOOL_CHARS, MAX_REASONING_CHARS } from './types.js';
32
+ import { MAX_EXPANDED_TOOL_CHARS, MAX_REASONING_CHARS, } from './types.js';
31
33
  function useTerminalSize() {
32
34
  const { stdout } = useStdout();
33
35
  const read = useCallback(() => ({
@@ -78,13 +80,17 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
78
80
  const [cancelling, setCancelling] = useState(false);
79
81
  const [pendingApproval, setPendingApproval] = useState(null);
80
82
  const [pickerOpen, setPickerOpen] = useState(false);
81
- const [slashMenuRows, setSlashMenuRows] = useState(0);
83
+ const [palette, setPalette] = useState(null);
84
+ const [usageCardEnabled, setUsageCardEnabled] = useState(true);
82
85
  const [mouseOn, setMouseOn] = useState(mouseEnabled);
83
86
  const [expandedToolId, setExpandedToolId] = useState(null);
84
87
  const messagesRef = useRef((initialSession?.messages ?? []).filter((message) => message.role !== 'system'));
85
88
  const usageRef = useRef(null);
86
89
  const roundStartedAtRef = useRef(0);
87
90
  const roundCompletionTokensRef = useRef(null);
91
+ const [sessionUsage, setSessionUsage] = useState(() => initialSession?.usage ?? EMPTY_USAGE);
92
+ const sessionUsageRef = useRef(sessionUsage);
93
+ const [lastReply, setLastReply] = useState(null);
88
94
  const [contextTokens, setContextTokens] = useState(() => estimateMessagesTokens(messagesRef.current));
89
95
  const contextTokensRef = useRef(contextTokens);
90
96
  const sessionRef = useRef(initialSession
@@ -134,9 +140,6 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
134
140
  contextTokensRef.current = rounded;
135
141
  setContextTokens(rounded);
136
142
  }, []);
137
- const handleMenuRowsChange = useCallback((rows) => {
138
- setSlashMenuRows((current) => (current === rows ? current : rows));
139
- }, []);
140
143
  const recomputeContext = useCallback(() => {
141
144
  const messages = messagesRef.current;
142
145
  const usage = usageRef.current;
@@ -322,6 +325,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
322
325
  }
323
326
  const session = sessionRef.current;
324
327
  const snapshot = structuredClone(messages);
328
+ const usage = { ...sessionUsageRef.current };
325
329
  const write = saveChainRef.current
326
330
  .then(() => saveSession({
327
331
  id: session.id,
@@ -331,6 +335,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
331
335
  title: session.title,
332
336
  createdAt: session.createdAt,
333
337
  messages: snapshot,
338
+ usage,
334
339
  }))
335
340
  .then(() => undefined)
336
341
  .catch((error) => {
@@ -515,6 +520,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
515
520
  ? Math.round(completionTokens / (durationMs / 1_000))
516
521
  : undefined;
517
522
  finalizeAssistant(event.content, durationMs, tokensPerSecond);
523
+ setLastReply({ durationMs, tokensPerSecond });
518
524
  roundCompletionTokensRef.current = null;
519
525
  setReplying(false);
520
526
  recomputeContext();
@@ -561,16 +567,20 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
561
567
  roundStartedAtRef.current = Date.now();
562
568
  roundCompletionTokensRef.current = null;
563
569
  break;
564
- case 'usage':
570
+ case 'usage': {
565
571
  usageRef.current = {
566
572
  tokens: event.usage.totalTokens,
567
573
  // The assistant message from this response is appended after the
568
574
  // stream ends and is already counted in totalTokens.
569
575
  messageCount: messagesRef.current.length + 1,
570
576
  };
577
+ const totals = addUsage(sessionUsageRef.current, event.usage);
578
+ sessionUsageRef.current = totals;
579
+ setSessionUsage(totals);
571
580
  roundCompletionTokensRef.current = event.usage.completionTokens;
572
581
  recomputeContext();
573
582
  break;
583
+ }
574
584
  case 'notice':
575
585
  flushText();
576
586
  addNotice(event.level, event.message);
@@ -793,6 +803,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
793
803
  const used = contextTokensRef.current;
794
804
  const count = (role) => estimateMessagesTokens(messagesRef.current.filter((message) => message.role === role));
795
805
  const usage = usageRef.current;
806
+ const totals = sessionUsageRef.current;
796
807
  addNotice('info', [
797
808
  `Context: ~${formatTokens(used)} / ${formatTokens(window)} tokens (${formatPercent(used, window)} used)` +
798
809
  (profile?.contextWindow
@@ -803,10 +814,26 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
803
814
  usage
804
815
  ? `Last API usage: ${usage.tokens.toLocaleString()} tokens for the last request and response.`
805
816
  : 'The endpoint has not reported usage; counts are estimated at roughly 4 characters per token.',
817
+ totals.requests > 0
818
+ ? `Session usage: ↑ ${formatTokens(totals.promptTokens)} sent, ↓ ${formatTokens(totals.completionTokens)} received ` +
819
+ `across ${totals.requests} API request${totals.requests === 1 ? '' : 's'} (saved with this session).`
820
+ : 'Session usage: the endpoint has not reported token counts for this session yet.',
806
821
  `Auto-compaction runs at ${Math.round(COMPACT_THRESHOLD * 100)}% and keeps the last ${COMPACT_KEEP_USER_TURNS} user turns verbatim. /compact runs it now.`,
807
822
  ].join('\n'));
808
823
  return;
809
824
  }
825
+ case '/usage': {
826
+ if (argument) {
827
+ addNotice('error', 'Usage: /usage (toggles the usage card)');
828
+ return;
829
+ }
830
+ const next = !usageCardEnabled;
831
+ setUsageCardEnabled(next);
832
+ addNotice('info', next
833
+ ? 'Usage card on; it appears when the terminal is at least 110 columns wide.'
834
+ : 'Usage card hidden; the transcript gets the full width. Use /usage to show it again.');
835
+ return;
836
+ }
810
837
  case '/compact': {
811
838
  if (messagesRef.current.length === 0) {
812
839
  addNotice('muted', 'There is no conversation to compact yet.');
@@ -915,6 +942,10 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
915
942
  const record = await loadSession(cwd, targetId);
916
943
  messagesRef.current = record.messages.filter((message) => message.role !== 'system');
917
944
  usageRef.current = null;
945
+ const restoredUsage = record.usage ?? EMPTY_USAGE;
946
+ sessionUsageRef.current = restoredUsage;
947
+ setSessionUsage(restoredUsage);
948
+ setLastReply(null);
918
949
  recomputeContext();
919
950
  sessionRef.current = {
920
951
  id: record.id,
@@ -950,6 +981,9 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
950
981
  await saveChainRef.current;
951
982
  messagesRef.current = [];
952
983
  usageRef.current = null;
984
+ sessionUsageRef.current = EMPTY_USAGE;
985
+ setSessionUsage(EMPTY_USAGE);
986
+ setLastReply(null);
953
987
  updateContextTokens(0);
954
988
  sessionRef.current = null;
955
989
  listedSessionsRef.current = null;
@@ -1070,6 +1104,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1070
1104
  runModelFlow,
1071
1105
  runProfileTest,
1072
1106
  updateContextTokens,
1107
+ usageCardEnabled,
1073
1108
  version,
1074
1109
  yolo,
1075
1110
  ]);
@@ -1206,9 +1241,10 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1206
1241
  : null;
1207
1242
  const activeProfile = runtimeConfig.profiles[profileName];
1208
1243
  const contextWindow = contextWindowFor(activeProfile);
1209
- const menuRows = pendingApproval || pickerOpen ? 0 : slashMenuRows;
1210
- const viewportHeight = Math.max(3, rows - 5 - (pendingApproval ? 12 : 0) - (pickerOpen ? 13 : 0) - menuRows);
1211
- return (_jsxs(Box, { flexDirection: "column", width: columns, paddingX: 1, children: [_jsx(MessageList, { items: items, width: width, height: viewportHeight, resetSignal: resetSignal, expandedToolId: expandedToolId, interactive: !pendingApproval && !pickerOpen && !wizardActive && wizardPrompt === null }), pendingApproval ? (_jsx(ApprovalPrompt, { request: pendingApproval, width: width, onDecision: resolveApproval })) : pickerOpen ? (_jsx(ModelPicker, { config: runtimeConfig, activeProfile: profileName, width: width, onSelect: (name, model) => void selectModel(name, model), onRefresh: refreshProfileModels, onCancel: () => setPickerOpen(false) })) : (_jsx(Input, { disabled: false, width: width, mask: wizardPrompt?.mask, allowEmpty: wizardPrompt?.allowEmpty, history: wizardPrompt || wizardActive ? undefined : promptHistory, placeholder: wizardPrompt
1244
+ const viewportHeight = Math.max(3, rows - 5 - (pendingApproval ? 12 : 0) - (pickerOpen ? 13 : 0));
1245
+ const showUsageCard = usageCardEnabled && shouldShowUsageCard(columns, viewportHeight);
1246
+ const chatWidth = showUsageCard ? Math.max(40, width - USAGE_CARD_WIDTH - USAGE_CARD_GAP) : width;
1247
+ return (_jsxs(Box, { flexDirection: "column", width: columns, paddingX: 1, children: [_jsxs(Box, { flexDirection: "row", alignItems: "flex-start", width: width, children: [_jsx(MessageList, { items: items, width: chatWidth, height: viewportHeight, resetSignal: resetSignal, expandedToolId: expandedToolId, palette: palette, interactive: !pendingApproval && !pickerOpen && !wizardActive && wizardPrompt === null }), showUsageCard ? (_jsx(Box, { marginLeft: USAGE_CARD_GAP, flexShrink: 0, children: _jsx(UsageCard, { usage: sessionUsage, contextTokens: contextTokens, contextWindow: contextWindow, contextEstimated: usageRef.current === null, lastReply: lastReply, busy: busy }) })) : null] }), pendingApproval ? (_jsx(ApprovalPrompt, { request: pendingApproval, width: width, onDecision: resolveApproval })) : pickerOpen ? (_jsx(ModelPicker, { config: runtimeConfig, activeProfile: profileName, width: width, onSelect: (name, model) => void selectModel(name, model), onRefresh: refreshProfileModels, onCancel: () => setPickerOpen(false) })) : (_jsx(Input, { disabled: false, width: width, mask: wizardPrompt?.mask, allowEmpty: wizardPrompt?.allowEmpty, history: wizardPrompt || wizardActive ? undefined : promptHistory, onPaletteChange: setPalette, placeholder: wizardPrompt
1212
1248
  ? wizardPrompt.defaultValue && !wizardPrompt.mask
1213
1249
  ? `${wizardPrompt.label} [${wizardPrompt.defaultValue}]`
1214
1250
  : wizardPrompt.label
@@ -1216,6 +1252,6 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1216
1252
  ? 'Kiro is working… type ahead, or Ctrl+C to cancel'
1217
1253
  : wizardActive
1218
1254
  ? 'Working… Esc to cancel'
1219
- : 'Ask Kiro to build or change something…', slashMenu: !wizardActive && !wizardPrompt, onMenuRowsChange: handleMenuRowsChange, onSubmit: handleSubmit, onCancel: wizardActive ? cancelWizard : undefined }, wizardPrompt?.id ?? 0)), _jsx(StatusBar, { width: width, profile: profileName, model: activeProfile?.model ?? 'unknown', cwd: cwd, activity: activity, toolName: activeTool ?? undefined, busySince: busySince ?? undefined, queued: queuedCount > 0 ? queuedCount : undefined, yolo: yolo, autoAllowed: autoAllowed, contextTokens: contextTokens, contextWindow: contextWindow })] }));
1255
+ : 'Ask Kiro to build or change something…', slashMenu: !wizardActive && !wizardPrompt, onSubmit: handleSubmit, onCancel: wizardActive ? cancelWizard : undefined }, wizardPrompt?.id ?? 0)), _jsx(StatusBar, { width: width, profile: profileName, model: activeProfile?.model ?? 'unknown', cwd: cwd, activity: activity, toolName: activeTool ?? undefined, busySince: busySince ?? undefined, queued: queuedCount > 0 ? queuedCount : undefined, yolo: yolo, autoAllowed: autoAllowed, contextTokens: showUsageCard ? undefined : contextTokens, contextWindow: showUsageCard ? undefined : contextWindow })] }));
1220
1256
  }
1221
1257
  //# sourceMappingURL=App.js.map
package/dist/ui/Input.js CHANGED
@@ -7,7 +7,7 @@ import { isMouseSequence } from './mouse.js';
7
7
  import { applyInputOps, parseEditSequence, parseInputChunk, } from './text.js';
8
8
  const MAX_INPUT_CHARS = 20_000;
9
9
  const MAX_MENU_ROWS = 6;
10
- export function Input({ disabled, placeholder, width, mask = false, allowEmpty = false, slashMenu = true, history, onSubmit, onCancel, onMenuRowsChange, }) {
10
+ export function Input({ disabled, placeholder, width, mask = false, allowEmpty = false, slashMenu = true, history, onSubmit, onCancel, onPaletteChange, }) {
11
11
  const { stdin } = useStdin();
12
12
  const [state, setState] = useState({ chars: [], cursor: 0 });
13
13
  const [selected, setSelected] = useState(0);
@@ -31,13 +31,13 @@ export function Input({ disabled, placeholder, width, mask = false, allowEmpty =
31
31
  setSelected(0);
32
32
  }, [text]);
33
33
  useEffect(() => {
34
- // A fixed height keeps the layout still while the filter narrows; a shrinking
35
- // menu would push the input up and down on every keystroke.
36
- onMenuRowsChange?.(menuOpen ? MAX_MENU_ROWS : 0);
37
- }, [menuOpen, onMenuRowsChange]);
38
- useEffect(() => () => {
39
- onMenuRowsChange?.(0);
40
- }, [onMenuRowsChange]);
34
+ onPaletteChange?.(menuOpen
35
+ ? { commands: visibleCommands, activeIndex: Math.max(0, activeIndex - menuStart) }
36
+ : null);
37
+ // visibleCommands is derived from text, activeIndex and menuStart.
38
+ // eslint-disable-next-line react-hooks/exhaustive-deps
39
+ }, [menuOpen, text, activeIndex, menuStart, onPaletteChange]);
40
+ useEffect(() => () => onPaletteChange?.(null), [onPaletteChange]);
41
41
  const update = (chars, cursor) => {
42
42
  const next = { chars, cursor: Math.max(0, Math.min(cursor, chars.length)) };
43
43
  stateRef.current = next;
@@ -246,9 +246,6 @@ export function Input({ disabled, placeholder, width, mask = false, allowEmpty =
246
246
  const at = displayChars[cursor] ?? ' ';
247
247
  const after = displayChars.slice(cursor + 1, end).join('');
248
248
  const showPlaceholder = chars.length === 0;
249
- return (_jsxs(Box, { flexDirection: "column", children: [menuOpen ? (_jsxs(Box, { flexDirection: "column", paddingLeft: 2, children: [visibleCommands.map((command, offset) => {
250
- const active = menuStart + offset === activeIndex;
251
- return (_jsxs(Text, { inverse: active, bold: active, wrap: "truncate-end", children: [active ? '› ' : ' ', command.name, command.usage ? _jsx(Text, { dimColor: !active, children: ` ${command.usage}` }) : null, _jsx(Text, { dimColor: !active, children: ` ${command.description}` })] }, command.name));
252
- }), Array.from({ length: MAX_MENU_ROWS - visibleCommands.length }, (_, index) => (_jsx(Text, { children: " " }, `empty-${index}`)))] })) : null, _jsxs(Box, { flexShrink: 0, children: [_jsx(Text, { color: disabled ? 'gray' : 'cyan', bold: true, children: '› ' }), disabled ? (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: placeholder })) : showPlaceholder ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { inverse: true, children: " " }), _jsxs(Text, { dimColor: true, children: [" ", placeholder] })] })) : (_jsxs(Text, { wrap: "truncate-end", children: [before, _jsx(Text, { inverse: true, children: at }), after] }))] })] }));
249
+ return (_jsxs(Box, { flexShrink: 0, children: [_jsx(Text, { color: disabled ? 'gray' : 'cyan', bold: true, children: '› ' }), disabled ? (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: placeholder })) : showPlaceholder ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { inverse: true, children: " " }), _jsxs(Text, { dimColor: true, children: [" ", placeholder] })] })) : (_jsxs(Text, { wrap: "truncate-end", children: [before, _jsx(Text, { inverse: true, children: at }), after] }))] }));
253
250
  }
254
251
  //# sourceMappingURL=Input.js.map
@@ -183,7 +183,45 @@ export function buildLines(items, width, expandedToolId = null) {
183
183
  }
184
184
  return lines;
185
185
  }
186
- export function MessageList({ items, width, height, resetSignal, expandedToolId = null, interactive = true, }) {
186
+ const PALETTE_ROWS = 6;
187
+ /** Header plus the visible command rows; padded so filtering never changes its height. */
188
+ export function buildPaletteLines(palette, width) {
189
+ const header = {
190
+ prefix: ' ',
191
+ text: truncateToWidth('commands · ↑/↓ move · Tab complete · Enter run', width),
192
+ dim: true,
193
+ };
194
+ const rows = palette.commands.slice(0, PALETTE_ROWS).map((command, index) => {
195
+ const active = index === palette.activeIndex;
196
+ const label = command.usage ? `${command.name} ${command.usage}` : command.name;
197
+ return {
198
+ prefix: active ? '› ' : ' ',
199
+ prefixColor: active ? 'cyan' : undefined,
200
+ text: '',
201
+ segments: [
202
+ { text: label, bold: active },
203
+ { text: ` ${command.description}`, dim: !active },
204
+ ],
205
+ inverse: active,
206
+ };
207
+ });
208
+ while (rows.length < PALETTE_ROWS)
209
+ rows.push({ prefix: '', text: '' });
210
+ return [header, ...rows];
211
+ }
212
+ /**
213
+ * Replaces the last rows of the visible transcript with the palette, so opening
214
+ * the menu never resizes the transcript or moves the conversation.
215
+ */
216
+ export function applyPalette(lines, palette, width, maxRows) {
217
+ if (!palette)
218
+ return lines;
219
+ const height = Math.max(1, maxRows);
220
+ const overlay = buildPaletteLines(palette, width).slice(0, height);
221
+ const keep = Math.max(0, Math.min(lines.length, height) - overlay.length);
222
+ return [...lines.slice(0, keep), ...overlay];
223
+ }
224
+ export function MessageList({ items, width, height, resetSignal, expandedToolId = null, palette = null, interactive = true, }) {
187
225
  const { stdin } = useStdin();
188
226
  const lines = buildLines(items, width, expandedToolId);
189
227
  const maxScroll = Math.max(0, lines.length - height);
@@ -237,9 +275,10 @@ export function MessageList({ items, width, height, resetSignal, expandedToolId
237
275
  }
238
276
  }, { isActive: interactive });
239
277
  const visible = lines.slice(scrollTop, scrollTop + height);
240
- return (_jsx(Box, { flexDirection: "column", height: height, overflowY: "hidden", flexShrink: 0, justifyContent: "flex-end", children: visible.map((line, index) => {
278
+ const shown = applyPalette(visible, palette, width, height);
279
+ return (_jsx(Box, { flexDirection: "column", width: width, height: height, overflowY: "hidden", flexShrink: 0, justifyContent: "flex-end", children: shown.map((line, index) => {
241
280
  const hasSuffix = line.suffix !== undefined;
242
- return (_jsxs(Text, { wrap: "truncate-end", color: line.color, dimColor: line.dim, bold: line.bold, children: [line.prefix ? (_jsx(Text, { color: line.prefixColor, dimColor: line.prefixDim, bold: line.prefixColor === 'cyan', children: line.prefix })) : null, line.segments
281
+ return (_jsxs(Text, { wrap: "truncate-end", color: line.color, dimColor: line.dim, bold: line.bold, inverse: line.inverse, children: [line.prefix ? (_jsx(Text, { color: line.prefixColor, dimColor: line.prefixDim, bold: line.prefixColor === 'cyan', children: line.prefix })) : null, line.segments
243
282
  ? line.segments.map((segment, segmentIndex) => (_jsx(Text, { color: segment.color, dimColor: segment.dim, bold: segment.bold, italic: segment.italic, underline: segment.underline, strikethrough: segment.strikethrough, children: segment.text }, segmentIndex)))
244
283
  : line.text || (hasSuffix ? '' : ' '), line.suffix ? (_jsx(Text, { color: line.suffix.color, dimColor: line.suffix.dim, bold: line.suffix.bold, children: line.suffix.text })) : null] }, `${scrollTop}-${index}`));
245
284
  }) }));
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useState } from 'react';
3
3
  import { Box, Text, useInput } from 'ink';
4
- import { modelIds, pickerWindow, profileRows, selectableLines, selectableNames, } from './model-picker.js';
4
+ import { filterModelIds, modelIds, pickerWindow, profileRows, selectableLines, selectableNames, } from './model-picker.js';
5
5
  /** Keys are highlighted so the hint reads at a glance; the rest stays dim. */
6
6
  const KEY_COLOR = '#ff9e64';
7
7
  function Key({ children }) {
@@ -19,11 +19,13 @@ export function ModelPicker({ config, activeProfile, width, maxRows = 8, onSelec
19
19
  const [index, setIndex] = useState(0);
20
20
  const [refreshing, setRefreshing] = useState(false);
21
21
  const [error, setError] = useState(null);
22
+ const [query, setQuery] = useState('');
22
23
  const rows = profileRows(config, activeProfile);
23
24
  const names = selectableNames(rows);
24
25
  const lines = selectableLines(rows);
25
26
  const profile = step.kind === 'model' ? config.profiles[step.profile] : undefined;
26
- const models = modelIds(profile);
27
+ const allModels = modelIds(profile);
28
+ const models = step.kind === 'model' ? filterModelIds(allModels, query) : allModels;
27
29
  const count = step.kind === 'profile' ? names.length : models.length;
28
30
  const selected = Math.min(index, Math.max(0, count - 1));
29
31
  const selectedLine = step.kind === 'profile' ? (lines[selected] ?? 0) : selected;
@@ -42,10 +44,21 @@ export function ModelPicker({ config, activeProfile, width, maxRows = 8, onSelec
42
44
  useInput((input, key) => {
43
45
  if (refreshing)
44
46
  return;
47
+ if (step.kind === 'model' && key.ctrl && input === 'r') {
48
+ void refresh(step.profile);
49
+ return;
50
+ }
45
51
  if (key.escape) {
52
+ if (step.kind === 'model' && query) {
53
+ setQuery('');
54
+ setIndex(0);
55
+ setError(null);
56
+ return;
57
+ }
46
58
  if (step.kind === 'model') {
47
59
  setStep({ kind: 'profile' });
48
60
  setIndex(0);
61
+ setQuery('');
49
62
  setError(null);
50
63
  }
51
64
  else {
@@ -60,8 +73,21 @@ export function ModelPicker({ config, activeProfile, width, maxRows = 8, onSelec
60
73
  setIndex(Math.min(count - 1, Math.max(0, selected + delta)));
61
74
  return;
62
75
  }
63
- if (step.kind === 'model' && input === 'r') {
64
- void refresh(step.profile);
76
+ if (step.kind === 'model' && !key.return) {
77
+ if (key.backspace || key.delete) {
78
+ if (query) {
79
+ setQuery(query.slice(0, -1));
80
+ setIndex(0);
81
+ }
82
+ return;
83
+ }
84
+ if (key.ctrl || key.meta || key.tab || key.pageUp || key.pageDown)
85
+ return;
86
+ const typed = input.replace(/[\u0000-\u001f\u007f]/g, '');
87
+ if (typed) {
88
+ setQuery(query + typed);
89
+ setIndex(0);
90
+ }
65
91
  return;
66
92
  }
67
93
  if (!key.return)
@@ -72,6 +98,7 @@ export function ModelPicker({ config, activeProfile, width, maxRows = 8, onSelec
72
98
  return;
73
99
  setStep({ kind: 'model', profile: name });
74
100
  setIndex(0);
101
+ setQuery('');
75
102
  setError(null);
76
103
  return;
77
104
  }
@@ -81,8 +108,10 @@ export function ModelPicker({ config, activeProfile, width, maxRows = 8, onSelec
81
108
  });
82
109
  const title = step.kind === 'profile'
83
110
  ? `Model · ${names.length} profile${names.length === 1 ? '' : 's'}`
84
- : `Models · ${step.profile} (${models.length})`;
85
- return (_jsxs(Box, { flexDirection: "column", width: width, borderStyle: "round", borderColor: "cyan", paddingX: 1, flexShrink: 0, children: [_jsx(Text, { bold: true, color: "cyan", wrap: "truncate-end", children: title }), step.kind === 'profile'
111
+ : query.trim()
112
+ ? `Models · ${step.profile} (${models.length}/${allModels.length} match)`
113
+ : `Models · ${step.profile} (${models.length})`;
114
+ return (_jsxs(Box, { flexDirection: "column", width: width, borderStyle: "round", borderColor: "cyan", paddingX: 1, flexShrink: 0, children: [_jsx(Text, { bold: true, color: "cyan", wrap: "truncate-end", children: title }), step.kind === 'model' ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Said, { children: "Search: " }), query || _jsx(Said, { children: "type to filter" })] })) : null, step.kind === 'profile'
86
115
  ? rows.slice(start, end).map((row, offset) => {
87
116
  const line = start + offset;
88
117
  if (row.kind === 'header') {
@@ -95,6 +124,6 @@ export function ModelPicker({ config, activeProfile, width, maxRows = 8, onSelec
95
124
  const line = start + offset;
96
125
  const focused = line === selectedLine;
97
126
  return (_jsx(Text, { color: focused ? 'cyan' : undefined, bold: focused, wrap: "truncate-end", children: ` ${id === profile?.model ? '*' : ' '} ${id}` }, `m${line}`));
98
- }), step.kind === 'model' && profile && !profile.models?.length ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Said, { children: "Only the active model is stored; press " }), _jsx(Key, { children: "r" }), _jsx(Said, { children: " to fetch this endpoint." })] })) : null, error ? (_jsx(Text, { color: "red", wrap: "truncate-end", children: error })) : null, step.kind === 'profile' ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Key, { children: "\u2191/\u2193" }), _jsx(Said, { children: " move \u00B7 " }), _jsx(Key, { children: "Enter" }), _jsx(Said, { children: " choose profile \u00B7 " }), _jsx(Key, { children: "Esc" }), _jsx(Said, { children: " close" })] })) : refreshing ? (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: "Fetching models\u2026" })) : (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Key, { children: "Enter" }), _jsx(Said, { children: " use \u00B7 " }), _jsx(Key, { children: "r" }), _jsx(Said, { children: " refetch from endpoint \u00B7 " }), _jsx(Key, { children: "Esc" }), _jsx(Said, { children: " back" })] }))] }));
127
+ }), step.kind === 'model' && models.length === 0 ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["No models match \"", query, "\". Backspace to edit, Esc to clear."] })) : null, step.kind === 'model' && profile && !profile.models?.length ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Said, { children: "Only the active model is stored; press " }), _jsx(Key, { children: "Ctrl+R" }), _jsx(Said, { children: " to fetch this endpoint." })] })) : null, error ? (_jsx(Text, { color: "red", wrap: "truncate-end", children: error })) : null, step.kind === 'profile' ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Key, { children: "\u2191/\u2193" }), _jsx(Said, { children: " move \u00B7 " }), _jsx(Key, { children: "Enter" }), _jsx(Said, { children: " choose profile \u00B7 " }), _jsx(Key, { children: "Esc" }), _jsx(Said, { children: " close" })] })) : refreshing ? (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: "Fetching models\u2026" })) : (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Key, { children: "\u2191/\u2193" }), _jsx(Said, { children: " move \u00B7 " }), _jsx(Key, { children: "Enter" }), _jsx(Said, { children: " use \u00B7 type to filter \u00B7 " }), _jsx(Key, { children: "Ctrl+R" }), _jsx(Said, { children: " refetch \u00B7 " }), _jsx(Key, { children: "Esc" }), _jsx(Said, { children: query ? ' clear search' : ' back' })] }))] }));
99
128
  }
100
129
  //# sourceMappingURL=ModelPicker.js.map
@@ -0,0 +1,40 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text } from 'ink';
3
+ import { formatPercent, formatTokens } from '../agent/tokens.js';
4
+ import { formatDuration, truncateToWidth } from './text.js';
5
+ export const USAGE_CARD_WIDTH = 27;
6
+ /** Space between the transcript column and the card. */
7
+ export const USAGE_CARD_GAP = 2;
8
+ /** Below this the card would squeeze the transcript too much, so it hides. */
9
+ export const USAGE_CARD_MIN_COLUMNS = 110;
10
+ export const USAGE_CARD_MIN_ROWS = 9;
11
+ /** The card needs its own column (Ink cannot overlay reliably), so space is a hard requirement. */
12
+ export function shouldShowUsageCard(columns, viewportHeight) {
13
+ return columns >= USAGE_CARD_MIN_COLUMNS && viewportHeight >= USAGE_CARD_MIN_ROWS;
14
+ }
15
+ export function contextBar(used, window, width) {
16
+ const size = Math.max(1, Math.floor(width));
17
+ const ratio = window > 0 ? Math.min(1, Math.max(0, used / window)) : 0;
18
+ const filled = Math.min(size, Math.round(ratio * size));
19
+ return `${'█'.repeat(filled)}${'░'.repeat(size - filled)}`;
20
+ }
21
+ export function UsageCard({ usage, contextTokens, contextWindow, contextEstimated, lastReply, busy, width = USAGE_CARD_WIDTH, }) {
22
+ const accent = busy ? 'cyan' : 'gray';
23
+ const innerWidth = Math.max(8, width - 4);
24
+ const title = truncateToWidth(`Usage · ${usage.requests} req`, innerWidth);
25
+ const prompt = usage.requests > 0 ? formatTokens(usage.promptTokens) : '—';
26
+ const completion = usage.requests > 0 ? formatTokens(usage.completionTokens) : '—';
27
+ const bar = contextBar(contextTokens, contextWindow, Math.max(4, innerWidth - 9));
28
+ const contextLine = truncateToWidth(`ctx ${bar} ${formatPercent(contextTokens, contextWindow).padStart(4)}`, innerWidth);
29
+ const windowLine = truncateToWidth(`${contextEstimated ? '~' : ''}${formatTokens(contextTokens)} / ${formatTokens(contextWindow)} window`, innerWidth);
30
+ const speed = lastReply?.tokensPerSecond !== undefined
31
+ ? lastReply.tokensPerSecond >= 1_000
32
+ ? `${formatTokens(lastReply.tokensPerSecond)} tok/s`
33
+ : `${lastReply.tokensPerSecond} tok/s`
34
+ : '';
35
+ const lastLine = truncateToWidth(lastReply
36
+ ? `last ${formatDuration(lastReply.durationMs)}${speed ? ` · ${speed}` : ''}`
37
+ : 'no timed reply yet', innerWidth);
38
+ return (_jsxs(Box, { flexDirection: "column", width: width, borderStyle: "round", borderColor: accent, paddingX: 1, flexShrink: 0, children: [_jsx(Text, { bold: true, color: accent, wrap: "truncate-end", children: title }), _jsxs(Text, { wrap: "truncate-end", children: [_jsxs(Text, { color: "green", children: ["\u2191 ", prompt] }), _jsx(Text, { children: " " }), _jsxs(Text, { color: "blue", children: ["\u2193 ", completion] })] }), _jsx(Text, { dimColor: true, wrap: "truncate-end", children: contextLine }), _jsx(Text, { dimColor: true, wrap: "truncate-end", children: windowLine }), _jsx(Text, { dimColor: true, wrap: "truncate-end", children: lastLine })] }));
39
+ }
40
+ //# sourceMappingURL=UsageCard.js.map
@@ -2,6 +2,7 @@ export const SLASH_COMMANDS = [
2
2
  { name: '/help', description: 'show this help' },
3
3
  { name: '/model', usage: '[name | add | edit | remove | test | list]', description: 'list or switch models' },
4
4
  { name: '/context', description: 'show approximate context usage' },
5
+ { name: '/usage', description: 'show or hide the usage card' },
5
6
  { name: '/compact', description: 'summarize older turns to free context' },
6
7
  { name: '/sessions', description: 'list saved sessions for this directory' },
7
8
  { name: '/resume', usage: '<n | id>', description: 'resume a saved session' },
@@ -221,6 +221,131 @@ function quoteLines(text, width) {
221
221
  segments: [{ text: marker, color: 'cyan', dim: true }, ...segments],
222
222
  }));
223
223
  }
224
+ const MIN_TABLE_COLUMN = 4;
225
+ function segmentWidth(segments) {
226
+ return displayWidth(segments.map((segment) => segment.text).join(''));
227
+ }
228
+ /** Splits a table row on pipes that are not escaped or inside inline code. */
229
+ function splitTableRow(raw) {
230
+ let text = raw.trim();
231
+ if (text.startsWith('|'))
232
+ text = text.slice(1);
233
+ if (text.endsWith('|') && !text.endsWith('\\|'))
234
+ text = text.slice(0, -1);
235
+ const cells = [];
236
+ let cell = '';
237
+ let inCode = false;
238
+ for (let index = 0; index < text.length; index++) {
239
+ const char = text[index];
240
+ if (char === '\\' && text[index + 1] === '|') {
241
+ cell += '\\|';
242
+ index++;
243
+ continue;
244
+ }
245
+ if (char === '`') {
246
+ inCode = !inCode;
247
+ cell += char;
248
+ continue;
249
+ }
250
+ if (char === '|' && !inCode) {
251
+ cells.push(cell.trim());
252
+ cell = '';
253
+ continue;
254
+ }
255
+ cell += char;
256
+ }
257
+ cells.push(cell.trim());
258
+ return cells;
259
+ }
260
+ function isDelimiterCell(cell) {
261
+ return /^:?-{3,}:?$/.test(cell);
262
+ }
263
+ function columnAlign(cell) {
264
+ const left = cell.startsWith(':');
265
+ const right = cell.endsWith(':');
266
+ if (left && right)
267
+ return 'center';
268
+ return right ? 'right' : 'left';
269
+ }
270
+ function tableRowCells(raw) {
271
+ if (!raw.includes('|'))
272
+ return null;
273
+ const cells = splitTableRow(raw);
274
+ return cells.length >= 2 ? cells : null;
275
+ }
276
+ /**
277
+ * Renders a GitHub-style table inside `width`. Cells wrap inside their column;
278
+ * if the columns cannot be made readable, the caller falls back to plain text.
279
+ */
280
+ function tableLines(header, delimiter, body, width) {
281
+ const columns = header.length;
282
+ const aligns = delimiter.map(columnAlign);
283
+ const headerCells = header.map((cell) => inlineSegments(cell, { bold: true }));
284
+ const bodyCells = body.map((row) => Array.from({ length: columns }, (_, column) => inlineSegments(row[column] ?? '')));
285
+ const natural = headerCells.map((segments, column) => {
286
+ let widest = segmentWidth(segments);
287
+ for (const row of bodyCells) {
288
+ widest = Math.max(widest, segmentWidth(row[column]));
289
+ }
290
+ return Math.max(MIN_TABLE_COLUMN, widest);
291
+ });
292
+ const overhead = columns * 3 + 1;
293
+ const available = width - overhead;
294
+ if (available < columns * MIN_TABLE_COLUMN)
295
+ return null;
296
+ const widths = [...natural];
297
+ let total = widths.reduce((sum, value) => sum + value, 0);
298
+ while (total > available) {
299
+ let widest = 0;
300
+ for (let column = 1; column < widths.length; column++) {
301
+ if (widths[column] > widths[widest])
302
+ widest = column;
303
+ }
304
+ if (widths[widest] <= MIN_TABLE_COLUMN)
305
+ return null;
306
+ widths[widest] = widths[widest] - 1;
307
+ total--;
308
+ }
309
+ const border = (left, middle, right) => ({
310
+ segments: [
311
+ {
312
+ text: `${left}${widths.map((cellWidth) => '─'.repeat(cellWidth + 2)).join(middle)}${right}`,
313
+ dim: true,
314
+ },
315
+ ],
316
+ });
317
+ const renderRow = (cells) => {
318
+ const wrapped = cells.map((segments, column) => wrapSegments(segments, widths[column]));
319
+ const height = Math.max(...wrapped.map((lines) => lines.length));
320
+ const rendered = [];
321
+ for (let lineIndex = 0; lineIndex < height; lineIndex++) {
322
+ const segments = [{ text: '│', dim: true }];
323
+ for (let column = 0; column < columns; column++) {
324
+ const cellLine = wrapped[column][lineIndex] ?? [{ text: '' }];
325
+ const padding = Math.max(0, widths[column] - segmentWidth(cellLine));
326
+ const align = aligns[column];
327
+ const leftPad = align === 'right' ? padding : align === 'center' ? Math.floor(padding / 2) : 0;
328
+ const rightPad = padding - leftPad;
329
+ segments.push({ text: ' ' });
330
+ if (leftPad > 0)
331
+ segments.push({ text: ' '.repeat(leftPad) });
332
+ segments.push(...cellLine);
333
+ if (rightPad > 0)
334
+ segments.push({ text: ' '.repeat(rightPad) });
335
+ segments.push({ text: ' ' }, { text: '│', dim: true });
336
+ }
337
+ rendered.push({ segments });
338
+ }
339
+ return rendered;
340
+ };
341
+ const lines = [border('┌', '┬', '┐')];
342
+ lines.push(...renderRow(headerCells));
343
+ lines.push(border('├', '┼', '┤'));
344
+ for (const row of bodyCells)
345
+ lines.push(...renderRow(row));
346
+ lines.push(border('└', '┴', '┘'));
347
+ return lines;
348
+ }
224
349
  function renderLine(raw, width) {
225
350
  if (!raw.trim())
226
351
  return [EMPTY_LINE];
@@ -262,8 +387,10 @@ export function renderMarkdown(text, width) {
262
387
  if (!source)
263
388
  return [EMPTY_LINE];
264
389
  const lines = [];
390
+ const sourceLines = source.split('\n');
265
391
  let fence = null;
266
- for (const raw of source.split('\n')) {
392
+ for (let index = 0; index < sourceLines.length; index++) {
393
+ const raw = sourceLines[index];
267
394
  const match = /^\s*(`{3,}|~{3,})/.exec(raw);
268
395
  if (fence) {
269
396
  if (match && raw.trim().replace(/[`~]/g, '') === '') {
@@ -278,6 +405,30 @@ export function renderMarkdown(text, width) {
278
405
  fence = match[1];
279
406
  continue;
280
407
  }
408
+ const next = sourceLines[index + 1];
409
+ if (next !== undefined) {
410
+ const header = splitTableRow(raw);
411
+ const delimiter = splitTableRow(next);
412
+ if (header.length >= 2 &&
413
+ delimiter.length === header.length &&
414
+ delimiter.every(isDelimiterCell)) {
415
+ const rows = [];
416
+ let end = index + 2;
417
+ while (end < sourceLines.length) {
418
+ const cells = tableRowCells(sourceLines[end]);
419
+ if (!cells)
420
+ break;
421
+ rows.push(cells);
422
+ end++;
423
+ }
424
+ const rendered = tableLines(header, delimiter, rows, safeWidth);
425
+ if (rendered) {
426
+ lines.push(...rendered);
427
+ index = end - 1;
428
+ continue;
429
+ }
430
+ }
431
+ }
281
432
  lines.push(...renderLine(raw, safeWidth));
282
433
  }
283
434
  return lines;
@@ -26,6 +26,16 @@ export function modelIds(profile) {
26
26
  const stored = profile.models ?? [];
27
27
  return stored.includes(profile.model) ? stored : [profile.model, ...stored];
28
28
  }
29
+ /** Case-insensitive multi-term search: every whitespace-separated term must match. */
30
+ export function filterModelIds(ids, query) {
31
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
32
+ if (terms.length === 0)
33
+ return ids;
34
+ return ids.filter((id) => {
35
+ const haystack = id.toLowerCase();
36
+ return terms.every((term) => haystack.includes(term));
37
+ });
38
+ }
29
39
  /** Keeps the highlighted line inside a window of `maxRows` entries. */
30
40
  export function pickerWindow(index, count, maxRows) {
31
41
  if (count <= 0)
package/dist/usage.js ADDED
@@ -0,0 +1,31 @@
1
+ export const EMPTY_USAGE = Object.freeze({
2
+ promptTokens: 0,
3
+ completionTokens: 0,
4
+ requests: 0,
5
+ });
6
+ function countTokens(value) {
7
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
8
+ }
9
+ /** Adds one endpoint report to the running session totals. */
10
+ export function addUsage(current, usage) {
11
+ return {
12
+ promptTokens: current.promptTokens + countTokens(usage.promptTokens),
13
+ completionTokens: current.completionTokens + countTokens(usage.completionTokens),
14
+ requests: current.requests + 1,
15
+ };
16
+ }
17
+ /**
18
+ * Reads totals back from a session file. Bad counters reset to zero instead of
19
+ * failing the resume; usage is metadata, not conversation content.
20
+ */
21
+ export function normalizeUsage(raw) {
22
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
23
+ return { ...EMPTY_USAGE };
24
+ const record = raw;
25
+ return {
26
+ promptTokens: countTokens(record.promptTokens),
27
+ completionTokens: countTokens(record.completionTokens),
28
+ requests: countTokens(record.requests),
29
+ };
30
+ }
31
+ //# sourceMappingURL=usage.js.map
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const VERSION = '0.2.2';
1
+ export const VERSION = '0.2.4';
2
2
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ywldan/kiro",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "A small terminal coding agent with your own OpenAI-compatible endpoint",
5
5
  "keywords": [
6
6
  "ai",