@denizokcu/haze 0.9.0 → 0.11.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 +133 -17
- package/README.md +164 -68
- package/SECURITY.md +22 -0
- package/bin/haze.js +102 -1
- package/dist/buildInfo.json +7 -0
- package/dist/cli/chat/TaskBar.d.ts +2 -1
- package/dist/cli/chat/TaskBar.js +7 -4
- 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 +46 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
- package/dist/cli/chat/fileMentionSuggestions.js +92 -0
- package/dist/cli/chat/inputSuggestions.d.ts +5 -0
- package/dist/cli/chat/inputSuggestions.js +17 -3
- package/dist/cli/chat/liveRegion.d.ts +25 -0
- package/dist/cli/chat/liveRegion.js +48 -0
- package/dist/cli/chat/messages.d.ts +33 -2
- package/dist/cli/chat/messages.js +216 -33
- package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
- package/dist/cli/chat/sessionLifecycle.js +205 -0
- package/dist/cli/chat/sessionRecorder.js +80 -14
- package/dist/cli/chat/startupInfo.js +11 -4
- 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 +744 -0
- package/dist/cli/commands/chat.d.ts +6 -0
- package/dist/cli/commands/chat.js +373 -790
- 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 +5 -2
- package/dist/cli/commands/commands.js +22 -18
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- 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 +35 -6
- package/dist/cli/commands/logsCommand.js +1 -7
- package/dist/cli/commands/modelCommand.js +1 -1
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +10 -2
- package/dist/cli/commands/providerWizard.js +50 -4
- package/dist/cli/commands/runCommand.d.ts +4 -0
- package/dist/cli/commands/runCommand.js +142 -16
- package/dist/cli/commands/sessionPicker.d.ts +9 -0
- package/dist/cli/commands/sessionPicker.js +29 -0
- package/dist/cli/commands/settingsSummary.js +6 -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/abortCause.d.ts +24 -0
- package/dist/cli/commands/streaming/abortCause.js +16 -0
- package/dist/cli/commands/streaming/assistantText.js +9 -2
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
- package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
- package/dist/cli/commands/streaming/idleTimer.js +24 -0
- package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
- package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
- package/dist/cli/commands/streaming/toolResultState.js +29 -7
- package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
- package/dist/cli/commands/streaming/turnOutcome.js +27 -11
- package/dist/cli/commands/streaming/turnRuntime.js +6 -4
- package/dist/cli/commands/streaming.d.ts +82 -3
- package/dist/cli/commands/streaming.js +528 -91
- package/dist/cli/commands/wizardActions.d.ts +7 -0
- package/dist/cli/commands/wizardActions.js +7 -0
- package/dist/cli/commands/wizardPrompts.js +7 -1
- package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
- package/dist/cli/commands/wizardSuggestions.js +64 -14
- package/dist/cli/commands/wizardTransition.d.ts +4 -0
- package/dist/cli/commands/wizardTransition.js +1 -2
- package/dist/cli/index.js +82 -22
- package/dist/cli/terminalTitle.d.ts +6 -0
- package/dist/cli/terminalTitle.js +36 -0
- package/dist/config/inputHistory.d.ts +3 -3
- package/dist/config/inputHistory.js +12 -18
- package/dist/config/modelDiscovery.d.ts +71 -0
- package/dist/config/modelDiscovery.js +214 -0
- package/dist/config/privateStorage.js +28 -2
- package/dist/config/providerAuth.d.ts +14 -0
- package/dist/config/providerAuth.js +49 -0
- package/dist/config/providerPresets.d.ts +49 -5
- package/dist/config/providerPresets.js +573 -73
- package/dist/config/providers.d.ts +2 -0
- package/dist/config/providers.js +9 -0
- package/dist/config/settings.d.ts +58 -0
- package/dist/config/settings.js +38 -1
- package/dist/config/skillSettings.d.ts +6 -13
- package/dist/config/skillSettings.js +20 -19
- package/dist/core/agent/budgets.d.ts +36 -0
- package/dist/core/agent/budgets.js +44 -0
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +108 -19
- package/dist/core/agent/completionController.d.ts +230 -0
- package/dist/core/agent/completionController.js +287 -0
- package/dist/core/agent/contextBudget.d.ts +46 -0
- package/dist/core/agent/contextBudget.js +89 -7
- package/dist/core/agent/errors.js +6 -2
- package/dist/core/agent/events.d.ts +86 -0
- package/dist/core/agent/reasoningPolicy.d.ts +31 -0
- package/dist/core/agent/reasoningPolicy.js +27 -0
- package/dist/core/agent/toolCapabilities.d.ts +27 -0
- package/dist/core/agent/toolCapabilities.js +58 -0
- package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
- package/dist/core/agent/toolExecutionBudget.js +49 -0
- package/dist/core/agent/toolOutputStore.d.ts +13 -0
- package/dist/core/agent/toolOutputStore.js +27 -10
- package/dist/core/agent/toolResults.d.ts +12 -0
- package/dist/core/agent/toolResults.js +38 -0
- package/dist/core/agent/turnBudget.d.ts +35 -0
- package/dist/core/agent/turnBudget.js +27 -0
- package/dist/core/agent/turnPolicy.d.ts +11 -0
- package/dist/core/agent/turnPolicy.js +19 -0
- package/dist/core/agent/workState.d.ts +76 -1
- package/dist/core/agent/workState.js +120 -13
- 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/deadline.d.ts +33 -0
- package/dist/core/deadline.js +74 -0
- package/dist/core/goal/completionPolicy.d.ts +27 -0
- package/dist/core/goal/completionPolicy.js +37 -1
- package/dist/core/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -13
- package/dist/core/io/boundedRead.js +76 -29
- package/dist/core/limits/byteBudgets.d.ts +7 -0
- package/dist/core/limits/byteBudgets.js +7 -0
- package/dist/core/limits/textBudgets.d.ts +25 -0
- package/dist/core/limits/textBudgets.js +25 -0
- package/dist/core/log/llmLog.js +7 -0
- package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
- package/dist/core/persistence/orderedFileWriter.js +16 -2
- package/dist/core/process/backgroundRegistry.d.ts +35 -0
- package/dist/core/process/backgroundRegistry.js +195 -0
- package/dist/core/process/runBoundedProcess.d.ts +9 -0
- package/dist/core/process/runBoundedProcess.js +74 -29
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -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 +74 -0
- package/dist/core/session/sessionStore.js +268 -18
- package/dist/core/subagent/contracts.d.ts +120 -0
- package/dist/core/subagent/contracts.js +55 -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 +78 -0
- package/dist/core/subagent/subagentCoordinator.js +164 -0
- package/dist/core/subagent/subagentRunner.d.ts +211 -145
- package/dist/core/subagent/subagentRunner.js +208 -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 +36 -29
- package/dist/llm/client.js +102 -33
- package/dist/llm/hazeTools.d.ts +2559 -150
- package/dist/llm/hazeTools.js +119 -31
- package/dist/llm/lsp.d.ts +26 -4
- package/dist/llm/lsp.js +90 -14
- package/dist/llm/lspTools.d.ts +2366 -0
- package/dist/llm/lspTools.js +87 -79
- package/dist/llm/openaiCodex.d.ts +3 -0
- package/dist/llm/openaiCodex.js +47 -0
- package/dist/llm/openaiCodexOAuth.d.ts +54 -0
- package/dist/llm/openaiCodexOAuth.js +214 -0
- package/dist/llm/requestContext.d.ts +25 -1
- package/dist/llm/requestContext.js +51 -8
- package/dist/llm/systemPrompt.d.ts +15 -1
- package/dist/llm/systemPrompt.js +24 -8
- package/dist/llm/toolResultTypes.d.ts +8 -1
- package/dist/llm/tools/bashTool.d.ts +906 -32
- package/dist/llm/tools/bashTool.js +30 -4
- package/dist/llm/tools/editMatch.d.ts +14 -0
- package/dist/llm/tools/editMatch.js +72 -0
- package/dist/llm/tools/failures.d.ts +2 -0
- package/dist/llm/tools/failures.js +1 -0
- package/dist/llm/tools/fetchTool.d.ts +42 -26
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +6 -4
- package/dist/llm/tools/fileToolShared.js +18 -23
- package/dist/llm/tools/gitIgnore.d.ts +49 -0
- package/dist/llm/tools/gitIgnore.js +129 -0
- package/dist/llm/tools/grepRunner.d.ts +5 -0
- package/dist/llm/tools/grepRunner.js +52 -71
- 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/readRecovery.d.ts +10 -0
- package/dist/llm/tools/readRecovery.js +135 -0
- package/dist/llm/tools/toolContext.d.ts +9 -1
- package/dist/llm/tools/toolContext.js +83 -43
- package/dist/llm/tools/workspaceFile.d.ts +9 -1
- package/dist/llm/tools/workspaceFile.js +33 -4
- package/dist/llm/webFetch.d.ts +17 -0
- package/dist/llm/webFetch.js +66 -86
- 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/SkillRegistry.d.ts +3 -2
- package/dist/skills/SkillRegistry.js +43 -13
- 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 +6 -1
- package/dist/ui/codeHighlight.d.ts +4 -0
- package/dist/ui/codeHighlight.js +31 -0
- package/dist/ui/components/Header.d.ts +1 -1
- package/dist/ui/components/MarkdownText.d.ts +16 -2
- package/dist/ui/components/MarkdownText.js +244 -34
- package/dist/ui/components/TextInput.d.ts +12 -2
- package/dist/ui/components/TextInput.js +80 -8
- package/dist/ui/theme.d.ts +4 -3
- package/dist/ui/theme.js +5 -4
- package/dist/utils/buildInfo.d.ts +104 -0
- package/dist/utils/buildInfo.js +253 -0
- package/dist/utils/format.d.ts +2 -0
- package/dist/utils/format.js +8 -0
- package/dist/utils/fs.d.ts +9 -1
- package/dist/utils/fs.js +87 -29
- package/dist/utils/openPath.d.ts +2 -0
- package/dist/utils/openPath.js +22 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +5 -1
- package/dist/utils/utf8.d.ts +22 -0
- package/dist/utils/utf8.js +54 -0
- package/dist/utils/version.d.ts +9 -3
- package/dist/utils/version.js +28 -2
- package/package.json +24 -19
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import React from 'react';
|
|
2
3
|
import { Box, Text } from 'ink';
|
|
3
4
|
import Spinner from 'ink-spinner';
|
|
4
5
|
import { formatElapsedTime, formatElapsedTimeWhole } from '../commands/formatters.js';
|
|
5
|
-
import { MarkdownText } from '../../ui/components/MarkdownText.js';
|
|
6
|
+
import { MarkdownText, markdownRootChunks } from '../../ui/components/MarkdownText.js';
|
|
7
|
+
import { lineRows, clampTextTail } from './liveRegion.js';
|
|
6
8
|
import { isSubstantiveAssistantText } from '../commands/streaming/assistantText.js';
|
|
7
9
|
import { theme } from '../../ui/theme.js';
|
|
10
|
+
import { highlightedCodeLine, languageForPath } from '../../ui/codeHighlight.js';
|
|
8
11
|
function fullWidthLines(text, width, leftPadding = 0) {
|
|
9
12
|
const safeWidth = Math.max(1, width);
|
|
10
13
|
const prefix = ' '.repeat(leftPadding);
|
|
@@ -13,30 +16,136 @@ function fullWidthLines(text, width, leftPadding = 0) {
|
|
|
13
16
|
function fullWidthBlankLine(width) {
|
|
14
17
|
return ''.padEnd(Math.max(1, width));
|
|
15
18
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
19
|
+
/** Slash commands in system text are highlighted like `code` in the docs site. A command name never contains `/`, which keeps absolute paths like `/Users/...` plain. */
|
|
20
|
+
const SLASH_COMMAND_PATTERN = /(^|(?<=\s))\/[a-zA-Z][a-zA-Z0-9-]*(?![\w/-])/g;
|
|
21
|
+
function slashCommandParts(text) {
|
|
22
|
+
const parts = [];
|
|
23
|
+
let lastIndex = 0;
|
|
24
|
+
for (const match of text.matchAll(SLASH_COMMAND_PATTERN)) {
|
|
25
|
+
const index = match.index ?? 0;
|
|
26
|
+
if (index > lastIndex)
|
|
27
|
+
parts.push(text.slice(lastIndex, index));
|
|
28
|
+
parts.push(_jsx(Text, { color: theme.command, children: match[0] }, `cmd-${index}`));
|
|
29
|
+
lastIndex = index + match[0].length;
|
|
30
|
+
}
|
|
31
|
+
if (lastIndex < text.length)
|
|
32
|
+
parts.push(text.slice(lastIndex));
|
|
33
|
+
return parts;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Style one line of a system message: single-token list items that look like
|
|
37
|
+
* paths are orange, short leading "Key:" prefixes are bold, and slash
|
|
38
|
+
* commands are orange everywhere.
|
|
39
|
+
*/
|
|
40
|
+
function systemLineContent(line) {
|
|
41
|
+
const fileItem = /^- (\S+)$/.exec(line);
|
|
42
|
+
if (fileItem && /[./]/.test(fileItem[1] ?? ''))
|
|
43
|
+
return _jsx(Text, { color: theme.command, children: line });
|
|
44
|
+
const colonIndex = line.indexOf(':');
|
|
45
|
+
if (colonIndex > 0 && colonIndex <= 30) {
|
|
46
|
+
const key = line.slice(0, colonIndex);
|
|
47
|
+
// Exclude `/` and `.` from the key body so URLs like `https://example.com:443`
|
|
48
|
+
// don't match as a "Key:" prefix and get bolded as one span (which would
|
|
49
|
+
// bypass the slash-command highlighter for anything that follows).
|
|
50
|
+
if ((key.startsWith('- ') || key.includes(' ')) && /^[A-Za-z][\w ~-]*$/.test(key.replace(/^- /, ''))) {
|
|
51
|
+
return _jsxs(React.Fragment, { children: [_jsx(Text, { bold: true, children: key }), slashCommandParts(line.slice(colonIndex))] });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return slashCommandParts(line);
|
|
55
|
+
}
|
|
56
|
+
function SystemMessageText({ text }) {
|
|
57
|
+
return _jsx(Text, { children: text.split('\n').map((line, index) => _jsxs(React.Fragment, { children: [index > 0 ? '\n' : null, systemLineContent(line)] }, index)) });
|
|
58
|
+
}
|
|
59
|
+
function diffLineNumber(line) {
|
|
60
|
+
if (line.type === 'gap' || line.type === 'meta')
|
|
61
|
+
return undefined;
|
|
62
|
+
return line.type === 'remove' ? line.oldLine : line.newLine ?? line.oldLine;
|
|
63
|
+
}
|
|
64
|
+
function ToolDiffView({ diff, width }) {
|
|
65
|
+
const contentWidth = Math.max(1, width - 2);
|
|
66
|
+
const lineNumberWidth = Math.max(4, ...diff.lines.map(line => String(diffLineNumber(line) ?? '').length));
|
|
67
|
+
return _jsxs(Box, { flexDirection: "column", marginLeft: 2, marginTop: 1, children: [_jsxs(Text, { color: theme.muted, children: ["\u23BF ", _jsx(Text, { color: theme.command, children: diff.path }), " \u00B7 Added ", diff.addedLines, " line", diff.addedLines === 1 ? '' : 's', ", removed ", diff.removedLines, " line", diff.removedLines === 1 ? '' : 's'] }), diff.lines.map((line, index) => {
|
|
68
|
+
if (line.type === 'gap') {
|
|
69
|
+
return _jsxs(Text, { color: theme.muted, children: [" \u2026 ", line.omittedLines, " diff line", line.omittedLines === 1 ? '' : 's', " omitted \u2026"] }, `${diff.id}-${index}`);
|
|
70
|
+
}
|
|
71
|
+
if (line.type === 'meta') {
|
|
72
|
+
return _jsxs(Text, { color: theme.muted, children: [" \\ ", line.text] }, `${diff.id}-${index}`);
|
|
73
|
+
}
|
|
74
|
+
const marker = line.type === 'add' ? '+' : line.type === 'remove' ? '-' : ' ';
|
|
75
|
+
const lineNumber = `${String(diffLineNumber(line) ?? '').padStart(lineNumberWidth)} `;
|
|
76
|
+
const markerPrefix = `${marker} `;
|
|
77
|
+
const prefixWidth = lineNumber.length + markerPrefix.length;
|
|
78
|
+
const code = highlightedCodeLine(line.text, Math.max(1, contentWidth - prefixWidth), languageForPath(diff.path));
|
|
79
|
+
if (line.type === 'context') {
|
|
80
|
+
return _jsxs(Box, { flexDirection: "row", children: [_jsxs(Text, { color: theme.muted, children: [lineNumber, markerPrefix] }), _jsx(Text, { children: code })] }, `${diff.id}-${index}`);
|
|
81
|
+
}
|
|
82
|
+
const isAdd = line.type === 'add';
|
|
83
|
+
const backgroundColor = isAdd ? theme.successBg : theme.dangerBg;
|
|
84
|
+
return _jsxs(Box, { flexDirection: "row", children: [_jsx(Text, { color: theme.muted, children: lineNumber }), _jsxs(Text, { color: theme.foreground, backgroundColor: backgroundColor, children: [_jsx(Text, { color: isAdd ? theme.success : theme.danger, backgroundColor: backgroundColor, children: markerPrefix }), code] })] }, `${diff.id}-${index}`);
|
|
85
|
+
}), diff.handle ? _jsxs(Text, { color: theme.muted, children: [" Full diff: readToolOutput with handle ", _jsx(Text, { color: theme.command, children: diff.handle })] }) : null, diff.complete === false ? _jsxs(Text, { color: theme.muted, children: [" Preview is partial; ", diff.previousContentOmittedBytes ?? 0, " bytes of previous content were not captured."] }) : null] });
|
|
86
|
+
}
|
|
87
|
+
/** Rendered row count of a diff preview block (meta + code rows + optional handle/partial rows + top margin). */
|
|
88
|
+
function toolDiffRows(diff) {
|
|
89
|
+
return 1 + diff.lines.length + (diff.handle ? 1 : 0) + (diff.complete === false ? 1 : 0) + 1;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Live-region clamp for the streaming tool group (see liveRegion.ts): keep only
|
|
93
|
+
* the rows that fit the viewport budget, dropping whole logical lines from the
|
|
94
|
+
* top and whole diff previews from the bottom, with one indicator row each.
|
|
95
|
+
* The finalized group still enters the static transcript verbatim.
|
|
96
|
+
*/
|
|
97
|
+
function clampToolDisplay({ text, width, toolDiffs, maxVisibleLines }) {
|
|
98
|
+
const allLines = text.split('\n');
|
|
99
|
+
const allDiffs = toolDiffs ?? [];
|
|
100
|
+
if (maxVisibleLines == null)
|
|
101
|
+
return { lines: allLines, hiddenTextRowCount: 0, visibleDiffs: allDiffs, hiddenDiffCount: 0 };
|
|
102
|
+
const rows = allLines.map(line => lineRows(line, width));
|
|
103
|
+
const total = rows.reduce((sum, count) => sum + count, 0);
|
|
104
|
+
let lines = allLines;
|
|
105
|
+
let hiddenTextRowCount = 0;
|
|
106
|
+
let rowsUsed = total;
|
|
107
|
+
if (total > maxVisibleLines) {
|
|
108
|
+
const visibleBudget = Math.max(1, maxVisibleLines - 1); // indicator row
|
|
109
|
+
let used = 0;
|
|
110
|
+
let start = allLines.length;
|
|
111
|
+
while (start > 0) {
|
|
112
|
+
const next = rows[start - 1] ?? 0;
|
|
113
|
+
if (used + next > visibleBudget)
|
|
114
|
+
break;
|
|
115
|
+
used += next;
|
|
116
|
+
start -= 1;
|
|
117
|
+
}
|
|
118
|
+
hiddenTextRowCount = rows.slice(0, start).reduce((sum, count) => sum + count, 0);
|
|
119
|
+
lines = allLines.slice(start);
|
|
120
|
+
rowsUsed = used + 1;
|
|
121
|
+
}
|
|
122
|
+
// Diffs get whatever budget the text left; reserve an indicator row when any
|
|
123
|
+
// diff might be hidden.
|
|
124
|
+
let budget = Math.max(0, maxVisibleLines - rowsUsed - (allDiffs.length > 0 ? 1 : 0));
|
|
125
|
+
const visibleDiffs = [];
|
|
126
|
+
for (const diff of allDiffs) {
|
|
127
|
+
const cost = toolDiffRows(diff);
|
|
128
|
+
if (cost > budget)
|
|
129
|
+
break;
|
|
130
|
+
budget -= cost;
|
|
131
|
+
visibleDiffs.push(diff);
|
|
132
|
+
}
|
|
133
|
+
return { lines, hiddenTextRowCount, visibleDiffs, hiddenDiffCount: allDiffs.length - visibleDiffs.length };
|
|
134
|
+
}
|
|
135
|
+
function ToolMessageText({ text, streaming, width, toolDiffs, maxVisibleLines }) {
|
|
136
|
+
const clamped = clampToolDisplay({ text, width, toolDiffs, maxVisibleLines });
|
|
137
|
+
const lines = clamped.lines;
|
|
138
|
+
return _jsxs(Box, { flexDirection: "column", children: [clamped.hiddenTextRowCount > 0 ? _jsx(Text, { color: theme.muted, children: `⋯ +${clamped.hiddenTextRowCount} line${clamped.hiddenTextRowCount === 1 ? '' : 's'} above` }) : null, lines.map((line, index) => {
|
|
139
|
+
const row = /^(\s*)([✓✗…])\s+(\S+)(.*)$/.exec(line);
|
|
140
|
+
if (!row) {
|
|
141
|
+
const timer = /(.*) (\([0-9]+(?:h [0-9]+m [0-9]+(?:\.[0-9])?s|m [0-9]+(?:\.[0-9])?s|(?:\.[0-9])?s)\))$/.exec(line);
|
|
142
|
+
return _jsxs(Text, { color: theme.muted, children: [index === 0 && streaming ? _jsxs(_Fragment, { children: [_jsx(Spinner, { type: "dots" }), " "] }) : null, timer ? timer[1] : line, timer ? _jsxs(Text, { color: theme.muted, bold: false, children: [" ", timer[2]] }) : null] }, `${index}-${line}`);
|
|
143
|
+
}
|
|
144
|
+
const [, indent, icon, toolName, rest] = row;
|
|
145
|
+
const iconColor = icon === '✓' ? theme.success : icon === '✗' ? theme.danger : theme.muted;
|
|
146
|
+
const timer = /(.*) (\([0-9]+(?:h [0-9]+m [0-9]+(?:\.[0-9])?s|m [0-9]+(?:\.[0-9])?s|(?:\.[0-9])?s)\))$/.exec(rest);
|
|
147
|
+
return _jsxs(Text, { color: theme.muted, children: [indent, _jsx(Text, { color: iconColor, children: icon }), " ", _jsx(Text, { color: theme.purple, children: toolName }), timer ? timer[1] : rest, timer ? _jsxs(Text, { color: theme.muted, bold: false, children: [" ", timer[2]] }) : null] }, `${index}-${line}`);
|
|
148
|
+
}), clamped.visibleDiffs.map(diff => _jsx(ToolDiffView, { diff: diff, width: width }, diff.id)), clamped.hiddenDiffCount > 0 ? _jsx(Text, { color: theme.muted, children: `⋯ ${clamped.hiddenDiffCount} diff preview${clamped.hiddenDiffCount === 1 ? '' : 's'} hidden` }) : null] });
|
|
40
149
|
}
|
|
41
150
|
export function messageElapsedLabel(message) {
|
|
42
151
|
if (message.startedAt == null)
|
|
@@ -50,19 +159,93 @@ export function messageElapsedLabel(message) {
|
|
|
50
159
|
}
|
|
51
160
|
return message.streaming ? formatElapsedTimeWhole(elapsed) : formatElapsedTime(elapsed);
|
|
52
161
|
}
|
|
53
|
-
export function
|
|
162
|
+
export const AssistantMarkdownChunkView = React.memo(function AssistantMarkdownChunkView({ message, content, width, first, final }) {
|
|
163
|
+
const completion = final ? messageElapsedLabel(message) : '';
|
|
164
|
+
return _jsxs(Box, { flexDirection: "column", marginBottom: final ? 1 : 0, children: [first ? _jsx(Text, { color: theme.purple, bold: true, children: "haze" }) : null, _jsx(MarkdownText, { content: content, width: width }), completion ? _jsx(Text, { color: theme.muted, children: completion }) : null] });
|
|
165
|
+
});
|
|
166
|
+
/** Streaming assistant tail clamped to the live-region budget; the full text enters the static transcript once the root settles. */
|
|
167
|
+
function StreamingClampedText({ text, width, maxVisibleLines }) {
|
|
168
|
+
const clamped = clampTextTail(text, width, maxVisibleLines);
|
|
169
|
+
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 })] });
|
|
170
|
+
}
|
|
171
|
+
export const MessageView = React.memo(function MessageView({ message, width, showHeader = true, maxVisibleLines }) {
|
|
54
172
|
if (message.role === 'user') {
|
|
55
|
-
return _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { backgroundColor: theme.
|
|
173
|
+
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) })] });
|
|
56
174
|
}
|
|
57
|
-
return _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: message.role === 'assistant' ? theme.purple : message.role === 'tool' ? theme.blue : 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] }), message.role === 'tool'
|
|
58
|
-
? _jsx(ToolMessageText, { text: message.text, streaming: message.streaming })
|
|
175
|
+
return _jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [showHeader ? _jsxs(Text, { children: [_jsx(Text, { color: message.role === 'assistant' ? theme.purple : message.role === 'tool' ? theme.blue : 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'
|
|
176
|
+
? _jsx(ToolMessageText, { text: message.text, streaming: message.streaming, width: width, toolDiffs: message.toolDiffs, maxVisibleLines: message.streaming ? maxVisibleLines : undefined })
|
|
59
177
|
: message.role === 'assistant' && !message.streaming
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
178
|
+
// Only settled assistant messages get Markdown rendering. Streaming
|
|
179
|
+
// text re-tokenizes on every delta (expensive) and the partial Markdown
|
|
180
|
+
// would flicker; user text stays plain to keep pasted Markdown literal.
|
|
181
|
+
? _jsx(MarkdownText, { content: message.text, width: width })
|
|
182
|
+
: message.role === 'system'
|
|
183
|
+
? _jsx(SystemMessageText, { text: message.text })
|
|
184
|
+
: message.streaming && maxVisibleLines != null
|
|
185
|
+
? _jsx(StreamingClampedText, { text: message.text, width: width, maxVisibleLines: maxVisibleLines })
|
|
186
|
+
: _jsx(Text, { children: message.text })] });
|
|
187
|
+
});
|
|
63
188
|
export function messageKey(message, index) {
|
|
64
189
|
return message.id ?? `${index}-${message.role}-${message.text}`;
|
|
65
190
|
}
|
|
191
|
+
/** Partition display messages into append-only static Markdown roots and the active streaming tail. */
|
|
192
|
+
export function partitionDisplayMessages(messages) {
|
|
193
|
+
const staticItems = [];
|
|
194
|
+
const streamingItems = [];
|
|
195
|
+
let reachedDynamicTail = false;
|
|
196
|
+
orderedDisplayMessages(messages).forEach((message, index) => {
|
|
197
|
+
const key = messageKey(message, index);
|
|
198
|
+
// Static output must remain an ordered prefix. A settled notification that
|
|
199
|
+
// follows live text stays in the dynamic frame until that text is complete.
|
|
200
|
+
if (reachedDynamicTail) {
|
|
201
|
+
streamingItems.push({ key, message });
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (message.role !== 'assistant') {
|
|
205
|
+
if (message.streaming) {
|
|
206
|
+
reachedDynamicTail = true;
|
|
207
|
+
streamingItems.push({ key, message });
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
staticItems.push({ kind: 'message', key, message });
|
|
211
|
+
}
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const chunks = markdownRootChunks(message.text);
|
|
215
|
+
if (chunks.length === 0) {
|
|
216
|
+
if (message.streaming) {
|
|
217
|
+
reachedDynamicTail = true;
|
|
218
|
+
streamingItems.push({ key, message });
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
staticItems.push({ kind: 'message', key, message });
|
|
222
|
+
}
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
// Marked may still reclassify the final root while the stream grows. Keep
|
|
226
|
+
// only that root dynamic; every preceding root is now safe to append once.
|
|
227
|
+
const staticChunkCount = message.streaming ? Math.max(0, chunks.length - 1) : chunks.length;
|
|
228
|
+
for (let chunkIndex = 0; chunkIndex < staticChunkCount; chunkIndex++) {
|
|
229
|
+
staticItems.push({
|
|
230
|
+
kind: 'assistant-markdown',
|
|
231
|
+
key: `${key}-markdown-${chunkIndex}`,
|
|
232
|
+
message,
|
|
233
|
+
content: chunks[chunkIndex] ?? '',
|
|
234
|
+
first: chunkIndex === 0,
|
|
235
|
+
final: !message.streaming && chunkIndex === chunks.length - 1,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
if (message.streaming) {
|
|
239
|
+
reachedDynamicTail = true;
|
|
240
|
+
streamingItems.push({
|
|
241
|
+
key,
|
|
242
|
+
message: { ...message, text: chunks.at(-1) ?? message.text },
|
|
243
|
+
showHeader: staticChunkCount === 0,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
return { staticItems, streamingItems };
|
|
248
|
+
}
|
|
66
249
|
export function orderedDisplayMessages(messages) {
|
|
67
250
|
return messages
|
|
68
251
|
.map((message, index) => ({ message, index }))
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { ModelMessage } from 'ai';
|
|
2
|
+
import type { ContextFile } from '../../config/contextFiles.js';
|
|
3
|
+
import type { WorkState } from '../../core/agent/workState.js';
|
|
4
|
+
import { type HazeSession } from '../../core/session/sessionStore.js';
|
|
5
|
+
import { type LlmLog } from '../../core/log/llmLog.js';
|
|
6
|
+
import type { Message, TokenUsage } from '../commands/streaming.js';
|
|
7
|
+
import type { SessionRecorder } from './sessionRecorder.js';
|
|
8
|
+
/**
|
|
9
|
+
* Session lifecycle controller extracted from `chat.tsx` (CR-006): session
|
|
10
|
+
* init/continue/resume/new/clear/compact live here; the component keeps refs,
|
|
11
|
+
* state setters, and render work. Uses plain `{current}` holders so it works
|
|
12
|
+
* with React refs without importing React.
|
|
13
|
+
*/
|
|
14
|
+
export interface SessionLifecycleDeps {
|
|
15
|
+
version?: string;
|
|
16
|
+
/** Safe build provenance (commit, build time) recorded into session headers. */
|
|
17
|
+
build?: {
|
|
18
|
+
commit?: string;
|
|
19
|
+
builtAt?: string;
|
|
20
|
+
};
|
|
21
|
+
continueSession: boolean;
|
|
22
|
+
resumeSessionId?: string;
|
|
23
|
+
noSession: boolean;
|
|
24
|
+
debug: boolean;
|
|
25
|
+
contextFiles: () => ContextFile[];
|
|
26
|
+
sessionRef: {
|
|
27
|
+
current: HazeSession | undefined;
|
|
28
|
+
};
|
|
29
|
+
sessionRecorder: () => SessionRecorder | undefined;
|
|
30
|
+
sessionStartRef: {
|
|
31
|
+
current: Date;
|
|
32
|
+
};
|
|
33
|
+
conversationRef: {
|
|
34
|
+
current: ModelMessage[];
|
|
35
|
+
};
|
|
36
|
+
workStateRef: {
|
|
37
|
+
current: WorkState | undefined;
|
|
38
|
+
};
|
|
39
|
+
lastAssistantTextRef: {
|
|
40
|
+
current: string;
|
|
41
|
+
};
|
|
42
|
+
llmLogRef: {
|
|
43
|
+
current: LlmLog | undefined;
|
|
44
|
+
};
|
|
45
|
+
contextFileSignaturesRef: {
|
|
46
|
+
current: Map<string, string>;
|
|
47
|
+
};
|
|
48
|
+
setMessages: (updater: (messages: Message[]) => Message[]) => void;
|
|
49
|
+
setLiveMessagesState: (updater: (messages: Message[]) => Message[]) => void;
|
|
50
|
+
setTokenUsage: (usage: TokenUsage) => void;
|
|
51
|
+
/** Manual /compact mode: model-written summary (default) or heuristic excerpt. */
|
|
52
|
+
manualCompaction?: () => 'llm-summary' | 'heuristic';
|
|
53
|
+
debugLog: (line: string) => void;
|
|
54
|
+
showPersistenceWarning: (error: unknown) => void;
|
|
55
|
+
}
|
|
56
|
+
export interface SessionLifecycle {
|
|
57
|
+
initializeSession: () => Promise<void>;
|
|
58
|
+
startNewSession: (message?: string) => Promise<void>;
|
|
59
|
+
resumeLatestSession: () => Promise<void>;
|
|
60
|
+
resumeSessionById: (id: string) => Promise<boolean>;
|
|
61
|
+
forkSessionById: (id: string) => Promise<boolean>;
|
|
62
|
+
clearConversation: () => Promise<void>;
|
|
63
|
+
compactConversation: (instructions?: string) => boolean;
|
|
64
|
+
/** Manual /compact with a model-written summary; falls back to the heuristic excerpt on any failure (F-09). */
|
|
65
|
+
compactConversationWithModel: (instructions?: string) => Promise<boolean>;
|
|
66
|
+
}
|
|
67
|
+
export declare function createSessionLifecycle(deps: SessionLifecycleDeps): SessionLifecycle;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { generateText } from 'ai';
|
|
2
|
+
import { buildLlmCompactionPrompt, compactModelMessages, compactModelMessagesWithSummary, splitForCompaction } from '../../core/agent/compaction.js';
|
|
3
|
+
import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
|
|
4
|
+
import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
|
|
5
|
+
import { modelWithConfig } from '../../llm/client.js';
|
|
6
|
+
import { createSession, findSession, forkSession, formatSession, latestSession, restoreSessionState } from '../../core/session/sessionStore.js';
|
|
7
|
+
import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
|
|
8
|
+
import { displayMessagesFromConversation, estimateConversationTokens } from './chatMetrics.js';
|
|
9
|
+
import { EMPTY_TOKEN_USAGE } from './turnState.js';
|
|
10
|
+
import { teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
|
|
11
|
+
export function createSessionLifecycle(deps) {
|
|
12
|
+
async function startNewLog() {
|
|
13
|
+
if (!deps.debug)
|
|
14
|
+
return undefined;
|
|
15
|
+
if (deps.llmLogRef.current) {
|
|
16
|
+
await endLlmLog(deps.llmLogRef.current).catch(deps.showPersistenceWarning);
|
|
17
|
+
}
|
|
18
|
+
const log = await createLlmLog();
|
|
19
|
+
deps.llmLogRef.current = log;
|
|
20
|
+
return log;
|
|
21
|
+
}
|
|
22
|
+
async function startNewSession(message = 'New session started.', mergeWithPreviousInfo = false) {
|
|
23
|
+
await teardownBackgroundProcesses().catch(deps.showPersistenceWarning);
|
|
24
|
+
await deps.sessionRecorder()?.flush().catch(deps.showPersistenceWarning);
|
|
25
|
+
clearToolOutputs();
|
|
26
|
+
deps.contextFileSignaturesRef.current = new Map(deps.contextFiles().flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
27
|
+
deps.workStateRef.current = undefined;
|
|
28
|
+
deps.sessionStartRef.current = new Date();
|
|
29
|
+
if (deps.noSession) {
|
|
30
|
+
deps.sessionRef.current = undefined;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const session = await createSession({ hazeVersion: deps.version, ...(deps.build ? { build: deps.build } : {}) });
|
|
34
|
+
deps.sessionRef.current = session;
|
|
35
|
+
deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
36
|
+
await startNewLog();
|
|
37
|
+
const status = `${message}\nSession: ${session.file}`;
|
|
38
|
+
deps.setMessages(messages => {
|
|
39
|
+
const previous = messages.at(-1);
|
|
40
|
+
if (mergeWithPreviousInfo && previous?.role === 'system') {
|
|
41
|
+
return [...messages.slice(0, -1), { ...previous, text: `${previous.text}\n\n${status}` }];
|
|
42
|
+
}
|
|
43
|
+
return [...messages, { role: 'system', text: status }];
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
async function resumeSession(session, replaceTranscript) {
|
|
47
|
+
const { messages: conversation, workState, parseErrors } = await restoreSessionState(session);
|
|
48
|
+
deps.sessionRef.current = session;
|
|
49
|
+
deps.conversationRef.current = conversation;
|
|
50
|
+
deps.setLiveMessagesState(() => []);
|
|
51
|
+
const restoredMessages = displayMessagesFromConversation(conversation);
|
|
52
|
+
deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
|
|
53
|
+
deps.workStateRef.current = workState;
|
|
54
|
+
for (const error of parseErrors) {
|
|
55
|
+
deps.debugLog(`Session parse error: ${error}`);
|
|
56
|
+
}
|
|
57
|
+
deps.setMessages(messages => {
|
|
58
|
+
const restored = [{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...restoredMessages];
|
|
59
|
+
return replaceTranscript ? restored : [...messages, ...restored];
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/** Heuristic-excerpt compaction shared by the sync path and the LLM fallback (F-09). */
|
|
63
|
+
function compactConversationSync(instructions) {
|
|
64
|
+
// Manual /compact and overflow recovery use the centralized fallback
|
|
65
|
+
// window (RH-005); the live turn path applies the model-aware budget.
|
|
66
|
+
const result = compactModelMessages(deps.conversationRef.current, { instructions, tokenBudget: FALLBACK_CONTEXT_WINDOW_TOKENS, workState: deps.workStateRef.current });
|
|
67
|
+
if (!result.compacted) {
|
|
68
|
+
deps.setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${result.keptCount} model messages in context.` }]);
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
deps.conversationRef.current = result.messages;
|
|
72
|
+
deps.sessionRecorder()?.recordNamedEvent('compact', `Compacted ${result.olderCount} messages; kept ${result.keptCount}.`);
|
|
73
|
+
deps.sessionRecorder()?.recordConversation(result.messages);
|
|
74
|
+
deps.setMessages(m => [...m, { role: 'system', text: `Compacted context: condensed ${result.olderCount} older model messages into a bounded excerpt and kept the last ${result.keptCount}.` }]);
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
async initializeSession() {
|
|
79
|
+
if (deps.noSession)
|
|
80
|
+
return;
|
|
81
|
+
if (deps.resumeSessionId) {
|
|
82
|
+
const session = await findSession(deps.resumeSessionId);
|
|
83
|
+
if (!session)
|
|
84
|
+
throw new Error(`No session named ${deps.resumeSessionId} exists for this workspace.`);
|
|
85
|
+
await resumeSession(session, false);
|
|
86
|
+
deps.sessionStartRef.current = new Date();
|
|
87
|
+
await startNewLog();
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (deps.continueSession) {
|
|
91
|
+
const session = await latestSession();
|
|
92
|
+
if (session) {
|
|
93
|
+
await resumeSession(session, false);
|
|
94
|
+
deps.sessionStartRef.current = new Date();
|
|
95
|
+
await startNewLog();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
await startNewSession(deps.continueSession ? 'No previous session found. New session started.' : 'New session started.', true);
|
|
100
|
+
},
|
|
101
|
+
startNewSession,
|
|
102
|
+
async resumeLatestSession() {
|
|
103
|
+
await deps.sessionRecorder()?.flush().catch(deps.showPersistenceWarning);
|
|
104
|
+
const session = await latestSession();
|
|
105
|
+
if (!session) {
|
|
106
|
+
deps.setMessages(m => [...m, { role: 'system', text: 'No previous session found for this workspace.' }]);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
await teardownBackgroundProcesses().catch(deps.showPersistenceWarning);
|
|
110
|
+
clearToolOutputs();
|
|
111
|
+
await resumeSession(session, true);
|
|
112
|
+
deps.sessionStartRef.current = new Date();
|
|
113
|
+
await startNewLog();
|
|
114
|
+
},
|
|
115
|
+
async resumeSessionById(id) {
|
|
116
|
+
await deps.sessionRecorder()?.flush().catch(deps.showPersistenceWarning);
|
|
117
|
+
const session = await findSession(id);
|
|
118
|
+
if (!session) {
|
|
119
|
+
deps.setMessages(m => [...m, { role: 'system', text: `No session named ${id} exists for this workspace.` }]);
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
await teardownBackgroundProcesses().catch(deps.showPersistenceWarning);
|
|
123
|
+
clearToolOutputs();
|
|
124
|
+
await resumeSession(session, true);
|
|
125
|
+
deps.sessionStartRef.current = new Date();
|
|
126
|
+
await startNewLog();
|
|
127
|
+
return true;
|
|
128
|
+
},
|
|
129
|
+
async forkSessionById(id) {
|
|
130
|
+
await deps.sessionRecorder()?.flush().catch(deps.showPersistenceWarning);
|
|
131
|
+
const source = await findSession(id);
|
|
132
|
+
if (!source) {
|
|
133
|
+
deps.setMessages(m => [...m, { role: 'system', text: `No session named ${id} exists for this workspace.` }]);
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
let forked;
|
|
137
|
+
try {
|
|
138
|
+
forked = await forkSession(source, { hazeVersion: deps.version, ...(deps.build ? { build: deps.build } : {}) });
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
deps.setMessages(m => [...m, { role: 'system', text: error instanceof Error ? error.message : String(error) }]);
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
const { session, parseErrors } = forked;
|
|
145
|
+
for (const error of parseErrors)
|
|
146
|
+
deps.debugLog(`Session parse error: ${error}`);
|
|
147
|
+
await teardownBackgroundProcesses().catch(deps.showPersistenceWarning);
|
|
148
|
+
clearToolOutputs();
|
|
149
|
+
await resumeSession(session, true);
|
|
150
|
+
deps.sessionStartRef.current = new Date();
|
|
151
|
+
await startNewLog();
|
|
152
|
+
deps.setMessages(m => [...m, { role: 'system', text: `Forked from session ${id}. The original was left unchanged.` }]);
|
|
153
|
+
return true;
|
|
154
|
+
},
|
|
155
|
+
async clearConversation() {
|
|
156
|
+
clearToolOutputs();
|
|
157
|
+
deps.conversationRef.current = [];
|
|
158
|
+
deps.lastAssistantTextRef.current = '';
|
|
159
|
+
deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
160
|
+
deps.workStateRef.current = undefined;
|
|
161
|
+
deps.setLiveMessagesState(() => []);
|
|
162
|
+
deps.setMessages(() => [{ role: 'system', text: 'Cleared. The void is productive.' }]);
|
|
163
|
+
deps.sessionRecorder()?.recordNamedEvent('clear', 'Conversation cleared');
|
|
164
|
+
await deps.sessionRecorder()?.flush().catch(deps.showPersistenceWarning);
|
|
165
|
+
await startNewLog().catch(deps.showPersistenceWarning);
|
|
166
|
+
},
|
|
167
|
+
compactConversation(instructions) {
|
|
168
|
+
return compactConversationSync(instructions);
|
|
169
|
+
},
|
|
170
|
+
async compactConversationWithModel(instructions) {
|
|
171
|
+
if ((deps.manualCompaction?.() ?? 'llm-summary') === 'heuristic')
|
|
172
|
+
return compactConversationSync(instructions);
|
|
173
|
+
const messages = deps.conversationRef.current;
|
|
174
|
+
const split = splitForCompaction(messages, { tokenBudget: FALLBACK_CONTEXT_WINDOW_TOKENS });
|
|
175
|
+
if (!split) {
|
|
176
|
+
deps.setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${messages.length} model messages in context.` }]);
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
const runtime = await modelWithConfig();
|
|
181
|
+
if (!runtime?.model)
|
|
182
|
+
throw new Error('no model provider configured');
|
|
183
|
+
const summarization = await generateText({
|
|
184
|
+
model: runtime.model,
|
|
185
|
+
prompt: buildLlmCompactionPrompt({ older: split.older, instructions }),
|
|
186
|
+
});
|
|
187
|
+
const summaryText = summarization.text.trim();
|
|
188
|
+
if (!summaryText)
|
|
189
|
+
throw new Error('model returned an empty summary');
|
|
190
|
+
const result = compactModelMessagesWithSummary(messages, { summaryText, tokenBudget: FALLBACK_CONTEXT_WINDOW_TOKENS, instructions, workState: deps.workStateRef.current });
|
|
191
|
+
if (!result.compacted)
|
|
192
|
+
throw new Error('nothing older to compact');
|
|
193
|
+
deps.conversationRef.current = result.messages;
|
|
194
|
+
deps.sessionRecorder()?.recordNamedEvent('compact', `Compacted ${result.olderCount} messages with a model-written summary; kept ${result.keptCount}.`);
|
|
195
|
+
deps.sessionRecorder()?.recordConversation(result.messages);
|
|
196
|
+
deps.setMessages(m => [...m, { role: 'system', text: `Compacted context: replaced ${result.olderCount} older model messages with a model-written summary and kept the last ${result.keptCount}.` }]);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
deps.debugLog(`LLM compaction failed (${error instanceof Error ? error.message : String(error)}); falling back to the heuristic excerpt`);
|
|
201
|
+
return compactConversationSync(instructions);
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|