@denizokcu/haze 1.2.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +86 -1
- package/README.md +23 -10
- package/SECURITY.md +1 -1
- package/bin/haze.js +27 -7
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/BusyBar.d.ts +7 -0
- package/dist/cli/chat/BusyBar.js +8 -0
- package/dist/cli/chat/DynamicFrame.d.ts +37 -0
- package/dist/cli/chat/DynamicFrame.js +43 -0
- package/dist/cli/chat/busyIndicator.d.ts +3 -1
- package/dist/cli/chat/busyIndicator.js +11 -9
- package/dist/cli/chat/chatMetrics.d.ts +1 -1
- package/dist/cli/chat/chatMetrics.js +3 -3
- package/dist/cli/chat/inputSuggestions.js +4 -0
- package/dist/cli/chat/liveMessages.d.ts +36 -0
- package/dist/cli/chat/liveMessages.js +64 -0
- package/dist/cli/chat/liveRegion.js +1 -1
- package/dist/cli/chat/messages.js +27 -16
- package/dist/cli/chat/sessionLifecycle.d.ts +5 -2
- package/dist/cli/chat/sessionLifecycle.js +36 -4
- package/dist/cli/chat/sessionRecorder.d.ts +2 -1
- package/dist/cli/chat/sessionRecorder.js +8 -0
- package/dist/cli/chat/shutdown.d.ts +27 -0
- package/dist/cli/chat/shutdown.js +79 -0
- package/dist/cli/chat/terminalControl.d.ts +45 -0
- package/dist/cli/chat/terminalControl.js +107 -0
- package/dist/cli/chat/tips.js +1 -0
- package/dist/cli/chat/userInput.d.ts +43 -0
- package/dist/cli/chat/userInput.js +63 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +24 -1
- package/dist/cli/chat/wizard/types.d.ts +8 -1
- package/dist/cli/chat/wizardDispatch.js +1 -1
- package/dist/cli/commands/chat.js +277 -193
- package/dist/cli/commands/commandHelp.js +6 -0
- package/dist/cli/commands/commands.d.ts +8 -0
- package/dist/cli/commands/commands.js +13 -0
- package/dist/cli/commands/formatters.d.ts +1 -1
- package/dist/cli/commands/formatters.js +25 -3
- package/dist/cli/commands/logsCommand.js +21 -2
- package/dist/cli/commands/ndjsonSink.d.ts +12 -0
- package/dist/cli/commands/ndjsonSink.js +29 -0
- package/dist/cli/commands/reasoningCommand.d.ts +44 -0
- package/dist/cli/commands/reasoningCommand.js +79 -0
- package/dist/cli/commands/runCommand.d.ts +14 -0
- package/dist/cli/commands/runCommand.js +56 -22
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +3 -0
- package/dist/cli/commands/streaming/agentAttempt.js +2 -2
- package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
- package/dist/cli/commands/streaming/assistantSegments.js +1 -1
- package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
- package/dist/cli/commands/streaming/attemptOutcome.js +24 -9
- package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
- package/dist/cli/commands/streaming/attemptSetup.js +21 -7
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +14 -1
- package/dist/cli/commands/streaming/goalCheckpoint.js +4 -2
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +9 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +51 -10
- package/dist/cli/commands/streaming/prepareStep.d.ts +0 -3
- package/dist/cli/commands/streaming/prepareStep.js +14 -5
- package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
- package/dist/cli/commands/streaming/streamLoop.js +3 -0
- package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
- package/dist/cli/commands/streaming.d.ts +8 -3
- package/dist/cli/commands/streaming.js +46 -21
- package/dist/cli/commands/wizardFlow.d.ts +10 -0
- package/dist/cli/commands/wizardFlow.js +34 -5
- package/dist/cli/index.js +22 -2
- package/dist/config/contextFiles.d.ts +9 -0
- package/dist/config/contextFiles.js +21 -1
- package/dist/config/modelCatalog.d.ts +3 -0
- package/dist/config/modelCatalog.js +29 -0
- package/dist/config/modelDiscovery.js +68 -5
- package/dist/config/providerPresets.d.ts +1 -1
- package/dist/config/providerPresets.js +42 -3
- package/dist/config/settings.d.ts +14 -6
- package/dist/config/settings.js +16 -1
- package/dist/core/agent/budgets.d.ts +13 -17
- package/dist/core/agent/budgets.js +15 -19
- package/dist/core/agent/completionController.d.ts +14 -2
- package/dist/core/agent/completionController.js +48 -3
- package/dist/core/agent/events.d.ts +2 -1
- package/dist/core/agent/goalPolicy.d.ts +17 -0
- package/dist/core/agent/goalPolicy.js +53 -6
- package/dist/core/agent/projectPreflight.d.ts +2 -0
- package/dist/core/agent/projectPreflight.js +56 -0
- package/dist/core/agent/reasoningPolicy.d.ts +76 -10
- package/dist/core/agent/reasoningPolicy.js +72 -9
- package/dist/core/agent/toolCapabilities.d.ts +3 -3
- package/dist/core/agent/toolCapabilities.js +31 -7
- package/dist/core/agent/workState.d.ts +14 -4
- package/dist/core/agent/workState.js +229 -34
- package/dist/core/deadline.js +22 -24
- package/dist/core/providerContracts.d.ts +29 -0
- package/dist/core/providerContracts.js +1 -0
- package/dist/core/safety/secretPaths.js +10 -7
- package/dist/core/safety/shellClassifier.d.ts +2 -0
- package/dist/core/safety/shellClassifier.js +9 -1
- package/dist/core/session/sessionReport.d.ts +33 -0
- package/dist/core/session/sessionReport.js +121 -0
- package/dist/core/session/sessionSlimming.d.ts +2 -0
- package/dist/core/session/sessionSlimming.js +59 -4
- package/dist/core/session/sessionStore.d.ts +16 -8
- package/dist/core/session/sessionStore.js +71 -34
- package/dist/core/shellOutput/reducers/git.js +7 -2
- package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
- package/dist/core/shellOutput/reducers/validation.js +14 -1
- package/dist/core/shellOutput/registry.js +3 -2
- package/dist/core/subagent/contracts.d.ts +3 -18
- package/dist/core/subagent/executionProfiles.js +4 -4
- package/dist/core/tasks/taskStorage.js +8 -1
- package/dist/core/validation/outputParser.d.ts +6 -1
- package/dist/core/validation/outputParser.js +30 -2
- package/dist/llm/client.d.ts +6 -3
- package/dist/llm/client.js +28 -11
- package/dist/llm/hazeTools.d.ts +9161 -7135
- package/dist/llm/hazeTools.js +6 -462
- package/dist/llm/lsp/client.d.ts +7 -1
- package/dist/llm/lsp/client.js +58 -9
- package/dist/llm/lsp/pool.d.ts +11 -0
- package/dist/llm/lsp/pool.js +61 -4
- package/dist/llm/lsp/protocol.d.ts +6 -23
- package/dist/llm/lsp/requests.d.ts +54 -60
- package/dist/llm/lsp/requests.js +152 -28
- package/dist/llm/lsp/symbols.d.ts +16 -0
- package/dist/llm/lsp/symbols.js +70 -0
- package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
- package/dist/llm/lsp/workspaceEdit.js +117 -0
- package/dist/llm/lspTools.d.ts +7518 -2859
- package/dist/llm/lspTools.js +195 -110
- package/dist/llm/mcp.js +3 -0
- package/dist/llm/requestContext.d.ts +4 -3
- package/dist/llm/requestContext.js +9 -5
- package/dist/{core/subagent → llm}/subagentRunner.d.ts +13 -9
- package/dist/{core/subagent → llm}/subagentRunner.js +54 -49
- package/dist/llm/systemPrompt.d.ts +11 -1
- package/dist/llm/systemPrompt.js +4 -13
- package/dist/llm/tools/fetchTool.d.ts +34 -30
- package/dist/llm/tools/fileTools.d.ts +7768 -0
- package/dist/llm/tools/fileTools.js +510 -0
- package/dist/llm/tools/processTool.d.ts +34 -30
- package/dist/llm/tools/replaceInFiles.d.ts +105 -0
- package/dist/llm/tools/replaceInFiles.js +131 -0
- package/dist/llm/tools/shellTool.d.ts +34 -30
- package/dist/llm/tools/shellTool.js +8 -4
- package/dist/llm/tools/storedOutputTool.d.ts +4 -0
- package/dist/llm/tools/taskTool.d.ts +4 -0
- package/dist/llm/tools/toolContext.d.ts +3 -29
- package/dist/llm/tools/toolContext.js +56 -53
- package/dist/llm/tools/toolContextState.d.ts +40 -0
- package/dist/llm/tools/toolContextState.js +34 -0
- package/dist/llm/workerContext.d.ts +7 -0
- package/dist/llm/workerContext.js +18 -1
- package/dist/skills/SkillLoader.js +30 -4
- package/dist/skills/SkillRegistry.js +3 -3
- package/dist/skills/builder/SkillBuilder.js +3 -3
- package/dist/skills/confinement.d.ts +7 -0
- package/dist/skills/confinement.js +15 -0
- package/dist/ui/codeHighlight.js +4 -4
- package/dist/ui/components/MarkdownText.js +7 -8
- package/dist/ui/components/NativeIndicators.d.ts +15 -0
- package/dist/ui/components/NativeIndicators.js +32 -0
- package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
- package/dist/ui/components/StreamingMarkdownText.js +38 -0
- package/dist/ui/components/TextInput.d.ts +7 -2
- package/dist/ui/components/TextInput.js +103 -46
- package/dist/ui/components/WizardChoices.d.ts +18 -0
- package/dist/ui/components/WizardChoices.js +32 -0
- package/dist/ui/components/useInputSuggestions.js +18 -6
- package/dist/ui/inputBuffer.js +12 -6
- package/dist/ui/textGeometry.d.ts +14 -0
- package/dist/ui/textGeometry.js +31 -0
- package/dist/utils/buildInfo.js +29 -8
- package/dist/utils/fs.js +5 -1
- package/package.json +23 -22
- /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
- /package/dist/cli/{contextReport.js → contextReportCli.js} +0 -0
|
@@ -1,17 +1,19 @@
|
|
|
1
|
-
import { jsx as _jsx, jsxs as _jsxs
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import React from 'react';
|
|
3
3
|
import { Box, Text } from 'ink';
|
|
4
|
-
import
|
|
4
|
+
import { ActivitySpinner } from '../../ui/components/NativeIndicators.js';
|
|
5
5
|
import { formatElapsedTime, formatElapsedTimeWhole } from '../../utils/format.js';
|
|
6
6
|
import { MarkdownText } from '../../ui/components/MarkdownText.js';
|
|
7
|
+
import { StreamingMarkdownText } from '../../ui/components/StreamingMarkdownText.js';
|
|
7
8
|
import { clampTextTail, wrapLine } from './liveRegion.js';
|
|
8
9
|
import { isSubstantiveAssistantText } from '../commands/streaming/assistantText.js';
|
|
9
10
|
import { theme } from '../../ui/theme.js';
|
|
11
|
+
import { cellWidth } from '../../ui/textGeometry.js';
|
|
10
12
|
import { highlightedCodeLine, languageForPath } from '../../ui/codeHighlight.js';
|
|
11
13
|
function fullWidthLines(text, width, leftPadding = 0) {
|
|
12
14
|
const safeWidth = Math.max(1, width);
|
|
13
15
|
const prefix = ' '.repeat(leftPadding);
|
|
14
|
-
return text.replace(/\r\n|\r/g, '\n').split('\n').map(line => `${prefix}${line}
|
|
16
|
+
return text.replace(/\r\n|\r/g, '\n').split('\n').map(line => `${prefix}${line}${' '.repeat(Math.max(0, safeWidth - cellWidth(line) - leftPadding))}`);
|
|
15
17
|
}
|
|
16
18
|
function fullWidthBlankLine(width) {
|
|
17
19
|
return ''.padEnd(Math.max(1, width));
|
|
@@ -95,10 +97,12 @@ const TOOL_ROW_PATTERN = /^(\s*)([✓✗…])\s+(\S+)(.*)$/;
|
|
|
95
97
|
* settings, see liveRegion.ts) and continuation rows are padded to align
|
|
96
98
|
* under the tool name instead of dropping back to the left edge.
|
|
97
99
|
*/
|
|
98
|
-
function toolGroupLineRows(line, width) {
|
|
100
|
+
function toolGroupLineRows(line, width, spinner = false) {
|
|
99
101
|
const match = TOOL_ROW_PATTERN.exec(line);
|
|
100
102
|
if (!match)
|
|
101
|
-
return
|
|
103
|
+
return spinner && width > 2
|
|
104
|
+
? wrapLine(line, width - 2).map(row => ` ${row}`)
|
|
105
|
+
: wrapLine(line, width);
|
|
102
106
|
const [, indent, icon, toolName, rest] = match;
|
|
103
107
|
const hang = indent.length + 2; // icon + separating space
|
|
104
108
|
const rows = wrapLine(`${toolName}${rest}`, Math.max(1, width - hang));
|
|
@@ -110,14 +114,14 @@ function toolGroupLineRows(line, width) {
|
|
|
110
114
|
* top and whole diff previews from the bottom, with one indicator row each.
|
|
111
115
|
* The finalized group still enters the static transcript verbatim.
|
|
112
116
|
*/
|
|
113
|
-
function clampToolDisplay({ text, width, toolDiffs, maxVisibleLines }) {
|
|
117
|
+
function clampToolDisplay({ text, width, toolDiffs, maxVisibleLines, streaming }) {
|
|
114
118
|
const allLines = text.split('\n');
|
|
115
119
|
const allDiffs = toolDiffs ?? [];
|
|
116
120
|
if (maxVisibleLines == null)
|
|
117
121
|
return { lines: allLines, hiddenTextRowCount: 0, visibleDiffs: allDiffs, hiddenDiffCount: 0 };
|
|
118
122
|
// Row counts must mirror toolGroupLineRows so the budget matches what is
|
|
119
123
|
// actually rendered (icon rows consume one extra hang indent column).
|
|
120
|
-
const rows = allLines.map(line => toolGroupLineRows(line, width).length);
|
|
124
|
+
const rows = allLines.map((line, index) => toolGroupLineRows(line, width, streaming && index === 0).length);
|
|
121
125
|
const total = rows.reduce((sum, count) => sum + count, 0);
|
|
122
126
|
let lines = allLines;
|
|
123
127
|
let hiddenTextRowCount = 0;
|
|
@@ -151,13 +155,16 @@ function clampToolDisplay({ text, width, toolDiffs, maxVisibleLines }) {
|
|
|
151
155
|
return { lines, hiddenTextRowCount, visibleDiffs, hiddenDiffCount: allDiffs.length - visibleDiffs.length };
|
|
152
156
|
}
|
|
153
157
|
function ToolMessageText({ text, streaming, width, toolDiffs, maxVisibleLines }) {
|
|
154
|
-
const clamped = clampToolDisplay({ text, width, toolDiffs, maxVisibleLines });
|
|
158
|
+
const clamped = clampToolDisplay({ text, width, toolDiffs, maxVisibleLines, streaming });
|
|
155
159
|
return _jsxs(Box, { flexDirection: "column", children: [clamped.hiddenTextRowCount > 0 ? _jsx(Text, { color: theme.muted, children: `⋯ +${clamped.hiddenTextRowCount} line${clamped.hiddenTextRowCount === 1 ? '' : 's'} above` }) : null, clamped.lines.flatMap((line, index) => {
|
|
156
160
|
const match = TOOL_ROW_PATTERN.exec(line);
|
|
157
161
|
if (!match) {
|
|
158
162
|
// Summary header / caption rows: plain muted rows (spinner on the
|
|
159
163
|
// first row while streaming).
|
|
160
|
-
|
|
164
|
+
const spinner = !!streaming && index === 0 && clamped.hiddenTextRowCount === 0 && width > 2;
|
|
165
|
+
return toolGroupLineRows(line, width, spinner).map((row, rowIndex) => spinner && rowIndex === 0
|
|
166
|
+
? _jsxs(Box, { width: width, overflow: "hidden", children: [_jsx(ActivitySpinner, { color: theme.muted }), _jsx(Box, { flexShrink: 0, width: 1 }), _jsx(Text, { color: theme.muted, wrap: "truncate-end", children: row.slice(2) })] }, `${index}-${rowIndex}`)
|
|
167
|
+
: _jsx(Text, { color: theme.muted, children: row }, `${index}-${rowIndex}`));
|
|
161
168
|
}
|
|
162
169
|
const [, indent, icon, toolName] = match;
|
|
163
170
|
const iconColor = icon === '✓' ? theme.success : icon === '✗' ? theme.danger : theme.muted;
|
|
@@ -193,19 +200,23 @@ export const AssistantMarkdownChunkView = React.memo(function AssistantMarkdownC
|
|
|
193
200
|
/** Streaming assistant tail clamped to the live-region budget; the full text enters the static transcript once the root settles. */
|
|
194
201
|
function StreamingClampedText({ text, width, maxVisibleLines }) {
|
|
195
202
|
const clamped = clampTextTail(text, width, maxVisibleLines);
|
|
196
|
-
return _jsxs(Box, { flexDirection: "column", children: [clamped.hiddenLineCount > 0 ? _jsx(Text, { color: theme.muted, children: `⋯ +${clamped.hiddenLineCount} line${clamped.hiddenLineCount === 1 ? '' : 's'} above` }) : null, _jsx(Text, { children: clamped.text })] });
|
|
203
|
+
return _jsxs(Box, { flexDirection: "column", children: [clamped.hiddenLineCount > 0 ? _jsx(Text, { color: theme.muted, wrap: "truncate-end", children: `⋯ +${clamped.hiddenLineCount} line${clamped.hiddenLineCount === 1 ? '' : 's'} above` }) : null, clamped.text || clamped.hiddenLineCount === 0 ? _jsx(Text, { children: clamped.text }) : null] });
|
|
197
204
|
}
|
|
198
205
|
export const MessageView = React.memo(function MessageView({ message, width, showHeader = true, maxVisibleLines }) {
|
|
206
|
+
if (maxVisibleLines != null && message.role !== 'tool') {
|
|
207
|
+
return _jsxs(Box, { flexDirection: "column", flexShrink: 0, maxHeight: maxVisibleLines + (showHeader ? 1 : 0), overflow: "hidden", children: [showHeader && _jsx(Text, { color: theme.muted, wrap: "truncate-end", children: message.role === 'assistant' ? 'haze' : message.role === 'user' ? 'You asked' : 'Info' }), message.role === 'assistant'
|
|
208
|
+
? _jsx(StreamingMarkdownText, { content: message.text, width: width, maxVisibleLines: maxVisibleLines })
|
|
209
|
+
: _jsx(StreamingClampedText, { text: message.text, width: width, maxVisibleLines: maxVisibleLines })] });
|
|
210
|
+
}
|
|
199
211
|
if (message.role === 'user') {
|
|
200
212
|
return _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { backgroundColor: theme.surfaceBg, children: fullWidthBlankLine(width) }), _jsx(Text, { color: theme.success, bold: true, backgroundColor: theme.surfaceBg, children: ' You asked'.padEnd(width) }), fullWidthLines(message.text, width, 2).map((line, lineIndex) => _jsx(Text, { color: theme.foreground, backgroundColor: theme.surfaceBg, children: line }, lineIndex)), _jsx(Text, { backgroundColor: theme.surfaceBg, children: fullWidthBlankLine(width) })] });
|
|
201
213
|
}
|
|
202
214
|
return _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [showHeader ? _jsxs(Text, { children: [_jsx(Text, { color: message.role === 'assistant' ? theme.accent : message.role === 'tool' ? theme.info : message.role === 'system' ? theme.success : theme.muted, bold: true, children: message.role === 'assistant' ? 'haze' : message.role === 'tool' ? 'Tool' : 'Info' }), messageElapsedLabel(message) ? _jsxs(Text, { color: theme.muted, bold: false, children: [" \u00B7 ", messageElapsedLabel(message)] }) : null] }) : null, message.role === 'tool'
|
|
203
|
-
? _jsx(ToolMessageText, { text: message.text, streaming: message.streaming, width: width, toolDiffs: message.toolDiffs, maxVisibleLines:
|
|
204
|
-
: message.role === 'assistant'
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
? _jsx(MarkdownText, { content: message.text, width: width })
|
|
215
|
+
? _jsx(ToolMessageText, { text: message.text, streaming: message.streaming, width: width, toolDiffs: message.toolDiffs, maxVisibleLines: maxVisibleLines })
|
|
216
|
+
: message.role === 'assistant'
|
|
217
|
+
? message.streaming
|
|
218
|
+
? _jsx(StreamingMarkdownText, { content: message.text, width: width })
|
|
219
|
+
: _jsx(MarkdownText, { content: message.text, width: width })
|
|
209
220
|
: message.role === 'system'
|
|
210
221
|
? _jsx(SystemMessageText, { text: message.text })
|
|
211
222
|
: message.streaming && maxVisibleLines != null
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ModelMessage } from 'ai';
|
|
2
2
|
import type { ContextFile } from '../../config/contextFiles.js';
|
|
3
3
|
import type { WorkState } from '../../core/agent/workState.js';
|
|
4
|
-
import { type GoalLedgerFrontier, type HazeSession } from '../../core/session/sessionStore.js';
|
|
4
|
+
import { type GoalLedgerFrontier, type HazeSession, type SessionModelSelection } from '../../core/session/sessionStore.js';
|
|
5
5
|
import { type LlmLog } from '../../core/log/llmLog.js';
|
|
6
6
|
import type { Message } from '../commands/streaming.js';
|
|
7
7
|
import type { TokenUsage } from '../commands/streaming/turnRuntime.js';
|
|
@@ -24,6 +24,8 @@ export interface SessionLifecycleDeps {
|
|
|
24
24
|
noSession: boolean;
|
|
25
25
|
debug: boolean;
|
|
26
26
|
contextFiles: () => ContextFile[];
|
|
27
|
+
modelSelection?: () => SessionModelSelection | undefined;
|
|
28
|
+
onModelSelection?: (selection: SessionModelSelection | undefined) => void;
|
|
27
29
|
sessionRef: {
|
|
28
30
|
current: HazeSession | undefined;
|
|
29
31
|
};
|
|
@@ -47,7 +49,8 @@ export interface SessionLifecycleDeps {
|
|
|
47
49
|
current: Map<string, string>;
|
|
48
50
|
};
|
|
49
51
|
setMessages: (updater: (messages: Message[]) => Message[]) => void;
|
|
50
|
-
|
|
52
|
+
/** Drop the live tail (clear/new-session). */
|
|
53
|
+
clearLiveMessages: () => void;
|
|
51
54
|
setTokenUsage: (usage: TokenUsage) => void;
|
|
52
55
|
/** Manual /compact mode: model-written summary (default) or heuristic excerpt. */
|
|
53
56
|
manualCompaction?: () => 'llm-summary' | 'heuristic';
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { generateText } from 'ai';
|
|
2
2
|
import { buildLlmCompactionPrompt, compactModelMessages, compactModelMessagesWithSummary, splitForCompaction } from '../../core/agent/compaction.js';
|
|
3
3
|
import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
|
|
4
|
+
import { COMPACTION_LLM_MAX_OUTPUT_TOKENS } from '../../core/agent/budgets.js';
|
|
4
5
|
import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
|
|
5
6
|
import { modelWithConfig } from '../../llm/client.js';
|
|
6
7
|
import { createSession, findSession, forkSession, formatSession, latestSession, restoreSessionState } from '../../core/session/sessionStore.js';
|
|
7
8
|
import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
|
|
8
9
|
import { displayMessagesFromConversation, estimateConversationTokens } from './chatMetrics.js';
|
|
9
10
|
import { EMPTY_TOKEN_USAGE } from './turnState.js';
|
|
11
|
+
/** Bounded wall-clock budget for one manual LLM compaction summary (SU-03). */
|
|
12
|
+
const COMPACT_SUMMARY_TIMEOUT_MS = 120_000;
|
|
10
13
|
import { teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
|
|
11
14
|
export function createSessionLifecycle(deps) {
|
|
12
15
|
async function startNewLog() {
|
|
@@ -26,12 +29,16 @@ export function createSessionLifecycle(deps) {
|
|
|
26
29
|
deps.contextFileSignaturesRef.current = new Map(deps.contextFiles().flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
27
30
|
deps.workStateRef.current = undefined;
|
|
28
31
|
deps.sessionStartRef.current = new Date();
|
|
32
|
+
deps.onModelSelection?.(undefined);
|
|
29
33
|
if (deps.noSession) {
|
|
30
34
|
deps.sessionRef.current = undefined;
|
|
31
35
|
return;
|
|
32
36
|
}
|
|
33
37
|
const session = await createSession({ hazeVersion: deps.version, ...(deps.build ? { build: deps.build } : {}) });
|
|
34
38
|
deps.sessionRef.current = session;
|
|
39
|
+
const selection = deps.modelSelection?.();
|
|
40
|
+
if (selection)
|
|
41
|
+
deps.sessionRecorder()?.recordModelSelection(selection);
|
|
35
42
|
deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
36
43
|
await startNewLog();
|
|
37
44
|
const status = `${message}\nSession: ${session.file}`;
|
|
@@ -44,10 +51,16 @@ export function createSessionLifecycle(deps) {
|
|
|
44
51
|
});
|
|
45
52
|
}
|
|
46
53
|
async function resumeSession(session, replaceTranscript) {
|
|
47
|
-
const { messages: conversation, workState, parseErrors, goalFrontier } = await restoreSessionState(session);
|
|
54
|
+
const { messages: conversation, workState, parseErrors, goalFrontier, modelSelection } = await restoreSessionState(session);
|
|
48
55
|
deps.sessionRef.current = session;
|
|
56
|
+
deps.onModelSelection?.(modelSelection);
|
|
57
|
+
if (!modelSelection) {
|
|
58
|
+
const selection = deps.modelSelection?.();
|
|
59
|
+
if (selection)
|
|
60
|
+
deps.sessionRecorder()?.recordModelSelection(selection);
|
|
61
|
+
}
|
|
49
62
|
deps.conversationRef.current = conversation;
|
|
50
|
-
deps.
|
|
63
|
+
deps.clearLiveMessages();
|
|
51
64
|
const restoredMessages = displayMessagesFromConversation(conversation);
|
|
52
65
|
deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
|
|
53
66
|
deps.workStateRef.current = workState;
|
|
@@ -164,8 +177,12 @@ export function createSessionLifecycle(deps) {
|
|
|
164
177
|
deps.lastAssistantTextRef.current = '';
|
|
165
178
|
deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
166
179
|
deps.workStateRef.current = undefined;
|
|
167
|
-
deps.
|
|
180
|
+
deps.clearLiveMessages();
|
|
168
181
|
deps.setMessages(() => [{ role: 'system', text: 'Cleared. The void is productive.' }]);
|
|
182
|
+
// SU-02: record the empty snapshot so the clear is durable immediately;
|
|
183
|
+
// restore replays the clear marker and yields an empty conversation even
|
|
184
|
+
// if the process exits before the next conversation snapshot arrives.
|
|
185
|
+
deps.sessionRecorder()?.recordConversation([]);
|
|
169
186
|
deps.sessionRecorder()?.recordNamedEvent('clear', 'Conversation cleared');
|
|
170
187
|
await deps.sessionRecorder()?.flush().catch(deps.showPersistenceWarning);
|
|
171
188
|
await startNewLog().catch(deps.showPersistenceWarning);
|
|
@@ -182,14 +199,29 @@ export function createSessionLifecycle(deps) {
|
|
|
182
199
|
deps.setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${messages.length} model messages in context.` }]);
|
|
183
200
|
return false;
|
|
184
201
|
}
|
|
202
|
+
// SU-03: commit against the exact session and conversation we captured.
|
|
203
|
+
// A submission/session change while the summary was pending must not be
|
|
204
|
+
// overwritten — the stale compaction is reported and discarded instead.
|
|
205
|
+
const sessionAtStart = deps.sessionRef.current;
|
|
185
206
|
try {
|
|
186
|
-
const
|
|
207
|
+
const selection = deps.modelSelection?.();
|
|
208
|
+
const runtime = await modelWithConfig(selection ? { modelSelector: `${selection.provider}:${selection.model}` } : undefined);
|
|
187
209
|
if (!runtime?.model)
|
|
188
210
|
throw new Error('no model provider configured');
|
|
189
211
|
const summarization = await generateText({
|
|
190
212
|
model: runtime.model,
|
|
191
213
|
prompt: buildLlmCompactionPrompt({ older: split.older, instructions }),
|
|
214
|
+
maxOutputTokens: COMPACTION_LLM_MAX_OUTPUT_TOKENS,
|
|
215
|
+
abortSignal: AbortSignal.timeout(COMPACT_SUMMARY_TIMEOUT_MS),
|
|
192
216
|
});
|
|
217
|
+
if (deps.sessionRef.current !== sessionAtStart) {
|
|
218
|
+
deps.setMessages(m => [...m, { role: 'system', text: 'Compaction result discarded: the session changed while the summary was being written.' }]);
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
if (deps.conversationRef.current !== messages) {
|
|
222
|
+
deps.setMessages(m => [...m, { role: 'system', text: 'Compaction result discarded: the conversation changed while the summary was being written. Run /compact again.' }]);
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
193
225
|
const summaryText = summarization.text.trim();
|
|
194
226
|
if (!summaryText)
|
|
195
227
|
throw new Error('model returned an empty summary');
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { ModelMessage } from 'ai';
|
|
2
|
-
import { type HazeSession } from '../../core/session/sessionStore.js';
|
|
2
|
+
import { type HazeSession, type SessionModelSelection } from '../../core/session/sessionStore.js';
|
|
3
3
|
import type { GoalLedgerAppend } from '../commands/streaming/goalCheckpoint.js';
|
|
4
4
|
import type { AgentEvent } from '../../core/agent/events.js';
|
|
5
5
|
import type { WorkState } from '../../core/agent/workState.js';
|
|
6
6
|
import type { Message } from '../commands/streaming.js';
|
|
7
7
|
export declare function createSessionRecorder(getSession: () => HazeSession | undefined): {
|
|
8
|
+
recordModelSelection(selection: SessionModelSelection): void;
|
|
8
9
|
recordUiMessage(message: Message): void;
|
|
9
10
|
recordConversation(messages: ModelMessage[]): void;
|
|
10
11
|
recordWorkState(state: WorkState): void;
|
|
@@ -60,7 +60,15 @@ export function createSessionRecorder(getSession) {
|
|
|
60
60
|
pendingWorkState = undefined;
|
|
61
61
|
writeWorkState(snapshot);
|
|
62
62
|
};
|
|
63
|
+
let lastModelSelection;
|
|
63
64
|
return {
|
|
65
|
+
recordModelSelection(selection) {
|
|
66
|
+
const session = getSession();
|
|
67
|
+
if (!session || (lastModelSelection?.session === session && lastModelSelection.provider === selection.provider && lastModelSelection.model === selection.model))
|
|
68
|
+
return;
|
|
69
|
+
lastModelSelection = { session, ...selection };
|
|
70
|
+
appendEntry({ type: 'model_selection', at: new Date().toISOString(), selection });
|
|
71
|
+
},
|
|
64
72
|
recordUiMessage(message) {
|
|
65
73
|
appendEntry({ type: 'ui_message', at: new Date().toISOString(), role: message.role, text: message.text });
|
|
66
74
|
},
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface ShutdownOwners {
|
|
2
|
+
stop: () => void;
|
|
3
|
+
abort: () => void;
|
|
4
|
+
settle: () => Promise<unknown> | undefined;
|
|
5
|
+
seal: () => void;
|
|
6
|
+
flush: () => Promise<unknown> | undefined;
|
|
7
|
+
endLog: () => Promise<unknown> | undefined;
|
|
8
|
+
cleanup: () => Promise<unknown>;
|
|
9
|
+
exit: () => void;
|
|
10
|
+
report: (message: string) => void;
|
|
11
|
+
}
|
|
12
|
+
/** One owner for slash exit and interrupt; late rejection is consumed by the race. */
|
|
13
|
+
export declare function createChatShutdown(owners: ShutdownOwners, settlementMs?: number, cleanupMs?: number): () => Promise<void>;
|
|
14
|
+
export interface TerminalApp {
|
|
15
|
+
waitUntilExit: () => Promise<unknown>;
|
|
16
|
+
unmount: () => void;
|
|
17
|
+
cleanup: () => void;
|
|
18
|
+
/** Ink 8: settles once pending render output is flushed to stdout. */
|
|
19
|
+
waitUntilRenderFlush?: () => Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
/** Adoption and synchronous render failures share the same restoration boundary. */
|
|
22
|
+
export declare function runTerminalSession(owners: {
|
|
23
|
+
adopt: () => void;
|
|
24
|
+
create: () => TerminalApp;
|
|
25
|
+
shutdown: () => Promise<void> | undefined;
|
|
26
|
+
restore: () => void;
|
|
27
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
async function bounded(action, timeoutMs) {
|
|
2
|
+
let timer;
|
|
3
|
+
try {
|
|
4
|
+
await Promise.race([
|
|
5
|
+
Promise.resolve().then(action),
|
|
6
|
+
new Promise((_resolve, reject) => {
|
|
7
|
+
timer = setTimeout(() => reject(new Error('Shutdown deadline exceeded')), timeoutMs);
|
|
8
|
+
}),
|
|
9
|
+
]);
|
|
10
|
+
}
|
|
11
|
+
finally {
|
|
12
|
+
if (timer)
|
|
13
|
+
clearTimeout(timer);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** One owner for slash exit and interrupt; late rejection is consumed by the race. */
|
|
17
|
+
export function createChatShutdown(owners, settlementMs = 12_000, cleanupMs = 5_000) {
|
|
18
|
+
let pending;
|
|
19
|
+
return () => {
|
|
20
|
+
if (pending)
|
|
21
|
+
return pending;
|
|
22
|
+
owners.stop();
|
|
23
|
+
pending = (async () => {
|
|
24
|
+
const attempt = async (label, action, timeout) => {
|
|
25
|
+
try {
|
|
26
|
+
await bounded(action, timeout);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
owners.report(`Shutdown warning: ${label} failed or exceeded its deadline.`);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
try {
|
|
33
|
+
await attempt('abort', owners.abort, cleanupMs);
|
|
34
|
+
await attempt('active turn settlement', owners.settle, settlementMs);
|
|
35
|
+
owners.seal();
|
|
36
|
+
await attempt('session persistence', owners.flush, cleanupMs);
|
|
37
|
+
await attempt('log persistence', owners.endLog, cleanupMs);
|
|
38
|
+
await attempt('resource cleanup', owners.cleanup, cleanupMs);
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
owners.exit();
|
|
42
|
+
}
|
|
43
|
+
})();
|
|
44
|
+
return pending;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Adoption and synchronous render failures share the same restoration boundary. */
|
|
48
|
+
export async function runTerminalSession(owners) {
|
|
49
|
+
let app;
|
|
50
|
+
try {
|
|
51
|
+
owners.adopt();
|
|
52
|
+
app = owners.create();
|
|
53
|
+
await app.waitUntilExit();
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
try {
|
|
57
|
+
await owners.shutdown();
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
// Flush the final frame before teardown so the last rendered state
|
|
61
|
+
// (goodbye line, final status) actually reaches the TTY.
|
|
62
|
+
try {
|
|
63
|
+
await app?.waitUntilRenderFlush?.();
|
|
64
|
+
}
|
|
65
|
+
catch { /* terminal already gone */ }
|
|
66
|
+
try {
|
|
67
|
+
app?.unmount();
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
try {
|
|
71
|
+
app?.cleanup();
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
owners.restore();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for interactive child-process handoff via Ink 8's
|
|
3
|
+
* `suspendTerminal`. Kept free of Ink/React imports so they stay testable.
|
|
4
|
+
*/
|
|
5
|
+
export interface EditorLaunch {
|
|
6
|
+
command: string;
|
|
7
|
+
args: string[];
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Resolve the editor command for an external `$EDITOR` compose. Follows the
|
|
11
|
+
* common `VISUAL` over `EDITOR` precedence; `false` means the environment has
|
|
12
|
+
* no editor configured. Composite EDITOR values (`code -w`, `vim -f`) are
|
|
13
|
+
* split into a command and args so no shell is needed.
|
|
14
|
+
*/
|
|
15
|
+
export declare function resolveEditorCommand(env?: NodeJS.ProcessEnv): EditorLaunch | false;
|
|
16
|
+
/**
|
|
17
|
+
* Resolve a pager for viewing long text: `$PAGER`, else `less` (POSIX) or
|
|
18
|
+
* `more` (Windows). Returns undefined when the text plausibly fits one screen
|
|
19
|
+
* and a pager would only add a keypress.
|
|
20
|
+
*/
|
|
21
|
+
export declare function resolvePager(text: string, terminalRows: number, env?: NodeJS.ProcessEnv): {
|
|
22
|
+
command: string;
|
|
23
|
+
args: string[];
|
|
24
|
+
} | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Run a child process while Ink has suspended the terminal (raw mode off,
|
|
27
|
+
* child owns the TTY). Resolves with the exit code; rejects on spawn or
|
|
28
|
+
* unexpected input-stream errors. Early pager closure (EPIPE) is normal. `stdinText` pipes text into the child (pager);
|
|
29
|
+
* without it the child inherits the terminal stdin (editor).
|
|
30
|
+
*/
|
|
31
|
+
export declare function runSuspendedChild(launch: {
|
|
32
|
+
command: string;
|
|
33
|
+
args: string[];
|
|
34
|
+
}, stdinText?: string): Promise<number | null>;
|
|
35
|
+
/**
|
|
36
|
+
* `suspendTerminal` affordances for ChatScreen: run a fullscreen child
|
|
37
|
+
* ($EDITOR, pager) with the terminal handed over, then restore Ink state and
|
|
38
|
+
* force a full redraw. `composeInEditor` returns the composed text (or
|
|
39
|
+
* undefined when no editor is configured / nothing was typed); `viewInPager`
|
|
40
|
+
* returns whether a pager actually ran.
|
|
41
|
+
*/
|
|
42
|
+
export declare function useTerminalControl(): {
|
|
43
|
+
composeInEditor: () => Promise<string | undefined>;
|
|
44
|
+
viewInPager: (text: string) => Promise<boolean>;
|
|
45
|
+
};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
/** Split an editor/pager executable and quoted arguments without invoking a shell. */
|
|
3
|
+
function parseTerminalCommand(raw) {
|
|
4
|
+
const parts = raw.match(/"([^"]+)"|'([^']+)'|(\S+)/g) ?? [];
|
|
5
|
+
const words = parts.map(part => part.replace(/^["']|["']$/g, '')).filter(Boolean);
|
|
6
|
+
const command = words[0];
|
|
7
|
+
return command ? { command, args: words.slice(1) } : false;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Resolve the editor command for an external `$EDITOR` compose. Follows the
|
|
11
|
+
* common `VISUAL` over `EDITOR` precedence; `false` means the environment has
|
|
12
|
+
* no editor configured. Composite EDITOR values (`code -w`, `vim -f`) are
|
|
13
|
+
* split into a command and args so no shell is needed.
|
|
14
|
+
*/
|
|
15
|
+
export function resolveEditorCommand(env = process.env) {
|
|
16
|
+
const raw = (env['VISUAL'] || env['EDITOR'] || '').trim();
|
|
17
|
+
return parseTerminalCommand(raw);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Resolve a pager for viewing long text: `$PAGER`, else `less` (POSIX) or
|
|
21
|
+
* `more` (Windows). Returns undefined when the text plausibly fits one screen
|
|
22
|
+
* and a pager would only add a keypress.
|
|
23
|
+
*/
|
|
24
|
+
export function resolvePager(text, terminalRows, env = process.env) {
|
|
25
|
+
if (text.split('\n').length <= Math.max(1, terminalRows - 1))
|
|
26
|
+
return undefined;
|
|
27
|
+
const pager = env['PAGER']?.trim() || (process.platform === 'win32' ? 'more' : 'less');
|
|
28
|
+
const launch = parseTerminalCommand(pager);
|
|
29
|
+
if (!launch)
|
|
30
|
+
return undefined;
|
|
31
|
+
return launch.command === 'less' && launch.args.length === 0
|
|
32
|
+
? { command: launch.command, args: ['-R', '-X'] } : launch;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Run a child process while Ink has suspended the terminal (raw mode off,
|
|
36
|
+
* child owns the TTY). Resolves with the exit code; rejects on spawn or
|
|
37
|
+
* unexpected input-stream errors. Early pager closure (EPIPE) is normal. `stdinText` pipes text into the child (pager);
|
|
38
|
+
* without it the child inherits the terminal stdin (editor).
|
|
39
|
+
*/
|
|
40
|
+
export function runSuspendedChild(launch, stdinText) {
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
const child = stdinText == null
|
|
43
|
+
? spawn(launch.command, launch.args, { stdio: 'inherit' })
|
|
44
|
+
: spawn(launch.command, launch.args, { stdio: ['pipe', 'inherit', 'inherit'] });
|
|
45
|
+
child.once('error', reject);
|
|
46
|
+
child.once('close', code => resolve(code));
|
|
47
|
+
if (stdinText != null && child.stdin) {
|
|
48
|
+
// Quitting a pager can close its pipe while a large write is pending.
|
|
49
|
+
// Stream errors are separate from the child's spawn error event.
|
|
50
|
+
child.stdin.on('error', (error) => {
|
|
51
|
+
if (error.code !== 'EPIPE')
|
|
52
|
+
reject(error);
|
|
53
|
+
});
|
|
54
|
+
child.stdin.end(stdinText);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
// Ink-side wiring lives in chat.tsx via useApp(); this module deliberately
|
|
59
|
+
// stays React-free. The interactive hook is defined in terminalControlHook.tsx.
|
|
60
|
+
// --- Ink-side wiring (React, no JSX) -------------------------------------
|
|
61
|
+
import { useCallback } from 'react';
|
|
62
|
+
import { useApp, useIsScreenReaderEnabled, useWindowSize } from 'ink';
|
|
63
|
+
import os from 'node:os';
|
|
64
|
+
import path from 'node:path';
|
|
65
|
+
import fs from 'fs-extra';
|
|
66
|
+
import { randomUUID } from 'node:crypto';
|
|
67
|
+
/**
|
|
68
|
+
* `suspendTerminal` affordances for ChatScreen: run a fullscreen child
|
|
69
|
+
* ($EDITOR, pager) with the terminal handed over, then restore Ink state and
|
|
70
|
+
* force a full redraw. `composeInEditor` returns the composed text (or
|
|
71
|
+
* undefined when no editor is configured / nothing was typed); `viewInPager`
|
|
72
|
+
* returns whether a pager actually ran.
|
|
73
|
+
*/
|
|
74
|
+
export function useTerminalControl() {
|
|
75
|
+
const { suspendTerminal } = useApp();
|
|
76
|
+
const { rows } = useWindowSize();
|
|
77
|
+
const screenReader = useIsScreenReaderEnabled();
|
|
78
|
+
const composeInEditor = useCallback(async () => {
|
|
79
|
+
const editor = resolveEditorCommand();
|
|
80
|
+
if (editor === false)
|
|
81
|
+
return undefined;
|
|
82
|
+
const file = path.join(os.tmpdir(), `haze-compose-${randomUUID()}.md`);
|
|
83
|
+
await fs.writeFile(file, '', 'utf8');
|
|
84
|
+
try {
|
|
85
|
+
await suspendTerminal(async () => {
|
|
86
|
+
await runSuspendedChild({ command: editor.command, args: [...editor.args, file] });
|
|
87
|
+
});
|
|
88
|
+
const text = (await fs.readFile(file, 'utf8')).trim();
|
|
89
|
+
return text || undefined;
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
await fs.remove(file).catch(() => undefined);
|
|
93
|
+
}
|
|
94
|
+
}, [suspendTerminal]);
|
|
95
|
+
const viewInPager = useCallback(async (text) => {
|
|
96
|
+
if (screenReader)
|
|
97
|
+
return false;
|
|
98
|
+
const pager = resolvePager(text, rows);
|
|
99
|
+
if (!pager)
|
|
100
|
+
return false;
|
|
101
|
+
await suspendTerminal(async () => {
|
|
102
|
+
await runSuspendedChild(pager, text);
|
|
103
|
+
});
|
|
104
|
+
return true;
|
|
105
|
+
}, [rows, screenReader, suspendTerminal]);
|
|
106
|
+
return { composeInEditor, viewInPager };
|
|
107
|
+
}
|
package/dist/cli/chat/tips.js
CHANGED
|
@@ -24,6 +24,7 @@ export const TIPS = [
|
|
|
24
24
|
'/context shows a token breakdown — system, project context, tools, and messages.',
|
|
25
25
|
'/model <name> sets a model directly (e.g. /model sonnet); selecting one also sets its provider.',
|
|
26
26
|
'/tips toggles this hint line off if you find it distracting.',
|
|
27
|
+
'/editor composes long prompts in your $EDITOR; /logs <id> view pages a raw log through $PAGER.',
|
|
27
28
|
];
|
|
28
29
|
/**
|
|
29
30
|
* Pick a random tip index, avoiding the previous one when possible so the
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ContextFile } from '../../config/contextFiles.js';
|
|
2
|
+
import type { HazeSettings } from '../../config/settings.js';
|
|
3
|
+
import type { TurnExecutionOptions } from '../commands/streaming.js';
|
|
4
|
+
/**
|
|
5
|
+
* Pure user-input policies extracted from ChatScreen so they are unit-testable
|
|
6
|
+
* outside React (architecture-review round 1): attachment gating (F03), the
|
|
7
|
+
* paused-goal recovery-command classification (SU-04), the session
|
|
8
|
+
* model-selection patch policy, and the context-file signature map.
|
|
9
|
+
*/
|
|
10
|
+
/** F03: resolve @image mentions into attachments, gated on provider image capability. */
|
|
11
|
+
export declare function prepareUserInput(value: string, settings: HazeSettings): Promise<{
|
|
12
|
+
value: string;
|
|
13
|
+
displayValue?: string;
|
|
14
|
+
options: TurnExecutionOptions;
|
|
15
|
+
error?: string;
|
|
16
|
+
} | undefined>;
|
|
17
|
+
/** SU-04: recovery/configuration commands keep the paused-goal resume affordance alive. */
|
|
18
|
+
export declare function isPausedGoalRecoveryCommand(mode: string, value: string): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Preserve a resumed session's model selection across unrelated settings
|
|
21
|
+
* writes: the patched fields win, untouched fields keep the current selection.
|
|
22
|
+
*/
|
|
23
|
+
export declare function mergeSettingsSelection(next: HazeSettings, current: {
|
|
24
|
+
provider?: string;
|
|
25
|
+
model?: string;
|
|
26
|
+
}, patch?: HazeSettings): HazeSettings;
|
|
27
|
+
/** Signature map for context files (path → `size:mtimeMs`), shared by startup and /context refresh. */
|
|
28
|
+
export declare function contextFileSignatureMap(files: readonly ContextFile[]): Map<string, string>;
|
|
29
|
+
/**
|
|
30
|
+
* One-key resume kind: an incomplete-goal checkpoint restarts the supervisor
|
|
31
|
+
* from its checkpoint; anything else continues the idle-stall retry pool.
|
|
32
|
+
*/
|
|
33
|
+
export declare function resumeKindFor(resume: {
|
|
34
|
+
kind: 'model-stream-idle' | 'incomplete-goal';
|
|
35
|
+
retryAttempt: number;
|
|
36
|
+
checkpoint?: unknown;
|
|
37
|
+
}): {
|
|
38
|
+
kind: 'incomplete-goal';
|
|
39
|
+
checkpoint: unknown;
|
|
40
|
+
} | {
|
|
41
|
+
kind: 'model-stream-idle';
|
|
42
|
+
retryAttempt: number;
|
|
43
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { activeProvider } from '../../config/providers.js';
|
|
2
|
+
import { imageAttachmentLine } from '../commands/formatters.js';
|
|
3
|
+
import { imageCapabilityError, IMAGE_ONLY_PROMPT_TEXT, resolveImageAttachments } from '../../core/attachments/imageAttachments.js';
|
|
4
|
+
import { resolveReadBlessings } from '../../core/attachments/readBlessings.js';
|
|
5
|
+
/**
|
|
6
|
+
* Pure user-input policies extracted from ChatScreen so they are unit-testable
|
|
7
|
+
* outside React (architecture-review round 1): attachment gating (F03), the
|
|
8
|
+
* paused-goal recovery-command classification (SU-04), the session
|
|
9
|
+
* model-selection patch policy, and the context-file signature map.
|
|
10
|
+
*/
|
|
11
|
+
/** F03: resolve @image mentions into attachments, gated on provider image capability. */
|
|
12
|
+
export async function prepareUserInput(value, settings) {
|
|
13
|
+
let resolved;
|
|
14
|
+
try {
|
|
15
|
+
resolved = await resolveImageAttachments(value);
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
return { value: '', options: {}, error: error instanceof Error ? error.message : String(error) };
|
|
19
|
+
}
|
|
20
|
+
const blessed = await resolveReadBlessings(resolved.text);
|
|
21
|
+
if (resolved.attachments.length === 0 && blessed.blessedPaths.length === 0)
|
|
22
|
+
return { value, options: {} };
|
|
23
|
+
const gateError = imageCapabilityError(activeProvider(settings));
|
|
24
|
+
if (resolved.attachments.length > 0 && gateError) {
|
|
25
|
+
return { value: '', options: {}, error: gateError };
|
|
26
|
+
}
|
|
27
|
+
const displayValue = [resolved.text, ...resolved.attachments.map(imageAttachmentLine)].filter(Boolean).join('\n');
|
|
28
|
+
return {
|
|
29
|
+
value: resolved.text || IMAGE_ONLY_PROMPT_TEXT,
|
|
30
|
+
displayValue,
|
|
31
|
+
options: { attachments: resolved.attachments, blessedPaths: blessed.blessedPaths },
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** SU-04: recovery/configuration commands keep the paused-goal resume affordance alive. */
|
|
35
|
+
export function isPausedGoalRecoveryCommand(mode, value) {
|
|
36
|
+
return mode !== 'chat' || /^(?:\/compact|\/model|\/provider|\/settings|\/themes|\/resume|\/sessions)\b/.test(value.trim());
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Preserve a resumed session's model selection across unrelated settings
|
|
40
|
+
* writes: the patched fields win, untouched fields keep the current selection.
|
|
41
|
+
*/
|
|
42
|
+
export function mergeSettingsSelection(next, current, patch) {
|
|
43
|
+
if (!patch)
|
|
44
|
+
return next;
|
|
45
|
+
return {
|
|
46
|
+
...next,
|
|
47
|
+
provider: 'provider' in patch ? next.provider : current.provider,
|
|
48
|
+
model: 'model' in patch ? next.model : current.model,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Signature map for context files (path → `size:mtimeMs`), shared by startup and /context refresh. */
|
|
52
|
+
export function contextFileSignatureMap(files) {
|
|
53
|
+
return new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* One-key resume kind: an incomplete-goal checkpoint restarts the supervisor
|
|
57
|
+
* from its checkpoint; anything else continues the idle-stall retry pool.
|
|
58
|
+
*/
|
|
59
|
+
export function resumeKindFor(resume) {
|
|
60
|
+
return resume.kind === 'incomplete-goal' && resume.checkpoint
|
|
61
|
+
? { kind: 'incomplete-goal', checkpoint: resume.checkpoint }
|
|
62
|
+
: { kind: 'model-stream-idle', retryAttempt: resume.retryAttempt };
|
|
63
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { Mode } from '../../commands/chatModes.js';
|
|
2
2
|
import type { WizardDispatchDeps, WizardHandler, WizardSetterContext } from './types.js';
|
|
3
|
-
/** Session picker and
|
|
3
|
+
/** Session picker, theme picker, and reasoning picker handlers (tiny single-purpose flows). */
|
|
4
4
|
export declare function createSessionThemeHandlers(deps: WizardDispatchDeps, ctx: WizardSetterContext): Partial<Record<Mode, WizardHandler>>;
|