@denizokcu/haze 0.9.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 (241) hide show
  1. package/CHANGELOG.md +133 -17
  2. package/README.md +164 -68
  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/chatMetrics.d.ts +17 -1
  9. package/dist/cli/chat/chatMetrics.js +22 -5
  10. package/dist/cli/chat/contextReport.d.ts +11 -0
  11. package/dist/cli/chat/contextReport.js +46 -0
  12. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  13. package/dist/cli/chat/fileMentionSuggestions.js +92 -0
  14. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  15. package/dist/cli/chat/inputSuggestions.js +17 -3
  16. package/dist/cli/chat/liveRegion.d.ts +25 -0
  17. package/dist/cli/chat/liveRegion.js +48 -0
  18. package/dist/cli/chat/messages.d.ts +33 -2
  19. package/dist/cli/chat/messages.js +216 -33
  20. package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
  21. package/dist/cli/chat/sessionLifecycle.js +205 -0
  22. package/dist/cli/chat/sessionRecorder.js +80 -14
  23. package/dist/cli/chat/startupInfo.js +11 -4
  24. package/dist/cli/chat/tips.d.ts +21 -0
  25. package/dist/cli/chat/tips.js +43 -0
  26. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  27. package/dist/cli/chat/wizardDispatch.js +744 -0
  28. package/dist/cli/commands/chat.d.ts +6 -0
  29. package/dist/cli/commands/chat.js +373 -790
  30. package/dist/cli/commands/chatModes.d.ts +1 -1
  31. package/dist/cli/commands/chatModes.js +7 -2
  32. package/dist/cli/commands/commandHelp.js +5 -3
  33. package/dist/cli/commands/commands.d.ts +5 -2
  34. package/dist/cli/commands/commands.js +22 -18
  35. package/dist/cli/commands/doctor.d.ts +19 -0
  36. package/dist/cli/commands/doctor.js +76 -0
  37. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  38. package/dist/cli/commands/fleetCommand.js +46 -0
  39. package/dist/cli/commands/formatters.d.ts +5 -0
  40. package/dist/cli/commands/formatters.js +35 -6
  41. package/dist/cli/commands/logsCommand.js +1 -7
  42. package/dist/cli/commands/modelCommand.js +1 -1
  43. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  44. package/dist/cli/commands/ndjsonSink.js +38 -0
  45. package/dist/cli/commands/providerWizard.d.ts +10 -2
  46. package/dist/cli/commands/providerWizard.js +50 -4
  47. package/dist/cli/commands/runCommand.d.ts +4 -0
  48. package/dist/cli/commands/runCommand.js +142 -16
  49. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  50. package/dist/cli/commands/sessionPicker.js +29 -0
  51. package/dist/cli/commands/settingsSummary.js +6 -4
  52. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  53. package/dist/cli/commands/skillWizard.d.ts +2 -0
  54. package/dist/cli/commands/skillWizard.js +16 -6
  55. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  56. package/dist/cli/commands/streaming/abortCause.js +16 -0
  57. package/dist/cli/commands/streaming/assistantText.js +9 -2
  58. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  59. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  61. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  62. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  63. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  64. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  66. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
  68. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  69. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  70. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  71. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  73. package/dist/cli/commands/streaming.d.ts +82 -3
  74. package/dist/cli/commands/streaming.js +528 -91
  75. package/dist/cli/commands/wizardActions.d.ts +7 -0
  76. package/dist/cli/commands/wizardActions.js +7 -0
  77. package/dist/cli/commands/wizardPrompts.js +7 -1
  78. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  79. package/dist/cli/commands/wizardSuggestions.js +64 -14
  80. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  81. package/dist/cli/commands/wizardTransition.js +1 -2
  82. package/dist/cli/index.js +82 -22
  83. package/dist/cli/terminalTitle.d.ts +6 -0
  84. package/dist/cli/terminalTitle.js +36 -0
  85. package/dist/config/inputHistory.d.ts +3 -3
  86. package/dist/config/inputHistory.js +12 -18
  87. package/dist/config/modelDiscovery.d.ts +71 -0
  88. package/dist/config/modelDiscovery.js +214 -0
  89. package/dist/config/privateStorage.js +28 -2
  90. package/dist/config/providerAuth.d.ts +14 -0
  91. package/dist/config/providerAuth.js +49 -0
  92. package/dist/config/providerPresets.d.ts +49 -5
  93. package/dist/config/providerPresets.js +573 -73
  94. package/dist/config/providers.d.ts +2 -0
  95. package/dist/config/providers.js +9 -0
  96. package/dist/config/settings.d.ts +58 -0
  97. package/dist/config/settings.js +38 -1
  98. package/dist/config/skillSettings.d.ts +6 -13
  99. package/dist/config/skillSettings.js +20 -19
  100. package/dist/core/agent/budgets.d.ts +36 -0
  101. package/dist/core/agent/budgets.js +44 -0
  102. package/dist/core/agent/compaction.d.ts +38 -0
  103. package/dist/core/agent/compaction.js +108 -19
  104. package/dist/core/agent/completionController.d.ts +230 -0
  105. package/dist/core/agent/completionController.js +287 -0
  106. package/dist/core/agent/contextBudget.d.ts +46 -0
  107. package/dist/core/agent/contextBudget.js +89 -7
  108. package/dist/core/agent/errors.js +6 -2
  109. package/dist/core/agent/events.d.ts +86 -0
  110. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  111. package/dist/core/agent/reasoningPolicy.js +27 -0
  112. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  113. package/dist/core/agent/toolCapabilities.js +58 -0
  114. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  115. package/dist/core/agent/toolExecutionBudget.js +49 -0
  116. package/dist/core/agent/toolOutputStore.d.ts +13 -0
  117. package/dist/core/agent/toolOutputStore.js +27 -10
  118. package/dist/core/agent/toolResults.d.ts +12 -0
  119. package/dist/core/agent/toolResults.js +38 -0
  120. package/dist/core/agent/turnBudget.d.ts +35 -0
  121. package/dist/core/agent/turnBudget.js +27 -0
  122. package/dist/core/agent/turnPolicy.d.ts +11 -0
  123. package/dist/core/agent/turnPolicy.js +19 -0
  124. package/dist/core/agent/workState.d.ts +76 -1
  125. package/dist/core/agent/workState.js +120 -13
  126. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  127. package/dist/core/attachments/imageAttachments.js +245 -0
  128. package/dist/core/attachments/readBlessings.d.ts +37 -0
  129. package/dist/core/attachments/readBlessings.js +79 -0
  130. package/dist/core/deadline.d.ts +33 -0
  131. package/dist/core/deadline.js +74 -0
  132. package/dist/core/goal/completionPolicy.d.ts +27 -0
  133. package/dist/core/goal/completionPolicy.js +37 -1
  134. package/dist/core/goal/requestClassifier.d.ts +0 -3
  135. package/dist/core/goal/requestClassifier.js +0 -13
  136. package/dist/core/io/boundedRead.js +76 -29
  137. package/dist/core/limits/byteBudgets.d.ts +7 -0
  138. package/dist/core/limits/byteBudgets.js +7 -0
  139. package/dist/core/limits/textBudgets.d.ts +25 -0
  140. package/dist/core/limits/textBudgets.js +25 -0
  141. package/dist/core/log/llmLog.js +7 -0
  142. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  143. package/dist/core/persistence/orderedFileWriter.js +16 -2
  144. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  145. package/dist/core/process/backgroundRegistry.js +195 -0
  146. package/dist/core/process/runBoundedProcess.d.ts +9 -0
  147. package/dist/core/process/runBoundedProcess.js +74 -29
  148. package/dist/core/safety/missingExecutable.d.ts +42 -0
  149. package/dist/core/safety/missingExecutable.js +77 -0
  150. package/dist/core/safety/urlGuard.d.ts +2 -1
  151. package/dist/core/safety/urlGuard.js +3 -2
  152. package/dist/core/session/sessionSlimming.js +47 -4
  153. package/dist/core/session/sessionStore.d.ts +74 -0
  154. package/dist/core/session/sessionStore.js +268 -18
  155. package/dist/core/subagent/contracts.d.ts +120 -0
  156. package/dist/core/subagent/contracts.js +55 -0
  157. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  158. package/dist/core/subagent/executionProfiles.js +45 -0
  159. package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
  160. package/dist/core/subagent/subagentCoordinator.js +164 -0
  161. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  162. package/dist/core/subagent/subagentRunner.js +208 -98
  163. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  164. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  165. package/dist/core/tasks/taskStorage.js +12 -1
  166. package/dist/llm/client.d.ts +36 -29
  167. package/dist/llm/client.js +102 -33
  168. package/dist/llm/hazeTools.d.ts +2559 -150
  169. package/dist/llm/hazeTools.js +119 -31
  170. package/dist/llm/lsp.d.ts +26 -4
  171. package/dist/llm/lsp.js +90 -14
  172. package/dist/llm/lspTools.d.ts +2366 -0
  173. package/dist/llm/lspTools.js +87 -79
  174. package/dist/llm/openaiCodex.d.ts +3 -0
  175. package/dist/llm/openaiCodex.js +47 -0
  176. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  177. package/dist/llm/openaiCodexOAuth.js +214 -0
  178. package/dist/llm/requestContext.d.ts +25 -1
  179. package/dist/llm/requestContext.js +51 -8
  180. package/dist/llm/systemPrompt.d.ts +15 -1
  181. package/dist/llm/systemPrompt.js +24 -8
  182. package/dist/llm/toolResultTypes.d.ts +8 -1
  183. package/dist/llm/tools/bashTool.d.ts +906 -32
  184. package/dist/llm/tools/bashTool.js +30 -4
  185. package/dist/llm/tools/editMatch.d.ts +14 -0
  186. package/dist/llm/tools/editMatch.js +72 -0
  187. package/dist/llm/tools/failures.d.ts +2 -0
  188. package/dist/llm/tools/failures.js +1 -0
  189. package/dist/llm/tools/fetchTool.d.ts +42 -26
  190. package/dist/llm/tools/fetchTool.js +1 -1
  191. package/dist/llm/tools/fileToolShared.d.ts +6 -4
  192. package/dist/llm/tools/fileToolShared.js +18 -23
  193. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  194. package/dist/llm/tools/gitIgnore.js +129 -0
  195. package/dist/llm/tools/grepRunner.d.ts +5 -0
  196. package/dist/llm/tools/grepRunner.js +52 -71
  197. package/dist/llm/tools/outputCap.d.ts +2 -6
  198. package/dist/llm/tools/outputCap.js +2 -6
  199. package/dist/llm/tools/processTool.d.ts +1077 -0
  200. package/dist/llm/tools/processTool.js +41 -0
  201. package/dist/llm/tools/readRecovery.d.ts +10 -0
  202. package/dist/llm/tools/readRecovery.js +135 -0
  203. package/dist/llm/tools/toolContext.d.ts +9 -1
  204. package/dist/llm/tools/toolContext.js +83 -43
  205. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  206. package/dist/llm/tools/workspaceFile.js +33 -4
  207. package/dist/llm/webFetch.d.ts +17 -0
  208. package/dist/llm/webFetch.js +66 -86
  209. package/dist/llm/workerContext.d.ts +18 -0
  210. package/dist/llm/workerContext.js +55 -0
  211. package/dist/skills/SkillLoader.d.ts +2 -2
  212. package/dist/skills/SkillRegistry.d.ts +3 -2
  213. package/dist/skills/SkillRegistry.js +43 -13
  214. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  215. package/dist/skills/builder/SkillBuilder.js +23 -5
  216. package/dist/skills/skillTools.js +11 -4
  217. package/dist/skills/types.d.ts +6 -1
  218. package/dist/ui/codeHighlight.d.ts +4 -0
  219. package/dist/ui/codeHighlight.js +31 -0
  220. package/dist/ui/components/Header.d.ts +1 -1
  221. package/dist/ui/components/MarkdownText.d.ts +16 -2
  222. package/dist/ui/components/MarkdownText.js +244 -34
  223. package/dist/ui/components/TextInput.d.ts +12 -2
  224. package/dist/ui/components/TextInput.js +80 -8
  225. package/dist/ui/theme.d.ts +4 -3
  226. package/dist/ui/theme.js +5 -4
  227. package/dist/utils/buildInfo.d.ts +104 -0
  228. package/dist/utils/buildInfo.js +253 -0
  229. package/dist/utils/format.d.ts +2 -0
  230. package/dist/utils/format.js +8 -0
  231. package/dist/utils/fs.d.ts +9 -1
  232. package/dist/utils/fs.js +87 -29
  233. package/dist/utils/openPath.d.ts +2 -0
  234. package/dist/utils/openPath.js +22 -0
  235. package/dist/utils/path.d.ts +2 -0
  236. package/dist/utils/path.js +5 -1
  237. package/dist/utils/utf8.d.ts +22 -0
  238. package/dist/utils/utf8.js +54 -0
  239. package/dist/utils/version.d.ts +9 -3
  240. package/dist/utils/version.js +28 -2
  241. package/package.json +24 -19
@@ -2,14 +2,42 @@ import { configuredProviders, findProvider, upsertProvider } from '../../config/
2
2
  import { PROVIDER_ACTIONS } from './wizardActions.js';
3
3
  import { commaList } from './wizardInput.js';
4
4
  import { assertCredentialedEndpointSecure } from '../../config/endpointSecurity.js';
5
- export function providerAppendModels(settings, providerName, modelsValue) {
5
+ import { presetModelLimitsForModels } from '../../config/providerPresets.js';
6
+ import { CHATGPT_CODEX_BASE_URL } from '../../llm/openaiCodexOAuth.js';
7
+ /**
8
+ * Warning when a `chatgpt-codex` provider's configured URL diverges from the
9
+ * canonical endpoint (F-14): requests always route to the registered OAuth
10
+ * client's endpoint, so a hand-edited URL (e.g. a proxy) is silently ignored.
11
+ */
12
+ export function chatgptCodexUrlWarning(provider) {
13
+ if (provider.kind !== 'chatgpt-codex' || provider.url === CHATGPT_CODEX_BASE_URL)
14
+ return undefined;
15
+ return `Note: ${provider.name} uses ChatGPT sign-in, which always sends requests to ${CHATGPT_CODEX_BASE_URL}. The configured URL (${provider.url}) is ignored for requests.`;
16
+ }
17
+ /** Merge order for per-model limits on add: preset-curated < live-discovered < existing user settings. */
18
+ function mergedModelLimits(curated, models, discovered, existing) {
19
+ const discoveredSubset = {};
20
+ for (const model of models)
21
+ if (discovered?.[model])
22
+ discoveredSubset[model] = discovered[model];
23
+ const merged = { ...curated, ...discoveredSubset, ...existing };
24
+ return Object.keys(merged).length > 0 ? merged : undefined;
25
+ }
26
+ export function providerAppendModels(settings, providerName, modelsValue, discoveredLimits) {
6
27
  const provider = providerName ? findProvider(settings, providerName) : undefined;
7
28
  const models = commaList(modelsValue);
8
29
  if (!provider)
9
30
  return { message: 'No provider selected.' };
10
31
  if (models.length === 0)
11
32
  return { provider, models, message: 'Enter at least one model name.' };
12
- const nextProvider = { ...provider, models: [...new Set([...provider.models, ...models])] };
33
+ // Preset-curated limits (models.dev) flow into settings so request budgeting
34
+ // uses the real window without the user configuring anything. Live values the
35
+ // provider itself reported in /models discovery win over the static catalog
36
+ // (this is the only source that knows a local server's configured window);
37
+ // existing user-configured keys always win over both.
38
+ const curatedLimits = presetModelLimitsForModels({ name: provider.name, url: provider.url }, models);
39
+ const modelLimits = mergedModelLimits(curatedLimits, models, discoveredLimits, provider.modelLimits);
40
+ const nextProvider = { ...provider, models: [...new Set([...provider.models, ...models])], ...(modelLimits ? { modelLimits } : {}) };
13
41
  return {
14
42
  provider,
15
43
  models,
@@ -17,7 +45,7 @@ export function providerAppendModels(settings, providerName, modelsValue) {
17
45
  message: `Added ${models.length} model${models.length === 1 ? '' : 's'} to ${provider.name}. Choose a model.`,
18
46
  };
19
47
  }
20
- export function providerFinishAdd(settings, draft, modelsValue) {
48
+ export function providerFinishAdd(settings, draft, modelsValue, discoveredLimits) {
21
49
  const models = commaList(modelsValue);
22
50
  if (!draft.name || !draft.url || models.length === 0) {
23
51
  return { models, message: 'Provider name, URL, and at least one model are required.' };
@@ -28,17 +56,22 @@ export function providerFinishAdd(settings, draft, modelsValue) {
28
56
  catch (error) {
29
57
  return { models, message: error instanceof Error ? error.message : String(error) };
30
58
  }
59
+ const curatedLimits = presetModelLimitsForModels({ name: draft.name, url: draft.url }, models);
60
+ const modelLimits = mergedModelLimits(curatedLimits, models, discoveredLimits, undefined);
31
61
  const provider = {
32
62
  name: draft.name,
33
63
  url: draft.url,
34
64
  ...(draft.key ? { key: draft.key } : {}),
65
+ ...(draft.kind ? { kind: draft.kind } : {}),
35
66
  models: [...new Set(models)],
67
+ ...(modelLimits ? { modelLimits } : {}),
36
68
  };
69
+ const divergence = chatgptCodexUrlWarning(provider);
37
70
  return {
38
71
  provider,
39
72
  models,
40
73
  settingsPatch: { providers: upsertProvider(settings, provider), provider: provider.name },
41
- message: `Added provider ${provider.name}. Choose a model.`,
74
+ message: `Added provider ${provider.name}. Choose a model.${divergence ? ` ${divergence}` : ''}`,
42
75
  };
43
76
  }
44
77
  export function providerRemoveModels(settings, providerName, modelsValue) {
@@ -90,6 +123,19 @@ export function providerRemove(settings, providerName) {
90
123
  message: `Removed provider ${provider.name}.${wasActiveProvider ? ' Active provider and model selection cleared.' : ''}`,
91
124
  };
92
125
  }
126
+ export function providerSetImageCapable(settings, providerName, enabled) {
127
+ const provider = providerName ? findProvider(settings, providerName) : undefined;
128
+ if (!provider)
129
+ return { message: 'No provider selected.' };
130
+ const capabilities = { ...(provider.capabilities ?? {}), images: enabled };
131
+ return {
132
+ provider,
133
+ settingsPatch: { providers: upsertProvider(settings, { ...provider, capabilities }) },
134
+ message: enabled
135
+ ? `Provider ${provider.name} marked image-capable. Attached images will be sent to it.`
136
+ : `Provider ${provider.name} is no longer image-capable.`,
137
+ };
138
+ }
93
139
  export function providerSetKey(settings, providerName, value) {
94
140
  const provider = providerName ? findProvider(settings, providerName) : undefined;
95
141
  if (!provider)
@@ -2,8 +2,10 @@ export type HeadlessOutput = 'text' | 'json' | 'stream-json';
2
2
  export interface HeadlessOptions {
3
3
  prompt: string;
4
4
  modelOverride?: string;
5
+ resumeSessionId?: string;
5
6
  output: HeadlessOutput;
6
7
  debug?: boolean;
8
+ timeout?: string;
7
9
  }
8
10
  /** Pinned, documented usage shape emitted in `--output json` (avoids leaking internal estimates). */
9
11
  export interface HeadlessUsage {
@@ -13,4 +15,6 @@ export interface HeadlessUsage {
13
15
  cacheWriteTokens: number;
14
16
  reasoningTokens: number;
15
17
  }
18
+ /** Parse a `--timeout` duration like `30s`, `10m`, `2h`, or raw ms. Throws on invalid input. */
19
+ export declare function parseTurnTimeoutMs(raw: string | undefined): number | undefined;
16
20
  export declare function runHeadless(options: HeadlessOptions): Promise<number>;
@@ -1,13 +1,15 @@
1
1
  import { readContextFiles } from '../../config/contextFiles.js';
2
- import { runAgentTurn } from './streaming.js';
2
+ import { runAgentGoal } from './streaming/goalSupervisor.js';
3
3
  import { EMPTY_TOKEN_USAGE, accumulateTokenUsage } from '../chat/turnState.js';
4
4
  import { readSettings } from '../../config/settings.js';
5
5
  import { activeModel, modelSelector, resolveModelSelector } from '../../config/providers.js';
6
6
  import { createLog, endLog } from '../../core/log/llmLog.js';
7
- function debug(line) {
8
- if (process.env.HAZE_DEBUG)
9
- process.stderr.write(`[haze] ${line}\n`);
10
- }
7
+ import { findSession, restoreSessionState } from '../../core/session/sessionStore.js';
8
+ import { compactModelMessages } from '../../core/agent/compaction.js';
9
+ import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
10
+ import { teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
11
+ import { MAX_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
12
+ import { NdjsonSink } from './ndjsonSink.js';
11
13
  function pinnedUsage(usage) {
12
14
  // Normalize every field to a number: TokenUsage seeds most fields to 0 but
13
15
  // inputTokens/outputTokens may be undefined until the first report. A uniform ?? 0
@@ -20,35 +22,84 @@ function pinnedUsage(usage) {
20
22
  reasoningTokens: usage.reasoningTokens ?? 0,
21
23
  };
22
24
  }
25
+ /** Parse a `--timeout` duration like `30s`, `10m`, `2h`, or raw ms. Throws on invalid input. */
26
+ export function parseTurnTimeoutMs(raw) {
27
+ if (raw === undefined || raw.trim() === '')
28
+ return undefined;
29
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(raw.trim());
30
+ if (!match)
31
+ throw new Error(`Invalid --timeout '${raw}'. Use a number with optional ms/s/m/h units (e.g. 30s, 10m, 2h).`);
32
+ const value = Number(match[1]);
33
+ const unit = match[2] ?? 'ms';
34
+ const multiplier = unit === 'ms' ? 1 : unit === 's' ? 1000 : unit === 'm' ? 60_000 : 3_600_000;
35
+ const ms = Math.round(value * multiplier);
36
+ if (ms < 1000)
37
+ throw new Error(`--timeout must be at least 1 second (got ${ms}ms).`);
38
+ if (ms > MAX_TURN_DEADLINE_MS)
39
+ throw new Error(`--timeout must be at most 24 hours (got ${ms}ms).`);
40
+ return ms;
41
+ }
23
42
  function errorText(error) {
24
- return error instanceof Error ? error.message : String(error);
43
+ const value = error instanceof Error ? error.message : String(error);
44
+ const normalized = value.replace(/\p{Cc}+/gu, ' ').replace(/\s+/g, ' ').trim();
45
+ return normalized.length <= 500 ? normalized : `${normalized.slice(0, 499)}…`;
25
46
  }
26
47
  function toHeadlessStreamEvent(event) {
27
48
  switch (event.type) {
28
49
  case 'turn_start':
29
50
  return { type: 'turn_start', request: event.request, at: event.at };
30
51
  case 'turn_end':
31
- return { type: 'turn_end', request: event.request, status: event.status, at: event.at };
52
+ return { ...(event.evidence ? { evidence: event.evidence } : {}), type: 'turn_end', request: event.request, status: event.status, at: event.at };
53
+ case 'goal_start':
54
+ return { type: 'goal_start', goalId: event.goalId, request: event.request, at: event.at };
55
+ case 'goal_continue':
56
+ return { type: 'goal_continue', goalId: event.goalId, cycle: event.cycle, reason: event.reason, at: event.at };
57
+ case 'goal_end':
58
+ return { ...(event.stopReason ? { stopReason: event.stopReason } : {}), ...(event.evidence ? { evidence: event.evidence } : {}), type: 'goal_end', goalId: event.goalId, status: event.status, cycles: event.cycles, at: event.at };
59
+ case 'step_start':
60
+ return { type: 'step_start', attempt: event.attempt, step: event.step, at: event.at };
61
+ case 'step_end':
62
+ return { type: 'step_end', attempt: event.attempt, step: event.step, finishReason: event.finishReason, toolCallCount: event.toolCallCount, usage: event.usage, at: event.at };
32
63
  case 'message_start':
33
64
  return { type: 'message_start', id: event.id, role: event.role, at: event.at };
34
65
  case 'message_update':
35
- return { type: 'message_update', id: event.id, text: event.text, at: event.at };
66
+ // Handled directly in emitStreamEvent with delta tracking; this case is
67
+ // unreachable but kept for type exhaustiveness.
68
+ return undefined;
36
69
  case 'message_end':
37
70
  return { ...(event.hidden === undefined ? {} : { hidden: event.hidden }), type: 'message_end', id: event.id, text: event.text, at: event.at };
38
71
  case 'tool_start':
39
72
  // Intentionally omit raw tool input: stdout is often persisted by harnesses/CI.
40
73
  return { type: 'tool_start', id: event.id, name: event.name, at: event.at };
41
74
  case 'tool_end':
42
- return { type: 'tool_end', id: event.id, name: event.name, success: event.success, durationMs: event.durationMs, ...(event.error === undefined ? {} : { error: errorText(event.error) }), at: event.at };
75
+ return { type: 'tool_end', id: event.id, name: event.name, success: event.success, durationMs: event.durationMs, ...(event.errorCode === undefined ? {} : { errorCode: event.errorCode }), ...(event.error === undefined ? {} : { error: errorText(event.error) }), at: event.at };
43
76
  case 'retry':
44
77
  return { type: 'retry', attempt: event.attempt, maxAttempts: event.maxAttempts, delayMs: event.delayMs, error: event.error, at: event.at };
45
78
  case 'context_overflow':
46
79
  return { type: 'context_overflow', recovered: event.recovered, error: event.error, at: event.at };
80
+ case 'timeout':
81
+ return { type: 'timeout', phase: event.phase, timeoutMs: event.timeoutMs, at: event.at };
82
+ case 'reasoning_policy':
83
+ return { ...(event.requested ? { requested: event.requested } : {}), type: 'reasoning_policy', effective: event.effective, reason: event.reason, at: event.at };
84
+ case 'context_budget':
85
+ return { type: 'context_budget', contextWindowTokens: event.contextWindowTokens, source: event.source, at: event.at };
47
86
  }
48
87
  }
49
88
  function writeNdjson(value) {
50
89
  process.stdout.write(`${JSON.stringify(value)}\n`);
51
90
  }
91
+ /** Apply a cumulative-text message_update as a delta against the last emitted text for the segment. */
92
+ function messageUpdateDelta(event, emitted) {
93
+ const prev = emitted.get(event.id) ?? '';
94
+ // Delta from the last emitted text. If display sanitization reset the suffix,
95
+ // re-emit from offset 0 so consumers can reconstruct the exact final text.
96
+ const delta = event.text.startsWith(prev) ? event.text.slice(prev.length) : event.text;
97
+ const offset = event.text.startsWith(prev) ? prev.length : 0;
98
+ emitted.set(event.id, event.text);
99
+ if (delta.length === 0)
100
+ return undefined;
101
+ return { type: 'message_update', id: event.id, delta, offset, at: event.at };
102
+ }
52
103
  /**
53
104
  * Resolve the model the run will use *before* invoking the agent, so a bad `--model`
54
105
  * selector or a missing provider produces a precise error (not the generic no-provider
@@ -73,14 +124,38 @@ async function resolveModelOrError(modelOverride) {
73
124
  return undefined;
74
125
  }
75
126
  export async function runHeadless(options) {
127
+ let turnDeadlineMs;
128
+ try {
129
+ turnDeadlineMs = parseTurnTimeoutMs(options.timeout);
130
+ }
131
+ catch (error) {
132
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
133
+ return 2;
134
+ }
135
+ const resumed = options.resumeSessionId ? await findSession(options.resumeSessionId) : undefined;
136
+ if (options.resumeSessionId && !resumed) {
137
+ process.stderr.write(`No session named ${options.resumeSessionId} exists for this workspace.\n`);
138
+ return 1;
139
+ }
76
140
  const modelError = await resolveModelOrError(options.modelOverride);
77
141
  if (modelError) {
78
142
  process.stderr.write(`${modelError}\n`);
79
143
  return 1;
80
144
  }
145
+ // stderr keeps stdout clean for --output json/stream-json consumers.
146
+ const debugLog = (line) => {
147
+ if (options.debug)
148
+ process.stderr.write(`[haze] ${line}\n`);
149
+ };
81
150
  const contextFiles = await readContextFiles(process.cwd());
82
151
  const session = { start: new Date(), cwd: process.cwd() };
83
152
  let conversation = [];
153
+ if (resumed) {
154
+ const restored = await restoreSessionState(resumed);
155
+ conversation = restored.messages;
156
+ for (const error of restored.parseErrors)
157
+ process.stderr.write(`Session parse error: ${error}\n`);
158
+ }
84
159
  // Assistant text is delivered in two stages by runAgentTurn: an initial streaming
85
160
  // `addMessage`, then a finalizing `updateMessage` with the complete text. We key
86
161
  // segments by id and patch them on update so finalized (and multi-segment) text is captured.
@@ -90,11 +165,23 @@ export async function runHeadless(options) {
90
165
  let log;
91
166
  if (options.debug)
92
167
  log = await createLog();
93
- const emitStreamEvent = options.output === 'stream-json'
168
+ const streamSink = options.output === 'stream-json' ? new NdjsonSink(process.stdout) : undefined;
169
+ // Last cumulative text emitted per segment, used to derive deltas (RH-006) so
170
+ // the total stream-json update payload is linear in the final text size.
171
+ const emittedSegmentText = new Map();
172
+ const emitStreamEvent = options.output === 'stream-json' && streamSink
94
173
  ? (event) => {
174
+ if (event.type === 'message_update') {
175
+ const delta = messageUpdateDelta(event, emittedSegmentText);
176
+ if (delta)
177
+ void streamSink.write(delta);
178
+ return;
179
+ }
180
+ if (event.type === 'message_end')
181
+ emittedSegmentText.delete(event.id);
95
182
  const headlessEvent = toHeadlessStreamEvent(event);
96
183
  if (headlessEvent)
97
- writeNdjson(headlessEvent);
184
+ void streamSink.write(headlessEvent);
98
185
  }
99
186
  : undefined;
100
187
  const callbacks = {
@@ -116,7 +203,7 @@ export async function runHeadless(options) {
116
203
  },
117
204
  setBusy: () => undefined,
118
205
  setBusyLabel: () => undefined,
119
- debugLog: debug,
206
+ debugLog,
120
207
  getConversation: () => conversation,
121
208
  getLastAssistantText: () => lastAssistantText,
122
209
  setLastAssistantText: (text) => {
@@ -125,14 +212,39 @@ export async function runHeadless(options) {
125
212
  recordTokenUsage: (u) => {
126
213
  usage = accumulateTokenUsage(usage, u);
127
214
  },
215
+ compactConversation: (instructions) => {
216
+ // Headless context-overflow recovery (F-10): compact the in-scope
217
+ // conversation exactly like the interactive fallback path so a long CI
218
+ // run self-heals instead of dying on the first provider overflow.
219
+ const result = compactModelMessages(conversation, { instructions, tokenBudget: FALLBACK_CONTEXT_WINDOW_TOKENS });
220
+ if (!result.compacted)
221
+ return false;
222
+ conversation = result.messages;
223
+ return true;
224
+ },
128
225
  onEvent: emitStreamEvent,
129
226
  log,
130
227
  };
131
228
  let status;
132
229
  let result;
230
+ let evidence;
231
+ let goal;
133
232
  let persistenceError;
233
+ let backgroundTeardownError;
134
234
  try {
135
- ({ status } = await runAgentTurn(options.prompt, options.prompt, contextFiles, callbacks, 0, false, false, session, options.modelOverride));
235
+ // The logical-goal supervisor owns the whole request: `--timeout` bounds
236
+ // the entire goal, and per-turn budgets merely end physical turns that
237
+ // continue automatically while recoverable work and progress remain.
238
+ const goalResult = await runAgentGoal({ request: options.prompt, displayValue: options.prompt, contextFiles, callbacks, session, modelOverride: options.modelOverride, ...(turnDeadlineMs != null ? { goalDeadlineMs: turnDeadlineMs } : {}) });
239
+ status = goalResult.status;
240
+ evidence = goalResult.evidence;
241
+ goal = {
242
+ cycles: goalResult.cycles,
243
+ stopReason: goalResult.stopReason,
244
+ mutations: goalResult.evidence?.mutationCount ?? 0,
245
+ ...(goalResult.evidence && goalResult.evidence.validationOutcome !== 'not_applicable' ? { validationOutcome: goalResult.evidence.validationOutcome } : {}),
246
+ ...(goalResult.evidence?.taskProgress ? { taskProgress: goalResult.evidence.taskProgress } : {}),
247
+ };
136
248
  result = segments.filter((s) => !s.hidden && s.text).map((s) => s.text).join('\n');
137
249
  }
138
250
  catch (error) {
@@ -140,17 +252,31 @@ export async function runHeadless(options) {
140
252
  result = error instanceof Error ? error.message : String(error);
141
253
  }
142
254
  finally {
255
+ await teardownBackgroundProcesses().catch(error => {
256
+ backgroundTeardownError = error instanceof Error ? error.message : String(error);
257
+ });
143
258
  if (log)
144
259
  await endLog(log).catch(error => {
145
260
  persistenceError = error instanceof Error ? error.message : String(error);
146
261
  });
147
262
  }
263
+ if (backgroundTeardownError)
264
+ process.stderr.write(`haze background teardown warning: ${backgroundTeardownError}\n`);
148
265
  if (persistenceError)
149
266
  process.stderr.write(`haze persistence warning: ${persistenceError}\n`);
150
267
  if (options.output === 'json' || options.output === 'stream-json') {
151
- // For stream-json the authoritative agent events have already streamed above; this is the terminal line.
152
- // It is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
153
- writeNdjson({ type: 'result', status, result, usage: pinnedUsage(usage) });
268
+ // For stream-json the authoritative agent events have already streamed; flush
269
+ // them before the terminal result so ordering is preserved under backpressure.
270
+ if (streamSink)
271
+ await streamSink.flush().catch(() => undefined);
272
+ // This terminal line is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
273
+ const resultLine = { type: 'result', status, result, usage: pinnedUsage(usage), ...(evidence ? { evidence } : {}), ...(goal ? { goal } : {}) };
274
+ if (streamSink)
275
+ await streamSink.write(resultLine).catch(() => undefined);
276
+ else
277
+ writeNdjson(resultLine);
278
+ if (streamSink)
279
+ await streamSink.flush().catch(() => undefined);
154
280
  }
155
281
  else if (status === 'complete') {
156
282
  process.stdout.write(result + (result.endsWith('\n') ? '' : '\n'));
@@ -0,0 +1,9 @@
1
+ import type { SessionSummary } from '../../core/session/sessionStore.js';
2
+ import type { TextInputSuggestion } from '../../ui/components/TextInput.js';
3
+ export declare const MAX_SESSION_PICKER_RESULTS = 20;
4
+ export declare const SESSION_ACTIONS: {
5
+ readonly resume: "resume";
6
+ readonly fork: "fork";
7
+ };
8
+ export declare function sessionSuggestions(sessions: SessionSummary[]): TextInputSuggestion[];
9
+ export declare function sessionActionSuggestions(): TextInputSuggestion[];
@@ -0,0 +1,29 @@
1
+ export const MAX_SESSION_PICKER_RESULTS = 20;
2
+ export const SESSION_ACTIONS = { resume: 'resume', fork: 'fork' };
3
+ function formatDate(value) {
4
+ const date = new Date(value);
5
+ if (Number.isNaN(date.getTime()))
6
+ return value;
7
+ const pad = (part) => String(part).padStart(2, '0');
8
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
9
+ }
10
+ function formatBytes(bytes) {
11
+ if (bytes < 1024)
12
+ return `${bytes} B`;
13
+ if (bytes < 1024 * 1024)
14
+ return `${Math.ceil(bytes / 1024)} KB`;
15
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
16
+ }
17
+ export function sessionSuggestions(sessions) {
18
+ return sessions.slice(0, MAX_SESSION_PICKER_RESULTS).map(session => ({
19
+ value: session.id,
20
+ description: `${formatDate(session.lastActivityAt)} · ${session.messageCount} msg${session.messageCount === 1 ? '' : 's'} · ${formatBytes(session.sizeBytes)}${session.lastStatus ? ` · ${session.lastStatus}` : ''}${session.parseErrors.length ? ' · ⚠ malformed lines' : ''}${session.firstUserPreview ? ` · “${session.firstUserPreview}”` : ''}`,
21
+ kind: 'session',
22
+ }));
23
+ }
24
+ export function sessionActionSuggestions() {
25
+ return [
26
+ { value: SESSION_ACTIONS.resume, description: 'Resume this session', kind: 'session' },
27
+ { value: SESSION_ACTIONS.fork, description: 'Start a new session from its latest snapshot', kind: 'session' },
28
+ ];
29
+ }
@@ -1,7 +1,7 @@
1
1
  import { contextFileDiagnostics, summarizeContextDiagnostics } from '../../config/contextFiles.js';
2
2
  import { configuredLspServers } from '../../config/lspSettings.js';
3
3
  import { configuredMcpServers } from '../../config/mcpSettings.js';
4
- import { activeProvider as resolveActiveProvider, configuredProviders, providerHasKey } from '../../config/providers.js';
4
+ import { activeProvider as resolveActiveProvider, configuredProviders, providerHasKey, providerImageCapable } from '../../config/providers.js';
5
5
  import { isSkillEnabled } from '../../config/skillSettings.js';
6
6
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
7
7
  export async function formatSettingsSummary(settings, contextFiles) {
@@ -22,19 +22,21 @@ export async function formatSettingsSummary(settings, contextFiles) {
22
22
  }
23
23
  const lspServers = configuredLspServers(settings);
24
24
  const skillRegistry = await loadSkillRegistry();
25
- const installedSkills = [...skillRegistry.skills.values()];
26
- const skillNames = installedSkills.map(skill => `${skill.name}${isSkillEnabled(settings, skill.name) ? '' : ' (disabled)'}`).join(', ');
25
+ const installedSkills = skillRegistry.candidates ?? [...skillRegistry.skills.values()];
26
+ const skillNames = installedSkills.map(skill => `${skill.name}${isSkillEnabled(settings, skill.name, skill.source) ? '' : ' (disabled)'} · ${skill.source}`).join(', ');
27
+ const projectSkillNames = installedSkills.filter(skill => skill.source === 'project').map(skill => skill.name).join(', ');
27
28
  const lines = [
28
29
  `Provider: ${activeProvider?.name ?? 'not configured'}`,
29
30
  `Model: ${settings.model ?? 'not set'}`,
30
31
  `Base URL: ${activeProvider?.url ?? settings.baseURL ?? 'not configured'}`,
31
32
  `API key: ${activeProvider && providerHasKey(settings, activeProvider) ? 'saved' : 'missing'}`,
32
- `Configured providers: ${providers.map(provider => provider.name).join(', ') || 'none'}`,
33
+ `Configured providers: ${providers.map(provider => `${provider.name}${providerImageCapable(provider) ? ' (images)' : ''}`).join(', ') || 'none'}`,
33
34
  `LSP servers: ${lspServers.map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
34
35
  `MCP servers: ${configuredMcpServers(settings).map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
35
36
  `Skills: ${skillNames || 'none'}`,
36
37
  ...(skillRegistry.errors.length ? [`Skill load errors: ${skillRegistry.errors.map(error => `${error.directory}: ${error.message}`).join('; ')}`] : []),
37
38
  `Context files: ${contextFiles.length ? `${contextFiles.map(file => file.path).join(', ')} (~${contextTokens} tokens)` : 'none'}`,
39
+ `Project skills (repo context): ${projectSkillNames || 'none'}`,
38
40
  ];
39
41
  if (notes.length > 0)
40
42
  lines.push(`Context note: ${notes.join('; ')}`);
@@ -1,11 +1,12 @@
1
1
  import { removeSkillSetting } from '../../config/skillSettings.js';
2
2
  import { isYesConfirmation } from './wizardInput.js';
3
+ import { findSelectedSkill } from './skillWizard.js';
3
4
  export function skillConfirmRemoveResult(settings, skills, selectedName, value) {
4
5
  if (!selectedName)
5
6
  return { mode: 'chat' };
6
7
  if (!isYesConfirmation(value))
7
8
  return { mode: 'chat', selectedName: undefined, message: 'Cancelled. Skill not removed.' };
8
- const skill = skills.find(candidate => candidate.name === selectedName);
9
+ const skill = findSelectedSkill(skills, selectedName);
9
10
  if (!skill)
10
11
  return { mode: 'chat', selectedName: undefined, message: `Skill ${selectedName} not found.` };
11
12
  return {
@@ -13,7 +14,7 @@ export function skillConfirmRemoveResult(settings, skills, selectedName, value)
13
14
  selectedName: undefined,
14
15
  skill,
15
16
  removedDir: skill.dir,
16
- settingsPatch: { skills: removeSkillSetting(settings, selectedName) },
17
- message: `Removed skill ${selectedName}.`,
17
+ settingsPatch: { skills: removeSkillSetting(settings, skill.name, skill.source) },
18
+ message: skill.source === 'global' ? `Removed skill ${skill.name}.` : `Removed project skill ${skill.name}.`,
18
19
  };
19
20
  }
@@ -7,6 +7,8 @@ export type SkillWizardResult = {
7
7
  settingsPatch?: Partial<HazeSettings>;
8
8
  clearDraft?: boolean;
9
9
  };
10
+ export declare function skillPickerValue(skill: LoadedSkill): string;
11
+ export declare function findSelectedSkill(skills: LoadedSkill[], selection: string | undefined): LoadedSkill | undefined;
10
12
  export declare function selectSkillResult(skills: LoadedSkill[], name: string): SkillWizardResult;
11
13
  export declare function skillInfoMessage(settings: HazeSettings, skill: LoadedSkill): string;
12
14
  export declare function selectSkillActionResult(settings: HazeSettings, skills: LoadedSkill[], selectedName: string | undefined, action: string): SkillWizardResult & {
@@ -1,38 +1,48 @@
1
1
  import { isSkillEnabled, setSkillEnabled } from '../../config/skillSettings.js';
2
2
  import { COMMON_ACTIONS, SKILL_ACTIONS, SKILL_CHOICES } from './wizardActions.js';
3
+ export function skillPickerValue(skill) {
4
+ return `${skill.name} · ${skill.source}`;
5
+ }
6
+ export function findSelectedSkill(skills, selection) {
7
+ if (!selection)
8
+ return undefined;
9
+ return skills.find(skill => skillPickerValue(skill) === selection)
10
+ ?? skills.find(skill => skill.name === selection);
11
+ }
3
12
  export function selectSkillResult(skills, name) {
4
13
  if (name === SKILL_CHOICES.addSkill)
5
14
  return { mode: 'skillsAddName', clearDraft: true, message: 'Name the skill (kebab-case, e.g. security-review). ESC cancels.' };
6
- const skill = skills.find(candidate => candidate.name === name);
15
+ const skill = findSelectedSkill(skills, name);
7
16
  if (!skill)
8
17
  return { mode: 'chat', message: `No skill named ${name}. Use /skills and choose add skill.` };
9
- return { mode: 'skillsAction', selectedName: skill.name, message: `${skill.name}: choose an action.` };
18
+ return { mode: 'skillsAction', selectedName: name === skill.name ? skill.name : skillPickerValue(skill), message: `${skill.name} · ${skill.source}: choose an action.` };
10
19
  }
11
20
  export function skillInfoMessage(settings, skill) {
12
21
  return [
13
22
  `${skill.name}`,
14
23
  skill.description,
15
24
  '',
25
+ `Source: ${skill.source}`,
16
26
  `References: ${skill.references.length}`,
17
27
  `Path: ${skill.dir}`,
18
- `State: ${isSkillEnabled(settings, skill.name) ? 'enabled' : 'disabled'}`,
28
+ `State: ${isSkillEnabled(settings, skill.name, skill.source) ? 'enabled' : 'disabled'}`,
19
29
  ].join('\n');
20
30
  }
21
31
  export function selectSkillActionResult(settings, skills, selectedName, action) {
22
32
  if (!selectedName)
23
33
  return { mode: 'skills' };
24
- const skill = skills.find(candidate => candidate.name === selectedName);
34
+ const skill = findSelectedSkill(skills, selectedName);
25
35
  if (!skill)
26
36
  return { mode: 'chat', selectedName: undefined, message: `Skill ${selectedName} not found.` };
27
37
  if (action === COMMON_ACTIONS.enable || action === COMMON_ACTIONS.disable) {
28
38
  const enabled = action === COMMON_ACTIONS.enable;
29
- return { mode: 'chat', selectedName: undefined, settingsPatch: { skills: setSkillEnabled(settings, selectedName, enabled) }, message: `Skill ${selectedName} ${enabled ? 'enabled' : 'disabled'}.`, skill };
39
+ return { mode: 'chat', selectedName: undefined, settingsPatch: { skills: setSkillEnabled(settings, skill.name, enabled, skill.source) }, message: `Skill ${skill.name} (${skill.source}) ${enabled ? 'enabled' : 'disabled'}.`, skill };
30
40
  }
31
41
  if (action === SKILL_ACTIONS.showInfo)
32
42
  return { message: skillInfoMessage(settings, skill), skill };
33
43
  if (action === SKILL_ACTIONS.validate)
34
44
  return { validate: true, skill };
35
45
  if (action === SKILL_ACTIONS.removeSkill)
36
- return { mode: 'skillsConfirmRemove', message: `Remove skill ${selectedName}? This deletes ~/.haze/skills/${selectedName}. Type "yes" to confirm. Esc to cancel.`, skill };
46
+ return { mode: 'skillsConfirmRemove', message: `Remove ${skill.source} skill ${skill.name}? This deletes ${skill.dir}. Type "yes" to confirm. Esc to cancel.`, skill };
37
47
  return { message: `Unknown skill action: ${action}`, skill };
38
48
  }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Why a turn's AbortController fired.
3
+ *
4
+ * One controller is shared by three abort sites: the model-stream idle timer,
5
+ * the absolute turn deadline (both in this subtree), and the user's cancel
6
+ * action (chat.tsx aborts the controller it holds). All three land in the same
7
+ * catch block in `runAgentAttempt`, so the *cause* is tracked in a per-turn
8
+ * mutable holder set by whichever internal site aborts first. A user abort
9
+ * never sets it and therefore stays `'user'` (the default).
10
+ */
11
+ export type TurnAbortCauseKind = 'user' | 'turn-deadline' | 'model-stream-idle';
12
+ export interface TurnAbortCause {
13
+ kind: TurnAbortCauseKind;
14
+ /** Window of the timer that fired (idle window or turn deadline), for messages and diagnostics. */
15
+ timeoutMs?: number;
16
+ }
17
+ /** Fresh per-turn cause tracker. An unset cause means the user aborted. */
18
+ export declare function createUserAbortCause(): TurnAbortCause;
19
+ /**
20
+ * Record `next` as the abort cause and abort `controller`. First aborter wins:
21
+ * a no-op once the controller already aborted, so a user Esc raced against an
22
+ * idle timeout keeps whichever cause actually fired first.
23
+ */
24
+ export declare function abortForTurn(cause: TurnAbortCause, next: TurnAbortCause, controller: AbortController, reason: string): void;
@@ -0,0 +1,16 @@
1
+ /** Fresh per-turn cause tracker. An unset cause means the user aborted. */
2
+ export function createUserAbortCause() {
3
+ return { kind: 'user' };
4
+ }
5
+ /**
6
+ * Record `next` as the abort cause and abort `controller`. First aborter wins:
7
+ * a no-op once the controller already aborted, so a user Esc raced against an
8
+ * idle timeout keeps whichever cause actually fired first.
9
+ */
10
+ export function abortForTurn(cause, next, controller, reason) {
11
+ if (controller.signal.aborted)
12
+ return;
13
+ cause.kind = next.kind;
14
+ cause.timeoutMs = next.timeoutMs;
15
+ controller.abort(reason);
16
+ }
@@ -64,8 +64,15 @@ function isLikelyUnfinishedMarkdownFragment(text) {
64
64
  const trimmed = text.trim();
65
65
  if (!trimmed.includes('\n'))
66
66
  return false;
67
- const last = trimmed.at(-1) ?? '';
68
- return last === '-' || last === '*' || last === '#' || last === '`' || last === '>';
67
+ // A dangling structural marker alone on the last line ("- ", "#", ">") means
68
+ // the model just opened a list/heading/blockquote and is about to continue.
69
+ const lastLine = trimmed.split('\n').pop()?.trim() ?? '';
70
+ if (lastLine.length === 1 && '-*#>'.includes(lastLine))
71
+ return true;
72
+ // An odd number of fence-open lines means a code block was opened but never
73
+ // closed. An even count (including a trailing closing fence) is balanced.
74
+ const fenceCount = (trimmed.match(/^`{3,}/gm) ?? []).length;
75
+ return fenceCount % 2 === 1;
69
76
  }
70
77
  // Procedural pre-tool lead-ins (e.g. "Confirmed:", "Files written.", "Now let me",
71
78
  // "I checked the tests.") are short preambles the model emits before calling a tool; they