@denizokcu/haze 0.6.0 → 0.8.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 +42 -7
- package/README.md +81 -34
- package/dist/cli/chat/TaskBar.d.ts +9 -0
- package/dist/cli/chat/TaskBar.js +40 -0
- package/dist/cli/chat/chatMetrics.d.ts +11 -0
- package/dist/cli/chat/chatMetrics.js +50 -0
- package/dist/cli/chat/inputSuggestions.d.ts +16 -0
- package/dist/cli/chat/inputSuggestions.js +55 -0
- package/dist/cli/chat/messages.d.ts +9 -0
- package/dist/cli/chat/messages.js +76 -0
- package/dist/cli/chat/sessionRecorder.d.ts +12 -0
- package/dist/cli/chat/sessionRecorder.js +21 -0
- package/dist/cli/chat/startupInfo.d.ts +4 -0
- package/dist/cli/chat/startupInfo.js +53 -0
- package/dist/cli/chat/turnState.d.ts +5 -0
- package/dist/cli/chat/turnState.js +20 -0
- package/dist/cli/commands/chat.d.ts +0 -1
- package/dist/cli/commands/chat.js +331 -906
- package/dist/cli/commands/chatModes.d.ts +8 -0
- package/dist/cli/commands/chatModes.js +44 -0
- package/dist/cli/commands/commandHelp.d.ts +6 -0
- package/dist/cli/commands/commandHelp.js +25 -0
- package/dist/cli/commands/commands.d.ts +1 -1
- package/dist/cli/commands/commands.js +41 -267
- package/dist/cli/commands/formatters.d.ts +6 -0
- package/dist/cli/commands/formatters.js +50 -4
- package/dist/cli/commands/initCommand.d.ts +2 -0
- package/dist/cli/commands/initCommand.js +19 -0
- package/dist/cli/commands/logsCommand.d.ts +2 -0
- package/dist/cli/commands/logsCommand.js +63 -0
- package/dist/cli/commands/lspWizard.d.ts +14 -0
- package/dist/cli/commands/lspWizard.js +44 -0
- package/dist/cli/commands/mcpWizard.d.ts +15 -0
- package/dist/cli/commands/mcpWizard.js +69 -0
- package/dist/cli/commands/modelCommand.d.ts +2 -0
- package/dist/cli/commands/modelCommand.js +36 -0
- package/dist/cli/commands/providerWizard.d.ts +30 -0
- package/dist/cli/commands/providerWizard.js +114 -0
- package/dist/cli/commands/runCommand.d.ts +16 -0
- package/dist/cli/commands/runCommand.js +170 -0
- package/dist/cli/commands/settingsSummary.d.ts +3 -0
- package/dist/cli/commands/settingsSummary.js +40 -0
- package/dist/cli/commands/skillConfirmRemove.d.ts +11 -0
- package/dist/cli/commands/skillConfirmRemove.js +19 -0
- package/dist/cli/commands/skillCreation.d.ts +12 -0
- package/dist/cli/commands/skillCreation.js +14 -0
- package/dist/cli/commands/skillWizard.d.ts +15 -0
- package/dist/cli/commands/skillWizard.js +38 -0
- package/dist/cli/commands/streaming/assistantText.d.ts +17 -0
- package/dist/cli/commands/streaming/assistantText.js +115 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +55 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +102 -0
- package/dist/cli/commands/streaming/toolResultState.d.ts +13 -0
- package/dist/cli/commands/streaming/toolResultState.js +25 -0
- package/dist/cli/commands/streaming/turnRuntime.d.ts +78 -0
- package/dist/cli/commands/streaming/turnRuntime.js +86 -0
- package/dist/cli/commands/streaming.d.ts +9 -25
- package/dist/cli/commands/streaming.js +109 -363
- package/dist/cli/commands/wizardActions.d.ts +40 -0
- package/dist/cli/commands/wizardActions.js +40 -0
- package/dist/cli/commands/wizardInput.d.ts +4 -0
- package/dist/cli/commands/wizardInput.js +19 -0
- package/dist/cli/commands/wizardPrompts.d.ts +22 -0
- package/dist/cli/commands/wizardPrompts.js +52 -0
- package/dist/cli/commands/wizardSuggestions.d.ts +23 -0
- package/dist/cli/commands/wizardSuggestions.js +139 -0
- package/dist/cli/index.js +62 -4
- package/dist/config/contextFiles.d.ts +8 -1
- package/dist/config/contextFiles.js +25 -12
- package/dist/config/lspSettings.js +3 -6
- package/dist/config/mcpSettings.js +5 -5
- package/dist/config/providers.js +8 -12
- package/dist/config/settings.d.ts +1 -0
- package/dist/config/settings.js +54 -2
- package/dist/config/skillSettings.js +4 -3
- package/dist/core/agent/budgets.d.ts +6 -0
- package/dist/core/agent/budgets.js +6 -0
- package/dist/core/agent/compaction.js +3 -3
- package/dist/core/agent/errors.js +1 -1
- package/dist/core/agent/requestAssembly.d.ts +1 -7
- package/dist/core/agent/requestAssembly.js +40 -5
- package/dist/core/agent/toolOutputStore.js +5 -4
- package/dist/core/agent/toolResults.d.ts +31 -0
- package/dist/core/agent/toolResults.js +42 -0
- package/dist/core/agent/turnPolicy.d.ts +8 -0
- package/dist/core/agent/turnPolicy.js +23 -0
- package/dist/core/agent/workState.d.ts +18 -5
- package/dist/core/agent/workState.js +39 -20
- package/dist/core/bashOutput/reducers/content.d.ts +1 -0
- package/dist/core/bashOutput/reducers/content.js +1 -1
- package/dist/core/bashOutput/reducers/gh.d.ts +1 -0
- package/dist/core/bashOutput/reducers/gh.js +77 -0
- package/dist/core/bashOutput/registry.js +18 -8
- package/dist/core/goal/completionPolicy.js +1 -1
- package/dist/core/goal/sessionGoal.d.ts +6 -30
- package/dist/core/goal/sessionGoal.js +3 -68
- package/dist/core/safety/bashClassifier.js +30 -0
- package/dist/core/safety/urlGuard.d.ts +1 -0
- package/dist/core/safety/urlGuard.js +6 -1
- package/dist/core/session/sessionSlimming.d.ts +5 -0
- package/dist/core/session/sessionSlimming.js +78 -0
- package/dist/core/session/sessionStore.d.ts +23 -3
- package/dist/core/session/sessionStore.js +30 -10
- package/dist/core/subagent/subagentRunner.d.ts +258 -5
- package/dist/core/subagent/subagentRunner.js +14 -18
- package/dist/core/toolOutput/reduction.d.ts +2 -0
- package/dist/core/toolOutput/reduction.js +12 -0
- package/dist/core/validation/outputParser.js +5 -3
- package/dist/llm/capabilities.d.ts +12 -0
- package/dist/llm/capabilities.js +10 -0
- package/dist/llm/client.d.ts +3 -2
- package/dist/llm/client.js +26 -4
- package/dist/llm/hazeTools.d.ts +7710 -366
- package/dist/llm/hazeTools.js +46 -567
- package/dist/llm/initPrompt.js +1 -1
- package/dist/llm/lsp.d.ts +46 -1
- package/dist/llm/lsp.js +19 -10
- package/dist/llm/lspTools.d.ts +2310 -119
- package/dist/llm/mcp.js +9 -0
- package/dist/llm/requestContext.js +7 -22
- package/dist/llm/systemPrompt.d.ts +1 -0
- package/dist/llm/systemPrompt.js +3 -3
- package/dist/llm/tools/bashTool.d.ts +251 -0
- package/dist/llm/tools/bashTool.js +82 -0
- package/dist/llm/tools/editMatch.d.ts +55 -0
- package/dist/llm/tools/editMatch.js +99 -0
- package/dist/llm/tools/failures.d.ts +36 -0
- package/dist/llm/tools/failures.js +38 -0
- package/dist/llm/tools/fetchTool.d.ts +1201 -0
- package/dist/llm/tools/fetchTool.js +46 -0
- package/dist/llm/tools/fileToolShared.d.ts +10 -0
- package/dist/llm/tools/fileToolShared.js +43 -0
- package/dist/llm/tools/grepParse.d.ts +13 -0
- package/dist/llm/tools/grepParse.js +67 -0
- package/dist/llm/tools/outputCap.d.ts +53 -0
- package/dist/llm/tools/outputCap.js +67 -0
- package/dist/llm/tools/storedOutputTool.d.ts +351 -0
- package/dist/llm/tools/storedOutputTool.js +17 -0
- package/dist/llm/tools/taskTool.d.ts +629 -0
- package/dist/llm/tools/taskTool.js +41 -0
- package/dist/llm/tools/toolContext.d.ts +74 -0
- package/dist/llm/tools/toolContext.js +196 -0
- package/dist/llm/tools/workspaceFile.d.ts +33 -0
- package/dist/llm/tools/workspaceFile.js +27 -0
- package/dist/llm/webFetch.d.ts +13 -1
- package/dist/llm/webFetch.js +122 -28
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +8 -8
- package/dist/ui/components/TextInput.d.ts +7 -0
- package/dist/ui/components/TextInput.js +10 -98
- package/dist/ui/inputBuffer.d.ts +28 -0
- package/dist/ui/inputBuffer.js +99 -0
- package/dist/utils/collections.d.ts +6 -0
- package/dist/utils/collections.js +9 -0
- package/dist/utils/modelName.d.ts +2 -0
- package/dist/utils/modelName.js +15 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +40 -0
- package/examples/skills/files/SKILL.md +1 -1
- package/package.json +14 -15
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { isSkillEnabled, setSkillEnabled } from '../../config/skillSettings.js';
|
|
2
|
+
import { COMMON_ACTIONS, SKILL_ACTIONS, SKILL_CHOICES } from './wizardActions.js';
|
|
3
|
+
export function selectSkillResult(skills, name) {
|
|
4
|
+
if (name === SKILL_CHOICES.addSkill)
|
|
5
|
+
return { mode: 'skillsAddName', clearDraft: true, message: 'Name the skill (kebab-case, e.g. security-review). ESC cancels.' };
|
|
6
|
+
const skill = skills.find(candidate => candidate.name === name);
|
|
7
|
+
if (!skill)
|
|
8
|
+
return { mode: 'chat', message: `No skill named ${name}. Use /skills and choose add skill.` };
|
|
9
|
+
return { mode: 'skillsAction', selectedName: skill.name, message: `${skill.name}: choose an action.` };
|
|
10
|
+
}
|
|
11
|
+
export function skillInfoMessage(settings, skill) {
|
|
12
|
+
return [
|
|
13
|
+
`${skill.name}`,
|
|
14
|
+
skill.description,
|
|
15
|
+
'',
|
|
16
|
+
`References: ${skill.references.length}`,
|
|
17
|
+
`Path: ${skill.dir}`,
|
|
18
|
+
`State: ${isSkillEnabled(settings, skill.name) ? 'enabled' : 'disabled'}`,
|
|
19
|
+
].join('\n');
|
|
20
|
+
}
|
|
21
|
+
export function selectSkillActionResult(settings, skills, selectedName, action) {
|
|
22
|
+
if (!selectedName)
|
|
23
|
+
return { mode: 'skills' };
|
|
24
|
+
const skill = skills.find(candidate => candidate.name === selectedName);
|
|
25
|
+
if (!skill)
|
|
26
|
+
return { mode: 'chat', selectedName: undefined, message: `Skill ${selectedName} not found.` };
|
|
27
|
+
if (action === COMMON_ACTIONS.enable || action === COMMON_ACTIONS.disable) {
|
|
28
|
+
const enabled = action === COMMON_ACTIONS.enable;
|
|
29
|
+
return { mode: 'chat', selectedName: undefined, settingsPatch: { skills: setSkillEnabled(settings, selectedName, enabled) }, message: `Skill ${selectedName} ${enabled ? 'enabled' : 'disabled'}.`, skill };
|
|
30
|
+
}
|
|
31
|
+
if (action === SKILL_ACTIONS.showInfo)
|
|
32
|
+
return { message: skillInfoMessage(settings, skill), skill };
|
|
33
|
+
if (action === SKILL_ACTIONS.validate)
|
|
34
|
+
return { validate: true, skill };
|
|
35
|
+
if (action === SKILL_ACTIONS.removeSkill)
|
|
36
|
+
return { mode: 'skillsConfirmRemove', message: `Remove skill ${selectedName}? This deletes ~/.haze/skills/${selectedName}. Type "yes" to confirm. Esc to cancel.`, skill };
|
|
37
|
+
return { message: `Unknown skill action: ${action}`, skill };
|
|
38
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure heuristics for gating and normalizing streamed assistant text.
|
|
3
|
+
*
|
|
4
|
+
* These decide when an assistant segment is "substantive" enough to show,
|
|
5
|
+
* whether a fragment is an unfinished markdown/bridge prefix that should stay
|
|
6
|
+
* hidden, and how to strip synthetic tool-call markup. None of them touch
|
|
7
|
+
* agent/callback state, which keeps them trivially unit-testable.
|
|
8
|
+
*/
|
|
9
|
+
export declare function sanitizeAssistantText(text: string): string;
|
|
10
|
+
export declare function isSubstantiveAssistantText(text: string): boolean;
|
|
11
|
+
export declare function isShortLeadInBeforeTool(text: string): boolean;
|
|
12
|
+
export declare function isShortUnfinishedLeadIn(text: string): boolean;
|
|
13
|
+
export declare function isHiddenAssistantFragment(text: string): boolean;
|
|
14
|
+
export declare function isHiddenUnstartedFinalText(text: string): boolean;
|
|
15
|
+
export declare function shouldStartAssistantStream(text: string, startedAt: number): boolean;
|
|
16
|
+
export declare function assistantDisplayText(text: string): string;
|
|
17
|
+
export declare function normalizeAssistantText(text: string): string;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure heuristics for gating and normalizing streamed assistant text.
|
|
3
|
+
*
|
|
4
|
+
* These decide when an assistant segment is "substantive" enough to show,
|
|
5
|
+
* whether a fragment is an unfinished markdown/bridge prefix that should stay
|
|
6
|
+
* hidden, and how to strip synthetic tool-call markup. None of them touch
|
|
7
|
+
* agent/callback state, which keeps them trivially unit-testable.
|
|
8
|
+
*/
|
|
9
|
+
export function sanitizeAssistantText(text) {
|
|
10
|
+
return [...text].filter(char => {
|
|
11
|
+
const code = char.charCodeAt(0);
|
|
12
|
+
return !(code <= 8 || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127 || code === 155);
|
|
13
|
+
}).join('');
|
|
14
|
+
}
|
|
15
|
+
function hideSyntheticToolCallMarkup(text) {
|
|
16
|
+
return text
|
|
17
|
+
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*?<\/tool_call>\s*(?:```)?/gi, '$1')
|
|
18
|
+
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*$/i, '$1');
|
|
19
|
+
}
|
|
20
|
+
function isWordChar(char) {
|
|
21
|
+
return char.toLowerCase() !== char.toUpperCase() || (char >= '0' && char <= '9');
|
|
22
|
+
}
|
|
23
|
+
function wordCount(text) {
|
|
24
|
+
let count = 0;
|
|
25
|
+
let inWord = false;
|
|
26
|
+
for (const char of text) {
|
|
27
|
+
if (isWordChar(char)) {
|
|
28
|
+
if (!inWord)
|
|
29
|
+
count += 1;
|
|
30
|
+
inWord = true;
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
inWord = false;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return count;
|
|
37
|
+
}
|
|
38
|
+
function endsWithSentenceBoundary(text) {
|
|
39
|
+
const trimmed = text.trim();
|
|
40
|
+
if (!trimmed || wordCount(trimmed) === 0)
|
|
41
|
+
return false;
|
|
42
|
+
const last = trimmed.at(-1) ?? '';
|
|
43
|
+
return last === '.' || last === '!' || last === '?' || last === ':' || last === ';' || last === ')';
|
|
44
|
+
}
|
|
45
|
+
function isNonSubstantiveAssistantText(text) {
|
|
46
|
+
return wordCount(text) === 0;
|
|
47
|
+
}
|
|
48
|
+
export function isSubstantiveAssistantText(text) {
|
|
49
|
+
const trimmed = text.trim();
|
|
50
|
+
const words = wordCount(trimmed);
|
|
51
|
+
if (words === 0)
|
|
52
|
+
return false;
|
|
53
|
+
if (trimmed.length >= 24)
|
|
54
|
+
return true;
|
|
55
|
+
if (endsWithSentenceBoundary(trimmed))
|
|
56
|
+
return true;
|
|
57
|
+
return words >= 4;
|
|
58
|
+
}
|
|
59
|
+
function isIncompleteAssistantFragment(text) {
|
|
60
|
+
const trimmed = text.trim();
|
|
61
|
+
return !isSubstantiveAssistantText(trimmed) && wordCount(trimmed) <= 2 && !endsWithSentenceBoundary(trimmed);
|
|
62
|
+
}
|
|
63
|
+
function isLikelyUnfinishedMarkdownFragment(text) {
|
|
64
|
+
const trimmed = text.trim();
|
|
65
|
+
if (!trimmed.includes('\n'))
|
|
66
|
+
return false;
|
|
67
|
+
const last = trimmed.at(-1) ?? '';
|
|
68
|
+
return last === '-' || last === '*' || last === '#' || last === '`' || last === '>';
|
|
69
|
+
}
|
|
70
|
+
// Procedural pre-tool lead-ins (e.g. "Confirmed:", "Files written.", "Now let me",
|
|
71
|
+
// "I checked the tests.") are short preambles the model emits before calling a tool; they
|
|
72
|
+
// should stay hidden so they don't surface as standalone bubbles. The ceiling is kept well
|
|
73
|
+
// below the length of genuine multi-segment answer content: a substantive sentence of ~12
|
|
74
|
+
// words preceding a tool call is real answer text and must be preserved (see the
|
|
75
|
+
// multi-segment headless integration test). Empirically procedural lead-ins are <=5 words,
|
|
76
|
+
// so 6 catches them while leaving real content visible.
|
|
77
|
+
const LEAD_IN_WORD_CEILING = 6;
|
|
78
|
+
export function isShortLeadInBeforeTool(text) {
|
|
79
|
+
const trimmed = text.trim();
|
|
80
|
+
return trimmed.length > 0 && wordCount(trimmed) <= LEAD_IN_WORD_CEILING && !isLikelyUnfinishedMarkdownFragment(trimmed);
|
|
81
|
+
}
|
|
82
|
+
export function isShortUnfinishedLeadIn(text) {
|
|
83
|
+
const trimmed = text.trim();
|
|
84
|
+
const words = wordCount(trimmed);
|
|
85
|
+
return words >= 3
|
|
86
|
+
&& words <= 4
|
|
87
|
+
&& !isSubstantiveAssistantText(trimmed)
|
|
88
|
+
&& !endsWithSentenceBoundary(trimmed)
|
|
89
|
+
&& !isLikelyUnfinishedMarkdownFragment(trimmed);
|
|
90
|
+
}
|
|
91
|
+
function isHiddenAssistantText(text) {
|
|
92
|
+
return text.length === 0 || isNonSubstantiveAssistantText(text);
|
|
93
|
+
}
|
|
94
|
+
export function isHiddenAssistantFragment(text) {
|
|
95
|
+
return isHiddenAssistantText(text) || isIncompleteAssistantFragment(text) || isLikelyUnfinishedMarkdownFragment(text);
|
|
96
|
+
}
|
|
97
|
+
export function isHiddenUnstartedFinalText(text) {
|
|
98
|
+
return isHiddenAssistantText(text) || isLikelyUnfinishedMarkdownFragment(text);
|
|
99
|
+
}
|
|
100
|
+
const ASSISTANT_STREAM_DEBOUNCE_MS = 200;
|
|
101
|
+
export function shouldStartAssistantStream(text, startedAt) {
|
|
102
|
+
if (isHiddenAssistantFragment(text))
|
|
103
|
+
return false;
|
|
104
|
+
return isSubstantiveAssistantText(text) || Date.now() - startedAt >= ASSISTANT_STREAM_DEBOUNCE_MS;
|
|
105
|
+
}
|
|
106
|
+
export function assistantDisplayText(text) {
|
|
107
|
+
return hideSyntheticToolCallMarkup(text).trim();
|
|
108
|
+
}
|
|
109
|
+
export function normalizeAssistantText(text) {
|
|
110
|
+
return assistantDisplayText(text)
|
|
111
|
+
.replace(/[`*_~#>\-–—:;,.!?()[\]{}"']/g, '')
|
|
112
|
+
.replace(/\s+/g, ' ')
|
|
113
|
+
.trim()
|
|
114
|
+
.toLowerCase();
|
|
115
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type AgentEventSink } from '../../../core/agent/events.js';
|
|
2
|
+
import { type LlmLog } from '../../../core/log/llmLog.js';
|
|
3
|
+
/**
|
|
4
|
+
* Live "tool group" renderer for the agent turn: batches concurrent/sequential
|
|
5
|
+
* tool calls into one rolling `tool` chat message with a summary header and a
|
|
6
|
+
* per-call line (icon, summary, result, duration). Holds its own mutable state
|
|
7
|
+
* (the active group + a 1s refresh timer) so `runAgentTurn` stays linear.
|
|
8
|
+
*/
|
|
9
|
+
export type NativeToolCall = {
|
|
10
|
+
toolCallId: string;
|
|
11
|
+
toolName: string;
|
|
12
|
+
input: unknown;
|
|
13
|
+
};
|
|
14
|
+
export type ToolDisplayItem = {
|
|
15
|
+
id: string;
|
|
16
|
+
summary: string;
|
|
17
|
+
status: 'running' | 'success' | 'error';
|
|
18
|
+
result?: string;
|
|
19
|
+
startedAt: number;
|
|
20
|
+
finishedAt?: number;
|
|
21
|
+
durationMs?: number;
|
|
22
|
+
showResult?: boolean;
|
|
23
|
+
};
|
|
24
|
+
export interface ToolGroupRendererDeps {
|
|
25
|
+
addMessage: (msg: {
|
|
26
|
+
id: string;
|
|
27
|
+
role: 'tool';
|
|
28
|
+
text: string;
|
|
29
|
+
streaming: boolean;
|
|
30
|
+
}) => void;
|
|
31
|
+
updateMessage: (id: string, update: {
|
|
32
|
+
text?: string;
|
|
33
|
+
streaming?: boolean;
|
|
34
|
+
}) => void;
|
|
35
|
+
debugLog: (line: string) => void;
|
|
36
|
+
onEvent?: AgentEventSink;
|
|
37
|
+
log?: LlmLog;
|
|
38
|
+
}
|
|
39
|
+
export interface ToolGroupRenderer {
|
|
40
|
+
/** Find or create the display item for a tool call (rendering + logging on first sight). */
|
|
41
|
+
ensureToolItem: (toolCall: NativeToolCall) => ToolDisplayItem;
|
|
42
|
+
/** Re-render the active group (e.g. after mutating an item's status/result). */
|
|
43
|
+
updateToolGroup: (streaming?: boolean) => void;
|
|
44
|
+
/** Finalize the current group and start a fresh one (used when text resumes). */
|
|
45
|
+
startFreshToolGroup: () => void;
|
|
46
|
+
/** Final, non-streaming render of the active group if not already finalized. */
|
|
47
|
+
finalizeToolGroup: () => void;
|
|
48
|
+
/** Stop the 1s refresh timer. */
|
|
49
|
+
stopToolTimer: () => void;
|
|
50
|
+
/** Attach a dim caption line above the next tool group. */
|
|
51
|
+
setGroupCaption: (text: string) => void;
|
|
52
|
+
/** Add a scoped context-file read to the active tool group display. */
|
|
53
|
+
addContextFileRead: (path: string) => void;
|
|
54
|
+
}
|
|
55
|
+
export declare function createToolGroupRenderer(deps: ToolGroupRendererDeps): ToolGroupRenderer;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
|
+
import { appendLogEntry as logAppend } from '../../../core/log/llmLog.js';
|
|
3
|
+
import { toolCallSummary, compact, formatElapsedTimeWhole, formatSeconds } from '../formatters.js';
|
|
4
|
+
function logEntry(log, entry) {
|
|
5
|
+
if (log)
|
|
6
|
+
void logAppend(log, entry).catch(() => undefined);
|
|
7
|
+
}
|
|
8
|
+
const createToolGroup = () => ({ id: `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`, items: [], started: false, finalized: false });
|
|
9
|
+
export function createToolGroupRenderer(deps) {
|
|
10
|
+
let toolGroup = createToolGroup();
|
|
11
|
+
let toolTimer;
|
|
12
|
+
let pendingCaption;
|
|
13
|
+
const setGroupCaption = (text) => { pendingCaption = text.trim() || undefined; };
|
|
14
|
+
const renderToolGroup = (group) => {
|
|
15
|
+
const running = group.items.some(item => item.status === 'running');
|
|
16
|
+
const failures = group.items.filter(item => item.status === 'error').length;
|
|
17
|
+
const changes = group.items.filter(item => /^(editFile|replaceLines|writeFile)\b/.test(item.summary)).length;
|
|
18
|
+
const elapsedMs = group.items.length > 0
|
|
19
|
+
? (running ? Date.now() : Math.max(...group.items.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...group.items.map(item => item.startedAt))
|
|
20
|
+
: 0;
|
|
21
|
+
const summaryParts = [`${group.items.length} calls`, `${changes} changes`];
|
|
22
|
+
if (failures > 0)
|
|
23
|
+
summaryParts.push(`${failures} failed`);
|
|
24
|
+
summaryParts.push(formatElapsedTimeWhole(elapsedMs));
|
|
25
|
+
const lines = [summaryParts.join(' · '), ...group.items.map(item => {
|
|
26
|
+
const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
|
|
27
|
+
const result = item.status === 'running' || item.showResult === false ? '' : ` — ${item.result ?? item.status}${item.durationMs == null ? '' : ` in ${formatSeconds(item.durationMs)}`}`;
|
|
28
|
+
return ` ${icon} ${item.summary}${result}`;
|
|
29
|
+
})];
|
|
30
|
+
return (group.caption ? [group.caption, ...lines] : lines).join('\n');
|
|
31
|
+
};
|
|
32
|
+
const updateToolGroup = (streaming = true, group = toolGroup) => {
|
|
33
|
+
const text = renderToolGroup(group);
|
|
34
|
+
if (!group.started) {
|
|
35
|
+
group.started = true;
|
|
36
|
+
group.finalized = !streaming;
|
|
37
|
+
deps.addMessage({ id: group.id, role: 'tool', text, streaming });
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
group.finalized = !streaming;
|
|
41
|
+
deps.updateMessage(group.id, { text, streaming });
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const finalizeToolGroup = (group = toolGroup) => {
|
|
45
|
+
if (!group.started || group.finalized)
|
|
46
|
+
return;
|
|
47
|
+
updateToolGroup(false, group);
|
|
48
|
+
};
|
|
49
|
+
const stopToolTimer = () => {
|
|
50
|
+
if (!toolTimer)
|
|
51
|
+
return;
|
|
52
|
+
clearInterval(toolTimer);
|
|
53
|
+
toolTimer = undefined;
|
|
54
|
+
};
|
|
55
|
+
const startToolTimer = () => {
|
|
56
|
+
if (toolTimer)
|
|
57
|
+
return;
|
|
58
|
+
toolTimer = setInterval(() => {
|
|
59
|
+
if (toolGroup.items.some(item => item.status === 'running'))
|
|
60
|
+
updateToolGroup(true);
|
|
61
|
+
else
|
|
62
|
+
stopToolTimer();
|
|
63
|
+
}, 1000);
|
|
64
|
+
};
|
|
65
|
+
const ensureToolItem = (toolCall) => {
|
|
66
|
+
if (toolGroup.finalized)
|
|
67
|
+
toolGroup = createToolGroup();
|
|
68
|
+
if (pendingCaption && toolGroup.items.length === 0) {
|
|
69
|
+
toolGroup.caption = pendingCaption;
|
|
70
|
+
pendingCaption = undefined;
|
|
71
|
+
}
|
|
72
|
+
let item = toolGroup.items.find(candidate => candidate.id === toolCall.toolCallId);
|
|
73
|
+
if (!item) {
|
|
74
|
+
item = { id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() };
|
|
75
|
+
toolGroup.items.push(item);
|
|
76
|
+
deps.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
|
|
77
|
+
logEntry(deps.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
|
|
78
|
+
deps.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
|
|
79
|
+
startToolTimer();
|
|
80
|
+
updateToolGroup(true);
|
|
81
|
+
}
|
|
82
|
+
return item;
|
|
83
|
+
};
|
|
84
|
+
const startFreshToolGroup = () => {
|
|
85
|
+
if (!toolGroup.started || toolGroup.items.some(item => item.status === 'running'))
|
|
86
|
+
return;
|
|
87
|
+
finalizeToolGroup(toolGroup);
|
|
88
|
+
toolGroup = createToolGroup();
|
|
89
|
+
};
|
|
90
|
+
const addContextFileRead = (path) => {
|
|
91
|
+
if (toolGroup.finalized)
|
|
92
|
+
toolGroup = createToolGroup();
|
|
93
|
+
if (pendingCaption && toolGroup.items.length === 0) {
|
|
94
|
+
toolGroup.caption = pendingCaption;
|
|
95
|
+
pendingCaption = undefined;
|
|
96
|
+
}
|
|
97
|
+
const now = Date.now();
|
|
98
|
+
toolGroup.items.push({ id: `context-file-${now}-${Math.random().toString(36).slice(2)}`, summary: `understanding: ${path}`, status: 'success', startedAt: now, finishedAt: now, durationMs: 0, showResult: false });
|
|
99
|
+
updateToolGroup(true);
|
|
100
|
+
};
|
|
101
|
+
return { ensureToolItem, updateToolGroup, startFreshToolGroup, finalizeToolGroup, stopToolTimer, setGroupCaption, addContextFileRead };
|
|
102
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface ToolResultState {
|
|
2
|
+
mutatingToolSucceeded: boolean;
|
|
3
|
+
editRecoveryPath?: string;
|
|
4
|
+
editRecoveryReadSatisfied: boolean;
|
|
5
|
+
}
|
|
6
|
+
export declare function initialToolResultState(): ToolResultState;
|
|
7
|
+
export declare function applyToolResultState(state: ToolResultState, event: {
|
|
8
|
+
toolName: string;
|
|
9
|
+
input: unknown;
|
|
10
|
+
output: unknown;
|
|
11
|
+
ok: boolean;
|
|
12
|
+
}): ToolResultState;
|
|
13
|
+
export declare function isMutatingToolName(toolName: string): boolean;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { isDuplicateSkippedOutput, toolInputField } from '../../../core/agent/toolResults.js';
|
|
2
|
+
const MUTATING_TOOLS = new Set(['editFile', 'replaceLines', 'writeFile']);
|
|
3
|
+
export function initialToolResultState() {
|
|
4
|
+
return { mutatingToolSucceeded: false, editRecoveryReadSatisfied: false };
|
|
5
|
+
}
|
|
6
|
+
export function applyToolResultState(state, event) {
|
|
7
|
+
const path = toolInputField(event.input, 'path');
|
|
8
|
+
if (!event.ok && MUTATING_TOOLS.has(event.toolName)) {
|
|
9
|
+
return { ...state, editRecoveryPath: path, editRecoveryReadSatisfied: false };
|
|
10
|
+
}
|
|
11
|
+
if (event.ok && event.toolName === 'readFile' && path && path === state.editRecoveryPath && !isDuplicateSkippedOutput(event.output)) {
|
|
12
|
+
return { ...state, editRecoveryReadSatisfied: true };
|
|
13
|
+
}
|
|
14
|
+
if (event.ok && !isDuplicateSkippedOutput(event.output) && MUTATING_TOOLS.has(event.toolName)) {
|
|
15
|
+
return {
|
|
16
|
+
mutatingToolSucceeded: true,
|
|
17
|
+
editRecoveryPath: !path || path === state.editRecoveryPath ? undefined : state.editRecoveryPath,
|
|
18
|
+
editRecoveryReadSatisfied: !path || path === state.editRecoveryPath ? false : state.editRecoveryReadSatisfied,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
return state;
|
|
22
|
+
}
|
|
23
|
+
export function isMutatingToolName(toolName) {
|
|
24
|
+
return MUTATING_TOOLS.has(toolName);
|
|
25
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { ModelMessage } from 'ai';
|
|
2
|
+
import type { ContextFile } from '../../../config/contextFiles.js';
|
|
3
|
+
export interface TokenUsage {
|
|
4
|
+
inputTokens: number | undefined;
|
|
5
|
+
outputTokens: number | undefined;
|
|
6
|
+
systemPrompt: number;
|
|
7
|
+
messages: number;
|
|
8
|
+
toolSchemas: number;
|
|
9
|
+
outputEstimate: number;
|
|
10
|
+
cacheReadTokens: number;
|
|
11
|
+
cacheWriteTokens: number;
|
|
12
|
+
noCacheTokens: number;
|
|
13
|
+
reasoningTokens: number;
|
|
14
|
+
logicalInputEstimate: number;
|
|
15
|
+
effectiveNonCachedInput: number | undefined;
|
|
16
|
+
}
|
|
17
|
+
export declare function retryDelayMs(attempt: number): number;
|
|
18
|
+
export declare function abortableDelay(milliseconds: number, signal: AbortSignal): Promise<void>;
|
|
19
|
+
export declare function estimateInputBreakdown(input: {
|
|
20
|
+
system: string;
|
|
21
|
+
contextFiles: ContextFile[];
|
|
22
|
+
messages: ModelMessage[];
|
|
23
|
+
tools?: Record<string, unknown>;
|
|
24
|
+
}): {
|
|
25
|
+
breakdown: import("../../../core/agent/contextBudget.js").ContextBreakdown;
|
|
26
|
+
systemPrompt: number;
|
|
27
|
+
messages: number;
|
|
28
|
+
toolSchemas: number;
|
|
29
|
+
logicalInputEstimate: number;
|
|
30
|
+
};
|
|
31
|
+
export declare function responseCompletionMetrics(text: string, generationStartedAt: number): {
|
|
32
|
+
finishedAt: number;
|
|
33
|
+
tokensPerSecond: number | undefined;
|
|
34
|
+
};
|
|
35
|
+
export declare function extractUsage(event: {
|
|
36
|
+
usage?: {
|
|
37
|
+
inputTokens?: number;
|
|
38
|
+
outputTokens?: number;
|
|
39
|
+
inputTokenDetails?: {
|
|
40
|
+
cacheReadTokens?: number;
|
|
41
|
+
cacheWriteTokens?: number;
|
|
42
|
+
noCacheTokens?: number;
|
|
43
|
+
};
|
|
44
|
+
outputTokenDetails?: {
|
|
45
|
+
reasoningTokens?: number;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
}): {
|
|
49
|
+
inputTokens: number | undefined;
|
|
50
|
+
outputTokens: number | undefined;
|
|
51
|
+
cacheReadTokens: number;
|
|
52
|
+
cacheWriteTokens: number;
|
|
53
|
+
noCacheTokens: number;
|
|
54
|
+
effectiveNonCachedInput: number | undefined;
|
|
55
|
+
reasoningTokens: number;
|
|
56
|
+
};
|
|
57
|
+
export declare function stepCacheMetrics(usage: {
|
|
58
|
+
inputTokens?: number;
|
|
59
|
+
inputTokenDetails?: {
|
|
60
|
+
cacheReadTokens?: number;
|
|
61
|
+
cacheWriteTokens?: number;
|
|
62
|
+
};
|
|
63
|
+
outputTokenDetails?: {
|
|
64
|
+
reasoningTokens?: number;
|
|
65
|
+
};
|
|
66
|
+
} | undefined): {
|
|
67
|
+
inputTokens: number | undefined;
|
|
68
|
+
cacheReadTokens: number;
|
|
69
|
+
cacheWriteTokens: number;
|
|
70
|
+
reasoningTokens: number;
|
|
71
|
+
noCacheTokens: number;
|
|
72
|
+
cacheHitRatio: number | undefined;
|
|
73
|
+
};
|
|
74
|
+
export declare function subagentTokenEstimate(output: unknown): {
|
|
75
|
+
input: number;
|
|
76
|
+
output: number;
|
|
77
|
+
} | undefined;
|
|
78
|
+
export declare function rememberContextFilesFromToolOutput(activeContextFiles: ContextFile[], output: unknown): ContextFile[];
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { cacheHitRatio, contextBreakdown, effectiveNonCachedInput, estimateValueTokens } from '../../../core/agent/contextBudget.js';
|
|
2
|
+
export function retryDelayMs(attempt) {
|
|
3
|
+
return Math.min(4000, 1000 * 2 ** attempt);
|
|
4
|
+
}
|
|
5
|
+
export async function abortableDelay(milliseconds, signal) {
|
|
6
|
+
if (signal.aborted)
|
|
7
|
+
return;
|
|
8
|
+
await new Promise(resolve => {
|
|
9
|
+
const timer = setTimeout(resolve, milliseconds);
|
|
10
|
+
signal.addEventListener('abort', () => {
|
|
11
|
+
clearTimeout(timer);
|
|
12
|
+
resolve();
|
|
13
|
+
}, { once: true });
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
export function estimateInputBreakdown(input) {
|
|
17
|
+
const breakdown = contextBreakdown(input);
|
|
18
|
+
return {
|
|
19
|
+
breakdown,
|
|
20
|
+
systemPrompt: breakdown.system,
|
|
21
|
+
messages: Object.values(breakdown.messagesByRole).reduce((sum, value) => sum + value, 0),
|
|
22
|
+
toolSchemas: breakdown.toolSchemas.reduce((sum, value) => sum + value.tokens, 0),
|
|
23
|
+
logicalInputEstimate: breakdown.logicalInputEstimate,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export function responseCompletionMetrics(text, generationStartedAt) {
|
|
27
|
+
const finishedAt = Date.now();
|
|
28
|
+
const elapsedSeconds = Math.max((finishedAt - generationStartedAt) / 1000, 0.001);
|
|
29
|
+
const outputTokens = estimateValueTokens(text);
|
|
30
|
+
return {
|
|
31
|
+
finishedAt,
|
|
32
|
+
tokensPerSecond: outputTokens > 0 ? outputTokens / elapsedSeconds : undefined,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export function extractUsage(event) {
|
|
36
|
+
const cacheReadTokens = event.usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
37
|
+
const computedNonCachedInput = effectiveNonCachedInput(event.usage?.inputTokens, cacheReadTokens);
|
|
38
|
+
return {
|
|
39
|
+
inputTokens: event.usage?.inputTokens,
|
|
40
|
+
outputTokens: event.usage?.outputTokens,
|
|
41
|
+
cacheReadTokens,
|
|
42
|
+
cacheWriteTokens: event.usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
|
|
43
|
+
noCacheTokens: event.usage?.inputTokenDetails?.noCacheTokens ?? computedNonCachedInput ?? 0,
|
|
44
|
+
effectiveNonCachedInput: computedNonCachedInput,
|
|
45
|
+
reasoningTokens: event.usage?.outputTokenDetails?.reasoningTokens ?? 0,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function stepCacheMetrics(usage) {
|
|
49
|
+
const inputTokens = usage?.inputTokens;
|
|
50
|
+
const cacheReadTokens = usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
51
|
+
return {
|
|
52
|
+
inputTokens,
|
|
53
|
+
cacheReadTokens,
|
|
54
|
+
cacheWriteTokens: usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
|
|
55
|
+
reasoningTokens: usage?.outputTokenDetails?.reasoningTokens ?? 0,
|
|
56
|
+
noCacheTokens: effectiveNonCachedInput(inputTokens, cacheReadTokens) ?? 0,
|
|
57
|
+
cacheHitRatio: cacheHitRatio(inputTokens, cacheReadTokens || undefined),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export function subagentTokenEstimate(output) {
|
|
61
|
+
if (typeof output !== 'object' || output == null || !('tokens' in output))
|
|
62
|
+
return undefined;
|
|
63
|
+
const tokens = output.tokens;
|
|
64
|
+
const input = typeof tokens?.in === 'number' ? tokens.in : 0;
|
|
65
|
+
const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
|
|
66
|
+
return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
|
|
67
|
+
}
|
|
68
|
+
export function rememberContextFilesFromToolOutput(activeContextFiles, output) {
|
|
69
|
+
if (typeof output !== 'object' || output == null)
|
|
70
|
+
return activeContextFiles;
|
|
71
|
+
const files = output.applicableProjectInstructions;
|
|
72
|
+
if (!Array.isArray(files))
|
|
73
|
+
return activeContextFiles;
|
|
74
|
+
const seen = new Set(activeContextFiles.map(file => file.path));
|
|
75
|
+
const next = [...activeContextFiles];
|
|
76
|
+
for (const file of files) {
|
|
77
|
+
if (typeof file !== 'object' || file == null)
|
|
78
|
+
continue;
|
|
79
|
+
const candidate = file;
|
|
80
|
+
if (typeof candidate.path !== 'string' || typeof candidate.content !== 'string' || seen.has(candidate.path))
|
|
81
|
+
continue;
|
|
82
|
+
next.push({ path: candidate.path, content: candidate.content });
|
|
83
|
+
seen.add(candidate.path);
|
|
84
|
+
}
|
|
85
|
+
return next;
|
|
86
|
+
}
|
|
@@ -3,7 +3,10 @@ import type { LlmLog } from '../../core/log/llmLog.js';
|
|
|
3
3
|
import { type PromptSession } from '../../llm/systemPrompt.js';
|
|
4
4
|
import type { ContextFile } from '../../config/contextFiles.js';
|
|
5
5
|
import { type AgentEventSink } from '../../core/agent/events.js';
|
|
6
|
+
export { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
|
|
6
7
|
import type { WorkState } from '../../core/agent/workState.js';
|
|
8
|
+
import { type TokenUsage } from './streaming/turnRuntime.js';
|
|
9
|
+
export type { TokenUsage } from './streaming/turnRuntime.js';
|
|
7
10
|
export type Message = {
|
|
8
11
|
id?: string;
|
|
9
12
|
role: 'system' | 'user' | 'assistant' | 'tool';
|
|
@@ -15,30 +18,10 @@ export type Message = {
|
|
|
15
18
|
tokensPerSecond?: number;
|
|
16
19
|
displayOrder?: number;
|
|
17
20
|
};
|
|
18
|
-
export
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
export declare function toolOnlyStepCount(steps: Array<{
|
|
23
|
-
toolCalls: unknown[];
|
|
24
|
-
text: string;
|
|
25
|
-
}>): number;
|
|
26
|
-
export declare function isShortUnfinishedBridgeBeforeTool(text: string): boolean;
|
|
27
|
-
export declare function isHiddenUnstartedFinalText(text: string): boolean;
|
|
28
|
-
export declare function shouldStartAssistantStream(text: string, startedAt: number): boolean;
|
|
29
|
-
export interface TokenUsage {
|
|
30
|
-
inputTokens: number | undefined;
|
|
31
|
-
outputTokens: number | undefined;
|
|
32
|
-
systemPrompt: number;
|
|
33
|
-
messages: number;
|
|
34
|
-
toolSchemas: number;
|
|
35
|
-
outputEstimate: number;
|
|
36
|
-
cacheReadTokens: number;
|
|
37
|
-
cacheWriteTokens: number;
|
|
38
|
-
noCacheTokens: number;
|
|
39
|
-
reasoningTokens: number;
|
|
40
|
-
logicalInputEstimate: number;
|
|
41
|
-
effectiveNonCachedInput: number | undefined;
|
|
21
|
+
export type TurnStatus = 'complete' | 'aborted' | 'failed';
|
|
22
|
+
/** Authoritative outcome of a turn, so callers (esp. headless/CI) need not sniff message text. */
|
|
23
|
+
export interface TurnResult {
|
|
24
|
+
status: TurnStatus;
|
|
42
25
|
}
|
|
43
26
|
export interface StreamCallbacks {
|
|
44
27
|
addMessage: (msg: Message) => void;
|
|
@@ -58,5 +41,6 @@ export interface StreamCallbacks {
|
|
|
58
41
|
setWorkState?: (state: WorkState) => void;
|
|
59
42
|
onTasksChanged?: () => void;
|
|
60
43
|
log?: LlmLog;
|
|
44
|
+
contextFileSignatures?: Map<string, string>;
|
|
61
45
|
}
|
|
62
|
-
export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession): Promise<
|
|
46
|
+
export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession, modelOverride?: string): Promise<TurnResult>;
|