march-cli 0.1.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 (217) hide show
  1. package/bin/march.mjs +13 -0
  2. package/package.json +36 -0
  3. package/src/agent/command-exec-tool.mjs +91 -0
  4. package/src/agent/context-stats-tool.mjs +57 -0
  5. package/src/agent/editing/diff-apply.mjs +28 -0
  6. package/src/agent/editing/diff-format.mjs +57 -0
  7. package/src/agent/file-edit-tool.mjs +276 -0
  8. package/src/agent/find-tool.mjs +112 -0
  9. package/src/agent/model-payload-dumper.mjs +201 -0
  10. package/src/agent/pi-session/pi-session-sidecar-failure.mjs +10 -0
  11. package/src/agent/provider/payload-messages.mjs +138 -0
  12. package/src/agent/read-file-tool.mjs +112 -0
  13. package/src/agent/runner/fast-model.mjs +36 -0
  14. package/src/agent/runner/runner-cleanup.mjs +12 -0
  15. package/src/agent/runner/runner-init.mjs +15 -0
  16. package/src/agent/runner/runner-session-state.mjs +40 -0
  17. package/src/agent/runner.mjs +266 -0
  18. package/src/agent/runtime/runner-runtime-host.mjs +73 -0
  19. package/src/agent/runtime/runtime-factory.mjs +42 -0
  20. package/src/agent/runtime/runtime-host.mjs +34 -0
  21. package/src/agent/session/session-auto-name.mjs +41 -0
  22. package/src/agent/session/session-binding.mjs +12 -0
  23. package/src/agent/session/session-options.mjs +46 -0
  24. package/src/agent/tool-names.mjs +1 -0
  25. package/src/agent/tool-result.mjs +3 -0
  26. package/src/agent/tools.mjs +54 -0
  27. package/src/agent/turn/turn-events.mjs +64 -0
  28. package/src/agent/turn/turn-runner.mjs +103 -0
  29. package/src/auth/login-command.mjs +90 -0
  30. package/src/auth/storage.mjs +33 -0
  31. package/src/cli/args.mjs +71 -0
  32. package/src/cli/commands/copy-command.mjs +73 -0
  33. package/src/cli/commands/export-command.mjs +206 -0
  34. package/src/cli/commands/extensions-command.mjs +53 -0
  35. package/src/cli/commands/help-command.mjs +7 -0
  36. package/src/cli/commands/model-command.mjs +110 -0
  37. package/src/cli/commands/paste-image-command.mjs +43 -0
  38. package/src/cli/commands/provider-command.mjs +55 -0
  39. package/src/cli/commands/status-command.mjs +157 -0
  40. package/src/cli/commands/thinking-command.mjs +80 -0
  41. package/src/cli/fallback-ui.mjs +156 -0
  42. package/src/cli/input/attachment-tokens.mjs +20 -0
  43. package/src/cli/input/autocomplete.mjs +106 -0
  44. package/src/cli/input/external-editor.mjs +39 -0
  45. package/src/cli/input/history-store.mjs +35 -0
  46. package/src/cli/input/image-clipboard.mjs +55 -0
  47. package/src/cli/input/keybinding-dispatch.mjs +76 -0
  48. package/src/cli/input/keybindings.mjs +96 -0
  49. package/src/cli/input/mode-state.mjs +43 -0
  50. package/src/cli/input/prompt-templates.mjs +84 -0
  51. package/src/cli/input/select-with-keyboard.mjs +67 -0
  52. package/src/cli/permissions.mjs +103 -0
  53. package/src/cli/repl-commands.mjs +86 -0
  54. package/src/cli/repl-loop.mjs +157 -0
  55. package/src/cli/selector-list.mjs +21 -0
  56. package/src/cli/session/pi-session-switch-command.mjs +41 -0
  57. package/src/cli/session/session-command.mjs +23 -0
  58. package/src/cli/session/session-list-command.mjs +68 -0
  59. package/src/cli/session/session-name-command.mjs +26 -0
  60. package/src/cli/session/session-source-command.mjs +89 -0
  61. package/src/cli/session/session-switch-command.mjs +1 -0
  62. package/src/cli/shell/shell-command.mjs +55 -0
  63. package/src/cli/shell/shell-drawer-controls.mjs +33 -0
  64. package/src/cli/shell/shell-drawer.mjs +192 -0
  65. package/src/cli/shell/shell-split-layout.mjs +70 -0
  66. package/src/cli/slash-commands.mjs +176 -0
  67. package/src/cli/startup/startup-banner.mjs +17 -0
  68. package/src/cli/startup/startup-session.mjs +51 -0
  69. package/src/cli/status-line-updater.mjs +74 -0
  70. package/src/cli/tool-output.mjs +9 -0
  71. package/src/cli/tui/editor/external-editor-runner.mjs +24 -0
  72. package/src/cli/tui/input/mouse-selection-controller.mjs +89 -0
  73. package/src/cli/tui/input/mouse-tracking.mjs +20 -0
  74. package/src/cli/tui/layout/main-pane-layout.mjs +38 -0
  75. package/src/cli/tui/layout/safe-render-boundary.mjs +46 -0
  76. package/src/cli/tui/markdown-renderer.mjs +279 -0
  77. package/src/cli/tui/output/scroll-state.mjs +79 -0
  78. package/src/cli/tui/output/tool-card-renderer.mjs +59 -0
  79. package/src/cli/tui/output-buffer.mjs +297 -0
  80. package/src/cli/tui/permission-request-ui.mjs +18 -0
  81. package/src/cli/tui/recall-rendering.mjs +25 -0
  82. package/src/cli/tui/select/editor-select-list.mjs +111 -0
  83. package/src/cli/tui/selection-screen.mjs +212 -0
  84. package/src/cli/tui/status/retry-status.mjs +72 -0
  85. package/src/cli/tui/status/spinner-status.mjs +42 -0
  86. package/src/cli/tui/status/status-bar.mjs +88 -0
  87. package/src/cli/tui/syntax/highlighting.mjs +277 -0
  88. package/src/cli/tui/syntax/languages.mjs +91 -0
  89. package/src/cli/tui/syntax/tree-sitter/bash.highlights.scm +261 -0
  90. package/src/cli/tui/syntax/tree-sitter/c.highlights.scm +341 -0
  91. package/src/cli/tui/syntax/tree-sitter/cpp.highlights.scm +268 -0
  92. package/src/cli/tui/syntax/tree-sitter/csharp.highlights.scm +577 -0
  93. package/src/cli/tui/syntax/tree-sitter/css.highlights.scm +109 -0
  94. package/src/cli/tui/syntax/tree-sitter/diff.highlights.scm +49 -0
  95. package/src/cli/tui/syntax/tree-sitter/go.highlights.scm +254 -0
  96. package/src/cli/tui/syntax/tree-sitter/html.highlights.scm +13 -0
  97. package/src/cli/tui/syntax/tree-sitter/java.highlights.scm +330 -0
  98. package/src/cli/tui/syntax/tree-sitter/json.highlights.scm +38 -0
  99. package/src/cli/tui/syntax/tree-sitter/php.highlights.scm +203 -0
  100. package/src/cli/tui/syntax/tree-sitter/python.highlights.scm +137 -0
  101. package/src/cli/tui/syntax/tree-sitter/ruby.highlights.scm +309 -0
  102. package/src/cli/tui/syntax/tree-sitter/rust.highlights.scm +531 -0
  103. package/src/cli/tui/syntax/tree-sitter/toml.highlights.scm +39 -0
  104. package/src/cli/tui/syntax/tree-sitter/tree-sitter-bash.wasm +0 -0
  105. package/src/cli/tui/syntax/tree-sitter/tree-sitter-c-sharp.wasm +0 -0
  106. package/src/cli/tui/syntax/tree-sitter/tree-sitter-c.wasm +0 -0
  107. package/src/cli/tui/syntax/tree-sitter/tree-sitter-cpp.wasm +0 -0
  108. package/src/cli/tui/syntax/tree-sitter/tree-sitter-css.wasm +0 -0
  109. package/src/cli/tui/syntax/tree-sitter/tree-sitter-diff.wasm +0 -0
  110. package/src/cli/tui/syntax/tree-sitter/tree-sitter-go.wasm +0 -0
  111. package/src/cli/tui/syntax/tree-sitter/tree-sitter-html.wasm +0 -0
  112. package/src/cli/tui/syntax/tree-sitter/tree-sitter-java.wasm +0 -0
  113. package/src/cli/tui/syntax/tree-sitter/tree-sitter-json.wasm +0 -0
  114. package/src/cli/tui/syntax/tree-sitter/tree-sitter-php.wasm +0 -0
  115. package/src/cli/tui/syntax/tree-sitter/tree-sitter-python.wasm +0 -0
  116. package/src/cli/tui/syntax/tree-sitter/tree-sitter-ruby.wasm +0 -0
  117. package/src/cli/tui/syntax/tree-sitter/tree-sitter-rust.wasm +0 -0
  118. package/src/cli/tui/syntax/tree-sitter/tree-sitter-toml.wasm +0 -0
  119. package/src/cli/tui/syntax/tree-sitter/tree-sitter-tsx.wasm +0 -0
  120. package/src/cli/tui/syntax/tree-sitter/tree-sitter-typescript.wasm +0 -0
  121. package/src/cli/tui/syntax/tree-sitter/tree-sitter-yaml.wasm +0 -0
  122. package/src/cli/tui/syntax/tree-sitter/tsx.highlights.scm +35 -0
  123. package/src/cli/tui/syntax/tree-sitter/typescript.highlights.scm +35 -0
  124. package/src/cli/tui/syntax/tree-sitter/yaml.highlights.scm +99 -0
  125. package/src/cli/tui/tool-rendering.mjs +194 -0
  126. package/src/cli/tui/tui-diff-rendering.mjs +157 -0
  127. package/src/cli/tui/tui-handlers.mjs +110 -0
  128. package/src/cli/tui/tui-input-controller.mjs +61 -0
  129. package/src/cli/tui/ui-theme.mjs +148 -0
  130. package/src/cli/ui.mjs +299 -0
  131. package/src/config/config-json.mjs +73 -0
  132. package/src/config/dotenv.mjs +20 -0
  133. package/src/config/features.mjs +75 -0
  134. package/src/config/loader.mjs +109 -0
  135. package/src/config/settings-command.mjs +97 -0
  136. package/src/context/diagnostics.mjs +70 -0
  137. package/src/context/engine.mjs +148 -0
  138. package/src/context/injections.mjs +26 -0
  139. package/src/context/project-context.mjs +20 -0
  140. package/src/context/session-status.mjs +15 -0
  141. package/src/context/shell-layers.mjs +23 -0
  142. package/src/context/system-core/base.md +60 -0
  143. package/src/context/system-core/prompts/deepseek-v4-pro.md +3 -0
  144. package/src/context/system-core/prompts/default.md +3 -0
  145. package/src/context/system-core.mjs +35 -0
  146. package/src/debug/model-context-dumper.mjs +52 -0
  147. package/src/extensions/discovery.mjs +40 -0
  148. package/src/extensions/lifecycle-adapter.mjs +210 -0
  149. package/src/extensions/lifecycle-manifest.mjs +69 -0
  150. package/src/image-gen/index.mjs +7 -0
  151. package/src/image-gen/provider.mjs +231 -0
  152. package/src/image-gen/tool.mjs +84 -0
  153. package/src/lsp/client.mjs +204 -0
  154. package/src/lsp/diagnostic-store.mjs +39 -0
  155. package/src/lsp/servers.mjs +212 -0
  156. package/src/lsp/service.mjs +65 -0
  157. package/src/main.mjs +294 -0
  158. package/src/mcp/client.mjs +195 -0
  159. package/src/mcp/config.mjs +130 -0
  160. package/src/mcp/index.mjs +48 -0
  161. package/src/mcp/tools.mjs +98 -0
  162. package/src/memory/database.mjs +219 -0
  163. package/src/memory/glossary.mjs +124 -0
  164. package/src/memory/graph/graph-cascades.mjs +109 -0
  165. package/src/memory/graph/graph-diagnostics.mjs +73 -0
  166. package/src/memory/graph/graph-path-removal.mjs +50 -0
  167. package/src/memory/graph/graph-path-utils.mjs +17 -0
  168. package/src/memory/graph/graph-primitives.mjs +103 -0
  169. package/src/memory/graph/graph-read.mjs +159 -0
  170. package/src/memory/graph.mjs +282 -0
  171. package/src/memory/markdown/markdown-delete.mjs +23 -0
  172. package/src/memory/markdown/markdown-format.mjs +128 -0
  173. package/src/memory/markdown/markdown-recall.mjs +28 -0
  174. package/src/memory/markdown/ripgrep.mjs +16 -0
  175. package/src/memory/markdown/sqlite-index.mjs +87 -0
  176. package/src/memory/markdown-store.mjs +286 -0
  177. package/src/memory/markdown-tools.mjs +103 -0
  178. package/src/memory/search.mjs +142 -0
  179. package/src/memory/snapshot.mjs +86 -0
  180. package/src/memory/system-views.mjs +120 -0
  181. package/src/memory/tools.mjs +282 -0
  182. package/src/notification/desktop-notifier.mjs +85 -0
  183. package/src/platform/open-file.mjs +28 -0
  184. package/src/provider/config-command.mjs +129 -0
  185. package/src/provider/presets.mjs +72 -0
  186. package/src/session/attachment-display.mjs +16 -0
  187. package/src/session/attachment-references.mjs +65 -0
  188. package/src/session/attachments.mjs +140 -0
  189. package/src/session/persist.mjs +1 -0
  190. package/src/session/pi-manager.mjs +34 -0
  191. package/src/session/session-utils.mjs +16 -0
  192. package/src/session/sidecar-sync.mjs +19 -0
  193. package/src/session/sidecar.mjs +68 -0
  194. package/src/session/transcript.mjs +83 -0
  195. package/src/session/tree.mjs +42 -0
  196. package/src/shell/cli-runtime.mjs +11 -0
  197. package/src/shell/hints.mjs +12 -0
  198. package/src/shell/node-pty-adapter.mjs +81 -0
  199. package/src/shell/runtime-state.mjs +126 -0
  200. package/src/shell/runtime.mjs +244 -0
  201. package/src/shell/screen-buffer.mjs +136 -0
  202. package/src/shell/tool-read.mjs +74 -0
  203. package/src/shell/tools.mjs +299 -0
  204. package/src/supergrok/actions/image-generate.mjs +60 -0
  205. package/src/supergrok/actions/search.mjs +78 -0
  206. package/src/supergrok/auth.mjs +36 -0
  207. package/src/supergrok/constants.mjs +18 -0
  208. package/src/supergrok/oauth-provider.mjs +278 -0
  209. package/src/supergrok/provider.mjs +36 -0
  210. package/src/supergrok/response.mjs +76 -0
  211. package/src/supergrok/tool.mjs +61 -0
  212. package/src/text/ansi.mjs +3 -0
  213. package/src/web/config-command.mjs +43 -0
  214. package/src/web/fetch.mjs +78 -0
  215. package/src/web/presets.mjs +16 -0
  216. package/src/web/search.mjs +83 -0
  217. package/src/web/tools.mjs +107 -0
@@ -0,0 +1,89 @@
1
+ import { parseMouseEvent } from "./mouse-tracking.mjs";
2
+ import { brightBlack } from "../ui-theme.mjs";
3
+
4
+ export function createMouseSelectionController({
5
+ terminal,
6
+ output,
7
+ shellDrawer,
8
+ shellDrawerControls,
9
+ selection,
10
+ writeClipboard,
11
+ requestRender,
12
+ }) {
13
+ function copySelectionText(text) {
14
+ if (!text) return false;
15
+ let result;
16
+ try {
17
+ result = writeClipboard(text);
18
+ } catch (err) {
19
+ setCopyStatus({ ok: false, message: err.message }, text.length);
20
+ return false;
21
+ }
22
+ if (result?.then) {
23
+ output.setOverlayStatus([brightBlack(`● copying selection (${text.length} chars)`)]);
24
+ requestRender();
25
+ result.then(
26
+ (resolved) => setCopyStatus(resolved, text.length),
27
+ (err) => setCopyStatus({ ok: false, message: err.message }, text.length)
28
+ );
29
+ return true;
30
+ }
31
+ setCopyStatus(result, text.length);
32
+ return result?.ok !== false;
33
+ }
34
+
35
+ function setCopyStatus(result, length) {
36
+ output.setOverlayStatus([
37
+ result?.ok === false
38
+ ? brightBlack(`● selection copy failed: ${compactStatusMessage(result.message)}`)
39
+ : brightBlack(`● copied selection (${length} chars)`),
40
+ ]);
41
+ requestRender();
42
+ }
43
+
44
+ return {
45
+ handleMouseInput(data, mouseOn) {
46
+ if (!mouseOn) return undefined;
47
+ const mouse = parseMouseEvent(data);
48
+ if (mouse?.type === "scroll") {
49
+ if (shellDrawer.isVisible?.() && mouse.col > Math.floor((terminal.columns || 80) * 0.64)) {
50
+ shellDrawerControls.scroll(mouse.delta);
51
+ } else {
52
+ output.scroll(mouse.delta);
53
+ }
54
+ requestRender();
55
+ return { consume: true };
56
+ }
57
+ if (mouse?.type === "down" && mouse.button === 0) {
58
+ selection.start(mouse);
59
+ requestRender();
60
+ return { consume: true };
61
+ }
62
+ if (mouse?.type === "drag" && mouse.button === 0) {
63
+ selection.update(mouse);
64
+ requestRender();
65
+ return { consume: true };
66
+ }
67
+ if (mouse?.type === "up") {
68
+ selection.finish(mouse, { clear: false });
69
+ requestRender();
70
+ return { consume: true };
71
+ }
72
+ return undefined;
73
+ },
74
+
75
+ handleCopyKey(data) {
76
+ if (data !== "\x03") return undefined;
77
+ const text = selection.text();
78
+ if (!text) return undefined;
79
+ selection.clear();
80
+ copySelectionText(text);
81
+ return { consume: true };
82
+ },
83
+ };
84
+ }
85
+
86
+ function compactStatusMessage(message) {
87
+ const text = String(message || "unknown error").replace(/\s+/g, " ").trim();
88
+ return text.length > 80 ? `${text.slice(0, 79)}…` : text;
89
+ }
@@ -0,0 +1,20 @@
1
+ export function parseMouseEvent(data) {
2
+ const match = data.match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/);
3
+ if (!match) return null;
4
+ const code = parseInt(match[1], 10);
5
+ const col = parseInt(match[2], 10);
6
+ const row = parseInt(match[3], 10);
7
+ const final = match[4];
8
+
9
+ if (code === 64 || code === 65) {
10
+ return { type: "scroll", delta: code === 64 ? -1 : 1, col, row };
11
+ }
12
+ if (final === "m") return { type: "up", button: code & 3, col, row };
13
+ if ((code & 32) === 32) return { type: "drag", button: code & 3, col, row };
14
+ return { type: "down", button: code & 3, col, row };
15
+ }
16
+
17
+ export function parseMouseScroll(data) {
18
+ const event = parseMouseEvent(data);
19
+ return event?.type === "scroll" ? event.delta : null;
20
+ }
@@ -0,0 +1,38 @@
1
+ export class MainPaneLayout {
2
+ constructor({ output, statusBar, editor, terminal, selection = null }) {
3
+ this.output = output;
4
+ this.statusBar = statusBar;
5
+ this.editor = editor;
6
+ this.terminal = terminal;
7
+ this.selection = selection;
8
+ }
9
+
10
+ render(width) {
11
+ const safeWidth = Math.max(1, Math.trunc(width));
12
+ const statusLines = this.statusBar.render(safeWidth);
13
+ const editorLines = this.editor.render(safeWidth);
14
+ const fixedHeight = statusLines.length + editorLines.length;
15
+ const viewportHeight = Math.max(1, (this.terminal?.rows || 30) - fixedHeight);
16
+ this.output.setViewportHeight(viewportHeight);
17
+ const outputLines = this.output.render(safeWidth);
18
+ const outputTop = Math.max(0, viewportHeight - outputLines.length);
19
+ this.selection?.setViewport({ topRow: outputTop, leftCol: 0, width: safeWidth, lines: outputLines });
20
+ const selectedOutputLines = this.selection?.apply(outputLines) ?? outputLines;
21
+ return [
22
+ ...padToHeight(selectedOutputLines, viewportHeight),
23
+ ...statusLines,
24
+ ...editorLines,
25
+ ];
26
+ }
27
+
28
+ invalidate() {
29
+ this.output.invalidate?.();
30
+ this.statusBar.invalidate?.();
31
+ this.editor.invalidate?.();
32
+ }
33
+ }
34
+
35
+ function padToHeight(lines, height) {
36
+ if (lines.length >= height) return lines;
37
+ return [...Array(height - lines.length).fill(""), ...lines];
38
+ }
@@ -0,0 +1,46 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { brightBlack } from "../ui-theme.mjs";
3
+
4
+ export class SafeRenderBoundary {
5
+ constructor(child, { onError = null } = {}) {
6
+ this.child = child;
7
+ this.onError = onError;
8
+ }
9
+
10
+ render(width) {
11
+ const safeWidth = Math.max(1, Math.trunc(width));
12
+ try {
13
+ return sanitizeRenderedLines(this.child.render(safeWidth), safeWidth);
14
+ } catch (err) {
15
+ this.onError?.(err);
16
+ return sanitizeRenderedLines([brightBlack(`March UI recovered from render error: ${err.message}`)], safeWidth);
17
+ }
18
+ }
19
+
20
+ invalidate() {
21
+ this.child.invalidate?.();
22
+ }
23
+ }
24
+
25
+ export function sanitizeRenderedLines(lines, width) {
26
+ const safeWidth = Math.max(1, Math.trunc(width));
27
+ const result = [];
28
+ for (const line of Array.isArray(lines) ? lines : []) {
29
+ for (const part of String(line ?? "").split(/\r?\n/)) {
30
+ result.push(fitRenderedLine(part, safeWidth));
31
+ }
32
+ }
33
+ return result;
34
+ }
35
+
36
+ function fitRenderedLine(line, width) {
37
+ if (visibleWidth(line) <= width) return line;
38
+ const truncated = truncateToWidth(line, width, "…");
39
+ if (visibleWidth(truncated) <= width) return truncated;
40
+ const plain = truncateToWidth(stripAnsi(line), width, "…");
41
+ return visibleWidth(plain) <= width ? plain : "";
42
+ }
43
+
44
+ function stripAnsi(text) {
45
+ return String(text ?? "").replace(/\x1b(?:\][^\x07]*(?:\x07|\x1b\\)|[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
46
+ }
@@ -0,0 +1,279 @@
1
+ import { marked } from "marked";
2
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { R, brightBlack, dim, orange, softGreen, bold, cyan } from "./ui-theme.mjs";
4
+ import { highlightCodeLines } from "./syntax/highlighting.mjs";
5
+ const TABLE_CELL_PADDING = 2;
6
+ export function renderMarkdown(markdown, width) {
7
+ return renderMarkdownText(markdown, Math.max(1, width));
8
+ }
9
+ export function renderStreamingMarkdown(markdown, width, cache = new Map()) {
10
+ const text = String(markdown ?? "");
11
+ const maxWidth = Math.max(1, width);
12
+ const split = splitStableMarkdown(text);
13
+ if (!split.prefix) return renderMarkdownText(split.tail, maxWidth);
14
+
15
+ const key = `${maxWidth}\0${split.prefix}`;
16
+ let prefixLines = cache.get(key);
17
+ if (!prefixLines) {
18
+ prefixLines = renderMarkdownText(split.prefix, maxWidth);
19
+ cache.set(key, prefixLines);
20
+ }
21
+ const tailLines = split.tail ? renderMarkdownText(split.tail, maxWidth) : [];
22
+ return tailLines.length ? [...prefixLines, ...tailLines] : prefixLines;
23
+ }
24
+
25
+ function renderMarkdownText(markdown, maxWidth) {
26
+ let tokens;
27
+ try {
28
+ tokens = marked.lexer(String(markdown ?? ""));
29
+ } catch {
30
+ return renderPlainMarkdownFallback(markdown, maxWidth);
31
+ }
32
+ const lines = [];
33
+ for (const token of tokens) renderBlock(token, lines, maxWidth, 0);
34
+ return clampRenderedLines(lines.length ? lines : [""], maxWidth);
35
+ }
36
+
37
+ function clampRenderedLines(lines, width) {
38
+ return lines.flatMap((line) => String(line ?? "").split(/\r?\n/).map((part) => fitMarkdownLine(part, width)));
39
+ }
40
+
41
+ function fitMarkdownLine(line, width) {
42
+ if (visibleWidth(line) <= width) return line;
43
+ const truncated = truncateToWidth(line, width, "…");
44
+ return visibleWidth(truncated) <= width ? truncated : "";
45
+ }
46
+
47
+ function splitStableMarkdown(text) {
48
+ const lines = text.split("\n");
49
+ let offset = 0;
50
+ let stableOffset = 0;
51
+ let inFence = false;
52
+ for (const line of lines) {
53
+ const nextOffset = offset + line.length + 1;
54
+ if (/^\s*```/.test(line)) {
55
+ inFence = !inFence;
56
+ if (!inFence) stableOffset = Math.min(text.length, nextOffset);
57
+ } else if (!inFence && line.trim() === "") {
58
+ stableOffset = Math.min(text.length, nextOffset);
59
+ }
60
+ offset = nextOffset;
61
+ }
62
+ return { prefix: text.slice(0, stableOffset), tail: text.slice(stableOffset) };
63
+ }
64
+
65
+ function renderBlock(token, lines, width, depth) {
66
+ if (!token) return;
67
+ if (token.type === "space") {
68
+ if (lines.length && lines.at(-1) !== "") lines.push("");
69
+ return;
70
+ }
71
+ if (token.type === "heading") {
72
+ if (lines.length && lines.at(-1) !== "") lines.push("");
73
+ appendWrappedRuns(lines, inlineRuns(token.tokens ?? [{ type: "text", text: token.text }], "heading"), width, 0);
74
+ return;
75
+ }
76
+ if (token.type === "paragraph" || token.type === "text") {
77
+ appendWrappedRuns(lines, inlineRuns(token.tokens ?? [{ type: "text", text: token.text }]), width, depth * 2);
78
+ return;
79
+ }
80
+ if (token.type === "list") return renderList(token, lines, width, depth);
81
+ if (token.type === "table") return renderTable(token, lines, width);
82
+ if (token.type === "blockquote") return renderBlockquote(token, lines, width, depth);
83
+ if (token.type === "code") return renderCode(token, lines, width);
84
+ if (token.type === "hr") {
85
+ lines.push(brightBlack("─".repeat(Math.min(width, 60))));
86
+ return;
87
+ }
88
+ appendWrappedRuns(lines, [{ text: token.raw ?? token.text ?? "", style: null }], width, depth * 2);
89
+ }
90
+
91
+ function renderList(token, lines, width, depth) {
92
+ token.items?.forEach((item, index) => {
93
+ const marker = token.ordered ? `${Number(token.start || 1) + index}.` : "•";
94
+ const prefix = `${' '.repeat(depth)}${cyan(marker)} `;
95
+ const inlineTokens = item.tokens?.filter((t) => t.type !== "list") ?? [];
96
+ const nested = item.tokens?.filter((t) => t.type === "list") ?? [];
97
+ const runs = inlineTokens.length
98
+ ? inlineTokens.flatMap((t) => inlineRuns(t.tokens ?? [{ type: "text", text: t.text }]))
99
+ : inlineRuns([{ type: "text", text: item.text ?? "" }]);
100
+ appendWrappedRuns(lines, runs, width, visibleWidth(stripAnsi(prefix)), prefix);
101
+ for (const child of nested) renderList(child, lines, width, depth + 1);
102
+ });
103
+ }
104
+
105
+ function renderTable(token, lines, width) {
106
+ const rows = [token.header ?? [], ...(token.rows ?? [])];
107
+ if (!rows.length) return;
108
+ const cells = rows.map((row) => row.map((cell) => plainInline(cell.tokens ?? [{ type: "text", text: cell.text }])));
109
+ const columnCount = Math.max(...cells.map((row) => row.length));
110
+ const widths = Array.from({ length: columnCount }, (_, i) => Math.max(3, ...cells.map((row) => visibleWidth(row[i] ?? ""))));
111
+ const borderWidth = columnCount + 1;
112
+ const paddingWidth = TABLE_CELL_PADDING * columnCount;
113
+ shrinkColumns(widths, Math.max(1, width - borderWidth - paddingWidth));
114
+
115
+ lines.push(formatTableBorder(widths, "┌", "┬", "┐"));
116
+ lines.push(formatTableRow(cells[0], widths, true));
117
+ lines.push(formatTableBorder(widths, "├", "┼", "┤"));
118
+ for (const row of cells.slice(1)) lines.push(formatTableRow(row, widths, false));
119
+ lines.push(formatTableBorder(widths, "└", "┴", "┘"));
120
+ }
121
+
122
+ function renderBlockquote(token, lines, width, depth) {
123
+ const inner = [];
124
+ for (const child of token.tokens ?? []) renderBlock(child, inner, Math.max(1, width - 2), depth);
125
+ for (const line of inner) lines.push(`${brightBlack("│")} ${dim(line)}`);
126
+ }
127
+
128
+ function renderCode(token, lines, width) {
129
+ const innerWidth = Math.max(1, width - 4);
130
+ lines.push(formatCodeBorder("╭", token.lang ? ` ${token.lang} ` : "", "╮", width));
131
+ for (const line of highlightCodeLines(String(token.text ?? ""), token.lang)) {
132
+ for (const wrapped of wrapAnsi(line, innerWidth)) {
133
+ lines.push(formatCodeLine(wrapped, width));
134
+ }
135
+ }
136
+ lines.push(formatCodeBorder("╰", "", "╯", width));
137
+ }
138
+
139
+ function formatCodeBorder(left, label, right, width) {
140
+ const prefix = `${left}─${label}`;
141
+ const fill = "─".repeat(Math.max(0, width - visibleWidth(prefix) - 1));
142
+ return brightBlack(`${prefix}${fill}${right}`);
143
+ }
144
+
145
+ function formatCodeLine(content, width) {
146
+ const padding = " ".repeat(Math.max(0, width - visibleWidth(stripAnsi(content)) - 4));
147
+ return `${brightBlack("│")} ${content}${padding} ${brightBlack("│")}`;
148
+ }
149
+
150
+ function inlineRuns(tokens, forcedStyle = null) {
151
+ const runs = [];
152
+ for (const token of tokens ?? []) {
153
+ if (token.type === "strong") runs.push(...inlineRuns(token.tokens, "strong"));
154
+ else if (token.type === "em") runs.push(...inlineRuns(token.tokens, "em"));
155
+ else if (token.type === "codespan") runs.push({ text: token.text ?? "", style: "code" });
156
+ else if (token.type === "link") runs.push(...inlineRuns(token.tokens ?? [{ type: "text", text: token.text }], "link"));
157
+ else runs.push({ text: token.text ?? token.raw ?? "", style: forcedStyle });
158
+ }
159
+ return runs;
160
+ }
161
+
162
+ function appendWrappedRuns(lines, runs, width, indent = 0, firstPrefix = null) {
163
+ const prefix = firstPrefix ?? " ".repeat(indent);
164
+ const restPrefix = " ".repeat(indent);
165
+ let current = prefix;
166
+ let currentWidth = visibleWidth(stripAnsi(prefix));
167
+ const maxWidth = Math.max(1, width);
168
+ for (const run of runs) {
169
+ for (const ch of run.text) {
170
+ const charWidth = visibleWidth(ch);
171
+ if (currentWidth + charWidth > maxWidth && currentWidth > visibleWidth(stripAnsi(prefix))) {
172
+ lines.push(current);
173
+ current = restPrefix;
174
+ currentWidth = visibleWidth(restPrefix);
175
+ }
176
+ current += styleText(ch, run.style);
177
+ currentWidth += charWidth;
178
+ }
179
+ }
180
+ lines.push(current);
181
+ }
182
+
183
+ function styleText(text, style) {
184
+ if (!style) return text;
185
+ if (style === "heading" || style === "strong") return orange(text);
186
+ if (style === "code") return softGreen(text);
187
+ if (style === "em") return dim(text);
188
+ if (style === "link") return cyan(text);
189
+ return text;
190
+ }
191
+
192
+ function plainInline(tokens) {
193
+ return stripAnsi(inlineRuns(tokens).map((run) => run.text).join(""));
194
+ }
195
+
196
+ function formatTableRow(row, widths, header) {
197
+ const cells = widths.map((width, i) => {
198
+ const text = truncateCell(row[i] ?? "", width);
199
+ const padded = text + " ".repeat(Math.max(0, width - visibleWidth(text)));
200
+ return ` ${header ? bold(padded) : padded} `;
201
+ });
202
+ return `${brightBlack("│")}${cells.join(brightBlack("│"))}${brightBlack("│")}`;
203
+ }
204
+
205
+ function formatTableBorder(widths, left, join, right) {
206
+ return brightBlack(`${left}${widths.map((width) => "─".repeat(width + TABLE_CELL_PADDING)).join(join)}${right}`);
207
+ }
208
+
209
+ function shrinkColumns(widths, maxTotal) {
210
+ while (widths.reduce((a, b) => a + b, 0) > maxTotal && Math.max(...widths) > 6) {
211
+ const index = widths.indexOf(Math.max(...widths));
212
+ widths[index] -= 1;
213
+ }
214
+ }
215
+
216
+ function truncateCell(text, width) {
217
+ const chars = [];
218
+ const sourceChars = Array.from(text);
219
+ let used = 0;
220
+ for (const ch of sourceChars) {
221
+ const w = visibleWidth(ch);
222
+ if (used + w > width) break;
223
+ chars.push(ch);
224
+ used += w;
225
+ }
226
+ if (chars.length < sourceChars.length && width > 1) {
227
+ while (chars.length && used + 1 > width) used -= visibleWidth(chars.pop());
228
+ return `${chars.join("")}…`;
229
+ }
230
+ return chars.join("");
231
+ }
232
+
233
+ function renderPlainMarkdownFallback(markdown, width) {
234
+ return String(markdown ?? "").split("\n").flatMap((line) => wrapAnsi(line, width));
235
+ }
236
+
237
+ function wrapAnsi(text, maxWidth) {
238
+ if (maxWidth <= 0) return [""];
239
+ const result = [];
240
+ let cur = "";
241
+ let curW = 0;
242
+ let activeSgr = "";
243
+ for (let i = 0; i < text.length;) {
244
+ if (text[i] === "\x1b") {
245
+ const match = text.slice(i).match(/^\x1b\[[0-?]*[ -/]*[@-~]/);
246
+ if (match) {
247
+ const seq = match[0];
248
+ cur += seq;
249
+ activeSgr = updateActiveSgr(activeSgr, seq);
250
+ i += seq.length;
251
+ continue;
252
+ }
253
+ }
254
+ const ch = text[i];
255
+ const w = visibleWidth(ch);
256
+ if (curW + w > maxWidth) {
257
+ result.push(activeSgr ? `${cur}${R}` : cur);
258
+ cur = activeSgr + ch;
259
+ curW = w;
260
+ } else {
261
+ cur += ch;
262
+ curW += w;
263
+ }
264
+ i += 1;
265
+ }
266
+ if (cur) result.push(cur);
267
+ return result.length ? result : [""];
268
+ }
269
+
270
+ function updateActiveSgr(activeSgr, seq) {
271
+ if (!seq.endsWith("m")) return activeSgr;
272
+ const body = seq.slice(2, -1);
273
+ if (body === "" || body.split(";").includes("0")) return "";
274
+ return seq;
275
+ }
276
+
277
+ function stripAnsi(text) {
278
+ return String(text ?? "").replace(/\x1b(?:\][^\x07]*(?:\x07|\x1b\\)|[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
279
+ }
@@ -0,0 +1,79 @@
1
+ export class OutputScrollState {
2
+ constructor() {
3
+ this.offset = 0;
4
+ this.anchorStart = null;
5
+ this.viewportHeight = null;
6
+ this.totalLines = 0;
7
+ }
8
+
9
+ clear() {
10
+ this.offset = 0;
11
+ this.anchorStart = null;
12
+ this.viewportHeight = null;
13
+ this.totalLines = 0;
14
+ }
15
+
16
+ setTotalLines(total) {
17
+ this.totalLines = Math.max(0, Math.trunc(total));
18
+ }
19
+
20
+ scroll(delta) {
21
+ const total = this.totalLines;
22
+ const win = this._windowHeight();
23
+ const maxOffset = this.getMaxOffset();
24
+ const step = this.getStep();
25
+ const currentStart = this.anchorStart ?? Math.max(0, total - this.offset - win);
26
+ const maxStart = Math.max(0, total - win);
27
+ const nextStart = clamp(currentStart + (delta < 0 ? -step : step), 0, maxStart);
28
+ const nextEnd = Math.min(total, nextStart + win);
29
+ this.offset = clamp(total - nextEnd, 0, maxOffset);
30
+ this.anchorStart = this.offset > 0 ? nextStart : null;
31
+ return { offset: this.offset, maxOffset, atTail: this.offset === 0 };
32
+ }
33
+
34
+ getStep() {
35
+ return Math.max(1, Math.floor(this._windowHeight() / 3));
36
+ }
37
+
38
+ getMaxOffset() {
39
+ return Math.max(0, this.totalLines - this._windowHeight());
40
+ }
41
+
42
+ setViewportHeight(height) {
43
+ this.viewportHeight = Math.max(1, Math.trunc(height));
44
+ this.offset = clamp(this.offset, 0, this.getMaxOffset());
45
+ if (this.offset === 0) this.anchorStart = null;
46
+ }
47
+
48
+ reset() {
49
+ this.offset = 0;
50
+ this.anchorStart = null;
51
+ }
52
+
53
+ sliceRange() {
54
+ const win = this.viewportHeight;
55
+ if (win === null) return null;
56
+ const maxOffset = this.getMaxOffset();
57
+ if (this.anchorStart !== null && this.offset > 0) {
58
+ const start = clamp(this.anchorStart, 0, Math.max(0, this.totalLines - win));
59
+ const end = Math.min(this.totalLines, start + win);
60
+ this.offset = clamp(this.totalLines - end, 0, maxOffset);
61
+ if (this.offset === 0) this.anchorStart = null;
62
+ else this.anchorStart = start;
63
+ return { start, end };
64
+ }
65
+
66
+ this.offset = clamp(this.offset, 0, maxOffset);
67
+ if (this.offset === 0) this.anchorStart = null;
68
+ const end = Math.max(0, this.totalLines - this.offset);
69
+ return { start: Math.max(0, end - win), end };
70
+ }
71
+
72
+ _windowHeight() {
73
+ return this.viewportHeight || (process.stdout.rows || 30) - 2;
74
+ }
75
+ }
76
+
77
+ function clamp(value, min, max) {
78
+ return Math.min(max, Math.max(min, value));
79
+ }
@@ -0,0 +1,59 @@
1
+ import { visibleWidth } from "@earendil-works/pi-tui";
2
+ import { R, brightBlack, dim, red } from "../ui-theme.mjs";
3
+
4
+ export function renderToolCardBlock(block, width) {
5
+ const lines = [];
6
+ const border = brightBlack("┃");
7
+ const marker = block.state === "running" ? "▶" : block.expanded ? "▾" : "▸";
8
+ const summary = block.summary ? ` · ${block.summary}` : "";
9
+ const head = `${marker} ${block.title}${summary}`;
10
+ appendCardWrapped(lines, border, (block.isError ? red : dim)(head), width);
11
+
12
+ if (block.expanded && block.bodyLines?.length) {
13
+ lines.push(border);
14
+ for (const line of block.bodyLines) appendCardWrapped(lines, border, dim(line), width, " ");
15
+ }
16
+ return lines;
17
+ }
18
+
19
+ function appendCardWrapped(lines, border, text, width, indent = "") {
20
+ const prefix = `${border} ${indent}`;
21
+ const contentWidth = Math.max(8, width - visibleWidth(prefix));
22
+ for (const part of wrapLine(text, contentWidth)) lines.push(`${prefix}${part}`);
23
+ }
24
+
25
+ function wrapLine(text, maxWidth) {
26
+ if (maxWidth <= 0) return [""];
27
+ const result = [];
28
+ let cur = "", curW = 0, activeSgr = "";
29
+ for (let i = 0; i < text.length;) {
30
+ if (text[i] === "\x1b") {
31
+ const match = text.slice(i).match(/^\x1b\[[0-?]*[ -/]*[@-~]/);
32
+ if (match) {
33
+ cur += match[0];
34
+ activeSgr = updateActiveSgr(activeSgr, match[0]);
35
+ i += match[0].length;
36
+ continue;
37
+ }
38
+ }
39
+ const ch = text[i], w = visibleWidth(ch);
40
+ if (curW + w > maxWidth) {
41
+ result.push(activeSgr ? `${cur}${R}` : cur);
42
+ cur = activeSgr + ch;
43
+ curW = w;
44
+ } else {
45
+ cur += ch;
46
+ curW += w;
47
+ }
48
+ i += 1;
49
+ }
50
+ if (cur) result.push(cur);
51
+ return result.length > 0 ? result : [""];
52
+ }
53
+
54
+ function updateActiveSgr(activeSgr, seq) {
55
+ if (!seq.endsWith("m")) return activeSgr;
56
+ const body = seq.slice(2, -1);
57
+ if (body === "" || body.split(";").includes("0")) return "";
58
+ return seq;
59
+ }