chainlesschain 0.40.2 → 0.40.3

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,861 @@
1
+ /**
2
+ * Agent Core — transport-independent agentic logic
3
+ *
4
+ * Extracted from agent-repl.js so that both the terminal REPL and the
5
+ * WebSocket session handler can share the same tool definitions,
6
+ * execution logic, and LLM-driven agent loop.
7
+ *
8
+ * Key exports:
9
+ * - AGENT_TOOLS — OpenAI function-calling tool definitions
10
+ * - getBaseSystemPrompt — system prompt generator
11
+ * - executeTool — tool execution with plan-mode + hook pipeline
12
+ * - chatWithTools — LLM call with tool definitions injected
13
+ * - agentLoop — async generator yielding structured events
14
+ * - formatToolArgs — human-readable tool argument formatting
15
+ */
16
+
17
+ import fs from "fs";
18
+ import path from "path";
19
+ import { execSync } from "child_process";
20
+ import os from "os";
21
+ import { getPlanModeManager } from "./plan-mode.js";
22
+ import { CLISkillLoader } from "./skill-loader.js";
23
+ import { executeHooks, HookEvents } from "./hook-manager.js";
24
+
25
+ // ─── Tool definitions ────────────────────────────────────────────────────
26
+
27
+ export const AGENT_TOOLS = [
28
+ {
29
+ type: "function",
30
+ function: {
31
+ name: "read_file",
32
+ description: "Read a file's content",
33
+ parameters: {
34
+ type: "object",
35
+ properties: {
36
+ path: { type: "string", description: "File path to read" },
37
+ },
38
+ required: ["path"],
39
+ },
40
+ },
41
+ },
42
+ {
43
+ type: "function",
44
+ function: {
45
+ name: "write_file",
46
+ description: "Write content to a file (create or overwrite)",
47
+ parameters: {
48
+ type: "object",
49
+ properties: {
50
+ path: { type: "string", description: "File path" },
51
+ content: { type: "string", description: "File content" },
52
+ },
53
+ required: ["path", "content"],
54
+ },
55
+ },
56
+ },
57
+ {
58
+ type: "function",
59
+ function: {
60
+ name: "edit_file",
61
+ description: "Replace a specific string in a file with new content",
62
+ parameters: {
63
+ type: "object",
64
+ properties: {
65
+ path: { type: "string", description: "File path" },
66
+ old_string: {
67
+ type: "string",
68
+ description: "Exact string to find and replace",
69
+ },
70
+ new_string: {
71
+ type: "string",
72
+ description: "Replacement string",
73
+ },
74
+ },
75
+ required: ["path", "old_string", "new_string"],
76
+ },
77
+ },
78
+ },
79
+ {
80
+ type: "function",
81
+ function: {
82
+ name: "run_shell",
83
+ description:
84
+ "Execute a shell command and return the output. Use for running tests, installing packages, git operations, etc.",
85
+ parameters: {
86
+ type: "object",
87
+ properties: {
88
+ command: { type: "string", description: "Shell command to execute" },
89
+ cwd: {
90
+ type: "string",
91
+ description: "Working directory (optional)",
92
+ },
93
+ },
94
+ required: ["command"],
95
+ },
96
+ },
97
+ },
98
+ {
99
+ type: "function",
100
+ function: {
101
+ name: "search_files",
102
+ description: "Search for files by name pattern or content",
103
+ parameters: {
104
+ type: "object",
105
+ properties: {
106
+ pattern: {
107
+ type: "string",
108
+ description: "Glob pattern or search string",
109
+ },
110
+ directory: {
111
+ type: "string",
112
+ description: "Directory to search in (default: cwd)",
113
+ },
114
+ content_search: {
115
+ type: "boolean",
116
+ description: "If true, search file contents instead of names",
117
+ },
118
+ },
119
+ required: ["pattern"],
120
+ },
121
+ },
122
+ },
123
+ {
124
+ type: "function",
125
+ function: {
126
+ name: "list_dir",
127
+ description: "List contents of a directory",
128
+ parameters: {
129
+ type: "object",
130
+ properties: {
131
+ path: {
132
+ type: "string",
133
+ description: "Directory path (default: cwd)",
134
+ },
135
+ },
136
+ },
137
+ },
138
+ },
139
+ {
140
+ type: "function",
141
+ function: {
142
+ name: "run_skill",
143
+ description:
144
+ "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.",
145
+ parameters: {
146
+ type: "object",
147
+ properties: {
148
+ skill_name: {
149
+ type: "string",
150
+ description:
151
+ "Name of the skill to run (e.g. code-review, summarize, translate)",
152
+ },
153
+ input: {
154
+ type: "string",
155
+ description: "Input text or parameters for the skill",
156
+ },
157
+ },
158
+ required: ["skill_name", "input"],
159
+ },
160
+ },
161
+ },
162
+ {
163
+ type: "function",
164
+ function: {
165
+ name: "list_skills",
166
+ description:
167
+ "List available built-in skills, optionally filtered by category or keyword",
168
+ parameters: {
169
+ type: "object",
170
+ properties: {
171
+ category: {
172
+ type: "string",
173
+ description:
174
+ "Filter by category (e.g. development, automation, data)",
175
+ },
176
+ query: {
177
+ type: "string",
178
+ description: "Search keyword to filter skills",
179
+ },
180
+ },
181
+ },
182
+ },
183
+ },
184
+ {
185
+ type: "function",
186
+ function: {
187
+ name: "run_code",
188
+ description:
189
+ "Write and execute code in Python, Node.js, or Bash. Use this when the user needs data processing, calculations, file batch operations, API calls, or any task best solved with a script. The code is saved to a temp file and executed.",
190
+ parameters: {
191
+ type: "object",
192
+ properties: {
193
+ language: {
194
+ type: "string",
195
+ enum: ["python", "node", "bash"],
196
+ description: "Programming language",
197
+ },
198
+ code: { type: "string", description: "Code to execute" },
199
+ timeout: {
200
+ type: "number",
201
+ description: "Execution timeout in seconds (default: 60, max: 300)",
202
+ },
203
+ },
204
+ required: ["language", "code"],
205
+ },
206
+ },
207
+ },
208
+ ];
209
+
210
+ // ─── Shared skill loader ──────────────────────────────────────────────────
211
+
212
+ const _defaultSkillLoader = new CLISkillLoader();
213
+
214
+ // ─── System prompt ────────────────────────────────────────────────────────
215
+
216
+ export function getBaseSystemPrompt(cwd) {
217
+ return `You are ChainlessChain AI Assistant, a powerful agentic coding assistant running in the terminal.
218
+
219
+ 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.
220
+
221
+ Key behaviors:
222
+ - When asked to modify code, read the file first, then edit it
223
+ - When asked to create something, use write_file to create it
224
+ - When asked to run/test something, use run_shell to execute it
225
+ - When asked about files or code, use read_file and search_files to find information
226
+ - You have multi-layer skills (built-in, marketplace, global, project-level) — use list_skills to discover them and run_skill to execute them
227
+ - Always explain what you're doing and show results
228
+ - Be concise but thorough
229
+
230
+ When the user's problem involves data processing, calculations, file operations, text parsing, API calls, web scraping, or any task that can be solved programmatically:
231
+ - Proactively write and execute code using run_code tool
232
+ - Choose the best language: Python for data/math/scraping, Node.js for JSON/API, Bash for system tasks
233
+ - Show the results and explain them clearly
234
+ - If the first attempt fails, debug and retry with a different approach
235
+
236
+ You are not just a chatbot — you are a capable coding agent. Think step by step, write code when needed, and deliver real results.
237
+
238
+ Current working directory: ${cwd || process.cwd()}`;
239
+ }
240
+
241
+ // ─── Tool execution ──────────────────────────────────────────────────────
242
+
243
+ /**
244
+ * Execute a single tool call with plan-mode filtering and hook pipeline.
245
+ *
246
+ * @param {string} name - tool name
247
+ * @param {object} args - tool arguments
248
+ * @param {object} [context] - optional context
249
+ * @param {object} [context.hookDb] - DB for hooks
250
+ * @param {CLISkillLoader} [context.skillLoader] - skill loader instance
251
+ * @param {string} [context.cwd] - working directory override
252
+ * @returns {Promise<object>} tool result
253
+ */
254
+ export async function executeTool(name, args, context = {}) {
255
+ const hookDb = context.hookDb || null;
256
+ const skillLoader = context.skillLoader || _defaultSkillLoader;
257
+ const cwd = context.cwd || process.cwd();
258
+
259
+ // Plan mode: check if tool is allowed
260
+ const planManager = getPlanModeManager();
261
+ if (planManager.isActive() && !planManager.isToolAllowed(name)) {
262
+ planManager.addPlanItem({
263
+ title: `${name}: ${formatToolArgs(name, args)}`,
264
+ tool: name,
265
+ params: args,
266
+ estimatedImpact:
267
+ name === "run_shell" || name === "run_code"
268
+ ? "high"
269
+ : name === "write_file"
270
+ ? "medium"
271
+ : "low",
272
+ });
273
+ return {
274
+ error: `[Plan Mode] Tool "${name}" is blocked during planning. It has been added to the plan. Use /plan approve to execute.`,
275
+ };
276
+ }
277
+
278
+ // PreToolUse hook
279
+ if (hookDb) {
280
+ try {
281
+ await executeHooks(hookDb, HookEvents.PreToolUse, {
282
+ tool: name,
283
+ args,
284
+ timestamp: new Date().toISOString(),
285
+ });
286
+ } catch (_err) {
287
+ // Hook failure should not block tool execution
288
+ }
289
+ }
290
+
291
+ let toolResult;
292
+ try {
293
+ toolResult = await executeToolInner(name, args, { skillLoader, cwd });
294
+ } catch (err) {
295
+ if (hookDb) {
296
+ try {
297
+ await executeHooks(hookDb, HookEvents.ToolError, {
298
+ tool: name,
299
+ args,
300
+ error: err.message,
301
+ });
302
+ } catch (_err) {
303
+ // Non-critical
304
+ }
305
+ }
306
+ throw err;
307
+ }
308
+
309
+ // PostToolUse hook
310
+ if (hookDb) {
311
+ try {
312
+ await executeHooks(hookDb, HookEvents.PostToolUse, {
313
+ tool: name,
314
+ args,
315
+ result:
316
+ typeof toolResult === "object"
317
+ ? JSON.stringify(toolResult).substring(0, 500)
318
+ : String(toolResult).substring(0, 500),
319
+ });
320
+ } catch (_err) {
321
+ // Non-critical
322
+ }
323
+ }
324
+
325
+ return toolResult;
326
+ }
327
+
328
+ /**
329
+ * Inner tool execution — no hooks, no plan-mode checks.
330
+ */
331
+ async function executeToolInner(name, args, { skillLoader, cwd }) {
332
+ switch (name) {
333
+ case "read_file": {
334
+ const filePath = path.resolve(cwd, args.path);
335
+ if (!fs.existsSync(filePath)) {
336
+ return { error: `File not found: ${filePath}` };
337
+ }
338
+ const content = fs.readFileSync(filePath, "utf8");
339
+ if (content.length > 50000) {
340
+ return {
341
+ content: content.substring(0, 50000) + "\n...(truncated)",
342
+ size: content.length,
343
+ };
344
+ }
345
+ return { content };
346
+ }
347
+
348
+ case "write_file": {
349
+ const filePath = path.resolve(cwd, args.path);
350
+ const dir = path.dirname(filePath);
351
+ if (!fs.existsSync(dir)) {
352
+ fs.mkdirSync(dir, { recursive: true });
353
+ }
354
+ fs.writeFileSync(filePath, args.content, "utf8");
355
+ return { success: true, path: filePath, size: args.content.length };
356
+ }
357
+
358
+ case "edit_file": {
359
+ const filePath = path.resolve(cwd, args.path);
360
+ if (!fs.existsSync(filePath)) {
361
+ return { error: `File not found: ${filePath}` };
362
+ }
363
+ const content = fs.readFileSync(filePath, "utf8");
364
+ if (!content.includes(args.old_string)) {
365
+ return { error: "old_string not found in file" };
366
+ }
367
+ const newContent = content.replace(args.old_string, args.new_string);
368
+ fs.writeFileSync(filePath, newContent, "utf8");
369
+ return { success: true, path: filePath };
370
+ }
371
+
372
+ case "run_shell": {
373
+ try {
374
+ const output = execSync(args.command, {
375
+ cwd: args.cwd || cwd,
376
+ encoding: "utf8",
377
+ timeout: 60000,
378
+ maxBuffer: 1024 * 1024,
379
+ });
380
+ return { stdout: output.substring(0, 30000) };
381
+ } catch (err) {
382
+ return {
383
+ error: err.message.substring(0, 2000),
384
+ stderr: (err.stderr || "").substring(0, 2000),
385
+ exitCode: err.status,
386
+ };
387
+ }
388
+ }
389
+
390
+ case "run_code": {
391
+ const lang = args.language;
392
+ const code = args.code;
393
+ const timeoutSec = Math.min(Math.max(args.timeout || 60, 1), 300);
394
+
395
+ const extMap = { python: ".py", node: ".js", bash: ".sh" };
396
+ const ext = extMap[lang];
397
+ if (!ext) {
398
+ return {
399
+ error: `Unsupported language: ${lang}. Use python, node, or bash.`,
400
+ };
401
+ }
402
+
403
+ const tmpFile = path.join(os.tmpdir(), `cc-agent-${Date.now()}${ext}`);
404
+
405
+ try {
406
+ fs.writeFileSync(tmpFile, code, "utf8");
407
+
408
+ let interpreter;
409
+ if (lang === "python") {
410
+ try {
411
+ execSync("python3 --version", { encoding: "utf8", timeout: 5000 });
412
+ interpreter = "python3";
413
+ } catch {
414
+ interpreter = "python";
415
+ }
416
+ } else if (lang === "node") {
417
+ interpreter = "node";
418
+ } else {
419
+ interpreter = "bash";
420
+ }
421
+
422
+ const start = Date.now();
423
+ const output = execSync(`${interpreter} "${tmpFile}"`, {
424
+ cwd,
425
+ encoding: "utf8",
426
+ timeout: timeoutSec * 1000,
427
+ maxBuffer: 5 * 1024 * 1024,
428
+ });
429
+ const duration = Date.now() - start;
430
+
431
+ return {
432
+ success: true,
433
+ output: output.substring(0, 50000),
434
+ language: lang,
435
+ duration: `${duration}ms`,
436
+ };
437
+ } catch (err) {
438
+ return {
439
+ error: (err.stderr || err.message || "").substring(0, 5000),
440
+ stderr: (err.stderr || "").substring(0, 5000),
441
+ exitCode: err.status,
442
+ language: lang,
443
+ };
444
+ } finally {
445
+ try {
446
+ fs.unlinkSync(tmpFile);
447
+ } catch {
448
+ // Cleanup best-effort
449
+ }
450
+ }
451
+ }
452
+
453
+ case "search_files": {
454
+ const dir = args.directory ? path.resolve(cwd, args.directory) : cwd;
455
+ try {
456
+ if (args.content_search) {
457
+ const cmd =
458
+ process.platform === "win32"
459
+ ? `findstr /s /i /n "${args.pattern}" *`
460
+ : `grep -r -l -i "${args.pattern}" . --include="*" 2>/dev/null | head -20`;
461
+ const output = execSync(cmd, {
462
+ cwd: dir,
463
+ encoding: "utf8",
464
+ timeout: 10000,
465
+ });
466
+ return { matches: output.trim().split("\n").slice(0, 20) };
467
+ } else {
468
+ const cmd =
469
+ process.platform === "win32"
470
+ ? `dir /s /b *${args.pattern}* 2>NUL`
471
+ : `find . -name "*${args.pattern}*" -type f 2>/dev/null | head -20`;
472
+ const output = execSync(cmd, {
473
+ cwd: dir,
474
+ encoding: "utf8",
475
+ timeout: 10000,
476
+ });
477
+ return {
478
+ files: output.trim().split("\n").filter(Boolean).slice(0, 20),
479
+ };
480
+ }
481
+ } catch {
482
+ return { files: [], message: "No matches found" };
483
+ }
484
+ }
485
+
486
+ case "list_dir": {
487
+ const dirPath = args.path ? path.resolve(cwd, args.path) : cwd;
488
+ if (!fs.existsSync(dirPath)) {
489
+ return { error: `Directory not found: ${dirPath}` };
490
+ }
491
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
492
+ return {
493
+ entries: entries.map((e) => ({
494
+ name: e.name,
495
+ type: e.isDirectory() ? "dir" : "file",
496
+ })),
497
+ };
498
+ }
499
+
500
+ case "run_skill": {
501
+ const allSkills = skillLoader.getResolvedSkills();
502
+ if (allSkills.length === 0) {
503
+ return {
504
+ error:
505
+ "No skills found. Make sure you're in the ChainlessChain project root or have skills installed.",
506
+ };
507
+ }
508
+ const match = allSkills.find(
509
+ (s) => s.id === args.skill_name || s.dirName === args.skill_name,
510
+ );
511
+ if (!match || !match.hasHandler) {
512
+ return {
513
+ error: `Skill "${args.skill_name}" not found or has no handler. Use list_skills to see available skills.`,
514
+ };
515
+ }
516
+ try {
517
+ const handlerPath = path.join(match.skillDir, "handler.js");
518
+ const imported = await import(
519
+ `file://${handlerPath.replace(/\\/g, "/")}`
520
+ );
521
+ const handler = imported.default || imported;
522
+ if (handler.init) await handler.init(match);
523
+ const task = {
524
+ params: { input: args.input },
525
+ input: args.input,
526
+ action: args.input,
527
+ };
528
+ const taskContext = {
529
+ projectRoot: cwd,
530
+ workspacePath: cwd,
531
+ };
532
+ const result = await handler.execute(task, taskContext, match);
533
+ return result;
534
+ } catch (err) {
535
+ return { error: `Skill execution failed: ${err.message}` };
536
+ }
537
+ }
538
+
539
+ case "list_skills": {
540
+ let skills = skillLoader.getResolvedSkills();
541
+ if (skills.length === 0) {
542
+ return { error: "No skills found." };
543
+ }
544
+ if (args.category) {
545
+ skills = skills.filter(
546
+ (s) => s.category.toLowerCase() === args.category.toLowerCase(),
547
+ );
548
+ }
549
+ if (args.query) {
550
+ const q = args.query.toLowerCase();
551
+ skills = skills.filter(
552
+ (s) =>
553
+ s.id.includes(q) ||
554
+ s.description.toLowerCase().includes(q) ||
555
+ s.category.toLowerCase().includes(q),
556
+ );
557
+ }
558
+ return {
559
+ count: skills.length,
560
+ skills: skills.map((s) => ({
561
+ id: s.id,
562
+ category: s.category,
563
+ source: s.source,
564
+ hasHandler: s.hasHandler,
565
+ description: (s.description || "").substring(0, 80),
566
+ })),
567
+ };
568
+ }
569
+
570
+ default:
571
+ return { error: `Unknown tool: ${name}` };
572
+ }
573
+ }
574
+
575
+ // ─── LLM chat with tools ─────────────────────────────────────────────────
576
+
577
+ /**
578
+ * Send a chat completion request with tool definitions.
579
+ * Supports 8 providers: ollama, anthropic, openai, deepseek, dashscope, gemini, mistral, volcengine
580
+ *
581
+ * @param {Array} rawMessages
582
+ * @param {object} options
583
+ * @returns {Promise<object>} response with .message
584
+ */
585
+ export async function chatWithTools(rawMessages, options) {
586
+ const { provider, model, baseUrl, apiKey, contextEngine: ce } = options;
587
+
588
+ const lastUserMsg = [...rawMessages].reverse().find((m) => m.role === "user");
589
+ const messages = ce
590
+ ? ce.buildOptimizedMessages(rawMessages, {
591
+ userQuery: lastUserMsg?.content,
592
+ })
593
+ : rawMessages;
594
+
595
+ if (provider === "ollama") {
596
+ const response = await fetch(`${baseUrl}/api/chat`, {
597
+ method: "POST",
598
+ headers: { "Content-Type": "application/json" },
599
+ body: JSON.stringify({
600
+ model,
601
+ messages,
602
+ tools: AGENT_TOOLS,
603
+ stream: false,
604
+ }),
605
+ });
606
+ if (!response.ok) {
607
+ throw new Error(`Ollama error: ${response.status}`);
608
+ }
609
+ return await response.json();
610
+ }
611
+
612
+ if (provider === "anthropic") {
613
+ const key = apiKey || process.env.ANTHROPIC_API_KEY;
614
+ if (!key) throw new Error("ANTHROPIC_API_KEY required");
615
+
616
+ const systemMsgs = messages.filter((m) => m.role === "system");
617
+ const otherMsgs = messages.filter((m) => m.role !== "system");
618
+
619
+ const anthropicTools = AGENT_TOOLS.map((t) => ({
620
+ name: t.function.name,
621
+ description: t.function.description,
622
+ input_schema: t.function.parameters,
623
+ }));
624
+
625
+ const body = {
626
+ model: model || "claude-sonnet-4-20250514",
627
+ max_tokens: 8192,
628
+ messages: otherMsgs,
629
+ tools: anthropicTools,
630
+ };
631
+ if (systemMsgs.length > 0) {
632
+ body.system = systemMsgs.map((m) => m.content).join("\n");
633
+ }
634
+
635
+ const url =
636
+ baseUrl && baseUrl !== "http://localhost:11434"
637
+ ? baseUrl
638
+ : "https://api.anthropic.com/v1";
639
+
640
+ const response = await fetch(`${url}/messages`, {
641
+ method: "POST",
642
+ headers: {
643
+ "Content-Type": "application/json",
644
+ "x-api-key": key,
645
+ "anthropic-version": "2023-06-01",
646
+ },
647
+ body: JSON.stringify(body),
648
+ });
649
+
650
+ if (!response.ok) {
651
+ throw new Error(`Anthropic error: ${response.status}`);
652
+ }
653
+
654
+ const data = await response.json();
655
+ return _normalizeAnthropicResponse(data);
656
+ }
657
+
658
+ // OpenAI-compatible providers
659
+ const providerUrls = {
660
+ openai: "https://api.openai.com/v1",
661
+ deepseek: "https://api.deepseek.com/v1",
662
+ dashscope: "https://dashscope.aliyuncs.com/compatible-mode/v1",
663
+ mistral: "https://api.mistral.ai/v1",
664
+ gemini: "https://generativelanguage.googleapis.com/v1beta/openai",
665
+ volcengine: "https://ark.cn-beijing.volces.com/api/v3",
666
+ };
667
+
668
+ const providerApiKeyEnvs = {
669
+ openai: "OPENAI_API_KEY",
670
+ deepseek: "DEEPSEEK_API_KEY",
671
+ dashscope: "DASHSCOPE_API_KEY",
672
+ mistral: "MISTRAL_API_KEY",
673
+ gemini: "GEMINI_API_KEY",
674
+ volcengine: "VOLCENGINE_API_KEY",
675
+ };
676
+
677
+ const url =
678
+ baseUrl && baseUrl !== "http://localhost:11434"
679
+ ? baseUrl
680
+ : providerUrls[provider];
681
+
682
+ if (!url) {
683
+ throw new Error(
684
+ `Unsupported provider: ${provider}. Supported: ollama, anthropic, openai, deepseek, dashscope, mistral, gemini, volcengine`,
685
+ );
686
+ }
687
+
688
+ const envKey = providerApiKeyEnvs[provider] || "OPENAI_API_KEY";
689
+ const key = apiKey || process.env[envKey];
690
+ if (!key) throw new Error(`${envKey} required for provider ${provider}`);
691
+
692
+ const defaultModels = {
693
+ openai: "gpt-4o",
694
+ deepseek: "deepseek-chat",
695
+ dashscope: "qwen-turbo",
696
+ mistral: "mistral-large-latest",
697
+ gemini: "gemini-2.0-flash",
698
+ volcengine: "doubao-seed-1-6-251015",
699
+ };
700
+
701
+ const response = await fetch(`${url}/chat/completions`, {
702
+ method: "POST",
703
+ headers: {
704
+ "Content-Type": "application/json",
705
+ Authorization: `Bearer ${key}`,
706
+ },
707
+ body: JSON.stringify({
708
+ model: model || defaultModels[provider] || "gpt-4o-mini",
709
+ messages,
710
+ tools: AGENT_TOOLS,
711
+ }),
712
+ });
713
+
714
+ if (!response.ok) {
715
+ throw new Error(`${provider} API error: ${response.status}`);
716
+ }
717
+
718
+ const data = await response.json();
719
+ if (!data.choices || !data.choices[0]) {
720
+ throw new Error("Invalid API response: no choices returned");
721
+ }
722
+ const choice = data.choices[0];
723
+ return { message: choice.message };
724
+ }
725
+
726
+ function _normalizeAnthropicResponse(data) {
727
+ const content = data.content || [];
728
+ const textBlocks = content.filter((b) => b.type === "text");
729
+ const toolBlocks = content.filter((b) => b.type === "tool_use");
730
+
731
+ const message = {
732
+ role: "assistant",
733
+ content: textBlocks.map((b) => b.text).join("\n") || "",
734
+ };
735
+
736
+ if (toolBlocks.length > 0) {
737
+ message.tool_calls = toolBlocks.map((b) => ({
738
+ id: b.id,
739
+ type: "function",
740
+ function: {
741
+ name: b.name,
742
+ arguments: JSON.stringify(b.input),
743
+ },
744
+ }));
745
+ }
746
+
747
+ return { message };
748
+ }
749
+
750
+ // ─── Agent loop (async generator) ─────────────────────────────────────────
751
+
752
+ /**
753
+ * Async generator that drives the agentic tool-use loop.
754
+ *
755
+ * Yields events:
756
+ * { type: "tool-executing", tool, args }
757
+ * { type: "tool-result", tool, result, error }
758
+ * { type: "response-complete", content }
759
+ *
760
+ * @param {Array} messages - mutable messages array (will be appended to)
761
+ * @param {object} options - provider, model, baseUrl, apiKey, contextEngine, hookDb, skillLoader, cwd
762
+ */
763
+ export async function* agentLoop(messages, options) {
764
+ const MAX_ITERATIONS = 15;
765
+ const toolContext = {
766
+ hookDb: options.hookDb || null,
767
+ skillLoader: options.skillLoader || _defaultSkillLoader,
768
+ cwd: options.cwd || process.cwd(),
769
+ };
770
+
771
+ for (let i = 0; i < MAX_ITERATIONS; i++) {
772
+ const result = await chatWithTools(messages, options);
773
+ const msg = result?.message;
774
+
775
+ if (!msg) {
776
+ yield { type: "response-complete", content: "(No response from LLM)" };
777
+ return;
778
+ }
779
+
780
+ const toolCalls = msg.tool_calls;
781
+
782
+ if (!toolCalls || toolCalls.length === 0) {
783
+ yield { type: "response-complete", content: msg.content || "" };
784
+ return;
785
+ }
786
+
787
+ // Add assistant message with tool calls
788
+ messages.push(msg);
789
+
790
+ for (const call of toolCalls) {
791
+ const fn = call.function;
792
+ const toolName = fn.name;
793
+ let toolArgs;
794
+
795
+ try {
796
+ toolArgs =
797
+ typeof fn.arguments === "string"
798
+ ? JSON.parse(fn.arguments)
799
+ : fn.arguments;
800
+ } catch {
801
+ toolArgs = {};
802
+ }
803
+
804
+ yield { type: "tool-executing", tool: toolName, args: toolArgs };
805
+
806
+ let toolResult;
807
+ let toolError = null;
808
+ try {
809
+ toolResult = await executeTool(toolName, toolArgs, toolContext);
810
+ } catch (err) {
811
+ toolResult = { error: err.message };
812
+ toolError = err.message;
813
+ }
814
+
815
+ yield {
816
+ type: "tool-result",
817
+ tool: toolName,
818
+ result: toolResult,
819
+ error: toolError,
820
+ };
821
+
822
+ messages.push({
823
+ role: "tool",
824
+ content: JSON.stringify(toolResult).substring(0, 5000),
825
+ tool_call_id: call.id,
826
+ });
827
+ }
828
+ }
829
+
830
+ yield {
831
+ type: "response-complete",
832
+ content: "(Reached max tool call iterations)",
833
+ };
834
+ }
835
+
836
+ // ─── Format helpers ───────────────────────────────────────────────────────
837
+
838
+ export function formatToolArgs(name, args) {
839
+ switch (name) {
840
+ case "read_file":
841
+ return args.path;
842
+ case "write_file":
843
+ return `${args.path} (${args.content?.length || 0} chars)`;
844
+ case "edit_file":
845
+ return args.path;
846
+ case "run_shell":
847
+ return args.command;
848
+ case "search_files":
849
+ return args.pattern;
850
+ case "list_dir":
851
+ return args.path || ".";
852
+ case "run_skill":
853
+ return `${args.skill_name}: ${(args.input || "").substring(0, 50)}`;
854
+ case "list_skills":
855
+ return args.category || args.query || "all";
856
+ case "run_code":
857
+ return `${args.language} (${(args.code || "").length} chars)`;
858
+ default:
859
+ return JSON.stringify(args).substring(0, 60);
860
+ }
861
+ }