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