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