@denizokcu/haze 0.8.0 → 0.10.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/CHANGELOG.md +67 -17
- package/README.md +121 -64
- package/dist/cli/chat/chatMetrics.d.ts +17 -1
- package/dist/cli/chat/chatMetrics.js +22 -5
- package/dist/cli/chat/contextReport.d.ts +11 -0
- package/dist/cli/chat/contextReport.js +44 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
- package/dist/cli/chat/fileMentionSuggestions.js +91 -0
- package/dist/cli/chat/inputSuggestions.d.ts +5 -0
- package/dist/cli/chat/inputSuggestions.js +17 -3
- package/dist/cli/chat/sessionLifecycle.d.ts +58 -0
- package/dist/cli/chat/sessionLifecycle.js +155 -0
- package/dist/cli/chat/sessionRecorder.d.ts +3 -0
- package/dist/cli/chat/sessionRecorder.js +21 -8
- package/dist/cli/chat/startupInfo.d.ts +1 -0
- package/dist/cli/chat/startupInfo.js +11 -0
- package/dist/cli/chat/tips.d.ts +21 -0
- package/dist/cli/chat/tips.js +43 -0
- package/dist/cli/chat/wizardDispatch.d.ts +64 -0
- package/dist/cli/chat/wizardDispatch.js +645 -0
- package/dist/cli/commands/chat.d.ts +1 -0
- package/dist/cli/commands/chat.js +246 -779
- package/dist/cli/commands/chatModes.d.ts +1 -1
- package/dist/cli/commands/chatModes.js +7 -2
- package/dist/cli/commands/commandHelp.js +5 -3
- package/dist/cli/commands/commands.d.ts +4 -3
- package/dist/cli/commands/commands.js +12 -13
- package/dist/cli/commands/fleetCommand.d.ts +14 -0
- package/dist/cli/commands/fleetCommand.js +46 -0
- package/dist/cli/commands/formatters.d.ts +5 -0
- package/dist/cli/commands/formatters.js +36 -9
- package/dist/cli/commands/logsCommand.js +8 -28
- package/dist/cli/commands/mcpWizard.js +24 -2
- package/dist/cli/commands/modelCommand.js +1 -1
- package/dist/cli/commands/providerWizard.d.ts +1 -0
- package/dist/cli/commands/providerWizard.js +31 -5
- package/dist/cli/commands/runCommand.d.ts +1 -0
- package/dist/cli/commands/runCommand.js +32 -20
- package/dist/cli/commands/sessionPicker.d.ts +9 -0
- package/dist/cli/commands/sessionPicker.js +29 -0
- package/dist/cli/commands/settingsSummary.js +8 -4
- package/dist/cli/commands/skillConfirmRemove.js +4 -3
- package/dist/cli/commands/skillWizard.d.ts +2 -0
- package/dist/cli/commands/skillWizard.js +16 -6
- package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
- package/dist/cli/commands/streaming/idleTimer.js +24 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
- package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
- package/dist/cli/commands/streaming/turnOutcome.js +13 -0
- package/dist/cli/commands/streaming/turnRuntime.js +6 -4
- package/dist/cli/commands/streaming.d.ts +13 -1
- package/dist/cli/commands/streaming.js +104 -44
- package/dist/cli/commands/wizardActions.d.ts +6 -0
- package/dist/cli/commands/wizardActions.js +6 -0
- package/dist/cli/commands/wizardPrompts.js +1 -1
- package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
- package/dist/cli/commands/wizardSuggestions.js +62 -13
- package/dist/cli/commands/wizardTransition.d.ts +37 -0
- package/dist/cli/commands/wizardTransition.js +43 -0
- package/dist/cli/index.js +17 -3
- package/dist/cli/terminalTitle.d.ts +6 -0
- package/dist/cli/terminalTitle.js +36 -0
- package/dist/config/contextFiles.js +6 -3
- package/dist/config/endpointSecurity.d.ts +2 -0
- package/dist/config/endpointSecurity.js +28 -0
- package/dist/config/inputHistory.d.ts +3 -3
- package/dist/config/inputHistory.js +13 -17
- package/dist/config/modelDiscovery.d.ts +20 -0
- package/dist/config/modelDiscovery.js +51 -0
- package/dist/config/privateStorage.d.ts +6 -0
- package/dist/config/privateStorage.js +61 -0
- package/dist/config/providerPresets.d.ts +16 -4
- package/dist/config/providerPresets.js +263 -34
- package/dist/config/providers.d.ts +2 -0
- package/dist/config/providers.js +7 -0
- package/dist/config/settings.d.ts +22 -0
- package/dist/config/settings.js +33 -5
- package/dist/config/skillSettings.d.ts +6 -13
- package/dist/config/skillSettings.js +20 -19
- package/dist/config/updateCheck.js +4 -2
- package/dist/core/agent/budgets.d.ts +26 -0
- package/dist/core/agent/budgets.js +34 -0
- package/dist/core/agent/compaction.js +17 -3
- package/dist/core/agent/contextBudget.d.ts +8 -0
- package/dist/core/agent/contextBudget.js +29 -0
- package/dist/core/agent/errors.js +6 -2
- package/dist/core/agent/events.d.ts +12 -0
- package/dist/core/agent/toolOutputStore.d.ts +8 -0
- package/dist/core/agent/toolOutputStore.js +49 -11
- package/dist/core/agent/workState.d.ts +1 -1
- package/dist/core/agent/workState.js +0 -4
- package/dist/core/attachments/imageAttachments.d.ts +90 -0
- package/dist/core/attachments/imageAttachments.js +245 -0
- package/dist/core/attachments/readBlessings.d.ts +37 -0
- package/dist/core/attachments/readBlessings.js +79 -0
- package/dist/core/goal/completionPolicy.d.ts +0 -28
- package/dist/core/goal/completionPolicy.js +0 -88
- package/dist/core/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -13
- package/dist/core/io/boundedRead.d.ts +15 -0
- package/dist/core/io/boundedRead.js +144 -0
- package/dist/core/limits/byteBudgets.d.ts +18 -0
- package/dist/core/limits/byteBudgets.js +18 -0
- package/dist/core/limits/textBudgets.d.ts +23 -0
- package/dist/core/limits/textBudgets.js +23 -0
- package/dist/core/log/llmLog.d.ts +10 -0
- package/dist/core/log/llmLog.js +59 -13
- package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
- package/dist/core/persistence/orderedFileWriter.js +29 -0
- package/dist/core/process/backgroundRegistry.d.ts +35 -0
- package/dist/core/process/backgroundRegistry.js +194 -0
- package/dist/core/process/runBoundedProcess.d.ts +30 -0
- package/dist/core/process/runBoundedProcess.js +116 -0
- package/dist/core/safety/urlGuard.d.ts +2 -1
- package/dist/core/safety/urlGuard.js +3 -2
- package/dist/core/session/sessionSlimming.js +47 -4
- package/dist/core/session/sessionStore.d.ts +37 -0
- package/dist/core/session/sessionStore.js +136 -27
- package/dist/core/subagent/contracts.d.ts +116 -0
- package/dist/core/subagent/contracts.js +54 -0
- package/dist/core/subagent/executionProfiles.d.ts +28 -0
- package/dist/core/subagent/executionProfiles.js +45 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
- package/dist/core/subagent/subagentCoordinator.js +134 -0
- package/dist/core/subagent/subagentRunner.d.ts +211 -145
- package/dist/core/subagent/subagentRunner.js +228 -98
- package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
- package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
- package/dist/core/tasks/taskStorage.js +12 -1
- package/dist/llm/client.d.ts +20 -29
- package/dist/llm/client.js +33 -29
- package/dist/llm/hazeTools.d.ts +2396 -67
- package/dist/llm/hazeTools.js +50 -37
- package/dist/llm/lsp.d.ts +23 -3
- package/dist/llm/lsp.js +73 -16
- package/dist/llm/lspTools.d.ts +96 -48
- package/dist/llm/mcp.d.ts +1 -1
- package/dist/llm/mcp.js +65 -16
- package/dist/llm/requestContext.d.ts +23 -1
- package/dist/llm/requestContext.js +50 -7
- package/dist/llm/systemPrompt.d.ts +4 -1
- package/dist/llm/systemPrompt.js +14 -4
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/tools/bashTool.d.ts +1210 -16
- package/dist/llm/tools/bashTool.js +43 -60
- package/dist/llm/tools/fetchTool.d.ts +26 -26
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +2 -1
- package/dist/llm/tools/fileToolShared.js +5 -5
- package/dist/llm/tools/grepRunner.d.ts +20 -0
- package/dist/llm/tools/grepRunner.js +66 -0
- package/dist/llm/tools/outputCap.d.ts +2 -6
- package/dist/llm/tools/outputCap.js +2 -6
- package/dist/llm/tools/processTool.d.ts +1077 -0
- package/dist/llm/tools/processTool.js +41 -0
- package/dist/llm/tools/toolContext.d.ts +8 -0
- package/dist/llm/tools/toolContext.js +22 -11
- package/dist/llm/tools/workspaceFile.d.ts +9 -1
- package/dist/llm/tools/workspaceFile.js +33 -4
- package/dist/llm/webFetch.js +24 -11
- package/dist/llm/workerContext.d.ts +18 -0
- package/dist/llm/workerContext.js +55 -0
- package/dist/skills/SkillLoader.d.ts +2 -2
- package/dist/skills/SkillLoader.js +17 -5
- package/dist/skills/SkillRegistry.d.ts +3 -2
- package/dist/skills/SkillRegistry.js +53 -10
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +23 -5
- package/dist/skills/skillTools.js +11 -4
- package/dist/skills/types.d.ts +11 -1
- package/dist/ui/components/TextInput.d.ts +5 -2
- package/dist/ui/components/TextInput.js +76 -8
- package/dist/utils/format.d.ts +2 -0
- package/dist/utils/format.js +8 -0
- package/dist/utils/fs.d.ts +0 -1
- package/dist/utils/fs.js +0 -4
- package/dist/utils/openPath.d.ts +2 -0
- package/dist/utils/openPath.js +9 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +9 -4
- package/package.json +1 -1
|
@@ -2,7 +2,6 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
2
2
|
import { useEffect, useRef, useState } from 'react';
|
|
3
3
|
import { execFile as execFileCallback } from 'node:child_process';
|
|
4
4
|
import { promisify } from 'node:util';
|
|
5
|
-
import fs from 'fs-extra';
|
|
6
5
|
import { Box, render, Static, Text, useApp, useStdout } from 'ink';
|
|
7
6
|
import Spinner from 'ink-spinner';
|
|
8
7
|
import { readContextFiles } from '../../config/contextFiles.js';
|
|
@@ -10,46 +9,37 @@ import { checkForUpdate } from '../../config/updateCheck.js';
|
|
|
10
9
|
import { addInputHistoryItem, readInputHistory } from '../../config/inputHistory.js';
|
|
11
10
|
import { loadTasks as loadTasksFromStore, clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
|
|
12
11
|
import { readSettings, updateSettings } from '../../config/settings.js';
|
|
13
|
-
import { activeModel,
|
|
14
|
-
import { removeLspServer } from '../../config/lspSettings.js';
|
|
15
|
-
import { removeMcpServer } from '../../config/mcpSettings.js';
|
|
12
|
+
import { activeModel, activeProvider } from '../../config/providers.js';
|
|
16
13
|
import { isSkillEnabled } from '../../config/skillSettings.js';
|
|
17
14
|
import { Header } from '../../ui/components/Header.js';
|
|
18
15
|
import { TextInput } from '../../ui/components/TextInput.js';
|
|
19
16
|
import { theme } from '../../ui/theme.js';
|
|
20
17
|
import { handleSlashCommand } from './commands.js';
|
|
21
18
|
import { runAgentTurn } from './streaming.js';
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
19
|
+
import { formatElapsedTimeWhole, imageAttachmentLine } from './formatters.js';
|
|
20
|
+
import { imageCapabilityError, IMAGE_ONLY_PROMPT_TEXT, resolveImageAttachments } from '../../core/attachments/imageAttachments.js';
|
|
21
|
+
import { resolveReadBlessings } from '../../core/attachments/readBlessings.js';
|
|
22
|
+
import { endLog as endLlmLog } from '../../core/log/llmLog.js';
|
|
24
23
|
import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
|
|
25
|
-
import {
|
|
26
|
-
import { findPreset } from '../../config/providerPresets.js';
|
|
27
|
-
import { appendSessionEntry, createSession, formatSession, latestSession, restoreConversation, restoreWorkState } from '../../core/session/sessionStore.js';
|
|
28
|
-
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
29
|
-
import { contextBreakdown } from '../../core/agent/contextBudget.js';
|
|
30
|
-
import { stripSyntheticControls } from '../../core/agent/requestAssembly.js';
|
|
31
|
-
import { modelWithConfig } from '../../llm/client.js';
|
|
32
|
-
import { assembleRequestContext } from '../../llm/requestContext.js';
|
|
33
|
-
import { closeMcpClients } from '../../llm/mcp.js';
|
|
24
|
+
import { formatSession, listSessions } from '../../core/session/sessionStore.js';
|
|
34
25
|
import { MAX_VISIBLE_TASKS, TaskBar } from '../chat/TaskBar.js';
|
|
35
|
-
import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
|
|
36
26
|
import { MessageView, messageKey, orderedDisplayMessages } from '../chat/messages.js';
|
|
37
27
|
import { createSessionRecorder } from '../chat/sessionRecorder.js';
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
28
|
+
import { createSessionLifecycle } from '../chat/sessionLifecycle.js';
|
|
29
|
+
import { createWizardDispatch } from '../chat/wizardDispatch.js';
|
|
30
|
+
import { buildContextReport } from '../chat/contextReport.js';
|
|
31
|
+
import { startupContextInfo, startupInputTips, startupProviderInfo } from '../chat/startupInfo.js';
|
|
32
|
+
import { TIPS, randomTipIndex, tipsEnabled } from '../chat/tips.js';
|
|
33
|
+
import { fileMentionSuggestions } from '../chat/fileMentionSuggestions.js';
|
|
34
|
+
import { compactHomePath, formatTokenCount, statusBarMetrics } from '../chat/chatMetrics.js';
|
|
40
35
|
import { accumulateTokenUsage, EMPTY_TOKEN_USAGE, shouldClearCompletedTasks } from '../chat/turnState.js';
|
|
41
36
|
import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } from './chatModes.js';
|
|
42
37
|
import { inputSuggestionsForState } from '../chat/inputSuggestions.js';
|
|
43
38
|
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
44
|
-
import {
|
|
45
|
-
import {
|
|
46
|
-
import {
|
|
47
|
-
import {
|
|
48
|
-
import { providerActionResult, providerAppendModels, providerFinishAdd, providerRemove, providerRemoveModels, providerSetKey } from './providerWizard.js';
|
|
49
|
-
import { selectSkillActionResult, selectSkillResult } from './skillWizard.js';
|
|
50
|
-
import { captureSkillDescription as captureSkillDescriptionResult, skillCreationFailure, skillCreationMessage } from './skillCreation.js';
|
|
51
|
-
import { skillConfirmRemoveResult as skillConfirmRemove } from './skillConfirmRemove.js';
|
|
52
|
-
import { commandParts, isYesConfirmation } from './wizardInput.js';
|
|
39
|
+
import { transitionMcpField, transitionProviderField } from './wizardTransition.js';
|
|
40
|
+
import { commandParts } from './wizardInput.js';
|
|
41
|
+
import { backgroundProcessCount, subscribeBackgroundProcesses, teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
|
|
42
|
+
import { MAX_SESSION_PICKER_RESULTS } from './sessionPicker.js';
|
|
53
43
|
const execFile = promisify(execFileCallback);
|
|
54
44
|
async function currentBranchName() {
|
|
55
45
|
try {
|
|
@@ -70,7 +60,7 @@ function busyElapsedLabel(startedAt) {
|
|
|
70
60
|
function thinkingLabelForSettings(settings) {
|
|
71
61
|
return modelThinkingLabel(activeModel(settings)?.model);
|
|
72
62
|
}
|
|
73
|
-
function ChatScreen({ debug = false, version, continueSession = false, noSession = false }) {
|
|
63
|
+
function ChatScreen({ debug = false, version, continueSession = false, resumeSessionId, noSession = false }) {
|
|
74
64
|
const { exit } = useApp();
|
|
75
65
|
const { stdout } = useStdout();
|
|
76
66
|
const width = stdout.columns ?? process.stdout.columns ?? 80;
|
|
@@ -97,20 +87,30 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
97
87
|
});
|
|
98
88
|
};
|
|
99
89
|
const [settings, setSettings] = useState({});
|
|
90
|
+
const [settingsError, setSettingsError] = useState();
|
|
100
91
|
const conversationRef = useRef([]);
|
|
101
92
|
const lastAssistantTextRef = useRef('');
|
|
102
93
|
const abortControllerRef = useRef(null);
|
|
103
94
|
const sessionRef = useRef(undefined);
|
|
95
|
+
const sessionRecorderRef = useRef(undefined);
|
|
96
|
+
if (!sessionRecorderRef.current)
|
|
97
|
+
sessionRecorderRef.current = createSessionRecorder(() => sessionRef.current);
|
|
104
98
|
const sessionStartRef = useRef(new Date());
|
|
105
99
|
const workStateRef = useRef(undefined);
|
|
106
100
|
const llmLogRef = useRef(undefined);
|
|
101
|
+
const persistenceWarningShownRef = useRef(false);
|
|
102
|
+
const skillErrorSignatureRef = useRef('');
|
|
103
|
+
const projectSkillSignatureRef = useRef('');
|
|
107
104
|
const contextFileSignaturesRef = useRef(new Map());
|
|
108
105
|
const followUpQueueRef = useRef([]);
|
|
109
106
|
const [inputHistory, setInputHistory] = useState([]);
|
|
110
107
|
const [debugLogs, setDebugLogs] = useState([]);
|
|
111
108
|
const [contextFiles, setContextFiles] = useState([]);
|
|
112
109
|
const [mode, setMode] = useState('chat');
|
|
110
|
+
const [sessions, setSessions] = useState([]);
|
|
111
|
+
const [selectedSessionId, setSelectedSessionId] = useState();
|
|
113
112
|
const [busy, setBusy] = useState(false);
|
|
113
|
+
const [backgroundCount, setBackgroundCount] = useState(backgroundProcessCount);
|
|
114
114
|
const [busyLabel, setBusyLabel] = useState(() => thinkingLabelForSettings(settings));
|
|
115
115
|
// Heartbeat for the busy indicator: ticks every second while haze is working
|
|
116
116
|
// so the developer always sees rolling activity (elapsed turn time) even when
|
|
@@ -125,6 +125,8 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
125
125
|
const [skills, setSkills] = useState([]);
|
|
126
126
|
const [branchName, setBranchName] = useState();
|
|
127
127
|
const [modelProviderFilter, setModelProviderFilter] = useState();
|
|
128
|
+
const [discoveredModels, setDiscoveredModels] = useState([]);
|
|
129
|
+
const [suggestedModels, setSuggestedModels] = useState([]);
|
|
128
130
|
const [selectedProviderName, setSelectedProviderName] = useState();
|
|
129
131
|
const [providerDraft, setProviderDraft] = useState({});
|
|
130
132
|
const [skillDraft, setSkillDraft] = useState({});
|
|
@@ -144,25 +146,47 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
144
146
|
turnStartedAtRef.current = undefined;
|
|
145
147
|
setBusy(nextBusy);
|
|
146
148
|
};
|
|
149
|
+
useEffect(() => subscribeBackgroundProcesses(() => setBackgroundCount(backgroundProcessCount())), []);
|
|
147
150
|
useEffect(() => {
|
|
148
151
|
if (!busy)
|
|
149
152
|
return;
|
|
150
153
|
const heartbeat = setInterval(() => setBusyTick(tick => tick + 1), 1000);
|
|
151
154
|
return () => clearInterval(heartbeat);
|
|
152
155
|
}, [busy]);
|
|
156
|
+
// One tip per thinking section, shown under the busy label while the model
|
|
157
|
+
// is purely thinking (no tool running) and the user has not disabled tips.
|
|
158
|
+
// A fresh tip is picked each time the model enters thinking mode; no
|
|
159
|
+
// rotation during a single thinking section.
|
|
160
|
+
const [tipIndex, setTipIndex] = useState(() => randomTipIndex());
|
|
161
|
+
const thinkingLabel = thinkingLabelForSettings(settings);
|
|
162
|
+
const showingTip = busy && busyLabel === thinkingLabel && tipsEnabled(settings);
|
|
163
|
+
useEffect(() => {
|
|
164
|
+
if (!showingTip)
|
|
165
|
+
return;
|
|
166
|
+
setTipIndex(current => randomTipIndex(current));
|
|
167
|
+
}, [showingTip]);
|
|
168
|
+
// Refresh the branch at turn boundaries so switching branches during a turn
|
|
169
|
+
// shows up promptly without tight idle polling (CR-026).
|
|
170
|
+
useEffect(() => {
|
|
171
|
+
if (busy)
|
|
172
|
+
return;
|
|
173
|
+
currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
|
|
174
|
+
}, [busy]);
|
|
153
175
|
useEffect(() => {
|
|
154
176
|
Promise.all([
|
|
155
|
-
readSettings().
|
|
177
|
+
readSettings().then(value => ({ value, error: undefined })).catch(error => ({ value: {}, error: error instanceof Error ? error.message : String(error) })),
|
|
156
178
|
currentBranchName().catch(() => undefined),
|
|
157
179
|
readContextFiles().catch(() => []),
|
|
158
|
-
]).then(([
|
|
180
|
+
]).then(([settingsResult, branch, files]) => {
|
|
181
|
+
const next = settingsResult.value;
|
|
159
182
|
setSettings(next);
|
|
183
|
+
setSettingsError(settingsResult.error);
|
|
160
184
|
setBranchName(branch);
|
|
161
185
|
setContextFiles(files);
|
|
162
186
|
contextFileSignaturesRef.current = new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
163
|
-
setMessages(m => [...m, { role: 'system', text: `${startupProviderInfo(next)}\n\n${startupContextInfo(files)}` }]);
|
|
187
|
+
setMessages(m => [...m, { role: 'system', text: settingsResult.error ? settingsResult.error : `${startupProviderInfo(next)}\n\n${startupContextInfo(files)}` }]);
|
|
164
188
|
}).catch(() => undefined);
|
|
165
|
-
initializeSession().catch(error => {
|
|
189
|
+
sessionLifecycle.initializeSession().catch(error => {
|
|
166
190
|
const text = error instanceof Error ? error.message : String(error);
|
|
167
191
|
setMessages(m => [...m, { role: 'system', text: `Session disabled: ${text}` }]);
|
|
168
192
|
});
|
|
@@ -180,7 +204,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
180
204
|
}
|
|
181
205
|
const branchTimer = setInterval(() => {
|
|
182
206
|
currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
|
|
183
|
-
},
|
|
207
|
+
}, 15_000);
|
|
184
208
|
return () => clearInterval(branchTimer);
|
|
185
209
|
}, []);
|
|
186
210
|
function persistInputHistory(value) {
|
|
@@ -188,8 +212,19 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
188
212
|
}
|
|
189
213
|
async function refreshSkills() {
|
|
190
214
|
const registry = await loadSkillRegistry();
|
|
191
|
-
const nextSkills = [...registry.skills.values()];
|
|
215
|
+
const nextSkills = registry.candidates ?? [...registry.skills.values()];
|
|
192
216
|
setSkills(nextSkills);
|
|
217
|
+
const projectSkills = nextSkills.filter(skill => skill.source === 'project');
|
|
218
|
+
const projectSignature = projectSkills.map(skill => `${skill.name}:${skill.path}`).join('\n');
|
|
219
|
+
if (projectSignature && projectSignature !== projectSkillSignatureRef.current) {
|
|
220
|
+
setMessages(messages => [...messages, { role: 'system', text: `Project skills discovered (repository-provided, untrusted content): ${projectSkills.map(skill => skill.name).join(', ')}` }]);
|
|
221
|
+
}
|
|
222
|
+
projectSkillSignatureRef.current = projectSignature;
|
|
223
|
+
const errorSignature = registry.errors.map(error => `${error.source ? `${error.source}/` : ''}${error.directory}: ${error.message}`).join('\n');
|
|
224
|
+
if (errorSignature && errorSignature !== skillErrorSignatureRef.current) {
|
|
225
|
+
setMessages(messages => [...messages, { role: 'system', text: `Invalid skills were isolated:\n${errorSignature}` }]);
|
|
226
|
+
}
|
|
227
|
+
skillErrorSignatureRef.current = errorSignature;
|
|
193
228
|
return nextSkills;
|
|
194
229
|
}
|
|
195
230
|
function skillInvocation(value) {
|
|
@@ -198,147 +233,60 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
198
233
|
const [name, ...args] = commandParts(value.slice(1));
|
|
199
234
|
if (!name)
|
|
200
235
|
return undefined;
|
|
201
|
-
const skill = skills.find(candidate => candidate.name === name);
|
|
202
|
-
//
|
|
203
|
-
//
|
|
204
|
-
return skill
|
|
236
|
+
const skill = skills.find(candidate => candidate.name === name && isSkillEnabled(settings, candidate.name, candidate.source));
|
|
237
|
+
// Candidates are ordered project-first, so disabling a project collision
|
|
238
|
+
// automatically re-surfaces the enabled global skill.
|
|
239
|
+
return skill ? { skill, args: args.join(' ') } : undefined;
|
|
205
240
|
}
|
|
206
241
|
function debugLog(line) {
|
|
207
242
|
if (!debug)
|
|
208
243
|
return;
|
|
209
244
|
setDebugLogs(current => [...current.slice(-7), line]);
|
|
210
245
|
}
|
|
211
|
-
|
|
212
|
-
if (
|
|
213
|
-
return
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
const { state: workState, parseErrors: workStateErrors } = await restoreWorkState(session);
|
|
251
|
-
workStateRef.current = workState;
|
|
252
|
-
for (const error of [...conversationErrors, ...workStateErrors]) {
|
|
253
|
-
debugLog(`Session parse error: ${error}`);
|
|
254
|
-
}
|
|
255
|
-
setMessages(m => [...m, { role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...restoredMessages]);
|
|
256
|
-
await startNewLog();
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
await startNewSession(continueSession ? 'No previous session found. Started a new session.' : 'Started a new session.');
|
|
261
|
-
}
|
|
262
|
-
function clearConversation() {
|
|
263
|
-
clearToolOutputs();
|
|
264
|
-
conversationRef.current = [];
|
|
265
|
-
lastAssistantTextRef.current = '';
|
|
266
|
-
setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
267
|
-
workStateRef.current = undefined;
|
|
268
|
-
setLiveMessagesState(() => []);
|
|
269
|
-
setMessages([{ role: 'system', text: 'Cleared. The void is productive.' }]);
|
|
270
|
-
void startNewLog();
|
|
271
|
-
const session = sessionRef.current;
|
|
272
|
-
if (session)
|
|
273
|
-
void appendSessionEntry(session, { type: 'event', at: new Date().toISOString(), name: 'clear', text: 'Conversation cleared' }).catch(() => undefined);
|
|
274
|
-
}
|
|
275
|
-
function compactConversation(instructions) {
|
|
276
|
-
const result = compactModelMessages(conversationRef.current, { instructions, tokenBudget: 40_000, workState: workStateRef.current });
|
|
277
|
-
if (!result.compacted) {
|
|
278
|
-
setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${result.keptCount} model messages in context.` }]);
|
|
279
|
-
return false;
|
|
280
|
-
}
|
|
281
|
-
conversationRef.current = result.messages;
|
|
282
|
-
const session = sessionRef.current;
|
|
283
|
-
if (session) {
|
|
284
|
-
void appendSessionEntry(session, { type: 'event', at: new Date().toISOString(), name: 'compact', text: `Compacted ${result.olderCount} messages; kept ${result.keptCount}.` }).catch(() => undefined);
|
|
285
|
-
void appendSessionEntry(session, { type: 'conversation_snapshot', at: new Date().toISOString(), messages: result.messages }).catch(() => undefined);
|
|
286
|
-
}
|
|
287
|
-
setMessages(m => [...m, { role: 'system', text: `Compacted context: summarized ${result.olderCount} older model messages and kept the last ${result.keptCount}.` }]);
|
|
288
|
-
return true;
|
|
289
|
-
}
|
|
290
|
-
async function resumeLatestSession() {
|
|
291
|
-
const session = await latestSession();
|
|
292
|
-
if (!session) {
|
|
293
|
-
setMessages(m => [...m, { role: 'system', text: 'No previous session found for this workspace.' }]);
|
|
246
|
+
function showPersistenceWarning(error) {
|
|
247
|
+
if (persistenceWarningShownRef.current)
|
|
248
|
+
return;
|
|
249
|
+
persistenceWarningShownRef.current = true;
|
|
250
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
251
|
+
setMessages(messages => [...messages, { role: 'system', text: `Persistence warning: ${text}` }]);
|
|
252
|
+
}
|
|
253
|
+
// Session lifecycle (init/continue/resume/new/clear/compact) lives in a
|
|
254
|
+
// dedicated controller so this component stays orchestration glue (CR-006).
|
|
255
|
+
const sessionLifecycle = createSessionLifecycle({
|
|
256
|
+
version,
|
|
257
|
+
continueSession,
|
|
258
|
+
resumeSessionId,
|
|
259
|
+
noSession,
|
|
260
|
+
debug,
|
|
261
|
+
contextFiles: () => contextFiles,
|
|
262
|
+
sessionRef,
|
|
263
|
+
sessionRecorder: () => sessionRecorderRef.current,
|
|
264
|
+
sessionStartRef,
|
|
265
|
+
conversationRef,
|
|
266
|
+
workStateRef,
|
|
267
|
+
lastAssistantTextRef,
|
|
268
|
+
llmLogRef,
|
|
269
|
+
contextFileSignaturesRef,
|
|
270
|
+
setMessages,
|
|
271
|
+
setLiveMessagesState,
|
|
272
|
+
setTokenUsage,
|
|
273
|
+
debugLog,
|
|
274
|
+
showPersistenceWarning,
|
|
275
|
+
});
|
|
276
|
+
const { clearConversation, compactConversation } = sessionLifecycle;
|
|
277
|
+
async function openSessionPicker() {
|
|
278
|
+
await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
|
|
279
|
+
const next = await listSessions();
|
|
280
|
+
setSessions(next);
|
|
281
|
+
setSelectedSessionId(undefined);
|
|
282
|
+
if (next.length === 0) {
|
|
283
|
+
setMessages(m => [...m, { role: 'system', text: 'No saved sessions found for this workspace.' }]);
|
|
284
|
+
setMode('chat');
|
|
294
285
|
return;
|
|
295
286
|
}
|
|
296
|
-
|
|
297
|
-
const
|
|
298
|
-
|
|
299
|
-
debugLog(`Session parse error: ${error}`);
|
|
300
|
-
}
|
|
301
|
-
clearToolOutputs();
|
|
302
|
-
sessionRef.current = session;
|
|
303
|
-
conversationRef.current = conversation;
|
|
304
|
-
workStateRef.current = workState;
|
|
305
|
-
setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
306
|
-
setLiveMessagesState(() => []);
|
|
307
|
-
setMessages([{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...displayMessagesFromConversation(conversation)]);
|
|
308
|
-
}
|
|
309
|
-
async function buildContextReport() {
|
|
310
|
-
const runtime = await modelWithConfig({ cwd: process.cwd() });
|
|
311
|
-
if (!runtime?.model) {
|
|
312
|
-
return 'No model provider configured. Run /provider to choose or add a provider before /context can estimate tokens.';
|
|
313
|
-
}
|
|
314
|
-
const session = { start: sessionStartRef.current, cwd: process.cwd() };
|
|
315
|
-
const assembled = await assembleRequestContext({ contextFiles, session, model: runtime.model });
|
|
316
|
-
try {
|
|
317
|
-
const messages = stripSyntheticControls(conversationRef.current);
|
|
318
|
-
const breakdown = contextBreakdown({ system: assembled.systemPrompt, contextFiles, messages, tools: assembled.availableTools });
|
|
319
|
-
const tools = breakdown.toolSchemas.map(tool => ({
|
|
320
|
-
name: tool.name,
|
|
321
|
-
tokens: tool.tokens,
|
|
322
|
-
category: assembled.toolCategories.get(tool.name) ?? 'builtin',
|
|
323
|
-
}));
|
|
324
|
-
return formatContextReport({
|
|
325
|
-
modelLabel: `${runtime.config.providerName}:${runtime.config.modelName}`,
|
|
326
|
-
systemTokens: breakdown.system,
|
|
327
|
-
projectContext: breakdown.projectContext,
|
|
328
|
-
tools,
|
|
329
|
-
messagesByRole: breakdown.messagesByRole,
|
|
330
|
-
toolResults: breakdown.toolResults,
|
|
331
|
-
toolInputs: breakdown.toolInputs,
|
|
332
|
-
syntheticControl: breakdown.syntheticControl,
|
|
333
|
-
logicalInputEstimate: breakdown.logicalInputEstimate,
|
|
334
|
-
messageCount: messages.length,
|
|
335
|
-
mcpErrors: assembled.loadedMcp?.errors ?? [],
|
|
336
|
-
});
|
|
337
|
-
}
|
|
338
|
-
finally {
|
|
339
|
-
if (assembled.loadedMcp?.clients.length)
|
|
340
|
-
await closeMcpClients(assembled.loadedMcp.clients);
|
|
341
|
-
}
|
|
287
|
+
setMode('sessions');
|
|
288
|
+
const hidden = Math.max(0, next.length - MAX_SESSION_PICKER_RESULTS);
|
|
289
|
+
setMessages(m => [...m, { role: 'system', text: `Choose a saved session (newest first)${hidden ? `. Showing ${MAX_SESSION_PICKER_RESULTS} of ${next.length}; ${hidden} older sessions are hidden.` : '.'}` }]);
|
|
342
290
|
}
|
|
343
291
|
function cancelThinking() {
|
|
344
292
|
if (!busy)
|
|
@@ -362,7 +310,11 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
362
310
|
function closeInputList() {
|
|
363
311
|
if (mode !== 'chat') {
|
|
364
312
|
setMode('chat');
|
|
313
|
+
setSessions([]);
|
|
314
|
+
setSelectedSessionId(undefined);
|
|
365
315
|
setModelProviderFilter(undefined);
|
|
316
|
+
setDiscoveredModels([]);
|
|
317
|
+
setSuggestedModels([]);
|
|
366
318
|
setSelectedProviderName(undefined);
|
|
367
319
|
setProviderDraft({});
|
|
368
320
|
setSkillDraft({});
|
|
@@ -373,610 +325,84 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
373
325
|
setMcpDraft({});
|
|
374
326
|
}
|
|
375
327
|
}
|
|
376
|
-
async function selectProvider(providerName) {
|
|
377
|
-
if (providerName === PROVIDER_CHOICES.addProvider) {
|
|
378
|
-
setProviderDraft({});
|
|
379
|
-
setMode('providerAddPreset');
|
|
380
|
-
setMessages(m => [...m, { role: 'system', text: 'Choose a provider preset, or select "custom" to enter details manually.' }]);
|
|
381
|
-
return;
|
|
382
|
-
}
|
|
383
|
-
const provider = findProvider(settings, providerName);
|
|
384
|
-
if (!provider) {
|
|
385
|
-
setMessages(m => [...m, { role: 'system', text: `No provider named ${providerName}. Use /provider and choose add provider.` }]);
|
|
386
|
-
setMode('chat');
|
|
387
|
-
return;
|
|
388
|
-
}
|
|
389
|
-
setSelectedProviderName(provider.name);
|
|
390
|
-
setMode('providerAction');
|
|
391
|
-
setMessages(m => [...m, { role: 'system', text: `${provider.name}: choose an action.` }]);
|
|
392
|
-
}
|
|
393
|
-
async function selectPreset(presetId) {
|
|
394
|
-
if (presetId === PROVIDER_CHOICES.custom) {
|
|
395
|
-
setProviderDraft({});
|
|
396
|
-
setMode('providerAddName');
|
|
397
|
-
setMessages(m => [...m, { role: 'system', text: 'Provider name? Example: openrouter, local, lmstudio.' }]);
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
const preset = findPreset(presetId);
|
|
401
|
-
if (!preset) {
|
|
402
|
-
setMessages(m => [...m, { role: 'system', text: `Unknown preset: ${presetId}.` }]);
|
|
403
|
-
return;
|
|
404
|
-
}
|
|
405
|
-
// Check if a provider with this name already exists
|
|
406
|
-
const existingName = settings.providers?.some(p => p.name === preset.name) ? preset.id : preset.name;
|
|
407
|
-
const nameConflict = settings.providers?.some(p => p.name === existingName);
|
|
408
|
-
if (nameConflict) {
|
|
409
|
-
setMessages(m => [...m, { role: 'system', text: `Provider ${existingName} already exists. Use /provider to manage existing providers.` }]);
|
|
410
|
-
setMode('chat');
|
|
411
|
-
setProviderDraft({});
|
|
412
|
-
return;
|
|
413
|
-
}
|
|
414
|
-
setProviderDraft({ name: existingName, url: preset.baseUrl });
|
|
415
|
-
if (preset.needsApiKey) {
|
|
416
|
-
setMode('providerAddKey');
|
|
417
|
-
setMessages(m => [...m, { role: 'system', text: `${preset.name} (${preset.baseUrl})\nAPI key${preset.apiKeyHint ? ` (${preset.apiKeyHint})` : ''}?` }]);
|
|
418
|
-
}
|
|
419
|
-
else {
|
|
420
|
-
// Local/keyless: skip API key, go straight to models
|
|
421
|
-
setMode('providerAddModels');
|
|
422
|
-
const hint = preset.suggestedModels?.length ? ` Example: ${preset.suggestedModels.join(', ')}` : '';
|
|
423
|
-
setMessages(m => [...m, { role: 'system', text: `${preset.name} (${preset.baseUrl}) — no API key needed.\nComma-separated model names?${hint}` }]);
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
async function useProvider(providerName) {
|
|
427
|
-
const provider = findProvider(settings, providerName);
|
|
428
|
-
if (!provider) {
|
|
429
|
-
setMessages(m => [...m, { role: 'system', text: `No provider named ${providerName}.` }]);
|
|
430
|
-
setMode('chat');
|
|
431
|
-
setSelectedProviderName(undefined);
|
|
432
|
-
return;
|
|
433
|
-
}
|
|
434
|
-
const next = await updateSettings({ provider: provider.name });
|
|
435
|
-
setSettings(next);
|
|
436
|
-
setSelectedProviderName(undefined);
|
|
437
|
-
setModelProviderFilter(provider.name);
|
|
438
|
-
setMode('model');
|
|
439
|
-
setMessages(m => [...m, { role: 'system', text: `Provider set to ${provider.name}. Choose a model.` }]);
|
|
440
|
-
}
|
|
441
|
-
async function selectProviderAction(action) {
|
|
442
|
-
if (!selectedProviderName) {
|
|
443
|
-
setMode('provider');
|
|
444
|
-
return;
|
|
445
|
-
}
|
|
446
|
-
const provider = findProvider(settings, selectedProviderName);
|
|
447
|
-
if (!provider) {
|
|
448
|
-
setMessages(m => [...m, { role: 'system', text: `Provider ${selectedProviderName} not found.` }]);
|
|
449
|
-
setMode('chat');
|
|
450
|
-
setSelectedProviderName(undefined);
|
|
451
|
-
return;
|
|
452
|
-
}
|
|
453
|
-
if (action === PROVIDER_ACTIONS.useProvider) {
|
|
454
|
-
await useProvider(selectedProviderName);
|
|
455
|
-
return;
|
|
456
|
-
}
|
|
457
|
-
const actionResult = providerActionResult(action, provider);
|
|
458
|
-
if (actionResult.selectedName === undefined)
|
|
459
|
-
setSelectedProviderName(undefined);
|
|
460
|
-
if (actionResult.mode)
|
|
461
|
-
setMode(actionResult.mode);
|
|
462
|
-
showWizardMessage(actionResult.message);
|
|
463
|
-
}
|
|
464
|
-
async function selectModel(selector) {
|
|
465
|
-
const scopedSelector = modelProviderFilter ? `${modelProviderFilter}:${selector}` : selector;
|
|
466
|
-
const resolved = resolveModelSelector(settings, scopedSelector);
|
|
467
|
-
if (resolved.status === 'ambiguous') {
|
|
468
|
-
setMessages(m => [...m, { role: 'system', text: `Model ${resolved.model} exists on multiple providers: ${resolved.providers.map(provider => modelSelector(provider, resolved.model)).join(', ')}` }]);
|
|
469
|
-
return;
|
|
470
|
-
}
|
|
471
|
-
if (resolved.status === 'missing') {
|
|
472
|
-
setMessages(m => [...m, { role: 'system', text: `No configured model named ${selector}. Use /provider, select a provider, then choose add models.` }]);
|
|
473
|
-
return;
|
|
474
|
-
}
|
|
475
|
-
const next = await updateSettings({ provider: resolved.provider.name, model: resolved.model });
|
|
476
|
-
setSettings(next);
|
|
477
|
-
setModelProviderFilter(undefined);
|
|
478
|
-
setMode('chat');
|
|
479
|
-
setMessages(m => [...m, { role: 'system', text: `Model set to ${resolved.model} on ${resolved.provider.name}.\n\n${startupProviderInfo(next)}` }]);
|
|
480
|
-
}
|
|
481
|
-
async function appendModelsToProvider(modelsValue) {
|
|
482
|
-
const result = providerAppendModels(settings, selectedProviderName, modelsValue);
|
|
483
|
-
if (!result.provider) {
|
|
484
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
485
|
-
setMode('chat');
|
|
486
|
-
return;
|
|
487
|
-
}
|
|
488
|
-
if (!result.settingsPatch) {
|
|
489
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
490
|
-
return;
|
|
491
|
-
}
|
|
492
|
-
const next = await updateSettings(result.settingsPatch);
|
|
493
|
-
setSettings(next);
|
|
494
|
-
setSelectedProviderName(undefined);
|
|
495
|
-
setModelProviderFilter(result.provider.name);
|
|
496
|
-
setMode('model');
|
|
497
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
498
|
-
}
|
|
499
|
-
async function finishProviderAdd(modelsValue) {
|
|
500
|
-
const result = providerFinishAdd(settings, providerDraft, modelsValue);
|
|
501
|
-
if (!result.provider || !result.settingsPatch) {
|
|
502
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
503
|
-
setMode('chat');
|
|
504
|
-
setProviderDraft({});
|
|
505
|
-
return;
|
|
506
|
-
}
|
|
507
|
-
const next = await updateSettings(result.settingsPatch);
|
|
508
|
-
setSettings(next);
|
|
509
|
-
setProviderDraft({});
|
|
510
|
-
setModelProviderFilter(result.provider.name);
|
|
511
|
-
setMode('model');
|
|
512
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
513
|
-
}
|
|
514
|
-
// --- LSP wizard handlers (mirror the provider wizard) ---
|
|
515
328
|
function showWizardMessage(message) {
|
|
516
329
|
if (message)
|
|
517
330
|
setMessages(m => [...m, { role: 'system', text: message }]);
|
|
518
331
|
}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
if (result.mode)
|
|
538
|
-
setMode(result.mode);
|
|
539
|
-
showWizardMessage(result.message);
|
|
540
|
-
}
|
|
541
|
-
async function selectLspAction(action) {
|
|
542
|
-
const result = selectLspActionResult(settings, selectedLspName, action);
|
|
543
|
-
if (result.settingsPatch)
|
|
544
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
545
|
-
if ('selectedName' in result)
|
|
546
|
-
setSelectedLspName(result.selectedName);
|
|
547
|
-
if (result.mode)
|
|
548
|
-
setMode(result.mode);
|
|
549
|
-
showWizardMessage(result.message);
|
|
550
|
-
}
|
|
551
|
-
async function finishLspCustom(commandLine) {
|
|
552
|
-
const result = finishLspCustomResult(settings, lspDraft.name, commandLine);
|
|
553
|
-
if (result.settingsPatch)
|
|
554
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
555
|
-
if (result.clearDraft)
|
|
556
|
-
setLspDraft({});
|
|
557
|
-
if (result.mode)
|
|
558
|
-
setMode(result.mode);
|
|
559
|
-
showWizardMessage(result.message);
|
|
560
|
-
}
|
|
561
|
-
// --- MCP wizard handlers (mirror the provider wizard) ---
|
|
562
|
-
async function selectMcpServer(serverName) {
|
|
563
|
-
const result = selectMcpServerResult(settings, serverName);
|
|
564
|
-
if (result.clearDraft)
|
|
565
|
-
setMcpDraft({});
|
|
566
|
-
if (serverName === SERVER_CHOICES.addServer)
|
|
567
|
-
setMode('mcpAddPreset');
|
|
568
|
-
else if (result.mode)
|
|
569
|
-
setMode(result.mode);
|
|
570
|
-
if (result.selectedName !== undefined)
|
|
571
|
-
setSelectedMcpName(result.selectedName);
|
|
572
|
-
showWizardMessage(result.message);
|
|
573
|
-
}
|
|
574
|
-
async function selectMcpPreset(presetId) {
|
|
575
|
-
const result = selectMcpPresetResult(settings, presetId);
|
|
576
|
-
if (result.clearDraft)
|
|
577
|
-
setMcpDraft({});
|
|
578
|
-
if (result.draft)
|
|
579
|
-
setMcpDraft(result.draft);
|
|
580
|
-
if (result.mode)
|
|
581
|
-
setMode(result.mode);
|
|
582
|
-
showWizardMessage(result.message);
|
|
583
|
-
}
|
|
584
|
-
async function selectMcpAction(action) {
|
|
585
|
-
const result = selectMcpActionResult(settings, selectedMcpName, action);
|
|
586
|
-
if (result.settingsPatch)
|
|
587
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
588
|
-
if ('selectedName' in result)
|
|
589
|
-
setSelectedMcpName(result.selectedName);
|
|
590
|
-
if (result.mode)
|
|
591
|
-
setMode(result.mode);
|
|
592
|
-
showWizardMessage(result.message);
|
|
593
|
-
}
|
|
594
|
-
async function finishMcpCustom(keyValue) {
|
|
595
|
-
const result = finishMcpCustomResult(settings, mcpDraft, keyValue);
|
|
596
|
-
if (result.settingsPatch)
|
|
597
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
598
|
-
if (result.clearDraft)
|
|
599
|
-
setMcpDraft({});
|
|
600
|
-
if (result.mode)
|
|
601
|
-
setMode(result.mode);
|
|
602
|
-
showWizardMessage(result.message);
|
|
603
|
-
}
|
|
604
|
-
async function setMcpServerKey(keyValue) {
|
|
605
|
-
const result = setMcpServerKeyResult(settings, selectedMcpName, keyValue);
|
|
606
|
-
if (result.settingsPatch)
|
|
607
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
608
|
-
if ('selectedName' in result)
|
|
609
|
-
setSelectedMcpName(result.selectedName);
|
|
610
|
-
if (result.mode)
|
|
611
|
-
setMode(result.mode);
|
|
612
|
-
showWizardMessage(result.message);
|
|
613
|
-
}
|
|
614
|
-
// --- Skills wizard handlers (mirror the provider/LSP/MCP wizards) ---
|
|
615
|
-
async function selectSkill(name) {
|
|
616
|
-
const result = selectSkillResult(skills, name);
|
|
617
|
-
if (result.clearDraft)
|
|
618
|
-
setSkillDraft({});
|
|
619
|
-
if ('selectedName' in result)
|
|
620
|
-
setSelectedSkillName(result.selectedName);
|
|
621
|
-
if (result.mode)
|
|
622
|
-
setMode(result.mode);
|
|
623
|
-
showWizardMessage(result.message);
|
|
624
|
-
}
|
|
625
|
-
async function selectSkillAction(action) {
|
|
626
|
-
const result = selectSkillActionResult(settings, skills, selectedSkillName, action);
|
|
627
|
-
if (result.settingsPatch)
|
|
628
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
629
|
-
if ('selectedName' in result)
|
|
630
|
-
setSelectedSkillName(result.selectedName);
|
|
631
|
-
if (result.mode)
|
|
632
|
-
setMode(result.mode);
|
|
633
|
-
if (result.validate && result.skill) {
|
|
634
|
-
const { loadSkill } = await import('../../skills/SkillLoader.js');
|
|
635
|
-
try {
|
|
636
|
-
const loaded = await loadSkill(result.skill.dir, 'global');
|
|
637
|
-
showWizardMessage(loaded ? `Valid: ${loaded.name}` : 'No SKILL.md found');
|
|
638
|
-
}
|
|
639
|
-
catch (error) {
|
|
640
|
-
const text = error instanceof Error ? error.message : String(error);
|
|
641
|
-
showWizardMessage(`Invalid skill: ${text}`);
|
|
642
|
-
}
|
|
643
|
-
return;
|
|
644
|
-
}
|
|
645
|
-
showWizardMessage(result.message);
|
|
646
|
-
}
|
|
647
|
-
async function captureSkillName(value) {
|
|
648
|
-
const dirName = toSkillDirName(value);
|
|
649
|
-
if (!dirName) {
|
|
650
|
-
setMessages(m => [...m, { role: 'system', text: 'Skill name must contain at least one letter or number. Try again, or press ESC to cancel.' }]);
|
|
651
|
-
return;
|
|
652
|
-
}
|
|
653
|
-
const registry = await loadSkillRegistry();
|
|
654
|
-
if (registry.skills.has(dirName)) {
|
|
655
|
-
setMessages(m => [...m, { role: 'system', text: `A skill named "${dirName}" already exists. Pick another name, or press ESC to cancel.` }]);
|
|
656
|
-
return;
|
|
657
|
-
}
|
|
658
|
-
setSkillDraft(d => ({ ...d, name: dirName }));
|
|
659
|
-
setMode('skillsAddDescription');
|
|
660
|
-
setMessages(m => [...m, { role: 'system', text: `Describe what "${dirName}" should do. This is the work the LLM will expand into the skill body.` }]);
|
|
661
|
-
}
|
|
662
|
-
async function captureSkillDescription(value) {
|
|
663
|
-
const result = captureSkillDescriptionResult(value, skillDraft.name);
|
|
664
|
-
if (result.message) {
|
|
665
|
-
const message = result.message;
|
|
666
|
-
setMessages(m => [...m, { role: 'system', text: message }]);
|
|
667
|
-
}
|
|
668
|
-
if (result.mode === 'chat')
|
|
669
|
-
setMode('chat');
|
|
670
|
-
if (result.clearDraft)
|
|
671
|
-
setSkillDraft({});
|
|
672
|
-
if (result.description && result.draftName) {
|
|
673
|
-
const name = result.draftName;
|
|
674
|
-
const description = result.description;
|
|
675
|
-
setBusyLabel(result.busyLabel ?? 'Creating skill');
|
|
676
|
-
setBusyWithHeartbeat(true);
|
|
332
|
+
// Wizard/picker submit dispatch lives in one table-driven module with a
|
|
333
|
+
// shared settings-patch applier (CR-006). Rebuilt every render so handlers
|
|
334
|
+
// see current state without new React state.
|
|
335
|
+
const wizard = createWizardDispatch({
|
|
336
|
+
settings, skills, modelProviderFilter, selectedProviderName, selectedSkillName, selectedLspName, selectedMcpName,
|
|
337
|
+
sessions, selectedSessionId,
|
|
338
|
+
providerDraft, lspDraft, mcpDraft, skillDraft,
|
|
339
|
+
setMode, setSettings,
|
|
340
|
+
setSelectedProviderName, setSelectedSkillName, setSelectedLspName, setSelectedMcpName, setSelectedSessionId,
|
|
341
|
+
resumeSessionById: sessionLifecycle.resumeSessionById,
|
|
342
|
+
forkSessionById: sessionLifecycle.forkSessionById,
|
|
343
|
+
setModelProviderFilter, setProviderDraft, setSkillDraft, setLspDraft, setMcpDraft, setDiscoveredModels, setSuggestedModels,
|
|
344
|
+
showMessage: showWizardMessage, refreshSkills,
|
|
345
|
+
setBusyLabel, setBusy: setBusyWithHeartbeat,
|
|
346
|
+
idleBusyLabel: thinkingLabelForSettings(settings),
|
|
347
|
+
});
|
|
348
|
+
async function submit(value) {
|
|
349
|
+
if (settingsError) {
|
|
677
350
|
try {
|
|
678
|
-
const
|
|
679
|
-
|
|
680
|
-
|
|
351
|
+
const repaired = await readSettings();
|
|
352
|
+
setSettings(repaired);
|
|
353
|
+
setSettingsError(undefined);
|
|
681
354
|
}
|
|
682
355
|
catch (error) {
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
356
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
357
|
+
setSettingsError(message);
|
|
358
|
+
if (!/^\/(?:settings\s+(?:open|edit)|help|exit|quit)\b/i.test(value.trim())) {
|
|
359
|
+
setMessages(messages => [...messages, { role: 'system', text: `${message}\nRepair settings, then retry. /settings open, /help, and /exit remain available.` }]);
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
688
362
|
}
|
|
689
363
|
}
|
|
690
|
-
}
|
|
691
|
-
async function submit(value) {
|
|
692
364
|
if (busy) {
|
|
693
365
|
if (mode === 'chat')
|
|
694
366
|
queueFollowUp(value);
|
|
695
367
|
return;
|
|
696
368
|
}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
if (result.message) {
|
|
716
|
-
const message = result.message;
|
|
717
|
-
setMessages(m => [...m, { role: 'system', text: message }]);
|
|
718
|
-
}
|
|
719
|
-
if (result.selectedName === undefined)
|
|
720
|
-
setSelectedSkillName(undefined);
|
|
721
|
-
if (result.mode === 'chat')
|
|
722
|
-
setMode('chat');
|
|
723
|
-
if (result.removedDir)
|
|
724
|
-
await fs.remove(result.removedDir);
|
|
725
|
-
if (result.settingsPatch)
|
|
726
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
727
|
-
if (result.removedDir)
|
|
728
|
-
await refreshSkills();
|
|
729
|
-
return;
|
|
730
|
-
}
|
|
731
|
-
if (mode === 'provider') {
|
|
732
|
-
await selectProvider(value);
|
|
733
|
-
return;
|
|
734
|
-
}
|
|
735
|
-
if (mode === 'providerAction') {
|
|
736
|
-
await selectProviderAction(value);
|
|
737
|
-
return;
|
|
738
|
-
}
|
|
739
|
-
if (mode === 'providerAddPreset') {
|
|
740
|
-
await selectPreset(value);
|
|
741
|
-
return;
|
|
742
|
-
}
|
|
743
|
-
if (mode === 'model') {
|
|
744
|
-
await selectModel(value);
|
|
745
|
-
return;
|
|
746
|
-
}
|
|
747
|
-
if (mode === 'providerAddName') {
|
|
748
|
-
const result = captureProviderName(settings, value);
|
|
749
|
-
if (result.message) {
|
|
750
|
-
showWizardMessage(result.message);
|
|
751
|
-
return;
|
|
752
|
-
}
|
|
753
|
-
if (result.draft)
|
|
754
|
-
setProviderDraft({ name: result.draft.name });
|
|
755
|
-
if (result.nextMode)
|
|
756
|
-
setMode(result.nextMode);
|
|
757
|
-
showWizardMessage(result.systemMessage);
|
|
758
|
-
return;
|
|
759
|
-
}
|
|
760
|
-
if (mode === 'providerAddUrl') {
|
|
761
|
-
const result = captureProviderUrl(value);
|
|
762
|
-
if (result.message) {
|
|
763
|
-
showWizardMessage(result.message);
|
|
764
|
-
return;
|
|
765
|
-
}
|
|
766
|
-
if (result.draft)
|
|
767
|
-
setProviderDraft(draft => ({ ...draft, ...result.draft }));
|
|
768
|
-
if (result.nextMode)
|
|
769
|
-
setMode(result.nextMode);
|
|
770
|
-
showWizardMessage(result.systemMessage);
|
|
771
|
-
return;
|
|
772
|
-
}
|
|
773
|
-
if (mode === 'providerAddKey') {
|
|
774
|
-
setProviderDraft(draft => ({ ...draft, ...(value.trim() ? { key: value.trim() } : {}) }));
|
|
775
|
-
setMode('providerAddModels');
|
|
776
|
-
setMessages(m => [...m, { role: 'system', text: 'Comma-separated model names? Example: llama3.1, qwen2.5-coder, gpt-4o' }]);
|
|
777
|
-
return;
|
|
778
|
-
}
|
|
779
|
-
if (mode === 'providerAddModels') {
|
|
780
|
-
await finishProviderAdd(value);
|
|
781
|
-
return;
|
|
782
|
-
}
|
|
783
|
-
if (mode === 'providerAppendModels') {
|
|
784
|
-
await appendModelsToProvider(value);
|
|
785
|
-
return;
|
|
786
|
-
}
|
|
787
|
-
if (mode === 'providerSetKey') {
|
|
788
|
-
const result = providerSetKey(settings, selectedProviderName, value);
|
|
789
|
-
if (!result.provider) {
|
|
790
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
791
|
-
setMode('chat');
|
|
792
|
-
return;
|
|
793
|
-
}
|
|
794
|
-
if (!result.settingsPatch) {
|
|
795
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
796
|
-
return;
|
|
797
|
-
}
|
|
798
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
799
|
-
setSelectedProviderName(undefined);
|
|
800
|
-
setMode('chat');
|
|
801
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
if (mode === 'providerRemoveModels') {
|
|
805
|
-
const result = providerRemoveModels(settings, selectedProviderName, value);
|
|
806
|
-
if (!result.provider) {
|
|
807
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
808
|
-
setMode('chat');
|
|
809
|
-
return;
|
|
810
|
-
}
|
|
811
|
-
if (!result.settingsPatch) {
|
|
812
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
813
|
-
return;
|
|
814
|
-
}
|
|
815
|
-
const next = await updateSettings(result.settingsPatch);
|
|
816
|
-
setSettings(next);
|
|
817
|
-
setSelectedProviderName(undefined);
|
|
818
|
-
setMode('chat');
|
|
819
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
820
|
-
return;
|
|
821
|
-
}
|
|
822
|
-
if (mode === 'providerConfirmRemove') {
|
|
823
|
-
const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
|
|
824
|
-
if (!provider) {
|
|
825
|
-
setMessages(m => [...m, { role: 'system', text: 'No provider selected.' }]);
|
|
826
|
-
setMode('chat');
|
|
827
|
-
return;
|
|
828
|
-
}
|
|
829
|
-
if (!isYesConfirmation(value)) {
|
|
830
|
-
setMessages(m => [...m, { role: 'system', text: 'Cancelled. Provider not removed.' }]);
|
|
831
|
-
setSelectedProviderName(undefined);
|
|
832
|
-
setMode('chat');
|
|
833
|
-
return;
|
|
834
|
-
}
|
|
835
|
-
const result = providerRemove(settings, selectedProviderName);
|
|
836
|
-
const next = await updateSettings(result.settingsPatch ?? {});
|
|
837
|
-
setSettings(next);
|
|
838
|
-
setSelectedProviderName(undefined);
|
|
839
|
-
setMode('chat');
|
|
840
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
841
|
-
return;
|
|
842
|
-
}
|
|
843
|
-
if (mode === 'lsp') {
|
|
844
|
-
await selectLspServer(value);
|
|
845
|
-
return;
|
|
846
|
-
}
|
|
847
|
-
if (mode === 'lspAction') {
|
|
848
|
-
await selectLspAction(value);
|
|
849
|
-
return;
|
|
850
|
-
}
|
|
851
|
-
if (mode === 'lspAddPreset') {
|
|
852
|
-
await selectLspPreset(value);
|
|
853
|
-
return;
|
|
854
|
-
}
|
|
855
|
-
if (mode === 'lspAddName') {
|
|
856
|
-
const result = captureLspName(settings, value);
|
|
857
|
-
if (result.message) {
|
|
858
|
-
showWizardMessage(result.message);
|
|
859
|
-
return;
|
|
860
|
-
}
|
|
861
|
-
if (result.draft)
|
|
862
|
-
setLspDraft({ name: result.draft.name });
|
|
863
|
-
if (result.nextMode)
|
|
864
|
-
setMode(result.nextMode);
|
|
865
|
-
showWizardMessage(result.systemMessage);
|
|
866
|
-
return;
|
|
867
|
-
}
|
|
868
|
-
if (mode === 'lspAddCommand') {
|
|
869
|
-
await finishLspCustom(value);
|
|
870
|
-
return;
|
|
871
|
-
}
|
|
872
|
-
if (mode === 'lspConfirmRemove') {
|
|
873
|
-
if (!selectedLspName) {
|
|
874
|
-
setMode('chat');
|
|
875
|
-
return;
|
|
876
|
-
}
|
|
877
|
-
if (!isYesConfirmation(value)) {
|
|
878
|
-
setMessages(m => [...m, { role: 'system', text: 'Cancelled. LSP server not removed.' }]);
|
|
879
|
-
setSelectedLspName(undefined);
|
|
880
|
-
setMode('chat');
|
|
881
|
-
return;
|
|
882
|
-
}
|
|
883
|
-
const next = await updateSettings({ lspServers: removeLspServer(settings, selectedLspName) });
|
|
884
|
-
setSettings(next);
|
|
885
|
-
setMessages(m => [...m, { role: 'system', text: `Removed LSP server ${selectedLspName}.` }]);
|
|
886
|
-
setSelectedLspName(undefined);
|
|
887
|
-
setMode('chat');
|
|
888
|
-
return;
|
|
889
|
-
}
|
|
890
|
-
if (mode === 'mcp') {
|
|
891
|
-
await selectMcpServer(value);
|
|
892
|
-
return;
|
|
893
|
-
}
|
|
894
|
-
if (mode === 'mcpAction') {
|
|
895
|
-
await selectMcpAction(value);
|
|
896
|
-
return;
|
|
897
|
-
}
|
|
898
|
-
if (mode === 'mcpAddPreset') {
|
|
899
|
-
await selectMcpPreset(value);
|
|
900
|
-
return;
|
|
901
|
-
}
|
|
902
|
-
if (mode === 'mcpAddName') {
|
|
903
|
-
const result = captureMcpName(settings, value);
|
|
904
|
-
if (result.message) {
|
|
905
|
-
showWizardMessage(result.message);
|
|
906
|
-
return;
|
|
907
|
-
}
|
|
908
|
-
if (result.draft)
|
|
909
|
-
setMcpDraft({ name: result.draft.name });
|
|
910
|
-
if (result.nextMode)
|
|
911
|
-
setMode(result.nextMode);
|
|
912
|
-
showWizardMessage(result.systemMessage);
|
|
913
|
-
return;
|
|
914
|
-
}
|
|
915
|
-
if (mode === 'mcpAddTransport') {
|
|
916
|
-
const result = captureMcpTransport(value);
|
|
917
|
-
if (result.message) {
|
|
918
|
-
showWizardMessage(result.message);
|
|
919
|
-
return;
|
|
920
|
-
}
|
|
921
|
-
if (result.draft)
|
|
922
|
-
setMcpDraft(draft => ({ ...draft, ...result.draft }));
|
|
923
|
-
if (result.nextMode)
|
|
924
|
-
setMode(result.nextMode);
|
|
925
|
-
showWizardMessage(result.systemMessage);
|
|
926
|
-
return;
|
|
927
|
-
}
|
|
928
|
-
if (mode === 'mcpAddUrl') {
|
|
929
|
-
const result = captureMcpUrl(value);
|
|
930
|
-
if (result.message) {
|
|
931
|
-
showWizardMessage(result.message);
|
|
932
|
-
return;
|
|
369
|
+
const providerEffects = transitionProviderField({ mode, value, settings, draft: providerDraft });
|
|
370
|
+
if (providerEffects) {
|
|
371
|
+
for (const effect of providerEffects) {
|
|
372
|
+
if (effect.type === 'message')
|
|
373
|
+
showWizardMessage(effect.text);
|
|
374
|
+
else if (effect.type === 'mode')
|
|
375
|
+
setMode(effect.mode);
|
|
376
|
+
else if (effect.type === 'provider-draft') {
|
|
377
|
+
if (effect.replace)
|
|
378
|
+
setProviderDraft(effect.patch);
|
|
379
|
+
else
|
|
380
|
+
setProviderDraft(draft => ({ ...draft, ...effect.patch }));
|
|
381
|
+
}
|
|
382
|
+
else if (effect.type === 'discover-provider-models') {
|
|
383
|
+
// The draft patch above is still pending React state, so discovery
|
|
384
|
+
// receives the merged draft explicitly (same pattern as MCP stdio).
|
|
385
|
+
await wizard.discoverProviderModelsForDraft(effect.draft);
|
|
386
|
+
}
|
|
933
387
|
}
|
|
934
|
-
if (result.draft)
|
|
935
|
-
setMcpDraft(draft => ({ ...draft, ...result.draft }));
|
|
936
|
-
if (result.nextMode)
|
|
937
|
-
setMode(result.nextMode);
|
|
938
|
-
showWizardMessage(result.systemMessage);
|
|
939
388
|
return;
|
|
940
389
|
}
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
390
|
+
const mcpEffects = transitionMcpField({ mode, value, settings, draft: mcpDraft });
|
|
391
|
+
if (mcpEffects) {
|
|
392
|
+
for (const effect of mcpEffects) {
|
|
393
|
+
if (effect.type === 'message')
|
|
394
|
+
showWizardMessage(effect.text);
|
|
395
|
+
else if (effect.type === 'mode')
|
|
396
|
+
setMode(effect.mode);
|
|
397
|
+
else if (effect.type === 'mcp-draft')
|
|
398
|
+
setMcpDraft(draft => ({ ...draft, ...effect.patch }));
|
|
399
|
+
else if (effect.type === 'finish-mcp-stdio')
|
|
400
|
+
await wizard.finishMcpCustom(undefined, effect.draft);
|
|
946
401
|
}
|
|
947
|
-
if (result.draft)
|
|
948
|
-
setMcpDraft(draft => ({ ...draft, ...result.draft }));
|
|
949
|
-
if (result.nextMode)
|
|
950
|
-
setMode(result.nextMode);
|
|
951
|
-
showWizardMessage(result.systemMessage);
|
|
952
|
-
return;
|
|
953
|
-
}
|
|
954
|
-
if (mode === 'mcpAddKey') {
|
|
955
|
-
await finishMcpCustom(value);
|
|
956
|
-
return;
|
|
957
|
-
}
|
|
958
|
-
if (mode === 'mcpSetKey') {
|
|
959
|
-
await setMcpServerKey(value);
|
|
960
402
|
return;
|
|
961
403
|
}
|
|
962
|
-
if (mode
|
|
963
|
-
if (!selectedMcpName) {
|
|
964
|
-
setMode('chat');
|
|
965
|
-
return;
|
|
966
|
-
}
|
|
967
|
-
if (!isYesConfirmation(value)) {
|
|
968
|
-
setMessages(m => [...m, { role: 'system', text: 'Cancelled. MCP server not removed.' }]);
|
|
969
|
-
setSelectedMcpName(undefined);
|
|
970
|
-
setMode('chat');
|
|
971
|
-
return;
|
|
972
|
-
}
|
|
973
|
-
const next = await updateSettings({ mcpServers: removeMcpServer(settings, selectedMcpName) });
|
|
974
|
-
setSettings(next);
|
|
975
|
-
setMessages(m => [...m, { role: 'system', text: `Removed MCP server ${selectedMcpName}.` }]);
|
|
976
|
-
setSelectedMcpName(undefined);
|
|
977
|
-
setMode('chat');
|
|
404
|
+
if (await wizard.dispatch(mode, value))
|
|
978
405
|
return;
|
|
979
|
-
}
|
|
980
406
|
const invokedSkill = skillInvocation(value);
|
|
981
407
|
if (invokedSkill) {
|
|
982
408
|
const argumentText = invokedSkill.args ? `\nUser-provided skill arguments: ${invokedSkill.args}` : '';
|
|
@@ -995,12 +421,17 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
995
421
|
lastAssistantTextRef.current = '';
|
|
996
422
|
setLiveMessagesState(() => []);
|
|
997
423
|
setMessages([{ role: 'system', text: 'Started fresh. The fog parts.' }]);
|
|
998
|
-
await startNewSession('Started a new session.');
|
|
424
|
+
await sessionLifecycle.startNewSession('Started a new session.');
|
|
425
|
+
},
|
|
426
|
+
resumeSession: noSession ? undefined : async (id) => {
|
|
427
|
+
if (id)
|
|
428
|
+
await sessionLifecycle.resumeSessionById(id);
|
|
429
|
+
else
|
|
430
|
+
await openSessionPicker();
|
|
999
431
|
},
|
|
1000
|
-
resumeSession: resumeLatestSession,
|
|
1001
432
|
sessionInfo: () => sessionRef.current ? formatSession(sessionRef.current) : 'Session persistence is off.',
|
|
1002
433
|
compactConversation,
|
|
1003
|
-
runAgentTurn: (prompt, displayValue) => doAgentTurn(prompt, displayValue),
|
|
434
|
+
runAgentTurn: (prompt, displayValue, options) => doAgentTurn(prompt, displayValue, options),
|
|
1004
435
|
refreshContextFiles: async () => {
|
|
1005
436
|
const files = await readContextFiles().catch(() => contextFiles);
|
|
1006
437
|
setContextFiles(files);
|
|
@@ -1012,7 +443,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1012
443
|
setSettings(next);
|
|
1013
444
|
return next;
|
|
1014
445
|
},
|
|
1015
|
-
getContextReport:
|
|
446
|
+
getContextReport: () => buildContextReport({ sessionStart: sessionStartRef.current, contextFiles, conversation: conversationRef.current }),
|
|
1016
447
|
};
|
|
1017
448
|
let result;
|
|
1018
449
|
try {
|
|
@@ -1023,17 +454,56 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1023
454
|
setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
|
|
1024
455
|
return;
|
|
1025
456
|
}
|
|
1026
|
-
if (result === 'exit')
|
|
457
|
+
if (result === 'exit') {
|
|
458
|
+
await teardownBackgroundProcesses().catch(showPersistenceWarning);
|
|
459
|
+
await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
|
|
460
|
+
if (llmLogRef.current)
|
|
461
|
+
await endLlmLog(llmLogRef.current).catch(showPersistenceWarning);
|
|
1027
462
|
return exit();
|
|
463
|
+
}
|
|
1028
464
|
if (result === 'handled') {
|
|
1029
465
|
if (value === '/clear') {
|
|
1030
466
|
loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
|
|
1031
467
|
}
|
|
1032
468
|
return;
|
|
1033
469
|
}
|
|
1034
|
-
await
|
|
470
|
+
const prepared = await prepareUserInput(value);
|
|
471
|
+
if (!prepared)
|
|
472
|
+
return;
|
|
473
|
+
await doAgentTurn(prepared.value, prepared.displayValue, prepared.options);
|
|
1035
474
|
}
|
|
1036
|
-
|
|
475
|
+
// F03: resolve @image mentions in a prompt the user typed into attachments and
|
|
476
|
+
// gate them on the active provider's explicit capability before any model call.
|
|
477
|
+
// Applied only to genuine user input (direct chat and queued follow-ups), never
|
|
478
|
+
// to synthetic control prompts (/init, /fleet, skill invocations). Resolution
|
|
479
|
+
// errors and capability rejections surface an actionable system message and
|
|
480
|
+
// return undefined instead of starting a turn.
|
|
481
|
+
async function prepareUserInput(value) {
|
|
482
|
+
let resolved;
|
|
483
|
+
try {
|
|
484
|
+
resolved = await resolveImageAttachments(value);
|
|
485
|
+
}
|
|
486
|
+
catch (error) {
|
|
487
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
488
|
+
setMessages(m => [...m, { role: 'system', text }]);
|
|
489
|
+
return undefined;
|
|
490
|
+
}
|
|
491
|
+
const blessed = await resolveReadBlessings(resolved.text);
|
|
492
|
+
if (resolved.attachments.length === 0 && blessed.blessedPaths.length === 0)
|
|
493
|
+
return { value, options: {} };
|
|
494
|
+
const gateError = imageCapabilityError(activeProvider(settings));
|
|
495
|
+
if (resolved.attachments.length > 0 && gateError) {
|
|
496
|
+
setMessages(m => [...m, { role: 'system', text: gateError }]);
|
|
497
|
+
return undefined;
|
|
498
|
+
}
|
|
499
|
+
const displayValue = [resolved.text, ...resolved.attachments.map(imageAttachmentLine)].filter(Boolean).join('\n');
|
|
500
|
+
return {
|
|
501
|
+
value: resolved.text || IMAGE_ONLY_PROMPT_TEXT,
|
|
502
|
+
displayValue,
|
|
503
|
+
options: { attachments: resolved.attachments, blessedPaths: blessed.blessedPaths },
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
async function doAgentTurn(value, displayValue, turnOptions = {}) {
|
|
1037
507
|
setDebugLogs([]);
|
|
1038
508
|
// When every task is already completed, start the new turn with a clean
|
|
1039
509
|
// slate: the task bar clears (nothing shown for simple questions) and the
|
|
@@ -1044,17 +514,20 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1044
514
|
setTaskBarPadding(0);
|
|
1045
515
|
await clearTasksFromStore().catch(() => undefined);
|
|
1046
516
|
}
|
|
1047
|
-
await runSingleAgentTurn(value, displayValue);
|
|
517
|
+
await runSingleAgentTurn(value, displayValue, turnOptions);
|
|
1048
518
|
while (followUpQueueRef.current.length > 0) {
|
|
1049
519
|
const next = followUpQueueRef.current[0];
|
|
1050
520
|
followUpQueueRef.current = followUpQueueRef.current.slice(1);
|
|
1051
521
|
setQueuedFollowUps(followUpQueueRef.current);
|
|
1052
522
|
setMessages(m => [...m, { role: 'system', text: `Running queued follow-up: ${next}` }]);
|
|
1053
|
-
await
|
|
523
|
+
const preparedFollowUp = await prepareUserInput(next);
|
|
524
|
+
if (!preparedFollowUp)
|
|
525
|
+
continue;
|
|
526
|
+
await runSingleAgentTurn(preparedFollowUp.value, preparedFollowUp.displayValue, preparedFollowUp.options);
|
|
1054
527
|
}
|
|
1055
528
|
}
|
|
1056
|
-
async function runSingleAgentTurn(value, displayValue) {
|
|
1057
|
-
const sessionRecorder =
|
|
529
|
+
async function runSingleAgentTurn(value, displayValue, turnOptions = {}) {
|
|
530
|
+
const sessionRecorder = sessionRecorderRef.current;
|
|
1058
531
|
const finalizeMessage = (msg) => {
|
|
1059
532
|
if (msg.hidden)
|
|
1060
533
|
return;
|
|
@@ -1110,7 +583,9 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1110
583
|
onTasksChanged: () => { loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined); },
|
|
1111
584
|
contextFileSignatures: contextFileSignaturesRef.current,
|
|
1112
585
|
log: llmLogRef.current,
|
|
1113
|
-
}, 0, false, false, { start: sessionStartRef.current, cwd: process.cwd() });
|
|
586
|
+
}, 0, false, false, { start: sessionStartRef.current, cwd: process.cwd() }, undefined, turnOptions);
|
|
587
|
+
await sessionRecorder.flush().catch(showPersistenceWarning);
|
|
588
|
+
await llmLogRef.current?.writer?.flush().catch(showPersistenceWarning);
|
|
1114
589
|
}
|
|
1115
590
|
const visible = messages.filter(message => !message.hidden);
|
|
1116
591
|
const activeLiveMessages = liveMessages.filter(message => !message.hidden);
|
|
@@ -1126,26 +601,17 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1126
601
|
'Start with simple chat, then teach haze your habits with skills:',
|
|
1127
602
|
'/skills — add, enable/disable, validate, or remove Markdown skills.',
|
|
1128
603
|
'',
|
|
604
|
+
startupInputTips(),
|
|
605
|
+
'',
|
|
1129
606
|
'The most adaptive workflow is the one you shape as you go.',
|
|
1130
607
|
'',
|
|
1131
608
|
'Guardrails are light: haze lets the LLM work from the terminal almost like you,',
|
|
1132
609
|
'while trying to stay scoped to this project.',
|
|
1133
610
|
].join('\n');
|
|
1134
611
|
const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
|
|
1135
|
-
const
|
|
1136
|
-
const
|
|
1137
|
-
const
|
|
1138
|
-
const fallbackTokens = estimateConversationTokens(allDisplayMessages);
|
|
1139
|
-
const estimatedLogicalInput = tokenUsage.logicalInputEstimate || fallbackTokens.input || 0;
|
|
1140
|
-
const providerInput = tokenUsage.inputTokens;
|
|
1141
|
-
const effectiveInput = providerInput == null ? estimatedLogicalInput : Math.max(providerInput, estimatedLogicalInput);
|
|
1142
|
-
const effectiveOutput = tokenUsage.outputTokens ?? (fallbackTokens.output || 0);
|
|
1143
|
-
const inputEstimated = providerInput == null || effectiveInput !== providerInput;
|
|
1144
|
-
const outputEstimated = tokenUsage.outputTokens == null;
|
|
1145
|
-
const enabledSkills = skills.filter(skill => isSkillEnabled(settings, skill.name));
|
|
1146
|
-
const statusDetailLabel = `${hazeMessages} haze message${hazeMessages === 1 ? '' : 's'} / ${toolsUsed} tool call${toolsUsed === 1 ? '' : 's'} / LLM ${inputEstimated ? '~' : ''}↑${formatTokenCount(effectiveInput)} ${outputEstimated ? '~' : ''}↓${formatTokenCount(effectiveOutput)} / ${enabledSkills.length} skill${enabledSkills.length === 1 ? '' : 's'}`;
|
|
1147
|
-
const hasTokenBreakdown = tokenUsage.systemPrompt > 0 || tokenUsage.messages > 0 || tokenUsage.toolSchemas > 0 || effectiveInput > 0 || effectiveOutput > 0;
|
|
1148
|
-
const inputSuggestions = inputSuggestionsForState({ mode, settings, skills, selectedProviderName, modelProviderFilter, selectedSkillName, selectedLspName, selectedMcpName });
|
|
612
|
+
const enabledSkillCount = new Set(skills.filter(skill => isSkillEnabled(settings, skill.name, skill.source)).map(skill => skill.name)).size;
|
|
613
|
+
const metrics = statusBarMetrics({ messages: [...messages, ...liveMessages], tokenUsage, enabledSkillCount, backgroundProcessCount: backgroundCount });
|
|
614
|
+
const inputSuggestions = inputSuggestionsForState({ mode, settings, skills, sessions, selectedProviderName, modelProviderFilter, providerDraftName: providerDraft.name, discoveredModels, suggestedModels, selectedSkillName, selectedLspName, selectedMcpName });
|
|
1149
615
|
const staticItems = [
|
|
1150
616
|
{ kind: 'header', key: `header-${activeModelName}`, subtitle: headerSubtitle },
|
|
1151
617
|
...transcriptItems.map(item => ({ kind: 'message', ...item })),
|
|
@@ -1153,7 +619,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1153
619
|
const busyElapsed = busyElapsedLabel(turnStartedAtRef.current);
|
|
1154
620
|
return _jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
|
|
1155
621
|
? _jsx(Header, { subtitle: item.subtitle, version: version }, item.key)
|
|
1156
|
-
: _jsx(MessageView, { message: item.message, width: width }, item.key) }), streamingItems.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, children: streamingItems.map((message, index) => _jsx(MessageView, { message: message, width: width }, messageKey(message, index))) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }), queuedFollowUps.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: [_jsx(Text, { color: theme.muted, children: "Queued follow-ups:" }), queuedFollowUps.map((item, index) => _jsxs(Text, { color: theme.muted, dimColor: true, children: [" ", index + 1, ". ", item] }, `${index}-${item}`))] }), visibleTasks.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: _jsx(TaskBar, { tasks: visibleTasks, width: width, expanded: tasksExpanded, padding: taskBarPadding }) }), busy &&
|
|
622
|
+
: _jsx(MessageView, { message: item.message, width: width }, item.key) }), streamingItems.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, children: streamingItems.map((message, index) => _jsx(MessageView, { message: message, width: width }, messageKey(message, index))) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }), queuedFollowUps.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: [_jsx(Text, { color: theme.muted, children: "Queued follow-ups:" }), queuedFollowUps.map((item, index) => _jsxs(Text, { color: theme.muted, dimColor: true, children: [" ", index + 1, ". ", item] }, `${index}-${item}`))] }), visibleTasks.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: _jsx(TaskBar, { tasks: visibleTasks, width: width, expanded: tasksExpanded, padding: taskBarPadding }) }), busy && _jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [_jsx(Box, { children: _jsxs(Text, { children: [_jsxs(Text, { color: theme.orange, bold: true, children: [_jsx(Spinner, { type: "dots" }), " ", busyLabel, busyElapsed ? _jsxs(Text, { color: theme.muted, dimColor: true, children: [" \u00B7 ", busyElapsed] }) : null] }), _jsx(Text, { color: theme.muted, dimColor: true, children: " \u00B7 type to queue follow-up \u00B7 esc to interrupt" })] }) }), showingTip && (_jsx(Box, { children: _jsxs(Text, { color: theme.muted, children: [_jsx(Text, { bold: true, children: "Tip:" }), " ", TIPS[tipIndex] ?? ''] }) }))] }), _jsx(Box, { borderStyle: "round", borderColor: theme.deepPurple, paddingX: 1, flexShrink: 0, children: _jsx(Box, { flexGrow: 1, minWidth: 0, children: _jsx(TextInput, { placeholder: placeholder, disabled: busy && mode !== 'chat', mask: MASKED_MODES.has(mode), historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: PICKER_MODES.has(mode) ? 'always' : 'slash', submitOnEmpty: SUBMIT_EMPTY_MODES.has(mode), width: Math.max(20, width - 4), getMentionSuggestions: fileMentionSuggestions, onHistoryAdd: persistInputHistory, onToggleTasks: () => {
|
|
1157
623
|
if (!tasksExpanded) {
|
|
1158
624
|
setTaskBarPadding(0);
|
|
1159
625
|
setTasksExpanded(true);
|
|
@@ -1169,14 +635,15 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1169
635
|
cancelThinking();
|
|
1170
636
|
else
|
|
1171
637
|
closeInputList();
|
|
1172
|
-
}, onSubmit: submit }) }) }), debug && hasTokenBreakdown && _jsxs(Box, { flexShrink: 0, flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: theme.muted, bold: true, children: ["Token usage ", inputEstimated || outputEstimated ? '(estimated)' : '(precise)'] }), _jsxs(Text, { color: theme.muted, children: [" in=", formatTokenCount(effectiveInput), " out=", formatTokenCount(effectiveOutput), tokenUsage.cacheReadTokens > 0 ? ` cached=${formatTokenCount(tokenUsage.cacheReadTokens)}` : '', tokenUsage.noCacheTokens > 0 ? ` uncached=${formatTokenCount(tokenUsage.noCacheTokens)}` : '', tokenUsage.cacheWriteTokens > 0 ? ` cache_write=${formatTokenCount(tokenUsage.cacheWriteTokens)}` : '', tokenUsage.reasoningTokens > 0 ? ` reasoning=${formatTokenCount(tokenUsage.reasoningTokens)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" logical=", formatTokenCount(tokenUsage.logicalInputEstimate), tokenUsage.effectiveNonCachedInput != null ? ` effective_non_cached=${formatTokenCount(tokenUsage.effectiveNonCachedInput)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" system=", formatTokenCount(tokenUsage.systemPrompt), " messages=", formatTokenCount(tokenUsage.messages), " tools=", formatTokenCount(tokenUsage.toolSchemas), " output=", formatTokenCount(tokenUsage.outputEstimate)] })] }), _jsxs(Box, { flexShrink: 0, justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", flexShrink: 1, minWidth: 0, children: [_jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-end", children: workspaceLabel }), _jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-end", children: statusDetailLabel })] }), _jsx(Box, { flexShrink: 0, marginLeft: 2, children: _jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-start", children: activeModelName }) })] })] });
|
|
638
|
+
}, onSubmit: submit }) }) }), debug && metrics.hasTokenBreakdown && _jsxs(Box, { flexShrink: 0, flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: theme.muted, bold: true, children: ["Token usage ", metrics.inputEstimated || metrics.outputEstimated ? '(estimated)' : '(precise)'] }), _jsxs(Text, { color: theme.muted, children: [" in=", formatTokenCount(metrics.effectiveInput), " out=", formatTokenCount(metrics.effectiveOutput), tokenUsage.cacheReadTokens > 0 ? ` cached=${formatTokenCount(tokenUsage.cacheReadTokens)}` : '', tokenUsage.noCacheTokens > 0 ? ` uncached=${formatTokenCount(tokenUsage.noCacheTokens)}` : '', tokenUsage.cacheWriteTokens > 0 ? ` cache_write=${formatTokenCount(tokenUsage.cacheWriteTokens)}` : '', tokenUsage.reasoningTokens > 0 ? ` reasoning=${formatTokenCount(tokenUsage.reasoningTokens)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" logical=", formatTokenCount(tokenUsage.logicalInputEstimate), tokenUsage.effectiveNonCachedInput != null ? ` effective_non_cached=${formatTokenCount(tokenUsage.effectiveNonCachedInput)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" system=", formatTokenCount(tokenUsage.systemPrompt), " messages=", formatTokenCount(tokenUsage.messages), " tools=", formatTokenCount(tokenUsage.toolSchemas), " output=", formatTokenCount(tokenUsage.outputEstimate)] })] }), _jsxs(Box, { flexShrink: 0, justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", flexShrink: 1, minWidth: 0, children: [_jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-end", children: workspaceLabel }), _jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-end", children: metrics.statusDetailLabel })] }), _jsx(Box, { flexShrink: 0, marginLeft: 2, children: _jsx(Text, { color: theme.muted, dimColor: true, wrap: "truncate-start", children: activeModelName }) })] })] });
|
|
1173
639
|
}
|
|
1174
640
|
export async function chatCommand(options = {}) {
|
|
1175
641
|
if (process.stdout.isTTY) {
|
|
1176
642
|
process.stdout.write('\u001B[2J\u001B[3J\u001B[H');
|
|
1177
643
|
}
|
|
1178
644
|
await clearTasksFromStore().catch(() => undefined);
|
|
1179
|
-
const app = render(_jsx(ChatScreen, { debug: options.debug, version: options.version, continueSession: options.continueSession, noSession: options.noSession }));
|
|
645
|
+
const app = render(_jsx(ChatScreen, { debug: options.debug, version: options.version, continueSession: options.continueSession, resumeSessionId: options.resumeSessionId, noSession: options.noSession }));
|
|
1180
646
|
await app.waitUntilExit();
|
|
647
|
+
await teardownBackgroundProcesses().catch(() => undefined);
|
|
1181
648
|
await clearTasksFromStore().catch(() => undefined);
|
|
1182
649
|
}
|