@denizokcu/haze 0.2.0 → 0.4.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 +41 -0
- package/README.md +38 -22
- package/dist/cli/commands/chat.d.ts +1 -1
- package/dist/cli/commands/chat.js +411 -74
- package/dist/cli/commands/commands.js +122 -54
- package/dist/cli/commands/formatters.d.ts +2 -0
- package/dist/cli/commands/formatters.js +34 -0
- package/dist/cli/commands/streaming.d.ts +36 -1
- package/dist/cli/commands/streaming.js +312 -103
- package/dist/cli/contextReport.d.ts +1 -0
- package/dist/cli/contextReport.js +47 -0
- package/dist/config/contextFiles.d.ts +25 -0
- package/dist/config/contextFiles.js +53 -0
- package/dist/config/providerPresets.d.ts +23 -0
- package/dist/config/providerPresets.js +230 -0
- 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 +146 -0
- package/dist/core/agent/toolOutputStore.d.ts +11 -0
- package/dist/core/agent/toolOutputStore.js +33 -0
- package/dist/core/agent/workState.d.ts +38 -0
- package/dist/core/agent/workState.js +89 -0
- package/dist/core/goal/completionPolicy.js +1 -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/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/tasks/taskStorage.d.ts +13 -0
- package/dist/core/tasks/taskStorage.js +29 -0
- package/dist/core/validation/outputParser.js +15 -2
- package/dist/llm/client.d.ts +39 -0
- package/dist/llm/client.js +46 -2
- package/dist/llm/hazeTools.d.ts +53 -12
- package/dist/llm/hazeTools.js +170 -46
- package/dist/llm/systemPrompt.d.ts +6 -1
- package/dist/llm/systemPrompt.js +42 -79
- 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/TextInput.d.ts +2 -1
- package/dist/ui/components/TextInput.js +6 -2
- package/package.json +2 -1
|
@@ -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,29 @@ 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
|
+
}
|
|
5
25
|
export declare function readContextFiles(cwd?: string): Promise<ContextFile[]>;
|
|
26
|
+
export declare function contextFileDiagnostics(files: ContextFile[]): ContextFileDiagnostic[];
|
|
27
|
+
export declare function summarizeContextDiagnostics(files: ContextFile[], options?: {
|
|
28
|
+
windowSize?: number;
|
|
29
|
+
budgetThreshold?: number;
|
|
30
|
+
}): ContextFileDiagnosticsSummary;
|
|
@@ -1,7 +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';
|
|
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
|
+
const envValue = Number.parseFloat(process.env.HAZE_CONTEXT_BUDGET_SHARE ?? '');
|
|
11
|
+
if (Number.isFinite(envValue))
|
|
12
|
+
return Math.min(1, Math.max(0, envValue));
|
|
13
|
+
return DEFAULT_BUDGET_THRESHOLD;
|
|
14
|
+
}
|
|
5
15
|
const CONTEXT_FILE_NAMES = ['AGENTS.md', 'CLAUDE.md'];
|
|
6
16
|
const MAX_CONTEXT_FILE_CHARS = 20_000;
|
|
7
17
|
function uniqueExistingAncestors(fromDir) {
|
|
@@ -57,3 +67,46 @@ export async function readContextFiles(cwd = process.cwd()) {
|
|
|
57
67
|
}
|
|
58
68
|
return contextFiles;
|
|
59
69
|
}
|
|
70
|
+
export function contextFileDiagnostics(files) {
|
|
71
|
+
return files.map(file => ({
|
|
72
|
+
path: file.path,
|
|
73
|
+
characters: file.content.length,
|
|
74
|
+
estimatedTokens: Math.ceil(file.content.length / 4),
|
|
75
|
+
contentHash: crypto.createHash('sha256').update(file.content).digest('hex').slice(0, 12),
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
export function summarizeContextDiagnostics(files, options = {}) {
|
|
79
|
+
const perFile = contextFileDiagnostics(files);
|
|
80
|
+
const totalCharacters = perFile.reduce((sum, file) => sum + file.characters, 0);
|
|
81
|
+
const totalTokens = perFile.reduce((sum, file) => sum + file.estimatedTokens, 0);
|
|
82
|
+
const byHash = new Map();
|
|
83
|
+
for (const file of perFile) {
|
|
84
|
+
const existing = byHash.get(file.contentHash);
|
|
85
|
+
if (existing)
|
|
86
|
+
existing.push(file.path);
|
|
87
|
+
else
|
|
88
|
+
byHash.set(file.contentHash, [file.path]);
|
|
89
|
+
}
|
|
90
|
+
const duplicateGroups = [...byHash.entries()]
|
|
91
|
+
.filter(([, paths]) => paths.length >= 2)
|
|
92
|
+
.map(([hash, paths]) => ({ hash, paths }))
|
|
93
|
+
.sort((a, b) => b.paths.length - a.paths.length || a.hash.localeCompare(b.hash));
|
|
94
|
+
const duplicateFileCount = duplicateGroups.reduce((sum, group) => sum + group.paths.length, 0);
|
|
95
|
+
const budgetThreshold = resolveBudgetThreshold(options.budgetThreshold);
|
|
96
|
+
const windowSize = typeof options.windowSize === 'number' && Number.isFinite(options.windowSize) && options.windowSize > 0
|
|
97
|
+
? options.windowSize
|
|
98
|
+
: undefined;
|
|
99
|
+
const budgetShare = windowSize ? totalTokens / windowSize : undefined;
|
|
100
|
+
const exceedsBudget = budgetShare == null ? undefined : budgetShare > budgetThreshold;
|
|
101
|
+
return {
|
|
102
|
+
totalCharacters,
|
|
103
|
+
totalTokens,
|
|
104
|
+
fileCount: perFile.length,
|
|
105
|
+
duplicateGroups,
|
|
106
|
+
duplicateFileCount,
|
|
107
|
+
windowSize,
|
|
108
|
+
budgetShare,
|
|
109
|
+
exceedsBudget,
|
|
110
|
+
budgetThreshold,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Known provider presets derived from community conventions (nanocoder, OpenRouter docs, etc.).
|
|
3
|
+
* Each preset carries a pre-configured base URL so users only need to supply an API key and model names.
|
|
4
|
+
* Local/keyless providers have sensible localhost defaults.
|
|
5
|
+
*/
|
|
6
|
+
export interface ProviderPreset {
|
|
7
|
+
/** Unique identifier used as the selection value. */
|
|
8
|
+
id: string;
|
|
9
|
+
/** Human-readable name shown in the picker. */
|
|
10
|
+
name: string;
|
|
11
|
+
/** Pre-configured OpenAI-compatible base URL. */
|
|
12
|
+
baseUrl: string;
|
|
13
|
+
/** Whether an API key is typically required. Local providers default to false. */
|
|
14
|
+
needsApiKey: boolean;
|
|
15
|
+
/** Hint shown when prompting for the API key. */
|
|
16
|
+
apiKeyHint?: string;
|
|
17
|
+
/** Optional suggested default model(s). */
|
|
18
|
+
suggestedModels?: string[];
|
|
19
|
+
/** Category for grouping in the picker. */
|
|
20
|
+
category: 'cloud' | 'local';
|
|
21
|
+
}
|
|
22
|
+
export declare const PROVIDER_PRESETS: ProviderPreset[];
|
|
23
|
+
export declare function findPreset(id: string): ProviderPreset | undefined;
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Known provider presets derived from community conventions (nanocoder, OpenRouter docs, etc.).
|
|
3
|
+
* Each preset carries a pre-configured base URL so users only need to supply an API key and model names.
|
|
4
|
+
* Local/keyless providers have sensible localhost defaults.
|
|
5
|
+
*/
|
|
6
|
+
export const PROVIDER_PRESETS = [
|
|
7
|
+
// ── Cloud providers (API key required) ──────────────────────────────
|
|
8
|
+
{
|
|
9
|
+
id: 'openrouter',
|
|
10
|
+
name: 'OpenRouter',
|
|
11
|
+
baseUrl: 'https://openrouter.ai/api/v1',
|
|
12
|
+
needsApiKey: true,
|
|
13
|
+
suggestedModels: [
|
|
14
|
+
// SOTA
|
|
15
|
+
'anthropic/claude-opus-4.8',
|
|
16
|
+
'openai/gpt-5.4',
|
|
17
|
+
'google/gemini-3.1-pro',
|
|
18
|
+
// Fast
|
|
19
|
+
'anthropic/claude-sonnet-4.6',
|
|
20
|
+
'openai/gpt-5.4-mini',
|
|
21
|
+
'google/gemini-3.5-flash',
|
|
22
|
+
'deepseek/deepseek-v4-flash',
|
|
23
|
+
],
|
|
24
|
+
category: 'cloud',
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
id: 'openai',
|
|
28
|
+
name: 'OpenAI',
|
|
29
|
+
baseUrl: 'https://api.openai.com/v1',
|
|
30
|
+
needsApiKey: true,
|
|
31
|
+
suggestedModels: [
|
|
32
|
+
// SOTA
|
|
33
|
+
'gpt-5.5',
|
|
34
|
+
'o3',
|
|
35
|
+
// Fast
|
|
36
|
+
'gpt-5.4',
|
|
37
|
+
'gpt-5.4-mini',
|
|
38
|
+
'o4-mini',
|
|
39
|
+
],
|
|
40
|
+
category: 'cloud',
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: 'anthropic',
|
|
44
|
+
name: 'Anthropic Claude',
|
|
45
|
+
baseUrl: 'https://api.anthropic.com/v1',
|
|
46
|
+
needsApiKey: true,
|
|
47
|
+
suggestedModels: [
|
|
48
|
+
// SOTA
|
|
49
|
+
'claude-opus-4-8',
|
|
50
|
+
'claude-fable-5',
|
|
51
|
+
// Fast
|
|
52
|
+
'claude-sonnet-4-6',
|
|
53
|
+
'claude-haiku-4-5',
|
|
54
|
+
],
|
|
55
|
+
category: 'cloud',
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
id: 'google-gemini',
|
|
59
|
+
name: 'Google Gemini',
|
|
60
|
+
baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
|
|
61
|
+
needsApiKey: true,
|
|
62
|
+
apiKeyHint: 'API Key (from https://aistudio.google.com/apikey)',
|
|
63
|
+
suggestedModels: [
|
|
64
|
+
// SOTA
|
|
65
|
+
'gemini-3.5-flash',
|
|
66
|
+
'gemini-3.1-pro',
|
|
67
|
+
// Fast
|
|
68
|
+
'gemini-3.1-flash-lite',
|
|
69
|
+
'gemini-2.5-flash',
|
|
70
|
+
'gemini-2.5-pro',
|
|
71
|
+
],
|
|
72
|
+
category: 'cloud',
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
id: 'mistral',
|
|
76
|
+
name: 'Mistral AI',
|
|
77
|
+
baseUrl: 'https://api.mistral.ai/v1',
|
|
78
|
+
needsApiKey: true,
|
|
79
|
+
suggestedModels: [
|
|
80
|
+
// SOTA
|
|
81
|
+
'mistral-large-2512',
|
|
82
|
+
'mistral-medium-3-5',
|
|
83
|
+
// Fast
|
|
84
|
+
'mistral-small-2603',
|
|
85
|
+
'codestral-2508',
|
|
86
|
+
],
|
|
87
|
+
category: 'cloud',
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
id: 'z-ai',
|
|
91
|
+
name: 'Z.ai',
|
|
92
|
+
baseUrl: 'https://api.z.ai/api/paas/v4/',
|
|
93
|
+
needsApiKey: true,
|
|
94
|
+
suggestedModels: [
|
|
95
|
+
'glm-5.1',
|
|
96
|
+
'glm-5.1-fw',
|
|
97
|
+
],
|
|
98
|
+
category: 'cloud',
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: 'z-ai-coding',
|
|
102
|
+
name: 'Z.ai Coding Subscription',
|
|
103
|
+
baseUrl: 'https://api.z.ai/api/coding/paas/v4/',
|
|
104
|
+
needsApiKey: true,
|
|
105
|
+
suggestedModels: [
|
|
106
|
+
'glm-5.1',
|
|
107
|
+
'glm-5.1-fw',
|
|
108
|
+
],
|
|
109
|
+
category: 'cloud',
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
id: 'github-models',
|
|
113
|
+
name: 'GitHub Models',
|
|
114
|
+
baseUrl: 'https://models.github.ai/inference',
|
|
115
|
+
needsApiKey: true,
|
|
116
|
+
apiKeyHint: 'GitHub Token (PAT with models:read scope)',
|
|
117
|
+
suggestedModels: [
|
|
118
|
+
'gpt-5.4',
|
|
119
|
+
'gpt-5.4-mini',
|
|
120
|
+
'claude-sonnet-4-6',
|
|
121
|
+
'gemini-3.1-pro',
|
|
122
|
+
],
|
|
123
|
+
category: 'cloud',
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
id: 'github-copilot',
|
|
127
|
+
name: 'GitHub Copilot',
|
|
128
|
+
baseUrl: 'https://api.githubcopilot.com',
|
|
129
|
+
needsApiKey: true,
|
|
130
|
+
apiKeyHint: 'GitHub Copilot token (OAuth)',
|
|
131
|
+
suggestedModels: [
|
|
132
|
+
'gpt-5.4',
|
|
133
|
+
'claude-fable-5',
|
|
134
|
+
'claude-sonnet-4-6',
|
|
135
|
+
'gemini-3.1-pro',
|
|
136
|
+
],
|
|
137
|
+
category: 'cloud',
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
id: 'chatgpt-codex',
|
|
141
|
+
name: 'ChatGPT / Codex',
|
|
142
|
+
baseUrl: 'https://chatgpt.com/backend-api/codex',
|
|
143
|
+
needsApiKey: true,
|
|
144
|
+
apiKeyHint: 'ChatGPT session token (OAuth)',
|
|
145
|
+
suggestedModels: [
|
|
146
|
+
'gpt-5.4',
|
|
147
|
+
'o4-mini',
|
|
148
|
+
],
|
|
149
|
+
category: 'cloud',
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
id: 'kimi-code',
|
|
153
|
+
name: 'Kimi Code',
|
|
154
|
+
baseUrl: 'https://api.kimi.com/coding/v1',
|
|
155
|
+
needsApiKey: true,
|
|
156
|
+
suggestedModels: [
|
|
157
|
+
'kimi-for-coding',
|
|
158
|
+
],
|
|
159
|
+
category: 'cloud',
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
id: 'minimax-coding',
|
|
163
|
+
name: 'MiniMax Coding Plan',
|
|
164
|
+
baseUrl: 'https://api.minimax.io/anthropic/v1',
|
|
165
|
+
needsApiKey: true,
|
|
166
|
+
suggestedModels: [
|
|
167
|
+
// SOTA
|
|
168
|
+
'MiniMax-M3',
|
|
169
|
+
// Fast
|
|
170
|
+
'MiniMax-M2.7',
|
|
171
|
+
],
|
|
172
|
+
category: 'cloud',
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
id: 'poe',
|
|
176
|
+
name: 'Poe',
|
|
177
|
+
baseUrl: 'https://api.poe.com/v1',
|
|
178
|
+
needsApiKey: true,
|
|
179
|
+
apiKeyHint: 'API Key (from poe.com/api_key)',
|
|
180
|
+
suggestedModels: [
|
|
181
|
+
// SOTA
|
|
182
|
+
'claude-opus-4.8',
|
|
183
|
+
'gpt-5.5',
|
|
184
|
+
'gemini-3.5-flash',
|
|
185
|
+
// Fast
|
|
186
|
+
'gpt-5.4-mini',
|
|
187
|
+
'claude-sonnet-4.6',
|
|
188
|
+
'kimi-k2.5',
|
|
189
|
+
],
|
|
190
|
+
category: 'cloud',
|
|
191
|
+
},
|
|
192
|
+
// ── Local providers (no API key) ────────────────────────────────────
|
|
193
|
+
{
|
|
194
|
+
id: 'ollama',
|
|
195
|
+
name: 'Ollama',
|
|
196
|
+
baseUrl: 'http://localhost:11434/v1',
|
|
197
|
+
needsApiKey: false,
|
|
198
|
+
suggestedModels: [
|
|
199
|
+
'qwen3-coder',
|
|
200
|
+
'devstral-small-2512',
|
|
201
|
+
'gemma4:26b',
|
|
202
|
+
'llama4:scout',
|
|
203
|
+
],
|
|
204
|
+
category: 'local',
|
|
205
|
+
},
|
|
206
|
+
{
|
|
207
|
+
id: 'llamacpp',
|
|
208
|
+
name: 'llama.cpp server',
|
|
209
|
+
baseUrl: 'http://localhost:8080/v1',
|
|
210
|
+
needsApiKey: false,
|
|
211
|
+
category: 'local',
|
|
212
|
+
},
|
|
213
|
+
{
|
|
214
|
+
id: 'mlx-server',
|
|
215
|
+
name: 'MLX Server',
|
|
216
|
+
baseUrl: 'http://localhost:8080/v1',
|
|
217
|
+
needsApiKey: false,
|
|
218
|
+
category: 'local',
|
|
219
|
+
},
|
|
220
|
+
{
|
|
221
|
+
id: 'lmstudio',
|
|
222
|
+
name: 'LM Studio',
|
|
223
|
+
baseUrl: 'http://localhost:1234/v1',
|
|
224
|
+
needsApiKey: false,
|
|
225
|
+
category: 'local',
|
|
226
|
+
},
|
|
227
|
+
];
|
|
228
|
+
export function findPreset(id) {
|
|
229
|
+
return PROVIDER_PRESETS.find(preset => preset.id === id);
|
|
230
|
+
}
|
|
@@ -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
|
+
};
|