@denizokcu/haze 0.10.0 → 0.11.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 (169) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +66 -25
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/contextReport.js +2 -0
  9. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  10. package/dist/cli/chat/liveRegion.d.ts +25 -0
  11. package/dist/cli/chat/liveRegion.js +48 -0
  12. package/dist/cli/chat/messages.d.ts +33 -2
  13. package/dist/cli/chat/messages.js +216 -33
  14. package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
  15. package/dist/cli/chat/sessionLifecycle.js +64 -14
  16. package/dist/cli/chat/sessionRecorder.js +75 -7
  17. package/dist/cli/chat/startupInfo.d.ts +0 -1
  18. package/dist/cli/chat/startupInfo.js +11 -15
  19. package/dist/cli/chat/wizardDispatch.js +111 -12
  20. package/dist/cli/commands/chat.d.ts +5 -0
  21. package/dist/cli/commands/chat.js +203 -101
  22. package/dist/cli/commands/commands.d.ts +2 -0
  23. package/dist/cli/commands/commands.js +10 -5
  24. package/dist/cli/commands/doctor.d.ts +19 -0
  25. package/dist/cli/commands/doctor.js +76 -0
  26. package/dist/cli/commands/formatters.js +2 -0
  27. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  28. package/dist/cli/commands/ndjsonSink.js +38 -0
  29. package/dist/cli/commands/providerWizard.d.ts +9 -2
  30. package/dist/cli/commands/providerWizard.js +37 -4
  31. package/dist/cli/commands/runCommand.d.ts +3 -0
  32. package/dist/cli/commands/runCommand.js +117 -11
  33. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  34. package/dist/cli/commands/streaming/abortCause.js +16 -0
  35. package/dist/cli/commands/streaming/assistantText.js +9 -2
  36. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  38. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  39. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  40. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  41. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  42. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
  43. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  44. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  45. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  46. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  47. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  48. package/dist/cli/commands/streaming.d.ts +70 -3
  49. package/dist/cli/commands/streaming.js +491 -77
  50. package/dist/cli/commands/wizardActions.d.ts +1 -0
  51. package/dist/cli/commands/wizardActions.js +1 -0
  52. package/dist/cli/commands/wizardPrompts.js +7 -1
  53. package/dist/cli/commands/wizardSuggestions.js +5 -3
  54. package/dist/cli/index.js +68 -22
  55. package/dist/cli/terminalTitle.js +1 -1
  56. package/dist/config/modelDiscovery.d.ts +51 -0
  57. package/dist/config/modelDiscovery.js +164 -1
  58. package/dist/config/privateStorage.js +28 -2
  59. package/dist/config/providerAuth.d.ts +14 -0
  60. package/dist/config/providerAuth.js +49 -0
  61. package/dist/config/providerPresets.d.ts +39 -7
  62. package/dist/config/providerPresets.js +371 -100
  63. package/dist/config/providers.js +2 -0
  64. package/dist/config/settings.d.ts +36 -0
  65. package/dist/config/settings.js +9 -0
  66. package/dist/core/agent/budgets.d.ts +10 -0
  67. package/dist/core/agent/budgets.js +10 -0
  68. package/dist/core/agent/compaction.d.ts +38 -0
  69. package/dist/core/agent/compaction.js +92 -17
  70. package/dist/core/agent/completionController.d.ts +230 -0
  71. package/dist/core/agent/completionController.js +287 -0
  72. package/dist/core/agent/contextBudget.d.ts +38 -0
  73. package/dist/core/agent/contextBudget.js +60 -7
  74. package/dist/core/agent/events.d.ts +74 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  76. package/dist/core/agent/reasoningPolicy.js +27 -0
  77. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  78. package/dist/core/agent/toolCapabilities.js +58 -0
  79. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  80. package/dist/core/agent/toolExecutionBudget.js +49 -0
  81. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  82. package/dist/core/agent/toolOutputStore.js +10 -10
  83. package/dist/core/agent/toolResults.d.ts +12 -0
  84. package/dist/core/agent/toolResults.js +38 -0
  85. package/dist/core/agent/turnBudget.d.ts +35 -0
  86. package/dist/core/agent/turnBudget.js +27 -0
  87. package/dist/core/agent/turnPolicy.d.ts +11 -0
  88. package/dist/core/agent/turnPolicy.js +19 -0
  89. package/dist/core/agent/workState.d.ts +75 -0
  90. package/dist/core/agent/workState.js +120 -9
  91. package/dist/core/deadline.d.ts +33 -0
  92. package/dist/core/deadline.js +74 -0
  93. package/dist/core/goal/completionPolicy.d.ts +27 -0
  94. package/dist/core/goal/completionPolicy.js +37 -1
  95. package/dist/core/limits/byteBudgets.d.ts +2 -0
  96. package/dist/core/limits/byteBudgets.js +2 -0
  97. package/dist/core/limits/textBudgets.d.ts +2 -0
  98. package/dist/core/limits/textBudgets.js +2 -0
  99. package/dist/core/log/llmLog.js +7 -0
  100. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  101. package/dist/core/persistence/orderedFileWriter.js +16 -2
  102. package/dist/core/process/backgroundRegistry.js +8 -7
  103. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  104. package/dist/core/process/runBoundedProcess.js +15 -6
  105. package/dist/core/safety/missingExecutable.d.ts +42 -0
  106. package/dist/core/safety/missingExecutable.js +77 -0
  107. package/dist/core/session/sessionStore.d.ts +37 -0
  108. package/dist/core/session/sessionStore.js +215 -51
  109. package/dist/core/subagent/contracts.d.ts +4 -0
  110. package/dist/core/subagent/contracts.js +1 -0
  111. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  112. package/dist/core/subagent/subagentCoordinator.js +32 -2
  113. package/dist/core/subagent/subagentRunner.js +17 -37
  114. package/dist/llm/client.d.ts +17 -1
  115. package/dist/llm/client.js +82 -14
  116. package/dist/llm/hazeTools.d.ts +554 -80
  117. package/dist/llm/hazeTools.js +103 -24
  118. package/dist/llm/lsp.d.ts +24 -4
  119. package/dist/llm/lsp.js +72 -11
  120. package/dist/llm/lspTools.d.ts +2366 -0
  121. package/dist/llm/lspTools.js +87 -79
  122. package/dist/llm/openaiCodex.d.ts +3 -0
  123. package/dist/llm/openaiCodex.js +47 -0
  124. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  125. package/dist/llm/openaiCodexOAuth.js +214 -0
  126. package/dist/llm/requestContext.d.ts +3 -0
  127. package/dist/llm/requestContext.js +7 -4
  128. package/dist/llm/systemPrompt.d.ts +11 -0
  129. package/dist/llm/systemPrompt.js +12 -6
  130. package/dist/llm/toolResultTypes.d.ts +8 -1
  131. package/dist/llm/tools/bashTool.d.ts +48 -16
  132. package/dist/llm/tools/bashTool.js +5 -0
  133. package/dist/llm/tools/editMatch.d.ts +14 -0
  134. package/dist/llm/tools/editMatch.js +72 -0
  135. package/dist/llm/tools/failures.d.ts +2 -0
  136. package/dist/llm/tools/failures.js +1 -0
  137. package/dist/llm/tools/fetchTool.d.ts +16 -0
  138. package/dist/llm/tools/fileToolShared.d.ts +4 -3
  139. package/dist/llm/tools/fileToolShared.js +16 -21
  140. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  141. package/dist/llm/tools/gitIgnore.js +129 -0
  142. package/dist/llm/tools/readRecovery.d.ts +10 -0
  143. package/dist/llm/tools/readRecovery.js +135 -0
  144. package/dist/llm/tools/toolContext.d.ts +1 -1
  145. package/dist/llm/tools/toolContext.js +61 -32
  146. package/dist/llm/webFetch.d.ts +17 -0
  147. package/dist/llm/webFetch.js +64 -97
  148. package/dist/ui/codeHighlight.d.ts +4 -0
  149. package/dist/ui/codeHighlight.js +31 -0
  150. package/dist/ui/components/Header.d.ts +1 -1
  151. package/dist/ui/components/MarkdownText.d.ts +16 -2
  152. package/dist/ui/components/MarkdownText.js +244 -34
  153. package/dist/ui/components/TextInput.d.ts +8 -1
  154. package/dist/ui/components/TextInput.js +6 -2
  155. package/dist/ui/theme.d.ts +4 -3
  156. package/dist/ui/theme.js +5 -4
  157. package/dist/utils/buildInfo.d.ts +104 -0
  158. package/dist/utils/buildInfo.js +253 -0
  159. package/dist/utils/fs.d.ts +9 -0
  160. package/dist/utils/fs.js +87 -25
  161. package/dist/utils/openPath.d.ts +2 -2
  162. package/dist/utils/openPath.js +19 -6
  163. package/dist/utils/path.d.ts +2 -0
  164. package/dist/utils/path.js +5 -1
  165. package/dist/utils/utf8.d.ts +22 -0
  166. package/dist/utils/utf8.js +54 -0
  167. package/dist/utils/version.d.ts +9 -3
  168. package/dist/utils/version.js +28 -2
  169. package/package.json +24 -19
@@ -25,7 +25,9 @@ function normalizeProvider(provider, fallbackModel) {
25
25
  name,
26
26
  url,
27
27
  ...(key ? { key } : {}),
28
+ ...(provider.kind ? { kind: provider.kind } : {}),
28
29
  ...(capabilities ? { capabilities } : {}),
30
+ ...(provider.modelLimits ? { modelLimits: provider.modelLimits } : {}),
29
31
  models: normalizeModels(provider.models, fallbackModel),
30
32
  };
31
33
  }
@@ -1,8 +1,18 @@
1
+ import { z } from 'zod';
2
+ /** Optional, explicitly user-controlled reasoning depth (provider/protocol gated). */
3
+ export type ReasoningLevel = 'low' | 'medium' | 'high';
4
+ export declare const reasoningLevelSchema: z.ZodEnum<{
5
+ high: "high";
6
+ medium: "medium";
7
+ low: "low";
8
+ }>;
1
9
  export interface HazeProviderSettings {
2
10
  name: string;
3
11
  url: string;
4
12
  key?: string;
5
13
  models: string[];
14
+ /** Explicit runtime/auth protocol. Omitted means a normal OpenAI-compatible endpoint. */
15
+ kind?: 'openai-compatible' | 'chatgpt-codex';
6
16
  /**
7
17
  * Explicit endpoint capabilities. Never inferred: images are only sent to
8
18
  * providers the user marked image-capable (F03).
@@ -10,6 +20,15 @@ export interface HazeProviderSettings {
10
20
  capabilities?: {
11
21
  images?: boolean;
12
22
  };
23
+ /**
24
+ * Optional per-model capacity metadata used for request budgeting (RH-005).
25
+ * Absent entries fall back to a conservative default window. Preserved as
26
+ * passthrough so unknown metadata is not dropped.
27
+ */
28
+ modelLimits?: Record<string, {
29
+ contextWindowTokens?: number;
30
+ maxOutputTokens?: number;
31
+ }>;
13
32
  }
14
33
  export interface HazeLspServerSettings {
15
34
  name: string;
@@ -58,6 +77,23 @@ export interface HazeSettings {
58
77
  mcpServers?: HazeMcpServer[];
59
78
  skills?: HazeSkillSetting[];
60
79
  subagents?: HazeSubagentSettings;
80
+ /** Optional reasoning depth; unset by default, mapped by supported provider protocol. */
81
+ reasoning?: ReasoningLevel;
82
+ /**
83
+ * Context-window fallback for models without `modelLimits` metadata, in
84
+ * tokens. Unset means the built-in default (128K hosted / 32K local —
85
+ * see `contextBudget.ts`). The local variant applies to localhost inference
86
+ * servers, whose effective window is server-configured and silently truncated.
87
+ */
88
+ contextWindowFallbackTokens?: number;
89
+ localContextWindowFallbackTokens?: number;
90
+ /**
91
+ * Manual `/compact` mode (F-09): `llm-summary` (default) asks the active
92
+ * model to summarize the older history; `heuristic` keeps the bounded
93
+ * excerpt without a model call. Automatic mid-turn compaction is always
94
+ * heuristic.
95
+ */
96
+ manualCompaction?: 'llm-summary' | 'heuristic';
61
97
  /** UI tweaks: rotating tips under the busy label, etc. Default enabled. */
62
98
  tips?: {
63
99
  enabled?: boolean;
@@ -4,6 +4,7 @@ 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
8
  export const SETTINGS_FILE = path.join(HAZE_DIR, 'settings.json');
8
9
  const providerCapabilitiesSchema = z.object({
9
10
  images: z.boolean().optional(),
@@ -13,7 +14,9 @@ const providerSchema = z.object({
13
14
  url: z.string(),
14
15
  key: z.string().optional(),
15
16
  models: z.array(z.string()),
17
+ kind: z.enum(['openai-compatible', 'chatgpt-codex']).optional(),
16
18
  capabilities: providerCapabilitiesSchema.optional(),
19
+ modelLimits: z.record(z.string(), z.object({ contextWindowTokens: z.number().int().positive(), maxOutputTokens: z.number().int().positive() }).partial()).optional(),
17
20
  }).passthrough();
18
21
  const lspServerSchema = z.object({
19
22
  name: z.string(),
@@ -39,6 +42,8 @@ const subagentSettingsSchema = z.object({
39
42
  defaultProfile: z.string().trim().min(1).optional(),
40
43
  profiles: z.record(z.string().min(1), customProfileSchema).optional(),
41
44
  }).passthrough();
45
+ /** Fallback windows must be plausible positive token counts (not fractions/junk). */
46
+ const contextWindowFallbackSchema = z.number().int().min(1_000).max(10_000_000);
42
47
  const settingsSchema = z.object({
43
48
  provider: z.string().optional(),
44
49
  model: z.string().optional(),
@@ -47,6 +52,10 @@ const settingsSchema = z.object({
47
52
  mcpServers: z.array(mcpServerSchema).optional(),
48
53
  skills: z.array(skillSettingSchema).optional(),
49
54
  subagents: subagentSettingsSchema.optional(),
55
+ reasoning: reasoningLevelSchema.optional(),
56
+ contextWindowFallbackTokens: contextWindowFallbackSchema.optional(),
57
+ localContextWindowFallbackTokens: contextWindowFallbackSchema.optional(),
58
+ manualCompaction: z.enum(['llm-summary', 'heuristic']).optional(),
50
59
  tips: z.object({ enabled: z.boolean().optional() }).optional(),
51
60
  apiKey: z.string().optional(),
52
61
  baseURL: z.string().optional(),
@@ -1,5 +1,15 @@
1
1
  export declare const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
2
+ /** Keep generated file payloads comfortably below a model's output-token ceiling. */
3
+ export declare const WRITE_FILE_CHUNK_BYTES: number;
2
4
  export declare const IDLE_TIMEOUT_MS: number;
5
+ /** Default per-tool execution deadline; an uncooperative tool cannot defer the turn indefinitely (RH-004). */
6
+ export declare const DEFAULT_TOOL_DEADLINE_MS: number;
7
+ /** Subagents legitimately run long; give their wrapper a larger deadline. */
8
+ export declare const SUBAGENT_TOOL_DEADLINE_MS: number;
9
+ /** Absolute main-turn deadline: no single turn runs longer than this by default. */
10
+ export declare const DEFAULT_TURN_DEADLINE_MS: number;
11
+ /** Maximum accepted explicit `--timeout` value (24 hours). */
12
+ export declare const MAX_TURN_DEADLINE_MS: number;
3
13
  export declare const MAIN_STEP_LIMIT = 64;
4
14
  export declare const MAIN_TOOL_CALL_LIMIT = 120;
5
15
  export declare const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
@@ -1,5 +1,15 @@
1
1
  export const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
2
+ /** Keep generated file payloads comfortably below a model's output-token ceiling. */
3
+ export const WRITE_FILE_CHUNK_BYTES = 16 * 1024;
2
4
  export const IDLE_TIMEOUT_MS = 5 * 60_000;
5
+ /** Default per-tool execution deadline; an uncooperative tool cannot defer the turn indefinitely (RH-004). */
6
+ export const DEFAULT_TOOL_DEADLINE_MS = 10 * 60_000;
7
+ /** Subagents legitimately run long; give their wrapper a larger deadline. */
8
+ export const SUBAGENT_TOOL_DEADLINE_MS = 20 * 60_000;
9
+ /** Absolute main-turn deadline: no single turn runs longer than this by default. */
10
+ export const DEFAULT_TURN_DEADLINE_MS = 30 * 60_000;
11
+ /** Maximum accepted explicit `--timeout` value (24 hours). */
12
+ export const MAX_TURN_DEADLINE_MS = 24 * 60 * 60_000;
3
13
  export const MAIN_STEP_LIMIT = 64;
4
14
  export const MAIN_TOOL_CALL_LIMIT = 120;
5
15
  export const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
@@ -7,6 +7,21 @@ export interface CompactionResult {
7
7
  keptCount: number;
8
8
  summary?: string;
9
9
  }
10
+ export interface CompactionSplit {
11
+ older: ModelMessage[];
12
+ recent: ModelMessage[];
13
+ }
14
+ /**
15
+ * Decide which trailing messages survive compaction and which are folded into
16
+ * the summary. Returns undefined when there is nothing older to compact (the
17
+ * whole history is recent, or the recent window reaches back past the first
18
+ * message once trailing tool messages are reattached to their calls).
19
+ * Shared by the heuristic and the LLM-summarized paths (F-09).
20
+ */
21
+ export declare function splitForCompaction(messages: ModelMessage[], options?: {
22
+ keepRecentMessages?: number;
23
+ tokenBudget?: number;
24
+ }): CompactionSplit | undefined;
10
25
  export declare function modelMessageText(message: ModelMessage): string;
11
26
  export declare function compactModelMessages(messages: ModelMessage[], options?: {
12
27
  keepRecentMessages?: number;
@@ -14,3 +29,26 @@ export declare function compactModelMessages(messages: ModelMessage[], options?:
14
29
  instructions?: string;
15
30
  workState?: WorkState;
16
31
  }): CompactionResult;
32
+ /**
33
+ * 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.
37
+ */
38
+ export declare function buildLlmCompactionPrompt(input: {
39
+ older: ModelMessage[];
40
+ instructions?: string;
41
+ maxChars?: number;
42
+ }): string;
43
+ /**
44
+ * Assemble the compacted history around a model-written summary (F-09). Same
45
+ * split rules as the heuristic path; the excerpt is replaced by the summary
46
+ * text the model produced.
47
+ */
48
+ export declare function compactModelMessagesWithSummary(messages: ModelMessage[], options: {
49
+ summaryText: string;
50
+ keepRecentMessages?: number;
51
+ tokenBudget?: number;
52
+ instructions?: string;
53
+ workState?: WorkState;
54
+ }): CompactionResult;
@@ -1,38 +1,49 @@
1
- import { estimateValueTokens } from './contextBudget.js';
1
+ import { estimateModelMessageTokens } from './contextBudget.js';
2
2
  import { workStatePrompt } from './workState.js';
3
- import { COMPACTION_OLDER_CHARS } from '../limits/textBudgets.js';
4
- export function modelMessageText(message) {
5
- const content = message.content;
6
- if (typeof content === 'string')
7
- return content;
8
- if (!Array.isArray(content))
9
- return '';
10
- return content.map(part => typeof part === 'object' && part != null && 'text' in part && typeof part.text === 'string' ? part.text : '').filter(Boolean).join('\n');
11
- }
12
- export function compactModelMessages(messages, options = {}) {
3
+ import { COMPACTION_LLM_TRANSCRIPT_CHARS, COMPACTION_OLDER_CHARS } from '../limits/textBudgets.js';
4
+ /**
5
+ * Decide which trailing messages survive compaction and which are folded into
6
+ * the summary. Returns undefined when there is nothing older to compact (the
7
+ * whole history is recent, or the recent window reaches back past the first
8
+ * message once trailing tool messages are reattached to their calls).
9
+ * Shared by the heuristic and the LLM-summarized paths (F-09).
10
+ */
11
+ export function splitForCompaction(messages, options = {}) {
13
12
  const maxRecentMessages = Math.min(options.keepRecentMessages ?? 12, messages.length);
14
13
  let keepRecentMessages = maxRecentMessages;
15
14
  if (options.tokenBudget != null) {
16
15
  let recentTokens = 0;
17
16
  keepRecentMessages = 0;
18
17
  for (let index = messages.length - 1; index >= 0 && keepRecentMessages < maxRecentMessages; index--) {
19
- const tokens = estimateValueTokens(messages[index]);
18
+ const tokens = estimateModelMessageTokens(messages[index]);
20
19
  if (keepRecentMessages > 0 && recentTokens + tokens > options.tokenBudget)
21
20
  break;
22
21
  recentTokens += tokens;
23
22
  keepRecentMessages += 1;
24
23
  }
25
24
  }
26
- if (messages.length <= keepRecentMessages) {
27
- return { compacted: false, messages, olderCount: 0, keptCount: messages.length };
28
- }
25
+ if (messages.length <= keepRecentMessages)
26
+ return undefined;
29
27
  let recentStart = messages.length - keepRecentMessages;
30
28
  while (recentStart > 0 && messages[recentStart]?.role === 'tool')
31
29
  recentStart -= 1;
32
30
  if (recentStart === 0)
31
+ return undefined;
32
+ return { older: messages.slice(0, recentStart), recent: messages.slice(recentStart) };
33
+ }
34
+ export function modelMessageText(message) {
35
+ const content = message.content;
36
+ if (typeof content === 'string')
37
+ return content;
38
+ if (!Array.isArray(content))
39
+ return '';
40
+ return content.map(part => typeof part === 'object' && part != null && 'text' in part && typeof part.text === 'string' ? part.text : '').filter(Boolean).join('\n');
41
+ }
42
+ export function compactModelMessages(messages, options = {}) {
43
+ const split = splitForCompaction(messages, options);
44
+ if (!split)
33
45
  return { compacted: false, messages, olderCount: 0, keptCount: messages.length };
34
- const older = messages.slice(0, recentStart);
35
- const recent = messages.slice(recentStart);
46
+ const { older, recent } = split;
36
47
  const olderEntries = older.map(message => {
37
48
  const text = modelMessageText(message).replace(/\s+/g, ' ').trim();
38
49
  return text ? `- ${message.role}: ${text}` : '';
@@ -68,3 +79,67 @@ export function compactModelMessages(messages, options = {}) {
68
79
  summary,
69
80
  };
70
81
  }
82
+ /**
83
+ * Build the summarization request for the LLM-summarized compaction path
84
+ * (F-09). The transcript is the older half, bounded to a character budget and
85
+ * truncated from the front (the oldest context is the least valuable) so the
86
+ * request itself can never overflow the model.
87
+ */
88
+ export function buildLlmCompactionPrompt(input) {
89
+ const maxChars = input.maxChars ?? COMPACTION_LLM_TRANSCRIPT_CHARS;
90
+ const entries = input.older.map(message => {
91
+ const text = modelMessageText(message).replace(/\s+/g, ' ').trim();
92
+ return text ? `- ${message.role}: ${text}` : '';
93
+ }).filter(Boolean);
94
+ // Keep the most recent entries within the bound; drop whole oldest entries
95
+ // first, then hard-trim whatever single entry still exceeds the budget.
96
+ const kept = [];
97
+ let total = 0;
98
+ for (let index = entries.length - 1; index >= 0; index--) {
99
+ const entry = entries[index];
100
+ if (total + entry.length + 1 > maxChars && kept.length > 0)
101
+ break;
102
+ kept.unshift(entry);
103
+ total += entry.length + 1;
104
+ }
105
+ if (kept.length === 1 && kept[0].length > maxChars)
106
+ kept[0] = `${kept[0].slice(kept[0].length - maxChars)}…`;
107
+ const omitted = entries.length - kept.length;
108
+ return [
109
+ 'Summarize the following older conversation history for continuity. The summary replaces the history in a coding agent context.',
110
+ 'Preserve: current user goal and success condition; explicit user constraints, preferences, and decisions; files created/changed/read; validation commands and their pass/fail results; blockers or pending decisions; the exact next action if work was unfinished.',
111
+ 'Drop: restatements, exploration dead ends that led nowhere, raw tool output detail, and anything the recent messages supersede.',
112
+ input.instructions ? `User compaction instructions: ${input.instructions}` : undefined,
113
+ `Write a dense summary in at most 60 lines. ${omitted > 0 ? `(${omitted} oldest message(s) already omitted from this transcript.)` : ''}`.trim(),
114
+ '',
115
+ '<older_conversation>',
116
+ ...kept,
117
+ '</older_conversation>',
118
+ ].filter((line) => line !== undefined).join('\n');
119
+ }
120
+ /**
121
+ * Assemble the compacted history around a model-written summary (F-09). Same
122
+ * split rules as the heuristic path; the excerpt is replaced by the summary
123
+ * text the model produced.
124
+ */
125
+ export function compactModelMessagesWithSummary(messages, options) {
126
+ const split = splitForCompaction(messages, options);
127
+ if (!split)
128
+ return { compacted: false, messages, olderCount: 0, keptCount: messages.length };
129
+ const summary = [
130
+ 'Compacted prior haze conversation. Treat this as continuity context, not a new user request.',
131
+ 'Do not treat older tool outputs as current unless the recent conversation confirms they still apply.',
132
+ options.instructions ? `User compaction instructions: ${options.instructions}` : undefined,
133
+ options.workState ? workStatePrompt(options.workState) : undefined,
134
+ '',
135
+ 'Model-written summary of the older conversation:',
136
+ options.summaryText.trim(),
137
+ ].filter((line) => line !== undefined).join('\n');
138
+ return {
139
+ compacted: true,
140
+ messages: [{ role: 'user', content: `<haze_compaction>\n${summary}\n</haze_compaction>` }, ...split.recent],
141
+ olderCount: split.older.length,
142
+ keptCount: split.recent.length,
143
+ summary,
144
+ };
145
+ }
@@ -0,0 +1,230 @@
1
+ import type { ValidationKind } from '../../llm/toolResultTypes.js';
2
+ import type { TurnBudget } from './turnBudget.js';
3
+ import { type ValidationOutcome, type WorkTaskProgress } from './workState.js';
4
+ import type { RequestIntent } from '../goal/requestClassifier.js';
5
+ /**
6
+ * Normalized reason a model stream finished. Derived from the AI SDK
7
+ * `finishReason` string so policy code never branches on raw provider strings.
8
+ */
9
+ export type FinishCause = 'stop' | 'length' | 'tool-calls' | 'error' | 'content-filter' | 'unknown';
10
+ export declare function normalizeFinishReason(finishReason: string | undefined): FinishCause;
11
+ /**
12
+ * Turn-wide execution state, accumulated across provider retries and recovery
13
+ * slices. It is the single source of truth for "how much of the global budget
14
+ * has this whole turn consumed" and for completion evidence.
15
+ *
16
+ * Counters are turn-wide (never per-slice): a retry or recovery slice observes
17
+ * prior usage so the global budget cannot be reset or exceeded.
18
+ */
19
+ export interface TurnExecutionState {
20
+ stepsUsed: number;
21
+ toolCallsUsed: number;
22
+ toolOnlyStepsUsed: number;
23
+ finishCause: FinishCause | undefined;
24
+ /** Length-continuation credit (Increment 2). */
25
+ lengthCreditUsed: boolean;
26
+ lengthRecoveriesAttempted: number;
27
+ /** Completion-rescue credit (Increment 2). */
28
+ rescueUsed: boolean;
29
+ /** Observable work evidence (Increment 3). */
30
+ mutationCount: number;
31
+ validationOutcome: ValidationOutcome;
32
+ validationKind: ValidationKind | undefined;
33
+ validationAfterMutation: boolean;
34
+ /** Request intent driving the validation policy (implement/fix/test expect validation). */
35
+ intent: RequestIntent;
36
+ /** Latest current-turn task-list evidence from a successful writeTasks call. */
37
+ taskProgress: WorkTaskProgress | undefined;
38
+ /** Goal-continuation cycles issued this turn (bounded by the global budget + progress guard). */
39
+ goalContinuationsUsed: number;
40
+ /** Work/task evidence signature recorded when the latest goal continuation was issued. */
41
+ goalContinuationProgress: string | undefined;
42
+ /** Whether the single allowed no-progress corrective nudge has been consumed. */
43
+ goalContinuationCorrectiveUsed: boolean;
44
+ budgetBoundary: boolean;
45
+ aborted: boolean;
46
+ }
47
+ export declare function createTurnExecutionState(): TurnExecutionState;
48
+ /**
49
+ * Bounded, safe completion evidence for headless/CI consumers. Contains only
50
+ * enums, booleans, and counts — never raw commands, tool inputs/outputs, or
51
+ * credentials. Additive on top of existing JSON/stream-JSON results.
52
+ */
53
+ export interface TurnCompletionEvidence {
54
+ validationOutcome: ValidationOutcome;
55
+ validationKind?: ValidationKind;
56
+ validationAfterMutation: boolean;
57
+ mutationCount: number;
58
+ /** Current-turn task counts from writeTasks, when a task list was declared. */
59
+ taskProgress?: {
60
+ total: number;
61
+ pending: number;
62
+ inProgress: number;
63
+ completed: number;
64
+ };
65
+ finishCause: FinishCause | undefined;
66
+ recoveryUsed: {
67
+ length: boolean;
68
+ rescue: boolean;
69
+ goal: number;
70
+ };
71
+ budgetBoundary: boolean;
72
+ }
73
+ /** Project the turn-wide state into the safe evidence shape. */
74
+ export declare function toCompletionEvidence(state: TurnExecutionState): TurnCompletionEvidence;
75
+ /** Evidence snapshot the terminal-status decision consumes (decoupled from WorkState). */
76
+ export interface CompletionEvidence {
77
+ sawToolCall: boolean;
78
+ assistantText: string;
79
+ lastToolOk: boolean | undefined;
80
+ unresolvedToolInputError: boolean;
81
+ }
82
+ export type TurnStatus = 'complete' | 'aborted' | 'failed';
83
+ /**
84
+ * Reasoned completion readiness from structured current-turn evidence. A
85
+ * voluntary final is acceptable only when the declared work is actually done;
86
+ * prose alone is never evidence of completion (no semantic judge — task,
87
+ * mutation, validation, tool, and budget evidence is authoritative).
88
+ */
89
+ export type CompletionReadiness = 'ready' | 'pending_tasks' | 'validation_failed' | 'validation_stale' | 'validation_absent_after_mutation' | 'tool_failure' | 'unresolved_tool_input' | 'aborted';
90
+ /** Inputs `assessCompletionReadiness` needs; matches the TurnExecutionState projection. */
91
+ export interface CompletionReadinessInput {
92
+ aborted: boolean;
93
+ intent: RequestIntent;
94
+ mutationCount: number;
95
+ validationOutcome: ValidationOutcome;
96
+ taskProgress: WorkTaskProgress | undefined;
97
+ }
98
+ /**
99
+ * Pure completion-readiness assessment. Priority: abort, unresolved tool
100
+ * input, failed tool, declared task progress, then intent-sensitive validation
101
+ * policy (implement/fix/test turns with successful mutations require fresh
102
+ * passing validation; plan/review/answer turns never do). A task list is
103
+ * enforced only when this turn declared one via a successful writeTasks call.
104
+ */
105
+ export declare function assessCompletionReadiness(state: CompletionReadinessInput, evidence: Pick<CompletionEvidence, 'lastToolOk' | 'unresolvedToolInputError'>): CompletionReadiness;
106
+ /** Human-readable, safe (no commands/content) description of a readiness result. */
107
+ export declare function describeCompletionReadiness(readiness: CompletionReadiness, taskProgress?: WorkTaskProgress): string;
108
+ /**
109
+ * True when the turn-wide budget is exhausted. Expressed against turn-wide
110
+ * counters so a retry or recovery slice observes prior usage and the global
111
+ * budget cannot be reset or exceeded. A `length` finish counts as exhausted
112
+ * for the *terminal* status (the output was truncated); recovery uses
113
+ * `hasRemainingRecoveryBudget` instead, because a length finish often leaves
114
+ * plenty of step/tool budget.
115
+ */
116
+ export declare function isBudgetExhausted(state: Pick<TurnExecutionState, 'stepsUsed' | 'toolCallsUsed' | 'toolOnlyStepsUsed' | 'finishCause'>, budget: TurnBudget): boolean;
117
+ /** Whether step/tool-call resources remain for a recovery slice (length finish excluded). */
118
+ export declare function hasRemainingRecoveryBudget(state: Pick<TurnExecutionState, 'stepsUsed' | 'toolCallsUsed'>, budget: TurnBudget): boolean;
119
+ /**
120
+ * Authoritative terminal turn status. This is the pure, unit-testable core of
121
+ * the old inline `terminalTurnStatus` in the CLI layer; the CLI wrapper still
122
+ * owns the single call site.
123
+ *
124
+ * `budgetExhausted` is supplied by the caller (typically via `isBudgetExhausted`)
125
+ * so this function stays free of budget-wiring details and a turn-wide caller
126
+ * and a per-slice caller can share one decision.
127
+ *
128
+ * Increment 1 reproduces historical behavior exactly: a `length` finish is a
129
+ * failure (length-continuation lands in Increment 2 and only flips on when a
130
+ * recovery credit is both available and warranted).
131
+ */
132
+ export declare function decideTerminalStatus(state: TurnExecutionState, evidence: CompletionEvidence, budgetExhausted: boolean): TurnStatus;
133
+ export type RecoveryAction = 'continue' | 'stop';
134
+ export interface RecoverySlice {
135
+ steps: number;
136
+ toolCalls: number;
137
+ }
138
+ export interface LengthRecoveryDecision {
139
+ action: RecoveryAction;
140
+ reason: string;
141
+ /** Slice size to request when action is 'continue'. */
142
+ slice: RecoverySlice;
143
+ }
144
+ export interface RescueRecoveryDecision {
145
+ action: RecoveryAction;
146
+ reason: string;
147
+ slice: RecoverySlice;
148
+ }
149
+ /** Length-continuation slice cap: four model steps / four tool calls (global). */
150
+ export declare const LENGTH_RECOVERY_SLICE: RecoverySlice;
151
+ /** Completion-rescue slice: one tool-bearing step (≤2 calls) + one synthesis step. */
152
+ export declare const RESCUE_SLICE: RecoverySlice;
153
+ /** Number of trailing tool-only slots reserved for the rescue slice. */
154
+ export declare const RESCUE_RESERVE = 1;
155
+ /** Tool-only boundary at which rescue becomes eligible (normal exploration stops here). */
156
+ export declare const RESCUE_BOUNDARY: number;
157
+ /**
158
+ * Length-continuation decision. Fires once per turn when an output-length finish
159
+ * truncates the response, the turn is not aborted, the credit is unused, the
160
+ * global budget still has room, and the work is not already satisfactorily
161
+ * validated (a fresh passing validation means the artifact landed). A repeated
162
+ * length finish terminates cleanly because the credit is single-use.
163
+ */
164
+ export declare function decideLengthRecovery(state: TurnExecutionState, budget: TurnBudget): LengthRecoveryDecision;
165
+ /**
166
+ * Whether a request intent has a deliverable the rescue slice could apply or
167
+ * validate. Deliberately matches `intentExpectsValidation` so a test-orchestration
168
+ * turn (F-04) gets the same bounded rescue as implement/fix: a `test` finish is
169
+ * driven by tool runs exactly like the intents `decideRescue` already serves.
170
+ */
171
+ export declare function rescueEligibleRequest(intent: RequestIntent): boolean;
172
+ /**
173
+ * Completion-rescue decision near the tool-only boundary. Fires once when normal
174
+ * exploration exhausted the (reserved) tool-only slots without producing a
175
+ * substantive answer, the turn is not aborted, the rescue credit is unused, and
176
+ * the global budget still has room. Rescue never reopens discovery and never
177
+ * extends the global budget.
178
+ */
179
+ export declare function decideRescue(state: TurnExecutionState, evidence: CompletionEvidence, budget: TurnBudget, isMutatingRequest: boolean): RescueRecoveryDecision;
180
+ /** Goal-continuation slice: real per-cycle work headroom, clamped to remaining global budget. */
181
+ export declare const GOAL_CONTINUATION_SLICE: RecoverySlice;
182
+ export interface GoalContinuationDecision {
183
+ action: RecoveryAction;
184
+ reason: string;
185
+ /** Slice size to request when action is 'continue'. */
186
+ slice: RecoverySlice;
187
+ }
188
+ /** Readiness reasons a bounded continuation can plausibly resolve with more work. */
189
+ /** Readiness reasons a bounded continuation can plausibly resolve with more work. */
190
+ export declare function goalContinuationRecoverable(readiness: CompletionReadiness): boolean;
191
+ export declare function isRecoverableFinishCause(finishCause: FinishCause | undefined): boolean;
192
+ /**
193
+ * Terminal classification of a finished attempt against the logical goal.
194
+ * - `goal-complete`: readiness satisfied, substantive answer, clean stop.
195
+ * - `recoverable-incomplete`: structured readiness shows declared work
196
+ * remaining (pending tasks, missing/stale/failed validation after edits)
197
+ * and the finish shape can still be continued — regardless of turn
198
+ * budget. A budget boundary ends a physical turn, not the goal.
199
+ * - `hard-blocked`: concrete tool/input failure, provider error, or a
200
+ * readiness that more work cannot resolve.
201
+ * - `user-aborted`.
202
+ */
203
+ export type TerminalClassification = 'goal-complete' | 'recoverable-incomplete' | 'hard-blocked' | 'user-aborted';
204
+ export declare function classifyTerminalOutcome(state: TurnExecutionState, evidence: CompletionEvidence): TerminalClassification;
205
+ /** Compact signature of measurable work: mutations, validation outcome/kind, task counts. */
206
+ export declare function goalProgressSignature(state: Pick<TurnExecutionState, 'mutationCount' | 'validationOutcome' | 'validationKind' | 'taskProgress'>): string;
207
+ /**
208
+ * Record that a goal-continuation slice was issued. Progress since the previous
209
+ * continuation (work/task signature comparison) decides whether this issuance
210
+ * is the single allowed corrective nudge; a second no-progress stop then
211
+ * terminates as failed (see `decideGoalContinuation`). Never resets counters.
212
+ */
213
+ export declare function recordGoalContinuation(state: TurnExecutionState): void;
214
+ /**
215
+ * Goal-continuation decision for a `recoverable-incomplete` attempt with a
216
+ * substantive answer to reject: continue in-turn with a slice when the global
217
+ * budget and progress guard allow it. Any other outcome is the caller's signal
218
+ * to end the physical turn — the goal-level invariant (failed + recoverable +
219
+ * no same-turn recovery → `incomplete-goal` checkpoint) is enforced by the
220
+ * caller via `classifyTerminalOutcome`, not here. Never resets budgets.
221
+ */
222
+ export declare function decideGoalContinuation(state: TurnExecutionState, evidence: CompletionEvidence, budget: TurnBudget): GoalContinuationDecision;
223
+ /**
224
+ * Does the turn have a satisfactory terminal outcome that should stop recovery?
225
+ * A substantive assistant answer is satisfactory only when the structured
226
+ * completion evidence agrees: declared tasks finished, no unresolved tool
227
+ * failure, and (for validation-bearing intents) fresh validation after edits.
228
+ * Used by recovery guards so a normal successful turn makes no extra model call.
229
+ */
230
+ export declare function hasSatisfactoryTerminalOutcome(state: TurnExecutionState, evidence: CompletionEvidence): boolean;