@denizokcu/haze 0.6.0 → 0.8.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 (160) hide show
  1. package/CHANGELOG.md +42 -7
  2. package/README.md +81 -34
  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 +331 -906
  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.d.ts +6 -0
  26. package/dist/cli/commands/formatters.js +50 -4
  27. package/dist/cli/commands/initCommand.d.ts +2 -0
  28. package/dist/cli/commands/initCommand.js +19 -0
  29. package/dist/cli/commands/logsCommand.d.ts +2 -0
  30. package/dist/cli/commands/logsCommand.js +63 -0
  31. package/dist/cli/commands/lspWizard.d.ts +14 -0
  32. package/dist/cli/commands/lspWizard.js +44 -0
  33. package/dist/cli/commands/mcpWizard.d.ts +15 -0
  34. package/dist/cli/commands/mcpWizard.js +69 -0
  35. package/dist/cli/commands/modelCommand.d.ts +2 -0
  36. package/dist/cli/commands/modelCommand.js +36 -0
  37. package/dist/cli/commands/providerWizard.d.ts +30 -0
  38. package/dist/cli/commands/providerWizard.js +114 -0
  39. package/dist/cli/commands/runCommand.d.ts +16 -0
  40. package/dist/cli/commands/runCommand.js +170 -0
  41. package/dist/cli/commands/settingsSummary.d.ts +3 -0
  42. package/dist/cli/commands/settingsSummary.js +40 -0
  43. package/dist/cli/commands/skillConfirmRemove.d.ts +11 -0
  44. package/dist/cli/commands/skillConfirmRemove.js +19 -0
  45. package/dist/cli/commands/skillCreation.d.ts +12 -0
  46. package/dist/cli/commands/skillCreation.js +14 -0
  47. package/dist/cli/commands/skillWizard.d.ts +15 -0
  48. package/dist/cli/commands/skillWizard.js +38 -0
  49. package/dist/cli/commands/streaming/assistantText.d.ts +17 -0
  50. package/dist/cli/commands/streaming/assistantText.js +115 -0
  51. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +55 -0
  52. package/dist/cli/commands/streaming/toolGroupRenderer.js +102 -0
  53. package/dist/cli/commands/streaming/toolResultState.d.ts +13 -0
  54. package/dist/cli/commands/streaming/toolResultState.js +25 -0
  55. package/dist/cli/commands/streaming/turnRuntime.d.ts +78 -0
  56. package/dist/cli/commands/streaming/turnRuntime.js +86 -0
  57. package/dist/cli/commands/streaming.d.ts +9 -25
  58. package/dist/cli/commands/streaming.js +109 -363
  59. package/dist/cli/commands/wizardActions.d.ts +40 -0
  60. package/dist/cli/commands/wizardActions.js +40 -0
  61. package/dist/cli/commands/wizardInput.d.ts +4 -0
  62. package/dist/cli/commands/wizardInput.js +19 -0
  63. package/dist/cli/commands/wizardPrompts.d.ts +22 -0
  64. package/dist/cli/commands/wizardPrompts.js +52 -0
  65. package/dist/cli/commands/wizardSuggestions.d.ts +23 -0
  66. package/dist/cli/commands/wizardSuggestions.js +139 -0
  67. package/dist/cli/index.js +62 -4
  68. package/dist/config/contextFiles.d.ts +8 -1
  69. package/dist/config/contextFiles.js +25 -12
  70. package/dist/config/lspSettings.js +3 -6
  71. package/dist/config/mcpSettings.js +5 -5
  72. package/dist/config/providers.js +8 -12
  73. package/dist/config/settings.d.ts +1 -0
  74. package/dist/config/settings.js +54 -2
  75. package/dist/config/skillSettings.js +4 -3
  76. package/dist/core/agent/budgets.d.ts +6 -0
  77. package/dist/core/agent/budgets.js +6 -0
  78. package/dist/core/agent/compaction.js +3 -3
  79. package/dist/core/agent/errors.js +1 -1
  80. package/dist/core/agent/requestAssembly.d.ts +1 -7
  81. package/dist/core/agent/requestAssembly.js +40 -5
  82. package/dist/core/agent/toolOutputStore.js +5 -4
  83. package/dist/core/agent/toolResults.d.ts +31 -0
  84. package/dist/core/agent/toolResults.js +42 -0
  85. package/dist/core/agent/turnPolicy.d.ts +8 -0
  86. package/dist/core/agent/turnPolicy.js +23 -0
  87. package/dist/core/agent/workState.d.ts +18 -5
  88. package/dist/core/agent/workState.js +39 -20
  89. package/dist/core/bashOutput/reducers/content.d.ts +1 -0
  90. package/dist/core/bashOutput/reducers/content.js +1 -1
  91. package/dist/core/bashOutput/reducers/gh.d.ts +1 -0
  92. package/dist/core/bashOutput/reducers/gh.js +77 -0
  93. package/dist/core/bashOutput/registry.js +18 -8
  94. package/dist/core/goal/completionPolicy.js +1 -1
  95. package/dist/core/goal/sessionGoal.d.ts +6 -30
  96. package/dist/core/goal/sessionGoal.js +3 -68
  97. package/dist/core/safety/bashClassifier.js +30 -0
  98. package/dist/core/safety/urlGuard.d.ts +1 -0
  99. package/dist/core/safety/urlGuard.js +6 -1
  100. package/dist/core/session/sessionSlimming.d.ts +5 -0
  101. package/dist/core/session/sessionSlimming.js +78 -0
  102. package/dist/core/session/sessionStore.d.ts +23 -3
  103. package/dist/core/session/sessionStore.js +30 -10
  104. package/dist/core/subagent/subagentRunner.d.ts +258 -5
  105. package/dist/core/subagent/subagentRunner.js +14 -18
  106. package/dist/core/toolOutput/reduction.d.ts +2 -0
  107. package/dist/core/toolOutput/reduction.js +12 -0
  108. package/dist/core/validation/outputParser.js +5 -3
  109. package/dist/llm/capabilities.d.ts +12 -0
  110. package/dist/llm/capabilities.js +10 -0
  111. package/dist/llm/client.d.ts +3 -2
  112. package/dist/llm/client.js +26 -4
  113. package/dist/llm/hazeTools.d.ts +7710 -366
  114. package/dist/llm/hazeTools.js +46 -567
  115. package/dist/llm/initPrompt.js +1 -1
  116. package/dist/llm/lsp.d.ts +46 -1
  117. package/dist/llm/lsp.js +19 -10
  118. package/dist/llm/lspTools.d.ts +2310 -119
  119. package/dist/llm/mcp.js +9 -0
  120. package/dist/llm/requestContext.js +7 -22
  121. package/dist/llm/systemPrompt.d.ts +1 -0
  122. package/dist/llm/systemPrompt.js +3 -3
  123. package/dist/llm/tools/bashTool.d.ts +251 -0
  124. package/dist/llm/tools/bashTool.js +82 -0
  125. package/dist/llm/tools/editMatch.d.ts +55 -0
  126. package/dist/llm/tools/editMatch.js +99 -0
  127. package/dist/llm/tools/failures.d.ts +36 -0
  128. package/dist/llm/tools/failures.js +38 -0
  129. package/dist/llm/tools/fetchTool.d.ts +1201 -0
  130. package/dist/llm/tools/fetchTool.js +46 -0
  131. package/dist/llm/tools/fileToolShared.d.ts +10 -0
  132. package/dist/llm/tools/fileToolShared.js +43 -0
  133. package/dist/llm/tools/grepParse.d.ts +13 -0
  134. package/dist/llm/tools/grepParse.js +67 -0
  135. package/dist/llm/tools/outputCap.d.ts +53 -0
  136. package/dist/llm/tools/outputCap.js +67 -0
  137. package/dist/llm/tools/storedOutputTool.d.ts +351 -0
  138. package/dist/llm/tools/storedOutputTool.js +17 -0
  139. package/dist/llm/tools/taskTool.d.ts +629 -0
  140. package/dist/llm/tools/taskTool.js +41 -0
  141. package/dist/llm/tools/toolContext.d.ts +74 -0
  142. package/dist/llm/tools/toolContext.js +196 -0
  143. package/dist/llm/tools/workspaceFile.d.ts +33 -0
  144. package/dist/llm/tools/workspaceFile.js +27 -0
  145. package/dist/llm/webFetch.d.ts +13 -1
  146. package/dist/llm/webFetch.js +122 -28
  147. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  148. package/dist/skills/builder/SkillBuilder.js +8 -8
  149. package/dist/ui/components/TextInput.d.ts +7 -0
  150. package/dist/ui/components/TextInput.js +10 -98
  151. package/dist/ui/inputBuffer.d.ts +28 -0
  152. package/dist/ui/inputBuffer.js +99 -0
  153. package/dist/utils/collections.d.ts +6 -0
  154. package/dist/utils/collections.js +9 -0
  155. package/dist/utils/modelName.d.ts +2 -0
  156. package/dist/utils/modelName.js +15 -0
  157. package/dist/utils/path.d.ts +2 -0
  158. package/dist/utils/path.js +40 -0
  159. package/examples/skills/files/SKILL.md +1 -1
  160. package/package.json +14 -15
@@ -0,0 +1,74 @@
1
+ import { z } from 'zod';
2
+ import type { ToolFailureReasonCode } from '../toolResultTypes.js';
3
+ import { type ContextFile } from '../../config/contextFiles.js';
4
+ /**
5
+ * Turn-scoped tool-call orchestration shared by every built-in tool: in-flight
6
+ * and completed-call deduplication, a mutation epoch that invalidates read
7
+ * caches after writes, edit-recovery gating, and lazy discovery of scoped
8
+ * project instructions (CLAUDE.md / AGENTS.md below the cwd).
9
+ *
10
+ * All state lives on per-tool `context` values, which the agent turn owns and
11
+ * passes to the AI SDK. Tests and older callers may still provide the legacy
12
+ * `experimental_context` shape. Nothing here is persisted.
13
+ */
14
+ export type ToolExecutionContext = {
15
+ abortSignal?: AbortSignal;
16
+ context?: unknown;
17
+ experimental_context?: unknown;
18
+ };
19
+ export type HazeToolContext = {
20
+ inFlightToolCalls?: Map<string, Promise<unknown>>;
21
+ completedToolCalls?: Map<string, number>;
22
+ mutationEpoch?: number;
23
+ failedMutationPaths?: Set<string>;
24
+ failedMutationReasons?: Map<string, ToolFailureReasonCode | undefined>;
25
+ pathsReadAfterFailedMutation?: Set<string>;
26
+ inFlightMutationPaths?: Set<string>;
27
+ loadedContextFilePaths?: Set<string>;
28
+ loadedContextFileSignatures?: Map<string, string>;
29
+ pendingContextFiles?: ContextFile[];
30
+ scopedContextDiscovery?: Promise<void>;
31
+ onContextFileRead?: (path: string) => void;
32
+ };
33
+ export declare const hazeToolContextSchema: z.ZodCustom<HazeToolContext, HazeToolContext>;
34
+ export declare function hazeContext(context: ToolExecutionContext): HazeToolContext | undefined;
35
+ export declare function toolsContextFor<T extends Record<string, unknown>>(tools: T, context: HazeToolContext): Partial<Record<keyof T, HazeToolContext>>;
36
+ /**
37
+ * Lazily load scoped CLAUDE.md/AGENTS.md files that apply to `filePath` and
38
+ * have not been surfaced yet this turn. Mutates the context's loaded-set so
39
+ * each file is only returned once.
40
+ */
41
+ export declare function discoverScopedContext(filePath: string, context: ToolExecutionContext): Promise<ContextFile[]>;
42
+ /** Attach discovered scoped instructions to a tool result, if any. */
43
+ export declare function withScopedContext<T extends Record<string, unknown>>(result: T, files: ContextFile[]): T & {
44
+ applicableProjectInstructions?: ContextFile[];
45
+ };
46
+ /**
47
+ * When scoped project instructions apply to a path being mutated, pause the
48
+ * mutation so the model can review them first. Returns a structured failure
49
+ * the tool yields directly (no file change).
50
+ */
51
+ export declare function scopedContextMutationStop(toolName: string, filePath: string, files: ContextFile[]): {
52
+ ok: boolean;
53
+ toolName: string;
54
+ path: string;
55
+ error: string;
56
+ reasonCode: "scoped_instructions_discovered";
57
+ recoverable: boolean;
58
+ suggestedNextStep: string;
59
+ applicableProjectInstructions: ContextFile[];
60
+ } | undefined;
61
+ /**
62
+ * Wrap a tool's execution with turn-scoped deduplication and edit-recovery:
63
+ * - skip concurrent mutations of the same path;
64
+ * - force a re-read before retrying an edit that just failed on a path;
65
+ * - skip identical completed read-only calls until a mutation occurs;
66
+ * - skip identical in-flight calls;
67
+ * - bump a mutation epoch on successful writes so read caches invalidate.
68
+ */
69
+ export declare function runDedupedTool<T>(toolName: string, input: unknown, context: ToolExecutionContext, execute: () => Promise<T>): Promise<T | {
70
+ ok: true;
71
+ duplicateSkipped: true;
72
+ toolName: string;
73
+ reason: string;
74
+ }>;
@@ -0,0 +1,196 @@
1
+ import { z } from 'zod';
2
+ import { readScopedContextFilesForPath } from '../../config/contextFiles.js';
3
+ import { workspaceRoot } from '../../utils/path.js';
4
+ import { isFailedToolOutput, toolInputField } from '../../core/agent/toolResults.js';
5
+ import { HazeToolError } from './failures.js';
6
+ function stableJsonStringify(value) {
7
+ if (Array.isArray(value))
8
+ return `[${value.map(stableJsonStringify).join(',')}]`;
9
+ if (value && typeof value === 'object') {
10
+ const entries = Object.entries(value)
11
+ .filter(([, entryValue]) => entryValue !== undefined)
12
+ .sort(([a], [b]) => a.localeCompare(b));
13
+ return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`).join(',')}}`;
14
+ }
15
+ return JSON.stringify(value) ?? 'undefined';
16
+ }
17
+ function toolCallKey(toolName, input) {
18
+ return `${toolName}:${stableJsonStringify(input)}`;
19
+ }
20
+ export const hazeToolContextSchema = z.custom(value => typeof value === 'object' && value !== null);
21
+ export function hazeContext(context) {
22
+ const value = typeof context.context === 'object' && context.context != null
23
+ ? context.context
24
+ : context.experimental_context;
25
+ return typeof value === 'object' && value != null
26
+ ? value
27
+ : undefined;
28
+ }
29
+ export function toolsContextFor(tools, context) {
30
+ const hazeToolNames = new Set(['listFiles', 'readFile', 'grep', 'replaceLines', 'writeFile', 'editFile', 'bash', 'fetch']);
31
+ return Object.fromEntries(Object.keys(tools).filter(name => hazeToolNames.has(name)).map(name => [name, context]));
32
+ }
33
+ /**
34
+ * Lazily load scoped CLAUDE.md/AGENTS.md files that apply to `filePath` and
35
+ * have not been surfaced yet this turn. Mutates the context's loaded-set so
36
+ * each file is only returned once.
37
+ */
38
+ export async function discoverScopedContext(filePath, context) {
39
+ const ctx = hazeContext(context);
40
+ const previousDiscovery = ctx?.scopedContextDiscovery;
41
+ let releaseDiscovery = () => undefined;
42
+ const currentDiscovery = new Promise(resolve => { releaseDiscovery = resolve; });
43
+ if (ctx)
44
+ ctx.scopedContextDiscovery = previousDiscovery ? previousDiscovery.catch(() => undefined).then(() => currentDiscovery) : currentDiscovery;
45
+ await previousDiscovery?.catch(() => undefined);
46
+ try {
47
+ const loaded = ctx?.loadedContextFilePaths ?? new Set();
48
+ const signatures = ctx?.loadedContextFileSignatures;
49
+ const files = await readScopedContextFilesForPath(filePath, { cwd: workspaceRoot(), alreadyLoadedPaths: loaded, alreadyLoadedSignatures: signatures, onContextFileRead: ctx?.onContextFileRead });
50
+ if (ctx && !ctx.loadedContextFilePaths)
51
+ ctx.loadedContextFilePaths = loaded;
52
+ for (const file of files) {
53
+ loaded.add(file.path);
54
+ if (file.signature)
55
+ signatures?.set(file.path, file.signature);
56
+ }
57
+ if (ctx && files.length > 0)
58
+ ctx.pendingContextFiles = [...(ctx.pendingContextFiles ?? []), ...files];
59
+ return files;
60
+ }
61
+ finally {
62
+ releaseDiscovery();
63
+ }
64
+ }
65
+ /** Attach discovered scoped instructions to a tool result, if any. */
66
+ export function withScopedContext(result, files) {
67
+ return files.length > 0 ? { ...result, applicableProjectInstructions: files } : result;
68
+ }
69
+ /**
70
+ * When scoped project instructions apply to a path being mutated, pause the
71
+ * mutation so the model can review them first. Returns a structured failure
72
+ * the tool yields directly (no file change).
73
+ */
74
+ export function scopedContextMutationStop(toolName, filePath, files) {
75
+ if (files.length === 0)
76
+ return undefined;
77
+ return {
78
+ ok: false,
79
+ toolName,
80
+ path: filePath,
81
+ error: `Scoped project instructions apply to ${filePath}: ${files.map(file => file.path).join(', ')}. Review them before mutating this path.`,
82
+ reasonCode: 'scoped_instructions_discovered',
83
+ recoverable: true,
84
+ suggestedNextStep: `Read the applicableProjectInstructions returned in this result, then retry ${toolName} only if the change follows those scoped instructions.`,
85
+ applicableProjectInstructions: files,
86
+ };
87
+ }
88
+ function isMutatingTool(toolName) {
89
+ return ['editFile', 'replaceLines', 'writeFile'].includes(toolName);
90
+ }
91
+ function isReadOnlyFileTool(toolName) {
92
+ return ['listFiles', 'readFile', 'grep'].includes(toolName);
93
+ }
94
+ // Read-only tools that participate in completed-call deduplication within a
95
+ // turn (no side effects). File tools + bash + fetch; fetch has no path and is
96
+ // network-side-effect-free for the agent's purposes.
97
+ function isDeduplicableReadOnlyTool(toolName) {
98
+ return isReadOnlyFileTool(toolName) || toolName === 'bash' || toolName === 'fetch';
99
+ }
100
+ /**
101
+ * Wrap a tool's execution with turn-scoped deduplication and edit-recovery:
102
+ * - skip concurrent mutations of the same path;
103
+ * - force a re-read before retrying an edit that just failed on a path;
104
+ * - skip identical completed read-only calls until a mutation occurs;
105
+ * - skip identical in-flight calls;
106
+ * - bump a mutation epoch on successful writes so read caches invalidate.
107
+ */
108
+ export async function runDedupedTool(toolName, input, context, execute) {
109
+ const ctx = hazeContext(context);
110
+ if (!ctx)
111
+ return execute();
112
+ ctx.inFlightToolCalls ??= new Map();
113
+ ctx.completedToolCalls ??= new Map();
114
+ ctx.failedMutationPaths ??= new Set();
115
+ ctx.failedMutationReasons ??= new Map();
116
+ ctx.pathsReadAfterFailedMutation ??= new Set();
117
+ ctx.inFlightMutationPaths ??= new Set();
118
+ ctx.mutationEpoch ??= 0;
119
+ const key = toolCallKey(toolName, input);
120
+ const pathForInput = toolInputField(input, 'path');
121
+ if (isMutatingTool(toolName) && pathForInput && ctx.inFlightMutationPaths.has(pathForInput)) {
122
+ return {
123
+ ok: true,
124
+ duplicateSkipped: true,
125
+ toolName,
126
+ 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.`,
127
+ };
128
+ }
129
+ if (isMutatingTool(toolName) && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput)) {
130
+ const reason = ctx.failedMutationReasons.get(pathForInput);
131
+ throw new HazeToolError(`Read ${pathForInput} before attempting another edit after the previous edit failure${reason ? ` (${reason})` : ''}.`, reason ?? 'io_error', { recoveryTool: 'readFile', recoveryInput: { path: pathForInput } });
132
+ }
133
+ const completedAt = ctx.completedToolCalls.get(key);
134
+ const readAfterFailedMutation = toolName === 'readFile' && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput);
135
+ if ((isDeduplicableReadOnlyTool(toolName)) && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
136
+ return {
137
+ ok: true,
138
+ duplicateSkipped: true,
139
+ toolName,
140
+ reason: toolName === 'bash'
141
+ ? 'Skipped duplicate bash command; no files changed since the previous run.'
142
+ : toolName === 'fetch'
143
+ ? 'Skipped duplicate fetch with identical URL; no files changed since the previous call.'
144
+ : 'Skipped duplicate read-only tool call with identical input; no files changed since the previous call.',
145
+ };
146
+ }
147
+ if (ctx.inFlightToolCalls.has(key)) {
148
+ return {
149
+ ok: true,
150
+ duplicateSkipped: true,
151
+ toolName,
152
+ reason: 'Skipped duplicate in-flight tool call with identical input.',
153
+ };
154
+ }
155
+ if (isMutatingTool(toolName) && pathForInput)
156
+ ctx.inFlightMutationPaths.add(pathForInput);
157
+ const promise = execute();
158
+ ctx.inFlightToolCalls.set(key, promise);
159
+ try {
160
+ const result = await promise;
161
+ if (isFailedToolOutput(result)) {
162
+ if (isMutatingTool(toolName) && pathForInput) {
163
+ ctx.failedMutationPaths.add(pathForInput);
164
+ const reasonCode = typeof result === 'object' && result != null && 'reasonCode' in result ? result.reasonCode : undefined;
165
+ ctx.failedMutationReasons.set(pathForInput, reasonCode);
166
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
167
+ }
168
+ return result;
169
+ }
170
+ if (toolName === 'readFile' && pathForInput)
171
+ ctx.pathsReadAfterFailedMutation.add(pathForInput);
172
+ if (isMutatingTool(toolName)) {
173
+ ctx.mutationEpoch += 1;
174
+ if (pathForInput) {
175
+ ctx.failedMutationPaths.delete(pathForInput);
176
+ ctx.failedMutationReasons.delete(pathForInput);
177
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
178
+ }
179
+ }
180
+ ctx.completedToolCalls.set(key, ctx.mutationEpoch);
181
+ return result;
182
+ }
183
+ catch (error) {
184
+ if (isMutatingTool(toolName) && pathForInput) {
185
+ ctx.failedMutationPaths.add(pathForInput);
186
+ ctx.failedMutationReasons.set(pathForInput, error instanceof HazeToolError ? error.reasonCode : undefined);
187
+ ctx.pathsReadAfterFailedMutation.delete(pathForInput);
188
+ }
189
+ throw error;
190
+ }
191
+ finally {
192
+ ctx.inFlightToolCalls.delete(key);
193
+ if (isMutatingTool(toolName) && pathForInput)
194
+ ctx.inFlightMutationPaths?.delete(pathForInput);
195
+ }
196
+ }
@@ -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
+ }>;
@@ -0,0 +1,27 @@
1
+ import { assertRealPathInsideWorkspace, assertWritablePathInsideWorkspace, resolveWorkspacePath } from '../../utils/path.js';
2
+ import { assertNotIgnored } from './fileToolShared.js';
3
+ import { discoverScopedContext, scopedContextMutationStop } from './toolContext.js';
4
+ export async function prepareWorkspaceExisting(filePath) {
5
+ const absolutePath = resolveWorkspacePath(filePath);
6
+ await assertRealPathInsideWorkspace(absolutePath, filePath);
7
+ return absolutePath;
8
+ }
9
+ export async function prepareWorkspaceRead(filePath, allowIgnored) {
10
+ const absolutePath = resolveWorkspacePath(filePath);
11
+ await assertNotIgnored(absolutePath, filePath, allowIgnored);
12
+ await assertRealPathInsideWorkspace(absolutePath, filePath);
13
+ return absolutePath;
14
+ }
15
+ export async function prepareWorkspaceMutation(toolName, filePath, allowIgnored, context) {
16
+ const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored);
17
+ const scopedContext = await discoverScopedContext(filePath, context);
18
+ const scopedStop = scopedContextMutationStop(toolName, filePath, scopedContext);
19
+ return { absolutePath, scopedContext, scopedStop };
20
+ }
21
+ export async function prepareWorkspaceWritePath(toolName, filePath, allowIgnored, context) {
22
+ const absolutePath = resolveWorkspacePath(filePath);
23
+ await assertNotIgnored(absolutePath, filePath, allowIgnored);
24
+ const scopedContext = await discoverScopedContext(filePath, context);
25
+ const scopedStop = scopedContextMutationStop(toolName, filePath, scopedContext);
26
+ return { absolutePath, scopedContext, scopedStop, assertExistingInsideWorkspace: async () => await assertRealPathInsideWorkspace(absolutePath, filePath), assertWritableInsideWorkspace: async () => await assertWritablePathInsideWorkspace(absolutePath, filePath) };
27
+ }
@@ -1,4 +1,4 @@
1
- import { type UrlValidation } from '../core/safety/urlGuard.js';
1
+ import { type UrlValidation, type DnsLookupFn } from '../core/safety/urlGuard.js';
2
2
  /**
3
3
  * Bounded HTTP fetch + content extraction for the `fetch` tool.
4
4
  *
@@ -19,7 +19,18 @@ export interface FetchOptions {
19
19
  maxRedirects?: number;
20
20
  signal?: AbortSignal;
21
21
  format?: 'auto' | 'text';
22
+ /** @internal custom DNS resolver forwarded to validateUrl (testing seam). */
23
+ lookup?: DnsLookupFn;
24
+ /** @internal transport override (testing seam); defaults to pinnedFetch. */
25
+ fetcher?: PinnedFetcher;
22
26
  }
27
+ /**
28
+ * Transport signature: fetch `url`, pinning the TCP connection to `pinnedIp`
29
+ * when set (hostname URL whose DNS was already resolved and validated by the
30
+ * caller). When `pinnedIp` is undefined (literal-IP URL), the transport falls
31
+ * back to the global fetch — no DNS-rebinding surface exists for a literal IP.
32
+ */
33
+ export type PinnedFetcher = (url: URL, pinnedIp: string | undefined, init: RequestInit) => Promise<Response>;
23
34
  export interface FetchResult {
24
35
  url: string;
25
36
  status: number;
@@ -47,6 +58,7 @@ export declare function extractContent(html: string, url: string): Promise<{
47
58
  content: string;
48
59
  title?: string;
49
60
  }>;
61
+ export declare function pinnedFetch(url: URL, pinnedIp: string | undefined, init: RequestInit): Promise<Response>;
50
62
  /**
51
63
  * Fetch a public http(s) URL and return readable content.
52
64
  *
@@ -1,8 +1,11 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import { Readable } from 'node:stream';
1
4
  import { validateUrl } from '../core/safety/urlGuard.js';
2
5
  const DEFAULT_TIMEOUT_MS = 30_000;
3
6
  const DEFAULT_MAX_BYTES = 2_000_000;
4
7
  const DEFAULT_MAX_REDIRECTS = 5;
5
- const USER_AGENT = 'Haze/0.5 (+https://github.com/DenizOkcu/haze)';
8
+ const USER_AGENT = 'haze/0.5 (+https://github.com/DenizOkcu/haze)';
6
9
  /** Error thrown when a URL is rejected by the SSRF guard. */
7
10
  export class BlockedUrlError extends Error {
8
11
  reasonCode;
@@ -68,36 +71,49 @@ function classifyContentType(contentType) {
68
71
  return 'html';
69
72
  return 'text';
70
73
  }
74
+ function decodeValidUtf8Prefix(buffer) {
75
+ for (let end = buffer.byteLength; end >= 0; end--) {
76
+ try {
77
+ return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, end));
78
+ }
79
+ catch {
80
+ // Back up until we land on a UTF-8 character boundary.
81
+ }
82
+ }
83
+ return '';
84
+ }
85
+ function truncateUtf8Bytes(text, maxBytes) {
86
+ const buffer = Buffer.from(text, 'utf8');
87
+ if (buffer.byteLength <= maxBytes)
88
+ return { text, bytes: buffer.byteLength, truncated: false };
89
+ return { text: decodeValidUtf8Prefix(buffer.subarray(0, maxBytes)), bytes: maxBytes, truncated: true };
90
+ }
71
91
  async function readBodyCapped(response, maxBytes, abortController) {
72
92
  const body = response.body;
73
93
  if (body == null || typeof body.getReader !== 'function') {
74
94
  // No streamable body; read as text once and cap.
75
- const text = await response.text();
76
- const bytes = Buffer.byteLength(text, 'utf8');
77
- if (bytes > maxBytes) {
78
- return { text: text.slice(0, maxBytes), bytes: maxBytes, truncated: true };
79
- }
80
- return { text, bytes, truncated: false };
95
+ return truncateUtf8Bytes(await response.text(), maxBytes);
81
96
  }
82
97
  const reader = body.getReader();
83
- const decoder = new TextDecoder('utf-8');
84
- let text = '';
98
+ const chunks = [];
85
99
  let received = 0;
100
+ let kept = 0;
86
101
  let truncated = false;
87
102
  try {
88
- // Stream with a byte counter; stop and mark truncated once the ceiling is hit.
103
+ // Stream with a byte counter; keep only bytes up to the ceiling and stop once hit.
89
104
  while (true) {
90
105
  const { done, value } = await reader.read();
91
106
  if (done)
92
107
  break;
93
- const chunkBytes = value.byteLength;
94
- received += chunkBytes;
108
+ const chunk = Buffer.from(value);
109
+ received += chunk.byteLength;
110
+ const remaining = Math.max(0, maxBytes - kept);
111
+ if (remaining > 0) {
112
+ const slice = chunk.subarray(0, Math.min(remaining, chunk.byteLength));
113
+ chunks.push(slice);
114
+ kept += slice.byteLength;
115
+ }
95
116
  if (received > maxBytes) {
96
- const already = received - chunkBytes;
97
- const remaining = Math.max(0, maxBytes - already);
98
- if (remaining > 0)
99
- text += decoder.decode(value.slice(0, remaining), { stream: true });
100
- text += decoder.decode();
101
117
  truncated = true;
102
118
  try {
103
119
  reader.cancel();
@@ -105,10 +121,7 @@ async function readBodyCapped(response, maxBytes, abortController) {
105
121
  catch { /* ignore */ }
106
122
  break;
107
123
  }
108
- text += decoder.decode(value, { stream: true });
109
124
  }
110
- if (!truncated)
111
- text += decoder.decode();
112
125
  }
113
126
  finally {
114
127
  try {
@@ -119,7 +132,81 @@ async function readBodyCapped(response, maxBytes, abortController) {
119
132
  if (truncated && !abortController.signal.aborted)
120
133
  abortController.abort();
121
134
  }
122
- return { text, bytes: Math.min(received, maxBytes), truncated };
135
+ return { text: decodeValidUtf8Prefix(Buffer.concat(chunks)), bytes: Math.min(received, maxBytes), truncated };
136
+ }
137
+ /**
138
+ * Perform an HTTP(S) request with the TCP connection pinned to `pinnedIp`.
139
+ *
140
+ * This closes the DNS-rebinding TOCTOU: `validateUrl` resolved the hostname and
141
+ * verified every address is public, but the global `fetch` would re-resolve the
142
+ * hostname at connect time — an attacker-controlled DNS server can return a
143
+ * public IP for the validation lookup and a private/internal IP for the connect
144
+ * lookup. By connecting directly to the already-validated IP (`hostname:
145
+ * pinnedIp`) while keeping the original `Host` header and TLS `servername`
146
+ * (`url.hostname`), the connection target is fixed to what we validated, with no
147
+ * second DNS lookup. TLS certificate verification still runs against the original
148
+ * hostname via `servername`, so pinning does not weaken identity checks.
149
+ *
150
+ * Literal-IP URLs carry no DNS-rebinding surface (`pinnedIp` is undefined), so
151
+ * they fall through to the global `fetch` — which also keeps the test mocks that
152
+ * stub `globalThis.fetch` working for that path.
153
+ */
154
+ /**
155
+ * Coerce a RequestInit headers value into a plain string record. Keeps the
156
+ * transport defensive against `Headers`/tuple/array inputs instead of blindly
157
+ * casting (the fetch tool only ever passes a plain object, but be safe).
158
+ */
159
+ function normalizeHeaders(input) {
160
+ if (!input)
161
+ return {};
162
+ if (Array.isArray(input)) {
163
+ const out = {};
164
+ for (const pair of input) {
165
+ if (Array.isArray(pair) && pair.length === 2)
166
+ out[String(pair[0])] = String(pair[1]);
167
+ }
168
+ return out;
169
+ }
170
+ if (input instanceof Headers) {
171
+ const out = {};
172
+ input.forEach((value, key) => {
173
+ out[key] = value;
174
+ });
175
+ return out;
176
+ }
177
+ return { ...input };
178
+ }
179
+ export async function pinnedFetch(url, pinnedIp, init) {
180
+ if (!pinnedIp)
181
+ return globalThis.fetch(url, init);
182
+ const isTls = url.protocol === 'https:';
183
+ const port = url.port ? Number(url.port) : (isTls ? 443 : 80);
184
+ const path = url.pathname + url.search;
185
+ const headers = normalizeHeaders(init.headers);
186
+ // Preserve the original host in the request line; node would otherwise send
187
+ // the pinned IP as the Host header.
188
+ headers.host = url.host;
189
+ const lib = isTls ? https : http;
190
+ return new Promise((resolve, reject) => {
191
+ const req = lib.request({
192
+ method: init.method ?? 'GET',
193
+ hostname: pinnedIp,
194
+ port,
195
+ path,
196
+ headers,
197
+ ...(isTls ? { servername: url.hostname, rejectUnauthorized: true } : {}),
198
+ signal: init.signal,
199
+ }, (res) => {
200
+ const body = Readable.toWeb(res);
201
+ resolve(new Response(body, {
202
+ status: res.statusCode ?? 200,
203
+ statusText: res.statusMessage ?? '',
204
+ headers: res.headers,
205
+ }));
206
+ });
207
+ req.on('error', reject);
208
+ req.end();
209
+ });
123
210
  }
124
211
  /**
125
212
  * Fetch a public http(s) URL and return readable content.
@@ -132,10 +219,16 @@ export async function fetchUrlContent(input, opts) {
132
219
  const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
133
220
  const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
134
221
  const maxRedirects = opts?.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
135
- const initial = await validateUrl(input);
222
+ const fetcher = opts?.fetcher ?? pinnedFetch;
223
+ const validateOpts = opts?.lookup ? { lookup: opts.lookup } : undefined;
224
+ const initial = await validateUrl(input, validateOpts);
136
225
  if (!initial.ok)
137
226
  throw new BlockedUrlError(initial);
138
227
  let currentUrl = initial.url;
228
+ // Pin the connection to the address we just validated — the validated IP
229
+ // flows from validateUrl straight into the transport, with no second DNS
230
+ // lookup in between (that gap was the rebinding window).
231
+ let currentPinnedIp = initial.resolvedAddresses?.[0];
139
232
  let response;
140
233
  const visited = [];
141
234
  for (let hop = 0; hop <= maxRedirects; hop++) {
@@ -150,7 +243,7 @@ export async function fetchUrlContent(input, opts) {
150
243
  }
151
244
  const combined = AbortSignal.any([timeoutSignal, abortController.signal]);
152
245
  try {
153
- response = await fetch(currentUrl, {
246
+ response = await fetcher(currentUrl, currentPinnedIp, {
154
247
  redirect: 'manual',
155
248
  signal: combined,
156
249
  headers: { accept: 'text/html,application/xhtml+xml,application/json,text/plain;q=0.5,*/*;q=0.1', 'user-agent': USER_AGENT },
@@ -189,7 +282,7 @@ export async function fetchUrlContent(input, opts) {
189
282
  if (nextUrl.protocol !== 'http:' && nextUrl.protocol !== 'https:') {
190
283
  throw new BlockedUrlError({ ok: false, reasonCode: 'blocked_scheme', reason: `Redirect to non-http(s) scheme '${nextUrl.protocol}' is blocked.` });
191
284
  }
192
- const redirectValidation = await validateUrl(nextUrl.href);
285
+ const redirectValidation = await validateUrl(nextUrl.href, validateOpts);
193
286
  if (!redirectValidation.ok)
194
287
  throw new BlockedUrlError(redirectValidation);
195
288
  if (visited.includes(nextUrl.href)) {
@@ -197,16 +290,17 @@ export async function fetchUrlContent(input, opts) {
197
290
  }
198
291
  visited.push(currentUrl.href);
199
292
  currentUrl = nextUrl;
293
+ currentPinnedIp = redirectValidation.resolvedAddresses?.[0];
200
294
  continue;
201
295
  }
202
296
  break;
203
297
  }
204
298
  if (!response)
205
299
  throw new Error(`No response fetching ${input}`);
206
- // Belt-and-suspenders: re-validate the final URL after redirects.
207
- const finalValidation = await validateUrl(currentUrl.href);
208
- if (!finalValidation.ok)
209
- throw new BlockedUrlError(finalValidation);
300
+ // No post-fetch re-validation: every hop (including the final response) was
301
+ // validated and connection-pinned at fetch time. Re-resolving the final URL
302
+ // here would only reopen a rebinding race against a connection that already
303
+ // used a safe, pinned IP.
210
304
  const abortController = new AbortController();
211
305
  const onAbort = () => abortController.abort();
212
306
  if (opts?.signal) {
@@ -26,6 +26,7 @@ declare function withSkillName(content: string, name: string): string;
26
26
  declare function normalizeSkillDescription(description: string): string;
27
27
  declare function withSkillDescription(content: string, description: string): string;
28
28
  declare function parseGeneratedSkill(text: string, description: string): GeneratedSkill;
29
+ declare function assertSafeGeneratedFile(filePath: string): string;
29
30
  export declare function createSkill(input: CreateSkillInput): Promise<{
30
31
  name: string;
31
32
  dir: string;
@@ -41,5 +42,7 @@ export declare const internals: {
41
42
  withSkillDescription: typeof withSkillDescription;
42
43
  normalizeSkillDescription: typeof normalizeSkillDescription;
43
44
  toSkillDirName: typeof toSkillDirName;
45
+ slug: typeof slug;
46
+ assertSafeGeneratedFile: typeof assertSafeGeneratedFile;
44
47
  };
45
48
  export {};
@@ -21,12 +21,12 @@ const STANDARD_SKILL_REQUIREMENTS = `
21
21
  `;
22
22
  const SKILL_CREATOR_SKILL = `---
23
23
  name: skill-creator
24
- description: Use when the user asks Haze to create a new skill from a natural-language description.
24
+ description: Use when the user asks haze to create a new skill from a natural-language description.
25
25
  ---
26
26
 
27
- You create predictable, high-quality Haze skills.
27
+ You create predictable, high-quality haze skills.
28
28
 
29
- A Haze skill is a directory in ~/.haze/skills containing SKILL.md and optional referenced files.
29
+ A haze skill is a directory in ~/.haze/skills containing SKILL.md and optional referenced files.
30
30
  SKILL.md must be Markdown with YAML frontmatter, followed by a role and focused prompt:
31
31
 
32
32
  ---
@@ -45,7 +45,7 @@ The body must be a deterministic operating procedure, not generic advice.
45
45
  Keep skills simple, short, and practical: prefer the fewest commands and sections that reliably complete the workflow for a professional user.
46
46
  Avoid exhaustive checklists, rigid citation requirements, or heavyweight output formats unless the user's request truly requires them.
47
47
  Additional files are allowed only when SKILL.md explicitly references them with relative paths.
48
- Skills do not execute code. They teach Haze how to behave for a workflow.
48
+ Skills do not execute code. They teach haze how to behave for a workflow.
49
49
 
50
50
  Every skill you create must include, in this order:
51
51
  - YAML frontmatter.
@@ -179,12 +179,12 @@ async function generateSkill(input) {
179
179
  const role = input.role?.trim() || DEFAULT_SKILL_ROLE;
180
180
  const result = await generateObject({
181
181
  model: activeModel,
182
- system: SKILL_CREATOR_SKILL,
182
+ instructions: SKILL_CREATOR_SKILL,
183
183
  schema: generatedSkillSchema,
184
184
  schemaName: 'GeneratedHazeSkill',
185
- schemaDescription: 'A generated Haze Markdown skill and optional referenced files.',
185
+ schemaDescription: 'A generated haze Markdown skill and optional referenced files.',
186
186
  prompt: [
187
- 'A user is creating a Haze skill via a 3-step wizard. They have already chosen the NAME and the ROLE; you do NOT choose those.',
187
+ 'A user is creating a haze skill via a 3-step wizard. They have already chosen the NAME and the ROLE; you do NOT choose those.',
188
188
  '',
189
189
  `User-chosen skill name (use VERBATIM in frontmatter, do not rename): ${input.name}`,
190
190
  `User-chosen Role text (paste VERBATIM into the # Role section): ${role}`,
@@ -273,4 +273,4 @@ export async function createSkill(input) {
273
273
  }
274
274
  return { name: finalName, dir, file: skillFile };
275
275
  }
276
- export const internals = { SKILL_CREATOR_SKILL, STANDARD_SKILL_REQUIREMENTS, parseGeneratedSkill, fallbackSkill, withStandardRequirements, withSkillName, withSkillDescription, normalizeSkillDescription, toSkillDirName };
276
+ export const internals = { SKILL_CREATOR_SKILL, STANDARD_SKILL_REQUIREMENTS, parseGeneratedSkill, fallbackSkill, withStandardRequirements, withSkillName, withSkillDescription, normalizeSkillDescription, toSkillDirName, slug, assertSafeGeneratedFile };