@ywldan/kiro 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +429 -2
- package/dist/agent/compact.js +133 -0
- package/dist/agent/compact.js.map +1 -0
- package/dist/agent/loop.js +253 -0
- package/dist/agent/loop.js.map +1 -0
- package/dist/agent/prompt.js +53 -0
- package/dist/agent/prompt.js.map +1 -0
- package/dist/agent/tokens.js +36 -0
- package/dist/agent/tokens.js.map +1 -0
- package/dist/config.js +382 -0
- package/dist/config.js.map +1 -0
- package/dist/env.js +203 -0
- package/dist/env.js.map +1 -0
- package/dist/index.js +272 -0
- package/dist/index.js.map +1 -0
- package/dist/model/cli-ui.js +458 -0
- package/dist/model/cli-ui.js.map +1 -0
- package/dist/model/cli.js +382 -0
- package/dist/model/cli.js.map +1 -0
- package/dist/model/contexts.js +61 -0
- package/dist/model/contexts.js.map +1 -0
- package/dist/model/discovery.js +225 -0
- package/dist/model/discovery.js.map +1 -0
- package/dist/model/presets.js +60 -0
- package/dist/model/presets.js.map +1 -0
- package/dist/model/wizard.js +663 -0
- package/dist/model/wizard.js.map +1 -0
- package/dist/providers/index.js +10 -0
- package/dist/providers/index.js.map +1 -0
- package/dist/providers/openai.js +422 -0
- package/dist/providers/openai.js.map +1 -0
- package/dist/providers/types.js +19 -0
- package/dist/providers/types.js.map +1 -0
- package/dist/secrets.js +63 -0
- package/dist/secrets.js.map +1 -0
- package/dist/sessions.js +248 -0
- package/dist/sessions.js.map +1 -0
- package/dist/tools/diff.js +32 -0
- package/dist/tools/diff.js.map +1 -0
- package/dist/tools/fs.js +524 -0
- package/dist/tools/fs.js.map +1 -0
- package/dist/tools/glob.js +105 -0
- package/dist/tools/glob.js.map +1 -0
- package/dist/tools/ignore.js +63 -0
- package/dist/tools/ignore.js.map +1 -0
- package/dist/tools/index.js +65 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/patch.js +191 -0
- package/dist/tools/patch.js.map +1 -0
- package/dist/tools/paths.js +85 -0
- package/dist/tools/paths.js.map +1 -0
- package/dist/tools/search.js +553 -0
- package/dist/tools/search.js.map +1 -0
- package/dist/tools/shell.js +189 -0
- package/dist/tools/shell.js.map +1 -0
- package/dist/tools/types.js +16 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/ui/App.js +1074 -0
- package/dist/ui/App.js.map +1 -0
- package/dist/ui/ApprovalPrompt.js +48 -0
- package/dist/ui/ApprovalPrompt.js.map +1 -0
- package/dist/ui/Input.js +213 -0
- package/dist/ui/Input.js.map +1 -0
- package/dist/ui/MessageList.js +214 -0
- package/dist/ui/MessageList.js.map +1 -0
- package/dist/ui/ModelPicker.js +100 -0
- package/dist/ui/ModelPicker.js.map +1 -0
- package/dist/ui/StatusBar.js +63 -0
- package/dist/ui/StatusBar.js.map +1 -0
- package/dist/ui/approval-policy.js +22 -0
- package/dist/ui/approval-policy.js.map +1 -0
- package/dist/ui/commands.js +30 -0
- package/dist/ui/commands.js.map +1 -0
- package/dist/ui/export.js +65 -0
- package/dist/ui/export.js.map +1 -0
- package/dist/ui/history.js +86 -0
- package/dist/ui/history.js.map +1 -0
- package/dist/ui/markdown.js +285 -0
- package/dist/ui/markdown.js.map +1 -0
- package/dist/ui/model-picker.js +59 -0
- package/dist/ui/model-picker.js.map +1 -0
- package/dist/ui/mouse.js +36 -0
- package/dist/ui/mouse.js.map +1 -0
- package/dist/ui/profile-list.js +40 -0
- package/dist/ui/profile-list.js.map +1 -0
- package/dist/ui/text.js +328 -0
- package/dist/ui/text.js.map +1 -0
- package/dist/ui/types.js +3 -0
- package/dist/ui/types.js.map +1 -0
- package/dist/version.js +2 -0
- package/dist/version.js.map +1 -0
- package/package.json +58 -4
package/dist/ui/App.js
ADDED
|
@@ -0,0 +1,1074 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { Box, useApp, useInput, useStdout } from 'ink';
|
|
4
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { buildSystemPrompt } from '../agent/prompt.js';
|
|
7
|
+
import { runAgentTurn } from '../agent/loop.js';
|
|
8
|
+
import { COMPACT_KEEP_USER_TURNS, COMPACT_THRESHOLD, compactMessages, shouldCompact, } from '../agent/compact.js';
|
|
9
|
+
import { estimateMessagesTokens, formatPercent, formatTokens } from '../agent/tokens.js';
|
|
10
|
+
import { applyOverrides, contextWindowFor, resolveProfile, saveConfig, } from '../config.js';
|
|
11
|
+
import { discoverModels, testConnection } from '../model/discovery.js';
|
|
12
|
+
import { runAddFlow, runEditFlow, runRemoveFlow, } from '../model/wizard.js';
|
|
13
|
+
import { createProvider } from '../providers/index.js';
|
|
14
|
+
import { dropIncompleteToolCalls, formatSessionTime, isSessionId, listSessions, loadSession, newSessionId, projectSessionsDir, saveSession, titleFromMessages, } from '../sessions.js';
|
|
15
|
+
import { ApprovalPrompt } from './ApprovalPrompt.js';
|
|
16
|
+
import { ApprovalPolicy } from './approval-policy.js';
|
|
17
|
+
import { slashHelpLines } from './commands.js';
|
|
18
|
+
import { defaultExportPath, renderTranscriptMarkdown } from './export.js';
|
|
19
|
+
import { buildResumedView } from './history.js';
|
|
20
|
+
import { Input } from './Input.js';
|
|
21
|
+
import { MessageList } from './MessageList.js';
|
|
22
|
+
import { MOUSE_OFF, MOUSE_ON } from './mouse.js';
|
|
23
|
+
import { ModelPicker } from './ModelPicker.js';
|
|
24
|
+
import { withProfileModel, withProfileModels } from './model-picker.js';
|
|
25
|
+
import { formatProfileList } from './profile-list.js';
|
|
26
|
+
import { StatusBar } from './StatusBar.js';
|
|
27
|
+
import { summarizeToolArgs } from './text.js';
|
|
28
|
+
import { MAX_EXPANDED_TOOL_CHARS } from './types.js';
|
|
29
|
+
function useTerminalSize() {
|
|
30
|
+
const { stdout } = useStdout();
|
|
31
|
+
const read = useCallback(() => ({
|
|
32
|
+
columns: stdout.columns || 80,
|
|
33
|
+
rows: stdout.rows || 24,
|
|
34
|
+
}), [stdout]);
|
|
35
|
+
const [size, setSize] = useState(read);
|
|
36
|
+
useEffect(() => {
|
|
37
|
+
const onResize = () => setSize(read());
|
|
38
|
+
stdout.on('resize', onResize);
|
|
39
|
+
return () => {
|
|
40
|
+
stdout.off('resize', onResize);
|
|
41
|
+
};
|
|
42
|
+
}, [stdout, read]);
|
|
43
|
+
return size;
|
|
44
|
+
}
|
|
45
|
+
export function App({ config, baseConfig, overrides, configPath, configCreated, cwd, version, yolo, mouseEnabled, initialSession, startupNotices, }) {
|
|
46
|
+
const { exit } = useApp();
|
|
47
|
+
const { stdout } = useStdout();
|
|
48
|
+
const { columns, rows } = useTerminalSize();
|
|
49
|
+
const width = Math.max(20, columns - 2);
|
|
50
|
+
const initialViewRef = useRef(null);
|
|
51
|
+
if (initialViewRef.current === null) {
|
|
52
|
+
const view = initialSession
|
|
53
|
+
? buildResumedView(initialSession.messages, { cwd, version, sessionId: initialSession.id })
|
|
54
|
+
: { items: [{ kind: 'banner', id: 0, cwd, version }], nextId: 1 };
|
|
55
|
+
if (yolo) {
|
|
56
|
+
view.items.push({
|
|
57
|
+
kind: 'notice',
|
|
58
|
+
id: view.nextId++,
|
|
59
|
+
level: 'error',
|
|
60
|
+
text: 'YOLO mode: Kiro writes files and runs commands without asking. Restart without --yolo to get approvals back.',
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
initialViewRef.current = view;
|
|
64
|
+
}
|
|
65
|
+
const nextItemIdRef = useRef(initialViewRef.current.nextId);
|
|
66
|
+
const [items, setItems] = useState(initialViewRef.current.items);
|
|
67
|
+
const [resetSignal, setResetSignal] = useState(0);
|
|
68
|
+
const [runtimeConfig, setRuntimeConfig] = useState(config);
|
|
69
|
+
const [profileName, setProfileName] = useState(config.activeProfile);
|
|
70
|
+
const [busy, setBusy] = useState(false);
|
|
71
|
+
const [wizardPrompt, setWizardPrompt] = useState(null);
|
|
72
|
+
const [wizardActive, setWizardActive] = useState(false);
|
|
73
|
+
const [activeTool, setActiveTool] = useState(null);
|
|
74
|
+
const [cancelling, setCancelling] = useState(false);
|
|
75
|
+
const [pendingApproval, setPendingApproval] = useState(null);
|
|
76
|
+
const [pickerOpen, setPickerOpen] = useState(false);
|
|
77
|
+
const [slashMenuRows, setSlashMenuRows] = useState(0);
|
|
78
|
+
const [mouseOn, setMouseOn] = useState(mouseEnabled);
|
|
79
|
+
const [expandedToolId, setExpandedToolId] = useState(null);
|
|
80
|
+
const messagesRef = useRef((initialSession?.messages ?? []).filter((message) => message.role !== 'system'));
|
|
81
|
+
const usageRef = useRef(null);
|
|
82
|
+
const [contextTokens, setContextTokens] = useState(() => estimateMessagesTokens(messagesRef.current));
|
|
83
|
+
const contextTokensRef = useRef(contextTokens);
|
|
84
|
+
const sessionRef = useRef(initialSession
|
|
85
|
+
? {
|
|
86
|
+
id: initialSession.id,
|
|
87
|
+
createdAt: initialSession.createdAt,
|
|
88
|
+
title: initialSession.title,
|
|
89
|
+
}
|
|
90
|
+
: null);
|
|
91
|
+
const saveChainRef = useRef(Promise.resolve());
|
|
92
|
+
const saveErrorShownRef = useRef(false);
|
|
93
|
+
const listedSessionsRef = useRef(null);
|
|
94
|
+
const transitioningRef = useRef(false);
|
|
95
|
+
const quittingRef = useRef(false);
|
|
96
|
+
const configRef = useRef(runtimeConfig);
|
|
97
|
+
configRef.current = runtimeConfig;
|
|
98
|
+
const baseConfigRef = useRef(baseConfig);
|
|
99
|
+
const wizardResolveRef = useRef(null);
|
|
100
|
+
const wizardPromptRef = useRef(wizardPrompt);
|
|
101
|
+
wizardPromptRef.current = wizardPrompt;
|
|
102
|
+
const wizardActiveRef = useRef(false);
|
|
103
|
+
const wizardCancelRequestedRef = useRef(false);
|
|
104
|
+
const wizardAbortRef = useRef(null);
|
|
105
|
+
const wizardPromptIdRef = useRef(0);
|
|
106
|
+
const busyRef = useRef(false);
|
|
107
|
+
const abortRef = useRef(null);
|
|
108
|
+
const cancelRequestedRef = useRef(false);
|
|
109
|
+
const [approvalPolicy] = useState(() => new ApprovalPolicy(yolo));
|
|
110
|
+
const [autoAllowed, setAutoAllowed] = useState([]);
|
|
111
|
+
const pendingApprovalRef = useRef(null);
|
|
112
|
+
const pendingResolverRef = useRef(null);
|
|
113
|
+
const textBufferRef = useRef('');
|
|
114
|
+
const flushTimerRef = useRef(null);
|
|
115
|
+
const addNotice = useCallback((level, text) => {
|
|
116
|
+
setItems((current) => [
|
|
117
|
+
...current,
|
|
118
|
+
{ kind: 'notice', id: nextItemIdRef.current++, level, text },
|
|
119
|
+
]);
|
|
120
|
+
}, []);
|
|
121
|
+
const updateContextTokens = useCallback((tokens) => {
|
|
122
|
+
const rounded = Math.max(0, Math.round(tokens));
|
|
123
|
+
contextTokensRef.current = rounded;
|
|
124
|
+
setContextTokens(rounded);
|
|
125
|
+
}, []);
|
|
126
|
+
const handleMenuRowsChange = useCallback((rows) => {
|
|
127
|
+
setSlashMenuRows((current) => (current === rows ? current : rows));
|
|
128
|
+
}, []);
|
|
129
|
+
const recomputeContext = useCallback(() => {
|
|
130
|
+
const messages = messagesRef.current;
|
|
131
|
+
const usage = usageRef.current;
|
|
132
|
+
updateContextTokens(usage && usage.messageCount <= messages.length
|
|
133
|
+
? usage.tokens + estimateMessagesTokens(messages.slice(usage.messageCount))
|
|
134
|
+
: estimateMessagesTokens(messages));
|
|
135
|
+
}, [updateContextTokens]);
|
|
136
|
+
const autoCompact = useCallback(async (messages, signal, options) => {
|
|
137
|
+
const profile = configRef.current.profiles[profileName];
|
|
138
|
+
const window = contextWindowFor(profile);
|
|
139
|
+
const used = Math.max(estimateMessagesTokens(messages), contextTokensRef.current);
|
|
140
|
+
if (!options?.force && !shouldCompact(used, window, COMPACT_THRESHOLD))
|
|
141
|
+
return null;
|
|
142
|
+
const resolved = resolveProfile(configRef.current, profileName);
|
|
143
|
+
const provider = createProvider(resolved.profile, resolved.apiKey);
|
|
144
|
+
const result = await compactMessages({
|
|
145
|
+
messages,
|
|
146
|
+
provider,
|
|
147
|
+
signal,
|
|
148
|
+
keepUserTurns: COMPACT_KEEP_USER_TURNS,
|
|
149
|
+
});
|
|
150
|
+
if (result) {
|
|
151
|
+
usageRef.current = null;
|
|
152
|
+
updateContextTokens(result.afterTokens);
|
|
153
|
+
}
|
|
154
|
+
return result;
|
|
155
|
+
}, [profileName, updateContextTokens]);
|
|
156
|
+
const persistConfig = useCallback(async (next) => {
|
|
157
|
+
await saveConfig(next);
|
|
158
|
+
baseConfigRef.current = next;
|
|
159
|
+
let effective = next;
|
|
160
|
+
try {
|
|
161
|
+
effective = applyOverrides(next, overrides);
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
if (overrides.profile) {
|
|
165
|
+
addNotice('muted', `CLI profile override "${overrides.profile}" is no longer configured; using the saved active profile.`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
configRef.current = effective;
|
|
169
|
+
setRuntimeConfig(effective);
|
|
170
|
+
setProfileName(effective.activeProfile);
|
|
171
|
+
}, [addNotice, overrides]);
|
|
172
|
+
/** Saves a profile edit without resetting the session's active profile. */
|
|
173
|
+
const persistProfileChange = useCallback(async (next) => {
|
|
174
|
+
await saveConfig(next);
|
|
175
|
+
baseConfigRef.current = next;
|
|
176
|
+
let effective = next;
|
|
177
|
+
try {
|
|
178
|
+
effective = applyOverrides(next, overrides);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
// A CLI override that no longer resolves falls back to the saved config.
|
|
182
|
+
}
|
|
183
|
+
configRef.current = effective;
|
|
184
|
+
setRuntimeConfig(effective);
|
|
185
|
+
}, [overrides]);
|
|
186
|
+
const selectModel = useCallback(async (name, model) => {
|
|
187
|
+
setPickerOpen(false);
|
|
188
|
+
const switching = name !== profileName;
|
|
189
|
+
if (switching)
|
|
190
|
+
setProfileName(name);
|
|
191
|
+
try {
|
|
192
|
+
await persistProfileChange(withProfileModel(baseConfigRef.current, name, model));
|
|
193
|
+
addNotice('info', switching
|
|
194
|
+
? `Switched to profile "${name}" (${model}).`
|
|
195
|
+
: `Model "${model}" is now active for profile "${name}".`);
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
addNotice('error', `Could not save the model choice: ${error.message}`);
|
|
199
|
+
}
|
|
200
|
+
}, [addNotice, persistProfileChange, profileName]);
|
|
201
|
+
const refreshProfileModels = useCallback(async (name) => {
|
|
202
|
+
const profile = baseConfigRef.current.profiles[name] ?? configRef.current.profiles[name];
|
|
203
|
+
if (!profile)
|
|
204
|
+
return { ok: false, message: `Unknown profile "${name}".` };
|
|
205
|
+
const key = profile.apiKeyEnv ? process.env[profile.apiKeyEnv] : undefined;
|
|
206
|
+
if (profile.apiKeyEnv && !key) {
|
|
207
|
+
return { ok: false, message: `API key is missing: $${profile.apiKeyEnv} is not set.` };
|
|
208
|
+
}
|
|
209
|
+
const result = await discoverModels({ baseUrl: profile.baseUrl, apiKey: key });
|
|
210
|
+
if (!result.ok)
|
|
211
|
+
return { ok: false, message: result.message };
|
|
212
|
+
if (result.models.length === 0) {
|
|
213
|
+
return { ok: false, message: 'The endpoint returned an empty model list.' };
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
await persistProfileChange(withProfileModels(baseConfigRef.current, name, result.models));
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
return { ok: false, message: `Could not save the model list: ${error.message}` };
|
|
220
|
+
}
|
|
221
|
+
return { ok: true };
|
|
222
|
+
}, [persistProfileChange]);
|
|
223
|
+
const finishWizardPrompt = useCallback((value) => {
|
|
224
|
+
const resolve = wizardResolveRef.current;
|
|
225
|
+
wizardResolveRef.current = null;
|
|
226
|
+
setWizardPrompt(null);
|
|
227
|
+
if (resolve)
|
|
228
|
+
resolve(value);
|
|
229
|
+
}, []);
|
|
230
|
+
const wizardText = useCallback((options) => {
|
|
231
|
+
return new Promise((resolve) => {
|
|
232
|
+
const id = ++wizardPromptIdRef.current;
|
|
233
|
+
wizardResolveRef.current = resolve;
|
|
234
|
+
setWizardPrompt({ id, ...options });
|
|
235
|
+
});
|
|
236
|
+
}, []);
|
|
237
|
+
const wizardUi = React.useMemo(() => ({
|
|
238
|
+
note: (tone, text) => addNotice(tone, text),
|
|
239
|
+
text: wizardText,
|
|
240
|
+
confirm: async (label, defaultValue) => {
|
|
241
|
+
for (;;) {
|
|
242
|
+
const answer = await wizardText({
|
|
243
|
+
label: `${label} [${defaultValue ? 'Y/n' : 'y/N'}]`,
|
|
244
|
+
allowEmpty: true,
|
|
245
|
+
});
|
|
246
|
+
if (answer === null)
|
|
247
|
+
return null;
|
|
248
|
+
const value = answer.trim().toLowerCase();
|
|
249
|
+
if (!value)
|
|
250
|
+
return defaultValue;
|
|
251
|
+
if (value === 'y' || value === 'yes')
|
|
252
|
+
return true;
|
|
253
|
+
if (value === 'n' || value === 'no')
|
|
254
|
+
return false;
|
|
255
|
+
addNotice('error', 'Please answer y or n.');
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
}), [addNotice, wizardText]);
|
|
259
|
+
const cancelWizard = useCallback(() => {
|
|
260
|
+
if (!wizardActiveRef.current)
|
|
261
|
+
return;
|
|
262
|
+
wizardCancelRequestedRef.current = true;
|
|
263
|
+
wizardAbortRef.current?.abort();
|
|
264
|
+
finishWizardPrompt(null);
|
|
265
|
+
}, [finishWizardPrompt]);
|
|
266
|
+
const runModelFlow = useCallback(async (flow) => {
|
|
267
|
+
if (wizardActiveRef.current || busyRef.current || transitioningRef.current) {
|
|
268
|
+
addNotice('muted', 'Finish the current activity before changing models.');
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
wizardActiveRef.current = true;
|
|
272
|
+
wizardCancelRequestedRef.current = false;
|
|
273
|
+
const controller = new AbortController();
|
|
274
|
+
wizardAbortRef.current = controller;
|
|
275
|
+
setWizardActive(true);
|
|
276
|
+
transitioningRef.current = true;
|
|
277
|
+
const ctx = {
|
|
278
|
+
ui: wizardUi,
|
|
279
|
+
config: baseConfigRef.current,
|
|
280
|
+
signal: controller.signal,
|
|
281
|
+
cancelled: () => wizardCancelRequestedRef.current,
|
|
282
|
+
save: persistConfig,
|
|
283
|
+
};
|
|
284
|
+
try {
|
|
285
|
+
await flow(ctx);
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
addNotice('error', error instanceof Error ? error.message : String(error));
|
|
289
|
+
}
|
|
290
|
+
finally {
|
|
291
|
+
finishWizardPrompt(null);
|
|
292
|
+
wizardAbortRef.current = null;
|
|
293
|
+
wizardActiveRef.current = false;
|
|
294
|
+
wizardCancelRequestedRef.current = false;
|
|
295
|
+
transitioningRef.current = false;
|
|
296
|
+
setWizardActive(false);
|
|
297
|
+
}
|
|
298
|
+
}, [addNotice, finishWizardPrompt, persistConfig, wizardUi]);
|
|
299
|
+
const persistSession = useCallback(() => {
|
|
300
|
+
const messages = dropIncompleteToolCalls(messagesRef.current.filter((message) => message.role !== 'system'));
|
|
301
|
+
if (messages.length === 0)
|
|
302
|
+
return Promise.resolve();
|
|
303
|
+
const now = new Date().toISOString();
|
|
304
|
+
if (!sessionRef.current) {
|
|
305
|
+
sessionRef.current = {
|
|
306
|
+
id: newSessionId(),
|
|
307
|
+
createdAt: now,
|
|
308
|
+
title: titleFromMessages(messages),
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
const session = sessionRef.current;
|
|
312
|
+
const snapshot = structuredClone(messages);
|
|
313
|
+
const write = saveChainRef.current
|
|
314
|
+
.then(() => saveSession({
|
|
315
|
+
id: session.id,
|
|
316
|
+
cwd,
|
|
317
|
+
profile: profileName,
|
|
318
|
+
model: configRef.current.profiles[profileName]?.model ?? 'unknown',
|
|
319
|
+
title: session.title,
|
|
320
|
+
createdAt: session.createdAt,
|
|
321
|
+
messages: snapshot,
|
|
322
|
+
}))
|
|
323
|
+
.then(() => undefined)
|
|
324
|
+
.catch((error) => {
|
|
325
|
+
if (saveErrorShownRef.current)
|
|
326
|
+
return;
|
|
327
|
+
saveErrorShownRef.current = true;
|
|
328
|
+
addNotice('error', `Could not save session: ${error instanceof Error ? error.message : String(error)}`);
|
|
329
|
+
});
|
|
330
|
+
saveChainRef.current = write;
|
|
331
|
+
return write;
|
|
332
|
+
}, [addNotice, cwd, profileName]);
|
|
333
|
+
const quit = useCallback(() => {
|
|
334
|
+
if (quittingRef.current)
|
|
335
|
+
return;
|
|
336
|
+
quittingRef.current = true;
|
|
337
|
+
void (async () => {
|
|
338
|
+
await persistSession();
|
|
339
|
+
await saveChainRef.current;
|
|
340
|
+
exit();
|
|
341
|
+
})();
|
|
342
|
+
}, [exit, persistSession]);
|
|
343
|
+
const flushText = useCallback(() => {
|
|
344
|
+
if (flushTimerRef.current) {
|
|
345
|
+
clearTimeout(flushTimerRef.current);
|
|
346
|
+
flushTimerRef.current = null;
|
|
347
|
+
}
|
|
348
|
+
const chunk = textBufferRef.current;
|
|
349
|
+
textBufferRef.current = '';
|
|
350
|
+
if (!chunk)
|
|
351
|
+
return;
|
|
352
|
+
setItems((current) => {
|
|
353
|
+
const last = current[current.length - 1];
|
|
354
|
+
if (last?.kind === 'assistant' && last.draft) {
|
|
355
|
+
return [...current.slice(0, -1), { ...last, text: last.text + chunk }];
|
|
356
|
+
}
|
|
357
|
+
return [...current, { kind: 'assistant', id: nextItemIdRef.current++, text: chunk, draft: true }];
|
|
358
|
+
});
|
|
359
|
+
}, []);
|
|
360
|
+
const queueText = useCallback((text) => {
|
|
361
|
+
textBufferRef.current += text;
|
|
362
|
+
if (!flushTimerRef.current) {
|
|
363
|
+
flushTimerRef.current = setTimeout(() => {
|
|
364
|
+
flushTimerRef.current = null;
|
|
365
|
+
flushText();
|
|
366
|
+
}, 30);
|
|
367
|
+
}
|
|
368
|
+
}, [flushText]);
|
|
369
|
+
const finalizeAssistant = useCallback((content) => {
|
|
370
|
+
setItems((current) => {
|
|
371
|
+
const last = current[current.length - 1];
|
|
372
|
+
if (last?.kind === 'assistant' && last.draft) {
|
|
373
|
+
return [...current.slice(0, -1), { ...last, text: content, draft: false }];
|
|
374
|
+
}
|
|
375
|
+
return [...current, { kind: 'assistant', id: nextItemIdRef.current++, text: content }];
|
|
376
|
+
});
|
|
377
|
+
}, []);
|
|
378
|
+
const resolveApproval = useCallback((decision) => {
|
|
379
|
+
const request = pendingApprovalRef.current;
|
|
380
|
+
const resolver = pendingResolverRef.current;
|
|
381
|
+
pendingApprovalRef.current = null;
|
|
382
|
+
pendingResolverRef.current = null;
|
|
383
|
+
setPendingApproval(null);
|
|
384
|
+
if (!request || !resolver)
|
|
385
|
+
return;
|
|
386
|
+
if (decision === 'allow-session') {
|
|
387
|
+
approvalPolicy.markSession(request.tool);
|
|
388
|
+
setAutoAllowed(approvalPolicy.list());
|
|
389
|
+
addNotice('info', `${request.tool} will run without asking. Use /allow to list, /allow clear to revoke.`);
|
|
390
|
+
}
|
|
391
|
+
resolver(decision);
|
|
392
|
+
}, [addNotice, approvalPolicy]);
|
|
393
|
+
const approve = useCallback((request) => {
|
|
394
|
+
if (approvalPolicy.isAuto(request.tool))
|
|
395
|
+
return Promise.resolve('allow');
|
|
396
|
+
if (abortRef.current?.signal.aborted)
|
|
397
|
+
return Promise.resolve('deny');
|
|
398
|
+
return new Promise((resolve) => {
|
|
399
|
+
pendingApprovalRef.current = request;
|
|
400
|
+
pendingResolverRef.current = resolve;
|
|
401
|
+
setPendingApproval(request);
|
|
402
|
+
});
|
|
403
|
+
}, [approvalPolicy]);
|
|
404
|
+
const resetAutoAllowed = useCallback(() => {
|
|
405
|
+
approvalPolicy.clear();
|
|
406
|
+
setAutoAllowed([]);
|
|
407
|
+
}, [approvalPolicy]);
|
|
408
|
+
const sendTurn = useCallback(async (rawInput) => {
|
|
409
|
+
if (busyRef.current || transitioningRef.current)
|
|
410
|
+
return;
|
|
411
|
+
const text = rawInput.trim();
|
|
412
|
+
if (!text)
|
|
413
|
+
return;
|
|
414
|
+
busyRef.current = true;
|
|
415
|
+
cancelRequestedRef.current = false;
|
|
416
|
+
setBusy(true);
|
|
417
|
+
setCancelling(false);
|
|
418
|
+
setActiveTool(null);
|
|
419
|
+
setItems((current) => [
|
|
420
|
+
...current,
|
|
421
|
+
{ kind: 'user', id: nextItemIdRef.current++, text },
|
|
422
|
+
]);
|
|
423
|
+
messagesRef.current.push({ role: 'user', content: text });
|
|
424
|
+
recomputeContext();
|
|
425
|
+
void persistSession();
|
|
426
|
+
const controller = new AbortController();
|
|
427
|
+
abortRef.current = controller;
|
|
428
|
+
try {
|
|
429
|
+
const systemPrompt = await buildSystemPrompt(cwd);
|
|
430
|
+
messagesRef.current = [
|
|
431
|
+
{ role: 'system', content: systemPrompt },
|
|
432
|
+
...messagesRef.current.filter((message) => message.role !== 'system'),
|
|
433
|
+
];
|
|
434
|
+
recomputeContext();
|
|
435
|
+
const resolved = resolveProfile(configRef.current, profileName);
|
|
436
|
+
const provider = createProvider(resolved.profile, resolved.apiKey);
|
|
437
|
+
const ctx = {
|
|
438
|
+
cwd,
|
|
439
|
+
signal: controller.signal,
|
|
440
|
+
approve,
|
|
441
|
+
};
|
|
442
|
+
for await (const event of runAgentTurn({
|
|
443
|
+
provider,
|
|
444
|
+
messages: messagesRef.current,
|
|
445
|
+
ctx,
|
|
446
|
+
compactContext: autoCompact,
|
|
447
|
+
})) {
|
|
448
|
+
switch (event.type) {
|
|
449
|
+
case 'text':
|
|
450
|
+
queueText(event.text);
|
|
451
|
+
break;
|
|
452
|
+
case 'assistant':
|
|
453
|
+
flushText();
|
|
454
|
+
finalizeAssistant(event.content);
|
|
455
|
+
recomputeContext();
|
|
456
|
+
break;
|
|
457
|
+
case 'tool-start':
|
|
458
|
+
flushText();
|
|
459
|
+
setActiveTool(event.toolCall.function.name);
|
|
460
|
+
setItems((current) => [
|
|
461
|
+
...current,
|
|
462
|
+
{
|
|
463
|
+
kind: 'tool',
|
|
464
|
+
id: nextItemIdRef.current++,
|
|
465
|
+
callId: event.toolCall.id,
|
|
466
|
+
name: event.toolCall.function.name,
|
|
467
|
+
argsSummary: summarizeToolArgs(event.toolCall.function.name, event.toolCall.function.arguments),
|
|
468
|
+
status: 'running',
|
|
469
|
+
},
|
|
470
|
+
]);
|
|
471
|
+
break;
|
|
472
|
+
case 'tool-end':
|
|
473
|
+
setActiveTool(null);
|
|
474
|
+
setItems((current) => {
|
|
475
|
+
const index = current.findIndex((item) => item.kind === 'tool' && item.callId === event.toolCall.id && item.status === 'running');
|
|
476
|
+
if (index === -1)
|
|
477
|
+
return current;
|
|
478
|
+
const next = [...current];
|
|
479
|
+
const item = next[index];
|
|
480
|
+
if (item?.kind !== 'tool')
|
|
481
|
+
return current;
|
|
482
|
+
next[index] = {
|
|
483
|
+
...item,
|
|
484
|
+
status: event.result.status,
|
|
485
|
+
resultSummary: event.result.summary,
|
|
486
|
+
resultFull: event.result.content.slice(0, MAX_EXPANDED_TOOL_CHARS),
|
|
487
|
+
durationMs: event.durationMs,
|
|
488
|
+
};
|
|
489
|
+
return next;
|
|
490
|
+
});
|
|
491
|
+
recomputeContext();
|
|
492
|
+
break;
|
|
493
|
+
case 'usage':
|
|
494
|
+
usageRef.current = {
|
|
495
|
+
tokens: event.usage.totalTokens,
|
|
496
|
+
// The assistant message from this response is appended after the
|
|
497
|
+
// stream ends and is already counted in totalTokens.
|
|
498
|
+
messageCount: messagesRef.current.length + 1,
|
|
499
|
+
};
|
|
500
|
+
recomputeContext();
|
|
501
|
+
break;
|
|
502
|
+
case 'notice':
|
|
503
|
+
flushText();
|
|
504
|
+
addNotice(event.level, event.message);
|
|
505
|
+
break;
|
|
506
|
+
case 'done':
|
|
507
|
+
flushText();
|
|
508
|
+
recomputeContext();
|
|
509
|
+
if (event.reason === 'aborted') {
|
|
510
|
+
addNotice('info', 'Turn cancelled.');
|
|
511
|
+
}
|
|
512
|
+
break;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
catch (error) {
|
|
517
|
+
flushText();
|
|
518
|
+
addNotice('error', error instanceof Error ? error.message : String(error));
|
|
519
|
+
}
|
|
520
|
+
finally {
|
|
521
|
+
flushText();
|
|
522
|
+
abortRef.current = null;
|
|
523
|
+
busyRef.current = false;
|
|
524
|
+
setBusy(false);
|
|
525
|
+
setActiveTool(null);
|
|
526
|
+
setCancelling(false);
|
|
527
|
+
if (pendingApprovalRef.current)
|
|
528
|
+
resolveApproval('deny');
|
|
529
|
+
recomputeContext();
|
|
530
|
+
void persistSession();
|
|
531
|
+
}
|
|
532
|
+
}, [
|
|
533
|
+
addNotice,
|
|
534
|
+
approve,
|
|
535
|
+
autoCompact,
|
|
536
|
+
cwd,
|
|
537
|
+
finalizeAssistant,
|
|
538
|
+
flushText,
|
|
539
|
+
persistSession,
|
|
540
|
+
profileName,
|
|
541
|
+
queueText,
|
|
542
|
+
recomputeContext,
|
|
543
|
+
resolveApproval,
|
|
544
|
+
]);
|
|
545
|
+
const runProfileTest = useCallback(async (requested) => {
|
|
546
|
+
if (busyRef.current || transitioningRef.current || wizardActiveRef.current) {
|
|
547
|
+
addNotice('muted', 'Finish the current activity first.');
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
transitioningRef.current = true;
|
|
551
|
+
try {
|
|
552
|
+
const name = requested ?? profileName;
|
|
553
|
+
const profile = configRef.current.profiles[name];
|
|
554
|
+
if (!profile) {
|
|
555
|
+
addNotice('error', `Unknown profile "${name}". Available profiles: ${Object.keys(configRef.current.profiles).join(', ')}.`);
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
const key = profile.apiKeyEnv ? process.env[profile.apiKeyEnv] : undefined;
|
|
559
|
+
if (profile.apiKeyEnv && !key) {
|
|
560
|
+
addNotice('error', `API key is missing: $${profile.apiKeyEnv} is not set (profile "${name}"). ` +
|
|
561
|
+
`Store it with /model edit ${name}.`);
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
addNotice('muted', `Testing ${profile.baseUrl} with model "${profile.model}"…`);
|
|
565
|
+
const result = await testConnection(profile, key);
|
|
566
|
+
addNotice(result.ok ? 'info' : 'error', result.message);
|
|
567
|
+
}
|
|
568
|
+
finally {
|
|
569
|
+
transitioningRef.current = false;
|
|
570
|
+
}
|
|
571
|
+
}, [addNotice, profileName]);
|
|
572
|
+
const listRemoteModels = useCallback(async () => {
|
|
573
|
+
if (busyRef.current || transitioningRef.current || wizardActiveRef.current) {
|
|
574
|
+
addNotice('muted', 'Finish the current activity first.');
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
transitioningRef.current = true;
|
|
578
|
+
try {
|
|
579
|
+
const profile = configRef.current.profiles[profileName];
|
|
580
|
+
if (!profile) {
|
|
581
|
+
addNotice('error', `Unknown active profile "${profileName}".`);
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
const key = profile.apiKeyEnv ? process.env[profile.apiKeyEnv] : undefined;
|
|
585
|
+
if (profile.apiKeyEnv && !key) {
|
|
586
|
+
addNotice('error', `API key is missing: $${profile.apiKeyEnv} is not set (profile "${profileName}").`);
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
addNotice('muted', `Fetching models from ${profile.baseUrl}…`);
|
|
590
|
+
const result = await discoverModels({ baseUrl: profile.baseUrl, apiKey: key });
|
|
591
|
+
if (!result.ok) {
|
|
592
|
+
addNotice('error', result.message);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
if (result.models.length === 0) {
|
|
596
|
+
addNotice('muted', 'The endpoint returned an empty model list. Use /model add to enter a model id manually.');
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
const shown = result.models.slice(0, 100);
|
|
600
|
+
const lines = [
|
|
601
|
+
`Models offered by ${profile.baseUrl} (${result.models.length}):`,
|
|
602
|
+
...shown.map((id) => ` ${id}`),
|
|
603
|
+
];
|
|
604
|
+
if (result.models.length > shown.length) {
|
|
605
|
+
lines.push(` … and ${result.models.length - shown.length} more`);
|
|
606
|
+
}
|
|
607
|
+
addNotice('info', lines.join('\n'));
|
|
608
|
+
}
|
|
609
|
+
finally {
|
|
610
|
+
transitioningRef.current = false;
|
|
611
|
+
}
|
|
612
|
+
}, [addNotice, profileName]);
|
|
613
|
+
const expandLastToolOutput = useCallback(() => {
|
|
614
|
+
for (let index = items.length - 1; index >= 0; index--) {
|
|
615
|
+
const item = items[index];
|
|
616
|
+
if (item?.kind !== 'tool' || !item.resultFull)
|
|
617
|
+
continue;
|
|
618
|
+
const expanding = expandedToolId !== item.id;
|
|
619
|
+
setExpandedToolId(expanding ? item.id : null);
|
|
620
|
+
if (expanding) {
|
|
621
|
+
addNotice('muted', `Showing the full ${item.name} output above; Ctrl+O collapses it.`);
|
|
622
|
+
}
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
addNotice('muted', 'No finished tool output to expand yet.');
|
|
626
|
+
}, [addNotice, expandedToolId, items]);
|
|
627
|
+
const handleCommand = useCallback(async (input) => {
|
|
628
|
+
if (busyRef.current || transitioningRef.current)
|
|
629
|
+
return;
|
|
630
|
+
const [command, ...rest] = input.trim().split(/\s+/);
|
|
631
|
+
const argument = rest[0];
|
|
632
|
+
switch (command) {
|
|
633
|
+
case '/help': {
|
|
634
|
+
addNotice('info', [
|
|
635
|
+
'Commands (type / to open the menu, ↑↓ to choose, Enter to run):',
|
|
636
|
+
...slashHelpLines(),
|
|
637
|
+
'',
|
|
638
|
+
' Model subcommands: /model <name> · /model add · /model edit [name] ·',
|
|
639
|
+
' /model remove [name] · /model test [name] · /model list --remote',
|
|
640
|
+
'',
|
|
641
|
+
'Keys: Enter sends · / opens commands · PgUp/PgDn scrolls · Ctrl+O expands tool output ·',
|
|
642
|
+
' Tab completes a command · Esc cancels a wizard step · /mouse toggles wheel scroll',
|
|
643
|
+
' Ctrl+C cancels a turn, again exits',
|
|
644
|
+
yolo
|
|
645
|
+
? ' YOLO mode is on: every write and command runs without approval.'
|
|
646
|
+
: ' [a] on an approval prompt allows that tool for the rest of the session.',
|
|
647
|
+
].join('\n'));
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
case '/model': {
|
|
651
|
+
const listProfiles = () => {
|
|
652
|
+
addNotice('info', [
|
|
653
|
+
...formatProfileList(configRef.current),
|
|
654
|
+
'',
|
|
655
|
+
'Use /model <name> to switch, /model add to create one, or /model list --remote to see endpoint models.',
|
|
656
|
+
].join('\n'));
|
|
657
|
+
};
|
|
658
|
+
if (!argument) {
|
|
659
|
+
setPickerOpen(true);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
if (argument === 'list') {
|
|
663
|
+
if (rest[1] === '--remote') {
|
|
664
|
+
void listRemoteModels();
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
if (rest[1]) {
|
|
668
|
+
addNotice('error', 'Usage: /model list [--remote]');
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
listProfiles();
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
if (argument === 'add') {
|
|
675
|
+
void runModelFlow((ctx) => runAddFlow(ctx));
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (argument === 'edit') {
|
|
679
|
+
void runModelFlow((ctx) => runEditFlow(ctx, rest[1]));
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (argument === 'remove') {
|
|
683
|
+
void runModelFlow((ctx) => runRemoveFlow(ctx, rest[1]));
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
if (argument === 'test') {
|
|
687
|
+
void runProfileTest(rest[1]);
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
const profile = configRef.current.profiles[argument];
|
|
691
|
+
if (!profile) {
|
|
692
|
+
addNotice('error', `Unknown profile "${argument}". Available profiles: ${Object.keys(configRef.current.profiles).join(', ')}.`);
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
if (profile.type !== 'openai') {
|
|
696
|
+
addNotice('error', `Profile "${argument}" uses unsupported provider type "${profile.type}". Phase 1 supports "openai".`);
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
setProfileName(argument);
|
|
700
|
+
addNotice('info', `Switched to profile "${argument}" (${profile.model}).`);
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
case '/context': {
|
|
704
|
+
recomputeContext();
|
|
705
|
+
const profile = configRef.current.profiles[profileName];
|
|
706
|
+
const window = contextWindowFor(profile);
|
|
707
|
+
const used = contextTokensRef.current;
|
|
708
|
+
const count = (role) => estimateMessagesTokens(messagesRef.current.filter((message) => message.role === role));
|
|
709
|
+
const usage = usageRef.current;
|
|
710
|
+
addNotice('info', [
|
|
711
|
+
`Context: ~${formatTokens(used)} / ${formatTokens(window)} tokens (${formatPercent(used, window)} used)` +
|
|
712
|
+
(profile?.contextWindow
|
|
713
|
+
? '.'
|
|
714
|
+
: ' — window inferred from the model id; set "contextWindow" in the profile to override.'),
|
|
715
|
+
` system ~${formatTokens(count('system'))} · user ~${formatTokens(count('user'))} · ` +
|
|
716
|
+
`assistant ~${formatTokens(count('assistant'))} · tool ~${formatTokens(count('tool'))}`,
|
|
717
|
+
usage
|
|
718
|
+
? `Last API usage: ${usage.tokens.toLocaleString()} tokens for the last request and response.`
|
|
719
|
+
: 'The endpoint has not reported usage; counts are estimated at roughly 4 characters per token.',
|
|
720
|
+
`Auto-compaction runs at ${Math.round(COMPACT_THRESHOLD * 100)}% and keeps the last ${COMPACT_KEEP_USER_TURNS} user turns verbatim. /compact runs it now.`,
|
|
721
|
+
].join('\n'));
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
case '/compact': {
|
|
725
|
+
if (messagesRef.current.length === 0) {
|
|
726
|
+
addNotice('muted', 'There is no conversation to compact yet.');
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const controller = new AbortController();
|
|
730
|
+
busyRef.current = true;
|
|
731
|
+
abortRef.current = controller;
|
|
732
|
+
setBusy(true);
|
|
733
|
+
addNotice('muted', 'Compacting earlier conversation…');
|
|
734
|
+
try {
|
|
735
|
+
const resolved = resolveProfile(configRef.current, profileName);
|
|
736
|
+
const provider = createProvider(resolved.profile, resolved.apiKey);
|
|
737
|
+
const result = await compactMessages({
|
|
738
|
+
messages: messagesRef.current,
|
|
739
|
+
provider,
|
|
740
|
+
signal: controller.signal,
|
|
741
|
+
keepUserTurns: COMPACT_KEEP_USER_TURNS,
|
|
742
|
+
});
|
|
743
|
+
if (!result) {
|
|
744
|
+
addNotice('muted', `Nothing to compact yet; Kiro keeps the last ${COMPACT_KEEP_USER_TURNS} user turns verbatim and needs older turns first.`);
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
messagesRef.current.splice(0, messagesRef.current.length, ...result.messages);
|
|
748
|
+
usageRef.current = null;
|
|
749
|
+
updateContextTokens(result.afterTokens);
|
|
750
|
+
await persistSession();
|
|
751
|
+
addNotice('info', `Compacted ${result.summarizedMessages} earlier messages ` +
|
|
752
|
+
`(~${formatTokens(result.beforeTokens)} → ~${formatTokens(result.afterTokens)} tokens).`);
|
|
753
|
+
}
|
|
754
|
+
catch (error) {
|
|
755
|
+
if (controller.signal.aborted) {
|
|
756
|
+
addNotice('info', 'Compaction cancelled.');
|
|
757
|
+
}
|
|
758
|
+
else {
|
|
759
|
+
addNotice('error', `Could not compact context: ${error instanceof Error ? error.message : String(error)}`);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
finally {
|
|
763
|
+
abortRef.current = null;
|
|
764
|
+
busyRef.current = false;
|
|
765
|
+
setBusy(false);
|
|
766
|
+
}
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
case '/sessions':
|
|
770
|
+
case '/resume': {
|
|
771
|
+
transitioningRef.current = true;
|
|
772
|
+
try {
|
|
773
|
+
if (command === '/sessions' || !argument) {
|
|
774
|
+
const { sessions, skipped } = await listSessions(cwd, 10);
|
|
775
|
+
listedSessionsRef.current = sessions;
|
|
776
|
+
if (sessions.length === 0) {
|
|
777
|
+
addNotice('info', `No saved sessions for this directory yet. Sessions are stored in ${projectSessionsDir(cwd)}.`);
|
|
778
|
+
}
|
|
779
|
+
else {
|
|
780
|
+
const lines = sessions.map((session, index) => {
|
|
781
|
+
const marker = session.id === sessionRef.current?.id ? '*' : ' ';
|
|
782
|
+
const messages = `${session.messageCount} msg${session.messageCount === 1 ? '' : 's'}`;
|
|
783
|
+
return `${marker} ${index + 1}. ${session.id} ${formatSessionTime(session.updatedAt)} ${messages} ${session.title}`;
|
|
784
|
+
});
|
|
785
|
+
addNotice('info', [
|
|
786
|
+
'Sessions (most recent first):',
|
|
787
|
+
...lines,
|
|
788
|
+
'',
|
|
789
|
+
'Use /resume <number|id> to load one.',
|
|
790
|
+
].join('\n'));
|
|
791
|
+
}
|
|
792
|
+
if (skipped > 0) {
|
|
793
|
+
addNotice('muted', `Skipped ${skipped} unreadable session file${skipped === 1 ? '' : 's'}.`);
|
|
794
|
+
}
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
let sessions = listedSessionsRef.current;
|
|
798
|
+
if (!sessions) {
|
|
799
|
+
sessions = (await listSessions(cwd, 10)).sessions;
|
|
800
|
+
listedSessionsRef.current = sessions;
|
|
801
|
+
}
|
|
802
|
+
let target;
|
|
803
|
+
const numeric = /^\d+$/.test(argument);
|
|
804
|
+
if (numeric) {
|
|
805
|
+
target = sessions[Number(argument) - 1];
|
|
806
|
+
}
|
|
807
|
+
else {
|
|
808
|
+
target = sessions.find((session) => session.id === argument);
|
|
809
|
+
if (!target) {
|
|
810
|
+
const matches = sessions.filter((session) => session.id.startsWith(argument));
|
|
811
|
+
if (matches.length > 1) {
|
|
812
|
+
addNotice('error', `Session id "${argument}" is ambiguous; use more characters.`);
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
target = matches[0];
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
if (!target && (numeric || !isSessionId(argument))) {
|
|
819
|
+
addNotice('error', `No saved session matches "${argument}". Use /sessions to list them.`);
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
const targetId = target?.id ?? argument;
|
|
823
|
+
if (targetId === sessionRef.current?.id) {
|
|
824
|
+
addNotice('info', `Session ${targetId} is already active.`);
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
await persistSession();
|
|
828
|
+
await saveChainRef.current;
|
|
829
|
+
const record = await loadSession(cwd, targetId);
|
|
830
|
+
messagesRef.current = record.messages.filter((message) => message.role !== 'system');
|
|
831
|
+
usageRef.current = null;
|
|
832
|
+
recomputeContext();
|
|
833
|
+
sessionRef.current = {
|
|
834
|
+
id: record.id,
|
|
835
|
+
createdAt: record.createdAt,
|
|
836
|
+
title: record.title,
|
|
837
|
+
};
|
|
838
|
+
const view = buildResumedView(messagesRef.current, {
|
|
839
|
+
cwd,
|
|
840
|
+
version,
|
|
841
|
+
sessionId: record.id,
|
|
842
|
+
});
|
|
843
|
+
setItems(view.items);
|
|
844
|
+
nextItemIdRef.current = view.nextId;
|
|
845
|
+
setResetSignal((current) => current + 1);
|
|
846
|
+
setExpandedToolId(null);
|
|
847
|
+
resetAutoAllowed();
|
|
848
|
+
if (record.profile && record.profile !== profileName) {
|
|
849
|
+
addNotice('muted', `Session was saved with profile "${record.profile}"; staying on "${profileName}". Use /model ${record.profile} to switch.`);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
catch (error) {
|
|
853
|
+
addNotice('error', error instanceof Error ? error.message : String(error));
|
|
854
|
+
}
|
|
855
|
+
finally {
|
|
856
|
+
transitioningRef.current = false;
|
|
857
|
+
}
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
case '/clear': {
|
|
861
|
+
transitioningRef.current = true;
|
|
862
|
+
try {
|
|
863
|
+
await persistSession();
|
|
864
|
+
await saveChainRef.current;
|
|
865
|
+
messagesRef.current = [];
|
|
866
|
+
usageRef.current = null;
|
|
867
|
+
updateContextTokens(0);
|
|
868
|
+
sessionRef.current = null;
|
|
869
|
+
listedSessionsRef.current = null;
|
|
870
|
+
resetAutoAllowed();
|
|
871
|
+
setItems([
|
|
872
|
+
{ kind: 'banner', id: nextItemIdRef.current++, cwd, version },
|
|
873
|
+
{
|
|
874
|
+
kind: 'notice',
|
|
875
|
+
id: nextItemIdRef.current++,
|
|
876
|
+
level: 'info',
|
|
877
|
+
text: 'Conversation cleared. Your next message starts a new session.',
|
|
878
|
+
},
|
|
879
|
+
]);
|
|
880
|
+
setResetSignal((current) => current + 1);
|
|
881
|
+
setExpandedToolId(null);
|
|
882
|
+
}
|
|
883
|
+
finally {
|
|
884
|
+
transitioningRef.current = false;
|
|
885
|
+
}
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
case '/export': {
|
|
889
|
+
const transcript = messagesRef.current.filter((message) => message.role !== 'system');
|
|
890
|
+
if (transcript.length === 0) {
|
|
891
|
+
addNotice('muted', 'There is no conversation to export yet.');
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
const target = argument
|
|
895
|
+
? path.resolve(cwd, argument)
|
|
896
|
+
: defaultExportPath(sessionRef.current?.id);
|
|
897
|
+
try {
|
|
898
|
+
await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
899
|
+
await writeFile(target, renderTranscriptMarkdown(transcript, {
|
|
900
|
+
cwd,
|
|
901
|
+
sessionId: sessionRef.current?.id,
|
|
902
|
+
profile: profileName,
|
|
903
|
+
model: configRef.current.profiles[profileName]?.model,
|
|
904
|
+
version,
|
|
905
|
+
}), { encoding: 'utf8', mode: 0o600 });
|
|
906
|
+
addNotice('info', `Transcript written to ${target} (${transcript.length} messages, full tool output included).`);
|
|
907
|
+
}
|
|
908
|
+
catch (error) {
|
|
909
|
+
addNotice('error', `Could not export the transcript: ${error instanceof Error ? error.message : String(error)}`);
|
|
910
|
+
}
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
case '/mouse': {
|
|
914
|
+
if (argument) {
|
|
915
|
+
addNotice('error', 'Usage: /mouse (toggles mouse reporting)');
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
const next = !mouseOn;
|
|
919
|
+
setMouseOn(next);
|
|
920
|
+
addNotice('info', next
|
|
921
|
+
? 'Mouse reporting on: the wheel scrolls the transcript, but text selection needs Shift+drag.'
|
|
922
|
+
: 'Mouse reporting off: click-drag selects text normally; use PgUp/PgDn to scroll.');
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
case '/allow': {
|
|
926
|
+
if (argument === 'clear') {
|
|
927
|
+
resetAutoAllowed();
|
|
928
|
+
addNotice('info', yolo
|
|
929
|
+
? 'Session allowances cleared. YOLO mode still runs everything without asking; restart without --yolo to get prompts back.'
|
|
930
|
+
: 'Session allowances cleared. Every tool will ask for approval again.');
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
if (argument) {
|
|
934
|
+
addNotice('error', 'Usage: /allow or /allow clear');
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
addNotice('info', yolo
|
|
938
|
+
? `YOLO mode is on: nothing asks for approval.${autoAllowed.length > 0 ? ` Also allowed for this session: ${autoAllowed.join(', ')}.` : ''}\nUse /allow clear to drop the session allowances.`
|
|
939
|
+
: autoAllowed.length === 0
|
|
940
|
+
? 'No tools are auto-allowed. Choose [a] on an approval prompt to allow a tool for the rest of the session.'
|
|
941
|
+
: `Auto-allowed this session: ${autoAllowed.join(', ')}\nUse /allow clear to ask again.`);
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
case '/exit':
|
|
945
|
+
quit();
|
|
946
|
+
return;
|
|
947
|
+
default:
|
|
948
|
+
addNotice('error', `Unknown command "${command}". Type /help for commands.`);
|
|
949
|
+
}
|
|
950
|
+
}, [
|
|
951
|
+
addNotice,
|
|
952
|
+
autoAllowed,
|
|
953
|
+
cwd,
|
|
954
|
+
listRemoteModels,
|
|
955
|
+
mouseOn,
|
|
956
|
+
persistSession,
|
|
957
|
+
profileName,
|
|
958
|
+
quit,
|
|
959
|
+
recomputeContext,
|
|
960
|
+
resetAutoAllowed,
|
|
961
|
+
runModelFlow,
|
|
962
|
+
runProfileTest,
|
|
963
|
+
updateContextTokens,
|
|
964
|
+
version,
|
|
965
|
+
yolo,
|
|
966
|
+
]);
|
|
967
|
+
const handleSubmit = useCallback((value) => {
|
|
968
|
+
if (wizardResolveRef.current || wizardPromptRef.current) {
|
|
969
|
+
finishWizardPrompt(value);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
if (wizardActiveRef.current || transitioningRef.current)
|
|
973
|
+
return;
|
|
974
|
+
const trimmed = value.trim();
|
|
975
|
+
if (!trimmed)
|
|
976
|
+
return;
|
|
977
|
+
if (trimmed.startsWith('/')) {
|
|
978
|
+
void handleCommand(trimmed);
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
void sendTurn(trimmed);
|
|
982
|
+
}, [finishWizardPrompt, handleCommand, sendTurn]);
|
|
983
|
+
useEffect(() => {
|
|
984
|
+
if (configCreated) {
|
|
985
|
+
addNotice('info', `Created config template at ${configPath}. Set your endpoint, model, and API key.`);
|
|
986
|
+
}
|
|
987
|
+
const active = config.profiles[config.activeProfile];
|
|
988
|
+
if (active) {
|
|
989
|
+
if (active.type !== 'openai') {
|
|
990
|
+
addNotice('error', `Profile "${config.activeProfile}" uses unsupported provider type "${active.type}".`);
|
|
991
|
+
}
|
|
992
|
+
else if (active.apiKeyEnv && !process.env[active.apiKeyEnv]) {
|
|
993
|
+
addNotice('error', `API key is not set: export ${active.apiKeyEnv}=... (profile "${config.activeProfile}").`);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
if (initialSession?.profile && initialSession.profile !== config.activeProfile) {
|
|
997
|
+
addNotice('muted', `Session ${initialSession.id} was saved with profile "${initialSession.profile}"; using "${config.activeProfile}". Use /model ${initialSession.profile} to switch.`);
|
|
998
|
+
}
|
|
999
|
+
for (const notice of startupNotices ?? [])
|
|
1000
|
+
addNotice(notice.level, notice.text);
|
|
1001
|
+
// Startup notices only.
|
|
1002
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
1003
|
+
}, []);
|
|
1004
|
+
useEffect(() => {
|
|
1005
|
+
if (!stdout.isTTY)
|
|
1006
|
+
return;
|
|
1007
|
+
stdout.write(mouseOn ? MOUSE_ON : MOUSE_OFF);
|
|
1008
|
+
return () => {
|
|
1009
|
+
if (stdout.isTTY)
|
|
1010
|
+
stdout.write(MOUSE_OFF);
|
|
1011
|
+
};
|
|
1012
|
+
}, [stdout, mouseOn]);
|
|
1013
|
+
useInput((input, key) => {
|
|
1014
|
+
if (key.ctrl && input === 'o') {
|
|
1015
|
+
if (wizardActiveRef.current || wizardPromptRef.current || pendingApprovalRef.current)
|
|
1016
|
+
return;
|
|
1017
|
+
if (pickerOpen)
|
|
1018
|
+
return;
|
|
1019
|
+
expandLastToolOutput();
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
if (!(key.ctrl && input === 'c'))
|
|
1023
|
+
return;
|
|
1024
|
+
if (pickerOpen) {
|
|
1025
|
+
setPickerOpen(false);
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
if (wizardActiveRef.current) {
|
|
1029
|
+
cancelWizard();
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
if (pendingApprovalRef.current) {
|
|
1033
|
+
cancelRequestedRef.current = true;
|
|
1034
|
+
setCancelling(true);
|
|
1035
|
+
resolveApproval('deny');
|
|
1036
|
+
abortRef.current?.abort();
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
if (busyRef.current) {
|
|
1040
|
+
if (cancelRequestedRef.current) {
|
|
1041
|
+
quit();
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
cancelRequestedRef.current = true;
|
|
1045
|
+
setCancelling(true);
|
|
1046
|
+
abortRef.current?.abort();
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
quit();
|
|
1050
|
+
});
|
|
1051
|
+
const activity = pendingApproval
|
|
1052
|
+
? 'approval'
|
|
1053
|
+
: cancelling
|
|
1054
|
+
? 'cancelling'
|
|
1055
|
+
: busy
|
|
1056
|
+
? activeTool
|
|
1057
|
+
? 'running'
|
|
1058
|
+
: 'thinking'
|
|
1059
|
+
: null;
|
|
1060
|
+
const activeProfile = runtimeConfig.profiles[profileName];
|
|
1061
|
+
const contextWindow = contextWindowFor(activeProfile);
|
|
1062
|
+
const menuRows = pendingApproval || pickerOpen ? 0 : slashMenuRows;
|
|
1063
|
+
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
|
|
1065
|
+
? wizardPrompt.defaultValue && !wizardPrompt.mask
|
|
1066
|
+
? `${wizardPrompt.label} [${wizardPrompt.defaultValue}]`
|
|
1067
|
+
: wizardPrompt.label
|
|
1068
|
+
: busy
|
|
1069
|
+
? 'Kiro is working… Ctrl+C to cancel'
|
|
1070
|
+
: wizardActive
|
|
1071
|
+
? '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 })] }));
|
|
1073
|
+
}
|
|
1074
|
+
//# sourceMappingURL=App.js.map
|