sparkecoder 0.1.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,1366 @@
1
+ // src/tools/bash.ts
2
+ import { tool } from "ai";
3
+ import { z } from "zod";
4
+ import { exec } from "child_process";
5
+ import { promisify } from "util";
6
+
7
+ // src/utils/truncate.ts
8
+ var MAX_OUTPUT_CHARS = 1e4;
9
+ function truncateOutput(output, maxChars = MAX_OUTPUT_CHARS) {
10
+ if (output.length <= maxChars) {
11
+ return output;
12
+ }
13
+ const halfMax = Math.floor(maxChars / 2);
14
+ const truncatedChars = output.length - maxChars;
15
+ return output.slice(0, halfMax) + `
16
+
17
+ ... [TRUNCATED: ${truncatedChars.toLocaleString()} characters omitted] ...
18
+
19
+ ` + output.slice(-halfMax);
20
+ }
21
+
22
+ // src/tools/bash.ts
23
+ var execAsync = promisify(exec);
24
+ var COMMAND_TIMEOUT = 6e4;
25
+ var MAX_OUTPUT_CHARS2 = 1e4;
26
+ var BLOCKED_COMMANDS = [
27
+ "rm -rf /",
28
+ "rm -rf ~",
29
+ "mkfs",
30
+ "dd if=/dev/zero",
31
+ ":(){:|:&};:",
32
+ "chmod -R 777 /"
33
+ ];
34
+ function isBlockedCommand(command) {
35
+ const normalizedCommand = command.toLowerCase().trim();
36
+ return BLOCKED_COMMANDS.some(
37
+ (blocked) => normalizedCommand.includes(blocked.toLowerCase())
38
+ );
39
+ }
40
+ var bashInputSchema = z.object({
41
+ command: z.string().describe("The bash command to execute. Can be a single command or a pipeline.")
42
+ });
43
+ function createBashTool(options) {
44
+ return tool({
45
+ description: `Execute a bash command in the terminal. The command runs in the working directory: ${options.workingDirectory}.
46
+ Use this for running shell commands, scripts, git operations, package managers (npm, pip, etc.), and other CLI tools.
47
+ Long outputs will be automatically truncated. Commands have a 60 second timeout.
48
+ IMPORTANT: Avoid destructive commands. Be careful with rm, chmod, and similar operations.`,
49
+ inputSchema: bashInputSchema,
50
+ execute: async ({ command }) => {
51
+ if (isBlockedCommand(command)) {
52
+ return {
53
+ success: false,
54
+ error: "This command is blocked for safety reasons.",
55
+ stdout: "",
56
+ stderr: "",
57
+ exitCode: 1
58
+ };
59
+ }
60
+ try {
61
+ const { stdout, stderr } = await execAsync(command, {
62
+ cwd: options.workingDirectory,
63
+ timeout: COMMAND_TIMEOUT,
64
+ maxBuffer: 10 * 1024 * 1024,
65
+ // 10MB buffer
66
+ shell: "/bin/bash"
67
+ });
68
+ const truncatedStdout = truncateOutput(stdout, MAX_OUTPUT_CHARS2);
69
+ const truncatedStderr = truncateOutput(stderr, MAX_OUTPUT_CHARS2 / 2);
70
+ if (options.onOutput) {
71
+ options.onOutput(truncatedStdout);
72
+ }
73
+ return {
74
+ success: true,
75
+ stdout: truncatedStdout,
76
+ stderr: truncatedStderr,
77
+ exitCode: 0
78
+ };
79
+ } catch (error) {
80
+ const stdout = error.stdout ? truncateOutput(error.stdout, MAX_OUTPUT_CHARS2) : "";
81
+ const stderr = error.stderr ? truncateOutput(error.stderr, MAX_OUTPUT_CHARS2) : "";
82
+ if (options.onOutput) {
83
+ options.onOutput(stderr || error.message);
84
+ }
85
+ if (error.killed) {
86
+ return {
87
+ success: false,
88
+ error: `Command timed out after ${COMMAND_TIMEOUT / 1e3} seconds`,
89
+ stdout,
90
+ stderr,
91
+ exitCode: 124
92
+ // Standard timeout exit code
93
+ };
94
+ }
95
+ return {
96
+ success: false,
97
+ error: error.message,
98
+ stdout,
99
+ stderr,
100
+ exitCode: error.code ?? 1
101
+ };
102
+ }
103
+ }
104
+ });
105
+ }
106
+
107
+ // src/tools/read-file.ts
108
+ import { tool as tool2 } from "ai";
109
+ import { z as z2 } from "zod";
110
+ import { readFile, stat } from "fs/promises";
111
+ import { resolve, relative, isAbsolute } from "path";
112
+ import { existsSync } from "fs";
113
+ var MAX_FILE_SIZE = 5 * 1024 * 1024;
114
+ var MAX_OUTPUT_CHARS3 = 5e4;
115
+ var readFileInputSchema = z2.object({
116
+ path: z2.string().describe("The path to the file to read. Can be relative to working directory or absolute."),
117
+ startLine: z2.number().optional().describe("Optional: Start reading from this line number (1-indexed)"),
118
+ endLine: z2.number().optional().describe("Optional: Stop reading at this line number (1-indexed, inclusive)")
119
+ });
120
+ function createReadFileTool(options) {
121
+ return tool2({
122
+ description: `Read the contents of a file. Provide a path relative to the working directory (${options.workingDirectory}) or an absolute path.
123
+ Large files will be automatically truncated. Binary files are not supported.
124
+ Use this to understand existing code, check file contents, or gather context.`,
125
+ inputSchema: readFileInputSchema,
126
+ execute: async ({ path, startLine, endLine }) => {
127
+ try {
128
+ const absolutePath = isAbsolute(path) ? path : resolve(options.workingDirectory, path);
129
+ const relativePath = relative(options.workingDirectory, absolutePath);
130
+ if (relativePath.startsWith("..") && !isAbsolute(path)) {
131
+ return {
132
+ success: false,
133
+ error: "Path escapes the working directory. Use an absolute path if intentional.",
134
+ content: null
135
+ };
136
+ }
137
+ if (!existsSync(absolutePath)) {
138
+ return {
139
+ success: false,
140
+ error: `File not found: ${path}`,
141
+ content: null
142
+ };
143
+ }
144
+ const stats = await stat(absolutePath);
145
+ if (stats.size > MAX_FILE_SIZE) {
146
+ return {
147
+ success: false,
148
+ error: `File is too large (${(stats.size / 1024 / 1024).toFixed(2)}MB). Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB.`,
149
+ content: null
150
+ };
151
+ }
152
+ if (stats.isDirectory()) {
153
+ return {
154
+ success: false,
155
+ error: 'Path is a directory, not a file. Use bash with "ls" to list directory contents.',
156
+ content: null
157
+ };
158
+ }
159
+ let content = await readFile(absolutePath, "utf-8");
160
+ if (startLine !== void 0 || endLine !== void 0) {
161
+ const lines = content.split("\n");
162
+ const start = (startLine ?? 1) - 1;
163
+ const end = endLine ?? lines.length;
164
+ if (start < 0 || start >= lines.length) {
165
+ return {
166
+ success: false,
167
+ error: `Start line ${startLine} is out of range. File has ${lines.length} lines.`,
168
+ content: null
169
+ };
170
+ }
171
+ content = lines.slice(start, end).join("\n");
172
+ const lineNumbers = lines.slice(start, end).map((line, idx) => `${(start + idx + 1).toString().padStart(4)}: ${line}`).join("\n");
173
+ content = lineNumbers;
174
+ }
175
+ const truncatedContent = truncateOutput(content, MAX_OUTPUT_CHARS3);
176
+ const wasTruncated = truncatedContent.length < content.length;
177
+ return {
178
+ success: true,
179
+ path: absolutePath,
180
+ relativePath: relative(options.workingDirectory, absolutePath),
181
+ content: truncatedContent,
182
+ lineCount: content.split("\n").length,
183
+ wasTruncated,
184
+ sizeBytes: stats.size
185
+ };
186
+ } catch (error) {
187
+ if (error.code === "ERR_INVALID_ARG_VALUE" || error.message.includes("encoding")) {
188
+ return {
189
+ success: false,
190
+ error: "File appears to be binary and cannot be read as text.",
191
+ content: null
192
+ };
193
+ }
194
+ return {
195
+ success: false,
196
+ error: error.message,
197
+ content: null
198
+ };
199
+ }
200
+ }
201
+ });
202
+ }
203
+
204
+ // src/tools/write-file.ts
205
+ import { tool as tool3 } from "ai";
206
+ import { z as z3 } from "zod";
207
+ import { readFile as readFile2, writeFile, mkdir } from "fs/promises";
208
+ import { resolve as resolve2, relative as relative2, isAbsolute as isAbsolute2, dirname } from "path";
209
+ import { existsSync as existsSync2 } from "fs";
210
+ var writeFileInputSchema = z3.object({
211
+ path: z3.string().describe("The path to the file. Can be relative to working directory or absolute."),
212
+ mode: z3.enum(["full", "str_replace"]).describe('Write mode: "full" for complete file write, "str_replace" for targeted string replacement'),
213
+ content: z3.string().optional().describe('For "full" mode: The complete content to write to the file'),
214
+ old_string: z3.string().optional().describe('For "str_replace" mode: The exact string to find and replace'),
215
+ new_string: z3.string().optional().describe('For "str_replace" mode: The string to replace old_string with')
216
+ });
217
+ function createWriteFileTool(options) {
218
+ return tool3({
219
+ description: `Write content to a file. Supports two modes:
220
+ 1. "full" - Write the entire file content (creates new file or replaces existing)
221
+ 2. "str_replace" - Replace a specific string in an existing file (for precise edits)
222
+
223
+ For str_replace mode:
224
+ - Provide the exact string to find (old_string) and its replacement (new_string)
225
+ - The old_string must match EXACTLY (including whitespace and indentation)
226
+ - Only the first occurrence is replaced
227
+ - Use this for surgical edits to existing code
228
+
229
+ For full mode:
230
+ - Provide the complete file content
231
+ - Creates parent directories if they don't exist
232
+ - Use this for new files or complete rewrites
233
+
234
+ Working directory: ${options.workingDirectory}`,
235
+ inputSchema: writeFileInputSchema,
236
+ execute: async ({ path, mode, content, old_string, new_string }) => {
237
+ try {
238
+ const absolutePath = isAbsolute2(path) ? path : resolve2(options.workingDirectory, path);
239
+ const relativePath = relative2(options.workingDirectory, absolutePath);
240
+ if (relativePath.startsWith("..") && !isAbsolute2(path)) {
241
+ return {
242
+ success: false,
243
+ error: "Path escapes the working directory. Use an absolute path if intentional."
244
+ };
245
+ }
246
+ if (mode === "full") {
247
+ if (content === void 0) {
248
+ return {
249
+ success: false,
250
+ error: 'Content is required for "full" mode'
251
+ };
252
+ }
253
+ const dir = dirname(absolutePath);
254
+ if (!existsSync2(dir)) {
255
+ await mkdir(dir, { recursive: true });
256
+ }
257
+ const existed = existsSync2(absolutePath);
258
+ await writeFile(absolutePath, content, "utf-8");
259
+ return {
260
+ success: true,
261
+ path: absolutePath,
262
+ relativePath: relative2(options.workingDirectory, absolutePath),
263
+ mode: "full",
264
+ action: existed ? "replaced" : "created",
265
+ bytesWritten: Buffer.byteLength(content, "utf-8"),
266
+ lineCount: content.split("\n").length
267
+ };
268
+ } else if (mode === "str_replace") {
269
+ if (old_string === void 0 || new_string === void 0) {
270
+ return {
271
+ success: false,
272
+ error: 'Both old_string and new_string are required for "str_replace" mode'
273
+ };
274
+ }
275
+ if (!existsSync2(absolutePath)) {
276
+ return {
277
+ success: false,
278
+ error: `File not found: ${path}. Use "full" mode to create new files.`
279
+ };
280
+ }
281
+ const currentContent = await readFile2(absolutePath, "utf-8");
282
+ if (!currentContent.includes(old_string)) {
283
+ const lines = currentContent.split("\n");
284
+ const preview = lines.slice(0, 20).join("\n");
285
+ return {
286
+ success: false,
287
+ error: "old_string not found in file. The string must match EXACTLY including whitespace.",
288
+ hint: "Check for differences in indentation, line endings, or invisible characters.",
289
+ filePreview: lines.length > 20 ? `${preview}
290
+ ... (${lines.length - 20} more lines)` : preview
291
+ };
292
+ }
293
+ const occurrences = currentContent.split(old_string).length - 1;
294
+ if (occurrences > 1) {
295
+ return {
296
+ success: false,
297
+ error: `Found ${occurrences} occurrences of old_string. Please provide more context to make it unique.`,
298
+ hint: "Include surrounding lines or more specific content in old_string."
299
+ };
300
+ }
301
+ const newContent = currentContent.replace(old_string, new_string);
302
+ await writeFile(absolutePath, newContent, "utf-8");
303
+ const oldLines = old_string.split("\n").length;
304
+ const newLines = new_string.split("\n").length;
305
+ return {
306
+ success: true,
307
+ path: absolutePath,
308
+ relativePath: relative2(options.workingDirectory, absolutePath),
309
+ mode: "str_replace",
310
+ linesRemoved: oldLines,
311
+ linesAdded: newLines,
312
+ lineDelta: newLines - oldLines
313
+ };
314
+ }
315
+ return {
316
+ success: false,
317
+ error: `Invalid mode: ${mode}`
318
+ };
319
+ } catch (error) {
320
+ return {
321
+ success: false,
322
+ error: error.message
323
+ };
324
+ }
325
+ }
326
+ });
327
+ }
328
+
329
+ // src/tools/todo.ts
330
+ import { tool as tool4 } from "ai";
331
+ import { z as z4 } from "zod";
332
+
333
+ // src/db/index.ts
334
+ import Database from "better-sqlite3";
335
+ import { drizzle } from "drizzle-orm/better-sqlite3";
336
+ import { eq, desc, and, sql } from "drizzle-orm";
337
+ import { nanoid } from "nanoid";
338
+
339
+ // src/db/schema.ts
340
+ import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
341
+ var sessions = sqliteTable("sessions", {
342
+ id: text("id").primaryKey(),
343
+ name: text("name"),
344
+ workingDirectory: text("working_directory").notNull(),
345
+ model: text("model").notNull(),
346
+ status: text("status", { enum: ["active", "waiting", "completed", "error"] }).notNull().default("active"),
347
+ config: text("config", { mode: "json" }).$type(),
348
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
349
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
350
+ });
351
+ var messages = sqliteTable("messages", {
352
+ id: text("id").primaryKey(),
353
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
354
+ // Store the entire ModelMessage as JSON (role + content)
355
+ modelMessage: text("model_message", { mode: "json" }).$type().notNull(),
356
+ // Sequence number within session to maintain exact ordering
357
+ sequence: integer("sequence").notNull().default(0),
358
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
359
+ });
360
+ var toolExecutions = sqliteTable("tool_executions", {
361
+ id: text("id").primaryKey(),
362
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
363
+ messageId: text("message_id").references(() => messages.id, { onDelete: "cascade" }),
364
+ toolName: text("tool_name").notNull(),
365
+ toolCallId: text("tool_call_id").notNull(),
366
+ input: text("input", { mode: "json" }),
367
+ output: text("output", { mode: "json" }),
368
+ status: text("status", { enum: ["pending", "approved", "rejected", "completed", "error"] }).notNull().default("pending"),
369
+ requiresApproval: integer("requires_approval", { mode: "boolean" }).notNull().default(false),
370
+ error: text("error"),
371
+ startedAt: integer("started_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
372
+ completedAt: integer("completed_at", { mode: "timestamp" })
373
+ });
374
+ var todoItems = sqliteTable("todo_items", {
375
+ id: text("id").primaryKey(),
376
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
377
+ content: text("content").notNull(),
378
+ status: text("status", { enum: ["pending", "in_progress", "completed", "cancelled"] }).notNull().default("pending"),
379
+ order: integer("order").notNull().default(0),
380
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
381
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
382
+ });
383
+ var loadedSkills = sqliteTable("loaded_skills", {
384
+ id: text("id").primaryKey(),
385
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
386
+ skillName: text("skill_name").notNull(),
387
+ loadedAt: integer("loaded_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
388
+ });
389
+ var terminals = sqliteTable("terminals", {
390
+ id: text("id").primaryKey(),
391
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
392
+ name: text("name"),
393
+ // Optional friendly name (e.g., "dev-server")
394
+ command: text("command").notNull(),
395
+ // The command that was run
396
+ cwd: text("cwd").notNull(),
397
+ // Working directory
398
+ pid: integer("pid"),
399
+ // Process ID (null if not running)
400
+ status: text("status", { enum: ["running", "stopped", "error"] }).notNull().default("running"),
401
+ exitCode: integer("exit_code"),
402
+ // Exit code if stopped
403
+ error: text("error"),
404
+ // Error message if status is 'error'
405
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
406
+ stoppedAt: integer("stopped_at", { mode: "timestamp" })
407
+ });
408
+
409
+ // src/db/index.ts
410
+ var db = null;
411
+ function getDb() {
412
+ if (!db) {
413
+ throw new Error("Database not initialized. Call initDatabase first.");
414
+ }
415
+ return db;
416
+ }
417
+ var todoQueries = {
418
+ create(data) {
419
+ const id = nanoid();
420
+ const now = /* @__PURE__ */ new Date();
421
+ const result = getDb().insert(todoItems).values({
422
+ id,
423
+ ...data,
424
+ createdAt: now,
425
+ updatedAt: now
426
+ }).returning().get();
427
+ return result;
428
+ },
429
+ createMany(sessionId, items) {
430
+ const now = /* @__PURE__ */ new Date();
431
+ const values = items.map((item, index) => ({
432
+ id: nanoid(),
433
+ sessionId,
434
+ content: item.content,
435
+ order: item.order ?? index,
436
+ createdAt: now,
437
+ updatedAt: now
438
+ }));
439
+ return getDb().insert(todoItems).values(values).returning().all();
440
+ },
441
+ getBySession(sessionId) {
442
+ return getDb().select().from(todoItems).where(eq(todoItems.sessionId, sessionId)).orderBy(todoItems.order).all();
443
+ },
444
+ updateStatus(id, status) {
445
+ return getDb().update(todoItems).set({ status, updatedAt: /* @__PURE__ */ new Date() }).where(eq(todoItems.id, id)).returning().get();
446
+ },
447
+ delete(id) {
448
+ const result = getDb().delete(todoItems).where(eq(todoItems.id, id)).run();
449
+ return result.changes > 0;
450
+ },
451
+ clearSession(sessionId) {
452
+ const result = getDb().delete(todoItems).where(eq(todoItems.sessionId, sessionId)).run();
453
+ return result.changes;
454
+ }
455
+ };
456
+ var skillQueries = {
457
+ load(sessionId, skillName) {
458
+ const id = nanoid();
459
+ const result = getDb().insert(loadedSkills).values({
460
+ id,
461
+ sessionId,
462
+ skillName,
463
+ loadedAt: /* @__PURE__ */ new Date()
464
+ }).returning().get();
465
+ return result;
466
+ },
467
+ getBySession(sessionId) {
468
+ return getDb().select().from(loadedSkills).where(eq(loadedSkills.sessionId, sessionId)).orderBy(loadedSkills.loadedAt).all();
469
+ },
470
+ isLoaded(sessionId, skillName) {
471
+ const result = getDb().select().from(loadedSkills).where(
472
+ and(
473
+ eq(loadedSkills.sessionId, sessionId),
474
+ eq(loadedSkills.skillName, skillName)
475
+ )
476
+ ).get();
477
+ return !!result;
478
+ }
479
+ };
480
+ var terminalQueries = {
481
+ create(data) {
482
+ const id = nanoid();
483
+ const result = getDb().insert(terminals).values({
484
+ id,
485
+ ...data,
486
+ createdAt: /* @__PURE__ */ new Date()
487
+ }).returning().get();
488
+ return result;
489
+ },
490
+ getById(id) {
491
+ return getDb().select().from(terminals).where(eq(terminals.id, id)).get();
492
+ },
493
+ getBySession(sessionId) {
494
+ return getDb().select().from(terminals).where(eq(terminals.sessionId, sessionId)).orderBy(desc(terminals.createdAt)).all();
495
+ },
496
+ getRunning(sessionId) {
497
+ return getDb().select().from(terminals).where(
498
+ and(
499
+ eq(terminals.sessionId, sessionId),
500
+ eq(terminals.status, "running")
501
+ )
502
+ ).all();
503
+ },
504
+ updateStatus(id, status, exitCode, error) {
505
+ return getDb().update(terminals).set({
506
+ status,
507
+ exitCode,
508
+ error,
509
+ stoppedAt: status !== "running" ? /* @__PURE__ */ new Date() : void 0
510
+ }).where(eq(terminals.id, id)).returning().get();
511
+ },
512
+ updatePid(id, pid) {
513
+ return getDb().update(terminals).set({ pid }).where(eq(terminals.id, id)).returning().get();
514
+ },
515
+ delete(id) {
516
+ const result = getDb().delete(terminals).where(eq(terminals.id, id)).run();
517
+ return result.changes > 0;
518
+ },
519
+ deleteBySession(sessionId) {
520
+ const result = getDb().delete(terminals).where(eq(terminals.sessionId, sessionId)).run();
521
+ return result.changes;
522
+ }
523
+ };
524
+
525
+ // src/tools/todo.ts
526
+ var todoInputSchema = z4.object({
527
+ action: z4.enum(["add", "list", "mark", "clear"]).describe("The action to perform on the todo list"),
528
+ items: z4.array(
529
+ z4.object({
530
+ content: z4.string().describe("Description of the task"),
531
+ order: z4.number().optional().describe("Optional order/priority (lower = higher priority)")
532
+ })
533
+ ).optional().describe('For "add" action: Array of todo items to add'),
534
+ todoId: z4.string().optional().describe('For "mark" action: The ID of the todo item to update'),
535
+ status: z4.enum(["pending", "in_progress", "completed", "cancelled"]).optional().describe('For "mark" action: The new status for the todo item')
536
+ });
537
+ function createTodoTool(options) {
538
+ return tool4({
539
+ description: `Manage your task list for the current session. Use this to:
540
+ - Break down complex tasks into smaller steps
541
+ - Track progress on multi-step operations
542
+ - Organize your work systematically
543
+
544
+ Available actions:
545
+ - "add": Add one or more new todo items to the list
546
+ - "list": View all current todo items and their status
547
+ - "mark": Update the status of a todo item (pending, in_progress, completed, cancelled)
548
+ - "clear": Remove all todo items from the list
549
+
550
+ Best practices:
551
+ - Add todos before starting complex tasks
552
+ - Mark items as "in_progress" when actively working on them
553
+ - Update status as you complete each step`,
554
+ inputSchema: todoInputSchema,
555
+ execute: async ({ action, items, todoId, status }) => {
556
+ try {
557
+ switch (action) {
558
+ case "add": {
559
+ if (!items || items.length === 0) {
560
+ return {
561
+ success: false,
562
+ error: "No items provided. Include at least one todo item."
563
+ };
564
+ }
565
+ const created = todoQueries.createMany(options.sessionId, items);
566
+ return {
567
+ success: true,
568
+ action: "add",
569
+ itemsAdded: created.length,
570
+ items: created.map(formatTodoItem)
571
+ };
572
+ }
573
+ case "list": {
574
+ const todos = todoQueries.getBySession(options.sessionId);
575
+ const stats = {
576
+ total: todos.length,
577
+ pending: todos.filter((t) => t.status === "pending").length,
578
+ inProgress: todos.filter((t) => t.status === "in_progress").length,
579
+ completed: todos.filter((t) => t.status === "completed").length,
580
+ cancelled: todos.filter((t) => t.status === "cancelled").length
581
+ };
582
+ return {
583
+ success: true,
584
+ action: "list",
585
+ stats,
586
+ items: todos.map(formatTodoItem)
587
+ };
588
+ }
589
+ case "mark": {
590
+ if (!todoId) {
591
+ return {
592
+ success: false,
593
+ error: 'todoId is required for "mark" action'
594
+ };
595
+ }
596
+ if (!status) {
597
+ return {
598
+ success: false,
599
+ error: 'status is required for "mark" action'
600
+ };
601
+ }
602
+ const updated = todoQueries.updateStatus(todoId, status);
603
+ if (!updated) {
604
+ return {
605
+ success: false,
606
+ error: `Todo item not found: ${todoId}`
607
+ };
608
+ }
609
+ return {
610
+ success: true,
611
+ action: "mark",
612
+ item: formatTodoItem(updated)
613
+ };
614
+ }
615
+ case "clear": {
616
+ const count = todoQueries.clearSession(options.sessionId);
617
+ return {
618
+ success: true,
619
+ action: "clear",
620
+ itemsRemoved: count
621
+ };
622
+ }
623
+ default:
624
+ return {
625
+ success: false,
626
+ error: `Unknown action: ${action}`
627
+ };
628
+ }
629
+ } catch (error) {
630
+ return {
631
+ success: false,
632
+ error: error.message
633
+ };
634
+ }
635
+ }
636
+ });
637
+ }
638
+ function formatTodoItem(item) {
639
+ return {
640
+ id: item.id,
641
+ content: item.content,
642
+ status: item.status,
643
+ order: item.order,
644
+ createdAt: item.createdAt.toISOString()
645
+ };
646
+ }
647
+
648
+ // src/tools/load-skill.ts
649
+ import { tool as tool5 } from "ai";
650
+ import { z as z6 } from "zod";
651
+
652
+ // src/skills/index.ts
653
+ import { readFile as readFile3, readdir } from "fs/promises";
654
+ import { resolve as resolve3, basename, extname } from "path";
655
+ import { existsSync as existsSync3 } from "fs";
656
+
657
+ // src/config/types.ts
658
+ import { z as z5 } from "zod";
659
+ var ToolApprovalConfigSchema = z5.object({
660
+ bash: z5.boolean().optional().default(true),
661
+ write_file: z5.boolean().optional().default(false),
662
+ read_file: z5.boolean().optional().default(false),
663
+ load_skill: z5.boolean().optional().default(false),
664
+ todo: z5.boolean().optional().default(false)
665
+ });
666
+ var SkillMetadataSchema = z5.object({
667
+ name: z5.string(),
668
+ description: z5.string()
669
+ });
670
+ var SessionConfigSchema = z5.object({
671
+ toolApprovals: z5.record(z5.string(), z5.boolean()).optional(),
672
+ approvalWebhook: z5.string().url().optional(),
673
+ skillsDirectory: z5.string().optional(),
674
+ maxContextChars: z5.number().optional().default(2e5)
675
+ });
676
+ var SparkcoderConfigSchema = z5.object({
677
+ // Default model to use (Vercel AI Gateway format)
678
+ defaultModel: z5.string().default("anthropic/claude-opus-4-5"),
679
+ // Working directory for file operations
680
+ workingDirectory: z5.string().optional(),
681
+ // Tool approval settings
682
+ toolApprovals: ToolApprovalConfigSchema.optional().default({}),
683
+ // Approval webhook URL (called when approval is needed)
684
+ approvalWebhook: z5.string().url().optional(),
685
+ // Skills configuration
686
+ skills: z5.object({
687
+ // Directory containing skill files
688
+ directory: z5.string().optional().default("./skills"),
689
+ // Additional skill directories to include
690
+ additionalDirectories: z5.array(z5.string()).optional().default([])
691
+ }).optional().default({}),
692
+ // Context management
693
+ context: z5.object({
694
+ // Maximum context size before summarization (in characters)
695
+ maxChars: z5.number().optional().default(2e5),
696
+ // Enable automatic summarization
697
+ autoSummarize: z5.boolean().optional().default(true),
698
+ // Number of recent messages to keep after summarization
699
+ keepRecentMessages: z5.number().optional().default(10)
700
+ }).optional().default({}),
701
+ // Server configuration
702
+ server: z5.object({
703
+ port: z5.number().default(3141),
704
+ host: z5.string().default("127.0.0.1")
705
+ }).default({ port: 3141, host: "127.0.0.1" }),
706
+ // Database path
707
+ databasePath: z5.string().optional().default("./sparkecoder.db")
708
+ });
709
+
710
+ // src/skills/index.ts
711
+ function parseSkillFrontmatter(content) {
712
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
713
+ if (!frontmatterMatch) {
714
+ return null;
715
+ }
716
+ const [, frontmatter, body] = frontmatterMatch;
717
+ try {
718
+ const lines = frontmatter.split("\n");
719
+ const data = {};
720
+ for (const line of lines) {
721
+ const colonIndex = line.indexOf(":");
722
+ if (colonIndex > 0) {
723
+ const key = line.slice(0, colonIndex).trim();
724
+ let value = line.slice(colonIndex + 1).trim();
725
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
726
+ value = value.slice(1, -1);
727
+ }
728
+ data[key] = value;
729
+ }
730
+ }
731
+ const metadata = SkillMetadataSchema.parse(data);
732
+ return { metadata, body: body.trim() };
733
+ } catch {
734
+ return null;
735
+ }
736
+ }
737
+ function getSkillNameFromPath(filePath) {
738
+ return basename(filePath, extname(filePath)).replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
739
+ }
740
+ async function loadSkillsFromDirectory(directory) {
741
+ if (!existsSync3(directory)) {
742
+ return [];
743
+ }
744
+ const skills = [];
745
+ const files = await readdir(directory);
746
+ for (const file of files) {
747
+ if (!file.endsWith(".md")) continue;
748
+ const filePath = resolve3(directory, file);
749
+ const content = await readFile3(filePath, "utf-8");
750
+ const parsed = parseSkillFrontmatter(content);
751
+ if (parsed) {
752
+ skills.push({
753
+ name: parsed.metadata.name,
754
+ description: parsed.metadata.description,
755
+ filePath
756
+ });
757
+ } else {
758
+ const name = getSkillNameFromPath(filePath);
759
+ const firstParagraph = content.split("\n\n")[0]?.slice(0, 200) || "No description";
760
+ skills.push({
761
+ name,
762
+ description: firstParagraph.replace(/^#\s*/, "").trim(),
763
+ filePath
764
+ });
765
+ }
766
+ }
767
+ return skills;
768
+ }
769
+ async function loadAllSkills(directories) {
770
+ const allSkills = [];
771
+ const seenNames = /* @__PURE__ */ new Set();
772
+ for (const dir of directories) {
773
+ const skills = await loadSkillsFromDirectory(dir);
774
+ for (const skill of skills) {
775
+ if (!seenNames.has(skill.name.toLowerCase())) {
776
+ seenNames.add(skill.name.toLowerCase());
777
+ allSkills.push(skill);
778
+ }
779
+ }
780
+ }
781
+ return allSkills;
782
+ }
783
+ async function loadSkillContent(skillName, directories) {
784
+ const allSkills = await loadAllSkills(directories);
785
+ const skill = allSkills.find(
786
+ (s) => s.name.toLowerCase() === skillName.toLowerCase()
787
+ );
788
+ if (!skill) {
789
+ return null;
790
+ }
791
+ const content = await readFile3(skill.filePath, "utf-8");
792
+ const parsed = parseSkillFrontmatter(content);
793
+ return {
794
+ ...skill,
795
+ content: parsed ? parsed.body : content
796
+ };
797
+ }
798
+ function formatSkillsForContext(skills) {
799
+ if (skills.length === 0) {
800
+ return "No skills available.";
801
+ }
802
+ const lines = ["Available skills (use load_skill tool to load into context):"];
803
+ for (const skill of skills) {
804
+ lines.push(`- ${skill.name}: ${skill.description}`);
805
+ }
806
+ return lines.join("\n");
807
+ }
808
+
809
+ // src/tools/load-skill.ts
810
+ var loadSkillInputSchema = z6.object({
811
+ action: z6.enum(["list", "load"]).describe('Action to perform: "list" to see available skills, "load" to load a skill'),
812
+ skillName: z6.string().optional().describe('For "load" action: The name of the skill to load')
813
+ });
814
+ function createLoadSkillTool(options) {
815
+ return tool5({
816
+ description: `Load a skill document into the conversation context. Skills are specialized knowledge files that provide guidance on specific topics like debugging, code review, architecture patterns, etc.
817
+
818
+ Available actions:
819
+ - "list": Show all available skills with their descriptions
820
+ - "load": Load a specific skill's full content into context
821
+
822
+ Use this when you need specialized knowledge or guidance for a particular task.
823
+ Once loaded, a skill's content will be available in the conversation context.`,
824
+ inputSchema: loadSkillInputSchema,
825
+ execute: async ({ action, skillName }) => {
826
+ try {
827
+ switch (action) {
828
+ case "list": {
829
+ const skills = await loadAllSkills(options.skillsDirectories);
830
+ return {
831
+ success: true,
832
+ action: "list",
833
+ skillCount: skills.length,
834
+ skills: skills.map((s) => ({
835
+ name: s.name,
836
+ description: s.description
837
+ })),
838
+ formatted: formatSkillsForContext(skills)
839
+ };
840
+ }
841
+ case "load": {
842
+ if (!skillName) {
843
+ return {
844
+ success: false,
845
+ error: 'skillName is required for "load" action'
846
+ };
847
+ }
848
+ if (skillQueries.isLoaded(options.sessionId, skillName)) {
849
+ return {
850
+ success: false,
851
+ error: `Skill "${skillName}" is already loaded in this session`
852
+ };
853
+ }
854
+ const skill = await loadSkillContent(skillName, options.skillsDirectories);
855
+ if (!skill) {
856
+ const allSkills = await loadAllSkills(options.skillsDirectories);
857
+ return {
858
+ success: false,
859
+ error: `Skill "${skillName}" not found`,
860
+ availableSkills: allSkills.map((s) => s.name)
861
+ };
862
+ }
863
+ skillQueries.load(options.sessionId, skillName);
864
+ return {
865
+ success: true,
866
+ action: "load",
867
+ skillName: skill.name,
868
+ description: skill.description,
869
+ content: skill.content,
870
+ contentLength: skill.content.length
871
+ };
872
+ }
873
+ default:
874
+ return {
875
+ success: false,
876
+ error: `Unknown action: ${action}`
877
+ };
878
+ }
879
+ } catch (error) {
880
+ return {
881
+ success: false,
882
+ error: error.message
883
+ };
884
+ }
885
+ }
886
+ });
887
+ }
888
+
889
+ // src/tools/terminal.ts
890
+ import { tool as tool6 } from "ai";
891
+ import { z as z7 } from "zod";
892
+
893
+ // src/terminal/manager.ts
894
+ import { spawn } from "child_process";
895
+ import { EventEmitter } from "events";
896
+ var LogBuffer = class {
897
+ buffer = [];
898
+ maxSize;
899
+ totalBytes = 0;
900
+ maxBytes;
901
+ constructor(maxBytes = 50 * 1024) {
902
+ this.maxBytes = maxBytes;
903
+ this.maxSize = 1e3;
904
+ }
905
+ append(data) {
906
+ const lines = data.split("\n");
907
+ for (const line of lines) {
908
+ if (line) {
909
+ this.buffer.push(line);
910
+ this.totalBytes += line.length;
911
+ }
912
+ }
913
+ while (this.totalBytes > this.maxBytes && this.buffer.length > 1) {
914
+ const removed = this.buffer.shift();
915
+ if (removed) {
916
+ this.totalBytes -= removed.length;
917
+ }
918
+ }
919
+ while (this.buffer.length > this.maxSize) {
920
+ const removed = this.buffer.shift();
921
+ if (removed) {
922
+ this.totalBytes -= removed.length;
923
+ }
924
+ }
925
+ }
926
+ getAll() {
927
+ return this.buffer.join("\n");
928
+ }
929
+ getTail(lines) {
930
+ const start = Math.max(0, this.buffer.length - lines);
931
+ return this.buffer.slice(start).join("\n");
932
+ }
933
+ clear() {
934
+ this.buffer = [];
935
+ this.totalBytes = 0;
936
+ }
937
+ get lineCount() {
938
+ return this.buffer.length;
939
+ }
940
+ };
941
+ var TerminalManager = class _TerminalManager extends EventEmitter {
942
+ processes = /* @__PURE__ */ new Map();
943
+ static instance = null;
944
+ constructor() {
945
+ super();
946
+ }
947
+ static getInstance() {
948
+ if (!_TerminalManager.instance) {
949
+ _TerminalManager.instance = new _TerminalManager();
950
+ }
951
+ return _TerminalManager.instance;
952
+ }
953
+ /**
954
+ * Spawn a new background process
955
+ */
956
+ spawn(options) {
957
+ const { sessionId, command, cwd, name, env } = options;
958
+ const parts = this.parseCommand(command);
959
+ const executable = parts[0];
960
+ const args = parts.slice(1);
961
+ const terminal = terminalQueries.create({
962
+ sessionId,
963
+ name: name || null,
964
+ command,
965
+ cwd: cwd || process.cwd(),
966
+ status: "running"
967
+ });
968
+ const proc = spawn(executable, args, {
969
+ cwd: cwd || process.cwd(),
970
+ shell: true,
971
+ stdio: ["pipe", "pipe", "pipe"],
972
+ env: { ...process.env, ...env },
973
+ detached: false
974
+ });
975
+ if (proc.pid) {
976
+ terminalQueries.updatePid(terminal.id, proc.pid);
977
+ }
978
+ const logs = new LogBuffer();
979
+ proc.stdout?.on("data", (data) => {
980
+ const text2 = data.toString();
981
+ logs.append(text2);
982
+ this.emit("stdout", { terminalId: terminal.id, data: text2 });
983
+ });
984
+ proc.stderr?.on("data", (data) => {
985
+ const text2 = data.toString();
986
+ logs.append(`[stderr] ${text2}`);
987
+ this.emit("stderr", { terminalId: terminal.id, data: text2 });
988
+ });
989
+ proc.on("exit", (code, signal) => {
990
+ const exitCode = code ?? (signal ? 128 : 0);
991
+ terminalQueries.updateStatus(terminal.id, "stopped", exitCode);
992
+ this.emit("exit", { terminalId: terminal.id, code: exitCode, signal });
993
+ const managed2 = this.processes.get(terminal.id);
994
+ if (managed2) {
995
+ managed2.terminal = { ...managed2.terminal, status: "stopped", exitCode };
996
+ }
997
+ });
998
+ proc.on("error", (err) => {
999
+ terminalQueries.updateStatus(terminal.id, "error", void 0, err.message);
1000
+ this.emit("error", { terminalId: terminal.id, error: err.message });
1001
+ const managed2 = this.processes.get(terminal.id);
1002
+ if (managed2) {
1003
+ managed2.terminal = { ...managed2.terminal, status: "error", error: err.message };
1004
+ }
1005
+ });
1006
+ const managed = {
1007
+ id: terminal.id,
1008
+ process: proc,
1009
+ logs,
1010
+ terminal: { ...terminal, pid: proc.pid ?? null }
1011
+ };
1012
+ this.processes.set(terminal.id, managed);
1013
+ return this.toTerminalInfo(managed.terminal);
1014
+ }
1015
+ /**
1016
+ * Get logs from a terminal
1017
+ */
1018
+ getLogs(terminalId, tail) {
1019
+ const managed = this.processes.get(terminalId);
1020
+ if (!managed) {
1021
+ return null;
1022
+ }
1023
+ return {
1024
+ logs: tail ? managed.logs.getTail(tail) : managed.logs.getAll(),
1025
+ lineCount: managed.logs.lineCount
1026
+ };
1027
+ }
1028
+ /**
1029
+ * Get terminal status
1030
+ */
1031
+ getStatus(terminalId) {
1032
+ const managed = this.processes.get(terminalId);
1033
+ if (managed) {
1034
+ if (managed.process.exitCode !== null) {
1035
+ managed.terminal = {
1036
+ ...managed.terminal,
1037
+ status: "stopped",
1038
+ exitCode: managed.process.exitCode
1039
+ };
1040
+ }
1041
+ return this.toTerminalInfo(managed.terminal);
1042
+ }
1043
+ const terminal = terminalQueries.getById(terminalId);
1044
+ if (terminal) {
1045
+ return this.toTerminalInfo(terminal);
1046
+ }
1047
+ return null;
1048
+ }
1049
+ /**
1050
+ * Kill a terminal process
1051
+ */
1052
+ kill(terminalId, signal = "SIGTERM") {
1053
+ const managed = this.processes.get(terminalId);
1054
+ if (!managed) {
1055
+ return false;
1056
+ }
1057
+ try {
1058
+ managed.process.kill(signal);
1059
+ return true;
1060
+ } catch (err) {
1061
+ console.error(`Failed to kill terminal ${terminalId}:`, err);
1062
+ return false;
1063
+ }
1064
+ }
1065
+ /**
1066
+ * Write to a terminal's stdin
1067
+ */
1068
+ write(terminalId, input) {
1069
+ const managed = this.processes.get(terminalId);
1070
+ if (!managed || !managed.process.stdin) {
1071
+ return false;
1072
+ }
1073
+ try {
1074
+ managed.process.stdin.write(input);
1075
+ return true;
1076
+ } catch (err) {
1077
+ console.error(`Failed to write to terminal ${terminalId}:`, err);
1078
+ return false;
1079
+ }
1080
+ }
1081
+ /**
1082
+ * List all terminals for a session
1083
+ */
1084
+ list(sessionId) {
1085
+ const terminals2 = terminalQueries.getBySession(sessionId);
1086
+ return terminals2.map((t) => {
1087
+ const managed = this.processes.get(t.id);
1088
+ if (managed) {
1089
+ return this.toTerminalInfo(managed.terminal);
1090
+ }
1091
+ return this.toTerminalInfo(t);
1092
+ });
1093
+ }
1094
+ /**
1095
+ * Get all running terminals for a session
1096
+ */
1097
+ getRunning(sessionId) {
1098
+ return this.list(sessionId).filter((t) => t.status === "running");
1099
+ }
1100
+ /**
1101
+ * Kill all terminals for a session (cleanup)
1102
+ */
1103
+ killAll(sessionId) {
1104
+ let killed = 0;
1105
+ for (const [id, managed] of this.processes) {
1106
+ if (managed.terminal.sessionId === sessionId) {
1107
+ if (this.kill(id)) {
1108
+ killed++;
1109
+ }
1110
+ }
1111
+ }
1112
+ return killed;
1113
+ }
1114
+ /**
1115
+ * Clean up stopped terminals from memory (keep DB records)
1116
+ */
1117
+ cleanup(sessionId) {
1118
+ let cleaned = 0;
1119
+ for (const [id, managed] of this.processes) {
1120
+ if (sessionId && managed.terminal.sessionId !== sessionId) {
1121
+ continue;
1122
+ }
1123
+ if (managed.terminal.status !== "running") {
1124
+ this.processes.delete(id);
1125
+ cleaned++;
1126
+ }
1127
+ }
1128
+ return cleaned;
1129
+ }
1130
+ /**
1131
+ * Parse a command string into executable and arguments
1132
+ */
1133
+ parseCommand(command) {
1134
+ const parts = [];
1135
+ let current = "";
1136
+ let inQuote = false;
1137
+ let quoteChar = "";
1138
+ for (const char of command) {
1139
+ if ((char === '"' || char === "'") && !inQuote) {
1140
+ inQuote = true;
1141
+ quoteChar = char;
1142
+ } else if (char === quoteChar && inQuote) {
1143
+ inQuote = false;
1144
+ quoteChar = "";
1145
+ } else if (char === " " && !inQuote) {
1146
+ if (current) {
1147
+ parts.push(current);
1148
+ current = "";
1149
+ }
1150
+ } else {
1151
+ current += char;
1152
+ }
1153
+ }
1154
+ if (current) {
1155
+ parts.push(current);
1156
+ }
1157
+ return parts.length > 0 ? parts : [command];
1158
+ }
1159
+ toTerminalInfo(terminal) {
1160
+ return {
1161
+ id: terminal.id,
1162
+ name: terminal.name,
1163
+ command: terminal.command,
1164
+ cwd: terminal.cwd,
1165
+ pid: terminal.pid,
1166
+ status: terminal.status,
1167
+ exitCode: terminal.exitCode,
1168
+ error: terminal.error,
1169
+ createdAt: terminal.createdAt,
1170
+ stoppedAt: terminal.stoppedAt
1171
+ };
1172
+ }
1173
+ };
1174
+ function getTerminalManager() {
1175
+ return TerminalManager.getInstance();
1176
+ }
1177
+
1178
+ // src/tools/terminal.ts
1179
+ var TerminalInputSchema = z7.object({
1180
+ action: z7.enum(["spawn", "logs", "status", "kill", "write", "list"]).describe(
1181
+ "The action to perform: spawn (start process), logs (get output), status (check if running), kill (stop process), write (send stdin), list (show all)"
1182
+ ),
1183
+ // For spawn
1184
+ command: z7.string().optional().describe('For spawn: The command to run (e.g., "npm run dev")'),
1185
+ cwd: z7.string().optional().describe("For spawn: Working directory for the command"),
1186
+ name: z7.string().optional().describe('For spawn: Optional friendly name (e.g., "dev-server")'),
1187
+ // For logs, status, kill, write
1188
+ terminalId: z7.string().optional().describe("For logs/status/kill/write: The terminal ID"),
1189
+ tail: z7.number().optional().describe("For logs: Number of lines to return from the end"),
1190
+ // For kill
1191
+ signal: z7.enum(["SIGTERM", "SIGKILL"]).optional().describe("For kill: Signal to send (default: SIGTERM)"),
1192
+ // For write
1193
+ input: z7.string().optional().describe("For write: The input to send to stdin")
1194
+ });
1195
+ function createTerminalTool(options) {
1196
+ const { sessionId, workingDirectory } = options;
1197
+ return tool6({
1198
+ description: `Manage background terminal processes. Use this for long-running commands like dev servers, watchers, or any process that shouldn't block.
1199
+
1200
+ Actions:
1201
+ - spawn: Start a new background process. Requires 'command'. Returns terminal ID.
1202
+ - logs: Get output from a terminal. Requires 'terminalId'. Optional 'tail' for recent lines.
1203
+ - status: Check if a terminal is still running. Requires 'terminalId'.
1204
+ - kill: Stop a terminal process. Requires 'terminalId'. Optional 'signal'.
1205
+ - write: Send input to a terminal's stdin. Requires 'terminalId' and 'input'.
1206
+ - list: Show all terminals for this session. No other params needed.
1207
+
1208
+ Example workflow:
1209
+ 1. spawn with command="npm run dev", name="dev-server" \u2192 { id: "abc123", status: "running" }
1210
+ 2. logs with terminalId="abc123", tail=10 \u2192 "Ready on http://localhost:3000"
1211
+ 3. kill with terminalId="abc123" \u2192 { success: true }`,
1212
+ inputSchema: TerminalInputSchema,
1213
+ execute: async (input) => {
1214
+ const manager = getTerminalManager();
1215
+ switch (input.action) {
1216
+ case "spawn": {
1217
+ if (!input.command) {
1218
+ return { success: false, error: 'spawn requires a "command" parameter' };
1219
+ }
1220
+ const terminal = manager.spawn({
1221
+ sessionId,
1222
+ command: input.command,
1223
+ cwd: input.cwd || workingDirectory,
1224
+ name: input.name
1225
+ });
1226
+ return {
1227
+ success: true,
1228
+ terminal: formatTerminal(terminal),
1229
+ message: `Started "${input.command}" with terminal ID: ${terminal.id}`
1230
+ };
1231
+ }
1232
+ case "logs": {
1233
+ if (!input.terminalId) {
1234
+ return { success: false, error: 'logs requires a "terminalId" parameter' };
1235
+ }
1236
+ const result = manager.getLogs(input.terminalId, input.tail);
1237
+ if (!result) {
1238
+ return {
1239
+ success: false,
1240
+ error: `Terminal not found: ${input.terminalId}`
1241
+ };
1242
+ }
1243
+ return {
1244
+ success: true,
1245
+ terminalId: input.terminalId,
1246
+ logs: result.logs,
1247
+ lineCount: result.lineCount
1248
+ };
1249
+ }
1250
+ case "status": {
1251
+ if (!input.terminalId) {
1252
+ return { success: false, error: 'status requires a "terminalId" parameter' };
1253
+ }
1254
+ const status = manager.getStatus(input.terminalId);
1255
+ if (!status) {
1256
+ return {
1257
+ success: false,
1258
+ error: `Terminal not found: ${input.terminalId}`
1259
+ };
1260
+ }
1261
+ return {
1262
+ success: true,
1263
+ terminal: formatTerminal(status)
1264
+ };
1265
+ }
1266
+ case "kill": {
1267
+ if (!input.terminalId) {
1268
+ return { success: false, error: 'kill requires a "terminalId" parameter' };
1269
+ }
1270
+ const success = manager.kill(input.terminalId, input.signal);
1271
+ if (!success) {
1272
+ return {
1273
+ success: false,
1274
+ error: `Failed to kill terminal: ${input.terminalId}`
1275
+ };
1276
+ }
1277
+ return {
1278
+ success: true,
1279
+ message: `Sent ${input.signal || "SIGTERM"} to terminal ${input.terminalId}`
1280
+ };
1281
+ }
1282
+ case "write": {
1283
+ if (!input.terminalId) {
1284
+ return { success: false, error: 'write requires a "terminalId" parameter' };
1285
+ }
1286
+ if (!input.input) {
1287
+ return { success: false, error: 'write requires an "input" parameter' };
1288
+ }
1289
+ const success = manager.write(input.terminalId, input.input);
1290
+ if (!success) {
1291
+ return {
1292
+ success: false,
1293
+ error: `Failed to write to terminal: ${input.terminalId}`
1294
+ };
1295
+ }
1296
+ return {
1297
+ success: true,
1298
+ message: `Sent input to terminal ${input.terminalId}`
1299
+ };
1300
+ }
1301
+ case "list": {
1302
+ const terminals2 = manager.list(sessionId);
1303
+ return {
1304
+ success: true,
1305
+ terminals: terminals2.map(formatTerminal),
1306
+ count: terminals2.length,
1307
+ running: terminals2.filter((t) => t.status === "running").length
1308
+ };
1309
+ }
1310
+ default:
1311
+ return { success: false, error: `Unknown action: ${input.action}` };
1312
+ }
1313
+ }
1314
+ });
1315
+ }
1316
+ function formatTerminal(t) {
1317
+ return {
1318
+ id: t.id,
1319
+ name: t.name,
1320
+ command: t.command,
1321
+ cwd: t.cwd,
1322
+ pid: t.pid,
1323
+ status: t.status,
1324
+ exitCode: t.exitCode,
1325
+ error: t.error,
1326
+ createdAt: t.createdAt.toISOString(),
1327
+ stoppedAt: t.stoppedAt?.toISOString() || null
1328
+ };
1329
+ }
1330
+
1331
+ // src/tools/index.ts
1332
+ function createTools(options) {
1333
+ return {
1334
+ bash: createBashTool({
1335
+ workingDirectory: options.workingDirectory,
1336
+ onOutput: options.onBashOutput
1337
+ }),
1338
+ read_file: createReadFileTool({
1339
+ workingDirectory: options.workingDirectory
1340
+ }),
1341
+ write_file: createWriteFileTool({
1342
+ workingDirectory: options.workingDirectory
1343
+ }),
1344
+ todo: createTodoTool({
1345
+ sessionId: options.sessionId
1346
+ }),
1347
+ load_skill: createLoadSkillTool({
1348
+ sessionId: options.sessionId,
1349
+ skillsDirectories: options.skillsDirectories
1350
+ }),
1351
+ terminal: createTerminalTool({
1352
+ sessionId: options.sessionId,
1353
+ workingDirectory: options.workingDirectory
1354
+ })
1355
+ };
1356
+ }
1357
+ export {
1358
+ createBashTool,
1359
+ createLoadSkillTool,
1360
+ createReadFileTool,
1361
+ createTerminalTool,
1362
+ createTodoTool,
1363
+ createTools,
1364
+ createWriteFileTool
1365
+ };
1366
+ //# sourceMappingURL=index.js.map