chainlesschain 0.37.8 → 0.37.9

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.
@@ -0,0 +1,782 @@
1
+ /**
2
+ * Agentic REPL - Claude Code / Codex style
3
+ *
4
+ * User speaks naturally → AI understands intent → picks tools → executes → shows result
5
+ *
6
+ * Built-in tools:
7
+ * - read_file: Read a file
8
+ * - write_file: Write/create a file
9
+ * - edit_file: Edit part of a file
10
+ * - run_shell: Execute a shell command
11
+ * - search_files: Search for files by name/content
12
+ * - list_dir: List directory contents
13
+ * - db_query: Query the ChainlessChain database
14
+ * - note_add: Add a note
15
+ * - note_search: Search notes
16
+ *
17
+ * The AI decides which tools to call based on user intent.
18
+ */
19
+
20
+ import readline from "readline";
21
+ import chalk from "chalk";
22
+ import fs from "fs";
23
+ import path from "path";
24
+ import { execSync } from "child_process";
25
+ import { fileURLToPath } from "url";
26
+ import { logger } from "../lib/logger.js";
27
+
28
+ /**
29
+ * Tool definitions for function calling
30
+ */
31
+ const TOOLS = [
32
+ {
33
+ type: "function",
34
+ function: {
35
+ name: "read_file",
36
+ description: "Read a file's content",
37
+ parameters: {
38
+ type: "object",
39
+ properties: {
40
+ path: { type: "string", description: "File path to read" },
41
+ },
42
+ required: ["path"],
43
+ },
44
+ },
45
+ },
46
+ {
47
+ type: "function",
48
+ function: {
49
+ name: "write_file",
50
+ description: "Write content to a file (create or overwrite)",
51
+ parameters: {
52
+ type: "object",
53
+ properties: {
54
+ path: { type: "string", description: "File path" },
55
+ content: { type: "string", description: "File content" },
56
+ },
57
+ required: ["path", "content"],
58
+ },
59
+ },
60
+ },
61
+ {
62
+ type: "function",
63
+ function: {
64
+ name: "edit_file",
65
+ description: "Replace a specific string in a file with new content",
66
+ parameters: {
67
+ type: "object",
68
+ properties: {
69
+ path: { type: "string", description: "File path" },
70
+ old_string: {
71
+ type: "string",
72
+ description: "Exact string to find and replace",
73
+ },
74
+ new_string: {
75
+ type: "string",
76
+ description: "Replacement string",
77
+ },
78
+ },
79
+ required: ["path", "old_string", "new_string"],
80
+ },
81
+ },
82
+ },
83
+ {
84
+ type: "function",
85
+ function: {
86
+ name: "run_shell",
87
+ description:
88
+ "Execute a shell command and return the output. Use for running tests, installing packages, git operations, etc.",
89
+ parameters: {
90
+ type: "object",
91
+ properties: {
92
+ command: { type: "string", description: "Shell command to execute" },
93
+ cwd: {
94
+ type: "string",
95
+ description: "Working directory (optional)",
96
+ },
97
+ },
98
+ required: ["command"],
99
+ },
100
+ },
101
+ },
102
+ {
103
+ type: "function",
104
+ function: {
105
+ name: "search_files",
106
+ description: "Search for files by name pattern or content",
107
+ parameters: {
108
+ type: "object",
109
+ properties: {
110
+ pattern: {
111
+ type: "string",
112
+ description: "Glob pattern or search string",
113
+ },
114
+ directory: {
115
+ type: "string",
116
+ description: "Directory to search in (default: cwd)",
117
+ },
118
+ content_search: {
119
+ type: "boolean",
120
+ description: "If true, search file contents instead of names",
121
+ },
122
+ },
123
+ required: ["pattern"],
124
+ },
125
+ },
126
+ },
127
+ {
128
+ type: "function",
129
+ function: {
130
+ name: "list_dir",
131
+ description: "List contents of a directory",
132
+ parameters: {
133
+ type: "object",
134
+ properties: {
135
+ path: {
136
+ type: "string",
137
+ description: "Directory path (default: cwd)",
138
+ },
139
+ },
140
+ },
141
+ },
142
+ },
143
+ {
144
+ type: "function",
145
+ function: {
146
+ name: "run_skill",
147
+ description:
148
+ "Run a built-in ChainlessChain skill. Available skills include: code-review, summarize, translate, refactor, unit-test, debug, explain-code, browser-automation, data-analysis, git-history-analyzer, and 130+ more. Use list_skills first to discover available skills.",
149
+ parameters: {
150
+ type: "object",
151
+ properties: {
152
+ skill_name: {
153
+ type: "string",
154
+ description:
155
+ "Name of the skill to run (e.g. code-review, summarize, translate)",
156
+ },
157
+ input: {
158
+ type: "string",
159
+ description: "Input text or parameters for the skill",
160
+ },
161
+ },
162
+ required: ["skill_name", "input"],
163
+ },
164
+ },
165
+ },
166
+ {
167
+ type: "function",
168
+ function: {
169
+ name: "list_skills",
170
+ description:
171
+ "List available built-in skills, optionally filtered by category or keyword",
172
+ parameters: {
173
+ type: "object",
174
+ properties: {
175
+ category: {
176
+ type: "string",
177
+ description:
178
+ "Filter by category (e.g. development, automation, data)",
179
+ },
180
+ query: {
181
+ type: "string",
182
+ description: "Search keyword to filter skills",
183
+ },
184
+ },
185
+ },
186
+ },
187
+ },
188
+ ];
189
+
190
+ /**
191
+ * Find and load bundled skills (shared with skill command)
192
+ */
193
+ const __agentDirname = path.dirname(fileURLToPath(import.meta.url));
194
+
195
+ function findSkillsDir() {
196
+ const candidates = [
197
+ path.resolve(
198
+ __agentDirname,
199
+ "../../../../../desktop-app-vue/src/main/ai-engine/cowork/skills/builtin",
200
+ ),
201
+ path.resolve(
202
+ process.cwd(),
203
+ "desktop-app-vue/src/main/ai-engine/cowork/skills/builtin",
204
+ ),
205
+ ];
206
+ for (const dir of candidates) {
207
+ if (fs.existsSync(dir)) return dir;
208
+ }
209
+ return null;
210
+ }
211
+
212
+ function loadSkillList(skillsDir) {
213
+ const skills = [];
214
+ try {
215
+ const dirs = fs.readdirSync(skillsDir, { withFileTypes: true });
216
+ for (const dir of dirs) {
217
+ if (!dir.isDirectory()) continue;
218
+ const skillMd = path.join(skillsDir, dir.name, "SKILL.md");
219
+ if (!fs.existsSync(skillMd)) continue;
220
+ try {
221
+ const content = fs.readFileSync(skillMd, "utf8");
222
+ const lines = content.split("\n");
223
+ if (lines[0].trim() !== "---") continue;
224
+ let endIndex = -1;
225
+ for (let i = 1; i < lines.length; i++) {
226
+ if (lines[i].trim() === "---") {
227
+ endIndex = i;
228
+ break;
229
+ }
230
+ }
231
+ if (endIndex === -1) continue;
232
+ const data = {};
233
+ for (const line of lines.slice(1, endIndex)) {
234
+ const ci = line.indexOf(":");
235
+ if (ci > 0) {
236
+ const key = line.slice(0, ci).trim();
237
+ const val = line
238
+ .slice(ci + 1)
239
+ .trim()
240
+ .replace(/^['"]|['"]$/g, "");
241
+ data[key] = val;
242
+ }
243
+ }
244
+ skills.push({
245
+ id: data.name || dir.name,
246
+ description: data.description || "",
247
+ category: data.category || "uncategorized",
248
+ dirName: dir.name,
249
+ hasHandler: fs.existsSync(
250
+ path.join(skillsDir, dir.name, "handler.js"),
251
+ ),
252
+ });
253
+ } catch {
254
+ // Skip malformed skill files
255
+ }
256
+ }
257
+ } catch {
258
+ // Skills dir unreadable
259
+ }
260
+ return skills;
261
+ }
262
+
263
+ /**
264
+ * Execute a tool call
265
+ */
266
+ async function executeTool(name, args) {
267
+ switch (name) {
268
+ case "read_file": {
269
+ const filePath = path.resolve(args.path);
270
+ if (!fs.existsSync(filePath)) {
271
+ return { error: `File not found: ${filePath}` };
272
+ }
273
+ const content = fs.readFileSync(filePath, "utf8");
274
+ // Truncate very long files
275
+ if (content.length > 50000) {
276
+ return {
277
+ content: content.substring(0, 50000) + "\n...(truncated)",
278
+ size: content.length,
279
+ };
280
+ }
281
+ return { content };
282
+ }
283
+
284
+ case "write_file": {
285
+ const filePath = path.resolve(args.path);
286
+ const dir = path.dirname(filePath);
287
+ if (!fs.existsSync(dir)) {
288
+ fs.mkdirSync(dir, { recursive: true });
289
+ }
290
+ fs.writeFileSync(filePath, args.content, "utf8");
291
+ return { success: true, path: filePath, size: args.content.length };
292
+ }
293
+
294
+ case "edit_file": {
295
+ const filePath = path.resolve(args.path);
296
+ if (!fs.existsSync(filePath)) {
297
+ return { error: `File not found: ${filePath}` };
298
+ }
299
+ const content = fs.readFileSync(filePath, "utf8");
300
+ if (!content.includes(args.old_string)) {
301
+ return { error: "old_string not found in file" };
302
+ }
303
+ const newContent = content.replace(args.old_string, args.new_string);
304
+ fs.writeFileSync(filePath, newContent, "utf8");
305
+ return { success: true, path: filePath };
306
+ }
307
+
308
+ case "run_shell": {
309
+ try {
310
+ const output = execSync(args.command, {
311
+ cwd: args.cwd || process.cwd(),
312
+ encoding: "utf8",
313
+ timeout: 30000,
314
+ maxBuffer: 1024 * 1024,
315
+ });
316
+ return { stdout: output.substring(0, 10000) };
317
+ } catch (err) {
318
+ return {
319
+ error: err.message.substring(0, 2000),
320
+ stderr: (err.stderr || "").substring(0, 2000),
321
+ exitCode: err.status,
322
+ };
323
+ }
324
+ }
325
+
326
+ case "search_files": {
327
+ const dir = args.directory ? path.resolve(args.directory) : process.cwd();
328
+ try {
329
+ if (args.content_search) {
330
+ // Use grep/findstr for content search
331
+ const cmd =
332
+ process.platform === "win32"
333
+ ? `findstr /s /i /n "${args.pattern}" *`
334
+ : `grep -r -l -i "${args.pattern}" . --include="*" 2>/dev/null | head -20`;
335
+ const output = execSync(cmd, {
336
+ cwd: dir,
337
+ encoding: "utf8",
338
+ timeout: 10000,
339
+ });
340
+ return { matches: output.trim().split("\n").slice(0, 20) };
341
+ } else {
342
+ // File name search
343
+ const cmd =
344
+ process.platform === "win32"
345
+ ? `dir /s /b *${args.pattern}* 2>NUL`
346
+ : `find . -name "*${args.pattern}*" -type f 2>/dev/null | head -20`;
347
+ const output = execSync(cmd, {
348
+ cwd: dir,
349
+ encoding: "utf8",
350
+ timeout: 10000,
351
+ });
352
+ return {
353
+ files: output.trim().split("\n").filter(Boolean).slice(0, 20),
354
+ };
355
+ }
356
+ } catch {
357
+ return { files: [], message: "No matches found" };
358
+ }
359
+ }
360
+
361
+ case "list_dir": {
362
+ const dirPath = args.path ? path.resolve(args.path) : process.cwd();
363
+ if (!fs.existsSync(dirPath)) {
364
+ return { error: `Directory not found: ${dirPath}` };
365
+ }
366
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
367
+ return {
368
+ entries: entries.map((e) => ({
369
+ name: e.name,
370
+ type: e.isDirectory() ? "dir" : "file",
371
+ })),
372
+ };
373
+ }
374
+
375
+ case "run_skill": {
376
+ const skillsDir = findSkillsDir();
377
+ if (!skillsDir) {
378
+ return {
379
+ error:
380
+ "Skills directory not found. Make sure you're in the ChainlessChain project root.",
381
+ };
382
+ }
383
+ const handlerPath = path.join(skillsDir, args.skill_name, "handler.js");
384
+ if (!fs.existsSync(handlerPath)) {
385
+ // Try fuzzy match
386
+ const skills = loadSkillList(skillsDir);
387
+ const match = skills.find(
388
+ (s) => s.id === args.skill_name || s.dirName === args.skill_name,
389
+ );
390
+ if (match && match.hasHandler) {
391
+ const matchedPath = path.join(skillsDir, match.dirName, "handler.js");
392
+ try {
393
+ const handler = (
394
+ await import(`file://${matchedPath.replace(/\\/g, "/")}`)
395
+ ).default;
396
+ const task = {
397
+ params: { input: args.input },
398
+ input: args.input,
399
+ action: args.input,
400
+ };
401
+ const context = {
402
+ projectRoot: process.cwd(),
403
+ workspacePath: process.cwd(),
404
+ };
405
+ const result = await handler.execute(task, context);
406
+ return result;
407
+ } catch (err) {
408
+ return { error: `Skill execution failed: ${err.message}` };
409
+ }
410
+ }
411
+ return {
412
+ error: `Skill "${args.skill_name}" not found or has no handler. Use list_skills to see available skills.`,
413
+ };
414
+ }
415
+ try {
416
+ const handler = (
417
+ await import(`file://${handlerPath.replace(/\\/g, "/")}`)
418
+ ).default;
419
+ if (handler.init) await handler.init({});
420
+ const task = {
421
+ params: { input: args.input },
422
+ input: args.input,
423
+ action: args.input,
424
+ };
425
+ const context = {
426
+ projectRoot: process.cwd(),
427
+ workspacePath: process.cwd(),
428
+ };
429
+ const result = await handler.execute(task, context);
430
+ return result;
431
+ } catch (err) {
432
+ return { error: `Skill execution failed: ${err.message}` };
433
+ }
434
+ }
435
+
436
+ case "list_skills": {
437
+ const skillsDir = findSkillsDir();
438
+ if (!skillsDir) {
439
+ return { error: "Skills directory not found." };
440
+ }
441
+ let skills = loadSkillList(skillsDir);
442
+ if (args.category) {
443
+ skills = skills.filter(
444
+ (s) => s.category.toLowerCase() === args.category.toLowerCase(),
445
+ );
446
+ }
447
+ if (args.query) {
448
+ const q = args.query.toLowerCase();
449
+ skills = skills.filter(
450
+ (s) =>
451
+ s.id.includes(q) ||
452
+ s.description.toLowerCase().includes(q) ||
453
+ s.category.toLowerCase().includes(q),
454
+ );
455
+ }
456
+ return {
457
+ count: skills.length,
458
+ skills: skills.map((s) => ({
459
+ id: s.id,
460
+ category: s.category,
461
+ hasHandler: s.hasHandler,
462
+ description: s.description.substring(0, 80),
463
+ })),
464
+ };
465
+ }
466
+
467
+ default:
468
+ return { error: `Unknown tool: ${name}` };
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Send a chat completion request with tools
474
+ */
475
+ async function chatWithTools(messages, options) {
476
+ const { provider, model, baseUrl, apiKey } = options;
477
+
478
+ if (provider === "ollama") {
479
+ // Ollama supports tool calling for some models
480
+ const response = await fetch(`${baseUrl}/api/chat`, {
481
+ method: "POST",
482
+ headers: { "Content-Type": "application/json" },
483
+ body: JSON.stringify({
484
+ model,
485
+ messages,
486
+ tools: TOOLS,
487
+ stream: false,
488
+ }),
489
+ });
490
+
491
+ if (!response.ok) {
492
+ throw new Error(`Ollama error: ${response.status}`);
493
+ }
494
+
495
+ return await response.json();
496
+ } else if (provider === "openai") {
497
+ const url =
498
+ baseUrl && baseUrl !== "http://localhost:11434"
499
+ ? baseUrl
500
+ : "https://api.openai.com/v1";
501
+ const key = apiKey || process.env.OPENAI_API_KEY;
502
+ if (!key) throw new Error("API key required");
503
+
504
+ const response = await fetch(`${url}/chat/completions`, {
505
+ method: "POST",
506
+ headers: {
507
+ "Content-Type": "application/json",
508
+ Authorization: `Bearer ${key}`,
509
+ },
510
+ body: JSON.stringify({
511
+ model: model || "gpt-4o-mini",
512
+ messages,
513
+ tools: TOOLS,
514
+ }),
515
+ });
516
+
517
+ if (!response.ok) {
518
+ throw new Error(`API error: ${response.status}`);
519
+ }
520
+
521
+ const data = await response.json();
522
+ // Normalize to Ollama-like format
523
+ const choice = data.choices[0];
524
+ return {
525
+ message: choice.message,
526
+ };
527
+ }
528
+
529
+ throw new Error(`Unsupported provider: ${provider}`);
530
+ }
531
+
532
+ /**
533
+ * Agentic loop - keeps calling tools until the AI gives a final text response
534
+ */
535
+ async function agentLoop(messages, options) {
536
+ const MAX_ITERATIONS = 10;
537
+
538
+ for (let i = 0; i < MAX_ITERATIONS; i++) {
539
+ const result = await chatWithTools(messages, options);
540
+ const msg = result.message;
541
+
542
+ // Check for tool calls
543
+ const toolCalls = msg.tool_calls;
544
+
545
+ if (!toolCalls || toolCalls.length === 0) {
546
+ // No tool calls — final text response
547
+ return msg.content || "";
548
+ }
549
+
550
+ // Add assistant message with tool calls
551
+ messages.push(msg);
552
+
553
+ // Execute each tool call
554
+ for (const call of toolCalls) {
555
+ const fn = call.function;
556
+ const toolName = fn.name;
557
+ let toolArgs;
558
+
559
+ try {
560
+ toolArgs =
561
+ typeof fn.arguments === "string"
562
+ ? JSON.parse(fn.arguments)
563
+ : fn.arguments;
564
+ } catch {
565
+ toolArgs = {};
566
+ }
567
+
568
+ // Show what the AI is doing
569
+ process.stdout.write(
570
+ chalk.gray(` [${toolName}] ${formatToolArgs(toolName, toolArgs)}\n`),
571
+ );
572
+
573
+ const toolResult = await executeTool(toolName, toolArgs);
574
+
575
+ // Show brief result
576
+ if (toolResult.error) {
577
+ process.stdout.write(chalk.red(` Error: ${toolResult.error}\n`));
578
+ } else if (toolResult.success) {
579
+ process.stdout.write(chalk.green(` Done\n`));
580
+ }
581
+
582
+ // Add tool result to messages
583
+ messages.push({
584
+ role: "tool",
585
+ content: JSON.stringify(toolResult).substring(0, 5000),
586
+ tool_call_id: call.id,
587
+ });
588
+ }
589
+ }
590
+
591
+ return "(Reached max tool call iterations)";
592
+ }
593
+
594
+ /**
595
+ * Format tool args for display
596
+ */
597
+ function formatToolArgs(name, args) {
598
+ switch (name) {
599
+ case "read_file":
600
+ return args.path;
601
+ case "write_file":
602
+ return `${args.path} (${args.content?.length || 0} chars)`;
603
+ case "edit_file":
604
+ return args.path;
605
+ case "run_shell":
606
+ return args.command;
607
+ case "search_files":
608
+ return args.pattern;
609
+ case "list_dir":
610
+ return args.path || ".";
611
+ case "run_skill":
612
+ return `${args.skill_name}: ${(args.input || "").substring(0, 50)}`;
613
+ case "list_skills":
614
+ return args.category || args.query || "all";
615
+ default:
616
+ return JSON.stringify(args).substring(0, 60);
617
+ }
618
+ }
619
+
620
+ const SYSTEM_PROMPT = `You are ChainlessChain AI Assistant, a powerful agentic coding assistant running in the terminal.
621
+
622
+ You have access to tools that let you read files, write files, edit files, run shell commands, and search the codebase. When the user asks you to do something, USE THE TOOLS to actually do it — don't just describe what should be done.
623
+
624
+ Key behaviors:
625
+ - When asked to modify code, read the file first, then edit it
626
+ - When asked to create something, use write_file to create it
627
+ - When asked to run/test something, use run_shell to execute it
628
+ - When asked about files or code, use read_file and search_files to find information
629
+ - You have 138 built-in skills (code-review, summarize, translate, refactor, etc.) — use list_skills to discover them and run_skill to execute them
630
+ - Always explain what you're doing and show results
631
+ - Be concise but thorough
632
+
633
+ Current working directory: ${process.cwd()}`;
634
+
635
+ /**
636
+ * Start the agentic REPL
637
+ */
638
+ export async function startAgentRepl(options = {}) {
639
+ let model = options.model || "qwen2:7b";
640
+ let provider = options.provider || "ollama";
641
+ const baseUrl = options.baseUrl || "http://localhost:11434";
642
+ const apiKey = options.apiKey || process.env.OPENAI_API_KEY;
643
+
644
+ const messages = [{ role: "system", content: SYSTEM_PROMPT }];
645
+
646
+ const rl = readline.createInterface({
647
+ input: process.stdin,
648
+ output: process.stdout,
649
+ prompt: chalk.green("> "),
650
+ terminal: true,
651
+ });
652
+
653
+ logger.log(chalk.bold("\nChainlessChain Agent"));
654
+ logger.log(
655
+ chalk.gray(`Model: ${model} Provider: ${provider} CWD: ${process.cwd()}`),
656
+ );
657
+ logger.log(
658
+ chalk.gray(
659
+ "Describe what you want to do. I can read/write files, run commands, and more.",
660
+ ),
661
+ );
662
+ logger.log(chalk.gray("Type /exit to quit, /help for commands\n"));
663
+
664
+ rl.prompt();
665
+
666
+ rl.on("line", async (input) => {
667
+ const trimmed = input.trim();
668
+ if (!trimmed) {
669
+ rl.prompt();
670
+ return;
671
+ }
672
+
673
+ // Slash commands
674
+ if (trimmed === "/exit" || trimmed === "/quit") {
675
+ logger.log(chalk.gray("\nGoodbye!"));
676
+ rl.close();
677
+ return;
678
+ }
679
+
680
+ if (trimmed === "/help") {
681
+ logger.log(chalk.bold("\nCommands:"));
682
+ logger.log(` ${chalk.cyan("/exit")} Exit the agent`);
683
+ logger.log(
684
+ ` ${chalk.cyan("/model")} Show/change model (/model <name>)`,
685
+ );
686
+ logger.log(` ${chalk.cyan("/provider")} Show/change provider`);
687
+ logger.log(` ${chalk.cyan("/clear")} Clear conversation`);
688
+ logger.log(` ${chalk.cyan("/compact")} Keep only last 4 messages`);
689
+ logger.log(chalk.bold("\nCapabilities:"));
690
+ logger.log(" Read, write, and edit files");
691
+ logger.log(" Run shell commands (git, npm, etc.)");
692
+ logger.log(" Search codebase by filename or content");
693
+ logger.log(" Run 138 built-in skills (code-review, summarize, etc.)");
694
+ logger.log(" Answer questions about code\n");
695
+ rl.prompt();
696
+ return;
697
+ }
698
+
699
+ if (trimmed.startsWith("/model")) {
700
+ const arg = trimmed.slice(6).trim();
701
+ if (arg) {
702
+ model = arg;
703
+ logger.info(`Model: ${chalk.cyan(model)}`);
704
+ } else {
705
+ logger.info(`Current model: ${chalk.cyan(model)}`);
706
+ }
707
+ rl.prompt();
708
+ return;
709
+ }
710
+
711
+ if (trimmed.startsWith("/provider")) {
712
+ const arg = trimmed.slice(9).trim();
713
+ if (arg) {
714
+ provider = arg;
715
+ logger.info(`Provider: ${chalk.cyan(provider)}`);
716
+ } else {
717
+ logger.info(`Current provider: ${chalk.cyan(provider)}`);
718
+ }
719
+ rl.prompt();
720
+ return;
721
+ }
722
+
723
+ if (trimmed === "/clear") {
724
+ messages.length = 1; // Keep system prompt
725
+ logger.info("Conversation cleared");
726
+ rl.prompt();
727
+ return;
728
+ }
729
+
730
+ if (trimmed === "/compact") {
731
+ // Keep system prompt + last 4 messages
732
+ if (messages.length > 5) {
733
+ const systemMsg = messages[0];
734
+ const recent = messages.slice(-4);
735
+ messages.length = 0;
736
+ messages.push(systemMsg, ...recent);
737
+ logger.info("Conversation compacted to last 4 messages");
738
+ }
739
+ rl.prompt();
740
+ return;
741
+ }
742
+
743
+ // Add user message
744
+ messages.push({ role: "user", content: trimmed });
745
+
746
+ try {
747
+ process.stdout.write("\n");
748
+ const response = await agentLoop(messages, {
749
+ provider,
750
+ model,
751
+ baseUrl,
752
+ apiKey,
753
+ });
754
+
755
+ if (response) {
756
+ process.stdout.write(`\n${response}\n\n`);
757
+ messages.push({ role: "assistant", content: response });
758
+ } else {
759
+ process.stdout.write("\n");
760
+ }
761
+ } catch (err) {
762
+ logger.error(`Error: ${err.message}`);
763
+
764
+ // If connection error, provide helpful message
765
+ if (
766
+ err.message.includes("ECONNREFUSED") ||
767
+ err.message.includes("fetch failed")
768
+ ) {
769
+ logger.info(`Make sure ${provider} is running at ${baseUrl}`);
770
+ if (provider === "ollama") {
771
+ logger.info("Start Ollama: ollama serve");
772
+ }
773
+ }
774
+ }
775
+
776
+ rl.prompt();
777
+ });
778
+
779
+ rl.on("close", () => {
780
+ process.exit(0);
781
+ });
782
+ }