@@ -9,7 +9,9 @@
99 */
1010
1111 import { exec } from "node:child_process";
12+import { readdirSync, readFileSync } from "node:fs";
1213 import { homedir, platform } from "node:os";
14+import { isAbsolute, join } from "node:path";
1315 import type { SelectInstance } from "@cel-tui/components";
1416 import { Markdown, Select, Spacer } from "@cel-tui/components";
1517 import {
@@ -28,6 +30,7 @@ import type {
2830 ThinkingContent,
2931 ThinkingLevel,
3032 ToolCall,
33+ UserMessage,
3134 } from "@mariozechner/pi-ai";
3235 import type { OAuthProviderInterface } from "@mariozechner/pi-ai/oauth";
3336 import { getOAuthProviders } from "@mariozechner/pi-ai/oauth";
@@ -65,6 +68,7 @@ import {
6568 } from "./session.ts";
6669 import { updateSettings } from "./settings.ts";
6770 import type { Theme } from "./theme.ts";
71+import { executeReadImage } from "./tools.ts";
6872
6973 // ---------------------------------------------------------------------------
7074 // Constants
@@ -989,22 +993,6 @@ export function buildConversationLog(state: AppState): Node[] {
989993 );
990994 }
991995
992- // Empty state
993- if (nodes.length === 0) {
994- nodes.push(Spacer());
995- nodes.push(
996- VStack({ alignItems: "center" }, [
997- Text(
998- state.model
999- ? "Ready. Type a message to start."
1000- : "No providers configured. Use /login to authenticate.",
1001- { fgColor: state.theme.mutedText, italic: true },
1002- ),
1003- ]),
1004- );
1005- nodes.push(Spacer());
1006- }
1007-
1008996 return nodes;
1009997 }
1010998
@@ -1130,6 +1118,82 @@ export interface InputController {
11301118 onKeyPress: (key: string) => boolean | undefined;
11311119 }
11321120
1121+function getLongestCommonPrefix(values: readonly string[]): string {
1122+ if (values.length === 0) {
1123+ return "";
1124+ }
1125+
1126+ let prefix = values[0]!;
1127+ for (let i = 1; i < values.length && prefix.length > 0; i++) {
1128+ const value = values[i]!;
1129+ let j = 0;
1130+ while (j < prefix.length && j < value.length && prefix[j] === value[j]) {
1131+ j++;
1132+ }
1133+ prefix = prefix.slice(0, j);
1134+ }
1135+
1136+ return prefix;
1137+}
1138+
1139+function autocompleteInputPath(state: AppState): void {
1140+ const tokenMatch = /(^|\s)(\S+)$/.exec(inputValue);
1141+ if (!tokenMatch?.[2]) {
1142+ return;
1143+ }
1144+
1145+ const token = tokenMatch[2];
1146+ const tokenStart = tokenMatch.index + tokenMatch[1]!.length;
1147+ const slashIndex = token.lastIndexOf("/");
1148+ const dirToken = slashIndex >= 0 ? token.slice(0, slashIndex + 1) : "";
1149+ const partial = token.slice(slashIndex + 1);
1150+ const searchDir = isAbsolute(token)
1151+ ? dirToken || "/"
1152+ : join(state.cwd, dirToken || ".");
1153+
1154+ const entries = (() => {
1155+ try {
1156+ return readdirSync(searchDir, {
1157+ encoding: "utf8",
1158+ withFileTypes: true,
1159+ });
1160+ } catch {
1161+ return null;
1162+ }
1163+ })();
1164+ if (!entries) {
1165+ return;
1166+ }
1167+
1168+ const showHidden = partial.startsWith(".");
1169+ const matches = entries
1170+ .filter((entry) => (showHidden ? true : !entry.name.startsWith(".")))
1171+ .filter((entry) => entry.name.startsWith(partial))
1172+ .sort((a, b) => a.name.localeCompare(b.name));
1173+
1174+ if (matches.length === 0) {
1175+ return;
1176+ }
1177+
1178+ let completedName: string | null = null;
1179+ if (matches.length === 1) {
1180+ const match = matches[0]!;
1181+ completedName = `${match.name}${match.isDirectory() ? "/" : ""}`;
1182+ } else {
1183+ const prefix = getLongestCommonPrefix(matches.map((entry) => entry.name));
1184+ if (prefix.length > partial.length) {
1185+ completedName = prefix;
1186+ }
1187+ }
1188+
1189+ if (!completedName) {
1190+ return;
1191+ }
1192+
1193+ inputValue = `${inputValue.slice(0, tokenStart)}${dirToken}${completedName}`;
1194+ cel.render();
1195+}
1196+
11331197 /**
11341198 * Create stable handlers for the main TextInput.
11351199 *
@@ -1162,8 +1226,12 @@ export function createInputController(state: AppState): InputController {
11621226 handleInput(raw, state);
11631227 return false;
11641228 }
1165- if (key === "tab" && inputValue.startsWith("/")) {
1166- showCommandAutocomplete(state);
1229+ if (key === "tab") {
1230+ if (inputValue.startsWith("/")) {
1231+ showCommandAutocomplete(state);
1232+ } else {
1233+ autocompleteInputPath(state);
1234+ }
11671235 return false;
11681236 }
11691237 },
@@ -1849,9 +1917,83 @@ function handleCommand(command: string, state: AppState): boolean {
18491917 // Agent loop wiring
18501918 // ---------------------------------------------------------------------------
18511919
1920+function stripSkillFrontmatter(content: string): string {
1921+ const frontmatter = content.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);
1922+ return frontmatter ? content.slice(frontmatter[0].length) : content;
1923+}
1924+
1925+function buildSkillMessageContent(
1926+ skillName: string,
1927+ userText: string,
1928+ state: AppState,
1929+): string | null {
1930+ const skill = state.skills.find((entry) => entry.name === skillName);
1931+ if (!skill) {
1932+ appendInfoMessage(`Unknown skill: ${skillName}`, state);
1933+ return null;
1934+ }
1935+
1936+ let skillBody: string;
1937+ try {
1938+ skillBody = stripSkillFrontmatter(readFileSync(skill.path, "utf-8")).trim();
1939+ } catch (err) {
1940+ const message = err instanceof Error ? err.message : String(err);
1941+ appendInfoMessage(`Failed to read skill ${skillName}: ${message}`, state);
1942+ return null;
1943+ }
1944+
1945+ const parts = [skillBody, userText].filter((part) => part.length > 0);
1946+ return parts.length > 0 ? parts.join("\n\n") : null;
1947+}
1948+
1949+function buildImageMessageContent(
1950+ imagePath: string,
1951+ rawInput: string,
1952+ state: AppState,
1953+): UserMessage["content"] | null {
1954+ const displayPath = rawInput.trim();
1955+
1956+ try {
1957+ const result = executeReadImage({ path: imagePath }, state.cwd);
1958+ if (result.isError) {
1959+ return displayPath || null;
1960+ }
1961+
1962+ return [
1963+ { type: "text", text: displayPath },
1964+ ...result.content.filter((block) => block.type === "image"),
1965+ ];
1966+ } catch {
1967+ return displayPath || null;
1968+ }
1969+}
1970+
1971+function isEmptyUserContent(content: UserMessage["content"]): boolean {
1972+ if (typeof content === "string") {
1973+ return content.trim().length === 0;
1974+ }
1975+
1976+ return content.every(
1977+ (block) => block.type === "text" && block.text.trim().length === 0,
1978+ );
1979+}
1980+
1981+function submitMessageAsync(
1982+ content: UserMessage["content"],
1983+ state: AppState,
1984+ rawInput: string,
1985+): void {
1986+ submitMessage(content, state, rawInput).catch((err) => {
1987+ console.error("Submit error:", err);
1988+ });
1989+}
1990+
18521991 /** Route raw user input through parseInput and dispatch accordingly. */
18531992 export function handleInput(raw: string, state: AppState): void {
1854- const parsed = parseInput(raw);
1993+ const parsed = parseInput(raw, {
1994+ supportsImages: state.model?.input.includes("image") ?? false,
1995+ cwd: state.cwd,
1996+ });
18551997
18561998 switch (parsed.type) {
18571999 case "command":
@@ -1859,24 +2001,39 @@ export function handleInput(raw: string, state: AppState): void {
18592001 // Unimplemented command — ignore for now
18602002 }
18612003 break;
2004+ case "skill": {
2005+ const content = buildSkillMessageContent(
2006+ parsed.skillName,
2007+ parsed.userText,
2008+ state,
2009+ );
2010+ if (content) {
2011+ submitMessageAsync(content, state, raw);
2012+ }
2013+ break;
2014+ }
2015+ case "image": {
2016+ const content = buildImageMessageContent(parsed.path, raw, state);
2017+ if (content) {
2018+ submitMessageAsync(content, state, raw);
2019+ }
2020+ break;
2021+ }
18622022 case "text":
18632023 if (parsed.text) {
1864- submitMessage(parsed.text, state, raw).catch((err) => {
1865- console.error("Submit error:", err);
1866- });
2024+ submitMessageAsync(parsed.text, state, raw);
18672025 }
18682026 break;
1869- // skill and image handling will be added in Phase 4d
18702027 }
18712028 }
18722029
1873-/** Send a plain text message and run the agent loop. */
2030+/** Send a user message and run the agent loop. */
18742031 async function submitMessage(
1875- text: string,
2032+ content: UserMessage["content"],
18762033 state: AppState,
1877- rawInput = text,
2034+ rawInput: string,
18782035 ): Promise<void> {
1879- if (!text.trim() || !state.model || state.running) return;
2036+ if (isEmptyUserContent(content) || !state.model || state.running) return;
18802037
18812038 const session = ensureSession(state);
18822039 appendPromptHistory(state.db, {
@@ -1888,7 +2045,7 @@ async function submitMessage(
18882045
18892046 const userMessage: Message = {
18902047 role: "user",
1891- content: text,
2048+ content,
18922049 timestamp: Date.now(),
18932050 };