@denizokcu/haze 0.7.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 +35 -9
- package/README.md +37 -35
- package/dist/cli/chat/inputSuggestions.js +2 -2
- package/dist/cli/chat/sessionRecorder.d.ts +3 -0
- package/dist/cli/chat/sessionRecorder.js +23 -8
- package/dist/cli/commands/chat.js +136 -124
- package/dist/cli/commands/chatModes.js +1 -1
- package/dist/cli/commands/commandHelp.js +2 -2
- package/dist/cli/commands/commands.d.ts +1 -1
- package/dist/cli/commands/commands.js +1 -1
- package/dist/cli/commands/formatters.d.ts +6 -0
- package/dist/cli/commands/formatters.js +41 -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 +99 -51
- package/dist/cli/commands/wizardPrompts.js +1 -1
- package/dist/cli/commands/wizardSuggestions.js +3 -2
- 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/providers.js +5 -9
- package/dist/config/settings.d.ts +1 -0
- package/dist/config/settings.js +55 -3
- package/dist/config/updateCheck.js +4 -2
- package/dist/core/agent/compaction.js +2 -2
- package/dist/core/agent/errors.js +1 -1
- package/dist/core/agent/requestAssembly.d.ts +1 -0
- package/dist/core/agent/requestAssembly.js +13 -0
- package/dist/core/agent/toolOutputStore.d.ts +3 -0
- package/dist/core/agent/toolOutputStore.js +32 -11
- package/dist/core/bashOutput/registry.js +11 -9
- package/dist/core/goal/completionPolicy.d.ts +0 -28
- package/dist/core/goal/completionPolicy.js +1 -89
- 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.d.ts +252 -9
- package/dist/core/subagent/subagentRunner.js +14 -19
- 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/client.d.ts +2 -2
- package/dist/llm/client.js +19 -3
- package/dist/llm/hazeTools.d.ts +8103 -364
- package/dist/llm/hazeTools.js +43 -33
- package/dist/llm/initPrompt.js +1 -1
- package/dist/llm/lsp.d.ts +21 -3
- package/dist/llm/lsp.js +65 -14
- package/dist/llm/lspTools.d.ts +2358 -101
- 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/systemPrompt.js +2 -2
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/tools/bashTool.d.ts +603 -5
- package/dist/llm/tools/bashTool.js +23 -60
- package/dist/llm/tools/fetchTool.d.ts +1201 -65
- package/dist/llm/tools/fetchTool.js +2 -1
- package/dist/llm/tools/grepRunner.d.ts +15 -0
- package/dist/llm/tools/grepRunner.js +85 -0
- package/dist/llm/tools/storedOutputTool.d.ts +351 -10
- package/dist/llm/tools/taskTool.d.ts +629 -28
- package/dist/llm/tools/toolContext.d.ts +7 -2
- package/dist/llm/tools/toolContext.js +11 -2
- package/dist/llm/webFetch.js +31 -21
- package/dist/skills/SkillLoader.js +17 -5
- package/dist/skills/SkillRegistry.js +19 -6
- package/dist/skills/builder/SkillBuilder.js +7 -7
- package/dist/skills/types.d.ts +5 -0
- package/dist/ui/components/TextInput.d.ts +7 -0
- package/dist/ui/components/TextInput.js +10 -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 +9 -4
- package/examples/skills/files/SKILL.md +1 -1
- package/package.json +14 -14
|
@@ -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>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { HAZE_DIR } from './paths.js';
|
|
4
|
+
const DIRECTORY_MODE = 0o700;
|
|
5
|
+
const FILE_MODE = 0o600;
|
|
6
|
+
export async function ensurePrivateDir(dir) {
|
|
7
|
+
const absolute = path.resolve(dir);
|
|
8
|
+
await fs.mkdir(absolute, { recursive: true, mode: DIRECTORY_MODE });
|
|
9
|
+
if (process.platform === 'win32')
|
|
10
|
+
return;
|
|
11
|
+
const hazeRoot = path.resolve(HAZE_DIR);
|
|
12
|
+
const relative = path.relative(hazeRoot, absolute);
|
|
13
|
+
if (!relative.startsWith('..') && !path.isAbsolute(relative)) {
|
|
14
|
+
await fs.chmod(hazeRoot, DIRECTORY_MODE);
|
|
15
|
+
let current = hazeRoot;
|
|
16
|
+
for (const segment of relative.split(path.sep).filter(Boolean)) {
|
|
17
|
+
current = path.join(current, segment);
|
|
18
|
+
await fs.chmod(current, DIRECTORY_MODE);
|
|
19
|
+
}
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
await fs.chmod(absolute, DIRECTORY_MODE);
|
|
23
|
+
}
|
|
24
|
+
export async function ensurePrivateFile(file) {
|
|
25
|
+
await ensurePrivateDir(path.dirname(file));
|
|
26
|
+
const handle = await fs.open(file, 'a', FILE_MODE);
|
|
27
|
+
await handle.close();
|
|
28
|
+
if (process.platform !== 'win32')
|
|
29
|
+
await fs.chmod(file, FILE_MODE);
|
|
30
|
+
}
|
|
31
|
+
export async function tightenPrivateFile(file) {
|
|
32
|
+
await ensurePrivateDir(path.dirname(file));
|
|
33
|
+
if (process.platform !== 'win32')
|
|
34
|
+
await fs.chmod(file, FILE_MODE);
|
|
35
|
+
}
|
|
36
|
+
export async function appendPrivateFile(file, content) {
|
|
37
|
+
await ensurePrivateFile(file);
|
|
38
|
+
await fs.appendFile(file, content, { encoding: 'utf8', mode: FILE_MODE });
|
|
39
|
+
}
|
|
40
|
+
export async function writePrivateFileAtomic(file, content) {
|
|
41
|
+
await ensurePrivateDir(path.dirname(file));
|
|
42
|
+
const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
43
|
+
let handle;
|
|
44
|
+
try {
|
|
45
|
+
handle = await fs.open(temp, 'wx', FILE_MODE);
|
|
46
|
+
await handle.writeFile(content, 'utf8');
|
|
47
|
+
await handle.sync();
|
|
48
|
+
await handle.close();
|
|
49
|
+
handle = undefined;
|
|
50
|
+
await fs.rename(temp, file);
|
|
51
|
+
if (process.platform !== 'win32')
|
|
52
|
+
await fs.chmod(file, FILE_MODE);
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
await handle?.close().catch(() => undefined);
|
|
56
|
+
await fs.rm(temp, { force: true }).catch(() => undefined);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export async function writePrivateJsonAtomic(file, value) {
|
|
60
|
+
await writePrivateFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`);
|
|
61
|
+
}
|
package/dist/config/providers.js
CHANGED
|
@@ -47,19 +47,15 @@ export function findProvider(settings, name) {
|
|
|
47
47
|
return findByName(configuredProviders(settings), name);
|
|
48
48
|
}
|
|
49
49
|
export function activeProvider(settings) {
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
if (!settings.provider)
|
|
51
|
+
return undefined;
|
|
52
|
+
return configuredProviders(settings).find(provider => provider.name === settings.provider);
|
|
52
53
|
}
|
|
53
54
|
export function activeModel(settings) {
|
|
54
55
|
const provider = activeProvider(settings);
|
|
55
|
-
if (!provider)
|
|
56
|
-
return undefined;
|
|
57
|
-
const model = settings.model && provider.models.includes(settings.model)
|
|
58
|
-
? settings.model
|
|
59
|
-
: provider.models[0];
|
|
60
|
-
if (!model)
|
|
56
|
+
if (!provider || !settings.model || !provider.models.includes(settings.model))
|
|
61
57
|
return undefined;
|
|
62
|
-
return { provider, model };
|
|
58
|
+
return { provider, model: settings.model };
|
|
63
59
|
}
|
|
64
60
|
export function resolveModelSelector(settings, selector) {
|
|
65
61
|
const trimmed = selector.trim();
|
package/dist/config/settings.js
CHANGED
|
@@ -1,13 +1,65 @@
|
|
|
1
1
|
import fs from 'fs-extra';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
3
4
|
import { HAZE_DIR } from './paths.js';
|
|
5
|
+
import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
|
|
4
6
|
export const SETTINGS_FILE = path.join(HAZE_DIR, 'settings.json');
|
|
7
|
+
const providerSchema = z.object({
|
|
8
|
+
name: z.string(),
|
|
9
|
+
url: z.string(),
|
|
10
|
+
key: z.string().optional(),
|
|
11
|
+
models: z.array(z.string()),
|
|
12
|
+
}).passthrough();
|
|
13
|
+
const lspServerSchema = z.object({
|
|
14
|
+
name: z.string(),
|
|
15
|
+
command: z.string(),
|
|
16
|
+
args: z.array(z.string()).optional(),
|
|
17
|
+
extensions: z.array(z.string()).optional(),
|
|
18
|
+
rootPatterns: z.array(z.string()).optional(),
|
|
19
|
+
enabled: z.boolean().optional(),
|
|
20
|
+
}).passthrough();
|
|
21
|
+
const mcpHeaderSchema = z.object({ name: z.string(), value: z.string() }).passthrough();
|
|
22
|
+
const mcpServerSchema = z.object({
|
|
23
|
+
name: z.string(),
|
|
24
|
+
transport: z.enum(['http', 'sse', 'stdio']),
|
|
25
|
+
url: z.string().optional(),
|
|
26
|
+
command: z.string().optional(),
|
|
27
|
+
args: z.array(z.string()).optional(),
|
|
28
|
+
headers: z.array(mcpHeaderSchema).optional(),
|
|
29
|
+
enabled: z.boolean().optional(),
|
|
30
|
+
}).passthrough();
|
|
31
|
+
const skillSettingSchema = z.object({ name: z.string(), enabled: z.boolean().optional() }).passthrough();
|
|
32
|
+
const settingsSchema = z.object({
|
|
33
|
+
provider: z.string().optional(),
|
|
34
|
+
model: z.string().optional(),
|
|
35
|
+
providers: z.array(providerSchema).optional(),
|
|
36
|
+
lspServers: z.array(lspServerSchema).optional(),
|
|
37
|
+
mcpServers: z.array(mcpServerSchema).optional(),
|
|
38
|
+
skills: z.array(skillSettingSchema).optional(),
|
|
39
|
+
apiKey: z.string().optional(),
|
|
40
|
+
baseURL: z.string().optional(),
|
|
41
|
+
}).passthrough();
|
|
42
|
+
function settingsReadError(error) {
|
|
43
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
44
|
+
return new Error(`Failed to read Haze settings at ${SETTINGS_FILE}: ${message}. Fix or remove the settings file, then retry.`);
|
|
45
|
+
}
|
|
5
46
|
export async function readSettings() {
|
|
6
|
-
|
|
47
|
+
try {
|
|
48
|
+
if (await fs.pathExists(SETTINGS_FILE))
|
|
49
|
+
await tightenPrivateFile(SETTINGS_FILE);
|
|
50
|
+
const raw = await fs.readJson(SETTINGS_FILE);
|
|
51
|
+
return settingsSchema.parse(raw);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
|
|
55
|
+
if (code === 'ENOENT')
|
|
56
|
+
return {};
|
|
57
|
+
throw settingsReadError(error);
|
|
58
|
+
}
|
|
7
59
|
}
|
|
8
60
|
export async function writeSettings(settings) {
|
|
9
|
-
|
|
10
|
-
await
|
|
61
|
+
const parsed = settingsSchema.parse(settings);
|
|
62
|
+
await writePrivateJsonAtomic(SETTINGS_FILE, parsed);
|
|
11
63
|
}
|
|
12
64
|
export async function updateSettings(patch) {
|
|
13
65
|
const next = { ...await readSettings(), ...patch };
|
|
@@ -4,6 +4,7 @@ import fs from 'fs-extra';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { HAZE_DIR } from './paths.js';
|
|
6
6
|
import { isNewer } from '../utils/version.js';
|
|
7
|
+
import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
|
|
7
8
|
const execFile = promisify(execFileCallback);
|
|
8
9
|
export const UPDATE_CHECK_FILE = path.join(HAZE_DIR, 'updateCheck.json');
|
|
9
10
|
const DEFAULT_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24h
|
|
@@ -13,11 +14,12 @@ async function defaultExecVersion(packageName, options) {
|
|
|
13
14
|
return stdout;
|
|
14
15
|
}
|
|
15
16
|
async function defaultReadStore(file) {
|
|
17
|
+
if (await fs.pathExists(file))
|
|
18
|
+
await tightenPrivateFile(file);
|
|
16
19
|
return fs.readJson(file).catch(() => ({}));
|
|
17
20
|
}
|
|
18
21
|
async function defaultWriteStore(file, store) {
|
|
19
|
-
await
|
|
20
|
-
await fs.writeJson(file, store, { spaces: 2 });
|
|
22
|
+
await writePrivateJsonAtomic(file, store);
|
|
21
23
|
}
|
|
22
24
|
/**
|
|
23
25
|
* Non-blockingly check whether a newer version of `packageName` is published.
|
|
@@ -37,7 +37,7 @@ export function compactModelMessages(messages, options = {}) {
|
|
|
37
37
|
return text ? `- ${message.role}: ${text}` : '';
|
|
38
38
|
}).filter(Boolean).join('\n');
|
|
39
39
|
const summary = [
|
|
40
|
-
'Compacted prior
|
|
40
|
+
'Compacted prior haze conversation. Treat this as continuity context, not a new user request.',
|
|
41
41
|
'Preserve especially: current user goal and success condition; explicit user constraints/preferences/decisions; files created/changed/read; validation commands and pass/fail results; blockers or pending product decisions; exact next action if work was unfinished.',
|
|
42
42
|
'Do not treat older tool outputs as current unless the recent conversation confirms they still apply.',
|
|
43
43
|
options.instructions ? `User compaction instructions: ${options.instructions}` : undefined,
|
|
@@ -48,7 +48,7 @@ export function compactModelMessages(messages, options = {}) {
|
|
|
48
48
|
].filter((line) => line !== undefined).join('\n');
|
|
49
49
|
return {
|
|
50
50
|
compacted: true,
|
|
51
|
-
messages: [{ role: '
|
|
51
|
+
messages: [{ role: 'user', content: `<haze_compaction>\n${summary}\n</haze_compaction>` }, ...recent],
|
|
52
52
|
olderCount: older.length,
|
|
53
53
|
keptCount: recent.length,
|
|
54
54
|
summary,
|
|
@@ -9,5 +9,5 @@ export function isRetryableModelError(error) {
|
|
|
9
9
|
const text = errorText(error);
|
|
10
10
|
if (isContextOverflowError(error) || /quota|billing|balance|auth|api key|invalid request|permission|forbidden|401|403|400/.test(text))
|
|
11
11
|
return false;
|
|
12
|
-
return /overload|rate limit|429|500|502|503|504|network|connection|stream|timeout|timed? out|econnreset|etimedout|fetch failed/.test(text);
|
|
12
|
+
return /overload|rate limit|429|500|502|503|504|network|connection|stream|timeout|timed? out|terminated|econnreset|etimedout|fetch failed/.test(text);
|
|
13
13
|
}
|
|
@@ -2,6 +2,7 @@ import type { ModelMessage } from 'ai';
|
|
|
2
2
|
export declare const SYNTHETIC_CONTROL_OPEN = "<haze_control>";
|
|
3
3
|
export declare function isSyntheticControlMessage(message: ModelMessage): boolean;
|
|
4
4
|
export declare function stripSyntheticControls(messages: ModelMessage[]): ModelMessage[];
|
|
5
|
+
export declare function withoutSystemMessages(messages: ModelMessage[]): ModelMessage[];
|
|
5
6
|
export declare function withSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
|
|
6
7
|
export declare function compactToolHistory(messages: ModelMessage[], options?: {
|
|
7
8
|
keepRecentResults?: number;
|
|
@@ -9,6 +9,19 @@ export function isSyntheticControlMessage(message) {
|
|
|
9
9
|
export function stripSyntheticControls(messages) {
|
|
10
10
|
return messages.filter(message => !isSyntheticControlMessage(message));
|
|
11
11
|
}
|
|
12
|
+
export function withoutSystemMessages(messages) {
|
|
13
|
+
return messages.map(message => message.role === 'system'
|
|
14
|
+
? { ...message, role: 'user', content: `<haze_system_context>\n${modelMessageTextForContext(message)}\n</haze_system_context>` }
|
|
15
|
+
: message);
|
|
16
|
+
}
|
|
17
|
+
function modelMessageTextForContext(message) {
|
|
18
|
+
const content = message.content;
|
|
19
|
+
if (typeof content === 'string')
|
|
20
|
+
return content;
|
|
21
|
+
if (!Array.isArray(content))
|
|
22
|
+
return JSON.stringify(content);
|
|
23
|
+
return content.map(part => typeof part === 'object' && part != null && 'text' in part && typeof part.text === 'string' ? part.text : JSON.stringify(part)).join('\n');
|
|
24
|
+
}
|
|
12
25
|
export function withSyntheticControl(messages, control) {
|
|
13
26
|
return [
|
|
14
27
|
...stripSyntheticControls(messages),
|
|
@@ -1,15 +1,30 @@
|
|
|
1
1
|
import crypto from 'node:crypto';
|
|
2
|
+
import { TOOL_OUTPUT_ENTRY_BYTES, TOOL_OUTPUT_TOTAL_BYTES } from '../limits/byteBudgets.js';
|
|
2
3
|
const outputs = new Map();
|
|
3
4
|
const MAX_STORED_OUTPUTS = 100;
|
|
5
|
+
let storedBytes = 0;
|
|
6
|
+
function utf8Prefix(content, maxBytes) {
|
|
7
|
+
const bytes = Buffer.from(content, 'utf8');
|
|
8
|
+
if (bytes.length <= maxBytes)
|
|
9
|
+
return content;
|
|
10
|
+
let end = maxBytes;
|
|
11
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80)
|
|
12
|
+
end--;
|
|
13
|
+
return bytes.subarray(0, end).toString('utf8');
|
|
14
|
+
}
|
|
4
15
|
export function storeToolOutput(content) {
|
|
5
16
|
const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
17
|
+
const originalBytes = Buffer.byteLength(content, 'utf8');
|
|
18
|
+
const retained = utf8Prefix(content, TOOL_OUTPUT_ENTRY_BYTES);
|
|
19
|
+
const bytes = Buffer.byteLength(retained, 'utf8');
|
|
20
|
+
outputs.set(handle, { content: retained, bytes, originalBytes });
|
|
21
|
+
storedBytes += bytes;
|
|
22
|
+
while (outputs.size > MAX_STORED_OUTPUTS || storedBytes > TOOL_OUTPUT_TOTAL_BYTES) {
|
|
10
23
|
const oldest = outputs.keys().next().value;
|
|
11
|
-
if (oldest)
|
|
12
|
-
|
|
24
|
+
if (!oldest)
|
|
25
|
+
break;
|
|
26
|
+
storedBytes -= outputs.get(oldest)?.bytes ?? 0;
|
|
27
|
+
outputs.delete(oldest);
|
|
13
28
|
}
|
|
14
29
|
return handle;
|
|
15
30
|
}
|
|
@@ -39,15 +54,17 @@ function searchOutput(output, query, limit, contextLines = 2) {
|
|
|
39
54
|
chunks.push(`${index + 1}: ${lines[index] ?? ''}`);
|
|
40
55
|
}
|
|
41
56
|
const content = chunks.join('\n');
|
|
42
|
-
return {
|
|
57
|
+
return { offset: 0, totalChars: output.length, content: content.slice(0, limit), truncated: content.length > limit, query, matches: ranges.length };
|
|
43
58
|
}
|
|
44
59
|
export function readToolOutput(handle, offset = 0, limit = 12_000, options) {
|
|
45
|
-
const
|
|
46
|
-
if (
|
|
60
|
+
const stored = outputs.get(handle);
|
|
61
|
+
if (stored == null)
|
|
47
62
|
return undefined;
|
|
63
|
+
const output = stored.content;
|
|
48
64
|
if (options?.query?.trim()) {
|
|
49
65
|
const result = searchOutput(output, options.query.trim(), limit, options.contextLines);
|
|
50
|
-
|
|
66
|
+
const omittedBytes = stored.originalBytes - stored.bytes;
|
|
67
|
+
return { ...result, handle, truncated: result.truncated || omittedBytes > 0, totalBytes: stored.originalBytes, retainedBytes: stored.bytes, omittedBytes };
|
|
51
68
|
}
|
|
52
69
|
const safeOffset = Math.min(Math.max(0, offset), output.length);
|
|
53
70
|
const content = output.slice(safeOffset, safeOffset + limit);
|
|
@@ -57,10 +74,14 @@ export function readToolOutput(handle, offset = 0, limit = 12_000, options) {
|
|
|
57
74
|
offset: safeOffset,
|
|
58
75
|
...(nextOffset == null ? {} : { nextOffset }),
|
|
59
76
|
totalChars: output.length,
|
|
77
|
+
totalBytes: stored.originalBytes,
|
|
78
|
+
retainedBytes: stored.bytes,
|
|
79
|
+
omittedBytes: stored.originalBytes - stored.bytes,
|
|
60
80
|
content,
|
|
61
|
-
truncated: nextOffset != null,
|
|
81
|
+
truncated: nextOffset != null || stored.originalBytes > stored.bytes,
|
|
62
82
|
};
|
|
63
83
|
}
|
|
64
84
|
export function clearToolOutputs() {
|
|
65
85
|
outputs.clear();
|
|
86
|
+
storedBytes = 0;
|
|
66
87
|
}
|
|
@@ -4,7 +4,7 @@ import { reduceGitOutput } from './reducers/git.js';
|
|
|
4
4
|
import { reduceGhOutput } from './reducers/gh.js';
|
|
5
5
|
import { reduceSearchOutput } from './reducers/search.js';
|
|
6
6
|
import { reduceGenericLogOutput, reduceJsonOutput, reduceUnifiedDiffOutput } from './reducers/content.js';
|
|
7
|
-
import { isInflating, reductionMetrics, retrievalHint } from '../toolOutput/reduction.js';
|
|
7
|
+
import { capOutputForProcessing, isInflating, reductionMetrics, retrievalHint } from '../toolOutput/reduction.js';
|
|
8
8
|
export const builtInLineFilters = [
|
|
9
9
|
{ name: 'markdownlint', matchCommand: /(^|[;&|]\s*)markdownlint\b/, stripAnsi: true, truncateLinesAt: 200, maxLines: 80, onEmpty: 'markdownlint: ok' },
|
|
10
10
|
{ name: 'shellcheck', matchCommand: /(^|[;&|]\s*)shellcheck\b/, stripAnsi: true, stripLinesMatching: [/^In .* line \d+:/], truncateLinesAt: 200, maxLines: 100, onEmpty: 'shellcheck: ok' },
|
|
@@ -74,8 +74,10 @@ export function filterBashOutput(input) {
|
|
|
74
74
|
stderr = makeReduction(input.stderr, '', input.stderr.length > 0, filterName, input, undefined, 'validation');
|
|
75
75
|
}
|
|
76
76
|
else {
|
|
77
|
-
const
|
|
78
|
-
const
|
|
77
|
+
const stdoutIn = capOutputForProcessing(input.stdout);
|
|
78
|
+
const stderrIn = capOutputForProcessing(input.stderr);
|
|
79
|
+
const git = reduceGitOutput(input.command, stdoutIn, stderrIn);
|
|
80
|
+
const gh = git == null ? reduceGhOutput(input.command, stdoutIn, stderrIn) : undefined;
|
|
79
81
|
if (git != null) {
|
|
80
82
|
filterName = 'git';
|
|
81
83
|
const kind = /^git (?:diff|show):/.test(git) ? 'diff' : 'generic';
|
|
@@ -89,16 +91,16 @@ export function filterBashOutput(input) {
|
|
|
89
91
|
stderr = makeReduction(input.stderr, input.stdout ? '' : gh, true, filterName, input, undefined, kind);
|
|
90
92
|
}
|
|
91
93
|
else {
|
|
92
|
-
const search = reduceSearchOutput(input.command,
|
|
94
|
+
const search = reduceSearchOutput(input.command, stdoutIn, stderrIn);
|
|
93
95
|
if (search != null) {
|
|
94
96
|
filterName = 'search';
|
|
95
97
|
stdout = makeReduction(input.stdout, input.stdout ? search : '', true, filterName, input, undefined, 'search');
|
|
96
98
|
stderr = makeReduction(input.stderr, input.stdout ? '' : search, true, filterName, input, undefined, 'search');
|
|
97
99
|
}
|
|
98
100
|
else {
|
|
99
|
-
const diff = reduceUnifiedDiffOutput(
|
|
100
|
-
const json = diff == null ? reduceJsonOutput(
|
|
101
|
-
const log = diff == null && json == null ? reduceGenericLogOutput(
|
|
101
|
+
const diff = reduceUnifiedDiffOutput(stdoutIn, stderrIn);
|
|
102
|
+
const json = diff == null ? reduceJsonOutput(stdoutIn, stderrIn) : undefined;
|
|
103
|
+
const log = diff == null && json == null ? reduceGenericLogOutput(stdoutIn, stderrIn) : undefined;
|
|
102
104
|
const content = diff ?? json ?? log;
|
|
103
105
|
if (content != null) {
|
|
104
106
|
filterName = diff != null ? 'diff' : json != null ? 'json' : 'log';
|
|
@@ -110,8 +112,8 @@ export function filterBashOutput(input) {
|
|
|
110
112
|
const lineFilter = findLineFilter(builtInLineFilters, input.command);
|
|
111
113
|
if (lineFilter) {
|
|
112
114
|
filterName = lineFilter.name;
|
|
113
|
-
const out = input.stdout ? applyLineFilter(lineFilter, input.command,
|
|
114
|
-
const err = input.stderr ? applyLineFilter(lineFilter, input.command,
|
|
115
|
+
const out = input.stdout ? applyLineFilter(lineFilter, input.command, stdoutIn) : undefined;
|
|
116
|
+
const err = input.stderr ? applyLineFilter(lineFilter, input.command, stderrIn) : undefined;
|
|
115
117
|
stdout = makeReduction(input.stdout, out?.text ?? input.stdout, out?.filtered ?? false, lineFilter.name, input, out?.warning, 'log');
|
|
116
118
|
stderr = makeReduction(input.stderr, err?.text ?? input.stderr, err?.filtered ?? false, lineFilter.name, input, err?.warning, 'log');
|
|
117
119
|
}
|
|
@@ -1,30 +1,2 @@
|
|
|
1
|
-
import type { SessionGoal } from './sessionGoal.js';
|
|
2
|
-
export declare function looksIncomplete(text: string): boolean;
|
|
3
|
-
export declare function looksTruncated(text: string): boolean;
|
|
4
|
-
export declare function looksBlocked(text: string): boolean;
|
|
5
|
-
export interface CompletionPolicyInput {
|
|
6
|
-
request: string;
|
|
7
|
-
goal: SessionGoal;
|
|
8
|
-
assistantText: string;
|
|
9
|
-
sawReadOnlyTool: boolean;
|
|
10
|
-
sawToolCall: boolean;
|
|
11
|
-
mutatingToolSucceeded: boolean;
|
|
12
|
-
validationToolSucceeded: boolean;
|
|
13
|
-
validationToolFailed: boolean;
|
|
14
|
-
editFileFailed: boolean;
|
|
15
|
-
editRecoveryPath?: string;
|
|
16
|
-
editRecoveryReasonCode?: string;
|
|
17
|
-
}
|
|
18
|
-
export interface CompletionDecision {
|
|
19
|
-
needsActionContinuation: boolean;
|
|
20
|
-
needsValidationContinuation: boolean;
|
|
21
|
-
requestCompletedByTools: boolean;
|
|
22
|
-
assistantAdmitsIncomplete: boolean;
|
|
23
|
-
assistantReportsBlocker: boolean;
|
|
24
|
-
continuationPrompt?: string;
|
|
25
|
-
}
|
|
26
|
-
export declare function completionDecision(input: CompletionPolicyInput): CompletionDecision;
|
|
27
1
|
export declare function toolLoopBudgetPrompt(): string;
|
|
28
2
|
export declare function repeatedToolCallPrompt(toolNames: string[]): string;
|
|
29
|
-
export declare function postContinuationPrompt(): string;
|
|
30
|
-
export declare function noTextAfterToolPrompt(allowTools: boolean): "Continue the original request now. If it asks for a change, edit or write the necessary files. If it asks to run or verify tests, run the command. Do not provide only a retrospective summary unless blocked or needing a user decision." | "Continue from the tool result and answer my original request. Do not call tools. Use the final status template for implementation-like requests; summarize only current-turn changes and validation; do not recap unrelated earlier tasks.";
|