@ywldan/kiro 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +46 -4
  2. package/dist/agent/loop.js +3 -0
  3. package/dist/headless.js +219 -0
  4. package/dist/index.js +56 -7
  5. package/dist/providers/openai.js +101 -4
  6. package/dist/tools/checkpoint.js +158 -0
  7. package/dist/tools/fs.js +4 -0
  8. package/dist/tools/patch.js +2 -0
  9. package/dist/ui/App.js +128 -14
  10. package/dist/ui/Input.js +42 -1
  11. package/dist/ui/MessageList.js +26 -1
  12. package/dist/ui/StatusBar.js +3 -2
  13. package/dist/ui/commands.js +1 -0
  14. package/dist/ui/prompt-history.js +69 -0
  15. package/dist/ui/types.js +2 -0
  16. package/dist/version.js +1 -1
  17. package/package.json +2 -1
  18. package/dist/agent/compact.js.map +0 -1
  19. package/dist/agent/loop.js.map +0 -1
  20. package/dist/agent/prompt.js.map +0 -1
  21. package/dist/agent/tokens.js.map +0 -1
  22. package/dist/config.js.map +0 -1
  23. package/dist/env.js.map +0 -1
  24. package/dist/index.js.map +0 -1
  25. package/dist/model/cli-ui.js.map +0 -1
  26. package/dist/model/cli.js.map +0 -1
  27. package/dist/model/contexts.js.map +0 -1
  28. package/dist/model/discovery.js.map +0 -1
  29. package/dist/model/presets.js.map +0 -1
  30. package/dist/model/wizard.js.map +0 -1
  31. package/dist/providers/index.js.map +0 -1
  32. package/dist/providers/openai.js.map +0 -1
  33. package/dist/providers/types.js.map +0 -1
  34. package/dist/secrets.js.map +0 -1
  35. package/dist/sessions.js.map +0 -1
  36. package/dist/tools/diff.js.map +0 -1
  37. package/dist/tools/fs.js.map +0 -1
  38. package/dist/tools/glob.js.map +0 -1
  39. package/dist/tools/ignore.js.map +0 -1
  40. package/dist/tools/index.js.map +0 -1
  41. package/dist/tools/patch.js.map +0 -1
  42. package/dist/tools/paths.js.map +0 -1
  43. package/dist/tools/search.js.map +0 -1
  44. package/dist/tools/shell.js.map +0 -1
  45. package/dist/tools/types.js.map +0 -1
  46. package/dist/ui/App.js.map +0 -1
  47. package/dist/ui/ApprovalPrompt.js.map +0 -1
  48. package/dist/ui/Input.js.map +0 -1
  49. package/dist/ui/MessageList.js.map +0 -1
  50. package/dist/ui/ModelPicker.js.map +0 -1
  51. package/dist/ui/StatusBar.js.map +0 -1
  52. package/dist/ui/approval-policy.js.map +0 -1
  53. package/dist/ui/commands.js.map +0 -1
  54. package/dist/ui/export.js.map +0 -1
  55. package/dist/ui/history.js.map +0 -1
  56. package/dist/ui/markdown.js.map +0 -1
  57. package/dist/ui/model-picker.js.map +0 -1
  58. package/dist/ui/mouse.js.map +0 -1
  59. package/dist/ui/profile-list.js.map +0 -1
  60. package/dist/ui/text.js.map +0 -1
  61. package/dist/ui/types.js.map +0 -1
  62. package/dist/version.js.map +0 -1
@@ -0,0 +1,158 @@
1
+ import { mkdir, readFile, rename, rm, stat, writeFile, unlink } from 'node:fs/promises';
2
+ import { createHash, randomBytes } from 'node:crypto';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ /**
6
+ * File snapshots taken just before Kiro mutates workspace files, so a mistaken
7
+ * edit can be taken back with /undo. Snapshots live under
8
+ * ~/.kiro/checkpoints/<cwd-hash>/ and cost either a copy of the old bytes or a
9
+ * marker recording that the tool call created the file.
10
+ *
11
+ * run_command is not checkpointed: a shell command can touch anything, and
12
+ * snapshotting the whole workspace on every call would be too expensive.
13
+ */
14
+ const MAX_CHECKPOINTS = 30;
15
+ function checkpointsRoot() {
16
+ return process.env.KIRO_CHECKPOINTS_DIR || path.join(homedir(), '.kiro', 'checkpoints');
17
+ }
18
+ function projectCheckpointsDir(cwd) {
19
+ const key = createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 16);
20
+ return path.join(checkpointsRoot(), key);
21
+ }
22
+ function manifestPath(cwd) {
23
+ return path.join(projectCheckpointsDir(cwd), 'manifest.json');
24
+ }
25
+ function entryDir(cwd, entryId) {
26
+ return path.join(projectCheckpointsDir(cwd), entryId);
27
+ }
28
+ function emptyManifest() {
29
+ return { entries: [] };
30
+ }
31
+ async function readManifest(cwd) {
32
+ try {
33
+ const parsed = JSON.parse(await readFile(manifestPath(cwd), 'utf8'));
34
+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.entries)) {
35
+ const entries = parsed.entries.filter((entry) => entry !== null &&
36
+ typeof entry === 'object' &&
37
+ Array.isArray(entry.files));
38
+ return { entries };
39
+ }
40
+ }
41
+ catch {
42
+ // No manifest yet: a fresh store.
43
+ }
44
+ return emptyManifest();
45
+ }
46
+ async function writeManifest(cwd, manifest) {
47
+ const dir = projectCheckpointsDir(cwd);
48
+ await mkdir(dir, { recursive: true, mode: 0o700 });
49
+ const temp = `${manifestPath(cwd)}.${randomBytes(4).toString('hex')}.tmp`;
50
+ await writeFile(temp, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
51
+ await rename(temp, manifestPath(cwd));
52
+ }
53
+ function prune(cwd, entries) {
54
+ const dropped = entries.slice(0, Math.max(0, entries.length - MAX_CHECKPOINTS));
55
+ for (const entry of dropped) {
56
+ void rm(entryDir(cwd, entry.id), { recursive: true, force: true }).catch(() => undefined);
57
+ }
58
+ return entries.slice(-MAX_CHECKPOINTS);
59
+ }
60
+ /**
61
+ * Reads every file that is about to be changed. Call this before the first
62
+ * write of a tool call; paths are absolute and each entry is stored once.
63
+ */
64
+ export async function snapshotBeforeMutation(cwd, tool, absPaths) {
65
+ if (absPaths.length === 0)
66
+ return;
67
+ try {
68
+ const unique = [...new Set(absPaths.filter((abs) => path.isAbsolute(abs)))];
69
+ if (unique.length === 0)
70
+ return;
71
+ const snapshot = [];
72
+ for (const abs of unique) {
73
+ try {
74
+ const info = await stat(abs);
75
+ if (info.isDirectory())
76
+ continue;
77
+ snapshot.push({ abs, data: await readFile(abs) });
78
+ }
79
+ catch (error) {
80
+ if (error.code === 'ENOENT') {
81
+ snapshot.push({ abs, data: null });
82
+ }
83
+ // Other read errors: skip this path; /undo will simply not restore it.
84
+ }
85
+ }
86
+ if (snapshot.length === 0)
87
+ return;
88
+ const entries = prune(cwd, (await readManifest(cwd)).entries);
89
+ const entry = {
90
+ id: `${Date.now().toString(36)}-${randomBytes(3).toString('hex')}`,
91
+ tool,
92
+ files: [],
93
+ createdAt: new Date().toISOString(),
94
+ };
95
+ if (snapshot.some((file) => file.data !== null)) {
96
+ await mkdir(entryDir(cwd, entry.id), { recursive: true, mode: 0o700 });
97
+ }
98
+ for (const [index, file] of snapshot.entries()) {
99
+ let backup = null;
100
+ if (file.data !== null) {
101
+ backup = path.join(entryDir(cwd, entry.id), `${index}.bin`);
102
+ await writeFile(backup, file.data, { mode: 0o600 });
103
+ }
104
+ entry.files.push({ abs: file.abs, backup });
105
+ }
106
+ entries.push(entry);
107
+ await writeManifest(cwd, { entries });
108
+ }
109
+ catch {
110
+ // Snapshots are best effort; a failed snapshot never blocks the tool.
111
+ }
112
+ }
113
+ /**
114
+ * Reverts the most recent recorded tool call. Repeated calls step back through
115
+ * history. Returns null when there is nothing recorded.
116
+ */
117
+ export async function undoLastCheckpoint(cwd) {
118
+ const manifest = await readManifest(cwd);
119
+ if (manifest.entries.length === 0)
120
+ return null;
121
+ const entry = manifest.entries[manifest.entries.length - 1];
122
+ const restored = [];
123
+ const deleted = [];
124
+ const failed = [];
125
+ for (const file of entry.files) {
126
+ if (file.backup) {
127
+ try {
128
+ await writeFile(file.abs, await readFile(file.backup));
129
+ restored.push(file.abs);
130
+ }
131
+ catch {
132
+ failed.push(file.abs);
133
+ }
134
+ continue;
135
+ }
136
+ // The tool created this file; undo removes it again.
137
+ try {
138
+ await unlink(file.abs);
139
+ deleted.push(file.abs);
140
+ }
141
+ catch (error) {
142
+ if (error.code === 'ENOENT')
143
+ deleted.push(file.abs);
144
+ else
145
+ failed.push(file.abs);
146
+ }
147
+ }
148
+ if (failed.length > 0) {
149
+ // Keep the entry so a later /undo can retry instead of skipping the call.
150
+ throw new Error(`could not undo ${entry.tool}: ${failed.join(', ')} could not be written or removed. ` +
151
+ 'Fix the permissions and run /undo again.');
152
+ }
153
+ manifest.entries.pop();
154
+ await writeManifest(cwd, manifest);
155
+ void rm(entryDir(cwd, entry.id), { recursive: true, force: true }).catch(() => undefined);
156
+ return { tool: entry.tool, restored, deleted };
157
+ }
158
+ //# sourceMappingURL=checkpoint.js.map
package/dist/tools/fs.js CHANGED
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import readline from 'node:readline';
5
5
  import { denied, ok, requestApproval, toolError, } from './types.js';
6
6
  import { buildDiff } from './diff.js';
7
+ import { snapshotBeforeMutation } from './checkpoint.js';
7
8
  import { booleanArg, integerArg, MAX_FILE_BYTES, resolvePath, stringArg, } from './paths.js';
8
9
  const MAX_READ_BYTES = 30_000;
9
10
  const MAX_READ_LINES = 2_000;
@@ -199,6 +200,7 @@ const writeFileTool = {
199
200
  return denied();
200
201
  if (ctx.signal.aborted)
201
202
  return denied('Cancelled by user.');
203
+ await snapshotBeforeMutation(ctx.cwd, 'write_file', [resolved.abs]);
202
204
  await mkdir(path.dirname(resolved.abs), { recursive: true });
203
205
  await writeFile(resolved.abs, content, 'utf8');
204
206
  const lines = countLines(content);
@@ -375,6 +377,7 @@ const editFileTool = {
375
377
  return denied();
376
378
  if (ctx.signal.aborted)
377
379
  return denied('Cancelled by user.');
380
+ await snapshotBeforeMutation(ctx.cwd, 'edit_file', [resolved.abs]);
378
381
  await writeFile(resolved.abs, updated, 'utf8');
379
382
  const change = `+${preview.added} -${preview.removed}`;
380
383
  return ok(`Edited ${resolved.display} (${replacements} replacement${replacements === 1 ? '' : 's'}, ${change}).`, `edited ${resolved.display} (${change})`);
@@ -455,6 +458,7 @@ const multiEditTool = {
455
458
  return denied();
456
459
  if (ctx.signal.aborted)
457
460
  return denied('Cancelled by user.');
461
+ await snapshotBeforeMutation(ctx.cwd, 'multi_edit', [resolved.abs]);
458
462
  await writeFile(resolved.abs, updated, 'utf8');
459
463
  const change = `+${preview.added} -${preview.removed}`;
460
464
  return ok(`Edited ${resolved.display} (${edits.length} edit${edits.length === 1 ? '' : 's'}, ${change}).`, `edited ${resolved.display} (${change})`);
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { applyPatch as applyUnified, parsePatch } from 'diff';
5
5
  import { denied, ok, requestApproval, toolError } from './types.js';
6
6
  import { buildDiff } from './diff.js';
7
+ import { snapshotBeforeMutation } from './checkpoint.js';
7
8
  import { MAX_FILE_BYTES, resolvePath, stringArg } from './paths.js';
8
9
  const MAX_PATCH_CHARS = 1_000_000;
9
10
  const MAX_PATCH_FILES = 20;
@@ -160,6 +161,7 @@ const applyPatchTool = {
160
161
  return denied();
161
162
  if (ctx.signal.aborted)
162
163
  return denied('Cancelled by user.');
164
+ await snapshotBeforeMutation(ctx.cwd, 'apply_patch', planned.map((file) => file.abs));
163
165
  const staged = [];
164
166
  try {
165
167
  for (const file of planned) {
package/dist/ui/App.js CHANGED
@@ -23,9 +23,11 @@ import { MOUSE_OFF, MOUSE_ON } from './mouse.js';
23
23
  import { ModelPicker } from './ModelPicker.js';
24
24
  import { withProfileModel, withProfileModels } from './model-picker.js';
25
25
  import { formatProfileList } from './profile-list.js';
26
+ import { loadPromptHistory, recordPrompt } from './prompt-history.js';
26
27
  import { StatusBar } from './StatusBar.js';
27
28
  import { summarizeToolArgs } from './text.js';
28
- import { MAX_EXPANDED_TOOL_CHARS } from './types.js';
29
+ import { undoLastCheckpoint } from '../tools/checkpoint.js';
30
+ import { MAX_EXPANDED_TOOL_CHARS, MAX_REASONING_CHARS } from './types.js';
29
31
  function useTerminalSize() {
30
32
  const { stdout } = useStdout();
31
33
  const read = useCallback(() => ({
@@ -111,6 +113,11 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
111
113
  const pendingApprovalRef = useRef(null);
112
114
  const pendingResolverRef = useRef(null);
113
115
  const textBufferRef = useRef('');
116
+ const queuedRef = useRef([]);
117
+ const [queuedCount, setQueuedCount] = useState(0);
118
+ const [promptHistory, setPromptHistory] = useState([]);
119
+ const handleSubmitRef = useRef(null);
120
+ const drainQueueRef = useRef(null);
114
121
  const flushTimerRef = useRef(null);
115
122
  const addNotice = useCallback((level, text) => {
116
123
  setItems((current) => [
@@ -294,6 +301,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
294
301
  wizardCancelRequestedRef.current = false;
295
302
  transitioningRef.current = false;
296
303
  setWizardActive(false);
304
+ drainQueueRef.current?.();
297
305
  }
298
306
  }, [addNotice, finishWizardPrompt, persistConfig, wizardUi]);
299
307
  const persistSession = useCallback(() => {
@@ -375,6 +383,14 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
375
383
  return [...current, { kind: 'assistant', id: nextItemIdRef.current++, text: content }];
376
384
  });
377
385
  }, []);
386
+ /** Marks live "thinking…" items finished; reasoning is display-only and not saved. */
387
+ const finalizeReasoning = useCallback(() => {
388
+ setItems((current) => {
389
+ if (!current.some((item) => item.kind === 'reasoning' && item.draft))
390
+ return current;
391
+ return current.map((item) => item.kind === 'reasoning' && item.draft ? { ...item, draft: false } : item);
392
+ });
393
+ }, []);
378
394
  const resolveApproval = useCallback((decision) => {
379
395
  const request = pendingApprovalRef.current;
380
396
  const resolver = pendingResolverRef.current;
@@ -405,7 +421,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
405
421
  approvalPolicy.clear();
406
422
  setAutoAllowed([]);
407
423
  }, [approvalPolicy]);
408
- const sendTurn = useCallback(async (rawInput) => {
424
+ const sendTurn = useCallback(async (rawInput, alreadyDisplayed = false) => {
409
425
  if (busyRef.current || transitioningRef.current)
410
426
  return;
411
427
  const text = rawInput.trim();
@@ -416,11 +432,14 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
416
432
  setBusy(true);
417
433
  setCancelling(false);
418
434
  setActiveTool(null);
419
- setItems((current) => [
420
- ...current,
421
- { kind: 'user', id: nextItemIdRef.current++, text },
422
- ]);
435
+ if (!alreadyDisplayed) {
436
+ setItems((current) => [
437
+ ...current,
438
+ { kind: 'user', id: nextItemIdRef.current++, text },
439
+ ]);
440
+ }
423
441
  messagesRef.current.push({ role: 'user', content: text });
442
+ void recordPrompt(cwd, text).then(setPromptHistory);
424
443
  recomputeContext();
425
444
  void persistSession();
426
445
  const controller = new AbortController();
@@ -447,15 +466,39 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
447
466
  })) {
448
467
  switch (event.type) {
449
468
  case 'text':
469
+ flushText();
470
+ finalizeReasoning();
450
471
  queueText(event.text);
451
472
  break;
473
+ case 'reasoning': {
474
+ flushText();
475
+ setItems((current) => {
476
+ const last = current[current.length - 1];
477
+ if (last?.kind === 'reasoning' && last.draft) {
478
+ // Append live; MessageList clamps the rendered size.
479
+ return [...current.slice(0, -1), { ...last, text: (last.text + event.text).slice(-MAX_REASONING_CHARS) }];
480
+ }
481
+ return [
482
+ ...current,
483
+ {
484
+ kind: 'reasoning',
485
+ id: nextItemIdRef.current++,
486
+ text: event.text,
487
+ draft: true,
488
+ },
489
+ ];
490
+ });
491
+ break;
492
+ }
452
493
  case 'assistant':
453
494
  flushText();
495
+ finalizeReasoning();
454
496
  finalizeAssistant(event.content);
455
497
  recomputeContext();
456
498
  break;
457
499
  case 'tool-start':
458
500
  flushText();
501
+ finalizeReasoning();
459
502
  setActiveTool(event.toolCall.function.name);
460
503
  setItems((current) => [
461
504
  ...current,
@@ -505,6 +548,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
505
548
  break;
506
549
  case 'done':
507
550
  flushText();
551
+ finalizeReasoning();
508
552
  recomputeContext();
509
553
  if (event.reason === 'aborted') {
510
554
  addNotice('info', 'Turn cancelled.');
@@ -515,10 +559,12 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
515
559
  }
516
560
  catch (error) {
517
561
  flushText();
562
+ finalizeReasoning();
518
563
  addNotice('error', error instanceof Error ? error.message : String(error));
519
564
  }
520
565
  finally {
521
566
  flushText();
567
+ finalizeReasoning();
522
568
  abortRef.current = null;
523
569
  busyRef.current = false;
524
570
  setBusy(false);
@@ -528,6 +574,15 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
528
574
  resolveApproval('deny');
529
575
  recomputeContext();
530
576
  void persistSession();
577
+ if (!quittingRef.current) {
578
+ if (cancelRequestedRef.current && queuedRef.current.length > 0) {
579
+ queuedRef.current = [];
580
+ setQueuedCount(0);
581
+ addNotice('muted', 'Queued messages were discarded after the cancel.');
582
+ }
583
+ // Messages typed while the agent was working run next, like a chat queue.
584
+ drainQueueRef.current?.();
585
+ }
531
586
  }
532
587
  }, [
533
588
  addNotice,
@@ -941,6 +996,29 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
941
996
  : `Auto-allowed this session: ${autoAllowed.join(', ')}\nUse /allow clear to ask again.`);
942
997
  return;
943
998
  }
999
+ case '/undo': {
1000
+ if (argument) {
1001
+ addNotice('error', 'Usage: /undo (reverts the last file change; run again to step back)');
1002
+ return;
1003
+ }
1004
+ try {
1005
+ const result = await undoLastCheckpoint(cwd);
1006
+ if (!result) {
1007
+ addNotice('muted', 'Nothing to undo yet: records start with the first write, edit, or patch Kiro performs.');
1008
+ return;
1009
+ }
1010
+ const reverted = [...result.restored, ...result.deleted];
1011
+ addNotice('info', `Reverted ${reverted.length} file${reverted.length === 1 ? '' : 's'} from ${result.tool}: ` +
1012
+ [
1013
+ ...result.restored.map((p) => `restored ${p}`),
1014
+ ...result.deleted.map((p) => `deleted ${p}`),
1015
+ ].join(', '));
1016
+ }
1017
+ catch (error) {
1018
+ addNotice('error', `/undo failed: ${error instanceof Error ? error.message : String(error)}`);
1019
+ }
1020
+ return;
1021
+ }
944
1022
  case '/exit':
945
1023
  quit();
946
1024
  return;
@@ -964,26 +1042,62 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
964
1042
  version,
965
1043
  yolo,
966
1044
  ]);
967
- const handleSubmit = useCallback((value) => {
1045
+ /** Runs the next queued item once the app is idle, including queued slash commands. */
1046
+ const drainQueue = useCallback(() => {
1047
+ if (busyRef.current ||
1048
+ transitioningRef.current ||
1049
+ wizardActiveRef.current ||
1050
+ quittingRef.current) {
1051
+ return;
1052
+ }
1053
+ const next = queuedRef.current.shift();
1054
+ setQueuedCount(queuedRef.current.length);
1055
+ if (!next)
1056
+ return;
1057
+ if (next.startsWith('/')) {
1058
+ void handleCommand(next).finally(() => drainQueueRef.current?.());
1059
+ return;
1060
+ }
1061
+ handleSubmitRef.current?.(next, true);
1062
+ }, [handleCommand]);
1063
+ drainQueueRef.current = drainQueue;
1064
+ const handleSubmit = useCallback((value, fromQueue = false) => {
968
1065
  if (wizardResolveRef.current || wizardPromptRef.current) {
969
1066
  finishWizardPrompt(value);
970
1067
  return;
971
1068
  }
972
- if (wizardActiveRef.current || transitioningRef.current)
973
- return;
974
1069
  const trimmed = value.trim();
975
1070
  if (!trimmed)
976
1071
  return;
1072
+ if (wizardActiveRef.current || transitioningRef.current) {
1073
+ // The wizard owns the keyboard; ignore stray input.
1074
+ return;
1075
+ }
1076
+ if (busyRef.current && !fromQueue) {
1077
+ // Type-ahead: the message runs as soon as the current turn finishes.
1078
+ queuedRef.current.push(trimmed);
1079
+ setQueuedCount(queuedRef.current.length);
1080
+ if (!trimmed.startsWith('/')) {
1081
+ setItems((current) => [
1082
+ ...current,
1083
+ { kind: 'user', id: nextItemIdRef.current++, text: trimmed },
1084
+ ]);
1085
+ }
1086
+ addNotice('muted', 'Queued. It runs after the current turn; PgUp/PgDn still scrolls the transcript meanwhile.');
1087
+ return;
1088
+ }
977
1089
  if (trimmed.startsWith('/')) {
978
- void handleCommand(trimmed);
1090
+ void handleCommand(trimmed).finally(() => drainQueueRef.current?.());
979
1091
  return;
980
1092
  }
981
1093
  void sendTurn(trimmed);
982
- }, [finishWizardPrompt, handleCommand, sendTurn]);
1094
+ }, [addNotice, finishWizardPrompt, handleCommand, sendTurn]);
1095
+ handleSubmitRef.current = handleSubmit;
983
1096
  useEffect(() => {
984
1097
  if (configCreated) {
985
1098
  addNotice('info', `Created config template at ${configPath}. Set your endpoint, model, and API key.`);
986
1099
  }
1100
+ void loadPromptHistory(cwd).then(setPromptHistory);
987
1101
  const active = config.profiles[config.activeProfile];
988
1102
  if (active) {
989
1103
  if (active.type !== 'openai') {
@@ -1061,14 +1175,14 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1061
1175
  const contextWindow = contextWindowFor(activeProfile);
1062
1176
  const menuRows = pendingApproval || pickerOpen ? 0 : slashMenuRows;
1063
1177
  const viewportHeight = Math.max(3, rows - 5 - (pendingApproval ? 12 : 0) - (pickerOpen ? 13 : 0) - menuRows);
1064
- 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: busy, width: width, mask: wizardPrompt?.mask, allowEmpty: wizardPrompt?.allowEmpty, placeholder: wizardPrompt
1178
+ 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
1065
1179
  ? wizardPrompt.defaultValue && !wizardPrompt.mask
1066
1180
  ? `${wizardPrompt.label} [${wizardPrompt.defaultValue}]`
1067
1181
  : wizardPrompt.label
1068
1182
  : busy
1069
- ? 'Kiro is working… Ctrl+C to cancel'
1183
+ ? 'Kiro is working… type ahead, or Ctrl+C to cancel'
1070
1184
  : wizardActive
1071
1185
  ? 'Working… Esc to cancel'
1072
- : '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, yolo: yolo, autoAllowed: autoAllowed, contextTokens: contextTokens, contextWindow: contextWindow })] }));
1186
+ : '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, queued: queuedCount > 0 ? queuedCount : undefined, yolo: yolo, autoAllowed: autoAllowed, contextTokens: contextTokens, contextWindow: contextWindow })] }));
1073
1187
  }
1074
1188
  //# sourceMappingURL=App.js.map
package/dist/ui/Input.js CHANGED
@@ -7,13 +7,21 @@ 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, onSubmit, onCancel, onMenuRowsChange, }) {
10
+ export function Input({ disabled, placeholder, width, mask = false, allowEmpty = false, slashMenu = true, history, onSubmit, onCancel, onMenuRowsChange, }) {
11
11
  const { stdin } = useStdin();
12
12
  const [state, setState] = useState({ chars: [], cursor: 0 });
13
13
  const [selected, setSelected] = useState(0);
14
+ const [historyIndex, setHistoryIndex] = useState(null);
14
15
  const stateRef = useRef(state);
15
16
  stateRef.current = state;
16
17
  const text = state.chars.join('');
18
+ const recalled = historyIndex !== null ? (history?.[historyIndex] ?? null) : null;
19
+ useEffect(() => {
20
+ // Editing the recalled entry (or pressing a letter) ends history browsing.
21
+ if (historyIndex !== null && text !== recalled) {
22
+ setHistoryIndex(null);
23
+ }
24
+ }, [historyIndex, recalled, text]);
17
25
  const matches = slashMenu && !mask && !disabled ? filterSlashCommands(text) : [];
18
26
  const menuOpen = matches.length > 0;
19
27
  const activeIndex = Math.min(selected, Math.max(0, matches.length - 1));
@@ -103,6 +111,39 @@ export function Input({ disabled, placeholder, width, mask = false, allowEmpty =
103
111
  return;
104
112
  }
105
113
  }
114
+ if (!mask && history && history.length > 0) {
115
+ if (key.upArrow) {
116
+ // History recall starts from an empty prompt: ↑ steps backwards
117
+ // through submitted prompts, ↓ leaves history again.
118
+ if (historyIndex === null) {
119
+ if (chars.length > 0)
120
+ return;
121
+ setHistoryIndex(history.length - 1);
122
+ const value = history[history.length - 1] ?? '';
123
+ update(Array.from(value), value.length);
124
+ return;
125
+ }
126
+ if (historyIndex > 0) {
127
+ setHistoryIndex(historyIndex - 1);
128
+ const value = history[historyIndex - 1] ?? '';
129
+ update(Array.from(value), value.length);
130
+ }
131
+ return;
132
+ }
133
+ if (key.downArrow && historyIndex !== null) {
134
+ const next = historyIndex + 1;
135
+ if (next >= history.length) {
136
+ setHistoryIndex(null);
137
+ update([], 0);
138
+ }
139
+ else {
140
+ setHistoryIndex(next);
141
+ const value = history[next] ?? '';
142
+ update(Array.from(value), value.length);
143
+ }
144
+ return;
145
+ }
146
+ }
106
147
  if (key.return) {
107
148
  if (menuOpen) {
108
149
  const command = matches[activeIndex].name;
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useRef, useState } from 'react';
3
3
  import { Box, Text, useInput, useStdin } from 'ink';
4
- import { MAX_EXPANDED_TOOL_CHARS } from './types.js';
4
+ import { MAX_EXPANDED_TOOL_CHARS, MAX_REASONING_CHARS } from './types.js';
5
5
  import { renderMarkdown } from './markdown.js';
6
6
  import { parseMouseWheel } from './mouse.js';
7
7
  import { displayWidth, formatDuration, sanitizeText, truncateToWidth, wrapPlain, } from './text.js';
@@ -16,6 +16,14 @@ const BANNER = [
16
16
  function blankLine() {
17
17
  return { prefix: '', text: '' };
18
18
  }
19
+ /** Keeps head and tail of a long reasoning trace so the newest thinking stays visible. */
20
+ function clampReasoning(text) {
21
+ if (text.length <= MAX_REASONING_CHARS)
22
+ return text;
23
+ const head = Math.floor(MAX_REASONING_CHARS * 0.4);
24
+ const tail = MAX_REASONING_CHARS - head;
25
+ return `${text.slice(0, head)}\n… [earlier reasoning omitted] …\n${text.slice(-tail)}`;
26
+ }
19
27
  function block(text, firstPrefix, restPrefix, width, style = {}) {
20
28
  const prefixWidth = displayWidth(firstPrefix);
21
29
  const contentWidth = Math.max(1, width - Math.max(prefixWidth, displayWidth(restPrefix)));
@@ -127,6 +135,23 @@ function itemLines(item, width, expandedToolId) {
127
135
  lines.push(blankLine());
128
136
  return lines;
129
137
  }
138
+ case 'reasoning': {
139
+ const header = [
140
+ {
141
+ prefix: '◔ ',
142
+ prefixColor: 'magenta',
143
+ text: item.draft ? 'thinking…' : 'reasoning (done, not saved)',
144
+ dim: true,
145
+ },
146
+ ];
147
+ // Collapse finished traces: they are display-only, and leaving every
148
+ // reasoning block expanded floods the transcript in long tool loops.
149
+ if (item.draft) {
150
+ header.push(...block(clampReasoning(item.text), ' · ', ' · ', width - 2, { dim: true }));
151
+ }
152
+ header.push(blankLine());
153
+ return header;
154
+ }
130
155
  case 'tool':
131
156
  return toolLines(item, width, item.id === expandedToolId);
132
157
  case 'notice': {
@@ -14,7 +14,7 @@ function prettyCwd(cwd) {
14
14
  }
15
15
  return cwd;
16
16
  }
17
- export function StatusBar({ width, profile, model, cwd, activity, toolName, yolo = false, autoAllowed = [], contextTokens, contextWindow, }) {
17
+ export function StatusBar({ width, profile, model, cwd, activity, toolName, queued, yolo = false, autoAllowed = [], contextTokens, contextWindow, }) {
18
18
  const busy = activity !== null;
19
19
  const [frame, setFrame] = useState(0);
20
20
  useEffect(() => {
@@ -34,6 +34,7 @@ export function StatusBar({ width, profile, model, cwd, activity, toolName, yolo
34
34
  : 'ready';
35
35
  const stateColor = activity === 'cancelling' ? 'red' : activity === null ? 'green' : 'yellow';
36
36
  const spinner = busy ? `${SPINNER[frame] ?? '⠋'} ` : '';
37
+ const queueNote = queued ? `${queued} queued · ` : '';
37
38
  const badge = yolo
38
39
  ? 'YOLO'
39
40
  : autoAllowed.length > 0
@@ -42,7 +43,7 @@ export function StatusBar({ width, profile, model, cwd, activity, toolName, yolo
42
43
  const badgeWidth = badge === '' ? 0 : displayWidth(badge) + 2;
43
44
  // The bar is indented to line up with the chat text, so budgets use the inner width.
44
45
  const innerWidth = Math.max(10, width - 2);
45
- const state = `${spinner}${stateText}`;
46
+ const state = `${spinner}${queueNote}${stateText}`;
46
47
  const stateBudget = Math.max(4, Math.max(10, Math.floor(innerWidth / 2)) - badgeWidth);
47
48
  const stateShown = truncateToWidth(state, stateBudget);
48
49
  const restBudget = Math.max(0, innerWidth - badgeWidth - displayWidth(stateShown) - 2 - 6);
@@ -5,6 +5,7 @@ export const SLASH_COMMANDS = [
5
5
  { name: '/compact', description: 'summarize older turns to free context' },
6
6
  { name: '/sessions', description: 'list saved sessions for this directory' },
7
7
  { name: '/resume', usage: '<n | id>', description: 'resume a saved session' },
8
+ { name: '/undo', description: 'revert the last file change Kiro made (write/edit/patch)' },
8
9
  { name: '/clear', description: 'start a new session' },
9
10
  { name: '/export', usage: '[file]', description: 'write the transcript to a Markdown file' },
10
11
  { name: '/mouse', description: 'toggle mouse reporting (wheel scroll vs text selection)' },