@denizokcu/haze 1.4.0 → 1.5.1

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 (134) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +28 -12
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/BusyBar.d.ts +7 -0
  6. package/dist/cli/chat/BusyBar.js +8 -0
  7. package/dist/cli/chat/DynamicFrame.d.ts +37 -0
  8. package/dist/cli/chat/DynamicFrame.js +48 -0
  9. package/dist/cli/chat/busyIndicator.d.ts +3 -1
  10. package/dist/cli/chat/busyIndicator.js +11 -9
  11. package/dist/cli/chat/chatMetrics.d.ts +1 -1
  12. package/dist/cli/chat/chatMetrics.js +3 -3
  13. package/dist/cli/chat/inputSuggestions.js +2 -1
  14. package/dist/cli/chat/liveRegion.js +1 -1
  15. package/dist/cli/chat/messages.js +27 -16
  16. package/dist/cli/chat/resizeGuard.d.ts +20 -0
  17. package/dist/cli/chat/resizeGuard.js +25 -0
  18. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  19. package/dist/cli/chat/sessionLifecycle.js +13 -2
  20. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  21. package/dist/cli/chat/sessionRecorder.js +8 -0
  22. package/dist/cli/chat/shutdown.d.ts +27 -0
  23. package/dist/cli/chat/shutdown.js +79 -0
  24. package/dist/cli/chat/terminalControl.d.ts +45 -0
  25. package/dist/cli/chat/terminalControl.js +107 -0
  26. package/dist/cli/chat/tips.js +1 -0
  27. package/dist/cli/chat/userInput.d.ts +43 -0
  28. package/dist/cli/chat/userInput.js +63 -0
  29. package/dist/cli/chat/wizard/sessionThemeHandlers.js +14 -6
  30. package/dist/cli/chat/wizard/types.d.ts +8 -1
  31. package/dist/cli/chat/wizardDispatch.js +1 -1
  32. package/dist/cli/commands/chat.js +258 -172
  33. package/dist/cli/commands/commandHelp.js +6 -2
  34. package/dist/cli/commands/commands.d.ts +8 -0
  35. package/dist/cli/commands/commands.js +11 -0
  36. package/dist/cli/commands/formatters.d.ts +1 -1
  37. package/dist/cli/commands/formatters.js +20 -2
  38. package/dist/cli/commands/logsCommand.js +21 -2
  39. package/dist/cli/commands/reasoningCommand.d.ts +23 -14
  40. package/dist/cli/commands/reasoningCommand.js +53 -20
  41. package/dist/cli/commands/runCommand.js +19 -11
  42. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  43. package/dist/cli/commands/streaming/attemptOutcome.js +11 -6
  44. package/dist/cli/commands/streaming/attemptSetup.d.ts +1 -0
  45. package/dist/cli/commands/streaming/attemptSetup.js +11 -5
  46. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +8 -1
  47. package/dist/cli/commands/streaming/goalCheckpoint.js +3 -2
  48. package/dist/cli/commands/streaming/goalSupervisor.d.ts +4 -0
  49. package/dist/cli/commands/streaming/goalSupervisor.js +43 -7
  50. package/dist/cli/commands/streaming/prepareStep.js +7 -3
  51. package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
  52. package/dist/cli/commands/streaming/streamLoop.js +3 -0
  53. package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
  54. package/dist/cli/commands/streaming.d.ts +1 -1
  55. package/dist/cli/commands/streaming.js +23 -17
  56. package/dist/cli/commands/wizardFlow.d.ts +5 -2
  57. package/dist/cli/commands/wizardFlow.js +17 -10
  58. package/dist/cli/index.js +17 -1
  59. package/dist/config/contextFiles.d.ts +9 -0
  60. package/dist/config/contextFiles.js +21 -1
  61. package/dist/config/modelCatalog.d.ts +3 -0
  62. package/dist/config/modelCatalog.js +29 -0
  63. package/dist/config/providerPresets.d.ts +1 -1
  64. package/dist/config/providerPresets.js +42 -3
  65. package/dist/config/settings.d.ts +11 -4
  66. package/dist/config/settings.js +9 -0
  67. package/dist/core/agent/budgets.d.ts +13 -15
  68. package/dist/core/agent/budgets.js +15 -17
  69. package/dist/core/agent/completionController.d.ts +6 -2
  70. package/dist/core/agent/completionController.js +16 -3
  71. package/dist/core/agent/goalPolicy.d.ts +10 -0
  72. package/dist/core/agent/goalPolicy.js +44 -6
  73. package/dist/core/agent/projectPreflight.d.ts +2 -0
  74. package/dist/core/agent/projectPreflight.js +56 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +34 -4
  76. package/dist/core/agent/reasoningPolicy.js +27 -4
  77. package/dist/core/agent/workState.d.ts +8 -0
  78. package/dist/core/agent/workState.js +191 -8
  79. package/dist/core/providerContracts.d.ts +32 -0
  80. package/dist/core/providerContracts.js +1 -0
  81. package/dist/core/session/sessionReport.d.ts +33 -0
  82. package/dist/core/session/sessionReport.js +121 -0
  83. package/dist/core/session/sessionSlimming.js +9 -3
  84. package/dist/core/session/sessionStore.d.ts +12 -0
  85. package/dist/core/session/sessionStore.js +20 -4
  86. package/dist/core/subagent/contracts.d.ts +3 -25
  87. package/dist/core/subagent/executionProfiles.js +4 -4
  88. package/dist/core/validation/outputParser.d.ts +6 -1
  89. package/dist/core/validation/outputParser.js +6 -2
  90. package/dist/llm/client.d.ts +4 -2
  91. package/dist/llm/client.js +44 -16
  92. package/dist/llm/hazeTools.d.ts +8553 -8550
  93. package/dist/llm/hazeTools.js +6 -503
  94. package/dist/llm/lspTools.d.ts +120 -120
  95. package/dist/llm/mcp.js +3 -0
  96. package/dist/llm/requestContext.d.ts +1 -1
  97. package/dist/llm/requestContext.js +1 -1
  98. package/dist/{core/subagent → llm}/subagentRunner.d.ts +9 -9
  99. package/dist/{core/subagent → llm}/subagentRunner.js +22 -25
  100. package/dist/llm/systemPrompt.d.ts +11 -1
  101. package/dist/llm/systemPrompt.js +2 -11
  102. package/dist/llm/tools/fetchTool.d.ts +30 -30
  103. package/dist/llm/tools/fileTools.d.ts +7768 -0
  104. package/dist/llm/tools/fileTools.js +510 -0
  105. package/dist/llm/tools/processTool.d.ts +30 -30
  106. package/dist/llm/tools/shellTool.d.ts +30 -30
  107. package/dist/llm/tools/shellTool.js +8 -4
  108. package/dist/llm/tools/toolContext.d.ts +3 -32
  109. package/dist/llm/tools/toolContext.js +33 -52
  110. package/dist/llm/tools/toolContextState.d.ts +40 -0
  111. package/dist/llm/tools/toolContextState.js +34 -0
  112. package/dist/llm/workerContext.d.ts +7 -0
  113. package/dist/llm/workerContext.js +18 -1
  114. package/dist/skills/SkillLoader.js +3 -3
  115. package/dist/skills/SkillRegistry.js +3 -3
  116. package/dist/skills/builder/SkillBuilder.js +3 -3
  117. package/dist/skills/confinement.d.ts +7 -0
  118. package/dist/skills/confinement.js +15 -0
  119. package/dist/ui/codeHighlight.js +4 -4
  120. package/dist/ui/components/MarkdownText.js +7 -8
  121. package/dist/ui/components/NativeIndicators.d.ts +15 -0
  122. package/dist/ui/components/NativeIndicators.js +32 -0
  123. package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
  124. package/dist/ui/components/StreamingMarkdownText.js +38 -0
  125. package/dist/ui/components/TextInput.d.ts +7 -2
  126. package/dist/ui/components/TextInput.js +103 -46
  127. package/dist/ui/components/WizardChoices.d.ts +18 -0
  128. package/dist/ui/components/WizardChoices.js +32 -0
  129. package/dist/ui/inputBuffer.js +12 -6
  130. package/dist/ui/textGeometry.d.ts +14 -0
  131. package/dist/ui/textGeometry.js +31 -0
  132. package/package.json +14 -13
  133. /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
  134. /package/dist/cli/{contextReport.js → contextReportCli.js} +0 -0
@@ -0,0 +1,121 @@
1
+ function record(value) {
2
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
3
+ }
4
+ /** Summarize a session without copying prompts, commands, paths, or tool output. */
5
+ export function summarizeSessionEntries(entries) {
6
+ const report = {
7
+ models: [], peakInputTokens: 0, steps: 0, toolCalls: {}, failedToolCalls: 0,
8
+ failedValidations: {}, continuations: 0, compactions: 0, budgetBoundaries: 0, goals: [],
9
+ };
10
+ const goals = new Map();
11
+ const finalEvidence = new Map();
12
+ const hasCompactEntries = entries.some(entry => entry.type === 'compact');
13
+ for (const entry of entries) {
14
+ if (entry.type === 'header') {
15
+ report.sessionId = entry.id;
16
+ report.version = entry.hazeVersion;
17
+ }
18
+ else if (entry.type === 'compact') {
19
+ report.compactions++;
20
+ }
21
+ else if (entry.type === 'goal') {
22
+ let goal = goals.get(entry.goalId);
23
+ if (!goal) {
24
+ goal = { id: entry.goalId, intent: entry.intent, cycles: 0, status: 'active', validation: 'not_applicable', openTasks: 0, mutations: 0, openCheckCount: 0 };
25
+ goals.set(entry.goalId, goal);
26
+ report.goals.push(goal);
27
+ }
28
+ goal.cycles = Math.max(goal.cycles, entry.cycle);
29
+ goal.validation = entry.validationOutcome;
30
+ goal.mutations = entry.mutationCount;
31
+ goal.openTasks = (entry.taskCounts?.pending ?? 0) + (entry.taskCounts?.inProgress ?? 0);
32
+ goal.openCheckCount = entry.failedCheckIds?.length ?? 0;
33
+ if (entry.phase === 'goal_end') {
34
+ goal.status = entry.status ?? 'unknown';
35
+ goal.stopReason = entry.stopReason;
36
+ goal.gateDecision = entry.gateDecision;
37
+ }
38
+ else {
39
+ goal.status = 'active';
40
+ delete goal.stopReason;
41
+ delete goal.gateDecision;
42
+ finalEvidence.delete(entry.goalId);
43
+ }
44
+ }
45
+ else if (entry.type === 'event' && entry.text) {
46
+ let event;
47
+ try {
48
+ event = record(JSON.parse(entry.text));
49
+ }
50
+ catch {
51
+ continue;
52
+ }
53
+ if (!event)
54
+ continue;
55
+ if (entry.name === 'step_end') {
56
+ report.steps++;
57
+ if (typeof event.responseModel === 'string') {
58
+ report.model = event.responseModel;
59
+ if (!report.models.includes(event.responseModel))
60
+ report.models.push(event.responseModel);
61
+ }
62
+ const usage = record(event.usage);
63
+ if (typeof usage?.inputTokens === 'number')
64
+ report.peakInputTokens = Math.max(report.peakInputTokens, usage.inputTokens);
65
+ }
66
+ else if (entry.name === 'tool_end') {
67
+ const name = typeof event.name === 'string' ? event.name : 'unknown';
68
+ report.toolCalls[name] = (report.toolCalls[name] ?? 0) + 1;
69
+ if (event.success === false)
70
+ report.failedToolCalls++;
71
+ const summary = record(event.validation) ?? record(record(event.output)?.validationSummary);
72
+ if (summary?.status === 'failed') {
73
+ const kind = typeof summary.kind === 'string' ? summary.kind : 'generic';
74
+ report.failedValidations[kind] = (report.failedValidations[kind] ?? 0) + 1;
75
+ }
76
+ }
77
+ else if (entry.name === 'goal_continue') {
78
+ report.continuations++;
79
+ }
80
+ else if (entry.name === 'turn_end' && record(event.evidence)?.budgetBoundary === true) {
81
+ report.budgetBoundaries++;
82
+ }
83
+ else if (entry.name === 'goal_end' && typeof event.goalId === 'string') {
84
+ const evidence = record(event.evidence);
85
+ if (evidence)
86
+ finalEvidence.set(event.goalId, evidence);
87
+ }
88
+ else if (entry.name === 'reasoning_policy' && typeof event.effective === 'string') {
89
+ report.reasoning = event.effective;
90
+ }
91
+ else if (entry.name === 'context_budget' && typeof event.contextWindowTokens === 'number') {
92
+ report.contextWindowTokens = event.contextWindowTokens;
93
+ }
94
+ else if (!hasCompactEntries && entry.name === 'compaction_end' && event.compacted === true) {
95
+ report.compactions++;
96
+ }
97
+ }
98
+ }
99
+ for (const goal of report.goals) {
100
+ const evidence = finalEvidence.get(goal.id);
101
+ if (!evidence || goal.status === 'active')
102
+ continue;
103
+ const tasks = record(evidence.taskProgress);
104
+ const eventOpenTasks = (typeof tasks?.pending === 'number' ? tasks.pending : 0) + (typeof tasks?.inProgress === 'number' ? tasks.inProgress : 0);
105
+ if (evidence.validationOutcome !== goal.validation || evidence.mutationCount !== goal.mutations || eventOpenTasks !== goal.openTasks)
106
+ goal.evidenceMismatch = true;
107
+ }
108
+ return report;
109
+ }
110
+ export function formatSessionReport(report, parseErrors = 0) {
111
+ const toolLines = Object.entries(report.toolCalls).sort((a, b) => b[1] - a[1]).map(([name, count]) => ` ${name}: ${count}`);
112
+ const goalLines = report.goals.map(goal => ` ${goal.id}: ${goal.status}${goal.stopReason ? ` (${goal.stopReason})` : ''} · ${goal.intent} · ${goal.cycles} cycle(s) · gate ${goal.gateDecision ?? 'unknown'} · validation ${goal.validation} · ${goal.openTasks} open task(s) · ${goal.openCheckCount} open check(s)${goal.evidenceMismatch ? ' · terminal evidence mismatch' : ''}`);
113
+ return [
114
+ `Session ${report.sessionId ?? 'unknown'}${report.version ? ` · Haze ${report.version}` : ''}`,
115
+ `Models: ${report.models.join(' → ') || report.model || 'unknown'}${report.reasoning ? ` · reasoning ${report.reasoning}` : ''}${report.contextWindowTokens ? ` · context ${report.contextWindowTokens}` : ''}`,
116
+ `Steps: ${report.steps} · peak input: ${report.peakInputTokens} tokens · continuations: ${report.continuations} · budget boundaries: ${report.budgetBoundaries} · compactions: ${report.compactions}`,
117
+ `Tool failures: ${report.failedToolCalls} · failed validations: ${Object.entries(report.failedValidations).map(([kind, count]) => `${kind} ${count}`).join(', ') || '0'}`,
118
+ ...(parseErrors ? [`Parse errors: ${parseErrors}`] : []),
119
+ 'Goals:', ...goalLines, 'Tool calls:', ...toolLines,
120
+ ].join('\n');
121
+ }
@@ -145,11 +145,17 @@ export function prepareSessionEntryForWrite(entry) {
145
145
  if (entry.name === 'tool_end' && entry.text) {
146
146
  try {
147
147
  const event = JSON.parse(entry.text);
148
+ const output = isRecord(event.output) ? event.output : undefined;
149
+ const validation = isRecord(output?.validationSummary) ? output.validationSummary : undefined;
150
+ // Keep the outcome even when the output body is replaced by a preview.
151
+ // The report needs only these enums, never command text or diagnostics.
152
+ if (validation && typeof validation.kind === 'string' && (validation.status === 'passed' || validation.status === 'failed')) {
153
+ event.validation = { kind: validation.kind, status: validation.status };
154
+ }
148
155
  if (event.name === 'subagent' && typeof event.output === 'object' && event.output != null) {
149
- const output = event.output;
150
- const telemetry = typeof output.telemetry === 'object' && output.telemetry != null ? output.telemetry : undefined;
156
+ const telemetry = typeof output?.telemetry === 'object' && output.telemetry != null ? output.telemetry : undefined;
151
157
  event.output = {
152
- capsule: output.capsule,
158
+ capsule: output?.capsule,
153
159
  coordinator: telemetry ? { modelSelector: telemetry.modelSelector, profile: telemetry.profile, durationMs: telemetry.durationMs, queueMs: telemetry.queueMs, toolCallCount: telemetry.toolCallCount } : undefined,
154
160
  };
155
161
  }
@@ -1,6 +1,10 @@
1
1
  import type { ModelMessage } from 'ai';
2
2
  import type { WorkState } from '../agent/workState.js';
3
3
  import type { ValidationKind } from '../../llm/toolResultTypes.js';
4
+ export interface SessionModelSelection {
5
+ provider: string;
6
+ model: string;
7
+ }
4
8
  export type SessionEntry = {
5
9
  type: 'header';
6
10
  id: string;
@@ -25,6 +29,10 @@ export type SessionEntry = {
25
29
  type: 'work_state_snapshot';
26
30
  at: string;
27
31
  state: WorkState;
32
+ } | {
33
+ type: 'model_selection';
34
+ at: string;
35
+ selection: SessionModelSelection;
28
36
  } | {
29
37
  type: 'event';
30
38
  at: string;
@@ -64,8 +72,10 @@ export type SessionEntry = {
64
72
  summary: string;
65
73
  };
66
74
  validationKind?: ValidationKind;
75
+ failedCheckIds?: string[];
67
76
  stopReason?: string;
68
77
  status?: string;
78
+ gateDecision?: string;
69
79
  };
70
80
  /** Durable goal-ledger entry (P1): one append per supervisor boundary. */
71
81
  export type GoalLedgerEntry = Extract<SessionEntry, {
@@ -86,6 +96,7 @@ export interface GoalLedgerFrontier {
86
96
  redEvidence?: GoalLedgerEntry['redEvidence'];
87
97
  /** Kind of the frontier's carried validation, when one rode the ledger (R2-03). */
88
98
  validationKind?: ValidationKind;
99
+ failedCheckIds?: string[];
89
100
  at: string;
90
101
  }
91
102
  type SessionHeader = Extract<SessionEntry, {
@@ -154,6 +165,7 @@ export interface RestoreConversationResult {
154
165
  }
155
166
  export interface RestoreSessionStateResult {
156
167
  messages: ModelMessage[];
168
+ modelSelection?: SessionModelSelection;
157
169
  workState: WorkState | undefined;
158
170
  parseErrors: string[];
159
171
  /** Unterminated goal frontier from the durable ledger, if any (P1 resume path). */
@@ -113,7 +113,7 @@ export async function appendSessionEntry(session, entry) {
113
113
  * type, so dropping superseded ones is lossless for restore; summaries keep
114
114
  * their ui_message/event history). Atomic replace, never partial.
115
115
  */
116
- export const SESSION_VACUUM_THRESHOLD_BYTES = 16 * 1024 * 1024;
116
+ export const SESSION_VACUUM_THRESHOLD_BYTES = 5 * 1024 * 1024;
117
117
  let effectiveVacuumThresholdBytes = SESSION_VACUUM_THRESHOLD_BYTES;
118
118
  /** Test-only override for the vacuum trigger; tests restore the original. */
119
119
  export function setSessionVacuumThresholdForTests(bytes) {
@@ -205,6 +205,9 @@ const LEDGER_VALIDATION_KINDS = new Set(['test', 'typecheck', 'lint', 'build', '
205
205
  function optionalLedgerValidationKind(value) {
206
206
  return value === undefined || (typeof value === 'string' && LEDGER_VALIDATION_KINDS.has(value));
207
207
  }
208
+ function optionalFailedCheckIds(value) {
209
+ return value === undefined || (Array.isArray(value) && value.every(id => typeof id === 'string' && /^[0-9a-f]{16}$/.test(id)));
210
+ }
208
211
  function frontierFromGoalEntry(entry) {
209
212
  return {
210
213
  goalId: entry.goalId,
@@ -218,6 +221,7 @@ function frontierFromGoalEntry(entry) {
218
221
  ...(entry.taskCounts ? { taskCounts: entry.taskCounts } : {}),
219
222
  ...(entry.redEvidence ? { redEvidence: entry.redEvidence } : {}),
220
223
  ...(entry.validationKind ? { validationKind: entry.validationKind } : {}),
224
+ ...(entry.failedCheckIds?.length ? { failedCheckIds: [...entry.failedCheckIds] } : {}),
221
225
  at: entry.at,
222
226
  };
223
227
  }
@@ -250,6 +254,12 @@ function parseSessionEntry(value) {
250
254
  && MODEL_MESSAGE_ROLES.has(message.role)))
251
255
  return invalid('conversation_snapshot contains an invalid message role');
252
256
  return value;
257
+ case 'model_selection':
258
+ if (typeof value.at !== 'string' || !isRecord(value.selection)
259
+ || typeof value.selection.provider !== 'string' || !value.selection.provider.trim()
260
+ || typeof value.selection.model !== 'string' || !value.selection.model.trim())
261
+ return invalid('invalid model_selection');
262
+ return value;
253
263
  case 'work_state_snapshot':
254
264
  if (typeof value.at !== 'string' || !isRecord(value.state))
255
265
  return invalid('work_state_snapshot state must be an object');
@@ -271,9 +281,10 @@ function parseSessionEntry(value) {
271
281
  || typeof value.cycle !== 'number' || typeof value.mutationCount !== 'number'
272
282
  || typeof value.validationOutcome !== 'string' || typeof value.progressSignature !== 'string'
273
283
  || !optionalTaskCounts(value.taskCounts)
274
- || !optionalString(value.stopReason) || !optionalString(value.status)
284
+ || !optionalString(value.stopReason) || !optionalString(value.status) || !optionalString(value.gateDecision)
275
285
  || !optionalLedgerRedEvidence(value.redEvidence)
276
- || !optionalLedgerValidationKind(value.validationKind))
286
+ || !optionalLedgerValidationKind(value.validationKind)
287
+ || !optionalFailedCheckIds(value.failedCheckIds))
277
288
  return invalid('invalid goal');
278
289
  return value;
279
290
  default:
@@ -372,6 +383,7 @@ export async function readGoalLedgerFrontier(session) {
372
383
  export async function restoreSessionState(session) {
373
384
  let messages = [];
374
385
  let workState;
386
+ let modelSelection;
375
387
  const tracker = new GoalLedgerFrontierTracker();
376
388
  const parseErrors = await scanSessionEntries(session, entry => {
377
389
  // Legacy slim markers (pre-envelope-fix) are re-wrapped so the restored
@@ -385,11 +397,13 @@ export async function restoreSessionState(session) {
385
397
  messages = [];
386
398
  workState = undefined;
387
399
  }
400
+ if (entry.type === 'model_selection')
401
+ modelSelection = entry.selection;
388
402
  if (entry.type === 'work_state_snapshot')
389
403
  workState = entry.state;
390
404
  tracker.observe(entry);
391
405
  });
392
- return { messages, workState, parseErrors, goalFrontier: tracker.result() };
406
+ return { messages, workState, parseErrors, goalFrontier: tracker.result(), ...(modelSelection ? { modelSelection } : {}) };
393
407
  }
394
408
  export async function restoreConversation(session) {
395
409
  const { messages, parseErrors } = await restoreSessionState(session);
@@ -502,6 +516,8 @@ export async function forkSession(source, options = {}) {
502
516
  throw new Error(`Session ${source.id} has no conversation snapshot to fork.`);
503
517
  const session = await createSession({ cwd: source.cwd, sessionsDir: options.sessionsDir, hazeVersion: options.hazeVersion, forkedFrom: source.id, ...(options.build ? { build: options.build } : {}) });
504
518
  const at = new Date().toISOString();
519
+ if (restored.modelSelection)
520
+ await appendSessionEntry(session, { type: 'model_selection', at, selection: restored.modelSelection });
505
521
  await appendSessionEntry(session, { type: 'conversation_snapshot', at, messages: restored.messages });
506
522
  if (restored.workState)
507
523
  await appendSessionEntry(session, { type: 'work_state_snapshot', at, state: restored.workState });
@@ -1,6 +1,7 @@
1
- import type { JSONValue, LanguageModel } from 'ai';
1
+ import type { LanguageModel } from 'ai';
2
2
  import { z } from 'zod';
3
- import type { ReasoningLevel } from '../agent/reasoningPolicy.js';
3
+ import type { ProviderCapabilities, ProviderRequestOptions } from '../providerContracts.js';
4
+ export type { ProviderCapabilities, ProviderRequestOptions } from '../providerContracts.js';
4
5
  declare const workerModes: readonly ["inspect", "research", "implement", "validate"];
5
6
  export type WorkerMode = typeof workerModes[number];
6
7
  export declare const subagentInputSchema: z.ZodObject<{
@@ -77,28 +78,6 @@ export interface SubagentExecutionResult {
77
78
  durationMs: number;
78
79
  error?: string;
79
80
  }
80
- export interface ProviderCapabilities {
81
- reportsCacheUsage: boolean;
82
- supportsPromptCacheKey: boolean;
83
- supportsExtendedCacheRetention: boolean;
84
- supportsStickySessionId: boolean;
85
- supportsServerCompaction: boolean;
86
- supportsTextVerbosity: boolean;
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
- */
92
- supportsReasoningEffort: boolean;
93
- }
94
- export interface ProviderRequestOptions {
95
- providerOptions?: Record<string, Record<string, JSONValue | undefined>>;
96
- headers?: Record<string, string>;
97
- /** AI SDK top-level `reasoning` call setting; omitted when unset/unsupported. */
98
- reasoning?: ReasoningLevel;
99
- /** Codex subscription requests let the provider manage the output limit. */
100
- omitMaxOutputTokens?: boolean;
101
- }
102
81
  export interface WorkerRuntime {
103
82
  model: LanguageModel;
104
83
  selector: string;
@@ -112,4 +91,3 @@ export declare function fallbackProviderCapabilities(): ProviderCapabilities;
112
91
  export declare function fallbackWorkerRuntime(model: WorkerRuntime['model'], selector?: string, providerName?: string): WorkerRuntime;
113
92
  export declare function normalizeSubagentInput(input: SubagentToolInput, id: string): SubagentTaskCapsule;
114
93
  export declare function withLegacyProjection(capsule: SubagentResultCapsule, telemetry: SubagentTelemetry, error?: string): SubagentExecutionResult;
115
- export {};
@@ -17,10 +17,10 @@ export const COMPATIBILITY_PROFILE = {
17
17
  deadlineMs: SUBAGENT_DEFAULT_DEADLINE_MS, maxRetries: 2,
18
18
  };
19
19
  export const BUILT_IN_SUBAGENT_PROFILES = {
20
- 'local-safe': { ...COMPATIBILITY_PROFILE, name: 'local-safe', maxConcurrency: 1, maxSteps: 16, maxToolCalls: 12, maxOutputTokens: 2_048, maxInputTokens: 20_000, maxRetries: 0 },
21
- 'local-throughput': { ...COMPATIBILITY_PROFILE, name: 'local-throughput', maxConcurrency: 2, maxSteps: 20, maxToolCalls: 16, maxOutputTokens: 3_072, maxInputTokens: 24_000, maxRetries: 0 },
22
- 'cloud-balanced': { ...COMPATIBILITY_PROFILE, name: 'cloud-balanced', maxConcurrency: 3, deadlineMs: 180_000 },
23
- 'cloud-fast': { ...COMPATIBILITY_PROFILE, name: 'cloud-fast', maxConcurrency: 5, deadlineMs: 120_000, maxRetries: 1 },
20
+ 'local-safe': { ...COMPATIBILITY_PROFILE, name: 'local-safe', maxConcurrency: 1, maxSteps: 32, maxToolCalls: 24, maxOutputTokens: 4_096, maxInputTokens: 40_000, maxRetries: 0 },
21
+ 'local-throughput': { ...COMPATIBILITY_PROFILE, name: 'local-throughput', maxConcurrency: 2, maxSteps: 40, maxToolCalls: 32, maxOutputTokens: 6_144, maxInputTokens: 48_000, maxRetries: 0 },
22
+ 'cloud-balanced': { ...COMPATIBILITY_PROFILE, name: 'cloud-balanced', maxConcurrency: 3, deadlineMs: 360_000 },
23
+ 'cloud-fast': { ...COMPATIBILITY_PROFILE, name: 'cloud-fast', maxConcurrency: 5, deadlineMs: 240_000, maxRetries: 1 },
24
24
  };
25
25
  export const MODE_TOOL_NAMES = {
26
26
  inspect: ['listFiles', 'readFile', 'grep', 'readToolOutput'],
@@ -1,5 +1,10 @@
1
1
  import { type ShellClassification } from '../safety/shellClassifier.js';
2
- import type { ValidationSummary } from '../../llm/toolResultTypes.js';
2
+ import type { ValidationKind, ValidationSummary } from '../../llm/toolResultTypes.js';
3
+ /**
4
+ * Shape-only kind inference on the unquoted command, exported for per-stage
5
+ * classification of `&&` compounds in work-state validation recording.
6
+ */
7
+ export declare function inferValidationKind(command: string, classification?: ShellClassification): ValidationKind;
3
8
  export declare function parseValidationOutput(input: {
4
9
  command: string;
5
10
  code: number | null;
@@ -3,7 +3,11 @@ import { capOutputForProcessing } from '../toolOutput/reduction.js';
3
3
  function uniq(values) {
4
4
  return [...new Set(values.filter(Boolean))];
5
5
  }
6
- function inferKind(command, classification) {
6
+ /**
7
+ * Shape-only kind inference on the unquoted command, exported for per-stage
8
+ * classification of `&&` compounds in work-state validation recording.
9
+ */
10
+ export function inferValidationKind(command, classification) {
7
11
  // Shape-only inference on the unquoted command: kind authority must come
8
12
  // from running a recognized tool, never from words the model authored
9
13
  // inside a quoted payload (found by the honest-impossibility eval — a
@@ -25,7 +29,7 @@ export function parseValidationOutput(input) {
25
29
  const diagnostics = [];
26
30
  const failedTests = [];
27
31
  const failedFiles = [];
28
- const kind = inferKind(input.command, input.classification);
32
+ const kind = inferValidationKind(input.command, input.classification);
29
33
  for (let index = 0; index < lines.length; index++) {
30
34
  const line = lines[index];
31
35
  const ts = line.match(/^(.+?\.(?:ts|tsx|js|jsx|mts|cts))\((\d+),(\d+)\):\s+(error|warning)\s+TS\d+:\s+(.+)$/);
@@ -1,7 +1,8 @@
1
1
  import { readSettings, type HazeProviderSettings } from '../config/settings.js';
2
- import type { ProviderCapabilities, ProviderRequestOptions, WorkerRuntime } from '../core/subagent/contracts.js';
2
+ import type { ProviderCapabilities, ProviderRequestOptions } from '../core/providerContracts.js';
3
+ import type { WorkerRuntime } from '../core/subagent/contracts.js';
3
4
  import { type ResolvedReasoningPolicy, type StoredReasoningSetting } from '../core/agent/reasoningPolicy.js';
4
- export type { ProviderCapabilities, ProviderRequestOptions } from '../core/subagent/contracts.js';
5
+ export type { ProviderCapabilities, ProviderRequestOptions } from '../core/providerContracts.js';
5
6
  export interface ModelRuntimeSelection {
6
7
  model: WorkerRuntime['model'];
7
8
  config: ModelRuntimeConfig;
@@ -33,6 +34,7 @@ export declare function modelWithConfig(session?: {
33
34
  cwd?: string;
34
35
  modelSelector?: string;
35
36
  reasoningOverride?: StoredReasoningSetting;
37
+ reasoningByModel?: Record<string, StoredReasoningSetting>;
36
38
  }, settings?: Awaited<ReturnType<typeof readSettings>>): Promise<ModelRuntimeSelection | undefined>;
37
39
  export declare function resolveWorkerRuntime(input: {
38
40
  active: ModelRuntimeSelection;
@@ -4,7 +4,7 @@ import { readSettings } from '../config/settings.js';
4
4
  import { catalogLimitsFor } from '../config/modelCatalog.js';
5
5
  import { activeModel, modelSelector, resolveModelSelector } from '../config/providers.js';
6
6
  import { assertCredentialedEndpointSecure } from '../config/endpointSecurity.js';
7
- import { effectiveRequestedReasoning, isStoredReasoning, reasoningCallSetting, resolveReasoningPolicy } from '../core/agent/reasoningPolicy.js';
7
+ import { effectiveRequestedReasoning, isStoredReasoning, reasoningCallSetting, resolveAttemptReasoning, resolveReasoningPolicy } from '../core/agent/reasoningPolicy.js';
8
8
  import { FALLBACK_CONTEXT_WINDOW_TOKENS, FALLBACK_LOCAL_CONTEXT_TOKENS } from '../core/agent/contextBudget.js';
9
9
  import { createChatGptCodexFetch } from './openaiCodex.js';
10
10
  const HAZE_SITE_URL = 'https://denizokcu.github.io/haze/';
@@ -24,9 +24,16 @@ function openRouterHeaders(providerName, baseURL) {
24
24
  'X-Title': HAZE_TITLE,
25
25
  };
26
26
  }
27
- function capabilities(providerName, baseURL, providerKind) {
27
+ function capabilities(providerName, baseURL, providerKind, explicit) {
28
28
  const directOpenAI = providerKind !== 'chatgpt-codex' && (providerName === 'openai' || /api\.openai\.com/i.test(baseURL));
29
29
  const openRouter = isOpenRouter(providerName, baseURL);
30
+ // Reasoning-effort support is explicit-first: a user override wins either
31
+ // way. Otherwise loopback/local inference servers (LM Studio, Ollama,
32
+ // llama.cpp) default to `false`: their own reasoning switches coerce
33
+ // unsupported levels — even `none` — to `on` (LM Studio), inverting the
34
+ // request, and subagent workers rely on `none` meaning off. Hosted
35
+ // OpenAI-compatible endpoints keep the SDK pass-through (`true`).
36
+ const supportsReasoningEffort = explicit?.reasoningEffort ?? !isLocalProviderUrl(baseURL);
30
37
  return {
31
38
  reportsCacheUsage: directOpenAI || openRouter,
32
39
  supportsPromptCacheKey: directOpenAI,
@@ -34,11 +41,25 @@ function capabilities(providerName, baseURL, providerKind) {
34
41
  supportsStickySessionId: openRouter,
35
42
  supportsServerCompaction: false,
36
43
  supportsTextVerbosity: directOpenAI,
37
- // Pass-through marker: the SDK maps the top-level `reasoning` parameter
38
- // per provider and endpoints without native support ignore the field.
39
- supportsReasoningEffort: true,
44
+ supportsReasoningEffort,
40
45
  };
41
46
  }
47
+ /**
48
+ * Match the pinned OpenAI SDK's GPT-6+ effort restrictions before transport.
49
+ * Unsupported choices are omitted, not promoted to a different effort; the
50
+ * policy retains the request and explains why the provider default will apply.
51
+ */
52
+ function reasoningPolicyForModel(modelName, requested, caps) {
53
+ const policy = resolveReasoningPolicy({ requested, capabilities: caps });
54
+ if (policy.effective === 'disabled')
55
+ return policy;
56
+ const version = /^gpt-(\d+)(?:\.\d+)?(?:-.+)?$/.exec(modelName);
57
+ const supportsNone = modelName === 'gpt-6-sol' || modelName === 'gpt-6-luna';
58
+ if (version && Number(version[1]) >= 6 && (requested === 'minimal' || (requested === 'none' && !supportsNone))) {
59
+ return { requested, effective: 'disabled', reason: `${modelName} does not support reasoning effort ${requested}; parameter omitted (provider default). Choose low, medium, high, xhigh, or unset.` };
60
+ }
61
+ return policy;
62
+ }
42
63
  /** True for loopback/local inference servers, whose effective window is server-configured (often far below the model's). */
43
64
  export function isLocalProviderUrl(url) {
44
65
  try {
@@ -49,7 +70,7 @@ export function isLocalProviderUrl(url) {
49
70
  return false;
50
71
  }
51
72
  }
52
- function runtimeForSelection(settings, selection, cwd, reasoningOverride) {
73
+ function runtimeForSelection(settings, selection, cwd, reasoningOverride, sessionReasoningByModel) {
53
74
  const baseURL = selection.provider.url;
54
75
  const providerKind = selection.provider.kind;
55
76
  const configuredKey = providerKind === 'chatgpt-codex' ? undefined : selection.provider.key ?? settings.apiKey;
@@ -58,15 +79,22 @@ function runtimeForSelection(settings, selection, cwd, reasoningOverride) {
58
79
  const name = selection.model;
59
80
  const cacheSeed = cwd ?? process.cwd();
60
81
  const cacheKey = crypto.createHash('sha256').update(`${cacheSeed}\0${name}`).digest('hex').slice(0, 32);
61
- const caps = capabilities(selection.provider.name, baseURL, providerKind);
62
- // Run-scoped reasoning override (CLI `--reasoning`): an explicit level or
63
- // the provider-default sentinel wins for this run; otherwise the stored
64
- // settings value (default high, sentinel → no parameter) applies. The
65
- // capability gate in resolveReasoningPolicy is unchanged — an override never
66
- // forces the parameter onto an unsupported protocol.
67
- const storedReasoning = reasoningOverride ?? (isStoredReasoning(settings.reasoning) ? settings.reasoning : undefined);
82
+ const caps = capabilities(selection.provider.name, baseURL, providerKind, selection.provider.capabilities);
83
+ const selector = modelSelector(selection.provider, name);
84
+ // The full precedence chain lives in one pure resolver
85
+ // (`resolveAttemptReasoning`): run-scoped override → session per-model map →
86
+ // global settings → built-in default (medium). The stored or session
87
+ // `provider-default` sentinel sends no parameter at all. The capability gate
88
+ // in resolveReasoningPolicy is unchanged — nothing forces the parameter onto
89
+ // an unsupported protocol.
90
+ const storedReasoning = resolveAttemptReasoning({
91
+ modelSelector: selector,
92
+ runOverride: reasoningOverride,
93
+ sessionReasoningByModel,
94
+ globalSetting: isStoredReasoning(settings.reasoning) ? settings.reasoning : undefined,
95
+ });
68
96
  const requestedReasoning = effectiveRequestedReasoning(storedReasoning);
69
- const reasoningPolicy = resolveReasoningPolicy({ requested: requestedReasoning, capabilities: caps });
97
+ const reasoningPolicy = reasoningPolicyForModel(name, requestedReasoning, caps);
70
98
  const openai = providerKind === 'chatgpt-codex'
71
99
  ? createOpenAI({ apiKey: OAUTH_SDK_SENTINEL, baseURL, fetch: createChatGptCodexFetch(selection.provider.name) })
72
100
  : createOpenAI({ apiKey, baseURL, headers: openRouterHeaders(selection.provider.name, baseURL) });
@@ -91,7 +119,7 @@ function runtimeForSelection(settings, selection, cwd, reasoningOverride) {
91
119
  const maxOutputTokens = limits.maxOutputTokens ?? catalog?.maxOutputTokens;
92
120
  return {
93
121
  model: providerKind === 'chatgpt-codex' ? openai.responses(name) : openai.chat(name),
94
- selector: modelSelector(selection.provider, name),
122
+ selector,
95
123
  config: {
96
124
  providerName: selection.provider.name,
97
125
  providerKind,
@@ -131,7 +159,7 @@ export async function modelWithConfig(session, settings) {
131
159
  }
132
160
  else
133
161
  selection = activeModel(resolvedSettings);
134
- return selection ? runtimeForSelection(resolvedSettings, selection, session?.cwd, session?.reasoningOverride) : undefined;
162
+ return selection ? runtimeForSelection(resolvedSettings, selection, session?.cwd, session?.reasoningOverride, session?.reasoningByModel) : undefined;
135
163
  }
136
164
  export async function resolveWorkerRuntime(input) {
137
165
  const requested = input.selector?.trim();