@denizokcu/haze 1.1.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +26 -15
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/inputSuggestions.js +3 -0
  7. package/dist/cli/chat/liveMessages.d.ts +36 -0
  8. package/dist/cli/chat/liveMessages.js +64 -0
  9. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  10. package/dist/cli/chat/sessionLifecycle.js +25 -2
  11. package/dist/cli/chat/sessionRecorder.d.ts +7 -0
  12. package/dist/cli/chat/sessionRecorder.js +6 -0
  13. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  14. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  15. package/dist/cli/commands/chat.js +63 -36
  16. package/dist/cli/commands/commandHelp.js +2 -0
  17. package/dist/cli/commands/commands.js +2 -0
  18. package/dist/cli/commands/formatters.js +5 -1
  19. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  20. package/dist/cli/commands/ndjsonSink.js +29 -0
  21. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  22. package/dist/cli/commands/reasoningCommand.js +46 -0
  23. package/dist/cli/commands/runCommand.d.ts +14 -0
  24. package/dist/cli/commands/runCommand.js +43 -11
  25. package/dist/cli/commands/settingsSummary.js +2 -0
  26. package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
  27. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  28. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  29. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  30. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  31. package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
  32. package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
  33. package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
  34. package/dist/cli/commands/streaming/attemptSetup.js +40 -15
  35. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  36. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  37. package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
  38. package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
  39. package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
  40. package/dist/cli/commands/streaming/prepareStep.js +43 -22
  41. package/dist/cli/commands/streaming/stallRecovery.js +2 -2
  42. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  43. package/dist/cli/commands/streaming/streamLoop.js +280 -44
  44. package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
  45. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  46. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  47. package/dist/cli/commands/streaming.d.ts +15 -2
  48. package/dist/cli/commands/streaming.js +37 -8
  49. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  50. package/dist/cli/commands/wizardFlow.js +22 -0
  51. package/dist/cli/index.js +8 -3
  52. package/dist/config/modelCatalog.d.ts +32 -0
  53. package/dist/config/modelCatalog.js +84 -0
  54. package/dist/config/modelDiscovery.js +68 -5
  55. package/dist/config/settings.d.ts +18 -6
  56. package/dist/config/settings.js +11 -1
  57. package/dist/core/agent/budgets.d.ts +10 -2
  58. package/dist/core/agent/budgets.js +10 -2
  59. package/dist/core/agent/compaction.d.ts +42 -3
  60. package/dist/core/agent/compaction.js +53 -5
  61. package/dist/core/agent/completionController.d.ts +11 -1
  62. package/dist/core/agent/completionController.js +33 -0
  63. package/dist/core/agent/contextBudget.d.ts +56 -0
  64. package/dist/core/agent/contextBudget.js +53 -0
  65. package/dist/core/agent/errors.js +2 -2
  66. package/dist/core/agent/events.d.ts +26 -2
  67. package/dist/core/agent/goalPolicy.d.ts +7 -0
  68. package/dist/core/agent/goalPolicy.js +9 -0
  69. package/dist/core/agent/overflow.d.ts +45 -0
  70. package/dist/core/agent/overflow.js +91 -0
  71. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  72. package/dist/core/agent/reasoningPolicy.js +49 -9
  73. package/dist/core/agent/requestAssembly.d.ts +7 -0
  74. package/dist/core/agent/requestAssembly.js +15 -7
  75. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  76. package/dist/core/agent/toolCapabilities.js +31 -7
  77. package/dist/core/agent/workState.d.ts +6 -4
  78. package/dist/core/agent/workState.js +53 -29
  79. package/dist/core/deadline.js +22 -24
  80. package/dist/core/safety/secretPaths.js +10 -7
  81. package/dist/core/safety/shellClassifier.d.ts +18 -0
  82. package/dist/core/safety/shellClassifier.js +39 -0
  83. package/dist/core/session/sessionSlimming.d.ts +2 -0
  84. package/dist/core/session/sessionSlimming.js +50 -1
  85. package/dist/core/session/sessionStore.d.ts +14 -8
  86. package/dist/core/session/sessionStore.js +59 -32
  87. package/dist/core/shellOutput/reducers/git.js +7 -2
  88. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  89. package/dist/core/shellOutput/reducers/validation.js +14 -1
  90. package/dist/core/shellOutput/registry.js +3 -2
  91. package/dist/core/subagent/contracts.d.ts +8 -1
  92. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  93. package/dist/core/subagent/subagentRunner.js +33 -25
  94. package/dist/core/tasks/taskStorage.js +8 -1
  95. package/dist/core/validation/outputParser.d.ts +1 -1
  96. package/dist/core/validation/outputParser.js +30 -1
  97. package/dist/llm/client.d.ts +4 -3
  98. package/dist/llm/client.js +34 -16
  99. package/dist/llm/hazeTools.d.ts +2039 -16
  100. package/dist/llm/hazeTools.js +43 -2
  101. package/dist/llm/lsp/client.d.ts +7 -1
  102. package/dist/llm/lsp/client.js +58 -9
  103. package/dist/llm/lsp/pool.d.ts +11 -0
  104. package/dist/llm/lsp/pool.js +61 -4
  105. package/dist/llm/lsp/protocol.d.ts +6 -23
  106. package/dist/llm/lsp/requests.d.ts +54 -60
  107. package/dist/llm/lsp/requests.js +152 -28
  108. package/dist/llm/lsp/symbols.d.ts +16 -0
  109. package/dist/llm/lsp/symbols.js +70 -0
  110. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  111. package/dist/llm/lsp/workspaceEdit.js +117 -0
  112. package/dist/llm/lspTools.d.ts +7518 -2859
  113. package/dist/llm/lspTools.js +195 -110
  114. package/dist/llm/requestContext.d.ts +3 -2
  115. package/dist/llm/requestContext.js +8 -4
  116. package/dist/llm/systemPrompt.js +2 -2
  117. package/dist/llm/tools/fetchTool.d.ts +4 -0
  118. package/dist/llm/tools/processTool.d.ts +4 -0
  119. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  120. package/dist/llm/tools/replaceInFiles.js +131 -0
  121. package/dist/llm/tools/shellTool.d.ts +4 -0
  122. package/dist/llm/tools/shellTool.js +27 -8
  123. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  124. package/dist/llm/tools/taskTool.d.ts +4 -0
  125. package/dist/llm/tools/toolContext.d.ts +3 -0
  126. package/dist/llm/tools/toolContext.js +26 -4
  127. package/dist/skills/SkillLoader.js +27 -1
  128. package/dist/ui/components/TextInput.d.ts +18 -1
  129. package/dist/ui/components/TextInput.js +44 -6
  130. package/dist/ui/components/useInputSuggestions.js +18 -6
  131. package/dist/utils/buildInfo.js +29 -8
  132. package/dist/utils/fs.js +5 -1
  133. package/package.json +20 -19
@@ -1,5 +1,6 @@
1
1
  import type { ModelMessage } from 'ai';
2
2
  import type { WorkState } from '../agent/workState.js';
3
+ import type { ValidationKind } from '../../llm/toolResultTypes.js';
3
4
  export type SessionEntry = {
4
5
  type: 'header';
5
6
  id: string;
@@ -29,6 +30,16 @@ export type SessionEntry = {
29
30
  at: string;
30
31
  name: string;
31
32
  text?: string;
33
+ }
34
+ /** First-class compaction audit entry (Pillar 1.7): conversation snapshots remain the restore source of truth; this records what was compacted, when, and how. */
35
+ | {
36
+ type: 'compact';
37
+ at: string;
38
+ method: 'heuristic' | 'llm';
39
+ olderCount: number;
40
+ keptCount: number;
41
+ instructions?: string;
42
+ summary: string;
32
43
  } | {
33
44
  type: 'goal';
34
45
  at: string;
@@ -52,6 +63,7 @@ export type SessionEntry = {
52
63
  commandKey: string;
53
64
  summary: string;
54
65
  };
66
+ validationKind?: ValidationKind;
55
67
  stopReason?: string;
56
68
  status?: string;
57
69
  };
@@ -72,6 +84,8 @@ export interface GoalLedgerFrontier {
72
84
  taskCounts?: GoalLedgerEntry['taskCounts'];
73
85
  /** Unresolved red evidence carried so crash resume preserves the pending same-check green requirement. */
74
86
  redEvidence?: GoalLedgerEntry['redEvidence'];
87
+ /** Kind of the frontier's carried validation, when one rode the ledger (R2-03). */
88
+ validationKind?: ValidationKind;
75
89
  at: string;
76
90
  }
77
91
  type SessionHeader = Extract<SessionEntry, {
@@ -132,14 +146,6 @@ export interface ReadSessionEntriesResult {
132
146
  * loss in debug mode instead of silently dropping messages.
133
147
  */
134
148
  export declare function readSessionEntries(session: HazeSession): Promise<ReadSessionEntriesResult>;
135
- /**
136
- * Pure frontier detection over parsed session entries (P1): the append-only
137
- * goal ledger's frontier is the last entry of the most recent goal id that has
138
- * no `goal_end` entry. A truncated or malformed tail line parses as absent, so
139
- * a crash mid-write can never resurrect a half-written boundary
140
- * (autoprompt's "treat half-written artifacts as absent").
141
- */
142
- export declare function findGoalLedgerFrontier(entries: readonly SessionEntry[]): GoalLedgerFrontier | undefined;
143
149
  /** Read the goal-ledger frontier of a stored session (one file scan). */
144
150
  export declare function readGoalLedgerFrontier(session: HazeSession): Promise<GoalLedgerFrontier | undefined>;
145
151
  export interface RestoreConversationResult {
@@ -2,7 +2,7 @@ import crypto from 'node:crypto';
2
2
  import path from 'node:path';
3
3
  import fs from 'fs-extra';
4
4
  import { HAZE_DIR } from '../../config/paths.js';
5
- import { prepareSessionEntryForWrite } from './sessionSlimming.js';
5
+ import { prepareSessionEntryForWrite, repairRestoredConversation } from './sessionSlimming.js';
6
6
  import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile, writePrivateFileAtomic } from '../../config/privateStorage.js';
7
7
  import { JSONL_LINE_BYTES } from '../limits.js';
8
8
  import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
@@ -143,7 +143,10 @@ export async function vacuumSessionFileIfLarge(session, thresholdBytes = effecti
143
143
  // turn; intermediate `goal_continue` entries of superseded cycles are audit
144
144
  // trail only. Keep the trailing few per goal id — the frontier and the
145
145
  // terminal entry are always among them — so a very long-lived session file
146
- // stays bounded without ever losing a live frontier.
146
+ // stays bounded without ever losing a live frontier. The keep decision and
147
+ // `keepGoal` must both use original `entries` indexes (R2-01): filtering a
148
+ // candidate array first would shift positions whenever snapshots precede or
149
+ // interleave goal entries, silently dropping the live frontier.
147
150
  const keepGoal = new Set();
148
151
  const goalIndexesByGoal = new Map();
149
152
  entries.forEach((entry, index) => {
@@ -157,11 +160,11 @@ export async function vacuumSessionFileIfLarge(session, thresholdBytes = effecti
157
160
  // Malformed lines are dropped by the rewrite: they were already unusable
158
161
  // (and reported as parse errors on read) and keeping them would defeat the
159
162
  // size bound the vacuum exists to enforce.
160
- const candidate = entries.filter((entry, index) => (entry.type !== 'conversation_snapshot' && entry.type !== 'work_state_snapshot')
163
+ const kept = entries.filter((entry, index) => ((entry.type !== 'conversation_snapshot' && entry.type !== 'work_state_snapshot')
161
164
  || index === lastConversation
162
- || index === lastWorkState);
163
- const kept = candidate.filter((entry, index) => entry.type !== 'goal' || keepGoal.has(index));
164
- const droppedGoalBytes = candidate
165
+ || index === lastWorkState)
166
+ && (entry.type !== 'goal' || keepGoal.has(index)));
167
+ const droppedGoalBytes = entries
165
168
  .filter((entry, index) => entry.type === 'goal' && !keepGoal.has(index))
166
169
  .reduce((sum, entry) => sum + Buffer.byteLength(JSON.stringify(entry), 'utf8'), 0);
167
170
  const serialized = kept.map(entry => JSON.stringify(entry)).join('\n') + '\n';
@@ -198,6 +201,10 @@ function optionalTaskCounts(value) {
198
201
  function optionalLedgerRedEvidence(value) {
199
202
  return value === undefined || parseLedgerRedEvidence(value) !== undefined;
200
203
  }
204
+ const LEDGER_VALIDATION_KINDS = new Set(['test', 'typecheck', 'lint', 'build', 'generic']);
205
+ function optionalLedgerValidationKind(value) {
206
+ return value === undefined || (typeof value === 'string' && LEDGER_VALIDATION_KINDS.has(value));
207
+ }
201
208
  function frontierFromGoalEntry(entry) {
202
209
  return {
203
210
  goalId: entry.goalId,
@@ -210,6 +217,7 @@ function frontierFromGoalEntry(entry) {
210
217
  progressSignature: entry.progressSignature,
211
218
  ...(entry.taskCounts ? { taskCounts: entry.taskCounts } : {}),
212
219
  ...(entry.redEvidence ? { redEvidence: entry.redEvidence } : {}),
220
+ ...(entry.validationKind ? { validationKind: entry.validationKind } : {}),
213
221
  at: entry.at,
214
222
  };
215
223
  }
@@ -250,6 +258,12 @@ function parseSessionEntry(value) {
250
258
  if (typeof value.at !== 'string' || typeof value.name !== 'string' || !optionalString(value.text))
251
259
  return invalid('invalid event');
252
260
  return value;
261
+ case 'compact':
262
+ if (typeof value.at !== 'string' || (value.method !== 'heuristic' && value.method !== 'llm')
263
+ || typeof value.olderCount !== 'number' || typeof value.keptCount !== 'number'
264
+ || typeof value.summary !== 'string' || !optionalString(value.instructions))
265
+ return invalid('invalid compact');
266
+ return value;
253
267
  case 'goal':
254
268
  if (typeof value.at !== 'string' || typeof value.goalId !== 'string'
255
269
  || (value.phase !== 'goal_start' && value.phase !== 'goal_continue' && value.phase !== 'goal_end')
@@ -258,7 +272,8 @@ function parseSessionEntry(value) {
258
272
  || typeof value.validationOutcome !== 'string' || typeof value.progressSignature !== 'string'
259
273
  || !optionalTaskCounts(value.taskCounts)
260
274
  || !optionalString(value.stopReason) || !optionalString(value.status)
261
- || !optionalLedgerRedEvidence(value.redEvidence))
275
+ || !optionalLedgerRedEvidence(value.redEvidence)
276
+ || !optionalLedgerValidationKind(value.validationKind))
262
277
  return invalid('invalid goal');
263
278
  return value;
264
279
  default:
@@ -315,19 +330,34 @@ export async function readSessionEntries(session) {
315
330
  * a crash mid-write can never resurrect a half-written boundary
316
331
  * (autoprompt's "treat half-written artifacts as absent").
317
332
  */
318
- export function findGoalLedgerFrontier(entries) {
319
- let frontier;
320
- for (const entry of entries) {
333
+ /**
334
+ * Ordered frontier state shared by list-based lookup and streaming restore
335
+ * (SU-01): a later start/continue of the same goal id REOPENS it, because an
336
+ * explicit resume reuses the goalId after an orderly pause (`goal_end`). Only
337
+ * the newest goal id can hold the frontier; a terminal end closes exactly that
338
+ * goal. Both consumers must return identical results for any entry sequence.
339
+ */
340
+ class GoalLedgerFrontierTracker {
341
+ frontier;
342
+ observe(entry) {
321
343
  if (entry.type !== 'goal')
322
- continue;
344
+ return;
323
345
  if (entry.phase === 'goal_end') {
324
- if (frontier?.goalId === entry.goalId)
325
- frontier = undefined;
326
- continue;
346
+ if (this.frontier?.goalId === entry.goalId)
347
+ this.frontier = undefined;
348
+ return;
327
349
  }
328
- frontier = frontierFromGoalEntry(entry);
350
+ this.frontier = frontierFromGoalEntry(entry);
351
+ }
352
+ result() {
353
+ return this.frontier;
329
354
  }
330
- return frontier;
355
+ }
356
+ function findGoalLedgerFrontier(entries) {
357
+ const tracker = new GoalLedgerFrontierTracker();
358
+ for (const entry of entries)
359
+ tracker.observe(entry);
360
+ return tracker.result();
331
361
  }
332
362
  /** Read the goal-ledger frontier of a stored session (one file scan). */
333
363
  export async function readGoalLedgerFrontier(session) {
@@ -342,27 +372,24 @@ export async function readGoalLedgerFrontier(session) {
342
372
  export async function restoreSessionState(session) {
343
373
  let messages = [];
344
374
  let workState;
345
- let goalFrontier;
346
- const terminatedGoals = new Set();
375
+ const tracker = new GoalLedgerFrontierTracker();
347
376
  const parseErrors = await scanSessionEntries(session, entry => {
377
+ // Legacy slim markers (pre-envelope-fix) are re-wrapped so the restored
378
+ // conversation is a protocol-safe ModelMessage[] for the next provider
379
+ // request (F-09).
348
380
  if (entry.type === 'conversation_snapshot')
349
- messages = entry.messages;
381
+ messages = repairRestoredConversation(entry.messages);
382
+ // SU-02: a durable clear marker means "no conversation after this line";
383
+ // later snapshots (if any) re-materialize it, otherwise restore yields [].
384
+ if (entry.type === 'event' && entry.name === 'clear') {
385
+ messages = [];
386
+ workState = undefined;
387
+ }
350
388
  if (entry.type === 'work_state_snapshot')
351
389
  workState = entry.state;
352
- if (entry.type === 'goal') {
353
- if (entry.phase === 'goal_end') {
354
- terminatedGoals.add(entry.goalId);
355
- if (goalFrontier?.goalId === entry.goalId)
356
- goalFrontier = undefined;
357
- }
358
- else {
359
- goalFrontier = frontierFromGoalEntry(entry);
360
- }
361
- }
390
+ tracker.observe(entry);
362
391
  });
363
- if (goalFrontier && terminatedGoals.has(goalFrontier.goalId))
364
- goalFrontier = undefined;
365
- return { messages, workState, parseErrors, goalFrontier };
392
+ return { messages, workState, parseErrors, goalFrontier: tracker.result() };
366
393
  }
367
394
  export async function restoreConversation(session) {
368
395
  const { messages, parseErrors } = await restoreSessionState(session);
@@ -1,9 +1,10 @@
1
1
  import { commandCandidates } from '../command.js';
2
+ import { isSingleForegroundCommand } from '../../safety/shellClassifier.js';
2
3
  function gitSubcommand(command) {
3
4
  for (const candidate of commandCandidates(command)) {
4
5
  const words = candidate.toLowerCase().split(/\s+/).filter(Boolean);
5
6
  const gitIndex = words.indexOf('git');
6
- if (gitIndex === -1)
7
+ if (gitIndex !== 0)
7
8
  continue;
8
9
  for (let index = gitIndex + 1; index < words.length; index++) {
9
10
  const word = words[index] ?? '';
@@ -19,7 +20,9 @@ function gitSubcommand(command) {
19
20
  return undefined;
20
21
  }
21
22
  export function reduceGitOutput(command, stdout, stderr) {
22
- const text = stdout || stderr;
23
+ if (!isSingleForegroundCommand(command) || stderr.trim())
24
+ return undefined;
25
+ const text = stdout;
23
26
  const subcommand = gitSubcommand(command);
24
27
  if (subcommand === 'status')
25
28
  return reduceGitStatus(text);
@@ -66,6 +69,8 @@ function reduceGitStatus(text) {
66
69
  items.push(inUntracked && !/^\w+:/.test(item) ? `?? ${item}` : item);
67
70
  }
68
71
  }
72
+ if (!branch && items.length === 0)
73
+ return undefined;
69
74
  const untracked = items.filter(line => line.startsWith('?? ')).length;
70
75
  const changed = items.length - untracked;
71
76
  const shown = items.slice(0, 30);
@@ -1,2 +1,2 @@
1
1
  import type { ValidationSummary } from '../../../llm/toolResultTypes.js';
2
- export declare function renderValidationReduction(summary: ValidationSummary, rawHandle?: string): string;
2
+ export declare function renderValidationReduction(summary: ValidationSummary, rawHandle?: string, raw?: string): string;
@@ -6,7 +6,17 @@ function groupDiagnostics(summary) {
6
6
  }
7
7
  return grouped;
8
8
  }
9
- export function renderValidationReduction(summary, rawHandle) {
9
+ /** Inline cap for small raw output kept alongside the summary (RT-04). */
10
+ const INLINE_RAW_CHARS = 800;
11
+ const INLINE_RAW_LINES = 12;
12
+ /** Small failing-command output is the diagnostic itself (RT-04): keep it inline so a readToolOutput round-trip (a full model step) is saved. */
13
+ function inlineRawLines(raw) {
14
+ if (raw.length === 0 || raw.length > INLINE_RAW_CHARS)
15
+ return [];
16
+ const lines = raw.split(/\r?\n/).map(line => line.trimEnd()).filter(Boolean);
17
+ return lines.length === 0 || lines.length > INLINE_RAW_LINES ? [] : lines;
18
+ }
19
+ export function renderValidationReduction(summary, rawHandle, raw = '') {
10
20
  const lines = [summary.summaryText];
11
21
  if (summary.failedTests.length) {
12
22
  lines.push('', 'failed tests:');
@@ -35,6 +45,9 @@ export function renderValidationReduction(summary, rawHandle) {
35
45
  }
36
46
  if (summary.suggestedNextStep)
37
47
  lines.push('', `next: ${summary.suggestedNextStep}`);
48
+ const inline = inlineRawLines(raw);
49
+ if (inline.length)
50
+ lines.push('', ...inline);
38
51
  if (rawHandle)
39
52
  lines.push('', `raw output: use readToolOutput with handle ${rawHandle}`);
40
53
  return lines.join('\n');
@@ -1,3 +1,4 @@
1
+ import { isSingleForegroundCommand } from '../safety/shellClassifier.js';
1
2
  import { applyLineFilter, findLineFilter } from './lineFilter.js';
2
3
  import { renderValidationReduction } from './reducers/validation.js';
3
4
  import { reduceGitOutput } from './reducers/git.js';
@@ -70,10 +71,10 @@ export function filterShellOutput(input) {
70
71
  filterName = `validation-${input.validationSummary.kind}`;
71
72
  const raw = `${input.stdout}${input.stderr ? `\n${input.stderr}` : ''}`;
72
73
  const rawHandle = input.storeRawOutput?.(raw);
73
- stdout = makeReduction(input.stdout, renderValidationReduction(input.validationSummary, rawHandle), true, filterName, input, undefined, 'validation');
74
+ stdout = makeReduction(input.stdout, renderValidationReduction(input.validationSummary, rawHandle, raw), true, filterName, input, undefined, 'validation');
74
75
  stderr = makeReduction(input.stderr, '', input.stderr.length > 0, filterName, input, undefined, 'validation');
75
76
  }
76
- else {
77
+ else if (isSingleForegroundCommand(input.command)) {
77
78
  const stdoutIn = capOutputForProcessing(input.stdout);
78
79
  const stderrIn = capOutputForProcessing(input.stderr);
79
80
  const git = reduceGitOutput(input.command, stdoutIn, stderrIn);
@@ -1,5 +1,6 @@
1
1
  import type { JSONValue, LanguageModel } from 'ai';
2
2
  import { z } from 'zod';
3
+ import type { ReasoningLevel } from '../agent/reasoningPolicy.js';
3
4
  declare const workerModes: readonly ["inspect", "research", "implement", "validate"];
4
5
  export type WorkerMode = typeof workerModes[number];
5
6
  export declare const subagentInputSchema: z.ZodObject<{
@@ -83,12 +84,18 @@ export interface ProviderCapabilities {
83
84
  supportsStickySessionId: boolean;
84
85
  supportsServerCompaction: boolean;
85
86
  supportsTextVerbosity: boolean;
86
- /** Protocol accepts an OpenAI-style reasoning-effort provider option. */
87
+ /**
88
+ * Protocol accepts a reasoning-effort request. The AI SDK maps its top-level
89
+ * `reasoning` parameter per provider; endpoints without native support ignore
90
+ * the field. Kept as a capability so a future provider kind can opt out.
91
+ */
87
92
  supportsReasoningEffort: boolean;
88
93
  }
89
94
  export interface ProviderRequestOptions {
90
95
  providerOptions?: Record<string, Record<string, JSONValue | undefined>>;
91
96
  headers?: Record<string, string>;
97
+ /** AI SDK top-level `reasoning` call setting; omitted when unset/unsupported. */
98
+ reasoning?: ReasoningLevel;
92
99
  /** Codex subscription requests let the provider manage the output limit. */
93
100
  omitMaxOutputTokens?: boolean;
94
101
  }
@@ -43,6 +43,7 @@ export declare function createSubagentTool(options: {
43
43
  contextFiles?: ContextFile[];
44
44
  session?: PromptSession;
45
45
  }): ({
46
+ deferLoading?: boolean;
46
47
  title?: string;
47
48
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
48
49
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -124,6 +125,7 @@ export declare function createSubagentTool(options: {
124
125
  acceptanceCriteria?: string[] | undefined;
125
126
  }, SubagentExecutionResult, NoInfer<HazeToolContext>>;
126
127
  }) | ({
128
+ deferLoading?: boolean;
127
129
  title?: string;
128
130
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
129
131
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -205,6 +207,7 @@ export declare function createSubagentTool(options: {
205
207
  acceptanceCriteria?: string[] | undefined;
206
208
  }, SubagentExecutionResult, NoInfer<HazeToolContext>>;
207
209
  }) | ({
210
+ deferLoading?: boolean;
208
211
  title?: string;
209
212
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
210
213
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -275,6 +278,7 @@ export declare function createSubagentTool(options: {
275
278
  acceptanceCriteria?: string[] | undefined;
276
279
  }, SubagentExecutionResult, NoInfer<HazeToolContext>>;
277
280
  }) | ({
281
+ deferLoading?: boolean;
278
282
  title?: string;
279
283
  providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
280
284
  metadata?: import("@ai-sdk/provider").JSONObject;
@@ -1,7 +1,8 @@
1
- import { generateText, isStepCount, tool } from 'ai';
1
+ import { isStepCount, streamText, tool } from 'ai';
2
2
  import { estimateToolSchemas, estimateValueTokens } from '../agent/contextBudget.js';
3
3
  import { SUBAGENT_MAX_STEPS, SUBAGENT_MIN_STEPS, SUBAGENT_SYNTHESIS_RESERVE, SUBAGENT_TOOL_ONLY_LIMIT, createToolExecutionBudget, isToolBudgetBlocked, withToolExecutionBudget, } from '../agent/budgets.js';
4
4
  import { storeToolOutput } from '../agent/toolOutputStore.js';
5
+ import { changedPathsFromTool } from '../agent/toolCapabilities.js';
5
6
  import { withSyntheticControl } from '../agent/requestAssembly.js';
6
7
  import { toolOnlyStepCount } from '../agent/turnPolicy.js';
7
8
  import { assembleWorkerContext, workerTaskMessage } from '../../llm/workerContext.js';
@@ -39,19 +40,6 @@ function pendingScopedControl(messages, context) {
39
40
  context.pendingContextFiles = [];
40
41
  return withSyntheticControl(messages, `Additional scoped project instructions now apply. Follow them before subsequent work.${projectContextSection(files)}`);
41
42
  }
42
- function changedPathFromOutput(name, output) {
43
- if (!['editFile', 'replaceLines', 'writeFile'].includes(name) || typeof output !== 'object' || output == null)
44
- return undefined;
45
- const value = output;
46
- if (value.ok !== true || typeof value.path !== 'string')
47
- return undefined;
48
- try {
49
- return workspaceRelativePath(resolveWorkspacePath(value.path));
50
- }
51
- catch {
52
- return undefined;
53
- }
54
- }
55
43
  function validationFromOutput(name, output) {
56
44
  if (name !== 'shell' || typeof output !== 'object' || output == null)
57
45
  return undefined;
@@ -107,7 +95,10 @@ export async function runSubagent(taskInput, options) {
107
95
  return terminalResult(task, runtime, profile, options.deadlineExpired?.() ? 'deadline_exceeded' : 'cancelled', 'Worker cancelled before workspace admission.', options.queueMs);
108
96
  try {
109
97
  const { omitMaxOutputTokens, ...providerRequestOptions } = runtime.requestOptions;
110
- const result = await generateText({
98
+ // Use the streaming model path even though workers return one collected
99
+ // capsule. ChatGPT Codex's Responses endpoint requires `stream: true`;
100
+ // `generateText` takes the non-streaming doGenerate path and is rejected.
101
+ const result = await streamText({
111
102
  model: runtime.model,
112
103
  instructions: bundle.systemPrompt,
113
104
  messages: [{ role: 'user', content: workerTaskMessage(task) }],
@@ -139,18 +130,22 @@ export async function runSubagent(taskInput, options) {
139
130
  const toolError = 'error' in event.toolOutput ? event.toolOutput.error : 'tool execution failed';
140
131
  if (toolCallLog.length < profile.maxToolCalls)
141
132
  toolCallLog.push({ name: event.toolCall.toolName, summary: output === undefined ? `failed: ${String(toolError).slice(0, 120)}` : toolSummary(output), durationMs: event.toolExecutionMs });
142
- const changedPath = changedPathFromOutput(event.toolCall.toolName, output);
143
- if (changedPath)
144
- changedPaths.add(changedPath);
133
+ for (const changedPath of changedPathsFromTool(event.toolCall.toolName, event.toolCall.input, output)) {
134
+ try {
135
+ changedPaths.add(workspaceRelativePath(resolveWorkspacePath(changedPath)));
136
+ }
137
+ catch { /* Ignore invalid paths in external results. */ }
138
+ }
145
139
  const validationRecord = validationFromOutput(event.toolCall.toolName, output);
146
- if (validationRecord)
140
+ if (validationRecord && validation.length < profile.maxToolCalls)
147
141
  validation.push(validationRecord);
148
142
  }
149
143
  },
150
144
  });
151
- usageIn = result.usage.inputTokens ?? usageIn;
152
- usageOut = result.usage.outputTokens ?? usageOut;
153
- const fullText = result.text.trim();
145
+ const [text, usage, steps] = await Promise.all([result.text, result.usage, result.steps]);
146
+ usageIn = usage.inputTokens ?? usageIn;
147
+ usageOut = usage.outputTokens ?? usageOut;
148
+ const fullText = text.trim();
154
149
  const truncated = fullText.length > profile.maxSummaryChars;
155
150
  const resultHandle = truncated ? storeToolOutput(fullText) : undefined;
156
151
  const deliverable = fullText
@@ -161,7 +156,7 @@ export async function runSubagent(taskInput, options) {
161
156
  const termination = options.deadlineExpired?.() ? 'deadline_exceeded'
162
157
  : options.abortSignal?.aborted ? 'cancelled'
163
158
  : toolLimited ? 'tool_limit'
164
- : result.steps.length >= maxSteps && !fullText ? 'step_limit'
159
+ : steps.length >= maxSteps && !fullText ? 'step_limit'
165
160
  : !fullText ? 'no_output'
166
161
  : 'completed';
167
162
  const capsule = { id: task.id, termination, usable: fullText.length > 0, deliverable, changedPaths: [...changedPaths].sort(), validation, coverageGaps: [], truncated, ...(resultHandle ? { resultHandle } : {}) };
@@ -177,9 +172,22 @@ export async function runSubagent(taskInput, options) {
177
172
  return withLegacyProjection(capsule, telemetry);
178
173
  }
179
174
  catch (error) {
180
- const message = error instanceof Error ? error.message : String(error);
175
+ // Bounded, actionable provider-failure capsule (RT-03): a worker that dies
176
+ // before producing output must tell the parent model what happened and what
177
+ // to do next — an empty deliverable (observed live: provider errors with no
178
+ // message surfaced as `deliverable: ""`) leaves the parent guessing and
179
+ // re-dispatching blind. Never echo provider bodies; bound the text.
180
+ const rawMessage = error instanceof Error && error.message.trim().length > 0 ? error.message.trim() : 'the provider call failed before any output';
181
+ const boundedMessage = rawMessage.length > 300 ? `${rawMessage.slice(0, 299)}…` : rawMessage;
182
+ const capsuleMessage = `${boundedMessage}. No usable worker output was produced; retry this subagent once with the same task, or do the work directly in the main conversation.`;
181
183
  const termination = options.deadlineExpired?.() ? 'deadline_exceeded' : options.abortSignal?.aborted ? 'cancelled' : 'provider_error';
182
- const result = terminalResult(task, runtime, profile, termination, message, options.queueMs);
184
+ const result = terminalResult(task, runtime, profile, termination, capsuleMessage, options.queueMs);
185
+ // Keep the raw provider message on the legacy `error` field so machine
186
+ // consumers see exactly what the provider said (unchanged contract).
187
+ result.error = rawMessage;
188
+ result.capsule.changedPaths = [...changedPaths].sort();
189
+ result.capsule.validation = [...validation];
190
+ result.telemetry.estimates.resultCapsuleTokens = estimateValueTokens(result.capsule);
183
191
  result.telemetry.durationMs = performance.now() - startedAt;
184
192
  result.durationMs = result.telemetry.durationMs;
185
193
  result.telemetry.toolCalls = toolCallLog;
@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { z } from 'zod';
5
5
  import { resolveWorkspacePath } from '../../utils/path.js';
6
+ import { assertRealPathInsideWorkspace, assertWritablePathInsideWorkspace } from '../../utils/path.js';
6
7
  const taskSchema = z.object({
7
8
  id: z.string(),
8
9
  title: z.string(),
@@ -23,7 +24,11 @@ export function generateTaskId() {
23
24
  }
24
25
  export async function loadTasks() {
25
26
  try {
26
- const content = await fs.readFile(getTasksFilePath(), 'utf-8');
27
+ const filePath = getTasksFilePath();
28
+ // CI-05: real-path confinement — a symlinked `.haze`/`tasks.json` must not
29
+ // redirect task state outside the workspace. Refusal is nonfatal (CR-012).
30
+ await assertRealPathInsideWorkspace(filePath, filePath);
31
+ const content = await fs.readFile(filePath, 'utf-8');
27
32
  return tasksSchema.parse(JSON.parse(content));
28
33
  }
29
34
  catch {
@@ -32,6 +37,8 @@ export async function loadTasks() {
32
37
  }
33
38
  export async function saveTasks(tasks) {
34
39
  const filePath = getTasksFilePath();
40
+ // Mutation guards fail closed: an escaped real path throws instead of writing.
41
+ await assertWritablePathInsideWorkspace(filePath, filePath);
35
42
  await fs.mkdir(path.dirname(filePath), { recursive: true });
36
43
  await fs.writeFile(filePath, JSON.stringify(tasks, null, 2), 'utf-8');
37
44
  }
@@ -1,4 +1,4 @@
1
- import type { ShellClassification } from '../safety/shellClassifier.js';
1
+ import { type ShellClassification } from '../safety/shellClassifier.js';
2
2
  import type { ValidationSummary } from '../../llm/toolResultTypes.js';
3
3
  export declare function parseValidationOutput(input: {
4
4
  command: string;
@@ -1,9 +1,14 @@
1
+ import { stripQuotedSpans } from '../safety/shellClassifier.js';
1
2
  import { capOutputForProcessing } from '../toolOutput/reduction.js';
2
3
  function uniq(values) {
3
4
  return [...new Set(values.filter(Boolean))];
4
5
  }
5
6
  function inferKind(command, classification) {
6
- const lower = command.toLowerCase();
7
+ // Shape-only inference on the unquoted command: kind authority must come
8
+ // from running a recognized tool, never from words the model authored
9
+ // inside a quoted payload (found by the honest-impossibility eval — a
10
+ // self-written `node -e` script mentioning "test" claimed kind 'test').
11
+ const lower = stripQuotedSpans(command).toLowerCase();
7
12
  if (/typecheck|\btsc\b/.test(lower))
8
13
  return 'typecheck';
9
14
  if (/\beslint\b|\blint\b/.test(lower))
@@ -85,6 +90,30 @@ export function parseValidationOutput(input) {
85
90
  summaryText = `${kind} failed: ${diagCount} diagnostic${diagCount === 1 ? '' : 's'}${uniqueFiles.length ? ` in ${uniqueFiles.join(', ')}` : ''}`;
86
91
  else
87
92
  summaryText = `${kind} ${status}`;
93
+ // First distinct failure lines are the diagnostic, not noise (RT-04): the
94
+ // live review session saw "release:verify" summarized as "10 failed tests"
95
+ // while the handle held 32 distinct mismatches, forcing a readToolOutput
96
+ // round-trip (a full model step) before the real failures were visible.
97
+ // Preserve up to three distinct first failure lines inline, bounded.
98
+ if (status !== 'passed' && status !== 'timed_out') {
99
+ const failureLines = [];
100
+ for (const line of lines) {
101
+ const trimmed = line.trim();
102
+ if (!trimmed)
103
+ continue;
104
+ const isFailureLine = /^(?:✗|FAIL|FAILED|AssertionError|Error:|error|✖|×|●)/i.test(trimmed)
105
+ || /^\S+\.(?:ts|tsx|js|jsx|mts|cts):\d+/i.test(trimmed)
106
+ || /\b(failed|mismatch|does not|missing|unexpected)\b/i.test(trimmed);
107
+ if (!isFailureLine)
108
+ continue;
109
+ if (!failureLines.some(existing => existing === trimmed))
110
+ failureLines.push(trimmed.length > 200 ? `${trimmed.slice(0, 199)}…` : trimmed);
111
+ if (failureLines.length >= 3)
112
+ break;
113
+ }
114
+ if (failureLines.length > 0)
115
+ summaryText = `${summaryText} — ${failureLines.join(' | ')}`;
116
+ }
88
117
  const suggestedNextStep = status === 'failed'
89
118
  ? uniqueFiles.length > 0
90
119
  ? `Inspect ${uniqueFiles.slice(0, 3).join(', ')} and fix the first relevant failure.`
@@ -1,6 +1,6 @@
1
1
  import { readSettings, type HazeProviderSettings } from '../config/settings.js';
2
2
  import type { ProviderCapabilities, ProviderRequestOptions, WorkerRuntime } from '../core/subagent/contracts.js';
3
- import { type ResolvedReasoningPolicy } from '../core/agent/reasoningPolicy.js';
3
+ import { type ResolvedReasoningPolicy, type StoredReasoningSetting } from '../core/agent/reasoningPolicy.js';
4
4
  export type { ProviderCapabilities, ProviderRequestOptions } from '../core/subagent/contracts.js';
5
5
  export interface ModelRuntimeSelection {
6
6
  model: WorkerRuntime['model'];
@@ -22,8 +22,8 @@ export interface ModelRuntimeConfig {
22
22
  * (128K hosted / 32K local) so `contextWindowSource` can flag the guess.
23
23
  */
24
24
  contextWindowTokens: number;
25
- /** Where contextWindowTokens came from: per-model settings, a user-set fallback, or the built-in default. */
26
- contextWindowSource: 'settings' | 'user-fallback' | 'default-fallback';
25
+ /** Where contextWindowTokens came from: per-model settings, the curated model catalog, a user-set fallback, or the built-in default. */
26
+ contextWindowSource: 'settings' | 'catalog' | 'user-fallback' | 'default-fallback';
27
27
  /** Optional output-token limit metadata for request budgeting (RH-005). */
28
28
  maxOutputTokens?: number;
29
29
  }
@@ -32,6 +32,7 @@ export declare function isLocalProviderUrl(url: string): boolean;
32
32
  export declare function modelWithConfig(session?: {
33
33
  cwd?: string;
34
34
  modelSelector?: string;
35
+ reasoningOverride?: StoredReasoningSetting;
35
36
  }, settings?: Awaited<ReturnType<typeof readSettings>>): Promise<ModelRuntimeSelection | undefined>;
36
37
  export declare function resolveWorkerRuntime(input: {
37
38
  active: ModelRuntimeSelection;