xonecas.io
64875
Mc

mini-coder / commit 0c58d3f

refactor: extract ui module tests and simplify helpers

xonecas2026-04-08 0c58d3ffeca7494ba606cef84e542f7c5abffef4 parent 38ffdbd

18 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

TODO.md+0−1
@@ -14,7 +14,6 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
1414 ## Future ideas
1515
1616 - [ ] Headless one-shot CLI mode for non-interactive runs and benchmark harnesses like Harbor/Terminal-Bench (https://www.tbench.ai/)
17-- [ ] Colocate extracted UI module tests under `src/ui/` (`agent.test.ts`, `commands.test.ts`, etc.) instead of keeping them at `src/ui.*.test.ts`
1817 - [ ] Session list preview — show first user message snippet in `/session` selector
1918 - [ ] Use dark/cold to warm/bright gradient for the statusbar backgrounds, the model info based on the thinking effort, and the session stats based on context percentage.
2019 - [ ] Divider theme plugin — customizable divider animations (scanning pulse, breathing, flowing dots, wave)
biome.json+9−0
@@ -16,6 +16,15 @@
1616 "recommended": true,
1717 "style": {
1818 "noNonNullAssertion": "off"
19+ },
20+ "complexity": {
21+ "noExcessiveCognitiveComplexity": {
22+ "level": "error",
23+ "options": {
24+ "maxAllowedComplexity": 15
25+ }
26+ },
27+ "noExcessiveNestedTestSuites": "error"
1928 }
2029 }
2130 },
src/agent.ts+283−187
@@ -132,6 +132,46 @@ function cloneAssistantContent(
132132 });
133133 }
134134
135+interface MergedAssistantBlock {
136+ block: AssistantMessage["content"][number];
137+ partialStep: number;
138+ finalStep: number;
139+}
140+
141+function mergeAssistantBlocks(
142+ partialBlock: AssistantMessage["content"][number] | undefined,
143+ finalBlock: AssistantMessage["content"][number] | undefined,
144+): MergedAssistantBlock | null {
145+ if (!partialBlock && !finalBlock) {
146+ return null;
147+ }
148+ if (!partialBlock && finalBlock) {
149+ return { block: finalBlock, partialStep: 0, finalStep: 1 };
150+ }
151+ if (partialBlock && !finalBlock) {
152+ return { block: partialBlock, partialStep: 1, finalStep: 0 };
153+ }
154+ if (!partialBlock || !finalBlock) {
155+ return null;
156+ }
157+ if (partialBlock.type === finalBlock.type) {
158+ const shouldPreservePartialThinking =
159+ partialBlock.type === "thinking" &&
160+ finalBlock.type === "thinking" &&
161+ partialBlock.thinking &&
162+ !finalBlock.thinking;
163+ return {
164+ block: shouldPreservePartialThinking ? partialBlock : finalBlock,
165+ partialStep: 1,
166+ finalStep: 1,
167+ };
168+ }
169+ if (partialBlock.type === "thinking") {
170+ return { block: partialBlock, partialStep: 1, finalStep: 0 };
171+ }
172+ return { block: finalBlock, partialStep: 1, finalStep: 1 };
173+}
174+
135175 /** Merge streamed partial assistant content into the final message content. */
136176 function mergeAssistantContent(
137177 partialContent: AssistantMessage["content"],
@@ -148,42 +188,16 @@ function mergeAssistantContent(
148188 partialIndex < partialContent.length ||
149189 finalIndex < finalContent.length
150190 ) {
151- const partialBlock = partialContent[partialIndex];
152- const finalBlock = finalContent[finalIndex];
153-
154- if (!partialBlock) {
155- merged.push(finalBlock!);
156- finalIndex++;
157- continue;
158- }
159- if (!finalBlock) {
160- merged.push(partialBlock);
161- partialIndex++;
162- continue;
163- }
164- if (partialBlock.type === finalBlock.type) {
165- if (
166- partialBlock.type === "thinking" &&
167- finalBlock.type === "thinking" &&
168- partialBlock.thinking &&
169- !finalBlock.thinking
170- ) {
171- merged.push(partialBlock);
172- } else {
173- merged.push(finalBlock);
174- }
175- partialIndex++;
176- finalIndex++;
177- continue;
178- }
179- if (partialBlock.type === "thinking") {
180- merged.push(partialBlock);
181- partialIndex++;
182- continue;
191+ const nextBlock = mergeAssistantBlocks(
192+ partialContent[partialIndex],
193+ finalContent[finalIndex],
194+ );
195+ if (!nextBlock) {
196+ break;
183197 }
184- merged.push(finalBlock);
185- partialIndex++;
186- finalIndex++;
198+ merged.push(nextBlock.block);
199+ partialIndex += nextBlock.partialStep;
200+ finalIndex += nextBlock.finalStep;
187201 }
188202
189203 return merged;
@@ -212,6 +226,207 @@ function toolErrorResult(name: string, error: unknown): ToolExecResult {
212226 };
213227 }
214228
229+function unknownToolResult(name: string): ToolExecResult {
230+ return {
231+ content: [{ type: "text", text: `Unknown tool: ${name}` }],
232+ isError: true,
233+ };
234+}
235+
236+function buildAgentContext(
237+ systemPrompt: string,
238+ messages: Message[],
239+ tools: Tool[],
240+) {
241+ return tools.length > 0
242+ ? { systemPrompt, messages, tools }
243+ : { systemPrompt, messages };
244+}
245+
246+function buildStreamOptions(
247+ apiKey: string | undefined,
248+ effort: ThinkingLevel | undefined,
249+ signal: AbortSignal | undefined,
250+) {
251+ return {
252+ ...(apiKey ? { apiKey } : {}),
253+ ...(effort ? { reasoning: effort } : {}),
254+ ...(signal ? { signal } : {}),
255+ };
256+}
257+
258+async function streamAssistantMessage(
259+ opts: Pick<
260+ RunAgentOpts,
261+ | "model"
262+ | "systemPrompt"
263+ | "tools"
264+ | "messages"
265+ | "apiKey"
266+ | "effort"
267+ | "signal"
268+ | "onEvent"
269+ >,
270+): Promise<AssistantMessage> {
271+ const eventStream = streamSimple(
272+ opts.model,
273+ buildAgentContext(opts.systemPrompt, opts.messages, opts.tools),
274+ buildStreamOptions(opts.apiKey, opts.effort, opts.signal),
275+ );
276+ let assistantMessage: AssistantMessage | undefined;
277+ let partialAssistantMessage: AssistantMessage | undefined;
278+
279+ for await (const event of eventStream) {
280+ if ("partial" in event) {
281+ partialAssistantMessage = event.partial;
282+ }
283+
284+ switch (event.type) {
285+ case "text_delta":
286+ opts.onEvent?.({
287+ type: "text_delta",
288+ delta: event.delta,
289+ content: cloneAssistantContent(event.partial.content),
290+ });
291+ continue;
292+ case "thinking_delta":
293+ opts.onEvent?.({
294+ type: "thinking_delta",
295+ delta: event.delta,
296+ content: cloneAssistantContent(event.partial.content),
297+ });
298+ continue;
299+ case "done":
300+ assistantMessage = event.message;
301+ continue;
302+ case "error":
303+ assistantMessage = event.error;
304+ continue;
305+ case "toolcall_end":
306+ continue;
307+ }
308+ }
309+
310+ const finalAssistantMessage =
311+ assistantMessage ?? (await eventStream.result());
312+ if (!partialAssistantMessage) {
313+ return finalAssistantMessage;
314+ }
315+ return mergeAssistantMessage(partialAssistantMessage, finalAssistantMessage);
316+}
317+
318+function appendAssistantMessage(
319+ db: Database,
320+ sessionId: string,
321+ messages: Message[],
322+ assistantMessage: AssistantMessage,
323+ turn: number,
324+ onEvent: RunAgentOpts["onEvent"],
325+): void {
326+ messages.push(assistantMessage);
327+ appendMessage(db, sessionId, assistantMessage, turn);
328+ onEvent?.({ type: "assistant_message", message: assistantMessage });
329+}
330+
331+function resolveLoopStopReason(
332+ assistantMessage: AssistantMessage,
333+ messages: Message[],
334+ onEvent: RunAgentOpts["onEvent"],
335+): AgentLoopResult | null {
336+ if (
337+ assistantMessage.stopReason === "error" ||
338+ assistantMessage.stopReason === "aborted"
339+ ) {
340+ const eventType =
341+ assistantMessage.stopReason === "error" ? "error" : "aborted";
342+ onEvent?.({ type: eventType, message: assistantMessage });
343+ return { messages, stopReason: assistantMessage.stopReason };
344+ }
345+
346+ if (
347+ assistantMessage.stopReason === "stop" ||
348+ assistantMessage.stopReason === "length"
349+ ) {
350+ onEvent?.({ type: "done", message: assistantMessage });
351+ return { messages, stopReason: assistantMessage.stopReason };
352+ }
353+
354+ return null;
355+}
356+
357+function getAssistantToolCalls(message: AssistantMessage): ToolCall[] {
358+ return message.content.filter((content): content is ToolCall => {
359+ return content.type === "toolCall";
360+ });
361+}
362+
363+async function executeToolCall(
364+ toolCall: ToolCall,
365+ opts: Pick<RunAgentOpts, "toolHandlers" | "cwd" | "signal" | "onEvent">,
366+): Promise<ToolExecResult> {
367+ const handler = opts.toolHandlers.get(toolCall.name);
368+ if (!handler) {
369+ return unknownToolResult(toolCall.name);
370+ }
371+
372+ opts.onEvent?.({
373+ type: "tool_start",
374+ toolCallId: toolCall.id,
375+ name: toolCall.name,
376+ args: toolCall.arguments,
377+ });
378+
379+ let result: ToolExecResult;
380+ try {
381+ result = await handler(
382+ toolCall.arguments,
383+ opts.cwd,
384+ opts.signal,
385+ (partial) => {
386+ opts.onEvent?.({
387+ type: "tool_delta",
388+ toolCallId: toolCall.id,
389+ name: toolCall.name,
390+ result: partial,
391+ });
392+ },
393+ );
394+ } catch (error) {
395+ result = toolErrorResult(toolCall.name, error);
396+ }
397+
398+ opts.onEvent?.({
399+ type: "tool_end",
400+ toolCallId: toolCall.id,
401+ name: toolCall.name,
402+ result,
403+ });
404+ return result;
405+}
406+
407+function appendToolResultMessage(
408+ db: Database,
409+ sessionId: string,
410+ messages: Message[],
411+ toolCall: ToolCall,
412+ result: ToolExecResult,
413+ turn: number,
414+ onEvent: RunAgentOpts["onEvent"],
415+): void {
416+ const toolResultMessage: ToolResultMessage = {
417+ role: "toolResult",
418+ toolCallId: toolCall.id,
419+ toolName: toolCall.name,
420+ content: result.content,
421+ isError: result.isError,
422+ timestamp: Date.now(),
423+ };
424+
425+ messages.push(toolResultMessage);
426+ appendMessage(db, sessionId, toolResultMessage, turn);
427+ onEvent?.({ type: "tool_result", message: toolResultMessage });
428+}
429+
215430 // ---------------------------------------------------------------------------
216431 // Agent loop
217432 // ---------------------------------------------------------------------------
@@ -230,168 +445,49 @@ function toolErrorResult(name: string, error: unknown): ToolExecResult {
230445 export async function runAgentLoop(
231446 opts: RunAgentOpts,
232447 ): Promise<AgentLoopResult> {
233- const {
234- db,
235- sessionId,
236- turn,
237- model,
238- systemPrompt,
239- tools,
240- toolHandlers,
241- messages,
242- cwd,
243- apiKey,
244- effort,
245- signal,
246- onEvent,
247- } = opts;
448+ const { db, sessionId, turn, messages, signal, onEvent, toolHandlers, cwd } =
449+ opts;
248450
249451 while (true) {
250- // Build context for this iteration
251- const context =
252- tools.length > 0
253- ? { systemPrompt, messages, tools }
254- : { systemPrompt, messages };
255-
256- // Stream to LLM
257- const streamOpts = {
258- ...(apiKey ? { apiKey } : {}),
259- ...(effort ? { reasoning: effort } : {}),
260- ...(signal ? { signal } : {}),
261- };
262- const eventStream = streamSimple(model, context, streamOpts);
263- let assistantMessage: AssistantMessage | undefined;
264- let partialAssistantMessage: AssistantMessage | undefined;
265-
266- for await (const event of eventStream) {
267- if ("partial" in event) {
268- partialAssistantMessage = event.partial;
269- }
452+ const assistantMessage = await streamAssistantMessage(opts);
453+ appendAssistantMessage(
454+ db,
455+ sessionId,
456+ messages,
457+ assistantMessage,
458+ turn,
459+ onEvent,
460+ );
270461
271- switch (event.type) {
272- case "text_delta":
273- onEvent?.({
274- type: "text_delta",
275- delta: event.delta,
276- content: cloneAssistantContent(event.partial.content),
277- });
278- break;
279- case "thinking_delta":
280- onEvent?.({
281- type: "thinking_delta",
282- delta: event.delta,
283- content: cloneAssistantContent(event.partial.content),
284- });
285- break;
286- case "toolcall_end":
287- // Tool calls are collected from the final assistant message
288- break;
289- case "done":
290- assistantMessage = event.message;
291- break;
292- case "error":
293- assistantMessage = event.error;
294- break;
295- }
462+ const stopResult = resolveLoopStopReason(
463+ assistantMessage,
464+ messages,
465+ onEvent,
466+ );
467+ if (stopResult) {
468+ return stopResult;
296469 }
297470
298- // If somehow we got no message, fall back to the stream result
299- if (!assistantMessage) {
300- assistantMessage = await eventStream.result();
301- }
302- if (partialAssistantMessage) {
303- assistantMessage = mergeAssistantMessage(
304- partialAssistantMessage,
305- assistantMessage,
471+ for (const toolCall of getAssistantToolCalls(assistantMessage)) {
472+ const result = await executeToolCall(toolCall, {
473+ toolHandlers,
474+ cwd,
475+ signal,
476+ onEvent,
477+ });
478+ appendToolResultMessage(
479+ db,
480+ sessionId,
481+ messages,
482+ toolCall,
483+ result,
484+ turn,
485+ onEvent,
306486 );
307- }
308-
309- // Append assistant message to history and DB
310- messages.push(assistantMessage);
311- appendMessage(db, sessionId, assistantMessage, turn);
312- onEvent?.({ type: "assistant_message", message: assistantMessage });
313-
314- // Handle stop reasons
315- if (
316- assistantMessage.stopReason === "error" ||
317- assistantMessage.stopReason === "aborted"
318- ) {
319- const eventType =
320- assistantMessage.stopReason === "error" ? "error" : "aborted";
321- onEvent?.({ type: eventType, message: assistantMessage });
322- return { messages, stopReason: assistantMessage.stopReason };
323- }
324-
325- if (
326- assistantMessage.stopReason === "stop" ||
327- assistantMessage.stopReason === "length"
328- ) {
329- onEvent?.({ type: "done", message: assistantMessage });
330- return { messages, stopReason: assistantMessage.stopReason };
331- }
332-
333- // stopReason === "toolUse" — execute tool calls and loop
334- const toolCalls = assistantMessage.content.filter(
335- (c): c is ToolCall => c.type === "toolCall",
336- );
337-
338- for (const toolCall of toolCalls) {
339- const handler = toolHandlers.get(toolCall.name);
340-
341- let result: ToolExecResult;
342-
343- if (!handler) {
344- result = {
345- content: [{ type: "text", text: `Unknown tool: ${toolCall.name}` }],
346- isError: true,
347- };
348- } else {
349- onEvent?.({
350- type: "tool_start",
351- toolCallId: toolCall.id,
352- name: toolCall.name,
353- args: toolCall.arguments,
354- });
355-
356- try {
357- result = await handler(toolCall.arguments, cwd, signal, (partial) => {
358- onEvent?.({
359- type: "tool_delta",
360- toolCallId: toolCall.id,
361- name: toolCall.name,
362- result: partial,
363- });
364- });
365- } catch (error) {
366- result = toolErrorResult(toolCall.name, error);
367- }
368-
369- onEvent?.({
370- type: "tool_end",
371- toolCallId: toolCall.id,
372- name: toolCall.name,
373- result,
374- });
375- }
376-
377- const toolResultMessage: ToolResultMessage = {
378- role: "toolResult",
379- toolCallId: toolCall.id,
380- toolName: toolCall.name,
381- content: result.content,
382- isError: result.isError,
383- timestamp: Date.now(),
384- };
385-
386- messages.push(toolResultMessage);
387- appendMessage(db, sessionId, toolResultMessage, turn);
388- onEvent?.({ type: "tool_result", message: toolResultMessage });
389487
390488 if (signal?.aborted) {
391489 return { messages, stopReason: "aborted" };
392490 }
393491 }
394-
395- // Loop back to stream with updated context
396492 }
397493 }
src/git.ts+27−11
@@ -59,6 +59,17 @@ async function run(
5959 return trim ? out.trim() : out;
6060 }
6161
62+function isUntrackedStatus(
63+ indexStatus: string,
64+ workingTreeStatus: string,
65+): boolean {
66+ return indexStatus === "?" && workingTreeStatus === "?";
67+}
68+
69+function hasTrackedChange(status: string): boolean {
70+ return status !== " " && status !== "?";
71+}
72+
6273 /**
6374 * Parse `git status --porcelain` output into staged, modified, and untracked counts.
6475 *
@@ -79,20 +90,25 @@ function parseStatus(output: string): {
7990 let modified = 0;
8091 let untracked = 0;
8192
82- if (!output) return { staged, modified, untracked };
83-
8493 for (const line of output.split("\n")) {
85- if (line.length < 2) continue;
86- const x = line[0]; // index status
87- const y = line[1]; // working tree status
94+ if (line.length < 2) {
95+ continue;
96+ }
8897
89- if (x === "?" && y === "?") {
98+ const indexStatus = line[0];
99+ const workingTreeStatus = line[1];
100+ if (!indexStatus || !workingTreeStatus) {
101+ continue;
102+ }
103+ if (isUntrackedStatus(indexStatus, workingTreeStatus)) {
90104 untracked++;
91- } else {
92- // Any non-space in index column = staged change
93- if (x !== " " && x !== "?") staged++;
94- // Any non-space in working tree column = unstaged modification
95- if (y !== " " && y !== "?") modified++;
105+ continue;
106+ }
107+ if (hasTrackedChange(indexStatus)) {
108+ staged++;
109+ }
110+ if (hasTrackedChange(workingTreeStatus)) {
111+ modified++;
96112 }
97113 }
98114
src/input.ts+59−37
@@ -67,6 +67,59 @@ export interface ParseInputOpts {
6767 // Parsing
6868 // ---------------------------------------------------------------------------
6969
70+function isCommand(value: string): value is Command {
71+ return COMMAND_SET.has(value);
72+}
73+
74+function parseSlashInput(trimmed: string): ParsedInput | null {
75+ const skillMatch = trimmed.match(/^\/skill:(\S+)(?:\s+(.*))?$/s);
76+ if (skillMatch?.[1]) {
77+ return {
78+ type: "skill",
79+ skillName: skillMatch[1],
80+ userText: skillMatch[2]?.trim() ?? "",
81+ };
82+ }
83+
84+ const commandMatch = trimmed.match(/^\/(\S+)(?:\s+(.*))?$/s);
85+ const command = commandMatch?.[1];
86+ if (!command || !isCommand(command)) {
87+ return null;
88+ }
89+
90+ return {
91+ type: "command",
92+ command,
93+ args: commandMatch[2]?.trim() ?? "",
94+ };
95+}
96+
97+function resolveImagePath(input: string, cwd?: string): string {
98+ if (isAbsolute(input) || !cwd) {
99+ return input;
100+ }
101+ return join(cwd, input);
102+}
103+
104+function parseImageInput(
105+ trimmed: string,
106+ opts?: ParseInputOpts,
107+): Extract<ParsedInput, { type: "image" }> | null {
108+ if (!opts?.supportsImages) {
109+ return null;
110+ }
111+ if (!IMAGE_EXTENSIONS.has(extname(trimmed).toLowerCase())) {
112+ return null;
113+ }
114+
115+ const resolvedPath = resolveImagePath(trimmed, opts.cwd);
116+ if (!existsSync(resolvedPath)) {
117+ return null;
118+ }
119+
120+ return { type: "image", path: resolvedPath };
121+}
122+
70123 /**
71124 * Parse raw user input into a structured result.
72125 *
@@ -82,52 +135,21 @@ export interface ParseInputOpts {
82135 */
83136 export function parseInput(raw: string, opts?: ParseInputOpts): ParsedInput {
84137 const trimmed = raw.trim();
85-
86- // Empty or whitespace-only
87138 if (trimmed.length === 0) {
88139 return { type: "text", text: "" };
89140 }
90141
91- // Slash-prefixed: command or skill
92142 if (trimmed[0] === "/") {
93- // Skill reference: /skill:name [rest]
94- const skillMatch = trimmed.match(/^\/skill:(\S+)(?:\s+(.*))?$/s);
95- if (skillMatch?.[1]) {
96- return {
97- type: "skill",
98- skillName: skillMatch[1],
99- userText: skillMatch[2]?.trim() ?? "",
100- };
101- }
102-
103- // Slash command: /name [args]
104- const cmdMatch = trimmed.match(/^\/(\S+)(?:\s+(.*))?$/s);
105- if (cmdMatch?.[1] && COMMAND_SET.has(cmdMatch[1])) {
106- return {
107- type: "command",
108- command: cmdMatch[1] as Command,
109- args: cmdMatch[2]?.trim() ?? "",
110- };
143+ const slashInput = parseSlashInput(trimmed);
144+ if (slashInput) {
145+ return slashInput;
111146 }
112-
113- // Not a recognized command or skill — fall through to text
114147 }
115148
116- // Image path detection
117- if (opts?.supportsImages) {
118- const ext = extname(trimmed).toLowerCase();
119- if (IMAGE_EXTENSIONS.has(ext)) {
120- const resolved = isAbsolute(trimmed)
121- ? trimmed
122- : opts.cwd
123- ? join(opts.cwd, trimmed)
124- : trimmed;
125- if (existsSync(resolved)) {
126- return { type: "image", path: resolved };
127- }
128- }
149+ const imageInput = parseImageInput(trimmed, opts);
150+ if (imageInput) {
151+ return imageInput;
129152 }
130153
131- // Plain text
132154 return { type: "text", text: trimmed };
133155 }
src/prompt.ts+39−36
@@ -73,6 +73,38 @@ function isWithinScanRoot(path: string, scanRoot: string): boolean {
7373 );
7474 }
7575
76+function collectAgentsSearchDirs(start: string, root: string): string[] {
77+ if (!isWithinScanRoot(start, root)) {
78+ return [start];
79+ }
80+
81+ const dirs: string[] = [];
82+ let current = start;
83+ while (true) {
84+ dirs.push(current);
85+ if (current === root) {
86+ return dirs.reverse();
87+ }
88+
89+ const parent = dirname(current);
90+ if (parent === current) {
91+ return dirs.reverse();
92+ }
93+ current = parent;
94+ }
95+}
96+
97+function readAgentsMdFile(dir: string): AgentsMdFile | null {
98+ const filePath = join(dir, AGENT_FILENAME);
99+ if (!existsSync(filePath)) {
100+ return null;
101+ }
102+ return {
103+ path: filePath,
104+ content: readFileSync(filePath, "utf-8"),
105+ };
106+}
107+
76108 /**
77109 * Walk from `cwd` up to `scanRoot`, collecting AGENTS.md files.
78110 *
@@ -92,48 +124,19 @@ export function discoverAgentsMd(
92124 ): AgentsMdFile[] {
93125 const root = canonicalizePath(scanRoot);
94126 const start = canonicalizePath(cwd);
95-
96- // Collect canonical directories from scanRoot to cwd
97- const dirs: string[] = [];
98- let current = start;
99-
100- if (!isWithinScanRoot(start, root)) {
101- dirs.push(start);
102- } else {
103- while (true) {
104- dirs.push(current);
105- if (current === root) break;
106- const parent = dirname(current);
107- // Safety: stop if we can't go higher (e.g., filesystem root)
108- if (parent === current) break;
109- current = parent;
110- }
111-
112- // Reverse so we go root-to-leaf
113- dirs.reverse();
114- }
115-
116- // Collect files from the global agents dir first
117127 const files: AgentsMdFile[] = [];
118128
119129 if (globalAgentsDir) {
120- const filePath = join(globalAgentsDir, AGENT_FILENAME);
121- if (existsSync(filePath)) {
122- files.push({
123- path: filePath,
124- content: readFileSync(filePath, "utf-8"),
125- });
130+ const globalFile = readAgentsMdFile(globalAgentsDir);
131+ if (globalFile) {
132+ files.push(globalFile);
126133 }
127134 }
128135
129- // Walk from root to cwd
130- for (const dir of dirs) {
131- const filePath = join(dir, AGENT_FILENAME);
132- if (existsSync(filePath)) {
133- files.push({
134- path: filePath,
135- content: readFileSync(filePath, "utf-8"),
136- });
136+ for (const dir of collectAgentsSearchDirs(start, root)) {
137+ const agentsFile = readAgentsMdFile(dir);
138+ if (agentsFile) {
139+ files.push(agentsFile);
137140 }
138141 }
139142
src/skills.ts+113−70
@@ -35,6 +35,63 @@ export interface Skill {
3535 // Frontmatter parsing
3636 // ---------------------------------------------------------------------------
3737
38+function getFrontmatterLines(content: string): string[] | null {
39+ if (!content.startsWith("---")) {
40+ return null;
41+ }
42+
43+ const endIdx = content.indexOf("\n---", 3);
44+ if (endIdx === -1) {
45+ return null;
46+ }
47+
48+ return content.slice(4, endIdx).split("\n");
49+}
50+
51+function parseFrontmatterEntry(
52+ line: string,
53+): { key: string; value: string } | null {
54+ const colonIdx = line.indexOf(":");
55+ if (colonIdx === -1) {
56+ return null;
57+ }
58+
59+ return {
60+ key: line.slice(0, colonIdx).trim(),
61+ value: line.slice(colonIdx + 1).trim(),
62+ };
63+}
64+
65+function isIndentedFrontmatterLine(line: string): boolean {
66+ return line.startsWith(" ") || line.startsWith("\t");
67+}
68+
69+function readFoldedFrontmatterValue(
70+ lines: string[],
71+ startIndex: number,
72+): string {
73+ const folded: string[] = [];
74+ for (let i = startIndex; i < lines.length; i++) {
75+ const line = lines[i];
76+ if (!line || !isIndentedFrontmatterLine(line)) {
77+ break;
78+ }
79+ folded.push(line.trim());
80+ }
81+ return folded.join(" ");
82+}
83+
84+function readDescriptionValue(
85+ lines: string[],
86+ lineIndex: number,
87+ value: string,
88+): string {
89+ if (value === ">") {
90+ return readFoldedFrontmatterValue(lines, lineIndex + 1);
91+ }
92+ return stripQuotes(value);
93+}
94+
3895 /**
3996 * Parse YAML frontmatter from a SKILL.md file's content.
4097 *
@@ -49,53 +106,25 @@ function parseFrontmatter(content: string): {
49106 name: string | undefined;
50107 description: string | undefined;
51108 } {
52- // Frontmatter must start with ---
53- if (!content.startsWith("---")) {
54- return { name: undefined, description: undefined };
55- }
56-
57- const endIdx = content.indexOf("\n---", 3);
58- if (endIdx === -1) {
109+ const lines = getFrontmatterLines(content);
110+ if (!lines) {
59111 return { name: undefined, description: undefined };
60112 }
61113
62- const frontmatter = content.slice(4, endIdx); // skip opening "---\n"
63- const lines = frontmatter.split("\n");
64-
65114 let name: string | undefined;
66115 let description: string | undefined;
67116
68- for (let i = 0; i < lines.length; i++) {
69- const line = lines[i]!;
70-
71- const colonIdx = line.indexOf(":");
72- if (colonIdx === -1) continue;
73-
74- const key = line.slice(0, colonIdx).trim();
75- const value = line.slice(colonIdx + 1).trim();
76-
77- if (key === "name") {
78- name = stripQuotes(value);
79- } else if (key === "description") {
80- // Handle folded scalar (>)
81- if (value === ">") {
82- const folded: string[] = [];
83- for (let j = i + 1; j < lines.length; j++) {
84- const nextLine = lines[j]!;
85- // Continuation lines must be indented
86- if (
87- nextLine.length > 0 &&
88- (nextLine[0] === " " || nextLine[0] === "\t")
89- ) {
90- folded.push(nextLine.trim());
91- } else {
92- break;
93- }
94- }
95- description = folded.join(" ");
96- } else {
97- description = stripQuotes(value);
98- }
117+ for (const [index, line] of lines.entries()) {
118+ const entry = parseFrontmatterEntry(line);
119+ if (!entry) {
120+ continue;
121+ }
122+ if (entry.key === "name") {
123+ name = stripQuotes(entry.value);
124+ continue;
125+ }
126+ if (entry.key === "description") {
127+ description = readDescriptionValue(lines, index, entry.value);
99128 }
100129 }
101130
@@ -124,6 +153,45 @@ function stripQuotes(s: string): string {
124153 // Discovery
125154 // ---------------------------------------------------------------------------
126155
156+function listSkillEntries(basePath: string): string[] {
157+ if (!existsSync(basePath)) {
158+ return [];
159+ }
160+ try {
161+ return readdirSync(basePath);
162+ } catch {
163+ return [];
164+ }
165+}
166+
167+function isDirectory(path: string): boolean {
168+ try {
169+ return statSync(path).isDirectory();
170+ } catch {
171+ return false;
172+ }
173+}
174+
175+function readSkill(basePath: string, entry: string): Skill | null {
176+ const dir = join(basePath, entry);
177+ if (!isDirectory(dir)) {
178+ return null;
179+ }
180+
181+ const skillPath = join(dir, "SKILL.md");
182+ if (!existsSync(skillPath)) {
183+ return null;
184+ }
185+
186+ const content = readFileSync(skillPath, "utf-8");
187+ const frontmatter = parseFrontmatter(content);
188+ return {
189+ name: frontmatter.name ?? entry,
190+ description: frontmatter.description ?? "",
191+ path: skillPath,
192+ };
193+}
194+
127195 /**
128196 * Discover agent skills from the given scan paths.
129197 *
@@ -138,37 +206,12 @@ export function discoverSkills(scanPaths: string[]): Skill[] {
138206 const seen = new Map<string, Skill>();
139207
140208 for (const basePath of scanPaths) {
141- if (!existsSync(basePath)) continue;
142-
143- let entries: string[];
144- try {
145- entries = readdirSync(basePath);
146- } catch {
147- continue;
148- }
149-
150- for (const entry of entries) {
151- const dir = join(basePath, entry);
152- const skillPath = join(dir, "SKILL.md");
153-
154- // Must be a directory containing SKILL.md
155- try {
156- if (!statSync(dir).isDirectory()) continue;
157- } catch {
Cut short: this commit's diff is over 1000 lines.
src/ui.conversation.test.ts+0−180
Cut short: this commit's diff is over 1000 lines.
src/ui.test.ts+2−672
Cut short: this commit's diff is over 1000 lines.
src/ui/agent.test.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.test.ts+104−9
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.test.ts+366−0
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.ts+194−157
Cut short: this commit's diff is over 1000 lines.
src/ui/help.test.ts+2−2
Cut short: this commit's diff is over 1000 lines.
src/ui/input.test.ts+2−2
Cut short: this commit's diff is over 1000 lines.
src/ui/overlay.test.ts+2−2
Cut short: this commit's diff is over 1000 lines.
src/ui/status.test.ts+334−0
Cut short: this commit's diff is over 1000 lines.
src/ui/status.ts+69−41
Cut short: this commit's diff is over 1000 lines.