@denizokcu/haze 0.10.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 +77 -1
- package/README.md +66 -25
- 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/contextReport.js +2 -0
- package/dist/cli/chat/fileMentionSuggestions.js +3 -2
- 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 +9 -0
- package/dist/cli/chat/sessionLifecycle.js +64 -14
- package/dist/cli/chat/sessionRecorder.js +75 -7
- package/dist/cli/chat/startupInfo.d.ts +0 -1
- package/dist/cli/chat/startupInfo.js +11 -15
- package/dist/cli/chat/wizardDispatch.js +111 -12
- package/dist/cli/commands/chat.d.ts +5 -0
- package/dist/cli/commands/chat.js +203 -101
- package/dist/cli/commands/commands.d.ts +2 -0
- package/dist/cli/commands/commands.js +10 -5
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/formatters.js +2 -0
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +9 -2
- package/dist/cli/commands/providerWizard.js +37 -4
- package/dist/cli/commands/runCommand.d.ts +3 -0
- package/dist/cli/commands/runCommand.js +117 -11
- 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/toolCallRecovery.d.ts +2 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
- 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.d.ts +70 -3
- package/dist/cli/commands/streaming.js +491 -77
- package/dist/cli/commands/wizardActions.d.ts +1 -0
- package/dist/cli/commands/wizardActions.js +1 -0
- package/dist/cli/commands/wizardPrompts.js +7 -1
- package/dist/cli/commands/wizardSuggestions.js +5 -3
- package/dist/cli/index.js +68 -22
- package/dist/cli/terminalTitle.js +1 -1
- package/dist/config/modelDiscovery.d.ts +51 -0
- package/dist/config/modelDiscovery.js +164 -1
- 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 +39 -7
- package/dist/config/providerPresets.js +371 -100
- package/dist/config/providers.js +2 -0
- package/dist/config/settings.d.ts +36 -0
- package/dist/config/settings.js +9 -0
- package/dist/core/agent/budgets.d.ts +10 -0
- package/dist/core/agent/budgets.js +10 -0
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +92 -17
- package/dist/core/agent/completionController.d.ts +230 -0
- package/dist/core/agent/completionController.js +287 -0
- package/dist/core/agent/contextBudget.d.ts +38 -0
- package/dist/core/agent/contextBudget.js +60 -7
- package/dist/core/agent/events.d.ts +74 -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 +8 -0
- package/dist/core/agent/toolOutputStore.js +10 -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 +75 -0
- package/dist/core/agent/workState.js +120 -9
- 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/limits/byteBudgets.d.ts +2 -0
- package/dist/core/limits/byteBudgets.js +2 -0
- package/dist/core/limits/textBudgets.d.ts +2 -0
- package/dist/core/limits/textBudgets.js +2 -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.js +8 -7
- package/dist/core/process/runBoundedProcess.d.ts +8 -2
- package/dist/core/process/runBoundedProcess.js +15 -6
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -0
- package/dist/core/session/sessionStore.d.ts +37 -0
- package/dist/core/session/sessionStore.js +215 -51
- package/dist/core/subagent/contracts.d.ts +4 -0
- package/dist/core/subagent/contracts.js +1 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
- package/dist/core/subagent/subagentCoordinator.js +32 -2
- package/dist/core/subagent/subagentRunner.js +17 -37
- package/dist/llm/client.d.ts +17 -1
- package/dist/llm/client.js +82 -14
- package/dist/llm/hazeTools.d.ts +554 -80
- package/dist/llm/hazeTools.js +103 -24
- package/dist/llm/lsp.d.ts +24 -4
- package/dist/llm/lsp.js +72 -11
- 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 +3 -0
- package/dist/llm/requestContext.js +7 -4
- package/dist/llm/systemPrompt.d.ts +11 -0
- package/dist/llm/systemPrompt.js +12 -6
- package/dist/llm/toolResultTypes.d.ts +8 -1
- package/dist/llm/tools/bashTool.d.ts +48 -16
- package/dist/llm/tools/bashTool.js +5 -0
- 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 +16 -0
- package/dist/llm/tools/fileToolShared.d.ts +4 -3
- package/dist/llm/tools/fileToolShared.js +16 -21
- package/dist/llm/tools/gitIgnore.d.ts +49 -0
- package/dist/llm/tools/gitIgnore.js +129 -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 +1 -1
- package/dist/llm/tools/toolContext.js +61 -32
- package/dist/llm/webFetch.d.ts +17 -0
- package/dist/llm/webFetch.js +64 -97
- 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 +8 -1
- package/dist/ui/components/TextInput.js +6 -2
- 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/fs.d.ts +9 -0
- package/dist/utils/fs.js +87 -25
- package/dist/utils/openPath.d.ts +2 -2
- package/dist/utils/openPath.js +19 -6
- 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
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import wrapAnsi from 'wrap-ansi';
|
|
2
|
+
/**
|
|
3
|
+
* Live-region row budgeting.
|
|
4
|
+
*
|
|
5
|
+
* Ink reclaims the terminal with `clearTerminal` (which erases scrollback)
|
|
6
|
+
* whenever the *dynamic* frame grows taller than the viewport, so every dynamic
|
|
7
|
+
* section must be clamped to keep the frame under one screen. These helpers
|
|
8
|
+
* mirror Ink's own line wrapping (`wrapAnsi` with `trim: false, hard: true`) so
|
|
9
|
+
* our row estimates match what Ink actually renders.
|
|
10
|
+
*/
|
|
11
|
+
/** Wrap one logical line exactly like an Ink `<Text>` with default wrap mode. */
|
|
12
|
+
export function wrapLine(line, width) {
|
|
13
|
+
const safeWidth = Math.max(1, width);
|
|
14
|
+
if (line.length === 0)
|
|
15
|
+
return [''];
|
|
16
|
+
return wrapAnsi(line, safeWidth, { trim: false, hard: true }).split('\n');
|
|
17
|
+
}
|
|
18
|
+
/** Wrapped row count of a logical line at the given width. */
|
|
19
|
+
export function lineRows(line, width) {
|
|
20
|
+
return wrapLine(line, width).length;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Keep the last `maxLines` wrapped rows of `text`, dropping whole logical lines
|
|
24
|
+
* from the top (a wrapped group is never split). When clamping occurs, one row
|
|
25
|
+
* is reserved for the caller's `⋯ +N lines` indicator. Nothing is lost: the
|
|
26
|
+
* full text is committed verbatim to the static transcript once it settles.
|
|
27
|
+
*/
|
|
28
|
+
export function clampTextTail(text, width, maxLines) {
|
|
29
|
+
if (maxLines < 1)
|
|
30
|
+
return { text: '', hiddenLineCount: 0 };
|
|
31
|
+
const logical = text.replace(/\r\n|\r/g, '\n').split('\n');
|
|
32
|
+
const rows = logical.map(line => lineRows(line, width));
|
|
33
|
+
const total = rows.reduce((sum, count) => sum + count, 0);
|
|
34
|
+
if (total <= maxLines)
|
|
35
|
+
return { text, hiddenLineCount: 0 };
|
|
36
|
+
const visibleBudget = Math.max(1, maxLines - 1); // reserve the indicator row
|
|
37
|
+
let used = 0;
|
|
38
|
+
let start = logical.length;
|
|
39
|
+
while (start > 0) {
|
|
40
|
+
const next = rows[start - 1] ?? 0;
|
|
41
|
+
if (used + next > visibleBudget)
|
|
42
|
+
break;
|
|
43
|
+
used += next;
|
|
44
|
+
start -= 1;
|
|
45
|
+
}
|
|
46
|
+
const hiddenLineCount = rows.slice(0, start).reduce((sum, count) => sum + count, 0);
|
|
47
|
+
return { text: logical.slice(start).join('\n'), hiddenLineCount };
|
|
48
|
+
}
|
|
@@ -1,9 +1,40 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import type { Message } from '../commands/streaming.js';
|
|
3
3
|
export declare function messageElapsedLabel(message: Message): string;
|
|
4
|
-
export declare
|
|
4
|
+
export declare const AssistantMarkdownChunkView: React.MemoExoticComponent<({ message, content, width, first, final }: {
|
|
5
5
|
message: Message;
|
|
6
|
+
content: string;
|
|
6
7
|
width: number;
|
|
7
|
-
|
|
8
|
+
first: boolean;
|
|
9
|
+
final: boolean;
|
|
10
|
+
}) => React.JSX.Element>;
|
|
11
|
+
export declare const MessageView: React.MemoExoticComponent<({ message, width, showHeader, maxVisibleLines }: {
|
|
12
|
+
message: Message;
|
|
13
|
+
width: number;
|
|
14
|
+
showHeader?: boolean;
|
|
15
|
+
maxVisibleLines?: number;
|
|
16
|
+
}) => React.JSX.Element>;
|
|
8
17
|
export declare function messageKey(message: Message, index: number): string;
|
|
18
|
+
export type TranscriptStaticItem = {
|
|
19
|
+
kind: 'message';
|
|
20
|
+
key: string;
|
|
21
|
+
message: Message;
|
|
22
|
+
} | {
|
|
23
|
+
kind: 'assistant-markdown';
|
|
24
|
+
key: string;
|
|
25
|
+
message: Message;
|
|
26
|
+
content: string;
|
|
27
|
+
first: boolean;
|
|
28
|
+
final: boolean;
|
|
29
|
+
};
|
|
30
|
+
export type TranscriptStreamingItem = {
|
|
31
|
+
key: string;
|
|
32
|
+
message: Message;
|
|
33
|
+
showHeader?: boolean;
|
|
34
|
+
};
|
|
35
|
+
/** Partition display messages into append-only static Markdown roots and the active streaming tail. */
|
|
36
|
+
export declare function partitionDisplayMessages(messages: Message[]): {
|
|
37
|
+
staticItems: TranscriptStaticItem[];
|
|
38
|
+
streamingItems: TranscriptStreamingItem[];
|
|
39
|
+
};
|
|
9
40
|
export declare function orderedDisplayMessages(messages: Message[]): Message[];
|
|
@@ -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 }))
|
|
@@ -13,6 +13,11 @@ import type { SessionRecorder } from './sessionRecorder.js';
|
|
|
13
13
|
*/
|
|
14
14
|
export interface SessionLifecycleDeps {
|
|
15
15
|
version?: string;
|
|
16
|
+
/** Safe build provenance (commit, build time) recorded into session headers. */
|
|
17
|
+
build?: {
|
|
18
|
+
commit?: string;
|
|
19
|
+
builtAt?: string;
|
|
20
|
+
};
|
|
16
21
|
continueSession: boolean;
|
|
17
22
|
resumeSessionId?: string;
|
|
18
23
|
noSession: boolean;
|
|
@@ -43,6 +48,8 @@ export interface SessionLifecycleDeps {
|
|
|
43
48
|
setMessages: (updater: (messages: Message[]) => Message[]) => void;
|
|
44
49
|
setLiveMessagesState: (updater: (messages: Message[]) => Message[]) => void;
|
|
45
50
|
setTokenUsage: (usage: TokenUsage) => void;
|
|
51
|
+
/** Manual /compact mode: model-written summary (default) or heuristic excerpt. */
|
|
52
|
+
manualCompaction?: () => 'llm-summary' | 'heuristic';
|
|
46
53
|
debugLog: (line: string) => void;
|
|
47
54
|
showPersistenceWarning: (error: unknown) => void;
|
|
48
55
|
}
|
|
@@ -54,5 +61,7 @@ export interface SessionLifecycle {
|
|
|
54
61
|
forkSessionById: (id: string) => Promise<boolean>;
|
|
55
62
|
clearConversation: () => Promise<void>;
|
|
56
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>;
|
|
57
66
|
}
|
|
58
67
|
export declare function createSessionLifecycle(deps: SessionLifecycleDeps): SessionLifecycle;
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import {
|
|
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';
|
|
2
4
|
import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
|
|
5
|
+
import { modelWithConfig } from '../../llm/client.js';
|
|
3
6
|
import { createSession, findSession, forkSession, formatSession, latestSession, restoreSessionState } from '../../core/session/sessionStore.js';
|
|
4
7
|
import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
|
|
5
8
|
import { displayMessagesFromConversation, estimateConversationTokens } from './chatMetrics.js';
|
|
@@ -16,7 +19,7 @@ export function createSessionLifecycle(deps) {
|
|
|
16
19
|
deps.llmLogRef.current = log;
|
|
17
20
|
return log;
|
|
18
21
|
}
|
|
19
|
-
async function startNewSession(message = '
|
|
22
|
+
async function startNewSession(message = 'New session started.', mergeWithPreviousInfo = false) {
|
|
20
23
|
await teardownBackgroundProcesses().catch(deps.showPersistenceWarning);
|
|
21
24
|
await deps.sessionRecorder()?.flush().catch(deps.showPersistenceWarning);
|
|
22
25
|
clearToolOutputs();
|
|
@@ -27,11 +30,18 @@ export function createSessionLifecycle(deps) {
|
|
|
27
30
|
deps.sessionRef.current = undefined;
|
|
28
31
|
return;
|
|
29
32
|
}
|
|
30
|
-
const session = await createSession({ hazeVersion: deps.version });
|
|
33
|
+
const session = await createSession({ hazeVersion: deps.version, ...(deps.build ? { build: deps.build } : {}) });
|
|
31
34
|
deps.sessionRef.current = session;
|
|
32
35
|
deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
33
36
|
await startNewLog();
|
|
34
|
-
|
|
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
|
+
});
|
|
35
45
|
}
|
|
36
46
|
async function resumeSession(session, replaceTranscript) {
|
|
37
47
|
const { messages: conversation, workState, parseErrors } = await restoreSessionState(session);
|
|
@@ -49,6 +59,21 @@ export function createSessionLifecycle(deps) {
|
|
|
49
59
|
return replaceTranscript ? restored : [...messages, ...restored];
|
|
50
60
|
});
|
|
51
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
|
+
}
|
|
52
77
|
return {
|
|
53
78
|
async initializeSession() {
|
|
54
79
|
if (deps.noSession)
|
|
@@ -71,7 +96,7 @@ export function createSessionLifecycle(deps) {
|
|
|
71
96
|
return;
|
|
72
97
|
}
|
|
73
98
|
}
|
|
74
|
-
await startNewSession(deps.continueSession ? 'No previous session found.
|
|
99
|
+
await startNewSession(deps.continueSession ? 'No previous session found. New session started.' : 'New session started.', true);
|
|
75
100
|
},
|
|
76
101
|
startNewSession,
|
|
77
102
|
async resumeLatestSession() {
|
|
@@ -110,7 +135,7 @@ export function createSessionLifecycle(deps) {
|
|
|
110
135
|
}
|
|
111
136
|
let forked;
|
|
112
137
|
try {
|
|
113
|
-
forked = await forkSession(source, { hazeVersion: deps.version });
|
|
138
|
+
forked = await forkSession(source, { hazeVersion: deps.version, ...(deps.build ? { build: deps.build } : {}) });
|
|
114
139
|
}
|
|
115
140
|
catch (error) {
|
|
116
141
|
deps.setMessages(m => [...m, { role: 'system', text: error instanceof Error ? error.message : String(error) }]);
|
|
@@ -140,16 +165,41 @@ export function createSessionLifecycle(deps) {
|
|
|
140
165
|
await startNewLog().catch(deps.showPersistenceWarning);
|
|
141
166
|
},
|
|
142
167
|
compactConversation(instructions) {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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.` }]);
|
|
146
177
|
return false;
|
|
147
178
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
+
}
|
|
153
203
|
},
|
|
154
204
|
};
|
|
155
205
|
}
|
|
@@ -4,31 +4,99 @@ export function createSessionRecorder(getSession) {
|
|
|
4
4
|
// Ordered appends and first-error capture come from the shared writer
|
|
5
5
|
// primitive; entries recorded before a session exists are dropped (CR-005).
|
|
6
6
|
const writer = new OrderedFileWriter(({ session, entry }) => appendSessionEntry(session, entry));
|
|
7
|
-
const
|
|
7
|
+
const appendEntry = (entry) => {
|
|
8
8
|
const session = getSession();
|
|
9
9
|
if (!session)
|
|
10
10
|
return;
|
|
11
11
|
void writer.append({ session, entry });
|
|
12
12
|
};
|
|
13
|
+
// Full-history snapshot coalescing (RH-008). conversation_snapshot and
|
|
14
|
+
// work_state_snapshot entries are large and only the latest of each is ever
|
|
15
|
+
// restored. A long autonomous turn calls setConversation many times; writing
|
|
16
|
+
// the full history on every call makes the JSONL grow quadratically. Keep at
|
|
17
|
+
// most one snapshot of each type in flight: while a write is pending, newer
|
|
18
|
+
// snapshots replace the pending one so only the latest reaches disk.
|
|
19
|
+
let pendingConversation;
|
|
20
|
+
let pendingWorkState;
|
|
21
|
+
let conversationInFlight = false;
|
|
22
|
+
let workStateInFlight = false;
|
|
23
|
+
const writeConversation = (snapshot) => {
|
|
24
|
+
const session = getSession();
|
|
25
|
+
if (!session)
|
|
26
|
+
return;
|
|
27
|
+
conversationInFlight = true;
|
|
28
|
+
void writer
|
|
29
|
+
.append({ session, entry: { type: 'conversation_snapshot', at: snapshot.at, messages: snapshot.messages } })
|
|
30
|
+
.catch(() => undefined)
|
|
31
|
+
.finally(() => {
|
|
32
|
+
conversationInFlight = false;
|
|
33
|
+
drainConversation();
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
const drainConversation = () => {
|
|
37
|
+
if (conversationInFlight || !pendingConversation)
|
|
38
|
+
return;
|
|
39
|
+
const snapshot = pendingConversation;
|
|
40
|
+
pendingConversation = undefined;
|
|
41
|
+
writeConversation(snapshot);
|
|
42
|
+
};
|
|
43
|
+
const writeWorkState = (snapshot) => {
|
|
44
|
+
const session = getSession();
|
|
45
|
+
if (!session)
|
|
46
|
+
return;
|
|
47
|
+
workStateInFlight = true;
|
|
48
|
+
void writer
|
|
49
|
+
.append({ session, entry: { type: 'work_state_snapshot', at: snapshot.at, state: snapshot.state } })
|
|
50
|
+
.catch(() => undefined)
|
|
51
|
+
.finally(() => {
|
|
52
|
+
workStateInFlight = false;
|
|
53
|
+
drainWorkState();
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
const drainWorkState = () => {
|
|
57
|
+
if (workStateInFlight || !pendingWorkState)
|
|
58
|
+
return;
|
|
59
|
+
const snapshot = pendingWorkState;
|
|
60
|
+
pendingWorkState = undefined;
|
|
61
|
+
writeWorkState(snapshot);
|
|
62
|
+
};
|
|
13
63
|
return {
|
|
14
64
|
recordUiMessage(message) {
|
|
15
|
-
|
|
65
|
+
appendEntry({ type: 'ui_message', at: new Date().toISOString(), role: message.role, text: message.text });
|
|
16
66
|
},
|
|
17
67
|
recordConversation(messages) {
|
|
18
|
-
|
|
68
|
+
pendingConversation = { messages, at: new Date().toISOString() };
|
|
69
|
+
drainConversation();
|
|
19
70
|
},
|
|
20
71
|
recordWorkState(state) {
|
|
21
|
-
|
|
72
|
+
pendingWorkState = { state, at: new Date().toISOString() };
|
|
73
|
+
drainWorkState();
|
|
22
74
|
},
|
|
23
75
|
recordEvent(event) {
|
|
24
|
-
|
|
76
|
+
// message_update is transient UI progress; never persist it (RH-006). It is
|
|
77
|
+
// dropped here, before JSON.stringify, so high-volume streaming updates do
|
|
78
|
+
// not pay serialization or queueing cost in the durable writer.
|
|
79
|
+
if (event.type === 'message_update')
|
|
80
|
+
return;
|
|
81
|
+
appendEntry({ type: 'event', at: event.at, name: event.type, text: JSON.stringify(event) });
|
|
25
82
|
},
|
|
26
83
|
recordNamedEvent(name, text) {
|
|
27
|
-
|
|
84
|
+
appendEntry({ type: 'event', at: new Date().toISOString(), name, text });
|
|
28
85
|
},
|
|
29
86
|
async flush() {
|
|
87
|
+
// Fold coalesced snapshots into the writer queue, then wait for the queue
|
|
88
|
+
// to drain. Loop because a write completing mid-flush may have queued a
|
|
89
|
+
// newer coalesced snapshot from its finally callback.
|
|
90
|
+
let guard = 0;
|
|
91
|
+
while ((pendingConversation || conversationInFlight || pendingWorkState || workStateInFlight) && guard++ < 1000) {
|
|
92
|
+
drainConversation();
|
|
93
|
+
drainWorkState();
|
|
94
|
+
await writer.flush();
|
|
95
|
+
}
|
|
30
96
|
await writer.flush();
|
|
31
97
|
},
|
|
32
|
-
error() {
|
|
98
|
+
error() {
|
|
99
|
+
return writer.error();
|
|
100
|
+
},
|
|
33
101
|
};
|
|
34
102
|
}
|