@denizokcu/haze 1.7.12 → 1.8.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 (178) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +30 -6
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +47 -19
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/BusyBar.d.ts +1 -2
  7. package/dist/cli/chat/ChatHeader.d.ts +6 -0
  8. package/dist/cli/chat/ChatHeader.js +11 -0
  9. package/dist/cli/chat/ChatScreen.d.ts +16 -0
  10. package/dist/cli/chat/ChatScreen.js +399 -0
  11. package/dist/cli/chat/ChatScreenView.d.ts +68 -0
  12. package/dist/cli/chat/ChatScreenView.js +47 -0
  13. package/dist/cli/chat/LiveTail.d.ts +11 -0
  14. package/dist/cli/chat/LiveTail.js +26 -0
  15. package/dist/cli/chat/TaskBar.d.ts +3 -2
  16. package/dist/cli/chat/TaskBar.js +4 -0
  17. package/dist/cli/chat/agentTurnRunner.d.ts +12 -0
  18. package/dist/cli/chat/agentTurnRunner.js +177 -0
  19. package/dist/cli/chat/busyIndicator.js +9 -5
  20. package/dist/cli/chat/chatMetrics.d.ts +7 -0
  21. package/dist/cli/chat/chatMetrics.js +15 -1
  22. package/dist/cli/chat/chatViewModel.d.ts +85 -0
  23. package/dist/cli/chat/chatViewModel.js +66 -0
  24. package/dist/cli/chat/fileMentionSuggestions.d.ts +0 -14
  25. package/dist/cli/chat/fileMentionSuggestions.js +4 -21
  26. package/dist/cli/chat/liveTheme.d.ts +11 -0
  27. package/dist/cli/chat/liveTheme.js +26 -0
  28. package/dist/cli/chat/messageFinalize.d.ts +4 -0
  29. package/dist/cli/chat/messageFinalize.js +8 -0
  30. package/dist/cli/chat/messages.js +1 -1
  31. package/dist/cli/chat/pickerOpeners.d.ts +23 -0
  32. package/dist/cli/chat/pickerOpeners.js +36 -0
  33. package/dist/cli/chat/promptSessionState.d.ts +11 -0
  34. package/dist/cli/chat/promptSessionState.js +39 -0
  35. package/dist/cli/chat/renderMetrics.d.ts +8 -0
  36. package/dist/cli/chat/renderMetrics.js +14 -0
  37. package/dist/cli/chat/resizeGuard.d.ts +11 -0
  38. package/dist/cli/chat/resizeGuard.js +25 -0
  39. package/dist/cli/chat/screenDeps.d.ts +116 -0
  40. package/dist/cli/chat/screenDeps.js +1 -0
  41. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  42. package/dist/cli/chat/sessionLifecycle.js +4 -1
  43. package/dist/cli/chat/settingsSelection.d.ts +33 -0
  44. package/dist/cli/chat/settingsSelection.js +46 -0
  45. package/dist/cli/chat/skillNotices.d.ts +18 -0
  46. package/dist/cli/chat/skillNotices.js +26 -0
  47. package/dist/cli/chat/startupInfo.js +1 -1
  48. package/dist/cli/chat/submitPipeline.d.ts +8 -0
  49. package/dist/cli/chat/submitPipeline.js +141 -0
  50. package/dist/cli/chat/terminalControl.js +1 -1
  51. package/dist/cli/chat/toolSummaries.d.ts +29 -0
  52. package/dist/cli/chat/toolSummaries.js +268 -0
  53. package/dist/cli/chat/turnState.d.ts +8 -0
  54. package/dist/cli/chat/turnState.js +1 -0
  55. package/dist/cli/chat/userCommandFlow.d.ts +21 -0
  56. package/dist/cli/chat/userCommandFlow.js +66 -0
  57. package/dist/cli/chat/userCommandRunner.d.ts +14 -0
  58. package/dist/cli/chat/userCommandRunner.js +56 -0
  59. package/dist/cli/chat/wizard/providerHandlers.js +19 -2
  60. package/dist/cli/chat/wizardTrail.d.ts +22 -0
  61. package/dist/cli/chat/wizardTrail.js +55 -0
  62. package/dist/cli/commands/chat.d.ts +1 -13
  63. package/dist/cli/commands/chat.js +10 -798
  64. package/dist/cli/commands/commandHelp.js +7 -5
  65. package/dist/cli/commands/commandSuggest.d.ts +2 -0
  66. package/dist/cli/commands/commandSuggest.js +35 -0
  67. package/dist/cli/commands/commands.js +10 -3
  68. package/dist/cli/commands/formatters.d.ts +1 -23
  69. package/dist/cli/commands/formatters.js +3 -252
  70. package/dist/cli/commands/modelCommand.js +11 -7
  71. package/dist/cli/commands/reasoningCommand.js +3 -3
  72. package/dist/cli/commands/runCommand.js +6 -2
  73. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  74. package/dist/cli/commands/streaming/attemptOutcome.js +7 -2
  75. package/dist/cli/commands/streaming/attemptSetup.d.ts +1 -0
  76. package/dist/cli/commands/streaming/attemptSetup.js +26 -2
  77. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
  78. package/dist/cli/commands/streaming/stepProjection.d.ts +59 -0
  79. package/dist/cli/commands/streaming/stepProjection.js +54 -0
  80. package/dist/cli/commands/streaming/streamLoop.js +31 -23
  81. package/dist/cli/commands/streaming/toolGroupRenderer.js +1 -1
  82. package/dist/cli/commands/streaming/toolPartHandlers.js +1 -1
  83. package/dist/cli/commands/streaming.d.ts +3 -1
  84. package/dist/cli/commands/wizardFlow.d.ts +2 -0
  85. package/dist/cli/commands/wizardFlow.js +3 -0
  86. package/dist/cli/index.js +8 -4
  87. package/dist/cli/terminalTitle.js +9 -3
  88. package/dist/config/contextFiles.d.ts +2 -5
  89. package/dist/config/contextFiles.js +1 -1
  90. package/dist/config/inputHistory.js +2 -2
  91. package/dist/config/providerAuth.js +2 -2
  92. package/dist/config/providerModelFacts.js +5 -0
  93. package/dist/config/providerPresets.js +1 -1
  94. package/dist/config/settings.d.ts +7 -0
  95. package/dist/config/settings.js +9 -2
  96. package/dist/config/updateCheck.js +2 -2
  97. package/dist/core/agent/completionController.d.ts +1 -1
  98. package/dist/core/agent/contextBudget.d.ts +1 -1
  99. package/dist/core/agent/goalPolicy.js +8 -2
  100. package/dist/core/agent/overflow.js +5 -0
  101. package/dist/core/agent/toolCapabilities.js +14 -0
  102. package/dist/core/agent/userCommands.d.ts +53 -0
  103. package/dist/core/agent/userCommands.js +116 -0
  104. package/dist/core/agent/workState.d.ts +3 -1
  105. package/dist/core/agent/workState.js +57 -26
  106. package/dist/core/contextFileTypes.d.ts +12 -0
  107. package/dist/core/contextFileTypes.js +1 -0
  108. package/dist/core/graph/buildGraph.js +1 -1
  109. package/dist/core/graph/store.js +1 -1
  110. package/dist/core/limits.d.ts +2 -0
  111. package/dist/core/limits.js +2 -0
  112. package/dist/core/log/llmLog.js +2 -2
  113. package/dist/{config → core/persistence}/privateStorage.js +1 -1
  114. package/dist/core/process/runBoundedProcess.d.ts +7 -4
  115. package/dist/core/process/runBoundedProcess.js +10 -5
  116. package/dist/core/safety/redaction.d.ts +2 -0
  117. package/dist/core/safety/redaction.js +26 -5
  118. package/dist/core/safety/secretPaths.js +12 -3
  119. package/dist/core/safety/urlGuard.js +2 -0
  120. package/dist/core/session/sessionStore.d.ts +8 -1
  121. package/dist/core/session/sessionStore.js +15 -4
  122. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  123. package/dist/core/shellOutput/types.d.ts +1 -1
  124. package/dist/{llm → core}/toolResultTypes.d.ts +1 -1
  125. package/dist/core/validation/outputParser.d.ts +1 -1
  126. package/dist/llm/hazeTools.js +2 -0
  127. package/dist/llm/lsp/pool.js +1 -1
  128. package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
  129. package/dist/llm/requestContext.d.ts +3 -0
  130. package/dist/llm/requestContext.js +20 -8
  131. package/dist/llm/systemPrompt.js +10 -3
  132. package/dist/llm/toolGroups.d.ts +534 -0
  133. package/dist/llm/toolGroups.js +57 -0
  134. package/dist/llm/tools/editMatch.d.ts +1 -1
  135. package/dist/llm/tools/failures.d.ts +1 -1
  136. package/dist/llm/tools/fileToolShared.d.ts +1 -1
  137. package/dist/llm/tools/fileToolShared.js +1 -1
  138. package/dist/llm/tools/fileTools.js +1 -1
  139. package/dist/llm/tools/gitTools.d.ts +12 -0
  140. package/dist/llm/tools/gitTools.js +527 -0
  141. package/dist/llm/tools/readRecovery.d.ts +1 -1
  142. package/dist/llm/tools/replaceInFiles.d.ts +1 -1
  143. package/dist/llm/tools/replaceInFiles.js +1 -1
  144. package/dist/llm/tools/taskTool.js +4 -1
  145. package/dist/llm/tools/toolContext.js +5 -2
  146. package/dist/llm/tools/toolContextState.d.ts +1 -1
  147. package/dist/llm/tools/workspaceFile.d.ts +2 -2
  148. package/dist/llm/tools/workspaceFile.js +10 -5
  149. package/dist/skills/SkillRegistry.js +1 -1
  150. package/dist/skills/builder/SkillBuilder.js +1 -1
  151. package/dist/skills/plugins/installer.js +1 -1
  152. package/dist/skills/plugins/runtime.js +1 -1
  153. package/dist/ui/components/MarkdownText.d.ts +14 -0
  154. package/dist/ui/components/MarkdownText.js +77 -12
  155. package/dist/ui/components/NativeIndicators.js +5 -1
  156. package/dist/ui/components/StreamingMarkdownText.d.ts +3 -1
  157. package/dist/ui/components/StreamingMarkdownText.js +39 -11
  158. package/dist/ui/components/TextInput.d.ts +1 -2
  159. package/dist/ui/components/TextInput.js +79 -9
  160. package/dist/ui/components/WizardChoices.d.ts +1 -2
  161. package/dist/ui/components/useInputSuggestions.d.ts +1 -1
  162. package/dist/ui/components/useInputSuggestions.js +1 -1
  163. package/dist/ui/mentionDetection.d.ts +20 -0
  164. package/dist/ui/mentionDetection.js +24 -0
  165. package/dist/ui/terminalColors.d.ts +4 -4
  166. package/dist/ui/terminalColors.js +23 -6
  167. package/dist/ui/terminalSanitize.js +8 -3
  168. package/dist/ui/textGeometry.d.ts +2 -0
  169. package/dist/ui/textGeometry.js +6 -0
  170. package/dist/ui/themes/registry.js +33 -33
  171. package/dist/utils/openPath.js +7 -0
  172. package/package.json +13 -13
  173. /package/dist/{llm/tools → core/ignore}/gitIgnore.d.ts +0 -0
  174. /package/dist/{llm/tools → core/ignore}/gitIgnore.js +0 -0
  175. /package/dist/{config → core}/paths.d.ts +0 -0
  176. /package/dist/{config → core}/paths.js +0 -0
  177. /package/dist/{config → core/persistence}/privateStorage.d.ts +0 -0
  178. /package/dist/{llm → core}/toolResultTypes.js +0 -0
@@ -0,0 +1,268 @@
1
+ import { stripTerminalControlSequences } from '../../ui/terminalSanitize.js';
2
+ /**
3
+ * Pure one-line builders for tool calls, tool results and the busy label
4
+ * (compact, toolCallSummary, toolResultSummary, busyToolLabel): the transcript
5
+ * vocabulary shared by commands/formatters.ts (which re-exports them) and by
6
+ * the turn engine under commands/streaming/, which records them into display
7
+ * state while a step runs (ARCH-03).
8
+ */
9
+ export function compact(value, maxLength = 180) {
10
+ let text;
11
+ if (value instanceof Error) {
12
+ text = value.message;
13
+ }
14
+ else if (typeof value === 'string') {
15
+ text = value;
16
+ }
17
+ else {
18
+ text = JSON.stringify(value, (_key, nestedValue) => nestedValue instanceof Error ? nestedValue.message : nestedValue);
19
+ }
20
+ if (!text)
21
+ return value === null ? 'null' : value === undefined ? 'undefined' : '';
22
+ if (text === '{}')
23
+ return ''; // empty object: nothing useful to render; avoid "[object Object]"
24
+ return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text;
25
+ }
26
+ /**
27
+ * One-line summary of a tool call for the transcript rows. Wraps the raw
28
+ * builder: paths, patterns, and commands are model/repo-derived, so terminal
29
+ * control sequences are stripped at this sink (HZA-3).
30
+ */
31
+ export function toolCallSummary(toolName, input) {
32
+ return stripTerminalControlSequences(toolCallSummaryText(toolName, input));
33
+ }
34
+ function toolCallSummaryText(toolName, input) {
35
+ const data = input;
36
+ if (toolName === 'shell' && typeof data?.command === 'string') {
37
+ const mode = data.background === true ? ' (background)' : typeof data.timeoutSeconds === 'number' ? ` (timeout ${data.timeoutSeconds}s)` : '';
38
+ return `shell $ ${data.command}${mode}`;
39
+ }
40
+ if (toolName === 'process' && typeof data?.action === 'string')
41
+ return `process ${data.action}${typeof data.backgroundId === 'string' ? ` ${data.backgroundId}` : ''}`;
42
+ if (toolName.startsWith('git')) {
43
+ const detail = typeof data?.path === 'string' && data.path !== '.' ? ` ${data.path}`
44
+ : typeof data?.range === 'string' ? ` ${data.range}`
45
+ : toolName === 'gitBranchManage' && typeof data?.action === 'string' && typeof data?.name === 'string' ? ` ${data.action} ${data.name}`
46
+ : toolName === 'gitCommit' && typeof data?.message === 'string' ? ` "${compact(data.message, 60)}"`
47
+ : toolName === 'gitStage' && Array.isArray(data?.paths) ? ` ${data.paths.join(', ')}`
48
+ : '';
49
+ return `${toolName}${detail}`;
50
+ }
51
+ if (toolName === 'grep' && typeof data?.pattern === 'string') {
52
+ const path = typeof data.path === 'string' && data.path !== '.' ? ` in ${data.path}` : '';
53
+ const glob = typeof data.glob === 'string' ? ` (${data.glob})` : '';
54
+ return `grep "${data.pattern}"${path}${glob}`;
55
+ }
56
+ if (toolName === 'listFiles' && typeof data?.path === 'string')
57
+ return `listFiles ${data.path}`;
58
+ if ((toolName === 'readFile' || toolName === 'writeFile')) {
59
+ if (typeof data?.path === 'string')
60
+ return `${toolName} ${data.path}`;
61
+ if (data == null || (typeof data === 'object' && Object.keys(data).length === 0))
62
+ return toolName; // input not yet streamed (tool-input-start) or empty
63
+ }
64
+ if (toolName === 'editFile' && typeof data?.path === 'string') {
65
+ const edits = Array.isArray(data.edits) ? ` (${data.edits.length} edit${data.edits.length === 1 ? '' : 's'})` : '';
66
+ return `${toolName} ${data.path}${edits}`;
67
+ }
68
+ if (toolName === 'replaceInFiles' && typeof data?.needle === 'string')
69
+ return `replaceInFiles "${compact(data.needle, 60)}"${typeof data.path === 'string' && data.path !== '.' ? ` in ${data.path}` : ''}${data.dryRun === false ? '' : ' (dry run)'}`;
70
+ if (toolName === 'replaceLines' && typeof data?.path === 'string')
71
+ return `replaceLines ${data.path}:${data.startLine}-${data.endLine}`;
72
+ if ((toolName === 'editFile' || toolName === 'replaceInFiles' || toolName === 'replaceLines') && (data == null || (typeof data === 'object' && Object.keys(data).length === 0)))
73
+ return toolName;
74
+ if (toolName === 'subagent') {
75
+ const task = typeof data?.objective === 'string' ? data.objective : typeof data?.task === 'string' ? data.task : undefined;
76
+ if (task) {
77
+ const taskPreview = task.length > 60 ? `${task.slice(0, 60).trimEnd()}…` : task;
78
+ return `subagent "${taskPreview}"`;
79
+ }
80
+ }
81
+ if (toolName === 'writeTasks') {
82
+ const tasks = Array.isArray(data?.tasks) ? data.tasks : [];
83
+ return `writeTasks (${tasks.length} task${tasks.length === 1 ? '' : 's'})`;
84
+ }
85
+ if (toolName === 'lspWorkspaceSymbols' && typeof data?.query === 'string')
86
+ return `lspWorkspaceSymbols "${data.query}"`;
87
+ if (toolName === 'lspSymbols' && typeof data?.path === 'string')
88
+ return `lspSymbols ${data.path}`;
89
+ if ((toolName === 'lspFindSymbol' || toolName === 'lspRenameSymbol' || toolName === 'lspSafeDeleteSymbol' || toolName === 'lspDiagnosticsForSymbol') && typeof data?.namePath === 'string')
90
+ return `${toolName} ${typeof data.path === 'string' ? `${data.path}:` : ''}${data.namePath}`;
91
+ if (toolName === 'lspDiagnostics' && typeof data?.path === 'string')
92
+ return `lspDiagnostics ${data.path}`;
93
+ if ((toolName === 'lspDefinition' || toolName === 'lspTypeDefinition' || toolName === 'lspImplementation' || toolName === 'lspReferences') && typeof data?.path === 'string')
94
+ return `${toolName} ${data.path}:${data.line}:${data.column}`;
95
+ if (toolName === 'graphQuery' && typeof data?.question === 'string')
96
+ return `map: query "${compact(data.question, 60)}"`;
97
+ if ((toolName === 'graphExplain' || toolName === 'graphAffected') && typeof data?.symbol === 'string')
98
+ return `map: ${toolName === 'graphExplain' ? 'explain' : 'affected'} ${data.symbol}`;
99
+ if (toolName === 'graphPath' && typeof data?.from === 'string' && typeof data?.to === 'string')
100
+ return `map: path ${data.from} -> ${data.to}`;
101
+ if (toolName === 'graphRebuild')
102
+ return 'map: rebuild';
103
+ return `${toolName} ${compact(input)}`;
104
+ }
105
+ /**
106
+ * One-line summary of a tool result for the transcript rows; same terminal
107
+ * control-sequence sink discipline as `toolCallSummary` (HZA-3).
108
+ */
109
+ export function toolResultSummary(event) {
110
+ return stripTerminalControlSequences(toolResultSummaryText(event));
111
+ }
112
+ function toolResultSummaryText(event) {
113
+ const output = event.output;
114
+ if (!event.success)
115
+ return `failed: ${compact(event.error ?? output?.error ?? event.output)}`;
116
+ if (output?.duplicateSkipped === true)
117
+ return 'skipped duplicate';
118
+ if (output?.background === true && typeof output.backgroundId === 'string') {
119
+ return `⏵ ${output.backgroundId} ${compact(output.command, 80)}${typeof output.pid === 'number' ? ` (pid ${output.pid})` : ''}`;
120
+ }
121
+ if (typeof output?.totalMatches === 'number') {
122
+ const count = output.totalMatches;
123
+ return count === 0 ? 'no matches' : `${output.matchCountIsLowerBound === true ? 'at least ' : ''}${count} match${count === 1 ? '' : 'es'}`;
124
+ }
125
+ if (typeof output?.validationSummary === 'object' && output.validationSummary != null && 'summaryText' in output.validationSummary) {
126
+ const summary = output.validationSummary;
127
+ const next = typeof summary.suggestedNextStep === 'string' ? `; next: ${summary.suggestedNextStep}` : '';
128
+ return `${String(summary.summaryText)}${next}`;
129
+ }
130
+ if (typeof output?.code === 'number') {
131
+ const risk = typeof output.classification?.riskLevel === 'string'
132
+ ? ` (${output.classification.riskLevel})`
133
+ : '';
134
+ return `exited with code ${output.code}${risk}`;
135
+ }
136
+ const resultOutput = output ?? {};
137
+ const capsule = typeof resultOutput.capsule === 'object' && resultOutput.capsule != null ? resultOutput.capsule : undefined;
138
+ if (capsule && typeof capsule.termination === 'string' && typeof capsule.deliverable === 'string') {
139
+ const summary = capsule.deliverable.split('\n')[0] ?? '';
140
+ const preview = summary.length > 120 ? `${summary.slice(0, 120).trimEnd()}…` : summary;
141
+ const telemetry = typeof resultOutput.telemetry === 'object' && resultOutput.telemetry != null ? resultOutput.telemetry : undefined;
142
+ const calls = typeof telemetry?.toolCallCount === 'number' ? telemetry.toolCallCount : typeof resultOutput.toolCallCount === 'number' ? resultOutput.toolCallCount : 0;
143
+ const durationMs = typeof telemetry?.durationMs === 'number' ? telemetry.durationMs : resultOutput.durationMs;
144
+ const duration = typeof durationMs === 'number' ? ` in ${(durationMs / 1000).toFixed(1)}s` : '';
145
+ const meta = calls > 0 ? ` (${calls} call${calls === 1 ? '' : 's'}${duration})` : '';
146
+ return `${capsule.termination}${capsule.usable === false ? ' · unusable' : ''}${capsule.truncated === true ? ' · truncated' : ''}${meta}: ${preview}`;
147
+ }
148
+ if (typeof output?.status === 'string' && typeof output?.summary === 'string') {
149
+ const summary = output.summary.split('\n')[0] ?? '';
150
+ const preview = summary.length > 120 ? `${summary.slice(0, 120).trimEnd()}…` : summary;
151
+ const calls = typeof output.toolCallCount === 'number' ? output.toolCallCount : output.toolCalls?.length ?? 0;
152
+ const duration = typeof output.durationMs === 'number' ? ` in ${(output.durationMs / 1000).toFixed(1)}s` : '';
153
+ const meta = calls > 0 ? ` (${calls} call${calls === 1 ? '' : 's'}${duration})` : '';
154
+ return `${output.status}${meta}: ${preview}`;
155
+ }
156
+ if (typeof output?.server === 'string' && Array.isArray(output.symbols)) {
157
+ const count = output.symbols.length;
158
+ return `${count} symbol${count === 1 ? '' : 's'} from ${output.server}`;
159
+ }
160
+ if (typeof output?.server === 'string' && Array.isArray(output.locations)) {
161
+ const count = output.locations.length;
162
+ return `${count} location${count === 1 ? '' : 's'} from ${output.server}`;
163
+ }
164
+ if (typeof output?.answer === 'string' && typeof output?.graph === 'object') {
165
+ // graphQuery/graphPath answers
166
+ const stale = output.graph.stale === true ? ' · stale graph' : '';
167
+ const seeds = typeof output.seeds === 'number' ? `${output.seeds} seed${output.seeds === 1 ? '' : 's'}` : typeof output.hops === 'number' ? `${output.hops} hop${output.hops === 1 ? '' : 's'}` : '';
168
+ return `${seeds}${stale}: ${compact(output.answer, 120)}`;
169
+ }
170
+ if (Array.isArray(output?.affected) && typeof output.symbol === 'string') {
171
+ const count = output.affected.length;
172
+ return count === 0 ? `no reverse relationships for ${output.symbol}` : `${count} affected by ${output.symbol}`;
173
+ }
174
+ if (typeof output?.nodes === 'number' && typeof output?.edges === 'number' && output?.toolName === 'graphRebuild') {
175
+ return `graph built: ${output.nodes} nodes · ${output.edges} edges · ${output.files} files`;
176
+ }
177
+ if (typeof output?.ok === 'boolean') {
178
+ // writeTasks result
179
+ if (output.ok && typeof output.summary === 'string') {
180
+ return compact(output.summary, 120);
181
+ }
182
+ if (output.ok) {
183
+ if (output.noChange === true)
184
+ return 'No changes made';
185
+ if (typeof output.addedLines === 'number' || typeof output.removedLines === 'number') {
186
+ const added = typeof output.addedLines === 'number' ? output.addedLines : 0;
187
+ const removed = typeof output.removedLines === 'number' ? output.removedLines : 0;
188
+ return `Added ${added} line${added === 1 ? '' : 's'}, removed ${removed} line${removed === 1 ? '' : 's'}`;
189
+ }
190
+ return 'completed';
191
+ }
192
+ if (output.reasonCode === 'secret_file_protected' || output.reasonCode === 'git_internals_protected') {
193
+ // Protection events are visible but distinct from ordinary failures so
194
+ // the developer can audit them at a glance; never print file contents.
195
+ const protectedPath = typeof output.path === 'string' && output.path ? ` (${compact(output.path, 80)})` : '';
196
+ const kind = output.reasonCode === 'secret_file_protected' ? 'protected secret file' : 'protected git internals';
197
+ return `blocked: ${kind}${protectedPath}`;
198
+ }
199
+ const reason = typeof output.reasonCode === 'string' ? ` (${output.reasonCode})` : '';
200
+ return typeof output.error === 'string' ? `failed${reason}: ${compact(output.error)}` : `failed${reason}`;
201
+ }
202
+ return 'completed';
203
+ }
204
+ /**
205
+ * The short head of a shell command for the busy label: the program plus its
206
+ * first non-flag argument ("git diff", "npm test") — enough to identify the
207
+ * action without echoing the full (possibly long or sensitive) command line.
208
+ */
209
+ function commandHead(command) {
210
+ const parts = command.trim().split(/\s+/);
211
+ const head = [parts[0]];
212
+ for (const part of parts.slice(1)) {
213
+ if (part.startsWith('-'))
214
+ continue;
215
+ head.push(part);
216
+ break;
217
+ }
218
+ return compact(head.filter(Boolean).join(' '), 80);
219
+ }
220
+ /**
221
+ * A short, human label for the live busy indicator while a tool is running,
222
+ * e.g. "Running npm test", "Reading src/foo.ts", "Searching".
223
+ * Lets the developer see *what* is happening, not just that something is.
224
+ */
225
+ export function busyToolLabel(toolName, input) {
226
+ const data = input;
227
+ const pathLabel = typeof data?.path === 'string' ? compact(data.path, 80) : undefined;
228
+ switch (toolName) {
229
+ case 'shell':
230
+ if (data?.background === true)
231
+ return 'Starting background process';
232
+ return typeof data?.command === 'string' && data.command ? `Running ${commandHead(data.command)}` : 'Running command';
233
+ case 'process':
234
+ return 'Managing background process';
235
+ case 'grep':
236
+ return 'Searching';
237
+ case 'listFiles':
238
+ return 'Listing files';
239
+ case 'readFile':
240
+ return pathLabel ? `Reading ${pathLabel}` : 'Reading file';
241
+ case 'writeFile':
242
+ return pathLabel ? `Writing ${pathLabel}` : 'Writing file';
243
+ case 'editFile':
244
+ case 'replaceLines':
245
+ return pathLabel ? `Editing ${pathLabel}` : 'Editing file';
246
+ case 'fetch':
247
+ return 'Fetching URL';
248
+ case 'subagent':
249
+ return 'Running subagent';
250
+ case 'writeTasks':
251
+ return 'Updating tasks';
252
+ case 'graphQuery':
253
+ case 'graphExplain':
254
+ case 'graphPath':
255
+ case 'graphAffected':
256
+ return 'Querying code graph';
257
+ case 'graphRebuild':
258
+ return 'Building code graph';
259
+ case 'skill':
260
+ return 'Loading skill';
261
+ default:
262
+ if (toolName.startsWith('lsp'))
263
+ return 'Querying LSP';
264
+ if (toolName.startsWith('mcp'))
265
+ return 'Running MCP tool';
266
+ return `Running ${toolName}`;
267
+ }
268
+ }
@@ -1,5 +1,13 @@
1
1
  import type { Task } from '../../core/tasks/taskStorage.js';
2
2
  import type { TokenUsage } from '../commands/streaming/turnRuntime.js';
3
3
  export declare const EMPTY_TOKEN_USAGE: TokenUsage;
4
+ /** What the status bar knows about context: the model's window and the last provider-measured request size. */
5
+ export interface ContextUsage {
6
+ windowTokens: number | undefined;
7
+ usedTokens: number | undefined;
8
+ /** `usedTokens` is a chars/4 estimate because no provider usage exists yet. */
9
+ estimated: boolean;
10
+ }
11
+ export declare const EMPTY_CONTEXT_USAGE: ContextUsage;
4
12
  export declare function shouldClearCompletedTasks(tasks: Task[]): boolean;
5
13
  export declare function accumulateTokenUsage(current: TokenUsage, usage: TokenUsage): TokenUsage;
@@ -1,4 +1,5 @@
1
1
  export const EMPTY_TOKEN_USAGE = { inputTokens: undefined, outputTokens: undefined, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: 0, reasoningTokens: 0, logicalInputEstimate: 0, effectiveNonCachedInput: undefined };
2
+ export const EMPTY_CONTEXT_USAGE = { windowTokens: undefined, usedTokens: undefined, estimated: false };
2
3
  export function shouldClearCompletedTasks(tasks) {
3
4
  return tasks.length > 0 && tasks.every(task => task.status === 'completed');
4
5
  }
@@ -0,0 +1,21 @@
1
+ import type { ChatScreenDeps } from './screenDeps.js';
2
+ export declare const NO_USER_COMMAND_MESSAGE = "No command given after \"!\".";
3
+ /**
4
+ * Run one user command (`! <command>`) end to end: busy label, cancel wiring,
5
+ * transcript row, durable conversation record, one model turn over the output
6
+ * (skipped when the user cancelled), then the follow-up queue drain (the
7
+ * existing drain only runs after agent turns). The screen stays busy from the
8
+ * run through the record flush until the model turn owns it, so a submit in
9
+ * that window queues instead of starting a concurrent turn.
10
+ */
11
+ export declare function runUserCommandLine(deps: ChatScreenDeps, command: string): Promise<void>;
12
+ /**
13
+ * Route one queued line: a `!` command runs as a user command, `\!` loses its
14
+ * backslash, anything else is returned unchanged for the normal agent path.
15
+ */
16
+ export declare function routeQueuedLine(deps: ChatScreenDeps, line: string): Promise<{
17
+ handled: true;
18
+ } | {
19
+ handled: false;
20
+ value: string;
21
+ }>;
@@ -0,0 +1,66 @@
1
+ import { formatUserCommandRecord, parseUserInputLine, USER_COMMAND_RESPONSE_REQUEST, userCommandHead, userCommandTranscriptText } from '../../core/agent/userCommands.js';
2
+ import { runUserCommand } from './userCommandRunner.js';
3
+ export const NO_USER_COMMAND_MESSAGE = 'No command given after "!".';
4
+ /**
5
+ * Run one user command (`! <command>`) end to end: busy label, cancel wiring,
6
+ * transcript row, durable conversation record, one model turn over the output
7
+ * (skipped when the user cancelled), then the follow-up queue drain (the
8
+ * existing drain only runs after agent turns). The screen stays busy from the
9
+ * run through the record flush until the model turn owns it, so a submit in
10
+ * that window queues instead of starting a concurrent turn.
11
+ */
12
+ export async function runUserCommandLine(deps, command) {
13
+ if (deps.stoppingRef.current)
14
+ return;
15
+ const controller = new AbortController();
16
+ const startedAt = Date.now();
17
+ // Esc cancels through the shared abort ref (cancelThinking).
18
+ deps.abortControllerRef.current = controller;
19
+ deps.setBusyLabel(`! ${userCommandHead(command)}`);
20
+ deps.setBusy(true);
21
+ try {
22
+ let run;
23
+ try {
24
+ run = await runUserCommand({ command, signal: controller.signal });
25
+ }
26
+ finally {
27
+ deps.abortControllerRef.current = null;
28
+ }
29
+ if (deps.sealedRef.current)
30
+ return;
31
+ deps.finalizeMessage({ role: 'tool', text: userCommandTranscriptText(run), startedAt, finishedAt: Date.now() });
32
+ deps.conversationRef.current = [...deps.conversationRef.current, { role: 'user', content: formatUserCommandRecord(run) }];
33
+ deps.sessionRecorderRef.current?.recordConversation(deps.conversationRef.current);
34
+ await deps.sessionRecorderRef.current?.flush().catch(deps.showPersistenceWarning);
35
+ if (run.status !== 'cancelled' && !deps.stoppingRef.current && !deps.sealedRef.current) {
36
+ await deps.doAgentTurn(USER_COMMAND_RESPONSE_REQUEST, `! ${userCommandHead(command)}`);
37
+ }
38
+ }
39
+ finally {
40
+ // The turn clears its own busy state; this covers the skipped and failed paths.
41
+ deps.setBusy(false);
42
+ }
43
+ for (let next = deps.followUps.takeNext(); !deps.stoppingRef.current && next !== undefined; next = deps.followUps.takeNext()) {
44
+ const routed = await routeQueuedLine(deps, next);
45
+ if (routed.handled)
46
+ continue;
47
+ const prepared = await deps.prepareUserInput(routed.value);
48
+ if (prepared)
49
+ await deps.doAgentTurn(prepared.value, prepared.displayValue, prepared.options);
50
+ }
51
+ }
52
+ /**
53
+ * Route one queued line: a `!` command runs as a user command, `\!` loses its
54
+ * backslash, anything else is returned unchanged for the normal agent path.
55
+ */
56
+ export async function routeQueuedLine(deps, line) {
57
+ const parsed = parseUserInputLine(line);
58
+ if (parsed.kind === 'command') {
59
+ if (parsed.command)
60
+ await runUserCommandLine(deps, parsed.command);
61
+ else
62
+ deps.setMessages(m => [...m, { role: 'system', text: NO_USER_COMMAND_MESSAGE }]);
63
+ return { handled: true };
64
+ }
65
+ return { handled: false, value: parsed.kind === 'escaped' ? parsed.value : line };
66
+ }
@@ -0,0 +1,14 @@
1
+ import { type UserCommandRun } from '../../core/agent/userCommands.js';
2
+ /**
3
+ * Run one user command (`! <command>`) through the model's `shell` tool, so
4
+ * both paths share one execution, bounds, env cleaning and output reduction.
5
+ * Called outside a turn: there is no tool context, so nothing is deduplicated
6
+ * and the result's validation summary is never observed or recorded. Resolves
7
+ * with a run result instead of throwing.
8
+ */
9
+ export declare function runUserCommand(input: {
10
+ command: string;
11
+ signal?: AbortSignal;
12
+ }): Promise<UserCommandRun>;
13
+ /** Map a `shell` tool result onto the run shape. */
14
+ export declare function toUserCommandRun(result: unknown): UserCommandRun;
@@ -0,0 +1,56 @@
1
+ import { shellTool } from '../../llm/tools/shellTool.js';
2
+ import { userCommandStatus } from '../../core/agent/userCommands.js';
3
+ const CALLER = { toolCallId: 'user-command', messages: [], context: {} };
4
+ const EMPTY_STREAM = { text: '', truncated: false, filtered: false, omittedChars: 0 };
5
+ /**
6
+ * Run one user command (`! <command>`) through the model's `shell` tool, so
7
+ * both paths share one execution, bounds, env cleaning and output reduction.
8
+ * Called outside a turn: there is no tool context, so nothing is deduplicated
9
+ * and the result's validation summary is never observed or recorded. Resolves
10
+ * with a run result instead of throwing.
11
+ */
12
+ export async function runUserCommand(input) {
13
+ try {
14
+ const context = { ...CALLER, ...(input.signal ? { abortSignal: input.signal } : {}) };
15
+ return toUserCommandRun(await shellTool.execute({ command: input.command }, context));
16
+ }
17
+ catch (error) {
18
+ return { command: input.command, status: 'error', exitCode: null, durationMs: 0, stdout: { ...EMPTY_STREAM }, stderr: { ...EMPTY_STREAM }, error: error instanceof Error ? error.message : String(error) };
19
+ }
20
+ }
21
+ /** Map a `shell` tool result onto the run shape. */
22
+ export function toUserCommandRun(result) {
23
+ const tool = record(result);
24
+ if (!tool)
25
+ return { command: '', status: 'error', exitCode: null, durationMs: 0, stdout: { ...EMPTY_STREAM }, stderr: { ...EMPTY_STREAM }, error: 'shell tool returned no result' };
26
+ const stdout = stream(tool.stdout);
27
+ const stderr = stream(tool.stderr);
28
+ const command = typeof tool.command === 'string' ? tool.command : '';
29
+ const code = typeof tool.code === 'number' ? tool.code : null;
30
+ const error = typeof tool.error === 'string' ? tool.error : undefined;
31
+ return {
32
+ command,
33
+ status: userCommandStatus({ code, timedOut: tool.timedOut === true, aborted: tool.aborted === true, ...(error ? { error } : {}) }),
34
+ exitCode: code,
35
+ durationMs: typeof tool?.durationMs === 'number' ? tool.durationMs : 0,
36
+ stdout,
37
+ stderr,
38
+ ...(error ? { error } : {}),
39
+ };
40
+ }
41
+ function record(value) {
42
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
43
+ }
44
+ function stream(value) {
45
+ const candidate = record(value);
46
+ if (!candidate || typeof candidate.text !== 'string')
47
+ return { ...EMPTY_STREAM };
48
+ const handle = [candidate.handle, candidate.rawHandle].find(entry => typeof entry === 'string');
49
+ return {
50
+ text: candidate.text,
51
+ truncated: candidate.truncated === true,
52
+ filtered: false,
53
+ omittedChars: typeof candidate.omittedChars === 'number' ? candidate.omittedChars : 0,
54
+ ...(handle ? { handle: handle } : {}),
55
+ };
56
+ }
@@ -33,6 +33,11 @@ export function createProviderWizardHandlers(deps, ctx) {
33
33
  showMessage('Choose a provider preset, or select "custom" to enter details manually.');
34
34
  return;
35
35
  }
36
+ if (providerName === PROVIDER_CHOICES.later) {
37
+ setMode('chat');
38
+ showMessage('Provider setup skipped. Run /provider any time; a provider is needed before the first turn.');
39
+ return;
40
+ }
36
41
  const provider = findProvider(deps.settings, providerName);
37
42
  if (!provider) {
38
43
  showMessage(`No provider named ${providerName}. Use /provider and choose add provider.`);
@@ -42,7 +47,6 @@ export function createProviderWizardHandlers(deps, ctx) {
42
47
  setSelectedProviderName(provider.name);
43
48
  setMode('providerAction');
44
49
  // Surface canonical-endpoint divergence for ChatGPT sign-in providers up
45
- // front: a hand-edited URL is silently ignored by the Codex fetch (F-14).
46
50
  const divergence = chatgptCodexUrlWarning(provider);
47
51
  showMessage(`${provider.name}: choose an action.${divergence ? `\n${divergence}` : ''}`);
48
52
  }
@@ -415,7 +419,20 @@ export function createProviderWizardHandlers(deps, ctx) {
415
419
  await ctx.applySettings(result.settingsPatch);
416
420
  setSelectedProviderName(undefined);
417
421
  setMode('chat');
418
- showMessage(result.message);
422
+ // UX-05: probe /models with the fresh key so a bad one surfaces now, not
423
+ // at the first turn. The key stays saved either way — the probe is
424
+ // advisory, so a failure only annotates the notice.
425
+ let message = result.message;
426
+ if (result.provider && result.provider.kind !== 'chatgpt-codex') {
427
+ deps.setBusyLabel(`Probing ${result.provider.name} model list`);
428
+ deps.setBusy(true);
429
+ const probe = await discoverProviderModels({ url: result.provider.url, key: result.key });
430
+ deps.setBusy(false);
431
+ message += probe.status === 'ok'
432
+ ? `\nKey works: ${probe.models.length} model${probe.models.length === 1 ? '' : 's'} listed on ${result.provider.name}.`
433
+ : `\nKey saved, but the model-list probe failed (${probe.error}). The key may be wrong — it is kept; fix it with /provider → set API key.`;
434
+ }
435
+ showMessage(message);
419
436
  }
420
437
  async function providerRemoveModelsMode(value) {
421
438
  const result = providerRemoveModels(deps.settings, deps.wizard.selectedProviderName, value);
@@ -0,0 +1,22 @@
1
+ import type { Dispatch, SetStateAction } from 'react';
2
+ import type { Mode } from '../commands/chatModes.js';
3
+ /**
4
+ * Wizard back navigation (UX-03). Every mode change away from a wizard step
5
+ * pushes that step onto a trail, so Esc pops one step (selections and drafts
6
+ * survive because the wizard state is not reset) and only a trail-less wizard
7
+ * step exits to chat. Entering `chat` clears the trail, so a finished flow
8
+ * never leaves a stale path behind.
9
+ */
10
+ export declare function createWizardTrail(): {
11
+ enter(next: Mode): void;
12
+ /** Steps the current step was reached through, oldest first. */
13
+ steps(): readonly Mode[];
14
+ current(): Mode;
15
+ /** Returns the step to return to, or `undefined` at a wizard root. */
16
+ back(): Mode | undefined;
17
+ };
18
+ /** `setMode` wrapper that records the trail, plus the Esc handler's `goBack`. */
19
+ export declare function useWizardNavigation(setModeRaw: Dispatch<SetStateAction<Mode>>): {
20
+ setMode: (action: SetStateAction<Mode>) => void;
21
+ goBack: () => boolean;
22
+ };
@@ -0,0 +1,55 @@
1
+ import { useCallback, useRef } from 'react';
2
+ /**
3
+ * Wizard back navigation (UX-03). Every mode change away from a wizard step
4
+ * pushes that step onto a trail, so Esc pops one step (selections and drafts
5
+ * survive because the wizard state is not reset) and only a trail-less wizard
6
+ * step exits to chat. Entering `chat` clears the trail, so a finished flow
7
+ * never leaves a stale path behind.
8
+ */
9
+ export function createWizardTrail() {
10
+ const trail = [];
11
+ let current = 'chat';
12
+ return {
13
+ enter(next) {
14
+ if (next === 'chat')
15
+ trail.length = 0;
16
+ else if (current !== 'chat' && next !== current)
17
+ trail.push(current);
18
+ current = next;
19
+ },
20
+ /** Steps the current step was reached through, oldest first. */
21
+ steps() {
22
+ return trail;
23
+ },
24
+ current() {
25
+ return current;
26
+ },
27
+ /** Returns the step to return to, or `undefined` at a wizard root. */
28
+ back() {
29
+ const previous = trail.pop();
30
+ if (previous !== undefined)
31
+ current = previous;
32
+ return previous;
33
+ },
34
+ };
35
+ }
36
+ /** `setMode` wrapper that records the trail, plus the Esc handler's `goBack`. */
37
+ export function useWizardNavigation(setModeRaw) {
38
+ const trailRef = useRef(undefined);
39
+ if (!trailRef.current)
40
+ trailRef.current = createWizardTrail();
41
+ const trail = trailRef.current;
42
+ const setMode = useCallback((action) => {
43
+ const next = typeof action === 'function' ? action(trail.current()) : action;
44
+ trail.enter(next);
45
+ setModeRaw(next);
46
+ }, [trail, setModeRaw]);
47
+ const goBack = useCallback(() => {
48
+ const previous = trail.back();
49
+ if (previous === undefined)
50
+ return false;
51
+ setModeRaw(previous);
52
+ return true;
53
+ }, [trail, setModeRaw]);
54
+ return { setMode, goBack };
55
+ }
@@ -1,14 +1,2 @@
1
- interface ChatOptions {
2
- debug?: boolean;
3
- version?: string;
4
- /** Safe build provenance (commit, build time) recorded into session headers. */
5
- build?: {
6
- commit?: string;
7
- builtAt?: string;
8
- };
9
- continueSession?: boolean;
10
- resumeSessionId?: string;
11
- noSession?: boolean;
12
- }
1
+ import { type ChatOptions } from '../chat/ChatScreen.js';
13
2
  export declare function chatCommand(options?: ChatOptions): Promise<void>;
14
- export {};