agentgui 1.0.398 → 1.0.399
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/lib/ws-events.js +20 -0
- package/lib/ws-handlers-conv.js +183 -0
- package/lib/ws-handlers-run.js +157 -0
- package/lib/ws-handlers-session.js +165 -0
- package/lib/ws-handlers-util.js +186 -0
- package/lib/ws-optimizer.js +2 -2
- package/lib/ws-protocol.js +81 -0
- package/package.json +1 -1
- package/server.js +275 -91
- package/static/app.js +7 -17
- package/static/index.html +19 -18
- package/static/js/client.js +4 -13
- package/static/js/conversations.js +12 -51
- package/static/js/features.js +12 -11
- package/static/js/voice.js +69 -64
- package/static/js/ws-client.js +80 -0
package/lib/ws-events.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const S2L = {
|
|
2
|
+
's.start': 'streaming_start', 's.prog': 'streaming_progress',
|
|
3
|
+
's.done': 'streaming_complete', 's.err': 'streaming_error',
|
|
4
|
+
's.cancel': 'streaming_cancelled', 'conv.new': 'conversation_created',
|
|
5
|
+
'conv.upd': 'conversation_updated', 'convs.upd': 'conversations_updated',
|
|
6
|
+
'conv.del': 'conversation_deleted', 'msg.new': 'message_created',
|
|
7
|
+
'q.stat': 'queue_status', 'q.upd': 'queue_updated',
|
|
8
|
+
'rl.hit': 'rate_limit_hit', 'rl.clr': 'rate_limit_clear',
|
|
9
|
+
'scr.start': 'script_started', 'scr.stop': 'script_stopped',
|
|
10
|
+
'scr.out': 'script_output', 'mdl.prog': 'model_download_progress',
|
|
11
|
+
'stt.prog': 'stt_progress', 'tts.prog': 'tts_setup_progress',
|
|
12
|
+
'voice.ls': 'voice_list', 'sub.ok': 'subscription_confirmed',
|
|
13
|
+
'term.out': 'terminal_output', 'term.exit': 'terminal_exit',
|
|
14
|
+
'term.start': 'terminal_started'
|
|
15
|
+
};
|
|
16
|
+
const L2S = Object.fromEntries(Object.entries(S2L).map(([k, v]) => [v, k]));
|
|
17
|
+
const toLong = (s) => S2L[s] || s;
|
|
18
|
+
const toShort = (l) => L2S[l] || l;
|
|
19
|
+
if (typeof window !== 'undefined') window.wsEvents = { S2L, L2S, toLong, toShort };
|
|
20
|
+
export { S2L, L2S, toLong, toShort };
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
|
|
3
|
+
function fail(code, message) { const e = new Error(message); e.code = code; throw e; }
|
|
4
|
+
function notFound(msg = 'Not found') { fail(404, msg); }
|
|
5
|
+
|
|
6
|
+
export function register(router, deps) {
|
|
7
|
+
const { queries, activeExecutions, messageQueues, rateLimitState,
|
|
8
|
+
broadcastSync, processMessageWithStreaming } = deps;
|
|
9
|
+
|
|
10
|
+
router.handle('conv.ls', () => {
|
|
11
|
+
const conversations = queries.getConversationsList();
|
|
12
|
+
for (const c of conversations) { if (c.isStreaming && !activeExecutions.has(c.id)) c.isStreaming = 0; }
|
|
13
|
+
return { conversations };
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
router.handle('conv.new', (p) => {
|
|
17
|
+
const wd = p.workingDirectory ? path.resolve(p.workingDirectory) : null;
|
|
18
|
+
const conv = queries.createConversation(p.agentId, p.title, wd, p.model || null);
|
|
19
|
+
queries.createEvent('conversation.created', { agentId: p.agentId, workingDirectory: conv.workingDirectory, model: conv.model }, conv.id);
|
|
20
|
+
broadcastSync({ type: 'conversation_created', conversation: conv });
|
|
21
|
+
return { conversation: conv };
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
router.handle('conv.get', (p) => {
|
|
25
|
+
const conv = queries.getConversation(p.id);
|
|
26
|
+
if (!conv) notFound();
|
|
27
|
+
return { conversation: conv, isActivelyStreaming: activeExecutions.has(p.id), latestSession: queries.getLatestSession(p.id) };
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
router.handle('conv.upd', (p) => {
|
|
31
|
+
const { id, ...data } = p;
|
|
32
|
+
if (data.workingDirectory) data.workingDirectory = path.resolve(data.workingDirectory);
|
|
33
|
+
const conv = queries.updateConversation(id, data);
|
|
34
|
+
if (!conv) notFound('Conversation not found');
|
|
35
|
+
queries.createEvent('conversation.updated', data, id);
|
|
36
|
+
broadcastSync({ type: 'conversation_updated', conversation: conv });
|
|
37
|
+
return { conversation: conv };
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
router.handle('conv.del', (p) => {
|
|
41
|
+
if (!queries.deleteConversation(p.id)) notFound();
|
|
42
|
+
broadcastSync({ type: 'conversation_deleted', conversationId: p.id });
|
|
43
|
+
return { deleted: true };
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
router.handle('conv.full', (p) => {
|
|
47
|
+
const conv = queries.getConversation(p.id);
|
|
48
|
+
if (!conv) notFound();
|
|
49
|
+
const chunkLimit = Math.min(p.chunkLimit || 500, 5000);
|
|
50
|
+
const totalChunks = queries.getConversationChunkCount(p.id);
|
|
51
|
+
const chunks = (p.allChunks || totalChunks <= chunkLimit)
|
|
52
|
+
? queries.getConversationChunks(p.id) : queries.getRecentConversationChunks(p.id, chunkLimit);
|
|
53
|
+
return {
|
|
54
|
+
conversation: conv, isActivelyStreaming: activeExecutions.has(p.id),
|
|
55
|
+
latestSession: queries.getLatestSession(p.id), chunks, totalChunks,
|
|
56
|
+
messages: queries.getPaginatedMessages(p.id, 100, 0).messages,
|
|
57
|
+
rateLimitInfo: rateLimitState.get(p.id) || null
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
router.handle('conv.chunks', (p) => {
|
|
62
|
+
if (!queries.getConversation(p.id)) notFound('Conversation not found');
|
|
63
|
+
const since = parseInt(p.since || '0');
|
|
64
|
+
const allChunks = queries.getConversationChunks(p.id);
|
|
65
|
+
return { ok: true, chunks: since > 0 ? allChunks.filter(c => c.created_at > since) : allChunks };
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
router.handle('conv.cancel', (p) => {
|
|
69
|
+
const entry = activeExecutions.get(p.id);
|
|
70
|
+
if (!entry) notFound('No active execution to cancel');
|
|
71
|
+
const { pid, sessionId } = entry;
|
|
72
|
+
if (pid) { try { process.kill(-pid, 'SIGKILL'); } catch { try { process.kill(pid, 'SIGKILL'); } catch {} } }
|
|
73
|
+
if (sessionId) queries.updateSession(sessionId, { status: 'interrupted', completed_at: Date.now() });
|
|
74
|
+
queries.setIsStreaming(p.id, false);
|
|
75
|
+
activeExecutions.delete(p.id);
|
|
76
|
+
broadcastSync({ type: 'streaming_complete', sessionId, conversationId: p.id, interrupted: true, timestamp: Date.now() });
|
|
77
|
+
return { ok: true, cancelled: true, conversationId: p.id, sessionId };
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
router.handle('conv.inject', (p) => {
|
|
81
|
+
const conv = queries.getConversation(p.id);
|
|
82
|
+
if (!conv) notFound('Conversation not found');
|
|
83
|
+
if (!p.content) fail(400, 'Missing content');
|
|
84
|
+
const entry = activeExecutions.get(p.id);
|
|
85
|
+
if (entry && p.eager) fail(409, 'Cannot eagerly inject while execution is running - message queued');
|
|
86
|
+
const message = queries.createMessage(p.id, 'user', '[INJECTED] ' + p.content);
|
|
87
|
+
if (!entry) {
|
|
88
|
+
const agentId = conv.agentId || 'claude-code';
|
|
89
|
+
const session = queries.createSession(p.id, agentId, 'pending');
|
|
90
|
+
processMessageWithStreaming(p.id, message.id, session.id, message.content, agentId, conv.model || null);
|
|
91
|
+
}
|
|
92
|
+
return { ok: true, injected: true, conversationId: p.id, messageId: message.id };
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
router.handle('msg.ls', (p) => {
|
|
96
|
+
return queries.getPaginatedMessages(p.id, Math.min(p.limit || 50, 100), Math.max(p.offset || 0, 0));
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
function startExecution(convId, message, agentId, model, content) {
|
|
100
|
+
const session = queries.createSession(convId);
|
|
101
|
+
queries.createEvent('session.created', { messageId: message.id, sessionId: session.id }, convId, session.id);
|
|
102
|
+
activeExecutions.set(convId, { pid: null, startTime: Date.now(), sessionId: session.id, lastActivity: Date.now() });
|
|
103
|
+
queries.setIsStreaming(convId, true);
|
|
104
|
+
broadcastSync({ type: 'streaming_start', sessionId: session.id, conversationId: convId, messageId: message.id, agentId, timestamp: Date.now() });
|
|
105
|
+
processMessageWithStreaming(convId, message.id, session.id, content, agentId, model).catch(() => {});
|
|
106
|
+
return session;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function enqueue(convId, content, agentId, model, messageId) {
|
|
110
|
+
if (!messageQueues.has(convId)) messageQueues.set(convId, []);
|
|
111
|
+
messageQueues.get(convId).push({ content, agentId, model, messageId });
|
|
112
|
+
const queueLength = messageQueues.get(convId).length;
|
|
113
|
+
broadcastSync({ type: 'queue_status', conversationId: convId, queueLength, messageId, timestamp: Date.now() });
|
|
114
|
+
return queueLength;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
router.handle('msg.send', (p) => {
|
|
118
|
+
const conv = queries.getConversation(p.id);
|
|
119
|
+
if (!conv) notFound('Conversation not found');
|
|
120
|
+
const agentId = p.agentId || conv.agentType || conv.agentId || 'claude-code';
|
|
121
|
+
const model = p.model || conv.model || null;
|
|
122
|
+
const idempotencyKey = p.idempotencyKey || null;
|
|
123
|
+
const message = queries.createMessage(p.id, 'user', p.content, idempotencyKey);
|
|
124
|
+
queries.createEvent('message.created', { role: 'user', messageId: message.id }, p.id);
|
|
125
|
+
broadcastSync({ type: 'message_created', conversationId: p.id, message, timestamp: Date.now() });
|
|
126
|
+
if (activeExecutions.has(p.id)) {
|
|
127
|
+
const qp = enqueue(p.id, p.content, agentId, model, message.id);
|
|
128
|
+
return { message, queued: true, queuePosition: qp, idempotencyKey };
|
|
129
|
+
}
|
|
130
|
+
const session = startExecution(p.id, message, agentId, model, p.content);
|
|
131
|
+
return { message, session, idempotencyKey };
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
router.handle('msg.get', (p) => {
|
|
135
|
+
const msg = queries.getMessage(p.messageId);
|
|
136
|
+
if (!msg || msg.conversationId !== p.id) notFound();
|
|
137
|
+
return { message: msg };
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
router.handle('msg.stream', (p) => {
|
|
141
|
+
const conv = queries.getConversation(p.id);
|
|
142
|
+
if (!conv) notFound('Conversation not found');
|
|
143
|
+
const prompt = p.content || p.message || '';
|
|
144
|
+
const agentId = p.agentId || conv.agentType || conv.agentId || 'claude-code';
|
|
145
|
+
const model = p.model || conv.model || null;
|
|
146
|
+
const userMessage = queries.createMessage(p.id, 'user', prompt);
|
|
147
|
+
queries.createEvent('message.created', { role: 'user', messageId: userMessage.id }, p.id);
|
|
148
|
+
broadcastSync({ type: 'message_created', conversationId: p.id, message: userMessage, timestamp: Date.now() });
|
|
149
|
+
if (activeExecutions.has(p.id)) {
|
|
150
|
+
const qp = enqueue(p.id, prompt, agentId, model, userMessage.id);
|
|
151
|
+
return { message: userMessage, queued: true, queuePosition: qp };
|
|
152
|
+
}
|
|
153
|
+
const session = startExecution(p.id, userMessage, agentId, model, prompt);
|
|
154
|
+
return { message: userMessage, session, streamId: session.id };
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
router.handle('q.ls', (p) => {
|
|
158
|
+
if (!queries.getConversation(p.id)) notFound('Conversation not found');
|
|
159
|
+
return { queue: messageQueues.get(p.id) || [] };
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
router.handle('q.del', (p) => {
|
|
163
|
+
const queue = messageQueues.get(p.id);
|
|
164
|
+
if (!queue) notFound('Queue not found');
|
|
165
|
+
const idx = queue.findIndex(q => q.messageId === p.messageId);
|
|
166
|
+
if (idx === -1) notFound('Queued message not found');
|
|
167
|
+
queue.splice(idx, 1);
|
|
168
|
+
if (queue.length === 0) messageQueues.delete(p.id);
|
|
169
|
+
broadcastSync({ type: 'queue_status', conversationId: p.id, queueLength: queue?.length || 0, timestamp: Date.now() });
|
|
170
|
+
return { deleted: true };
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
router.handle('q.upd', (p) => {
|
|
174
|
+
const queue = messageQueues.get(p.id);
|
|
175
|
+
if (!queue) notFound('Queue not found');
|
|
176
|
+
const item = queue.find(q => q.messageId === p.messageId);
|
|
177
|
+
if (!item) notFound('Queued message not found');
|
|
178
|
+
if (p.content !== undefined) item.content = p.content;
|
|
179
|
+
if (p.agentId !== undefined) item.agentId = p.agentId;
|
|
180
|
+
broadcastSync({ type: 'queue_updated', conversationId: p.id, messageId: p.messageId, content: item.content, agentId: item.agentId, timestamp: Date.now() });
|
|
181
|
+
return { updated: true, item };
|
|
182
|
+
});
|
|
183
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
function err(code, message) { const e = new Error(message); e.code = code; throw e; }
|
|
2
|
+
function need(p, key) { if (!p[key]) err(400, `Missing required param: ${key}`); return p[key]; }
|
|
3
|
+
|
|
4
|
+
function register(router, deps) {
|
|
5
|
+
const { queries, discoveredAgents, activeExecutions, activeProcessesByRunId, broadcastSync, processMessageWithStreaming } = deps;
|
|
6
|
+
|
|
7
|
+
function findAgent(id) { const a = discoveredAgents.find(x => x.id === id); if (!a) err(404, 'Agent not found'); return a; }
|
|
8
|
+
function getRunOrThrow(id) { const r = queries.getRun(id); if (!r) err(404, 'Run not found'); return r; }
|
|
9
|
+
function getThreadOrThrow(id) { const t = queries.getThread(id); if (!t) err(404, 'Thread not found'); return t; }
|
|
10
|
+
|
|
11
|
+
function killExecution(threadId, runId) {
|
|
12
|
+
const ex = activeExecutions.get(threadId);
|
|
13
|
+
if (ex?.pid) {
|
|
14
|
+
try { process.kill(-ex.pid, 'SIGTERM'); } catch { try { process.kill(ex.pid, 'SIGTERM'); } catch {} }
|
|
15
|
+
setTimeout(() => { try { process.kill(-ex.pid, 'SIGKILL'); } catch { try { process.kill(ex.pid, 'SIGKILL'); } catch {} } }, 3000);
|
|
16
|
+
}
|
|
17
|
+
if (ex?.sessionId) queries.updateSession(ex.sessionId, { status: 'error', error: 'Cancelled by user', completed_at: Date.now() });
|
|
18
|
+
activeExecutions.delete(threadId);
|
|
19
|
+
activeProcessesByRunId.delete(runId);
|
|
20
|
+
queries.setIsStreaming(threadId, false);
|
|
21
|
+
return ex;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function startExecution(runId, threadId, agentId, input, config) {
|
|
25
|
+
const conv = queries.getConversation(threadId);
|
|
26
|
+
if (!conv || !input?.content) return;
|
|
27
|
+
const session = queries.createSession(threadId);
|
|
28
|
+
queries.updateRunStatus(runId, 'active');
|
|
29
|
+
activeExecutions.set(threadId, { pid: null, startTime: Date.now(), sessionId: session.id, lastActivity: Date.now() });
|
|
30
|
+
activeProcessesByRunId.set(runId, { threadId, sessionId: session.id });
|
|
31
|
+
queries.setIsStreaming(threadId, true);
|
|
32
|
+
processMessageWithStreaming(threadId, null, session.id, input.content, agentId, config?.model || null)
|
|
33
|
+
.then(() => { queries.updateRunStatus(runId, 'success'); activeProcessesByRunId.delete(runId); })
|
|
34
|
+
.catch(() => { queries.updateRunStatus(runId, 'error'); activeProcessesByRunId.delete(runId); });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
router.handle('run.new', async (p) => {
|
|
38
|
+
findAgent(need(p, 'agent_id'));
|
|
39
|
+
return queries.createRun(p.agent_id, p.thread_id || null, p.input || null, p.config || null, p.webhook_url || null);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
router.handle('run.get', async (p) => getRunOrThrow(need(p, 'id')));
|
|
43
|
+
|
|
44
|
+
router.handle('run.del', async (p) => {
|
|
45
|
+
try { queries.deleteRun(need(p, 'id')); } catch { err(404, 'Run not found'); }
|
|
46
|
+
return { deleted: true };
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
router.handle('run.resume', async (p) => {
|
|
50
|
+
const id = need(p, 'id'), run = getRunOrThrow(id);
|
|
51
|
+
if (run.status !== 'pending') err(409, 'Run is not resumable');
|
|
52
|
+
if (run.thread_id) startExecution(id, run.thread_id, run.agent_id, p.input, p.config);
|
|
53
|
+
return queries.getRun(id) || run;
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
router.handle('run.cancel', async (p) => {
|
|
57
|
+
const id = need(p, 'id'), run = getRunOrThrow(id);
|
|
58
|
+
if (['success', 'error', 'cancelled'].includes(run.status)) err(409, 'Run already completed or cancelled');
|
|
59
|
+
const cancelled = queries.cancelRun(id);
|
|
60
|
+
if (run.thread_id) {
|
|
61
|
+
const ex = killExecution(run.thread_id, id);
|
|
62
|
+
broadcastSync({ type: 'streaming_cancelled', sessionId: ex?.sessionId || id, conversationId: run.thread_id, runId: id, timestamp: Date.now() });
|
|
63
|
+
}
|
|
64
|
+
return cancelled;
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
router.handle('run.search', async (p) => queries.searchRuns(p));
|
|
68
|
+
|
|
69
|
+
router.handle('run.wait', async (p) => {
|
|
70
|
+
const id = need(p, 'id');
|
|
71
|
+
getRunOrThrow(id);
|
|
72
|
+
const timeout = p.timeout || 30000, start = Date.now();
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
const poll = setInterval(() => {
|
|
75
|
+
const cur = queries.getRun(id);
|
|
76
|
+
if (cur && ['success', 'error', 'cancelled'].includes(cur.status)) { clearInterval(poll); resolve(cur); }
|
|
77
|
+
else if (Date.now() - start > timeout) { clearInterval(poll); resolve({ error: 'Run still pending', run_id: id, status: cur?.status }); }
|
|
78
|
+
}, 500);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
router.handle('run.stream', async (p) => {
|
|
83
|
+
const agent_id = need(p, 'agent_id');
|
|
84
|
+
findAgent(agent_id);
|
|
85
|
+
const run = queries.createRun(agent_id, null, p.input, p.config);
|
|
86
|
+
const threadId = queries.getRun(run.run_id)?.thread_id;
|
|
87
|
+
if (threadId) startExecution(run.run_id, threadId, agent_id, p.input, p.config);
|
|
88
|
+
return run;
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
router.handle('run.stream.get', async (p) => getRunOrThrow(need(p, 'id')));
|
|
92
|
+
|
|
93
|
+
router.handle('thread.new', async (p) => queries.createThread(p.metadata || {}));
|
|
94
|
+
router.handle('thread.search', async (p) => queries.searchThreads(p));
|
|
95
|
+
router.handle('thread.get', async (p) => getThreadOrThrow(need(p, 'id')));
|
|
96
|
+
|
|
97
|
+
router.handle('thread.upd', async (p) => {
|
|
98
|
+
try { return queries.patchThread(need(p, 'id'), p); } catch (e) {
|
|
99
|
+
if (e.message.includes('not found')) err(404, e.message);
|
|
100
|
+
throw e;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
router.handle('thread.del', async (p) => {
|
|
105
|
+
try { queries.deleteThread(need(p, 'id')); return { deleted: true }; } catch (e) {
|
|
106
|
+
if (e.message.includes('not found')) err(404, e.message);
|
|
107
|
+
if (e.message.includes('pending runs')) err(409, e.message);
|
|
108
|
+
throw e;
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
router.handle('thread.history', async (p) => {
|
|
113
|
+
const id = need(p, 'id'), limit = p.limit || 50, offset = p.before ? parseInt(p.before, 10) : 0;
|
|
114
|
+
const result = queries.getThreadHistory(id, limit, offset);
|
|
115
|
+
return { states: result.states, next_cursor: result.hasMore ? String(offset + limit) : null };
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
router.handle('thread.copy', async (p) => {
|
|
119
|
+
try {
|
|
120
|
+
const nt = queries.copyThread(need(p, 'id'));
|
|
121
|
+
return p.metadata ? queries.patchThread(nt.thread_id, { metadata: p.metadata }) : nt;
|
|
122
|
+
} catch (e) {
|
|
123
|
+
if (e.message.includes('not found')) err(404, e.message);
|
|
124
|
+
throw e;
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
router.handle('thread.run.stream', async (p) => {
|
|
129
|
+
const threadId = need(p, 'id'), agent_id = need(p, 'agent_id');
|
|
130
|
+
const thread = getThreadOrThrow(threadId);
|
|
131
|
+
if (thread.status !== 'idle') err(409, 'Thread has pending runs');
|
|
132
|
+
findAgent(agent_id);
|
|
133
|
+
const run = queries.createRun(agent_id, threadId, p.input, p.config);
|
|
134
|
+
startExecution(run.run_id, threadId, agent_id, p.input, p.config);
|
|
135
|
+
return run;
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
router.handle('thread.run.cancel', async (p) => {
|
|
139
|
+
const threadId = need(p, 'id'), runId = need(p, 'runId'), run = getRunOrThrow(runId);
|
|
140
|
+
if (run.thread_id !== threadId) err(400, 'Run does not belong to specified thread');
|
|
141
|
+
if (['success', 'error', 'cancelled'].includes(run.status)) err(409, 'Run already completed or cancelled');
|
|
142
|
+
const cancelled = queries.cancelRun(runId);
|
|
143
|
+
const ex = killExecution(threadId, runId);
|
|
144
|
+
broadcastSync({ type: 'run_cancelled', runId, threadId, sessionId: ex?.sessionId, timestamp: Date.now() });
|
|
145
|
+
return cancelled;
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
router.handle('thread.run.stream.get', async (p) => {
|
|
149
|
+
const threadId = need(p, 'id'), runId = need(p, 'runId');
|
|
150
|
+
getThreadOrThrow(threadId);
|
|
151
|
+
const run = queries.getRun(runId);
|
|
152
|
+
if (!run || run.thread_id !== threadId) err(404, 'Run not found on thread');
|
|
153
|
+
return run;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export { register };
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { execSync, spawn } from 'child_process';
|
|
5
|
+
|
|
6
|
+
function spawnScript(cmd, args, convId, scriptName, agentId, deps) {
|
|
7
|
+
const { activeScripts, broadcastSync, modelCache } = deps;
|
|
8
|
+
if (activeScripts.has(convId)) throw { code: 409, message: 'Process already running' };
|
|
9
|
+
const child = spawn(cmd, args, {
|
|
10
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
11
|
+
env: { ...process.env, FORCE_COLOR: '1' },
|
|
12
|
+
shell: os.platform() === 'win32'
|
|
13
|
+
});
|
|
14
|
+
activeScripts.set(convId, { process: child, script: scriptName, startTime: Date.now() });
|
|
15
|
+
broadcastSync({ type: 'script_started', conversationId: convId, script: scriptName, agentId, timestamp: Date.now() });
|
|
16
|
+
const relay = (stream) => (chunk) => {
|
|
17
|
+
broadcastSync({ type: 'script_output', conversationId: convId, data: chunk.toString(), stream, timestamp: Date.now() });
|
|
18
|
+
};
|
|
19
|
+
child.stdout.on('data', relay('stdout'));
|
|
20
|
+
child.stderr.on('data', relay('stderr'));
|
|
21
|
+
child.on('error', (err) => {
|
|
22
|
+
activeScripts.delete(convId);
|
|
23
|
+
broadcastSync({ type: 'script_stopped', conversationId: convId, code: 1, error: err.message, timestamp: Date.now() });
|
|
24
|
+
});
|
|
25
|
+
child.on('close', (code) => {
|
|
26
|
+
activeScripts.delete(convId);
|
|
27
|
+
if (modelCache && agentId) modelCache.delete(agentId);
|
|
28
|
+
broadcastSync({ type: 'script_stopped', conversationId: convId, code: code || 0, timestamp: Date.now() });
|
|
29
|
+
});
|
|
30
|
+
return child.pid;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readJson(filePath) {
|
|
34
|
+
try { return fs.existsSync(filePath) ? JSON.parse(fs.readFileSync(filePath, 'utf-8')) : null; } catch { return null; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function checkAgentAuth(agent) {
|
|
38
|
+
const s = { id: agent.id, name: agent.name, authenticated: false, detail: '' };
|
|
39
|
+
try {
|
|
40
|
+
if (agent.id === 'claude-code') {
|
|
41
|
+
const creds = readJson(path.join(os.homedir(), '.claude', '.credentials.json'));
|
|
42
|
+
if (creds?.claudeAiOauth?.expiresAt > Date.now()) {
|
|
43
|
+
s.authenticated = true;
|
|
44
|
+
s.detail = creds.claudeAiOauth.subscriptionType || 'authenticated';
|
|
45
|
+
} else { s.detail = creds ? 'expired' : 'no credentials'; }
|
|
46
|
+
} else if (agent.id === 'gemini') {
|
|
47
|
+
const oauth = readJson(path.join(os.homedir(), '.gemini', 'oauth_creds.json'));
|
|
48
|
+
const accts = readJson(path.join(os.homedir(), '.gemini', 'google_accounts.json'));
|
|
49
|
+
const hasOAuth = !!(oauth?.refresh_token || oauth?.access_token);
|
|
50
|
+
if (accts?.active) { s.authenticated = true; s.detail = accts.active; }
|
|
51
|
+
else if (hasOAuth) { s.authenticated = true; s.detail = 'oauth'; }
|
|
52
|
+
else { s.detail = accts ? 'logged out' : 'no credentials'; }
|
|
53
|
+
} else if (agent.id === 'opencode') {
|
|
54
|
+
const out = execSync('opencode auth list 2>&1', { encoding: 'utf-8', timeout: 5000 });
|
|
55
|
+
const m = out.match(/(\d+)\s+credentials?/);
|
|
56
|
+
if (m && parseInt(m[1], 10) > 0) { s.authenticated = true; s.detail = m[1] + ' credential(s)'; }
|
|
57
|
+
else { s.detail = 'no credentials'; }
|
|
58
|
+
} else { s.detail = 'unknown'; }
|
|
59
|
+
} catch { s.detail = 'check failed'; }
|
|
60
|
+
return s;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function register(router, deps) {
|
|
64
|
+
const { db, discoveredAgents, getModelsForAgent, modelCache,
|
|
65
|
+
getAgentDescriptor, activeScripts, broadcastSync, startGeminiOAuth,
|
|
66
|
+
geminiOAuthState } = deps;
|
|
67
|
+
|
|
68
|
+
router.handle('sess.get', (p) => {
|
|
69
|
+
const sess = db.getSession(p.id);
|
|
70
|
+
if (!sess) throw { code: 404, message: 'Not found' };
|
|
71
|
+
return { session: sess, events: db.getSessionEvents(p.id) };
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
router.handle('sess.latest', (p) => {
|
|
75
|
+
const s = db.getLatestSession(p.id);
|
|
76
|
+
if (!s) return { session: null };
|
|
77
|
+
return { session: s, events: db.getSessionEvents(s.id) };
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
router.handle('sess.chunks', (p) => {
|
|
81
|
+
if (!db.getSession(p.id)) throw { code: 404, message: 'Session not found' };
|
|
82
|
+
const sinceSeq = parseInt(p.sinceSeq ?? '-1');
|
|
83
|
+
const since = parseInt(p.since ?? '0');
|
|
84
|
+
const chunks = sinceSeq >= 0 ? db.getChunksSinceSeq(p.id, sinceSeq) : db.getChunksSince(p.id, since);
|
|
85
|
+
return { ok: true, chunks };
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
router.handle('sess.exec', (p) => {
|
|
89
|
+
const limit = Math.min(parseInt(p.limit || '1000'), 5000);
|
|
90
|
+
const offset = Math.max(parseInt(p.offset || '0'), 0);
|
|
91
|
+
const filterType = p.filterType || null;
|
|
92
|
+
const data = {
|
|
93
|
+
sessionId: p.id, events: [], total: 0, limit, offset, hasMore: false,
|
|
94
|
+
metadata: { status: 'pending', startTime: Date.now(), duration: 0, eventCount: 0 }
|
|
95
|
+
};
|
|
96
|
+
if (filterType) data.events = data.events.filter(e => e.type === filterType);
|
|
97
|
+
return data;
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
router.handle('agent.ls', () => ({ agents: discoveredAgents }));
|
|
101
|
+
|
|
102
|
+
router.handle('agent.get', (p) => {
|
|
103
|
+
const a = discoveredAgents.find(x => x.id === p.id);
|
|
104
|
+
if (!a) throw { code: 404, message: 'Agent not found' };
|
|
105
|
+
return { id: a.id, name: a.name, description: a.description || '', icon: a.icon || null, status: 'available' };
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
router.handle('agent.desc', (p) => {
|
|
109
|
+
const d = getAgentDescriptor(p.id);
|
|
110
|
+
if (!d) throw { code: 404, message: 'Agent not found' };
|
|
111
|
+
return d;
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
router.handle('agent.models', async (p) => {
|
|
115
|
+
const cached = modelCache.get(p.id);
|
|
116
|
+
if (cached && (Date.now() - cached.ts) < 300000) return { models: cached.models };
|
|
117
|
+
try {
|
|
118
|
+
const models = await getModelsForAgent(p.id);
|
|
119
|
+
modelCache.set(p.id, { models, ts: Date.now() });
|
|
120
|
+
return { models };
|
|
121
|
+
} catch { return { models: [] }; }
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
router.handle('agent.search', (p) => db.searchAgents(discoveredAgents, p.query || p));
|
|
125
|
+
|
|
126
|
+
router.handle('agent.auth', async (p) => {
|
|
127
|
+
const agentId = p.id;
|
|
128
|
+
if (!discoveredAgents.find(a => a.id === agentId)) throw { code: 404, message: 'Agent not found' };
|
|
129
|
+
if (agentId === 'gemini') {
|
|
130
|
+
const result = await startGeminiOAuth();
|
|
131
|
+
const cid = '__agent_auth__';
|
|
132
|
+
broadcastSync({ type: 'script_started', conversationId: cid, script: 'auth-gemini', agentId: 'gemini', timestamp: Date.now() });
|
|
133
|
+
broadcastSync({ type: 'script_output', conversationId: cid, data: `\x1b[36mOpening Google OAuth...\x1b[0m\r\n\r\nVisit:\r\n${result.authUrl}\r\n`, stream: 'stdout', timestamp: Date.now() });
|
|
134
|
+
const pollId = setInterval(() => {
|
|
135
|
+
const st = geminiOAuthState();
|
|
136
|
+
if (st.status === 'success') {
|
|
137
|
+
clearInterval(pollId);
|
|
138
|
+
broadcastSync({ type: 'script_output', conversationId: cid, data: `\r\n\x1b[32mAuth OK${st.email ? ' (' + st.email + ')' : ''}\x1b[0m\r\n`, stream: 'stdout', timestamp: Date.now() });
|
|
139
|
+
broadcastSync({ type: 'script_stopped', conversationId: cid, code: 0, timestamp: Date.now() });
|
|
140
|
+
} else if (st.status === 'error') {
|
|
141
|
+
clearInterval(pollId);
|
|
142
|
+
broadcastSync({ type: 'script_output', conversationId: cid, data: `\r\n\x1b[31mAuth failed: ${st.error}\x1b[0m\r\n`, stream: 'stderr', timestamp: Date.now() });
|
|
143
|
+
broadcastSync({ type: 'script_stopped', conversationId: cid, code: 1, error: st.error, timestamp: Date.now() });
|
|
144
|
+
}
|
|
145
|
+
}, 1000);
|
|
146
|
+
setTimeout(() => clearInterval(pollId), 5 * 60 * 1000);
|
|
147
|
+
return { ok: true, agentId, authUrl: result.authUrl, mode: result.mode };
|
|
148
|
+
}
|
|
149
|
+
const cmds = { 'claude-code': { cmd: 'claude', args: ['setup-token'] }, 'opencode': { cmd: 'opencode', args: ['auth', 'login'] } };
|
|
150
|
+
const c = cmds[agentId];
|
|
151
|
+
if (!c) throw { code: 400, message: 'No auth command for this agent' };
|
|
152
|
+
const pid = spawnScript(c.cmd, c.args, '__agent_auth__', 'auth-' + agentId, agentId, { activeScripts, broadcastSync });
|
|
153
|
+
return { ok: true, agentId, pid };
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
router.handle('agent.authstat', () => ({ agents: discoveredAgents.map(checkAgentAuth) }));
|
|
157
|
+
|
|
158
|
+
router.handle('agent.update', (p) => {
|
|
159
|
+
const cmds = { 'claude-code': { cmd: 'claude', args: ['update', '--yes'] } };
|
|
160
|
+
const c = cmds[p.id];
|
|
161
|
+
if (!c) throw { code: 400, message: 'No update command for this agent' };
|
|
162
|
+
const pid = spawnScript(c.cmd, c.args, '__agent_update__', 'update-' + p.id, p.id, { activeScripts, broadcastSync, modelCache });
|
|
163
|
+
return { ok: true, agentId: p.id, pid };
|
|
164
|
+
});
|
|
165
|
+
}
|