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,129 @@
1
+ import { createInterface } from "node:readline";
2
+ import { AuthStorage } from "@earendil-works/pi-coding-agent";
3
+ import { globalConfigJsonPath, upsertProviderProfile } from "../config/config-json.mjs";
4
+ import { getMarchAuthPath } from "../auth/storage.mjs";
5
+ import { selectWithKeyboard } from "../cli/input/select-with-keyboard.mjs";
6
+ import { PROVIDER_PRESETS } from "./presets.mjs";
7
+
8
+ export { formatSelectionList, selectWithKeyboard } from "../cli/input/select-with-keyboard.mjs";
9
+
10
+ export async function runProviderConfigCommand({
11
+ homeDir,
12
+ input = process.stdin,
13
+ output = process.stdout,
14
+ select = selectWithKeyboard,
15
+ readSecret = readLine,
16
+ authStorage = AuthStorage.create(getMarchAuthPath(homeDir)),
17
+ } = {}) {
18
+ const preset = await select({
19
+ input,
20
+ output,
21
+ message: "Choose provider to configure",
22
+ items: PROVIDER_PRESETS.map((item) => ({ label: item.label, value: item })),
23
+ });
24
+ if (!preset) {
25
+ output.write("Provider configuration cancelled.\n");
26
+ return 1;
27
+ }
28
+
29
+ const authMethod = preset.authMethods.length === 1
30
+ ? preset.authMethods[0]
31
+ : await select({
32
+ input,
33
+ output,
34
+ message: "Choose auth method",
35
+ items: preset.authMethods.map((method) => ({ label: formatAuthMethod(method), value: method })),
36
+ });
37
+ if (!authMethod) {
38
+ output.write("Provider configuration cancelled.\n");
39
+ return 1;
40
+ }
41
+
42
+ if (authMethod === "oauth") {
43
+ return runOAuthConfig({ preset, authStorage, input, output, homeDir });
44
+ }
45
+
46
+ if (authMethod !== "apiKey") {
47
+ output.write(`Unsupported auth method: ${authMethod}\n`);
48
+ return 1;
49
+ }
50
+
51
+ const apiKey = String(await readSecret({ input, output, prompt: `${preset.apiKeyLabel}: ` }) ?? "").trim();
52
+ if (!apiKey) {
53
+ output.write("API key is required.\n");
54
+ return 1;
55
+ }
56
+
57
+ const path = globalConfigJsonPath(homeDir);
58
+ upsertProviderProfile({
59
+ path,
60
+ id: preset.id,
61
+ type: preset.type,
62
+ auth: { method: "apiKey", apiKey },
63
+ });
64
+ output.write(`Saved provider: ${preset.label}\n`);
65
+ output.write(`Config: ${path}\n`);
66
+ return 0;
67
+ }
68
+
69
+ function formatAuthMethod(method) {
70
+ if (method === "apiKey") return "API key";
71
+ if (method === "oauth") return "OAuth / subscription";
72
+ return method;
73
+ }
74
+
75
+ async function runOAuthConfig({ preset, authStorage, input, output, homeDir }) {
76
+ const rl = createInterface({ input, output });
77
+ try {
78
+ output.write(`Logging in to ${preset.label}...\n`);
79
+ await authStorage.login(preset.type, {
80
+ onAuth: (info) => {
81
+ output.write(`\nOpen this URL in your browser:\n${info.url}\n`);
82
+ if (info.instructions) output.write(`${info.instructions}\n`);
83
+ output.write("\n");
84
+ },
85
+ onPrompt: (prompt) => ask(rl, `${prompt.message}${prompt.placeholder ? ` (${prompt.placeholder})` : ""}: `),
86
+ onManualCodeInput: () => ask(rl, "Paste redirect URL or code: "),
87
+ onProgress: (message) => output.write(`${message}\n`),
88
+ onSelect: async (prompt) => selectOAuthOption({ prompt, rl, output }),
89
+ });
90
+ output.write(`\nCredentials saved to ${getMarchAuthPath(homeDir)}\n`);
91
+ return 0;
92
+ } catch (error) {
93
+ output.write(`OAuth login failed: ${error instanceof Error ? error.message : String(error)}\n`);
94
+ return 1;
95
+ } finally {
96
+ rl.close();
97
+ }
98
+ }
99
+
100
+ async function selectOAuthOption({ prompt, rl, output }) {
101
+ output.write(`${prompt.message}\n`);
102
+ for (let i = 0; i < prompt.options.length; i++) {
103
+ const option = prompt.options[i];
104
+ output.write(` ${i + 1}. ${option.label} (${option.id})\n`);
105
+ }
106
+ const answer = await ask(rl, `Enter option id or number (1-${prompt.options.length}): `);
107
+ return resolveSelection(answer, prompt.options);
108
+ }
109
+
110
+ function resolveSelection(answer, options) {
111
+ const trimmed = answer.trim();
112
+ const index = Number.parseInt(trimmed, 10);
113
+ if (Number.isInteger(index) && String(index) === trimmed && index >= 1 && index <= options.length) {
114
+ return options[index - 1].id;
115
+ }
116
+ return options.some((option) => option.id === trimmed) ? trimmed : undefined;
117
+ }
118
+
119
+ function ask(rl, question) {
120
+ return new Promise((resolve) => rl.question(question, resolve));
121
+ }
122
+
123
+ function readLine({ input = process.stdin, output = process.stdout, prompt }) {
124
+ const rl = createInterface({ input, output });
125
+ return new Promise((resolve) => rl.question(prompt, (answer) => {
126
+ rl.close();
127
+ resolve(answer);
128
+ }));
129
+ }
@@ -0,0 +1,72 @@
1
+ import { getProviders } from "@earendil-works/pi-ai";
2
+ import { getOAuthProviders } from "@earendil-works/pi-ai/oauth";
3
+ import { registerSuperGrokOAuthProvider } from "../supergrok/oauth-provider.mjs";
4
+
5
+ registerSuperGrokOAuthProvider();
6
+
7
+ const PROVIDER_LABELS = {
8
+ anthropic: "Anthropic",
9
+ "amazon-bedrock": "Amazon Bedrock",
10
+ "azure-openai-responses": "Azure OpenAI Responses",
11
+ cerebras: "Cerebras",
12
+ "cloudflare-ai-gateway": "Cloudflare AI Gateway",
13
+ "cloudflare-workers-ai": "Cloudflare Workers AI",
14
+ deepseek: "DeepSeek",
15
+ fireworks: "Fireworks",
16
+ google: "Google Gemini",
17
+ "google-vertex": "Google Vertex AI",
18
+ groq: "Groq",
19
+ huggingface: "Hugging Face",
20
+ "kimi-coding": "Kimi For Coding",
21
+ mistral: "Mistral",
22
+ minimax: "MiniMax",
23
+ "minimax-cn": "MiniMax (China)",
24
+ moonshotai: "Moonshot AI",
25
+ "moonshotai-cn": "Moonshot AI (China)",
26
+ opencode: "OpenCode Zen",
27
+ "opencode-go": "OpenCode Go",
28
+ openai: "OpenAI",
29
+ "openai-codex": "OpenAI Codex",
30
+ openrouter: "OpenRouter",
31
+ "supergrok-oauth": "SuperGrok OAuth (xAI Subscription)",
32
+ "vercel-ai-gateway": "Vercel AI Gateway",
33
+ xai: "xAI",
34
+ "xai-oauth": "xAI OAuth (SuperGrok compatible)",
35
+ zai: "ZAI",
36
+ xiaomi: "Xiaomi MiMo",
37
+ "xiaomi-token-plan-cn": "Xiaomi MiMo Token Plan (China)",
38
+ "xiaomi-token-plan-ams": "Xiaomi MiMo Token Plan (Amsterdam)",
39
+ "xiaomi-token-plan-sgp": "Xiaomi MiMo Token Plan (Singapore)",
40
+ };
41
+
42
+ export const PROVIDER_PRESETS = buildProviderPresets();
43
+
44
+ export function buildProviderPresets() {
45
+ const oauthProviderIds = new Set(getOAuthProviders().map((provider) => provider.id));
46
+ const ids = new Set([...getProviders(), ...oauthProviderIds]);
47
+ return [...ids].map((id) => {
48
+ const label = getProviderLabel(id);
49
+ return {
50
+ id,
51
+ label,
52
+ type: id,
53
+ authMethods: getAuthMethods(id, oauthProviderIds),
54
+ apiKeyLabel: `${label} API key`,
55
+ };
56
+ }).sort((a, b) => a.label.localeCompare(b.label));
57
+ }
58
+
59
+ export function getProviderPreset(id) {
60
+ return PROVIDER_PRESETS.find((preset) => preset.id === id || preset.type === id) ?? null;
61
+ }
62
+
63
+ export function getProviderLabel(id) {
64
+ return PROVIDER_LABELS[id] ?? id;
65
+ }
66
+
67
+ function getAuthMethods(id, oauthProviderIds) {
68
+ const methods = [];
69
+ if (oauthProviderIds.has(id)) methods.push("oauth");
70
+ methods.push("apiKey");
71
+ return methods;
72
+ }
@@ -0,0 +1,16 @@
1
+ import { basename } from "node:path";
2
+
3
+ const ATTACHMENT_MARKER_RE = /@\.march\/attachments\/[^\s"'`<>)]+/g;
4
+
5
+ export function formatAttachmentMarkerForDisplay(marker) {
6
+ const name = formatAttachmentDisplayName(basename(String(marker || "").replace(/\\/g, "/")) || "image");
7
+ return `[image: ${name}]`;
8
+ }
9
+
10
+ export function formatMessageAttachmentsForDisplay(text) {
11
+ return String(text || "").replace(ATTACHMENT_MARKER_RE, (marker) => formatAttachmentMarkerForDisplay(marker));
12
+ }
13
+
14
+ export function formatAttachmentDisplayName(name) {
15
+ return String(name || "image").replace(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z_/, "");
16
+ }
@@ -0,0 +1,65 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { extname, join, relative, resolve } from "node:path";
3
+ import { getAttachmentRoot, imageExtensionForMime } from "./attachments.mjs";
4
+
5
+ const ATTACHMENT_MARKER_RE = /@\.march\/attachments\/[^\s"'`<>)]+/g;
6
+
7
+ const IMAGE_MIME_BY_EXT = Object.freeze({
8
+ ".gif": "image/gif",
9
+ ".jpg": "image/jpeg",
10
+ ".jpeg": "image/jpeg",
11
+ ".png": "image/png",
12
+ ".webp": "image/webp",
13
+ });
14
+
15
+ export function resolveImageAttachmentReferences({ text, projectMarchDir } = {}) {
16
+ if (!text || !projectMarchDir) return { images: [], references: [] };
17
+
18
+ const seen = new Set();
19
+ const images = [];
20
+ const references = [];
21
+ for (const marker of String(text).match(ATTACHMENT_MARKER_RE) || []) {
22
+ if (seen.has(marker)) continue;
23
+ seen.add(marker);
24
+
25
+ const relativePath = marker.slice("@.march/".length);
26
+ const path = assertInsideAttachmentRoot(join(projectMarchDir, relativePath), projectMarchDir);
27
+ if (!existsSync(path)) continue;
28
+
29
+ const mimeType = readSupportedAttachmentMimeType(path) ?? mimeTypeForPath(path);
30
+ if (!mimeType) continue;
31
+
32
+ const data = readFileSync(path).toString("base64");
33
+ images.push({ type: "image", mimeType, data });
34
+ references.push({ marker, path, mimeType });
35
+ }
36
+
37
+ return { images, references };
38
+ }
39
+
40
+ function readSupportedAttachmentMimeType(path) {
41
+ const metadataPath = path.replace(/\.[^.\\/]+$/, ".json");
42
+ if (!existsSync(metadataPath)) return null;
43
+ try {
44
+ const metadata = JSON.parse(readFileSync(metadataPath, "utf8"));
45
+ if (typeof metadata.mimeType !== "string") return null;
46
+ imageExtensionForMime(metadata.mimeType);
47
+ return metadata.mimeType;
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ function mimeTypeForPath(path) {
54
+ return IMAGE_MIME_BY_EXT[extname(path).toLowerCase()] ?? null;
55
+ }
56
+
57
+ function assertInsideAttachmentRoot(path, projectMarchDir) {
58
+ const root = resolve(getAttachmentRoot(projectMarchDir));
59
+ const resolvedPath = resolve(path);
60
+ const rel = relative(root, resolvedPath);
61
+ if (rel.startsWith("..") || rel === "" || resolve(root, rel) !== resolvedPath) {
62
+ throw new Error("attachment marker escaped attachments root");
63
+ }
64
+ return resolvedPath;
65
+ }
@@ -0,0 +1,140 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { basename, join, relative, resolve } from "node:path";
4
+
5
+ export const ATTACHMENT_STORE_VERSION = 1;
6
+
7
+ const IMAGE_EXTENSIONS = Object.freeze({
8
+ "image/gif": "gif",
9
+ "image/jpeg": "jpg",
10
+ "image/png": "png",
11
+ "image/webp": "webp",
12
+ });
13
+
14
+ export function getAttachmentRoot(projectMarchDir) {
15
+ if (!projectMarchDir) throw new Error("projectMarchDir is required");
16
+ return join(projectMarchDir, "attachments");
17
+ }
18
+
19
+ export function getSessionAttachmentDir({ projectMarchDir, sessionId }) {
20
+ return join(getAttachmentRoot(projectMarchDir), sanitizePathSegment(sessionId || "session"));
21
+ }
22
+
23
+ export function saveImageAttachment({
24
+ projectMarchDir,
25
+ sessionId,
26
+ data,
27
+ mimeType,
28
+ source = "unknown",
29
+ now = new Date(),
30
+ id = randomUUID().slice(0, 8),
31
+ } = {}) {
32
+ const ext = imageExtensionForMime(mimeType);
33
+ const buffer = toBuffer(data);
34
+ if (buffer.length === 0) throw new Error("attachment data is empty");
35
+
36
+ const dir = getSessionAttachmentDir({ projectMarchDir, sessionId });
37
+ mkdirSync(dir, { recursive: true });
38
+
39
+ const createdAt = now.toISOString();
40
+ const stem = `${formatTimestampForFile(createdAt)}_${sanitizePathSegment(id)}`;
41
+ const path = assertInsideRoot(resolve(dir, `${stem}.${ext}`), getAttachmentRoot(projectMarchDir));
42
+ const metadataPath = assertInsideRoot(resolve(dir, `${stem}.json`), getAttachmentRoot(projectMarchDir));
43
+ writeFileSync(path, buffer);
44
+
45
+ const metadata = {
46
+ version: ATTACHMENT_STORE_VERSION,
47
+ sessionId: sessionId || null,
48
+ source,
49
+ mimeType,
50
+ sizeBytes: buffer.length,
51
+ createdAt,
52
+ filename: basename(path),
53
+ relativePath: toProjectMarchRelative(projectMarchDir, path),
54
+ };
55
+ writeFileSync(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
56
+ return {
57
+ path,
58
+ metadataPath,
59
+ relativePath: metadata.relativePath,
60
+ metadata,
61
+ };
62
+ }
63
+
64
+ export function saveGeneratedImageAttachment({
65
+ projectMarchDir,
66
+ data,
67
+ mimeType,
68
+ now = new Date(),
69
+ id = randomUUID().slice(0, 8),
70
+ } = {}) {
71
+ const ext = imageExtensionForMime(mimeType);
72
+ const buffer = toBuffer(data);
73
+ if (buffer.length === 0) throw new Error("attachment data is empty");
74
+
75
+ const dir = assertInsideRoot(resolve(getAttachmentRoot(projectMarchDir), "generated"), getAttachmentRoot(projectMarchDir));
76
+ mkdirSync(dir, { recursive: true });
77
+
78
+ const createdAt = now.toISOString();
79
+ const stem = `${formatTimestampForFile(createdAt)}_${sanitizePathSegment(id)}`;
80
+ const path = assertInsideRoot(resolve(dir, `${stem}.${ext}`), getAttachmentRoot(projectMarchDir));
81
+ const metadataPath = assertInsideRoot(resolve(dir, `${stem}.json`), getAttachmentRoot(projectMarchDir));
82
+ writeFileSync(path, buffer);
83
+
84
+ const metadata = {
85
+ version: ATTACHMENT_STORE_VERSION,
86
+ sessionId: null,
87
+ source: "image_generate",
88
+ mimeType,
89
+ sizeBytes: buffer.length,
90
+ createdAt,
91
+ filename: basename(path),
92
+ relativePath: toProjectMarchRelative(projectMarchDir, path),
93
+ };
94
+ writeFileSync(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
95
+ return {
96
+ path,
97
+ metadataPath,
98
+ relativePath: metadata.relativePath,
99
+ marker: `@.march/${metadata.relativePath}`,
100
+ metadata,
101
+ };
102
+ }
103
+
104
+ export function imageExtensionForMime(mimeType) {
105
+ const ext = IMAGE_EXTENSIONS[String(mimeType || "").toLowerCase()];
106
+ if (!ext) throw new Error(`unsupported image mime type: ${mimeType || "unknown"}`);
107
+ return ext;
108
+ }
109
+
110
+ export function sanitizePathSegment(value) {
111
+ return String(value || "value")
112
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
113
+ .replace(/^[._-]+|[._-]+$/g, "")
114
+ .slice(0, 80) || "value";
115
+ }
116
+
117
+ function toBuffer(data) {
118
+ if (Buffer.isBuffer(data)) return data;
119
+ if (data instanceof Uint8Array) return Buffer.from(data);
120
+ if (typeof data === "string") return Buffer.from(data, "base64");
121
+ throw new Error("attachment data must be a Buffer, Uint8Array, or base64 string");
122
+ }
123
+
124
+ function formatTimestampForFile(isoString) {
125
+ return isoString.replace(/[:.]/g, "-");
126
+ }
127
+
128
+ function assertInsideRoot(path, root) {
129
+ const resolvedRoot = resolve(root);
130
+ const resolvedPath = resolve(path);
131
+ const rel = relative(resolvedRoot, resolvedPath);
132
+ if (rel.startsWith("..") || rel === "" || resolve(resolvedRoot, rel) !== resolvedPath) {
133
+ throw new Error("attachment path escaped attachments root");
134
+ }
135
+ return resolvedPath;
136
+ }
137
+
138
+ function toProjectMarchRelative(projectMarchDir, path) {
139
+ return relative(resolve(projectMarchDir), resolve(path)).replace(/\\/g, "/");
140
+ }
@@ -0,0 +1 @@
1
+ // Legacy session persistence removed. All sessions use pi JSONL format.
@@ -0,0 +1,34 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
4
+
5
+ export function getPiSessionDir(projectMarchDir) {
6
+ return join(projectMarchDir, "pi-sessions");
7
+ }
8
+
9
+ export function createPiSessionManager({ cwd, projectMarchDir }) {
10
+ const sessionDir = getPiSessionDir(projectMarchDir);
11
+ mkdirSync(sessionDir, { recursive: true });
12
+ return SessionManager.create(cwd, sessionDir);
13
+ }
14
+
15
+ export function resolvePiSessionManager({ cwd, projectMarchDir, enabled = false }) {
16
+ if (!enabled) return null;
17
+ return createPiSessionManager({ cwd, projectMarchDir });
18
+ }
19
+
20
+ export async function listPiSessionInfos({ cwd, projectMarchDir }) {
21
+ const sessionDir = getPiSessionDir(projectMarchDir);
22
+ const sessions = await SessionManager.list(cwd, sessionDir);
23
+ return sessions.map((session) => ({
24
+ id: session.id,
25
+ path: session.path,
26
+ savedAt: session.modified?.toISOString?.() ?? "",
27
+ createdAt: session.created?.toISOString?.() ?? "",
28
+ cwd: session.cwd,
29
+ name: session.name,
30
+ turnCount: session.messageCount,
31
+ firstMessage: session.firstMessage,
32
+ parentSessionPath: session.parentSessionPath ?? null,
33
+ }));
34
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Shared session utility functions.
3
+ */
4
+ export function formatSessionId(namespace, sessionName) {
5
+ if (!namespace && !sessionName) return "default";
6
+ if (!sessionName) return namespace;
7
+ if (!namespace) return sessionName;
8
+ return `${namespace}/${sessionName}`;
9
+ }
10
+
11
+ export function parseSessionId(sessionId) {
12
+ if (!sessionId || sessionId === "default") return { namespace: "", sessionName: "default" };
13
+ const idx = sessionId.indexOf("/");
14
+ if (idx === -1) return { namespace: "", sessionName: sessionId };
15
+ return { namespace: sessionId.slice(0, idx), sessionName: sessionId.slice(idx + 1) };
16
+ }
@@ -0,0 +1,19 @@
1
+ import { savePiSessionSidecar } from "./sidecar.mjs";
2
+
3
+ export function syncPiSessionSidecar({ enabled = false, projectMarchDir, engine, sessionStats, metadata = {} }) {
4
+ if (!enabled || !projectMarchDir || !sessionStats?.persisted || !sessionStats.sessionFile) {
5
+ return null;
6
+ }
7
+
8
+ return savePiSessionSidecar({
9
+ projectMarchDir,
10
+ sessionRef: sessionStats.sessionFile,
11
+ engine,
12
+ metadata: {
13
+ sessionId: sessionStats.sessionId,
14
+ sessionFile: sessionStats.sessionFile,
15
+ runtimeHost: Boolean(sessionStats.runtimeHost),
16
+ ...metadata,
17
+ },
18
+ });
19
+ }
@@ -0,0 +1,68 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+
4
+ export const PI_SIDECAR_VERSION = 1;
5
+
6
+ export function getPiSidecarDir(projectMarchDir) {
7
+ return join(projectMarchDir, "pi-sidecars");
8
+ }
9
+
10
+ export function getPiSidecarPath(projectMarchDir, sessionRef) {
11
+ return join(getPiSidecarDir(projectMarchDir), `${normalizeSessionRef(sessionRef)}.json`);
12
+ }
13
+
14
+ export function captureContextSidecar(engine, metadata = {}) {
15
+ return {
16
+ version: PI_SIDECAR_VERSION,
17
+ savedAt: new Date().toISOString(),
18
+ ...metadata,
19
+ cwd: engine.cwd,
20
+ modelId: engine.modelId,
21
+ provider: engine.provider,
22
+ sessionName: engine.sessionName ?? "",
23
+ thinkingLevel: engine.thinkingLevel,
24
+ namespace: engine.namespace,
25
+ turns: engine.turns,
26
+ };
27
+ }
28
+
29
+ export function savePiSessionSidecar({ projectMarchDir, sessionRef, engine, metadata = {} }) {
30
+ return savePiSessionSidecarState({
31
+ projectMarchDir,
32
+ sessionRef,
33
+ state: captureContextSidecar(engine, metadata),
34
+ });
35
+ }
36
+
37
+ export function savePiSessionSidecarState({ projectMarchDir, sessionRef, state }) {
38
+ const sidecarDir = getPiSidecarDir(projectMarchDir);
39
+ mkdirSync(sidecarDir, { recursive: true });
40
+ validateSidecarState(state);
41
+ const path = getPiSidecarPath(projectMarchDir, sessionRef);
42
+ writeFileSync(path, JSON.stringify(state, null, 2), "utf8");
43
+ return { path, state };
44
+ }
45
+
46
+ export function loadPiSessionSidecar({ projectMarchDir, sessionRef }) {
47
+ const path = getPiSidecarPath(projectMarchDir, sessionRef);
48
+ if (!existsSync(path)) return null;
49
+ const state = JSON.parse(readFileSync(path, "utf8"));
50
+ if (!isValidSidecarState(state)) {
51
+ throw new Error("Invalid pi session sidecar");
52
+ }
53
+ return { path, state };
54
+ }
55
+
56
+ function validateSidecarState(state) {
57
+ if (!isValidSidecarState(state)) throw new Error("Invalid pi session sidecar");
58
+ }
59
+
60
+ function isValidSidecarState(state) {
61
+ return state?.version === PI_SIDECAR_VERSION && Boolean(state.cwd) && Array.isArray(state.turns);
62
+ }
63
+
64
+ function normalizeSessionRef(sessionRef) {
65
+ const ref = basename(String(sessionRef).trim()).replace(/\.jsonl$/i, "");
66
+ if (!ref || ref === "." || ref === "..") throw new Error("Invalid pi session reference");
67
+ return ref.replace(/[^a-zA-Z0-9._-]/g, "_");
68
+ }
@@ -0,0 +1,83 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export const DEFAULT_TRANSCRIPT_TURN_LIMIT = 20;
4
+
5
+ export function loadPiSessionTranscriptTurns(sessionPath, { limit = DEFAULT_TRANSCRIPT_TURN_LIMIT } = {}) {
6
+ const entries = readPiSessionEntries(sessionPath);
7
+ const turns = [];
8
+ let current = null;
9
+
10
+ for (const entry of entries) {
11
+ if (entry?.type !== "message") continue;
12
+ const message = entry.message;
13
+ if (message?.role === "user") {
14
+ current = { userMessage: extractMessageText(message), assistantMessage: "" };
15
+ turns.push(current);
16
+ continue;
17
+ }
18
+ if (message?.role === "assistant") {
19
+ const text = extractMessageText(message);
20
+ if (!current) {
21
+ current = { userMessage: "", assistantMessage: text };
22
+ turns.push(current);
23
+ } else if (current.assistantMessage) {
24
+ current.assistantMessage += `\n\n${text}`;
25
+ } else {
26
+ current.assistantMessage = text;
27
+ }
28
+ }
29
+ }
30
+
31
+ const normalized = turns
32
+ .filter((turn) => turn.userMessage || turn.assistantMessage)
33
+ .map((turn, index) => ({ index: index + 1, ...turn }));
34
+ return normalized.slice(-Math.max(0, limit));
35
+ }
36
+
37
+ export function writeTranscriptToOutput(output, turns) {
38
+ if (!Array.isArray(turns) || turns.length === 0) return;
39
+ for (const turn of turns) {
40
+ if (turn.userMessage) {
41
+ output.writeln("You");
42
+ for (const line of String(turn.userMessage).split(/\r?\n/)) output.writeln(line);
43
+ }
44
+ if (turn.assistantMessage) {
45
+ output.writeln("");
46
+ output.writeln("March");
47
+ output.writeMarkdown(String(turn.assistantMessage));
48
+ output.ensureNewline();
49
+ output.sealCurrentText();
50
+ }
51
+ output.writeln("");
52
+ }
53
+ }
54
+
55
+ function readPiSessionEntries(sessionPath) {
56
+ const text = readFileSync(sessionPath, "utf8");
57
+ const entries = [];
58
+ for (const line of text.split(/\r?\n/)) {
59
+ if (!line.trim()) continue;
60
+ try {
61
+ entries.push(JSON.parse(line));
62
+ } catch {
63
+ // Ignore partial or malformed JSONL entries; transcript restore is best effort.
64
+ }
65
+ }
66
+ return entries;
67
+ }
68
+
69
+ function extractMessageText(message) {
70
+ const content = message?.content;
71
+ if (typeof content === "string") return content;
72
+ if (Array.isArray(content)) {
73
+ return content
74
+ .map((part) => {
75
+ if (typeof part === "string") return part;
76
+ if (part?.type === "text" || part?.type === "input_text") return part.text ?? "";
77
+ return "";
78
+ })
79
+ .filter(Boolean)
80
+ .join("\n");
81
+ }
82
+ return "";
83
+ }