@ywldan/kiro 0.2.3 → 0.2.5

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,7 +290,9 @@ 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, anchored to the bottom just above the input, 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
+
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.
294
296
 
295
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
 
@@ -312,7 +314,8 @@ Slash commands:
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) |
@@ -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,6 +26,8 @@ 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
32
  import { MAX_EXPANDED_TOOL_CHARS, MAX_REASONING_CHARS, } from './types.js';
31
33
  function useTerminalSize() {
@@ -79,12 +81,16 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
79
81
  const [pendingApproval, setPendingApproval] = useState(null);
80
82
  const [pickerOpen, setPickerOpen] = useState(false);
81
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
@@ -319,6 +325,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
319
325
  }
320
326
  const session = sessionRef.current;
321
327
  const snapshot = structuredClone(messages);
328
+ const usage = { ...sessionUsageRef.current };
322
329
  const write = saveChainRef.current
323
330
  .then(() => saveSession({
324
331
  id: session.id,
@@ -328,6 +335,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
328
335
  title: session.title,
329
336
  createdAt: session.createdAt,
330
337
  messages: snapshot,
338
+ usage,
331
339
  }))
332
340
  .then(() => undefined)
333
341
  .catch((error) => {
@@ -512,6 +520,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
512
520
  ? Math.round(completionTokens / (durationMs / 1_000))
513
521
  : undefined;
514
522
  finalizeAssistant(event.content, durationMs, tokensPerSecond);
523
+ setLastReply({ durationMs, tokensPerSecond });
515
524
  roundCompletionTokensRef.current = null;
516
525
  setReplying(false);
517
526
  recomputeContext();
@@ -558,16 +567,20 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
558
567
  roundStartedAtRef.current = Date.now();
559
568
  roundCompletionTokensRef.current = null;
560
569
  break;
561
- case 'usage':
570
+ case 'usage': {
562
571
  usageRef.current = {
563
572
  tokens: event.usage.totalTokens,
564
573
  // The assistant message from this response is appended after the
565
574
  // stream ends and is already counted in totalTokens.
566
575
  messageCount: messagesRef.current.length + 1,
567
576
  };
577
+ const totals = addUsage(sessionUsageRef.current, event.usage);
578
+ sessionUsageRef.current = totals;
579
+ setSessionUsage(totals);
568
580
  roundCompletionTokensRef.current = event.usage.completionTokens;
569
581
  recomputeContext();
570
582
  break;
583
+ }
571
584
  case 'notice':
572
585
  flushText();
573
586
  addNotice(event.level, event.message);
@@ -790,6 +803,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
790
803
  const used = contextTokensRef.current;
791
804
  const count = (role) => estimateMessagesTokens(messagesRef.current.filter((message) => message.role === role));
792
805
  const usage = usageRef.current;
806
+ const totals = sessionUsageRef.current;
793
807
  addNotice('info', [
794
808
  `Context: ~${formatTokens(used)} / ${formatTokens(window)} tokens (${formatPercent(used, window)} used)` +
795
809
  (profile?.contextWindow
@@ -800,10 +814,26 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
800
814
  usage
801
815
  ? `Last API usage: ${usage.tokens.toLocaleString()} tokens for the last request and response.`
802
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.',
803
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.`,
804
822
  ].join('\n'));
805
823
  return;
806
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
+ }
807
837
  case '/compact': {
808
838
  if (messagesRef.current.length === 0) {
809
839
  addNotice('muted', 'There is no conversation to compact yet.');
@@ -912,6 +942,10 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
912
942
  const record = await loadSession(cwd, targetId);
913
943
  messagesRef.current = record.messages.filter((message) => message.role !== 'system');
914
944
  usageRef.current = null;
945
+ const restoredUsage = record.usage ?? EMPTY_USAGE;
946
+ sessionUsageRef.current = restoredUsage;
947
+ setSessionUsage(restoredUsage);
948
+ setLastReply(null);
915
949
  recomputeContext();
916
950
  sessionRef.current = {
917
951
  id: record.id,
@@ -947,6 +981,9 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
947
981
  await saveChainRef.current;
948
982
  messagesRef.current = [];
949
983
  usageRef.current = null;
984
+ sessionUsageRef.current = EMPTY_USAGE;
985
+ setSessionUsage(EMPTY_USAGE);
986
+ setLastReply(null);
950
987
  updateContextTokens(0);
951
988
  sessionRef.current = null;
952
989
  listedSessionsRef.current = null;
@@ -1067,6 +1104,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1067
1104
  runModelFlow,
1068
1105
  runProfileTest,
1069
1106
  updateContextTokens,
1107
+ usageCardEnabled,
1070
1108
  version,
1071
1109
  yolo,
1072
1110
  ]);
@@ -1204,7 +1242,9 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1204
1242
  const activeProfile = runtimeConfig.profiles[profileName];
1205
1243
  const contextWindow = contextWindowFor(activeProfile);
1206
1244
  const viewportHeight = Math.max(3, rows - 5 - (pendingApproval ? 12 : 0) - (pickerOpen ? 13 : 0));
1207
- return (_jsxs(Box, { flexDirection: "column", width: columns, paddingX: 1, children: [_jsx(MessageList, { items: items, width: width, height: viewportHeight, resetSignal: resetSignal, expandedToolId: expandedToolId, palette: palette, 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, onPaletteChange: setPalette, placeholder: wizardPrompt
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-end", 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
1208
1248
  ? wizardPrompt.defaultValue && !wizardPrompt.mask
1209
1249
  ? `${wizardPrompt.label} [${wizardPrompt.defaultValue}]`
1210
1250
  : wizardPrompt.label
@@ -1212,6 +1252,6 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1212
1252
  ? 'Kiro is working… type ahead, or Ctrl+C to cancel'
1213
1253
  : wizardActive
1214
1254
  ? 'Working… Esc to cancel'
1215
- : '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: 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 })] }));
1216
1256
  }
1217
1257
  //# sourceMappingURL=App.js.map
@@ -276,7 +276,7 @@ export function MessageList({ items, width, height, resetSignal, expandedToolId
276
276
  }, { isActive: interactive });
277
277
  const visible = lines.slice(scrollTop, scrollTop + height);
278
278
  const shown = applyPalette(visible, palette, width, height);
279
- return (_jsx(Box, { flexDirection: "column", height: height, overflowY: "hidden", flexShrink: 0, justifyContent: "flex-end", children: shown.map((line, index) => {
279
+ return (_jsx(Box, { flexDirection: "column", width: width, height: height, overflowY: "hidden", flexShrink: 0, justifyContent: "flex-end", children: shown.map((line, index) => {
280
280
  const hasSuffix = line.suffix !== undefined;
281
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
282
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)))
@@ -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;
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.3';
1
+ export const VERSION = '0.2.5';
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.3",
3
+ "version": "0.2.5",
4
4
  "description": "A small terminal coding agent with your own OpenAI-compatible endpoint",
5
5
  "keywords": [
6
6
  "ai",