@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,10 +1,11 @@
1
1
  import { agentEvent } from '../../core/agent/events.js';
2
- import { createTurnExecutionState, toCompletionEvidence } from '../../core/agent/completionController.js';
2
+ import { createTurnExecutionState, describeTurnFailure, toCompletionEvidence } from '../../core/agent/completionController.js';
3
3
  import { createSessionGoal } from '../../core/agent/goalPolicy.js';
4
4
  import { seedCarriedGoalEvidence } from '../../core/agent/workState.js';
5
- import { createToolExecutionBudget, mainTurnBudget, DEFAULT_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
5
+ import { createToolExecutionBudget, mainTurnBudget, DEFAULT_TURN_DEADLINE_MS, OVERFLOW_SHRINK_FACTOR } from '../../core/agent/budgets.js';
6
6
  import { createAbsoluteDeadline } from '../../core/deadline.js';
7
7
  import { modelThinkingLabel } from '../../utils/modelName.js';
8
+ import { goalCheckpointSignature, taskCountsOf } from './streaming/goalCheckpoint.js';
8
9
  import { abortableDelay } from './streaming/turnRuntime.js';
9
10
  import { abortForTurn, createUserAbortCause } from './streaming/abortCause.js';
10
11
  import { runAgentAttempt } from './streaming/agentAttempt.js';
@@ -12,7 +13,7 @@ import { projectGoalEvidence } from './streaming/attemptOutcome.js';
12
13
  import { awaitAttemptWithForcedSettlement, createAttemptCleanupRegistry, createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
13
14
  import { startRecoverySlice } from './streaming/recoverySlices.js';
14
15
  import { formatIdleMinutes } from '../../utils/format.js';
15
- export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
16
+ export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}, reasoningOverride) {
16
17
  // The controller is replaced when an idle-stall retry needs a live signal
17
18
  // after aborting a hung stream, so both it and the cause are mutable.
18
19
  let abortController = new AbortController();
@@ -36,6 +37,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
36
37
  // logical goal shares the same lease.
37
38
  const turnScope = turnOptions.sharedTurnScope ?? {};
38
39
  const turnBudget = mainTurnBudget();
40
+ // Turn-scoped provider-usage anchor (Pillar 1.1): context estimation prefers
41
+ // real usage from the last completed step, with chars/4 estimates only for
42
+ // trailing messages. Shared across attempts and invalidated by compaction.
43
+ const usageAnchor = { current: undefined };
39
44
  // Turn-wide execution budget (RH-003): one authoritative counter of
40
45
  // underlying tool executions, shared across retries and recovery slices so
41
46
  // the global limit cannot be reset or exceeded. The slice budget caps the
@@ -57,7 +62,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
57
62
  turnState.intent = goal.intent;
58
63
  let activeOptions = turnOptions;
59
64
  let attempt = retryAttempt;
60
- let overflowRecovered = contextOverflowRecovered;
65
+ let overflowRetries = contextOverflowRecovered ? 1 : 0;
66
+ let overflowShrinkFactor = contextOverflowRecovered ? OVERFLOW_SHRINK_FACTOR : 1;
67
+ let stepsUsedAtLastRetry = 0;
61
68
  let retrying = retryingExistingRequest;
62
69
  // The attempt machinery runs against quarantinable callbacks so an
63
70
  // abort-ignoring stream that outlives forced settlement cannot mutate the
@@ -80,7 +87,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
80
87
  },
81
88
  });
82
89
  const cleanup = createAttemptCleanupRegistry();
83
- const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, contextOverflowRecovered: overflowRecovered, session, modelOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)) }), {
90
+ const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, overflowShrinkFactor, overflowRetries, progressSinceLastRetry: turnState.stepsUsed > stepsUsedAtLastRetry, session, modelOverride, reasoningOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)), usageAnchor }), {
84
91
  abortController,
85
92
  cleanup,
86
93
  quarantine,
@@ -102,7 +109,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
102
109
  resume = result.resume;
103
110
  if (result.retry) {
104
111
  attempt = result.retry.attempt;
105
- overflowRecovered = result.retry.contextOverflowRecovered;
112
+ if (result.retry.overflowShrinkFactor != null) {
113
+ overflowRetries += 1;
114
+ overflowShrinkFactor = result.retry.overflowShrinkFactor;
115
+ }
116
+ stepsUsedAtLastRetry = turnState.stepsUsed;
106
117
  retrying = true;
107
118
  if (result.retry.freshController) {
108
119
  // The idle stall aborted the previous controller to kill the hung
@@ -131,11 +142,29 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
131
142
  }
132
143
  projectGoalEvidence(turnState, goal);
133
144
  const evidence = toCompletionEvidence(turnState);
134
- return { status, evidence, ...(abortReason ? { abortReason } : {}), ...(resume ? { resume } : {}) };
145
+ const checkpoint = {
146
+ goalId: turnOptions.goalContext?.goalId ?? goal.id, request: value,
147
+ cycle: turnOptions.goalContext?.cycle ?? 1, mutationCount: goal.mutationCount,
148
+ validationOutcome: turnState.validationOutcome, taskCounts: taskCountsOf(goal.taskProgress),
149
+ progressSignature: goalCheckpointSignature({ mutationCount: goal.mutationCount, validationOutcome: turnState.validationOutcome, taskCounts: taskCountsOf(goal.taskProgress) }),
150
+ noProgressCount: turnOptions.goalContext?.noProgressCount ?? 0,
151
+ requestHash: turnOptions.goalContext?.requestHash, intent: goal.normalizedIntent,
152
+ ...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
153
+ ...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
154
+ };
155
+ return { status, evidence, ...(status !== 'complete' ? { checkpoint } : {}), ...(abortReason ? { abortReason } : {}), ...(resume ? { resume } : {}) };
135
156
  }
136
157
  finally {
137
158
  turnDeadline?.clear();
138
- callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status, evidence: toCompletionEvidence(turnState) }));
159
+ // RT-05: persist an explicit cause for unexplained outcomes in the ledger
160
+ // (no --debug required) and tell the user when a turn dies silently — the
161
+ // live session saw a 20s goal fail with zero assistant output and no
162
+ // timeout/retry events, forcing the user to re-send the prompt.
163
+ const turnEndReason = status === 'failed' ? describeTurnFailure(turnState, callbacks.getLastAssistantText()) : undefined;
164
+ if (turnEndReason === 'model-returned-no-output') {
165
+ callbacks.addMessage({ role: 'system', text: 'The model returned no output for this turn. Send the request again, or retry after a moment; completed work is preserved in the conversation.' });
166
+ }
167
+ callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status, evidence: toCompletionEvidence(turnState), ...(turnEndReason ? { reason: turnEndReason } : {}) }));
139
168
  callbacks.setAbortController?.(null);
140
169
  callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
141
170
  callbacks.setBusy(false);
@@ -108,6 +108,8 @@ export declare function skillScopeSuggestions(): TextInputSuggestion[];
108
108
  export declare function skillsActionSuggestions(settings: HazeSettings, skills: LoadedSkill[], selectedSkillName: string | undefined): TextInputSuggestion[];
109
109
  /** Every built-in theme with its palette brightness and the active one marked (`resolveTheme` validates names). */
110
110
  export declare function themeSuggestions(settings: HazeSettings): TextInputSuggestion[];
111
+ /** Reasoning-effort picker values: every level plus the unset action. */
112
+ export declare function reasoningSuggestions(settings: HazeSettings): TextInputSuggestion[];
111
113
  type WizardStepKind = 'pick' | 'input' | 'masked-input' | 'confirm';
112
114
  /** Inputs available to a step's suggestion builder (mirrors the picker state). */
113
115
  export interface WizardSuggestionState {
@@ -334,6 +336,11 @@ export declare const WIZARD_STEPS: readonly [{
334
336
  readonly kind: "pick";
335
337
  readonly placeholder: "Choose a theme";
336
338
  readonly suggestions: (s: WizardSuggestionState) => TextInputSuggestion[];
339
+ }, {
340
+ readonly id: "reasoning";
341
+ readonly kind: "pick";
342
+ readonly placeholder: "Choose a reasoning effort level";
343
+ readonly suggestions: (s: WizardSuggestionState) => TextInputSuggestion[];
337
344
  }];
338
345
  export type WizardStepId = (typeof WIZARD_STEPS)[number]['id'];
339
346
  /** Suggestions for a wizard mode, or undefined when the mode is not a wizard step ('chat'). */
@@ -4,6 +4,7 @@ import { configuredMcpServers, findMcpServer, findMcpPreset, presetIds } from '.
4
4
  import { isSkillEnabled } from '../../config/skillSettings.js';
5
5
  import { PROVIDER_PRESETS } from '../../config/providerPresets.js';
6
6
  import { CHATGPT_CODEX_BASE_URL } from '../../llm/openaiCodexOAuth.js';
7
+ import { DEFAULT_REASONING_LEVEL, REASONING_LEVELS } from '../../core/agent/reasoningPolicy.js';
7
8
  import { BUILT_IN_THEME_SPECS, DEFAULT_THEME_NAME, resolveTheme } from '../../ui/theme.js';
8
9
  import { sessionActionSuggestions, sessionSuggestions } from './sessionPicker.js';
9
10
  /**
@@ -342,6 +343,25 @@ export function themeSuggestions(settings) {
342
343
  kind: 'theme',
343
344
  }));
344
345
  }
346
+ /** Reasoning-effort picker values: every level plus the unset action. */
347
+ export function reasoningSuggestions(settings) {
348
+ const descriptions = {
349
+ none: 'disable reasoning',
350
+ minimal: 'least reasoning',
351
+ low: 'light reasoning',
352
+ medium: 'moderate reasoning',
353
+ high: 'deep reasoning',
354
+ xhigh: 'maximum reasoning',
355
+ };
356
+ return [
357
+ ...REASONING_LEVELS.map(level => ({
358
+ value: level,
359
+ description: `${descriptions[level] ?? 'reasoning level'}${settings.reasoning === level || (settings.reasoning === undefined && level === DEFAULT_REASONING_LEVEL) ? ' · active' : ''}`,
360
+ kind: 'command',
361
+ })),
362
+ { value: 'unset', description: 'provider default — sends no reasoning parameter', kind: 'command' },
363
+ ];
364
+ }
345
365
  export const WIZARD_STEPS = [
346
366
  // Sessions
347
367
  { id: 'sessions', kind: 'pick', placeholder: 'Choose a saved session', suggestions: (s) => sessionSuggestions(s.sessions ?? []) },
@@ -388,6 +408,8 @@ export const WIZARD_STEPS = [
388
408
  { id: 'mcpConfirmRemove', kind: 'confirm', placeholder: 'Type "yes" to confirm', suggestions: () => [] },
389
409
  // Themes
390
410
  { id: 'themes', kind: 'pick', placeholder: 'Choose a theme', suggestions: (s) => themeSuggestions(s.settings) },
411
+ // Reasoning effort
412
+ { id: 'reasoning', kind: 'pick', placeholder: 'Choose a reasoning effort level', suggestions: (s) => reasoningSuggestions(s.settings) },
391
413
  ];
392
414
  const WIZARD_STEP_BY_ID = Object.fromEntries(WIZARD_STEPS.map(step => [step.id, step]));
393
415
  /** Suggestions for a wizard mode, or undefined when the mode is not a wizard step ('chat'). */
package/dist/cli/index.js CHANGED
@@ -23,6 +23,7 @@ program
23
23
  .option('--no-session', 'run without saving or resuming a durable session')
24
24
  .option('-p, --prompt <text>', 'print mode: run a single non-interactive turn and print the result (falls back to piped stdin)')
25
25
  .option('-m, --model <selector>', 'override the model for this run only — a registered model name or provider:name')
26
+ .addOption(new Option('--reasoning <level>', 'print-mode reasoning effort for this run only — none, minimal, low, medium, high, xhigh, or unset (no parameter sent; provider default)').choices(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'unset', 'off']))
26
27
  .addOption(new Option('--output <format>', 'print-mode output: plain text, a single JSON result envelope, or a stream-json NDJSON event stream').choices(['text', 'json', 'stream-json']).default('text'))
27
28
  .option('--timeout <duration>', 'print-mode absolute turn deadline (e.g. 30s, 10m, 2h); bounds total elapsed time so a busy tool cannot run indefinitely')
28
29
  .option('--until-done', 'print mode: relaunch the goal after transient model failures (with backoff) until it structurally completes, the --timeout deadline hits, or repeated relaunches make no progress');
@@ -34,6 +35,7 @@ Examples:
34
35
  $ haze -p "list the top 3 bugs" --output json emit a JSON envelope { type, status, result, usage }
35
36
  $ haze -p "audit src/" --output stream-json stream NDJSON events live, then the final result envelope
36
37
  $ haze -p "summarize" --model openai:gpt-4o-mini override the model for this run only
38
+ $ haze -p "audit src/" --reasoning xhigh run with maximum reasoning effort (unset = provider default)
37
39
  $ haze --resume <id> -p "continue the review" load a saved context for one print-mode turn
38
40
  $ haze -p "audit auth.ts" --debug also write a detailed JSONL log to ~/.haze/logs/
39
41
 
@@ -48,10 +50,12 @@ Print mode (-p):
48
50
  harnesses live progress, per-step usage, bounded tool-failure diagnostics, and stagnation
49
51
  detection without raw tool inputs or outputs. --model overrides the model for this
50
52
  run only (no settings change) and must already be registered under a provider (add it once via
51
- the /provider picker). Print-mode runs are non-durable: --continue is ignored and no session is
53
+ the /provider picker). --reasoning overrides the reasoning effort for this run only (levels
54
+ none–xhigh; unset sends no reasoning parameter, provider default). Print-mode runs are non-durable: --continue is ignored and no session is
52
55
  saved. --resume <id> loads saved context for the turn without changing that session. On a
53
- provider context overflow, haze compacts the conversation and retries the request once; when
54
- compaction is unavailable, the error says so explicitly.
56
+ provider context overflow, haze compacts the conversation and retries at a progressively smaller
57
+ message budget (up to twice); exhausted retries pause with a context_exhausted checkpoint, and
58
+ when compaction is unavailable, the error says so explicitly.
55
59
  `);
56
60
  async function readStdinPrompt() {
57
61
  // Only read stdin when it is piped (non-TTY); never hang waiting on an interactive terminal.
@@ -115,6 +119,7 @@ program.action(async () => {
115
119
  const code = await runHeadless({
116
120
  prompt,
117
121
  modelOverride: opts.model,
122
+ reasoning: opts.reasoning,
118
123
  resumeSessionId: opts.resume,
119
124
  // commander validates --output against the choices above, so opts.output is one of
120
125
  // 'text' | 'json' | 'stream-json'; default to text for piped/stdin runs without the flag.
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Curated model metadata catalog (Pillar 1.8 of the Pi learning roadmap).
3
+ *
4
+ * Keys are **model-name patterns** (not provider names) because haze reaches
5
+ * most models through user-configured OpenAI-compatible gateways where the
6
+ * provider name is arbitrary — the model id is the only stable identity.
7
+ *
8
+ * Precedence (enforced in `llm/client.ts`): per-model `modelLimits` settings →
9
+ * this catalog → user-set context-window fallback → built-in default fallback.
10
+ * Values are deliberately conservative (input-safe): when a family differs
11
+ * between variants, the smaller window wins — under-budgeting only compacts a
12
+ * little earlier, over-budgeting hard-fails the request. First match wins, so
13
+ * keep more specific patterns before broader family prefixes.
14
+ *
15
+ * Local inference servers (localhost URLs) never consult the catalog: their
16
+ * effective window is set by server configuration (often far below the model's
17
+ * nominal window) and silent truncation there is undetectable.
18
+ */
19
+ export interface CatalogModelLimits {
20
+ contextWindowTokens: number;
21
+ maxOutputTokens?: number;
22
+ }
23
+ interface CatalogEntry extends CatalogModelLimits {
24
+ /** Lower-cased model-name pattern; matched with `startsWith` unless it contains '*', then prefix-before-'*' match. */
25
+ match: string;
26
+ note?: string;
27
+ }
28
+ /** Look up catalog limits for a model name (case-insensitive prefix families). Gateway-style `vendor/model` and `vendor:model` identifiers match on their final segment. */
29
+ export declare function catalogLimitsFor(modelName: string): CatalogModelLimits | undefined;
30
+ /** Catalog entries exposed for pinning tests (like the theme registry). */
31
+ export declare function getModelCatalog(): readonly CatalogEntry[];
32
+ export {};
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Curated model metadata catalog (Pillar 1.8 of the Pi learning roadmap).
3
+ *
4
+ * Keys are **model-name patterns** (not provider names) because haze reaches
5
+ * most models through user-configured OpenAI-compatible gateways where the
6
+ * provider name is arbitrary — the model id is the only stable identity.
7
+ *
8
+ * Precedence (enforced in `llm/client.ts`): per-model `modelLimits` settings →
9
+ * this catalog → user-set context-window fallback → built-in default fallback.
10
+ * Values are deliberately conservative (input-safe): when a family differs
11
+ * between variants, the smaller window wins — under-budgeting only compacts a
12
+ * little earlier, over-budgeting hard-fails the request. First match wins, so
13
+ * keep more specific patterns before broader family prefixes.
14
+ *
15
+ * Local inference servers (localhost URLs) never consult the catalog: their
16
+ * effective window is set by server configuration (often far below the model's
17
+ * nominal window) and silent truncation there is undetectable.
18
+ */
19
+ const MODEL_CATALOG = [
20
+ // ── OpenAI ────────────────────────────────────────────────────────────────
21
+ { match: 'gpt-5.1-codex', contextWindowTokens: 400_000, maxOutputTokens: 128_000 },
22
+ { match: 'gpt-5.1-codex-mini', contextWindowTokens: 400_000, maxOutputTokens: 128_000 },
23
+ { match: 'gpt-5', contextWindowTokens: 400_000, maxOutputTokens: 128_000 },
24
+ { match: 'gpt-4.1', contextWindowTokens: 1_047_576, maxOutputTokens: 32_768 },
25
+ { match: 'gpt-4o', contextWindowTokens: 128_000, maxOutputTokens: 16_384 },
26
+ { match: 'o4', contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
27
+ { match: 'o3', contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
28
+ { match: 'o1', contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
29
+ // ── Anthropic ─────────────────────────────────────────────────────────────
30
+ { match: 'claude-opus-4', contextWindowTokens: 200_000, maxOutputTokens: 32_000 },
31
+ { match: 'claude-sonnet-4', contextWindowTokens: 200_000, maxOutputTokens: 64_000 },
32
+ { match: 'claude-haiku-4', contextWindowTokens: 200_000, maxOutputTokens: 32_000 },
33
+ { match: 'claude-3-7', contextWindowTokens: 200_000, maxOutputTokens: 64_000 },
34
+ { match: 'claude-3-5', contextWindowTokens: 200_000, maxOutputTokens: 8_192 },
35
+ // ── Google ────────────────────────────────────────────────────────────────
36
+ { match: 'gemini-3', contextWindowTokens: 1_048_576, maxOutputTokens: 65_536 },
37
+ { match: 'gemini-2.5', contextWindowTokens: 1_048_576, maxOutputTokens: 65_536 },
38
+ { match: 'gemini-2.0', contextWindowTokens: 1_048_576, maxOutputTokens: 8_192 },
39
+ // ── xAI ───────────────────────────────────────────────────────────────────
40
+ { match: 'grok-4', contextWindowTokens: 256_000, maxOutputTokens: 32_768 },
41
+ { match: 'grok-3', contextWindowTokens: 131_072, maxOutputTokens: 32_768 },
42
+ // ── DeepSeek ──────────────────────────────────────────────────────────────
43
+ { match: 'deepseek-reasoner', contextWindowTokens: 128_000, maxOutputTokens: 32_768, note: 'R1/reasoner family' },
44
+ { match: 'deepseek-r1', contextWindowTokens: 128_000, maxOutputTokens: 32_768 },
45
+ { match: 'deepseek', contextWindowTokens: 128_000, maxOutputTokens: 8_192 },
46
+ // ── Alibaba / Moonshot / Zhipu / MiniMax ─────────────────────────────────
47
+ { match: 'qwen3-coder', contextWindowTokens: 262_144, maxOutputTokens: 32_768 },
48
+ { match: 'qwen3', contextWindowTokens: 131_072, maxOutputTokens: 32_768, note: 'native window without YaRN extension' },
49
+ { match: 'qwen', contextWindowTokens: 131_072, maxOutputTokens: 8_192 },
50
+ { match: 'kimi-k2', contextWindowTokens: 131_072, maxOutputTokens: 32_768, note: 'input-safe half of the 256K total' },
51
+ { match: 'glm-4.6', contextWindowTokens: 200_000, maxOutputTokens: 32_768 },
52
+ { match: 'glm-4.5', contextWindowTokens: 131_072, maxOutputTokens: 32_768 },
53
+ { match: 'minimax-m2', contextWindowTokens: 204_800, maxOutputTokens: 1_048_576, note: 'output budget exceeds window in interleave mode' },
54
+ // ── Meta / Mistral ───────────────────────────────────────────────────────
55
+ { match: 'llama-4-maverick', contextWindowTokens: 1_048_576, maxOutputTokens: 32_768 },
56
+ { match: 'llama-4-scout', contextWindowTokens: 1_048_576, maxOutputTokens: 32_768, note: 'gateway-served window; self-host is server-configured' },
57
+ { match: 'llama-3.3', contextWindowTokens: 128_000, maxOutputTokens: 8_192 },
58
+ { match: 'llama-3.1', contextWindowTokens: 128_000, maxOutputTokens: 8_192 },
59
+ { match: 'mistral-large', contextWindowTokens: 128_000, maxOutputTokens: 32_768 },
60
+ { match: 'mistral-medium', contextWindowTokens: 128_000, maxOutputTokens: 32_768 },
61
+ { match: 'devstral', contextWindowTokens: 128_000, maxOutputTokens: 32_768 },
62
+ { match: 'codestral', contextWindowTokens: 256_000, maxOutputTokens: 32_768 },
63
+ { match: 'mistral', contextWindowTokens: 128_000, maxOutputTokens: 8_192 },
64
+ ];
65
+ /** Look up catalog limits for a model name (case-insensitive prefix families). Gateway-style `vendor/model` and `vendor:model` identifiers match on their final segment. */
66
+ export function catalogLimitsFor(modelName) {
67
+ const name = modelName.trim().toLowerCase();
68
+ if (!name)
69
+ return undefined;
70
+ for (const entry of MODEL_CATALOG) {
71
+ if (name.startsWith(entry.match) || lastSegment(name).startsWith(entry.match)) {
72
+ return { contextWindowTokens: entry.contextWindowTokens, ...(entry.maxOutputTokens !== undefined ? { maxOutputTokens: entry.maxOutputTokens } : {}) };
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+ function lastSegment(name) {
78
+ const slash = Math.max(name.lastIndexOf('/'), name.lastIndexOf(':'));
79
+ return slash === -1 ? name : name.slice(slash + 1);
80
+ }
81
+ /** Catalog entries exposed for pinning tests (like the theme registry). */
82
+ export function getModelCatalog() {
83
+ return MODEL_CATALOG;
84
+ }
@@ -1,6 +1,45 @@
1
+ import { assertCredentialedEndpointSecure } from './endpointSecurity.js';
1
2
  const DEFAULT_TIMEOUT_MS = 5000;
2
3
  /** Discovery feeds a type-filtered picker; cap the stored list, not the UX. */
3
4
  const MAX_DISCOVERED_MODELS = 500;
5
+ /** Redirect hops followed; each hop re-validates the credential transport policy. */
6
+ const MAX_DISCOVERY_REDIRECTS = 2;
7
+ /** CI-04: bound the JSON body before parsing so an oversized response fails loudly. */
8
+ const MAX_DISCOVERY_BODY_BYTES = 1_000_000;
9
+ /** Read a discovery response body as bounded UTF-8; an oversized body fails. */
10
+ async function readBodyBounded(response) {
11
+ if (response.body == null)
12
+ return await response.json();
13
+ const read = await readUtf8PrefixFromStream(response.body, MAX_DISCOVERY_BODY_BYTES);
14
+ if (read.truncated)
15
+ throw new Error(`endpoint response exceeds ${MAX_DISCOVERY_BODY_BYTES} bytes`);
16
+ return JSON.parse(read.content);
17
+ }
18
+ function readUtf8PrefixFromStream(stream, maxBytes) {
19
+ const reader = stream.getReader();
20
+ const chunks = [];
21
+ let received = 0;
22
+ return new Promise((resolve, reject) => {
23
+ const pump = () => {
24
+ reader.read().then(({ done, value }) => {
25
+ if (done) {
26
+ resolve({ content: Buffer.concat(chunks).toString('utf8'), truncated: false });
27
+ return;
28
+ }
29
+ received += value.byteLength;
30
+ if (received > maxBytes) {
31
+ // Cancel and resolve truncated; the caller decides what that means.
32
+ void reader.cancel().catch(() => undefined);
33
+ resolve({ content: '', truncated: true });
34
+ return;
35
+ }
36
+ chunks.push(value);
37
+ pump();
38
+ }, reject);
39
+ };
40
+ pump();
41
+ });
42
+ }
4
43
  export function modelsEndpointUrl(baseUrl) {
5
44
  return `${baseUrl.trim().replace(/\/+$/, '')}/models`;
6
45
  }
@@ -187,12 +226,36 @@ function describeFetchError(error) {
187
226
  export async function discoverProviderModels(provider, options = {}) {
188
227
  const fetchImpl = options.fetchImpl ?? fetch;
189
228
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
229
+ let url = modelsEndpointUrl(provider.url);
230
+ // CI-01: validate before the first network call — a draft key must never be
231
+ // transmitted to a remote plaintext endpoint just because the user is still
232
+ // in a wizard. Re-checked on every redirect hop (downgrades are refused).
233
+ try {
234
+ assertCredentialedEndpointSecure(url, provider.key);
235
+ }
236
+ catch (error) {
237
+ return { status: 'failed', error: error instanceof Error ? error.message : String(error) };
238
+ }
190
239
  let response;
191
240
  try {
192
- response = await fetchImpl(modelsEndpointUrl(provider.url), {
193
- headers: { accept: 'application/json', ...(provider.key ? { authorization: `Bearer ${provider.key}` } : {}) },
194
- signal: AbortSignal.timeout(timeoutMs),
195
- });
241
+ for (let hop = 0;; hop += 1) {
242
+ response = await fetchImpl(url, {
243
+ headers: { accept: 'application/json', ...(provider.key ? { authorization: `Bearer ${provider.key}` } : {}) },
244
+ redirect: 'manual',
245
+ signal: AbortSignal.timeout(timeoutMs),
246
+ });
247
+ const location = response.status >= 300 && response.status < 400 ? response.headers?.get('location') : null;
248
+ if (!location)
249
+ break;
250
+ if (hop >= MAX_DISCOVERY_REDIRECTS)
251
+ return { status: 'failed', error: `endpoint redirected more than ${MAX_DISCOVERY_REDIRECTS} times` };
252
+ const nextUrl = new URL(location, url).toString();
253
+ if (provider.key && new URL(nextUrl).origin !== new URL(url).origin) {
254
+ return { status: 'failed', error: 'credentialed endpoint redirected to a different origin' };
255
+ }
256
+ url = nextUrl;
257
+ assertCredentialedEndpointSecure(url, provider.key);
258
+ }
196
259
  }
197
260
  catch (error) {
198
261
  return { status: 'failed', error: describeFetchError(error) };
@@ -201,7 +264,7 @@ export async function discoverProviderModels(provider, options = {}) {
201
264
  return { status: 'failed', error: `endpoint returned HTTP ${response.status}` };
202
265
  let body;
203
266
  try {
204
- body = await response.json();
267
+ body = await readBodyBounded(response);
205
268
  }
206
269
  catch {
207
270
  return { status: 'failed', error: 'endpoint returned no JSON' };
@@ -1,10 +1,14 @@
1
1
  import { z } from 'zod';
2
- /** Optional, explicitly user-controlled reasoning depth (provider/protocol gated). */
3
- export type ReasoningLevel = 'low' | 'medium' | 'high';
2
+ import { type ReasoningLevel, type StoredReasoningSetting } from '../core/agent/reasoningPolicy.js';
3
+ export type { ReasoningLevel, StoredReasoningSetting };
4
4
  export declare const reasoningLevelSchema: z.ZodEnum<{
5
5
  high: "high";
6
6
  medium: "medium";
7
7
  low: "low";
8
+ none: "none";
9
+ minimal: "minimal";
10
+ xhigh: "xhigh";
11
+ "provider-default": "provider-default";
8
12
  }>;
9
13
  export interface HazeProviderSettings {
10
14
  name: string;
@@ -77,8 +81,8 @@ export interface HazeSettings {
77
81
  mcpServers?: HazeMcpServer[];
78
82
  skills?: HazeSkillSetting[];
79
83
  subagents?: HazeSubagentSettings;
80
- /** Optional reasoning depth; unset by default, mapped by supported provider protocol. */
81
- reasoning?: ReasoningLevel;
84
+ /** Optional reasoning depth; absent means the built-in default (`high`), the `provider-default` sentinel sends no parameter. */
85
+ reasoning?: StoredReasoningSetting;
82
86
  /**
83
87
  * Context-window fallback for models without `modelLimits` metadata, in
84
88
  * tokens. Unset means the built-in default (128K hosted / 32K local —
@@ -94,11 +98,19 @@ export interface HazeSettings {
94
98
  * OpenAI-compatible gateways); 0 disables automatic retries.
95
99
  */
96
100
  modelRetries?: number;
101
+ /**
102
+ * Base delay in milliseconds for the shared model-retry pool backoff
103
+ * (`base * 2^attempt`, capped at 4× the base). Unset means the built-in
104
+ * default of 1000ms. The pool resets whenever an attempt completes a
105
+ * successful step, so intermittent blips never exhaust it.
106
+ */
107
+ retryBaseDelayMs?: number;
97
108
  /**
98
109
  * Manual `/compact` mode (F-09): `llm-summary` (default) asks the active
99
110
  * model to summarize the older history; `heuristic` keeps the bounded
100
- * excerpt without a model call. Automatic mid-turn compaction is always
101
- * heuristic.
111
+ * excerpt without a model call. Mid-turn compaction prefers an LLM summary
112
+ * when the older history is large and falls back to the heuristic excerpt
113
+ * for small trims and on any summarization failure.
102
114
  */
103
115
  manualCompaction?: 'llm-summary' | 'heuristic';
104
116
  /** UI tweaks: rotating tips under the busy label, etc. Default enabled. */
@@ -4,7 +4,14 @@ import { z } from 'zod';
4
4
  import { HAZE_DIR } from './paths.js';
5
5
  import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
6
6
  import { customProfileSchema } from '../core/subagent/executionProfiles.js';
7
- export const reasoningLevelSchema = z.enum(['low', 'medium', 'high']);
7
+ import { REASONING_LEVELS, REASONING_PROVIDER_DEFAULT } from '../core/agent/reasoningPolicy.js';
8
+ /**
9
+ * Optional, explicitly user-controlled reasoning depth (provider/protocol
10
+ * gated). Absent means the built-in default (`high`); the `provider-default`
11
+ * sentinel stores an explicit "send no parameter" opt-out.
12
+ */
13
+ const storedReasoningValues = [...REASONING_LEVELS, REASONING_PROVIDER_DEFAULT];
14
+ export const reasoningLevelSchema = z.enum(storedReasoningValues);
8
15
  export const SETTINGS_FILE = path.join(HAZE_DIR, 'settings.json');
9
16
  const providerCapabilitiesSchema = z.object({
10
17
  images: z.boolean().optional(),
@@ -46,6 +53,8 @@ const subagentSettingsSchema = z.object({
46
53
  const contextWindowFallbackSchema = z.number().int().min(1_000).max(10_000_000);
47
54
  /** Retry-pool size must be a small non-negative count (0 disables retries). */
48
55
  const modelRetriesSchema = z.number().int().min(0).max(10);
56
+ /** Retry backoff base must be a plausible delay (not fractions/junk). */
57
+ const retryBaseDelaySchema = z.number().int().min(250).max(60_000);
49
58
  const settingsSchema = z.object({
50
59
  provider: z.string().optional(),
51
60
  model: z.string().optional(),
@@ -58,6 +67,7 @@ const settingsSchema = z.object({
58
67
  contextWindowFallbackTokens: contextWindowFallbackSchema.optional(),
59
68
  localContextWindowFallbackTokens: contextWindowFallbackSchema.optional(),
60
69
  modelRetries: modelRetriesSchema.optional(),
70
+ retryBaseDelayMs: retryBaseDelaySchema.optional(),
61
71
  manualCompaction: z.enum(['llm-summary', 'heuristic']).optional(),
62
72
  tips: z.object({ enabled: z.boolean().optional() }).optional(),
63
73
  theme: z.string().optional(),
@@ -42,8 +42,16 @@ export declare const SUBAGENT_MAX_CONCURRENCY = 10;
42
42
  export declare const SUBAGENT_MAX_RETRIES = 5;
43
43
  /** Default size of the shared bounded model-retry pool for transient model errors and idle-stream stalls, per turn. Configurable via the `modelRetries` setting (0 disables automatic retries). */
44
44
  export declare const DEFAULT_MODEL_RETRIES = 2;
45
- /** Upper bound accepted for the `modelRetries` setting (mirrors the settings schema). */
46
- export declare const MAX_MODEL_RETRIES_SETTING = 10;
45
+ /** Default base delay for the shared model-retry pool backoff (`base * 2^attempt`, capped at 4× the base). Configurable via the `retryBaseDelayMs` setting. */
46
+ export declare const DEFAULT_RETRY_BASE_DELAY_MS = 1000;
47
+ /** Each context-overflow retry multiplies the message-token budget by this factor (Pillar 1.4: 0.6 → 0.36 → checkpoint). */
48
+ export declare const OVERFLOW_SHRINK_FACTOR = 0.6;
49
+ /** Bounded context-overflow retries per turn before the goal checkpoints instead of hard-failing (Pillar 1.4). */
50
+ export declare const MAX_OVERFLOW_RETRIES = 2;
51
+ /** Older-history estimate (tokens) at which mid-turn compaction prefers an LLM-written summary over the heuristic excerpt (Pillar 1.5). */
52
+ export declare const COMPACTION_LLM_MIN_OLDER_TOKENS = 6000;
53
+ /** Output cap for mid-turn LLM summarization calls; summaries never need the full response budget. */
54
+ export declare const COMPACTION_LLM_MAX_OUTPUT_TOKENS = 4096;
47
55
  export interface TurnBudget {
48
56
  /** Maximum completed model steps across the whole turn (incl. recovery). */
49
57
  stepLimit: number;
@@ -49,8 +49,16 @@ export const SUBAGENT_MAX_CONCURRENCY = 10;
49
49
  export const SUBAGENT_MAX_RETRIES = 5;
50
50
  /** Default size of the shared bounded model-retry pool for transient model errors and idle-stream stalls, per turn. Configurable via the `modelRetries` setting (0 disables automatic retries). */
51
51
  export const DEFAULT_MODEL_RETRIES = 2;
52
- /** Upper bound accepted for the `modelRetries` setting (mirrors the settings schema). */
53
- export const MAX_MODEL_RETRIES_SETTING = 10;
52
+ /** Default base delay for the shared model-retry pool backoff (`base * 2^attempt`, capped at 4× the base). Configurable via the `retryBaseDelayMs` setting. */
53
+ export const DEFAULT_RETRY_BASE_DELAY_MS = 1_000;
54
+ /** Each context-overflow retry multiplies the message-token budget by this factor (Pillar 1.4: 0.6 → 0.36 → checkpoint). */
55
+ export const OVERFLOW_SHRINK_FACTOR = 0.6;
56
+ /** Bounded context-overflow retries per turn before the goal checkpoints instead of hard-failing (Pillar 1.4). */
57
+ export const MAX_OVERFLOW_RETRIES = 2;
58
+ /** Older-history estimate (tokens) at which mid-turn compaction prefers an LLM-written summary over the heuristic excerpt (Pillar 1.5). */
59
+ export const COMPACTION_LLM_MIN_OLDER_TOKENS = 6_000;
60
+ /** Output cap for mid-turn LLM summarization calls; summaries never need the full response budget. */
61
+ export const COMPACTION_LLM_MAX_OUTPUT_TOKENS = 4_096;
54
62
  export function mainTurnBudget() {
55
63
  return { stepLimit: MAIN_STEP_LIMIT, toolCallLimit: MAIN_TOOL_CALL_LIMIT, toolOnlyStepLimit: MAIN_TOOL_ONLY_STEP_LIMIT };
56
64
  }
@@ -10,6 +10,13 @@ export interface CompactionResult {
10
10
  export interface CompactionSplit {
11
11
  older: ModelMessage[];
12
12
  recent: ModelMessage[];
13
+ /**
14
+ * The recent window lands mid-turn: the first kept message is not a user
15
+ * message, so the older half contains the early prefix of the current
16
+ * (unfinished) turn (Pillar 1.6). The LLM summarization path uses this to
17
+ * preserve the in-flight task's request, progress, and next action.
18
+ */
19
+ splitTurn: boolean;
13
20
  }
14
21
  /**
15
22
  * Decide which trailing messages survive compaction and which are folded into
@@ -29,16 +36,48 @@ export declare function compactModelMessages(messages: ModelMessage[], options?:
29
36
  instructions?: string;
30
37
  workState?: WorkState;
31
38
  }): CompactionResult;
39
+ /**
40
+ * Extract the summary text of an existing `<haze_compaction>` message so a
41
+ * later LLM summarization can update it in place instead of re-summarizing
42
+ * the whole history from scratch (Pillar 1.5, iterative summaries).
43
+ */
44
+ export declare function extractExistingCompactionSummary(messages: ModelMessage[]): string | undefined;
45
+ /** Which mid-turn compaction method an epoch boundary should use (Pillar 1.5). */
46
+ export type BoundaryCompactionMethod = 'none' | 'heuristic' | 'llm';
47
+ /**
48
+ * Choose the mid-turn compaction method: `none` while the conversation fits
49
+ * the budget; the deterministic heuristic excerpt for small older halves (fast,
50
+ * no extra model call); an LLM-written summary once the older history is large
51
+ * enough that an excerpt loses decisions and next steps. `totalTokens`
52
+ * overrides the chars/4 estimate for the over-budget check so a usage-anchored
53
+ * total (Pillar 1.1) can trigger compaction for token-dense history that the
54
+ * heuristic estimate undercounts.
55
+ */
56
+ export declare function chooseBoundaryCompactionMethod(input: {
57
+ messages: ModelMessage[];
58
+ messageTokenBudget: number;
59
+ olderTokenThreshold: number;
60
+ estimateTokens?: (messages: ModelMessage[]) => number;
61
+ totalTokens?: number;
62
+ }): {
63
+ method: BoundaryCompactionMethod;
64
+ split?: CompactionSplit;
65
+ };
32
66
  /**
33
67
  * Build the summarization request for the LLM-summarized compaction path
34
- * (F-09). The transcript is the older half, bounded to a character budget and
35
- * truncated from the front (the oldest context is the least valuable) so the
36
- * request itself can never overflow the model.
68
+ * (F-09; also the mid-turn path, Pillar 1.5). The transcript is the older
69
+ * half, bounded to a character budget and truncated from the front (the oldest
70
+ * context is the least valuable) so the request itself can never overflow the
71
+ * model. When a previous compaction summary exists it is included so the model
72
+ * updates it in place (iterative summaries); a split turn adds instructions to
73
+ * preserve the unfinished task's request, progress, and next action.
37
74
  */
38
75
  export declare function buildLlmCompactionPrompt(input: {
39
76
  older: ModelMessage[];
40
77
  instructions?: string;
41
78
  maxChars?: number;
79
+ previousSummary?: string;
80
+ splitTurn?: boolean;
42
81
  }): string;
43
82
  /**
44
83
  * Assemble the compacted history around a model-written summary (F-09). Same