@denizokcu/haze 1.4.0 → 1.5.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 (132) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/README.md +13 -8
  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 +43 -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/sessionLifecycle.d.ts +3 -1
  17. package/dist/cli/chat/sessionLifecycle.js +13 -2
  18. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  19. package/dist/cli/chat/sessionRecorder.js +8 -0
  20. package/dist/cli/chat/shutdown.d.ts +27 -0
  21. package/dist/cli/chat/shutdown.js +79 -0
  22. package/dist/cli/chat/terminalControl.d.ts +45 -0
  23. package/dist/cli/chat/terminalControl.js +107 -0
  24. package/dist/cli/chat/tips.js +1 -0
  25. package/dist/cli/chat/userInput.d.ts +43 -0
  26. package/dist/cli/chat/userInput.js +63 -0
  27. package/dist/cli/chat/wizard/sessionThemeHandlers.js +14 -6
  28. package/dist/cli/chat/wizard/types.d.ts +8 -1
  29. package/dist/cli/chat/wizardDispatch.js +1 -1
  30. package/dist/cli/commands/chat.js +251 -172
  31. package/dist/cli/commands/commandHelp.js +6 -2
  32. package/dist/cli/commands/commands.d.ts +8 -0
  33. package/dist/cli/commands/commands.js +11 -0
  34. package/dist/cli/commands/formatters.d.ts +1 -1
  35. package/dist/cli/commands/formatters.js +20 -2
  36. package/dist/cli/commands/logsCommand.js +21 -2
  37. package/dist/cli/commands/reasoningCommand.d.ts +23 -14
  38. package/dist/cli/commands/reasoningCommand.js +53 -20
  39. package/dist/cli/commands/runCommand.js +19 -11
  40. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  41. package/dist/cli/commands/streaming/attemptOutcome.js +11 -6
  42. package/dist/cli/commands/streaming/attemptSetup.d.ts +1 -0
  43. package/dist/cli/commands/streaming/attemptSetup.js +11 -5
  44. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +8 -1
  45. package/dist/cli/commands/streaming/goalCheckpoint.js +3 -2
  46. package/dist/cli/commands/streaming/goalSupervisor.d.ts +4 -0
  47. package/dist/cli/commands/streaming/goalSupervisor.js +43 -7
  48. package/dist/cli/commands/streaming/prepareStep.js +7 -3
  49. package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
  50. package/dist/cli/commands/streaming/streamLoop.js +3 -0
  51. package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
  52. package/dist/cli/commands/streaming.d.ts +1 -1
  53. package/dist/cli/commands/streaming.js +23 -17
  54. package/dist/cli/commands/wizardFlow.d.ts +5 -2
  55. package/dist/cli/commands/wizardFlow.js +17 -10
  56. package/dist/cli/index.js +17 -1
  57. package/dist/config/contextFiles.d.ts +9 -0
  58. package/dist/config/contextFiles.js +21 -1
  59. package/dist/config/modelCatalog.d.ts +3 -0
  60. package/dist/config/modelCatalog.js +29 -0
  61. package/dist/config/providerPresets.d.ts +1 -1
  62. package/dist/config/providerPresets.js +42 -3
  63. package/dist/config/settings.d.ts +7 -3
  64. package/dist/config/settings.js +8 -0
  65. package/dist/core/agent/budgets.d.ts +13 -15
  66. package/dist/core/agent/budgets.js +15 -17
  67. package/dist/core/agent/completionController.d.ts +6 -2
  68. package/dist/core/agent/completionController.js +16 -3
  69. package/dist/core/agent/goalPolicy.d.ts +10 -0
  70. package/dist/core/agent/goalPolicy.js +44 -6
  71. package/dist/core/agent/projectPreflight.d.ts +2 -0
  72. package/dist/core/agent/projectPreflight.js +56 -0
  73. package/dist/core/agent/reasoningPolicy.d.ts +34 -4
  74. package/dist/core/agent/reasoningPolicy.js +27 -4
  75. package/dist/core/agent/workState.d.ts +8 -0
  76. package/dist/core/agent/workState.js +191 -8
  77. package/dist/core/providerContracts.d.ts +29 -0
  78. package/dist/core/providerContracts.js +1 -0
  79. package/dist/core/session/sessionReport.d.ts +33 -0
  80. package/dist/core/session/sessionReport.js +121 -0
  81. package/dist/core/session/sessionSlimming.js +9 -3
  82. package/dist/core/session/sessionStore.d.ts +12 -0
  83. package/dist/core/session/sessionStore.js +20 -4
  84. package/dist/core/subagent/contracts.d.ts +3 -25
  85. package/dist/core/subagent/executionProfiles.js +4 -4
  86. package/dist/core/validation/outputParser.d.ts +6 -1
  87. package/dist/core/validation/outputParser.js +6 -2
  88. package/dist/llm/client.d.ts +4 -2
  89. package/dist/llm/client.js +17 -10
  90. package/dist/llm/hazeTools.d.ts +8553 -8550
  91. package/dist/llm/hazeTools.js +6 -503
  92. package/dist/llm/lspTools.d.ts +120 -120
  93. package/dist/llm/mcp.js +3 -0
  94. package/dist/llm/requestContext.d.ts +1 -1
  95. package/dist/llm/requestContext.js +1 -1
  96. package/dist/{core/subagent → llm}/subagentRunner.d.ts +9 -9
  97. package/dist/{core/subagent → llm}/subagentRunner.js +22 -25
  98. package/dist/llm/systemPrompt.d.ts +11 -1
  99. package/dist/llm/systemPrompt.js +2 -11
  100. package/dist/llm/tools/fetchTool.d.ts +30 -30
  101. package/dist/llm/tools/fileTools.d.ts +7768 -0
  102. package/dist/llm/tools/fileTools.js +510 -0
  103. package/dist/llm/tools/processTool.d.ts +30 -30
  104. package/dist/llm/tools/shellTool.d.ts +30 -30
  105. package/dist/llm/tools/shellTool.js +8 -4
  106. package/dist/llm/tools/toolContext.d.ts +3 -32
  107. package/dist/llm/tools/toolContext.js +33 -52
  108. package/dist/llm/tools/toolContextState.d.ts +40 -0
  109. package/dist/llm/tools/toolContextState.js +34 -0
  110. package/dist/llm/workerContext.d.ts +7 -0
  111. package/dist/llm/workerContext.js +18 -1
  112. package/dist/skills/SkillLoader.js +3 -3
  113. package/dist/skills/SkillRegistry.js +3 -3
  114. package/dist/skills/builder/SkillBuilder.js +3 -3
  115. package/dist/skills/confinement.d.ts +7 -0
  116. package/dist/skills/confinement.js +15 -0
  117. package/dist/ui/codeHighlight.js +4 -4
  118. package/dist/ui/components/MarkdownText.js +7 -8
  119. package/dist/ui/components/NativeIndicators.d.ts +15 -0
  120. package/dist/ui/components/NativeIndicators.js +32 -0
  121. package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
  122. package/dist/ui/components/StreamingMarkdownText.js +38 -0
  123. package/dist/ui/components/TextInput.d.ts +7 -2
  124. package/dist/ui/components/TextInput.js +103 -46
  125. package/dist/ui/components/WizardChoices.d.ts +18 -0
  126. package/dist/ui/components/WizardChoices.js +32 -0
  127. package/dist/ui/inputBuffer.js +12 -6
  128. package/dist/ui/textGeometry.d.ts +14 -0
  129. package/dist/ui/textGeometry.js +31 -0
  130. package/package.json +14 -13
  131. /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
  132. /package/dist/cli/{contextReport.js → contextReportCli.js} +0 -0
@@ -7,8 +7,10 @@ export const COMMAND_HELP_ENTRIES = [
7
7
  { usage: '/settings open', description: 'Open ~/.haze/settings.json with the OS default app.' },
8
8
  { usage: '/themes', description: 'Choose a terminal theme from the built-in registry (light palettes and oh-my-zsh ports included); applies immediately.' },
9
9
  { usage: '/themes <name>', description: 'Set the theme directly, e.g. /themes robbyrussell. Saved to ~/.haze/settings.json; text already on screen keeps its old colors.' },
10
- { usage: '/reasoning', description: 'Choose a reasoning effort level (none, minimal, low, medium, high, xhigh) or unset; high is the default and applies from the next turn.' },
11
- { usage: '/reasoning <level|unset|status>', description: 'Set the reasoning effort directly, clear it with unset (no parameter sent), or show the current level with status. Endpoints without native support ignore the parameter.' },
10
+ { usage: '/reasoning', description: 'Choose a reasoning effort level (none, minimal, low, medium, high, xhigh) for the active model, for this session; unset sends no parameter, reset falls back to the saved/default level.' },
11
+ { usage: '/reasoning <level|unset|reset|status>', description: 'Set the reasoning effort for the active model for this session, send no parameter with unset, remove the override with reset, or show the current level with status. Medium is the default. Endpoints without native support ignore the parameter.' },
12
+ { usage: '/thinking', description: 'Alias for /reasoning. Choose a reasoning effort level (none, minimal, low, medium, high, xhigh) for the active model, for this session; unset sends no parameter, reset falls back to the saved/default level.' },
13
+ { usage: '/thinking <level|unset|reset|status>', description: 'Alias for /reasoning. Set the reasoning effort for the active model for this session, send no parameter with unset, remove the override with reset, or show the current level with status. Medium is the default. Endpoints without native support ignore the parameter.' },
12
14
  { usage: '/skills', description: 'Manage Markdown skills: generate a custom skill, show info, enable/disable, validate, or remove.' },
13
15
  { usage: '/tips', description: 'Toggle the rotating tips shown under the busy label while the model is thinking.' },
14
16
  { usage: '/fleet [--review] [--profile <name>] [--workers <provider:model>] [--concurrency <n>] [--] <prompt>', description: 'Run genuinely independent tasks through disposable contexts. Runtime enforces profile concurrency, deadlines, and mutation serialization; control guidance is not persisted. Declines non-parallel work.' },
@@ -21,6 +23,8 @@ export const COMMAND_HELP_ENTRIES = [
21
23
  { usage: '/lsp', description: 'Configure Language Server Protocol navigation tools (interactive picker).' },
22
24
  { usage: '/mcp', description: 'Configure Model Context Protocol servers like Context7 (interactive picker).' },
23
25
  { usage: '/logs <id>', description: 'Show summary of a specific log: entry counts by type, total tokens, tool calls.' },
26
+ { usage: '/logs <id> view', description: 'Page the raw log JSONL through $PAGER in a fullscreen terminal handoff.' },
27
+ { usage: '/editor', description: 'Compose a prompt in $EDITOR, then submit it as the next message.' },
24
28
  { usage: '/compact [instructions]', description: 'Summarize older model context and keep recent messages.' },
25
29
  { usage: '/clear', description: 'Clear the current chat conversation history.' },
26
30
  { usage: '/exit', description: 'Exit haze.' },
@@ -1,6 +1,7 @@
1
1
  import type { ContextFile } from '../../config/contextFiles.js';
2
2
  import { type HazeSettings } from '../../config/settings.js';
3
3
  import type { Mode } from './chatModes.js';
4
+ import type { StoredReasoningSetting } from '../../core/agent/reasoningPolicy.js';
4
5
  import type { TurnExecutionOptions } from './streaming.js';
5
6
  export type CommandContext = {
6
7
  settings: HazeSettings;
@@ -16,8 +17,15 @@ export type CommandContext = {
16
17
  /** LLM-summarized /compact (F-09); preferred over `compactConversation` when present. */
17
18
  compactConversationLlm?: (instructions?: string) => Promise<boolean>;
18
19
  runAgentTurn: (prompt: string, displayValue?: string, options?: TurnExecutionOptions) => Promise<void>;
20
+ /** Ink 8 `suspendTerminal` affordances; provided by the interactive screen only. */
21
+ composeInEditor?: () => Promise<string | undefined>;
22
+ viewInPager?: (text: string) => Promise<boolean>;
19
23
  refreshContextFiles: () => Promise<ContextFile[]>;
20
24
  updateSettings: (patch: Partial<HazeSettings>) => Promise<HazeSettings>;
25
+ /** Read the session-scoped per-model reasoning override (`provider:model` key). */
26
+ getSessionReasoning: (modelSelector: string) => StoredReasoningSetting | undefined;
27
+ /** Write (or clear, with undefined) the session-scoped per-model reasoning override. */
28
+ setSessionReasoning: (modelSelector: string, setting: StoredReasoningSetting | undefined) => void;
21
29
  getContextReport?: () => Promise<string>;
22
30
  };
23
31
  export type CommandResult = 'handled' | 'unhandled' | 'exit';
@@ -46,6 +46,16 @@ const SLASH_COMMANDS = [
46
46
  } },
47
47
  { match: exact('/clear'), run: async (_args, ctx) => { await ctx.clearConversation(); await clearTasks(); return HANDLED; } },
48
48
  { match: exactOrArgs('/logs'), run: async (args, ctx) => await handleLogsCommand(args, ctx) },
49
+ { match: exact('/editor'), run: async (_args, ctx) => {
50
+ if (!ctx.composeInEditor) {
51
+ ctx.addSystemMessage('/editor needs an interactive terminal.');
52
+ return HANDLED;
53
+ }
54
+ const text = await ctx.composeInEditor();
55
+ if (text)
56
+ await ctx.runAgentTurn(text);
57
+ return HANDLED;
58
+ } },
49
59
  { match: exactOrArgs('/lsp'), run: (_args, ctx) => { ctx.setMode('lsp'); ctx.addSystemMessage('Choose an LSP server to enable, disable, or remove it. Choose "add server" to add one from presets (e.g. typescript) or enter a custom command.'); return HANDLED; } },
50
60
  { match: exactOrArgs('/mcp'), run: (_args, ctx) => { ctx.setMode('mcp'); ctx.addSystemMessage('Choose an MCP server to enable, disable, remove, or set a key for it. Choose "add server" to add one from presets (e.g. context7) or enter custom details.'); return HANDLED; } },
51
61
  { match: value => value === '/settings open' || value === '/settings edit' ? { args: '' } : false, run: async (_args, ctx) => { const file = await ensureSettingsFile(ctx.settings); await openPath(file); ctx.addSystemMessage(`Opened settings file: ${file}`); return HANDLED; } },
@@ -61,6 +71,7 @@ const SLASH_COMMANDS = [
61
71
  } },
62
72
  { match: exactOrArgs('/themes'), run: async (args, ctx) => await handleThemesCommand(args, ctx) },
63
73
  { match: exactOrArgs('/reasoning'), run: async (args, ctx) => await handleReasoningCommand(args, ctx) },
74
+ { match: exactOrArgs('/thinking'), run: async (args, ctx) => await handleReasoningCommand(args, ctx) },
64
75
  { match: exactOrArgs('/fleet'), run: (args, ctx) => handleFleetCommand(args, ctx) },
65
76
  ];
66
77
  export async function handleSlashCommand(value, ctx) {
@@ -7,7 +7,7 @@ export declare function toolResultSummary(event: {
7
7
  }): string;
8
8
  /**
9
9
  * A short, human label for the live busy indicator while a tool is running,
10
- * e.g. "Running command", "Reading src/foo.ts", "Searching".
10
+ * e.g. "Running npm test", "Reading src/foo.ts", "Searching".
11
11
  * Lets the developer see *what* is happening, not just that something is.
12
12
  */
13
13
  export declare function busyToolLabel(toolName: string, input: unknown): string;
@@ -148,9 +148,25 @@ export function toolResultSummary(event) {
148
148
  }
149
149
  return 'completed';
150
150
  }
151
+ /**
152
+ * The short head of a shell command for the busy label: the program plus its
153
+ * first non-flag argument ("git diff", "npm test") — enough to identify the
154
+ * action without echoing the full (possibly long or sensitive) command line.
155
+ */
156
+ function commandHead(command) {
157
+ const parts = command.trim().split(/\s+/);
158
+ const head = [parts[0]];
159
+ for (const part of parts.slice(1)) {
160
+ if (part.startsWith('-'))
161
+ continue;
162
+ head.push(part);
163
+ break;
164
+ }
165
+ return compact(head.filter(Boolean).join(' '), 80);
166
+ }
151
167
  /**
152
168
  * A short, human label for the live busy indicator while a tool is running,
153
- * e.g. "Running command", "Reading src/foo.ts", "Searching".
169
+ * e.g. "Running npm test", "Reading src/foo.ts", "Searching".
154
170
  * Lets the developer see *what* is happening, not just that something is.
155
171
  */
156
172
  export function busyToolLabel(toolName, input) {
@@ -158,7 +174,9 @@ export function busyToolLabel(toolName, input) {
158
174
  const pathLabel = typeof data?.path === 'string' ? compact(data.path, 80) : undefined;
159
175
  switch (toolName) {
160
176
  case 'shell':
161
- return data?.background === true ? 'Starting background process' : 'Running command';
177
+ if (data?.background === true)
178
+ return 'Starting background process';
179
+ return typeof data?.command === 'string' && data.command ? `Running ${commandHead(data.command)}` : 'Running command';
162
180
  case 'process':
163
181
  return 'Managing background process';
164
182
  case 'grep':
@@ -1,7 +1,12 @@
1
- import { listLogs, summarizeLog } from '../../core/log/llmLog.js';
1
+ import { listLogs, readLogEntries, summarizeLog } from '../../core/log/llmLog.js';
2
2
  import { formatBytes } from '../../utils/format.js';
3
+ import { SESSION_PREVIEW_CHARS } from '../../core/limits.js';
3
4
  export async function handleLogsCommand(args, ctx) {
4
- const id = args.trim();
5
+ const trimmed = args.trim();
6
+ // `/logs <id> view` pages the raw JSONL through $PAGER; the suffix is part
7
+ // of haze's syntax, not the log id.
8
+ const viewRaw = /^(\S+)\s+view$/i.exec(trimmed);
9
+ const id = viewRaw ? viewRaw[1] : trimmed;
5
10
  if (!id) {
6
11
  const logs = await listLogs();
7
12
  if (logs.length === 0) {
@@ -20,6 +25,20 @@ export async function handleLogsCommand(args, ctx) {
20
25
  ctx.addSystemMessage(`No log found with id ${id}.`);
21
26
  return 'handled';
22
27
  }
28
+ // Page raw transcripts when possible; short logs and screen-reader mode
29
+ // still get the requested content through a bounded inline preview.
30
+ if (viewRaw) {
31
+ const entries = await readLogEntries(id);
32
+ const text = entries.map(entry => JSON.stringify(entry)).join('\n');
33
+ const paged = await ctx.viewInPager?.(text);
34
+ if (!paged) {
35
+ const preview = text.length > SESSION_PREVIEW_CHARS
36
+ ? `${text.slice(0, SESSION_PREVIEW_CHARS)}\n[Raw log preview truncated; /logs ${id} shows the summary.]`
37
+ : text || '(empty log)';
38
+ ctx.addSystemMessage(`Log: ${id} (inline view; pager not used)\n${preview}`);
39
+ }
40
+ return 'handled';
41
+ }
23
42
  const typeLines = Object.entries(summary.typeCounts)
24
43
  .sort(([a], [b]) => a.localeCompare(b))
25
44
  .map(([type, count]) => ` ${type}: ${count}`);
@@ -1,24 +1,29 @@
1
- import type { HazeSettings } from '../../config/settings.js';
1
+ import { type ResolvedReasoningChoice, type StoredReasoningSetting } from '../../core/agent/reasoningPolicy.js';
2
2
  import type { CommandContext, CommandResult } from './commands.js';
3
3
  /**
4
- * `/reasoning` — reasoning-effort picker and direct set, modeled on
5
- * `/themes`. The picker is one step in the `wizardFlow.ts` table (mode
6
- * `reasoning`); this module holds the pure result function shared by the
7
- * slash path and the wizard submit handler. The setting applies from the next
8
- * turn (reasoning is resolved once per attempt in `attemptSetup`).
4
+ * `/reasoning` — per-model, per-session reasoning-effort picker and direct
5
+ * set, modeled on `/themes`. The picker is one step in the `wizardFlow.ts`
6
+ * table (mode `reasoning`); this module holds the pure result function shared
7
+ * by the slash path and the wizard submit handler. The chosen level applies to
8
+ * the active `provider:model` for the current session only — kept in memory on
9
+ * the `PromptSession` object, never written to `~/.haze/settings.json` — and
10
+ * applies from the next turn (reasoning is resolved once per attempt in
11
+ * `attemptSetup`). A model without a session override falls back to the saved
12
+ * global `reasoning` setting, then the built-in default.
9
13
  */
10
- /** Picker value that clears the setting (also accepted as `off` on the slash path). */
14
+ /** Picker value that stops sending a reasoning parameter (also accepted as `off` on the slash path). */
11
15
  export declare const REASONING_UNSET = "unset";
16
+ /** Picker/slash value that removes the session override and inherits the saved/default level. */
17
+ export declare const REASONING_RESET = "reset";
12
18
  export type ReasoningCommandResult = {
13
19
  action: 'status';
14
20
  message: string;
15
21
  } | {
16
22
  action: 'set';
17
- settingsPatch: HazeSettings;
23
+ setting: StoredReasoningSetting;
18
24
  message: string;
19
25
  } | {
20
- action: 'clear';
21
- settingsPatch: HazeSettings;
26
+ action: 'reset';
22
27
  message: string;
23
28
  } | {
24
29
  action: 'error';
@@ -27,9 +32,13 @@ export type ReasoningCommandResult = {
27
32
  action: 'open-picker';
28
33
  };
29
34
  /**
30
- * Resolve a `/reasoning` invocation against the current setting. Pure: the
31
- * caller applies `settingsPatch` (a `reasoning: undefined` clear drops the
32
- * key, because settings writes serialize with `JSON.stringify`).
35
+ * Resolve a `/reasoning` invocation against the current choice for the active
36
+ * model. Pure: the caller applies `set`/`reset` to the session-scoped
37
+ * per-model map (`PromptSession.reasoningByModel`); nothing touches settings.
33
38
  */
34
- export declare function resolveReasoningCommand(args: string, current: unknown): ReasoningCommandResult;
39
+ export declare function resolveReasoningCommand(args: string, input: {
40
+ current: ResolvedReasoningChoice;
41
+ stored: StoredReasoningSetting | undefined;
42
+ modelSelector?: string;
43
+ }): ReasoningCommandResult;
35
44
  export declare function handleReasoningCommand(args: string, ctx: CommandContext): Promise<CommandResult>;
@@ -1,44 +1,77 @@
1
- import { DEFAULT_REASONING_LEVEL, REASONING_LEVELS, REASONING_PROVIDER_DEFAULT, isReasoningLevel, isReasoningUnsetAlias } from '../../core/agent/reasoningPolicy.js';
1
+ import { REASONING_LEVELS, REASONING_PROVIDER_DEFAULT, isReasoningLevel, isReasoningUnsetAlias, isStoredReasoning, resolveReasoningChoice } from '../../core/agent/reasoningPolicy.js';
2
2
  /**
3
- * `/reasoning` — reasoning-effort picker and direct set, modeled on
4
- * `/themes`. The picker is one step in the `wizardFlow.ts` table (mode
5
- * `reasoning`); this module holds the pure result function shared by the
6
- * slash path and the wizard submit handler. The setting applies from the next
7
- * turn (reasoning is resolved once per attempt in `attemptSetup`).
3
+ * `/reasoning` — per-model, per-session reasoning-effort picker and direct
4
+ * set, modeled on `/themes`. The picker is one step in the `wizardFlow.ts`
5
+ * table (mode `reasoning`); this module holds the pure result function shared
6
+ * by the slash path and the wizard submit handler. The chosen level applies to
7
+ * the active `provider:model` for the current session only — kept in memory on
8
+ * the `PromptSession` object, never written to `~/.haze/settings.json` — and
9
+ * applies from the next turn (reasoning is resolved once per attempt in
10
+ * `attemptSetup`). A model without a session override falls back to the saved
11
+ * global `reasoning` setting, then the built-in default.
8
12
  */
9
- /** Picker value that clears the setting (also accepted as `off` on the slash path). */
13
+ /** Picker value that stops sending a reasoning parameter (also accepted as `off` on the slash path). */
10
14
  export const REASONING_UNSET = 'unset';
15
+ /** Picker/slash value that removes the session override and inherits the saved/default level. */
16
+ export const REASONING_RESET = 'reset';
11
17
  const LEVELS_LIST = REASONING_LEVELS.join(', ');
18
+ function describeChoice(choice) {
19
+ if (choice.level === undefined)
20
+ return 'provider default (no parameter sent)';
21
+ if (choice.source === 'session')
22
+ return `${choice.level} (session override)`;
23
+ if (choice.source === 'settings')
24
+ return `${choice.level} (from settings)`;
25
+ return `${choice.level} (default)`;
26
+ }
12
27
  /**
13
- * Resolve a `/reasoning` invocation against the current setting. Pure: the
14
- * caller applies `settingsPatch` (a `reasoning: undefined` clear drops the
15
- * key, because settings writes serialize with `JSON.stringify`).
28
+ * Resolve a `/reasoning` invocation against the current choice for the active
29
+ * model. Pure: the caller applies `set`/`reset` to the session-scoped
30
+ * per-model map (`PromptSession.reasoningByModel`); nothing touches settings.
16
31
  */
17
- export function resolveReasoningCommand(args, current) {
32
+ export function resolveReasoningCommand(args, input) {
18
33
  const value = args.trim().toLowerCase();
34
+ const scope = input.modelSelector ? ` for ${input.modelSelector}` : '';
19
35
  if (!value)
20
36
  return { action: 'open-picker' };
21
37
  if (value === 'status') {
22
- const level = isReasoningLevel(current) ? current : DEFAULT_REASONING_LEVEL;
23
- return { action: 'status', message: `Reasoning effort: ${level}${current === level ? '' : ` (default ${DEFAULT_REASONING_LEVEL})`}. Sent as the model's reasoning parameter. Change with /reasoning <level>, /reasoning unset for the provider default, or /reasoning none to turn reasoning off. Levels: ${LEVELS_LIST}.` };
38
+ return { action: 'status', message: `Reasoning effort${scope}: ${describeChoice(input.current)}. Set with /reasoning <level> (this model, this session), /reasoning unset to send no reasoning parameter, or /reasoning reset to fall back to the saved/default level. Levels: ${LEVELS_LIST}.` };
39
+ }
40
+ if (value === REASONING_RESET) {
41
+ const fallback = resolveReasoningChoice(undefined, input.stored);
42
+ return { action: 'reset', message: `Session reasoning override removed${scope}. ${describeChoice(fallback)} applies from the next turn.` };
24
43
  }
25
44
  if (isReasoningUnsetAlias(value)) {
26
- return { action: 'clear', settingsPatch: { reasoning: REASONING_PROVIDER_DEFAULT }, message: `Reasoning effort unset. No reasoning parameter is sent from the next turn; the provider default applies.` };
45
+ return { action: 'set', setting: REASONING_PROVIDER_DEFAULT, message: `Reasoning effort unset${scope}: no reasoning parameter is sent from the next turn; the provider default applies (this model, this session).` };
27
46
  }
28
47
  if (!isReasoningLevel(value)) {
29
- return { action: 'error', message: `Unknown reasoning level "${value}". Valid levels: ${LEVELS_LIST} — or ${REASONING_UNSET} for the provider default.` };
48
+ return { action: 'error', message: `Unknown reasoning level "${value}". Valid levels: ${LEVELS_LIST} — unset sends no reasoning parameter, reset falls back to the saved/default level.` };
30
49
  }
31
- return { action: 'set', settingsPatch: { reasoning: value }, message: `Reasoning effort set to ${value}. Saved to ~/.haze/settings.json; applies from the next turn. Endpoints without native support ignore the parameter.` };
50
+ return { action: 'set', setting: value, message: `Reasoning effort set to ${value}${scope}. Applies to this model for the current session; each model keeps its own level. Not written to ~/.haze/settings.json.` };
51
+ }
52
+ /** `provider:model` key for the settings-configured active model, or undefined when unconfigured. */
53
+ function activeModelSelector(context) {
54
+ const { provider, model } = context.settings;
55
+ return provider && model ? `${provider}:${model}` : undefined;
32
56
  }
33
57
  export async function handleReasoningCommand(args, ctx) {
58
+ const modelSelector = activeModelSelector(ctx);
34
59
  if (!args.trim()) {
35
60
  ctx.setMode('reasoning');
36
- ctx.addSystemMessage('Choose a reasoning effort level. Selecting one saves it to ~/.haze/settings.json and applies from the next turn; unset sends no reasoning parameter (provider default).');
61
+ ctx.addSystemMessage('Choose a reasoning effort level for the active model, for this session. unset sends no reasoning parameter (provider default); reset falls back to the saved or default level.');
62
+ return 'handled';
63
+ }
64
+ if (!modelSelector) {
65
+ ctx.addSystemMessage('No provider/model configured. /reasoning sets a per-model level; run /provider and /model first.');
37
66
  return 'handled';
38
67
  }
39
- const result = resolveReasoningCommand(args, ctx.settings.reasoning);
40
- if (result.action === 'set' || result.action === 'clear')
41
- await ctx.updateSettings(result.settingsPatch);
68
+ const stored = isStoredReasoning(ctx.settings.reasoning) ? ctx.settings.reasoning : undefined;
69
+ const current = resolveReasoningChoice(ctx.getSessionReasoning(modelSelector), stored);
70
+ const result = resolveReasoningCommand(args, { current, stored, modelSelector });
71
+ if (result.action === 'set')
72
+ ctx.setSessionReasoning(modelSelector, result.setting);
73
+ else if (result.action === 'reset')
74
+ ctx.setSessionReasoning(modelSelector, undefined);
42
75
  // Unreachable (args are non-empty here) but narrows the open-picker variant away.
43
76
  if (result.action !== 'open-picker')
44
77
  ctx.addSystemMessage(result.message);
@@ -124,8 +124,7 @@ export function parseHeadlessReasoning(raw) {
124
124
  const parsed = parseReasoningOverride(raw);
125
125
  return parsed.ok ? { setting: parsed.setting } : { error: parsed.error };
126
126
  }
127
- async function resolveModelOrError(modelOverride) {
128
- const settings = await readSettings();
127
+ function resolveModelOrError(settings, modelOverride) {
129
128
  const override = modelOverride?.trim();
130
129
  if (override) {
131
130
  const resolved = resolveModelSelector(settings, override);
@@ -161,11 +160,22 @@ export async function runHeadless(options) {
161
160
  process.stderr.write(`${reasoning.error}\n`);
162
161
  return 2;
163
162
  }
164
- const modelError = await resolveModelOrError(options.modelOverride);
163
+ const restored = resumed ? await restoreSessionState(resumed) : undefined;
164
+ const savedModel = restored?.modelSelection;
165
+ const runSettings = await readSettings();
166
+ const defaultModel = activeModel(runSettings);
167
+ const requestedModel = options.modelOverride?.trim()
168
+ || (savedModel ? `${savedModel.provider}:${savedModel.model}` : undefined)
169
+ || (defaultModel ? modelSelector(defaultModel.provider, defaultModel.model) : undefined);
170
+ const modelError = resolveModelOrError(runSettings, requestedModel);
165
171
  if (modelError) {
166
172
  process.stderr.write(`${modelError}\n`);
167
173
  return 1;
168
174
  }
175
+ // Resolve bare --model selectors to a provider-qualified selection once,
176
+ // so retries cannot follow changes to the global default.
177
+ const resolvedModel = requestedModel ? resolveModelSelector(runSettings, requestedModel) : undefined;
178
+ const sessionModel = resolvedModel?.status === 'found' ? modelSelector(resolvedModel.provider, resolvedModel.model) : requestedModel;
169
179
  // stderr keeps stdout clean for --output json/stream-json consumers.
170
180
  const debugLog = (line) => {
171
181
  if (options.debug)
@@ -173,13 +183,9 @@ export async function runHeadless(options) {
173
183
  };
174
184
  const contextFiles = await readContextFiles(process.cwd());
175
185
  const session = { start: new Date(), cwd: process.cwd() };
176
- let conversation = [];
177
- if (resumed) {
178
- const restored = await restoreSessionState(resumed);
179
- conversation = restored.messages;
180
- for (const error of restored.parseErrors)
181
- process.stderr.write(`Session parse error: ${error}\n`);
182
- }
186
+ let conversation = restored?.messages ?? [];
187
+ for (const error of restored?.parseErrors ?? [])
188
+ process.stderr.write(`Session parse error: ${error}\n`);
183
189
  // Assistant text is delivered in two stages by runAgentTurn: an initial streaming
184
190
  // `addMessage`, then a finalizing `updateMessage` with the complete text. We key
185
191
  // segments by id and patch them on update so finalized (and multi-segment) text is captured.
@@ -282,7 +288,8 @@ export async function runHeadless(options) {
282
288
  contextFiles,
283
289
  callbacks,
284
290
  session,
285
- modelOverride: options.modelOverride,
291
+ modelOverride: sessionModel,
292
+ escalationModel: runSettings.escalationModel,
286
293
  ...(reasoning.setting !== undefined ? { reasoningOverride: reasoning.setting } : {}),
287
294
  ...(turnDeadlineMs != null ? { goalDeadlineMs: Math.max(1, deadlineAt - Date.now()) } : {}),
288
295
  ...(relaunchOptions.resumeFrom ? { resumeFrom: relaunchOptions.resumeFrom } : {}),
@@ -324,6 +331,7 @@ export async function runHeadless(options) {
324
331
  cycles: goalResult.cycles,
325
332
  stopReason: goalResult.stopReason,
326
333
  mutations: goalResult.evidence?.mutationCount ?? 0,
334
+ ...(goalResult.escalations ? { escalations: goalResult.escalations } : {}),
327
335
  ...(goalResult.evidence && goalResult.evidence.validationOutcome !== 'not_applicable' ? { validationOutcome: goalResult.evidence.validationOutcome } : {}),
328
336
  ...(goalResult.evidence?.taskProgress ? { taskProgress: goalResult.evidence.taskProgress } : {}),
329
337
  };
@@ -23,6 +23,7 @@ export declare function terminalTurnStatus(input: {
23
23
  assistantText: string;
24
24
  sawToolCall: boolean;
25
25
  lastToolOk?: boolean;
26
+ lastFailedToolWasValidation?: boolean;
26
27
  finishReason?: string;
27
28
  budgetReached?: boolean;
28
29
  unresolvedToolInputError?: boolean;
@@ -30,6 +31,7 @@ export declare function terminalTurnStatus(input: {
30
31
  mutationCount?: number;
31
32
  validationOutcome?: ValidationOutcome;
32
33
  taskProgress?: WorkTaskProgress;
34
+ requiresTaskLedger?: boolean;
33
35
  redPair?: 'not-required' | 'missing' | 'satisfied';
34
36
  }): TurnStatus;
35
37
  /** Bounded recovery slice an attempt proposes for the next agent call. */
@@ -2,8 +2,8 @@ import { assessCompletionReadiness, classifyTerminalOutcome, createTurnExecution
2
2
  import { agentEvent } from '../../../core/agent/events.js';
3
3
  import { isContextOverflowError, isRetryableModelError } from '../../../core/agent/errors.js';
4
4
  import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
5
- import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
6
- import { deriveValidationOutcome, redPairStatus } from '../../../core/agent/workState.js';
5
+ import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
6
+ import { deriveValidationOutcome, redPairStatus, unresolvedFailedCheckIds } from '../../../core/agent/workState.js';
7
7
  import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
8
8
  import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
9
9
  import { formatSeconds } from '../../../utils/format.js';
@@ -30,12 +30,14 @@ export function terminalTurnStatus(input) {
30
30
  mutationCount: input.mutationCount ?? 0,
31
31
  ...(input.validationOutcome ? { validationOutcome: input.validationOutcome } : {}),
32
32
  ...(input.taskProgress ? { taskProgress: input.taskProgress } : {}),
33
+ requiresTaskLedger: Boolean(input.requiresTaskLedger),
33
34
  ...(input.redPair ? { redPair: input.redPair } : {}),
34
35
  };
35
36
  return decideTerminalStatus(state, {
36
37
  sawToolCall: input.sawToolCall,
37
38
  assistantText: input.assistantText,
38
39
  lastToolOk: input.lastToolOk,
40
+ lastFailedToolWasValidation: Boolean(input.lastFailedToolWasValidation),
39
41
  unresolvedToolInputError: Boolean(input.unresolvedToolInputError),
40
42
  }, Boolean(input.budgetReached));
41
43
  }
@@ -47,6 +49,7 @@ export function projectGoalEvidence(turnState, goal) {
47
49
  turnState.validationKind = goal.validations.at(-1)?.kind ?? goal.carriedValidation?.kind;
48
50
  turnState.validationAfterMutation = goal.validationSeq > 0 && goal.validationSeq >= goal.mutationSeq;
49
51
  turnState.taskProgress = goal.taskProgress;
52
+ turnState.requiresTaskLedger = Boolean(goal.requiresTaskLedger);
50
53
  // Opportunistic red→green: only an actually observed red can gate.
51
54
  turnState.redPair = redPairStatus(goal);
52
55
  }
@@ -64,10 +67,10 @@ export function finalizeAttemptOutcome(deps) {
64
67
  // terminal paths report the same cumulative state.
65
68
  projectGoalEvidence(turnState, goal);
66
69
  turnState.budgetBoundary = isBudgetExhausted(turnState, turnBudget);
67
- const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, unresolvedToolInputError: stream.unresolvedToolInputError };
70
+ const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, lastFailedToolWasValidation: stream.lastFailedToolWasValidation, unresolvedToolInputError: stream.unresolvedToolInputError };
68
71
  const readiness = assessCompletionReadiness(turnState, completionEvidence);
69
72
  const classification = classifyTerminalOutcome(turnState, completionEvidence);
70
- const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress, ...(turnState.redPair ? { redPair: turnState.redPair } : {}) });
73
+ const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, lastFailedToolWasValidation: stream.lastFailedToolWasValidation, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress, requiresTaskLedger: turnState.requiresTaskLedger, ...(turnState.redPair ? { redPair: turnState.redPair } : {}) });
71
74
  if (stream.unresolvedMalformedToolName)
72
75
  callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
73
76
  goal.phase = 'done';
@@ -116,6 +119,7 @@ export function finalizeAttemptOutcome(deps) {
116
119
  // includes boundaries reached after red capture but before the first edit.
117
120
  ...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
118
121
  ...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
122
+ ...(unresolvedFailedCheckIds(goal).length ? { failedCheckIds: unresolvedFailedCheckIds(goal) } : {}),
119
123
  };
120
124
  const discardRejectedFinal = () => callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
121
125
  const checkpointResult = () => {
@@ -144,7 +148,7 @@ export function finalizeAttemptOutcome(deps) {
144
148
  discardRejectedFinal();
145
149
  if (readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation')
146
150
  turnState.validationContinuationUsed = true;
147
- return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress), taskCountsOf(turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
151
+ return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress), taskCountsOf(turnState.taskProgress), turnState.redPair === 'missing' ? 'The captured pre-edit failing check still needs the same validation command to pass after the fix.' : undefined), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
148
152
  }
149
153
  else if (rescueSlice && rescueSlice.steps > 0) {
150
154
  return { status: turnStatus, recovery: { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } } };
@@ -211,7 +215,7 @@ export function handleAttemptFailure(deps) {
211
215
  // the bound), but completed-step progress stays in the conversation.
212
216
  turnState.aborted = true;
213
217
  callbacks.debugLog('turn exceeded the absolute deadline');
214
- callbacks.addMessage({ role: 'system', text: `Turn stopped: the ${formatIdleMinutes(abortCause.timeoutMs ?? DEFAULT_TURN_DEADLINE_MS)} turn budget elapsed before the model finished. Completed steps are preserved in the conversation; send a follow-up to continue.` });
218
+ callbacks.addMessage({ role: 'system', text: `Turn stopped: the ${formatIdleMinutes(abortCause.timeoutMs ?? 0)} turn budget elapsed before the model finished. Completed steps are preserved in the conversation; send a follow-up to continue.` });
215
219
  return { status: 'aborted', abortReason: 'turn-deadline' };
216
220
  }
217
221
  turnState.aborted = true;
@@ -236,6 +240,7 @@ export function handleAttemptFailure(deps) {
236
240
  ...(turnOptions.goalContext?.requestHash ? { requestHash: turnOptions.goalContext.requestHash } : {}),
237
241
  ...(redPairStatus(goal) !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
238
242
  ...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
243
+ ...(unresolvedFailedCheckIds(goal).length ? { failedCheckIds: unresolvedFailedCheckIds(goal) } : {}),
239
244
  };
240
245
  return { status: 'failed', resume: buildIncompleteGoalResume(value, turnOptions.goalContext?.goalId ?? goal.id, turnOptions.goalContext?.cycle ?? 1, turnState, 'context_exhausted', carried) };
241
246
  }
@@ -50,6 +50,7 @@ export interface AttemptSetup {
50
50
  modelRetries: number;
51
51
  /** Backoff base for the shared model-retry pool, from the `retryBaseDelayMs` setting (default 1000ms). */
52
52
  retryBaseDelayMs: number;
53
+ steeringProfile: 'standard' | 'compact';
53
54
  }
54
55
  export interface AttemptSetupDeps {
55
56
  value: string;
@@ -1,7 +1,8 @@
1
1
  import { readSettings } from '../../../config/settings.js';
2
2
  import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_RETRY_BASE_DELAY_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_MODEL_RETRIES, withToolExecutionBudget } from '../../../core/agent/budgets.js';
3
3
  import { agentEvent } from '../../../core/agent/events.js';
4
- import { isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
4
+ import { goalDirectionPrompt, isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
5
+ import { projectPreflight } from '../../../core/agent/projectPreflight.js';
5
6
  import { formatGoalStatus } from '../../../core/agent/goalPolicy.js';
6
7
  import { calculateRequestTokenBudget, estimateConversationTokens } from '../../../core/agent/contextBudget.js';
7
8
  import { stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
@@ -45,7 +46,8 @@ export async function prepareAttempt(deps) {
45
46
  // provider/model switch mid-goal applies from the next attempt — the first
46
47
  // attempt of each physical turn keeps the original read).
47
48
  const turnSettings = await readSettings();
48
- const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride, reasoningOverride }, turnSettings);
49
+ const steeringProfile = turnSettings.steeringProfile ?? 'standard';
50
+ const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride, reasoningOverride, reasoningByModel: session?.reasoningByModel }, turnSettings);
49
51
  if (!runtime?.model) {
50
52
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
51
53
  return undefined;
@@ -81,6 +83,9 @@ export async function prepareAttempt(deps) {
81
83
  : { type: 'subagent_state', id: event.id, state: 'settled', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: 'settled', running: event.running })) });
82
84
  turnScope.executionScope ??= assembled.executionScope;
83
85
  const availableTools = assembled.availableTools;
86
+ const direction = goalDirectionPrompt(goal.intent, steeringProfile === 'compact');
87
+ const preflight = steeringProfile === 'compact' ? await projectPreflight(session?.cwd ?? process.cwd()) : '';
88
+ const systemPrompt = [assembled.systemPrompt, direction, preflight].filter(Boolean).join('\n\n');
84
89
  const toolCategories = assembled.toolCategories;
85
90
  const loadedMcp = assembled.loadedMcp;
86
91
  const lspPool = assembled.lspPool;
@@ -102,12 +107,13 @@ export async function prepareAttempt(deps) {
102
107
  // margin — not a fixed 40K constant. Small contexts get a safe budget; the
103
108
  // assembled request plus output reserve stays within configured capacity.
104
109
  const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
105
- const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: assembled.systemPrompt, tools: availableTools });
110
+ const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: systemPrompt, tools: availableTools });
106
111
  // A context-overflow retry progressively shrinks the target so it cannot loop
107
112
  // at an unchanged budget; further overflows get even smaller (RH-005, Pillar
108
113
  // 1.4: 0.6 after the first, 0.36 after the second).
109
114
  const overflowShrinkFactor = deps.overflowShrinkFactor;
110
- const overflowTargetTokens = overflowShrinkFactor < 1 ? Math.floor(requestBudget.messageTokens * overflowShrinkFactor) : requestBudget.messageTokens;
115
+ const profileTargetTokens = Math.floor(requestBudget.messageTokens * (steeringProfile === 'compact' ? 0.7 : 1));
116
+ const overflowTargetTokens = overflowShrinkFactor < 1 ? Math.floor(profileTargetTokens * overflowShrinkFactor) : profileTargetTokens;
111
117
  const overheadTokens = requestBudget.systemTokens + requestBudget.toolSchemaTokens;
112
118
  let requestMessages = durableRequestMessages;
113
119
  if (estimateConversationTokens(requestMessages, usageAnchor.current, overheadTokens).tokens > overflowTargetTokens) {
@@ -124,7 +130,6 @@ export async function prepareAttempt(deps) {
124
130
  callbacks.setConversation(stripSyntheticControls(requestMessages));
125
131
  if (turnOptions.ephemeralControl)
126
132
  requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
127
- const systemPrompt = assembled.systemPrompt;
128
133
  const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
129
134
  logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
130
135
  const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
@@ -188,5 +193,6 @@ export async function prepareAttempt(deps) {
188
193
  toolCategories,
189
194
  modelRetries: typeof turnSettings.modelRetries === 'number' ? turnSettings.modelRetries : DEFAULT_MODEL_RETRIES,
190
195
  retryBaseDelayMs: typeof turnSettings.retryBaseDelayMs === 'number' ? turnSettings.retryBaseDelayMs : DEFAULT_RETRY_BASE_DELAY_MS,
196
+ steeringProfile,
191
197
  };
192
198
  }
@@ -35,6 +35,7 @@ export interface IncompleteGoalResume {
35
35
  redEvidence?: RedEvidence;
36
36
  /** Kind of the carried validation, when one rode the checkpoint (R2-03). */
37
37
  validationKind?: ValidationKind;
38
+ failedCheckIds?: string[];
38
39
  }
39
40
  /** Supervisor-level checkpoint persisted between physical turns (in memory and, via the goal ledger, in the session JSONL). */
40
41
  export interface GoalCheckpoint {
@@ -65,6 +66,7 @@ export interface GoalCheckpoint {
65
66
  redEvidence?: RedEvidence;
66
67
  /** Kind of the carried validation, when one rode the checkpoint (R2-03). */
67
68
  validationKind?: ValidationKind;
69
+ failedCheckIds?: string[];
68
70
  }
69
71
  /** Durable goal-ledger append (P1): one entry per supervisor boundary; the writer stamps `type`/`at`. Shared by the supervisor and the session recorder. */
70
72
  export interface GoalLedgerAppend {
@@ -76,6 +78,8 @@ export interface GoalLedgerAppend {
76
78
  cycle: number;
77
79
  mutationCount: number;
78
80
  validationOutcome: ValidationOutcome;
81
+ validationKind?: ValidationKind;
82
+ failedCheckIds?: string[];
79
83
  progressSignature: string;
80
84
  taskCounts?: {
81
85
  total: number;
@@ -86,10 +90,11 @@ export interface GoalLedgerAppend {
86
90
  redEvidence?: RedEvidence;
87
91
  stopReason?: string;
88
92
  status?: 'complete' | 'failed' | 'aborted';
93
+ gateDecision?: CompletionReadiness;
89
94
  }
90
95
  /** Hash binding for the exact mission bytes (P1): everything downstream that references "the mission" carries this. */
91
96
  export declare function hashRequest(request: string): string;
92
- /** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
97
+ /** Cumulative outcome signature; monotonic mutation activity alone is not net progress. Open failed-check count is progress too: a turn that greens one of three red checks must not look identical to a turn that greened none (observed 2026-10-04, goal `on373gg0l1e`). */
93
98
  export declare function goalCheckpointSignature(input: {
94
99
  mutationCount: number;
95
100
  validationOutcome: ValidationOutcome;
@@ -99,6 +104,7 @@ export declare function goalCheckpointSignature(input: {
99
104
  completed: number;
100
105
  total: number;
101
106
  };
107
+ openCheckCount?: number;
102
108
  }): string;
103
109
  /** Goal-scoped evidence carried across a physical-turn boundary (checkpoint subset). */
104
110
  export interface CarriedGoalEvidence {
@@ -106,6 +112,7 @@ export interface CarriedGoalEvidence {
106
112
  intent?: RequestIntent;
107
113
  redEvidence?: RedEvidence;
108
114
  validationKind?: ValidationKind;
115
+ failedCheckIds?: string[];
109
116
  }
110
117
  /**
111
118
  * Build the checkpoint payload for a `recoverable-incomplete` attempt that no