@ywldan/kiro 0.3.2 → 0.5.0

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/dist/ui/App.js CHANGED
@@ -14,6 +14,7 @@ import { runAddFlow, runEditFlow, runRemoveFlow, } from '../model/wizard.js';
14
14
  import { createProvider } from '../providers/index.js';
15
15
  import { dropIncompleteToolCalls, formatSessionTime, isSessionId, listAllSessions, listSessions, loadSession, newSessionId, projectSessionsDir, saveSession, titleFromMessages, } from '../sessions.js';
16
16
  import { ApprovalPrompt } from './ApprovalPrompt.js';
17
+ import { AskUserPrompt } from './AskUserPrompt.js';
17
18
  import { ApprovalPolicy } from './approval-policy.js';
18
19
  import { builtinCommandNames, buildSkillCommands, SLASH_COMMANDS, slashHelpLines, } from './commands.js';
19
20
  import { defaultExportPath, renderTranscriptMarkdown } from './export.js';
@@ -30,12 +31,19 @@ import { formatProfileList } from './profile-list.js';
30
31
  import { loadPromptHistory, recordPrompt } from './prompt-history.js';
31
32
  import { StatusBar } from './StatusBar.js';
32
33
  import { summarizeToolArgs } from './text.js';
34
+ import { MAX_PREVIEW_LINES } from './approval-preview.js';
35
+ import { formatMcpStatus } from '../mcp/registry.js';
33
36
  import { UsageCard, USAGE_CARD_GAP, USAGE_CARD_WIDTH, shouldShowUsageCard, } from './UsageCard.js';
34
37
  import { addUsage, EMPTY_USAGE } from '../usage.js';
38
+ import { formatCost } from '../cost.js';
39
+ import { addCost, priceFor, sessionCost as restoredCost, } from '../cost.js';
35
40
  import { undoLastCheckpoint } from '../tools/checkpoint.js';
41
+ import { addRule, clearRules, loadRules, permissionsPath, removeRule, } from '../permissions.js';
36
42
  import { MAX_EXPANDED_TOOL_CHARS, MAX_REASONING_CHARS, } from './types.js';
37
43
  /** Idle Ctrl+C must be pressed again within this window to exit. */
38
44
  const QUIT_CONFIRM_MS = 2_000;
45
+ /** Tallest inline question block: title, three question lines, four options, other, footer, borders. */
46
+ const ASK_INLINE_ROWS = 12;
39
47
  function useTerminalSize() {
40
48
  const { stdout } = useStdout();
41
49
  const read = useCallback(() => ({
@@ -52,7 +60,7 @@ function useTerminalSize() {
52
60
  }, [stdout, read]);
53
61
  return size;
54
62
  }
55
- export function App({ config, baseConfig, overrides, configPath, configCreated, cwd: initialCwd, version, yolo, mouseEnabled, initialSession, startupNotices, }) {
63
+ export function App({ config, baseConfig, overrides, configPath, configCreated, cwd: initialCwd, version, yolo, mouseEnabled, initialSession, startupNotices, mcp, }) {
56
64
  const { exit } = useApp();
57
65
  const { stdout } = useStdout();
58
66
  const { columns, rows } = useTerminalSize();
@@ -85,8 +93,11 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
85
93
  const [wizardPrompt, setWizardPrompt] = useState(null);
86
94
  const [wizardActive, setWizardActive] = useState(false);
87
95
  const [activeTool, setActiveTool] = useState(null);
96
+ /** Newest output line of the running command, shown in the status bar. */
97
+ const [liveTail, setLiveTail] = useState(null);
88
98
  const [cancelling, setCancelling] = useState(false);
89
99
  const [pendingApproval, setPendingApproval] = useState(null);
100
+ const [pendingQuestion, setPendingQuestion] = useState(null);
90
101
  const [pickerOpen, setPickerOpen] = useState(false);
91
102
  const [sessionPicker, setSessionPicker] = useState(null);
92
103
  const [quitArmed, setQuitArmed] = useState(false);
@@ -111,6 +122,16 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
111
122
  const roundCompletionTokensRef = useRef(null);
112
123
  const [sessionUsage, setSessionUsage] = useState(() => initialSession?.usage ?? EMPTY_USAGE);
113
124
  const sessionUsageRef = useRef(sessionUsage);
125
+ /** Running cost estimate; `complete` turns false once a request had no known price. */
126
+ const [sessionCost, setSessionCost] = useState({ dollars: 0, complete: true });
127
+ const sessionCostRef = useRef(sessionCost);
128
+ /** Price of the active profile's model; a profile `pricing` entry wins over the table. */
129
+ const profilePricing = config.profiles[profileName]?.pricing;
130
+ const currentPrice = profilePricing ?? priceFor(config.profiles[profileName]?.model ?? '', config.profiles[profileName]?.baseUrl);
131
+ const currentPriceRef = useRef(currentPrice);
132
+ currentPriceRef.current = currentPrice;
133
+ const priceRef = currentPriceRef;
134
+ const hasPrice = currentPrice !== null;
114
135
  const [lastReply, setLastReply] = useState(null);
115
136
  const [contextTokens, setContextTokens] = useState(() => estimateMessagesTokens(messagesRef.current));
116
137
  const contextTokensRef = useRef(contextTokens);
@@ -144,8 +165,14 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
144
165
  const quitTimerRef = useRef(null);
145
166
  const [approvalPolicy] = useState(() => new ApprovalPolicy(yolo));
146
167
  const [autoAllowed, setAutoAllowed] = useState([]);
168
+ /** Saved rules for this project; empty until the first read finishes. */
169
+ const [savedRules, setSavedRules] = useState([]);
170
+ /** Set when a saved rule refused the pending request. */
171
+ const [ruleNote, setRuleNote] = useState(null);
147
172
  const pendingApprovalRef = useRef(null);
148
173
  const pendingResolverRef = useRef(null);
174
+ const pendingQuestionRef = useRef(null);
175
+ const questionResolverRef = useRef(null);
149
176
  const textBufferRef = useRef('');
150
177
  const queuedRef = useRef([]);
151
178
  const [queuedCount, setQueuedCount] = useState(0);
@@ -159,6 +186,19 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
159
186
  { kind: 'notice', id: nextItemIdRef.current++, level, text },
160
187
  ]);
161
188
  }, []);
189
+ /** Reads this project's saved rules; a broken file reports once and never blocks a turn. */
190
+ const refreshRules = useCallback(async (report = false) => {
191
+ const set = await loadRules(cwd);
192
+ if (set.problem && report)
193
+ addNotice('error', set.problem);
194
+ approvalPolicy.setRules(set.rules);
195
+ setSavedRules(set.rules);
196
+ return set.rules;
197
+ }, [addNotice, approvalPolicy, cwd]);
198
+ // Rules live in the project, so a resumed session in another directory reloads them.
199
+ useEffect(() => {
200
+ void refreshRules();
201
+ }, [refreshRules]);
162
202
  const updateContextTokens = useCallback((tokens) => {
163
203
  const rounded = Math.max(0, Math.round(tokens));
164
204
  contextTokensRef.current = rounded;
@@ -244,7 +284,11 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
244
284
  if (profile.apiKeyEnv && !key) {
245
285
  return { ok: false, message: `API key is missing: $${profile.apiKeyEnv} is not set.` };
246
286
  }
247
- const result = await discoverModels({ baseUrl: profile.baseUrl, apiKey: key });
287
+ const result = await discoverModels({
288
+ baseUrl: profile.baseUrl,
289
+ apiKey: key,
290
+ headers: profile.headers,
291
+ });
248
292
  if (!result.ok)
249
293
  return { ok: false, message: result.message };
250
294
  if (result.models.length === 0) {
@@ -465,17 +509,38 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
465
509
  pendingApprovalRef.current = null;
466
510
  pendingResolverRef.current = null;
467
511
  setPendingApproval(null);
512
+ setRuleNote(null);
468
513
  if (!request || !resolver)
469
514
  return;
515
+ const saveRule = (rule, note) => {
516
+ if (!rule)
517
+ return;
518
+ void addRule(cwd, rule)
519
+ .then((set) => {
520
+ approvalPolicy.setRules(set.rules);
521
+ setSavedRules(set.rules);
522
+ addNotice('info', note(set.path));
523
+ })
524
+ .catch((error) => {
525
+ addNotice('error', `Could not save the rule: ${error instanceof Error ? error.message : String(error)}`);
526
+ });
527
+ };
470
528
  if (decision === 'allow-session') {
471
529
  approvalPolicy.markSession(request.tool);
472
530
  setAutoAllowed(approvalPolicy.list());
473
531
  addNotice('info', `${request.tool} will run without asking. Use /allow to list, /allow clear to revoke.`);
474
532
  }
475
- resolver(decision);
476
- }, [addNotice, approvalPolicy]);
533
+ else if (decision === 'allow-rule') {
534
+ saveRule(approvalPolicy.ruleFor(request), (file) => `Saved ${approvalPolicy.ruleFor(request)?.match} to ${file}. Edit or delete it with /rules.`);
535
+ }
536
+ else if (decision === 'deny-rule') {
537
+ saveRule(approvalPolicy.denyRuleFor(request), (file) => `Added a deny rule for ${request.subject} to ${file}. /rules lists and removes it.`);
538
+ }
539
+ resolver(decision === 'allow-rule' ? 'allow' : decision === 'deny-rule' ? 'deny' : decision);
540
+ }, [addNotice, approvalPolicy, cwd]);
477
541
  const approve = useCallback((request) => {
478
- if (approvalPolicy.isAuto(request.tool))
542
+ const verdict = approvalPolicy.decide(request);
543
+ if (verdict === 'allow')
479
544
  return Promise.resolve('allow');
480
545
  if (abortRef.current?.signal.aborted)
481
546
  return Promise.resolve('deny');
@@ -483,8 +548,34 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
483
548
  pendingApprovalRef.current = request;
484
549
  pendingResolverRef.current = resolve;
485
550
  setPendingApproval(request);
551
+ setRuleNote(verdict === 'deny'
552
+ ? `A saved rule denies this ${request.tool === 'run_command' ? 'command' : 'path'}.`
553
+ : null);
486
554
  });
487
555
  }, [approvalPolicy]);
556
+ const resolveQuestion = useCallback((answer) => {
557
+ const resolver = questionResolverRef.current;
558
+ pendingQuestionRef.current = null;
559
+ questionResolverRef.current = null;
560
+ setPendingQuestion(null);
561
+ resolver?.(answer);
562
+ }, []);
563
+ const askUser = useCallback((request) => {
564
+ const signal = abortRef.current?.signal;
565
+ if (signal?.aborted)
566
+ return Promise.resolve({ selected: [], cancelled: true });
567
+ return new Promise((resolve) => {
568
+ // Cancelling the turn must release the tool, even if Ctrl+C skipped the prompt.
569
+ const onAbort = () => resolveQuestion({ selected: [], cancelled: true });
570
+ signal?.addEventListener('abort', onAbort, { once: true });
571
+ pendingQuestionRef.current = request;
572
+ questionResolverRef.current = (answer) => {
573
+ signal?.removeEventListener('abort', onAbort);
574
+ resolve(answer);
575
+ };
576
+ setPendingQuestion(request);
577
+ });
578
+ }, [resolveQuestion]);
488
579
  const resetAutoAllowed = useCallback(() => {
489
580
  approvalPolicy.clear();
490
581
  setAutoAllowed([]);
@@ -566,6 +657,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
566
657
  cwd,
567
658
  signal: controller.signal,
568
659
  approve,
660
+ askUser,
569
661
  };
570
662
  for await (const event of runAgentTurn({
571
663
  provider,
@@ -632,8 +724,23 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
632
724
  },
633
725
  ]);
634
726
  break;
727
+ case 'tool-output':
728
+ setLiveTail(event.tail);
729
+ setItems((current) => {
730
+ const index = current.findIndex((item) => item.kind === 'tool' && item.callId === event.toolCall.id);
731
+ if (index === -1)
732
+ return current;
733
+ const item = current[index];
734
+ if (item?.kind !== 'tool' || item.liveTail === event.tail)
735
+ return current;
736
+ const next = [...current];
737
+ next[index] = { ...item, liveTail: event.tail };
738
+ return next;
739
+ });
740
+ break;
635
741
  case 'tool-end':
636
742
  setActiveTool(null);
743
+ setLiveTail(null);
637
744
  setItems((current) => {
638
745
  const index = current.findIndex((item) => item.kind === 'tool' && item.callId === event.toolCall.id && item.status === 'running');
639
746
  if (index === -1)
@@ -645,6 +752,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
645
752
  next[index] = {
646
753
  ...item,
647
754
  status: event.result.status,
755
+ liveTail: undefined,
648
756
  resultSummary: event.result.summary,
649
757
  resultFull: event.result.content.slice(0, MAX_EXPANDED_TOOL_CHARS),
650
758
  durationMs: event.durationMs,
@@ -672,6 +780,9 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
672
780
  const totals = addUsage(sessionUsageRef.current, event.usage);
673
781
  sessionUsageRef.current = totals;
674
782
  setSessionUsage(totals);
783
+ const priced = addCost(sessionCostRef.current, event.usage, currentPriceRef.current);
784
+ sessionCostRef.current = priced;
785
+ setSessionCost(priced);
675
786
  roundCompletionTokensRef.current = event.usage.completionTokens;
676
787
  recomputeContext();
677
788
  break;
@@ -708,6 +819,8 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
708
819
  setCancelling(false);
709
820
  if (pendingApprovalRef.current)
710
821
  resolveApproval('deny');
822
+ if (pendingQuestionRef.current)
823
+ resolveQuestion({ selected: [], cancelled: true });
711
824
  recomputeContext();
712
825
  void persistSession();
713
826
  void refreshSkillCommands();
@@ -724,6 +837,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
724
837
  }, [
725
838
  addNotice,
726
839
  approve,
840
+ askUser,
727
841
  autoCompact,
728
842
  cwd,
729
843
  finalizeAssistant,
@@ -735,6 +849,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
735
849
  queueText,
736
850
  recomputeContext,
737
851
  resolveApproval,
852
+ resolveQuestion,
738
853
  ]);
739
854
  const runProfileTest = useCallback(async (requested) => {
740
855
  if (busyRef.current || transitioningRef.current || wizardActiveRef.current) {
@@ -781,7 +896,11 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
781
896
  return;
782
897
  }
783
898
  addNotice('muted', `Fetching models from ${profile.baseUrl}…`);
784
- const result = await discoverModels({ baseUrl: profile.baseUrl, apiKey: key });
899
+ const result = await discoverModels({
900
+ baseUrl: profile.baseUrl,
901
+ apiKey: key,
902
+ headers: profile.headers,
903
+ });
785
904
  if (!result.ok) {
786
905
  addNotice('error', result.message);
787
906
  return;
@@ -828,6 +947,9 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
828
947
  const restoredUsage = record.usage ?? EMPTY_USAGE;
829
948
  sessionUsageRef.current = restoredUsage;
830
949
  setSessionUsage(restoredUsage);
950
+ const restored = restoredCost(restoredUsage, priceRef.current);
951
+ sessionCostRef.current = restored;
952
+ setSessionCost(restored);
831
953
  setLastReply(null);
832
954
  recomputeContext();
833
955
  sessionRef.current = {
@@ -956,6 +1078,10 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
956
1078
  ? `Session usage: ↑ ${formatTokens(totals.promptTokens)} sent, ↓ ${formatTokens(totals.completionTokens)} received ` +
957
1079
  `across ${totals.requests} API request${totals.requests === 1 ? '' : 's'} (saved with this session).`
958
1080
  : 'Session usage: the endpoint has not reported token counts for this session yet.',
1081
+ hasPrice
1082
+ ? `Estimated cost: ${sessionCost.complete ? '' : '~'}${formatCost(sessionCost.dollars)} ` +
1083
+ `($${currentPrice.input}/M in, $${currentPrice.output}/M out${profilePricing ? ', from the profile' : ', list price'}).`
1084
+ : 'Cost: no known list price for this model. Set "pricing" in the profile to track it.',
959
1085
  `Auto-compaction runs at ${Math.round(COMPACT_THRESHOLD * 100)}% and keeps the last ${COMPACT_KEEP_USER_TURNS} user turns verbatim. /compact runs it now.`,
960
1086
  ].join('\n'));
961
1087
  return;
@@ -1162,6 +1288,8 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1162
1288
  usageRef.current = null;
1163
1289
  sessionUsageRef.current = EMPTY_USAGE;
1164
1290
  setSessionUsage(EMPTY_USAGE);
1291
+ sessionCostRef.current = { dollars: 0, complete: true };
1292
+ setSessionCost(sessionCostRef.current);
1165
1293
  setLastReply(null);
1166
1294
  updateContextTokens(0);
1167
1295
  sessionRef.current = null;
@@ -1221,6 +1349,61 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1221
1349
  : 'Mouse reporting off: click-drag selects text normally; use PgUp/PgDn to scroll.');
1222
1350
  return;
1223
1351
  }
1352
+ case '/mcp': {
1353
+ if (argument) {
1354
+ addNotice('error', 'Usage: /mcp (lists configured servers for this session)');
1355
+ return;
1356
+ }
1357
+ addNotice('info', formatMcpStatus(mcp ?? null, cwd));
1358
+ return;
1359
+ }
1360
+ case '/rules': {
1361
+ const rules = await refreshRules(true);
1362
+ if (argument === 'clear') {
1363
+ try {
1364
+ const file = await clearRules(cwd);
1365
+ approvalPolicy.setRules([]);
1366
+ setSavedRules([]);
1367
+ addNotice('info', `Removed ${file}. Every tool asks for approval again.`);
1368
+ }
1369
+ catch (error) {
1370
+ addNotice('error', `Could not clear the rules: ${error.message}`);
1371
+ }
1372
+ return;
1373
+ }
1374
+ if (argument?.startsWith('remove ')) {
1375
+ const index = Number(argument.slice('remove '.length).trim());
1376
+ const rule = rules[index - 1];
1377
+ if (!Number.isInteger(index) || !rule) {
1378
+ addNotice('error', `Usage: /rules remove <n>, where n is 1-${rules.length}.`);
1379
+ return;
1380
+ }
1381
+ try {
1382
+ const set = await removeRule(cwd, rule);
1383
+ approvalPolicy.setRules(set.rules);
1384
+ setSavedRules(set.rules);
1385
+ addNotice('info', `Removed "${rule.match}" for ${rule.tool}. ${set.rules.length} rules left.`);
1386
+ }
1387
+ catch (error) {
1388
+ addNotice('error', `Could not remove the rule: ${error.message}`);
1389
+ }
1390
+ return;
1391
+ }
1392
+ if (argument) {
1393
+ addNotice('error', 'Usage: /rules, /rules remove <n>, or /rules clear');
1394
+ return;
1395
+ }
1396
+ const numbered = rules.map((rule, index) => ` ${index + 1}. ${rule.action} ${rule.tool} ~ ${rule.match}`);
1397
+ addNotice('info', rules.length === 0
1398
+ ? `No saved rules for this project. Choose [s] on an approval prompt to allow a pattern, or [d] to deny one.\nRules live in ${permissionsPath(cwd)}.`
1399
+ : [
1400
+ `Saved rules (${permissionsPath(cwd)}):`,
1401
+ ...numbered,
1402
+ '',
1403
+ '/rules remove <n> deletes one; /rules clear deletes the file.',
1404
+ ].join('\n'));
1405
+ return;
1406
+ }
1224
1407
  case '/allow': {
1225
1408
  if (argument === 'clear') {
1226
1409
  resetAutoAllowed();
@@ -1409,8 +1592,12 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1409
1592
  }, [stdout, mouseOn]);
1410
1593
  useInput((input, key) => {
1411
1594
  if (key.ctrl && input === 'o') {
1412
- if (wizardActiveRef.current || wizardPromptRef.current || pendingApprovalRef.current)
1595
+ if (wizardActiveRef.current ||
1596
+ wizardPromptRef.current ||
1597
+ pendingApprovalRef.current ||
1598
+ pendingQuestionRef.current) {
1413
1599
  return;
1600
+ }
1414
1601
  if (pickerOpen || sessionPicker !== null)
1415
1602
  return;
1416
1603
  expandLastToolOutput();
@@ -1433,11 +1620,12 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1433
1620
  cancelWizard();
1434
1621
  return;
1435
1622
  }
1436
- if (pendingApprovalRef.current) {
1623
+ if (pendingApprovalRef.current || pendingQuestionRef.current) {
1437
1624
  disarmQuit();
1438
1625
  cancelRequestedRef.current = true;
1439
1626
  setCancelling(true);
1440
1627
  resolveApproval('deny');
1628
+ resolveQuestion({ selected: [], cancelled: true });
1441
1629
  abortRef.current?.abort();
1442
1630
  return;
1443
1631
  }
@@ -1458,45 +1646,59 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1458
1646
  }
1459
1647
  armQuit();
1460
1648
  });
1461
- const activity = pendingApproval
1462
- ? 'approval'
1463
- : cancelling
1464
- ? 'cancelling'
1465
- : busy
1466
- ? activeTool
1467
- ? 'running'
1468
- : replying
1469
- ? 'replying'
1470
- : 'thinking'
1471
- : null;
1649
+ const activity = pendingQuestion
1650
+ ? 'question'
1651
+ : pendingApproval
1652
+ ? 'approval'
1653
+ : cancelling
1654
+ ? 'cancelling'
1655
+ : busy
1656
+ ? activeTool
1657
+ ? 'running'
1658
+ : replying
1659
+ ? 'replying'
1660
+ : 'thinking'
1661
+ : null;
1472
1662
  const activeProfile = runtimeConfig.profiles[profileName];
1473
1663
  const contextWindow = contextWindowFor(activeProfile);
1664
+ const questionPopup = pendingQuestion !== null && !pendingApproval ? pickerPopupRect(columns, rows) : null;
1665
+ const questionInline = pendingQuestion !== null && !pendingApproval && questionPopup === null;
1474
1666
  const pickerPopup = (pickerOpen || sessionPicker !== null) && !pendingApproval
1475
1667
  ? pickerPopupRect(columns, rows)
1476
1668
  : null;
1477
1669
  const pickerInline = pickerOpen && !pendingApproval && pickerPopup === null;
1478
1670
  const sessionInline = sessionPicker !== null && !pendingApproval && pickerPopup === null && !pickerOpen;
1479
- const extraInputRows = pendingApproval || pickerInline || sessionInline ? 0 : Math.max(0, inputRows - 1);
1671
+ const extraInputRows = pendingApproval || questionInline || pickerInline || sessionInline
1672
+ ? 0
1673
+ : Math.max(0, inputRows - 1);
1480
1674
  const viewportHeight = Math.max(3, rows -
1481
1675
  5 -
1482
1676
  extraInputRows -
1483
1677
  (pendingApproval ? 12 : 0) -
1678
+ (questionInline ? ASK_INLINE_ROWS : 0) -
1484
1679
  (pickerInline ? PICKER_INLINE_ROWS : 0) -
1485
1680
  (sessionInline ? SESSION_INLINE_ROWS : 0));
1486
1681
  const showUsageCard = usageCardEnabled && shouldShowUsageCard(columns, viewportHeight);
1487
1682
  const chatWidth = showUsageCard ? Math.max(40, width - USAGE_CARD_WIDTH - USAGE_CARD_GAP) : width;
1488
- 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 && sessionPicker === null && !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 })) : pickerInline ? (_jsx(ModelPicker, { config: runtimeConfig, activeProfile: profileName, width: width, onSelect: (name, model) => void selectModel(name, model), onRefresh: refreshProfileModels, onCancel: () => setPickerOpen(false) })) : sessionInline && sessionPicker ? (_jsx(SessionPicker, { cwd: cwd, data: sessionPicker, activeSessionId: sessionRef.current?.id ?? null, width: width, onSelect: handleSessionPick, onCancel: () => setSessionPicker(null) })) : (_jsx(Input, { disabled: pickerOpen || sessionPicker !== null, width: width, mask: wizardPrompt?.mask, allowEmpty: wizardPrompt?.allowEmpty, fileMenu: !wizardActive && !wizardPrompt, loadFiles: loadFileIndex, maxRows: Math.max(1, Math.min(6, rows - 9)), history: wizardPrompt || wizardActive ? undefined : promptHistory, slashCommands: [...SLASH_COMMANDS, ...skillCommands], onPaletteChange: setPalette, onHeightChange: setInputRows, placeholder: pickerOpen
1683
+ 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 &&
1684
+ pendingQuestion === null &&
1685
+ !pickerOpen &&
1686
+ sessionPicker === null &&
1687
+ !wizardActive &&
1688
+ 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, cost: hasPrice ? sessionCost : undefined, busy: busy }) })) : null] }), pendingApproval ? (_jsx(ApprovalPrompt, { request: pendingApproval, width: width, rulePattern: approvalPolicy.ruleFor(pendingApproval)?.match, ruleNote: ruleNote ?? undefined, maxPreviewLines: rows - 5 - extraInputRows - 12 >= 16 ? MAX_PREVIEW_LINES : 3, onDecision: resolveApproval })) : questionInline && pendingQuestion ? (_jsx(AskUserPrompt, { request: pendingQuestion, width: width, onAnswer: resolveQuestion, onCancel: () => resolveQuestion({ selected: [], cancelled: true }) })) : pickerInline ? (_jsx(ModelPicker, { config: runtimeConfig, activeProfile: profileName, width: width, onSelect: (name, model) => void selectModel(name, model), onRefresh: refreshProfileModels, onCancel: () => setPickerOpen(false) })) : sessionInline && sessionPicker ? (_jsx(SessionPicker, { cwd: cwd, data: sessionPicker, activeSessionId: sessionRef.current?.id ?? null, width: width, onSelect: handleSessionPick, onCancel: () => setSessionPicker(null) })) : (_jsx(Input, { disabled: pickerOpen || sessionPicker !== null || pendingQuestion !== null, width: width, mask: wizardPrompt?.mask, allowEmpty: wizardPrompt?.allowEmpty, fileMenu: !wizardActive && !wizardPrompt, loadFiles: loadFileIndex, maxRows: Math.max(1, Math.min(6, rows - 9)), history: wizardPrompt || wizardActive ? undefined : promptHistory, slashCommands: [...SLASH_COMMANDS, ...skillCommands], onPaletteChange: setPalette, onHeightChange: setInputRows, placeholder: pickerOpen
1489
1689
  ? 'Model picker open · Esc to close'
1490
1690
  : sessionPicker
1491
1691
  ? 'Session picker open · Esc to close'
1492
- : wizardPrompt
1493
- ? wizardPrompt.defaultValue && !wizardPrompt.mask
1494
- ? `${wizardPrompt.label} [${wizardPrompt.defaultValue}]`
1495
- : wizardPrompt.label
1496
- : busy
1497
- ? 'Kiro is working… type ahead, or Ctrl+C to cancel'
1498
- : wizardActive
1499
- ? 'Working… Esc to cancel'
1500
- : '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, quitHint: quitArmed, contextTokens: showUsageCard ? undefined : contextTokens, contextWindow: showUsageCard ? undefined : contextWindow }), pickerOpen && pickerPopup ? (_jsx(Box, { position: "absolute", marginTop: pickerPopup.top, marginLeft: pickerPopup.left, children: _jsx(ModelPicker, { config: runtimeConfig, activeProfile: profileName, width: pickerPopup.width, height: pickerPopup.height, onSelect: (name, model) => void selectModel(name, model), onRefresh: refreshProfileModels, onCancel: () => setPickerOpen(false) }) })) : sessionPicker && pickerPopup ? (_jsx(Box, { position: "absolute", marginTop: pickerPopup.top, marginLeft: pickerPopup.left, children: _jsx(SessionPicker, { cwd: cwd, data: sessionPicker, activeSessionId: sessionRef.current?.id ?? null, width: pickerPopup.width, height: pickerPopup.height, onSelect: handleSessionPick, onCancel: () => setSessionPicker(null) }) })) : null] }));
1692
+ : pendingQuestion
1693
+ ? 'Answer the question above · Esc to cancel'
1694
+ : wizardPrompt
1695
+ ? wizardPrompt.defaultValue && !wizardPrompt.mask
1696
+ ? `${wizardPrompt.label} [${wizardPrompt.defaultValue}]`
1697
+ : wizardPrompt.label
1698
+ : busy
1699
+ ? 'Kiro is working… type ahead, or Ctrl+C to cancel'
1700
+ : wizardActive
1701
+ ? 'Working… Esc to cancel'
1702
+ : '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, liveTail: liveTail, busySince: busySince ?? undefined, queued: queuedCount > 0 ? queuedCount : undefined, yolo: yolo, autoAllowed: autoAllowed, quitHint: quitArmed, contextTokens: showUsageCard ? undefined : contextTokens, contextWindow: showUsageCard ? undefined : contextWindow }), pendingQuestion && questionPopup ? (_jsx(Box, { position: "absolute", marginTop: questionPopup.top, marginLeft: questionPopup.left, children: _jsx(AskUserPrompt, { request: pendingQuestion, width: questionPopup.width, height: questionPopup.height, onAnswer: resolveQuestion, onCancel: () => resolveQuestion({ selected: [], cancelled: true }) }) })) : pickerOpen && pickerPopup ? (_jsx(Box, { position: "absolute", marginTop: pickerPopup.top, marginLeft: pickerPopup.left, children: _jsx(ModelPicker, { config: runtimeConfig, activeProfile: profileName, width: pickerPopup.width, height: pickerPopup.height, onSelect: (name, model) => void selectModel(name, model), onRefresh: refreshProfileModels, onCancel: () => setPickerOpen(false) }) })) : sessionPicker && pickerPopup ? (_jsx(Box, { position: "absolute", marginTop: pickerPopup.top, marginLeft: pickerPopup.left, children: _jsx(SessionPicker, { cwd: cwd, data: sessionPicker, activeSessionId: sessionRef.current?.id ?? null, width: pickerPopup.width, height: pickerPopup.height, onSelect: handleSessionPick, onCancel: () => setSessionPicker(null) }) })) : null] }));
1501
1703
  }
1502
1704
  //# sourceMappingURL=App.js.map
@@ -1,48 +1,45 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { Box, Text, useInput } from 'ink';
3
+ import { MAX_PREVIEW_LINES, windowPreview } from './approval-preview.js';
3
4
  import { sanitizeText, truncateToWidth, wrapPlain } from './text.js';
4
- const MAX_PREVIEW_LINES = 5;
5
- export function ApprovalPrompt({ request, width, onDecision }) {
5
+ function lineColor(line) {
6
+ if (line.startsWith('+'))
7
+ return 'green';
8
+ if (line.startsWith('-'))
9
+ return 'red';
10
+ if (line.startsWith('@@'))
11
+ return 'cyan';
12
+ return undefined;
13
+ }
14
+ export function ApprovalPrompt({ request, width, rulePattern, ruleNote, maxPreviewLines = MAX_PREVIEW_LINES, onDecision, }) {
6
15
  useInput((input, key) => {
7
16
  if (input === 'y' || input === 'Y')
8
17
  onDecision('allow');
9
18
  else if (input === 'a' || input === 'A')
10
19
  onDecision('allow-session');
20
+ else if (input === 's' || input === 'S') {
21
+ if (rulePattern)
22
+ onDecision('allow-rule');
23
+ }
24
+ else if (input === 'd' || input === 'D') {
25
+ if (request.subject !== undefined)
26
+ onDecision('deny-rule');
27
+ }
11
28
  else if (input === 'n' || input === 'N' || key.escape)
12
29
  onDecision('deny');
13
30
  });
14
31
  const innerWidth = Math.max(10, width - 4);
15
- const rawDetail = sanitizeText(request.detail ?? '').split('\n');
16
- let previewLines;
17
- let truncated;
18
- if (request.tool === 'run_command') {
19
- const wrapped = rawDetail.flatMap((line) => wrapPlain(line, innerWidth));
20
- previewLines = wrapped.slice(0, MAX_PREVIEW_LINES);
21
- truncated = wrapped.length > MAX_PREVIEW_LINES;
22
- }
23
- else {
24
- previewLines = rawDetail
25
- .slice(0, MAX_PREVIEW_LINES)
26
- .map((line) => truncateToWidth(line, innerWidth));
27
- truncated = rawDetail.length > MAX_PREVIEW_LINES;
28
- }
29
- if (truncated && previewLines.length > 0) {
30
- const last = previewLines.length - 1;
31
- previewLines[last] = `${truncateToWidth(previewLines[last] ?? '', innerWidth - 2)} …`;
32
- }
33
- if (previewLines.length === 0)
34
- previewLines = ['(no preview)'];
35
- return (_jsxs(Box, { flexDirection: "column", width: width, borderStyle: "round", borderColor: "yellow", paddingX: 1, flexShrink: 0, children: [_jsx(Text, { bold: true, color: "yellow", wrap: "truncate-end", children: `⚠ Approval needed · ${request.title}` }), request.warning ? (_jsx(Text, { color: "red", wrap: "truncate-end", children: `! ${request.warning}` })) : null, previewLines.map((line, index) => {
36
- const color = request.tool !== 'run_command'
37
- ? line.startsWith('+') && !line.startsWith('+++')
38
- ? 'green'
39
- : line.startsWith('-') && !line.startsWith('---')
40
- ? 'red'
41
- : line.startsWith('@@')
42
- ? 'cyan'
43
- : undefined
44
- : undefined;
32
+ const detail = sanitizeText(request.detail ?? '').trimEnd();
33
+ const rawDetail = detail ? detail.split('\n') : [];
34
+ // Commands are wrapped so a long line does not hide the rest of the script;
35
+ // diffs are clipped, since a wrapped diff row reads as a different change.
36
+ const fitted = request.tool === 'run_command'
37
+ ? rawDetail.flatMap((line) => wrapPlain(line, innerWidth))
38
+ : rawDetail.map((line) => truncateToWidth(line, innerWidth));
39
+ const previewLines = fitted.length === 0 ? ['(no preview yet)'] : windowPreview(fitted, request.tool, maxPreviewLines);
40
+ return (_jsxs(Box, { flexDirection: "column", width: width, borderStyle: "round", borderColor: "yellow", paddingX: 1, flexShrink: 0, children: [_jsx(Text, { bold: true, color: "yellow", wrap: "truncate-end", children: `⚠ Approval needed · ${request.title}` }), request.warning ? (_jsx(Text, { color: "red", wrap: "truncate-end", children: `! ${request.warning}` })) : null, ruleNote ? (_jsx(Text, { color: "magenta", wrap: "truncate-end", children: `! ${ruleNote}` })) : null, previewLines.map((line, index) => {
41
+ const color = request.tool === 'run_command' ? undefined : lineColor(line);
45
42
  return (_jsx(Text, { color: color, dimColor: color === undefined, wrap: "truncate-end", children: line || ' ' }, index));
46
- }), _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "green", bold: true, children: "[y]" }), _jsx(Text, { children: " allow once " }), _jsx(Text, { color: "red", bold: true, children: "[n]" }), _jsx(Text, { children: " deny" })] }), _jsxs(Text, { dimColor: true, wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", bold: true, children: "[a]" }), ' ', "always allow ", request.tool, " for this session"] })] }));
43
+ }), _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "green", bold: true, children: "[y]" }), _jsx(Text, { children: " allow once " }), _jsx(Text, { color: "red", bold: true, children: "[n]" }), _jsx(Text, { children: " deny" })] }), _jsxs(Text, { dimColor: true, wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", bold: true, children: "[a]" }), ' ', "allow ", request.tool, " for this session", rulePattern ? (_jsxs(_Fragment, { children: [_jsx(Text, { children: " " }), _jsx(Text, { color: "green", bold: true, children: "[s]" }), _jsx(Text, { children: ` always allow ${rulePattern}` })] })) : null] }), request.subject !== undefined ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: [_jsx(Text, { color: "magenta", bold: true, children: "[d]" }), _jsx(Text, { children: ` always deny this ${request.tool === 'run_command' ? 'command' : 'path'}` })] })) : null] }));
47
44
  }
48
45
  //# sourceMappingURL=ApprovalPrompt.js.map