@denizokcu/haze 0.3.0 → 0.5.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 +62 -0
- package/README.md +50 -36
- package/dist/cli/commands/chat.d.ts +1 -1
- package/dist/cli/commands/chat.js +244 -94
- package/dist/cli/commands/commands.js +119 -114
- package/dist/cli/commands/streaming.d.ts +37 -5
- package/dist/cli/commands/streaming.js +455 -192
- package/dist/cli/contextReport.d.ts +1 -0
- package/dist/cli/contextReport.js +47 -0
- package/dist/config/contextFiles.d.ts +31 -0
- package/dist/config/contextFiles.js +97 -13
- package/dist/config/providers.d.ts +2 -5
- package/dist/config/providers.js +16 -12
- package/dist/core/agent/compaction.d.ts +3 -0
- package/dist/core/agent/compaction.js +23 -3
- package/dist/core/agent/contextBudget.d.ts +33 -0
- package/dist/core/agent/contextBudget.js +88 -0
- package/dist/core/agent/requestAssembly.d.ts +22 -0
- package/dist/core/agent/requestAssembly.js +157 -0
- package/dist/core/agent/toolOutputStore.d.ts +16 -0
- package/dist/core/agent/toolOutputStore.js +65 -0
- package/dist/core/agent/workState.d.ts +38 -0
- package/dist/core/agent/workState.js +89 -0
- package/dist/core/bashOutput/ansi.d.ts +1 -0
- package/dist/core/bashOutput/ansi.js +7 -0
- package/dist/core/bashOutput/command.d.ts +2 -0
- package/dist/core/bashOutput/command.js +62 -0
- package/dist/core/bashOutput/lineFilter.d.ts +25 -0
- package/dist/core/bashOutput/lineFilter.js +62 -0
- package/dist/core/bashOutput/reducers/content.d.ts +3 -0
- package/dist/core/bashOutput/reducers/content.js +134 -0
- package/dist/core/bashOutput/reducers/git.d.ts +1 -0
- package/dist/core/bashOutput/reducers/git.js +147 -0
- package/dist/core/bashOutput/reducers/search.d.ts +7 -0
- package/dist/core/bashOutput/reducers/search.js +76 -0
- package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
- package/dist/core/bashOutput/reducers/validation.js +41 -0
- package/dist/core/bashOutput/registry.d.ts +4 -0
- package/dist/core/bashOutput/registry.js +126 -0
- package/dist/core/bashOutput/types.d.ts +46 -0
- package/dist/core/bashOutput/types.js +1 -0
- package/dist/core/goal/completionPolicy.d.ts +1 -0
- package/dist/core/goal/completionPolicy.js +5 -1
- package/dist/core/goal/sessionGoal.d.ts +2 -0
- package/dist/core/goal/sessionGoal.js +8 -1
- package/dist/core/log/llmLog.d.ts +68 -0
- package/dist/core/log/llmLog.js +55 -0
- package/dist/core/safety/urlGuard.d.ts +37 -0
- package/dist/core/safety/urlGuard.js +206 -0
- package/dist/core/session/sessionStore.d.ts +6 -0
- package/dist/core/session/sessionStore.js +5 -0
- package/dist/core/subagent/subagentRunner.d.ts +4 -1
- package/dist/core/subagent/subagentRunner.js +5 -15
- package/dist/core/toolOutput/reduction.d.ts +25 -0
- package/dist/core/toolOutput/reduction.js +23 -0
- package/dist/core/validation/outputParser.js +15 -2
- package/dist/llm/client.d.ts +40 -1
- package/dist/llm/client.js +51 -5
- package/dist/llm/hazeTools.d.ts +165 -23
- package/dist/llm/hazeTools.js +317 -65
- package/dist/llm/initPrompt.js +2 -1
- package/dist/llm/systemPrompt.d.ts +6 -1
- package/dist/llm/systemPrompt.js +44 -81
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/webFetch.d.ts +57 -0
- package/dist/llm/webFetch.js +270 -0
- package/dist/skills/builder/SkillBuilder.d.ts +16 -2
- package/dist/skills/builder/SkillBuilder.js +68 -65
- package/dist/skills/skillTools.d.ts +2 -19
- package/dist/skills/skillTools.js +28 -19
- package/dist/ui/components/MarkdownText.d.ts +2 -0
- package/dist/ui/components/MarkdownText.js +116 -3
- package/package.json +18 -10
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { buildSystemPrompt } from '../llm/systemPrompt.js';
|
|
4
|
+
import { hazeTools } from '../llm/hazeTools.js';
|
|
5
|
+
import { contextBreakdown } from '../core/agent/contextBudget.js';
|
|
6
|
+
import { compactToolHistory } from '../core/agent/requestAssembly.js';
|
|
7
|
+
import { compactModelMessages } from '../core/agent/compaction.js';
|
|
8
|
+
import { summarizeContextDiagnostics } from '../config/contextFiles.js';
|
|
9
|
+
const reportSession = { start: new Date(0), cwd: process.cwd() };
|
|
10
|
+
async function loadFiles(paths) {
|
|
11
|
+
const candidates = paths.length > 0 ? paths : ['AGENTS.md', 'CLAUDE.md'];
|
|
12
|
+
const files = [];
|
|
13
|
+
for (const candidate of candidates) {
|
|
14
|
+
const absolute = path.resolve(candidate);
|
|
15
|
+
if (!await fs.pathExists(absolute) || !(await fs.stat(absolute)).isFile())
|
|
16
|
+
continue;
|
|
17
|
+
files.push({ path: path.relative(process.cwd(), absolute) || path.basename(absolute), content: await fs.readFile(absolute, 'utf8') });
|
|
18
|
+
}
|
|
19
|
+
return files;
|
|
20
|
+
}
|
|
21
|
+
const args = process.argv.slice(2);
|
|
22
|
+
const traceIndex = args.indexOf('--trace');
|
|
23
|
+
if (traceIndex >= 0) {
|
|
24
|
+
const tracePath = args[traceIndex + 1];
|
|
25
|
+
if (!tracePath)
|
|
26
|
+
throw new Error('--trace requires a JSON fixture path');
|
|
27
|
+
const raw = await fs.readJson(path.resolve(tracePath));
|
|
28
|
+
const messages = raw.messages ?? [];
|
|
29
|
+
const pruned = compactToolHistory(messages);
|
|
30
|
+
const compacted = compactModelMessages(pruned.messages, { tokenBudget: 4_000 });
|
|
31
|
+
const system = buildSystemPrompt([], reportSession);
|
|
32
|
+
process.stdout.write(`${JSON.stringify({
|
|
33
|
+
trace: tracePath,
|
|
34
|
+
before: contextBreakdown({ system, messages, tools: hazeTools }),
|
|
35
|
+
after: contextBreakdown({ system, messages: compacted.messages, tools: hazeTools }),
|
|
36
|
+
compactedToolResults: pruned.compactedResults,
|
|
37
|
+
compactedToolCalls: pruned.compactedCalls,
|
|
38
|
+
compactedMessages: compacted.compacted,
|
|
39
|
+
olderMessagesRemoved: compacted.olderCount,
|
|
40
|
+
}, null, 2)}\n`);
|
|
41
|
+
process.exit(0);
|
|
42
|
+
}
|
|
43
|
+
const files = await loadFiles(args);
|
|
44
|
+
const system = buildSystemPrompt(files, reportSession);
|
|
45
|
+
const breakdown = contextBreakdown({ system, contextFiles: files, messages: [], tools: hazeTools });
|
|
46
|
+
const summary = summarizeContextDiagnostics(files);
|
|
47
|
+
process.stdout.write(`${JSON.stringify({ breakdown, summary }, null, 2)}\n`);
|
|
@@ -2,4 +2,35 @@ export interface ContextFile {
|
|
|
2
2
|
path: string;
|
|
3
3
|
content: string;
|
|
4
4
|
}
|
|
5
|
+
export interface ContextFileDiagnostic {
|
|
6
|
+
path: string;
|
|
7
|
+
characters: number;
|
|
8
|
+
estimatedTokens: number;
|
|
9
|
+
contentHash: string;
|
|
10
|
+
}
|
|
11
|
+
export interface ContextFileDiagnosticsSummary {
|
|
12
|
+
totalCharacters: number;
|
|
13
|
+
totalTokens: number;
|
|
14
|
+
fileCount: number;
|
|
15
|
+
duplicateGroups: Array<{
|
|
16
|
+
hash: string;
|
|
17
|
+
paths: string[];
|
|
18
|
+
}>;
|
|
19
|
+
duplicateFileCount: number;
|
|
20
|
+
windowSize: number | undefined;
|
|
21
|
+
budgetShare: number | undefined;
|
|
22
|
+
exceedsBudget: boolean | undefined;
|
|
23
|
+
budgetThreshold: number;
|
|
24
|
+
}
|
|
25
|
+
/** Maximum characters of a context file included in every request's system context. */
|
|
26
|
+
export declare const MAX_CONTEXT_FILE_CHARS = 20000;
|
|
5
27
|
export declare function readContextFiles(cwd?: string): Promise<ContextFile[]>;
|
|
28
|
+
export declare function readScopedContextFilesForPath(targetPath: string, options?: {
|
|
29
|
+
cwd?: string;
|
|
30
|
+
alreadyLoadedPaths?: Iterable<string>;
|
|
31
|
+
}): Promise<ContextFile[]>;
|
|
32
|
+
export declare function contextFileDiagnostics(files: ContextFile[]): ContextFileDiagnostic[];
|
|
33
|
+
export declare function summarizeContextDiagnostics(files: ContextFile[], options?: {
|
|
34
|
+
windowSize?: number;
|
|
35
|
+
budgetThreshold?: number;
|
|
36
|
+
}): ContextFileDiagnosticsSummary;
|
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
import fs from 'fs-extra';
|
|
2
2
|
import os from 'node:os';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
4
5
|
import { HAZE_DIR } from './paths.js';
|
|
5
|
-
const
|
|
6
|
-
|
|
6
|
+
const DEFAULT_BUDGET_THRESHOLD = 0.15;
|
|
7
|
+
function resolveBudgetThreshold(explicit) {
|
|
8
|
+
if (typeof explicit === 'number' && Number.isFinite(explicit))
|
|
9
|
+
return Math.min(1, Math.max(0, explicit));
|
|
10
|
+
return DEFAULT_BUDGET_THRESHOLD;
|
|
11
|
+
}
|
|
12
|
+
const CONTEXT_FILE_NAMES = ['CLAUDE.md', 'AGENTS.md'];
|
|
13
|
+
/** Maximum characters of a context file included in every request's system context. */
|
|
14
|
+
export const MAX_CONTEXT_FILE_CHARS = 20_000;
|
|
7
15
|
function uniqueExistingAncestors(fromDir) {
|
|
8
16
|
const dirs = [];
|
|
9
17
|
let current = path.resolve(fromDir);
|
|
@@ -25,17 +33,7 @@ function displayPath(filePath) {
|
|
|
25
33
|
return `~/${path.relative(home, filePath)}`;
|
|
26
34
|
return filePath;
|
|
27
35
|
}
|
|
28
|
-
|
|
29
|
-
const candidates = [];
|
|
30
|
-
for (const name of CONTEXT_FILE_NAMES) {
|
|
31
|
-
candidates.push(path.join(HAZE_DIR, name));
|
|
32
|
-
}
|
|
33
|
-
for (const dir of uniqueExistingAncestors(cwd)) {
|
|
34
|
-
for (const name of CONTEXT_FILE_NAMES) {
|
|
35
|
-
candidates.push(path.join(dir, name));
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
const seen = new Set();
|
|
36
|
+
async function readContextCandidates(candidates, seen = new Set()) {
|
|
39
37
|
const contextFiles = [];
|
|
40
38
|
for (const candidate of candidates) {
|
|
41
39
|
const absolute = path.resolve(candidate);
|
|
@@ -57,3 +55,89 @@ export async function readContextFiles(cwd = process.cwd()) {
|
|
|
57
55
|
}
|
|
58
56
|
return contextFiles;
|
|
59
57
|
}
|
|
58
|
+
async function scopedDirsForPath(targetPath, cwd) {
|
|
59
|
+
const root = path.resolve(cwd);
|
|
60
|
+
const absolute = path.resolve(root, targetPath);
|
|
61
|
+
const relative = path.relative(root, absolute);
|
|
62
|
+
if (relative.startsWith('..') || path.isAbsolute(relative))
|
|
63
|
+
return [];
|
|
64
|
+
const stat = await fs.stat(absolute).catch(() => null);
|
|
65
|
+
let current = stat?.isDirectory() ? absolute : path.dirname(absolute);
|
|
66
|
+
const dirs = [];
|
|
67
|
+
while (current.startsWith(root + path.sep) && current !== root) {
|
|
68
|
+
dirs.push(current);
|
|
69
|
+
current = path.dirname(current);
|
|
70
|
+
}
|
|
71
|
+
return dirs.reverse();
|
|
72
|
+
}
|
|
73
|
+
export async function readContextFiles(cwd = process.cwd()) {
|
|
74
|
+
const candidates = [
|
|
75
|
+
path.join(os.homedir(), '.claude', 'CLAUDE.md'),
|
|
76
|
+
path.join(HAZE_DIR, 'AGENTS.md'),
|
|
77
|
+
];
|
|
78
|
+
for (const dir of uniqueExistingAncestors(cwd)) {
|
|
79
|
+
for (const name of CONTEXT_FILE_NAMES)
|
|
80
|
+
candidates.push(path.join(dir, name));
|
|
81
|
+
}
|
|
82
|
+
return await readContextCandidates(candidates);
|
|
83
|
+
}
|
|
84
|
+
export async function readScopedContextFilesForPath(targetPath, options = {}) {
|
|
85
|
+
const cwd = options.cwd ?? process.cwd();
|
|
86
|
+
const loaded = new Set(options.alreadyLoadedPaths ?? []);
|
|
87
|
+
const candidates = [];
|
|
88
|
+
for (const dir of await scopedDirsForPath(targetPath, cwd)) {
|
|
89
|
+
for (const name of CONTEXT_FILE_NAMES)
|
|
90
|
+
candidates.push(path.join(dir, name));
|
|
91
|
+
}
|
|
92
|
+
const alreadySeen = new Set();
|
|
93
|
+
for (const loadedPath of loaded) {
|
|
94
|
+
if (loadedPath.startsWith('~/'))
|
|
95
|
+
alreadySeen.add(path.resolve(os.homedir(), loadedPath.slice(2)));
|
|
96
|
+
else
|
|
97
|
+
alreadySeen.add(path.resolve(cwd, loadedPath));
|
|
98
|
+
}
|
|
99
|
+
return await readContextCandidates(candidates, alreadySeen);
|
|
100
|
+
}
|
|
101
|
+
export function contextFileDiagnostics(files) {
|
|
102
|
+
return files.map(file => ({
|
|
103
|
+
path: file.path,
|
|
104
|
+
characters: file.content.length,
|
|
105
|
+
estimatedTokens: Math.ceil(file.content.length / 4),
|
|
106
|
+
contentHash: crypto.createHash('sha256').update(file.content).digest('hex').slice(0, 12),
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
export function summarizeContextDiagnostics(files, options = {}) {
|
|
110
|
+
const perFile = contextFileDiagnostics(files);
|
|
111
|
+
const totalCharacters = perFile.reduce((sum, file) => sum + file.characters, 0);
|
|
112
|
+
const totalTokens = perFile.reduce((sum, file) => sum + file.estimatedTokens, 0);
|
|
113
|
+
const byHash = new Map();
|
|
114
|
+
for (const file of perFile) {
|
|
115
|
+
const existing = byHash.get(file.contentHash);
|
|
116
|
+
if (existing)
|
|
117
|
+
existing.push(file.path);
|
|
118
|
+
else
|
|
119
|
+
byHash.set(file.contentHash, [file.path]);
|
|
120
|
+
}
|
|
121
|
+
const duplicateGroups = [...byHash.entries()]
|
|
122
|
+
.filter(([, paths]) => paths.length >= 2)
|
|
123
|
+
.map(([hash, paths]) => ({ hash, paths }))
|
|
124
|
+
.sort((a, b) => b.paths.length - a.paths.length || a.hash.localeCompare(b.hash));
|
|
125
|
+
const duplicateFileCount = duplicateGroups.reduce((sum, group) => sum + group.paths.length, 0);
|
|
126
|
+
const budgetThreshold = resolveBudgetThreshold(options.budgetThreshold);
|
|
127
|
+
const windowSize = typeof options.windowSize === 'number' && Number.isFinite(options.windowSize) && options.windowSize > 0
|
|
128
|
+
? options.windowSize
|
|
129
|
+
: undefined;
|
|
130
|
+
const budgetShare = windowSize ? totalTokens / windowSize : undefined;
|
|
131
|
+
const exceedsBudget = budgetShare == null ? undefined : budgetShare > budgetThreshold;
|
|
132
|
+
return {
|
|
133
|
+
totalCharacters,
|
|
134
|
+
totalTokens,
|
|
135
|
+
fileCount: perFile.length,
|
|
136
|
+
duplicateGroups,
|
|
137
|
+
duplicateFileCount,
|
|
138
|
+
windowSize,
|
|
139
|
+
budgetShare,
|
|
140
|
+
exceedsBudget,
|
|
141
|
+
budgetThreshold,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import type { HazeSettings, HazeProviderSettings } from './settings.js';
|
|
2
|
-
export declare const DEFAULT_PROVIDER_NAME = "openrouter";
|
|
3
|
-
export declare const DEFAULT_PROVIDER_URL = "https://openrouter.ai/api/v1";
|
|
4
|
-
export declare const DEFAULT_MODEL = "x-ai/grok-build-0.1";
|
|
5
2
|
export type ModelResolution = {
|
|
6
3
|
status: 'found';
|
|
7
4
|
provider: HazeProviderSettings;
|
|
@@ -15,11 +12,11 @@ export type ModelResolution = {
|
|
|
15
12
|
};
|
|
16
13
|
export declare function configuredProviders(settings: HazeSettings): HazeProviderSettings[];
|
|
17
14
|
export declare function findProvider(settings: HazeSettings, name: string): HazeProviderSettings | undefined;
|
|
18
|
-
export declare function activeProvider(settings: HazeSettings): HazeProviderSettings;
|
|
15
|
+
export declare function activeProvider(settings: HazeSettings): HazeProviderSettings | undefined;
|
|
19
16
|
export declare function activeModel(settings: HazeSettings): {
|
|
20
17
|
provider: HazeProviderSettings;
|
|
21
18
|
model: string;
|
|
22
|
-
};
|
|
19
|
+
} | undefined;
|
|
23
20
|
export declare function resolveModelSelector(settings: HazeSettings, selector: string): ModelResolution;
|
|
24
21
|
export declare function modelSelector(provider: HazeProviderSettings, model: string): string;
|
|
25
22
|
export declare function upsertProvider(settings: HazeSettings, provider: HazeProviderSettings): HazeProviderSettings[];
|
package/dist/config/providers.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
// Used only to migrate legacy single-provider OpenRouter settings (apiKey/baseURL)
|
|
2
|
+
// into the providers array. There is no default provider or model anymore: users
|
|
3
|
+
// must configure a provider themselves via /provider.
|
|
4
|
+
const LEGACY_OPENROUTER_URL = 'https://openrouter.ai/api/v1';
|
|
4
5
|
function normalizeModels(models, fallbackModel) {
|
|
5
6
|
const values = Array.isArray(models) ? models : [];
|
|
6
7
|
const normalized = values
|
|
@@ -28,18 +29,17 @@ export function configuredProviders(settings) {
|
|
|
28
29
|
const providers = (settings.providers ?? [])
|
|
29
30
|
.map(provider => normalizeProvider(provider))
|
|
30
31
|
.filter((provider) => Boolean(provider));
|
|
31
|
-
|
|
32
|
-
|
|
32
|
+
// Legacy single-provider settings. Only migrate when the user actually supplied
|
|
33
|
+
// a base URL or API key — never invent a provider or model out of nothing.
|
|
34
|
+
const legacyUrl = settings.baseURL ?? (settings.apiKey ? LEGACY_OPENROUTER_URL : undefined);
|
|
35
|
+
if (legacyUrl && !providers.some(provider => provider.name === 'openrouter')) {
|
|
33
36
|
providers.unshift({
|
|
34
|
-
name:
|
|
37
|
+
name: 'openrouter',
|
|
35
38
|
url: legacyUrl,
|
|
36
39
|
...(settings.apiKey ? { key: settings.apiKey } : {}),
|
|
37
|
-
models: normalizeModels([], settings.model
|
|
40
|
+
models: normalizeModels([], settings.model),
|
|
38
41
|
});
|
|
39
42
|
}
|
|
40
|
-
if (providers.length === 0) {
|
|
41
|
-
return [{ name: DEFAULT_PROVIDER_NAME, url: DEFAULT_PROVIDER_URL, models: [settings.model ?? DEFAULT_MODEL] }];
|
|
42
|
-
}
|
|
43
43
|
return providers;
|
|
44
44
|
}
|
|
45
45
|
export function findProvider(settings, name) {
|
|
@@ -51,9 +51,13 @@ export function activeProvider(settings) {
|
|
|
51
51
|
}
|
|
52
52
|
export function activeModel(settings) {
|
|
53
53
|
const provider = activeProvider(settings);
|
|
54
|
+
if (!provider)
|
|
55
|
+
return undefined;
|
|
54
56
|
const model = settings.model && provider.models.includes(settings.model)
|
|
55
57
|
? settings.model
|
|
56
|
-
: settings.model ?? provider.models[0]
|
|
58
|
+
: settings.model ?? provider.models[0];
|
|
59
|
+
if (!model)
|
|
60
|
+
return undefined;
|
|
57
61
|
return { provider, model };
|
|
58
62
|
}
|
|
59
63
|
export function resolveModelSelector(settings, selector) {
|
|
@@ -84,5 +88,5 @@ export function upsertProvider(settings, provider) {
|
|
|
84
88
|
return [...providers, provider];
|
|
85
89
|
}
|
|
86
90
|
export function providerHasKey(settings, provider) {
|
|
87
|
-
return Boolean(provider.key ?? (provider.name ===
|
|
91
|
+
return Boolean(provider.key ?? (provider.name === 'openrouter' ? settings.apiKey : undefined));
|
|
88
92
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ModelMessage } from 'ai';
|
|
2
|
+
import { type WorkState } from './workState.js';
|
|
2
3
|
export interface CompactionResult {
|
|
3
4
|
compacted: boolean;
|
|
4
5
|
messages: ModelMessage[];
|
|
@@ -9,5 +10,7 @@ export interface CompactionResult {
|
|
|
9
10
|
export declare function modelMessageText(message: ModelMessage): string;
|
|
10
11
|
export declare function compactModelMessages(messages: ModelMessage[], options?: {
|
|
11
12
|
keepRecentMessages?: number;
|
|
13
|
+
tokenBudget?: number;
|
|
12
14
|
instructions?: string;
|
|
15
|
+
workState?: WorkState;
|
|
13
16
|
}): CompactionResult;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { estimateValueTokens } from './contextBudget.js';
|
|
2
|
+
import { workStatePrompt } from './workState.js';
|
|
1
3
|
export function modelMessageText(message) {
|
|
2
4
|
const content = message.content;
|
|
3
5
|
if (typeof content === 'string')
|
|
@@ -7,12 +9,29 @@ export function modelMessageText(message) {
|
|
|
7
9
|
return content.map(part => typeof part === 'object' && part != null && 'text' in part && typeof part.text === 'string' ? part.text : '').filter(Boolean).join('\n');
|
|
8
10
|
}
|
|
9
11
|
export function compactModelMessages(messages, options = {}) {
|
|
10
|
-
const
|
|
12
|
+
const maxRecentMessages = Math.min(options.keepRecentMessages ?? 12, messages.length);
|
|
13
|
+
let keepRecentMessages = maxRecentMessages;
|
|
14
|
+
if (options.tokenBudget != null) {
|
|
15
|
+
let recentTokens = 0;
|
|
16
|
+
keepRecentMessages = 0;
|
|
17
|
+
for (let index = messages.length - 1; index >= 0 && keepRecentMessages < maxRecentMessages; index--) {
|
|
18
|
+
const tokens = estimateValueTokens(messages[index]);
|
|
19
|
+
if (keepRecentMessages > 0 && recentTokens + tokens > options.tokenBudget)
|
|
20
|
+
break;
|
|
21
|
+
recentTokens += tokens;
|
|
22
|
+
keepRecentMessages += 1;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
11
25
|
if (messages.length <= keepRecentMessages) {
|
|
12
26
|
return { compacted: false, messages, olderCount: 0, keptCount: messages.length };
|
|
13
27
|
}
|
|
14
|
-
|
|
15
|
-
|
|
28
|
+
let recentStart = messages.length - keepRecentMessages;
|
|
29
|
+
while (recentStart > 0 && messages[recentStart]?.role === 'tool')
|
|
30
|
+
recentStart -= 1;
|
|
31
|
+
if (recentStart === 0)
|
|
32
|
+
return { compacted: false, messages, olderCount: 0, keptCount: messages.length };
|
|
33
|
+
const older = messages.slice(0, recentStart);
|
|
34
|
+
const recent = messages.slice(recentStart);
|
|
16
35
|
const oldText = older.map(message => {
|
|
17
36
|
const text = modelMessageText(message).replace(/\s+/g, ' ').trim();
|
|
18
37
|
return text ? `- ${message.role}: ${text.slice(0, 500)}` : '';
|
|
@@ -22,6 +41,7 @@ export function compactModelMessages(messages, options = {}) {
|
|
|
22
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.',
|
|
23
42
|
'Do not treat older tool outputs as current unless the recent conversation confirms they still apply.',
|
|
24
43
|
options.instructions ? `User compaction instructions: ${options.instructions}` : undefined,
|
|
44
|
+
options.workState ? workStatePrompt(options.workState) : undefined,
|
|
25
45
|
'',
|
|
26
46
|
'Older context summary:',
|
|
27
47
|
oldText || '- Older messages were tool-only or non-text.',
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ModelMessage } from 'ai';
|
|
2
|
+
import type { ContextFile } from '../../config/contextFiles.js';
|
|
3
|
+
export declare const DEFAULT_CHARS_PER_TOKEN = 4;
|
|
4
|
+
export interface ContextBreakdown {
|
|
5
|
+
logicalInputEstimate: number;
|
|
6
|
+
system: number;
|
|
7
|
+
projectContext: Array<{
|
|
8
|
+
path: string;
|
|
9
|
+
tokens: number;
|
|
10
|
+
}>;
|
|
11
|
+
toolSchemas: Array<{
|
|
12
|
+
name: string;
|
|
13
|
+
tokens: number;
|
|
14
|
+
}>;
|
|
15
|
+
messagesByRole: Record<string, number>;
|
|
16
|
+
toolInputs: Record<string, number>;
|
|
17
|
+
toolResults: Record<string, number>;
|
|
18
|
+
syntheticControl: number;
|
|
19
|
+
}
|
|
20
|
+
export declare function estimateTextTokens(text: string): number;
|
|
21
|
+
export declare function estimateValueTokens(value: unknown): number;
|
|
22
|
+
export declare function estimateToolSchemas(tools?: Record<string, unknown>): {
|
|
23
|
+
name: string;
|
|
24
|
+
tokens: number;
|
|
25
|
+
}[];
|
|
26
|
+
export declare function contextBreakdown(input: {
|
|
27
|
+
system: string;
|
|
28
|
+
contextFiles?: ContextFile[];
|
|
29
|
+
messages: ModelMessage[];
|
|
30
|
+
tools?: Record<string, unknown>;
|
|
31
|
+
}): ContextBreakdown;
|
|
32
|
+
export declare function effectiveNonCachedInput(inputTokens: number | undefined, cacheReadTokens: number): number | undefined;
|
|
33
|
+
export declare function cacheHitRatio(inputTokens: number | undefined, cacheReadTokens: number | undefined): number | undefined;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const DEFAULT_CHARS_PER_TOKEN = 4;
|
|
3
|
+
export function estimateTextTokens(text) {
|
|
4
|
+
return Math.ceil(text.length / DEFAULT_CHARS_PER_TOKEN);
|
|
5
|
+
}
|
|
6
|
+
export function estimateValueTokens(value) {
|
|
7
|
+
if (typeof value === 'string')
|
|
8
|
+
return estimateTextTokens(value);
|
|
9
|
+
try {
|
|
10
|
+
return estimateTextTokens(JSON.stringify(value));
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return estimateTextTokens(String(value));
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function toolSchemaText(toolValue) {
|
|
17
|
+
if (typeof toolValue !== 'object' || toolValue == null)
|
|
18
|
+
return '';
|
|
19
|
+
const value = toolValue;
|
|
20
|
+
let schema = value.inputSchema;
|
|
21
|
+
try {
|
|
22
|
+
schema = z.toJSONSchema(value.inputSchema);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// Provider-neutral fallback for non-Zod schemas.
|
|
26
|
+
}
|
|
27
|
+
return JSON.stringify({
|
|
28
|
+
description: typeof value.description === 'string' ? value.description : undefined,
|
|
29
|
+
inputSchema: schema,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
export function estimateToolSchemas(tools = {}) {
|
|
33
|
+
return Object.entries(tools).map(([name, value]) => ({
|
|
34
|
+
name,
|
|
35
|
+
tokens: estimateTextTokens(toolSchemaText(value)),
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
function contentParts(message) {
|
|
39
|
+
return Array.isArray(message.content) ? message.content : [];
|
|
40
|
+
}
|
|
41
|
+
function partType(part) {
|
|
42
|
+
return typeof part === 'object' && part != null && 'type' in part && typeof part.type === 'string'
|
|
43
|
+
? part.type
|
|
44
|
+
: undefined;
|
|
45
|
+
}
|
|
46
|
+
function toolName(part) {
|
|
47
|
+
if (typeof part !== 'object' || part == null)
|
|
48
|
+
return 'unknown';
|
|
49
|
+
if ('toolName' in part && typeof part.toolName === 'string')
|
|
50
|
+
return part.toolName;
|
|
51
|
+
return 'unknown';
|
|
52
|
+
}
|
|
53
|
+
export function contextBreakdown(input) {
|
|
54
|
+
const projectContext = (input.contextFiles ?? []).map(file => ({ path: file.path, tokens: estimateTextTokens(file.content) }));
|
|
55
|
+
const toolSchemas = estimateToolSchemas(input.tools);
|
|
56
|
+
const messagesByRole = {};
|
|
57
|
+
const toolInputs = {};
|
|
58
|
+
const toolResults = {};
|
|
59
|
+
let syntheticControl = 0;
|
|
60
|
+
for (const message of input.messages) {
|
|
61
|
+
const tokens = estimateValueTokens(message);
|
|
62
|
+
messagesByRole[message.role] = (messagesByRole[message.role] ?? 0) + tokens;
|
|
63
|
+
if (message.role === 'user' && typeof message.content === 'string' && message.content.startsWith('<haze_control>')) {
|
|
64
|
+
syntheticControl += tokens;
|
|
65
|
+
}
|
|
66
|
+
for (const part of contentParts(message)) {
|
|
67
|
+
const type = partType(part);
|
|
68
|
+
const name = toolName(part);
|
|
69
|
+
if (type === 'tool-call')
|
|
70
|
+
toolInputs[name] = (toolInputs[name] ?? 0) + estimateValueTokens(part);
|
|
71
|
+
if (type === 'tool-result')
|
|
72
|
+
toolResults[name] = (toolResults[name] ?? 0) + estimateValueTokens(part);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const system = estimateTextTokens(input.system);
|
|
76
|
+
const logicalInputEstimate = system
|
|
77
|
+
+ Object.values(messagesByRole).reduce((sum, tokens) => sum + tokens, 0)
|
|
78
|
+
+ toolSchemas.reduce((sum, tool) => sum + tool.tokens, 0);
|
|
79
|
+
return { logicalInputEstimate, system, projectContext, toolSchemas, messagesByRole, toolInputs, toolResults, syntheticControl };
|
|
80
|
+
}
|
|
81
|
+
export function effectiveNonCachedInput(inputTokens, cacheReadTokens) {
|
|
82
|
+
return inputTokens == null ? undefined : Math.max(0, inputTokens - cacheReadTokens);
|
|
83
|
+
}
|
|
84
|
+
export function cacheHitRatio(inputTokens, cacheReadTokens) {
|
|
85
|
+
if (!inputTokens || !cacheReadTokens)
|
|
86
|
+
return undefined;
|
|
87
|
+
return cacheReadTokens / inputTokens;
|
|
88
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ModelMessage } from 'ai';
|
|
2
|
+
export declare const SYNTHETIC_CONTROL_OPEN = "<haze_control>";
|
|
3
|
+
export declare function toolRequestSettings<T extends Record<string, unknown>>(tools: T, allowTools: boolean): {
|
|
4
|
+
tools: T;
|
|
5
|
+
toolChoice: "auto";
|
|
6
|
+
} | {
|
|
7
|
+
tools?: undefined;
|
|
8
|
+
toolChoice?: undefined;
|
|
9
|
+
};
|
|
10
|
+
export declare function isSyntheticControlMessage(message: ModelMessage): boolean;
|
|
11
|
+
export declare function stripSyntheticControls(messages: ModelMessage[]): ModelMessage[];
|
|
12
|
+
export declare function withSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
|
|
13
|
+
export declare function compactToolHistory(messages: ModelMessage[], options?: {
|
|
14
|
+
keepRecentResults?: number;
|
|
15
|
+
minResultTokens?: number;
|
|
16
|
+
keepRecentCalls?: number;
|
|
17
|
+
minCallTokens?: number;
|
|
18
|
+
}): {
|
|
19
|
+
messages: ModelMessage[];
|
|
20
|
+
compactedResults: number;
|
|
21
|
+
compactedCalls: number;
|
|
22
|
+
};
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { estimateValueTokens } from './contextBudget.js';
|
|
2
|
+
export const SYNTHETIC_CONTROL_OPEN = '<haze_control>';
|
|
3
|
+
export function toolRequestSettings(tools, allowTools) {
|
|
4
|
+
return allowTools ? { tools, toolChoice: 'auto' } : {};
|
|
5
|
+
}
|
|
6
|
+
export function isSyntheticControlMessage(message) {
|
|
7
|
+
return message.role === 'user'
|
|
8
|
+
&& typeof message.content === 'string'
|
|
9
|
+
&& message.content.startsWith(SYNTHETIC_CONTROL_OPEN);
|
|
10
|
+
}
|
|
11
|
+
export function stripSyntheticControls(messages) {
|
|
12
|
+
return messages.filter(message => !isSyntheticControlMessage(message));
|
|
13
|
+
}
|
|
14
|
+
export function withSyntheticControl(messages, control) {
|
|
15
|
+
return [
|
|
16
|
+
...stripSyntheticControls(messages),
|
|
17
|
+
{ role: 'user', content: `${SYNTHETIC_CONTROL_OPEN}\n${control}\n</haze_control>` },
|
|
18
|
+
];
|
|
19
|
+
}
|
|
20
|
+
function resultValue(output) {
|
|
21
|
+
return typeof output === 'object' && output != null && 'value' in output
|
|
22
|
+
? output.value
|
|
23
|
+
: undefined;
|
|
24
|
+
}
|
|
25
|
+
function isFailedResult(output) {
|
|
26
|
+
if (typeof output !== 'object' || output == null || !('type' in output))
|
|
27
|
+
return true;
|
|
28
|
+
const type = output.type;
|
|
29
|
+
if (type === 'error-text' || type === 'error-json' || type === 'execution-denied')
|
|
30
|
+
return true;
|
|
31
|
+
const value = resultValue(output);
|
|
32
|
+
return typeof value === 'object' && value != null && 'ok' in value && value.ok === false;
|
|
33
|
+
}
|
|
34
|
+
function compactJsonValue(value, toolName) {
|
|
35
|
+
if (typeof value !== 'object' || value == null || Array.isArray(value)) {
|
|
36
|
+
return { compacted: true, toolName, summary: 'Older successful tool result omitted.' };
|
|
37
|
+
}
|
|
38
|
+
const source = value;
|
|
39
|
+
const keys = [
|
|
40
|
+
'ok', 'path', 'command', 'code', 'signal', 'timedOut', 'durationMs', 'reasonCode',
|
|
41
|
+
'bytes', 'created', 'replacements', 'totalMatches', 'returnedMatches',
|
|
42
|
+
'omittedMatches', 'truncated', 'nextOffset', 'totalLines', 'startLine', 'endLine',
|
|
43
|
+
'validationSummary', 'classification', 'summary', 'counts', 'filterName', 'reducerName',
|
|
44
|
+
'contentKind', 'lossy', 'rawHandle', 'handle', 'rawChars', 'returnedChars',
|
|
45
|
+
'rawTokensEstimate', 'returnedTokensEstimate', 'estimatedSavedTokens', 'savingsPct',
|
|
46
|
+
];
|
|
47
|
+
const compacted = { compacted: true, toolName };
|
|
48
|
+
for (const key of keys)
|
|
49
|
+
if (key in source)
|
|
50
|
+
compacted[key] = source[key];
|
|
51
|
+
for (const stream of ['stdout', 'stderr']) {
|
|
52
|
+
const candidate = source[stream];
|
|
53
|
+
if (typeof candidate !== 'object' || candidate == null)
|
|
54
|
+
continue;
|
|
55
|
+
const details = candidate;
|
|
56
|
+
compacted[stream] = {
|
|
57
|
+
...(typeof details.handle === 'string' ? { handle: details.handle } : {}),
|
|
58
|
+
...(typeof details.rawHandle === 'string' ? { rawHandle: details.rawHandle } : {}),
|
|
59
|
+
...(typeof details.filterName === 'string' ? { filterName: details.filterName } : {}),
|
|
60
|
+
...(typeof details.reducerName === 'string' ? { reducerName: details.reducerName } : {}),
|
|
61
|
+
...(typeof details.contentKind === 'string' ? { contentKind: details.contentKind } : {}),
|
|
62
|
+
...(typeof details.lossy === 'boolean' ? { lossy: details.lossy } : {}),
|
|
63
|
+
...(typeof details.truncated === 'boolean' ? { truncated: details.truncated } : {}),
|
|
64
|
+
...(typeof details.omittedChars === 'number' ? { omittedChars: details.omittedChars } : {}),
|
|
65
|
+
...(typeof details.rawTokensEstimate === 'number' ? { rawTokensEstimate: details.rawTokensEstimate } : {}),
|
|
66
|
+
...(typeof details.returnedTokensEstimate === 'number' ? { returnedTokensEstimate: details.returnedTokensEstimate } : {}),
|
|
67
|
+
...(typeof details.estimatedSavedTokens === 'number' ? { estimatedSavedTokens: details.estimatedSavedTokens } : {}),
|
|
68
|
+
...(typeof details.savingsPct === 'number' ? { savingsPct: details.savingsPct } : {}),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return compacted;
|
|
72
|
+
}
|
|
73
|
+
function compactResultOutput(output, toolName) {
|
|
74
|
+
if (typeof output !== 'object' || output == null || !('type' in output))
|
|
75
|
+
return output;
|
|
76
|
+
const typed = output;
|
|
77
|
+
if (typed.type === 'json')
|
|
78
|
+
return { ...typed, value: compactJsonValue(typed.value, toolName) };
|
|
79
|
+
if (typed.type === 'text')
|
|
80
|
+
return { ...typed, value: `[Older successful ${toolName} result omitted from active context.]` };
|
|
81
|
+
return output;
|
|
82
|
+
}
|
|
83
|
+
const COMPACTABLE_INPUT_TOOLS = new Set(['writeFile', 'bash']);
|
|
84
|
+
const BASH_COMMAND_TRUNCATE_THRESHOLD = 200;
|
|
85
|
+
const BASH_COMMAND_KEEP_CHARS = 150;
|
|
86
|
+
function compactToolCallInput(input, toolName) {
|
|
87
|
+
if (typeof input !== 'object' || input == null)
|
|
88
|
+
return input;
|
|
89
|
+
const source = input;
|
|
90
|
+
if (toolName === 'writeFile' && typeof source.content === 'string') {
|
|
91
|
+
const bytes = source.content.length;
|
|
92
|
+
const path = typeof source.path === 'string' ? source.path : '<unknown>';
|
|
93
|
+
return {
|
|
94
|
+
...source,
|
|
95
|
+
content: `[Compacted: original ${bytes} bytes. Use readFile on "${path}" to inspect.]`,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
if (toolName === 'bash' && typeof source.command === 'string' && source.command.length > BASH_COMMAND_TRUNCATE_THRESHOLD) {
|
|
99
|
+
const total = source.command.length;
|
|
100
|
+
const truncated = source.command.slice(0, BASH_COMMAND_KEEP_CHARS).replace(/\s+/g, ' ').trim();
|
|
101
|
+
return {
|
|
102
|
+
...source,
|
|
103
|
+
command: `${truncated} [+${total - BASH_COMMAND_KEEP_CHARS} more chars compacted]`,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return input;
|
|
107
|
+
}
|
|
108
|
+
export function compactToolHistory(messages, options = {}) {
|
|
109
|
+
const keepRecentResults = options.keepRecentResults ?? 3;
|
|
110
|
+
const minResultTokens = options.minResultTokens ?? 300;
|
|
111
|
+
const keepRecentCalls = options.keepRecentCalls ?? 3;
|
|
112
|
+
const minCallTokens = options.minCallTokens ?? 400;
|
|
113
|
+
const resultIds = [];
|
|
114
|
+
const compactableCallIds = [];
|
|
115
|
+
for (const message of messages) {
|
|
116
|
+
if (!Array.isArray(message.content))
|
|
117
|
+
continue;
|
|
118
|
+
for (const part of message.content) {
|
|
119
|
+
if (typeof part !== 'object' || part == null)
|
|
120
|
+
continue;
|
|
121
|
+
if (part.type === 'tool-result' && typeof part.toolCallId === 'string')
|
|
122
|
+
resultIds.push(part.toolCallId);
|
|
123
|
+
else if (part.type === 'tool-call' && typeof part.toolCallId === 'string' && COMPACTABLE_INPUT_TOOLS.has(part.toolName))
|
|
124
|
+
compactableCallIds.push(part.toolCallId);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const recent = new Set(keepRecentResults > 0 ? resultIds.slice(-keepRecentResults) : []);
|
|
128
|
+
const recentCallIds = new Set(keepRecentCalls > 0 ? compactableCallIds.slice(-keepRecentCalls) : []);
|
|
129
|
+
let compactedResults = 0;
|
|
130
|
+
let compactedCalls = 0;
|
|
131
|
+
const next = messages.map(message => {
|
|
132
|
+
if (!Array.isArray(message.content))
|
|
133
|
+
return message;
|
|
134
|
+
let changed = false;
|
|
135
|
+
const content = message.content.map(part => {
|
|
136
|
+
if (typeof part !== 'object' || part == null)
|
|
137
|
+
return part;
|
|
138
|
+
if (part.type === 'tool-result') {
|
|
139
|
+
if (recent.has(part.toolCallId) || isFailedResult(part.output) || estimateValueTokens(part) < minResultTokens)
|
|
140
|
+
return part;
|
|
141
|
+
changed = true;
|
|
142
|
+
compactedResults += 1;
|
|
143
|
+
return { ...part, output: compactResultOutput(part.output, part.toolName) };
|
|
144
|
+
}
|
|
145
|
+
if (part.type === 'tool-call' && COMPACTABLE_INPUT_TOOLS.has(part.toolName)) {
|
|
146
|
+
if (recentCallIds.has(part.toolCallId) || estimateValueTokens(part) < minCallTokens)
|
|
147
|
+
return part;
|
|
148
|
+
changed = true;
|
|
149
|
+
compactedCalls += 1;
|
|
150
|
+
return { ...part, input: compactToolCallInput(part.input, part.toolName) };
|
|
151
|
+
}
|
|
152
|
+
return part;
|
|
153
|
+
});
|
|
154
|
+
return changed ? { ...message, content } : message;
|
|
155
|
+
});
|
|
156
|
+
return { messages: next, compactedResults, compactedCalls };
|
|
157
|
+
}
|