warden-agent 0.4.0 → 0.5.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.
package/src/tui/app.mjs CHANGED
@@ -1,500 +1,729 @@
1
- // Warden interactive terminal app: chat with any model, which reads, edits and runs code in this folder.
2
- import readline from "node:readline";
3
- import { spawn } from "node:child_process";
4
- import { C, MarkdownStream, Spinner, toolHeader, toolBody, fmtTokens } from "./render.mjs";
5
- import { runTurn } from "../agent/loop.mjs";
6
- import { Session } from "../agent/session.mjs";
7
- import { loadAgentConfig, saveAgentConfig, pickDefaultModel, CONFIG_FILE } from "../agent/config.mjs";
8
- import { parseModelSpec, keyStatus, listModels, resolveProvider } from "../agent/providers.mjs";
9
- import { MODES, detectShell } from "../agent/tools.mjs";
10
- import { CATALOG, ADD_ORDER } from "../agent/catalog.mjs";
11
- import { saveKey, removeKey, mask, CREDENTIALS_FILE } from "../agent/credentials.mjs";
12
- import { savedModels, findModel, resolveModelInput, addModel, removeModel, removeModelsOf, suggestName, probeToolSupport } from "../agent/models.mjs";
13
-
14
- import { VERSION } from "../version.mjs";
15
- import { updateNotice } from "../agent/update.mjs";
16
- const COMMANDS = {
17
- "/help": "show commands",
18
- "/add": "add a model: pick a source (OpenRouter, Hugging Face, NVIDIA, DeepSeek, Ollama…), paste a key, pick a model",
19
- "/model": "pick from your saved models, or /model <name> or /model provider/model",
20
- "/models": "browse a source's models: /models openrouter nemotron --free",
21
- "/providers": "which sources are connected",
22
- "/remove": "remove a saved model, or a source's saved key: /remove <name>",
23
- "/mode": "permission mode: ask | auto-edit | yolo (also shift+tab)",
24
- "/clear": "start a new conversation",
25
- "/resume": "continue an earlier conversation",
26
- "/usage": "tokens used in this conversation",
27
- "/init": "have the model write a WARDEN.md with notes about this project",
28
- "/exit": "quit (also ctrl+d)",
29
- };
30
-
31
- export async function startApp({ cwd = process.cwd(), model, mode, resume, initialPrompt } = {}) {
32
- const cfg = loadAgentConfig();
33
- const out = process.stdout;
34
- const tty = !!process.stdin.isTTY;
35
- let session;
36
- if (resume) {
37
- try { session = resume === true ? latestFor(cwd) : Session.load(resume); } catch (e) { console.error(C.red(e.message)); }
38
- }
39
- // --model accepts a saved name too
40
- if (model) { try { model = resolveModelInput(cfg, model); } catch (e) { console.error(C.red(e.message)); model = undefined; } }
41
- session ||= new Session({ cwd, model: model || cfg.model || pickDefaultModel() });
42
- if (model) session.model = model;
43
- const perm = { mode: MODES.includes(mode) ? mode : MODES.includes(cfg.mode) ? cfg.mode : "ask", allowed: new Set() };
44
-
45
- let busy = false, controller = null, lastSigint = 0, pending = [], flushTimer = null, closed = false;
46
-
47
- const rl = readline.createInterface({
48
- input: process.stdin, output: out, terminal: tty, historySize: 200,
49
- completer: (line) => {
50
- if (!line.startsWith("/")) return [[], line];
51
- const m = line.match(/^\/(model|remove) (.*)$/);
52
- if (m) { const opts = savedModels(cfg).map((x) => `/${m[1]} ${x.name}`).filter((o) => o.startsWith(line)); return [opts, line]; }
53
- const hits = Object.keys(COMMANDS).filter((c) => c.startsWith(line));
54
- return [hits.length ? hits : Object.keys(COMMANDS), line];
55
- },
56
- });
57
- const promptStr = () => `${C.accent("›")} `;
58
- rl.setPrompt(promptStr());
59
- const ask = (q) => new Promise((res) => rl.question(q, (a) => res(a)));
60
- // In piped mode a question takes the next input line, waiting for it if it has not arrived yet
61
- // (end of input = the default). Lines never leak past a question into the conversation.
62
- const waiters = [];
63
- const nextLine = (dflt) => (queue.length ? Promise.resolve(queue.shift()) : closed ? Promise.resolve(dflt) : new Promise((res) => waiters.push({ res, dflt })));
64
- const answer = async (q, dflt = "n") => { if (tty) return ask(q); const a = await nextLine(dflt); out.write(q + a + "\n"); return a; };
65
- // Hidden input for API keys: shows * per character and keeps the key out of the input history.
66
- const askSecret = async (q) => {
67
- if (!tty) { const a = await nextLine(""); out.write(q + (a ? "*".repeat(Math.min(a.length, 12)) : "") + "\n"); return a; }
68
- return new Promise((res) => {
69
- const orig = rl._writeToOutput;
70
- rl._writeToOutput = (s) => {
71
- if (s.includes(q)) out.write(q + "*".repeat(Math.min(rl.line.length, 40)));
72
- else if (/^[\r\n]+$/.test(s)) out.write(s);
73
- else out.write("*".repeat(s.length));
74
- };
75
- rl.question(q, (a) => {
76
- rl._writeToOutput = orig;
77
- if (Array.isArray(rl.history)) rl.history = rl.history.filter((h) => h !== a);
78
- res(a);
79
- });
80
- });
81
- };
82
-
83
- // ---------- banner ----------
84
- banner();
85
- if (session.messages.length) console.log(C.dim(` Resumed "${session.title || session.id}" (${session.messages.length} messages)\n`));
86
-
87
- // shift+tab cycles the permission mode while idle
88
- if (tty) {
89
- readline.emitKeypressEvents(process.stdin, rl);
90
- process.stdin.on("keypress", (_s, key) => {
91
- if (!busy && key?.name === "tab" && key.shift) {
92
- perm.mode = MODES[(MODES.indexOf(perm.mode) + 1) % MODES.length];
93
- readline.clearLine(out, 0); readline.cursorTo(out, 0);
94
- out.write(C.dim(` mode: ${modeLabel(perm.mode)}\n`));
95
- rl.prompt(true);
96
- }
97
- });
98
- }
99
-
100
- rl.on("SIGINT", () => {
101
- if (busy && controller) { controller.abort(); out.write(C.yellow("\n Interrupting…\n")); return; }
102
- if (rl.line) { rl.write(null, { ctrl: true, name: "u" }); return; }
103
- if (Date.now() - lastSigint < 1500) return quit();
104
- lastSigint = Date.now();
105
- out.write(C.dim("\n (press ctrl+c again to quit)\n")); rl.prompt();
106
- });
107
- // Piped input (not a terminal): every line is one message, processed in order, then quit at end of input.
108
- const queue = [];
109
- let draining = false;
110
- async function drain() {
111
- if (draining) return;
112
- draining = true;
113
- while (queue.length) await handle(queue.shift());
114
- draining = false;
115
- if (closed) quit();
116
- }
117
-
118
- rl.on("close", () => {
119
- closed = true;
120
- while (waiters.length) { const w = waiters.shift(); w.res(w.dflt); } // unanswered questions get their default
121
- if (!busy && !draining) quit();
122
- });
123
-
124
- rl.on("line", (line) => {
125
- if (!tty) {
126
- if (waiters.length) { waiters.shift().res(line); return; } // a question is waiting for this line
127
- queue.push(line); drain(); return;
128
- }
129
- if (busy) return; // typing while the model works is ignored; ctrl+c interrupts
130
- // Lines that arrive within a few ms are one pasted message; a trailing "\" continues on the next line.
131
- pending.push(line);
132
- clearTimeout(flushTimer);
133
- if (line.endsWith("\\")) { pending[pending.length - 1] = line.slice(0, -1); rl.setPrompt(C.dim("… ")); rl.prompt(); return; }
134
- flushTimer = setTimeout(() => { const text = pending.join("\n"); pending = []; rl.setPrompt(promptStr()); handle(text).then(() => { if (closed) quit(); else rl.prompt(); }); }, 25);
135
- });
136
-
137
- // First run (no usable key for the current model): walk the person through getting one, then start.
138
- (async () => {
139
- if (needsSetup()) await firstRun();
140
- if (initialPrompt) { queue.push(initialPrompt); await drain(); }
141
- if (tty && !closed) rl.prompt();
142
- })();
143
-
144
- function needsSetup() {
145
- try { return /missing/.test(keyStatus(parseModelSpec(session.model).provider, cfg)); } catch { return false; }
146
- }
147
-
148
- async function firstRun() {
149
- console.log(` ${C.bold("Welcome to Warden.")} It needs one AI model to work. The easiest free one is ${C.bold("Google Gemini")}:`);
150
- console.log(` 1. Open ${C.accent("https://aistudio.google.com/apikey")} and sign in with a Google account`);
151
- console.log(` 2. Click ${C.bold("Create API key")} and copy it`);
152
- console.log(` 3. Pick ${C.bold("1")} below and paste the key`);
153
- console.log(C.dim(` Other free sources are listed too. Press enter to skip; /add starts this again any time. Stuck? Run: warden doctor`));
154
- await addWizard();
155
- }
156
-
157
- // ---------- handlers ----------
158
- async function handle(raw) {
159
- const text = raw.trim();
160
- if (!text) return;
161
- if (!tty) console.log(`${C.accent("›")} ${text}`);
162
- if (text.startsWith("/")) return command(text);
163
- if (text.startsWith("!")) return shellPassthrough(text.slice(1).trim());
164
- await turn(text);
165
- }
166
-
167
- async function turn(text) {
168
- busy = true; controller = new AbortController();
169
- const md = new MarkdownStream(out, C);
170
- const spin = new Spinner(out, C);
171
- const t0 = Date.now(), before = { ...session.usage };
172
- let streaming = false;
173
- console.log();
174
- const ui = {
175
- onAssistantStart: () => { spin.start("Thinking"); streaming = false; },
176
- onText: (d) => { if (!streaming) { spin.stop(); streaming = true; } md.write(d); },
177
- onAssistantEnd: () => { spin.stop(); if (md.end()) out.write("\n"); },
178
- onRetry: ({ status, waitMs, attempt }) => spin.setLabel(`Rate limited (${status}), retrying in ${Math.round(waitMs / 1000)}s, attempt ${attempt}`),
179
- onNotice: (m) => console.log(C.dim(` ${m}\n`)),
180
- onToolStart: (call, tool) => { spin.stop(); call._shown = false; },
181
- confirm: async (call, tool, desc) => {
182
- spin.stop();
183
- showTool(call, tool, null, "run"); call._shown = true;
184
- const kind = tool.kind === "bash" ? "Run this command" : tool.kind === "edit" ? "Allow this change" : "Allow reading outside the project";
185
- if (tool.kind === "edit" && call.args?.old_string !== undefined) previewEdit(call.args);
186
- for (;;) {
187
- const a = (await answer(` ${C.yellow("?")} ${kind}? ${C.dim(`[y] yes [a] always allow ${tool.name} this session [n] no, or type what to do instead`)}\n ${C.accent("›")} `)).trim();
188
- if (controller.signal.aborted) return "no";
189
- if (/^(y|yes)$/i.test(a)) return "yes";
190
- if (/^(a|always)$/i.test(a)) return "always";
191
- if (/^(n|no)$/i.test(a)) return "no";
192
- if (a) return { reason: a };
193
- }
194
- },
195
- onToolEnd: (call, tool, res) => {
196
- const state = res?.denied ? "deny" : res?.error ? "err" : res?.isError ? "err" : "ok";
197
- showTool(call, tool, res, state, call._shown);
198
- console.log();
199
- },
200
- };
201
- try {
202
- const r = await runTurn({ session, userText: text, cfg, ui, perm, signal: controller.signal, cwd });
203
- if (r.interrupted) console.log(C.yellow(" Interrupted.\n"));
204
- } catch (e) {
205
- spin.stop(); md.end();
206
- console.log(C.red(` Error: ${e.message}`));
207
- if (/API key|no API key/i.test(e.message)) console.log(C.dim(` Set the key as an environment variable, or pick another model with /model. Providers: /model`));
208
- else if (/^4(01|03)/.test(e.message)) console.log(C.dim(" The provider rejected the key or the request. Check the key and the model name (/models <provider>)."));
209
- else if (/^404/.test(e.message)) console.log(C.dim(" Model not found. See what this provider offers with /models <provider>."));
210
- else if (/^429/.test(e.message)) console.log(C.dim(" This model's rate limit or free quota is used up. Switch with /model (another model usually has its own quota), or /add a free one."));
211
- console.log();
212
- } finally {
213
- spin.stop();
214
- busy = false; controller = null;
215
- const u = session.usage;
216
- const tin = u.input - before.input, tout = u.output - before.output;
217
- console.log(C.gray(` ${session.model} · ${tin || tout ? `${fmtTokens(tin)} in / ${fmtTokens(tout)} out · ` : ""}${((Date.now() - t0) / 1000).toFixed(1)}s · ${modeLabel(perm.mode)}`));
218
- console.log();
219
- }
220
- }
221
-
222
- function showTool(call, tool, res, state, alreadyShownHeader = false) {
223
- const title = res?.display?.title || (tool ? defaultTitle(tool, call.args) : `Unknown tool ${call.name}`);
224
- if (!alreadyShownHeader || res) {
225
- if (alreadyShownHeader && res) { /* header printed at confirm time; print result only */ }
226
- else console.log(toolHeader(C, title, state));
227
- }
228
- if (res) for (const l of toolBody(C, res.display, res)) console.log(l);
229
- }
230
-
231
- function previewEdit(a) {
232
- const lines = [...String(a.old_string).split("\n").map((s) => C.bgRed(C.red(` - ${s}`))), ...String(a.new_string ?? "").split("\n").map((s) => C.bgGreen(C.green(` + ${s}`)))];
233
- for (const l of lines.slice(0, 40)) console.log(" " + l);
234
- if (lines.length > 40) console.log(C.gray(` … ${lines.length - 40} more lines`));
235
- }
236
-
237
- async function shellPassthrough(cmd) {
238
- if (!cmd) return;
239
- const sh = detectShell();
240
- console.log(C.dim(` $ ${cmd}`));
241
- const r = await new Promise((res) => {
242
- const p = spawn(sh.cmd, sh.args(cmd), { cwd, windowsHide: true });
243
- let o = ""; p.stdout.on("data", (d) => { o += d; out.write(C.gray(String(d))); }); p.stderr.on("data", (d) => { o += d; out.write(C.gray(String(d))); });
244
- p.on("close", (code) => res({ code, o })); p.on("error", (e) => res({ code: -1, o: e.message }));
245
- });
246
- console.log(C.dim(` [exit ${r.code}]\n`));
247
- // the model sees what you ran, like a shared terminal
248
- session.push({ role: "user", content: `I ran this shell command myself:\n$ ${cmd}\n[exit ${r.code}]\n${r.o.slice(-8000)}\n(No reply needed unless I ask.)` });
249
- session.push({ role: "assistant", content: "Noted." });
250
- }
251
-
252
- async function command(text) {
253
- const [cmd, ...rest] = text.split(/\s+/);
254
- const arg = rest.join(" ").trim();
255
- switch (cmd) {
256
- case "/help": case "/?":
257
- console.log();
258
- for (const [k, v] of Object.entries(COMMANDS)) console.log(` ${C.accent(k.padEnd(9))} ${C.dim(v)}`);
259
- console.log(` ${C.accent("!cmd".padEnd(9))} ${C.dim("run a shell command yourself; the model sees the output")}`);
260
- console.log(C.dim(`\n Keys: ctrl+c interrupts the model (twice at an empty prompt quits) · shift+tab cycles the mode · end a line with \\ for multi-line\n Settings: ${CONFIG_FILE}\n`));
261
- break;
262
- case "/exit": case "/quit": closed = true; break;
263
- case "/clear":
264
- session = new Session({ cwd, model: session.model }); perm.allowed.clear();
265
- console.log(C.dim(" New conversation.\n")); break;
266
- case "/usage": case "/cost": {
267
- const u = session.usage;
268
- console.log(C.dim(` ${u.calls} model calls · ${fmtTokens(u.input)} input / ${fmtTokens(u.output)} output tokens (as reported by the provider; free tiers cost nothing)\n`)); break;
269
- }
270
- case "/mode":
271
- if (!arg) { console.log(C.dim(` mode: ${modeLabel(perm.mode)}. Options: ${MODES.join(", ")}\n`)); break; }
272
- if (!MODES.includes(arg)) { console.log(C.red(` unknown mode "${arg}". Options: ${MODES.join(", ")}\n`)); break; }
273
- perm.mode = arg; saveAgentConfig({ mode: arg });
274
- console.log(C.dim(` mode: ${modeLabel(arg)}${arg === "yolo" ? C.yellow(" (edits and shell commands run without asking)") : ""}\n`)); break;
275
- case "/model": {
276
- if (!arg) {
277
- const list = savedModels(cfg);
278
- console.log(`\n current: ${C.bold(session.model)}${findModel(cfg, session.model) ? C.gray(` (${findModel(cfg, session.model).name})`) : ""}\n`);
279
- if (!list.length) { console.log(C.dim(" No saved models yet. /add connects a source and picks a model.\n")); break; }
280
- list.forEach((m, i) => console.log(` ${C.accent(String(i + 1).padStart(2))} ${(m.spec === session.model ? C.mint("● ") : " ") + m.name.padEnd(32)} ${C.gray(m.spec)}${toolTag(m.tools)}`));
281
- const pick = (await answer(`\n Number to switch to (enter to keep the current one) ${C.accent("›")} `, "")).trim();
282
- if (!pick) { console.log(); break; }
283
- const m = /^\d+$/.test(pick) ? list[Number(pick) - 1] : findModel(cfg, pick);
284
- if (!m) { console.log(C.red(" no such model\n")); break; }
285
- switchModel(m.spec);
286
- break;
287
- }
288
- try { switchModel(resolveModelInput(cfg, arg)); } catch (e) { console.log(C.red(` ${e.message}\n`)); }
289
- break;
290
- }
291
- case "/models": {
292
- const words = arg.split(/\s+/).filter(Boolean);
293
- const onlyFree = words.includes("--free");
294
- const rest = words.filter((w) => w !== "--free");
295
- const name = rest[0] || parseModelSpec(session.model).provider;
296
- const query = rest.slice(1).join(" ");
297
- const spin = new Spinner(out, C); spin.start(`Asking ${name} for its models`);
298
- try {
299
- let list = await listModels(name, cfg); spin.stop();
300
- if (onlyFree) list = list.filter((m) => m.free);
301
- if (query) list = list.filter((m) => m.id.toLowerCase().includes(query.toLowerCase()));
302
- console.log(`\n ${C.bold(name)}: ${list.length} model${list.length === 1 ? "" : "s"}${onlyFree ? " (free)" : ""}${query ? ` matching "${query}"` : ""}${list.length > 80 ? ", first 80 shown" : ""}`);
303
- for (const m of list.slice(0, 80)) console.log(` ${name}/${m.id}${modelFlags(m)}`);
304
- console.log(C.dim(`\n Use one: /model ${name}/<id> · save it with a short name: /add\n`));
305
- } catch (e) { spin.stop(); console.log(C.red(` ${e.message}\n`)); }
306
- break;
307
- }
308
- case "/add": await addWizard(); break;
309
- case "/providers": {
310
- console.log();
311
- for (const name of [...ADD_ORDER, ...Object.keys(cfg.providers || {}).filter((n) => !CATALOG[n])]) {
312
- let st; try { st = keyStatus(name, cfg); } catch (e) { st = e.message; }
313
- const ok = !/missing/.test(st);
314
- const n = savedModels(cfg).filter((m) => m.spec.startsWith(name + "/")).length;
315
- const p = CATALOG[name] || cfg.providers[name];
316
- console.log(` ${ok ? C.mint("●") : C.gray("○")} ${(p?.label || name).padEnd(14)} ${C.dim(st.padEnd(28))}${n ? C.accent(` ${n} saved model${n > 1 ? "s" : ""}`) : ""}${p?.blurb ? C.gray(" · " + p.blurb) : ""}`);
317
- }
318
- console.log(C.dim("\n /add connects one · /remove <source> forgets its saved key\n"));
319
- break;
320
- }
321
- case "/remove": {
322
- if (!arg) { console.log(C.dim(" usage: /remove <model name> or /remove <source> (e.g. /remove openrouter) to forget its saved key\n")); break; }
323
- if (removeModel(cfg, arg)) { console.log(C.dim(` Removed model "${arg}".\n`)); break; }
324
- const prov = Object.keys({ ...CATALOG, ...(cfg.providers || {}) }).find((n) => n === arg.toLowerCase());
325
- if (!prov) { console.log(C.red(` "${arg}" is neither a saved model nor a source. /model and /providers list them.\n`)); break; }
326
- const sure = (await answer(` Forget the saved ${prov} key and remove its saved models? [y/N] `, "n")).trim();
327
- if (!/^y/i.test(sure)) { console.log(C.dim(" Kept.\n")); break; }
328
- const hadKey = removeKey(prov), n = removeModelsOf(cfg, prov);
329
- if (cfg.providers?.[prov]) { delete cfg.providers[prov]; saveAgentConfig({ providers: cfg.providers }); }
330
- console.log(C.dim(` ${hadKey ? "Saved key deleted" : "No saved key (environment variables are not touched)"}; ${n} model${n === 1 ? "" : "s"} removed.\n`));
331
- break;
332
- }
333
- case "/resume": case "/sessions": {
334
- const list = Session.list(15);
335
- if (!list.length) { console.log(C.dim(" No saved conversations yet.\n")); break; }
336
- let pick = arg;
337
- if (!pick) {
338
- console.log();
339
- list.forEach((s, i) => console.log(` ${C.accent(String(i + 1).padStart(2))} ${(s.title || "").slice(0, 60).padEnd(60)} ${C.gray(new Date(s.mtime).toLocaleString())}${s.cwd !== cwd ? C.gray(" (other folder)") : ""}`));
340
- pick = (await answer(`\n Number to resume (enter to cancel) ${C.accent("›")} `)).trim();
341
- if (!pick) break;
342
- if (/^\d+$/.test(pick)) pick = list[Number(pick) - 1]?.id;
343
- }
344
- try {
345
- session = Session.load(pick); perm.allowed.clear();
346
- console.log(C.dim(` Resumed "${session.title}" (${session.messages.length} messages, model ${session.model}).\n`));
347
- replayTail();
348
- } catch (e) { console.log(C.red(` ${e.message}\n`)); }
349
- break;
350
- }
351
- case "/init":
352
- await turn("Explore this project (structure, languages, how to build, test and run it, conventions you notice) and write a concise WARDEN.md at the project root with notes that would help a coding agent work here. Keep it under 80 lines. If WARDEN.md exists, improve it instead of replacing useful content.");
353
- break;
354
- default:
355
- console.log(C.red(` unknown command ${cmd}. /help lists commands.\n`));
356
- }
357
- }
358
-
359
- function switchModel(spec) {
360
- const { provider } = parseModelSpec(spec);
361
- resolveProvider(provider, cfg);
362
- session.model = spec;
363
- const recent = [spec, ...(cfg.recentModels || []).filter((m) => m !== spec)].slice(0, 8);
364
- cfg.recentModels = recent; cfg.model = spec;
365
- saveAgentConfig({ model: spec, recentModels: recent });
366
- let st = ""; try { st = keyStatus(provider, cfg); } catch {}
367
- const m = findModel(cfg, spec);
368
- console.log(C.dim(` model: ${m ? m.name + " = " : ""}${spec} (${st})${m?.tools === "none" ? C.yellow(" · chat only, it cannot read or edit files") : m?.tools === "text" ? " · text tool format" : ""}. Saved as your default.\n`));
369
- }
370
-
371
- // /add: pick a source, give it a key, pick a model, test it, save it under a short name.
372
- async function addWizard() {
373
- const names = [...ADD_ORDER];
374
- console.log(`\n ${C.bold("Where do you want models from?")}\n`);
375
- names.forEach((n, i) => {
376
- const p = CATALOG[n];
377
- let st = ""; try { st = keyStatus(n, cfg); } catch {}
378
- const ok = !/missing/.test(st);
379
- console.log(` ${C.accent(String(i + 1).padStart(2))} ${(ok ? C.mint("● ") : C.gray("○ ")) + p.label.padEnd(14)} ${C.gray(p.blurb)}`);
380
- });
381
- console.log(` ${C.accent(" c")} ${C.gray("○ ")}${"Custom".padEnd(14)} ${C.gray("any OpenAI-compatible server (URL)")}`);
382
- const pick = (await answer(`\n Number (enter to cancel) ${C.accent("›")} `, "")).trim().toLowerCase();
383
- if (!pick) return console.log();
384
- let name;
385
- if (pick === "c") {
386
- name = (await answer(` Short name for this source (letters/numbers, e.g. together) ${C.accent("›")} `, "")).trim().toLowerCase().replace(/[^a-z0-9-]/g, "");
387
- if (!name || CATALOG[name]) return console.log(C.red(` ${name ? `"${name}" is a built-in source; pick it from the list` : "cancelled"}\n`));
388
- const url = (await answer(` Base URL (the part before /chat/completions, e.g. https://api.together.xyz/v1) ${C.accent("›")} `, "")).trim().replace(/\/+$/, "");
389
- if (!/^https?:\/\//.test(url)) return console.log(C.red(" That does not look like a URL. Cancelled.\n"));
390
- cfg.providers = { ...(cfg.providers || {}), [name]: { label: name, api: "openai", baseUrl: url, keyEnv: [] } };
391
- saveAgentConfig({ providers: cfg.providers });
392
- } else {
393
- name = names[Number(pick) - 1];
394
- if (!name) return console.log(C.red(" No such number.\n"));
395
- }
396
- const p = resolveProvider(name, cfg);
397
-
398
- // key
399
- let st = ""; try { st = keyStatus(name, cfg); } catch {}
400
- const needsKey = !!p.keyEnv?.length || pick === "c";
401
- if (needsKey) {
402
- const has = /key from|saved/.test(st);
403
- if (p.keyUrl) console.log(C.dim(` Get a key at ${p.keyUrl}`));
404
- const k = (await askSecret(` ${has ? `Key found (${st}). Paste a new one or press enter to keep it` : `Paste your ${p.label || name} key${pick === "c" ? " (enter if it needs none)" : ""}`}: `)).trim();
405
- if (k) { saveKey(name, k); console.log(C.dim(` Saved ${mask(k)} to ${CREDENTIALS_FILE}`)); }
406
- else if (!has && pick !== "c") return console.log(C.red(" No key, cancelled.\n"));
407
- } else console.log(C.dim(` ${p.label} runs on your PC; make sure it is running and has a model downloaded.`));
408
-
409
- // model
410
- const spin = new Spinner(out, C); spin.start(`Asking ${p.label || name} for its models`);
411
- let list = [];
412
- try { list = await listModels(name, cfg); spin.stop(); } catch (e) { spin.stop(); console.log(C.yellow(` Could not list models (${e.message}). You can still type a model id.`)); }
413
- let id;
414
- if (list.length) {
415
- const free = list.filter((m) => m.free);
416
- console.log(C.dim(` ${list.length} models${free.length ? `, ${free.length} free` : ""}.`));
417
- const q = (await answer(` Search (enter for ${free.length ? "free ones" : "all"}, "all" for everything) ${C.accent("›")} `, "")).trim().toLowerCase();
418
- let shown = q === "all" ? list : q ? list.filter((m) => m.id.toLowerCase().includes(q)) : free.length ? free : list;
419
- shown = [...shown].sort((a, b) => (b.free === true) - (a.free === true) || (b.tools === true) - (a.tools === true) || a.id.localeCompare(b.id));
420
- if (!shown.length) console.log(C.yellow(" Nothing matched."));
421
- shown.slice(0, 30).forEach((m, i) => console.log(` ${C.accent(String(i + 1).padStart(2))} ${m.id}${modelFlags(m)}`));
422
- if (shown.length > 30) console.log(C.gray(` … ${shown.length - 30} more; search to narrow down`));
423
- const sel = (await answer(` Number, or type a model id ${C.accent("›")} `, "")).trim();
424
- if (!sel) return console.log(C.dim(" Cancelled.\n"));
425
- id = /^\d+$/.test(sel) ? shown[Number(sel) - 1]?.id : sel;
426
- if (!id) return console.log(C.red(" No such number.\n"));
427
- } else {
428
- id = (await answer(` Model id ${C.accent("›")} `, "")).trim();
429
- if (!id) return console.log(C.dim(" Cancelled.\n"));
430
- }
431
- const spec = `${name}/${id}`;
432
- const meta = list.find((m) => m.id === id) || {};
433
-
434
- // test it once: proves the key and model work, and finds out how it can use tools
435
- const spin2 = new Spinner(out, C); spin2.start(`Testing ${spec}`);
436
- let tools = null;
437
- try {
438
- const r = await probeToolSupport(spec, cfg, { onRetry: ({ status, waitMs }) => spin2.setLabel(`Rate limited (${status}), retrying in ${Math.round(waitMs / 1000)}s`) });
439
- spin2.stop(); tools = r.mode;
440
- console.log(` ${r.mode === "none" ? C.yellow("!") : C.mint("✓")} Works. ${r.detail}.`);
441
- } catch (e) {
442
- spin2.stop();
443
- console.log(C.red(` Test failed: ${e.message}`));
444
- const keep = (await answer(` Save it anyway? [y/N] `, "n")).trim();
445
- if (!/^y/i.test(keep)) return console.log(C.dim(" Not saved.\n"));
446
- }
447
- let short = suggestName(id);
448
- const typed = (await answer(` Name it (enter for "${short}") ${C.accent("›")} `, "")).trim();
449
- if (typed) short = typed.replace(/\s+/g, "-");
450
- addModel(cfg, { name: short, spec, ctx: meta.ctx || null, tools });
451
- console.log(C.mint(` ✓ Added ${short}.`));
452
- switchModel(spec);
453
- }
454
-
455
- function replayTail() {
456
- const tail = session.messages.filter((m) => (m.role === "user" || (m.role === "assistant" && m.content))).slice(-4);
457
- for (const m of tail) console.log(m.role === "user" ? `${C.accent("›")} ${m.content.slice(0, 300)}` : C.dim(` ${m.content.slice(0, 400)}`));
458
- console.log();
459
- }
460
-
461
- function banner() {
462
- let st = ""; try { st = keyStatus(parseModelSpec(session.model).provider, cfg); } catch (e) { st = e.message; }
463
- console.log();
464
- console.log(` ${C.mint("◉")} ${C.bold("Warden")} ${C.gray("v" + VERSION)}`);
465
- console.log(` ${C.gray("model")} ${session.model} ${/missing/.test(st) ? C.red(`(${st})`) : C.gray(`(${st})`)}`);
466
- console.log(` ${C.gray("mode ")} ${modeLabel(perm.mode)} ${C.gray("(shift+tab or /mode)")}`);
467
- console.log(` ${C.gray("dir ")} ${cwd}`);
468
- console.log(C.gray(` /help for commands · /model to switch models · ctrl+c to interrupt`));
469
- const upd = updateNotice(cfg);
470
- if (upd) console.log(C.yellow(` Warden ${upd} is available (you have ${VERSION}). Run: warden update`));
471
- console.log();
472
- }
473
-
474
- function quit() {
475
- session.save();
476
- try { rl.close(); } catch {}
477
- out.write(C.dim(`\n Saved conversation ${session.id}. Resume with: warden --resume ${session.id.slice(0, 12)}\n`));
478
- process.exit(0);
479
- }
480
- }
481
-
482
- function latestFor(cwd) {
483
- const s = Session.list(200).find((x) => x.cwd === cwd);
484
- if (!s) throw new Error("no earlier conversation in this folder");
485
- return Session.load(s.id);
486
- }
487
-
488
- const toolTag = (t) => (t === "none" ? C.yellow(" chat only") : t === "text" ? C.gray(" text tools") : "");
489
- const fmtCtx = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(n % 1e6 ? 1 : 0)}M` : `${Math.round(n / 1000)}k`);
490
- const modelFlags = (m) => {
491
- const f = [];
492
- if (m.free) f.push(C.mint("free"));
493
- if (m.tools === true) f.push(C.gray("tools"));
494
- if (m.tools === false) f.push(C.yellow("no tools"));
495
- if (m.ctx) f.push(C.gray(fmtCtx(m.ctx) + " ctx"));
496
- return f.length ? " " + f.join(C.gray(" · ")) : "";
497
- };
498
- const modeLabel = (m) => (m === "yolo" ? C.red("yolo") : m === "auto-edit" ? C.yellow("auto-edit") : C.mint("ask"));
499
- const TITLES = { read_file: "Read", write_file: "Write", edit_file: "Edit", list_dir: "List", glob: "Glob", grep: "Grep" };
500
- const defaultTitle = (tool, a = {}) => tool.name === "bash" ? `Bash ${a.command}` : `${TITLES[tool.name] || tool.name} ${a.path || a.pattern || ""}`.trim();
1
+ // Warden interactive terminal app: chat with any model, which reads, edits and runs code in this folder.
2
+ import readline from "node:readline";
3
+ import { spawn } from "node:child_process";
4
+ import { Writable } from "node:stream";
5
+ import { C, MarkdownStream, Spinner, toolHeader, toolBody, fmtTokens, stripAnsi } from "./render.mjs";
6
+ import { runTurn } from "../agent/loop.mjs";
7
+ import { Session } from "../agent/session.mjs";
8
+ import { loadAgentConfig, saveAgentConfig, pickDefaultModel, CONFIG_FILE } from "../agent/config.mjs";
9
+ import { parseModelSpec, keyStatus, listModels, resolveProvider } from "../agent/providers.mjs";
10
+ import { MODES, detectShell, listJobs, stopJob, jobRunning, describeJob } from "../agent/tools.mjs";
11
+ import { CATALOG, ADD_ORDER } from "../agent/catalog.mjs";
12
+ import { saveKey, removeKey, mask, CREDENTIALS_FILE } from "../agent/credentials.mjs";
13
+ import { savedModels, chatModels, imageModels, currentImageModel, setImageModel, findModel, resolveModelInput, addModel, removeModel, removeModelsOf, suggestName, probeToolSupport } from "../agent/models.mjs";
14
+ import { generateImage, saveImage, looksLikeImageModel, ASPECTS, fmtBytes } from "../agent/images.mjs";
15
+
16
+ import { VERSION } from "../version.mjs";
17
+ import { updateNotice } from "../agent/update.mjs";
18
+ const COMMANDS = {
19
+ "/help": "show commands",
20
+ "/add": "add a model: pick a source (OpenRouter, Hugging Face, NVIDIA, DeepSeek, Ollama…), paste a key, pick a model",
21
+ "/model": "pick from your saved models, or /model <name> or /model provider/model",
22
+ "/models": "browse a source's models: /models openrouter nemotron --free",
23
+ "/image": "make a picture with your image model: /image a red bike at night (--wide, --tall, --square)",
24
+ "/image-model": "pick the image model /image uses (add one with /add)",
25
+ "/providers": "which sources are connected",
26
+ "/remove": "remove a saved model, or a source's saved key: /remove <name>",
27
+ "/mode": "permission mode: ask | auto-edit | yolo (also shift+tab)",
28
+ "/clear": "start a new conversation",
29
+ "/resume": "continue an earlier conversation",
30
+ "/usage": "tokens used in this conversation",
31
+ "/jobs": "background commands the model started (dev servers…); /jobs stop <id>",
32
+ "/init": "have the model write a WARDEN.md with notes about this project",
33
+ "/exit": "quit (also ctrl+d)",
34
+ };
35
+
36
+ export async function startApp({ cwd = process.cwd(), model, mode, resume, initialPrompt } = {}) {
37
+ const cfg = loadAgentConfig();
38
+ const out = process.stdout;
39
+ const tty = !!process.stdin.isTTY;
40
+ let session;
41
+ if (resume) {
42
+ try { session = resume === true ? latestFor(cwd) : Session.load(resume); } catch (e) { console.error(C.red(e.message)); }
43
+ }
44
+ // --model accepts a saved name too
45
+ if (model) { try { model = resolveModelInput(cfg, model); } catch (e) { console.error(C.red(e.message)); model = undefined; } }
46
+ session ||= new Session({ cwd, model: model || cfg.model || pickDefaultModel() });
47
+ if (model) session.model = model;
48
+ const perm = { mode: MODES.includes(mode) ? mode : MODES.includes(cfg.mode) ? cfg.mode : "ask", allowed: new Set() };
49
+
50
+ let busy = false, controller = null, lastSigint = 0, pending = [], flushTimer = null, closed = false;
51
+
52
+ const rl = readline.createInterface({
53
+ input: process.stdin, output: out, terminal: tty, historySize: 200,
54
+ completer: (line) => {
55
+ if (!line.startsWith("/")) return [[], line];
56
+ const m = line.match(/^\/(model|remove|image-model) (.*)$/);
57
+ if (m) { const pool = m[1] === "model" ? chatModels(cfg) : m[1] === "image-model" ? imageModels(cfg) : savedModels(cfg); const opts = pool.map((x) => `/${m[1]} ${x.name}`).filter((o) => o.startsWith(line)); return [opts, line]; }
58
+ const hits = Object.keys(COMMANDS).filter((c) => c.startsWith(line));
59
+ return [hits.length ? hits : Object.keys(COMMANDS), line];
60
+ },
61
+ });
62
+ const promptStr = () => `${C.accent("›")} `;
63
+ rl.setPrompt(promptStr());
64
+ // While the model works, readline keeps reading keys (so you can type your next message) but draws them into this
65
+ // silent stream instead of the screen, where they would mix with the model's output. What you type shows in the
66
+ // status line; Enter queues it for the model.
67
+ const sink = new Writable({ write(_c, _e, cb) { cb(); } });
68
+ sink.isTTY = true;
69
+ Object.defineProperty(sink, "columns", { get: () => out.columns || 80 });
70
+ const echo = (on) => { if (tty) rl.output = on ? out : sink; };
71
+ let questions = 0, cancelQuestion = null;
72
+ // A question during a turn (approve this edit?) must not pick up the half-typed next message, and must be
73
+ // answerable even though echo is off; esc / ctrl+c cancels it.
74
+ const ask = (q) => new Promise((res) => {
75
+ const draft = rl.line || "";
76
+ rl.line = ""; rl.cursor = 0;
77
+ questions++; echo(true);
78
+ cancelQuestion = () => { rl.line = ""; rl.cursor = 0; rl.write("\n"); };
79
+ rl.question(q, (a) => {
80
+ questions--; cancelQuestion = null;
81
+ if (busy && !questions) echo(false);
82
+ rl.line = draft; rl.cursor = draft.length;
83
+ res(a);
84
+ });
85
+ });
86
+ // In piped mode a question takes the next input line, waiting for it if it has not arrived yet
87
+ // (end of input = the default). Lines never leak past a question into the conversation.
88
+ const waiters = [];
89
+ const nextLine = (dflt) => (queue.length ? Promise.resolve(queue.shift()) : closed ? Promise.resolve(dflt) : new Promise((res) => waiters.push({ res, dflt })));
90
+ const answer = async (q, dflt = "n") => { if (tty) return ask(q); const a = await nextLine(dflt); out.write(q + a + "\n"); return a; };
91
+ // Hidden input for API keys: shows * per character and keeps the key out of the input history.
92
+ const askSecret = async (q) => {
93
+ if (!tty) { const a = await nextLine(""); out.write(q + (a ? "*".repeat(Math.min(a.length, 12)) : "") + "\n"); return a; }
94
+ return new Promise((res) => {
95
+ const orig = rl._writeToOutput;
96
+ rl._writeToOutput = (s) => {
97
+ if (s.includes(q)) out.write(q + "*".repeat(Math.min(rl.line.length, 40)));
98
+ else if (/^[\r\n]+$/.test(s)) out.write(s);
99
+ else out.write("*".repeat(s.length));
100
+ };
101
+ rl.question(q, (a) => {
102
+ rl._writeToOutput = orig;
103
+ if (Array.isArray(rl.history)) rl.history = rl.history.filter((h) => h !== a);
104
+ res(a);
105
+ });
106
+ });
107
+ };
108
+
109
+ // ---------- banner ----------
110
+ banner();
111
+ if (session.messages.length) console.log(C.dim(` Resumed "${session.title || session.id}" (${session.messages.length} messages)\n`));
112
+
113
+ // shift+tab cycles the permission mode while idle; esc interrupts the model (like ctrl+c)
114
+ if (tty) {
115
+ readline.emitKeypressEvents(process.stdin, rl);
116
+ process.stdin.on("keypress", (_s, key) => {
117
+ if (key?.name === "escape") {
118
+ // readline has just put the raw ESC character into the input line; take it out again
119
+ if (rl.line.includes("\x1b")) { const before = rl.line.slice(0, rl.cursor).replace(/\x1b/g, ""); rl.line = rl.line.replace(/\x1b/g, ""); rl.cursor = before.length; }
120
+ if (busy) interrupt(); else rl.prompt(true);
121
+ return;
122
+ }
123
+ if (!busy && key?.name === "tab" && key.shift) {
124
+ perm.mode = MODES[(MODES.indexOf(perm.mode) + 1) % MODES.length];
125
+ readline.clearLine(out, 0); readline.cursorTo(out, 0);
126
+ out.write(C.dim(` mode: ${modeLabel(perm.mode)}\n`));
127
+ rl.prompt(true);
128
+ }
129
+ });
130
+ }
131
+
132
+ // Stops the running turn. Also answers an open approval question with "no" so nothing waits for Enter.
133
+ function interrupt() {
134
+ if (!busy || !controller) return false;
135
+ if (controller.signal.aborted) return true;
136
+ controller.abort();
137
+ status.print(C.yellow(" Interrupting…"));
138
+ cancelQuestion?.();
139
+ return true;
140
+ }
141
+
142
+ rl.on("SIGINT", () => {
143
+ if (busy && controller) {
144
+ // a second ctrl+c while still stopping quits, in case something refuses to stop
145
+ if (controller.signal.aborted && Date.now() - lastSigint < 2000) { out.write(C.red("\n Quitting.\n")); return quit(); }
146
+ lastSigint = Date.now();
147
+ interrupt();
148
+ return;
149
+ }
150
+ if (rl.line) { rl.write(null, { ctrl: true, name: "u" }); return; }
151
+ if (Date.now() - lastSigint < 1500) return quit();
152
+ lastSigint = Date.now();
153
+ out.write(C.dim("\n (press ctrl+c again to quit)\n")); rl.prompt();
154
+ });
155
+ // Piped input (not a terminal): every line is one message, processed in order, then quit at end of input.
156
+ const queue = [];
157
+ let draining = false;
158
+ async function drain() {
159
+ if (draining) return;
160
+ draining = true;
161
+ while (queue.length) {
162
+ try { await handle(queue.shift()); }
163
+ catch (e) { status.stop(); console.log(C.red(` Something went wrong: ${e?.message || e}\n`)); }
164
+ }
165
+ draining = false;
166
+ if (closed) quit();
167
+ }
168
+
169
+ rl.on("close", () => {
170
+ closed = true;
171
+ while (waiters.length) { const w = waiters.shift(); w.res(w.dflt); } // unanswered questions get their default
172
+ if (!busy && !draining) quit();
173
+ });
174
+
175
+ rl.on("line", (line) => {
176
+ if (!tty) {
177
+ if (waiters.length) { waiters.shift().res(line); return; } // a question is waiting for this line
178
+ queue.push(line); drain(); return;
179
+ }
180
+ if (busy) { queueWhileBusy(line); return; }
181
+ // Lines that arrive within a few ms are one pasted message; a trailing "\" continues on the next line.
182
+ pending.push(line);
183
+ clearTimeout(flushTimer);
184
+ if (line.endsWith("\\")) { pending[pending.length - 1] = line.slice(0, -1); rl.setPrompt(C.dim("… ")); rl.prompt(); return; }
185
+ flushTimer = setTimeout(() => { const text = pending.join("\n"); pending = []; rl.setPrompt(promptStr()); runInput(text); }, 25);
186
+ });
187
+
188
+ // Runs one message or command, never leaving you without a prompt, even if something throws.
189
+ async function runInput(text) {
190
+ try { await handle(text); }
191
+ catch (e) { status.stop(); console.log(C.red(` Something went wrong: ${e?.message || e}`) + C.dim("\n Warden is still running; you can keep chatting.\n")); }
192
+ if (closed) return quit();
193
+ afterTurn();
194
+ }
195
+
196
+ // Back to the prompt. Messages typed during the turn that the model never got (it was interrupted, failed, or
197
+ // finished in the same moment) go back on the prompt line to send, edit or clear.
198
+ function afterTurn() {
199
+ if (!tty) return;
200
+ echo(true);
201
+ rl.prevRows = 0; // readline measured the draft against the silent stream; draw on a fresh line
202
+ const left = takeQueued();
203
+ if (left) {
204
+ const draft = left.replace(/\n/g, " ") + (rl.line ? " " + rl.line : "");
205
+ rl.line = draft; rl.cursor = draft.length;
206
+ console.log(C.dim(" Your message was not sent yet; it is on the prompt below. Press enter to send it, or ctrl+c to clear it."));
207
+ }
208
+ rl.prompt(true);
209
+ }
210
+
211
+ // Lines typed while the model works.
212
+ const typed = [];
213
+ function takeQueued() { if (!typed.length) return null; const t = typed.join("\n"); typed.length = 0; return t; }
214
+ function queueWhileBusy(line) {
215
+ const t = line.trim();
216
+ if (!t || questions) return;
217
+ if (t.startsWith("/") || t.startsWith("!")) {
218
+ status.note(C.yellow(` ${t.split(/\s+/)[0]} has to wait until Warden is idle. Press esc to interrupt, or type it again when it is done.`));
219
+ return;
220
+ }
221
+ typed.push(t);
222
+ status.note(` ${C.accent("↳")} ${C.dim("queued; the model gets it at its next step:")} ${t.length > 120 ? t.slice(0, 120) + "…" : t}`);
223
+ }
224
+
225
+ // The status line during a turn: one spinner shared by thinking, writing and running tools. Notes printed while
226
+ // the model is streaming text wait until the text ends, so they never land in the middle of a sentence.
227
+ const status = {
228
+ spin: new Spinner(out, C, { hint: "esc to interrupt", extra: () => (rl.line ? ` · ✎ ${rl.line}` : typed.length ? ` · ${typed.length} queued` : "") }),
229
+ streaming: false, later: [],
230
+ start(label) { this.spin.stop(); this.spin.start(label); },
231
+ stop() { this.spin.stop(); },
232
+ print(line) { if (this.streaming) this.later.push(line); else this.spin.print(line); },
233
+ note(line) { this.print(line); },
234
+ flush() { const l = this.later; this.later = []; for (const x of l) this.spin.print(x); },
235
+ };
236
+
237
+ // First run (no usable key for the current model): walk the person through getting one, then start.
238
+ (async () => {
239
+ if (needsSetup()) await firstRun();
240
+ if (initialPrompt) { queue.push(initialPrompt); await drain(); }
241
+ if (tty && !closed) rl.prompt();
242
+ })();
243
+
244
+ function needsSetup() {
245
+ try { return /missing/.test(keyStatus(parseModelSpec(session.model).provider, cfg)); } catch { return false; }
246
+ }
247
+
248
+ async function firstRun() {
249
+ console.log(` ${C.bold("Welcome to Warden.")} It needs one AI model to work. The easiest free one is ${C.bold("Google Gemini")}:`);
250
+ console.log(` 1. Open ${C.accent("https://aistudio.google.com/apikey")} and sign in with a Google account`);
251
+ console.log(` 2. Click ${C.bold("Create API key")} and copy it`);
252
+ console.log(` 3. Pick ${C.bold("1")} below and paste the key`);
253
+ console.log(C.dim(` Other free sources are listed too. Press enter to skip; /add starts this again any time. Stuck? Run: warden doctor`));
254
+ await addWizard();
255
+ }
256
+
257
+ // ---------- handlers ----------
258
+ async function handle(raw) {
259
+ const text = raw.trim();
260
+ if (!text) return;
261
+ if (!tty) console.log(`${C.accent("›")} ${text}`);
262
+ if (text.startsWith("/")) return command(text);
263
+ if (text.startsWith("!")) return shellPassthrough(text.slice(1).trim());
264
+ await turn(text);
265
+ }
266
+
267
+ async function turn(text) {
268
+ busy = true; controller = new AbortController();
269
+ echo(false);
270
+ const md = new MarkdownStream(out, C);
271
+ const t0 = Date.now(), before = { ...session.usage };
272
+ const modelName = findModel(cfg, session.model)?.name || session.model;
273
+ let reasoning = 0, writing = null, toolOut = "";
274
+ console.log();
275
+ // what the status line says while the model works
276
+ const thinkingLabel = () => {
277
+ if (writing) return `Writing ${writing.what} (${fmtChars(writing.chars)})`;
278
+ if (reasoning) return `Thinking (${fmtChars(reasoning)} of reasoning)`;
279
+ return status.spin.elapsed() > 20_000 ? `Waiting for ${modelName} (no reply yet)` : "Thinking";
280
+ };
281
+ const endText = () => { if (status.streaming) { status.streaming = false; if (md.end()) out.write("\n"); status.flush(); } };
282
+ const ui = {
283
+ onAssistantStart: () => { reasoning = 0; writing = null; status.start(thinkingLabel); },
284
+ onReasoning: (d) => { reasoning += d.length; },
285
+ onToolDelta: (name, args) => {
286
+ if (status.streaming) { endText(); status.start(thinkingLabel); }
287
+ const file = /"path"\s*:\s*"([^"]{1,120})"/.exec(args || "")?.[1];
288
+ writing = { what: file ? file.replace(/\\\\/g, "\\") : name || "a tool call", chars: (args || "").length }; // JSON doubles backslashes in Windows paths
289
+ },
290
+ onText: (d) => { if (!status.streaming) { status.stop(); status.streaming = true; } md.write(d); },
291
+ onAssistantEnd: () => { status.stop(); endText(); },
292
+ onRetry: ({ status: st, waitMs, attempt }) => status.spin.setLabel(st === "no response" ? `${modelName} did not respond; trying again` : `Rate limited (${st}), retrying in ${Math.round(waitMs / 1000)}s, attempt ${attempt}`),
293
+ onNotice: (m) => status.print(C.dim(` ${m}\n`)),
294
+ takeQueued: () => (tty ? takeQueued() : null),
295
+ onQueuedDelivered: (t) => { endText(); status.stop(); console.log(`${C.accent("›")} ${t} ${C.gray("(sent while Warden was working)")}\n`); },
296
+ onToolStart: (call, tool) => {
297
+ status.stop(); call._shown = false; toolOut = "";
298
+ status.start(() => `${defaultTitle(tool, call.args).slice(0, 70)}${toolOut ? " · " + toolOut : ""}`);
299
+ },
300
+ onToolApproved: (call, tool) => { status.start(() => `Running ${defaultTitle(tool, call.args).slice(0, 60)}${toolOut ? " · " + toolOut : ""}`); },
301
+ onToolOutput: (call, s) => { const last = stripAnsi(s).split(/\r?\n|\r/).map((l) => l.trim()).filter(Boolean).pop(); if (last) toolOut = last.slice(0, 80); },
302
+ confirm: async (call, tool, desc) => {
303
+ status.stop();
304
+ showTool(call, tool, null, "run"); call._shown = true;
305
+ const kind = tool.kind === "bash" ? "Run this command" : tool.kind === "edit" ? "Allow this change" : "Allow reading outside the project";
306
+ if (tool.kind === "edit" && call.args?.old_string !== undefined) previewEdit(call.args);
307
+ for (;;) {
308
+ const a = (await answer(` ${C.yellow("?")} ${kind}? ${C.dim(`[y] yes [a] always allow ${tool.name} this session [n] no, or type what to do instead`)}\n ${C.accent("›")} `)).trim();
309
+ if (controller.signal.aborted) return "no";
310
+ if (/^(y|yes)$/i.test(a)) return "yes";
311
+ if (/^(a|always)$/i.test(a)) return "always";
312
+ if (/^(n|no)$/i.test(a)) return "no";
313
+ if (a) return { reason: a };
314
+ }
315
+ },
316
+ onToolEnd: (call, tool, res) => {
317
+ status.stop();
318
+ const state = res?.denied ? "deny" : res?.error ? "err" : res?.isError ? "err" : "ok";
319
+ showTool(call, tool, res, state, call._shown);
320
+ console.log();
321
+ },
322
+ };
323
+ try {
324
+ const r = await runTurn({ session, userText: text, cfg, ui, perm, signal: controller.signal, cwd });
325
+ status.stop(); endText();
326
+ if (r.interrupted) console.log(C.yellow(" Interrupted.") + C.dim(" The conversation is kept; say what to do next.\n"));
327
+ } catch (e) {
328
+ status.stop(); endText();
329
+ console.log(C.red(` Error: ${e.message}`));
330
+ if (e.timeout) console.log(C.dim(" Nothing was lost: your message and everything so far are still in the conversation. Send it again or say \"continue\"."));
331
+ else if (/API key|no API key/i.test(e.message)) console.log(C.dim(` Set the key as an environment variable, or pick another model with /model. Providers: /model`));
332
+ else if (/^4(01|03)/.test(e.message)) console.log(C.dim(" The provider rejected the key or the request. Check the key and the model name (/models <provider>)."));
333
+ else if (/^404/.test(e.message)) console.log(C.dim(" Model not found. See what this provider offers with /models <provider>."));
334
+ else if (/^429/.test(e.message)) console.log(C.dim(" This model's rate limit or free quota is used up. Switch with /model (another model usually has its own quota), or /add a free one."));
335
+ else if (/^413|too large|context length|maximum context|too many tokens/i.test(e.message)) console.log(C.dim(" The conversation got too long for this model. Start a fresh one with /clear (your files are unchanged), or pick a model with a bigger context."));
336
+ console.log();
337
+ } finally {
338
+ status.stop(); status.streaming = false; status.later = [];
339
+ busy = false; controller = null;
340
+ echo(true); rl.prevRows = 0; // whatever started this turn (typed, `warden "task"`, /init), typing is visible again
341
+ const u = session.usage;
342
+ const tin = u.input - before.input, tout = u.output - before.output;
343
+ console.log(C.gray(` ${session.model} · ${tin || tout ? `${fmtTokens(tin)} in / ${fmtTokens(tout)} out · ` : ""}${((Date.now() - t0) / 1000).toFixed(1)}s · ${modeLabel(perm.mode)}`));
344
+ console.log();
345
+ }
346
+ }
347
+
348
+ function showTool(call, tool, res, state, alreadyShownHeader = false) {
349
+ const title = res?.display?.title || (tool ? defaultTitle(tool, call.args) : `Unknown tool ${call.name}`);
350
+ if (!alreadyShownHeader || res) {
351
+ if (alreadyShownHeader && res) { /* header printed at confirm time; print result only */ }
352
+ else console.log(toolHeader(C, title, state));
353
+ }
354
+ if (res) for (const l of toolBody(C, res.display, res)) console.log(l);
355
+ }
356
+
357
+ function previewEdit(a) {
358
+ const lines = [...String(a.old_string).split("\n").map((s) => C.bgRed(C.red(` - ${s}`))), ...String(a.new_string ?? "").split("\n").map((s) => C.bgGreen(C.green(` + ${s}`)))];
359
+ for (const l of lines.slice(0, 40)) console.log(" " + l);
360
+ if (lines.length > 40) console.log(C.gray(` … ${lines.length - 40} more lines`));
361
+ }
362
+
363
+ async function shellPassthrough(cmd) {
364
+ if (!cmd) return;
365
+ const sh = detectShell();
366
+ console.log(C.dim(` $ ${cmd}`));
367
+ const r = await new Promise((res) => {
368
+ const p = spawn(sh.cmd, sh.args(cmd), { cwd, windowsHide: true });
369
+ let o = ""; p.stdout.on("data", (d) => { o += d; out.write(C.gray(String(d))); }); p.stderr.on("data", (d) => { o += d; out.write(C.gray(String(d))); });
370
+ p.on("close", (code) => res({ code, o })); p.on("error", (e) => res({ code: -1, o: e.message }));
371
+ });
372
+ console.log(C.dim(` [exit ${r.code}]\n`));
373
+ // the model sees what you ran, like a shared terminal
374
+ session.push({ role: "user", content: `I ran this shell command myself:\n$ ${cmd}\n[exit ${r.code}]\n${r.o.slice(-8000)}\n(No reply needed unless I ask.)` });
375
+ session.push({ role: "assistant", content: "Noted." });
376
+ }
377
+
378
+ async function command(text) {
379
+ const [cmd, ...rest] = text.split(/\s+/);
380
+ const arg = rest.join(" ").trim();
381
+ switch (cmd) {
382
+ case "/help": case "/?":
383
+ console.log();
384
+ for (const [k, v] of Object.entries(COMMANDS)) console.log(` ${C.accent(k.padEnd(12))} ${C.dim(v)}`);
385
+ console.log(` ${C.accent("!cmd".padEnd(12))} ${C.dim("run a shell command yourself; the model sees the output")}`);
386
+ console.log(C.dim(`\n While the model works: keep typing and press enter to queue a message (it gets it at its next step) · esc or ctrl+c interrupts`));
387
+ console.log(C.dim(` Keys: ctrl+c twice at an empty prompt quits · shift+tab cycles the mode · end a line with \\ for multi-line\n Settings: ${CONFIG_FILE}\n`));
388
+ break;
389
+ case "/jobs": {
390
+ const jobs = listJobs();
391
+ const [sub, id] = arg.split(/\s+/);
392
+ if (sub === "stop") {
393
+ const targets = id === "all" || !id ? jobs.filter(jobRunning) : jobs.filter((j) => String(j.id) === id);
394
+ if (!targets.length) { console.log(C.dim(` ${id && id !== "all" ? `No job ${id}.` : "Nothing running."}\n`)); break; }
395
+ for (const j of targets) { stopJob(j); console.log(C.dim(` Stopped job ${j.id}: ${j.command}`)); }
396
+ console.log(); break;
397
+ }
398
+ if (!jobs.length) { console.log(C.dim(" No background jobs. The model starts one when it runs a server or watcher.\n")); break; }
399
+ console.log();
400
+ for (const j of jobs) console.log(` ${jobRunning(j) ? C.mint("●") : C.gray("○")} ${describeJob(j)}`);
401
+ console.log(C.dim("\n /jobs stop <id> or /jobs stop all. Warden stops them all when it exits.\n"));
402
+ break;
403
+ }
404
+ case "/exit": case "/quit": closed = true; break;
405
+ case "/clear":
406
+ session = new Session({ cwd, model: session.model }); perm.allowed.clear();
407
+ console.log(C.dim(" New conversation.\n")); break;
408
+ case "/usage": case "/cost": {
409
+ const u = session.usage;
410
+ console.log(C.dim(` ${u.calls} model calls · ${fmtTokens(u.input)} input / ${fmtTokens(u.output)} output tokens (as reported by the provider; free tiers cost nothing)\n`)); break;
411
+ }
412
+ case "/mode":
413
+ if (!arg) { console.log(C.dim(` mode: ${modeLabel(perm.mode)}. Options: ${MODES.join(", ")}\n`)); break; }
414
+ if (!MODES.includes(arg)) { console.log(C.red(` unknown mode "${arg}". Options: ${MODES.join(", ")}\n`)); break; }
415
+ perm.mode = arg; saveAgentConfig({ mode: arg });
416
+ console.log(C.dim(` mode: ${modeLabel(arg)}${arg === "yolo" ? C.yellow(" (edits and shell commands run without asking)") : ""}\n`)); break;
417
+ case "/model": {
418
+ if (!arg) {
419
+ const list = chatModels(cfg);
420
+ console.log(`\n current: ${C.bold(session.model)}${findModel(cfg, session.model) ? C.gray(` (${findModel(cfg, session.model).name})`) : ""}\n`);
421
+ if (!list.length) { console.log(C.dim(" No saved models yet. /add connects a source and picks a model.\n")); break; }
422
+ list.forEach((m, i) => console.log(` ${C.accent(String(i + 1).padStart(2))} ${(m.spec === session.model ? C.mint("● ") : " ") + m.name.padEnd(32)} ${C.gray(m.spec)}${toolTag(m.tools)}`));
423
+ const pick = (await answer(`\n Number to switch to (enter to keep the current one) ${C.accent("›")} `, "")).trim();
424
+ if (!pick) { console.log(); break; }
425
+ const m = /^\d+$/.test(pick) ? list[Number(pick) - 1] : list.find((x) => x.name === pick || x.spec === pick);
426
+ if (!m) { console.log(C.red(" no such model\n")); break; }
427
+ switchModel(m.spec);
428
+ break;
429
+ }
430
+ try { switchModel(resolveModelInput(cfg, arg)); } catch (e) { console.log(C.red(` ${e.message}\n`)); }
431
+ break;
432
+ }
433
+ case "/models": {
434
+ const words = arg.split(/\s+/).filter(Boolean);
435
+ const onlyFree = words.includes("--free");
436
+ const rest = words.filter((w) => w !== "--free");
437
+ const name = rest[0] || parseModelSpec(session.model).provider;
438
+ const query = rest.slice(1).join(" ");
439
+ const spin = new Spinner(out, C); spin.start(`Asking ${name} for its models`);
440
+ try {
441
+ let list = await listModels(name, cfg); spin.stop();
442
+ if (onlyFree) list = list.filter((m) => m.free);
443
+ if (query) list = list.filter((m) => m.id.toLowerCase().includes(query.toLowerCase()));
444
+ console.log(`\n ${C.bold(name)}: ${list.length} model${list.length === 1 ? "" : "s"}${onlyFree ? " (free)" : ""}${query ? ` matching "${query}"` : ""}${list.length > 80 ? ", first 80 shown" : ""}`);
445
+ for (const m of list.slice(0, 80)) console.log(` ${name}/${m.id}${modelFlags(m)}`);
446
+ console.log(C.dim(`\n Use one: /model ${name}/<id> · save it with a short name: /add\n`));
447
+ } catch (e) { spin.stop(); console.log(C.red(` ${e.message}\n`)); }
448
+ break;
449
+ }
450
+ case "/add": await addWizard(); break;
451
+ case "/image": await imageCommand(arg); break;
452
+ case "/image-model": await imageModelCommand(arg); break;
453
+ case "/providers": {
454
+ console.log();
455
+ for (const name of [...ADD_ORDER, ...Object.keys(cfg.providers || {}).filter((n) => !CATALOG[n])]) {
456
+ let st; try { st = keyStatus(name, cfg); } catch (e) { st = e.message; }
457
+ const ok = !/missing/.test(st);
458
+ const n = savedModels(cfg).filter((m) => m.spec.startsWith(name + "/")).length;
459
+ const p = CATALOG[name] || cfg.providers[name];
460
+ console.log(` ${ok ? C.mint("●") : C.gray("○")} ${(p?.label || name).padEnd(14)} ${C.dim(st.padEnd(28))}${n ? C.accent(` ${n} saved model${n > 1 ? "s" : ""}`) : ""}${p?.blurb ? C.gray(" · " + p.blurb) : ""}`);
461
+ }
462
+ console.log(C.dim("\n /add connects one · /remove <source> forgets its saved key\n"));
463
+ break;
464
+ }
465
+ case "/remove": {
466
+ if (!arg) { console.log(C.dim(" usage: /remove <model name> or /remove <source> (e.g. /remove openrouter) to forget its saved key\n")); break; }
467
+ if (removeModel(cfg, arg)) { console.log(C.dim(` Removed model "${arg}".\n`)); break; }
468
+ const prov = Object.keys({ ...CATALOG, ...(cfg.providers || {}) }).find((n) => n === arg.toLowerCase());
469
+ if (!prov) { console.log(C.red(` "${arg}" is neither a saved model nor a source. /model and /providers list them.\n`)); break; }
470
+ const sure = (await answer(` Forget the saved ${prov} key and remove its saved models? [y/N] `, "n")).trim();
471
+ if (!/^y/i.test(sure)) { console.log(C.dim(" Kept.\n")); break; }
472
+ const hadKey = removeKey(prov), n = removeModelsOf(cfg, prov);
473
+ if (cfg.providers?.[prov]) { delete cfg.providers[prov]; saveAgentConfig({ providers: cfg.providers }); }
474
+ console.log(C.dim(` ${hadKey ? "Saved key deleted" : "No saved key (environment variables are not touched)"}; ${n} model${n === 1 ? "" : "s"} removed.\n`));
475
+ break;
476
+ }
477
+ case "/resume": case "/sessions": {
478
+ const list = Session.list(15);
479
+ if (!list.length) { console.log(C.dim(" No saved conversations yet.\n")); break; }
480
+ let pick = arg;
481
+ if (!pick) {
482
+ console.log();
483
+ list.forEach((s, i) => console.log(` ${C.accent(String(i + 1).padStart(2))} ${(s.title || "").slice(0, 60).padEnd(60)} ${C.gray(new Date(s.mtime).toLocaleString())}${s.cwd !== cwd ? C.gray(" (other folder)") : ""}`));
484
+ pick = (await answer(`\n Number to resume (enter to cancel) ${C.accent("›")} `)).trim();
485
+ if (!pick) break;
486
+ if (/^\d+$/.test(pick)) pick = list[Number(pick) - 1]?.id;
487
+ }
488
+ try {
489
+ session = Session.load(pick); perm.allowed.clear();
490
+ console.log(C.dim(` Resumed "${session.title}" (${session.messages.length} messages, model ${session.model}).\n`));
491
+ replayTail();
492
+ } catch (e) { console.log(C.red(` ${e.message}\n`)); }
493
+ break;
494
+ }
495
+ case "/init":
496
+ await turn("Explore this project (structure, languages, how to build, test and run it, conventions you notice) and write a concise WARDEN.md at the project root with notes that would help a coding agent work here. Keep it under 80 lines. If WARDEN.md exists, improve it instead of replacing useful content.");
497
+ break;
498
+ default:
499
+ console.log(C.red(` unknown command ${cmd}. /help lists commands.\n`));
500
+ }
501
+ }
502
+
503
+ function switchModel(spec) {
504
+ const im = findModel(cfg, spec);
505
+ if (im?.kind === "image") { console.log(C.red(` ${im.name} is an image model; it cannot chat or code. Use it with /image-model.\n`)); return; }
506
+ const { provider } = parseModelSpec(spec);
507
+ resolveProvider(provider, cfg);
508
+ session.model = spec;
509
+ const recent = [spec, ...(cfg.recentModels || []).filter((m) => m !== spec)].slice(0, 8);
510
+ cfg.recentModels = recent; cfg.model = spec;
511
+ saveAgentConfig({ model: spec, recentModels: recent });
512
+ let st = ""; try { st = keyStatus(provider, cfg); } catch {}
513
+ const m = findModel(cfg, spec);
514
+ console.log(C.dim(` model: ${m ? m.name + " = " : ""}${spec} (${st})${m?.tools === "none" ? C.yellow(" · chat only, it cannot read or edit files") : m?.tools === "text" ? " · text tool format" : ""}. Saved as your default.\n`));
515
+ }
516
+
517
+ // /add: pick a source, give it a key, pick a model, test it, save it under a short name.
518
+ async function addWizard() {
519
+ const names = [...ADD_ORDER];
520
+ console.log(`\n ${C.bold("Where do you want models from?")}\n`);
521
+ names.forEach((n, i) => {
522
+ const p = CATALOG[n];
523
+ let st = ""; try { st = keyStatus(n, cfg); } catch {}
524
+ const ok = !/missing/.test(st);
525
+ console.log(` ${C.accent(String(i + 1).padStart(2))} ${(ok ? C.mint("● ") : C.gray("○ ")) + p.label.padEnd(14)} ${C.gray(p.blurb)}`);
526
+ });
527
+ console.log(` ${C.accent(" c")} ${C.gray("○ ")}${"Custom".padEnd(14)} ${C.gray("any OpenAI-compatible server (URL)")}`);
528
+ const pick = (await answer(`\n Number (enter to cancel) ${C.accent("›")} `, "")).trim().toLowerCase();
529
+ if (!pick) return console.log();
530
+ let name;
531
+ if (pick === "c") {
532
+ name = (await answer(` Short name for this source (letters/numbers, e.g. together) ${C.accent("›")} `, "")).trim().toLowerCase().replace(/[^a-z0-9-]/g, "");
533
+ if (!name || CATALOG[name]) return console.log(C.red(` ${name ? `"${name}" is a built-in source; pick it from the list` : "cancelled"}\n`));
534
+ const url = (await answer(` Base URL (the part before /chat/completions, e.g. https://api.together.xyz/v1) ${C.accent("›")} `, "")).trim().replace(/\/+$/, "");
535
+ if (!/^https?:\/\//.test(url)) return console.log(C.red(" That does not look like a URL. Cancelled.\n"));
536
+ cfg.providers = { ...(cfg.providers || {}), [name]: { label: name, api: "openai", baseUrl: url, keyEnv: [] } };
537
+ saveAgentConfig({ providers: cfg.providers });
538
+ } else {
539
+ name = names[Number(pick) - 1];
540
+ if (!name) return console.log(C.red(" No such number.\n"));
541
+ }
542
+ const p = resolveProvider(name, cfg);
543
+
544
+ // key
545
+ let st = ""; try { st = keyStatus(name, cfg); } catch {}
546
+ const needsKey = !!p.keyEnv?.length || pick === "c";
547
+ if (needsKey) {
548
+ const has = /key from|saved/.test(st);
549
+ if (p.keyUrl) console.log(C.dim(` Get a key at ${p.keyUrl}`));
550
+ const k = (await askSecret(` ${has ? `Key found (${st}). Paste a new one or press enter to keep it` : `Paste your ${p.label || name} key${pick === "c" ? " (enter if it needs none)" : ""}`}: `)).trim();
551
+ if (k) { saveKey(name, k); console.log(C.dim(` Saved ${mask(k)} to ${CREDENTIALS_FILE}`)); }
552
+ else if (!has && pick !== "c") return console.log(C.red(" No key, cancelled.\n"));
553
+ } else console.log(C.dim(` ${p.label} runs on your PC; make sure it is running and has a model downloaded.`));
554
+
555
+ // model
556
+ const spin = new Spinner(out, C); spin.start(`Asking ${p.label || name} for its models`);
557
+ let list = [];
558
+ try { list = await listModels(name, cfg); spin.stop(); } catch (e) { spin.stop(); console.log(C.yellow(` Could not list models (${e.message}). You can still type a model id.`)); }
559
+ let id;
560
+ if (list.length) {
561
+ const free = list.filter((m) => m.free);
562
+ console.log(C.dim(` ${list.length} models${free.length ? `, ${free.length} free` : ""}.`));
563
+ const q = (await answer(` Search (enter for ${free.length ? "free ones" : "all"}, "all" for everything) ${C.accent("›")} `, "")).trim().toLowerCase();
564
+ let shown = q === "all" ? list : q ? list.filter((m) => m.id.toLowerCase().includes(q)) : free.length ? free : list;
565
+ shown = [...shown].sort((a, b) => (!!a.image - !!b.image) || (b.free === true) - (a.free === true) || (b.tools === true) - (a.tools === true) || a.id.localeCompare(b.id));
566
+ if (!shown.length) console.log(C.yellow(" Nothing matched."));
567
+ if (shown.length && shown.every((m) => m.image)) console.log(C.dim(" These are image models: they make pictures with /image (your coding model stays as it is)."));
568
+ shown.slice(0, 30).forEach((m, i) => console.log(` ${C.accent(String(i + 1).padStart(2))} ${m.id}${modelFlags(m)}`));
569
+ if (shown.length > 30) console.log(C.gray(` … ${shown.length - 30} more; search to narrow down`));
570
+ const sel = (await answer(` Number, or type a model id ${C.accent("›")} `, "")).trim();
571
+ if (!sel) return console.log(C.dim(" Cancelled.\n"));
572
+ id = /^\d+$/.test(sel) ? shown[Number(sel) - 1]?.id : sel;
573
+ if (!id) return console.log(C.red(" No such number.\n"));
574
+ } else {
575
+ id = (await answer(` Model id ${C.accent("›")} `, "")).trim();
576
+ if (!id) return console.log(C.dim(" Cancelled.\n"));
577
+ }
578
+ const spec = `${name}/${id}`;
579
+ const meta = list.find((m) => m.id === id) || {};
580
+ if (meta.image ?? looksLikeImageModel(id)) return addImageModel(name, id, spec);
581
+
582
+ // test it once: proves the key and model work, and finds out how it can use tools
583
+ const spin2 = new Spinner(out, C); spin2.start(`Testing ${spec}`);
584
+ let tools = null;
585
+ try {
586
+ const r = await probeToolSupport(spec, cfg, { onRetry: ({ status, waitMs }) => spin2.setLabel(`Rate limited (${status}), retrying in ${Math.round(waitMs / 1000)}s`) });
587
+ spin2.stop(); tools = r.mode;
588
+ console.log(` ${r.mode === "none" ? C.yellow("!") : C.mint("✓")} Works. ${r.detail}.`);
589
+ } catch (e) {
590
+ spin2.stop();
591
+ console.log(C.red(` Test failed: ${e.message}`));
592
+ const keep = (await answer(` Save it anyway? [y/N] `, "n")).trim();
593
+ if (!/^y/i.test(keep)) return console.log(C.dim(" Not saved.\n"));
594
+ }
595
+ let short = suggestName(id);
596
+ const typed = (await answer(` Name it (enter for "${short}") ${C.accent("›")} `, "")).trim();
597
+ if (typed) short = typed.replace(/\s+/g, "-");
598
+ addModel(cfg, { name: short, spec, ctx: meta.ctx || null, tools });
599
+ console.log(C.mint(` ✓ Added ${short}.`));
600
+ switchModel(spec);
601
+ }
602
+
603
+ // /add picked an image model: save it as the image model (the coding model stays), optionally test it.
604
+ async function addImageModel(name, id, spec) {
605
+ console.log(` ${C.accent("🖼")} ${C.bold(id)} is an ${C.bold("image model")}: it makes pictures with /image and cannot chat or write code.`);
606
+ console.log(C.dim(` Your coding model stays ${findModel(cfg, session.model)?.name || session.model}.`));
607
+ if (name === "gemini") console.log(C.yellow(" Note: Google's image models need billing turned on; a free Gemini key cannot make images."));
608
+ const t = (await answer(` Test it by making one small image now? (uses one image from its quota) [Y/n] `, "y")).trim();
609
+ if (!/^n/i.test(t)) {
610
+ const spin = new Spinner(out, C); spin.start(`Making a test image with ${spec}`);
611
+ try {
612
+ const img = await generateImage({ spec, prompt: "a simple red circle on a plain white background", cfg, onRetry: ({ status: st, waitMs }) => spin.setLabel(`Rate limited (${st}), retrying in ${Math.round(waitMs / 1000)}s`) });
613
+ spin.stop(); console.log(` ${C.mint("✓")} Works. It sent a ${img.ext.toUpperCase()} image (${fmtBytes(img.bytes.length)}).`);
614
+ } catch (e) {
615
+ spin.stop(); console.log(C.red(` Test failed: ${e.message}`));
616
+ const keep = (await answer(` Save it anyway? [y/N] `, "n")).trim();
617
+ if (!/^y/i.test(keep)) return console.log(C.dim(" Not saved.\n"));
618
+ }
619
+ }
620
+ let short = suggestName(id);
621
+ const typed = (await answer(` Name it (enter for "${short}") ${C.accent("›")} `, "")).trim();
622
+ if (typed) short = typed.replace(/\s+/g, "-");
623
+ addModel(cfg, { name: short, spec, kind: "image" });
624
+ setImageModel(cfg, spec);
625
+ console.log(C.mint(` ✓ Added ${short} as your image model.`) + C.dim(` Try: /image a black sport bike on a wet road at night --wide\n`));
626
+ }
627
+
628
+ // /image-model: show the image models, switch to one by number or name.
629
+ async function imageModelCommand(arg) {
630
+ const list = imageModels(cfg);
631
+ const cur = currentImageModel(cfg);
632
+ if (arg) {
633
+ const m = list.find((x) => x.name === arg || x.spec === arg) || (arg.includes("/") ? { name: null, spec: arg } : null);
634
+ if (!m) return console.log(C.red(` No saved image model called "${arg}". /image-model lists them; /add adds one.\n`));
635
+ setImageModel(cfg, m.spec);
636
+ return console.log(C.dim(` image model: ${m.name ? m.name + " = " : ""}${m.spec}. Saved.\n`));
637
+ }
638
+ console.log(`\n image model: ${cur ? C.bold(cur.name || cur.spec) + C.gray(cur.name ? ` (${cur.spec})` : "") : C.gray("none yet")}\n`);
639
+ if (!list.length) return console.log(C.dim(" No image models saved. Add one with /add (on OpenRouter, search \"image\" or \"recraft\"; free ones end in :free).\n"));
640
+ list.forEach((m, i) => console.log(` ${C.accent(String(i + 1).padStart(2))} ${(m.spec === cur?.spec ? C.mint("● ") : " ") + m.name.padEnd(32)} ${C.gray(m.spec)}`));
641
+ const pick = (await answer(`\n Number to use (enter to keep the current one) ${C.accent("›")} `, "")).trim();
642
+ if (!pick) return console.log();
643
+ const m = /^\d+$/.test(pick) ? list[Number(pick) - 1] : list.find((x) => x.name === pick);
644
+ if (!m) return console.log(C.red(" no such image model\n"));
645
+ setImageModel(cfg, m.spec);
646
+ console.log(C.dim(` image model: ${m.name} = ${m.spec}. Saved.\n`));
647
+ }
648
+
649
+ // /image <description> [--wide|--tall|--square]: makes one picture and saves it in images/. Esc cancels.
650
+ async function imageCommand(arg) {
651
+ const words = arg.split(/\s+/).filter(Boolean);
652
+ const isFlag = (w) => /^--(wide|tall|square)$/.test(w);
653
+ const flag = words.filter(isFlag).pop();
654
+ const prompt = words.filter((w) => !isFlag(w)).join(" ").trim();
655
+ if (!prompt) return console.log(C.dim(" usage: /image <what to draw> [--wide | --tall | --square]\n e.g. /image a black sport bike on a wet road at night, red light --wide\n"));
656
+ const cur = currentImageModel(cfg);
657
+ if (!cur) return console.log(C.yellow(" No image model yet.") + C.dim(" Add one with /add: pick OpenRouter, search \"image\" or \"recraft\" (free ones end in :free).\n"));
658
+ const aspect = ASPECTS[flag ? flag.slice(2) : "square"];
659
+ busy = true; controller = new AbortController();
660
+ echo(false);
661
+ status.start(`Drawing with ${cur.name || cur.spec} (${aspect})`);
662
+ try {
663
+ const img = await generateImage({ spec: cur.spec, prompt, aspect, cfg, signal: controller.signal, onRetry: ({ status: st, waitMs }) => status.spin.setLabel(`Rate limited (${st}), retrying in ${Math.round(waitMs / 1000)}s`) });
664
+ status.stop();
665
+ const rel = saveImage(cwd, prompt, img);
666
+ console.log(` ${C.mint("✓")} Saved ${C.bold(rel)} ${C.gray(`(${img.ext.toUpperCase()}, ${fmtBytes(img.bytes.length)}, ${aspect})`)}`);
667
+ console.log(C.dim(` To use it, tell the model, e.g. "use ${rel} as the hero image".\n`));
668
+ // the coding model learns the file exists, like a shared terminal
669
+ session.push({ role: "user", content: `I made an image with /image and saved it as ${rel} (${img.ext}, ${aspect}). Description: ${prompt}\n(No reply needed unless I ask.)` });
670
+ session.push({ role: "assistant", content: "Noted." });
671
+ } catch (e) {
672
+ status.stop();
673
+ if (controller.signal.aborted) console.log(C.yellow(" Cancelled.") + C.dim(" No image was saved.\n"));
674
+ else console.log(C.red(` ${e.message}\n`));
675
+ } finally {
676
+ busy = false; controller = null;
677
+ echo(true); rl.prevRows = 0;
678
+ }
679
+ }
680
+
681
+ function replayTail() {
682
+ const tail = session.messages.filter((m) => (m.role === "user" || (m.role === "assistant" && m.content))).slice(-4);
683
+ for (const m of tail) console.log(m.role === "user" ? `${C.accent("›")} ${m.content.slice(0, 300)}` : C.dim(` ${m.content.slice(0, 400)}`));
684
+ console.log();
685
+ }
686
+
687
+ function banner() {
688
+ let st = ""; try { st = keyStatus(parseModelSpec(session.model).provider, cfg); } catch (e) { st = e.message; }
689
+ console.log();
690
+ console.log(` ${C.mint("◉")} ${C.bold("Warden")} ${C.gray("v" + VERSION)}`);
691
+ console.log(` ${C.gray("model")} ${session.model} ${/missing/.test(st) ? C.red(`(${st})`) : C.gray(`(${st})`)}`);
692
+ console.log(` ${C.gray("mode ")} ${modeLabel(perm.mode)} ${C.gray("(shift+tab or /mode)")}`);
693
+ const im = currentImageModel(cfg);
694
+ if (im) console.log(` ${C.gray("image")} ${im.name || im.spec} ${C.gray("(/image to draw, /image-model to switch)")}`);
695
+ console.log(` ${C.gray("dir ")} ${cwd}`);
696
+ console.log(C.gray(` /help for commands · /model to switch models · esc interrupts · type while it works to queue a message`));
697
+ const upd = updateNotice(cfg);
698
+ if (upd) console.log(C.yellow(` Warden ${upd} is available (you have ${VERSION}). Run: warden update`));
699
+ console.log();
700
+ }
701
+
702
+ function quit() {
703
+ session.save();
704
+ try { rl.close(); } catch {}
705
+ out.write(C.dim(`\n Saved conversation ${session.id}. Resume with: warden --resume ${session.id.slice(0, 12)}\n`));
706
+ process.exit(0);
707
+ }
708
+ }
709
+
710
+ function latestFor(cwd) {
711
+ const s = Session.list(200).find((x) => x.cwd === cwd);
712
+ if (!s) throw new Error("no earlier conversation in this folder");
713
+ return Session.load(s.id);
714
+ }
715
+
716
+ const fmtChars = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k chars` : `${n} chars`);
717
+ const toolTag = (t) => (t === "none" ? C.yellow(" chat only") : t === "text" ? C.gray(" text tools") : "");
718
+ const fmtCtx = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(n % 1e6 ? 1 : 0)}M` : `${Math.round(n / 1000)}k`);
719
+ const modelFlags = (m) => {
720
+ const f = [];
721
+ if (m.free) f.push(C.mint("free"));
722
+ if (m.tools === true) f.push(C.gray("tools"));
723
+ if (m.tools === false) f.push(C.yellow("no tools"));
724
+ if (m.ctx) f.push(C.gray(fmtCtx(m.ctx) + " ctx"));
725
+ return f.length ? " " + f.join(C.gray(" · ")) : "";
726
+ };
727
+ const modeLabel = (m) => (m === "yolo" ? C.red("yolo") : m === "auto-edit" ? C.yellow("auto-edit") : C.mint("ask"));
728
+ const TITLES = { read_file: "Read", write_file: "Write", edit_file: "Edit", list_dir: "List", glob: "Glob", grep: "Grep" };
729
+ const defaultTitle = (tool, a = {}) => tool.name === "bash" ? `Bash ${a.command}` : `${TITLES[tool.name] || tool.name} ${a.path || a.pattern || ""}`.trim();