@denizokcu/haze 0.6.0 → 0.7.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 (147) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +59 -12
  3. package/dist/cli/chat/TaskBar.d.ts +9 -0
  4. package/dist/cli/chat/TaskBar.js +40 -0
  5. package/dist/cli/chat/chatMetrics.d.ts +11 -0
  6. package/dist/cli/chat/chatMetrics.js +50 -0
  7. package/dist/cli/chat/inputSuggestions.d.ts +16 -0
  8. package/dist/cli/chat/inputSuggestions.js +55 -0
  9. package/dist/cli/chat/messages.d.ts +9 -0
  10. package/dist/cli/chat/messages.js +76 -0
  11. package/dist/cli/chat/sessionRecorder.d.ts +12 -0
  12. package/dist/cli/chat/sessionRecorder.js +21 -0
  13. package/dist/cli/chat/startupInfo.d.ts +4 -0
  14. package/dist/cli/chat/startupInfo.js +53 -0
  15. package/dist/cli/chat/turnState.d.ts +5 -0
  16. package/dist/cli/chat/turnState.js +20 -0
  17. package/dist/cli/commands/chat.d.ts +0 -1
  18. package/dist/cli/commands/chat.js +293 -894
  19. package/dist/cli/commands/chatModes.d.ts +8 -0
  20. package/dist/cli/commands/chatModes.js +44 -0
  21. package/dist/cli/commands/commandHelp.d.ts +6 -0
  22. package/dist/cli/commands/commandHelp.js +25 -0
  23. package/dist/cli/commands/commands.d.ts +1 -1
  24. package/dist/cli/commands/commands.js +41 -267
  25. package/dist/cli/commands/formatters.js +12 -4
  26. package/dist/cli/commands/initCommand.d.ts +2 -0
  27. package/dist/cli/commands/initCommand.js +19 -0
  28. package/dist/cli/commands/logsCommand.d.ts +2 -0
  29. package/dist/cli/commands/logsCommand.js +63 -0
  30. package/dist/cli/commands/lspWizard.d.ts +14 -0
  31. package/dist/cli/commands/lspWizard.js +44 -0
  32. package/dist/cli/commands/mcpWizard.d.ts +15 -0
  33. package/dist/cli/commands/mcpWizard.js +69 -0
  34. package/dist/cli/commands/modelCommand.d.ts +2 -0
  35. package/dist/cli/commands/modelCommand.js +36 -0
  36. package/dist/cli/commands/providerWizard.d.ts +30 -0
  37. package/dist/cli/commands/providerWizard.js +114 -0
  38. package/dist/cli/commands/runCommand.d.ts +16 -0
  39. package/dist/cli/commands/runCommand.js +170 -0
  40. package/dist/cli/commands/settingsSummary.d.ts +3 -0
  41. package/dist/cli/commands/settingsSummary.js +40 -0
  42. package/dist/cli/commands/skillConfirmRemove.d.ts +11 -0
  43. package/dist/cli/commands/skillConfirmRemove.js +19 -0
  44. package/dist/cli/commands/skillCreation.d.ts +12 -0
  45. package/dist/cli/commands/skillCreation.js +14 -0
  46. package/dist/cli/commands/skillWizard.d.ts +15 -0
  47. package/dist/cli/commands/skillWizard.js +38 -0
  48. package/dist/cli/commands/streaming/assistantText.d.ts +17 -0
  49. package/dist/cli/commands/streaming/assistantText.js +115 -0
  50. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +55 -0
  51. package/dist/cli/commands/streaming/toolGroupRenderer.js +102 -0
  52. package/dist/cli/commands/streaming/toolResultState.d.ts +13 -0
  53. package/dist/cli/commands/streaming/toolResultState.js +25 -0
  54. package/dist/cli/commands/streaming/turnRuntime.d.ts +78 -0
  55. package/dist/cli/commands/streaming/turnRuntime.js +86 -0
  56. package/dist/cli/commands/streaming.d.ts +9 -25
  57. package/dist/cli/commands/streaming.js +82 -347
  58. package/dist/cli/commands/wizardActions.d.ts +40 -0
  59. package/dist/cli/commands/wizardActions.js +40 -0
  60. package/dist/cli/commands/wizardInput.d.ts +4 -0
  61. package/dist/cli/commands/wizardInput.js +19 -0
  62. package/dist/cli/commands/wizardPrompts.d.ts +22 -0
  63. package/dist/cli/commands/wizardPrompts.js +52 -0
  64. package/dist/cli/commands/wizardSuggestions.d.ts +23 -0
  65. package/dist/cli/commands/wizardSuggestions.js +139 -0
  66. package/dist/cli/index.js +62 -4
  67. package/dist/config/contextFiles.d.ts +8 -1
  68. package/dist/config/contextFiles.js +25 -12
  69. package/dist/config/lspSettings.js +3 -6
  70. package/dist/config/mcpSettings.js +5 -5
  71. package/dist/config/providers.js +4 -4
  72. package/dist/config/skillSettings.js +4 -3
  73. package/dist/core/agent/budgets.d.ts +6 -0
  74. package/dist/core/agent/budgets.js +6 -0
  75. package/dist/core/agent/compaction.js +1 -1
  76. package/dist/core/agent/requestAssembly.d.ts +0 -7
  77. package/dist/core/agent/requestAssembly.js +27 -5
  78. package/dist/core/agent/toolOutputStore.js +5 -4
  79. package/dist/core/agent/toolResults.d.ts +31 -0
  80. package/dist/core/agent/toolResults.js +42 -0
  81. package/dist/core/agent/turnPolicy.d.ts +8 -0
  82. package/dist/core/agent/turnPolicy.js +23 -0
  83. package/dist/core/agent/workState.d.ts +18 -5
  84. package/dist/core/agent/workState.js +39 -20
  85. package/dist/core/bashOutput/reducers/content.d.ts +1 -0
  86. package/dist/core/bashOutput/reducers/content.js +1 -1
  87. package/dist/core/bashOutput/reducers/gh.d.ts +1 -0
  88. package/dist/core/bashOutput/reducers/gh.js +77 -0
  89. package/dist/core/bashOutput/registry.js +8 -0
  90. package/dist/core/goal/sessionGoal.d.ts +6 -30
  91. package/dist/core/goal/sessionGoal.js +3 -68
  92. package/dist/core/safety/bashClassifier.js +30 -0
  93. package/dist/core/safety/urlGuard.d.ts +1 -0
  94. package/dist/core/safety/urlGuard.js +6 -1
  95. package/dist/core/session/sessionSlimming.d.ts +5 -0
  96. package/dist/core/session/sessionSlimming.js +78 -0
  97. package/dist/core/session/sessionStore.d.ts +23 -3
  98. package/dist/core/session/sessionStore.js +30 -10
  99. package/dist/core/subagent/subagentRunner.d.ts +11 -1
  100. package/dist/core/subagent/subagentRunner.js +1 -0
  101. package/dist/llm/capabilities.d.ts +12 -0
  102. package/dist/llm/capabilities.js +10 -0
  103. package/dist/llm/client.d.ts +1 -0
  104. package/dist/llm/client.js +11 -2
  105. package/dist/llm/hazeTools.d.ts +31 -32
  106. package/dist/llm/hazeTools.js +40 -567
  107. package/dist/llm/lsp.d.ts +46 -1
  108. package/dist/llm/lsp.js +9 -9
  109. package/dist/llm/lspTools.d.ts +2 -20
  110. package/dist/llm/mcp.js +9 -0
  111. package/dist/llm/requestContext.js +7 -22
  112. package/dist/llm/systemPrompt.d.ts +1 -0
  113. package/dist/llm/systemPrompt.js +1 -1
  114. package/dist/llm/tools/bashTool.d.ts +5 -0
  115. package/dist/llm/tools/bashTool.js +81 -0
  116. package/dist/llm/tools/editMatch.d.ts +55 -0
  117. package/dist/llm/tools/editMatch.js +99 -0
  118. package/dist/llm/tools/failures.d.ts +36 -0
  119. package/dist/llm/tools/failures.js +38 -0
  120. package/dist/llm/tools/fetchTool.d.ts +65 -0
  121. package/dist/llm/tools/fetchTool.js +45 -0
  122. package/dist/llm/tools/fileToolShared.d.ts +10 -0
  123. package/dist/llm/tools/fileToolShared.js +43 -0
  124. package/dist/llm/tools/grepParse.d.ts +13 -0
  125. package/dist/llm/tools/grepParse.js +67 -0
  126. package/dist/llm/tools/outputCap.d.ts +53 -0
  127. package/dist/llm/tools/outputCap.js +67 -0
  128. package/dist/llm/tools/storedOutputTool.d.ts +10 -0
  129. package/dist/llm/tools/storedOutputTool.js +17 -0
  130. package/dist/llm/tools/taskTool.d.ts +28 -0
  131. package/dist/llm/tools/taskTool.js +41 -0
  132. package/dist/llm/tools/toolContext.d.ts +69 -0
  133. package/dist/llm/tools/toolContext.js +187 -0
  134. package/dist/llm/tools/workspaceFile.d.ts +33 -0
  135. package/dist/llm/tools/workspaceFile.js +27 -0
  136. package/dist/llm/webFetch.d.ts +13 -1
  137. package/dist/llm/webFetch.js +91 -7
  138. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  139. package/dist/skills/builder/SkillBuilder.js +1 -1
  140. package/dist/ui/components/TextInput.js +1 -99
  141. package/dist/ui/inputBuffer.d.ts +28 -0
  142. package/dist/ui/inputBuffer.js +99 -0
  143. package/dist/utils/collections.d.ts +6 -0
  144. package/dist/utils/collections.js +9 -0
  145. package/dist/utils/path.d.ts +2 -0
  146. package/dist/utils/path.js +40 -0
  147. package/package.json +1 -2
@@ -0,0 +1,10 @@
1
+ export declare const MAX_OUTPUT_CHARS = 50000;
2
+ export declare const DEFAULT_READ_LINES = 300;
3
+ /** Inline diff lines beyond this count are omitted (just the count is returned). */
4
+ export declare const INLINE_DIFF_LINE_LIMIT = 20;
5
+ export declare function isGitIgnored(absolutePath: string): Promise<boolean>;
6
+ export declare function assertNotIgnored(absolutePath: string, inputPath: string, allowIgnored?: boolean): Promise<void>;
7
+ export declare function sourceOutlineEntries(lines: string[], startLine: number): {
8
+ lineNumber: number;
9
+ text: string;
10
+ }[];
@@ -0,0 +1,43 @@
1
+ import { execFile as execFileCallback } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { workspaceRelativePath, workspaceRoot } from '../../utils/path.js';
4
+ import { HazeToolError } from './failures.js';
5
+ const execFile = promisify(execFileCallback);
6
+ export const MAX_OUTPUT_CHARS = 50_000;
7
+ export const DEFAULT_READ_LINES = 300;
8
+ /** Inline diff lines beyond this count are omitted (just the count is returned). */
9
+ export const INLINE_DIFF_LINE_LIMIT = 20;
10
+ export async function isGitIgnored(absolutePath) {
11
+ const relative = workspaceRelativePath(absolutePath);
12
+ if (relative === '.')
13
+ return false;
14
+ try {
15
+ await execFile('git', ['-C', workspaceRoot(), 'check-ignore', '-q', '--', relative]);
16
+ return true;
17
+ }
18
+ catch (error) {
19
+ const status = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
20
+ if (status === 1 || status === 128)
21
+ return false;
22
+ return false;
23
+ }
24
+ }
25
+ export async function assertNotIgnored(absolutePath, inputPath, allowIgnored) {
26
+ if (!allowIgnored && await isGitIgnored(absolutePath)) {
27
+ throw new HazeToolError(`Path is ignored by .gitignore: ${inputPath}. Set allowIgnored=true only if you explicitly need to access ignored files.`, 'ignored_path', { recoveryTool: 'listFiles' });
28
+ }
29
+ }
30
+ const SOURCE_OUTLINE_PATTERNS = [
31
+ /^\s*(?:import|from|export|package|namespace|module|using)\b/,
32
+ /^\s*#\s*include\b/,
33
+ /^\s*(?:public|private|protected|internal|static|async|final|open|sealed|abstract|export\s+)?\s*(?:class|interface|struct|enum|type|trait|record|protocol)\b/,
34
+ /^\s*(?:export\s+)?(?:async\s+)?function\b/,
35
+ /^\s*(?:def|func|fn)\s+[A-Za-z_]/,
36
+ /^\s*(?:pub\s+)?(?:async\s+)?fn\s+[A-Za-z_]/,
37
+ /^\s*(?:public|private|protected|internal|static|async|final|override|virtual|abstract)\s+[^=;{}]+\([^)]*\)\s*(?:\{|;|=>)?\s*$/,
38
+ ];
39
+ export function sourceOutlineEntries(lines, startLine) {
40
+ return lines
41
+ .map((line, index) => ({ lineNumber: startLine + index, text: line }))
42
+ .filter(entry => SOURCE_OUTLINE_PATTERNS.some(pattern => pattern.test(entry.text)));
43
+ }
@@ -0,0 +1,13 @@
1
+ export type GrepMatchItem = {
2
+ file: string;
3
+ line: number;
4
+ content: string;
5
+ isContext: boolean;
6
+ };
7
+ export type ParsedGrepOutput = {
8
+ matches: GrepMatchItem[];
9
+ totalMatches: number;
10
+ returnedMatches: number;
11
+ omittedMatches: number;
12
+ };
13
+ export declare function parseRipgrepJsonStream(stdout: string, maxMatches: number, contextLines: number, toRelativePath?: (absolute: string) => string): ParsedGrepOutput;
@@ -0,0 +1,67 @@
1
+ function isContextEvent(event) {
2
+ return event.type === 'context';
3
+ }
4
+ function isMatchEvent(event) {
5
+ return event.type === 'match';
6
+ }
7
+ function extractMatchItem(event) {
8
+ const file = event.data?.path?.text;
9
+ const lineNumber = event.data?.line_number;
10
+ const content = event.data?.lines?.text?.replace(/\r?\n$/, '');
11
+ if (!file || lineNumber == null || content == null)
12
+ return undefined;
13
+ return { file, line: lineNumber, content, isContext: isMatchEvent(event) ? false : true };
14
+ }
15
+ export function parseRipgrepJsonStream(stdout, maxMatches, contextLines, toRelativePath = value => value) {
16
+ if (!stdout)
17
+ return { matches: [], totalMatches: 0, returnedMatches: 0, omittedMatches: 0 };
18
+ const lines = stdout.split('\n').filter(Boolean);
19
+ const matches = [];
20
+ let totalMatches = 0;
21
+ let returnedMatches = 0;
22
+ let omittedMatches = 0;
23
+ let pendingContext = [];
24
+ let retainFollowingContext = false;
25
+ for (const line of lines) {
26
+ let event;
27
+ try {
28
+ event = JSON.parse(line);
29
+ }
30
+ catch {
31
+ continue;
32
+ }
33
+ if (event.type === 'begin' || event.type === 'end') {
34
+ pendingContext = [];
35
+ retainFollowingContext = false;
36
+ continue;
37
+ }
38
+ if (!isContextEvent(event) && !isMatchEvent(event))
39
+ continue;
40
+ const item = extractMatchItem(event);
41
+ if (!item)
42
+ continue;
43
+ const relative = { ...item, file: toRelativePath(item.file) };
44
+ if (isContextEvent(event)) {
45
+ if (retainFollowingContext) {
46
+ matches.push(relative);
47
+ continue;
48
+ }
49
+ pendingContext.push(relative);
50
+ if (pendingContext.length > contextLines)
51
+ pendingContext.shift();
52
+ continue;
53
+ }
54
+ totalMatches += 1;
55
+ if (returnedMatches >= maxMatches) {
56
+ omittedMatches += 1;
57
+ pendingContext = [];
58
+ retainFollowingContext = false;
59
+ continue;
60
+ }
61
+ matches.push(...pendingContext, relative);
62
+ returnedMatches += 1;
63
+ pendingContext = [];
64
+ retainFollowingContext = true;
65
+ }
66
+ return { matches, totalMatches, returnedMatches, omittedMatches };
67
+ }
@@ -0,0 +1,53 @@
1
+ /** Default ceiling for capped tool outputs (bash, fetch). */
2
+ export declare const COMPACT_COMMAND_CHARS = 12000;
3
+ /** Default ceiling for rendered grep output. */
4
+ export declare const GREP_MAX_OUTPUT_CHARS = 30000;
5
+ /** Default ceiling for a single grep match line. */
6
+ export declare const GREP_MAX_LINE_CHARS = 500;
7
+ /**
8
+ * Cap a string to `maxChars` characters, keeping a head + tail and storing the
9
+ * full text behind a `readToolOutput` handle so nothing is lost.
10
+ */
11
+ export declare function compactStoredOutput(text: string, maxChars?: number): {
12
+ text: string;
13
+ truncated: boolean;
14
+ omittedChars?: undefined;
15
+ handle?: undefined;
16
+ } | {
17
+ text: string;
18
+ truncated: boolean;
19
+ omittedChars: number;
20
+ handle: string;
21
+ };
22
+ /** Truncate a single over-long line in place. */
23
+ export declare function compactLine(text: string, maxChars?: number): {
24
+ text: string;
25
+ truncated: boolean;
26
+ };
27
+ /** Render structured grep matches as `file:line:content` lines (context flagged with `-`). */
28
+ export declare function renderGrepMatches(matches: Array<{
29
+ file: string;
30
+ line: number;
31
+ content: string;
32
+ isContext: boolean;
33
+ }>): string;
34
+ /**
35
+ * Compact grep matches to a byte budget, truncating individual lines and
36
+ * dropping trailing matches once the estimated serialized size is exceeded.
37
+ */
38
+ export declare function compactGrepMatches(matches: Array<{
39
+ file: string;
40
+ line: number;
41
+ content: string;
42
+ isContext: boolean;
43
+ }>, maxChars?: number): {
44
+ matches: {
45
+ file: string;
46
+ line: number;
47
+ content: string;
48
+ isContext: boolean;
49
+ }[];
50
+ lineTruncated: boolean;
51
+ omittedResultLines: number;
52
+ outputTruncated: boolean;
53
+ };
@@ -0,0 +1,67 @@
1
+ import { storeToolOutput } from '../../core/agent/toolOutputStore.js';
2
+ /** Default ceiling for capped tool outputs (bash, fetch). */
3
+ export const COMPACT_COMMAND_CHARS = 12_000;
4
+ /** Default ceiling for rendered grep output. */
5
+ export const GREP_MAX_OUTPUT_CHARS = 30_000;
6
+ /** Default ceiling for a single grep match line. */
7
+ export const GREP_MAX_LINE_CHARS = 500;
8
+ /**
9
+ * Cap a string to `maxChars` characters, keeping a head + tail and storing the
10
+ * full text behind a `readToolOutput` handle so nothing is lost.
11
+ */
12
+ export function compactStoredOutput(text, maxChars = COMPACT_COMMAND_CHARS) {
13
+ if (text.length <= maxChars)
14
+ return { text, truncated: false };
15
+ const handle = storeToolOutput(text);
16
+ const headChars = Math.floor(maxChars * 0.4);
17
+ const tailChars = maxChars - headChars;
18
+ return {
19
+ text: `${text.slice(0, headChars)}\n\n[... ${text.length - maxChars} characters omitted; use readToolOutput with handle ${handle} ...]\n\n${text.slice(-tailChars)}`,
20
+ truncated: true,
21
+ omittedChars: text.length - maxChars,
22
+ handle,
23
+ };
24
+ }
25
+ /** Truncate a single over-long line in place. */
26
+ export function compactLine(text, maxChars = GREP_MAX_LINE_CHARS) {
27
+ if (text.length <= maxChars)
28
+ return { text, truncated: false };
29
+ return { text: `${text.slice(0, Math.max(0, maxChars - 22))}[line truncated]`, truncated: true };
30
+ }
31
+ /** Render structured grep matches as `file:line:content` lines (context flagged with `-`). */
32
+ export function renderGrepMatches(matches) {
33
+ return matches.map(match => `${match.file}:${match.line}:${match.isContext ? '-' : ''}${match.content}`).join('\n');
34
+ }
35
+ /**
36
+ * Compact grep matches to a byte budget, truncating individual lines and
37
+ * dropping trailing matches once the estimated serialized size is exceeded.
38
+ */
39
+ export function compactGrepMatches(matches, maxChars = GREP_MAX_OUTPUT_CHARS) {
40
+ const compacted = [];
41
+ let lineTruncated = false;
42
+ let omittedResultLines = 0;
43
+ // Estimate the serialized size incrementally to keep this O(n) rather than
44
+ // re-serializing the whole accumulated array on every iteration (O(n²)).
45
+ // We approximate the JSON shape: a `[`/`]` wrapper, per-object structural
46
+ // overhead (keys, quotes, braces, separators), and the field values
47
+ // themselves. This is slightly tighter than a real `JSON.stringify` would
48
+ // be (it ignores escaping of `"`, `\`, and control chars in `content`),
49
+ // which is the safe direction for a soft truncation ceiling.
50
+ const itemSeparatorChars = 2; // `, ` between objects in the serialized array.
51
+ const objectOverheadChars = 30; // keys + quotes + braces + structural separators.
52
+ const arrayWrapperChars = 2; // the surrounding `[` and `]`.
53
+ let estimatedSize = arrayWrapperChars;
54
+ for (const match of matches) {
55
+ const line = compactLine(match.content);
56
+ lineTruncated = lineTruncated || line.truncated;
57
+ const lineText = line.text;
58
+ const itemSize = objectOverheadChars + match.file.length + String(match.line).length + lineText.length;
59
+ if (estimatedSize + itemSize > maxChars) {
60
+ omittedResultLines = matches.length - compacted.length;
61
+ break;
62
+ }
63
+ estimatedSize += itemSize + itemSeparatorChars;
64
+ compacted.push({ ...match, content: lineText });
65
+ }
66
+ return { matches: compacted, lineTruncated, omittedResultLines, outputTruncated: omittedResultLines > 0 || lineTruncated };
67
+ }
@@ -0,0 +1,10 @@
1
+ export declare const readToolOutputTool: import("ai").Tool<{
2
+ handle: string;
3
+ offset: number;
4
+ limit: number;
5
+ contextLines: number;
6
+ query?: string | undefined;
7
+ }, import("../../core/agent/toolOutputStore.js").StoredToolOutputPage | {
8
+ ok: boolean;
9
+ error: string;
10
+ }>;
@@ -0,0 +1,17 @@
1
+ import { tool } from 'ai';
2
+ import { z } from 'zod';
3
+ import { readToolOutput as readStoredToolOutput } from '../../core/agent/toolOutputStore.js';
4
+ export const readToolOutputTool = tool({
5
+ description: 'Read another page of oversized output previously returned by a tool handle.',
6
+ inputSchema: z.object({
7
+ handle: z.string().min(1).describe('Output handle from a prior tool result'),
8
+ offset: z.number().int().nonnegative().default(0).describe('Character offset to start reading'),
9
+ limit: z.number().int().positive().max(20_000).default(12_000).describe('Maximum characters to return'),
10
+ query: z.string().optional().describe('Optional case-insensitive substring search within the stored output instead of reading by offset'),
11
+ contextLines: z.number().int().nonnegative().max(20).default(2).describe('Lines of context around query matches'),
12
+ }),
13
+ execute: async ({ handle, offset, limit, query, contextLines }) => {
14
+ const page = readStoredToolOutput(handle, offset, limit, { query, contextLines });
15
+ return page ?? { ok: false, error: `Unknown or expired tool output handle: ${handle}` };
16
+ },
17
+ });
@@ -0,0 +1,28 @@
1
+ export declare const writeTasksTool: import("ai").Tool<{
2
+ tasks: {
3
+ title: string;
4
+ status?: "pending" | "in_progress" | "completed" | undefined;
5
+ }[];
6
+ }, {
7
+ ok: boolean;
8
+ error: string;
9
+ taskCount?: undefined;
10
+ summary?: undefined;
11
+ counts?: undefined;
12
+ } | {
13
+ ok: boolean;
14
+ taskCount: number;
15
+ summary: string;
16
+ error?: undefined;
17
+ counts?: undefined;
18
+ } | {
19
+ ok: boolean;
20
+ taskCount: number;
21
+ counts: {
22
+ pending: number;
23
+ in_progress: number;
24
+ completed: number;
25
+ };
26
+ summary: string;
27
+ error?: undefined;
28
+ }>;
@@ -0,0 +1,41 @@
1
+ import { tool } from 'ai';
2
+ import { z } from 'zod';
3
+ import { generateTaskId, saveTasks } from '../../core/tasks/taskStorage.js';
4
+ export const writeTasksTool = tool({
5
+ description: 'Replace the task list for substantial work. Update at meaningful phase changes, blockers, and completion; pass the complete list.',
6
+ inputSchema: z.object({
7
+ tasks: z.array(z.object({
8
+ title: z.string().max(200).describe('Short task description'),
9
+ status: z.enum(['pending', 'in_progress', 'completed']).optional().describe('Task status (defaults to pending)'),
10
+ })).describe('Complete task list. Replaces any existing tasks. Pass an empty array to clear.'),
11
+ }),
12
+ execute: async ({ tasks: inputTasks }) => {
13
+ if (!Array.isArray(inputTasks)) {
14
+ return { ok: false, error: 'Tasks must be an array. Pass an empty array to clear the list.' };
15
+ }
16
+ for (let i = 0; i < inputTasks.length; i++) {
17
+ const title = inputTasks[i]?.title?.trim();
18
+ if (!title)
19
+ return { ok: false, error: `Task ${i + 1}: title cannot be empty.` };
20
+ if (title.length > 200)
21
+ return { ok: false, error: `Task ${i + 1}: title is too long (max 200 characters).` };
22
+ }
23
+ const now = new Date().toISOString();
24
+ const tasks = inputTasks.map((input) => ({
25
+ id: generateTaskId(),
26
+ title: input.title.trim(),
27
+ status: input.status ?? 'pending',
28
+ createdAt: now,
29
+ updatedAt: now,
30
+ }));
31
+ await saveTasks(tasks);
32
+ if (tasks.length === 0)
33
+ return { ok: true, taskCount: 0, summary: 'Task list cleared.' };
34
+ const counts = {
35
+ pending: tasks.filter(t => t.status === 'pending').length,
36
+ in_progress: tasks.filter(t => t.status === 'in_progress').length,
37
+ completed: tasks.filter(t => t.status === 'completed').length,
38
+ };
39
+ return { ok: true, taskCount: tasks.length, counts, summary: `Tasks: ${counts.pending} pending, ${counts.in_progress} in progress, ${counts.completed} completed.` };
40
+ },
41
+ });
@@ -0,0 +1,69 @@
1
+ import type { ToolFailureReasonCode } from '../toolResultTypes.js';
2
+ import { type ContextFile } from '../../config/contextFiles.js';
3
+ /**
4
+ * Turn-scoped tool-call orchestration shared by every built-in tool: in-flight
5
+ * and completed-call deduplication, a mutation epoch that invalidates read
6
+ * caches after writes, edit-recovery gating, and lazy discovery of scoped
7
+ * project instructions (CLAUDE.md / AGENTS.md below the cwd).
8
+ *
9
+ * All state lives on `experimental_context`, which the agent turn owns and
10
+ * passes to the AI SDK. Nothing here is persisted.
11
+ */
12
+ export type ToolExecutionContext = {
13
+ abortSignal?: AbortSignal;
14
+ experimental_context?: unknown;
15
+ };
16
+ export type HazeToolContext = {
17
+ inFlightToolCalls?: Map<string, Promise<unknown>>;
18
+ completedToolCalls?: Map<string, number>;
19
+ mutationEpoch?: number;
20
+ failedMutationPaths?: Set<string>;
21
+ failedMutationReasons?: Map<string, ToolFailureReasonCode | undefined>;
22
+ pathsReadAfterFailedMutation?: Set<string>;
23
+ inFlightMutationPaths?: Set<string>;
24
+ loadedContextFilePaths?: Set<string>;
25
+ loadedContextFileSignatures?: Map<string, string>;
26
+ pendingContextFiles?: ContextFile[];
27
+ scopedContextDiscovery?: Promise<void>;
28
+ onContextFileRead?: (path: string) => void;
29
+ };
30
+ export declare function hazeContext(context: ToolExecutionContext): HazeToolContext | undefined;
31
+ /**
32
+ * Lazily load scoped CLAUDE.md/AGENTS.md files that apply to `filePath` and
33
+ * have not been surfaced yet this turn. Mutates the context's loaded-set so
34
+ * each file is only returned once.
35
+ */
36
+ export declare function discoverScopedContext(filePath: string, context: ToolExecutionContext): Promise<ContextFile[]>;
37
+ /** Attach discovered scoped instructions to a tool result, if any. */
38
+ export declare function withScopedContext<T extends Record<string, unknown>>(result: T, files: ContextFile[]): T & {
39
+ applicableProjectInstructions?: ContextFile[];
40
+ };
41
+ /**
42
+ * When scoped project instructions apply to a path being mutated, pause the
43
+ * mutation so the model can review them first. Returns a structured failure
44
+ * the tool yields directly (no file change).
45
+ */
46
+ export declare function scopedContextMutationStop(toolName: string, filePath: string, files: ContextFile[]): {
47
+ ok: boolean;
48
+ toolName: string;
49
+ path: string;
50
+ error: string;
51
+ reasonCode: "scoped_instructions_discovered";
52
+ recoverable: boolean;
53
+ suggestedNextStep: string;
54
+ applicableProjectInstructions: ContextFile[];
55
+ } | undefined;
56
+ /**
57
+ * Wrap a tool's execution with turn-scoped deduplication and edit-recovery:
58
+ * - skip concurrent mutations of the same path;
59
+ * - force a re-read before retrying an edit that just failed on a path;
60
+ * - skip identical completed read-only calls until a mutation occurs;
61
+ * - skip identical in-flight calls;
62
+ * - bump a mutation epoch on successful writes so read caches invalidate.
63
+ */
64
+ export declare function runDedupedTool<T>(toolName: string, input: unknown, context: ToolExecutionContext, execute: () => Promise<T>): Promise<T | {
65
+ ok: true;
66
+ duplicateSkipped: true;
67
+ toolName: string;
68
+ reason: string;
69
+ }>;
@@ -0,0 +1,187 @@
1
+ import { readScopedContextFilesForPath } from '../../config/contextFiles.js';
2
+ import { workspaceRoot } from '../../utils/path.js';
3
+ import { isFailedToolOutput, toolInputField } from '../../core/agent/toolResults.js';
4
+ import { HazeToolError } from './failures.js';
5
+ function stableJsonStringify(value) {
6
+ if (Array.isArray(value))
7
+ return `[${value.map(stableJsonStringify).join(',')}]`;
8
+ if (value && typeof value === 'object') {
9
+ const entries = Object.entries(value)
10
+ .filter(([, entryValue]) => entryValue !== undefined)
11
+ .sort(([a], [b]) => a.localeCompare(b));
12
+ return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`).join(',')}}`;
13
+ }
14
+ return JSON.stringify(value) ?? 'undefined';
15
+ }
16
+ function toolCallKey(toolName, input) {
17
+ return `${toolName}:${stableJsonStringify(input)}`;
18
+ }
19
+ export function hazeContext(context) {
20
+ return typeof context.experimental_context === 'object' && context.experimental_context != null
21
+ ? context.experimental_context
22
+ : undefined;
23
+ }
24
+ /**
25
+ * Lazily load scoped CLAUDE.md/AGENTS.md files that apply to `filePath` and
26
+ * have not been surfaced yet this turn. Mutates the context's loaded-set so
27
+ * each file is only returned once.
28
+ */
29
+ export async function discoverScopedContext(filePath, context) {
30
+ const ctx = hazeContext(context);
31
+ const previousDiscovery = ctx?.scopedContextDiscovery;
32
+ let releaseDiscovery = () => undefined;
33
+ const currentDiscovery = new Promise(resolve => { releaseDiscovery = resolve; });
34
+ if (ctx)
35
+ ctx.scopedContextDiscovery = previousDiscovery ? previousDiscovery.catch(() => undefined).then(() => currentDiscovery) : currentDiscovery;
36
+ await previousDiscovery?.catch(() => undefined);
37
+ try {
38
+ const loaded = ctx?.loadedContextFilePaths ?? new Set();
39
+ const signatures = ctx?.loadedContextFileSignatures;
40
+ const files = await readScopedContextFilesForPath(filePath, { cwd: workspaceRoot(), alreadyLoadedPaths: loaded, alreadyLoadedSignatures: signatures, onContextFileRead: ctx?.onContextFileRead });
41
+ if (ctx && !ctx.loadedContextFilePaths)
42
+ ctx.loadedContextFilePaths = loaded;
43
+ for (const file of files) {
44
+ loaded.add(file.path);
45
+ if (file.signature)
46
+ signatures?.set(file.path, file.signature);
47
+ }
48
+ if (ctx && files.length > 0)
49
+ ctx.pendingContextFiles = [...(ctx.pendingContextFiles ?? []), ...files];
50
+ return files;
51
+ }
52
+ finally {
53
+ releaseDiscovery();
54
+ }
55
+ }
56
+ /** Attach discovered scoped instructions to a tool result, if any. */
57
+ export function withScopedContext(result, files) {
58
+ return files.length > 0 ? { ...result, applicableProjectInstructions: files } : result;
59
+ }
60
+ /**
61
+ * When scoped project instructions apply to a path being mutated, pause the
62
+ * mutation so the model can review them first. Returns a structured failure
63
+ * the tool yields directly (no file change).
64
+ */
65
+ export function scopedContextMutationStop(toolName, filePath, files) {
66
+ if (files.length === 0)
67
+ return undefined;
68
+ return {
69
+ ok: false,
70
+ toolName,
71
+ path: filePath,
72
+ error: `Scoped project instructions apply to ${filePath}: ${files.map(file => file.path).join(', ')}. Review them before mutating this path.`,
73
+ reasonCode: 'scoped_instructions_discovered',
74
+ recoverable: true,
75
+ suggestedNextStep: `Read the applicableProjectInstructions returned in this result, then retry ${toolName} only if the change follows those scoped instructions.`,
76
+ applicableProjectInstructions: files,
77
+ };
78
+ }
79
+ function isMutatingTool(toolName) {
80
+ return ['editFile', 'replaceLines', 'writeFile'].includes(toolName);
81
+ }
82
+ function isReadOnlyFileTool(toolName) {
83
+ return ['listFiles', 'readFile', 'grep'].includes(toolName);
84
+ }
85
+ // Read-only tools that participate in completed-call deduplication within a
86
+ // turn (no side effects). File tools + bash + fetch; fetch has no path and is
87
+ // network-side-effect-free for the agent's purposes.
88
+ function isDeduplicableReadOnlyTool(toolName) {
89
+ return isReadOnlyFileTool(toolName) || toolName === 'bash' || toolName === 'fetch';
90
+ }
91
+ /**
92
+ * Wrap a tool's execution with turn-scoped deduplication and edit-recovery:
93
+ * - skip concurrent mutations of the same path;
94
+ * - force a re-read before retrying an edit that just failed on a path;
95
+ * - skip identical completed read-only calls until a mutation occurs;
96
+ * - skip identical in-flight calls;
97
+ * - bump a mutation epoch on successful writes so read caches invalidate.
98
+ */
99
+ export async function runDedupedTool(toolName, input, context, execute) {
100
+ const ctx = hazeContext(context);
101
+ if (!ctx)
102
+ return execute();
103
+ ctx.inFlightToolCalls ??= new Map();
104
+ ctx.completedToolCalls ??= new Map();
105
+ ctx.failedMutationPaths ??= new Set();
106
+ ctx.failedMutationReasons ??= new Map();
107
+ ctx.pathsReadAfterFailedMutation ??= new Set();
108
+ ctx.inFlightMutationPaths ??= new Set();
109
+ ctx.mutationEpoch ??= 0;
110
+ const key = toolCallKey(toolName, input);
111
+ const pathForInput = toolInputField(input, 'path');
112
+ if (isMutatingTool(toolName) && pathForInput && ctx.inFlightMutationPaths.has(pathForInput)) {
113
+ return {
114
+ ok: true,
115
+ duplicateSkipped: true,
116
+ toolName,
117
+ reason: `Skipped concurrent mutation for ${pathForInput}. Read the file again, then make one editFile call with all non-overlapping replacements or one replaceLines call based on the latest line numbers.`,
118
+ };
119
+ }
120
+ if (isMutatingTool(toolName) && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput)) {
121
+ const reason = ctx.failedMutationReasons.get(pathForInput);
122
+ throw new HazeToolError(`Read ${pathForInput} before attempting another edit after the previous edit failure${reason ? ` (${reason})` : ''}.`, reason ?? 'io_error', { recoveryTool: 'readFile', recoveryInput: { path: pathForInput } });
123
+ }
124
+ const completedAt = ctx.completedToolCalls.get(key);
125
+ const readAfterFailedMutation = toolName === 'readFile' && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput);
126
+ if ((isDeduplicableReadOnlyTool(toolName)) && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
127
+ return {
128
+ ok: true,
129
+ duplicateSkipped: true,
130
+ toolName,
131
+ reason: toolName === 'bash'
132
+ ? 'Skipped duplicate bash command; no files changed since the previous run.'
133
+ : toolName === 'fetch'
134
+ ? 'Skipped duplicate fetch with identical URL; no files changed since the previous call.'
135
+ : 'Skipped duplicate read-only tool call with identical input; no files changed since the previous call.',
136
+ };
137
+ }
138
+ if (ctx.inFlightToolCalls.has(key)) {
139
+ return {
140
+ ok: true,
141
+ duplicateSkipped: true,
142
+ toolName,
143
+ reason: 'Skipped duplicate in-flight tool call with identical input.',
144
+ };
145
+ }
146
+ if (isMutatingTool(toolName) && pathForInput)
147
+ ctx.inFlightMutationPaths.add(pathForInput);
148
+ const promise = execute();
149
+ ctx.inFlightToolCalls.set(key, promise);
150
+ try {
151
+ const result = await promise;
152
+ if (isFailedToolOutput(result)) {
153
+ if (isMutatingTool(toolName) && pathForInput) {
154
+ ctx.failedMutationPaths.add(pathForInput);
155
+ const reasonCode = typeof result === 'object' && result != null && 'reasonCode' in result ? result.reasonCode : undefined;
156
+ ctx.failedMutationReasons.set(pathForInput, reasonCode);
157
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
158
+ }
159
+ return result;
160
+ }
161
+ if (toolName === 'readFile' && pathForInput)
162
+ ctx.pathsReadAfterFailedMutation.add(pathForInput);
163
+ if (isMutatingTool(toolName)) {
164
+ ctx.mutationEpoch += 1;
165
+ if (pathForInput) {
166
+ ctx.failedMutationPaths.delete(pathForInput);
167
+ ctx.failedMutationReasons.delete(pathForInput);
168
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
169
+ }
170
+ }
171
+ ctx.completedToolCalls.set(key, ctx.mutationEpoch);
172
+ return result;
173
+ }
174
+ catch (error) {
175
+ if (isMutatingTool(toolName) && pathForInput) {
176
+ ctx.failedMutationPaths.add(pathForInput);
177
+ ctx.failedMutationReasons.set(pathForInput, error instanceof HazeToolError ? error.reasonCode : undefined);
178
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
179
+ }
180
+ throw error;
181
+ }
182
+ finally {
183
+ ctx.inFlightToolCalls.delete(key);
184
+ if (isMutatingTool(toolName) && pathForInput)
185
+ ctx.inFlightMutationPaths?.delete(pathForInput);
186
+ }
187
+ }
@@ -0,0 +1,33 @@
1
+ import { type ToolExecutionContext } from './toolContext.js';
2
+ export declare function prepareWorkspaceExisting(filePath: string): Promise<string>;
3
+ export declare function prepareWorkspaceRead(filePath: string, allowIgnored: boolean | undefined): Promise<string>;
4
+ export declare function prepareWorkspaceMutation(toolName: string, filePath: string, allowIgnored: boolean | undefined, context: ToolExecutionContext): Promise<{
5
+ absolutePath: string;
6
+ scopedContext: import("../../config/contextFiles.js").ContextFile[];
7
+ scopedStop: {
8
+ ok: boolean;
9
+ toolName: string;
10
+ path: string;
11
+ error: string;
12
+ reasonCode: "scoped_instructions_discovered";
13
+ recoverable: boolean;
14
+ suggestedNextStep: string;
15
+ applicableProjectInstructions: import("../../config/contextFiles.js").ContextFile[];
16
+ } | undefined;
17
+ }>;
18
+ export declare function prepareWorkspaceWritePath(toolName: string, filePath: string, allowIgnored: boolean | undefined, context: ToolExecutionContext): Promise<{
19
+ absolutePath: string;
20
+ scopedContext: import("../../config/contextFiles.js").ContextFile[];
21
+ scopedStop: {
22
+ ok: boolean;
23
+ toolName: string;
24
+ path: string;
25
+ error: string;
26
+ reasonCode: "scoped_instructions_discovered";
27
+ recoverable: boolean;
28
+ suggestedNextStep: string;
29
+ applicableProjectInstructions: import("../../config/contextFiles.js").ContextFile[];
30
+ } | undefined;
31
+ assertExistingInsideWorkspace: () => Promise<void>;
32
+ assertWritableInsideWorkspace: () => Promise<void>;
33
+ }>;