@denizokcu/haze 1.1.0 → 1.2.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 (149) hide show
  1. package/CHANGELOG.md +49 -1
  2. package/README.md +17 -10
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/busyIndicator.d.ts +11 -0
  6. package/dist/cli/chat/busyIndicator.js +34 -0
  7. package/dist/cli/chat/chatMetrics.d.ts +0 -1
  8. package/dist/cli/chat/chatMetrics.js +1 -7
  9. package/dist/cli/chat/followUpQueue.d.ts +11 -0
  10. package/dist/cli/chat/followUpQueue.js +38 -0
  11. package/dist/cli/chat/messages.d.ts +0 -22
  12. package/dist/cli/chat/messages.js +40 -85
  13. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  14. package/dist/cli/chat/sessionLifecycle.js +8 -1
  15. package/dist/cli/chat/sessionRecorder.d.ts +9 -0
  16. package/dist/cli/chat/sessionRecorder.js +12 -0
  17. package/dist/cli/chat/startupSequence.d.ts +29 -0
  18. package/dist/cli/chat/startupSequence.js +59 -0
  19. package/dist/cli/chat/transcriptPartition.d.ts +23 -0
  20. package/dist/cli/chat/transcriptPartition.js +78 -0
  21. package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
  22. package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
  23. package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
  24. package/dist/cli/chat/wizard/lspHandlers.js +85 -0
  25. package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
  26. package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
  27. package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
  28. package/dist/cli/chat/wizard/providerHandlers.js +420 -0
  29. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
  30. package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
  31. package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
  32. package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
  33. package/dist/cli/chat/wizard/types.d.ts +63 -0
  34. package/dist/cli/chat/wizard/types.js +24 -0
  35. package/dist/cli/chat/wizard/uiState.d.ts +56 -0
  36. package/dist/cli/chat/wizard/uiState.js +15 -0
  37. package/dist/cli/chat/wizardDispatch.d.ts +11 -113
  38. package/dist/cli/chat/wizardDispatch.js +41 -815
  39. package/dist/cli/commands/chat.js +69 -110
  40. package/dist/cli/commands/formatters.d.ts +0 -3
  41. package/dist/cli/commands/formatters.js +0 -29
  42. package/dist/cli/commands/runCommand.d.ts +2 -0
  43. package/dist/cli/commands/runCommand.js +73 -4
  44. package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
  45. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  46. package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
  47. package/dist/cli/commands/streaming/assistantSegments.js +48 -0
  48. package/dist/cli/commands/streaming/attemptOutcome.d.ts +25 -5
  49. package/dist/cli/commands/streaming/attemptOutcome.js +69 -16
  50. package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
  51. package/dist/cli/commands/streaming/attemptSetup.js +30 -13
  52. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
  53. package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
  54. package/dist/cli/commands/streaming/goalSupervisor.d.ts +18 -3
  55. package/dist/cli/commands/streaming/goalSupervisor.js +71 -12
  56. package/dist/cli/commands/streaming/prepareStep.d.ts +40 -0
  57. package/dist/cli/commands/streaming/prepareStep.js +116 -0
  58. package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
  59. package/dist/cli/commands/streaming/recoverySlices.js +29 -0
  60. package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
  61. package/dist/cli/commands/streaming/stallRecovery.js +2 -6
  62. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  63. package/dist/cli/commands/streaming/streamLoop.js +283 -268
  64. package/dist/cli/commands/streaming/toolGroupRenderer.js +2 -1
  65. package/dist/cli/commands/streaming/toolPartHandlers.d.ts +19 -0
  66. package/dist/cli/commands/streaming/toolPartHandlers.js +108 -0
  67. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  68. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  69. package/dist/cli/commands/streaming.d.ts +12 -1
  70. package/dist/cli/commands/streaming.js +20 -25
  71. package/dist/cli/index.js +6 -3
  72. package/dist/config/modelCatalog.d.ts +32 -0
  73. package/dist/config/modelCatalog.js +84 -0
  74. package/dist/config/providerPresets.d.ts +7 -0
  75. package/dist/config/providerPresets.js +195 -391
  76. package/dist/config/settings.d.ts +10 -2
  77. package/dist/config/settings.js +3 -0
  78. package/dist/core/agent/budgets.d.ts +10 -0
  79. package/dist/core/agent/budgets.js +10 -0
  80. package/dist/core/agent/compaction.d.ts +42 -3
  81. package/dist/core/agent/compaction.js +53 -5
  82. package/dist/core/agent/completionController.d.ts +16 -7
  83. package/dist/core/agent/completionController.js +13 -6
  84. package/dist/core/agent/contextBudget.d.ts +56 -0
  85. package/dist/core/agent/contextBudget.js +53 -0
  86. package/dist/core/agent/errors.js +2 -2
  87. package/dist/core/agent/events.d.ts +36 -1
  88. package/dist/core/agent/goalPolicy.d.ts +4 -3
  89. package/dist/core/agent/goalPolicy.js +9 -4
  90. package/dist/core/agent/overflow.d.ts +45 -0
  91. package/dist/core/agent/overflow.js +91 -0
  92. package/dist/core/agent/requestAssembly.d.ts +7 -0
  93. package/dist/core/agent/requestAssembly.js +15 -7
  94. package/dist/core/agent/workState.d.ts +25 -15
  95. package/dist/core/agent/workState.js +84 -44
  96. package/dist/core/safety/shellClassifier.d.ts +16 -0
  97. package/dist/core/safety/shellClassifier.js +31 -0
  98. package/dist/core/session/sessionSlimming.js +8 -0
  99. package/dist/core/session/sessionStore.d.ts +71 -1
  100. package/dist/core/session/sessionStore.js +121 -6
  101. package/dist/core/validation/outputParser.d.ts +1 -1
  102. package/dist/core/validation/outputParser.js +6 -1
  103. package/dist/llm/client.d.ts +2 -2
  104. package/dist/llm/client.js +14 -6
  105. package/dist/llm/hazeTools.d.ts +64 -208
  106. package/dist/llm/tools/shellTool.js +27 -8
  107. package/dist/llm/tools/taskTool.d.ts +64 -208
  108. package/dist/llm/tools/taskTool.js +22 -10
  109. package/dist/ui/components/TextInput.d.ts +18 -1
  110. package/dist/ui/components/TextInput.js +50 -73
  111. package/dist/ui/components/useInputSuggestions.d.ts +27 -0
  112. package/dist/ui/components/useInputSuggestions.js +98 -0
  113. package/dist/ui/theme.d.ts +8 -8
  114. package/dist/ui/theme.js +11 -12
  115. package/dist/ui/themes/registry.d.ts +5 -0
  116. package/dist/ui/themes/registry.js +436 -0
  117. package/dist/utils/format.d.ts +10 -0
  118. package/dist/utils/format.js +45 -0
  119. package/package.json +16 -15
  120. package/dist/ui/themes/af-magic.d.ts +0 -7
  121. package/dist/ui/themes/af-magic.js +0 -25
  122. package/dist/ui/themes/agnoster.d.ts +0 -10
  123. package/dist/ui/themes/agnoster.js +0 -40
  124. package/dist/ui/themes/bira.d.ts +0 -10
  125. package/dist/ui/themes/bira.js +0 -28
  126. package/dist/ui/themes/bureau.d.ts +0 -10
  127. package/dist/ui/themes/bureau.js +0 -28
  128. package/dist/ui/themes/clean.d.ts +0 -9
  129. package/dist/ui/themes/clean.js +0 -27
  130. package/dist/ui/themes/cloud.d.ts +0 -6
  131. package/dist/ui/themes/cloud.js +0 -24
  132. package/dist/ui/themes/dst.d.ts +0 -10
  133. package/dist/ui/themes/dst.js +0 -28
  134. package/dist/ui/themes/fishy.d.ts +0 -7
  135. package/dist/ui/themes/fishy.js +0 -25
  136. package/dist/ui/themes/index.d.ts +0 -8
  137. package/dist/ui/themes/index.js +0 -36
  138. package/dist/ui/themes/light.d.ts +0 -3
  139. package/dist/ui/themes/light.js +0 -21
  140. package/dist/ui/themes/purple.d.ts +0 -7
  141. package/dist/ui/themes/purple.js +0 -26
  142. package/dist/ui/themes/robbyrussell.d.ts +0 -8
  143. package/dist/ui/themes/robbyrussell.js +0 -26
  144. package/dist/ui/themes/solarized-dark.d.ts +0 -16
  145. package/dist/ui/themes/solarized-dark.js +0 -44
  146. package/dist/ui/themes/solarized-light.d.ts +0 -12
  147. package/dist/ui/themes/solarized-light.js +0 -40
  148. package/dist/ui/themes/steeef.d.ts +0 -11
  149. package/dist/ui/themes/steeef.js +0 -29
@@ -1,6 +1,7 @@
1
1
  import { agentEvent } from '../../../core/agent/events.js';
2
2
  import { appendLogEntry as logAppend } from '../../../core/log/llmLog.js';
3
- import { toolCallSummary, compact, formatElapsedTimeWhole, formatSeconds } from '../formatters.js';
3
+ import { toolCallSummary, compact } from '../formatters.js';
4
+ import { formatElapsedTimeWhole, formatSeconds } from '../../../utils/format.js';
4
5
  function logEntry(log, entry) {
5
6
  if (log)
6
7
  void logAppend(log, entry).catch(() => undefined);
@@ -0,0 +1,19 @@
1
+ import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
2
+ import { type ToolGroupRenderer } from './toolGroupRenderer.js';
3
+ import type { StreamCallbacks } from '../streaming.js';
4
+ import type { AttemptSetup } from './attemptSetup.js';
5
+ import type { AttemptLoopState } from './streamLoop.js';
6
+ /** One consumed public stream part, keyed by `type` (see the AI SDK's full-stream parts). */
7
+ export type AttemptStreamPart = {
8
+ type: string;
9
+ } & Record<string, unknown>;
10
+ type ToolPartHandlerDeps = {
11
+ loopState: AttemptLoopState;
12
+ callbacks: StreamCallbacks;
13
+ toolDisplay: ToolGroupRenderer;
14
+ setup: AttemptSetup;
15
+ goal: SessionGoal;
16
+ };
17
+ export declare function handleToolResultPart(deps: ToolPartHandlerDeps, part: AttemptStreamPart): void;
18
+ export declare function handleToolErrorPart(deps: ToolPartHandlerDeps, part: AttemptStreamPart): void;
19
+ export {};
@@ -0,0 +1,108 @@
1
+ import { agentEvent } from '../../../core/agent/events.js';
2
+ import { formatGoalStatus, observeGoalToolEvent } from '../../../core/agent/goalPolicy.js';
3
+ import { DEFAULT_TOOL_DEADLINE_MS, SUBAGENT_TOOL_DEADLINE_MS, isToolBudgetBlocked } from '../../../core/agent/budgets.js';
4
+ import { isToolDeadlineExceeded } from '../../../core/deadline.js';
5
+ import { isDuplicateSkippedOutput, safeToolFailureDetails, toolOutputOk } from '../../../core/agent/toolResults.js';
6
+ import { toolResultSummary } from '../formatters.js';
7
+ import { toolDiffFromResult } from './toolGroupRenderer.js';
8
+ import { isMalformedToolInputError } from './toolCallRecovery.js';
9
+ import { logEntry, rememberContextFilesFromToolOutput, subagentTokenEstimate } from './turnRuntime.js';
10
+ function releaseCompletedToolCall(loopState, toolCallId) {
11
+ // The exact protocol message remains in provider history; display state has
12
+ // already reduced the input to a summary, so do not retain a second copy in
13
+ // per-attempt bookkeeping after the result/error is consumed.
14
+ loopState.latestToolCalls.delete(toolCallId);
15
+ loopState.startedTools.delete(toolCallId);
16
+ }
17
+ export function handleToolResultPart(deps, part) {
18
+ const { loopState, callbacks, toolDisplay, setup, goal } = deps;
19
+ const toolCallId = part.toolCallId;
20
+ const toolName = part.toolName;
21
+ loopState.sawToolCall = true;
22
+ const toolCall = { toolCallId, toolName, input: part.input };
23
+ loopState.latestToolCalls.set(toolCallId, toolCall);
24
+ loopState.inFlightTools.delete(toolCallId);
25
+ const startedAt = loopState.startedTools.get(toolCallId) ?? Date.now();
26
+ // A budget-blocked call never reached the underlying implementation;
27
+ // record it as a bounded non-event with no goal/observal side effect (RH-003).
28
+ if (isToolBudgetBlocked(part.output)) {
29
+ const item = toolDisplay.ensureToolItem(toolCall);
30
+ item.status = 'error';
31
+ item.result = 'skipped: tool-call budget exhausted';
32
+ item.durationMs = Date.now() - startedAt;
33
+ item.finishedAt = startedAt + (item.durationMs ?? 0);
34
+ callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_budget_blocked', durationMs: item.durationMs ?? 0 }));
35
+ toolDisplay.updateToolGroup(true);
36
+ releaseCompletedToolCall(loopState, toolCallId);
37
+ return;
38
+ }
39
+ // A deadline-exceeded call was terminated at the wrapper boundary; the
40
+ // underlying work may still be settling and must not mutate goal state (RH-004).
41
+ if (isToolDeadlineExceeded(part.output)) {
42
+ const item = toolDisplay.ensureToolItem(toolCall);
43
+ item.status = 'error';
44
+ item.result = `timed out after ${DEFAULT_TOOL_DEADLINE_MS}ms`;
45
+ const durationMs = Date.now() - startedAt;
46
+ item.durationMs = durationMs;
47
+ item.finishedAt = startedAt + durationMs;
48
+ callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_deadline', durationMs }));
49
+ callbacks.onEvent?.(agentEvent({ type: 'timeout', phase: 'tool', timeoutMs: toolName === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS }));
50
+ toolDisplay.updateToolGroup(true);
51
+ releaseCompletedToolCall(loopState, toolCallId);
52
+ return;
53
+ }
54
+ const ok = toolOutputOk(part.output, true);
55
+ loopState.lastToolOk = ok;
56
+ if (ok && part.toolName === loopState.unresolvedMalformedToolName)
57
+ loopState.unresolvedMalformedToolName = undefined;
58
+ const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
59
+ const item = toolDisplay.ensureToolItem(toolCall);
60
+ item.status = ok ? 'success' : 'error';
61
+ item.result = toolResultSummary(finish);
62
+ item.diff = toolDiffFromResult(toolCall, part.output);
63
+ item.durationMs = finish.durationMs;
64
+ item.finishedAt = startedAt + finish.durationMs;
65
+ const failureDetails = ok || setup.toolCategories.get(toolCall.toolName) !== 'builtin' ? {} : safeToolFailureDetails(part.output);
66
+ callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, ...failureDetails, durationMs: finish.durationMs }));
67
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs } });
68
+ observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
69
+ callbacks.setWorkState?.(goal);
70
+ callbacks.setGoalStatus?.(formatGoalStatus(goal));
71
+ loopState.contextFiles = rememberContextFilesFromToolOutput(loopState.contextFiles, part.output);
72
+ if (toolCall.toolName === 'writeTasks')
73
+ callbacks.onTasksChanged?.();
74
+ const nestedTokens = subagentTokenEstimate(part.output);
75
+ if (nestedTokens)
76
+ callbacks.recordTokenUsage?.({ inputTokens: nestedTokens.input, outputTokens: nestedTokens.output, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: nestedTokens.input, reasoningTokens: 0, logicalInputEstimate: nestedTokens.input, effectiveNonCachedInput: nestedTokens.input });
77
+ toolDisplay.updateToolGroup(true);
78
+ releaseCompletedToolCall(loopState, toolCallId);
79
+ }
80
+ export function handleToolErrorPart(deps, part) {
81
+ const { loopState, callbacks, toolDisplay, setup, goal } = deps;
82
+ const toolCallId = part.toolCallId;
83
+ const toolName = part.toolName;
84
+ loopState.sawToolCall = true;
85
+ loopState.inFlightTools.delete(toolCallId);
86
+ const existing = loopState.latestToolCalls.get(toolCallId);
87
+ const toolCall = { toolCallId, toolName, input: part.input ?? existing?.input };
88
+ const startedAt = loopState.startedTools.get(toolCallId) ?? Date.now();
89
+ loopState.lastToolOk = false;
90
+ if (isMalformedToolInputError(part.error)) {
91
+ loopState.pendingMalformedToolName = toolName;
92
+ loopState.unresolvedMalformedToolName = toolName;
93
+ }
94
+ const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
95
+ const item = toolDisplay.ensureToolItem(toolCall);
96
+ item.status = 'error';
97
+ item.result = toolResultSummary(finish);
98
+ item.durationMs = finish.durationMs;
99
+ item.finishedAt = startedAt + finish.durationMs;
100
+ const publicError = setup.toolCategories.get(toolCall.toolName) === 'builtin' ? { error: part.error } : {};
101
+ callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_execution_error', ...publicError, durationMs: finish.durationMs }));
102
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs } });
103
+ observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
104
+ callbacks.setWorkState?.(goal);
105
+ callbacks.setGoalStatus?.(formatGoalStatus(goal));
106
+ toolDisplay.updateToolGroup(true);
107
+ releaseCompletedToolCall(loopState, toolCallId);
108
+ }
@@ -16,7 +16,7 @@ export interface TokenUsage {
16
16
  logicalInputEstimate: number;
17
17
  effectiveNonCachedInput: number | undefined;
18
18
  }
19
- export declare function retryDelayMs(attempt: number): number;
19
+ export declare function retryDelayMs(attempt: number, baseDelayMs?: number): number;
20
20
  /** Append one entry to the per-turn LLM log when file logging is enabled; never blocks the turn. */
21
21
  export declare function logEntry(log: LlmLog | undefined, entry: LlmLogEntry): void;
22
22
  export declare function abortableDelay(milliseconds: number, signal: AbortSignal): Promise<void>;
@@ -1,7 +1,8 @@
1
1
  import { appendLogEntry as logAppend } from '../../../core/log/llmLog.js';
2
2
  import { cacheHitRatio, contextBreakdown, effectiveNonCachedInput, estimateValueTokens } from '../../../core/agent/contextBudget.js';
3
- export function retryDelayMs(attempt) {
4
- return Math.min(4000, 1000 * 2 ** attempt);
3
+ import { DEFAULT_RETRY_BASE_DELAY_MS } from '../../../core/agent/budgets.js';
4
+ export function retryDelayMs(attempt, baseDelayMs = DEFAULT_RETRY_BASE_DELAY_MS) {
5
+ return Math.min(baseDelayMs * 4, baseDelayMs * 2 ** attempt);
5
6
  }
6
7
  /** Append one entry to the per-turn LLM log when file logging is enabled; never blocks the turn. */
7
8
  export function logEntry(log, entry) {
@@ -4,7 +4,7 @@ import { type AgentEventSink } from '../../core/agent/events.js';
4
4
  import type { ImageAttachment } from '../../core/attachments/imageAttachments.js';
5
5
  import { type BlessedPath } from '../../core/attachments/readBlessings.js';
6
6
  import type { TurnCompletionEvidence } from '../../core/agent/completionController.js';
7
- import type { ValidationOutcome, WorkTaskProgress, WorkState } from '../../core/agent/workState.js';
7
+ import type { RedEvidence, ValidationOutcome, WorkTaskProgress, WorkState } from '../../core/agent/workState.js';
8
8
  import type { SubagentOverrides, TurnExecutionScope } from '../../llm/requestContext.js';
9
9
  import type { PromptSession } from '../../llm/systemPrompt.js';
10
10
  import type { ContextFile } from '../../config/contextFiles.js';
@@ -64,9 +64,12 @@ interface TurnGoalContext {
64
64
  mutationCount: number;
65
65
  validationOutcome: ValidationOutcome;
66
66
  taskProgress?: WorkTaskProgress;
67
+ redEvidence?: RedEvidence;
67
68
  };
68
69
  /** Consecutive no-progress physical turns at goal level (diagnostics). */
69
70
  noProgressCount: number;
71
+ /** Hash binding of the exact mission bytes (P1); rides every checkpoint downstream. */
72
+ requestHash?: string;
70
73
  }
71
74
  export interface TurnExecutionOptions {
72
75
  ephemeralControl?: string;
@@ -104,6 +107,14 @@ export interface StreamCallbacks {
104
107
  setGoalStatus?: (status: string | undefined) => void;
105
108
  onEvent?: AgentEventSink;
106
109
  compactConversation?: (instructions?: string) => boolean;
110
+ /** Durable compaction audit hook (Pillar 1.7): fired for every automatic compaction that rewrites the conversation, mirroring the session `compact` entry shape. */
111
+ recordCompaction?: (entry: {
112
+ method: 'heuristic' | 'llm';
113
+ olderCount: number;
114
+ keptCount: number;
115
+ instructions?: string;
116
+ summary: string;
117
+ }) => void;
107
118
  recordTokenUsage?: (usage: TokenUsage) => void;
108
119
  setWorkState?: (state: WorkState) => void;
109
120
  onTasksChanged?: () => void;
@@ -1,8 +1,8 @@
1
1
  import { agentEvent } from '../../core/agent/events.js';
2
- import { createTurnExecutionState, recordGoalContinuation, toCompletionEvidence } from '../../core/agent/completionController.js';
2
+ import { createTurnExecutionState, 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
8
  import { abortableDelay } from './streaming/turnRuntime.js';
@@ -10,7 +10,8 @@ import { abortForTurn, createUserAbortCause } from './streaming/abortCause.js';
10
10
  import { runAgentAttempt } from './streaming/agentAttempt.js';
11
11
  import { projectGoalEvidence } from './streaming/attemptOutcome.js';
12
12
  import { awaitAttemptWithForcedSettlement, createAttemptCleanupRegistry, createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
13
- import { formatIdleMinutes } from './streaming/stallRecovery.js';
13
+ import { startRecoverySlice } from './streaming/recoverySlices.js';
14
+ import { formatIdleMinutes } from '../../utils/format.js';
14
15
  export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
15
16
  // The controller is replaced when an idle-stall retry needs a live signal
16
17
  // after aborting a hung stream, so both it and the cause are mutable.
@@ -35,6 +36,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
35
36
  // logical goal shares the same lease.
36
37
  const turnScope = turnOptions.sharedTurnScope ?? {};
37
38
  const turnBudget = mainTurnBudget();
39
+ // Turn-scoped provider-usage anchor (Pillar 1.1): context estimation prefers
40
+ // real usage from the last completed step, with chars/4 estimates only for
41
+ // trailing messages. Shared across attempts and invalidated by compaction.
42
+ const usageAnchor = { current: undefined };
38
43
  // Turn-wide execution budget (RH-003): one authoritative counter of
39
44
  // underlying tool executions, shared across retries and recovery slices so
40
45
  // the global limit cannot be reset or exceeded. The slice budget caps the
@@ -56,7 +61,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
56
61
  turnState.intent = goal.intent;
57
62
  let activeOptions = turnOptions;
58
63
  let attempt = retryAttempt;
59
- let overflowRecovered = contextOverflowRecovered;
64
+ let overflowRetries = contextOverflowRecovered ? 1 : 0;
65
+ let overflowShrinkFactor = contextOverflowRecovered ? OVERFLOW_SHRINK_FACTOR : 1;
66
+ let stepsUsedAtLastRetry = 0;
60
67
  let retrying = retryingExistingRequest;
61
68
  // The attempt machinery runs against quarantinable callbacks so an
62
69
  // abort-ignoring stream that outlives forced settlement cannot mutate the
@@ -79,7 +86,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
79
86
  },
80
87
  });
81
88
  const cleanup = createAttemptCleanupRegistry();
82
- 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)) }), {
89
+ const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, overflowShrinkFactor, overflowRetries, progressSinceLastRetry: turnState.stepsUsed > stepsUsedAtLastRetry, session, modelOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)), usageAnchor }), {
83
90
  abortController,
84
91
  cleanup,
85
92
  quarantine,
@@ -101,7 +108,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
101
108
  resume = result.resume;
102
109
  if (result.retry) {
103
110
  attempt = result.retry.attempt;
104
- overflowRecovered = result.retry.contextOverflowRecovered;
111
+ if (result.retry.overflowShrinkFactor != null) {
112
+ overflowRetries += 1;
113
+ overflowShrinkFactor = result.retry.overflowShrinkFactor;
114
+ }
115
+ stepsUsedAtLastRetry = turnState.stepsUsed;
105
116
  retrying = true;
106
117
  if (result.retry.freshController) {
107
118
  // The idle stall aborted the previous controller to kill the hung
@@ -119,27 +130,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
119
130
  continue;
120
131
  }
121
132
  // Bounded recovery slice (length-continuation, rescue, or goal
122
- // continuation). Length/rescue credits are single-use, so a slice cannot
123
- // trigger another of the same kind; goal continuation is repeatable but
124
- // progress-guarded and counts against the shared turn budget. Abort is
125
- // re-checked before and within the slice.
133
+ // continuation); see recoverySlices.ts. Abort is re-checked before and
134
+ // within the slice.
126
135
  if (result.recovery && !abortController.signal.aborted) {
127
- const rec = result.recovery;
128
- if (rec.kind === 'length') {
129
- turnState.lengthCreditUsed = true;
130
- turnState.lengthRecoveriesAttempted += 1;
131
- }
132
- else if (rec.kind === 'rescue')
133
- turnState.rescueUsed = true;
134
- else
135
- recordGoalContinuation(turnState);
136
- // A new slice gets a fresh execution allowance, clamped once here; the
137
- // slice budget persists across provider retries within the slice (C2).
138
- sliceBudget.started = 0;
139
- sliceBudget.exceeded = false;
140
- activeOptions = { ...activeOptions, ephemeralControl: rec.control, recoverySlice: { kind: rec.kind, maxSteps: rec.slice.maxSteps, maxToolCalls: rec.slice.maxToolCalls } };
136
+ activeOptions = startRecoverySlice(result.recovery, { turnState, sliceBudget, options: activeOptions }, callbacks.debugLog);
141
137
  retrying = true;
142
- callbacks.debugLog(`starting ${rec.kind} recovery slice: ${rec.slice.maxSteps} steps / ${rec.slice.maxToolCalls} tool calls`);
143
138
  continue;
144
139
  }
145
140
  break;
package/dist/cli/index.js CHANGED
@@ -24,7 +24,8 @@ program
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
26
  .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
- .option('--timeout <duration>', 'print-mode absolute turn deadline (e.g. 30s, 10m, 2h); bounds total elapsed time so a busy tool cannot run indefinitely');
27
+ .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
+ .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');
28
29
  program.addHelpText('after', `
29
30
  Examples:
30
31
  $ haze start the interactive chat
@@ -49,8 +50,9 @@ Print mode (-p):
49
50
  run only (no settings change) and must already be registered under a provider (add it once via
50
51
  the /provider picker). Print-mode runs are non-durable: --continue is ignored and no session is
51
52
  saved. --resume <id> loads saved context for the turn without changing that session. On a
52
- provider context overflow, haze compacts the conversation and retries the request once; when
53
- compaction is unavailable, the error says so explicitly.
53
+ provider context overflow, haze compacts the conversation and retries at a progressively smaller
54
+ message budget (up to twice); exhausted retries pause with a context_exhausted checkpoint, and
55
+ when compaction is unavailable, the error says so explicitly.
54
56
  `);
55
57
  async function readStdinPrompt() {
56
58
  // Only read stdin when it is piped (non-TTY); never hang waiting on an interactive terminal.
@@ -120,6 +122,7 @@ program.action(async () => {
120
122
  output: opts.output === 'json' || opts.output === 'stream-json' ? opts.output : 'text',
121
123
  debug: Boolean(opts.debug),
122
124
  timeout: opts.timeout,
125
+ untilDone: Boolean(opts.untilDone),
123
126
  });
124
127
  // Set the exit code and return instead of process.exit(code): the latter does not wait
125
128
  // for stdout to drain and can truncate piped/redirected output (e.g. `haze -p ... | jq`).
@@ -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
+ }
@@ -6,6 +6,13 @@
6
6
  * Hosted presets carry a pre-configured base URL so users only need to supply an API key
7
7
  * and model names. Local/keyless providers have sensible localhost defaults.
8
8
  *
9
+ * Presets are authored in a compact definition form (`ProviderPresetDefinition`) and
10
+ * expanded once into the public `ProviderPreset` records: each curated model is a single
11
+ * `[id, contextWindowTokens, maxOutputTokens]` tuple instead of appearing twice (once in
12
+ * `suggestedModels`, once in `modelLimits`), and `needsApiKey` is derived from the
13
+ * category (cloud presets need a key unless they carry an explicit OAuth flow; local
14
+ * ones never do).
15
+ *
9
16
  * `modelLimits` values are curated from models.dev (the same catalog pi and nanocoder
10
17
  * consume; refreshed 2026-08-15). They are keyed by the exact suggested model id for
11
18
  * THIS preset: aggregators may cap context below the origin model's capability (e.g.