@denizokcu/haze 1.7.11 → 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 (234) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +142 -102
  3. package/SECURITY.md +1 -1
  4. package/assets/graph-grammars/NOTICE.md +21 -0
  5. package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
  6. package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
  7. package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
  8. package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
  9. package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
  10. package/assets/graph-grammars/web-tree-sitter.js +4056 -0
  11. package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
  12. package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
  13. package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
  14. package/bin/haze.js +47 -19
  15. package/dist/buildInfo.json +3 -3
  16. package/dist/cli/chat/BusyBar.d.ts +1 -2
  17. package/dist/cli/chat/ChatHeader.d.ts +6 -0
  18. package/dist/cli/chat/ChatHeader.js +11 -0
  19. package/dist/cli/chat/ChatScreen.d.ts +16 -0
  20. package/dist/cli/chat/ChatScreen.js +399 -0
  21. package/dist/cli/chat/ChatScreenView.d.ts +68 -0
  22. package/dist/cli/chat/ChatScreenView.js +47 -0
  23. package/dist/cli/chat/LiveTail.d.ts +11 -0
  24. package/dist/cli/chat/LiveTail.js +26 -0
  25. package/dist/cli/chat/TaskBar.d.ts +3 -2
  26. package/dist/cli/chat/TaskBar.js +4 -0
  27. package/dist/cli/chat/agentTurnRunner.d.ts +12 -0
  28. package/dist/cli/chat/agentTurnRunner.js +177 -0
  29. package/dist/cli/chat/busyIndicator.js +9 -5
  30. package/dist/cli/chat/chatMetrics.d.ts +7 -0
  31. package/dist/cli/chat/chatMetrics.js +15 -1
  32. package/dist/cli/chat/chatViewModel.d.ts +85 -0
  33. package/dist/cli/chat/chatViewModel.js +66 -0
  34. package/dist/cli/chat/fileMentionSuggestions.d.ts +0 -14
  35. package/dist/cli/chat/fileMentionSuggestions.js +4 -21
  36. package/dist/cli/chat/inputSuggestions.js +1 -0
  37. package/dist/cli/chat/liveTheme.d.ts +11 -0
  38. package/dist/cli/chat/liveTheme.js +26 -0
  39. package/dist/cli/chat/messageFinalize.d.ts +4 -0
  40. package/dist/cli/chat/messageFinalize.js +8 -0
  41. package/dist/cli/chat/messages.js +1 -1
  42. package/dist/cli/chat/pickerOpeners.d.ts +23 -0
  43. package/dist/cli/chat/pickerOpeners.js +36 -0
  44. package/dist/cli/chat/promptSessionState.d.ts +11 -0
  45. package/dist/cli/chat/promptSessionState.js +39 -0
  46. package/dist/cli/chat/renderMetrics.d.ts +8 -0
  47. package/dist/cli/chat/renderMetrics.js +14 -0
  48. package/dist/cli/chat/resizeGuard.d.ts +11 -0
  49. package/dist/cli/chat/resizeGuard.js +25 -0
  50. package/dist/cli/chat/screenDeps.d.ts +116 -0
  51. package/dist/cli/chat/screenDeps.js +1 -0
  52. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  53. package/dist/cli/chat/sessionLifecycle.js +6 -2
  54. package/dist/cli/chat/sessionRecorder.js +4 -1
  55. package/dist/cli/chat/settingsSelection.d.ts +33 -0
  56. package/dist/cli/chat/settingsSelection.js +46 -0
  57. package/dist/cli/chat/skillNotices.d.ts +18 -0
  58. package/dist/cli/chat/skillNotices.js +26 -0
  59. package/dist/cli/chat/startupInfo.js +1 -1
  60. package/dist/cli/chat/startupSequence.d.ts +2 -0
  61. package/dist/cli/chat/startupSequence.js +6 -0
  62. package/dist/cli/chat/submitPipeline.d.ts +8 -0
  63. package/dist/cli/chat/submitPipeline.js +141 -0
  64. package/dist/cli/chat/terminalControl.js +1 -1
  65. package/dist/cli/chat/toolSummaries.d.ts +29 -0
  66. package/dist/cli/chat/toolSummaries.js +268 -0
  67. package/dist/cli/chat/turnState.d.ts +8 -0
  68. package/dist/cli/chat/turnState.js +1 -0
  69. package/dist/cli/chat/userCommandFlow.d.ts +21 -0
  70. package/dist/cli/chat/userCommandFlow.js +66 -0
  71. package/dist/cli/chat/userCommandRunner.d.ts +14 -0
  72. package/dist/cli/chat/userCommandRunner.js +56 -0
  73. package/dist/cli/chat/wizard/providerHandlers.js +19 -2
  74. package/dist/cli/chat/wizardTrail.d.ts +22 -0
  75. package/dist/cli/chat/wizardTrail.js +55 -0
  76. package/dist/cli/commands/chat.d.ts +1 -13
  77. package/dist/cli/commands/chat.js +10 -795
  78. package/dist/cli/commands/commandHelp.js +11 -6
  79. package/dist/cli/commands/commandSuggest.d.ts +2 -0
  80. package/dist/cli/commands/commandSuggest.js +35 -0
  81. package/dist/cli/commands/commands.js +12 -3
  82. package/dist/cli/commands/formatters.d.ts +1 -23
  83. package/dist/cli/commands/formatters.js +3 -224
  84. package/dist/cli/commands/graphCommand.d.ts +2 -0
  85. package/dist/cli/commands/graphCommand.js +60 -0
  86. package/dist/cli/commands/initCommand.js +14 -0
  87. package/dist/cli/commands/modelCommand.js +11 -7
  88. package/dist/cli/commands/reasoningCommand.js +3 -3
  89. package/dist/cli/commands/runCommand.js +6 -2
  90. package/dist/cli/commands/streaming/agentAttempt.js +11 -1
  91. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  92. package/dist/cli/commands/streaming/attemptOutcome.js +8 -3
  93. package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
  94. package/dist/cli/commands/streaming/attemptSetup.js +34 -5
  95. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
  96. package/dist/cli/commands/streaming/goalSupervisor.js +5 -3
  97. package/dist/cli/commands/streaming/prepareStep.js +1 -0
  98. package/dist/cli/commands/streaming/stepProjection.d.ts +59 -0
  99. package/dist/cli/commands/streaming/stepProjection.js +54 -0
  100. package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
  101. package/dist/cli/commands/streaming/streamLoop.js +34 -23
  102. package/dist/cli/commands/streaming/toolGroupRenderer.js +1 -1
  103. package/dist/cli/commands/streaming/toolPartHandlers.js +8 -2
  104. package/dist/cli/commands/streaming.d.ts +3 -1
  105. package/dist/cli/commands/streaming.js +5 -0
  106. package/dist/cli/commands/wizardFlow.d.ts +2 -0
  107. package/dist/cli/commands/wizardFlow.js +3 -0
  108. package/dist/cli/index.js +8 -4
  109. package/dist/cli/terminalTitle.js +9 -3
  110. package/dist/config/contextFiles.d.ts +2 -5
  111. package/dist/config/contextFiles.js +1 -1
  112. package/dist/config/inputHistory.js +2 -2
  113. package/dist/config/providerAuth.js +2 -2
  114. package/dist/config/providerModelFacts.js +5 -0
  115. package/dist/config/providerPresets.js +1 -1
  116. package/dist/config/settings.d.ts +7 -0
  117. package/dist/config/settings.js +9 -2
  118. package/dist/config/updateCheck.js +2 -2
  119. package/dist/core/agent/compaction.d.ts +1 -0
  120. package/dist/core/agent/compaction.js +3 -0
  121. package/dist/core/agent/completionController.d.ts +1 -1
  122. package/dist/core/agent/contextBudget.d.ts +1 -1
  123. package/dist/core/agent/goalPolicy.js +8 -2
  124. package/dist/core/agent/overflow.js +5 -0
  125. package/dist/core/agent/toolCapabilities.js +14 -0
  126. package/dist/core/agent/userCommands.d.ts +53 -0
  127. package/dist/core/agent/userCommands.js +116 -0
  128. package/dist/core/agent/workState.d.ts +3 -1
  129. package/dist/core/agent/workState.js +57 -26
  130. package/dist/core/contextFileTypes.d.ts +12 -0
  131. package/dist/core/contextFileTypes.js +1 -0
  132. package/dist/core/graph/analyze.d.ts +61 -0
  133. package/dist/core/graph/analyze.js +274 -0
  134. package/dist/core/graph/buildGraph.d.ts +44 -0
  135. package/dist/core/graph/buildGraph.js +290 -0
  136. package/dist/core/graph/digest.d.ts +2 -0
  137. package/dist/core/graph/digest.js +40 -0
  138. package/dist/core/graph/extract.d.ts +58 -0
  139. package/dist/core/graph/extract.js +394 -0
  140. package/dist/core/graph/model.d.ts +63 -0
  141. package/dist/core/graph/model.js +96 -0
  142. package/dist/core/graph/query.d.ts +69 -0
  143. package/dist/core/graph/query.js +391 -0
  144. package/dist/core/graph/store.d.ts +64 -0
  145. package/dist/core/graph/store.js +171 -0
  146. package/dist/core/limits.d.ts +2 -0
  147. package/dist/core/limits.js +2 -0
  148. package/dist/core/log/llmLog.js +2 -2
  149. package/dist/{config → core/persistence}/privateStorage.js +1 -1
  150. package/dist/core/process/runBoundedProcess.d.ts +7 -4
  151. package/dist/core/process/runBoundedProcess.js +22 -11
  152. package/dist/core/safety/redaction.d.ts +2 -0
  153. package/dist/core/safety/redaction.js +26 -5
  154. package/dist/core/safety/secretPaths.js +12 -3
  155. package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
  156. package/dist/core/safety/untrustedEnvelopes.js +17 -2
  157. package/dist/core/safety/urlGuard.js +2 -0
  158. package/dist/core/session/sessionStore.d.ts +8 -1
  159. package/dist/core/session/sessionStore.js +15 -4
  160. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  161. package/dist/core/shellOutput/types.d.ts +1 -1
  162. package/dist/core/subagent/executionProfiles.js +4 -4
  163. package/dist/core/tasks/taskStorage.js +11 -1
  164. package/dist/{llm → core}/toolResultTypes.d.ts +1 -1
  165. package/dist/core/validation/outputParser.d.ts +1 -1
  166. package/dist/core/validation/outputParser.js +16 -8
  167. package/dist/llm/hazeTools.d.ts +2 -12426
  168. package/dist/llm/hazeTools.js +4 -0
  169. package/dist/llm/lsp/pool.js +1 -1
  170. package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
  171. package/dist/llm/lspTools.d.ts +3 -12622
  172. package/dist/llm/requestContext.d.ts +6 -0
  173. package/dist/llm/requestContext.js +28 -7
  174. package/dist/llm/subagentRunner.d.ts +2 -308
  175. package/dist/llm/systemPrompt.js +17 -7
  176. package/dist/llm/toolGroups.d.ts +534 -0
  177. package/dist/llm/toolGroups.js +57 -0
  178. package/dist/llm/tools/editMatch.d.ts +1 -1
  179. package/dist/llm/tools/failures.d.ts +1 -1
  180. package/dist/llm/tools/fetchTool.d.ts +2 -1221
  181. package/dist/llm/tools/fileToolShared.d.ts +1 -1
  182. package/dist/llm/tools/fileToolShared.js +1 -1
  183. package/dist/llm/tools/fileTools.d.ts +2 -7768
  184. package/dist/llm/tools/fileTools.js +1 -1
  185. package/dist/llm/tools/gitTools.d.ts +12 -0
  186. package/dist/llm/tools/gitTools.js +527 -0
  187. package/dist/llm/tools/graphAdvisory.d.ts +22 -0
  188. package/dist/llm/tools/graphAdvisory.js +68 -0
  189. package/dist/llm/tools/graphTools.d.ts +13 -0
  190. package/dist/llm/tools/graphTools.js +195 -0
  191. package/dist/llm/tools/processTool.d.ts +2 -1081
  192. package/dist/llm/tools/readRecovery.d.ts +1 -1
  193. package/dist/llm/tools/replaceInFiles.d.ts +1 -1
  194. package/dist/llm/tools/replaceInFiles.js +1 -1
  195. package/dist/llm/tools/shellTool.d.ts +2 -1513
  196. package/dist/llm/tools/storedOutputTool.d.ts +2 -355
  197. package/dist/llm/tools/taskTool.d.ts +2 -489
  198. package/dist/llm/tools/taskTool.js +4 -1
  199. package/dist/llm/tools/toolContext.js +29 -11
  200. package/dist/llm/tools/toolContextState.d.ts +4 -1
  201. package/dist/llm/tools/toolContextState.js +2 -1
  202. package/dist/llm/tools/workspaceFile.d.ts +2 -2
  203. package/dist/llm/tools/workspaceFile.js +10 -5
  204. package/dist/skills/SkillRegistry.js +1 -1
  205. package/dist/skills/builder/SkillBuilder.js +1 -1
  206. package/dist/skills/plugins/installer.js +1 -1
  207. package/dist/skills/plugins/runtime.js +1 -1
  208. package/dist/skills/skillTools.js +4 -1
  209. package/dist/ui/components/MarkdownText.d.ts +14 -0
  210. package/dist/ui/components/MarkdownText.js +77 -12
  211. package/dist/ui/components/NativeIndicators.js +5 -1
  212. package/dist/ui/components/StreamingMarkdownText.d.ts +3 -1
  213. package/dist/ui/components/StreamingMarkdownText.js +39 -11
  214. package/dist/ui/components/TextInput.d.ts +1 -2
  215. package/dist/ui/components/TextInput.js +79 -9
  216. package/dist/ui/components/WizardChoices.d.ts +1 -2
  217. package/dist/ui/components/useInputSuggestions.d.ts +1 -1
  218. package/dist/ui/components/useInputSuggestions.js +1 -1
  219. package/dist/ui/mentionDetection.d.ts +20 -0
  220. package/dist/ui/mentionDetection.js +24 -0
  221. package/dist/ui/terminalColors.d.ts +4 -4
  222. package/dist/ui/terminalColors.js +23 -6
  223. package/dist/ui/terminalSanitize.js +8 -3
  224. package/dist/ui/textGeometry.d.ts +2 -0
  225. package/dist/ui/textGeometry.js +6 -0
  226. package/dist/ui/themes/registry.js +33 -33
  227. package/dist/utils/openPath.js +7 -0
  228. package/package.json +22 -19
  229. /package/dist/{llm/tools → core/ignore}/gitIgnore.d.ts +0 -0
  230. /package/dist/{llm/tools → core/ignore}/gitIgnore.js +0 -0
  231. /package/dist/{config → core}/paths.d.ts +0 -0
  232. /package/dist/{config → core}/paths.js +0 -0
  233. /package/dist/{config → core/persistence}/privateStorage.d.ts +0 -0
  234. /package/dist/{llm → core}/toolResultTypes.js +0 -0
@@ -0,0 +1,141 @@
1
+ import { readSettings, updateSettings } from '../../config/settings.js';
2
+ import { readContextFiles } from '../../config/contextFiles.js';
3
+ import { formatSession } from '../../core/session/sessionStore.js';
4
+ import { loadTasks as loadTasksFromStore } from '../../core/tasks/taskStorage.js';
5
+ import { handleSlashCommand } from '../commands/commands.js';
6
+ import { isPausedGoalRecoveryCommand, contextFileSignatureMap } from './userInput.js';
7
+ import { buildContextReport } from './contextReport.js';
8
+ import { parseUserInputLine } from '../../core/agent/userCommands.js';
9
+ import { NO_USER_COMMAND_MESSAGE } from './userCommandFlow.js';
10
+ /**
11
+ * The chat input submit pipeline: exit shortcut, settings repair, busy
12
+ * queueing, wizard dispatch, skill invocation, slash commands, then the
13
+ * agent turn. Extracted from `chat.tsx` (CR-006 pattern) — pure code motion
14
+ * over the explicit deps bundle.
15
+ */
16
+ export async function submit(deps, value) {
17
+ const { stoppingRef, mode, shutdown, settingsError, setSettings, setSettingsError, setMessages, busy, followUps, pausedResume, setPausedResume, wizard, skillInvocation, doAgentTurn, settings, contextFiles, setMode, updateWizard, sessionLifecycle, noSession, openSessionPicker, sessionRef, terminalControl, refreshSkills, openPluginPicker, setContextFiles, contextFileSignaturesRef, currentPromptSession, setSessionReasoningOverride, sessionStartRef, conversationRef, clearLiveMessages, lastAssistantTextRef, prepareUserInput, setVisibleTasks, setTaskBarPadding, } = deps;
18
+ if (stoppingRef.current)
19
+ return;
20
+ if (mode === 'chat' && /^\/(?:exit|quit)\s*$/i.test(value))
21
+ return shutdown();
22
+ if (settingsError) {
23
+ try {
24
+ const repaired = await readSettings();
25
+ setSettings(repaired, {});
26
+ setSettingsError(undefined);
27
+ }
28
+ catch (error) {
29
+ const message = error instanceof Error ? error.message : String(error);
30
+ setSettingsError(message);
31
+ if (!/^\/(?:settings\s+(?:open|edit)|help|exit|quit)\b/i.test(value.trim())) {
32
+ setMessages(messages => [...messages, { role: 'system', text: `${message}\nRepair settings, then retry. /settings edit (or /settings open), /help, and /exit remain available.` }]);
33
+ return;
34
+ }
35
+ }
36
+ }
37
+ if (busy) {
38
+ if (mode === 'chat')
39
+ followUps.queue(value);
40
+ return;
41
+ }
42
+ // A new goal or session reset supersedes the paused-goal resume affordance;
43
+ // recovery/configuration commands (compact, model, provider, settings,
44
+ // resume…) intentionally keep it — the pause notice tells the user to run
45
+ // exactly those and then press R (SU-04).
46
+ const isRecoveryCommand = isPausedGoalRecoveryCommand(mode, value);
47
+ if (pausedResume && !isRecoveryCommand)
48
+ setPausedResume(undefined);
49
+ if (await wizard.dispatch(mode, value))
50
+ return;
51
+ // `! <command>` runs directly, with no model turn; `\!` escapes the prefix.
52
+ if (mode === 'chat') {
53
+ const parsed = parseUserInputLine(value);
54
+ if (parsed.kind === 'command') {
55
+ if (parsed.command)
56
+ await deps.runUserCommand(parsed.command);
57
+ else
58
+ setMessages(m => [...m, { role: 'system', text: NO_USER_COMMAND_MESSAGE }]);
59
+ return;
60
+ }
61
+ if (parsed.kind === 'escaped')
62
+ value = parsed.value;
63
+ }
64
+ const invokedSkill = skillInvocation(value);
65
+ if (invokedSkill) {
66
+ const argumentText = invokedSkill.args ? `\nUser-provided skill arguments: ${invokedSkill.args}` : '';
67
+ await doAgentTurn(`The user explicitly invoked the "${invokedSkill.skill.name}" skill. Call skill with name="${invokedSkill.skill.name}" and follow its returned instructions.${argumentText}`, value);
68
+ return;
69
+ }
70
+ const { clearConversation, compactConversation, compactConversationWithModel } = sessionLifecycle;
71
+ const ctx = {
72
+ settings,
73
+ contextFiles,
74
+ setMode,
75
+ setModelProviderFilter: (filter) => updateWizard({ type: 'set', key: 'modelProviderFilter', value: filter }),
76
+ addSystemMessage: text => setMessages(m => [...m, { role: 'system', text }]),
77
+ clearConversation,
78
+ newSession: async () => {
79
+ conversationRef.current = [];
80
+ lastAssistantTextRef.current = '';
81
+ clearLiveMessages();
82
+ setMessages([{ role: 'system', text: 'Started fresh. The fog parts.' }]);
83
+ await sessionLifecycle.startNewSession('New session started.');
84
+ },
85
+ resumeSession: noSession ? undefined : async (id) => {
86
+ if (id)
87
+ await sessionLifecycle.resumeSessionById(id);
88
+ else
89
+ await openSessionPicker();
90
+ },
91
+ sessionInfo: () => sessionRef.current ? formatSession(sessionRef.current) : 'Session persistence is off.',
92
+ compactConversation,
93
+ compactConversationLlm: compactConversationWithModel,
94
+ runAgentTurn: (prompt, displayValue, options) => doAgentTurn(prompt, displayValue, options),
95
+ composeInEditor: async () => {
96
+ const text = await terminalControl.composeInEditor();
97
+ if (text === undefined)
98
+ setMessages(m => [...m, { role: 'system', text: '/editor needs $EDITOR (or $VISUAL) set to an editor command.' }]);
99
+ return text;
100
+ },
101
+ viewInPager: terminalControl.viewInPager,
102
+ editFileInEditor: terminalControl.editFileInEditor,
103
+ refreshSkills,
104
+ openPluginPicker,
105
+ refreshContextFiles: async () => {
106
+ const files = await readContextFiles().catch(() => contextFiles);
107
+ setContextFiles(files);
108
+ contextFileSignaturesRef.current = contextFileSignatureMap(files);
109
+ return files;
110
+ },
111
+ updateSettings: async (patch) => {
112
+ const next = await updateSettings(patch);
113
+ setSettings(next, patch);
114
+ return deps.settingsRef.current;
115
+ },
116
+ getSessionReasoning: modelSelector => currentPromptSession().reasoningByModel?.[modelSelector],
117
+ setSessionReasoning: setSessionReasoningOverride,
118
+ getContextReport: () => buildContextReport({ sessionStart: sessionStartRef.current, contextFiles, conversation: conversationRef.current }),
119
+ };
120
+ let result;
121
+ try {
122
+ result = await handleSlashCommand(value, ctx);
123
+ }
124
+ catch (error) {
125
+ const text = error instanceof Error ? error.message : String(error);
126
+ setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
127
+ return;
128
+ }
129
+ if (result === 'exit')
130
+ return shutdown();
131
+ if (result === 'handled') {
132
+ if (value === '/clear' || value === '/new') {
133
+ loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
134
+ }
135
+ return;
136
+ }
137
+ const prepared = await prepareUserInput(value);
138
+ if (!prepared)
139
+ return;
140
+ await doAgentTurn(prepared.value, prepared.displayValue, prepared.options);
141
+ }
@@ -55,7 +55,7 @@ export function runSuspendedChild(launch, stdinText) {
55
55
  }
56
56
  });
57
57
  }
58
- // Ink-side wiring lives in chat.tsx via useApp(); this module deliberately
58
+ // Ink-side wiring lives in chat/ChatScreen.tsx via useApp(); this module deliberately
59
59
  // stays React-free. The interactive hook is defined in terminalControlHook.tsx.
60
60
  // --- Ink-side wiring (React, no JSX) -------------------------------------
61
61
  import { useCallback } from 'react';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Pure one-line builders for tool calls, tool results and the busy label
3
+ * (compact, toolCallSummary, toolResultSummary, busyToolLabel): the transcript
4
+ * vocabulary shared by commands/formatters.ts (which re-exports them) and by
5
+ * the turn engine under commands/streaming/, which records them into display
6
+ * state while a step runs (ARCH-03).
7
+ */
8
+ export declare function compact(value: unknown, maxLength?: number): string;
9
+ /**
10
+ * One-line summary of a tool call for the transcript rows. Wraps the raw
11
+ * builder: paths, patterns, and commands are model/repo-derived, so terminal
12
+ * control sequences are stripped at this sink (HZA-3).
13
+ */
14
+ export declare function toolCallSummary(toolName: string, input: unknown): string;
15
+ /**
16
+ * One-line summary of a tool result for the transcript rows; same terminal
17
+ * control-sequence sink discipline as `toolCallSummary` (HZA-3).
18
+ */
19
+ export declare function toolResultSummary(event: {
20
+ success: boolean;
21
+ output?: unknown;
22
+ error?: unknown;
23
+ }): string;
24
+ /**
25
+ * A short, human label for the live busy indicator while a tool is running,
26
+ * e.g. "Running npm test", "Reading src/foo.ts", "Searching".
27
+ * Lets the developer see *what* is happening, not just that something is.
28
+ */
29
+ export declare function busyToolLabel(toolName: string, input: unknown): string;
@@ -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
+ }