@denizokcu/haze 0.3.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +31 -19
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +144 -52
  5. package/dist/cli/commands/commands.js +105 -114
  6. package/dist/cli/commands/streaming.d.ts +33 -5
  7. package/dist/cli/commands/streaming.js +235 -103
  8. package/dist/cli/contextReport.d.ts +1 -0
  9. package/dist/cli/contextReport.js +47 -0
  10. package/dist/config/contextFiles.d.ts +25 -0
  11. package/dist/config/contextFiles.js +53 -0
  12. package/dist/core/agent/compaction.d.ts +3 -0
  13. package/dist/core/agent/compaction.js +23 -3
  14. package/dist/core/agent/contextBudget.d.ts +33 -0
  15. package/dist/core/agent/contextBudget.js +88 -0
  16. package/dist/core/agent/requestAssembly.d.ts +22 -0
  17. package/dist/core/agent/requestAssembly.js +146 -0
  18. package/dist/core/agent/toolOutputStore.d.ts +11 -0
  19. package/dist/core/agent/toolOutputStore.js +33 -0
  20. package/dist/core/agent/workState.d.ts +38 -0
  21. package/dist/core/agent/workState.js +89 -0
  22. package/dist/core/goal/completionPolicy.js +1 -1
  23. package/dist/core/goal/sessionGoal.d.ts +2 -0
  24. package/dist/core/goal/sessionGoal.js +8 -1
  25. package/dist/core/log/llmLog.d.ts +68 -0
  26. package/dist/core/log/llmLog.js +55 -0
  27. package/dist/core/session/sessionStore.d.ts +6 -0
  28. package/dist/core/session/sessionStore.js +5 -0
  29. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  30. package/dist/core/subagent/subagentRunner.js +5 -15
  31. package/dist/core/validation/outputParser.js +15 -2
  32. package/dist/llm/client.d.ts +39 -0
  33. package/dist/llm/client.js +46 -2
  34. package/dist/llm/hazeTools.d.ts +37 -12
  35. package/dist/llm/hazeTools.js +133 -55
  36. package/dist/llm/systemPrompt.d.ts +6 -1
  37. package/dist/llm/systemPrompt.js +42 -81
  38. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  39. package/dist/skills/builder/SkillBuilder.js +68 -65
  40. package/dist/skills/skillTools.d.ts +2 -19
  41. package/dist/skills/skillTools.js +28 -19
  42. package/package.json +2 -1
@@ -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
+ }
@@ -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 keepRecentMessages = options.keepRecentMessages ?? 12;
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
- const older = messages.slice(0, -keepRecentMessages);
15
- const recent = messages.slice(-keepRecentMessages);
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,146 @@
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',
44
+ ];
45
+ const compacted = { compacted: true, toolName };
46
+ for (const key of keys)
47
+ if (key in source)
48
+ compacted[key] = source[key];
49
+ for (const stream of ['stdout', 'stderr']) {
50
+ const candidate = source[stream];
51
+ if (typeof candidate !== 'object' || candidate == null)
52
+ continue;
53
+ const details = candidate;
54
+ compacted[stream] = {
55
+ ...(typeof details.handle === 'string' ? { handle: details.handle } : {}),
56
+ ...(typeof details.truncated === 'boolean' ? { truncated: details.truncated } : {}),
57
+ ...(typeof details.omittedChars === 'number' ? { omittedChars: details.omittedChars } : {}),
58
+ };
59
+ }
60
+ return compacted;
61
+ }
62
+ function compactResultOutput(output, toolName) {
63
+ if (typeof output !== 'object' || output == null || !('type' in output))
64
+ return output;
65
+ const typed = output;
66
+ if (typed.type === 'json')
67
+ return { ...typed, value: compactJsonValue(typed.value, toolName) };
68
+ if (typed.type === 'text')
69
+ return { ...typed, value: `[Older successful ${toolName} result omitted from active context.]` };
70
+ return output;
71
+ }
72
+ const COMPACTABLE_INPUT_TOOLS = new Set(['writeFile', 'bash']);
73
+ const BASH_COMMAND_TRUNCATE_THRESHOLD = 200;
74
+ const BASH_COMMAND_KEEP_CHARS = 150;
75
+ function compactToolCallInput(input, toolName) {
76
+ if (typeof input !== 'object' || input == null)
77
+ return input;
78
+ const source = input;
79
+ if (toolName === 'writeFile' && typeof source.content === 'string') {
80
+ const bytes = source.content.length;
81
+ const path = typeof source.path === 'string' ? source.path : '<unknown>';
82
+ return {
83
+ ...source,
84
+ content: `[Compacted: original ${bytes} bytes. Use readFile on "${path}" to inspect.]`,
85
+ };
86
+ }
87
+ if (toolName === 'bash' && typeof source.command === 'string' && source.command.length > BASH_COMMAND_TRUNCATE_THRESHOLD) {
88
+ const total = source.command.length;
89
+ const truncated = source.command.slice(0, BASH_COMMAND_KEEP_CHARS).replace(/\s+/g, ' ').trim();
90
+ return {
91
+ ...source,
92
+ command: `${truncated} [+${total - BASH_COMMAND_KEEP_CHARS} more chars compacted]`,
93
+ };
94
+ }
95
+ return input;
96
+ }
97
+ export function compactToolHistory(messages, options = {}) {
98
+ const keepRecentResults = options.keepRecentResults ?? 3;
99
+ const minResultTokens = options.minResultTokens ?? 300;
100
+ const keepRecentCalls = options.keepRecentCalls ?? 3;
101
+ const minCallTokens = options.minCallTokens ?? 400;
102
+ const resultIds = [];
103
+ const compactableCallIds = [];
104
+ for (const message of messages) {
105
+ if (!Array.isArray(message.content))
106
+ continue;
107
+ for (const part of message.content) {
108
+ if (typeof part !== 'object' || part == null)
109
+ continue;
110
+ if (part.type === 'tool-result' && typeof part.toolCallId === 'string')
111
+ resultIds.push(part.toolCallId);
112
+ else if (part.type === 'tool-call' && typeof part.toolCallId === 'string' && COMPACTABLE_INPUT_TOOLS.has(part.toolName))
113
+ compactableCallIds.push(part.toolCallId);
114
+ }
115
+ }
116
+ const recent = new Set(keepRecentResults > 0 ? resultIds.slice(-keepRecentResults) : []);
117
+ const recentCallIds = new Set(keepRecentCalls > 0 ? compactableCallIds.slice(-keepRecentCalls) : []);
118
+ let compactedResults = 0;
119
+ let compactedCalls = 0;
120
+ const next = messages.map(message => {
121
+ if (!Array.isArray(message.content))
122
+ return message;
123
+ let changed = false;
124
+ const content = message.content.map(part => {
125
+ if (typeof part !== 'object' || part == null)
126
+ return part;
127
+ if (part.type === 'tool-result') {
128
+ if (recent.has(part.toolCallId) || isFailedResult(part.output) || estimateValueTokens(part) < minResultTokens)
129
+ return part;
130
+ changed = true;
131
+ compactedResults += 1;
132
+ return { ...part, output: compactResultOutput(part.output, part.toolName) };
133
+ }
134
+ if (part.type === 'tool-call' && COMPACTABLE_INPUT_TOOLS.has(part.toolName)) {
135
+ if (recentCallIds.has(part.toolCallId) || estimateValueTokens(part) < minCallTokens)
136
+ return part;
137
+ changed = true;
138
+ compactedCalls += 1;
139
+ return { ...part, input: compactToolCallInput(part.input, part.toolName) };
140
+ }
141
+ return part;
142
+ });
143
+ return changed ? { ...message, content } : message;
144
+ });
145
+ return { messages: next, compactedResults, compactedCalls };
146
+ }
@@ -0,0 +1,11 @@
1
+ export interface StoredToolOutputPage {
2
+ handle: string;
3
+ offset: number;
4
+ nextOffset?: number;
5
+ totalChars: number;
6
+ content: string;
7
+ truncated: boolean;
8
+ }
9
+ export declare function storeToolOutput(content: string): string;
10
+ export declare function readToolOutput(handle: string, offset?: number, limit?: number): StoredToolOutputPage | undefined;
11
+ export declare function clearToolOutputs(): void;
@@ -0,0 +1,33 @@
1
+ import crypto from 'node:crypto';
2
+ const outputs = new Map();
3
+ const MAX_STORED_OUTPUTS = 100;
4
+ export function storeToolOutput(content) {
5
+ const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
6
+ outputs.set(handle, content);
7
+ while (outputs.size > MAX_STORED_OUTPUTS) {
8
+ const oldest = outputs.keys().next().value;
9
+ if (!oldest)
10
+ break;
11
+ outputs.delete(oldest);
12
+ }
13
+ return handle;
14
+ }
15
+ export function readToolOutput(handle, offset = 0, limit = 12_000) {
16
+ const output = outputs.get(handle);
17
+ if (output == null)
18
+ return undefined;
19
+ const safeOffset = Math.min(Math.max(0, offset), output.length);
20
+ const content = output.slice(safeOffset, safeOffset + limit);
21
+ const nextOffset = safeOffset + content.length < output.length ? safeOffset + content.length : undefined;
22
+ return {
23
+ handle,
24
+ offset: safeOffset,
25
+ ...(nextOffset == null ? {} : { nextOffset }),
26
+ totalChars: output.length,
27
+ content,
28
+ truncated: nextOffset != null,
29
+ };
30
+ }
31
+ export function clearToolOutputs() {
32
+ outputs.clear();
33
+ }
@@ -0,0 +1,38 @@
1
+ import type { RequestIntent } from '../goal/requestClassifier.js';
2
+ export type WorkFileAction = 'read' | 'created' | 'modified';
3
+ export type WorkValidationStatus = 'passed' | 'failed';
4
+ export interface WorkState {
5
+ goal: string;
6
+ intent: RequestIntent;
7
+ successCriteria: string[];
8
+ constraints: string[];
9
+ decisions: Array<{
10
+ decision: string;
11
+ reason?: string;
12
+ }>;
13
+ files: Array<{
14
+ path: string;
15
+ action: WorkFileAction;
16
+ note?: string;
17
+ }>;
18
+ validations: Array<{
19
+ command: string;
20
+ status: WorkValidationStatus;
21
+ summary: string;
22
+ }>;
23
+ blockers: string[];
24
+ pending: string[];
25
+ nextAction?: string;
26
+ phase: string;
27
+ revision: number;
28
+ }
29
+ export interface WorkToolEvent {
30
+ toolName: string;
31
+ input?: unknown;
32
+ success: boolean;
33
+ output?: unknown;
34
+ duplicateSkipped?: boolean;
35
+ }
36
+ export declare function createWorkState(goal: string, intent: RequestIntent, successCriteria: string[]): WorkState;
37
+ export declare function observeWorkToolEvent(state: WorkState, event: WorkToolEvent): WorkState;
38
+ export declare function workStatePrompt(state: WorkState): string;
@@ -0,0 +1,89 @@
1
+ function inputString(input, key) {
2
+ return typeof input === 'object' && input != null && key in input && typeof input[key] === 'string'
3
+ ? input[key]
4
+ : undefined;
5
+ }
6
+ function upsertFile(state, path, action, note) {
7
+ const existing = state.files.find(file => file.path === path);
8
+ if (existing) {
9
+ if (action !== 'read')
10
+ existing.action = action;
11
+ if (note)
12
+ existing.note = note;
13
+ }
14
+ else {
15
+ state.files.push({ path, action, ...(note ? { note } : {}) });
16
+ }
17
+ }
18
+ function outputOk(output, success) {
19
+ return success && !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
20
+ }
21
+ function outputSummary(output) {
22
+ if (typeof output !== 'object' || output == null)
23
+ return '';
24
+ if ('validationSummary' in output && typeof output.validationSummary === 'object' && output.validationSummary != null && 'summaryText' in output.validationSummary) {
25
+ return String(output.validationSummary.summaryText);
26
+ }
27
+ if ('error' in output && typeof output.error === 'string')
28
+ return output.error;
29
+ if ('code' in output)
30
+ return `exit ${String(output.code)}`;
31
+ return '';
32
+ }
33
+ export function createWorkState(goal, intent, successCriteria) {
34
+ return {
35
+ goal,
36
+ intent,
37
+ successCriteria: [...successCriteria],
38
+ constraints: [],
39
+ decisions: [],
40
+ files: [],
41
+ validations: [],
42
+ blockers: [],
43
+ pending: [],
44
+ phase: 'starting',
45
+ revision: 0,
46
+ };
47
+ }
48
+ export function observeWorkToolEvent(state, event) {
49
+ if (event.duplicateSkipped)
50
+ return state;
51
+ const ok = outputOk(event.output, event.success);
52
+ const path = inputString(event.input, 'path');
53
+ if (ok && path && ['listFiles', 'readFile', 'grep'].includes(event.toolName)) {
54
+ if (event.toolName === 'readFile')
55
+ upsertFile(state, path, 'read');
56
+ state.phase = 'inspecting';
57
+ }
58
+ if (path && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
59
+ if (ok) {
60
+ upsertFile(state, path, event.toolName === 'writeFile' ? 'created' : 'modified');
61
+ state.phase = 'editing';
62
+ state.blockers = state.blockers.filter(blocker => !blocker.includes(path));
63
+ }
64
+ else {
65
+ state.blockers = [...new Set([...state.blockers, `Edit failed for ${path}: ${outputSummary(event.output) || 'fresh read required'}`])];
66
+ state.nextAction = `Read ${path}, then retry the edit with current content.`;
67
+ }
68
+ }
69
+ if (event.toolName === 'bash') {
70
+ const command = inputString(event.input, 'command');
71
+ if (command) {
72
+ const status = ok ? 'passed' : 'failed';
73
+ const existing = state.validations.find(validation => validation.command === command);
74
+ const summary = outputSummary(event.output);
75
+ if (existing)
76
+ Object.assign(existing, { status, summary });
77
+ else
78
+ state.validations.push({ command, status, summary });
79
+ state.phase = 'validating';
80
+ if (!ok)
81
+ state.blockers = [...new Set([...state.blockers, `Validation failed: ${command}`])];
82
+ }
83
+ }
84
+ state.revision += 1;
85
+ return state;
86
+ }
87
+ export function workStatePrompt(state) {
88
+ return `<work_state>\n${JSON.stringify(state)}\n</work_state>`;
89
+ }
@@ -79,7 +79,7 @@ export function completionDecision(input) {
79
79
  };
80
80
  }
81
81
  export function toolLoopBudgetPrompt() {
82
- return 'Tool slice reached for this model step. Do not output XML, JSON tool-call syntax, <tool_call> blocks, or function-call markup. If the current request is complete, answer with the final status template using only current-turn changes and validation evidence. If incomplete, state the single next concrete unfinished action so Haze can continue autonomously in a fresh tool slice. Do not claim tools are unavailable, recap unrelated earlier tasks, or provide a generic remains list.';
82
+ return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once: either the final status template (current-turn changes + validation evidence) or, if incomplete, a single short line stating the next concrete unfinished action so Haze can continue in a fresh tool slice. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
83
83
  }
84
84
  export function postContinuationPrompt() {
85
85
  return 'Your previous response still described unfinished work, missing validation, or a tool-budget issue. If tools are available, complete the remaining edit or run the final validation now. Only call something blocked for a concrete tool failure, missing dependency/permission, or unavoidable ambiguity.';
@@ -1,4 +1,5 @@
1
1
  import { type RequestIntent } from './requestClassifier.js';
2
+ import { type WorkState } from '../agent/workState.js';
2
3
  export type SessionGoalStatus = 'active' | 'needs-user' | 'blocked' | 'complete' | 'aborted';
3
4
  export type ValidationStatus = 'pending' | 'passed' | 'failed';
4
5
  export interface SessionGoal {
@@ -16,6 +17,7 @@ export interface SessionGoal {
16
17
  phase: 'starting' | 'inspecting' | 'editing' | 'validating' | 'summarizing' | 'done';
17
18
  blocker?: string;
18
19
  lastProgressAt: number;
20
+ workState: WorkState;
19
21
  }
20
22
  export interface GoalToolEvent {
21
23
  toolName: string;