@denizokcu/haze 0.5.0 → 0.7.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 +36 -1
- package/README.md +101 -24
- 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 +519 -495
- 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 +3 -2
- package/dist/cli/commands/commands.js +55 -320
- package/dist/cli/commands/formatters.d.ts +27 -0
- package/dist/cli/commands/formatters.js +149 -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 +10 -29
- package/dist/cli/commands/streaming.js +249 -911
- 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.d.ts +16 -0
- package/dist/config/lspSettings.js +95 -0
- package/dist/config/mcpSettings.d.ts +24 -0
- package/dist/config/mcpSettings.js +100 -0
- package/dist/config/providers.js +4 -4
- package/dist/config/settings.d.ts +34 -0
- package/dist/config/skillSettings.d.ts +15 -0
- package/dist/config/skillSettings.js +32 -0
- package/dist/config/updateCheck.d.ts +44 -0
- package/dist/config/updateCheck.js +83 -0
- package/dist/core/agent/budgets.d.ts +6 -0
- package/dist/core/agent/budgets.js +6 -0
- package/dist/core/agent/compaction.js +1 -1
- package/dist/core/agent/requestAssembly.d.ts +0 -7
- package/dist/core/agent/requestAssembly.js +27 -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 +8 -0
- 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 +11 -1
- package/dist/core/subagent/subagentRunner.js +1 -0
- package/dist/llm/capabilities.d.ts +12 -0
- package/dist/llm/capabilities.js +10 -0
- package/dist/llm/client.d.ts +1 -0
- package/dist/llm/client.js +11 -2
- package/dist/llm/hazeTools.d.ts +31 -32
- package/dist/llm/hazeTools.js +40 -567
- package/dist/llm/lsp.d.ts +109 -0
- package/dist/llm/lsp.js +241 -0
- package/dist/llm/lspTools.d.ts +104 -0
- package/dist/llm/lspTools.js +115 -0
- package/dist/llm/mcp.d.ts +19 -0
- package/dist/llm/mcp.js +73 -0
- package/dist/llm/requestContext.d.ts +28 -0
- package/dist/llm/requestContext.js +41 -0
- package/dist/llm/systemPrompt.d.ts +5 -1
- package/dist/llm/systemPrompt.js +9 -3
- package/dist/llm/tools/bashTool.d.ts +5 -0
- package/dist/llm/tools/bashTool.js +81 -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 +65 -0
- package/dist/llm/tools/fetchTool.js +45 -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 +10 -0
- package/dist/llm/tools/storedOutputTool.js +17 -0
- package/dist/llm/tools/taskTool.d.ts +28 -0
- package/dist/llm/tools/taskTool.js +41 -0
- package/dist/llm/tools/toolContext.d.ts +69 -0
- package/dist/llm/tools/toolContext.js +187 -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 +91 -7
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +24 -45
- package/dist/ui/components/TextInput.d.ts +1 -1
- package/dist/ui/components/TextInput.js +1 -99
- 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/path.d.ts +2 -0
- package/dist/utils/path.js +40 -0
- package/dist/utils/version.d.ts +20 -0
- package/dist/utils/version.js +72 -0
- package/package.json +2 -2
- package/dist/cli/commands/skills.d.ts +0 -4
- package/dist/cli/commands/skills.js +0 -38
|
@@ -9,8 +9,10 @@ export function compact(value, maxLength = 180) {
|
|
|
9
9
|
else {
|
|
10
10
|
text = JSON.stringify(value, (_key, nestedValue) => nestedValue instanceof Error ? nestedValue.message : nestedValue);
|
|
11
11
|
}
|
|
12
|
-
if (!text
|
|
13
|
-
return
|
|
12
|
+
if (!text)
|
|
13
|
+
return value === null ? 'null' : value === undefined ? 'undefined' : '';
|
|
14
|
+
if (text === '{}')
|
|
15
|
+
return ''; // empty object: nothing useful to render; avoid "[object Object]"
|
|
14
16
|
return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text;
|
|
15
17
|
}
|
|
16
18
|
export function toolCallSummary(toolName, input) {
|
|
@@ -26,14 +28,20 @@ export function toolCallSummary(toolName, input) {
|
|
|
26
28
|
}
|
|
27
29
|
if (toolName === 'listFiles' && typeof data?.path === 'string')
|
|
28
30
|
return `listFiles ${data.path}`;
|
|
29
|
-
if ((toolName === 'readFile' || toolName === 'writeFile')
|
|
30
|
-
|
|
31
|
+
if ((toolName === 'readFile' || toolName === 'writeFile')) {
|
|
32
|
+
if (typeof data?.path === 'string')
|
|
33
|
+
return `${toolName} ${data.path}`;
|
|
34
|
+
if (data == null || (typeof data === 'object' && Object.keys(data).length === 0))
|
|
35
|
+
return toolName; // input not yet streamed (tool-input-start) or empty
|
|
36
|
+
}
|
|
31
37
|
if (toolName === 'editFile' && typeof data?.path === 'string') {
|
|
32
38
|
const edits = Array.isArray(data.edits) ? ` (${data.edits.length} edit${data.edits.length === 1 ? '' : 's'})` : '';
|
|
33
39
|
return `${toolName} ${data.path}${edits}`;
|
|
34
40
|
}
|
|
35
41
|
if (toolName === 'replaceLines' && typeof data?.path === 'string')
|
|
36
42
|
return `replaceLines ${data.path}:${data.startLine}-${data.endLine}`;
|
|
43
|
+
if ((toolName === 'editFile' || toolName === 'replaceLines') && (data == null || (typeof data === 'object' && Object.keys(data).length === 0)))
|
|
44
|
+
return toolName;
|
|
37
45
|
if (toolName === 'subagent' && typeof data?.task === 'string') {
|
|
38
46
|
const taskPreview = data.task.length > 60 ? `${data.task.slice(0, 60).trimEnd()}…` : data.task;
|
|
39
47
|
return `subagent "${taskPreview}"`;
|
|
@@ -42,6 +50,12 @@ export function toolCallSummary(toolName, input) {
|
|
|
42
50
|
const tasks = Array.isArray(data?.tasks) ? data.tasks : [];
|
|
43
51
|
return `writeTasks (${tasks.length} task${tasks.length === 1 ? '' : 's'})`;
|
|
44
52
|
}
|
|
53
|
+
if (toolName === 'lspWorkspaceSymbols' && typeof data?.query === 'string')
|
|
54
|
+
return `lspWorkspaceSymbols "${data.query}"`;
|
|
55
|
+
if (toolName === 'lspSymbols' && typeof data?.path === 'string')
|
|
56
|
+
return `lspSymbols ${data.path}`;
|
|
57
|
+
if ((toolName === 'lspDefinition' || toolName === 'lspReferences') && typeof data?.path === 'string')
|
|
58
|
+
return `${toolName} ${data.path}:${data.line}:${data.column}`;
|
|
45
59
|
return `${toolName} ${compact(input)}`;
|
|
46
60
|
}
|
|
47
61
|
export function toolResultSummary(event) {
|
|
@@ -73,6 +87,14 @@ export function toolResultSummary(event) {
|
|
|
73
87
|
const meta = calls > 0 ? ` (${calls} call${calls === 1 ? '' : 's'}${duration})` : '';
|
|
74
88
|
return `${output.status}${meta}: ${preview}`;
|
|
75
89
|
}
|
|
90
|
+
if (typeof output?.server === 'string' && Array.isArray(output.symbols)) {
|
|
91
|
+
const count = output.symbols.length;
|
|
92
|
+
return `${count} symbol${count === 1 ? '' : 's'} from ${output.server}`;
|
|
93
|
+
}
|
|
94
|
+
if (typeof output?.server === 'string' && Array.isArray(output.locations)) {
|
|
95
|
+
const count = output.locations.length;
|
|
96
|
+
return `${count} location${count === 1 ? '' : 's'} from ${output.server}`;
|
|
97
|
+
}
|
|
76
98
|
if (typeof output?.ok === 'boolean') {
|
|
77
99
|
// writeTasks result
|
|
78
100
|
if (output.ok && typeof output.summary === 'string') {
|
|
@@ -141,3 +163,126 @@ export function toolOutputDetails(value) {
|
|
|
141
163
|
const truncated = output.stdout?.truncated || output.stderr?.truncated;
|
|
142
164
|
return `${parts.join('\n\n')}${truncated ? '\n… output truncated' : ''}`;
|
|
143
165
|
}
|
|
166
|
+
const CONTEXT_CATEGORY_LABEL = {
|
|
167
|
+
builtin: 'Built-in',
|
|
168
|
+
lsp: 'LSP',
|
|
169
|
+
skill: 'Skills',
|
|
170
|
+
subagent: 'Subagent',
|
|
171
|
+
mcp: 'MCP',
|
|
172
|
+
};
|
|
173
|
+
const CONTEXT_CATEGORY_ORDER = ['builtin', 'lsp', 'skill', 'subagent', 'mcp'];
|
|
174
|
+
function num(n) {
|
|
175
|
+
return Math.round(n).toLocaleString('en-US');
|
|
176
|
+
}
|
|
177
|
+
// Bar chart glyphs: full block, 1/8..7/8 left-fill blocks, and a light track.
|
|
178
|
+
const BAR_FULL = '█';
|
|
179
|
+
const BAR_EMPTY = '░';
|
|
180
|
+
const BAR_PARTIAL = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉'];
|
|
181
|
+
/** A fixed-width horizontal bar; `value` vs `max` controls the filled fraction. */
|
|
182
|
+
function bar(value, max, width) {
|
|
183
|
+
if (width <= 0)
|
|
184
|
+
return '';
|
|
185
|
+
if (max <= 0 || value <= 0)
|
|
186
|
+
return BAR_EMPTY.repeat(width);
|
|
187
|
+
const scaled = Math.min(1, value / max) * width;
|
|
188
|
+
let whole = Math.floor(scaled);
|
|
189
|
+
let partial = Math.round((scaled - whole) * 8); // 0..8
|
|
190
|
+
if (partial >= 8) {
|
|
191
|
+
whole += 1;
|
|
192
|
+
partial = 0;
|
|
193
|
+
}
|
|
194
|
+
whole = Math.min(whole, width);
|
|
195
|
+
if (whole === 0 && partial === 0 && value > 0)
|
|
196
|
+
partial = 1; // ensure a sliver for any nonzero value
|
|
197
|
+
const partialGlyph = (whole < width && partial > 0) ? BAR_PARTIAL[partial] : '';
|
|
198
|
+
const filled = BAR_FULL.repeat(whole);
|
|
199
|
+
const emptyCount = width - filled.length - partialGlyph.length;
|
|
200
|
+
return `${filled}${partialGlyph}${emptyCount > 0 ? BAR_EMPTY.repeat(emptyCount) : ''}`;
|
|
201
|
+
}
|
|
202
|
+
function row(label, tokens, total, labelCol, numCol, barWidth, indent = 0) {
|
|
203
|
+
const prefix = `${' '.repeat(indent)}${label}`.padEnd(labelCol);
|
|
204
|
+
const pct = total > 0 ? `${Math.round((tokens / total) * 100)}%`.padStart(4) : ' -';
|
|
205
|
+
return `${prefix}${bar(tokens, total, barWidth)} ${num(tokens).padStart(numCol)} ${pct}`;
|
|
206
|
+
}
|
|
207
|
+
/** Render a detailed, /context-style token breakdown. Pure for testability. */
|
|
208
|
+
export function formatContextReport(data) {
|
|
209
|
+
const lines = [];
|
|
210
|
+
lines.push(`Context overview — model: ${data.modelLabel}`);
|
|
211
|
+
lines.push(`Estimated input: ~${num(data.logicalInputEstimate)} tokens (4 chars/token heuristic). Bars show each row's share of that total; tool results/inputs are subsets of the messages total.`);
|
|
212
|
+
lines.push('');
|
|
213
|
+
const projectTokens = data.projectContext.reduce((sum, file) => sum + file.tokens, 0);
|
|
214
|
+
const toolsTotal = data.tools.reduce((sum, tool) => sum + tool.tokens, 0);
|
|
215
|
+
const messagesTotal = Object.values(data.messagesByRole).reduce((sum, value) => sum + value, 0);
|
|
216
|
+
const resultsTotal = Object.values(data.toolResults).reduce((sum, value) => sum + value, 0);
|
|
217
|
+
const inputsTotal = Object.values(data.toolInputs).reduce((sum, value) => sum + value, 0);
|
|
218
|
+
const numberValues = [
|
|
219
|
+
data.systemTokens, toolsTotal, messagesTotal, data.logicalInputEstimate, projectTokens, resultsTotal, inputsTotal,
|
|
220
|
+
...data.tools.map(tool => tool.tokens),
|
|
221
|
+
...Object.values(data.toolResults), ...Object.values(data.toolInputs),
|
|
222
|
+
...data.projectContext.map(file => file.tokens),
|
|
223
|
+
...Object.values(data.messagesByRole),
|
|
224
|
+
];
|
|
225
|
+
const numCol = Math.max(8, ...numberValues.map(value => num(value).length));
|
|
226
|
+
const labels = [
|
|
227
|
+
'System prompt', 'project context', 'base instructions', '(no project context files)',
|
|
228
|
+
`Tools (${data.tools.length})`, `Chat messages (${data.messageCount})`,
|
|
229
|
+
'tool results', 'tool inputs', 'synthetic control',
|
|
230
|
+
...data.tools.map(tool => tool.name),
|
|
231
|
+
...data.projectContext.map(file => file.path),
|
|
232
|
+
...Object.keys(data.messagesByRole),
|
|
233
|
+
...Object.keys(data.toolResults), ...Object.keys(data.toolInputs),
|
|
234
|
+
];
|
|
235
|
+
// Indented labels gain up to 4 spaces of leading indent; padEnd accounts for that.
|
|
236
|
+
const labelCol = Math.max(28, ...labels.map(label => label.length + 4)) + 2;
|
|
237
|
+
const barWidth = 20;
|
|
238
|
+
const r = (label, tokens, indent = 0) => row(label, tokens, data.logicalInputEstimate, labelCol, numCol, barWidth, indent);
|
|
239
|
+
// System prompt
|
|
240
|
+
lines.push(r('System prompt', data.systemTokens));
|
|
241
|
+
if (data.projectContext.length > 0) {
|
|
242
|
+
lines.push(r('project context', projectTokens, 2));
|
|
243
|
+
for (const file of [...data.projectContext].sort((a, b) => b.tokens - a.tokens))
|
|
244
|
+
lines.push(r(file.path, file.tokens, 4));
|
|
245
|
+
lines.push(r('base instructions', data.systemTokens - projectTokens, 2));
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
lines.push(r('(no project context files)', 0, 2));
|
|
249
|
+
}
|
|
250
|
+
lines.push('');
|
|
251
|
+
// Tools
|
|
252
|
+
lines.push(r(`Tools (${data.tools.length})`, toolsTotal));
|
|
253
|
+
for (const category of CONTEXT_CATEGORY_ORDER) {
|
|
254
|
+
const inCategory = data.tools.filter(tool => tool.category === category).sort((a, b) => b.tokens - a.tokens);
|
|
255
|
+
if (inCategory.length === 0)
|
|
256
|
+
continue;
|
|
257
|
+
const categoryTotal = inCategory.reduce((sum, tool) => sum + tool.tokens, 0);
|
|
258
|
+
lines.push(r(`${CONTEXT_CATEGORY_LABEL[category]} (${inCategory.length})`, categoryTotal, 2));
|
|
259
|
+
for (const tool of inCategory)
|
|
260
|
+
lines.push(r(tool.name, tool.tokens, 4));
|
|
261
|
+
}
|
|
262
|
+
if (data.mcpErrors.length > 0) {
|
|
263
|
+
lines.push('');
|
|
264
|
+
lines.push(`MCP errors: ${data.mcpErrors.join('; ')}`);
|
|
265
|
+
}
|
|
266
|
+
lines.push('');
|
|
267
|
+
// Messages
|
|
268
|
+
lines.push(r(`Chat messages (${data.messageCount})`, messagesTotal));
|
|
269
|
+
for (const role of Object.keys(data.messagesByRole).sort())
|
|
270
|
+
lines.push(r(role, data.messagesByRole[role], 2));
|
|
271
|
+
if (resultsTotal > 0 || inputsTotal > 0) {
|
|
272
|
+
lines.push('');
|
|
273
|
+
lines.push('Tool content inside messages (already counted above; bars are share of total input):');
|
|
274
|
+
if (resultsTotal > 0) {
|
|
275
|
+
lines.push(r('tool results', resultsTotal, 2));
|
|
276
|
+
for (const [name, value] of [...Object.entries(data.toolResults)].sort(([, a], [, b]) => b - a))
|
|
277
|
+
lines.push(r(name, value, 4));
|
|
278
|
+
}
|
|
279
|
+
if (inputsTotal > 0) {
|
|
280
|
+
lines.push(r('tool inputs', inputsTotal, 2));
|
|
281
|
+
for (const [name, value] of [...Object.entries(data.toolInputs)].sort(([, a], [, b]) => b - a))
|
|
282
|
+
lines.push(r(name, value, 4));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (data.syntheticControl > 0)
|
|
286
|
+
lines.push(r('synthetic control', data.syntheticControl, 2));
|
|
287
|
+
return lines.join('\n');
|
|
288
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { MAX_CONTEXT_FILE_CHARS } from '../../config/contextFiles.js';
|
|
4
|
+
import { buildInitPrompt } from '../../llm/initPrompt.js';
|
|
5
|
+
export async function handleInitCommand(ctx) {
|
|
6
|
+
await ctx.runAgentTurn(buildInitPrompt(), '/init');
|
|
7
|
+
await ctx.refreshContextFiles();
|
|
8
|
+
const agentsMdPath = path.join(process.cwd(), 'AGENTS.md');
|
|
9
|
+
if (await fs.pathExists(agentsMdPath)) {
|
|
10
|
+
const content = await fs.readFile(agentsMdPath, 'utf8');
|
|
11
|
+
const chars = content.length;
|
|
12
|
+
const lines = content.split('\n').length;
|
|
13
|
+
const msg = chars > MAX_CONTEXT_FILE_CHARS
|
|
14
|
+
? `AGENTS.md validation: ${chars.toLocaleString()} chars / ${lines} lines — exceeds the ${MAX_CONTEXT_FILE_CHARS.toLocaleString()}-char context budget and will be truncated. Trim it before relying on it.`
|
|
15
|
+
: `AGENTS.md validation: ${chars.toLocaleString()} chars / ${lines} lines — within the ${MAX_CONTEXT_FILE_CHARS.toLocaleString()}-char context budget.`;
|
|
16
|
+
ctx.addSystemMessage(msg);
|
|
17
|
+
}
|
|
18
|
+
return 'handled';
|
|
19
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { listLogs, readLogEntries } from '../../core/log/llmLog.js';
|
|
2
|
+
function formatBytes(bytes) {
|
|
3
|
+
if (bytes < 1024)
|
|
4
|
+
return `${bytes} B`;
|
|
5
|
+
if (bytes < 1024 * 1024)
|
|
6
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
7
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
8
|
+
}
|
|
9
|
+
export async function handleLogsCommand(args, ctx) {
|
|
10
|
+
const id = args.trim();
|
|
11
|
+
if (!id) {
|
|
12
|
+
const logs = await listLogs();
|
|
13
|
+
if (logs.length === 0) {
|
|
14
|
+
ctx.addSystemMessage('No log files found.');
|
|
15
|
+
return 'handled';
|
|
16
|
+
}
|
|
17
|
+
const lines = logs.slice(0, 20).map(log => {
|
|
18
|
+
const date = log.modified.slice(0, 19).replace('T', ' ');
|
|
19
|
+
return ` ${log.id} ${formatBytes(log.size).padStart(8)} ${date}`;
|
|
20
|
+
});
|
|
21
|
+
ctx.addSystemMessage(['Recent logs:', ' ID Size Modified', ...lines].join('\n'));
|
|
22
|
+
return 'handled';
|
|
23
|
+
}
|
|
24
|
+
const entries = await readLogEntries(id);
|
|
25
|
+
if (entries.length === 0) {
|
|
26
|
+
ctx.addSystemMessage(`No log found with id ${id}.`);
|
|
27
|
+
return 'handled';
|
|
28
|
+
}
|
|
29
|
+
const typeCounts = {};
|
|
30
|
+
let totalInput = 0;
|
|
31
|
+
let totalOutput = 0;
|
|
32
|
+
const toolCallCounts = {};
|
|
33
|
+
for (const entry of entries) {
|
|
34
|
+
typeCounts[entry.type] = (typeCounts[entry.type] ?? 0) + 1;
|
|
35
|
+
if (entry.usage) {
|
|
36
|
+
totalInput += entry.usage.inputTokens ?? 0;
|
|
37
|
+
totalOutput += entry.usage.outputTokens ?? 0;
|
|
38
|
+
}
|
|
39
|
+
if (entry.type === 'tool_call' && entry.toolCall) {
|
|
40
|
+
toolCallCounts[entry.toolCall.name] = (toolCallCounts[entry.toolCall.name] ?? 0) + 1;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const typeLines = Object.entries(typeCounts)
|
|
44
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
45
|
+
.map(([type, count]) => ` ${type}: ${count}`);
|
|
46
|
+
const toolLines = Object.entries(toolCallCounts)
|
|
47
|
+
.sort(([, a], [, b]) => b - a)
|
|
48
|
+
.map(([name, count]) => ` ${name}: ${count}`);
|
|
49
|
+
const parts = [
|
|
50
|
+
`Log: ${id}`,
|
|
51
|
+
`Entries: ${entries.length}`,
|
|
52
|
+
'',
|
|
53
|
+
'Entry counts by type:',
|
|
54
|
+
...typeLines,
|
|
55
|
+
'',
|
|
56
|
+
`Total token usage: in=${totalInput} out=${totalOutput}`,
|
|
57
|
+
];
|
|
58
|
+
if (toolLines.length > 0) {
|
|
59
|
+
parts.push('', 'Tool call counts:', ...toolLines);
|
|
60
|
+
}
|
|
61
|
+
ctx.addSystemMessage(parts.join('\n'));
|
|
62
|
+
return 'handled';
|
|
63
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type HazeLspServer } from '../../config/lspSettings.js';
|
|
2
|
+
import type { HazeSettings } from '../../config/settings.js';
|
|
3
|
+
export type LspWizardResult = {
|
|
4
|
+
message?: string;
|
|
5
|
+
mode?: 'chat' | 'lsp' | 'lspAction' | 'lspAddName' | 'lspConfirmRemove';
|
|
6
|
+
selectedName?: string;
|
|
7
|
+
settingsPatch?: Partial<HazeSettings>;
|
|
8
|
+
server?: HazeLspServer;
|
|
9
|
+
clearDraft?: boolean;
|
|
10
|
+
};
|
|
11
|
+
export declare function selectLspServerResult(settings: HazeSettings, serverName: string): LspWizardResult;
|
|
12
|
+
export declare function selectLspPresetResult(settings: HazeSettings, presetId: string): LspWizardResult;
|
|
13
|
+
export declare function selectLspActionResult(settings: HazeSettings, selectedName: string | undefined, action: string): LspWizardResult;
|
|
14
|
+
export declare function finishLspCustomResult(settings: HazeSettings, draftName: string | undefined, commandLine: string): LspWizardResult;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { configuredLspServers, lspPreset, upsertLspServer, setLspServerEnabled } from '../../config/lspSettings.js';
|
|
2
|
+
import { COMMON_ACTIONS, LSP_ACTIONS, SERVER_CHOICES } from './wizardActions.js';
|
|
3
|
+
import { commandParts } from './wizardInput.js';
|
|
4
|
+
export function selectLspServerResult(settings, serverName) {
|
|
5
|
+
if (serverName === SERVER_CHOICES.addServer)
|
|
6
|
+
return { mode: 'lspAddName', clearDraft: true, message: 'Choose an LSP preset, or select "custom" to enter a name and command manually.' };
|
|
7
|
+
const server = configuredLspServers(settings).find(candidate => candidate.name === serverName);
|
|
8
|
+
if (!server)
|
|
9
|
+
return { mode: 'chat', message: `No LSP server named ${serverName}. Use /lsp and choose add server.` };
|
|
10
|
+
return { mode: 'lspAction', selectedName: server.name, message: `${server.name}: choose an action.` };
|
|
11
|
+
}
|
|
12
|
+
export function selectLspPresetResult(settings, presetId) {
|
|
13
|
+
if (presetId === SERVER_CHOICES.custom)
|
|
14
|
+
return { mode: 'lspAddName', clearDraft: true, message: 'LSP server name? Example: typescript, rust, my-lsp.' };
|
|
15
|
+
const preset = lspPreset(presetId);
|
|
16
|
+
if (!preset)
|
|
17
|
+
return { message: `Unknown preset: ${presetId}.` };
|
|
18
|
+
if (configuredLspServers(settings).some(server => server.name === preset.name))
|
|
19
|
+
return { mode: 'chat', message: `LSP server ${preset.name} already exists. Use /lsp to manage existing servers.` };
|
|
20
|
+
return { mode: 'chat', server: preset, settingsPatch: { lspServers: upsertLspServer(settings, preset) }, message: `Added LSP preset ${preset.name}. Ensure ${preset.command} is installed and on PATH; tools appear once it is.` };
|
|
21
|
+
}
|
|
22
|
+
export function selectLspActionResult(settings, selectedName, action) {
|
|
23
|
+
if (!selectedName)
|
|
24
|
+
return { mode: 'lsp' };
|
|
25
|
+
const server = configuredLspServers(settings).find(candidate => candidate.name === selectedName);
|
|
26
|
+
if (!server)
|
|
27
|
+
return { mode: 'chat', selectedName: undefined, message: `LSP server ${selectedName} not found.` };
|
|
28
|
+
if (action === COMMON_ACTIONS.enable || action === COMMON_ACTIONS.disable) {
|
|
29
|
+
const enabled = action === COMMON_ACTIONS.enable;
|
|
30
|
+
return { mode: 'chat', selectedName: undefined, settingsPatch: { lspServers: setLspServerEnabled(settings, selectedName, enabled) }, message: `LSP server ${selectedName} ${enabled ? 'enabled' : 'disabled'}.` };
|
|
31
|
+
}
|
|
32
|
+
if (action === LSP_ACTIONS.removeServer)
|
|
33
|
+
return { mode: 'lspConfirmRemove', message: `Remove LSP server ${selectedName}? Type "yes" to confirm. Esc to cancel.` };
|
|
34
|
+
return { message: `Unknown LSP action: ${action}` };
|
|
35
|
+
}
|
|
36
|
+
export function finishLspCustomResult(settings, draftName, commandLine) {
|
|
37
|
+
const name = draftName?.trim();
|
|
38
|
+
const parts = commandParts(commandLine);
|
|
39
|
+
const command = parts[0];
|
|
40
|
+
if (!name || !command)
|
|
41
|
+
return { mode: 'chat', clearDraft: true, message: 'LSP server name and command are required.' };
|
|
42
|
+
const server = { name, command, args: parts.slice(1), extensions: [], rootPatterns: ['.git'], enabled: true };
|
|
43
|
+
return { mode: 'chat', clearDraft: true, server, settingsPatch: { lspServers: upsertLspServer(settings, server) }, message: `Added LSP server ${name} (${command}${parts.length > 1 ? ` ${parts.slice(1).join(' ')}` : ''}). Add extensions in ~/.haze/settings.json so tools can auto-select it.` };
|
|
44
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { HazeMcpServer, HazeSettings } from '../../config/settings.js';
|
|
2
|
+
export type McpWizardResult = {
|
|
3
|
+
message?: string;
|
|
4
|
+
mode?: 'chat' | 'mcp' | 'mcpAction' | 'mcpAddName' | 'mcpAddKey' | 'mcpSetKey' | 'mcpConfirmRemove';
|
|
5
|
+
selectedName?: string;
|
|
6
|
+
draft?: Partial<HazeMcpServer>;
|
|
7
|
+
settingsPatch?: Partial<HazeSettings>;
|
|
8
|
+
server?: HazeMcpServer;
|
|
9
|
+
clearDraft?: boolean;
|
|
10
|
+
};
|
|
11
|
+
export declare function selectMcpServerResult(settings: HazeSettings, serverName: string): McpWizardResult;
|
|
12
|
+
export declare function selectMcpPresetResult(settings: HazeSettings, presetId: string): McpWizardResult;
|
|
13
|
+
export declare function selectMcpActionResult(settings: HazeSettings, selectedName: string | undefined, action: string): McpWizardResult;
|
|
14
|
+
export declare function finishMcpCustomResult(settings: HazeSettings, draft: Partial<HazeMcpServer>, keyValue?: string): McpWizardResult;
|
|
15
|
+
export declare function setMcpServerKeyResult(settings: HazeSettings, selectedName: string | undefined, keyValue: string): McpWizardResult;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { findMcpPreset, findMcpServer, toggleMcpServer, upsertMcpServer } from '../../config/mcpSettings.js';
|
|
2
|
+
import { COMMON_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, SERVER_CHOICES } from './wizardActions.js';
|
|
3
|
+
export function selectMcpServerResult(settings, serverName) {
|
|
4
|
+
if (serverName === SERVER_CHOICES.addServer)
|
|
5
|
+
return { mode: 'mcpAddName', clearDraft: true, message: 'Choose an MCP preset, or select "custom" to enter details manually.' };
|
|
6
|
+
const server = findMcpServer(settings, serverName);
|
|
7
|
+
if (!server)
|
|
8
|
+
return { mode: 'chat', message: `No MCP server named ${serverName}. Use /mcp and choose add server.` };
|
|
9
|
+
return { mode: 'mcpAction', selectedName: server.name, message: `${server.name}: choose an action.` };
|
|
10
|
+
}
|
|
11
|
+
export function selectMcpPresetResult(settings, presetId) {
|
|
12
|
+
if (presetId === SERVER_CHOICES.custom)
|
|
13
|
+
return { mode: 'mcpAddName', clearDraft: true, message: 'MCP server name? Example: context7, github, filesystem.' };
|
|
14
|
+
const preset = findMcpPreset(presetId);
|
|
15
|
+
if (!preset)
|
|
16
|
+
return { message: `Unknown preset: ${presetId}.` };
|
|
17
|
+
if (findMcpServer(settings, presetId))
|
|
18
|
+
return { mode: 'chat', message: `MCP server ${presetId} already exists. Use /mcp to manage existing servers.` };
|
|
19
|
+
return {
|
|
20
|
+
mode: 'mcpAddKey',
|
|
21
|
+
draft: { name: presetId, transport: preset.transport, ...(preset.url ? { url: preset.url } : {}) },
|
|
22
|
+
message: `Adding ${presetId} (${preset.transport}${preset.url ? `, ${preset.url}` : ''}).\nOptional API key or auth header value? (Leave blank to skip — Enter works.)`,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function selectMcpActionResult(settings, selectedName, action) {
|
|
26
|
+
if (!selectedName)
|
|
27
|
+
return { mode: 'mcp' };
|
|
28
|
+
const server = findMcpServer(settings, selectedName);
|
|
29
|
+
if (!server)
|
|
30
|
+
return { mode: 'chat', selectedName: undefined, message: `MCP server ${selectedName} not found.` };
|
|
31
|
+
if (action === COMMON_ACTIONS.enable || action === COMMON_ACTIONS.disable) {
|
|
32
|
+
const enabled = action === COMMON_ACTIONS.enable;
|
|
33
|
+
return { mode: 'chat', selectedName: undefined, settingsPatch: { mcpServers: toggleMcpServer(settings, selectedName, enabled) ?? [] }, message: `MCP server ${selectedName} ${enabled ? 'enabled' : 'disabled'}.` };
|
|
34
|
+
}
|
|
35
|
+
if (action === MCP_ACTIONS.setApiKey)
|
|
36
|
+
return { mode: 'mcpSetKey', message: `New API key for ${selectedName}? (current: ${server.headers?.length ? 'saved' : 'not set'}) Sent as Authorization: Bearer <value>.` };
|
|
37
|
+
if (action === MCP_ACTIONS.removeServer)
|
|
38
|
+
return { mode: 'mcpConfirmRemove', message: `Remove MCP server ${selectedName}? Type "yes" to confirm. Esc to cancel.` };
|
|
39
|
+
return { message: `Unknown MCP action: ${action}` };
|
|
40
|
+
}
|
|
41
|
+
export function finishMcpCustomResult(settings, draft, keyValue) {
|
|
42
|
+
const name = draft.name?.trim();
|
|
43
|
+
const transport = draft.transport;
|
|
44
|
+
if (!name || !transport)
|
|
45
|
+
return { mode: 'chat', clearDraft: true, message: 'MCP server name and transport are required.' };
|
|
46
|
+
const headers = keyValue?.trim() ? [{ name: 'Authorization', value: `Bearer ${keyValue.trim()}` }] : undefined;
|
|
47
|
+
const server = transport === MCP_TRANSPORTS.stdio
|
|
48
|
+
? { name, transport, command: draft.command, args: draft.args, ...(headers ? { headers } : {}), enabled: true }
|
|
49
|
+
: { name, transport, url: draft.url, ...(headers ? { headers } : {}), enabled: true };
|
|
50
|
+
if (transport === MCP_TRANSPORTS.stdio && !server.command)
|
|
51
|
+
return { mode: 'chat', clearDraft: true, message: 'Command is required for stdio transport.' };
|
|
52
|
+
if (transport !== MCP_TRANSPORTS.stdio && !server.url)
|
|
53
|
+
return { mode: 'chat', clearDraft: true, message: `URL is required for ${transport} transport.` };
|
|
54
|
+
const location = transport === MCP_TRANSPORTS.stdio ? `${server.command}${(server.args ?? []).length ? ` ${(server.args ?? []).join(' ')}` : ''}` : server.url;
|
|
55
|
+
return { mode: 'chat', clearDraft: true, server, settingsPatch: { mcpServers: upsertMcpServer(settings, server) }, message: `Added MCP server ${name} (${transport}, ${location}). Tools load on the next turn.` };
|
|
56
|
+
}
|
|
57
|
+
export function setMcpServerKeyResult(settings, selectedName, keyValue) {
|
|
58
|
+
if (!selectedName)
|
|
59
|
+
return { mode: 'mcp' };
|
|
60
|
+
const server = findMcpServer(settings, selectedName);
|
|
61
|
+
if (!server)
|
|
62
|
+
return { mode: 'chat', selectedName: undefined, message: `MCP server ${selectedName} not found.` };
|
|
63
|
+
const key = keyValue.trim();
|
|
64
|
+
if (!key)
|
|
65
|
+
return { message: 'API key cannot be empty. Esc to cancel.' };
|
|
66
|
+
const headers = (server.headers ?? []).filter(header => header.name !== 'Authorization');
|
|
67
|
+
headers.push({ name: 'Authorization', value: `Bearer ${key}` });
|
|
68
|
+
return { mode: 'chat', selectedName: undefined, settingsPatch: { mcpServers: upsertMcpServer(settings, { ...server, headers }) }, message: `API key updated for ${server.name}.` };
|
|
69
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { activeProvider, configuredProviders, modelSelector, resolveModelSelector, upsertProvider } from '../../config/providers.js';
|
|
2
|
+
export async function handleModelCommand(value, ctx) {
|
|
3
|
+
if (value === '/model') {
|
|
4
|
+
ctx.setModelProviderFilter?.(undefined);
|
|
5
|
+
ctx.setMode('model');
|
|
6
|
+
ctx.addSystemMessage('Choose a model. Selecting a model also sets its provider.');
|
|
7
|
+
return 'handled';
|
|
8
|
+
}
|
|
9
|
+
if (value === '/model list') {
|
|
10
|
+
const providers = configuredProviders(ctx.settings);
|
|
11
|
+
ctx.addSystemMessage(['Configured models:', ...providers.flatMap(provider => provider.models.map(model => `- ${modelSelector(provider, model)} - ${provider.name}`))].join('\n'));
|
|
12
|
+
return 'handled';
|
|
13
|
+
}
|
|
14
|
+
if (!value.startsWith('/model '))
|
|
15
|
+
return undefined;
|
|
16
|
+
const selector = value.slice('/model '.length).trim();
|
|
17
|
+
const resolved = resolveModelSelector(ctx.settings, selector);
|
|
18
|
+
if (resolved.status === 'ambiguous') {
|
|
19
|
+
ctx.addSystemMessage(`Model ${resolved.model} exists on multiple providers: ${resolved.providers.map(provider => modelSelector(provider, resolved.model)).join(', ')}`);
|
|
20
|
+
return 'handled';
|
|
21
|
+
}
|
|
22
|
+
if (resolved.status === 'missing') {
|
|
23
|
+
const provider = activeProvider(ctx.settings);
|
|
24
|
+
if (!provider) {
|
|
25
|
+
ctx.addSystemMessage('No provider configured. Run /provider to choose or add a provider before setting a model.');
|
|
26
|
+
return 'handled';
|
|
27
|
+
}
|
|
28
|
+
const nextProvider = provider.models.includes(selector) ? provider : { ...provider, models: [...provider.models, selector] };
|
|
29
|
+
await ctx.updateSettings({ provider: provider.name, model: selector, providers: upsertProvider(ctx.settings, nextProvider) });
|
|
30
|
+
ctx.addSystemMessage(`Model set to ${selector} on ${provider.name}. Saved to ~/.haze/settings.json.`);
|
|
31
|
+
return 'handled';
|
|
32
|
+
}
|
|
33
|
+
await ctx.updateSettings({ provider: resolved.provider.name, model: resolved.model });
|
|
34
|
+
ctx.addSystemMessage(`Model set to ${resolved.model} on ${resolved.provider.name}. Saved to ~/.haze/settings.json.`);
|
|
35
|
+
return 'handled';
|
|
36
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { HazeProviderSettings, HazeSettings } from '../../config/settings.js';
|
|
2
|
+
import type { Mode } from './chatModes.js';
|
|
3
|
+
type WizardPatch = {
|
|
4
|
+
settingsPatch?: Partial<HazeSettings>;
|
|
5
|
+
message: string;
|
|
6
|
+
provider?: HazeProviderSettings;
|
|
7
|
+
providers?: HazeProviderSettings[];
|
|
8
|
+
models?: string[];
|
|
9
|
+
};
|
|
10
|
+
export declare function providerAppendModels(settings: HazeSettings, providerName: string | undefined, modelsValue: string): WizardPatch;
|
|
11
|
+
export declare function providerFinishAdd(settings: HazeSettings, draft: Partial<HazeProviderSettings>, modelsValue: string): WizardPatch;
|
|
12
|
+
export declare function providerRemoveModels(settings: HazeSettings, providerName: string | undefined, modelsValue: string): WizardPatch & {
|
|
13
|
+
remaining?: string[];
|
|
14
|
+
removed?: string[];
|
|
15
|
+
notFound?: string[];
|
|
16
|
+
wasActive?: boolean;
|
|
17
|
+
};
|
|
18
|
+
export declare function providerRemove(settings: HazeSettings, providerName: string | undefined): WizardPatch & {
|
|
19
|
+
wasActiveProvider?: boolean;
|
|
20
|
+
};
|
|
21
|
+
export declare function providerSetKey(settings: HazeSettings, providerName: string | undefined, value: string): WizardPatch & {
|
|
22
|
+
key?: string;
|
|
23
|
+
};
|
|
24
|
+
export type ProviderActionResult = {
|
|
25
|
+
message: string;
|
|
26
|
+
mode?: Mode;
|
|
27
|
+
selectedName?: string;
|
|
28
|
+
};
|
|
29
|
+
export declare function providerActionResult(action: string, provider: HazeProviderSettings | undefined): ProviderActionResult;
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { configuredProviders, findProvider, upsertProvider } from '../../config/providers.js';
|
|
2
|
+
import { PROVIDER_ACTIONS } from './wizardActions.js';
|
|
3
|
+
import { commaList } from './wizardInput.js';
|
|
4
|
+
export function providerAppendModels(settings, providerName, modelsValue) {
|
|
5
|
+
const provider = providerName ? findProvider(settings, providerName) : undefined;
|
|
6
|
+
const models = commaList(modelsValue);
|
|
7
|
+
if (!provider)
|
|
8
|
+
return { message: 'No provider selected.' };
|
|
9
|
+
if (models.length === 0)
|
|
10
|
+
return { provider, models, message: 'Enter at least one model name.' };
|
|
11
|
+
const nextProvider = { ...provider, models: [...new Set([...provider.models, ...models])] };
|
|
12
|
+
return {
|
|
13
|
+
provider,
|
|
14
|
+
models,
|
|
15
|
+
settingsPatch: { providers: upsertProvider(settings, nextProvider), provider: provider.name },
|
|
16
|
+
message: `Added ${models.length} model${models.length === 1 ? '' : 's'} to ${provider.name}. Choose a model.`,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function providerFinishAdd(settings, draft, modelsValue) {
|
|
20
|
+
const models = commaList(modelsValue);
|
|
21
|
+
if (!draft.name || !draft.url || models.length === 0) {
|
|
22
|
+
return { models, message: 'Provider name, URL, and at least one model are required.' };
|
|
23
|
+
}
|
|
24
|
+
const provider = {
|
|
25
|
+
name: draft.name,
|
|
26
|
+
url: draft.url,
|
|
27
|
+
...(draft.key ? { key: draft.key } : {}),
|
|
28
|
+
models: [...new Set(models)],
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
provider,
|
|
32
|
+
models,
|
|
33
|
+
settingsPatch: { providers: upsertProvider(settings, provider), provider: provider.name },
|
|
34
|
+
message: `Added provider ${provider.name}. Choose a model.`,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export function providerRemoveModels(settings, providerName, modelsValue) {
|
|
38
|
+
const provider = providerName ? findProvider(settings, providerName) : undefined;
|
|
39
|
+
if (!provider)
|
|
40
|
+
return { message: 'No provider selected.' };
|
|
41
|
+
const toRemove = commaList(modelsValue);
|
|
42
|
+
if (toRemove.length === 0)
|
|
43
|
+
return { provider, message: 'Enter at least one model name. Esc to cancel.' };
|
|
44
|
+
const remaining = provider.models.filter(model => !toRemove.includes(model));
|
|
45
|
+
if (remaining.length === 0)
|
|
46
|
+
return { provider, remaining, message: 'A provider must have at least one model. Remove the provider instead.' };
|
|
47
|
+
const removed = provider.models.filter(model => toRemove.includes(model));
|
|
48
|
+
const notFound = toRemove.filter(model => !provider.models.includes(model));
|
|
49
|
+
const updated = { ...provider, models: remaining };
|
|
50
|
+
const wasActive = Boolean(settings.model && provider.models.includes(settings.model) && !remaining.includes(settings.model));
|
|
51
|
+
const parts = [`Removed ${removed.join(', ')} from ${provider.name}.`];
|
|
52
|
+
if (notFound.length)
|
|
53
|
+
parts.push(`Not found: ${notFound.join(', ')}.`);
|
|
54
|
+
if (wasActive)
|
|
55
|
+
parts.push(`Active model updated to ${remaining[0]}.`);
|
|
56
|
+
return {
|
|
57
|
+
provider,
|
|
58
|
+
remaining,
|
|
59
|
+
removed,
|
|
60
|
+
notFound,
|
|
61
|
+
wasActive,
|
|
62
|
+
settingsPatch: {
|
|
63
|
+
providers: upsertProvider(settings, updated),
|
|
64
|
+
...(wasActive ? { model: remaining[0] } : {}),
|
|
65
|
+
},
|
|
66
|
+
message: parts.join(' '),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
export function providerRemove(settings, providerName) {
|
|
70
|
+
const provider = providerName ? findProvider(settings, providerName) : undefined;
|
|
71
|
+
if (!provider)
|
|
72
|
+
return { message: 'No provider selected.' };
|
|
73
|
+
const providers = configuredProviders(settings).filter(candidate => candidate.name !== providerName);
|
|
74
|
+
const wasActiveProvider = settings.provider === providerName || (!settings.provider && configuredProviders(settings)[0]?.name === providerName);
|
|
75
|
+
return {
|
|
76
|
+
provider,
|
|
77
|
+
providers,
|
|
78
|
+
wasActiveProvider,
|
|
79
|
+
settingsPatch: {
|
|
80
|
+
providers,
|
|
81
|
+
...(wasActiveProvider ? { provider: providers[0]?.name, model: providers[0]?.models[0] } : {}),
|
|
82
|
+
},
|
|
83
|
+
message: `Removed provider ${provider.name}.${wasActiveProvider ? ` Switched to ${providers[0]?.name ?? 'no provider'}.` : ''}`,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export function providerSetKey(settings, providerName, value) {
|
|
87
|
+
const provider = providerName ? findProvider(settings, providerName) : undefined;
|
|
88
|
+
if (!provider)
|
|
89
|
+
return { message: 'No provider selected.' };
|
|
90
|
+
const key = value.trim();
|
|
91
|
+
if (!key)
|
|
92
|
+
return { provider, message: 'API key cannot be empty. Esc to cancel.' };
|
|
93
|
+
return {
|
|
94
|
+
provider,
|
|
95
|
+
key,
|
|
96
|
+
settingsPatch: { providers: upsertProvider(settings, { ...provider, key }) },
|
|
97
|
+
message: `API key updated for ${provider.name}.`,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function providerActionResult(action, provider) {
|
|
101
|
+
if (!provider)
|
|
102
|
+
return { message: '', mode: 'provider' };
|
|
103
|
+
if (action === PROVIDER_ACTIONS.useProvider)
|
|
104
|
+
return { message: '', selectedName: undefined, mode: 'model' };
|
|
105
|
+
if (action === PROVIDER_ACTIONS.addModels)
|
|
106
|
+
return { message: `Comma-separated model names to add to ${provider.name}?`, mode: 'providerAppendModels' };
|
|
107
|
+
if (action === PROVIDER_ACTIONS.setApiKey)
|
|
108
|
+
return { message: `New API key for ${provider.name}? (current: ${provider.key ? 'saved' : 'not set'})`, mode: 'providerSetKey' };
|
|
109
|
+
if (action === PROVIDER_ACTIONS.removeModels)
|
|
110
|
+
return { message: `Comma-separated model names to remove from ${provider.name}?\nCurrent models: ${provider.models.join(', ')}`, mode: 'providerRemoveModels' };
|
|
111
|
+
if (action === PROVIDER_ACTIONS.removeProvider)
|
|
112
|
+
return { message: `Remove provider ${provider.name}? Type "yes" to confirm. Esc to cancel.`, mode: 'providerConfirmRemove' };
|
|
113
|
+
return { message: `Unknown provider action: ${action}` };
|
|
114
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type HeadlessOutput = 'text' | 'json' | 'stream-json';
|
|
2
|
+
export interface HeadlessOptions {
|
|
3
|
+
prompt: string;
|
|
4
|
+
modelOverride?: string;
|
|
5
|
+
output: HeadlessOutput;
|
|
6
|
+
debug?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** Pinned, documented usage shape emitted in `--output json` (avoids leaking internal estimates). */
|
|
9
|
+
export interface HeadlessUsage {
|
|
10
|
+
inputTokens: number;
|
|
11
|
+
outputTokens: number;
|
|
12
|
+
cacheReadTokens: number;
|
|
13
|
+
cacheWriteTokens: number;
|
|
14
|
+
reasoningTokens: number;
|
|
15
|
+
}
|
|
16
|
+
export declare function runHeadless(options: HeadlessOptions): Promise<number>;
|