@denizokcu/haze 0.8.0 → 0.9.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 +11 -1
- package/README.md +15 -13
- package/dist/cli/chat/sessionRecorder.d.ts +3 -0
- package/dist/cli/chat/sessionRecorder.js +23 -8
- package/dist/cli/commands/chat.js +90 -104
- package/dist/cli/commands/commands.d.ts +1 -1
- package/dist/cli/commands/commands.js +1 -1
- package/dist/cli/commands/formatters.js +3 -3
- package/dist/cli/commands/logsCommand.js +7 -21
- package/dist/cli/commands/mcpWizard.js +24 -2
- package/dist/cli/commands/providerWizard.js +18 -5
- package/dist/cli/commands/runCommand.js +7 -15
- package/dist/cli/commands/settingsSummary.js +3 -1
- package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
- package/dist/cli/commands/streaming/turnOutcome.js +13 -0
- package/dist/cli/commands/streaming.js +66 -29
- package/dist/cli/commands/wizardPrompts.js +1 -1
- package/dist/cli/commands/wizardSuggestions.js +2 -1
- package/dist/cli/commands/wizardTransition.d.ts +33 -0
- package/dist/cli/commands/wizardTransition.js +44 -0
- package/dist/config/contextFiles.js +6 -3
- package/dist/config/endpointSecurity.d.ts +2 -0
- package/dist/config/endpointSecurity.js +28 -0
- package/dist/config/inputHistory.js +4 -2
- package/dist/config/privateStorage.d.ts +6 -0
- package/dist/config/privateStorage.js +61 -0
- package/dist/config/settings.js +4 -4
- package/dist/config/updateCheck.js +4 -2
- package/dist/core/agent/toolOutputStore.d.ts +3 -0
- package/dist/core/agent/toolOutputStore.js +32 -11
- package/dist/core/goal/completionPolicy.d.ts +0 -28
- package/dist/core/goal/completionPolicy.js +0 -88
- package/dist/core/io/boundedRead.d.ts +15 -0
- package/dist/core/io/boundedRead.js +97 -0
- package/dist/core/limits/byteBudgets.d.ts +13 -0
- package/dist/core/limits/byteBudgets.js +13 -0
- package/dist/core/log/llmLog.d.ts +10 -0
- package/dist/core/log/llmLog.js +59 -13
- package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
- package/dist/core/persistence/orderedFileWriter.js +29 -0
- package/dist/core/process/runBoundedProcess.d.ts +27 -0
- package/dist/core/process/runBoundedProcess.js +80 -0
- package/dist/core/session/sessionStore.js +48 -25
- package/dist/core/subagent/subagentRunner.js +1 -1
- package/dist/llm/client.js +4 -1
- package/dist/llm/hazeTools.d.ts +410 -16
- package/dist/llm/hazeTools.js +36 -32
- package/dist/llm/lsp.d.ts +21 -3
- package/dist/llm/lsp.js +55 -13
- package/dist/llm/lspTools.d.ts +96 -48
- package/dist/llm/mcp.d.ts +1 -1
- package/dist/llm/mcp.js +65 -16
- package/dist/llm/requestContext.d.ts +1 -0
- package/dist/llm/requestContext.js +6 -3
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/tools/bashTool.d.ts +368 -16
- package/dist/llm/tools/bashTool.js +19 -57
- package/dist/llm/tools/grepRunner.d.ts +15 -0
- package/dist/llm/tools/grepRunner.js +85 -0
- package/dist/skills/SkillLoader.js +17 -5
- package/dist/skills/SkillRegistry.js +19 -6
- package/dist/skills/types.d.ts +5 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +9 -4
- package/package.json +1 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { findMcpPreset, findMcpServer, toggleMcpServer, upsertMcpServer } from '../../config/mcpSettings.js';
|
|
2
2
|
import { COMMON_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, SERVER_CHOICES } from './wizardActions.js';
|
|
3
|
+
import { assertCredentialedEndpointSecure } from '../../config/endpointSecurity.js';
|
|
3
4
|
export function selectMcpServerResult(settings, serverName) {
|
|
4
5
|
if (serverName === SERVER_CHOICES.addServer)
|
|
5
6
|
return { mode: 'mcpAddName', clearDraft: true, message: 'Choose an MCP preset, or select "custom" to enter details manually.' };
|
|
@@ -32,8 +33,11 @@ export function selectMcpActionResult(settings, selectedName, action) {
|
|
|
32
33
|
const enabled = action === COMMON_ACTIONS.enable;
|
|
33
34
|
return { mode: 'chat', selectedName: undefined, settingsPatch: { mcpServers: toggleMcpServer(settings, selectedName, enabled) ?? [] }, message: `MCP server ${selectedName} ${enabled ? 'enabled' : 'disabled'}.` };
|
|
34
35
|
}
|
|
35
|
-
if (action === MCP_ACTIONS.setApiKey)
|
|
36
|
+
if (action === MCP_ACTIONS.setApiKey) {
|
|
37
|
+
if (server.transport === 'stdio')
|
|
38
|
+
return { mode: 'chat', selectedName: undefined, message: 'Stdio MCP authentication must be handled by its command or wrapper; HTTP headers do not apply.' };
|
|
36
39
|
return { mode: 'mcpSetKey', message: `New API key for ${selectedName}? (current: ${server.headers?.length ? 'saved' : 'not set'}) Sent as Authorization: Bearer <value>.` };
|
|
40
|
+
}
|
|
37
41
|
if (action === MCP_ACTIONS.removeServer)
|
|
38
42
|
return { mode: 'mcpConfirmRemove', message: `Remove MCP server ${selectedName}? Type "yes" to confirm. Esc to cancel.` };
|
|
39
43
|
return { message: `Unknown MCP action: ${action}` };
|
|
@@ -45,12 +49,20 @@ export function finishMcpCustomResult(settings, draft, keyValue) {
|
|
|
45
49
|
return { mode: 'chat', clearDraft: true, message: 'MCP server name and transport are required.' };
|
|
46
50
|
const headers = keyValue?.trim() ? [{ name: 'Authorization', value: `Bearer ${keyValue.trim()}` }] : undefined;
|
|
47
51
|
const server = transport === MCP_TRANSPORTS.stdio
|
|
48
|
-
? { name, transport, command: draft.command, args: draft.args,
|
|
52
|
+
? { name, transport, command: draft.command, args: draft.args, enabled: true }
|
|
49
53
|
: { name, transport, url: draft.url, ...(headers ? { headers } : {}), enabled: true };
|
|
50
54
|
if (transport === MCP_TRANSPORTS.stdio && !server.command)
|
|
51
55
|
return { mode: 'chat', clearDraft: true, message: 'Command is required for stdio transport.' };
|
|
52
56
|
if (transport !== MCP_TRANSPORTS.stdio && !server.url)
|
|
53
57
|
return { mode: 'chat', clearDraft: true, message: `URL is required for ${transport} transport.` };
|
|
58
|
+
if (server.url) {
|
|
59
|
+
try {
|
|
60
|
+
assertCredentialedEndpointSecure(server.url, server.headers);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
return { mode: 'chat', clearDraft: true, message: error instanceof Error ? error.message : String(error) };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
54
66
|
const location = transport === MCP_TRANSPORTS.stdio ? `${server.command}${(server.args ?? []).length ? ` ${(server.args ?? []).join(' ')}` : ''}` : server.url;
|
|
55
67
|
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
68
|
}
|
|
@@ -60,10 +72,20 @@ export function setMcpServerKeyResult(settings, selectedName, keyValue) {
|
|
|
60
72
|
const server = findMcpServer(settings, selectedName);
|
|
61
73
|
if (!server)
|
|
62
74
|
return { mode: 'chat', selectedName: undefined, message: `MCP server ${selectedName} not found.` };
|
|
75
|
+
if (server.transport === 'stdio')
|
|
76
|
+
return { mode: 'chat', selectedName: undefined, message: 'Stdio MCP authentication must be handled by its command or wrapper.' };
|
|
63
77
|
const key = keyValue.trim();
|
|
64
78
|
if (!key)
|
|
65
79
|
return { message: 'API key cannot be empty. Esc to cancel.' };
|
|
66
80
|
const headers = (server.headers ?? []).filter(header => header.name !== 'Authorization');
|
|
67
81
|
headers.push({ name: 'Authorization', value: `Bearer ${key}` });
|
|
82
|
+
if (server.url) {
|
|
83
|
+
try {
|
|
84
|
+
assertCredentialedEndpointSecure(server.url, headers);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
return { mode: 'chat', selectedName: undefined, message: error instanceof Error ? error.message : String(error) };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
68
90
|
return { mode: 'chat', selectedName: undefined, settingsPatch: { mcpServers: upsertMcpServer(settings, { ...server, headers }) }, message: `API key updated for ${server.name}.` };
|
|
69
91
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { configuredProviders, findProvider, upsertProvider } from '../../config/providers.js';
|
|
2
2
|
import { PROVIDER_ACTIONS } from './wizardActions.js';
|
|
3
3
|
import { commaList } from './wizardInput.js';
|
|
4
|
+
import { assertCredentialedEndpointSecure } from '../../config/endpointSecurity.js';
|
|
4
5
|
export function providerAppendModels(settings, providerName, modelsValue) {
|
|
5
6
|
const provider = providerName ? findProvider(settings, providerName) : undefined;
|
|
6
7
|
const models = commaList(modelsValue);
|
|
@@ -21,6 +22,12 @@ export function providerFinishAdd(settings, draft, modelsValue) {
|
|
|
21
22
|
if (!draft.name || !draft.url || models.length === 0) {
|
|
22
23
|
return { models, message: 'Provider name, URL, and at least one model are required.' };
|
|
23
24
|
}
|
|
25
|
+
try {
|
|
26
|
+
assertCredentialedEndpointSecure(draft.url, draft.key);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
return { models, message: error instanceof Error ? error.message : String(error) };
|
|
30
|
+
}
|
|
24
31
|
const provider = {
|
|
25
32
|
name: draft.name,
|
|
26
33
|
url: draft.url,
|
|
@@ -52,7 +59,7 @@ export function providerRemoveModels(settings, providerName, modelsValue) {
|
|
|
52
59
|
if (notFound.length)
|
|
53
60
|
parts.push(`Not found: ${notFound.join(', ')}.`);
|
|
54
61
|
if (wasActive)
|
|
55
|
-
parts.push(
|
|
62
|
+
parts.push('Active model selection cleared. Choose a model explicitly.');
|
|
56
63
|
return {
|
|
57
64
|
provider,
|
|
58
65
|
remaining,
|
|
@@ -61,7 +68,7 @@ export function providerRemoveModels(settings, providerName, modelsValue) {
|
|
|
61
68
|
wasActive,
|
|
62
69
|
settingsPatch: {
|
|
63
70
|
providers: upsertProvider(settings, updated),
|
|
64
|
-
...(wasActive ? { model:
|
|
71
|
+
...(wasActive ? { model: undefined } : {}),
|
|
65
72
|
},
|
|
66
73
|
message: parts.join(' '),
|
|
67
74
|
};
|
|
@@ -71,16 +78,16 @@ export function providerRemove(settings, providerName) {
|
|
|
71
78
|
if (!provider)
|
|
72
79
|
return { message: 'No provider selected.' };
|
|
73
80
|
const providers = configuredProviders(settings).filter(candidate => candidate.name !== providerName);
|
|
74
|
-
const wasActiveProvider = settings.provider === providerName
|
|
81
|
+
const wasActiveProvider = settings.provider === providerName;
|
|
75
82
|
return {
|
|
76
83
|
provider,
|
|
77
84
|
providers,
|
|
78
85
|
wasActiveProvider,
|
|
79
86
|
settingsPatch: {
|
|
80
87
|
providers,
|
|
81
|
-
...(wasActiveProvider ? { provider:
|
|
88
|
+
...(wasActiveProvider ? { provider: undefined, model: undefined } : {}),
|
|
82
89
|
},
|
|
83
|
-
message: `Removed provider ${provider.name}.${wasActiveProvider ?
|
|
90
|
+
message: `Removed provider ${provider.name}.${wasActiveProvider ? ' Active provider and model selection cleared.' : ''}`,
|
|
84
91
|
};
|
|
85
92
|
}
|
|
86
93
|
export function providerSetKey(settings, providerName, value) {
|
|
@@ -90,6 +97,12 @@ export function providerSetKey(settings, providerName, value) {
|
|
|
90
97
|
const key = value.trim();
|
|
91
98
|
if (!key)
|
|
92
99
|
return { provider, message: 'API key cannot be empty. Esc to cancel.' };
|
|
100
|
+
try {
|
|
101
|
+
assertCredentialedEndpointSecure(provider.url, key);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
return { provider, message: error instanceof Error ? error.message : String(error) };
|
|
105
|
+
}
|
|
93
106
|
return {
|
|
94
107
|
provider,
|
|
95
108
|
key,
|
|
@@ -90,19 +90,8 @@ export async function runHeadless(options) {
|
|
|
90
90
|
let log;
|
|
91
91
|
if (options.debug)
|
|
92
92
|
log = await createLog();
|
|
93
|
-
let emittedTurnStart = false;
|
|
94
93
|
const emitStreamEvent = options.output === 'stream-json'
|
|
95
94
|
? (event) => {
|
|
96
|
-
// runAgentTurn emits nested turn_start/turn_end pairs for retries; expose one clean
|
|
97
|
-
// headless turn and emit the authoritative turn_end after the run settles.
|
|
98
|
-
if (event.type === 'turn_start') {
|
|
99
|
-
if (emittedTurnStart)
|
|
100
|
-
return;
|
|
101
|
-
emittedTurnStart = true;
|
|
102
|
-
}
|
|
103
|
-
else if (event.type === 'turn_end') {
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
95
|
const headlessEvent = toHeadlessStreamEvent(event);
|
|
107
96
|
if (headlessEvent)
|
|
108
97
|
writeNdjson(headlessEvent);
|
|
@@ -141,6 +130,7 @@ export async function runHeadless(options) {
|
|
|
141
130
|
};
|
|
142
131
|
let status;
|
|
143
132
|
let result;
|
|
133
|
+
let persistenceError;
|
|
144
134
|
try {
|
|
145
135
|
({ status } = await runAgentTurn(options.prompt, options.prompt, contextFiles, callbacks, 0, false, false, session, options.modelOverride));
|
|
146
136
|
result = segments.filter((s) => !s.hidden && s.text).map((s) => s.text).join('\n');
|
|
@@ -151,12 +141,14 @@ export async function runHeadless(options) {
|
|
|
151
141
|
}
|
|
152
142
|
finally {
|
|
153
143
|
if (log)
|
|
154
|
-
await endLog(log).catch(
|
|
144
|
+
await endLog(log).catch(error => {
|
|
145
|
+
persistenceError = error instanceof Error ? error.message : String(error);
|
|
146
|
+
});
|
|
155
147
|
}
|
|
148
|
+
if (persistenceError)
|
|
149
|
+
process.stderr.write(`haze persistence warning: ${persistenceError}\n`);
|
|
156
150
|
if (options.output === 'json' || options.output === 'stream-json') {
|
|
157
|
-
|
|
158
|
-
writeNdjson({ type: 'turn_end', request: options.prompt, status, at: new Date().toISOString() });
|
|
159
|
-
// For stream-json the agent events have already streamed above; this is the terminal line.
|
|
151
|
+
// For stream-json the authoritative agent events have already streamed above; this is the terminal line.
|
|
160
152
|
// It is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
|
|
161
153
|
writeNdjson({ type: 'result', status, result, usage: pinnedUsage(usage) });
|
|
162
154
|
}
|
|
@@ -21,7 +21,8 @@ export async function formatSettingsSummary(settings, contextFiles) {
|
|
|
21
21
|
notes.push(`${summary.duplicateGroups.length} duplicate group${summary.duplicateGroups.length === 1 ? '' : 's'} (${duplicateTotal} file${duplicateTotal === 1 ? '' : 's'} with identical content)`);
|
|
22
22
|
}
|
|
23
23
|
const lspServers = configuredLspServers(settings);
|
|
24
|
-
const
|
|
24
|
+
const skillRegistry = await loadSkillRegistry();
|
|
25
|
+
const installedSkills = [...skillRegistry.skills.values()];
|
|
25
26
|
const skillNames = installedSkills.map(skill => `${skill.name}${isSkillEnabled(settings, skill.name) ? '' : ' (disabled)'}`).join(', ');
|
|
26
27
|
const lines = [
|
|
27
28
|
`Provider: ${activeProvider?.name ?? 'not configured'}`,
|
|
@@ -32,6 +33,7 @@ export async function formatSettingsSummary(settings, contextFiles) {
|
|
|
32
33
|
`LSP servers: ${lspServers.map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
|
|
33
34
|
`MCP servers: ${configuredMcpServers(settings).map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
|
|
34
35
|
`Skills: ${skillNames || 'none'}`,
|
|
36
|
+
...(skillRegistry.errors.length ? [`Skill load errors: ${skillRegistry.errors.map(error => `${error.directory}: ${error.message}`).join('; ')}`] : []),
|
|
35
37
|
`Context files: ${contextFiles.length ? `${contextFiles.map(file => file.path).join(', ')} (~${contextTokens} tokens)` : 'none'}`,
|
|
36
38
|
];
|
|
37
39
|
if (notes.length > 0)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { TurnStatus } from '../streaming.js';
|
|
2
|
+
export declare function terminalTurnStatus(input: {
|
|
3
|
+
aborted: boolean;
|
|
4
|
+
error?: unknown;
|
|
5
|
+
assistantText: string;
|
|
6
|
+
sawToolCall: boolean;
|
|
7
|
+
lastToolOk?: boolean;
|
|
8
|
+
finishReason?: string;
|
|
9
|
+
budgetReached?: boolean;
|
|
10
|
+
}): TurnStatus;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function terminalTurnStatus(input) {
|
|
2
|
+
if (input.aborted)
|
|
3
|
+
return 'aborted';
|
|
4
|
+
if (input.error)
|
|
5
|
+
return 'failed';
|
|
6
|
+
if (input.lastToolOk === false)
|
|
7
|
+
return 'failed';
|
|
8
|
+
if (input.budgetReached || input.finishReason === 'length' || input.finishReason === 'error')
|
|
9
|
+
return 'failed';
|
|
10
|
+
if (input.sawToolCall && input.assistantText.trim().length === 0)
|
|
11
|
+
return 'failed';
|
|
12
|
+
return input.assistantText.trim().length > 0 ? 'complete' : 'failed';
|
|
13
|
+
}
|
|
@@ -23,6 +23,7 @@ import { applyToolResultState, initialToolResultState, isMutatingToolName } from
|
|
|
23
23
|
import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
|
|
24
24
|
import { toolsContextFor } from '../../llm/tools/toolContext.js';
|
|
25
25
|
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
26
|
+
import { terminalTurnStatus } from './streaming/turnOutcome.js';
|
|
26
27
|
function logEntry(log, entry) {
|
|
27
28
|
if (log)
|
|
28
29
|
void logAppend(log, entry).catch(() => undefined);
|
|
@@ -34,16 +35,9 @@ function withScopedContextControl(messages, context) {
|
|
|
34
35
|
context.pendingContextFiles = [];
|
|
35
36
|
return withSyntheticControl(messages, `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}`);
|
|
36
37
|
}
|
|
37
|
-
|
|
38
|
-
const displayVal = displayValue ?? value;
|
|
39
|
-
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
40
|
-
callbacks.setBusy(true);
|
|
38
|
+
async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController) {
|
|
41
39
|
let thinkingLabel = modelThinkingLabel(undefined);
|
|
42
40
|
callbacks.setBusyLabel?.(thinkingLabel);
|
|
43
|
-
if (!retryingExistingRequest)
|
|
44
|
-
callbacks.addMessage({ role: 'user', text: displayVal });
|
|
45
|
-
const abortController = new AbortController();
|
|
46
|
-
callbacks.setAbortController?.(abortController);
|
|
47
41
|
let turnStatus = 'failed';
|
|
48
42
|
let idleTimer;
|
|
49
43
|
let loadedMcp;
|
|
@@ -59,7 +53,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
59
53
|
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride });
|
|
60
54
|
if (!runtime?.model) {
|
|
61
55
|
callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
|
|
62
|
-
turnStatus = '
|
|
56
|
+
turnStatus = 'failed';
|
|
63
57
|
return { status: turnStatus };
|
|
64
58
|
}
|
|
65
59
|
thinkingLabel = modelThinkingLabel(runtime.config.modelName);
|
|
@@ -67,7 +61,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
67
61
|
let activeContextFiles = contextFiles;
|
|
68
62
|
const activeModel = runtime.model;
|
|
69
63
|
const providerSettings = providerRequestSettings(runtime.config);
|
|
70
|
-
const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel });
|
|
64
|
+
const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel, abortSignal: abortController.signal });
|
|
71
65
|
const availableTools = assembled.availableTools;
|
|
72
66
|
loadedMcp = assembled.loadedMcp;
|
|
73
67
|
if (loadedMcp?.errors.length)
|
|
@@ -109,6 +103,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
109
103
|
let currentAssistantText = '';
|
|
110
104
|
let streamError;
|
|
111
105
|
let streamFinished = false;
|
|
106
|
+
let finishReason;
|
|
107
|
+
let lastToolOk;
|
|
108
|
+
let completedSteps = 0;
|
|
109
|
+
let completedToolCalls = 0;
|
|
110
|
+
let completedToolOnlySteps = 0;
|
|
112
111
|
let toolResultState = initialToolResultState();
|
|
113
112
|
const resetAssistantSegment = () => {
|
|
114
113
|
currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
@@ -172,6 +171,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
172
171
|
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
173
172
|
},
|
|
174
173
|
onStepEnd({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
|
|
174
|
+
completedSteps++;
|
|
175
|
+
completedToolCalls += toolCalls.length;
|
|
176
|
+
if (toolCalls.length > 0 && text.trim().length === 0)
|
|
177
|
+
completedToolOnlySteps++;
|
|
175
178
|
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
176
179
|
latestAccumulatedResponseMessages = response.messages;
|
|
177
180
|
const stepUsage = stepCacheMetrics(usage);
|
|
@@ -260,15 +263,16 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
260
263
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
261
264
|
latestToolCalls.set(part.toolCallId, toolCall);
|
|
262
265
|
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
263
|
-
const
|
|
266
|
+
const ok = toolOutputOk(part.output, true);
|
|
267
|
+
lastToolOk = ok;
|
|
268
|
+
const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
|
|
264
269
|
const item = toolDisplay.ensureToolItem(toolCall);
|
|
265
|
-
item.status =
|
|
270
|
+
item.status = ok ? 'success' : 'error';
|
|
266
271
|
item.result = toolResultSummary(finish);
|
|
267
272
|
item.durationMs = finish.durationMs;
|
|
268
273
|
item.finishedAt = startedAt + finish.durationMs;
|
|
269
|
-
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success:
|
|
270
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success:
|
|
271
|
-
const ok = toolOutputOk(part.output, true);
|
|
274
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs }));
|
|
275
|
+
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs } });
|
|
272
276
|
toolResultState = applyToolResultState(toolResultState, { toolName: toolCall.toolName, input: toolCall.input, output: part.output, ok });
|
|
273
277
|
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
274
278
|
callbacks.setWorkState?.(goal);
|
|
@@ -286,6 +290,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
286
290
|
const existing = latestToolCalls.get(part.toolCallId);
|
|
287
291
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
|
|
288
292
|
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
293
|
+
lastToolOk = false;
|
|
289
294
|
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
290
295
|
const item = toolDisplay.ensureToolItem(toolCall);
|
|
291
296
|
item.status = 'error';
|
|
@@ -309,6 +314,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
309
314
|
break;
|
|
310
315
|
case 'finish':
|
|
311
316
|
streamFinished = true;
|
|
317
|
+
finishReason = part.finishReason;
|
|
312
318
|
callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
|
|
313
319
|
break;
|
|
314
320
|
default:
|
|
@@ -338,13 +344,17 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
338
344
|
finalizeAssistantSegment();
|
|
339
345
|
}
|
|
340
346
|
else if (latestToolCalls.size > 0) {
|
|
341
|
-
|
|
342
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(fallback, assistantStartedAt) });
|
|
347
|
+
callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
|
|
343
348
|
}
|
|
349
|
+
const budgetReached = finishReason === 'length'
|
|
350
|
+
|| completedSteps >= MAIN_STEP_LIMIT
|
|
351
|
+
|| completedToolCalls >= MAIN_TOOL_CALL_LIMIT
|
|
352
|
+
|| completedToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT;
|
|
353
|
+
turnStatus = terminalTurnStatus({ aborted: false, assistantText, sawToolCall: latestToolCalls.size > 0, lastToolOk, finishReason, budgetReached });
|
|
344
354
|
goal.phase = 'done';
|
|
345
|
-
goal.status = 'complete';
|
|
355
|
+
goal.status = turnStatus === 'complete' ? 'complete' : 'blocked';
|
|
356
|
+
callbacks.setWorkState?.(goal);
|
|
346
357
|
callbacks.setGoalStatus?.(undefined);
|
|
347
|
-
turnStatus = 'complete';
|
|
348
358
|
}
|
|
349
359
|
catch (error) {
|
|
350
360
|
if (abortController.signal.aborted) {
|
|
@@ -360,7 +370,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
360
370
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
361
371
|
if (compacted) {
|
|
362
372
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
|
|
363
|
-
return
|
|
373
|
+
return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
|
|
364
374
|
}
|
|
365
375
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
|
|
366
376
|
}
|
|
@@ -369,12 +379,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
369
379
|
const delay = retryDelayMs(retryAttempt);
|
|
370
380
|
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
|
|
371
381
|
callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
|
|
372
|
-
|
|
373
|
-
if (abortController.signal.aborted) {
|
|
374
|
-
turnStatus = 'aborted';
|
|
375
|
-
return { status: turnStatus };
|
|
376
|
-
}
|
|
377
|
-
return await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered, session, modelOverride);
|
|
382
|
+
return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
|
|
378
383
|
}
|
|
379
384
|
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
380
385
|
}
|
|
@@ -386,10 +391,42 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
386
391
|
clearTimeout(idleTimer);
|
|
387
392
|
toolDisplay.stopToolTimer();
|
|
388
393
|
toolDisplay.finalizeToolGroup();
|
|
389
|
-
|
|
394
|
+
}
|
|
395
|
+
return { status: turnStatus };
|
|
396
|
+
}
|
|
397
|
+
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
|
|
398
|
+
const abortController = new AbortController();
|
|
399
|
+
let status = 'failed';
|
|
400
|
+
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
401
|
+
callbacks.setBusy(true);
|
|
402
|
+
callbacks.setAbortController?.(abortController);
|
|
403
|
+
if (!retryingExistingRequest)
|
|
404
|
+
callbacks.addMessage({ role: 'user', text: displayValue ?? value });
|
|
405
|
+
try {
|
|
406
|
+
let attempt = retryAttempt;
|
|
407
|
+
let overflowRecovered = contextOverflowRecovered;
|
|
408
|
+
let retrying = retryingExistingRequest;
|
|
409
|
+
while (true) {
|
|
410
|
+
const result = await runAgentAttempt(value, contextFiles, callbacks, attempt, retrying, overflowRecovered, session, modelOverride, abortController);
|
|
411
|
+
status = result.status;
|
|
412
|
+
if (!result.retry)
|
|
413
|
+
break;
|
|
414
|
+
attempt = result.retry.attempt;
|
|
415
|
+
overflowRecovered = result.retry.contextOverflowRecovered;
|
|
416
|
+
retrying = true;
|
|
417
|
+
if (result.retry.delayMs > 0)
|
|
418
|
+
await abortableDelay(result.retry.delayMs, abortController.signal);
|
|
419
|
+
if (abortController.signal.aborted) {
|
|
420
|
+
status = 'aborted';
|
|
421
|
+
break;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return { status };
|
|
425
|
+
}
|
|
426
|
+
finally {
|
|
427
|
+
callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status }));
|
|
390
428
|
callbacks.setAbortController?.(null);
|
|
391
|
-
callbacks.setBusyLabel?.(
|
|
429
|
+
callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
|
|
392
430
|
callbacks.setBusy(false);
|
|
393
431
|
}
|
|
394
|
-
return { status: turnStatus };
|
|
395
432
|
}
|
|
@@ -48,5 +48,5 @@ export function captureMcpCommand(value) {
|
|
|
48
48
|
const parts = commandParts(value);
|
|
49
49
|
if (parts.length === 0)
|
|
50
50
|
return { message: 'Command is required.' };
|
|
51
|
-
return { draft: { command: parts[0], args: parts.slice(1) }, nextMode: '
|
|
51
|
+
return { draft: { command: parts[0], args: parts.slice(1) }, nextMode: 'chat', systemMessage: 'Stdio MCP authentication must be handled by the command or wrapper; HTTP headers do not apply.' };
|
|
52
52
|
}
|
|
@@ -96,7 +96,8 @@ export function mcpActionSuggestions(settings, selectedMcpName) {
|
|
|
96
96
|
const result = [];
|
|
97
97
|
if (server) {
|
|
98
98
|
result.push({ value: server.enabled === false ? COMMON_ACTIONS.enable : COMMON_ACTIONS.disable, description: `${server.enabled === false ? COMMON_ACTIONS.enable : COMMON_ACTIONS.disable} this server`, kind: 'mcp' });
|
|
99
|
-
|
|
99
|
+
if (server.transport !== 'stdio')
|
|
100
|
+
result.push({ value: MCP_ACTIONS.setApiKey, description: server.headers?.length ? 'update the saved API key' : 'add an API key', kind: 'mcp' });
|
|
100
101
|
}
|
|
101
102
|
result.push({ value: MCP_ACTIONS.removeServer, description: 'remove this server', kind: 'mcp' });
|
|
102
103
|
return result;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { HazeSettings, HazeMcpServer, HazeProviderSettings } from '../../config/settings.js';
|
|
2
|
+
import type { Mode } from './chatModes.js';
|
|
3
|
+
type SharedWizardEffect = {
|
|
4
|
+
type: 'message';
|
|
5
|
+
text?: string;
|
|
6
|
+
} | {
|
|
7
|
+
type: 'mode';
|
|
8
|
+
mode: Mode;
|
|
9
|
+
};
|
|
10
|
+
export type ProviderWizardEffect = SharedWizardEffect | {
|
|
11
|
+
type: 'provider-draft';
|
|
12
|
+
patch: Partial<HazeProviderSettings>;
|
|
13
|
+
replace?: boolean;
|
|
14
|
+
};
|
|
15
|
+
export type McpWizardEffect = SharedWizardEffect | {
|
|
16
|
+
type: 'mcp-draft';
|
|
17
|
+
patch: Partial<HazeMcpServer>;
|
|
18
|
+
} | {
|
|
19
|
+
type: 'finish-mcp-stdio';
|
|
20
|
+
draft: Partial<HazeMcpServer>;
|
|
21
|
+
};
|
|
22
|
+
export declare function transitionProviderField(input: {
|
|
23
|
+
mode: Mode;
|
|
24
|
+
value: string;
|
|
25
|
+
settings: HazeSettings;
|
|
26
|
+
}): ProviderWizardEffect[] | undefined;
|
|
27
|
+
export declare function transitionMcpField(input: {
|
|
28
|
+
mode: Mode;
|
|
29
|
+
value: string;
|
|
30
|
+
settings: HazeSettings;
|
|
31
|
+
draft: Partial<HazeMcpServer>;
|
|
32
|
+
}): McpWizardEffect[] | undefined;
|
|
33
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { captureMcpCommand, captureMcpName, captureMcpTransport, captureMcpUrl, captureProviderName, captureProviderUrl } from './wizardPrompts.js';
|
|
2
|
+
export function transitionProviderField(input) {
|
|
3
|
+
if (input.mode === 'providerAddKey') {
|
|
4
|
+
const key = input.value.trim();
|
|
5
|
+
return [
|
|
6
|
+
{ type: 'provider-draft', patch: key ? { key } : {} },
|
|
7
|
+
{ type: 'mode', mode: 'providerAddModels' },
|
|
8
|
+
{ type: 'message', text: 'Comma-separated model names? Example: llama3.1, qwen2.5-coder, gpt-4o' },
|
|
9
|
+
];
|
|
10
|
+
}
|
|
11
|
+
const result = input.mode === 'providerAddName' ? captureProviderName(input.settings, input.value)
|
|
12
|
+
: input.mode === 'providerAddUrl' ? captureProviderUrl(input.value)
|
|
13
|
+
: undefined;
|
|
14
|
+
if (!result)
|
|
15
|
+
return undefined;
|
|
16
|
+
if (result.message)
|
|
17
|
+
return [{ type: 'message', text: result.message }];
|
|
18
|
+
const patch = result.draft ?? {};
|
|
19
|
+
return [
|
|
20
|
+
...(Object.keys(patch).length ? [{ type: 'provider-draft', patch, replace: input.mode === 'providerAddName' }] : []),
|
|
21
|
+
...(result.nextMode ? [{ type: 'mode', mode: result.nextMode }] : []),
|
|
22
|
+
{ type: 'message', text: result.systemMessage },
|
|
23
|
+
];
|
|
24
|
+
}
|
|
25
|
+
export function transitionMcpField(input) {
|
|
26
|
+
const result = input.mode === 'mcpAddName' ? captureMcpName(input.settings, input.value)
|
|
27
|
+
: input.mode === 'mcpAddTransport' ? captureMcpTransport(input.value)
|
|
28
|
+
: input.mode === 'mcpAddUrl' ? captureMcpUrl(input.value)
|
|
29
|
+
: input.mode === 'mcpAddCommand' ? captureMcpCommand(input.value)
|
|
30
|
+
: undefined;
|
|
31
|
+
if (!result)
|
|
32
|
+
return undefined;
|
|
33
|
+
if (result.message)
|
|
34
|
+
return [{ type: 'message', text: result.message }];
|
|
35
|
+
const patch = result.draft ?? {};
|
|
36
|
+
const nextDraft = { ...input.draft, ...patch };
|
|
37
|
+
if (result.nextMode === 'chat' && input.mode === 'mcpAddCommand')
|
|
38
|
+
return [{ type: 'finish-mcp-stdio', draft: nextDraft }];
|
|
39
|
+
return [
|
|
40
|
+
...(Object.keys(patch).length ? [{ type: 'mcp-draft', patch }] : []),
|
|
41
|
+
...(result.nextMode ? [{ type: 'mode', mode: result.nextMode }] : []),
|
|
42
|
+
{ type: 'message', text: result.systemMessage },
|
|
43
|
+
];
|
|
44
|
+
}
|
|
@@ -3,6 +3,7 @@ import os from 'node:os';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import crypto from 'node:crypto';
|
|
5
5
|
import { HAZE_DIR } from './paths.js';
|
|
6
|
+
import { readUtf8Prefix } from '../core/io/boundedRead.js';
|
|
6
7
|
const DEFAULT_BUDGET_THRESHOLD = 0.15;
|
|
7
8
|
function resolveBudgetThreshold(explicit) {
|
|
8
9
|
if (typeof explicit === 'number' && Number.isFinite(explicit))
|
|
@@ -54,11 +55,13 @@ async function readContextCandidates(candidates, seen = new Set(), options = {})
|
|
|
54
55
|
if (loadedSignature === signature)
|
|
55
56
|
continue;
|
|
56
57
|
options.onContextFileRead?.(displayedPath);
|
|
57
|
-
const
|
|
58
|
+
const prefix = await readUtf8Prefix(absolute, MAX_CONTEXT_FILE_CHARS * 4);
|
|
59
|
+
const content = prefix.content.slice(0, MAX_CONTEXT_FILE_CHARS);
|
|
60
|
+
const truncated = prefix.truncated || prefix.content.length > MAX_CONTEXT_FILE_CHARS;
|
|
58
61
|
const file = {
|
|
59
62
|
path: displayedPath,
|
|
60
|
-
content:
|
|
61
|
-
? `${content
|
|
63
|
+
content: truncated
|
|
64
|
+
? `${content}\n\n[Context file truncated at ${MAX_CONTEXT_FILE_CHARS} characters; source is ${prefix.totalBytes} bytes]`
|
|
62
65
|
: content,
|
|
63
66
|
signature,
|
|
64
67
|
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
function hasCredentials(credentials) {
|
|
2
|
+
if (typeof credentials === 'string')
|
|
3
|
+
return credentials.trim().length > 0;
|
|
4
|
+
if (Array.isArray(credentials))
|
|
5
|
+
return credentials.some(item => typeof item === 'object' && item != null && 'value' in item && String(item.value).trim().length > 0);
|
|
6
|
+
return Boolean(credentials);
|
|
7
|
+
}
|
|
8
|
+
export function isLoopbackHostname(hostname) {
|
|
9
|
+
const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
10
|
+
if (host === 'localhost' || host.endsWith('.localhost') || host === '::1')
|
|
11
|
+
return true;
|
|
12
|
+
const parts = host.split('.').map(Number);
|
|
13
|
+
return parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255) && parts[0] === 127;
|
|
14
|
+
}
|
|
15
|
+
export function assertCredentialedEndpointSecure(urlValue, credentials) {
|
|
16
|
+
let url;
|
|
17
|
+
try {
|
|
18
|
+
url = new URL(urlValue);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
throw new Error(`Invalid endpoint URL: ${urlValue}`);
|
|
22
|
+
}
|
|
23
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
24
|
+
throw new Error(`Unsupported endpoint protocol: ${url.protocol}`);
|
|
25
|
+
if (url.protocol === 'http:' && hasCredentials(credentials) && !isLoopbackHostname(url.hostname)) {
|
|
26
|
+
throw new Error(`Refusing to send credentials over plaintext HTTP to remote endpoint ${url.origin}. Use HTTPS or a loopback endpoint.`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from 'fs-extra';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { HAZE_DIR } from './paths.js';
|
|
4
|
+
import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
|
|
4
5
|
const HISTORY_DIR = path.join(HAZE_DIR, 'history');
|
|
5
6
|
export const INPUT_HISTORY_FILE = path.join(HISTORY_DIR, 'input-history.json');
|
|
6
7
|
const MAX_HISTORY_ITEMS = 500;
|
|
@@ -14,6 +15,8 @@ function normalizeHistory(value) {
|
|
|
14
15
|
export async function readInputHistory() {
|
|
15
16
|
if (DISABLE_PERSISTENT_HISTORY)
|
|
16
17
|
return testHistory.slice(-MAX_HISTORY_ITEMS);
|
|
18
|
+
if (await fs.pathExists(INPUT_HISTORY_FILE))
|
|
19
|
+
await tightenPrivateFile(INPUT_HISTORY_FILE);
|
|
17
20
|
const data = await fs.readJson(INPUT_HISTORY_FILE).catch(() => []);
|
|
18
21
|
return normalizeHistory(data).slice(-MAX_HISTORY_ITEMS);
|
|
19
22
|
}
|
|
@@ -23,8 +26,7 @@ export async function writeInputHistory(history) {
|
|
|
23
26
|
testHistory = normalized;
|
|
24
27
|
return;
|
|
25
28
|
}
|
|
26
|
-
await
|
|
27
|
-
await fs.writeJson(INPUT_HISTORY_FILE, normalized, { spaces: 2 });
|
|
29
|
+
await writePrivateJsonAtomic(INPUT_HISTORY_FILE, normalized);
|
|
28
30
|
}
|
|
29
31
|
export async function addInputHistoryItem(item) {
|
|
30
32
|
const trimmed = item.trim();
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare function ensurePrivateDir(dir: string): Promise<void>;
|
|
2
|
+
export declare function ensurePrivateFile(file: string): Promise<void>;
|
|
3
|
+
export declare function tightenPrivateFile(file: string): Promise<void>;
|
|
4
|
+
export declare function appendPrivateFile(file: string, content: string): Promise<void>;
|
|
5
|
+
export declare function writePrivateFileAtomic(file: string, content: string): Promise<void>;
|
|
6
|
+
export declare function writePrivateJsonAtomic(file: string, value: unknown): Promise<void>;
|