@denizokcu/haze 0.10.0 → 0.11.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 (169) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +66 -25
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/contextReport.js +2 -0
  9. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  10. package/dist/cli/chat/liveRegion.d.ts +25 -0
  11. package/dist/cli/chat/liveRegion.js +48 -0
  12. package/dist/cli/chat/messages.d.ts +33 -2
  13. package/dist/cli/chat/messages.js +216 -33
  14. package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
  15. package/dist/cli/chat/sessionLifecycle.js +64 -14
  16. package/dist/cli/chat/sessionRecorder.js +75 -7
  17. package/dist/cli/chat/startupInfo.d.ts +0 -1
  18. package/dist/cli/chat/startupInfo.js +11 -15
  19. package/dist/cli/chat/wizardDispatch.js +111 -12
  20. package/dist/cli/commands/chat.d.ts +5 -0
  21. package/dist/cli/commands/chat.js +203 -101
  22. package/dist/cli/commands/commands.d.ts +2 -0
  23. package/dist/cli/commands/commands.js +10 -5
  24. package/dist/cli/commands/doctor.d.ts +19 -0
  25. package/dist/cli/commands/doctor.js +76 -0
  26. package/dist/cli/commands/formatters.js +2 -0
  27. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  28. package/dist/cli/commands/ndjsonSink.js +38 -0
  29. package/dist/cli/commands/providerWizard.d.ts +9 -2
  30. package/dist/cli/commands/providerWizard.js +37 -4
  31. package/dist/cli/commands/runCommand.d.ts +3 -0
  32. package/dist/cli/commands/runCommand.js +117 -11
  33. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  34. package/dist/cli/commands/streaming/abortCause.js +16 -0
  35. package/dist/cli/commands/streaming/assistantText.js +9 -2
  36. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  38. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  39. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  40. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  41. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  42. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
  43. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  44. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  45. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  46. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  47. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  48. package/dist/cli/commands/streaming.d.ts +70 -3
  49. package/dist/cli/commands/streaming.js +491 -77
  50. package/dist/cli/commands/wizardActions.d.ts +1 -0
  51. package/dist/cli/commands/wizardActions.js +1 -0
  52. package/dist/cli/commands/wizardPrompts.js +7 -1
  53. package/dist/cli/commands/wizardSuggestions.js +5 -3
  54. package/dist/cli/index.js +68 -22
  55. package/dist/cli/terminalTitle.js +1 -1
  56. package/dist/config/modelDiscovery.d.ts +51 -0
  57. package/dist/config/modelDiscovery.js +164 -1
  58. package/dist/config/privateStorage.js +28 -2
  59. package/dist/config/providerAuth.d.ts +14 -0
  60. package/dist/config/providerAuth.js +49 -0
  61. package/dist/config/providerPresets.d.ts +39 -7
  62. package/dist/config/providerPresets.js +371 -100
  63. package/dist/config/providers.js +2 -0
  64. package/dist/config/settings.d.ts +36 -0
  65. package/dist/config/settings.js +9 -0
  66. package/dist/core/agent/budgets.d.ts +10 -0
  67. package/dist/core/agent/budgets.js +10 -0
  68. package/dist/core/agent/compaction.d.ts +38 -0
  69. package/dist/core/agent/compaction.js +92 -17
  70. package/dist/core/agent/completionController.d.ts +230 -0
  71. package/dist/core/agent/completionController.js +287 -0
  72. package/dist/core/agent/contextBudget.d.ts +38 -0
  73. package/dist/core/agent/contextBudget.js +60 -7
  74. package/dist/core/agent/events.d.ts +74 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  76. package/dist/core/agent/reasoningPolicy.js +27 -0
  77. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  78. package/dist/core/agent/toolCapabilities.js +58 -0
  79. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  80. package/dist/core/agent/toolExecutionBudget.js +49 -0
  81. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  82. package/dist/core/agent/toolOutputStore.js +10 -10
  83. package/dist/core/agent/toolResults.d.ts +12 -0
  84. package/dist/core/agent/toolResults.js +38 -0
  85. package/dist/core/agent/turnBudget.d.ts +35 -0
  86. package/dist/core/agent/turnBudget.js +27 -0
  87. package/dist/core/agent/turnPolicy.d.ts +11 -0
  88. package/dist/core/agent/turnPolicy.js +19 -0
  89. package/dist/core/agent/workState.d.ts +75 -0
  90. package/dist/core/agent/workState.js +120 -9
  91. package/dist/core/deadline.d.ts +33 -0
  92. package/dist/core/deadline.js +74 -0
  93. package/dist/core/goal/completionPolicy.d.ts +27 -0
  94. package/dist/core/goal/completionPolicy.js +37 -1
  95. package/dist/core/limits/byteBudgets.d.ts +2 -0
  96. package/dist/core/limits/byteBudgets.js +2 -0
  97. package/dist/core/limits/textBudgets.d.ts +2 -0
  98. package/dist/core/limits/textBudgets.js +2 -0
  99. package/dist/core/log/llmLog.js +7 -0
  100. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  101. package/dist/core/persistence/orderedFileWriter.js +16 -2
  102. package/dist/core/process/backgroundRegistry.js +8 -7
  103. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  104. package/dist/core/process/runBoundedProcess.js +15 -6
  105. package/dist/core/safety/missingExecutable.d.ts +42 -0
  106. package/dist/core/safety/missingExecutable.js +77 -0
  107. package/dist/core/session/sessionStore.d.ts +37 -0
  108. package/dist/core/session/sessionStore.js +215 -51
  109. package/dist/core/subagent/contracts.d.ts +4 -0
  110. package/dist/core/subagent/contracts.js +1 -0
  111. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  112. package/dist/core/subagent/subagentCoordinator.js +32 -2
  113. package/dist/core/subagent/subagentRunner.js +17 -37
  114. package/dist/llm/client.d.ts +17 -1
  115. package/dist/llm/client.js +82 -14
  116. package/dist/llm/hazeTools.d.ts +554 -80
  117. package/dist/llm/hazeTools.js +103 -24
  118. package/dist/llm/lsp.d.ts +24 -4
  119. package/dist/llm/lsp.js +72 -11
  120. package/dist/llm/lspTools.d.ts +2366 -0
  121. package/dist/llm/lspTools.js +87 -79
  122. package/dist/llm/openaiCodex.d.ts +3 -0
  123. package/dist/llm/openaiCodex.js +47 -0
  124. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  125. package/dist/llm/openaiCodexOAuth.js +214 -0
  126. package/dist/llm/requestContext.d.ts +3 -0
  127. package/dist/llm/requestContext.js +7 -4
  128. package/dist/llm/systemPrompt.d.ts +11 -0
  129. package/dist/llm/systemPrompt.js +12 -6
  130. package/dist/llm/toolResultTypes.d.ts +8 -1
  131. package/dist/llm/tools/bashTool.d.ts +48 -16
  132. package/dist/llm/tools/bashTool.js +5 -0
  133. package/dist/llm/tools/editMatch.d.ts +14 -0
  134. package/dist/llm/tools/editMatch.js +72 -0
  135. package/dist/llm/tools/failures.d.ts +2 -0
  136. package/dist/llm/tools/failures.js +1 -0
  137. package/dist/llm/tools/fetchTool.d.ts +16 -0
  138. package/dist/llm/tools/fileToolShared.d.ts +4 -3
  139. package/dist/llm/tools/fileToolShared.js +16 -21
  140. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  141. package/dist/llm/tools/gitIgnore.js +129 -0
  142. package/dist/llm/tools/readRecovery.d.ts +10 -0
  143. package/dist/llm/tools/readRecovery.js +135 -0
  144. package/dist/llm/tools/toolContext.d.ts +1 -1
  145. package/dist/llm/tools/toolContext.js +61 -32
  146. package/dist/llm/webFetch.d.ts +17 -0
  147. package/dist/llm/webFetch.js +64 -97
  148. package/dist/ui/codeHighlight.d.ts +4 -0
  149. package/dist/ui/codeHighlight.js +31 -0
  150. package/dist/ui/components/Header.d.ts +1 -1
  151. package/dist/ui/components/MarkdownText.d.ts +16 -2
  152. package/dist/ui/components/MarkdownText.js +244 -34
  153. package/dist/ui/components/TextInput.d.ts +8 -1
  154. package/dist/ui/components/TextInput.js +6 -2
  155. package/dist/ui/theme.d.ts +4 -3
  156. package/dist/ui/theme.js +5 -4
  157. package/dist/utils/buildInfo.d.ts +104 -0
  158. package/dist/utils/buildInfo.js +253 -0
  159. package/dist/utils/fs.d.ts +9 -0
  160. package/dist/utils/fs.js +87 -25
  161. package/dist/utils/openPath.d.ts +2 -2
  162. package/dist/utils/openPath.js +19 -6
  163. package/dist/utils/path.d.ts +2 -0
  164. package/dist/utils/path.js +5 -1
  165. package/dist/utils/utf8.d.ts +22 -0
  166. package/dist/utils/utf8.js +54 -0
  167. package/dist/utils/version.d.ts +9 -3
  168. package/dist/utils/version.js +28 -2
  169. package/package.json +24 -19
@@ -1,4 +1,66 @@
1
+ import { isValidationSummary } from '../../llm/toolResultTypes.js';
1
2
  import { toolInputField, toolOutputOk } from './toolResults.js';
3
+ /** Request intents where a missing validation is itself meaningful evidence. */
4
+ export function intentExpectsValidation(intent) {
5
+ return intent === 'implement' || intent === 'fix' || intent === 'test';
6
+ }
7
+ /** Upper bound for parsed task counts; anything larger is treated as malformed. */
8
+ const TASK_COUNT_LIMIT = 10_000;
9
+ function boundedTaskCount(value) {
10
+ if (typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= TASK_COUNT_LIMIT)
11
+ return value;
12
+ if (typeof value === 'string' && /^(0|[1-9]\d{0,4})$/.test(value))
13
+ return Number(value);
14
+ return undefined;
15
+ }
16
+ /**
17
+ * Extract bounded task counts from a successful `writeTasks` structured result.
18
+ * Parses only numeric counts (`taskCount`, `counts.pending/in_progress/completed`),
19
+ * never titles or raw output. A non-empty list without a fully valid counts
20
+ * breakdown is ignored (rather than guessed) so partial shapes stay inert.
21
+ */
22
+ export function taskProgressFromOutput(output, revision) {
23
+ if (typeof output !== 'object' || output == null)
24
+ return undefined;
25
+ const candidate = output;
26
+ if (candidate.ok !== true)
27
+ return undefined;
28
+ const total = boundedTaskCount(candidate.taskCount);
29
+ if (total === undefined)
30
+ return undefined;
31
+ if (total === 0)
32
+ return { total: 0, pending: 0, inProgress: 0, completed: 0, revision };
33
+ if (typeof candidate.counts !== 'object' || candidate.counts === null)
34
+ return undefined;
35
+ const counts = candidate.counts;
36
+ const pending = boundedTaskCount(counts.pending);
37
+ const inProgress = boundedTaskCount(counts.in_progress);
38
+ const completed = boundedTaskCount(counts.completed);
39
+ if (pending === undefined || inProgress === undefined || completed === undefined)
40
+ return undefined;
41
+ return { total, pending, inProgress, completed, revision };
42
+ }
43
+ /**
44
+ * Seed a fresh per-turn work state with cumulative evidence from earlier
45
+ * physical turns of the same logical goal, so a new turn cannot complete while
46
+ * previously-declared tasks remain or previously-made edits still lack fresh
47
+ * validation. Seq baselines keep `deriveValidationOutcome` truthful across the
48
+ * boundary: a carried `stale`/`absent` outcome keeps demanding validation, a
49
+ * carried `passed`/`failed` outcome stands until this turn mutates or validates.
50
+ */
51
+ export function seedCarriedGoalEvidence(state, carried) {
52
+ if (carried.taskProgress && carried.taskProgress.total > 0) {
53
+ state.taskProgress = { ...carried.taskProgress, revision: 1 };
54
+ }
55
+ if (carried.mutationCount > 0) {
56
+ state.mutationCount = carried.mutationCount;
57
+ state.mutationSeq = 1;
58
+ }
59
+ if (carried.validationOutcome === 'passed' || carried.validationOutcome === 'failed') {
60
+ state.validationSeq = 1;
61
+ state.carriedValidation = carried.validationOutcome === 'passed' ? { status: 'passed' } : { status: 'failed' };
62
+ }
63
+ }
2
64
  function upsertFile(state, path, action, note) {
3
65
  const existing = state.files.find(file => file.path === path);
4
66
  if (existing) {
@@ -25,18 +87,25 @@ function outputSummary(output) {
25
87
  return `exit ${String(output.code)}`;
26
88
  return '';
27
89
  }
28
- function upsertValidation(state, command, status, summary) {
90
+ function upsertValidation(state, command, status, summary, kind) {
29
91
  const existing = state.validations.find(validation => validation.command === command);
30
92
  if (existing)
31
- Object.assign(existing, { status, summary });
93
+ Object.assign(existing, { status, summary, ...(kind ? { kind } : {}) });
32
94
  else
33
- state.validations.push({ command, status, summary });
95
+ state.validations.push({ command, status, summary, ...(kind ? { kind } : {}) });
34
96
  const existingCommand = state.validationCommands.find(item => item.command === command);
35
97
  if (existingCommand)
36
98
  existingCommand.status = status;
37
99
  else
38
100
  state.validationCommands.push({ command, status });
39
101
  }
102
+ /** Extract a classifier-confirmed validation summary from a tool output, if any. */
103
+ export function validationSummaryFromOutput(output) {
104
+ if (typeof output !== 'object' || output == null)
105
+ return undefined;
106
+ const candidate = output.validationSummary;
107
+ return isValidationSummary(candidate) ? candidate : undefined;
108
+ }
40
109
  export function createWorkState(goal, intent, successCriteria, now = Date.now()) {
41
110
  return {
42
111
  id: `goal-${now}-${Math.random().toString(36).slice(2)}`,
@@ -51,6 +120,9 @@ export function createWorkState(goal, intent, successCriteria, now = Date.now())
51
120
  touchedFiles: [],
52
121
  validations: [],
53
122
  validationCommands: [],
123
+ mutationCount: 0,
124
+ mutationSeq: 0,
125
+ validationSeq: 0,
54
126
  blockers: [],
55
127
  pending: [],
56
128
  status: 'active',
@@ -64,6 +136,9 @@ export function observeWorkToolEvent(state, event, now = Date.now()) {
64
136
  return state;
65
137
  const ok = toolOutputOk(event.output, event.success);
66
138
  const path = toolInputField(event.input, 'path');
139
+ // Monotonic turn-wide clock. mutationSeq/validationSeq snapshot this value so
140
+ // a validation that predates the latest mutation can be marked stale.
141
+ const seq = state.revision + 1;
67
142
  if (ok && path && ['listFiles', 'readFile', 'grep'].includes(event.toolName)) {
68
143
  if (event.toolName === 'readFile')
69
144
  upsertFile(state, path, 'read');
@@ -77,28 +152,64 @@ export function observeWorkToolEvent(state, event, now = Date.now()) {
77
152
  state.phase = 'editing';
78
153
  state.lastProgressAt = now;
79
154
  state.blockers = state.blockers.filter(blocker => !blocker.includes(path));
155
+ state.mutationCount += 1;
156
+ state.mutationSeq = seq;
80
157
  }
81
158
  else {
82
159
  state.blockers = [...new Set([...state.blockers, `Edit failed for ${path}: ${outputSummary(event.output) || 'fresh read required'}`])];
83
160
  state.nextAction = `Read ${path}, then retry the edit with current content.`;
84
161
  }
85
162
  }
163
+ // Only a classifier-confirmed bash command is a validation step. An arbitrary
164
+ // shell call (inspection, mkdir, echo) is process work, not validation; the
165
+ // bash tool embeds a `validationSummary` exactly when the classifier says so.
86
166
  if (event.toolName === 'bash') {
87
167
  const command = toolInputField(event.input, 'command');
88
- if (command) {
89
- const status = ok ? 'passed' : 'failed';
90
- const summary = outputSummary(event.output);
91
- upsertValidation(state, command, status, summary);
168
+ const summary = validationSummaryFromOutput(event.output);
169
+ if (command && summary) {
170
+ const status = summary.status === 'passed' ? 'passed' : 'failed';
171
+ upsertValidation(state, command, status, summary.summaryText, summary.kind);
172
+ state.validationSeq = seq;
92
173
  state.phase = 'validating';
93
174
  state.lastProgressAt = now;
94
- if (!ok) {
175
+ if (status === 'failed') {
95
176
  state.blockers = [...new Set([...state.blockers, `Validation failed: ${command}`])];
96
177
  }
97
178
  }
98
179
  }
99
- state.revision += 1;
180
+ // Task-list coordination: a successful writeTasks result records bounded
181
+ // current-turn task counts as completion evidence. It is not a file mutation,
182
+ // and a failed call leaves prior evidence untouched.
183
+ if (ok && event.toolName === 'writeTasks') {
184
+ const progress = taskProgressFromOutput(event.output, seq);
185
+ if (progress) {
186
+ state.taskProgress = progress;
187
+ state.lastProgressAt = now;
188
+ }
189
+ }
190
+ state.revision = seq;
100
191
  return state;
101
192
  }
193
+ /**
194
+ * Derive the bounded validation outcome for completion evidence.
195
+ * See `ValidationOutcome` for the contract. Honors mutation/validation
196
+ * ordering so a result that predates the latest mutation is `stale`.
197
+ */
198
+ export function deriveValidationOutcome(state) {
199
+ const hasValidation = state.validationSeq > 0;
200
+ if (!hasValidation) {
201
+ return intentExpectsValidation(state.normalizedIntent) ? 'absent' : 'not_applicable';
202
+ }
203
+ // A validation is stale when a mutation happened after it. `mutationSeq === 0`
204
+ // means no mutation occurred (e.g. a pure test/run request), so the latest
205
+ // validation stands on its own. With no validation this turn, a carried
206
+ // outcome from an earlier physical turn of the same logical goal stands in.
207
+ const stale = state.mutationSeq > 0 && state.validationSeq < state.mutationSeq;
208
+ if (stale)
209
+ return 'stale';
210
+ const latest = state.validations.at(-1) ?? state.carriedValidation;
211
+ return latest?.status === 'passed' ? 'passed' : 'failed';
212
+ }
102
213
  export function workStatePrompt(state) {
103
214
  return `<work_state>\n${JSON.stringify(state)}\n</work_state>`;
104
215
  }
@@ -0,0 +1,33 @@
1
+ export declare const TOOL_DEADLINE_EXCEEDED = "__hazeToolDeadlineExceeded";
2
+ export interface ToolDeadlineResult {
3
+ ok: false;
4
+ [TOOL_DEADLINE_EXCEEDED]: true;
5
+ error: string;
6
+ }
7
+ /** True when a tool result is the structured "deadline exceeded" placeholder. */
8
+ export declare function isToolDeadlineExceeded(output: unknown): boolean;
9
+ /**
10
+ * Run an underlying tool `execute` under a deadline. The wrapper resolves
11
+ * promptly when the deadline (or an optional parent abort signal) fires, even
12
+ * if the underlying work ignores cancellation. The still-pending work is
13
+ * quarantined so its eventual settlement cannot produce an unhandled rejection
14
+ * or mutate caller state (RH-004).
15
+ *
16
+ * - Normal completion → resolves with the underlying value.
17
+ * - Underlying rejection → rejects with that error (let the SDK classify it).
18
+ * - Deadline / parent abort → resolves with a structured bounded failure.
19
+ */
20
+ export declare function withToolDeadline(execute: () => Promise<unknown>, timeoutMs: number, signal?: AbortSignal): Promise<unknown>;
21
+ /**
22
+ * Create a clearable absolute deadline that fires `onTimeout` once after
23
+ * `timeoutMs`, unless `clear()` is called first. An already-aborted parent
24
+ * signal fires immediately. Used for the absolute main-turn bound (RH-004).
25
+ */
26
+ export interface AbsoluteDeadline {
27
+ clear: () => void;
28
+ }
29
+ export declare function createAbsoluteDeadline(input: {
30
+ timeoutMs: number;
31
+ signal?: AbortSignal;
32
+ onTimeout: () => void;
33
+ }): AbsoluteDeadline;
@@ -0,0 +1,74 @@
1
+ export const TOOL_DEADLINE_EXCEEDED = '__hazeToolDeadlineExceeded';
2
+ /** True when a tool result is the structured "deadline exceeded" placeholder. */
3
+ export function isToolDeadlineExceeded(output) {
4
+ return typeof output === 'object' && output !== null && TOOL_DEADLINE_EXCEEDED in output;
5
+ }
6
+ /**
7
+ * Run an underlying tool `execute` under a deadline. The wrapper resolves
8
+ * promptly when the deadline (or an optional parent abort signal) fires, even
9
+ * if the underlying work ignores cancellation. The still-pending work is
10
+ * quarantined so its eventual settlement cannot produce an unhandled rejection
11
+ * or mutate caller state (RH-004).
12
+ *
13
+ * - Normal completion → resolves with the underlying value.
14
+ * - Underlying rejection → rejects with that error (let the SDK classify it).
15
+ * - Deadline / parent abort → resolves with a structured bounded failure.
16
+ */
17
+ export function withToolDeadline(execute, timeoutMs, signal) {
18
+ return new Promise((resolve, reject) => {
19
+ let settled = false;
20
+ const handle = { timer: undefined };
21
+ const settle = (action) => {
22
+ if (settled)
23
+ return;
24
+ settled = true;
25
+ if (handle.timer)
26
+ clearTimeout(handle.timer);
27
+ action();
28
+ };
29
+ const quarantineLate = () => {
30
+ // Swallow the eventual resolution/rejection of an abort-ignoring tool so
31
+ // it cannot surface as an unhandled rejection after the wrapper returned.
32
+ work.catch(() => undefined);
33
+ };
34
+ const fire = (message) => settle(() => {
35
+ quarantineLate();
36
+ resolve({ ok: false, [TOOL_DEADLINE_EXCEEDED]: true, error: message });
37
+ });
38
+ const work = execute();
39
+ handle.timer = setTimeout(() => fire(`Tool execution exceeded the ${timeoutMs}ms deadline.`), timeoutMs);
40
+ if (signal) {
41
+ if (signal.aborted)
42
+ return fire('Tool execution was aborted.');
43
+ signal.addEventListener('abort', () => fire('Tool execution was aborted.'), { once: true });
44
+ }
45
+ work.then(value => settle(() => resolve(value)), error => settle(() => reject(error)));
46
+ });
47
+ }
48
+ export function createAbsoluteDeadline(input) {
49
+ const { timeoutMs, signal, onTimeout } = input;
50
+ let fired = false;
51
+ let timer;
52
+ const fire = () => {
53
+ if (fired)
54
+ return;
55
+ fired = true;
56
+ if (timer)
57
+ clearTimeout(timer);
58
+ onTimeout();
59
+ };
60
+ timer = setTimeout(fire, timeoutMs);
61
+ if (signal) {
62
+ if (signal.aborted)
63
+ fire();
64
+ else
65
+ signal.addEventListener('abort', fire, { once: true });
66
+ }
67
+ return {
68
+ clear: () => {
69
+ if (timer)
70
+ clearTimeout(timer);
71
+ timer = undefined;
72
+ },
73
+ };
74
+ }
@@ -1,2 +1,29 @@
1
1
  export declare function toolLoopBudgetPrompt(): string;
2
2
  export declare function repeatedToolCallPrompt(toolNames: string[]): string;
3
+ /**
4
+ * Ephemeral control appended to continue a response truncated by an
5
+ * output-length finish. Asks the model to resume from where it stopped and
6
+ * complete the requested artifact/answer. One-request nudge only.
7
+ */
8
+ export declare function lengthContinuationPrompt(): string;
9
+ /**
10
+ * Ephemeral control for the single completion-rescue slice. Only mutation and
11
+ * validation tools are available; discovery must not be reopened. The model gets
12
+ * one tool-bearing step (at most two tool calls) to apply a concrete remaining
13
+ * deliverable you already discovered, then one final tool-free synthesis.
14
+ */
15
+ export declare function completionRescuePrompt(): string;
16
+ export declare function malformedToolCallPrompt(toolName: string, chunkBytes: number): string;
17
+ /**
18
+ * Ephemeral control for a goal-continuation slice or a fresh continuation
19
+ * turn. The model's stop was rejected (or its physical turn hit a budget
20
+ * boundary) while structured evidence — declared task counts, post-edit
21
+ * validation — shows unfinished work; this nudge requires resuming concrete
22
+ * work rather than summarizing again. One-request nudge only.
23
+ */
24
+ export declare function goalContinuationPrompt(reason: string, taskCounts?: {
25
+ total: number;
26
+ pending: number;
27
+ inProgress: number;
28
+ completed: number;
29
+ }): string;
@@ -1,7 +1,43 @@
1
1
  export function toolLoopBudgetPrompt() {
2
- 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.';
2
+ 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 with a bounded progress checkpoint: what is done so far (changes + validation evidence) and, if work remains, the single next concrete unfinished action. haze continues the active goal automatically from that line — do not manufacture a completion summary and do not treat this as the end of the task. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
3
3
  }
4
4
  export function repeatedToolCallPrompt(toolNames) {
5
5
  const names = [...new Set(toolNames)].join(', ');
6
6
  return `You already called ${names || 'a tool'} with identical input in this turn. Do not call the same tool again with the same arguments. Use the existing tool result already in the conversation, choose a different concrete tool/input if genuinely needed, or give the final/blocked status now.`;
7
7
  }
8
+ /**
9
+ * Ephemeral control appended to continue a response truncated by an
10
+ * output-length finish. Asks the model to resume from where it stopped and
11
+ * complete the requested artifact/answer. One-request nudge only.
12
+ */
13
+ export function lengthContinuationPrompt() {
14
+ return 'Your previous response was truncated by the output-token limit before it finished. Continue exactly from where you stopped and complete the requested artifact or answer. Do not repeat what you already produced; finish the in-progress work and then stop.';
15
+ }
16
+ /**
17
+ * Ephemeral control for the single completion-rescue slice. Only mutation and
18
+ * validation tools are available; discovery must not be reopened. The model gets
19
+ * one tool-bearing step (at most two tool calls) to apply a concrete remaining
20
+ * deliverable you already discovered, then one final tool-free synthesis.
21
+ */
22
+ export function completionRescuePrompt() {
23
+ return 'You reached the tool-boundary without a substantive final answer. Only edit/write and validation tools are available now. Use at most two tool calls to apply the single most important remaining concrete deliverable you already discovered (do not explore or read new files), then give the final status: current-task changes plus validation evidence, or a single short line stating the next unfinished action. Do not loop.';
24
+ }
25
+ export function malformedToolCallPrompt(toolName, chunkBytes) {
26
+ const chunkGuidance = toolName === 'writeFile'
27
+ ? ` Keep content below ${chunkBytes} UTF-8 bytes per call: write the first chunk normally, then continue the same file with append=true.`
28
+ : '';
29
+ return `The ${toolName} call had invalid, malformed, or truncated JSON input and did not execute. Retry it now with valid smaller arguments; do not merely announce that you will retry.${chunkGuidance}`;
30
+ }
31
+ /**
32
+ * Ephemeral control for a goal-continuation slice or a fresh continuation
33
+ * turn. The model's stop was rejected (or its physical turn hit a budget
34
+ * boundary) while structured evidence — declared task counts, post-edit
35
+ * validation — shows unfinished work; this nudge requires resuming concrete
36
+ * work rather than summarizing again. One-request nudge only.
37
+ */
38
+ export function goalContinuationPrompt(reason, taskCounts) {
39
+ const taskLine = taskCounts
40
+ ? ` The task list currently shows ${taskCounts.pending + taskCounts.inProgress} open item${taskCounts.pending + taskCounts.inProgress === 1 ? '' : 's'} of ${taskCounts.total}; update writeTasks as you complete them.`
41
+ : '';
42
+ return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}). Do not summarize again or restate what remains — resume the next concrete unfinished task now.${taskLine} If you declared a task list with writeTasks, its pending and in-progress items are commitments: complete them and update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
43
+ }
@@ -12,6 +12,8 @@ export declare const SKILL_MARKDOWN_BYTES: number;
12
12
  export declare const EXACT_MUTATION_BYTES: number;
13
13
  export declare const JSONL_LINE_BYTES: number;
14
14
  export declare const TEXT_LINE_BYTES: number;
15
+ /** Maximum byte size of a prompt read from piped stdin. */
16
+ export declare const STDIN_PROMPT_BYTES: number;
15
17
  /** Maximum size of one user-attached image (checked before the read). */
16
18
  export declare const IMAGE_ATTACHMENT_BYTES: number;
17
19
  /** Maximum number of image attachments in a single user message. */
@@ -12,6 +12,8 @@ export const SKILL_MARKDOWN_BYTES = 256 * 1024;
12
12
  export const EXACT_MUTATION_BYTES = 8 * 1024 * 1024;
13
13
  export const JSONL_LINE_BYTES = 4 * 1024 * 1024;
14
14
  export const TEXT_LINE_BYTES = 1024 * 1024;
15
+ /** Maximum byte size of a prompt read from piped stdin. */
16
+ export const STDIN_PROMPT_BYTES = 256 * 1024;
15
17
  /** Maximum size of one user-attached image (checked before the read). */
16
18
  export const IMAGE_ATTACHMENT_BYTES = 5 * 1024 * 1024;
17
19
  /** Maximum number of image attachments in a single user message. */
@@ -15,6 +15,8 @@ export declare const GREP_MAX_OUTPUT_CHARS = 30000;
15
15
  export declare const GREP_MAX_LINE_CHARS = 500;
16
16
  /** Bounded excerpt of older messages kept by /compact-style compaction. */
17
17
  export declare const COMPACTION_OLDER_CHARS = 8000;
18
+ /** Bounded older-transcript budget sent to the model for LLM-summarized /compact (F-09). */
19
+ export declare const COMPACTION_LLM_TRANSCRIPT_CHARS = 60000;
18
20
  /** Session JSONL values up to this size stay inline; larger ones become previews. */
19
21
  export declare const SESSION_INLINE_VALUE_BYTES: number;
20
22
  /** Preview length for slimmed session values. */
@@ -15,6 +15,8 @@ export const GREP_MAX_OUTPUT_CHARS = 30_000;
15
15
  export const GREP_MAX_LINE_CHARS = 500;
16
16
  /** Bounded excerpt of older messages kept by /compact-style compaction. */
17
17
  export const COMPACTION_OLDER_CHARS = 8_000;
18
+ /** Bounded older-transcript budget sent to the model for LLM-summarized /compact (F-09). */
19
+ export const COMPACTION_LLM_TRANSCRIPT_CHARS = 60_000;
18
20
  /** Session JSONL values up to this size stay inline; larger ones become previews. */
19
21
  export const SESSION_INLINE_VALUE_BYTES = 32 * 1024;
20
22
  /** Preview length for slimmed session values. */
@@ -9,6 +9,9 @@ const LOGS_DIR = path.join(HAZE_DIR, 'logs');
9
9
  function logFileId(now = new Date()) {
10
10
  return now.toISOString().replace(/[:.]/g, '-');
11
11
  }
12
+ function isSafeLogId(id) {
13
+ return id.length > 0 && path.basename(id) === id && path.win32.basename(id) === id;
14
+ }
12
15
  function logFilePath(id) {
13
16
  return path.join(LOGS_DIR, `${id}.jsonl`);
14
17
  }
@@ -52,6 +55,8 @@ export async function listLogs() {
52
55
  return logs.sort((a, b) => b.modified.localeCompare(a.modified));
53
56
  }
54
57
  export async function readLogEntries(id) {
58
+ if (!isSafeLogId(id))
59
+ return [];
55
60
  const file = logFilePath(id);
56
61
  const entries = [];
57
62
  try {
@@ -71,6 +76,8 @@ export async function readLogEntries(id) {
71
76
  return entries;
72
77
  }
73
78
  export async function summarizeLog(id) {
79
+ if (!isSafeLogId(id))
80
+ return undefined;
74
81
  const file = logFilePath(id);
75
82
  const summary = { entries: 0, typeCounts: {}, totalInput: 0, totalOutput: 0, toolCallCounts: {} };
76
83
  try {
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Serializes async writes so appends land in arrival order, even when an earlier
3
+ * write rejects. Two contract points worth knowing:
4
+ * - The per-`append` promise rejects with the specific error of that write,
5
+ * so awaiting callers see their own failure. Subsequent appends still
6
+ * chain (the queue keeps draining) so a single bad write does not wedge
7
+ * the writer or reject unrelated callers.
8
+ * - `error()` and `flush()` surface the *first* captured error and never
9
+ * clear it; later successful writes do not reset the sticky state.
10
+ */
1
11
  export declare class OrderedFileWriter<T> {
2
12
  private readonly write;
3
13
  private tail;
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Serializes async writes so appends land in arrival order, even when an earlier
3
+ * write rejects. Two contract points worth knowing:
4
+ * - The per-`append` promise rejects with the specific error of that write,
5
+ * so awaiting callers see their own failure. Subsequent appends still
6
+ * chain (the queue keeps draining) so a single bad write does not wedge
7
+ * the writer or reject unrelated callers.
8
+ * - `error()` and `flush()` surface the *first* captured error and never
9
+ * clear it; later successful writes do not reset the sticky state.
10
+ */
1
11
  export class OrderedFileWriter {
2
12
  write;
3
13
  tail = Promise.resolve();
@@ -9,10 +19,14 @@ export class OrderedFileWriter {
9
19
  append(value) {
10
20
  if (this.closed)
11
21
  return Promise.reject(new Error('Writer is closed.'));
12
- this.tail = this.tail.then(() => this.write(value)).catch(error => {
22
+ // per-call result: rejects only with this append's own write error
23
+ const result = this.tail.then(() => this.write(value)).catch(error => {
13
24
  this.firstError ??= error instanceof Error ? error : new Error(String(error));
25
+ throw error;
14
26
  });
15
- return this.tail;
27
+ // Chain continues regardless so later appends are not blocked by this one's failure.
28
+ this.tail = result.catch(() => undefined);
29
+ return result;
16
30
  }
17
31
  async flush() {
18
32
  await this.tail;
@@ -4,6 +4,7 @@ import { BACKGROUND_PROCESS_HISTORY_LIMIT, BACKGROUND_PROCESS_MAX_CONCURRENCY }
4
4
  import { registerDynamicToolOutput, unregisterDynamicToolOutput } from '../agent/toolOutputStore.js';
5
5
  import { BACKGROUND_PROCESS_OUTPUT_BYTES } from '../limits/byteBudgets.js';
6
6
  import { signalProcessTree } from './runBoundedProcess.js';
7
+ import { truncateUtf8TailBufferAtBytes } from '../../utils/utf8.js';
7
8
  class OutputRing {
8
9
  decoder = new StringDecoder('utf8');
9
10
  retained = Buffer.alloc(0);
@@ -13,12 +14,7 @@ class OutputRing {
13
14
  return;
14
15
  const bytes = Buffer.from(completeText, 'utf8');
15
16
  this.retained = this.retained.length === 0 ? bytes : Buffer.concat([this.retained, bytes]);
16
- if (this.retained.length > BACKGROUND_PROCESS_OUTPUT_BYTES) {
17
- let start = this.retained.length - BACKGROUND_PROCESS_OUTPUT_BYTES;
18
- while (start < this.retained.length && (this.retained[start] & 0xc0) === 0x80)
19
- start++;
20
- this.retained = this.retained.subarray(start);
21
- }
17
+ this.retained = truncateUtf8TailBufferAtBytes(this.retained, BACKGROUND_PROCESS_OUTPUT_BYTES).buffer;
22
18
  }
23
19
  add(chunk) {
24
20
  this.totalBytes += chunk.length;
@@ -103,7 +99,12 @@ export function startBackgroundProcess(input) {
103
99
  child.stderr?.on('data', (chunk) => ring.add(chunk));
104
100
  child.once('error', error => {
105
101
  summary.status = 'failed';
106
- summary.error = error.message;
102
+ const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
103
+ // bash is required on Windows (via WSL or Git Bash). Without it, spawn
104
+ // fails with ENOENT; surface a clearer message than the raw syscall error.
105
+ summary.error = code === 'ENOENT' && process.platform === 'win32'
106
+ ? `bash was not found on PATH. Install WSL or Git Bash, or run haze on a POSIX shell. Underlying error: ${error.message}`
107
+ : error.message;
107
108
  notify();
108
109
  });
109
110
  child.once('close', (code, signal) => {
@@ -1,4 +1,4 @@
1
- import { type ChildProcess } from 'node:child_process';
1
+ import { spawn, type ChildProcess } from 'node:child_process';
2
2
  export interface BoundedStream {
3
3
  text: string;
4
4
  totalBytes: number;
@@ -16,7 +16,13 @@ export interface BoundedProcessResult {
16
16
  durationMs: number;
17
17
  error?: string;
18
18
  }
19
- export declare function signalProcessTree(child: Pick<ChildProcess, 'pid' | 'kill'>, signal: NodeJS.Signals): void;
19
+ export interface ProcessTreeSignalOptions {
20
+ /** @internal testing seam. */
21
+ platform?: NodeJS.Platform;
22
+ /** @internal testing seam. */
23
+ spawnProcess?: typeof spawn;
24
+ }
25
+ export declare function signalProcessTree(child: Pick<ChildProcess, 'pid' | 'kill'>, signal: NodeJS.Signals, options?: ProcessTreeSignalOptions): void;
20
26
  export declare function runBoundedProcess(input: {
21
27
  command: string;
22
28
  args: string[];
@@ -1,15 +1,16 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { StringDecoder } from 'node:string_decoder';
3
- export function signalProcessTree(child, signal) {
3
+ export function signalProcessTree(child, signal, options = {}) {
4
+ // When pid is null, child.kill is a no-op against a real Node child (returns
5
+ // false). Tests still rely on the call going through so they can observe
6
+ // which signal was used via their fake child's kill implementation.
4
7
  if (child.pid == null) {
5
8
  child.kill(signal);
6
9
  return;
7
10
  }
8
- if (process.platform === 'win32') {
9
- if (signal === 'SIGKILL')
10
- spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).unref();
11
- else
12
- child.kill('SIGTERM');
11
+ if ((options.platform ?? process.platform) === 'win32') {
12
+ const args = ['/pid', String(child.pid), '/T', ...(signal === 'SIGKILL' ? ['/F'] : [])];
13
+ (options.spawnProcess ?? spawn)('taskkill', args, { stdio: 'ignore' }).unref();
13
14
  return;
14
15
  }
15
16
  try {
@@ -27,6 +28,8 @@ function collector(limit) {
27
28
  add(chunk) {
28
29
  totalBytes += chunk.length;
29
30
  const remaining = limit - retainedBytes;
31
+ // Keep consuming data after the retention cap so the child does not
32
+ // block on a full pipe; only allocation and retained output are capped.
30
33
  if (remaining > 0) {
31
34
  const kept = chunk.subarray(0, remaining);
32
35
  chunks.push(kept);
@@ -78,6 +81,12 @@ export async function runBoundedProcess(input) {
78
81
  resolve({ code, signal, stdout: stdoutResult, stderr: stderrResult, timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
79
82
  };
80
83
  const scheduleCloseFallback = () => {
84
+ // Only call after SIGKILL — running this after SIGTERM would resolve the
85
+ // promise before the forced-kill escalation, leaking processes that ignore
86
+ // SIGTERM. 50ms is enough for the kernel to deliver the signal and for an
87
+ // 'exit' event to fire; if 'close' still doesn't fire, the descendant is
88
+ // holding stdio (escaped grandchild) and we settle with whatever exit
89
+ // info we already captured.
81
90
  closeTimer ??= setTimeout(() => settle(exitCode, exitSignal), 50);
82
91
  closeTimer.unref?.();
83
92
  };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Bounded, generic diagnostic for missing executables.
3
+ *
4
+ * When a shell command fails because an executable is not on PATH, this derives
5
+ * a precise, safe blocker: the executable name and a generic recovery order. It
6
+ * never returns raw stderr/command text and contains no dependency-specific
7
+ * branching (no special cases for Git, Python, Docker images, etc.).
8
+ *
9
+ * The recovery order is generic and safe:
10
+ * 1. an already-available alternative (versioned/similarly-named command);
11
+ * 2. the project's own manifest/package file + a project-local install;
12
+ * 3. a system install only with explicit user consent (deferred — see below).
13
+ *
14
+ * Product decision (deferred): a system-install permission model is not defined
15
+ * here. We never silently modify a user-managed toolchain. The diagnostic asks
16
+ * for consent and reports the blocker; it does not perform the install.
17
+ */
18
+ export interface MissingExecutableDiagnostic {
19
+ /** Best-effort name of the executable that was not found. */
20
+ executable: string;
21
+ /** Generic, dependency-agnostic next step (bounded, no raw command/stderr). */
22
+ suggestedNextStep: string;
23
+ }
24
+ /**
25
+ * Detect a missing-executable failure from a bounded command + reduced stderr +
26
+ * exit code. Returns undefined when the failure is not a missing-executable
27
+ * failure or no executable name can be derived.
28
+ */
29
+ export declare function detectMissingExecutable(input: {
30
+ command: string;
31
+ code: number | null;
32
+ stderr: string;
33
+ }): MissingExecutableDiagnostic | undefined;
34
+ /**
35
+ * Project the diagnostic into the bounded fields carried in safe tool output /
36
+ * events. Only the executable name and reasonCode are exposed — never stderr or
37
+ * the full command.
38
+ */
39
+ export declare function missingExecutableFields(diagnostic: MissingExecutableDiagnostic): {
40
+ reasonCode: 'missing_executable';
41
+ missingExecutable: string;
42
+ };