xonecas.io
64875
Mc

mini-coder / commit ac23235

refactor(cli): split command and input image modules

xonecas2026-03-14 ac23235f561420b2e426f205ba5bbb37575e1031 parent 0da6bfa

7 files changed

src/cli/commands-agent.ts+55−0
@@ -0,0 +1,55 @@
1+import * as c from "yoctocolors";
2+import { loadAgents } from "./agents.ts";
3+import { PREFIX, writeln } from "./output.ts";
4+import type { CommandContext } from "./types.ts";
5+
6+export function handleAgentCommand(ctx: CommandContext, args: string): void {
7+ const raw = args.trim();
8+ const agents = loadAgents(ctx.cwd);
9+
10+ if (!raw) {
11+ if (agents.size === 0) {
12+ writeln(
13+ c.dim(" no agents found (~/.agents/agents/ or .agents/agents/)"),
14+ );
15+ writeln(
16+ c.dim(" /agent <name> to activate · /agent off to deactivate"),
17+ );
18+ return;
19+ }
20+ writeln();
21+ writeln(c.dim(" agents:"));
22+ for (const agent of agents.values()) {
23+ const modeTag = agent.mode ? c.dim(` [${agent.mode}]`) : "";
24+ const srcTag =
25+ agent.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
26+ const active = ctx.activeAgent === agent.name ? c.cyan(" ◀ active") : "";
27+ writeln(
28+ ` ${c.magenta(`@${agent.name}`.padEnd(26))} ${c.dim(agent.description)}${modeTag}${srcTag}${active}`,
29+ );
30+ }
31+ writeln();
32+ writeln(
33+ c.dim(" /agent <name> to activate · /agent off to deactivate"),
34+ );
35+ writeln();
36+ return;
37+ }
38+
39+ if (raw.toLowerCase() === "off" || raw.toLowerCase() === "none") {
40+ ctx.setActiveAgent(null);
41+ writeln(`${PREFIX.info} ${c.dim("active agent cleared")}`);
42+ return;
43+ }
44+
45+ const agent = agents.get(raw);
46+ if (!agent) {
47+ writeln(`${PREFIX.error} agent ${c.cyan(raw)} not found`);
48+ return;
49+ }
50+
51+ ctx.setActiveAgent(raw, agent.systemPrompt);
52+ writeln(
53+ `${PREFIX.success} active agent → ${c.cyan(raw)} ${c.dim("(instructions appended to system prompt)")}`,
54+ );
55+}
src/cli/commands-help.ts+96−0
@@ -0,0 +1,96 @@
1+import * as c from "yoctocolors";
2+import { loadAgents } from "./agents.ts";
3+import type { CustomCommand } from "./custom-commands.ts";
4+import { writeln } from "./output.ts";
5+import { loadSkillsIndex } from "./skills.ts";
6+import type { CommandContext } from "./types.ts";
7+
8+export function renderHelpCommand(
9+ ctx: CommandContext,
10+ custom: Map<string, CustomCommand>,
11+): void {
12+ writeln();
13+
14+ const cmds: [string, string][] = [
15+ ["/model [id]", "list or switch models (fetches live list)"],
16+ ["/undo", "remove the last turn from conversation history"],
17+ ["/reasoning [on|off]", "toggle display of model reasoning output"],
18+ ["/context [prune|cap]", "configure context pruning and tool-result caps"],
19+ [
20+ "/cache [on|off|openai|gemini]",
21+ "configure provider prompt-caching settings",
22+ ],
23+ ["/agent [name]", "set or clear active primary agent"],
24+ ["/mcp list", "list MCP servers"],
25+ ["/mcp add <n> <t> [u]", "add an MCP server"],
26+ ["/mcp remove <name>", "remove an MCP server"],
27+ ["/new", "start a new session with clean context"],
28+ ["/help", "this message"],
29+ ["/exit", "quit"],
30+ ];
31+ for (const [cmd, desc] of cmds) {
32+ writeln(` ${c.cyan(cmd.padEnd(26))} ${c.dim(desc)}`);
33+ }
34+
35+ if (custom.size > 0) {
36+ writeln();
37+ writeln(c.dim(" custom commands:"));
38+ for (const cmd of custom.values()) {
39+ const tag =
40+ cmd.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
41+ writeln(
42+ ` ${c.green(`/${cmd.name}`.padEnd(26))} ${c.dim(cmd.description)}${tag}`,
43+ );
44+ }
45+ }
46+
47+ const agents = loadAgents(ctx.cwd);
48+ if (agents.size > 0) {
49+ writeln();
50+ writeln(c.dim(" agents (~/.agents/agents/ or .agents/agents/):"));
51+ for (const agent of agents.values()) {
52+ const modeTag = agent.mode ? c.dim(` [${agent.mode}]`) : "";
53+ const tag =
54+ agent.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
55+ writeln(
56+ ` ${c.magenta(agent.name.padEnd(26))} ${c.dim(agent.description)}${modeTag}${tag}`,
57+ );
58+ }
59+ }
60+
61+ const skills = loadSkillsIndex(ctx.cwd);
62+ if (skills.size > 0) {
63+ writeln();
64+ writeln(
65+ c.dim(
66+ " skills (walk-up local .agents/.claude/skills + global ~/.agents/skills ~/.claude/skills):",
67+ ),
68+ );
69+ for (const skill of skills.values()) {
70+ const tag =
71+ skill.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
72+ writeln(
73+ ` ${c.yellow(`@${skill.name}`.padEnd(26))} ${c.dim(skill.description)}${tag}`,
74+ );
75+ }
76+ }
77+
78+ writeln();
79+ writeln(
80+ ` ${c.green("/agent <name>".padEnd(26))} ${c.dim("activate a custom agent by name")}`,
81+ );
82+ writeln(
83+ ` ${c.green("@skill".padEnd(26))} ${c.dim("load a skill body on demand into the prompt (Tab to complete)")}`,
84+ );
85+ writeln(
86+ ` ${c.green("@file".padEnd(26))} ${c.dim("inject file contents into prompt (Tab to complete)")}`,
87+ );
88+ writeln(
89+ ` ${c.green("!cmd".padEnd(26))} ${c.dim("run shell command, output added as context")}`,
90+ );
91+ writeln();
92+ writeln(
93+ ` ${c.dim("esc")} cancel response ${c.dim("·")} ${c.dim("ctrl+c")} exit ${c.dim("·")} ${c.dim("ctrl+d")} exit ${c.dim("·")} ${c.dim("ctrl+r")} history search ${c.dim("·")} ${c.dim("↑↓")} history`,
94+ );
95+ writeln();
96+}
src/cli/commands-mcp.ts+115−0
@@ -0,0 +1,115 @@
1+import * as c from "yoctocolors";
2+import {
3+ deleteMcpServer,
4+ listMcpServers,
5+ upsertMcpServer,
6+} from "../session/db/index.ts";
7+import { PREFIX, writeln } from "./output.ts";
8+import type { CommandContext } from "./types.ts";
9+
10+export async function handleMcpCommand(
11+ ctx: CommandContext,
12+ args: string,
13+): Promise<void> {
14+ const parts = args.trim().split(/\s+/);
15+ const sub = parts[0] ?? "list";
16+
17+ switch (sub) {
18+ case "list": {
19+ const servers = listMcpServers();
20+ if (servers.length === 0) {
21+ writeln(c.dim(" no MCP servers configured"));
22+ writeln(
23+ c.dim(
24+ " /mcp add <name> http <url> · /mcp add <name> stdio <cmd> [args...]",
25+ ),
26+ );
27+ return;
28+ }
29+ writeln();
30+ for (const s of servers) {
31+ const detail = s.url
32+ ? c.dim(` ${s.url}`)
33+ : s.command
34+ ? c.dim(` ${s.command}`)
35+ : "";
36+ writeln(
37+ ` ${c.yellow("⚙")} ${c.bold(s.name)} ${c.dim(s.transport)}${detail}`,
38+ );
39+ }
40+ return;
41+ }
42+
43+ case "add": {
44+ const [, name, transport, ...rest] = parts;
45+ if (!name || !transport || rest.length === 0) {
46+ writeln(`${PREFIX.error} usage: /mcp add <name> http <url>`);
47+ writeln(`${PREFIX.error} /mcp add <name> stdio <cmd> [args...]`);
48+ return;
49+ }
50+ if (transport === "http") {
51+ const url = rest[0];
52+ if (!url) {
53+ writeln(`${PREFIX.error} usage: /mcp add <name> http <url>`);
54+ return;
55+ }
56+ upsertMcpServer({
57+ name,
58+ transport,
59+ url,
60+ command: null,
61+ args: null,
62+ env: null,
63+ });
64+ } else if (transport === "stdio") {
65+ const [command, ...cmdArgs] = rest;
66+ if (!command) {
67+ writeln(
68+ `${PREFIX.error} usage: /mcp add <name> stdio <cmd> [args...]`,
69+ );
70+ return;
71+ }
72+ upsertMcpServer({
73+ name,
74+ transport,
75+ url: null,
76+ command,
77+ args: cmdArgs.length ? JSON.stringify(cmdArgs) : null,
78+ env: null,
79+ });
80+ } else {
81+ writeln(
82+ `${PREFIX.error} unknown transport: ${transport} (use http or stdio)`,
83+ );
84+ return;
85+ }
86+ try {
87+ await ctx.connectMcpServer(name);
88+ writeln(
89+ `${PREFIX.success} mcp server ${c.cyan(name)} added and connected`,
90+ );
91+ } catch (e) {
92+ writeln(
93+ `${PREFIX.success} mcp server ${c.cyan(name)} saved ${c.dim(`(connection failed: ${String(e)})`)}`,
94+ );
95+ }
96+ return;
97+ }
98+
99+ case "remove":
100+ case "rm": {
101+ const [, name] = parts;
102+ if (!name) {
103+ writeln(`${PREFIX.error} usage: /mcp remove <name>`);
104+ return;
105+ }
106+ deleteMcpServer(name);
107+ writeln(`${PREFIX.success} mcp server ${c.cyan(name)} removed`);
108+ return;
109+ }
110+
111+ default:
112+ writeln(`${PREFIX.error} unknown: /mcp ${sub}`);
113+ writeln(c.dim(" subcommands: list · add · remove"));
114+ }
115+}
src/cli/commands.ts+6−275
@@ -1,16 +1,13 @@
11 import * as c from "yoctocolors";
22 import { isAbortError } from "../agent/agent-helpers.ts";
3-import {
4- deleteMcpServer,
5- listMcpServers,
6- upsertMcpServer,
7-} from "../session/db/index.ts";
8-import { loadAgents } from "./agents.ts";
3+import { handleAgentCommand } from "./commands-agent.ts";
94 import {
105 handleCacheCommand,
116 handleContextCommand,
127 handleReasoningCommand,
138 } from "./commands-config.ts";
9+import { renderHelpCommand } from "./commands-help.ts";
10+import { handleMcpCommand } from "./commands-mcp.ts";
1411 import { handleModelCommand } from "./commands-model.ts";
1512 import {
1613 type CustomCommand,
@@ -21,8 +18,6 @@ import { watchForCancel } from "./input.ts";
2118 import { renderMarkdown } from "./markdown.ts";
2219 import { PREFIX, renderBanner, write, writeln } from "./output.ts";
2320
24-import { loadSkillsIndex } from "./skills.ts";
25-
2621 // ─── Types ────────────────────────────────────────────────────────────────────
2722
2823 import type { CommandContext } from "./types.ts";
@@ -51,119 +46,6 @@ async function handleUndo(ctx: CommandContext): Promise<void> {
5146 }
5247 }
5348
54-async function handleMcp(ctx: CommandContext, args: string): Promise<void> {
55- const parts = args.trim().split(/\s+/);
56- const sub = parts[0] ?? "list";
57-
58- switch (sub) {
59- case "list": {
60- const servers = listMcpServers();
61- if (servers.length === 0) {
62- writeln(c.dim(" no MCP servers configured"));
63- writeln(
64- c.dim(
65- " /mcp add <name> http <url> · /mcp add <name> stdio <cmd> [args...]",
66- ),
67- );
68- return;
69- }
70- writeln();
71- for (const s of servers) {
72- const detail = s.url
73- ? c.dim(` ${s.url}`)
74- : s.command
75- ? c.dim(` ${s.command}`)
76- : "";
77- writeln(
78- ` ${c.yellow("⚙")} ${c.bold(s.name)} ${c.dim(s.transport)}${detail}`,
79- );
80- }
81- return;
82- }
83-
84- case "add": {
85- // http: /mcp add <name> http <url>
86- // stdio: /mcp add <name> stdio <cmd> [args...]
87- const [, name, transport, ...rest] = parts;
88- if (!name || !transport || rest.length === 0) {
89- writeln(`${PREFIX.error} usage: /mcp add <name> http <url>`);
90- writeln(`${PREFIX.error} /mcp add <name> stdio <cmd> [args...]`);
91-
92- return;
93- }
94- if (transport === "http") {
95- const url = rest[0];
96- if (!url) {
97- writeln(`${PREFIX.error} usage: /mcp add <name> http <url>`);
98-
99- return;
100- }
101- upsertMcpServer({
102- name,
103- transport,
104- url,
105- command: null,
106- args: null,
107- env: null,
108- });
109- } else if (transport === "stdio") {
110- const [command, ...cmdArgs] = rest;
111- if (!command) {
112- writeln(
113- `${PREFIX.error} usage: /mcp add <name> stdio <cmd> [args...]`,
114- );
115-
116- return;
117- }
118- upsertMcpServer({
119- name,
120- transport,
121- url: null,
122- command,
123- args: cmdArgs.length ? JSON.stringify(cmdArgs) : null,
124- env: null,
125- });
126- } else {
127- writeln(
128- `${PREFIX.error} unknown transport: ${transport} (use http or stdio)`,
129- );
130-
131- return;
132- }
133- // Connect immediately so tools are available in this session
134- try {
135- await ctx.connectMcpServer(name);
136- writeln(
137- `${PREFIX.success} mcp server ${c.cyan(name)} added and connected`,
138- );
139- } catch (e) {
140- writeln(
141- `${PREFIX.success} mcp server ${c.cyan(name)} saved ${c.dim(`(connection failed: ${String(e)})`)}`,
142- );
143- }
144- return;
145- }
146-
147- case "remove":
148- case "rm": {
149- const [, name] = parts;
150- if (!name) {
151- writeln(`${PREFIX.error} usage: /mcp remove <name>`);
152-
153- return;
154- }
155- deleteMcpServer(name);
156- writeln(`${PREFIX.success} mcp server ${c.cyan(name)} removed`);
157- return;
158- }
159-
160- default:
161- writeln(`${PREFIX.error} unknown: /mcp ${sub}`);
162-
163- writeln(c.dim(" subcommands: list · add · remove"));
164- }
165-}
166-
16749 function handleNew(ctx: CommandContext): void {
16850 ctx.startNewSession();
16951 // Clear terminal and reprint banner for a fresh session feel
@@ -228,157 +110,6 @@ async function handleCustomCommand(
228110 }
229111 }
230112
231-// ─── Agent ────────────────────────────────────────────────────────────────────
232-
233-function handleAgent(ctx: CommandContext, args: string): void {
234- const raw = args.trim();
235- const agents = loadAgents(ctx.cwd);
236-
237- if (!raw) {
238- // List all agents
239- if (agents.size === 0) {
240- writeln(
241- c.dim(" no agents found (~/.agents/agents/ or .agents/agents/)"),
242- );
243- writeln(
244- c.dim(" /agent <name> to activate · /agent off to deactivate"),
245- );
246- return;
247- }
248- writeln();
249- writeln(c.dim(" agents:"));
250- for (const agent of agents.values()) {
251- const modeTag = agent.mode ? c.dim(` [${agent.mode}]`) : "";
252- const srcTag =
253- agent.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
254- const active = ctx.activeAgent === agent.name ? c.cyan(" ◀ active") : "";
255- writeln(
256- ` ${c.magenta(`@${agent.name}`.padEnd(26))} ${c.dim(agent.description)}${modeTag}${srcTag}${active}`,
257- );
258- }
259- writeln();
260- writeln(
261- c.dim(" /agent <name> to activate · /agent off to deactivate"),
262- );
263- writeln();
264- return;
265- }
266-
267- if (raw.toLowerCase() === "off" || raw.toLowerCase() === "none") {
268- ctx.setActiveAgent(null);
269- writeln(`${PREFIX.info} ${c.dim("active agent cleared")}`);
270- return;
271- }
272-
273- const agent = agents.get(raw);
274- if (!agent) {
275- writeln(`${PREFIX.error} agent ${c.cyan(raw)} not found`);
276- return;
277- }
278-
279- // Pass the resolved system prompt so setActiveAgent never needs to re-lookup.
280- ctx.setActiveAgent(raw, agent.systemPrompt);
281- writeln(
282- `${PREFIX.success} active agent → ${c.cyan(raw)} ${c.dim("(instructions appended to system prompt)")}`,
283- );
284-}
285-
286-// ─── Help ─────────────────────────────────────────────────────────────────────
287-
288-function handleHelp(
289- ctx: CommandContext,
290- custom: Map<string, CustomCommand>,
291-): void {
292- writeln();
293-
294- const cmds: [string, string][] = [
295- ["/model [id]", "list or switch models (fetches live list)"],
296- ["/undo", "remove the last turn from conversation history"],
297- ["/reasoning [on|off]", "toggle display of model reasoning output"],
298- ["/context [prune|cap]", "configure context pruning and tool-result caps"],
299- [
300- "/cache [on|off|openai|gemini]",
301- "configure provider prompt-caching settings",
302- ],
303-
304- ["/agent [name]", "set or clear active primary agent"],
305- ["/mcp list", "list MCP servers"],
306- ["/mcp add <n> <t> [u]", "add an MCP server"],
307- ["/mcp remove <name>", "remove an MCP server"],
308- ["/new", "start a new session with clean context"],
309- ["/help", "this message"],
310- ["/exit", "quit"],
311- ];
312- for (const [cmd, desc] of cmds) {
313- writeln(` ${c.cyan(cmd.padEnd(26))} ${c.dim(desc)}`);
314- }
315-
316- // Show custom commands
317- if (custom.size > 0) {
318- writeln();
319- writeln(c.dim(" custom commands:"));
320- for (const cmd of custom.values()) {
321- const tag =
322- cmd.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
323- writeln(
324- ` ${c.green(`/${cmd.name}`.padEnd(26))} ${c.dim(cmd.description)}${tag}`,
325- );
326- }
327- }
328-
329- // Show agents
330- const agents = loadAgents(ctx.cwd);
331- if (agents.size > 0) {
332- writeln();
333- writeln(c.dim(" agents (~/.agents/agents/ or .agents/agents/):"));
334- for (const agent of agents.values()) {
335- const modeTag = agent.mode ? c.dim(` [${agent.mode}]`) : "";
336- const tag =
337- agent.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
338- writeln(
339- ` ${c.magenta(agent.name.padEnd(26))} ${c.dim(agent.description)}${modeTag}${tag}`,
340- );
341- }
342- }
343-
344- // Show skills
345- const skills = loadSkillsIndex(ctx.cwd);
346- if (skills.size > 0) {
347- writeln();
348- writeln(
349- c.dim(
350- " skills (walk-up local .agents/.claude/skills + global ~/.agents/skills ~/.claude/skills):",
351- ),
352- );
353- for (const skill of skills.values()) {
354- const tag =
355- skill.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
356- writeln(
357- ` ${c.yellow(`@${skill.name}`.padEnd(26))} ${c.dim(skill.description)}${tag}`,
358- );
359- }
360- }
361-
362- writeln();
363- writeln(
364- ` ${c.green("/agent <name>".padEnd(26))} ${c.dim("activate a custom agent by name")}`,
365- );
366- writeln(
367- ` ${c.green("@skill".padEnd(26))} ${c.dim("load a skill body on demand into the prompt (Tab to complete)")}`,
368- );
369- writeln(
370- ` ${c.green("@file".padEnd(26))} ${c.dim("inject file contents into prompt (Tab to complete)")}`,
371- );
372- writeln(
373- ` ${c.green("!cmd".padEnd(26))} ${c.dim("run shell command, output added as context")}`,
374- );
375- writeln();
376- writeln(
377- ` ${c.dim("esc")} cancel response ${c.dim("·")} ${c.dim("ctrl+c")} exit ${c.dim("·")} ${c.dim("ctrl+d")} exit ${c.dim("·")} ${c.dim("ctrl+r")} history search ${c.dim("·")} ${c.dim("↑↓")} history`,
378- );
379- writeln();
380-}
381-
382113 // ─── Dispatch ─────────────────────────────────────────────────────────────────
383114
384115 export async function handleCommand(
@@ -415,11 +146,11 @@ export async function handleCommand(
415146 return { type: "handled" };
416147
417148 case "agent":
418- handleAgent(ctx, args);
149+ handleAgentCommand(ctx, args);
419150 return { type: "handled" };
420151
421152 case "mcp":
422- await handleMcp(ctx, args);
153+ await handleMcpCommand(ctx, args);
423154 return { type: "handled" };
424155
425156 case "new":
@@ -428,7 +159,7 @@ export async function handleCommand(
428159
429160 case "help":
430161 case "?":
431- handleHelp(ctx, custom);
162+ renderHelpCommand(ctx, custom);
432163 return { type: "handled" };
433164
434165 case "exit":
src/cli/input-images.test.ts+49−0
@@ -0,0 +1,49 @@
1+import { describe, expect, test } from "bun:test";
2+import { tryExtractImageFromPaste } from "./input-images.ts";
3+
4+describe("tryExtractImageFromPaste", () => {
5+ test("extracts base64 data URLs", async () => {
6+ const result = await tryExtractImageFromPaste(
7+ "data:image/png;base64,Zm9v",
8+ "/tmp",
9+ );
10+
11+ expect(result).toEqual({
12+ attachment: { data: "Zm9v", mediaType: "image/png" },
13+ label: "[image: image/png]",
14+ });
15+ });
16+
17+ test("ignores non-base64 data URLs", async () => {
18+ const result = await tryExtractImageFromPaste(
19+ "data:image/svg+xml,<svg></svg>",
20+ "/tmp",
21+ );
22+ expect(result).toBeNull();
23+ });
24+
25+ test("resolves relative image paths", async () => {
26+ const result = await tryExtractImageFromPaste(
27+ "assets/logo.png",
28+ "/repo",
29+ async (path) => {
30+ expect(path).toBe("/repo/assets/logo.png");
31+ return { data: "abc", mediaType: "image/png" };
32+ },
33+ );
34+
35+ expect(result).toEqual({
36+ attachment: { data: "abc", mediaType: "image/png" },
37+ label: "[image: logo.png]",
38+ });
39+ });
40+
41+ test("does not treat spaced paths as image attachments", async () => {
42+ const result = await tryExtractImageFromPaste(
43+ "my image.png",
44+ "/repo",
45+ async () => ({ data: "abc", mediaType: "image/png" }),
46+ );
47+ expect(result).toBeNull();
48+ });
49+});
src/cli/input-images.ts+38−0
@@ -0,0 +1,38 @@
1+import { join } from "node:path";
2+import {
3+ type ImageAttachment,
4+ isImageFilename,
5+ loadImageFile,
6+} from "./image-types.ts";
7+
8+export async function tryExtractImageFromPaste(
9+ pasted: string,
10+ cwd: string,
11+ loadImage: (path: string) => Promise<ImageAttachment | null> = loadImageFile,
12+): Promise<{ attachment: ImageAttachment; label: string } | null> {
13+ const trimmed = pasted.trim();
14+
15+ if (trimmed.startsWith("data:image/")) {
16+ const commaIdx = trimmed.indexOf(",");
17+ if (commaIdx !== -1 && trimmed.slice(0, commaIdx).includes(";base64")) {
18+ const header = trimmed.slice(0, commaIdx);
19+ const b64 = trimmed.slice(commaIdx + 1);
20+ const mediaType = header.split(";")[0]?.slice(5) ?? "image/png";
21+ return {
22+ attachment: { data: b64, mediaType },
23+ label: `[image: ${mediaType}]`,
24+ };
25+ }
26+ }
27+
28+ if (!trimmed.includes(" ") && isImageFilename(trimmed)) {
29+ const filePath = trimmed.startsWith("/") ? trimmed : join(cwd, trimmed);
30+ const attachment = await loadImage(filePath);
31+ if (attachment) {
32+ const name = filePath.split("/").pop() ?? trimmed;
33+ return { attachment, label: `[image: ${name}]` };
34+ }
35+ }
36+
37+ return null;
38+}
src/cli/input.ts+2−54
@@ -1,12 +1,7 @@
1-import { join } from "node:path";
21 import * as c from "yoctocolors";
32
43 import { addPromptHistory, getPromptHistory } from "../session/db/index.ts";
5-import {
6- type ImageAttachment,
7- isImageFilename,
8- loadImageFile,
9-} from "./image-types.ts";
4+import type { ImageAttachment } from "./image-types.ts";
105 import {
116 buildPromptDisplay,
127 createPasteToken,
@@ -20,6 +15,7 @@ import {
2015 getSubagentControlAction,
2116 getTurnControlAction,
2217 } from "./input-control.ts";
18+import { tryExtractImageFromPaste } from "./input-images.ts";
2319 import { terminal } from "./terminal-io.ts";
2420
2521 // ─── ANSI escape sequences ────────────────────────────────────────────────────
@@ -71,54 +67,6 @@ export {
7167 getTurnControlAction,
7268 } from "./input-control.ts";
7369
74-// ─── Image detection ─────────────────────────────────────────────────────────
75-
76-/**
77- * Parse a pasted chunk and extract image attachments if present.
78- *
79- * Handles two cases:
80- * 1. The paste is a `data:image/...;base64,...` data URL.
81- * 2. The paste is a file path pointing to an image on disk.
82- *
83- * Returns `{ attachment, label }` when an image is found so the caller can
84- * replace the paste buffer with a placeholder label, or `null` when the paste
85- * is plain text.
86- */
87-async function tryExtractImageFromPaste(
88- pasted: string,
89- cwd: string,
90-): Promise<{ attachment: ImageAttachment; label: string } | null> {
91- const trimmed = pasted.trim();
92-
93- // Case 1: base64 data URL — only accept if explicitly base64-encoded
94- // (non-base64 data URLs like data:image/svg+xml,<svg>... would be sent as
95- // garbled base64 to the model if we don't guard here)
96- if (trimmed.startsWith("data:image/")) {
97- const commaIdx = trimmed.indexOf(",");
98- if (commaIdx !== -1 && trimmed.slice(0, commaIdx).includes(";base64")) {
99- const header = trimmed.slice(0, commaIdx); // "data:image/png;base64"
100- const b64 = trimmed.slice(commaIdx + 1);
101- const mediaType = header.split(";")[0]?.slice(5) ?? "image/png"; // strip "data:"
102- return {
103- attachment: { data: b64, mediaType },
104- label: `[image: ${mediaType}]`,
105- };
106- }
107- }
108-
109- // Case 2: file path to an image
110- if (!trimmed.includes(" ") && isImageFilename(trimmed)) {
111- const filePath = trimmed.startsWith("/") ? trimmed : join(cwd, trimmed);
112- const attachment = await loadImageFile(filePath);
113- if (attachment) {
114- const name = filePath.split("/").pop() ?? trimmed;
115- return { attachment, label: `[image: ${name}]` };
116- }
117- }
118-
119- return null;
120-}
121-
12270 // ─── Singleton stdin reader (shared across readline() calls) ─────────────────
12371 // We create the ReadableStream once so that repeated readline() calls don't
12472 // each wrap process.stdin in their own controller, which causes