@denizokcu/haze 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +66 -25
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/contextReport.js +2 -0
  9. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  10. package/dist/cli/chat/liveRegion.d.ts +25 -0
  11. package/dist/cli/chat/liveRegion.js +48 -0
  12. package/dist/cli/chat/messages.d.ts +33 -2
  13. package/dist/cli/chat/messages.js +216 -33
  14. package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
  15. package/dist/cli/chat/sessionLifecycle.js +64 -14
  16. package/dist/cli/chat/sessionRecorder.js +75 -7
  17. package/dist/cli/chat/startupInfo.d.ts +0 -1
  18. package/dist/cli/chat/startupInfo.js +11 -15
  19. package/dist/cli/chat/wizardDispatch.js +111 -12
  20. package/dist/cli/commands/chat.d.ts +5 -0
  21. package/dist/cli/commands/chat.js +203 -101
  22. package/dist/cli/commands/commands.d.ts +2 -0
  23. package/dist/cli/commands/commands.js +10 -5
  24. package/dist/cli/commands/doctor.d.ts +19 -0
  25. package/dist/cli/commands/doctor.js +76 -0
  26. package/dist/cli/commands/formatters.js +2 -0
  27. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  28. package/dist/cli/commands/ndjsonSink.js +38 -0
  29. package/dist/cli/commands/providerWizard.d.ts +9 -2
  30. package/dist/cli/commands/providerWizard.js +37 -4
  31. package/dist/cli/commands/runCommand.d.ts +3 -0
  32. package/dist/cli/commands/runCommand.js +117 -11
  33. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  34. package/dist/cli/commands/streaming/abortCause.js +16 -0
  35. package/dist/cli/commands/streaming/assistantText.js +9 -2
  36. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  38. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  39. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  40. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  41. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  42. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
  43. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  44. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  45. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  46. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  47. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  48. package/dist/cli/commands/streaming.d.ts +70 -3
  49. package/dist/cli/commands/streaming.js +491 -77
  50. package/dist/cli/commands/wizardActions.d.ts +1 -0
  51. package/dist/cli/commands/wizardActions.js +1 -0
  52. package/dist/cli/commands/wizardPrompts.js +7 -1
  53. package/dist/cli/commands/wizardSuggestions.js +5 -3
  54. package/dist/cli/index.js +68 -22
  55. package/dist/cli/terminalTitle.js +1 -1
  56. package/dist/config/modelDiscovery.d.ts +51 -0
  57. package/dist/config/modelDiscovery.js +164 -1
  58. package/dist/config/privateStorage.js +28 -2
  59. package/dist/config/providerAuth.d.ts +14 -0
  60. package/dist/config/providerAuth.js +49 -0
  61. package/dist/config/providerPresets.d.ts +39 -7
  62. package/dist/config/providerPresets.js +371 -100
  63. package/dist/config/providers.js +2 -0
  64. package/dist/config/settings.d.ts +36 -0
  65. package/dist/config/settings.js +9 -0
  66. package/dist/core/agent/budgets.d.ts +10 -0
  67. package/dist/core/agent/budgets.js +10 -0
  68. package/dist/core/agent/compaction.d.ts +38 -0
  69. package/dist/core/agent/compaction.js +92 -17
  70. package/dist/core/agent/completionController.d.ts +230 -0
  71. package/dist/core/agent/completionController.js +287 -0
  72. package/dist/core/agent/contextBudget.d.ts +38 -0
  73. package/dist/core/agent/contextBudget.js +60 -7
  74. package/dist/core/agent/events.d.ts +74 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  76. package/dist/core/agent/reasoningPolicy.js +27 -0
  77. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  78. package/dist/core/agent/toolCapabilities.js +58 -0
  79. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  80. package/dist/core/agent/toolExecutionBudget.js +49 -0
  81. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  82. package/dist/core/agent/toolOutputStore.js +10 -10
  83. package/dist/core/agent/toolResults.d.ts +12 -0
  84. package/dist/core/agent/toolResults.js +38 -0
  85. package/dist/core/agent/turnBudget.d.ts +35 -0
  86. package/dist/core/agent/turnBudget.js +27 -0
  87. package/dist/core/agent/turnPolicy.d.ts +11 -0
  88. package/dist/core/agent/turnPolicy.js +19 -0
  89. package/dist/core/agent/workState.d.ts +75 -0
  90. package/dist/core/agent/workState.js +120 -9
  91. package/dist/core/deadline.d.ts +33 -0
  92. package/dist/core/deadline.js +74 -0
  93. package/dist/core/goal/completionPolicy.d.ts +27 -0
  94. package/dist/core/goal/completionPolicy.js +37 -1
  95. package/dist/core/limits/byteBudgets.d.ts +2 -0
  96. package/dist/core/limits/byteBudgets.js +2 -0
  97. package/dist/core/limits/textBudgets.d.ts +2 -0
  98. package/dist/core/limits/textBudgets.js +2 -0
  99. package/dist/core/log/llmLog.js +7 -0
  100. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  101. package/dist/core/persistence/orderedFileWriter.js +16 -2
  102. package/dist/core/process/backgroundRegistry.js +8 -7
  103. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  104. package/dist/core/process/runBoundedProcess.js +15 -6
  105. package/dist/core/safety/missingExecutable.d.ts +42 -0
  106. package/dist/core/safety/missingExecutable.js +77 -0
  107. package/dist/core/session/sessionStore.d.ts +37 -0
  108. package/dist/core/session/sessionStore.js +215 -51
  109. package/dist/core/subagent/contracts.d.ts +4 -0
  110. package/dist/core/subagent/contracts.js +1 -0
  111. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  112. package/dist/core/subagent/subagentCoordinator.js +32 -2
  113. package/dist/core/subagent/subagentRunner.js +17 -37
  114. package/dist/llm/client.d.ts +17 -1
  115. package/dist/llm/client.js +82 -14
  116. package/dist/llm/hazeTools.d.ts +554 -80
  117. package/dist/llm/hazeTools.js +103 -24
  118. package/dist/llm/lsp.d.ts +24 -4
  119. package/dist/llm/lsp.js +72 -11
  120. package/dist/llm/lspTools.d.ts +2366 -0
  121. package/dist/llm/lspTools.js +87 -79
  122. package/dist/llm/openaiCodex.d.ts +3 -0
  123. package/dist/llm/openaiCodex.js +47 -0
  124. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  125. package/dist/llm/openaiCodexOAuth.js +214 -0
  126. package/dist/llm/requestContext.d.ts +3 -0
  127. package/dist/llm/requestContext.js +7 -4
  128. package/dist/llm/systemPrompt.d.ts +11 -0
  129. package/dist/llm/systemPrompt.js +12 -6
  130. package/dist/llm/toolResultTypes.d.ts +8 -1
  131. package/dist/llm/tools/bashTool.d.ts +48 -16
  132. package/dist/llm/tools/bashTool.js +5 -0
  133. package/dist/llm/tools/editMatch.d.ts +14 -0
  134. package/dist/llm/tools/editMatch.js +72 -0
  135. package/dist/llm/tools/failures.d.ts +2 -0
  136. package/dist/llm/tools/failures.js +1 -0
  137. package/dist/llm/tools/fetchTool.d.ts +16 -0
  138. package/dist/llm/tools/fileToolShared.d.ts +4 -3
  139. package/dist/llm/tools/fileToolShared.js +16 -21
  140. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  141. package/dist/llm/tools/gitIgnore.js +129 -0
  142. package/dist/llm/tools/readRecovery.d.ts +10 -0
  143. package/dist/llm/tools/readRecovery.js +135 -0
  144. package/dist/llm/tools/toolContext.d.ts +1 -1
  145. package/dist/llm/tools/toolContext.js +61 -32
  146. package/dist/llm/webFetch.d.ts +17 -0
  147. package/dist/llm/webFetch.js +64 -97
  148. package/dist/ui/codeHighlight.d.ts +4 -0
  149. package/dist/ui/codeHighlight.js +31 -0
  150. package/dist/ui/components/Header.d.ts +1 -1
  151. package/dist/ui/components/MarkdownText.d.ts +16 -2
  152. package/dist/ui/components/MarkdownText.js +244 -34
  153. package/dist/ui/components/TextInput.d.ts +8 -1
  154. package/dist/ui/components/TextInput.js +6 -2
  155. package/dist/ui/theme.d.ts +4 -3
  156. package/dist/ui/theme.js +5 -4
  157. package/dist/utils/buildInfo.d.ts +104 -0
  158. package/dist/utils/buildInfo.js +253 -0
  159. package/dist/utils/fs.d.ts +9 -0
  160. package/dist/utils/fs.js +87 -25
  161. package/dist/utils/openPath.d.ts +2 -2
  162. package/dist/utils/openPath.js +19 -6
  163. package/dist/utils/path.d.ts +2 -0
  164. package/dist/utils/path.js +5 -1
  165. package/dist/utils/utf8.d.ts +22 -0
  166. package/dist/utils/utf8.js +54 -0
  167. package/dist/utils/version.d.ts +9 -3
  168. package/dist/utils/version.js +28 -2
  169. package/package.json +24 -19
@@ -1,31 +1,17 @@
1
1
  import http from 'node:http';
2
2
  import https from 'node:https';
3
3
  import { Readable } from 'node:stream';
4
- import { readFileSync } from 'node:fs';
5
- import { fileURLToPath } from 'node:url';
6
- import { dirname, join } from 'node:path';
7
4
  import { validateUrl } from '../core/safety/urlGuard.js';
5
+ import { truncateUtf8AtBytes } from '../utils/utf8.js';
6
+ import { readPackageVersion } from '../utils/version.js';
8
7
  const DEFAULT_TIMEOUT_MS = 30_000;
9
8
  const DEFAULT_MAX_BYTES = 2_000_000;
10
9
  const DEFAULT_MAX_REDIRECTS = 5;
11
- // Derive the version from package.json (as cli/index.ts does) so the user
12
- // agent never goes stale; fall back to an unversioned agent if the read fails
13
- // (CR-017).
14
- let cachedUserAgent;
10
+ // Derive the version from package.json so the user agent never goes stale;
11
+ // fall back to an unversioned agent if package metadata is unavailable.
15
12
  function userAgent() {
16
- if (cachedUserAgent)
17
- return cachedUserAgent;
18
- let version;
19
- try {
20
- const here = dirname(fileURLToPath(import.meta.url));
21
- const pkg = JSON.parse(readFileSync(join(here, '..', '..', 'package.json'), 'utf8'));
22
- version = pkg.version;
23
- }
24
- catch {
25
- version = undefined;
26
- }
27
- cachedUserAgent = version ? `haze/${version} (+https://github.com/DenizOkcu/haze)` : 'haze (+https://github.com/DenizOkcu/haze)';
28
- return cachedUserAgent;
13
+ const version = readPackageVersion();
14
+ return version ? `haze/${version} (+https://github.com/DenizOkcu/haze)` : 'haze (+https://github.com/DenizOkcu/haze)';
29
15
  }
30
16
  /** Error thrown when a URL is rejected by the SSRF guard. */
31
17
  export class BlockedUrlError extends Error {
@@ -92,28 +78,12 @@ function classifyContentType(contentType) {
92
78
  return 'html';
93
79
  return 'text';
94
80
  }
95
- function decodeValidUtf8Prefix(buffer) {
96
- for (let end = buffer.byteLength; end >= 0; end--) {
97
- try {
98
- return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, end));
99
- }
100
- catch {
101
- // Back up until we land on a UTF-8 character boundary.
102
- }
103
- }
104
- return '';
105
- }
106
- function truncateUtf8Bytes(text, maxBytes) {
107
- const buffer = Buffer.from(text, 'utf8');
108
- if (buffer.byteLength <= maxBytes)
109
- return { text, bytes: buffer.byteLength, truncated: false };
110
- return { text: decodeValidUtf8Prefix(buffer.subarray(0, maxBytes)), bytes: maxBytes, truncated: true };
111
- }
112
81
  async function readBodyCapped(response, maxBytes, abortController) {
113
82
  const body = response.body;
114
- if (body == null || typeof body.getReader !== 'function') {
115
- // No streamable body; read as text once and cap.
116
- return truncateUtf8Bytes(await response.text(), maxBytes);
83
+ if (body == null)
84
+ return { text: '', bytes: 0, truncated: false };
85
+ if (typeof body.getReader !== 'function') {
86
+ throw new Error('Response body is not streamable; refusing unbounded read');
117
87
  }
118
88
  const reader = body.getReader();
119
89
  const chunks = [];
@@ -153,25 +123,8 @@ async function readBodyCapped(response, maxBytes, abortController) {
153
123
  if (truncated && !abortController.signal.aborted)
154
124
  abortController.abort();
155
125
  }
156
- return { text: decodeValidUtf8Prefix(Buffer.concat(chunks)), bytes: Math.min(received, maxBytes), truncated };
126
+ return { text: truncateUtf8AtBytes(Buffer.concat(chunks), maxBytes).text, bytes: Math.min(received, maxBytes), truncated };
157
127
  }
158
- /**
159
- * Perform an HTTP(S) request with the TCP connection pinned to `pinnedIp`.
160
- *
161
- * This closes the DNS-rebinding TOCTOU: `validateUrl` resolved the hostname and
162
- * verified every address is public, but the global `fetch` would re-resolve the
163
- * hostname at connect time — an attacker-controlled DNS server can return a
164
- * public IP for the validation lookup and a private/internal IP for the connect
165
- * lookup. By connecting directly to the already-validated IP (`hostname:
166
- * pinnedIp`) while keeping the original `Host` header and TLS `servername`
167
- * (`url.hostname`), the connection target is fixed to what we validated, with no
168
- * second DNS lookup. TLS certificate verification still runs against the original
169
- * hostname via `servername`, so pinning does not weaken identity checks.
170
- *
171
- * Literal-IP URLs carry no DNS-rebinding surface (`pinnedIp` is undefined), so
172
- * they fall through to the global `fetch` — which also keeps the test mocks that
173
- * stub `globalThis.fetch` working for that path.
174
- */
175
128
  /**
176
129
  * Coerce a RequestInit headers value into a plain string record. Keeps the
177
130
  * transport defensive against `Headers`/tuple/array inputs instead of blindly
@@ -197,9 +150,45 @@ function normalizeHeaders(input) {
197
150
  }
198
151
  return { ...input };
199
152
  }
153
+ function normalizeResponseHeaders(input) {
154
+ const headers = {};
155
+ for (const [key, value] of Object.entries(input)) {
156
+ if (value === undefined)
157
+ continue;
158
+ // Cookie fidelity is out of scope for this read-only transport; all array
159
+ // headers are represented deterministically as comma-separated values.
160
+ headers[key] = Array.isArray(value) ? value.join(', ') : value;
161
+ }
162
+ return headers;
163
+ }
164
+ /**
165
+ * Perform an HTTP(S) request with the TCP connection pinned to `pinnedIp`.
166
+ *
167
+ * This closes the DNS-rebinding TOCTOU: `validateUrl` resolved the hostname and
168
+ * verified every address is public, but the global `fetch` would re-resolve the
169
+ * hostname at connect time — an attacker-controlled DNS server can return a
170
+ * public IP for the validation lookup and a private/internal IP for the connect
171
+ * lookup. By connecting directly to the already-validated IP (`hostname:
172
+ * pinnedIp`) while keeping the original `Host` header and TLS `servername`
173
+ * (`url.hostname`), the connection target is fixed to what we validated, with no
174
+ * second DNS lookup. TLS certificate verification still runs against the original
175
+ * hostname via `servername`, so pinning does not weaken identity checks.
176
+ *
177
+ * Literal-IP URLs carry no DNS-rebinding surface (`pinnedIp` is undefined), so
178
+ * they fall through to the global `fetch` — which also keeps the test mocks that
179
+ * stub `globalThis.fetch` working for that path.
180
+ */
200
181
  export async function pinnedFetch(url, pinnedIp, init) {
182
+ const method = (init.method ?? 'GET').toUpperCase();
183
+ if (method !== 'GET' && method !== 'HEAD') {
184
+ throw new Error('Pinned fetch supports only GET and HEAD requests');
185
+ }
186
+ if (init.body != null)
187
+ throw new Error('Pinned fetch does not support request bodies');
188
+ if (url.username || url.password)
189
+ throw new Error('Pinned fetch does not support URL credentials');
201
190
  if (!pinnedIp)
202
- return globalThis.fetch(url, init);
191
+ return globalThis.fetch(url, { ...init, method });
203
192
  const isTls = url.protocol === 'https:';
204
193
  const port = url.port ? Number(url.port) : (isTls ? 443 : 80);
205
194
  const path = url.pathname + url.search;
@@ -210,7 +199,7 @@ export async function pinnedFetch(url, pinnedIp, init) {
210
199
  const lib = isTls ? https : http;
211
200
  return new Promise((resolve, reject) => {
212
201
  const req = lib.request({
213
- method: init.method ?? 'GET',
202
+ method,
214
203
  hostname: pinnedIp,
215
204
  port,
216
205
  path,
@@ -222,7 +211,7 @@ export async function pinnedFetch(url, pinnedIp, init) {
222
211
  resolve(new Response(body, {
223
212
  status: res.statusCode ?? 200,
224
213
  statusText: res.statusMessage ?? '',
225
- headers: res.headers,
214
+ headers: normalizeResponseHeaders(res.headers),
226
215
  }));
227
216
  });
228
217
  req.on('error', reject);
@@ -251,30 +240,22 @@ export async function fetchUrlContent(input, opts) {
251
240
  // lookup in between (that gap was the rebinding window).
252
241
  let currentPinnedIp = initial.resolvedAddresses?.[0];
253
242
  let response;
243
+ let responseAbortController;
254
244
  const visited = [];
245
+ const totalTimeoutSignal = AbortSignal.timeout(timeoutMs * 2);
255
246
  for (let hop = 0; hop <= maxRedirects; hop++) {
256
247
  const timeoutSignal = AbortSignal.timeout(timeoutMs);
257
248
  const abortController = new AbortController();
258
- const onAbort = () => abortController.abort();
259
- if (opts?.signal) {
260
- if (opts.signal.aborted)
261
- abortController.abort();
262
- else
263
- opts.signal.addEventListener('abort', onAbort, { once: true });
264
- }
265
- const combined = AbortSignal.any([timeoutSignal, abortController.signal]);
266
- try {
267
- response = await fetcher(currentUrl, currentPinnedIp, {
268
- redirect: 'manual',
269
- signal: combined,
270
- headers: { accept: 'text/html,application/xhtml+xml,application/json,text/plain;q=0.5,*/*;q=0.1', 'user-agent': userAgent() },
271
- });
272
- }
273
- finally {
274
- // Listener cleanup only; fetch errors propagate unchanged (CR-017).
275
- if (opts?.signal)
276
- opts.signal.removeEventListener('abort', onAbort);
277
- }
249
+ const signals = [totalTimeoutSignal, timeoutSignal, abortController.signal];
250
+ if (opts?.signal)
251
+ signals.push(opts.signal);
252
+ const combined = AbortSignal.any(signals);
253
+ response = await fetcher(currentUrl, currentPinnedIp, {
254
+ redirect: 'manual',
255
+ signal: combined,
256
+ headers: { accept: 'text/html,application/xhtml+xml,application/json,text/plain;q=0.5,*/*;q=0.1', 'user-agent': userAgent() },
257
+ });
258
+ responseAbortController = abortController;
278
259
  // Follow redirects ourselves, re-validating each Location (closes the
279
260
  // redirect-to-internal-IP hole).
280
261
  const status = response.status;
@@ -282,6 +263,7 @@ export async function fetchUrlContent(input, opts) {
282
263
  const location = response.headers.get('location');
283
264
  if (!location)
284
265
  break;
266
+ await response.body?.cancel().catch(() => undefined);
285
267
  if (hop >= maxRedirects) {
286
268
  throw new Error(`Too many redirects (>${maxRedirects}) fetching ${input}`);
287
269
  }
@@ -314,22 +296,7 @@ export async function fetchUrlContent(input, opts) {
314
296
  // validated and connection-pinned at fetch time. Re-resolving the final URL
315
297
  // here would only reopen a rebinding race against a connection that already
316
298
  // used a safe, pinned IP.
317
- const abortController = new AbortController();
318
- const onAbort = () => abortController.abort();
319
- if (opts?.signal) {
320
- if (opts.signal.aborted)
321
- abortController.abort();
322
- else
323
- opts.signal.addEventListener('abort', onAbort, { once: true });
324
- }
325
- let bodyResult;
326
- try {
327
- bodyResult = await readBodyCapped(response, maxBytes, abortController);
328
- }
329
- finally {
330
- if (opts?.signal)
331
- opts.signal.removeEventListener('abort', onAbort);
332
- }
299
+ const bodyResult = await readBodyCapped(response, maxBytes, responseAbortController ?? new AbortController());
333
300
  const contentType = response.headers.get('content-type') ?? 'application/octet-stream';
334
301
  const kind = classifyContentType(contentType);
335
302
  let content = bodyResult.text;
@@ -0,0 +1,4 @@
1
+ /** Map a source path to a cli-highlight language when its extension is known. */
2
+ export declare function languageForPath(filePath: string): string | undefined;
3
+ /** Highlight, clip, and pad one source line to an exact terminal width. */
4
+ export declare function highlightedCodeLine(code: string, width: number, language?: string): string;
@@ -0,0 +1,31 @@
1
+ import { highlight, supportsLanguage } from 'cli-highlight';
2
+ import stripAnsi from 'strip-ansi';
3
+ /** Map a source path to a cli-highlight language when its extension is known. */
4
+ export function languageForPath(filePath) {
5
+ const extension = /\.([^./]+)$/.exec(filePath)?.[1]?.toLowerCase();
6
+ if (!extension)
7
+ return undefined;
8
+ const aliases = {
9
+ cjs: 'javascript', cts: 'typescript', htm: 'html', js: 'javascript', md: 'markdown', mjs: 'javascript',
10
+ mts: 'typescript', py: 'python', rb: 'ruby', sh: 'bash', ts: 'typescript', yml: 'yaml',
11
+ };
12
+ const language = aliases[extension] ?? extension;
13
+ return supportsLanguage(language) ? language : undefined;
14
+ }
15
+ /** Highlight, clip, and pad one source line to an exact terminal width. */
16
+ export function highlightedCodeLine(code, width, language) {
17
+ const safeWidth = Math.max(1, width);
18
+ const singleLine = code.replace(/\t/g, ' ');
19
+ const fitted = singleLine.length > safeWidth
20
+ ? `${singleLine.slice(0, Math.max(0, safeWidth - 1))}…`
21
+ : singleLine;
22
+ let rendered = fitted;
23
+ try {
24
+ rendered = highlight(fitted, { language: language || undefined, ignoreIllegals: true });
25
+ }
26
+ catch {
27
+ // Unknown or malformed source still renders as plain text.
28
+ }
29
+ const padding = Math.max(0, safeWidth - stripAnsi(rendered).length);
30
+ return `${rendered}${' '.repeat(padding)}`;
31
+ }
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
2
  export declare function Header({ subtitle, version }: {
3
- subtitle?: string;
3
+ subtitle?: React.ReactNode;
4
4
  version?: string;
5
5
  }): React.JSX.Element;
@@ -1,6 +1,20 @@
1
1
  import React from 'react';
2
2
  import { type Tokens } from 'marked';
3
- export declare function MarkdownText({ content }: {
3
+ export declare const MarkdownText: React.MemoExoticComponent<({ content, width }: {
4
4
  content: string;
5
- }): React.JSX.Element;
5
+ width: number;
6
+ }) => React.JSX.Element>;
7
+ /** Test-only: clear the chunk cache to assert lexer call counts deterministically. */
8
+ export declare function clearMarkdownRootChunksCacheForTests(): void;
9
+ /**
10
+ * Split Markdown into stable root-level chunks. The final chunk is deliberately
11
+ * considered active: Marked may still reclassify it as more text arrives (for
12
+ * example, a paragraph can become a setext heading or a GFM table). Once a
13
+ * following root block exists, the preceding chunk is safe to render once in
14
+ * Ink's <Static> transcript.
15
+ *
16
+ * A source-path lead and its following fenced code block stay in one chunk so
17
+ * MarkdownText can preserve their shared filename and starting line metadata.
18
+ */
19
+ export declare function markdownRootChunks(content: string): string[];
6
20
  export declare function renderMarkdownTable(table: Tokens.Table, maxWidth?: number): string[];
@@ -1,16 +1,91 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Box, Text, useStdout } from 'ink';
2
+ import React from 'react';
3
+ import { Box, Text } from 'ink';
3
4
  import { marked } from 'marked';
4
- import { highlight } from 'cli-highlight';
5
5
  import stripAnsi from 'strip-ansi';
6
6
  import { theme } from '../theme.js';
7
- export function MarkdownText({ content }) {
8
- const tokens = marked.lexer(content, { gfm: true, breaks: true });
9
- const { stdout } = useStdout();
10
- const width = Math.max(20, (stdout.columns ?? process.stdout.columns ?? 100) - 2);
11
- return _jsx(Box, { flexDirection: "column", children: tokens.map((token, index) => _jsx(MarkdownBlock, { token: token, width: width }, index)) });
7
+ import { highlightedCodeLine } from '../codeHighlight.js';
8
+ const MARKED_OPTIONS = { gfm: true, breaks: true };
9
+ export const MarkdownText = React.memo(function MarkdownText({ content, width }) {
10
+ const tokens = marked.lexer(content, MARKED_OPTIONS);
11
+ const contentWidth = Math.max(20, width - 2);
12
+ return _jsx(Box, { flexDirection: "column", children: tokens.map((token, index) => {
13
+ const codeLead = token.type === 'paragraph' || token.type === 'text' ? codeLeadForFollowingFence(tokens, index) : undefined;
14
+ if (token.type === 'space' && bridgesCodeLeadToFence(tokens, index))
15
+ return null;
16
+ return _jsx(MarkdownBlock, { token: token, width: contentWidth, source: token.type === 'code' ? precedingCodeSource(tokens, index) : undefined, textOverride: codeLead?.text, compactAfter: codeLead != null }, index);
17
+ }) });
18
+ });
19
+ /**
20
+ * Bounded LRU cache for Markdown root chunking (RH-007). Settled assistant
21
+ * messages never change, but `partitionDisplayMessages` runs on every render
22
+ * and would otherwise re-lex the entire historical transcript each time. The
23
+ * chunking is a pure function of the source text, so identical content reuses a
24
+ * cached result; the LRU bound keeps memory predictable for long sessions.
25
+ */
26
+ const ROOT_CHUNKS_CACHE_MAX = 500;
27
+ const rootChunksCache = new Map();
28
+ /** Test-only: clear the chunk cache to assert lexer call counts deterministically. */
29
+ export function clearMarkdownRootChunksCacheForTests() {
30
+ rootChunksCache.clear();
31
+ }
32
+ function computeMarkdownRootChunks(content) {
33
+ const tokens = marked.lexer(content, MARKED_OPTIONS);
34
+ if (tokens.length === 0)
35
+ return content ? [content] : [];
36
+ const chunks = [];
37
+ let chunkStart = 0;
38
+ for (let index = 0; index < tokens.length; index++) {
39
+ const token = tokens[index];
40
+ if (!token || token.type === 'space')
41
+ continue;
42
+ let nextIndex = index + 1;
43
+ while (tokens[nextIndex]?.type === 'space')
44
+ nextIndex++;
45
+ if (nextIndex >= tokens.length)
46
+ continue;
47
+ const linkedCodeBlock = (token.type === 'paragraph' || token.type === 'text')
48
+ && tokens[nextIndex]?.type === 'code'
49
+ && codeLeadForFollowingFence(tokens, index) != null;
50
+ if (linkedCodeBlock)
51
+ continue;
52
+ const chunk = tokens.slice(chunkStart, nextIndex).map(item => item.raw).join('');
53
+ if (chunk)
54
+ chunks.push(chunk);
55
+ chunkStart = nextIndex;
56
+ }
57
+ const activeChunk = tokens.slice(chunkStart).map(token => token.raw).join('');
58
+ if (activeChunk)
59
+ chunks.push(activeChunk);
60
+ return chunks;
61
+ }
62
+ /**
63
+ * Split Markdown into stable root-level chunks. The final chunk is deliberately
64
+ * considered active: Marked may still reclassify it as more text arrives (for
65
+ * example, a paragraph can become a setext heading or a GFM table). Once a
66
+ * following root block exists, the preceding chunk is safe to render once in
67
+ * Ink's <Static> transcript.
68
+ *
69
+ * A source-path lead and its following fenced code block stay in one chunk so
70
+ * MarkdownText can preserve their shared filename and starting line metadata.
71
+ */
72
+ export function markdownRootChunks(content) {
73
+ const cached = rootChunksCache.get(content);
74
+ if (cached) {
75
+ rootChunksCache.delete(content);
76
+ rootChunksCache.set(content, cached);
77
+ return cached;
78
+ }
79
+ const chunks = computeMarkdownRootChunks(content);
80
+ if (rootChunksCache.size >= ROOT_CHUNKS_CACHE_MAX) {
81
+ const oldest = rootChunksCache.keys().next().value;
82
+ if (oldest !== undefined)
83
+ rootChunksCache.delete(oldest);
84
+ }
85
+ rootChunksCache.set(content, chunks);
86
+ return chunks;
12
87
  }
13
- function MarkdownBlock({ token, width }) {
88
+ function MarkdownBlock({ token, width, source, textOverride, compactAfter }) {
14
89
  switch (token.type) {
15
90
  case 'heading': {
16
91
  const heading = token;
@@ -18,11 +93,11 @@ function MarkdownBlock({ token, width }) {
18
93
  }
19
94
  case 'paragraph': {
20
95
  const paragraph = token;
21
- return _jsx(Box, { marginBottom: 1, children: _jsx(InlineMarkdown, { text: paragraph.text }) });
96
+ return _jsx(Box, { marginBottom: compactAfter ? 0 : 1, children: _jsx(InlineMarkdown, { text: textOverride ?? paragraph.text }) });
22
97
  }
23
98
  case 'text': {
24
99
  const text = token;
25
- return _jsx(InlineMarkdown, { text: text.text });
100
+ return _jsx(InlineMarkdown, { text: textOverride ?? text.text });
26
101
  }
27
102
  case 'space':
28
103
  return _jsx(Text, { children: " " });
@@ -30,15 +105,16 @@ function MarkdownBlock({ token, width }) {
30
105
  return _jsx(Text, { color: theme.deepPurple, children: "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500" });
31
106
  case 'blockquote': {
32
107
  const quote = token;
33
- return _jsx(Box, { flexDirection: "column", marginY: 1, children: quote.text.split('\n').map((line, index) => _jsx(Text, { backgroundColor: theme.quoteBg, children: padAnsi(line || ' ', width) }, index)) });
108
+ return _jsx(Box, { flexDirection: "column", marginY: 1, children: quote.text.split('\n').map((line, index) => _jsx(Text, { backgroundColor: theme.surfaceBg, children: padAnsi(line || ' ', width) }, index)) });
34
109
  }
35
110
  case 'list': {
36
111
  const list = token;
37
- return _jsx(Box, { flexDirection: "column", marginBottom: 1, children: list.items.map((item, index) => _jsxs(Box, { children: [_jsx(Text, { color: theme.purple, children: list.ordered ? `${index + 1}. ` : '• ' }), _jsx(InlineMarkdown, { text: item.text.replace(/\n/g, ' ') })] }, index)) });
112
+ return _jsx(Box, { flexDirection: "column", marginBottom: 1, children: list.items.map((item, index) => (_jsx(ListItemView, { item: item, ordered: list.ordered, index: index, width: width }, index))) });
38
113
  }
39
114
  case 'code': {
40
115
  const code = token;
41
- return _jsx(CodeBlock, { code: code.text, language: code.lang, width: width });
116
+ const fence = parseCodeFenceInfo(code.lang);
117
+ return _jsx(CodeBlock, { code: code.text, language: fence.language, source: fence.source ?? source, width: width });
42
118
  }
43
119
  case 'table': {
44
120
  const table = token;
@@ -49,13 +125,40 @@ function MarkdownBlock({ token, width }) {
49
125
  return _jsx(Text, { children: 'raw' in token ? String(token.raw) : '' });
50
126
  }
51
127
  }
128
+ function ListItemView({ item, ordered, index, width }) {
129
+ const marker = ordered ? `${index + 1}. ` : '• ';
130
+ const markerWidth = visibleLength(marker);
131
+ const blocks = (item.tokens ?? []).filter(child => child.type !== 'space');
132
+ if (blocks.length === 0) {
133
+ return _jsx(Box, { children: _jsx(Text, { color: theme.purple, children: marker }) });
134
+ }
135
+ return _jsx(Box, { flexDirection: "column", children: blocks.map((block, blockIndex) => (_jsx(ListItemBlock, { token: block, marker: blockIndex === 0 ? marker : null, markerWidth: markerWidth, width: width }, blockIndex))) });
136
+ }
137
+ function ListItemBlock({ token, marker, markerWidth, width }) {
138
+ if (token.type === 'paragraph' || token.type === 'text') {
139
+ const text = token.text;
140
+ // Pre-wrap manually. Ink's auto-wrap algorithm injects a stray leading
141
+ // space on wrapped lines at certain widths (the wrap-point whitespace gets
142
+ // preserved on top of the marker indent), so we hand-pack atoms into lines
143
+ // and render each line as its own row. Whitespace is preserved as separate
144
+ // "space" atoms so the original spacing (e.g. "code, code") survives.
145
+ const contentWidth = Math.max(1, width - markerWidth);
146
+ const lines = wrapInlineAtoms(splitInlineIntoAtoms(tokenizeInline(text)), contentWidth);
147
+ const prefix = (lineIndex) => lineIndex === 0 ? (marker ?? ' '.repeat(markerWidth)) : ' '.repeat(markerWidth);
148
+ return _jsx(Box, { flexDirection: "column", children: lines.map((line, lineIndex) => (_jsxs(Box, { flexDirection: "row", children: [_jsx(Box, { flexShrink: 0, children: _jsx(Text, { color: theme.purple, children: prefix(lineIndex) }) }), _jsx(Text, { children: line.map((atom, atomIndex) => atom.type === 'space' ? _jsx(Text, { children: ' ' }, atomIndex) : renderInlinePart(atom, atomIndex)) })] }, lineIndex))) });
149
+ }
150
+ // Block-level content (code, nested list, blockquote, table). The marker
151
+ // sits on its own line when this is the first block; the block then renders
152
+ // indented to align with the marker.
153
+ return _jsxs(Box, { flexDirection: "column", children: [marker ? _jsx(Text, { color: theme.purple, children: marker }) : null, _jsx(Box, { flexDirection: "column", marginLeft: markerWidth, children: _jsx(MarkdownBlock, { token: token, width: Math.max(20, width - markerWidth) }) })] });
154
+ }
52
155
  function HeadingBlock({ heading, width }) {
53
156
  const title = stripInline(heading.text).trim();
54
157
  if (heading.depth === 1)
55
158
  return _jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [_jsx(Text, { color: theme.purple, bold: true, children: title.toUpperCase() }), _jsx(Text, { color: theme.deepPurple, children: '─'.repeat(Math.min(width, Math.max(12, visibleLength(title)))) })] });
56
159
  if (heading.depth === 2)
57
160
  return _jsx(Box, { marginTop: 1, marginBottom: 1, children: _jsx(Text, { color: theme.purple, bold: true, children: title }) });
58
- return _jsx(Box, { marginTop: heading.depth <= 3 ? 1 : 0, children: _jsx(Text, { color: theme.violet, bold: true, children: title }) });
161
+ return _jsx(Box, { marginTop: heading.depth <= 3 ? 1 : 0, children: _jsx(Text, { color: theme.purple, bold: true, children: title }) });
59
162
  }
60
163
  function TableLine({ line }) {
61
164
  if (isTableBorder(line))
@@ -64,30 +167,137 @@ function TableLine({ line }) {
64
167
  ? _jsx(Text, { color: theme.deepPurple, children: char }, index)
65
168
  : _jsx(Text, { children: char }, index)) });
66
169
  }
67
- function CodeBlock({ code, language, width }) {
68
- let rendered;
69
- try {
70
- rendered = highlight(code, { language: language || undefined, ignoreIllegals: true });
71
- }
72
- catch {
73
- rendered = code;
170
+ function CodeBlock({ code, language, source, width }) {
171
+ const lines = code.replace(/\n$/, '').split('\n');
172
+ const firstLine = source?.startLine ?? 1;
173
+ const showLineNumbers = source != null || lines.length > 1;
174
+ const lineNumberWidth = String(firstLine + lines.length - 1).length;
175
+ const header = source ? `${source.path}:${source.startLine}${language ? ` · ${language}` : ''}` : language;
176
+ return _jsxs(Box, { flexDirection: "column", marginTop: source ? 0 : 1, marginBottom: 1, children: [header ? _jsx(Text, { color: source ? theme.command : theme.muted, backgroundColor: theme.codeBg, children: padAnsi(header, width) }) : null, lines.map((line, index) => {
177
+ const lineNumber = firstLine + index;
178
+ const prefix = showLineNumbers ? `${String(lineNumber).padStart(lineNumberWidth)} │ ` : '';
179
+ const rendered = highlightedCodeLine(line, Math.max(1, width - prefix.length), language);
180
+ return _jsxs(Text, { backgroundColor: theme.codeBg, children: [prefix ? _jsx(Text, { color: theme.muted, backgroundColor: theme.codeBg, children: prefix }) : null, rendered] }, index);
181
+ })] });
182
+ }
183
+ function parseCodeSource(value) {
184
+ const match = /((?:[A-Za-z]:)?[^\s`()]+?\.[A-Za-z0-9]+):([1-9]\d*)(?:-[1-9]\d*)?[).,;:]?$/.exec(stripInline(value).trim());
185
+ if (!match)
186
+ return undefined;
187
+ return { path: match[1], startLine: Number(match[2]) };
188
+ }
189
+ function precedingCodeSource(tokens, codeIndex) {
190
+ for (let index = codeIndex - 1; index >= 0; index--) {
191
+ const token = tokens[index];
192
+ if (!token || token.type === 'space')
193
+ continue;
194
+ if (token.type !== 'paragraph' && token.type !== 'text')
195
+ return undefined;
196
+ return parseCodeSource(token.text);
74
197
  }
75
- const lines = rendered.replace(/\n$/, '').split('\n');
76
- return _jsxs(Box, { flexDirection: "column", marginY: 1, children: [language ? _jsx(Text, { color: theme.muted, backgroundColor: theme.codeBg, children: padAnsi(language, width) }) : null, lines.map((line, index) => _jsx(Text, { backgroundColor: theme.codeBg, children: padAnsi(line || ' ', width) }, index))] });
198
+ return undefined;
199
+ }
200
+ function codeLeadForFollowingFence(tokens, leadIndex) {
201
+ const token = tokens[leadIndex];
202
+ if (!token || (token.type !== 'paragraph' && token.type !== 'text'))
203
+ return undefined;
204
+ const value = token.text;
205
+ const source = parseCodeSource(value);
206
+ if (!source)
207
+ return undefined;
208
+ let nextIndex = leadIndex + 1;
209
+ while (tokens[nextIndex]?.type === 'space')
210
+ nextIndex++;
211
+ if (tokens[nextIndex]?.type !== 'code')
212
+ return undefined;
213
+ const pathIndex = value.lastIndexOf(source.path);
214
+ const text = value.slice(0, pathIndex).replace(/\s*(?:—|–|-)\s*`?\s*$/, '').trimEnd();
215
+ return { source, text };
216
+ }
217
+ function bridgesCodeLeadToFence(tokens, spaceIndex) {
218
+ let previousIndex = spaceIndex - 1;
219
+ while (tokens[previousIndex]?.type === 'space')
220
+ previousIndex--;
221
+ let nextIndex = spaceIndex + 1;
222
+ while (tokens[nextIndex]?.type === 'space')
223
+ nextIndex++;
224
+ return codeLeadForFollowingFence(tokens, previousIndex) != null && tokens[nextIndex]?.type === 'code';
225
+ }
226
+ function parseCodeFenceInfo(info) {
227
+ const parts = info?.trim().split(/\s+/).filter(Boolean) ?? [];
228
+ const firstSource = parts.findIndex(part => parseCodeSource(part) != null);
229
+ if (firstSource === -1)
230
+ return { language: parts[0] };
231
+ return {
232
+ language: firstSource === 0 ? undefined : parts[0],
233
+ source: parseCodeSource(parts[firstSource]),
234
+ };
77
235
  }
78
236
  function InlineMarkdown({ text }) {
79
237
  const parts = tokenizeInline(text);
80
- return _jsx(Text, { children: parts.map((part, index) => {
81
- if (part.kind === 'code')
82
- return _jsx(Text, { color: theme.warning, children: part.text }, index);
83
- if (part.kind === 'strong')
84
- return _jsx(Text, { bold: true, children: part.text }, index);
85
- if (part.kind === 'em')
86
- return _jsx(Text, { italic: true, children: part.text }, index);
87
- if (part.kind === 'link')
88
- return _jsx(Text, { color: theme.violet, children: part.text }, index);
89
- return _jsx(Text, { children: part.text }, index);
90
- }) });
238
+ return _jsx(Text, { children: parts.map((part, index) => renderInlinePart(part, index)) });
239
+ }
240
+ function renderInlinePart(part, index) {
241
+ if (part.kind === 'code')
242
+ return _jsx(Text, { color: theme.warning, backgroundColor: theme.codeBg, children: part.text }, index);
243
+ if (part.kind === 'strong')
244
+ return _jsx(Text, { bold: true, children: part.text }, index);
245
+ if (part.kind === 'em')
246
+ return _jsx(Text, { italic: true, children: part.text }, index);
247
+ if (part.kind === 'link')
248
+ return _jsx(Text, { color: theme.purple, children: part.text }, index);
249
+ return _jsx(Text, { children: part.text }, index);
250
+ }
251
+ function splitInlineIntoAtoms(parts) {
252
+ const atoms = [];
253
+ for (const part of parts) {
254
+ for (const piece of part.text.split(/(\s+)/)) {
255
+ if (piece === '')
256
+ continue;
257
+ if (/^\s+$/.test(piece))
258
+ atoms.push({ type: 'space' });
259
+ else
260
+ atoms.push({ type: 'word', kind: part.kind, text: piece });
261
+ }
262
+ }
263
+ return atoms;
264
+ }
265
+ function wrapInlineAtoms(atoms, maxWidth) {
266
+ const lines = [];
267
+ let line = [];
268
+ let width = 0;
269
+ const flushLine = () => {
270
+ while (line.length > 0 && line[line.length - 1].type === 'space')
271
+ line.pop();
272
+ if (line.length > 0)
273
+ lines.push(line);
274
+ line = [];
275
+ width = 0;
276
+ };
277
+ for (const atom of atoms) {
278
+ if (atom.type === 'space') {
279
+ if (width > 0) {
280
+ line.push(atom);
281
+ width += 1;
282
+ }
283
+ continue;
284
+ }
285
+ const wordWidth = visibleLength(atom.text);
286
+ if (wordWidth > maxWidth && width === 0) {
287
+ // Overlong word on its own line: keep it whole so we don't pretend to
288
+ // have wrap behavior we can't actually render.
289
+ lines.push([atom]);
290
+ line = [];
291
+ width = 0;
292
+ continue;
293
+ }
294
+ if (width > 0 && width + wordWidth > maxWidth)
295
+ flushLine();
296
+ line.push(atom);
297
+ width += wordWidth;
298
+ }
299
+ flushLine();
300
+ return lines.length > 0 ? lines : [[]];
91
301
  }
92
302
  function tokenizeInline(text) {
93
303
  const out = [];