@denizokcu/haze 0.9.0 → 0.10.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 (158) hide show
  1. package/CHANGELOG.md +57 -17
  2. package/README.md +119 -64
  3. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  4. package/dist/cli/chat/chatMetrics.js +22 -5
  5. package/dist/cli/chat/contextReport.d.ts +11 -0
  6. package/dist/cli/chat/contextReport.js +44 -0
  7. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  8. package/dist/cli/chat/fileMentionSuggestions.js +91 -0
  9. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  10. package/dist/cli/chat/inputSuggestions.js +17 -3
  11. package/dist/cli/chat/sessionLifecycle.d.ts +58 -0
  12. package/dist/cli/chat/sessionLifecycle.js +155 -0
  13. package/dist/cli/chat/sessionRecorder.js +7 -9
  14. package/dist/cli/chat/startupInfo.d.ts +1 -0
  15. package/dist/cli/chat/startupInfo.js +11 -0
  16. package/dist/cli/chat/tips.d.ts +21 -0
  17. package/dist/cli/chat/tips.js +43 -0
  18. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  19. package/dist/cli/chat/wizardDispatch.js +645 -0
  20. package/dist/cli/commands/chat.d.ts +1 -0
  21. package/dist/cli/commands/chat.js +181 -700
  22. package/dist/cli/commands/chatModes.d.ts +1 -1
  23. package/dist/cli/commands/chatModes.js +7 -2
  24. package/dist/cli/commands/commandHelp.js +5 -3
  25. package/dist/cli/commands/commands.d.ts +3 -2
  26. package/dist/cli/commands/commands.js +12 -13
  27. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  28. package/dist/cli/commands/fleetCommand.js +46 -0
  29. package/dist/cli/commands/formatters.d.ts +5 -0
  30. package/dist/cli/commands/formatters.js +33 -6
  31. package/dist/cli/commands/logsCommand.js +1 -7
  32. package/dist/cli/commands/modelCommand.js +1 -1
  33. package/dist/cli/commands/providerWizard.d.ts +1 -0
  34. package/dist/cli/commands/providerWizard.js +13 -0
  35. package/dist/cli/commands/runCommand.d.ts +1 -0
  36. package/dist/cli/commands/runCommand.js +25 -5
  37. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  38. package/dist/cli/commands/sessionPicker.js +29 -0
  39. package/dist/cli/commands/settingsSummary.js +6 -4
  40. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  41. package/dist/cli/commands/skillWizard.d.ts +2 -0
  42. package/dist/cli/commands/skillWizard.js +16 -6
  43. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  44. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  45. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
  46. package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
  47. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  48. package/dist/cli/commands/streaming.d.ts +13 -1
  49. package/dist/cli/commands/streaming.js +42 -19
  50. package/dist/cli/commands/wizardActions.d.ts +6 -0
  51. package/dist/cli/commands/wizardActions.js +6 -0
  52. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  53. package/dist/cli/commands/wizardSuggestions.js +60 -12
  54. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  55. package/dist/cli/commands/wizardTransition.js +1 -2
  56. package/dist/cli/index.js +17 -3
  57. package/dist/cli/terminalTitle.d.ts +6 -0
  58. package/dist/cli/terminalTitle.js +36 -0
  59. package/dist/config/inputHistory.d.ts +3 -3
  60. package/dist/config/inputHistory.js +12 -18
  61. package/dist/config/modelDiscovery.d.ts +20 -0
  62. package/dist/config/modelDiscovery.js +51 -0
  63. package/dist/config/providerPresets.d.ts +16 -4
  64. package/dist/config/providerPresets.js +263 -34
  65. package/dist/config/providers.d.ts +2 -0
  66. package/dist/config/providers.js +7 -0
  67. package/dist/config/settings.d.ts +22 -0
  68. package/dist/config/settings.js +29 -1
  69. package/dist/config/skillSettings.d.ts +6 -13
  70. package/dist/config/skillSettings.js +20 -19
  71. package/dist/core/agent/budgets.d.ts +26 -0
  72. package/dist/core/agent/budgets.js +34 -0
  73. package/dist/core/agent/compaction.js +17 -3
  74. package/dist/core/agent/contextBudget.d.ts +8 -0
  75. package/dist/core/agent/contextBudget.js +29 -0
  76. package/dist/core/agent/errors.js +6 -2
  77. package/dist/core/agent/events.d.ts +12 -0
  78. package/dist/core/agent/toolOutputStore.d.ts +5 -0
  79. package/dist/core/agent/toolOutputStore.js +18 -1
  80. package/dist/core/agent/workState.d.ts +1 -1
  81. package/dist/core/agent/workState.js +0 -4
  82. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  83. package/dist/core/attachments/imageAttachments.js +245 -0
  84. package/dist/core/attachments/readBlessings.d.ts +37 -0
  85. package/dist/core/attachments/readBlessings.js +79 -0
  86. package/dist/core/goal/requestClassifier.d.ts +0 -3
  87. package/dist/core/goal/requestClassifier.js +0 -13
  88. package/dist/core/io/boundedRead.js +76 -29
  89. package/dist/core/limits/byteBudgets.d.ts +5 -0
  90. package/dist/core/limits/byteBudgets.js +5 -0
  91. package/dist/core/limits/textBudgets.d.ts +23 -0
  92. package/dist/core/limits/textBudgets.js +23 -0
  93. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  94. package/dist/core/process/backgroundRegistry.js +194 -0
  95. package/dist/core/process/runBoundedProcess.d.ts +3 -0
  96. package/dist/core/process/runBoundedProcess.js +65 -29
  97. package/dist/core/safety/urlGuard.d.ts +2 -1
  98. package/dist/core/safety/urlGuard.js +3 -2
  99. package/dist/core/session/sessionSlimming.js +47 -4
  100. package/dist/core/session/sessionStore.d.ts +37 -0
  101. package/dist/core/session/sessionStore.js +95 -9
  102. package/dist/core/subagent/contracts.d.ts +116 -0
  103. package/dist/core/subagent/contracts.js +54 -0
  104. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  105. package/dist/core/subagent/executionProfiles.js +45 -0
  106. package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
  107. package/dist/core/subagent/subagentCoordinator.js +134 -0
  108. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  109. package/dist/core/subagent/subagentRunner.js +228 -98
  110. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  111. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  112. package/dist/core/tasks/taskStorage.js +12 -1
  113. package/dist/llm/client.d.ts +20 -29
  114. package/dist/llm/client.js +29 -28
  115. package/dist/llm/hazeTools.d.ts +2013 -78
  116. package/dist/llm/hazeTools.js +16 -7
  117. package/dist/llm/lsp.d.ts +2 -0
  118. package/dist/llm/lsp.js +18 -3
  119. package/dist/llm/requestContext.d.ts +22 -1
  120. package/dist/llm/requestContext.js +45 -5
  121. package/dist/llm/systemPrompt.d.ts +4 -1
  122. package/dist/llm/systemPrompt.js +14 -4
  123. package/dist/llm/toolResultTypes.d.ts +1 -1
  124. package/dist/llm/tools/bashTool.d.ts +874 -32
  125. package/dist/llm/tools/bashTool.js +25 -4
  126. package/dist/llm/tools/fetchTool.d.ts +26 -26
  127. package/dist/llm/tools/fetchTool.js +1 -1
  128. package/dist/llm/tools/fileToolShared.d.ts +2 -1
  129. package/dist/llm/tools/fileToolShared.js +5 -5
  130. package/dist/llm/tools/grepRunner.d.ts +5 -0
  131. package/dist/llm/tools/grepRunner.js +52 -71
  132. package/dist/llm/tools/outputCap.d.ts +2 -6
  133. package/dist/llm/tools/outputCap.js +2 -6
  134. package/dist/llm/tools/processTool.d.ts +1077 -0
  135. package/dist/llm/tools/processTool.js +41 -0
  136. package/dist/llm/tools/toolContext.d.ts +8 -0
  137. package/dist/llm/tools/toolContext.js +22 -11
  138. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  139. package/dist/llm/tools/workspaceFile.js +33 -4
  140. package/dist/llm/webFetch.js +24 -11
  141. package/dist/llm/workerContext.d.ts +18 -0
  142. package/dist/llm/workerContext.js +55 -0
  143. package/dist/skills/SkillLoader.d.ts +2 -2
  144. package/dist/skills/SkillRegistry.d.ts +3 -2
  145. package/dist/skills/SkillRegistry.js +43 -13
  146. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  147. package/dist/skills/builder/SkillBuilder.js +23 -5
  148. package/dist/skills/skillTools.js +11 -4
  149. package/dist/skills/types.d.ts +6 -1
  150. package/dist/ui/components/TextInput.d.ts +5 -2
  151. package/dist/ui/components/TextInput.js +76 -8
  152. package/dist/utils/format.d.ts +2 -0
  153. package/dist/utils/format.js +8 -0
  154. package/dist/utils/fs.d.ts +0 -1
  155. package/dist/utils/fs.js +0 -4
  156. package/dist/utils/openPath.d.ts +2 -0
  157. package/dist/utils/openPath.js +9 -0
  158. package/package.json +1 -1
@@ -0,0 +1,26 @@
1
+ /**
2
+ * An idle timer for the main agent turn.
3
+ *
4
+ * The turn is considered "idle" (and aborted) after `timeoutMs` with no stream
5
+ * activity — UNLESS a tool call is currently executing (`isBusy()` returns
6
+ * true). Concurrent subagents can run for many minutes while emitting no stream
7
+ * parts; that is legitimate work, not a dead stream, so the timer defers (rearms)
8
+ * while any tool is in flight. This prevents a long subagent wave from being
9
+ * mistaken for a hung turn.
10
+ *
11
+ * Note: there is intentionally no upper bound on how long a single tool may run
12
+ * while in flight — a genuinely hung tool would defer indefinitely. A per-tool
13
+ * hard timeout is a separate concern; the idle timer only guards against a turn
14
+ * that is producing no model output AND doing no tool work.
15
+ */
16
+ export interface IdleTimer {
17
+ /** Clear any pending deadline and rearm it for a fresh idle window. */
18
+ reset: () => void;
19
+ /** Cancel the pending deadline without rearming. */
20
+ clear: () => void;
21
+ }
22
+ export declare function createIdleTimer(input: {
23
+ timeoutMs: number;
24
+ isBusy: () => boolean;
25
+ onTimeout: () => void;
26
+ }): IdleTimer;
@@ -0,0 +1,24 @@
1
+ export function createIdleTimer(input) {
2
+ const { timeoutMs, isBusy, onTimeout } = input;
3
+ let timer;
4
+ const fire = () => {
5
+ if (isBusy()) {
6
+ // Tools are executing — that is activity. Defer by rearming.
7
+ timer = setTimeout(fire, timeoutMs);
8
+ return;
9
+ }
10
+ onTimeout();
11
+ };
12
+ return {
13
+ reset: () => {
14
+ if (timer)
15
+ clearTimeout(timer);
16
+ timer = setTimeout(fire, timeoutMs);
17
+ },
18
+ clear: () => {
19
+ if (timer)
20
+ clearTimeout(timer);
21
+ timer = undefined;
22
+ },
23
+ };
24
+ }
@@ -27,10 +27,12 @@ export interface ToolGroupRendererDeps {
27
27
  role: 'tool';
28
28
  text: string;
29
29
  streaming: boolean;
30
+ toolCount: number;
30
31
  }) => void;
31
32
  updateMessage: (id: string, update: {
32
33
  text?: string;
33
34
  streaming?: boolean;
35
+ toolCount?: number;
34
36
  }) => void;
35
37
  debugLog: (line: string) => void;
36
38
  onEvent?: AgentEventSink;
@@ -31,14 +31,16 @@ export function createToolGroupRenderer(deps) {
31
31
  };
32
32
  const updateToolGroup = (streaming = true, group = toolGroup) => {
33
33
  const text = renderToolGroup(group);
34
+ // toolCount is carried structurally so metrics never depend on the rendered
35
+ // caption/row format (CR-015).
34
36
  if (!group.started) {
35
37
  group.started = true;
36
38
  group.finalized = !streaming;
37
- deps.addMessage({ id: group.id, role: 'tool', text, streaming });
39
+ deps.addMessage({ id: group.id, role: 'tool', text, streaming, toolCount: group.items.length });
38
40
  }
39
41
  else {
40
42
  group.finalized = !streaming;
41
- deps.updateMessage(group.id, { text, streaming });
43
+ deps.updateMessage(group.id, { text, streaming, toolCount: group.items.length });
42
44
  }
43
45
  };
44
46
  const finalizeToolGroup = (group = toolGroup) => {
@@ -58,11 +58,13 @@ export function stepCacheMetrics(usage) {
58
58
  };
59
59
  }
60
60
  export function subagentTokenEstimate(output) {
61
- if (typeof output !== 'object' || output == null || !('tokens' in output))
61
+ if (typeof output !== 'object' || output == null)
62
62
  return undefined;
63
- const tokens = output.tokens;
64
- const input = typeof tokens?.in === 'number' ? tokens.in : 0;
65
- const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
63
+ const value = output;
64
+ const inputValue = value.telemetry?.usage?.inputTokens ?? value.tokens?.in;
65
+ const outputValue = value.telemetry?.usage?.outputTokens ?? value.tokens?.out;
66
+ const input = typeof inputValue === 'number' ? inputValue : 0;
67
+ const outputTokens = typeof outputValue === 'number' ? outputValue : 0;
66
68
  return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
67
69
  }
68
70
  export function rememberContextFilesFromToolOutput(activeContextFiles, output) {
@@ -1,8 +1,11 @@
1
1
  import { type ModelMessage } from 'ai';
2
2
  import type { LlmLog } from '../../core/log/llmLog.js';
3
+ import { type SubagentOverrides } from '../../llm/requestContext.js';
3
4
  import { type PromptSession } from '../../llm/systemPrompt.js';
4
5
  import type { ContextFile } from '../../config/contextFiles.js';
5
6
  import { type AgentEventSink } from '../../core/agent/events.js';
7
+ import { type ImageAttachment } from '../../core/attachments/imageAttachments.js';
8
+ import { type BlessedPath } from '../../core/attachments/readBlessings.js';
6
9
  export { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
7
10
  import type { WorkState } from '../../core/agent/workState.js';
8
11
  import { type TokenUsage } from './streaming/turnRuntime.js';
@@ -17,12 +20,21 @@ export type Message = {
17
20
  finishedAt?: number;
18
21
  tokensPerSecond?: number;
19
22
  displayOrder?: number;
23
+ toolCount?: number;
20
24
  };
21
25
  export type TurnStatus = 'complete' | 'aborted' | 'failed';
22
26
  /** Authoritative outcome of a turn, so callers (esp. headless/CI) need not sniff message text. */
23
27
  export interface TurnResult {
24
28
  status: TurnStatus;
25
29
  }
30
+ export interface TurnExecutionOptions {
31
+ ephemeralControl?: string;
32
+ subagentOverrides?: SubagentOverrides;
33
+ /** User-attached images for this turn (F03); only the first attempt carries them. */
34
+ attachments?: readonly ImageAttachment[];
35
+ /** User-mentioned paths whose reads may escape workspace confinement this turn. */
36
+ blessedPaths?: readonly BlessedPath[];
37
+ }
26
38
  export interface StreamCallbacks {
27
39
  addMessage: (msg: Message) => void;
28
40
  updateMessage: (id: string, update: Partial<Message>) => void;
@@ -43,4 +55,4 @@ export interface StreamCallbacks {
43
55
  log?: LlmLog;
44
56
  contextFileSignatures?: Map<string, string>;
45
57
  }
46
- export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession, modelOverride?: string): Promise<TurnResult>;
58
+ export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession, modelOverride?: string, turnOptions?: TurnExecutionOptions): Promise<TurnResult>;
@@ -4,10 +4,12 @@ import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
4
4
  import { assembleRequestContext } from '../../llm/requestContext.js';
5
5
  import { projectContextSection } from '../../llm/systemPrompt.js';
6
6
  import { closeMcpClients } from '../../llm/mcp.js';
7
+ import { readSettings } from '../../config/settings.js';
7
8
  import { toolCallSummary, toolResultSummary, busyToolLabel, formatSeconds } from './formatters.js';
8
9
  import { agentEvent } from '../../core/agent/events.js';
9
10
  import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
10
11
  import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
12
+ import { userTurnMessage } from '../../core/attachments/imageAttachments.js';
11
13
  import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
12
14
  import { estimateValueTokens } from '../../core/agent/contextBudget.js';
13
15
  import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../core/agent/requestAssembly.js';
@@ -24,6 +26,8 @@ import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFi
24
26
  import { toolsContextFor } from '../../llm/tools/toolContext.js';
25
27
  import { modelThinkingLabel } from '../../utils/modelName.js';
26
28
  import { terminalTurnStatus } from './streaming/turnOutcome.js';
29
+ import { createIdleTimer } from './streaming/idleTimer.js';
30
+ import { WorkspaceMutationPolicy } from '../../core/subagent/workspaceMutationPolicy.js';
27
31
  function logEntry(log, entry) {
28
32
  if (log)
29
33
  void logAppend(log, entry).catch(() => undefined);
@@ -35,22 +39,26 @@ function withScopedContextControl(messages, context) {
35
39
  context.pendingContextFiles = [];
36
40
  return withSyntheticControl(messages, `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}`);
37
41
  }
38
- async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController) {
42
+ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope) {
39
43
  let thinkingLabel = modelThinkingLabel(undefined);
40
44
  callbacks.setBusyLabel?.(thinkingLabel);
41
45
  let turnStatus = 'failed';
42
- let idleTimer;
43
46
  let loadedMcp;
44
- const resetIdleTimer = () => {
45
- if (idleTimer)
46
- clearTimeout(idleTimer);
47
- idleTimer = setTimeout(() => {
48
- abortController.abort('haze turn timed out after no model/tool activity.');
49
- }, IDLE_TIMEOUT_MS);
50
- };
47
+ // Tool calls currently executing. A concurrent subagent wave can run for many
48
+ // minutes with no stream parts; that is activity, not a dead stream, so the
49
+ // idle timer defers while any tool is in flight (see streaming/idleTimer.ts).
50
+ const inFlightTools = new Set();
51
+ const idleTimer = createIdleTimer({
52
+ timeoutMs: IDLE_TIMEOUT_MS,
53
+ isBusy: () => inFlightTools.size > 0,
54
+ onTimeout: () => abortController.abort('haze turn timed out after no model/tool activity.'),
55
+ });
51
56
  const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
52
57
  try {
53
- const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride });
58
+ // Single choke point: one fresh settings read per turn, shared by model
59
+ // resolution and request assembly (CR-024).
60
+ const turnSettings = await readSettings();
61
+ const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
54
62
  if (!runtime?.model) {
55
63
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
56
64
  turnStatus = 'failed';
@@ -61,7 +69,14 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
61
69
  let activeContextFiles = contextFiles;
62
70
  const activeModel = runtime.model;
63
71
  const providerSettings = providerRequestSettings(runtime.config);
64
- const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel, abortSignal: abortController.signal });
72
+ const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel, modelRuntime: runtime, subagentOverrides: turnOptions.subagentOverrides, abortSignal: abortController.signal, executionScope: turnScope.executionScope, settings: turnSettings, onSubagentEvent: event => callbacks.onEvent?.(agentEvent(event.type === 'queued'
73
+ ? { type: 'subagent_state', id: event.id, state: 'queued', mode: event.mode, queued: event.queued, running: event.running }
74
+ : event.type === 'started'
75
+ ? { type: 'subagent_state', id: event.id, state: 'started', mode: event.mode, queueMs: event.queueMs, running: event.running }
76
+ : event.type === 'terminal'
77
+ ? { type: 'subagent_state', id: event.id, state: 'terminal', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: event.execution, running: event.running }
78
+ : { type: 'subagent_state', id: event.id, state: 'settled', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: 'settled', running: event.running })) });
79
+ turnScope.executionScope ??= assembled.executionScope;
65
80
  const availableTools = assembled.availableTools;
66
81
  loadedMcp = assembled.loadedMcp;
67
82
  if (loadedMcp?.errors.length)
@@ -72,13 +87,15 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
72
87
  const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
73
88
  const durableRequestMessages = compactToolHistory(retryingExistingRequest
74
89
  ? stripSyntheticControls(callbacks.getConversation())
75
- : [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
90
+ : [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]).messages;
76
91
  let requestMessages = durableRequestMessages;
77
92
  if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
78
93
  requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal }).messages;
79
94
  }
80
95
  requestMessages = withoutSystemMessages(requestMessages);
81
96
  callbacks.setConversation(stripSyntheticControls(requestMessages));
97
+ if (turnOptions.ephemeralControl)
98
+ requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
82
99
  const systemPrompt = assembled.systemPrompt;
83
100
  const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
84
101
  logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
@@ -92,7 +109,8 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
92
109
  callbacks.setLastAssistantText(text);
93
110
  };
94
111
  const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
95
- const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead: path => toolDisplay.addContextFileRead(path) };
112
+ const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
113
+ const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead: path => toolDisplay.addContextFileRead(path), mutationPolicy, blessedPaths: turnOptions.blessedPaths };
96
114
  const startedTools = new Map();
97
115
  const latestToolCalls = new Map();
98
116
  let latestAccumulatedResponseMessages = [];
@@ -203,10 +221,10 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
203
221
  callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
204
222
  },
205
223
  });
206
- resetIdleTimer();
224
+ idleTimer.reset();
207
225
  const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
208
226
  for await (const part of result.stream) {
209
- resetIdleTimer();
227
+ idleTimer.reset();
210
228
  switch (part.type) {
211
229
  case 'text-delta': {
212
230
  callbacks.setBusyLabel?.(thinkingLabel);
@@ -239,6 +257,7 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
239
257
  const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
240
258
  latestToolCalls.set(part.id, toolCall);
241
259
  startedTools.set(part.id, Date.now());
260
+ inFlightTools.add(part.id);
242
261
  callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
243
262
  toolDisplay.ensureToolItem(toolCall);
244
263
  break;
@@ -262,6 +281,7 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
262
281
  case 'tool-result': {
263
282
  const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
264
283
  latestToolCalls.set(part.toolCallId, toolCall);
284
+ inFlightTools.delete(part.toolCallId);
265
285
  const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
266
286
  const ok = toolOutputOk(part.output, true);
267
287
  lastToolOk = ok;
@@ -287,6 +307,7 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
287
307
  break;
288
308
  }
289
309
  case 'tool-error': {
310
+ inFlightTools.delete(part.toolCallId);
290
311
  const existing = latestToolCalls.get(part.toolCallId);
291
312
  const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
292
313
  const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
@@ -387,14 +408,13 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
387
408
  finally {
388
409
  if (loadedMcp?.clients.length)
389
410
  await closeMcpClients(loadedMcp.clients);
390
- if (idleTimer)
391
- clearTimeout(idleTimer);
411
+ idleTimer.clear();
392
412
  toolDisplay.stopToolTimer();
393
413
  toolDisplay.finalizeToolGroup();
394
414
  }
395
415
  return { status: turnStatus };
396
416
  }
397
- export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
417
+ export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
398
418
  const abortController = new AbortController();
399
419
  let status = 'failed';
400
420
  callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
@@ -403,11 +423,14 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
403
423
  if (!retryingExistingRequest)
404
424
  callbacks.addMessage({ role: 'user', text: displayValue ?? value });
405
425
  try {
426
+ // Retries are one logical turn and therefore share coordinator admission and
427
+ // the workspace mutation lease, including quarantined lingering work.
428
+ const turnScope = {};
406
429
  let attempt = retryAttempt;
407
430
  let overflowRecovered = contextOverflowRecovered;
408
431
  let retrying = retryingExistingRequest;
409
432
  while (true) {
410
- const result = await runAgentAttempt(value, contextFiles, callbacks, attempt, retrying, overflowRecovered, session, modelOverride, abortController);
433
+ const result = await runAgentAttempt(value, contextFiles, callbacks, attempt, retrying, overflowRecovered, session, modelOverride, abortController, turnOptions, turnScope);
411
434
  status = result.status;
412
435
  if (!result.retry)
413
436
  break;
@@ -6,9 +6,15 @@ export declare const PROVIDER_ACTIONS: {
6
6
  readonly useProvider: "use provider";
7
7
  readonly addModels: "add models";
8
8
  readonly setApiKey: "set API key";
9
+ readonly markImageCapable: "mark image-capable";
10
+ readonly clearImageCapable: "clear image-capable";
9
11
  readonly removeModels: "remove models";
10
12
  readonly removeProvider: "remove provider";
11
13
  };
14
+ export declare const MODEL_CHOICES: {
15
+ readonly addModels: "add models";
16
+ readonly enterModelNames: "enter model names";
17
+ };
12
18
  export declare const SERVER_CHOICES: {
13
19
  readonly addServer: "add server";
14
20
  readonly custom: "custom";
@@ -6,9 +6,15 @@ export const PROVIDER_ACTIONS = {
6
6
  useProvider: 'use provider',
7
7
  addModels: 'add models',
8
8
  setApiKey: 'set API key',
9
+ markImageCapable: 'mark image-capable',
10
+ clearImageCapable: 'clear image-capable',
9
11
  removeModels: 'remove models',
10
12
  removeProvider: 'remove provider',
11
13
  };
14
+ export const MODEL_CHOICES = {
15
+ addModels: 'add models',
16
+ enterModelNames: 'enter model names',
17
+ };
12
18
  export const SERVER_CHOICES = {
13
19
  addServer: 'add server',
14
20
  custom: 'custom',
@@ -12,6 +12,13 @@ export declare function providerSuggestions(settings: HazeSettings): TextInputSu
12
12
  export declare function providerActionSuggestions(settings: HazeSettings, selectedProviderName: string | undefined): TextInputSuggestion[];
13
13
  export declare function presetSuggestions(): TextInputSuggestion[];
14
14
  export declare function modelSuggestions(settings: HazeSettings, modelProviderFilter: string | undefined): TextInputSuggestion[];
15
+ export declare function modelAddProviderSuggestions(settings: HazeSettings): TextInputSuggestion[];
16
+ /**
17
+ * Model picker fed by live /models discovery. Curated `suggestedModels`
18
+ * (from provider presets) are pinned atop the discovered list when the
19
+ * endpoint actually serves them — stale curation entries simply don't pin.
20
+ */
21
+ export declare function modelPickSuggestions(settings: HazeSettings, providerName: string | undefined, discoveredModels: string[], suggestedModels?: string[]): TextInputSuggestion[];
15
22
  export declare function lspSuggestions(settings: HazeSettings): TextInputSuggestion[];
16
23
  export declare function lspActionSuggestions(settings: HazeSettings, selectedLspName: string | undefined): TextInputSuggestion[];
17
24
  export declare function lspPresetSuggestions(): TextInputSuggestion[];
@@ -20,4 +27,5 @@ export declare function mcpActionSuggestions(settings: HazeSettings, selectedMcp
20
27
  export declare function mcpPresetSuggestions(): TextInputSuggestion[];
21
28
  export declare function mcpTransportSuggestions(): TextInputSuggestion[];
22
29
  export declare function skillsSuggestions(settings: HazeSettings, skills: LoadedSkill[]): TextInputSuggestion[];
30
+ export declare function skillScopeSuggestions(): TextInputSuggestion[];
23
31
  export declare function skillsActionSuggestions(settings: HazeSettings, skills: LoadedSkill[], selectedSkillName: string | undefined): TextInputSuggestion[];
@@ -1,9 +1,10 @@
1
- import { configuredProviders, findProvider, modelSelector } from '../../config/providers.js';
1
+ import { configuredProviders, findProvider, modelSelector, providerImageCapable } from '../../config/providers.js';
2
2
  import { configuredLspServers, LSP_PRESETS } from '../../config/lspSettings.js';
3
3
  import { configuredMcpServers, findMcpServer, findMcpPreset, presetIds } from '../../config/mcpSettings.js';
4
4
  import { isSkillEnabled } from '../../config/skillSettings.js';
5
5
  import { PROVIDER_PRESETS } from '../../config/providerPresets.js';
6
- import { COMMON_ACTIONS, LSP_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, PROVIDER_ACTIONS, PROVIDER_CHOICES, SERVER_CHOICES, SKILL_ACTIONS, SKILL_CHOICES } from './wizardActions.js';
6
+ import { COMMON_ACTIONS, LSP_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, MODEL_CHOICES, PROVIDER_ACTIONS, PROVIDER_CHOICES, SERVER_CHOICES, SKILL_ACTIONS, SKILL_CHOICES } from './wizardActions.js';
7
+ import { findSelectedSkill, skillPickerValue } from './skillWizard.js';
7
8
  /**
8
9
  * Pure suggestion builders for the chat wizard pickers (provider / model / LSP /
9
10
  * MCP / skills). Extracted from the React component so they are unit-testable
@@ -25,8 +26,13 @@ export function providerActionSuggestions(settings, selectedProviderName) {
25
26
  const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
26
27
  return [
27
28
  { value: PROVIDER_ACTIONS.useProvider, description: 'Set this provider and choose a model', kind: 'provider' },
28
- { value: PROVIDER_ACTIONS.addModels, description: 'Append comma-separated model names', kind: 'provider' },
29
+ { value: PROVIDER_ACTIONS.addModels, description: 'Fetch the provider model list and add models', kind: 'provider' },
29
30
  { value: PROVIDER_ACTIONS.setApiKey, description: provider?.key ? 'Update the saved API key' : 'Add an API key', kind: 'provider' },
31
+ provider
32
+ ? (providerImageCapable(provider)
33
+ ? { value: PROVIDER_ACTIONS.clearImageCapable, description: 'Stop sending attached images to this provider', kind: 'provider' }
34
+ : { value: PROVIDER_ACTIONS.markImageCapable, description: 'Allow attached images to be sent to this provider', kind: 'provider' })
35
+ : { value: PROVIDER_ACTIONS.markImageCapable, description: 'Allow attached images to be sent to this provider', kind: 'provider' },
30
36
  ...(provider?.models?.length ? [{ value: PROVIDER_ACTIONS.removeModels, description: 'Remove models from this provider', kind: 'provider' }] : []),
31
37
  { value: PROVIDER_ACTIONS.removeProvider, description: 'Delete this provider from settings', kind: 'provider' },
32
38
  ];
@@ -50,11 +56,47 @@ export function presetSuggestions() {
50
56
  }
51
57
  export function modelSuggestions(settings, modelProviderFilter) {
52
58
  const providers = configuredProviders(settings).filter(provider => !modelProviderFilter || provider.name === modelProviderFilter);
53
- return providers.flatMap(provider => provider.models.map(model => ({
54
- value: modelProviderFilter ? model : modelSelector(provider, model),
55
- description: provider.name,
56
- kind: 'model',
57
- })));
59
+ return [
60
+ ...providers.flatMap(provider => provider.models.map(model => ({
61
+ value: modelProviderFilter ? model : modelSelector(provider, model),
62
+ description: provider.name,
63
+ kind: 'model',
64
+ }))),
65
+ { value: MODEL_CHOICES.addModels, description: modelProviderFilter ? `Add models to ${modelProviderFilter} (fetched from its models endpoint)` : 'Add models to a provider (fetched from its models endpoint)', kind: 'model' },
66
+ ];
67
+ }
68
+ export function modelAddProviderSuggestions(settings) {
69
+ return configuredProviders(settings).map(provider => ({
70
+ value: provider.name,
71
+ description: `${provider.models.length} model${provider.models.length === 1 ? '' : 's'} configured`,
72
+ kind: 'provider',
73
+ }));
74
+ }
75
+ /**
76
+ * Model picker fed by live /models discovery. Curated `suggestedModels`
77
+ * (from provider presets) are pinned atop the discovered list when the
78
+ * endpoint actually serves them — stale curation entries simply don't pin.
79
+ */
80
+ export function modelPickSuggestions(settings, providerName, discoveredModels, suggestedModels = []) {
81
+ const provider = providerName ? findProvider(settings, providerName) : undefined;
82
+ const configured = new Set(provider?.models ?? []);
83
+ const available = discoveredModels.filter(model => !configured.has(model));
84
+ const availableSet = new Set(available);
85
+ const pinned = suggestedModels.filter(model => availableSet.has(model));
86
+ const pinnedSet = new Set(pinned);
87
+ return [
88
+ ...pinned.map(model => ({
89
+ value: model,
90
+ description: 'suggested',
91
+ kind: 'model',
92
+ })),
93
+ ...available.filter(model => !pinnedSet.has(model)).map(model => ({
94
+ value: model,
95
+ description: providerName,
96
+ kind: 'model',
97
+ })),
98
+ { value: MODEL_CHOICES.enterModelNames, description: 'Type comma-separated model names instead', kind: 'model' },
99
+ ];
58
100
  }
59
101
  export function lspSuggestions(settings) {
60
102
  const servers = configuredLspServers(settings);
@@ -121,16 +163,22 @@ export function mcpTransportSuggestions() {
121
163
  export function skillsSuggestions(settings, skills) {
122
164
  return [{ value: SKILL_CHOICES.addSkill, description: 'describe a new skill for haze to generate', kind: 'skill' },
123
165
  ...skills.map(skill => ({
124
- value: skill.name,
125
- description: `${skill.description}${isSkillEnabled(settings, skill.name) ? '' : ' · disabled'}`,
166
+ value: skills.some(candidate => candidate !== skill && candidate.name === skill.name) ? skillPickerValue(skill) : skill.name,
167
+ description: `${skill.description} · ${skill.source}${isSkillEnabled(settings, skill.name, skill.source) ? '' : ' · disabled'}`,
126
168
  kind: 'skill',
127
169
  }))];
128
170
  }
171
+ export function skillScopeSuggestions() {
172
+ return [
173
+ { value: 'this project', description: 'create .haze/skills/<name>/SKILL.md for this repository', kind: 'skill' },
174
+ { value: 'global', description: 'create ~/.haze/skills/<name>/SKILL.md for your user', kind: 'skill' },
175
+ ];
176
+ }
129
177
  export function skillsActionSuggestions(settings, skills, selectedSkillName) {
130
- const skill = selectedSkillName ? skills.find(candidate => candidate.name === selectedSkillName) : undefined;
178
+ const skill = findSelectedSkill(skills, selectedSkillName);
131
179
  const result = [];
132
180
  if (skill) {
133
- const enabled = isSkillEnabled(settings, skill.name);
181
+ const enabled = isSkillEnabled(settings, skill.name, skill.source);
134
182
  result.push({ value: enabled ? COMMON_ACTIONS.disable : COMMON_ACTIONS.enable, description: `${enabled ? COMMON_ACTIONS.disable : COMMON_ACTIONS.enable} this skill`, kind: 'skill' });
135
183
  result.push({ value: SKILL_ACTIONS.showInfo, description: 'show description, references, and path', kind: 'skill' });
136
184
  result.push({ value: SKILL_ACTIONS.validate, description: 're-load and validate SKILL.md', kind: 'skill' });
@@ -11,6 +11,9 @@ export type ProviderWizardEffect = SharedWizardEffect | {
11
11
  type: 'provider-draft';
12
12
  patch: Partial<HazeProviderSettings>;
13
13
  replace?: boolean;
14
+ } | {
15
+ type: 'discover-provider-models';
16
+ draft: Partial<HazeProviderSettings>;
14
17
  };
15
18
  export type McpWizardEffect = SharedWizardEffect | {
16
19
  type: 'mcp-draft';
@@ -23,6 +26,7 @@ export declare function transitionProviderField(input: {
23
26
  mode: Mode;
24
27
  value: string;
25
28
  settings: HazeSettings;
29
+ draft: Partial<HazeProviderSettings>;
26
30
  }): ProviderWizardEffect[] | undefined;
27
31
  export declare function transitionMcpField(input: {
28
32
  mode: Mode;
@@ -4,8 +4,7 @@ export function transitionProviderField(input) {
4
4
  const key = input.value.trim();
5
5
  return [
6
6
  { type: 'provider-draft', patch: key ? { key } : {} },
7
- { type: 'mode', mode: 'providerAddModels' },
8
- { type: 'message', text: 'Comma-separated model names? Example: llama3.1, qwen2.5-coder, gpt-4o' },
7
+ { type: 'discover-provider-models', draft: { ...input.draft, ...(key ? { key } : {}) } },
9
8
  ];
10
9
  }
11
10
  const result = input.mode === 'providerAddName' ? captureProviderName(input.settings, input.value)
package/dist/cli/index.js CHANGED
@@ -5,7 +5,11 @@ import { dirname, join } from 'node:path';
5
5
  import { Command, Option } from 'commander';
6
6
  import { chatCommand } from './commands/chat.js';
7
7
  import { runHeadless } from './commands/runCommand.js';
8
+ import { installTerminalTitle, terminalTitleLabel } from './terminalTitle.js';
9
+ import { findSession } from '../core/session/sessionStore.js';
10
+ import { installBackgroundProcessSignalHandlers, teardownBackgroundProcesses } from '../core/process/backgroundRegistry.js';
8
11
  const __dirname = dirname(fileURLToPath(import.meta.url));
12
+ installBackgroundProcessSignalHandlers();
9
13
  const pkg = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8'));
10
14
  const program = new Command();
11
15
  program
@@ -14,6 +18,7 @@ program
14
18
  .version(pkg.version)
15
19
  .option('--debug', 'show model/tool debug logs and write a detailed JSONL log to ~/.haze/logs/')
16
20
  .option('-c, --continue', 'resume the latest saved session for this workspace')
21
+ .addOption(new Option('--resume <id>', 'resume an exact saved session id for this workspace').conflicts(['continue', 'session']))
17
22
  .option('--no-session', 'run without saving or resuming a durable session')
18
23
  .option('-p, --prompt <text>', 'print mode: run a single non-interactive turn and print the result (falls back to piped stdin)')
19
24
  .option('-m, --model <selector>', 'override the model for this run only — a registered model name or provider:name')
@@ -26,6 +31,7 @@ Examples:
26
31
  $ haze -p "list the top 3 bugs" --output json emit a JSON envelope { type, status, result, usage }
27
32
  $ haze -p "audit src/" --output stream-json stream NDJSON events live, then the final result envelope
28
33
  $ haze -p "summarize" --model openai:gpt-4o-mini override the model for this run only
34
+ $ haze --resume <id> -p "continue the review" load a saved context for one print-mode turn
29
35
  $ haze -p "audit auth.ts" --debug also write a detailed JSONL log to ~/.haze/logs/
30
36
 
31
37
  Print mode (-p):
@@ -38,7 +44,8 @@ Print mode (-p):
38
44
  harnesses live progress and stagnation detection. --model overrides the model for this
39
45
  run only (no settings change) and must already be registered under a provider (add it once via
40
46
  the /provider picker). Print-mode runs are non-durable: --continue is ignored and no session is
41
- saved, and there is no automatic context-overflow recovery.
47
+ saved. --resume <id> loads saved context for the turn without changing that session. There is no
48
+ automatic context-overflow recovery.
42
49
  `);
43
50
  async function readStdinPrompt() {
44
51
  // Only read stdin when it is piped (non-TTY); never hang waiting on an interactive terminal.
@@ -57,13 +64,19 @@ async function readStdinPrompt() {
57
64
  }
58
65
  program.action(async () => {
59
66
  const opts = program.opts();
67
+ // Name the terminal tab for the run; no-op unless stdout is a real TTY.
68
+ installTerminalTitle(terminalTitleLabel(process.cwd()));
60
69
  // -p takes precedence; otherwise fall back to piped stdin. An empty stdin yields no prompt.
61
70
  const prompt = opts.prompt?.trim() ? opts.prompt : await readStdinPrompt();
71
+ if (opts.resume && !await findSession(opts.resume)) {
72
+ throw new Error(`No session named ${opts.resume} exists for this workspace.`);
73
+ }
62
74
  if (prompt) {
63
75
  // One-shot runs are always fresh and non-durable; --continue is ignored in this mode.
64
76
  const code = await runHeadless({
65
77
  prompt,
66
78
  modelOverride: opts.model,
79
+ resumeSessionId: opts.resume,
67
80
  // commander validates --output against the choices above, so opts.output is one of
68
81
  // 'text' | 'json' | 'stream-json'; default to text for piped/stdin runs without the flag.
69
82
  output: opts.output === 'json' || opts.output === 'stream-json' ? opts.output : 'text',
@@ -74,9 +87,10 @@ program.action(async () => {
74
87
  process.exitCode = code;
75
88
  return;
76
89
  }
77
- await chatCommand({ debug: Boolean(opts.debug), continueSession: Boolean(opts.continue), noSession: opts.session === false, version: pkg.version });
90
+ await chatCommand({ debug: Boolean(opts.debug), continueSession: Boolean(opts.continue), resumeSessionId: opts.resume, noSession: opts.session === false, version: pkg.version });
78
91
  });
79
- program.parseAsync().catch((error) => {
92
+ program.parseAsync().catch(async (error) => {
80
93
  console.error(error instanceof Error ? error.message : error);
94
+ await teardownBackgroundProcesses().catch(() => undefined);
81
95
  process.exit(1);
82
96
  });
@@ -0,0 +1,6 @@
1
+ export declare function terminalTitleLabel(cwd: string): string;
2
+ /**
3
+ * Set the terminal title for the duration of this run. No-op when stdout is
4
+ * not a TTY (headless, piped, or redirected runs).
5
+ */
6
+ export declare function installTerminalTitle(label: string): void;
@@ -0,0 +1,36 @@
1
+ import { basename } from 'node:path';
2
+ /**
3
+ * Terminal tab/window title for interactive runs. Uses the OSC 0 escape
4
+ * sequence, understood by xterm-compatible terminals (Terminal.app, iTerm2,
5
+ * VS Code, etc.). Guarded to real TTYs so piped/redirected output is never
6
+ * polluted, and cleared on exit so the tab falls back to the shell's own
7
+ * naming instead of showing a stale haze title.
8
+ */
9
+ function titleEscape(label) {
10
+ return `\u001B]0;${label}\u0007`;
11
+ }
12
+ export function terminalTitleLabel(cwd) {
13
+ // eslint-disable-next-line no-control-regex -- stripping control characters is the point here.
14
+ const dir = basename(cwd).replace(/[\u0000-\u001F\u007F]/g, '').trim();
15
+ return `haze${dir ? ` - ${dir}` : ''}`;
16
+ }
17
+ /**
18
+ * Set the terminal title for the duration of this run. No-op when stdout is
19
+ * not a TTY (headless, piped, or redirected runs).
20
+ */
21
+ export function installTerminalTitle(label) {
22
+ if (!process.stdout.isTTY)
23
+ return;
24
+ process.stdout.write(titleEscape(label));
25
+ process.once('exit', () => {
26
+ // Re-check at exit time: the terminal may no longer be attached.
27
+ if (!process.stdout.isTTY)
28
+ return;
29
+ try {
30
+ process.stdout.write(titleEscape(''));
31
+ }
32
+ catch {
33
+ // Best effort only: title restoration must never break shutdown.
34
+ }
35
+ });
36
+ }
@@ -1,4 +1,4 @@
1
1
  export declare const INPUT_HISTORY_FILE: string;
2
- export declare function readInputHistory(): Promise<string[]>;
3
- export declare function writeInputHistory(history: string[]): Promise<void>;
4
- export declare function addInputHistoryItem(item: string): Promise<string[]>;
2
+ export declare function readInputHistory(file?: string): Promise<string[]>;
3
+ export declare function writeInputHistory(history: string[], file?: string): Promise<void>;
4
+ export declare function addInputHistoryItem(item: string, file?: string): Promise<string[]>;