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,3458 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/server/index.ts
8
+ import { Hono as Hono5 } from "hono";
9
+ import { serve } from "@hono/node-server";
10
+ import { cors } from "hono/cors";
11
+ import { logger } from "hono/logger";
12
+ import { existsSync as existsSync5, mkdirSync } from "fs";
13
+
14
+ // src/server/routes/sessions.ts
15
+ import { Hono } from "hono";
16
+ import { zValidator } from "@hono/zod-validator";
17
+ import { z as z9 } from "zod";
18
+
19
+ // src/db/index.ts
20
+ import Database from "better-sqlite3";
21
+ import { drizzle } from "drizzle-orm/better-sqlite3";
22
+ import { eq, desc, and, sql } from "drizzle-orm";
23
+ import { nanoid } from "nanoid";
24
+
25
+ // src/db/schema.ts
26
+ var schema_exports = {};
27
+ __export(schema_exports, {
28
+ loadedSkills: () => loadedSkills,
29
+ messages: () => messages,
30
+ sessions: () => sessions,
31
+ terminals: () => terminals,
32
+ todoItems: () => todoItems,
33
+ toolExecutions: () => toolExecutions
34
+ });
35
+ import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
36
+ var sessions = sqliteTable("sessions", {
37
+ id: text("id").primaryKey(),
38
+ name: text("name"),
39
+ workingDirectory: text("working_directory").notNull(),
40
+ model: text("model").notNull(),
41
+ status: text("status", { enum: ["active", "waiting", "completed", "error"] }).notNull().default("active"),
42
+ config: text("config", { mode: "json" }).$type(),
43
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
44
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
45
+ });
46
+ var messages = sqliteTable("messages", {
47
+ id: text("id").primaryKey(),
48
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
49
+ // Store the entire ModelMessage as JSON (role + content)
50
+ modelMessage: text("model_message", { mode: "json" }).$type().notNull(),
51
+ // Sequence number within session to maintain exact ordering
52
+ sequence: integer("sequence").notNull().default(0),
53
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
54
+ });
55
+ var toolExecutions = sqliteTable("tool_executions", {
56
+ id: text("id").primaryKey(),
57
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
58
+ messageId: text("message_id").references(() => messages.id, { onDelete: "cascade" }),
59
+ toolName: text("tool_name").notNull(),
60
+ toolCallId: text("tool_call_id").notNull(),
61
+ input: text("input", { mode: "json" }),
62
+ output: text("output", { mode: "json" }),
63
+ status: text("status", { enum: ["pending", "approved", "rejected", "completed", "error"] }).notNull().default("pending"),
64
+ requiresApproval: integer("requires_approval", { mode: "boolean" }).notNull().default(false),
65
+ error: text("error"),
66
+ startedAt: integer("started_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
67
+ completedAt: integer("completed_at", { mode: "timestamp" })
68
+ });
69
+ var todoItems = sqliteTable("todo_items", {
70
+ id: text("id").primaryKey(),
71
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
72
+ content: text("content").notNull(),
73
+ status: text("status", { enum: ["pending", "in_progress", "completed", "cancelled"] }).notNull().default("pending"),
74
+ order: integer("order").notNull().default(0),
75
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
76
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
77
+ });
78
+ var loadedSkills = sqliteTable("loaded_skills", {
79
+ id: text("id").primaryKey(),
80
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
81
+ skillName: text("skill_name").notNull(),
82
+ loadedAt: integer("loaded_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
83
+ });
84
+ var terminals = sqliteTable("terminals", {
85
+ id: text("id").primaryKey(),
86
+ sessionId: text("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
87
+ name: text("name"),
88
+ // Optional friendly name (e.g., "dev-server")
89
+ command: text("command").notNull(),
90
+ // The command that was run
91
+ cwd: text("cwd").notNull(),
92
+ // Working directory
93
+ pid: integer("pid"),
94
+ // Process ID (null if not running)
95
+ status: text("status", { enum: ["running", "stopped", "error"] }).notNull().default("running"),
96
+ exitCode: integer("exit_code"),
97
+ // Exit code if stopped
98
+ error: text("error"),
99
+ // Error message if status is 'error'
100
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
101
+ stoppedAt: integer("stopped_at", { mode: "timestamp" })
102
+ });
103
+
104
+ // src/db/index.ts
105
+ var db = null;
106
+ var sqlite = null;
107
+ function initDatabase(dbPath) {
108
+ sqlite = new Database(dbPath);
109
+ sqlite.pragma("journal_mode = WAL");
110
+ db = drizzle(sqlite, { schema: schema_exports });
111
+ sqlite.exec(`
112
+ DROP TABLE IF EXISTS terminals;
113
+ DROP TABLE IF EXISTS loaded_skills;
114
+ DROP TABLE IF EXISTS todo_items;
115
+ DROP TABLE IF EXISTS tool_executions;
116
+ DROP TABLE IF EXISTS messages;
117
+ DROP TABLE IF EXISTS sessions;
118
+
119
+ CREATE TABLE sessions (
120
+ id TEXT PRIMARY KEY,
121
+ name TEXT,
122
+ working_directory TEXT NOT NULL,
123
+ model TEXT NOT NULL,
124
+ status TEXT NOT NULL DEFAULT 'active',
125
+ config TEXT,
126
+ created_at INTEGER NOT NULL,
127
+ updated_at INTEGER NOT NULL
128
+ );
129
+
130
+ CREATE TABLE messages (
131
+ id TEXT PRIMARY KEY,
132
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
133
+ model_message TEXT NOT NULL,
134
+ sequence INTEGER NOT NULL DEFAULT 0,
135
+ created_at INTEGER NOT NULL
136
+ );
137
+
138
+ CREATE TABLE tool_executions (
139
+ id TEXT PRIMARY KEY,
140
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
141
+ message_id TEXT REFERENCES messages(id) ON DELETE CASCADE,
142
+ tool_name TEXT NOT NULL,
143
+ tool_call_id TEXT NOT NULL,
144
+ input TEXT,
145
+ output TEXT,
146
+ status TEXT NOT NULL DEFAULT 'pending',
147
+ requires_approval INTEGER NOT NULL DEFAULT 0,
148
+ error TEXT,
149
+ started_at INTEGER NOT NULL,
150
+ completed_at INTEGER
151
+ );
152
+
153
+ CREATE TABLE todo_items (
154
+ id TEXT PRIMARY KEY,
155
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
156
+ content TEXT NOT NULL,
157
+ status TEXT NOT NULL DEFAULT 'pending',
158
+ "order" INTEGER NOT NULL DEFAULT 0,
159
+ created_at INTEGER NOT NULL,
160
+ updated_at INTEGER NOT NULL
161
+ );
162
+
163
+ CREATE TABLE loaded_skills (
164
+ id TEXT PRIMARY KEY,
165
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
166
+ skill_name TEXT NOT NULL,
167
+ loaded_at INTEGER NOT NULL
168
+ );
169
+
170
+ CREATE TABLE terminals (
171
+ id TEXT PRIMARY KEY,
172
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
173
+ name TEXT,
174
+ command TEXT NOT NULL,
175
+ cwd TEXT NOT NULL,
176
+ pid INTEGER,
177
+ status TEXT NOT NULL DEFAULT 'running',
178
+ exit_code INTEGER,
179
+ error TEXT,
180
+ created_at INTEGER NOT NULL,
181
+ stopped_at INTEGER
182
+ );
183
+
184
+ CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id);
185
+ CREATE INDEX IF NOT EXISTS idx_tool_executions_session ON tool_executions(session_id);
186
+ CREATE INDEX IF NOT EXISTS idx_todo_items_session ON todo_items(session_id);
187
+ CREATE INDEX IF NOT EXISTS idx_loaded_skills_session ON loaded_skills(session_id);
188
+ CREATE INDEX IF NOT EXISTS idx_terminals_session ON terminals(session_id);
189
+ `);
190
+ return db;
191
+ }
192
+ function getDb() {
193
+ if (!db) {
194
+ throw new Error("Database not initialized. Call initDatabase first.");
195
+ }
196
+ return db;
197
+ }
198
+ function closeDatabase() {
199
+ if (sqlite) {
200
+ sqlite.close();
201
+ sqlite = null;
202
+ db = null;
203
+ }
204
+ }
205
+ var sessionQueries = {
206
+ create(data) {
207
+ const id = nanoid();
208
+ const now = /* @__PURE__ */ new Date();
209
+ const result = getDb().insert(sessions).values({
210
+ id,
211
+ ...data,
212
+ createdAt: now,
213
+ updatedAt: now
214
+ }).returning().get();
215
+ return result;
216
+ },
217
+ getById(id) {
218
+ return getDb().select().from(sessions).where(eq(sessions.id, id)).get();
219
+ },
220
+ list(limit = 50, offset = 0) {
221
+ return getDb().select().from(sessions).orderBy(desc(sessions.createdAt)).limit(limit).offset(offset).all();
222
+ },
223
+ updateStatus(id, status) {
224
+ return getDb().update(sessions).set({ status, updatedAt: /* @__PURE__ */ new Date() }).where(eq(sessions.id, id)).returning().get();
225
+ },
226
+ delete(id) {
227
+ const result = getDb().delete(sessions).where(eq(sessions.id, id)).run();
228
+ return result.changes > 0;
229
+ }
230
+ };
231
+ var messageQueries = {
232
+ /**
233
+ * Get the next sequence number for a session
234
+ */
235
+ getNextSequence(sessionId) {
236
+ const result = getDb().select({ maxSeq: sql`COALESCE(MAX(sequence), -1)` }).from(messages).where(eq(messages.sessionId, sessionId)).get();
237
+ return (result?.maxSeq ?? -1) + 1;
238
+ },
239
+ /**
240
+ * Create a single message from a ModelMessage
241
+ */
242
+ create(sessionId, modelMessage) {
243
+ const id = nanoid();
244
+ const sequence = this.getNextSequence(sessionId);
245
+ const result = getDb().insert(messages).values({
246
+ id,
247
+ sessionId,
248
+ modelMessage,
249
+ sequence,
250
+ createdAt: /* @__PURE__ */ new Date()
251
+ }).returning().get();
252
+ return result;
253
+ },
254
+ /**
255
+ * Add multiple ModelMessages at once (from response.messages)
256
+ * Maintains insertion order via sequence numbers
257
+ */
258
+ addMany(sessionId, modelMessages) {
259
+ const results = [];
260
+ let sequence = this.getNextSequence(sessionId);
261
+ for (const msg of modelMessages) {
262
+ const id = nanoid();
263
+ const result = getDb().insert(messages).values({
264
+ id,
265
+ sessionId,
266
+ modelMessage: msg,
267
+ sequence,
268
+ createdAt: /* @__PURE__ */ new Date()
269
+ }).returning().get();
270
+ results.push(result);
271
+ sequence++;
272
+ }
273
+ return results;
274
+ },
275
+ /**
276
+ * Get all messages for a session as ModelMessage[]
277
+ * Ordered by sequence to maintain exact insertion order
278
+ */
279
+ getBySession(sessionId) {
280
+ return getDb().select().from(messages).where(eq(messages.sessionId, sessionId)).orderBy(messages.sequence).all();
281
+ },
282
+ /**
283
+ * Get ModelMessages directly (for passing to AI SDK)
284
+ */
285
+ getModelMessages(sessionId) {
286
+ const messages2 = this.getBySession(sessionId);
287
+ return messages2.map((m) => m.modelMessage);
288
+ },
289
+ getRecentBySession(sessionId, limit = 50) {
290
+ return getDb().select().from(messages).where(eq(messages.sessionId, sessionId)).orderBy(desc(messages.sequence)).limit(limit).all().reverse();
291
+ },
292
+ countBySession(sessionId) {
293
+ const result = getDb().select({ count: sql`count(*)` }).from(messages).where(eq(messages.sessionId, sessionId)).get();
294
+ return result?.count ?? 0;
295
+ },
296
+ deleteBySession(sessionId) {
297
+ const result = getDb().delete(messages).where(eq(messages.sessionId, sessionId)).run();
298
+ return result.changes;
299
+ }
300
+ };
301
+ var toolExecutionQueries = {
302
+ create(data) {
303
+ const id = nanoid();
304
+ const result = getDb().insert(toolExecutions).values({
305
+ id,
306
+ ...data,
307
+ startedAt: /* @__PURE__ */ new Date()
308
+ }).returning().get();
309
+ return result;
310
+ },
311
+ getById(id) {
312
+ return getDb().select().from(toolExecutions).where(eq(toolExecutions.id, id)).get();
313
+ },
314
+ getByToolCallId(toolCallId) {
315
+ return getDb().select().from(toolExecutions).where(eq(toolExecutions.toolCallId, toolCallId)).get();
316
+ },
317
+ getPendingApprovals(sessionId) {
318
+ return getDb().select().from(toolExecutions).where(
319
+ and(
320
+ eq(toolExecutions.sessionId, sessionId),
321
+ eq(toolExecutions.status, "pending"),
322
+ eq(toolExecutions.requiresApproval, true)
323
+ )
324
+ ).all();
325
+ },
326
+ approve(id) {
327
+ return getDb().update(toolExecutions).set({ status: "approved" }).where(eq(toolExecutions.id, id)).returning().get();
328
+ },
329
+ reject(id) {
330
+ return getDb().update(toolExecutions).set({ status: "rejected" }).where(eq(toolExecutions.id, id)).returning().get();
331
+ },
332
+ complete(id, output, error) {
333
+ return getDb().update(toolExecutions).set({
334
+ status: error ? "error" : "completed",
335
+ output,
336
+ error,
337
+ completedAt: /* @__PURE__ */ new Date()
338
+ }).where(eq(toolExecutions.id, id)).returning().get();
339
+ },
340
+ getBySession(sessionId) {
341
+ return getDb().select().from(toolExecutions).where(eq(toolExecutions.sessionId, sessionId)).orderBy(toolExecutions.startedAt).all();
342
+ }
343
+ };
344
+ var todoQueries = {
345
+ create(data) {
346
+ const id = nanoid();
347
+ const now = /* @__PURE__ */ new Date();
348
+ const result = getDb().insert(todoItems).values({
349
+ id,
350
+ ...data,
351
+ createdAt: now,
352
+ updatedAt: now
353
+ }).returning().get();
354
+ return result;
355
+ },
356
+ createMany(sessionId, items) {
357
+ const now = /* @__PURE__ */ new Date();
358
+ const values = items.map((item, index) => ({
359
+ id: nanoid(),
360
+ sessionId,
361
+ content: item.content,
362
+ order: item.order ?? index,
363
+ createdAt: now,
364
+ updatedAt: now
365
+ }));
366
+ return getDb().insert(todoItems).values(values).returning().all();
367
+ },
368
+ getBySession(sessionId) {
369
+ return getDb().select().from(todoItems).where(eq(todoItems.sessionId, sessionId)).orderBy(todoItems.order).all();
370
+ },
371
+ updateStatus(id, status) {
372
+ return getDb().update(todoItems).set({ status, updatedAt: /* @__PURE__ */ new Date() }).where(eq(todoItems.id, id)).returning().get();
373
+ },
374
+ delete(id) {
375
+ const result = getDb().delete(todoItems).where(eq(todoItems.id, id)).run();
376
+ return result.changes > 0;
377
+ },
378
+ clearSession(sessionId) {
379
+ const result = getDb().delete(todoItems).where(eq(todoItems.sessionId, sessionId)).run();
380
+ return result.changes;
381
+ }
382
+ };
383
+ var skillQueries = {
384
+ load(sessionId, skillName) {
385
+ const id = nanoid();
386
+ const result = getDb().insert(loadedSkills).values({
387
+ id,
388
+ sessionId,
389
+ skillName,
390
+ loadedAt: /* @__PURE__ */ new Date()
391
+ }).returning().get();
392
+ return result;
393
+ },
394
+ getBySession(sessionId) {
395
+ return getDb().select().from(loadedSkills).where(eq(loadedSkills.sessionId, sessionId)).orderBy(loadedSkills.loadedAt).all();
396
+ },
397
+ isLoaded(sessionId, skillName) {
398
+ const result = getDb().select().from(loadedSkills).where(
399
+ and(
400
+ eq(loadedSkills.sessionId, sessionId),
401
+ eq(loadedSkills.skillName, skillName)
402
+ )
403
+ ).get();
404
+ return !!result;
405
+ }
406
+ };
407
+ var terminalQueries = {
408
+ create(data) {
409
+ const id = nanoid();
410
+ const result = getDb().insert(terminals).values({
411
+ id,
412
+ ...data,
413
+ createdAt: /* @__PURE__ */ new Date()
414
+ }).returning().get();
415
+ return result;
416
+ },
417
+ getById(id) {
418
+ return getDb().select().from(terminals).where(eq(terminals.id, id)).get();
419
+ },
420
+ getBySession(sessionId) {
421
+ return getDb().select().from(terminals).where(eq(terminals.sessionId, sessionId)).orderBy(desc(terminals.createdAt)).all();
422
+ },
423
+ getRunning(sessionId) {
424
+ return getDb().select().from(terminals).where(
425
+ and(
426
+ eq(terminals.sessionId, sessionId),
427
+ eq(terminals.status, "running")
428
+ )
429
+ ).all();
430
+ },
431
+ updateStatus(id, status, exitCode, error) {
432
+ return getDb().update(terminals).set({
433
+ status,
434
+ exitCode,
435
+ error,
436
+ stoppedAt: status !== "running" ? /* @__PURE__ */ new Date() : void 0
437
+ }).where(eq(terminals.id, id)).returning().get();
438
+ },
439
+ updatePid(id, pid) {
440
+ return getDb().update(terminals).set({ pid }).where(eq(terminals.id, id)).returning().get();
441
+ },
442
+ delete(id) {
443
+ const result = getDb().delete(terminals).where(eq(terminals.id, id)).run();
444
+ return result.changes > 0;
445
+ },
446
+ deleteBySession(sessionId) {
447
+ const result = getDb().delete(terminals).where(eq(terminals.sessionId, sessionId)).run();
448
+ return result.changes;
449
+ }
450
+ };
451
+
452
+ // src/agent/index.ts
453
+ import {
454
+ streamText,
455
+ generateText as generateText2,
456
+ tool as tool7,
457
+ stepCountIs
458
+ } from "ai";
459
+ import { gateway as gateway2 } from "@ai-sdk/gateway";
460
+ import { z as z8 } from "zod";
461
+ import { nanoid as nanoid2 } from "nanoid";
462
+
463
+ // src/config/index.ts
464
+ import { existsSync, readFileSync } from "fs";
465
+ import { resolve, dirname } from "path";
466
+
467
+ // src/config/types.ts
468
+ import { z } from "zod";
469
+ var ToolApprovalConfigSchema = z.object({
470
+ bash: z.boolean().optional().default(true),
471
+ write_file: z.boolean().optional().default(false),
472
+ read_file: z.boolean().optional().default(false),
473
+ load_skill: z.boolean().optional().default(false),
474
+ todo: z.boolean().optional().default(false)
475
+ });
476
+ var SkillMetadataSchema = z.object({
477
+ name: z.string(),
478
+ description: z.string()
479
+ });
480
+ var SessionConfigSchema = z.object({
481
+ toolApprovals: z.record(z.string(), z.boolean()).optional(),
482
+ approvalWebhook: z.string().url().optional(),
483
+ skillsDirectory: z.string().optional(),
484
+ maxContextChars: z.number().optional().default(2e5)
485
+ });
486
+ var SparkcoderConfigSchema = z.object({
487
+ // Default model to use (Vercel AI Gateway format)
488
+ defaultModel: z.string().default("anthropic/claude-opus-4-5"),
489
+ // Working directory for file operations
490
+ workingDirectory: z.string().optional(),
491
+ // Tool approval settings
492
+ toolApprovals: ToolApprovalConfigSchema.optional().default({}),
493
+ // Approval webhook URL (called when approval is needed)
494
+ approvalWebhook: z.string().url().optional(),
495
+ // Skills configuration
496
+ skills: z.object({
497
+ // Directory containing skill files
498
+ directory: z.string().optional().default("./skills"),
499
+ // Additional skill directories to include
500
+ additionalDirectories: z.array(z.string()).optional().default([])
501
+ }).optional().default({}),
502
+ // Context management
503
+ context: z.object({
504
+ // Maximum context size before summarization (in characters)
505
+ maxChars: z.number().optional().default(2e5),
506
+ // Enable automatic summarization
507
+ autoSummarize: z.boolean().optional().default(true),
508
+ // Number of recent messages to keep after summarization
509
+ keepRecentMessages: z.number().optional().default(10)
510
+ }).optional().default({}),
511
+ // Server configuration
512
+ server: z.object({
513
+ port: z.number().default(3141),
514
+ host: z.string().default("127.0.0.1")
515
+ }).default({ port: 3141, host: "127.0.0.1" }),
516
+ // Database path
517
+ databasePath: z.string().optional().default("./sparkecoder.db")
518
+ });
519
+
520
+ // src/config/index.ts
521
+ var CONFIG_FILE_NAMES = [
522
+ "sparkecoder.config.json",
523
+ "sparkecoder.json",
524
+ ".sparkecoder.json"
525
+ ];
526
+ var cachedConfig = null;
527
+ function findConfigFile(startDir) {
528
+ let currentDir = startDir;
529
+ while (currentDir !== dirname(currentDir)) {
530
+ for (const fileName of CONFIG_FILE_NAMES) {
531
+ const configPath = resolve(currentDir, fileName);
532
+ if (existsSync(configPath)) {
533
+ return configPath;
534
+ }
535
+ }
536
+ currentDir = dirname(currentDir);
537
+ }
538
+ return null;
539
+ }
540
+ function loadConfig(configPath, workingDirectory) {
541
+ const cwd = workingDirectory || process.cwd();
542
+ let rawConfig = {};
543
+ let configDir = cwd;
544
+ if (configPath) {
545
+ if (!existsSync(configPath)) {
546
+ throw new Error(`Config file not found: ${configPath}`);
547
+ }
548
+ const content = readFileSync(configPath, "utf-8");
549
+ rawConfig = JSON.parse(content);
550
+ configDir = dirname(resolve(configPath));
551
+ } else {
552
+ const foundPath = findConfigFile(cwd);
553
+ if (foundPath) {
554
+ const content = readFileSync(foundPath, "utf-8");
555
+ rawConfig = JSON.parse(content);
556
+ configDir = dirname(foundPath);
557
+ }
558
+ }
559
+ if (process.env.SPARKECODER_MODEL) {
560
+ rawConfig.defaultModel = process.env.SPARKECODER_MODEL;
561
+ }
562
+ if (process.env.SPARKECODER_PORT) {
563
+ rawConfig.server = {
564
+ port: parseInt(process.env.SPARKECODER_PORT, 10),
565
+ host: rawConfig.server?.host ?? "127.0.0.1"
566
+ };
567
+ }
568
+ if (process.env.DATABASE_PATH) {
569
+ rawConfig.databasePath = process.env.DATABASE_PATH;
570
+ }
571
+ const config = SparkcoderConfigSchema.parse(rawConfig);
572
+ const resolvedWorkingDirectory = config.workingDirectory ? resolve(configDir, config.workingDirectory) : cwd;
573
+ const resolvedSkillsDirectories = [
574
+ resolve(configDir, config.skills?.directory || "./skills"),
575
+ // Built-in skills
576
+ resolve(dirname(import.meta.url.replace("file://", "")), "../skills/default"),
577
+ ...(config.skills?.additionalDirectories || []).map(
578
+ (dir) => resolve(configDir, dir)
579
+ )
580
+ ].filter((dir) => {
581
+ try {
582
+ return existsSync(dir);
583
+ } catch {
584
+ return false;
585
+ }
586
+ });
587
+ const resolvedDatabasePath = resolve(configDir, config.databasePath || "./sparkecoder.db");
588
+ const resolved = {
589
+ ...config,
590
+ server: {
591
+ port: config.server.port,
592
+ host: config.server.host ?? "127.0.0.1"
593
+ },
594
+ resolvedWorkingDirectory,
595
+ resolvedSkillsDirectories,
596
+ resolvedDatabasePath
597
+ };
598
+ cachedConfig = resolved;
599
+ return resolved;
600
+ }
601
+ function getConfig() {
602
+ if (!cachedConfig) {
603
+ throw new Error("Config not loaded. Call loadConfig first.");
604
+ }
605
+ return cachedConfig;
606
+ }
607
+ function requiresApproval(toolName, sessionConfig) {
608
+ const config = getConfig();
609
+ if (sessionConfig?.toolApprovals?.[toolName] !== void 0) {
610
+ return sessionConfig.toolApprovals[toolName];
611
+ }
612
+ const globalApprovals = config.toolApprovals;
613
+ if (globalApprovals[toolName] !== void 0) {
614
+ return globalApprovals[toolName];
615
+ }
616
+ if (toolName === "bash") {
617
+ return true;
618
+ }
619
+ return false;
620
+ }
621
+
622
+ // src/tools/bash.ts
623
+ import { tool } from "ai";
624
+ import { z as z2 } from "zod";
625
+ import { exec } from "child_process";
626
+ import { promisify } from "util";
627
+
628
+ // src/utils/truncate.ts
629
+ var MAX_OUTPUT_CHARS = 1e4;
630
+ function truncateOutput(output, maxChars = MAX_OUTPUT_CHARS) {
631
+ if (output.length <= maxChars) {
632
+ return output;
633
+ }
634
+ const halfMax = Math.floor(maxChars / 2);
635
+ const truncatedChars = output.length - maxChars;
636
+ return output.slice(0, halfMax) + `
637
+
638
+ ... [TRUNCATED: ${truncatedChars.toLocaleString()} characters omitted] ...
639
+
640
+ ` + output.slice(-halfMax);
641
+ }
642
+ function calculateContextSize(messages2) {
643
+ return messages2.reduce((total, msg) => {
644
+ const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
645
+ return total + content.length;
646
+ }, 0);
647
+ }
648
+
649
+ // src/tools/bash.ts
650
+ var execAsync = promisify(exec);
651
+ var COMMAND_TIMEOUT = 6e4;
652
+ var MAX_OUTPUT_CHARS2 = 1e4;
653
+ var BLOCKED_COMMANDS = [
654
+ "rm -rf /",
655
+ "rm -rf ~",
656
+ "mkfs",
657
+ "dd if=/dev/zero",
658
+ ":(){:|:&};:",
659
+ "chmod -R 777 /"
660
+ ];
661
+ function isBlockedCommand(command) {
662
+ const normalizedCommand = command.toLowerCase().trim();
663
+ return BLOCKED_COMMANDS.some(
664
+ (blocked) => normalizedCommand.includes(blocked.toLowerCase())
665
+ );
666
+ }
667
+ var bashInputSchema = z2.object({
668
+ command: z2.string().describe("The bash command to execute. Can be a single command or a pipeline.")
669
+ });
670
+ function createBashTool(options) {
671
+ return tool({
672
+ description: `Execute a bash command in the terminal. The command runs in the working directory: ${options.workingDirectory}.
673
+ Use this for running shell commands, scripts, git operations, package managers (npm, pip, etc.), and other CLI tools.
674
+ Long outputs will be automatically truncated. Commands have a 60 second timeout.
675
+ IMPORTANT: Avoid destructive commands. Be careful with rm, chmod, and similar operations.`,
676
+ inputSchema: bashInputSchema,
677
+ execute: async ({ command }) => {
678
+ if (isBlockedCommand(command)) {
679
+ return {
680
+ success: false,
681
+ error: "This command is blocked for safety reasons.",
682
+ stdout: "",
683
+ stderr: "",
684
+ exitCode: 1
685
+ };
686
+ }
687
+ try {
688
+ const { stdout, stderr } = await execAsync(command, {
689
+ cwd: options.workingDirectory,
690
+ timeout: COMMAND_TIMEOUT,
691
+ maxBuffer: 10 * 1024 * 1024,
692
+ // 10MB buffer
693
+ shell: "/bin/bash"
694
+ });
695
+ const truncatedStdout = truncateOutput(stdout, MAX_OUTPUT_CHARS2);
696
+ const truncatedStderr = truncateOutput(stderr, MAX_OUTPUT_CHARS2 / 2);
697
+ if (options.onOutput) {
698
+ options.onOutput(truncatedStdout);
699
+ }
700
+ return {
701
+ success: true,
702
+ stdout: truncatedStdout,
703
+ stderr: truncatedStderr,
704
+ exitCode: 0
705
+ };
706
+ } catch (error) {
707
+ const stdout = error.stdout ? truncateOutput(error.stdout, MAX_OUTPUT_CHARS2) : "";
708
+ const stderr = error.stderr ? truncateOutput(error.stderr, MAX_OUTPUT_CHARS2) : "";
709
+ if (options.onOutput) {
710
+ options.onOutput(stderr || error.message);
711
+ }
712
+ if (error.killed) {
713
+ return {
714
+ success: false,
715
+ error: `Command timed out after ${COMMAND_TIMEOUT / 1e3} seconds`,
716
+ stdout,
717
+ stderr,
718
+ exitCode: 124
719
+ // Standard timeout exit code
720
+ };
721
+ }
722
+ return {
723
+ success: false,
724
+ error: error.message,
725
+ stdout,
726
+ stderr,
727
+ exitCode: error.code ?? 1
728
+ };
729
+ }
730
+ }
731
+ });
732
+ }
733
+
734
+ // src/tools/read-file.ts
735
+ import { tool as tool2 } from "ai";
736
+ import { z as z3 } from "zod";
737
+ import { readFile, stat } from "fs/promises";
738
+ import { resolve as resolve2, relative, isAbsolute } from "path";
739
+ import { existsSync as existsSync2 } from "fs";
740
+ var MAX_FILE_SIZE = 5 * 1024 * 1024;
741
+ var MAX_OUTPUT_CHARS3 = 5e4;
742
+ var readFileInputSchema = z3.object({
743
+ path: z3.string().describe("The path to the file to read. Can be relative to working directory or absolute."),
744
+ startLine: z3.number().optional().describe("Optional: Start reading from this line number (1-indexed)"),
745
+ endLine: z3.number().optional().describe("Optional: Stop reading at this line number (1-indexed, inclusive)")
746
+ });
747
+ function createReadFileTool(options) {
748
+ return tool2({
749
+ description: `Read the contents of a file. Provide a path relative to the working directory (${options.workingDirectory}) or an absolute path.
750
+ Large files will be automatically truncated. Binary files are not supported.
751
+ Use this to understand existing code, check file contents, or gather context.`,
752
+ inputSchema: readFileInputSchema,
753
+ execute: async ({ path, startLine, endLine }) => {
754
+ try {
755
+ const absolutePath = isAbsolute(path) ? path : resolve2(options.workingDirectory, path);
756
+ const relativePath = relative(options.workingDirectory, absolutePath);
757
+ if (relativePath.startsWith("..") && !isAbsolute(path)) {
758
+ return {
759
+ success: false,
760
+ error: "Path escapes the working directory. Use an absolute path if intentional.",
761
+ content: null
762
+ };
763
+ }
764
+ if (!existsSync2(absolutePath)) {
765
+ return {
766
+ success: false,
767
+ error: `File not found: ${path}`,
768
+ content: null
769
+ };
770
+ }
771
+ const stats = await stat(absolutePath);
772
+ if (stats.size > MAX_FILE_SIZE) {
773
+ return {
774
+ success: false,
775
+ error: `File is too large (${(stats.size / 1024 / 1024).toFixed(2)}MB). Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB.`,
776
+ content: null
777
+ };
778
+ }
779
+ if (stats.isDirectory()) {
780
+ return {
781
+ success: false,
782
+ error: 'Path is a directory, not a file. Use bash with "ls" to list directory contents.',
783
+ content: null
784
+ };
785
+ }
786
+ let content = await readFile(absolutePath, "utf-8");
787
+ if (startLine !== void 0 || endLine !== void 0) {
788
+ const lines = content.split("\n");
789
+ const start = (startLine ?? 1) - 1;
790
+ const end = endLine ?? lines.length;
791
+ if (start < 0 || start >= lines.length) {
792
+ return {
793
+ success: false,
794
+ error: `Start line ${startLine} is out of range. File has ${lines.length} lines.`,
795
+ content: null
796
+ };
797
+ }
798
+ content = lines.slice(start, end).join("\n");
799
+ const lineNumbers = lines.slice(start, end).map((line, idx) => `${(start + idx + 1).toString().padStart(4)}: ${line}`).join("\n");
800
+ content = lineNumbers;
801
+ }
802
+ const truncatedContent = truncateOutput(content, MAX_OUTPUT_CHARS3);
803
+ const wasTruncated = truncatedContent.length < content.length;
804
+ return {
805
+ success: true,
806
+ path: absolutePath,
807
+ relativePath: relative(options.workingDirectory, absolutePath),
808
+ content: truncatedContent,
809
+ lineCount: content.split("\n").length,
810
+ wasTruncated,
811
+ sizeBytes: stats.size
812
+ };
813
+ } catch (error) {
814
+ if (error.code === "ERR_INVALID_ARG_VALUE" || error.message.includes("encoding")) {
815
+ return {
816
+ success: false,
817
+ error: "File appears to be binary and cannot be read as text.",
818
+ content: null
819
+ };
820
+ }
821
+ return {
822
+ success: false,
823
+ error: error.message,
824
+ content: null
825
+ };
826
+ }
827
+ }
828
+ });
829
+ }
830
+
831
+ // src/tools/write-file.ts
832
+ import { tool as tool3 } from "ai";
833
+ import { z as z4 } from "zod";
834
+ import { readFile as readFile2, writeFile, mkdir } from "fs/promises";
835
+ import { resolve as resolve3, relative as relative2, isAbsolute as isAbsolute2, dirname as dirname2 } from "path";
836
+ import { existsSync as existsSync3 } from "fs";
837
+ var writeFileInputSchema = z4.object({
838
+ path: z4.string().describe("The path to the file. Can be relative to working directory or absolute."),
839
+ mode: z4.enum(["full", "str_replace"]).describe('Write mode: "full" for complete file write, "str_replace" for targeted string replacement'),
840
+ content: z4.string().optional().describe('For "full" mode: The complete content to write to the file'),
841
+ old_string: z4.string().optional().describe('For "str_replace" mode: The exact string to find and replace'),
842
+ new_string: z4.string().optional().describe('For "str_replace" mode: The string to replace old_string with')
843
+ });
844
+ function createWriteFileTool(options) {
845
+ return tool3({
846
+ description: `Write content to a file. Supports two modes:
847
+ 1. "full" - Write the entire file content (creates new file or replaces existing)
848
+ 2. "str_replace" - Replace a specific string in an existing file (for precise edits)
849
+
850
+ For str_replace mode:
851
+ - Provide the exact string to find (old_string) and its replacement (new_string)
852
+ - The old_string must match EXACTLY (including whitespace and indentation)
853
+ - Only the first occurrence is replaced
854
+ - Use this for surgical edits to existing code
855
+
856
+ For full mode:
857
+ - Provide the complete file content
858
+ - Creates parent directories if they don't exist
859
+ - Use this for new files or complete rewrites
860
+
861
+ Working directory: ${options.workingDirectory}`,
862
+ inputSchema: writeFileInputSchema,
863
+ execute: async ({ path, mode, content, old_string, new_string }) => {
864
+ try {
865
+ const absolutePath = isAbsolute2(path) ? path : resolve3(options.workingDirectory, path);
866
+ const relativePath = relative2(options.workingDirectory, absolutePath);
867
+ if (relativePath.startsWith("..") && !isAbsolute2(path)) {
868
+ return {
869
+ success: false,
870
+ error: "Path escapes the working directory. Use an absolute path if intentional."
871
+ };
872
+ }
873
+ if (mode === "full") {
874
+ if (content === void 0) {
875
+ return {
876
+ success: false,
877
+ error: 'Content is required for "full" mode'
878
+ };
879
+ }
880
+ const dir = dirname2(absolutePath);
881
+ if (!existsSync3(dir)) {
882
+ await mkdir(dir, { recursive: true });
883
+ }
884
+ const existed = existsSync3(absolutePath);
885
+ await writeFile(absolutePath, content, "utf-8");
886
+ return {
887
+ success: true,
888
+ path: absolutePath,
889
+ relativePath: relative2(options.workingDirectory, absolutePath),
890
+ mode: "full",
891
+ action: existed ? "replaced" : "created",
892
+ bytesWritten: Buffer.byteLength(content, "utf-8"),
893
+ lineCount: content.split("\n").length
894
+ };
895
+ } else if (mode === "str_replace") {
896
+ if (old_string === void 0 || new_string === void 0) {
897
+ return {
898
+ success: false,
899
+ error: 'Both old_string and new_string are required for "str_replace" mode'
900
+ };
901
+ }
902
+ if (!existsSync3(absolutePath)) {
903
+ return {
904
+ success: false,
905
+ error: `File not found: ${path}. Use "full" mode to create new files.`
906
+ };
907
+ }
908
+ const currentContent = await readFile2(absolutePath, "utf-8");
909
+ if (!currentContent.includes(old_string)) {
910
+ const lines = currentContent.split("\n");
911
+ const preview = lines.slice(0, 20).join("\n");
912
+ return {
913
+ success: false,
914
+ error: "old_string not found in file. The string must match EXACTLY including whitespace.",
915
+ hint: "Check for differences in indentation, line endings, or invisible characters.",
916
+ filePreview: lines.length > 20 ? `${preview}
917
+ ... (${lines.length - 20} more lines)` : preview
918
+ };
919
+ }
920
+ const occurrences = currentContent.split(old_string).length - 1;
921
+ if (occurrences > 1) {
922
+ return {
923
+ success: false,
924
+ error: `Found ${occurrences} occurrences of old_string. Please provide more context to make it unique.`,
925
+ hint: "Include surrounding lines or more specific content in old_string."
926
+ };
927
+ }
928
+ const newContent = currentContent.replace(old_string, new_string);
929
+ await writeFile(absolutePath, newContent, "utf-8");
930
+ const oldLines = old_string.split("\n").length;
931
+ const newLines = new_string.split("\n").length;
932
+ return {
933
+ success: true,
934
+ path: absolutePath,
935
+ relativePath: relative2(options.workingDirectory, absolutePath),
936
+ mode: "str_replace",
937
+ linesRemoved: oldLines,
938
+ linesAdded: newLines,
939
+ lineDelta: newLines - oldLines
940
+ };
941
+ }
942
+ return {
943
+ success: false,
944
+ error: `Invalid mode: ${mode}`
945
+ };
946
+ } catch (error) {
947
+ return {
948
+ success: false,
949
+ error: error.message
950
+ };
951
+ }
952
+ }
953
+ });
954
+ }
955
+
956
+ // src/tools/todo.ts
957
+ import { tool as tool4 } from "ai";
958
+ import { z as z5 } from "zod";
959
+ var todoInputSchema = z5.object({
960
+ action: z5.enum(["add", "list", "mark", "clear"]).describe("The action to perform on the todo list"),
961
+ items: z5.array(
962
+ z5.object({
963
+ content: z5.string().describe("Description of the task"),
964
+ order: z5.number().optional().describe("Optional order/priority (lower = higher priority)")
965
+ })
966
+ ).optional().describe('For "add" action: Array of todo items to add'),
967
+ todoId: z5.string().optional().describe('For "mark" action: The ID of the todo item to update'),
968
+ status: z5.enum(["pending", "in_progress", "completed", "cancelled"]).optional().describe('For "mark" action: The new status for the todo item')
969
+ });
970
+ function createTodoTool(options) {
971
+ return tool4({
972
+ description: `Manage your task list for the current session. Use this to:
973
+ - Break down complex tasks into smaller steps
974
+ - Track progress on multi-step operations
975
+ - Organize your work systematically
976
+
977
+ Available actions:
978
+ - "add": Add one or more new todo items to the list
979
+ - "list": View all current todo items and their status
980
+ - "mark": Update the status of a todo item (pending, in_progress, completed, cancelled)
981
+ - "clear": Remove all todo items from the list
982
+
983
+ Best practices:
984
+ - Add todos before starting complex tasks
985
+ - Mark items as "in_progress" when actively working on them
986
+ - Update status as you complete each step`,
987
+ inputSchema: todoInputSchema,
988
+ execute: async ({ action, items, todoId, status }) => {
989
+ try {
990
+ switch (action) {
991
+ case "add": {
992
+ if (!items || items.length === 0) {
993
+ return {
994
+ success: false,
995
+ error: "No items provided. Include at least one todo item."
996
+ };
997
+ }
998
+ const created = todoQueries.createMany(options.sessionId, items);
999
+ return {
1000
+ success: true,
1001
+ action: "add",
1002
+ itemsAdded: created.length,
1003
+ items: created.map(formatTodoItem)
1004
+ };
1005
+ }
1006
+ case "list": {
1007
+ const todos = todoQueries.getBySession(options.sessionId);
1008
+ const stats = {
1009
+ total: todos.length,
1010
+ pending: todos.filter((t) => t.status === "pending").length,
1011
+ inProgress: todos.filter((t) => t.status === "in_progress").length,
1012
+ completed: todos.filter((t) => t.status === "completed").length,
1013
+ cancelled: todos.filter((t) => t.status === "cancelled").length
1014
+ };
1015
+ return {
1016
+ success: true,
1017
+ action: "list",
1018
+ stats,
1019
+ items: todos.map(formatTodoItem)
1020
+ };
1021
+ }
1022
+ case "mark": {
1023
+ if (!todoId) {
1024
+ return {
1025
+ success: false,
1026
+ error: 'todoId is required for "mark" action'
1027
+ };
1028
+ }
1029
+ if (!status) {
1030
+ return {
1031
+ success: false,
1032
+ error: 'status is required for "mark" action'
1033
+ };
1034
+ }
1035
+ const updated = todoQueries.updateStatus(todoId, status);
1036
+ if (!updated) {
1037
+ return {
1038
+ success: false,
1039
+ error: `Todo item not found: ${todoId}`
1040
+ };
1041
+ }
1042
+ return {
1043
+ success: true,
1044
+ action: "mark",
1045
+ item: formatTodoItem(updated)
1046
+ };
1047
+ }
1048
+ case "clear": {
1049
+ const count = todoQueries.clearSession(options.sessionId);
1050
+ return {
1051
+ success: true,
1052
+ action: "clear",
1053
+ itemsRemoved: count
1054
+ };
1055
+ }
1056
+ default:
1057
+ return {
1058
+ success: false,
1059
+ error: `Unknown action: ${action}`
1060
+ };
1061
+ }
1062
+ } catch (error) {
1063
+ return {
1064
+ success: false,
1065
+ error: error.message
1066
+ };
1067
+ }
1068
+ }
1069
+ });
1070
+ }
1071
+ function formatTodoItem(item) {
1072
+ return {
1073
+ id: item.id,
1074
+ content: item.content,
1075
+ status: item.status,
1076
+ order: item.order,
1077
+ createdAt: item.createdAt.toISOString()
1078
+ };
1079
+ }
1080
+
1081
+ // src/tools/load-skill.ts
1082
+ import { tool as tool5 } from "ai";
1083
+ import { z as z6 } from "zod";
1084
+
1085
+ // src/skills/index.ts
1086
+ import { readFile as readFile3, readdir } from "fs/promises";
1087
+ import { resolve as resolve4, basename, extname } from "path";
1088
+ import { existsSync as existsSync4 } from "fs";
1089
+ function parseSkillFrontmatter(content) {
1090
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
1091
+ if (!frontmatterMatch) {
1092
+ return null;
1093
+ }
1094
+ const [, frontmatter, body] = frontmatterMatch;
1095
+ try {
1096
+ const lines = frontmatter.split("\n");
1097
+ const data = {};
1098
+ for (const line of lines) {
1099
+ const colonIndex = line.indexOf(":");
1100
+ if (colonIndex > 0) {
1101
+ const key = line.slice(0, colonIndex).trim();
1102
+ let value = line.slice(colonIndex + 1).trim();
1103
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1104
+ value = value.slice(1, -1);
1105
+ }
1106
+ data[key] = value;
1107
+ }
1108
+ }
1109
+ const metadata = SkillMetadataSchema.parse(data);
1110
+ return { metadata, body: body.trim() };
1111
+ } catch {
1112
+ return null;
1113
+ }
1114
+ }
1115
+ function getSkillNameFromPath(filePath) {
1116
+ return basename(filePath, extname(filePath)).replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
1117
+ }
1118
+ async function loadSkillsFromDirectory(directory) {
1119
+ if (!existsSync4(directory)) {
1120
+ return [];
1121
+ }
1122
+ const skills = [];
1123
+ const files = await readdir(directory);
1124
+ for (const file of files) {
1125
+ if (!file.endsWith(".md")) continue;
1126
+ const filePath = resolve4(directory, file);
1127
+ const content = await readFile3(filePath, "utf-8");
1128
+ const parsed = parseSkillFrontmatter(content);
1129
+ if (parsed) {
1130
+ skills.push({
1131
+ name: parsed.metadata.name,
1132
+ description: parsed.metadata.description,
1133
+ filePath
1134
+ });
1135
+ } else {
1136
+ const name = getSkillNameFromPath(filePath);
1137
+ const firstParagraph = content.split("\n\n")[0]?.slice(0, 200) || "No description";
1138
+ skills.push({
1139
+ name,
1140
+ description: firstParagraph.replace(/^#\s*/, "").trim(),
1141
+ filePath
1142
+ });
1143
+ }
1144
+ }
1145
+ return skills;
1146
+ }
1147
+ async function loadAllSkills(directories) {
1148
+ const allSkills = [];
1149
+ const seenNames = /* @__PURE__ */ new Set();
1150
+ for (const dir of directories) {
1151
+ const skills = await loadSkillsFromDirectory(dir);
1152
+ for (const skill of skills) {
1153
+ if (!seenNames.has(skill.name.toLowerCase())) {
1154
+ seenNames.add(skill.name.toLowerCase());
1155
+ allSkills.push(skill);
1156
+ }
1157
+ }
1158
+ }
1159
+ return allSkills;
1160
+ }
1161
+ async function loadSkillContent(skillName, directories) {
1162
+ const allSkills = await loadAllSkills(directories);
1163
+ const skill = allSkills.find(
1164
+ (s) => s.name.toLowerCase() === skillName.toLowerCase()
1165
+ );
1166
+ if (!skill) {
1167
+ return null;
1168
+ }
1169
+ const content = await readFile3(skill.filePath, "utf-8");
1170
+ const parsed = parseSkillFrontmatter(content);
1171
+ return {
1172
+ ...skill,
1173
+ content: parsed ? parsed.body : content
1174
+ };
1175
+ }
1176
+ function formatSkillsForContext(skills) {
1177
+ if (skills.length === 0) {
1178
+ return "No skills available.";
1179
+ }
1180
+ const lines = ["Available skills (use load_skill tool to load into context):"];
1181
+ for (const skill of skills) {
1182
+ lines.push(`- ${skill.name}: ${skill.description}`);
1183
+ }
1184
+ return lines.join("\n");
1185
+ }
1186
+
1187
+ // src/tools/load-skill.ts
1188
+ var loadSkillInputSchema = z6.object({
1189
+ action: z6.enum(["list", "load"]).describe('Action to perform: "list" to see available skills, "load" to load a skill'),
1190
+ skillName: z6.string().optional().describe('For "load" action: The name of the skill to load')
1191
+ });
1192
+ function createLoadSkillTool(options) {
1193
+ return tool5({
1194
+ 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.
1195
+
1196
+ Available actions:
1197
+ - "list": Show all available skills with their descriptions
1198
+ - "load": Load a specific skill's full content into context
1199
+
1200
+ Use this when you need specialized knowledge or guidance for a particular task.
1201
+ Once loaded, a skill's content will be available in the conversation context.`,
1202
+ inputSchema: loadSkillInputSchema,
1203
+ execute: async ({ action, skillName }) => {
1204
+ try {
1205
+ switch (action) {
1206
+ case "list": {
1207
+ const skills = await loadAllSkills(options.skillsDirectories);
1208
+ return {
1209
+ success: true,
1210
+ action: "list",
1211
+ skillCount: skills.length,
1212
+ skills: skills.map((s) => ({
1213
+ name: s.name,
1214
+ description: s.description
1215
+ })),
1216
+ formatted: formatSkillsForContext(skills)
1217
+ };
1218
+ }
1219
+ case "load": {
1220
+ if (!skillName) {
1221
+ return {
1222
+ success: false,
1223
+ error: 'skillName is required for "load" action'
1224
+ };
1225
+ }
1226
+ if (skillQueries.isLoaded(options.sessionId, skillName)) {
1227
+ return {
1228
+ success: false,
1229
+ error: `Skill "${skillName}" is already loaded in this session`
1230
+ };
1231
+ }
1232
+ const skill = await loadSkillContent(skillName, options.skillsDirectories);
1233
+ if (!skill) {
1234
+ const allSkills = await loadAllSkills(options.skillsDirectories);
1235
+ return {
1236
+ success: false,
1237
+ error: `Skill "${skillName}" not found`,
1238
+ availableSkills: allSkills.map((s) => s.name)
1239
+ };
1240
+ }
1241
+ skillQueries.load(options.sessionId, skillName);
1242
+ return {
1243
+ success: true,
1244
+ action: "load",
1245
+ skillName: skill.name,
1246
+ description: skill.description,
1247
+ content: skill.content,
1248
+ contentLength: skill.content.length
1249
+ };
1250
+ }
1251
+ default:
1252
+ return {
1253
+ success: false,
1254
+ error: `Unknown action: ${action}`
1255
+ };
1256
+ }
1257
+ } catch (error) {
1258
+ return {
1259
+ success: false,
1260
+ error: error.message
1261
+ };
1262
+ }
1263
+ }
1264
+ });
1265
+ }
1266
+
1267
+ // src/tools/terminal.ts
1268
+ import { tool as tool6 } from "ai";
1269
+ import { z as z7 } from "zod";
1270
+
1271
+ // src/terminal/manager.ts
1272
+ import { spawn } from "child_process";
1273
+ import { EventEmitter } from "events";
1274
+ var LogBuffer = class {
1275
+ buffer = [];
1276
+ maxSize;
1277
+ totalBytes = 0;
1278
+ maxBytes;
1279
+ constructor(maxBytes = 50 * 1024) {
1280
+ this.maxBytes = maxBytes;
1281
+ this.maxSize = 1e3;
1282
+ }
1283
+ append(data) {
1284
+ const lines = data.split("\n");
1285
+ for (const line of lines) {
1286
+ if (line) {
1287
+ this.buffer.push(line);
1288
+ this.totalBytes += line.length;
1289
+ }
1290
+ }
1291
+ while (this.totalBytes > this.maxBytes && this.buffer.length > 1) {
1292
+ const removed = this.buffer.shift();
1293
+ if (removed) {
1294
+ this.totalBytes -= removed.length;
1295
+ }
1296
+ }
1297
+ while (this.buffer.length > this.maxSize) {
1298
+ const removed = this.buffer.shift();
1299
+ if (removed) {
1300
+ this.totalBytes -= removed.length;
1301
+ }
1302
+ }
1303
+ }
1304
+ getAll() {
1305
+ return this.buffer.join("\n");
1306
+ }
1307
+ getTail(lines) {
1308
+ const start = Math.max(0, this.buffer.length - lines);
1309
+ return this.buffer.slice(start).join("\n");
1310
+ }
1311
+ clear() {
1312
+ this.buffer = [];
1313
+ this.totalBytes = 0;
1314
+ }
1315
+ get lineCount() {
1316
+ return this.buffer.length;
1317
+ }
1318
+ };
1319
+ var TerminalManager = class _TerminalManager extends EventEmitter {
1320
+ processes = /* @__PURE__ */ new Map();
1321
+ static instance = null;
1322
+ constructor() {
1323
+ super();
1324
+ }
1325
+ static getInstance() {
1326
+ if (!_TerminalManager.instance) {
1327
+ _TerminalManager.instance = new _TerminalManager();
1328
+ }
1329
+ return _TerminalManager.instance;
1330
+ }
1331
+ /**
1332
+ * Spawn a new background process
1333
+ */
1334
+ spawn(options) {
1335
+ const { sessionId, command, cwd, name, env } = options;
1336
+ const parts = this.parseCommand(command);
1337
+ const executable = parts[0];
1338
+ const args = parts.slice(1);
1339
+ const terminal = terminalQueries.create({
1340
+ sessionId,
1341
+ name: name || null,
1342
+ command,
1343
+ cwd: cwd || process.cwd(),
1344
+ status: "running"
1345
+ });
1346
+ const proc = spawn(executable, args, {
1347
+ cwd: cwd || process.cwd(),
1348
+ shell: true,
1349
+ stdio: ["pipe", "pipe", "pipe"],
1350
+ env: { ...process.env, ...env },
1351
+ detached: false
1352
+ });
1353
+ if (proc.pid) {
1354
+ terminalQueries.updatePid(terminal.id, proc.pid);
1355
+ }
1356
+ const logs = new LogBuffer();
1357
+ proc.stdout?.on("data", (data) => {
1358
+ const text2 = data.toString();
1359
+ logs.append(text2);
1360
+ this.emit("stdout", { terminalId: terminal.id, data: text2 });
1361
+ });
1362
+ proc.stderr?.on("data", (data) => {
1363
+ const text2 = data.toString();
1364
+ logs.append(`[stderr] ${text2}`);
1365
+ this.emit("stderr", { terminalId: terminal.id, data: text2 });
1366
+ });
1367
+ proc.on("exit", (code, signal) => {
1368
+ const exitCode = code ?? (signal ? 128 : 0);
1369
+ terminalQueries.updateStatus(terminal.id, "stopped", exitCode);
1370
+ this.emit("exit", { terminalId: terminal.id, code: exitCode, signal });
1371
+ const managed2 = this.processes.get(terminal.id);
1372
+ if (managed2) {
1373
+ managed2.terminal = { ...managed2.terminal, status: "stopped", exitCode };
1374
+ }
1375
+ });
1376
+ proc.on("error", (err) => {
1377
+ terminalQueries.updateStatus(terminal.id, "error", void 0, err.message);
1378
+ this.emit("error", { terminalId: terminal.id, error: err.message });
1379
+ const managed2 = this.processes.get(terminal.id);
1380
+ if (managed2) {
1381
+ managed2.terminal = { ...managed2.terminal, status: "error", error: err.message };
1382
+ }
1383
+ });
1384
+ const managed = {
1385
+ id: terminal.id,
1386
+ process: proc,
1387
+ logs,
1388
+ terminal: { ...terminal, pid: proc.pid ?? null }
1389
+ };
1390
+ this.processes.set(terminal.id, managed);
1391
+ return this.toTerminalInfo(managed.terminal);
1392
+ }
1393
+ /**
1394
+ * Get logs from a terminal
1395
+ */
1396
+ getLogs(terminalId, tail) {
1397
+ const managed = this.processes.get(terminalId);
1398
+ if (!managed) {
1399
+ return null;
1400
+ }
1401
+ return {
1402
+ logs: tail ? managed.logs.getTail(tail) : managed.logs.getAll(),
1403
+ lineCount: managed.logs.lineCount
1404
+ };
1405
+ }
1406
+ /**
1407
+ * Get terminal status
1408
+ */
1409
+ getStatus(terminalId) {
1410
+ const managed = this.processes.get(terminalId);
1411
+ if (managed) {
1412
+ if (managed.process.exitCode !== null) {
1413
+ managed.terminal = {
1414
+ ...managed.terminal,
1415
+ status: "stopped",
1416
+ exitCode: managed.process.exitCode
1417
+ };
1418
+ }
1419
+ return this.toTerminalInfo(managed.terminal);
1420
+ }
1421
+ const terminal = terminalQueries.getById(terminalId);
1422
+ if (terminal) {
1423
+ return this.toTerminalInfo(terminal);
1424
+ }
1425
+ return null;
1426
+ }
1427
+ /**
1428
+ * Kill a terminal process
1429
+ */
1430
+ kill(terminalId, signal = "SIGTERM") {
1431
+ const managed = this.processes.get(terminalId);
1432
+ if (!managed) {
1433
+ return false;
1434
+ }
1435
+ try {
1436
+ managed.process.kill(signal);
1437
+ return true;
1438
+ } catch (err) {
1439
+ console.error(`Failed to kill terminal ${terminalId}:`, err);
1440
+ return false;
1441
+ }
1442
+ }
1443
+ /**
1444
+ * Write to a terminal's stdin
1445
+ */
1446
+ write(terminalId, input) {
1447
+ const managed = this.processes.get(terminalId);
1448
+ if (!managed || !managed.process.stdin) {
1449
+ return false;
1450
+ }
1451
+ try {
1452
+ managed.process.stdin.write(input);
1453
+ return true;
1454
+ } catch (err) {
1455
+ console.error(`Failed to write to terminal ${terminalId}:`, err);
1456
+ return false;
1457
+ }
1458
+ }
1459
+ /**
1460
+ * List all terminals for a session
1461
+ */
1462
+ list(sessionId) {
1463
+ const terminals3 = terminalQueries.getBySession(sessionId);
1464
+ return terminals3.map((t) => {
1465
+ const managed = this.processes.get(t.id);
1466
+ if (managed) {
1467
+ return this.toTerminalInfo(managed.terminal);
1468
+ }
1469
+ return this.toTerminalInfo(t);
1470
+ });
1471
+ }
1472
+ /**
1473
+ * Get all running terminals for a session
1474
+ */
1475
+ getRunning(sessionId) {
1476
+ return this.list(sessionId).filter((t) => t.status === "running");
1477
+ }
1478
+ /**
1479
+ * Kill all terminals for a session (cleanup)
1480
+ */
1481
+ killAll(sessionId) {
1482
+ let killed = 0;
1483
+ for (const [id, managed] of this.processes) {
1484
+ if (managed.terminal.sessionId === sessionId) {
1485
+ if (this.kill(id)) {
1486
+ killed++;
1487
+ }
1488
+ }
1489
+ }
1490
+ return killed;
1491
+ }
1492
+ /**
1493
+ * Clean up stopped terminals from memory (keep DB records)
1494
+ */
1495
+ cleanup(sessionId) {
1496
+ let cleaned = 0;
1497
+ for (const [id, managed] of this.processes) {
1498
+ if (sessionId && managed.terminal.sessionId !== sessionId) {
1499
+ continue;
1500
+ }
1501
+ if (managed.terminal.status !== "running") {
1502
+ this.processes.delete(id);
1503
+ cleaned++;
1504
+ }
1505
+ }
1506
+ return cleaned;
1507
+ }
1508
+ /**
1509
+ * Parse a command string into executable and arguments
1510
+ */
1511
+ parseCommand(command) {
1512
+ const parts = [];
1513
+ let current = "";
1514
+ let inQuote = false;
1515
+ let quoteChar = "";
1516
+ for (const char of command) {
1517
+ if ((char === '"' || char === "'") && !inQuote) {
1518
+ inQuote = true;
1519
+ quoteChar = char;
1520
+ } else if (char === quoteChar && inQuote) {
1521
+ inQuote = false;
1522
+ quoteChar = "";
1523
+ } else if (char === " " && !inQuote) {
1524
+ if (current) {
1525
+ parts.push(current);
1526
+ current = "";
1527
+ }
1528
+ } else {
1529
+ current += char;
1530
+ }
1531
+ }
1532
+ if (current) {
1533
+ parts.push(current);
1534
+ }
1535
+ return parts.length > 0 ? parts : [command];
1536
+ }
1537
+ toTerminalInfo(terminal) {
1538
+ return {
1539
+ id: terminal.id,
1540
+ name: terminal.name,
1541
+ command: terminal.command,
1542
+ cwd: terminal.cwd,
1543
+ pid: terminal.pid,
1544
+ status: terminal.status,
1545
+ exitCode: terminal.exitCode,
1546
+ error: terminal.error,
1547
+ createdAt: terminal.createdAt,
1548
+ stoppedAt: terminal.stoppedAt
1549
+ };
1550
+ }
1551
+ };
1552
+ function getTerminalManager() {
1553
+ return TerminalManager.getInstance();
1554
+ }
1555
+
1556
+ // src/tools/terminal.ts
1557
+ var TerminalInputSchema = z7.object({
1558
+ action: z7.enum(["spawn", "logs", "status", "kill", "write", "list"]).describe(
1559
+ "The action to perform: spawn (start process), logs (get output), status (check if running), kill (stop process), write (send stdin), list (show all)"
1560
+ ),
1561
+ // For spawn
1562
+ command: z7.string().optional().describe('For spawn: The command to run (e.g., "npm run dev")'),
1563
+ cwd: z7.string().optional().describe("For spawn: Working directory for the command"),
1564
+ name: z7.string().optional().describe('For spawn: Optional friendly name (e.g., "dev-server")'),
1565
+ // For logs, status, kill, write
1566
+ terminalId: z7.string().optional().describe("For logs/status/kill/write: The terminal ID"),
1567
+ tail: z7.number().optional().describe("For logs: Number of lines to return from the end"),
1568
+ // For kill
1569
+ signal: z7.enum(["SIGTERM", "SIGKILL"]).optional().describe("For kill: Signal to send (default: SIGTERM)"),
1570
+ // For write
1571
+ input: z7.string().optional().describe("For write: The input to send to stdin")
1572
+ });
1573
+ function createTerminalTool(options) {
1574
+ const { sessionId, workingDirectory } = options;
1575
+ return tool6({
1576
+ description: `Manage background terminal processes. Use this for long-running commands like dev servers, watchers, or any process that shouldn't block.
1577
+
1578
+ Actions:
1579
+ - spawn: Start a new background process. Requires 'command'. Returns terminal ID.
1580
+ - logs: Get output from a terminal. Requires 'terminalId'. Optional 'tail' for recent lines.
1581
+ - status: Check if a terminal is still running. Requires 'terminalId'.
1582
+ - kill: Stop a terminal process. Requires 'terminalId'. Optional 'signal'.
1583
+ - write: Send input to a terminal's stdin. Requires 'terminalId' and 'input'.
1584
+ - list: Show all terminals for this session. No other params needed.
1585
+
1586
+ Example workflow:
1587
+ 1. spawn with command="npm run dev", name="dev-server" \u2192 { id: "abc123", status: "running" }
1588
+ 2. logs with terminalId="abc123", tail=10 \u2192 "Ready on http://localhost:3000"
1589
+ 3. kill with terminalId="abc123" \u2192 { success: true }`,
1590
+ inputSchema: TerminalInputSchema,
1591
+ execute: async (input) => {
1592
+ const manager = getTerminalManager();
1593
+ switch (input.action) {
1594
+ case "spawn": {
1595
+ if (!input.command) {
1596
+ return { success: false, error: 'spawn requires a "command" parameter' };
1597
+ }
1598
+ const terminal = manager.spawn({
1599
+ sessionId,
1600
+ command: input.command,
1601
+ cwd: input.cwd || workingDirectory,
1602
+ name: input.name
1603
+ });
1604
+ return {
1605
+ success: true,
1606
+ terminal: formatTerminal(terminal),
1607
+ message: `Started "${input.command}" with terminal ID: ${terminal.id}`
1608
+ };
1609
+ }
1610
+ case "logs": {
1611
+ if (!input.terminalId) {
1612
+ return { success: false, error: 'logs requires a "terminalId" parameter' };
1613
+ }
1614
+ const result = manager.getLogs(input.terminalId, input.tail);
1615
+ if (!result) {
1616
+ return {
1617
+ success: false,
1618
+ error: `Terminal not found: ${input.terminalId}`
1619
+ };
1620
+ }
1621
+ return {
1622
+ success: true,
1623
+ terminalId: input.terminalId,
1624
+ logs: result.logs,
1625
+ lineCount: result.lineCount
1626
+ };
1627
+ }
1628
+ case "status": {
1629
+ if (!input.terminalId) {
1630
+ return { success: false, error: 'status requires a "terminalId" parameter' };
1631
+ }
1632
+ const status = manager.getStatus(input.terminalId);
1633
+ if (!status) {
1634
+ return {
1635
+ success: false,
1636
+ error: `Terminal not found: ${input.terminalId}`
1637
+ };
1638
+ }
1639
+ return {
1640
+ success: true,
1641
+ terminal: formatTerminal(status)
1642
+ };
1643
+ }
1644
+ case "kill": {
1645
+ if (!input.terminalId) {
1646
+ return { success: false, error: 'kill requires a "terminalId" parameter' };
1647
+ }
1648
+ const success = manager.kill(input.terminalId, input.signal);
1649
+ if (!success) {
1650
+ return {
1651
+ success: false,
1652
+ error: `Failed to kill terminal: ${input.terminalId}`
1653
+ };
1654
+ }
1655
+ return {
1656
+ success: true,
1657
+ message: `Sent ${input.signal || "SIGTERM"} to terminal ${input.terminalId}`
1658
+ };
1659
+ }
1660
+ case "write": {
1661
+ if (!input.terminalId) {
1662
+ return { success: false, error: 'write requires a "terminalId" parameter' };
1663
+ }
1664
+ if (!input.input) {
1665
+ return { success: false, error: 'write requires an "input" parameter' };
1666
+ }
1667
+ const success = manager.write(input.terminalId, input.input);
1668
+ if (!success) {
1669
+ return {
1670
+ success: false,
1671
+ error: `Failed to write to terminal: ${input.terminalId}`
1672
+ };
1673
+ }
1674
+ return {
1675
+ success: true,
1676
+ message: `Sent input to terminal ${input.terminalId}`
1677
+ };
1678
+ }
1679
+ case "list": {
1680
+ const terminals3 = manager.list(sessionId);
1681
+ return {
1682
+ success: true,
1683
+ terminals: terminals3.map(formatTerminal),
1684
+ count: terminals3.length,
1685
+ running: terminals3.filter((t) => t.status === "running").length
1686
+ };
1687
+ }
1688
+ default:
1689
+ return { success: false, error: `Unknown action: ${input.action}` };
1690
+ }
1691
+ }
1692
+ });
1693
+ }
1694
+ function formatTerminal(t) {
1695
+ return {
1696
+ id: t.id,
1697
+ name: t.name,
1698
+ command: t.command,
1699
+ cwd: t.cwd,
1700
+ pid: t.pid,
1701
+ status: t.status,
1702
+ exitCode: t.exitCode,
1703
+ error: t.error,
1704
+ createdAt: t.createdAt.toISOString(),
1705
+ stoppedAt: t.stoppedAt?.toISOString() || null
1706
+ };
1707
+ }
1708
+
1709
+ // src/tools/index.ts
1710
+ function createTools(options) {
1711
+ return {
1712
+ bash: createBashTool({
1713
+ workingDirectory: options.workingDirectory,
1714
+ onOutput: options.onBashOutput
1715
+ }),
1716
+ read_file: createReadFileTool({
1717
+ workingDirectory: options.workingDirectory
1718
+ }),
1719
+ write_file: createWriteFileTool({
1720
+ workingDirectory: options.workingDirectory
1721
+ }),
1722
+ todo: createTodoTool({
1723
+ sessionId: options.sessionId
1724
+ }),
1725
+ load_skill: createLoadSkillTool({
1726
+ sessionId: options.sessionId,
1727
+ skillsDirectories: options.skillsDirectories
1728
+ }),
1729
+ terminal: createTerminalTool({
1730
+ sessionId: options.sessionId,
1731
+ workingDirectory: options.workingDirectory
1732
+ })
1733
+ };
1734
+ }
1735
+
1736
+ // src/agent/context.ts
1737
+ import { generateText } from "ai";
1738
+ import { gateway } from "@ai-sdk/gateway";
1739
+
1740
+ // src/agent/prompts.ts
1741
+ async function buildSystemPrompt(options) {
1742
+ const { workingDirectory, skillsDirectories, sessionId, customInstructions } = options;
1743
+ const skills = await loadAllSkills(skillsDirectories);
1744
+ const skillsContext = formatSkillsForContext(skills);
1745
+ const todos = todoQueries.getBySession(sessionId);
1746
+ const todosContext = formatTodosForContext(todos);
1747
+ const systemPrompt = `You are Sparkecoder, an expert AI coding assistant. You help developers write, debug, and improve code.
1748
+
1749
+ ## Working Directory
1750
+ You are working in: ${workingDirectory}
1751
+
1752
+ ## Core Capabilities
1753
+ You have access to powerful tools for:
1754
+ - **bash**: Execute shell commands, run scripts, install packages, use git
1755
+ - **read_file**: Read file contents to understand code and context
1756
+ - **write_file**: Create new files or edit existing ones (supports targeted string replacement)
1757
+ - **todo**: Manage your task list to track progress on complex operations
1758
+ - **load_skill**: Load specialized knowledge documents for specific tasks
1759
+
1760
+ ## Guidelines
1761
+
1762
+ ### Code Quality
1763
+ - Write clean, maintainable, well-documented code
1764
+ - Follow existing code style and conventions in the project
1765
+ - Use meaningful variable and function names
1766
+ - Add comments for complex logic
1767
+
1768
+ ### Problem Solving
1769
+ - Before making changes, understand the existing code structure
1770
+ - Break complex tasks into smaller, manageable steps using the todo tool
1771
+ - Test changes when possible using the bash tool
1772
+ - Handle errors gracefully and provide helpful error messages
1773
+
1774
+ ### File Operations
1775
+ - Use \`read_file\` to understand code before modifying
1776
+ - Use \`write_file\` with mode "str_replace" for targeted edits to existing files
1777
+ - Use \`write_file\` with mode "full" only for new files or complete rewrites
1778
+ - Always verify changes by reading files after modifications
1779
+
1780
+ ### Communication
1781
+ - Explain your reasoning and approach
1782
+ - Be concise but thorough
1783
+ - Ask clarifying questions when requirements are ambiguous
1784
+ - Report progress on multi-step tasks
1785
+
1786
+ ## Skills
1787
+ ${skillsContext}
1788
+
1789
+ ## Current Task List
1790
+ ${todosContext}
1791
+
1792
+ ${customInstructions ? `## Custom Instructions
1793
+ ${customInstructions}` : ""}
1794
+
1795
+ Remember: You are a helpful, capable coding assistant. Take initiative, be thorough, and deliver high-quality results.`;
1796
+ return systemPrompt;
1797
+ }
1798
+ function formatTodosForContext(todos) {
1799
+ if (todos.length === 0) {
1800
+ return "No active tasks. Use the todo tool to create a plan for complex operations.";
1801
+ }
1802
+ const statusEmoji = {
1803
+ pending: "\u2B1C",
1804
+ in_progress: "\u{1F504}",
1805
+ completed: "\u2705",
1806
+ cancelled: "\u274C"
1807
+ };
1808
+ const lines = ["Current tasks:"];
1809
+ for (const todo of todos) {
1810
+ const emoji = statusEmoji[todo.status] || "\u2022";
1811
+ lines.push(`${emoji} [${todo.id}] ${todo.content}`);
1812
+ }
1813
+ return lines.join("\n");
1814
+ }
1815
+ function createSummaryPrompt(conversationHistory) {
1816
+ return `Please provide a concise summary of the following conversation history. Focus on:
1817
+ 1. The main task or goal being worked on
1818
+ 2. Key decisions made
1819
+ 3. Important code changes or file operations performed
1820
+ 4. Current state and any pending actions
1821
+
1822
+ Keep the summary under 2000 characters while preserving essential context for continuing the work.
1823
+
1824
+ Conversation to summarize:
1825
+ ${conversationHistory}
1826
+
1827
+ Summary:`;
1828
+ }
1829
+
1830
+ // src/agent/context.ts
1831
+ var ContextManager = class {
1832
+ sessionId;
1833
+ maxContextChars;
1834
+ keepRecentMessages;
1835
+ autoSummarize;
1836
+ summary = null;
1837
+ constructor(options) {
1838
+ this.sessionId = options.sessionId;
1839
+ this.maxContextChars = options.maxContextChars;
1840
+ this.keepRecentMessages = options.keepRecentMessages;
1841
+ this.autoSummarize = options.autoSummarize;
1842
+ }
1843
+ /**
1844
+ * Get messages for the current context
1845
+ * Returns ModelMessage[] that can be passed directly to streamText/generateText
1846
+ */
1847
+ async getMessages() {
1848
+ let modelMessages = messageQueries.getModelMessages(this.sessionId);
1849
+ const contextSize = calculateContextSize(modelMessages);
1850
+ if (this.autoSummarize && contextSize > this.maxContextChars) {
1851
+ modelMessages = await this.summarizeContext(modelMessages);
1852
+ }
1853
+ if (this.summary) {
1854
+ modelMessages = [
1855
+ {
1856
+ role: "system",
1857
+ content: `[Previous conversation summary]
1858
+ ${this.summary}`
1859
+ },
1860
+ ...modelMessages
1861
+ ];
1862
+ }
1863
+ return modelMessages;
1864
+ }
1865
+ /**
1866
+ * Summarize older messages to reduce context size
1867
+ */
1868
+ async summarizeContext(messages2) {
1869
+ if (messages2.length <= this.keepRecentMessages) {
1870
+ return messages2;
1871
+ }
1872
+ const splitIndex = messages2.length - this.keepRecentMessages;
1873
+ const oldMessages = messages2.slice(0, splitIndex);
1874
+ const recentMessages = messages2.slice(splitIndex);
1875
+ const historyText = oldMessages.map((msg) => {
1876
+ const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1877
+ return `[${msg.role}]: ${content}`;
1878
+ }).join("\n\n");
1879
+ try {
1880
+ const config = getConfig();
1881
+ const summaryPrompt = createSummaryPrompt(historyText);
1882
+ const result = await generateText({
1883
+ model: gateway(config.defaultModel),
1884
+ prompt: summaryPrompt
1885
+ });
1886
+ this.summary = result.text;
1887
+ console.log(`[Context] Summarized ${oldMessages.length} messages into ${this.summary.length} chars`);
1888
+ return recentMessages;
1889
+ } catch (error) {
1890
+ console.error("[Context] Failed to summarize:", error);
1891
+ return recentMessages;
1892
+ }
1893
+ }
1894
+ /**
1895
+ * Add a user message to the context
1896
+ */
1897
+ addUserMessage(text2) {
1898
+ const userMessage = {
1899
+ role: "user",
1900
+ content: text2
1901
+ };
1902
+ messageQueries.create(this.sessionId, userMessage);
1903
+ }
1904
+ /**
1905
+ * Add response messages from AI SDK directly
1906
+ * This is the preferred method - use result.response.messages from streamText/generateText
1907
+ */
1908
+ addResponseMessages(messages2) {
1909
+ messageQueries.addMany(this.sessionId, messages2);
1910
+ }
1911
+ /**
1912
+ * Get current context statistics
1913
+ */
1914
+ getStats() {
1915
+ const messages2 = messageQueries.getModelMessages(this.sessionId);
1916
+ return {
1917
+ messageCount: messages2.length,
1918
+ contextChars: calculateContextSize(messages2),
1919
+ hasSummary: this.summary !== null
1920
+ };
1921
+ }
1922
+ /**
1923
+ * Clear all messages in the context
1924
+ */
1925
+ clear() {
1926
+ messageQueries.deleteBySession(this.sessionId);
1927
+ this.summary = null;
1928
+ }
1929
+ };
1930
+
1931
+ // src/agent/index.ts
1932
+ var approvalResolvers = /* @__PURE__ */ new Map();
1933
+ var Agent = class _Agent {
1934
+ session;
1935
+ context;
1936
+ tools;
1937
+ pendingApprovals = /* @__PURE__ */ new Map();
1938
+ constructor(session, context, tools) {
1939
+ this.session = session;
1940
+ this.context = context;
1941
+ this.tools = tools;
1942
+ }
1943
+ /**
1944
+ * Create or resume an agent session
1945
+ */
1946
+ static async create(options = {}) {
1947
+ const config = getConfig();
1948
+ let session;
1949
+ if (options.sessionId) {
1950
+ const existing = sessionQueries.getById(options.sessionId);
1951
+ if (!existing) {
1952
+ throw new Error(`Session not found: ${options.sessionId}`);
1953
+ }
1954
+ session = existing;
1955
+ } else {
1956
+ session = sessionQueries.create({
1957
+ name: options.name,
1958
+ workingDirectory: options.workingDirectory || config.resolvedWorkingDirectory,
1959
+ model: options.model || config.defaultModel,
1960
+ config: options.sessionConfig
1961
+ });
1962
+ }
1963
+ const context = new ContextManager({
1964
+ sessionId: session.id,
1965
+ maxContextChars: config.context?.maxChars || 2e5,
1966
+ keepRecentMessages: config.context?.keepRecentMessages || 10,
1967
+ autoSummarize: config.context?.autoSummarize ?? true
1968
+ });
1969
+ const tools = createTools({
1970
+ sessionId: session.id,
1971
+ workingDirectory: session.workingDirectory,
1972
+ skillsDirectories: config.resolvedSkillsDirectories
1973
+ });
1974
+ return new _Agent(session, context, tools);
1975
+ }
1976
+ /**
1977
+ * Get the session ID
1978
+ */
1979
+ get sessionId() {
1980
+ return this.session.id;
1981
+ }
1982
+ /**
1983
+ * Get session details
1984
+ */
1985
+ getSession() {
1986
+ return this.session;
1987
+ }
1988
+ /**
1989
+ * Run the agent with a prompt (streaming)
1990
+ */
1991
+ async stream(options) {
1992
+ const config = getConfig();
1993
+ this.context.addUserMessage(options.prompt);
1994
+ sessionQueries.updateStatus(this.session.id, "active");
1995
+ const systemPrompt = await buildSystemPrompt({
1996
+ workingDirectory: this.session.workingDirectory,
1997
+ skillsDirectories: config.resolvedSkillsDirectories,
1998
+ sessionId: this.session.id
1999
+ });
2000
+ const messages2 = await this.context.getMessages();
2001
+ const wrappedTools = this.wrapToolsWithApproval(options);
2002
+ const stream = streamText({
2003
+ model: gateway2(this.session.model),
2004
+ system: systemPrompt,
2005
+ messages: messages2,
2006
+ tools: wrappedTools,
2007
+ stopWhen: stepCountIs(20),
2008
+ onStepFinish: async (step) => {
2009
+ options.onStepFinish?.(step);
2010
+ }
2011
+ });
2012
+ const saveResponseMessages = async () => {
2013
+ const result = await stream;
2014
+ const response = await result.response;
2015
+ const responseMessages = response.messages;
2016
+ this.context.addResponseMessages(responseMessages);
2017
+ };
2018
+ return {
2019
+ sessionId: this.session.id,
2020
+ stream,
2021
+ waitForApprovals: () => this.waitForApprovals(),
2022
+ saveResponseMessages
2023
+ };
2024
+ }
2025
+ /**
2026
+ * Run the agent with a prompt (non-streaming)
2027
+ */
2028
+ async run(options) {
2029
+ const config = getConfig();
2030
+ this.context.addUserMessage(options.prompt);
2031
+ const systemPrompt = await buildSystemPrompt({
2032
+ workingDirectory: this.session.workingDirectory,
2033
+ skillsDirectories: config.resolvedSkillsDirectories,
2034
+ sessionId: this.session.id
2035
+ });
2036
+ const messages2 = await this.context.getMessages();
2037
+ const wrappedTools = this.wrapToolsWithApproval(options);
2038
+ const result = await generateText2({
2039
+ model: gateway2(this.session.model),
2040
+ system: systemPrompt,
2041
+ messages: messages2,
2042
+ tools: wrappedTools,
2043
+ stopWhen: stepCountIs(20)
2044
+ });
2045
+ const responseMessages = result.response.messages;
2046
+ this.context.addResponseMessages(responseMessages);
2047
+ return {
2048
+ text: result.text,
2049
+ steps: result.steps
2050
+ };
2051
+ }
2052
+ /**
2053
+ * Wrap tools to add approval checking
2054
+ */
2055
+ wrapToolsWithApproval(options) {
2056
+ const sessionConfig = this.session.config;
2057
+ const wrappedTools = {};
2058
+ for (const [name, originalTool] of Object.entries(this.tools)) {
2059
+ const needsApproval = requiresApproval(name, sessionConfig ?? void 0);
2060
+ if (!needsApproval) {
2061
+ wrappedTools[name] = originalTool;
2062
+ continue;
2063
+ }
2064
+ wrappedTools[name] = tool7({
2065
+ description: originalTool.description || "",
2066
+ inputSchema: originalTool.inputSchema || z8.object({}),
2067
+ execute: async (input, toolOptions) => {
2068
+ const toolCallId = toolOptions.toolCallId || nanoid2();
2069
+ const execution = toolExecutionQueries.create({
2070
+ sessionId: this.session.id,
2071
+ toolName: name,
2072
+ toolCallId,
2073
+ input,
2074
+ requiresApproval: true,
2075
+ status: "pending"
2076
+ });
2077
+ this.pendingApprovals.set(toolCallId, execution);
2078
+ options.onApprovalRequired?.(execution);
2079
+ sessionQueries.updateStatus(this.session.id, "waiting");
2080
+ const approved = await new Promise((resolve5) => {
2081
+ approvalResolvers.set(toolCallId, { resolve: resolve5, sessionId: this.session.id });
2082
+ });
2083
+ const resolverData = approvalResolvers.get(toolCallId);
2084
+ approvalResolvers.delete(toolCallId);
2085
+ this.pendingApprovals.delete(toolCallId);
2086
+ if (!approved) {
2087
+ const reason = resolverData?.reason || "User rejected the tool execution";
2088
+ toolExecutionQueries.reject(execution.id);
2089
+ sessionQueries.updateStatus(this.session.id, "active");
2090
+ return {
2091
+ status: "rejected",
2092
+ toolCallId,
2093
+ rejected: true,
2094
+ reason,
2095
+ message: `Tool "${name}" was rejected by the user. Reason: ${reason}`
2096
+ };
2097
+ }
2098
+ toolExecutionQueries.approve(execution.id);
2099
+ sessionQueries.updateStatus(this.session.id, "active");
2100
+ try {
2101
+ const result = await originalTool.execute(input, toolOptions);
2102
+ toolExecutionQueries.complete(execution.id, result);
2103
+ return result;
2104
+ } catch (error) {
2105
+ toolExecutionQueries.complete(execution.id, null, error.message);
2106
+ throw error;
2107
+ }
2108
+ }
2109
+ });
2110
+ }
2111
+ return wrappedTools;
2112
+ }
2113
+ /**
2114
+ * Wait for all pending approvals
2115
+ */
2116
+ async waitForApprovals() {
2117
+ return Array.from(this.pendingApprovals.values());
2118
+ }
2119
+ /**
2120
+ * Approve a pending tool execution
2121
+ */
2122
+ async approve(toolCallId) {
2123
+ const resolver = approvalResolvers.get(toolCallId);
2124
+ if (resolver) {
2125
+ resolver.resolve(true);
2126
+ return { approved: true };
2127
+ }
2128
+ const pendingFromDb = toolExecutionQueries.getPendingApprovals(this.session.id);
2129
+ const execution = pendingFromDb.find((e) => e.toolCallId === toolCallId);
2130
+ if (!execution) {
2131
+ throw new Error(`No pending approval for tool call: ${toolCallId}`);
2132
+ }
2133
+ toolExecutionQueries.approve(execution.id);
2134
+ return { approved: true };
2135
+ }
2136
+ /**
2137
+ * Reject a pending tool execution
2138
+ */
2139
+ reject(toolCallId, reason) {
2140
+ const resolver = approvalResolvers.get(toolCallId);
2141
+ if (resolver) {
2142
+ resolver.reason = reason;
2143
+ resolver.resolve(false);
2144
+ return { rejected: true };
2145
+ }
2146
+ const pendingFromDb = toolExecutionQueries.getPendingApprovals(this.session.id);
2147
+ const execution = pendingFromDb.find((e) => e.toolCallId === toolCallId);
2148
+ if (!execution) {
2149
+ throw new Error(`No pending approval for tool call: ${toolCallId}`);
2150
+ }
2151
+ toolExecutionQueries.reject(execution.id);
2152
+ return { rejected: true };
2153
+ }
2154
+ /**
2155
+ * Get pending approvals
2156
+ */
2157
+ getPendingApprovals() {
2158
+ return toolExecutionQueries.getPendingApprovals(this.session.id);
2159
+ }
2160
+ /**
2161
+ * Get context statistics
2162
+ */
2163
+ getContextStats() {
2164
+ return this.context.getStats();
2165
+ }
2166
+ /**
2167
+ * Clear conversation context (start fresh)
2168
+ */
2169
+ clearContext() {
2170
+ this.context.clear();
2171
+ }
2172
+ };
2173
+
2174
+ // src/server/routes/sessions.ts
2175
+ var sessions2 = new Hono();
2176
+ var createSessionSchema = z9.object({
2177
+ name: z9.string().optional(),
2178
+ workingDirectory: z9.string().optional(),
2179
+ model: z9.string().optional(),
2180
+ toolApprovals: z9.record(z9.string(), z9.boolean()).optional()
2181
+ });
2182
+ var paginationQuerySchema = z9.object({
2183
+ limit: z9.string().optional(),
2184
+ offset: z9.string().optional()
2185
+ });
2186
+ var messagesQuerySchema = z9.object({
2187
+ limit: z9.string().optional()
2188
+ });
2189
+ sessions2.get(
2190
+ "/",
2191
+ zValidator("query", paginationQuerySchema),
2192
+ async (c) => {
2193
+ const query = c.req.valid("query");
2194
+ const limit = parseInt(query.limit || "50");
2195
+ const offset = parseInt(query.offset || "0");
2196
+ const allSessions = sessionQueries.list(limit, offset);
2197
+ return c.json({
2198
+ sessions: allSessions.map((s) => ({
2199
+ id: s.id,
2200
+ name: s.name,
2201
+ workingDirectory: s.workingDirectory,
2202
+ model: s.model,
2203
+ status: s.status,
2204
+ createdAt: s.createdAt.toISOString(),
2205
+ updatedAt: s.updatedAt.toISOString()
2206
+ })),
2207
+ count: allSessions.length,
2208
+ limit,
2209
+ offset
2210
+ });
2211
+ }
2212
+ );
2213
+ sessions2.post(
2214
+ "/",
2215
+ zValidator("json", createSessionSchema),
2216
+ async (c) => {
2217
+ const body = c.req.valid("json");
2218
+ const config = getConfig();
2219
+ const agent = await Agent.create({
2220
+ name: body.name,
2221
+ workingDirectory: body.workingDirectory || config.resolvedWorkingDirectory,
2222
+ model: body.model || config.defaultModel,
2223
+ sessionConfig: body.toolApprovals ? { toolApprovals: body.toolApprovals } : void 0
2224
+ });
2225
+ const session = agent.getSession();
2226
+ return c.json({
2227
+ id: session.id,
2228
+ name: session.name,
2229
+ workingDirectory: session.workingDirectory,
2230
+ model: session.model,
2231
+ status: session.status,
2232
+ createdAt: session.createdAt.toISOString()
2233
+ }, 201);
2234
+ }
2235
+ );
2236
+ sessions2.get("/:id", async (c) => {
2237
+ const id = c.req.param("id");
2238
+ const session = sessionQueries.getById(id);
2239
+ if (!session) {
2240
+ return c.json({ error: "Session not found" }, 404);
2241
+ }
2242
+ const contextStats = await (async () => {
2243
+ const agent = await Agent.create({ sessionId: id });
2244
+ return agent.getContextStats();
2245
+ })();
2246
+ const todos = todoQueries.getBySession(id);
2247
+ const pendingApprovals = toolExecutionQueries.getPendingApprovals(id);
2248
+ return c.json({
2249
+ id: session.id,
2250
+ name: session.name,
2251
+ workingDirectory: session.workingDirectory,
2252
+ model: session.model,
2253
+ status: session.status,
2254
+ config: session.config,
2255
+ createdAt: session.createdAt.toISOString(),
2256
+ updatedAt: session.updatedAt.toISOString(),
2257
+ context: contextStats,
2258
+ todos: todos.map((t) => ({
2259
+ id: t.id,
2260
+ content: t.content,
2261
+ status: t.status,
2262
+ order: t.order
2263
+ })),
2264
+ pendingApprovals: pendingApprovals.map((p) => ({
2265
+ id: p.id,
2266
+ toolCallId: p.toolCallId,
2267
+ toolName: p.toolName,
2268
+ input: p.input
2269
+ }))
2270
+ });
2271
+ });
2272
+ sessions2.get(
2273
+ "/:id/messages",
2274
+ zValidator("query", messagesQuerySchema),
2275
+ async (c) => {
2276
+ const id = c.req.param("id");
2277
+ const query = c.req.valid("query");
2278
+ const limit = parseInt(query.limit || "100");
2279
+ const session = sessionQueries.getById(id);
2280
+ if (!session) {
2281
+ return c.json({ error: "Session not found" }, 404);
2282
+ }
2283
+ const messages2 = messageQueries.getRecentBySession(id, limit);
2284
+ return c.json({
2285
+ sessionId: id,
2286
+ messages: messages2.map((m) => ({
2287
+ id: m.id,
2288
+ ...m.modelMessage,
2289
+ // Spread the AI SDK ModelMessage (role, content)
2290
+ createdAt: m.createdAt.toISOString()
2291
+ })),
2292
+ count: messages2.length
2293
+ });
2294
+ }
2295
+ );
2296
+ sessions2.get("/:id/tools", async (c) => {
2297
+ const id = c.req.param("id");
2298
+ const session = sessionQueries.getById(id);
2299
+ if (!session) {
2300
+ return c.json({ error: "Session not found" }, 404);
2301
+ }
2302
+ const executions = toolExecutionQueries.getBySession(id);
2303
+ return c.json({
2304
+ sessionId: id,
2305
+ executions: executions.map((e) => ({
2306
+ id: e.id,
2307
+ toolCallId: e.toolCallId,
2308
+ toolName: e.toolName,
2309
+ input: e.input,
2310
+ output: e.output,
2311
+ status: e.status,
2312
+ requiresApproval: e.requiresApproval,
2313
+ error: e.error,
2314
+ startedAt: e.startedAt.toISOString(),
2315
+ completedAt: e.completedAt?.toISOString()
2316
+ })),
2317
+ count: executions.length
2318
+ });
2319
+ });
2320
+ sessions2.delete("/:id", async (c) => {
2321
+ const id = c.req.param("id");
2322
+ try {
2323
+ const manager = getTerminalManager();
2324
+ manager.killAll(id);
2325
+ } catch (e) {
2326
+ }
2327
+ const deleted = sessionQueries.delete(id);
2328
+ if (!deleted) {
2329
+ return c.json({ error: "Session not found" }, 404);
2330
+ }
2331
+ return c.json({ success: true, id });
2332
+ });
2333
+ sessions2.post("/:id/clear", async (c) => {
2334
+ const id = c.req.param("id");
2335
+ const session = sessionQueries.getById(id);
2336
+ if (!session) {
2337
+ return c.json({ error: "Session not found" }, 404);
2338
+ }
2339
+ const agent = await Agent.create({ sessionId: id });
2340
+ agent.clearContext();
2341
+ return c.json({ success: true, sessionId: id });
2342
+ });
2343
+
2344
+ // src/server/routes/agents.ts
2345
+ import { Hono as Hono2 } from "hono";
2346
+ import { zValidator as zValidator2 } from "@hono/zod-validator";
2347
+ import { streamSSE } from "hono/streaming";
2348
+ import { z as z10 } from "zod";
2349
+ var agents = new Hono2();
2350
+ var runPromptSchema = z10.object({
2351
+ prompt: z10.string().min(1)
2352
+ });
2353
+ var quickStartSchema = z10.object({
2354
+ prompt: z10.string().min(1),
2355
+ name: z10.string().optional(),
2356
+ workingDirectory: z10.string().optional(),
2357
+ model: z10.string().optional(),
2358
+ toolApprovals: z10.record(z10.string(), z10.boolean()).optional()
2359
+ });
2360
+ var rejectSchema = z10.object({
2361
+ reason: z10.string().optional()
2362
+ }).optional();
2363
+ agents.post(
2364
+ "/:id/run",
2365
+ zValidator2("json", runPromptSchema),
2366
+ async (c) => {
2367
+ const id = c.req.param("id");
2368
+ const { prompt } = c.req.valid("json");
2369
+ const session = sessionQueries.getById(id);
2370
+ if (!session) {
2371
+ return c.json({ error: "Session not found" }, 404);
2372
+ }
2373
+ c.header("Content-Type", "text/event-stream");
2374
+ c.header("Cache-Control", "no-cache");
2375
+ c.header("Connection", "keep-alive");
2376
+ c.header("x-vercel-ai-ui-message-stream", "v1");
2377
+ return streamSSE(c, async (stream) => {
2378
+ try {
2379
+ const agent = await Agent.create({ sessionId: id });
2380
+ const messageId = `msg_${Date.now()}`;
2381
+ await stream.writeSSE({
2382
+ data: JSON.stringify({ type: "start", messageId })
2383
+ });
2384
+ let textId = `text_${Date.now()}`;
2385
+ let textStarted = false;
2386
+ const result = await agent.stream({
2387
+ prompt,
2388
+ onToolCall: async (toolCall) => {
2389
+ await stream.writeSSE({
2390
+ data: JSON.stringify({
2391
+ type: "tool-input-start",
2392
+ toolCallId: toolCall.toolCallId,
2393
+ toolName: toolCall.toolName
2394
+ })
2395
+ });
2396
+ await stream.writeSSE({
2397
+ data: JSON.stringify({
2398
+ type: "tool-input-available",
2399
+ toolCallId: toolCall.toolCallId,
2400
+ toolName: toolCall.toolName,
2401
+ input: toolCall.input
2402
+ })
2403
+ });
2404
+ },
2405
+ onToolResult: async (result2) => {
2406
+ await stream.writeSSE({
2407
+ data: JSON.stringify({
2408
+ type: "tool-output-available",
2409
+ toolCallId: result2.toolCallId,
2410
+ output: result2.output
2411
+ })
2412
+ });
2413
+ },
2414
+ onApprovalRequired: async (execution) => {
2415
+ await stream.writeSSE({
2416
+ data: JSON.stringify({
2417
+ type: "data-approval-required",
2418
+ data: {
2419
+ id: execution.id,
2420
+ toolCallId: execution.toolCallId,
2421
+ toolName: execution.toolName,
2422
+ input: execution.input
2423
+ }
2424
+ })
2425
+ });
2426
+ },
2427
+ onStepFinish: async () => {
2428
+ await stream.writeSSE({
2429
+ data: JSON.stringify({ type: "finish-step" })
2430
+ });
2431
+ if (textStarted) {
2432
+ await stream.writeSSE({
2433
+ data: JSON.stringify({ type: "text-end", id: textId })
2434
+ });
2435
+ textStarted = false;
2436
+ textId = `text_${Date.now()}`;
2437
+ }
2438
+ }
2439
+ });
2440
+ for await (const part of result.stream.fullStream) {
2441
+ if (part.type === "text-delta") {
2442
+ if (!textStarted) {
2443
+ await stream.writeSSE({
2444
+ data: JSON.stringify({ type: "text-start", id: textId })
2445
+ });
2446
+ textStarted = true;
2447
+ }
2448
+ await stream.writeSSE({
2449
+ data: JSON.stringify({ type: "text-delta", id: textId, delta: part.text })
2450
+ });
2451
+ } else if (part.type === "tool-call") {
2452
+ await stream.writeSSE({
2453
+ data: JSON.stringify({
2454
+ type: "tool-input-available",
2455
+ toolCallId: part.toolCallId,
2456
+ toolName: part.toolName,
2457
+ input: part.input
2458
+ })
2459
+ });
2460
+ } else if (part.type === "tool-result") {
2461
+ await stream.writeSSE({
2462
+ data: JSON.stringify({
2463
+ type: "tool-output-available",
2464
+ toolCallId: part.toolCallId,
2465
+ output: part.output
2466
+ })
2467
+ });
2468
+ } else if (part.type === "error") {
2469
+ console.error("Stream error:", part.error);
2470
+ await stream.writeSSE({
2471
+ data: JSON.stringify({ type: "error", errorText: String(part.error) })
2472
+ });
2473
+ }
2474
+ }
2475
+ if (textStarted) {
2476
+ await stream.writeSSE({
2477
+ data: JSON.stringify({ type: "text-end", id: textId })
2478
+ });
2479
+ }
2480
+ await result.saveResponseMessages();
2481
+ await stream.writeSSE({
2482
+ data: JSON.stringify({ type: "finish" })
2483
+ });
2484
+ await stream.writeSSE({ data: "[DONE]" });
2485
+ } catch (error) {
2486
+ await stream.writeSSE({
2487
+ data: JSON.stringify({
2488
+ type: "error",
2489
+ errorText: error.message
2490
+ })
2491
+ });
2492
+ await stream.writeSSE({ data: "[DONE]" });
2493
+ }
2494
+ });
2495
+ }
2496
+ );
2497
+ agents.post(
2498
+ "/:id/generate",
2499
+ zValidator2("json", runPromptSchema),
2500
+ async (c) => {
2501
+ const id = c.req.param("id");
2502
+ const { prompt } = c.req.valid("json");
2503
+ const session = sessionQueries.getById(id);
2504
+ if (!session) {
2505
+ return c.json({ error: "Session not found" }, 404);
2506
+ }
2507
+ try {
2508
+ const agent = await Agent.create({ sessionId: id });
2509
+ const result = await agent.run({ prompt });
2510
+ return c.json({
2511
+ sessionId: id,
2512
+ text: result.text,
2513
+ stepCount: result.steps.length
2514
+ });
2515
+ } catch (error) {
2516
+ return c.json({ error: error.message }, 500);
2517
+ }
2518
+ }
2519
+ );
2520
+ agents.post("/:id/approve/:toolCallId", async (c) => {
2521
+ const sessionId = c.req.param("id");
2522
+ const toolCallId = c.req.param("toolCallId");
2523
+ const session = sessionQueries.getById(sessionId);
2524
+ if (!session) {
2525
+ return c.json({ error: "Session not found" }, 404);
2526
+ }
2527
+ try {
2528
+ const agent = await Agent.create({ sessionId });
2529
+ const result = await agent.approve(toolCallId);
2530
+ return c.json({
2531
+ success: true,
2532
+ toolCallId,
2533
+ result
2534
+ });
2535
+ } catch (error) {
2536
+ return c.json({ error: error.message }, 400);
2537
+ }
2538
+ });
2539
+ agents.post(
2540
+ "/:id/reject/:toolCallId",
2541
+ zValidator2("json", rejectSchema),
2542
+ async (c) => {
2543
+ const sessionId = c.req.param("id");
2544
+ const toolCallId = c.req.param("toolCallId");
2545
+ const body = c.req.valid("json");
2546
+ const session = sessionQueries.getById(sessionId);
2547
+ if (!session) {
2548
+ return c.json({ error: "Session not found" }, 404);
2549
+ }
2550
+ try {
2551
+ const agent = await Agent.create({ sessionId });
2552
+ agent.reject(toolCallId, body?.reason);
2553
+ return c.json({
2554
+ success: true,
2555
+ toolCallId,
2556
+ rejected: true
2557
+ });
2558
+ } catch (error) {
2559
+ return c.json({ error: error.message }, 400);
2560
+ }
2561
+ }
2562
+ );
2563
+ agents.get("/:id/approvals", async (c) => {
2564
+ const sessionId = c.req.param("id");
2565
+ const session = sessionQueries.getById(sessionId);
2566
+ if (!session) {
2567
+ return c.json({ error: "Session not found" }, 404);
2568
+ }
2569
+ const pendingApprovals = toolExecutionQueries.getPendingApprovals(sessionId);
2570
+ return c.json({
2571
+ sessionId,
2572
+ pendingApprovals: pendingApprovals.map((p) => ({
2573
+ id: p.id,
2574
+ toolCallId: p.toolCallId,
2575
+ toolName: p.toolName,
2576
+ input: p.input,
2577
+ startedAt: p.startedAt.toISOString()
2578
+ })),
2579
+ count: pendingApprovals.length
2580
+ });
2581
+ });
2582
+ agents.post(
2583
+ "/quick",
2584
+ zValidator2("json", quickStartSchema),
2585
+ async (c) => {
2586
+ const body = c.req.valid("json");
2587
+ const config = getConfig();
2588
+ const agent = await Agent.create({
2589
+ name: body.name,
2590
+ workingDirectory: body.workingDirectory || config.resolvedWorkingDirectory,
2591
+ model: body.model || config.defaultModel,
2592
+ sessionConfig: body.toolApprovals ? { toolApprovals: body.toolApprovals } : void 0
2593
+ });
2594
+ const session = agent.getSession();
2595
+ c.header("Content-Type", "text/event-stream");
2596
+ c.header("Cache-Control", "no-cache");
2597
+ c.header("Connection", "keep-alive");
2598
+ c.header("x-vercel-ai-ui-message-stream", "v1");
2599
+ return streamSSE(c, async (stream) => {
2600
+ try {
2601
+ await stream.writeSSE({
2602
+ data: JSON.stringify({
2603
+ type: "data-session",
2604
+ data: {
2605
+ id: session.id,
2606
+ name: session.name,
2607
+ workingDirectory: session.workingDirectory,
2608
+ model: session.model
2609
+ }
2610
+ })
2611
+ });
2612
+ const messageId = `msg_${Date.now()}`;
2613
+ await stream.writeSSE({
2614
+ data: JSON.stringify({ type: "start", messageId })
2615
+ });
2616
+ let textId = `text_${Date.now()}`;
2617
+ let textStarted = false;
2618
+ const result = await agent.stream({
2619
+ prompt: body.prompt,
2620
+ onStepFinish: async () => {
2621
+ await stream.writeSSE({
2622
+ data: JSON.stringify({ type: "finish-step" })
2623
+ });
2624
+ if (textStarted) {
2625
+ await stream.writeSSE({
2626
+ data: JSON.stringify({ type: "text-end", id: textId })
2627
+ });
2628
+ textStarted = false;
2629
+ textId = `text_${Date.now()}`;
2630
+ }
2631
+ }
2632
+ });
2633
+ for await (const part of result.stream.fullStream) {
2634
+ if (part.type === "text-delta") {
2635
+ if (!textStarted) {
2636
+ await stream.writeSSE({
2637
+ data: JSON.stringify({ type: "text-start", id: textId })
2638
+ });
2639
+ textStarted = true;
2640
+ }
2641
+ await stream.writeSSE({
2642
+ data: JSON.stringify({ type: "text-delta", id: textId, delta: part.text })
2643
+ });
2644
+ } else if (part.type === "error") {
2645
+ console.error("Stream error:", part.error);
2646
+ await stream.writeSSE({
2647
+ data: JSON.stringify({ type: "error", errorText: String(part.error) })
2648
+ });
2649
+ }
2650
+ }
2651
+ if (textStarted) {
2652
+ await stream.writeSSE({
2653
+ data: JSON.stringify({ type: "text-end", id: textId })
2654
+ });
2655
+ }
2656
+ await result.saveResponseMessages();
2657
+ await stream.writeSSE({
2658
+ data: JSON.stringify({ type: "finish" })
2659
+ });
2660
+ await stream.writeSSE({ data: "[DONE]" });
2661
+ } catch (error) {
2662
+ console.error("Agent error:", error);
2663
+ await stream.writeSSE({
2664
+ data: JSON.stringify({ type: "error", errorText: error.message })
2665
+ });
2666
+ await stream.writeSSE({ data: "[DONE]" });
2667
+ }
2668
+ });
2669
+ }
2670
+ );
2671
+
2672
+ // src/server/routes/health.ts
2673
+ import { Hono as Hono3 } from "hono";
2674
+ var health = new Hono3();
2675
+ health.get("/", async (c) => {
2676
+ const config = getConfig();
2677
+ return c.json({
2678
+ status: "ok",
2679
+ version: "0.1.0",
2680
+ uptime: process.uptime(),
2681
+ config: {
2682
+ workingDirectory: config.resolvedWorkingDirectory,
2683
+ defaultModel: config.defaultModel,
2684
+ port: config.server.port
2685
+ },
2686
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2687
+ });
2688
+ });
2689
+ health.get("/ready", async (c) => {
2690
+ try {
2691
+ getConfig();
2692
+ return c.json({
2693
+ status: "ready",
2694
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2695
+ });
2696
+ } catch (error) {
2697
+ return c.json(
2698
+ {
2699
+ status: "not_ready",
2700
+ error: error.message,
2701
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2702
+ },
2703
+ 503
2704
+ );
2705
+ }
2706
+ });
2707
+
2708
+ // src/server/routes/terminals.ts
2709
+ import { Hono as Hono4 } from "hono";
2710
+ import { zValidator as zValidator3 } from "@hono/zod-validator";
2711
+ import { z as z11 } from "zod";
2712
+ var terminals2 = new Hono4();
2713
+ var spawnSchema = z11.object({
2714
+ command: z11.string(),
2715
+ cwd: z11.string().optional(),
2716
+ name: z11.string().optional()
2717
+ });
2718
+ terminals2.post(
2719
+ "/:sessionId/terminals",
2720
+ zValidator3("json", spawnSchema),
2721
+ async (c) => {
2722
+ const sessionId = c.req.param("sessionId");
2723
+ const body = c.req.valid("json");
2724
+ const session = sessionQueries.getById(sessionId);
2725
+ if (!session) {
2726
+ return c.json({ error: "Session not found" }, 404);
2727
+ }
2728
+ const manager = getTerminalManager();
2729
+ const terminal = manager.spawn({
2730
+ sessionId,
2731
+ command: body.command,
2732
+ cwd: body.cwd || session.workingDirectory,
2733
+ name: body.name
2734
+ });
2735
+ return c.json(terminal, 201);
2736
+ }
2737
+ );
2738
+ terminals2.get("/:sessionId/terminals", async (c) => {
2739
+ const sessionId = c.req.param("sessionId");
2740
+ const session = sessionQueries.getById(sessionId);
2741
+ if (!session) {
2742
+ return c.json({ error: "Session not found" }, 404);
2743
+ }
2744
+ const manager = getTerminalManager();
2745
+ const terminalList = manager.list(sessionId);
2746
+ return c.json({
2747
+ sessionId,
2748
+ terminals: terminalList,
2749
+ count: terminalList.length,
2750
+ running: terminalList.filter((t) => t.status === "running").length
2751
+ });
2752
+ });
2753
+ terminals2.get("/:sessionId/terminals/:terminalId", async (c) => {
2754
+ const sessionId = c.req.param("sessionId");
2755
+ const terminalId = c.req.param("terminalId");
2756
+ const manager = getTerminalManager();
2757
+ const terminal = manager.getStatus(terminalId);
2758
+ if (!terminal) {
2759
+ return c.json({ error: "Terminal not found" }, 404);
2760
+ }
2761
+ return c.json(terminal);
2762
+ });
2763
+ var logsQuerySchema = z11.object({
2764
+ tail: z11.string().optional().transform((v) => v ? parseInt(v, 10) : void 0)
2765
+ });
2766
+ terminals2.get(
2767
+ "/:sessionId/terminals/:terminalId/logs",
2768
+ zValidator3("query", logsQuerySchema),
2769
+ async (c) => {
2770
+ const terminalId = c.req.param("terminalId");
2771
+ const query = c.req.valid("query");
2772
+ const manager = getTerminalManager();
2773
+ const result = manager.getLogs(terminalId, query.tail);
2774
+ if (!result) {
2775
+ return c.json({ error: "Terminal not found" }, 404);
2776
+ }
2777
+ return c.json({
2778
+ terminalId,
2779
+ logs: result.logs,
2780
+ lineCount: result.lineCount
2781
+ });
2782
+ }
2783
+ );
2784
+ var killSchema = z11.object({
2785
+ signal: z11.enum(["SIGTERM", "SIGKILL"]).optional()
2786
+ });
2787
+ terminals2.post(
2788
+ "/:sessionId/terminals/:terminalId/kill",
2789
+ zValidator3("json", killSchema.optional()),
2790
+ async (c) => {
2791
+ const terminalId = c.req.param("terminalId");
2792
+ const body = await c.req.json().catch(() => ({}));
2793
+ const manager = getTerminalManager();
2794
+ const success = manager.kill(terminalId, body.signal);
2795
+ if (!success) {
2796
+ return c.json({ error: "Failed to kill terminal" }, 400);
2797
+ }
2798
+ return c.json({ success: true, message: `Sent ${body.signal || "SIGTERM"} to terminal` });
2799
+ }
2800
+ );
2801
+ var writeSchema = z11.object({
2802
+ input: z11.string()
2803
+ });
2804
+ terminals2.post(
2805
+ "/:sessionId/terminals/:terminalId/write",
2806
+ zValidator3("json", writeSchema),
2807
+ async (c) => {
2808
+ const terminalId = c.req.param("terminalId");
2809
+ const body = c.req.valid("json");
2810
+ const manager = getTerminalManager();
2811
+ const success = manager.write(terminalId, body.input);
2812
+ if (!success) {
2813
+ return c.json({ error: "Failed to write to terminal" }, 400);
2814
+ }
2815
+ return c.json({ success: true });
2816
+ }
2817
+ );
2818
+ terminals2.post("/:sessionId/terminals/kill-all", async (c) => {
2819
+ const sessionId = c.req.param("sessionId");
2820
+ const manager = getTerminalManager();
2821
+ const killed = manager.killAll(sessionId);
2822
+ return c.json({ success: true, killed });
2823
+ });
2824
+ terminals2.get("/:sessionId/terminals/:terminalId/stream", async (c) => {
2825
+ const terminalId = c.req.param("terminalId");
2826
+ const manager = getTerminalManager();
2827
+ const terminal = manager.getStatus(terminalId);
2828
+ if (!terminal) {
2829
+ return c.json({ error: "Terminal not found" }, 404);
2830
+ }
2831
+ c.header("Content-Type", "text/event-stream");
2832
+ c.header("Cache-Control", "no-cache");
2833
+ c.header("Connection", "keep-alive");
2834
+ return new Response(
2835
+ new ReadableStream({
2836
+ start(controller) {
2837
+ const encoder = new TextEncoder();
2838
+ const initialLogs = manager.getLogs(terminalId);
2839
+ if (initialLogs) {
2840
+ controller.enqueue(
2841
+ encoder.encode(`event: logs
2842
+ data: ${JSON.stringify({ logs: initialLogs.logs })}
2843
+
2844
+ `)
2845
+ );
2846
+ }
2847
+ const onStdout = ({ terminalId: tid, data }) => {
2848
+ if (tid === terminalId) {
2849
+ controller.enqueue(
2850
+ encoder.encode(`event: stdout
2851
+ data: ${JSON.stringify({ data })}
2852
+
2853
+ `)
2854
+ );
2855
+ }
2856
+ };
2857
+ const onStderr = ({ terminalId: tid, data }) => {
2858
+ if (tid === terminalId) {
2859
+ controller.enqueue(
2860
+ encoder.encode(`event: stderr
2861
+ data: ${JSON.stringify({ data })}
2862
+
2863
+ `)
2864
+ );
2865
+ }
2866
+ };
2867
+ const onExit = ({ terminalId: tid, code, signal }) => {
2868
+ if (tid === terminalId) {
2869
+ controller.enqueue(
2870
+ encoder.encode(`event: exit
2871
+ data: ${JSON.stringify({ code, signal })}
2872
+
2873
+ `)
2874
+ );
2875
+ cleanup();
2876
+ controller.close();
2877
+ }
2878
+ };
2879
+ const cleanup = () => {
2880
+ manager.off("stdout", onStdout);
2881
+ manager.off("stderr", onStderr);
2882
+ manager.off("exit", onExit);
2883
+ };
2884
+ manager.on("stdout", onStdout);
2885
+ manager.on("stderr", onStderr);
2886
+ manager.on("exit", onExit);
2887
+ if (terminal.status !== "running") {
2888
+ controller.enqueue(
2889
+ encoder.encode(`event: exit
2890
+ data: ${JSON.stringify({ code: terminal.exitCode, status: terminal.status })}
2891
+
2892
+ `)
2893
+ );
2894
+ cleanup();
2895
+ controller.close();
2896
+ }
2897
+ }
2898
+ }),
2899
+ {
2900
+ headers: {
2901
+ "Content-Type": "text/event-stream",
2902
+ "Cache-Control": "no-cache",
2903
+ "Connection": "keep-alive"
2904
+ }
2905
+ }
2906
+ );
2907
+ });
2908
+
2909
+ // src/server/index.ts
2910
+ var serverInstance = null;
2911
+ async function createApp() {
2912
+ const app = new Hono5();
2913
+ app.use("*", cors());
2914
+ app.use("*", logger());
2915
+ app.route("/health", health);
2916
+ app.route("/sessions", sessions2);
2917
+ app.route("/agents", agents);
2918
+ app.route("/sessions", terminals2);
2919
+ app.get("/openapi.json", async (c) => {
2920
+ return c.json(generateOpenAPISpec());
2921
+ });
2922
+ app.get("/swagger", (c) => {
2923
+ const html = `<!DOCTYPE html>
2924
+ <html lang="en">
2925
+ <head>
2926
+ <meta charset="UTF-8">
2927
+ <title>Sparkecoder API - Swagger UI</title>
2928
+ <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css">
2929
+ </head>
2930
+ <body>
2931
+ <div id="swagger-ui"></div>
2932
+ <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
2933
+ <script>
2934
+ SwaggerUIBundle({
2935
+ url: '/openapi.json',
2936
+ dom_id: '#swagger-ui',
2937
+ presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
2938
+ layout: "BaseLayout"
2939
+ });
2940
+ </script>
2941
+ </body>
2942
+ </html>`;
2943
+ return c.html(html);
2944
+ });
2945
+ app.get("/", (c) => {
2946
+ return c.json({
2947
+ name: "Sparkecoder API",
2948
+ version: "0.1.0",
2949
+ description: "A powerful coding agent CLI with HTTP API",
2950
+ docs: "/openapi.json",
2951
+ endpoints: {
2952
+ health: "/health",
2953
+ sessions: "/sessions",
2954
+ agents: "/agents",
2955
+ terminals: "/sessions/:sessionId/terminals"
2956
+ }
2957
+ });
2958
+ });
2959
+ return app;
2960
+ }
2961
+ async function startServer(options = {}) {
2962
+ const config = await loadConfig(options.configPath, options.workingDirectory);
2963
+ if (options.workingDirectory) {
2964
+ config.resolvedWorkingDirectory = options.workingDirectory;
2965
+ }
2966
+ if (!existsSync5(config.resolvedWorkingDirectory)) {
2967
+ mkdirSync(config.resolvedWorkingDirectory, { recursive: true });
2968
+ console.log(`\u{1F4C1} Created agent workspace: ${config.resolvedWorkingDirectory}`);
2969
+ }
2970
+ initDatabase(config.resolvedDatabasePath);
2971
+ const port = options.port || config.server.port;
2972
+ const host = options.host || config.server.host || "0.0.0.0";
2973
+ const app = await createApp();
2974
+ console.log(`
2975
+ \u{1F680} Sparkecoder API Server`);
2976
+ console.log(` \u2192 Running at http://${host}:${port}`);
2977
+ console.log(` \u2192 Working directory: ${config.resolvedWorkingDirectory}`);
2978
+ console.log(` \u2192 Default model: ${config.defaultModel}`);
2979
+ console.log(` \u2192 OpenAPI spec: http://${host}:${port}/openapi.json
2980
+ `);
2981
+ serverInstance = serve({
2982
+ fetch: app.fetch,
2983
+ port,
2984
+ hostname: host
2985
+ });
2986
+ return { app, port, host };
2987
+ }
2988
+ function stopServer() {
2989
+ try {
2990
+ const manager = getTerminalManager();
2991
+ manager.cleanup();
2992
+ } catch (e) {
2993
+ }
2994
+ if (serverInstance) {
2995
+ serverInstance.close();
2996
+ serverInstance = null;
2997
+ }
2998
+ closeDatabase();
2999
+ }
3000
+ function generateOpenAPISpec() {
3001
+ return {
3002
+ openapi: "3.1.0",
3003
+ info: {
3004
+ title: "Sparkecoder API",
3005
+ version: "0.1.0",
3006
+ description: "A powerful coding agent CLI with HTTP API for development environments. Supports streaming responses following the Vercel AI SDK data stream protocol."
3007
+ },
3008
+ servers: [{ url: "http://localhost:3141", description: "Local development" }],
3009
+ paths: {
3010
+ "/": {
3011
+ get: {
3012
+ summary: "API Info",
3013
+ description: "Get basic API information and available endpoints",
3014
+ responses: {
3015
+ 200: {
3016
+ description: "API information",
3017
+ content: { "application/json": {} }
3018
+ }
3019
+ }
3020
+ }
3021
+ },
3022
+ "/health": {
3023
+ get: {
3024
+ summary: "Health Check",
3025
+ description: "Check API health status and configuration",
3026
+ responses: {
3027
+ 200: {
3028
+ description: "API is healthy",
3029
+ content: { "application/json": {} }
3030
+ }
3031
+ }
3032
+ }
3033
+ },
3034
+ "/health/ready": {
3035
+ get: {
3036
+ summary: "Readiness Check",
3037
+ description: "Check if the API is ready to accept requests",
3038
+ responses: {
3039
+ 200: { description: "API is ready" },
3040
+ 503: { description: "API is not ready" }
3041
+ }
3042
+ }
3043
+ },
3044
+ "/sessions": {
3045
+ get: {
3046
+ summary: "List Sessions",
3047
+ description: "Get a list of all agent sessions",
3048
+ parameters: [
3049
+ { name: "limit", in: "query", schema: { type: "integer", default: 50 } },
3050
+ { name: "offset", in: "query", schema: { type: "integer", default: 0 } }
3051
+ ],
3052
+ responses: {
3053
+ 200: { description: "List of sessions" }
3054
+ }
3055
+ },
3056
+ post: {
3057
+ summary: "Create Session",
3058
+ description: "Create a new agent session",
3059
+ requestBody: {
3060
+ content: {
3061
+ "application/json": {
3062
+ schema: {
3063
+ type: "object",
3064
+ properties: {
3065
+ name: { type: "string" },
3066
+ workingDirectory: { type: "string" },
3067
+ model: { type: "string" },
3068
+ toolApprovals: { type: "object" }
3069
+ }
3070
+ }
3071
+ }
3072
+ }
3073
+ },
3074
+ responses: {
3075
+ 201: { description: "Session created" }
3076
+ }
3077
+ }
3078
+ },
3079
+ "/sessions/{id}": {
3080
+ get: {
3081
+ summary: "Get Session",
3082
+ description: "Get details of a specific session",
3083
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3084
+ responses: {
3085
+ 200: { description: "Session details" },
3086
+ 404: { description: "Session not found" }
3087
+ }
3088
+ },
3089
+ delete: {
3090
+ summary: "Delete Session",
3091
+ description: "Delete a session and all its data",
3092
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3093
+ responses: {
3094
+ 200: { description: "Session deleted" },
3095
+ 404: { description: "Session not found" }
3096
+ }
3097
+ }
3098
+ },
3099
+ "/sessions/{id}/messages": {
3100
+ get: {
3101
+ summary: "Get Messages",
3102
+ description: "Get message history for a session",
3103
+ parameters: [
3104
+ { name: "id", in: "path", required: true, schema: { type: "string" } },
3105
+ { name: "limit", in: "query", schema: { type: "integer", default: 100 } }
3106
+ ],
3107
+ responses: {
3108
+ 200: { description: "Message history" },
3109
+ 404: { description: "Session not found" }
3110
+ }
3111
+ }
3112
+ },
3113
+ "/sessions/{id}/clear": {
3114
+ post: {
3115
+ summary: "Clear Context",
3116
+ description: "Clear conversation context for a session",
3117
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3118
+ responses: {
3119
+ 200: { description: "Context cleared" },
3120
+ 404: { description: "Session not found" }
3121
+ }
3122
+ }
3123
+ },
3124
+ "/agents/{id}/run": {
3125
+ post: {
3126
+ summary: "Run Agent (Streaming)",
3127
+ description: "Run the agent with a prompt and receive streaming response. Returns SSE stream following Vercel AI SDK data stream protocol.",
3128
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3129
+ requestBody: {
3130
+ content: {
3131
+ "application/json": {
3132
+ schema: {
3133
+ type: "object",
3134
+ required: ["prompt"],
3135
+ properties: {
3136
+ prompt: { type: "string" }
3137
+ }
3138
+ }
3139
+ }
3140
+ }
3141
+ },
3142
+ responses: {
3143
+ 200: {
3144
+ description: "SSE stream of agent output",
3145
+ content: { "text/event-stream": {} }
3146
+ },
3147
+ 404: { description: "Session not found" }
3148
+ }
3149
+ }
3150
+ },
3151
+ "/agents/{id}/generate": {
3152
+ post: {
3153
+ summary: "Run Agent (Non-streaming)",
3154
+ description: "Run the agent and receive complete response",
3155
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3156
+ requestBody: {
3157
+ content: {
3158
+ "application/json": {
3159
+ schema: {
3160
+ type: "object",
3161
+ required: ["prompt"],
3162
+ properties: {
3163
+ prompt: { type: "string" }
3164
+ }
3165
+ }
3166
+ }
3167
+ }
3168
+ },
3169
+ responses: {
3170
+ 200: { description: "Agent response" },
3171
+ 404: { description: "Session not found" }
3172
+ }
3173
+ }
3174
+ },
3175
+ "/agents/{id}/approve/{toolCallId}": {
3176
+ post: {
3177
+ summary: "Approve Tool",
3178
+ description: "Approve a pending tool execution",
3179
+ parameters: [
3180
+ { name: "id", in: "path", required: true, schema: { type: "string" } },
3181
+ { name: "toolCallId", in: "path", required: true, schema: { type: "string" } }
3182
+ ],
3183
+ responses: {
3184
+ 200: { description: "Tool approved and executed" },
3185
+ 400: { description: "Approval failed" },
3186
+ 404: { description: "Session not found" }
3187
+ }
3188
+ }
3189
+ },
3190
+ "/agents/{id}/reject/{toolCallId}": {
3191
+ post: {
3192
+ summary: "Reject Tool",
3193
+ description: "Reject a pending tool execution",
3194
+ parameters: [
3195
+ { name: "id", in: "path", required: true, schema: { type: "string" } },
3196
+ { name: "toolCallId", in: "path", required: true, schema: { type: "string" } }
3197
+ ],
3198
+ requestBody: {
3199
+ content: {
3200
+ "application/json": {
3201
+ schema: {
3202
+ type: "object",
3203
+ properties: {
3204
+ reason: { type: "string" }
3205
+ }
3206
+ }
3207
+ }
3208
+ }
3209
+ },
3210
+ responses: {
3211
+ 200: { description: "Tool rejected" },
3212
+ 400: { description: "Rejection failed" },
3213
+ 404: { description: "Session not found" }
3214
+ }
3215
+ }
3216
+ },
3217
+ "/agents/{id}/approvals": {
3218
+ get: {
3219
+ summary: "Get Pending Approvals",
3220
+ description: "Get all pending tool approvals for a session",
3221
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3222
+ responses: {
3223
+ 200: { description: "Pending approvals" },
3224
+ 404: { description: "Session not found" }
3225
+ }
3226
+ }
3227
+ },
3228
+ "/agents/quick": {
3229
+ post: {
3230
+ summary: "Quick Start",
3231
+ description: "Create a session and run agent in one request",
3232
+ requestBody: {
3233
+ content: {
3234
+ "application/json": {
3235
+ schema: {
3236
+ type: "object",
3237
+ required: ["prompt"],
3238
+ properties: {
3239
+ prompt: { type: "string" },
3240
+ name: { type: "string" },
3241
+ workingDirectory: { type: "string" },
3242
+ model: { type: "string" },
3243
+ toolApprovals: { type: "object" }
3244
+ }
3245
+ }
3246
+ }
3247
+ }
3248
+ },
3249
+ responses: {
3250
+ 200: {
3251
+ description: "SSE stream of agent output",
3252
+ content: { "text/event-stream": {} }
3253
+ }
3254
+ }
3255
+ }
3256
+ },
3257
+ "/sessions/{sessionId}/terminals": {
3258
+ get: {
3259
+ summary: "List Terminals",
3260
+ description: "Get all terminals for a session",
3261
+ parameters: [{ name: "sessionId", in: "path", required: true, schema: { type: "string" } }],
3262
+ responses: {
3263
+ 200: { description: "List of terminals" },
3264
+ 404: { description: "Session not found" }
3265
+ }
3266
+ },
3267
+ post: {
3268
+ summary: "Spawn Terminal",
3269
+ description: "Start a new background process",
3270
+ parameters: [{ name: "sessionId", in: "path", required: true, schema: { type: "string" } }],
3271
+ requestBody: {
3272
+ content: {
3273
+ "application/json": {
3274
+ schema: {
3275
+ type: "object",
3276
+ required: ["command"],
3277
+ properties: {
3278
+ command: { type: "string" },
3279
+ cwd: { type: "string" },
3280
+ name: { type: "string" }
3281
+ }
3282
+ }
3283
+ }
3284
+ }
3285
+ },
3286
+ responses: {
3287
+ 201: { description: "Terminal spawned" },
3288
+ 404: { description: "Session not found" }
3289
+ }
3290
+ }
3291
+ },
3292
+ "/sessions/{sessionId}/terminals/{terminalId}": {
3293
+ get: {
3294
+ summary: "Get Terminal Status",
3295
+ description: "Get status and details of a terminal",
3296
+ parameters: [
3297
+ { name: "sessionId", in: "path", required: true, schema: { type: "string" } },
3298
+ { name: "terminalId", in: "path", required: true, schema: { type: "string" } }
3299
+ ],
3300
+ responses: {
3301
+ 200: { description: "Terminal status" },
3302
+ 404: { description: "Terminal not found" }
3303
+ }
3304
+ }
3305
+ },
3306
+ "/sessions/{sessionId}/terminals/{terminalId}/logs": {
3307
+ get: {
3308
+ summary: "Get Terminal Logs",
3309
+ description: "Get output logs from a terminal",
3310
+ parameters: [
3311
+ { name: "sessionId", in: "path", required: true, schema: { type: "string" } },
3312
+ { name: "terminalId", in: "path", required: true, schema: { type: "string" } },
3313
+ { name: "tail", in: "query", schema: { type: "integer" } }
3314
+ ],
3315
+ responses: {
3316
+ 200: { description: "Terminal logs" },
3317
+ 404: { description: "Terminal not found" }
3318
+ }
3319
+ }
3320
+ },
3321
+ "/sessions/{sessionId}/terminals/{terminalId}/kill": {
3322
+ post: {
3323
+ summary: "Kill Terminal",
3324
+ description: "Stop a running terminal process",
3325
+ parameters: [
3326
+ { name: "sessionId", in: "path", required: true, schema: { type: "string" } },
3327
+ { name: "terminalId", in: "path", required: true, schema: { type: "string" } }
3328
+ ],
3329
+ requestBody: {
3330
+ content: {
3331
+ "application/json": {
3332
+ schema: {
3333
+ type: "object",
3334
+ properties: {
3335
+ signal: { type: "string", enum: ["SIGTERM", "SIGKILL"] }
3336
+ }
3337
+ }
3338
+ }
3339
+ }
3340
+ },
3341
+ responses: {
3342
+ 200: { description: "Terminal killed" },
3343
+ 400: { description: "Failed to kill terminal" }
3344
+ }
3345
+ }
3346
+ },
3347
+ "/sessions/{sessionId}/terminals/{terminalId}/write": {
3348
+ post: {
3349
+ summary: "Write to Terminal",
3350
+ description: "Send input to terminal stdin",
3351
+ parameters: [
3352
+ { name: "sessionId", in: "path", required: true, schema: { type: "string" } },
3353
+ { name: "terminalId", in: "path", required: true, schema: { type: "string" } }
3354
+ ],
3355
+ requestBody: {
3356
+ content: {
3357
+ "application/json": {
3358
+ schema: {
3359
+ type: "object",
3360
+ required: ["input"],
3361
+ properties: {
3362
+ input: { type: "string" }
3363
+ }
3364
+ }
3365
+ }
3366
+ }
3367
+ },
3368
+ responses: {
3369
+ 200: { description: "Input sent" },
3370
+ 400: { description: "Failed to write" }
3371
+ }
3372
+ }
3373
+ },
3374
+ "/sessions/{sessionId}/terminals/{terminalId}/stream": {
3375
+ get: {
3376
+ summary: "Stream Terminal Output",
3377
+ description: "SSE stream of terminal output",
3378
+ parameters: [
3379
+ { name: "sessionId", in: "path", required: true, schema: { type: "string" } },
3380
+ { name: "terminalId", in: "path", required: true, schema: { type: "string" } }
3381
+ ],
3382
+ responses: {
3383
+ 200: { description: "SSE stream", content: { "text/event-stream": {} } },
3384
+ 404: { description: "Terminal not found" }
3385
+ }
3386
+ }
3387
+ },
3388
+ "/sessions/{sessionId}/terminals/kill-all": {
3389
+ post: {
3390
+ summary: "Kill All Terminals",
3391
+ description: "Stop all running terminals for a session",
3392
+ parameters: [{ name: "sessionId", in: "path", required: true, schema: { type: "string" } }],
3393
+ responses: {
3394
+ 200: { description: "Terminals killed" }
3395
+ }
3396
+ }
3397
+ }
3398
+ },
3399
+ components: {
3400
+ schemas: {
3401
+ Session: {
3402
+ type: "object",
3403
+ properties: {
3404
+ id: { type: "string" },
3405
+ name: { type: "string" },
3406
+ workingDirectory: { type: "string" },
3407
+ model: { type: "string" },
3408
+ status: { type: "string", enum: ["active", "waiting", "completed", "error"] },
3409
+ createdAt: { type: "string", format: "date-time" },
3410
+ updatedAt: { type: "string", format: "date-time" }
3411
+ }
3412
+ },
3413
+ Message: {
3414
+ type: "object",
3415
+ properties: {
3416
+ id: { type: "string" },
3417
+ role: { type: "string", enum: ["user", "assistant", "system", "tool"] },
3418
+ content: { type: "object" },
3419
+ createdAt: { type: "string", format: "date-time" }
3420
+ }
3421
+ },
3422
+ ToolExecution: {
3423
+ type: "object",
3424
+ properties: {
3425
+ id: { type: "string" },
3426
+ toolCallId: { type: "string" },
3427
+ toolName: { type: "string" },
3428
+ input: { type: "object" },
3429
+ output: { type: "object" },
3430
+ status: { type: "string", enum: ["pending", "approved", "rejected", "completed", "error"] },
3431
+ requiresApproval: { type: "boolean" }
3432
+ }
3433
+ },
3434
+ Terminal: {
3435
+ type: "object",
3436
+ properties: {
3437
+ id: { type: "string" },
3438
+ name: { type: "string" },
3439
+ command: { type: "string" },
3440
+ cwd: { type: "string" },
3441
+ pid: { type: "integer" },
3442
+ status: { type: "string", enum: ["running", "stopped", "error"] },
3443
+ exitCode: { type: "integer" },
3444
+ error: { type: "string" },
3445
+ createdAt: { type: "string", format: "date-time" },
3446
+ stoppedAt: { type: "string", format: "date-time" }
3447
+ }
3448
+ }
3449
+ }
3450
+ }
3451
+ };
3452
+ }
3453
+ export {
3454
+ createApp,
3455
+ startServer,
3456
+ stopServer
3457
+ };
3458
+ //# sourceMappingURL=index.js.map