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,74 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { toolText } from "../agent/tool-result.mjs";
4
+
5
+ export function createTerminalReadTool(shellRuntime) {
6
+ return defineTool({
7
+ name: "terminal_read",
8
+ label: "Terminal Read",
9
+ description: "Read plain-text output from a running interactive terminal. Use this for normal shell inspection after shell hints, terminal_list, or terminal_send.",
10
+ parameters: Type.Object({
11
+ shell_id: Type.String({ description: "Shell id or name returned by terminal_spawn, terminal_list, or shell_hints" }),
12
+ source: Type.Optional(Type.String({ description: "screen (default), scrollback, or both" })),
13
+ lines: Type.Optional(Type.Number({ description: "Number of trailing lines to return. Default 80, max 300" })),
14
+ }),
15
+ execute: async (_toolCallId, params) => {
16
+ const resolved = resolveShellId(shellRuntime, params.shell_id);
17
+ if (!resolved.ok) return toolText(`Error: ${resolved.error}`, { error: true });
18
+ const snapshot = shellRuntime.snapshotShell(resolved.id);
19
+ const source = normalizeReadSource(params.source);
20
+ const lineLimit = normalizeLineLimit(params.lines);
21
+ const text = formatTerminalRead(snapshot, { source, lines: lineLimit });
22
+ return toolText(text, { shell: snapshot.shell, source, lines: lineLimit, snapshot });
23
+ },
24
+ });
25
+ }
26
+
27
+ function resolveShellId(shellRuntime, ref) {
28
+ const value = String(ref ?? "").trim();
29
+ const shells = shellRuntime.listShells();
30
+ const shell = shells.find((shell) => shell.id === value || shell.name === value);
31
+ if (shell) return { ok: true, id: shell.id, shell };
32
+ const available = shells.length
33
+ ? ` Active shells: ${shells.map((shell) => `${shell.id} (${shell.name})`).join(", ")}.`
34
+ : " No active shells.";
35
+ return { ok: false, error: `shell not found: ${value}.${available}` };
36
+ }
37
+
38
+ function normalizeReadSource(value) {
39
+ const normalized = String(value ?? "screen").trim().toLowerCase();
40
+ if (normalized === "scrollback") return "scrollback";
41
+ if (normalized === "both") return "both";
42
+ return "screen";
43
+ }
44
+
45
+ function normalizeLineLimit(value) {
46
+ const number = Math.trunc(Number(value) || 80);
47
+ return Math.min(300, Math.max(1, number));
48
+ }
49
+
50
+ function formatTerminalRead(snapshot, { source, lines }) {
51
+ const shell = snapshot.shell;
52
+ const header = [
53
+ `## ${shell.name} (${shell.id})`,
54
+ `status: ${shell.status}`,
55
+ `command: ${shell.command}${shell.args?.length ? ` ${shell.args.join(" ")}` : ""}`,
56
+ `cwd: ${shell.cwd}`,
57
+ `source: ${source}`,
58
+ `lines: ${lines}`,
59
+ "",
60
+ ].join("\n");
61
+ if (source === "both") {
62
+ return `${header}${formatReadSection("screen", snapshot.screen?.plain, lines)}\n\n${formatReadSection("scrollback", snapshot.plain, lines)}`;
63
+ }
64
+ const content = source === "scrollback" ? snapshot.plain : snapshot.screen?.plain;
65
+ return `${header}${lastLines(content, lines) || "(empty shell output)"}`;
66
+ }
67
+
68
+ function formatReadSection(label, text, lines) {
69
+ return `-- ${label} --\n${lastLines(text, lines) || "(empty shell output)"}`;
70
+ }
71
+
72
+ function lastLines(text, lines) {
73
+ return String(text ?? "").split(/\r?\n/).slice(-lines).join("\n").trimEnd();
74
+ }
@@ -0,0 +1,299 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { toolText } from "../agent/tool-result.mjs";
4
+ import { createTerminalReadTool } from "./tool-read.mjs";
5
+
6
+ export function createShellTools(shellRuntime = null, { platform = process.platform } = {}) {
7
+ if (!shellRuntime) return [];
8
+
9
+ const terminalSpawn = defineTool({
10
+ name: "terminal_spawn",
11
+ label: "Terminal Spawn",
12
+ description: "Start a named interactive terminal process. Omit command to start the platform default terminal. Use this for long-running or prompt-based commands, not one-shot commands.",
13
+ parameters: Type.Object({
14
+ name: Type.Optional(Type.String({ description: "Optional user-facing shell name" })),
15
+ command: Type.Optional(Type.String({ description: "Command to launch; omitted means platform default terminal" })),
16
+ args: Type.Optional(Type.Array(Type.String(), { description: "Command arguments" })),
17
+ cwd: Type.Optional(Type.String({ description: "Working directory" })),
18
+ cols: Type.Optional(Type.Number({ description: "Initial PTY columns" })),
19
+ rows: Type.Optional(Type.Number({ description: "Initial PTY rows" })),
20
+ if_exists: Type.Optional(Type.String({ description: "Name conflict behavior: reuse (default), replace, or new" })),
21
+ }),
22
+ execute: async (_toolCallId, params) => {
23
+ const shell = shellRuntime.spawnShell({
24
+ name: params.name,
25
+ command: params.command,
26
+ args: params.args ?? [],
27
+ cwd: params.cwd,
28
+ cols: params.cols,
29
+ rows: params.rows,
30
+ nameConflict: normalizeNameConflict(params.if_exists),
31
+ });
32
+ return toolText(formatShell(shell), { shell });
33
+ },
34
+ });
35
+
36
+ const terminalSend = defineTool({
37
+ name: "terminal_send",
38
+ label: "Terminal Send",
39
+ description: "Send text and/or a control key to a running interactive terminal. If both text and key are provided, the key is appended after the text. Set wait_for_idle=true after sending Enter when you need output. Enter is converted for the current platform; Windows PTYs use CRLF.",
40
+ parameters: Type.Object({
41
+ shell_id: Type.String({ description: "Shell id or name returned by terminal_spawn or terminal_list" }),
42
+ text: Type.Optional(Type.String({ description: "Text to type into the terminal. Include a newline (\\n/\\r) or combine with key:\"enter\" to execute a command. Newlines are converted to the platform Enter sequence; Windows PTYs use CRLF." })),
43
+ key: Type.Optional(Type.String({ description: "Named control key to send after text when text is provided: enter, ctrl_c, ctrl_d, ctrl_z, tab, escape, backspace" })),
44
+ wait_for_idle: Type.Optional(Type.Boolean({ description: "Wait until terminal output becomes idle and return the output delta; does not press Enter automatically; default false" })),
45
+ timeout_ms: Type.Optional(Type.Number({ description: "Maximum wait time when wait_for_idle=true, default 10000" })),
46
+ idle_ms: Type.Optional(Type.Number({ description: "Output idle time before returning when wait_for_idle=true, default 1000 after Enter, otherwise 300" })),
47
+ }),
48
+ execute: async (_toolCallId, params) => {
49
+ const resolved = resolveShellId(shellRuntime, params.shell_id);
50
+ if (!resolved.ok) return toolText(`Error: ${resolved.error}`, { error: true });
51
+ const shellId = resolved.id;
52
+ const before = params.wait_for_idle ? shellRuntime.snapshotShell(shellId) : null;
53
+ const text = normalizeShellToolInput(params.text, params.key, { platform });
54
+ const result = shellRuntime.sendShell(shellId, text);
55
+ if (!result.ok) return toolText(`Error: ${result.error}`, { error: true, shell: result.shell });
56
+ if (params.wait_for_idle) {
57
+ const submitted = text.includes("\r") || text.includes("\n");
58
+ const idle = await waitForShellIdle(shellRuntime, shellId, before, {
59
+ timeoutMs: params.timeout_ms,
60
+ idleMs: params.idle_ms ?? (submitted ? 1000 : 300),
61
+ submittedText: submitted ? text : "",
62
+ });
63
+ const output = idle.delta || idle.screenDelta || idle.snapshot.screen?.plain || idle.snapshot.plain || "(no output)";
64
+ return toolText(output, {
65
+ shell: idle.shell,
66
+ timedOut: idle.timedOut,
67
+ delta: idle.delta,
68
+ screenDelta: idle.screenDelta,
69
+ snapshot: idle.snapshot,
70
+ });
71
+ }
72
+ return toolText(`Sent ${text.length} chars to ${result.shell.name} (${result.shell.id}).`, { shell: result.shell });
73
+ },
74
+ });
75
+
76
+ const terminalList = defineTool({
77
+ name: "terminal_list",
78
+ label: "Terminal List",
79
+ description: "List active and recently exited interactive terminals.",
80
+ parameters: Type.Object({}),
81
+ execute: async () => {
82
+ const shells = shellRuntime.listShells();
83
+ if (!shells.length) return toolText("No shells.", { shells });
84
+ return toolText(shells.map(formatShell).join("\n"), { shells });
85
+ },
86
+ });
87
+
88
+ const terminalKill = defineTool({
89
+ name: "terminal_kill",
90
+ label: "Terminal Kill",
91
+ description: "Terminate a running interactive terminal.",
92
+ parameters: Type.Object({
93
+ shell_id: Type.String({ description: "Shell id or name returned by terminal_spawn or terminal_list" }),
94
+ }),
95
+ execute: async (_toolCallId, params) => {
96
+ const resolved = resolveShellId(shellRuntime, params.shell_id);
97
+ if (!resolved.ok) return toolText(`Error: ${resolved.error}`, { error: true });
98
+ const result = shellRuntime.killShell(resolved.id);
99
+ if (!result.ok) return toolText(`Error: ${result.error}`, { error: true, shell: result.shell });
100
+ return toolText(`Killed ${result.shell.name} (${result.shell.id}).`, { shell: result.shell });
101
+ },
102
+ });
103
+
104
+ const terminalResize = defineTool({
105
+ name: "terminal_resize",
106
+ label: "Terminal Resize",
107
+ description: "Resize an interactive terminal PTY.",
108
+ parameters: Type.Object({
109
+ shell_id: Type.String({ description: "Shell id or name returned by terminal_spawn or terminal_list" }),
110
+ cols: Type.Number({ description: "Columns" }),
111
+ rows: Type.Number({ description: "Rows" }),
112
+ }),
113
+ execute: async (_toolCallId, params) => {
114
+ const resolved = resolveShellId(shellRuntime, params.shell_id);
115
+ if (!resolved.ok) return toolText(`Error: ${resolved.error}`, { error: true });
116
+ const result = shellRuntime.resizeShell(resolved.id, { cols: params.cols, rows: params.rows });
117
+ if (!result.ok) return toolText(`Error: ${result.error}`, { error: true, shell: result.shell });
118
+ return toolText(`Resized ${result.shell.name} (${result.shell.id}) to ${result.shell.cols}x${result.shell.rows}.`, result);
119
+ },
120
+ });
121
+
122
+ const terminalClear = defineTool({
123
+ name: "terminal_clear",
124
+ label: "Terminal Clear",
125
+ description: "Clear March's captured scrollback and screen snapshot for a terminal without terminating the process.",
126
+ parameters: Type.Object({
127
+ shell_id: Type.String({ description: "Shell id or name returned by terminal_spawn or terminal_list" }),
128
+ }),
129
+ execute: async (_toolCallId, params) => {
130
+ let result;
131
+ try {
132
+ const resolved = resolveShellId(shellRuntime, params.shell_id);
133
+ if (!resolved.ok) return toolText(`Error: ${resolved.error}`, { error: true });
134
+ result = shellRuntime.clearShell(resolved.id);
135
+ } catch (error) {
136
+ return toolText(`Error: ${error?.message ?? String(error)}`, { error: true });
137
+ }
138
+ if (!result.ok) return toolText(`Error: ${result.error}`, { error: true, shell: result.shell });
139
+ return toolText(`Cleared ${result.shell.name} (${result.shell.id}).`, result);
140
+ },
141
+ });
142
+
143
+ const terminalSearch = defineTool({
144
+ name: "terminal_search",
145
+ label: "Terminal Search",
146
+ description: "Search a terminal's plain-text output. Defaults to visible screen first, then captured scrollback, while filtering prompt-only noise.",
147
+ parameters: Type.Object({
148
+ shell_id: Type.String({ description: "Shell id or name returned by terminal_spawn or terminal_list" }),
149
+ pattern: Type.String({ description: "Plain text to search for" }),
150
+ source: Type.Optional(Type.String({ description: "auto (default), screen, or scrollback" })),
151
+ include_prompts: Type.Optional(Type.Boolean({ description: "Include shell prompt/echo lines in results; default false" })),
152
+ }),
153
+ execute: async (_toolCallId, params) => {
154
+ const resolved = resolveShellId(shellRuntime, params.shell_id);
155
+ if (!resolved.ok) return toolText(`Error: ${resolved.error}`, { error: true });
156
+ const result = shellRuntime.searchShell(resolved.id, params.pattern, {
157
+ source: params.source,
158
+ includePrompts: params.include_prompts,
159
+ });
160
+ if (!result.matches.length) return toolText(`No matches in ${result.shell.name} (${result.shell.id}).`, result);
161
+ const lines = result.matches.map((match) => `${match.index + 1}: ${match.line}`);
162
+ return toolText(lines.join("\n"), result);
163
+ },
164
+ });
165
+
166
+ const terminalRead = createTerminalReadTool(shellRuntime);
167
+
168
+ const terminalSnapshot = defineTool({
169
+ name: "terminal_snapshot",
170
+ label: "Terminal Snapshot",
171
+ description: "Return the current terminal screen and scrollback as plain text and ANSI text for visual debugging.",
172
+ parameters: Type.Object({
173
+ shell_id: Type.String({ description: "Shell id or name returned by terminal_spawn or terminal_list" }),
174
+ }),
175
+ execute: async (_toolCallId, params) => {
176
+ const resolved = resolveShellId(shellRuntime, params.shell_id);
177
+ if (!resolved.ok) return toolText(`Error: ${resolved.error}`, { error: true });
178
+ const snapshot = shellRuntime.snapshotShell(resolved.id);
179
+ const text = snapshot.screen?.plain || snapshot.plain || "(empty shell output)";
180
+ return toolText(text, snapshot);
181
+ },
182
+ });
183
+
184
+ return [terminalSpawn, terminalSend, terminalList, terminalKill, terminalResize, terminalClear, terminalSearch, terminalRead, terminalSnapshot];
185
+ }
186
+
187
+ function formatShell(shell) {
188
+ const args = shell.args?.length ? ` ${shell.args.join(" ")}` : "";
189
+ const lines = `${shell.visibleLineCount ?? 0} visible, ${shell.scrollbackLineCount ?? shell.lineCount ?? 0} captured`;
190
+ const error = shell.error ? ` error: ${shell.error}` : "";
191
+ return `${shell.id} ${shell.name} ${shell.status} ${shell.command}${args} ${lines}${error}`;
192
+ }
193
+
194
+ function resolveShellId(shellRuntime, ref) {
195
+ const value = String(ref ?? "").trim();
196
+ const shells = shellRuntime.listShells();
197
+ const shell = shells.find((shell) => shell.id === value || shell.name === value);
198
+ if (shell) return { ok: true, id: shell.id, shell };
199
+ const available = shells.length
200
+ ? ` Active shells: ${shells.map((shell) => `${shell.id} (${shell.name})`).join(", ")}.`
201
+ : " No active shells.";
202
+ return { ok: false, error: `shell not found: ${value}.${available}` };
203
+ }
204
+
205
+ function normalizeNameConflict(value) {
206
+ const normalized = String(value ?? "reuse").trim().toLowerCase();
207
+ if (normalized === "replace") return "replace";
208
+ if (normalized === "new" || normalized === "suffix") return "suffix";
209
+ return "reuse";
210
+ }
211
+
212
+ function normalizeShellToolInput(text, key, { platform = process.platform } = {}) {
213
+ const enter = enterSequenceForPlatform(platform);
214
+ const marker = "\0MARCH_ENTER\0";
215
+ const normalizedText = String(text ?? "")
216
+ .replace(/\\r\\n|\\n|\\r/g, marker)
217
+ .replace(/\r\n|\n|\r/g, marker)
218
+ .replaceAll(marker, enter);
219
+ return normalizedText + (key ? controlKeyToSequence(key, { platform }) : "");
220
+ }
221
+
222
+ function controlKeyToSequence(key, { platform = process.platform } = {}) {
223
+ const normalized = String(key ?? "").trim().toLowerCase().replace(/[-+ ]/g, "_");
224
+ const sequences = {
225
+ enter: enterSequenceForPlatform(platform),
226
+ ctrl_c: "\x03",
227
+ ctrl_d: "\x04",
228
+ ctrl_z: "\x1a",
229
+ tab: "\t",
230
+ escape: "\x1b",
231
+ esc: "\x1b",
232
+ backspace: "\x7f",
233
+ };
234
+ if (!sequences[normalized]) throw new Error(`unsupported shell key: ${key}`);
235
+ return sequences[normalized];
236
+ }
237
+
238
+ async function waitForShellIdle(shellRuntime, shellId, beforeSnapshot, { timeoutMs = 10000, idleMs = 300, submittedText = "" } = {}) {
239
+ const timeout = Math.max(1, Number(timeoutMs) || 10000);
240
+ const idle = Math.max(1, Number(idleMs) || 300);
241
+ const submitted = Boolean(submittedText);
242
+ const echoOnlyGraceMs = Math.min(timeout, 2500);
243
+ const screenOnlyGraceMs = Math.min(timeout, 2500);
244
+ const beforePlain = beforeSnapshot?.plain ?? "";
245
+ const beforeScreenPlain = beforeSnapshot?.screen?.plain ?? "";
246
+ const started = Date.now();
247
+ let lastPlain = beforePlain;
248
+ let lastScreenPlain = beforeScreenPlain;
249
+ let lastChanged = Date.now();
250
+ let snapshot = shellRuntime.snapshotShell(shellId);
251
+
252
+ for (;;) {
253
+ await sleep(50);
254
+ snapshot = shellRuntime.snapshotShell(shellId);
255
+ const plain = snapshot.plain;
256
+ const screenPlain = snapshot.screen?.plain ?? "";
257
+ const hasPlainChange = plain !== beforePlain;
258
+ const hasScreenChange = screenPlain !== beforeScreenPlain;
259
+ const delta = plain.startsWith(beforePlain) ? plain.slice(beforePlain.length).replace(/^\n/, "") : plain;
260
+ const screenDelta = screenPlain.startsWith(beforeScreenPlain) ? screenPlain.slice(beforeScreenPlain.length).replace(/^\n/, "") : screenPlain;
261
+ if (plain !== lastPlain || screenPlain !== lastScreenPlain) {
262
+ lastPlain = plain;
263
+ lastScreenPlain = screenPlain;
264
+ lastChanged = Date.now();
265
+ }
266
+ const elapsed = Date.now() - started;
267
+ const timedOut = elapsed >= timeout;
268
+ const echoOnly = submitted && hasPlainChange && isLikelyEchoOnlyDelta(delta, submittedText);
269
+ const changedEnough = hasPlainChange || (!submitted && hasScreenChange) || (submitted && hasScreenChange && elapsed >= screenOnlyGraceMs);
270
+ const echoOnlyAllowed = !echoOnly || elapsed >= echoOnlyGraceMs;
271
+ if (timedOut || (changedEnough && echoOnlyAllowed && Date.now() - lastChanged >= idle)) {
272
+ return {
273
+ shell: shellRuntime.getShell(shellId),
274
+ snapshot,
275
+ delta,
276
+ screenDelta,
277
+ timedOut,
278
+ };
279
+ }
280
+ }
281
+ }
282
+
283
+ function sleep(ms) {
284
+ return new Promise((resolve) => setTimeout(resolve, ms));
285
+ }
286
+
287
+ function enterSequenceForPlatform(platform) {
288
+ return platform === "win32" ? "\r\n" : "\r";
289
+ }
290
+
291
+ function isLikelyEchoOnlyDelta(delta, submittedText) {
292
+ const submitted = String(submittedText ?? "").replace(/[\r\n]+$/g, "").trim();
293
+ const lines = String(delta ?? "")
294
+ .split("\n")
295
+ .map((line) => line.replace(/\r/g, "").trim())
296
+ .filter(Boolean);
297
+ if (!submitted || lines.length !== 1) return false;
298
+ return lines[0] === submitted || lines[0].endsWith(submitted);
299
+ }
@@ -0,0 +1,60 @@
1
+ import { DEFAULT_SUPERGROK_IMAGE_MODEL } from "../constants.mjs";
2
+ import { readErrorMessage, successEnvelope } from "../response.mjs";
3
+ import { saveGeneratedImageAttachment } from "../../session/attachments.mjs";
4
+
5
+ const ASPECT_RATIOS = new Set(["1:1", "16:9", "4:3", "3:2", "2:3", "3:4", "9:16"]);
6
+ const RESOLUTIONS = new Set(["1k", "2k"]);
7
+
8
+ export async function runSuperGrokImageGenerate({ query, options = {}, credentials, projectMarchDir, fetchImpl = fetch } = {}) {
9
+ if (!projectMarchDir) throw new Error("projectMarchDir is required for SuperGrok image generation");
10
+ const model = String(options.model || DEFAULT_SUPERGROK_IMAGE_MODEL).trim() || DEFAULT_SUPERGROK_IMAGE_MODEL;
11
+ const aspectRatio = normalizeEnum(options.aspect_ratio, ASPECT_RATIOS, "1:1");
12
+ const resolution = normalizeEnum(options.resolution, RESOLUTIONS, "1k");
13
+ const response = await fetchImpl(`${credentials.baseUrl}/images/generations`, {
14
+ method: "POST",
15
+ headers: {
16
+ Authorization: `Bearer ${credentials.apiKey}`,
17
+ "Content-Type": "application/json",
18
+ "User-Agent": "March-SuperGrok/0.1",
19
+ },
20
+ body: JSON.stringify({
21
+ model,
22
+ prompt: query,
23
+ aspect_ratio: aspectRatio,
24
+ resolution,
25
+ }),
26
+ });
27
+
28
+ if (!response.ok) {
29
+ throw new Error(`SuperGrok image generation failed (${response.status}): ${await readErrorMessage(response)}`);
30
+ }
31
+
32
+ const payload = await response.json();
33
+ const first = payload.data?.[0] || {};
34
+ const b64 = first.b64_json || first.image_base64 || "";
35
+ const url = first.url || "";
36
+ if (!b64 && !url) throw new Error("xAI image response contained neither b64_json nor url");
37
+
38
+ const artifacts = [];
39
+ if (b64) {
40
+ const saved = saveGeneratedImageAttachment({ projectMarchDir, data: b64, mimeType: "image/png" });
41
+ artifacts.push({ type: "image", path: saved.path, marker: saved.marker, mimeType: "image/png" });
42
+ } else {
43
+ artifacts.push({ type: "image", url, mimeType: first.mime_type || "image/png" });
44
+ }
45
+
46
+ return successEnvelope({
47
+ credentialSource: credentials.credentialSource,
48
+ action: "image_generate",
49
+ model,
50
+ query,
51
+ artifacts,
52
+ extra: { aspect_ratio: aspectRatio, resolution },
53
+ });
54
+ }
55
+
56
+ function normalizeEnum(value, allowed, fallback) {
57
+ const normalized = String(value || fallback).trim();
58
+ if (!allowed.has(normalized)) return fallback;
59
+ return normalized;
60
+ }
@@ -0,0 +1,78 @@
1
+ import { DEFAULT_SUPERGROK_SEARCH_MODEL } from "../constants.mjs";
2
+ import { extractInlineCitations, extractResponseText, readErrorMessage, successEnvelope } from "../response.mjs";
3
+
4
+ const MAX_DOMAINS = 5;
5
+ const MAX_HANDLES = 10;
6
+
7
+ export async function runSuperGrokSearch({ action, query, options = {}, credentials, fetchImpl = fetch } = {}) {
8
+ const model = String(options.model || DEFAULT_SUPERGROK_SEARCH_MODEL).trim() || DEFAULT_SUPERGROK_SEARCH_MODEL;
9
+ const tool = action === "x_search" ? buildXSearchTool(options) : buildWebSearchTool(options);
10
+ const response = await fetchImpl(`${credentials.baseUrl}/responses`, {
11
+ method: "POST",
12
+ headers: {
13
+ Authorization: `Bearer ${credentials.apiKey}`,
14
+ "Content-Type": "application/json",
15
+ "User-Agent": "March-SuperGrok/0.1",
16
+ },
17
+ body: JSON.stringify({
18
+ model,
19
+ input: [{ role: "user", content: query }],
20
+ tools: [tool],
21
+ store: false,
22
+ }),
23
+ });
24
+
25
+ if (!response.ok) {
26
+ throw new Error(`SuperGrok ${action} failed (${response.status}): ${await readErrorMessage(response)}`);
27
+ }
28
+
29
+ const payload = await response.json();
30
+ return successEnvelope({
31
+ credentialSource: credentials.credentialSource,
32
+ action,
33
+ model,
34
+ query,
35
+ answer: extractResponseText(payload),
36
+ citations: payload.citations || [],
37
+ inlineCitations: extractInlineCitations(payload),
38
+ });
39
+ }
40
+
41
+ function buildWebSearchTool(options) {
42
+ const allowed = normalizeList(options.allowed_domains, "allowed_domains", MAX_DOMAINS);
43
+ const excluded = normalizeList(options.excluded_domains, "excluded_domains", MAX_DOMAINS);
44
+ if (allowed.length && excluded.length) throw new Error("allowed_domains and excluded_domains cannot both be set");
45
+ const tool = {
46
+ type: "web_search",
47
+ enable_image_understanding: options.enable_image_understanding ?? true,
48
+ };
49
+ if (allowed.length) tool.filters = { allowed_domains: allowed };
50
+ if (excluded.length) tool.filters = { excluded_domains: excluded };
51
+ return tool;
52
+ }
53
+
54
+ function buildXSearchTool(options) {
55
+ const allowed = normalizeHandles(options.allowed_x_handles, "allowed_x_handles");
56
+ const excluded = normalizeHandles(options.excluded_x_handles, "excluded_x_handles");
57
+ if (allowed.length && excluded.length) throw new Error("allowed_x_handles and excluded_x_handles cannot both be set");
58
+ const tool = {
59
+ type: "x_search",
60
+ enable_image_understanding: options.enable_image_understanding ?? true,
61
+ enable_video_understanding: options.enable_video_understanding ?? true,
62
+ };
63
+ if (allowed.length) tool.allowed_x_handles = allowed;
64
+ if (excluded.length) tool.excluded_x_handles = excluded;
65
+ if (String(options.from_date || "").trim()) tool.from_date = String(options.from_date).trim();
66
+ if (String(options.to_date || "").trim()) tool.to_date = String(options.to_date).trim();
67
+ return tool;
68
+ }
69
+
70
+ function normalizeHandles(value, fieldName) {
71
+ return normalizeList(value, fieldName, MAX_HANDLES).map((handle) => handle.replace(/^@+/, "")).filter(Boolean);
72
+ }
73
+
74
+ function normalizeList(value, fieldName, max) {
75
+ const list = Array.isArray(value) ? value.map((item) => String(item || "").trim()).filter(Boolean) : [];
76
+ if (list.length > max) throw new Error(`${fieldName} supports at most ${max} entries`);
77
+ return list;
78
+ }
@@ -0,0 +1,36 @@
1
+ import {
2
+ SUPERGROK_OAUTH_PROVIDER_ID,
3
+ XAI_API_PROVIDER_ID,
4
+ XAI_BASE_URL,
5
+ XAI_OAUTH_COMPAT_PROVIDER_ID,
6
+ } from "./constants.mjs";
7
+ import { registerSuperGrokOAuthProvider } from "./oauth-provider.mjs";
8
+
9
+ export async function resolveSuperGrokCredentials({ authStorage, baseUrl = XAI_BASE_URL } = {}) {
10
+ registerSuperGrokOAuthProvider();
11
+
12
+ for (const providerId of [SUPERGROK_OAUTH_PROVIDER_ID, XAI_OAUTH_COMPAT_PROVIDER_ID]) {
13
+ const apiKey = await authStorage?.getApiKey?.(providerId, { includeFallback: false });
14
+ if (apiKey) {
15
+ const credentials = authStorage?.get?.(providerId) ?? {};
16
+ return {
17
+ provider: "xai",
18
+ credentialSource: providerId,
19
+ apiKey,
20
+ baseUrl: String(credentials.baseUrl || baseUrl).replace(/\/$/, ""),
21
+ };
22
+ }
23
+ }
24
+
25
+ const apiKey = await authStorage?.getApiKey?.(XAI_API_PROVIDER_ID, { includeFallback: true });
26
+ if (apiKey) {
27
+ return {
28
+ provider: "xai",
29
+ credentialSource: XAI_API_PROVIDER_ID,
30
+ apiKey,
31
+ baseUrl: String(baseUrl).replace(/\/$/, ""),
32
+ };
33
+ }
34
+
35
+ throw new Error("No SuperGrok credentials available. Run: march login supergrok-oauth, or configure XAI_API_KEY / xai provider.");
36
+ }
@@ -0,0 +1,18 @@
1
+ export const SUPERGROK_OAUTH_PROVIDER_ID = "supergrok-oauth";
2
+ export const XAI_OAUTH_COMPAT_PROVIDER_ID = "xai-oauth";
3
+ export const XAI_API_PROVIDER_ID = "xai";
4
+
5
+ export const XAI_BASE_URL = "https://api.x.ai/v1";
6
+ export const XAI_OAUTH_ISSUER = "https://auth.x.ai";
7
+ export const XAI_OAUTH_DISCOVERY_URL = `${XAI_OAUTH_ISSUER}/.well-known/openid-configuration`;
8
+
9
+ // Hermes/Grok CLI client id. xAI currently ties SuperGrok subscription access to this public client.
10
+ export const XAI_OAUTH_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
11
+ export const XAI_OAUTH_SCOPE = "openid profile email offline_access grok-cli:access api:access";
12
+ export const XAI_OAUTH_REDIRECT_HOST = "127.0.0.1";
13
+ export const XAI_OAUTH_REDIRECT_PORT = 56121;
14
+ export const XAI_OAUTH_REDIRECT_PATH = "/callback";
15
+
16
+ export const DEFAULT_SUPERGROK_MODEL = "grok-4.3";
17
+ export const DEFAULT_SUPERGROK_SEARCH_MODEL = "grok-4.3";
18
+ export const DEFAULT_SUPERGROK_IMAGE_MODEL = "grok-imagine-image";