agentgui 1.0.838 → 1.0.840

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/CHANGELOG.md CHANGED
@@ -1,6 +1,8 @@
1
1
  ## [Unreleased]
2
2
 
3
3
  ### Refactor
4
+ - Extract message/stream/queue routes (messagesMatch, streamMatch, queueMatch handlers) to lib/routes-messages.js (140L) and session/chunk/full/execution routes to lib/routes-sessions.js (145L); server.js reduced from 2406L to 2127L; both files ≤200L; wired via _messagesRoutes._match and _sessionsRoutes._match in request handler
5
+ - Extract runs/scripts/agent-auth/auth-config HTTP routes from server.js to lib/routes-runs.js (157L), lib/routes-scripts.js (136L), lib/routes-agent-actions.js (118L), lib/routes-auth-config.js (30L); routes-auth-config uses getProviderConfigs/saveProviderConfig from server.js deps (no duplication); server.js reduced from 2406L to 1399L total (-1007L)
4
6
  - Extract processMessageWithStreaming (539L), scheduleRetry, drainMessageQueue, and parseRateLimitResetTime from server.js into lib/process-message.js (127L, createProcessMessage factory), lib/stream-event-handler.js (116L, createEventHandler), lib/message-queue.js (63L, createMessageQueue), lib/process-message-rate-limit.js (19L); all files ≤200L; server.js reduced by ~660L and imports/wires all factories after broadcastSync is created
5
7
  - refactor: extract broadcastSync to lib/broadcast.js (createBroadcast factory) and recovery functions to lib/recovery.js (createRecovery factory); server.js reduced from 3419L to 3226L
6
8
  - refactor: remove JSDoc and standalone code comments from scripts/patch-fsbrowse.js; reduce from 229L to 200L
package/CLAUDE.md CHANGED
@@ -54,6 +54,12 @@ lib/routes-tools.js Tool management HTTP route handlers (list, install, updat
54
54
  lib/routes-util.js Utility HTTP route handlers (clone, folders, git, home, version, import)
55
55
  lib/routes-agents.js Agent list/search/auth-status/descriptor/models HTTP route handlers
56
56
  lib/routes-conversations.js Conversation CRUD HTTP route handlers (list, create, get, update, delete, archive, restore)
57
+ lib/routes-messages.js Message/stream/queue HTTP route handlers (GET+POST messages, stream, queue CRUD)
58
+ lib/routes-sessions.js Session/chunk/full/execution HTTP route handlers (session get, chunks, full load, execution events)
59
+ lib/routes-runs.js Runs HTTP route handlers (POST /api/runs, runs search, run by id, wait, cancel, thread run cancel/wait)
60
+ lib/routes-scripts.js Scripts/cancel/resume/inject HTTP route handlers (conversation scripts, run-script, stop-script, cancel, resume, inject)
61
+ lib/routes-agent-actions.js Agent auth and update HTTP route handlers (POST /api/agents/:id/auth, POST /api/agents/:id/update)
62
+ lib/routes-auth-config.js Auth config HTTP route handlers (GET /api/auth/configs, POST /api/auth/save-config)
57
63
  lib/routes-debug.js Debug/backup/restore/ws-stats HTTP route handlers
58
64
  lib/routes-threads.js Thread CRUD HTTP route handlers (ACP v0.2.3 thread API)
59
65
  lib/ws-protocol.js WebSocket RPC router (WsRouter class)
@@ -74,27 +80,27 @@ static/js/app-shortcuts.js Keyboard shortcuts overlay
74
80
  static/theme.js Theme switching
75
81
  static/css/main.css All application styles (extracted from index.html)
76
82
  static/css/tools-popup.css Tool popup styles
77
- static/js/client.js AgentGUIClient class (constructor + _dbg + init); instantiation at bottom
78
- static/js/client-ws.js WebSocket listeners, _convIsStreaming, _setConvStreaming, setupRendererListeners, restoreStateFromUrl, isValidId (prototype extension)
79
- static/js/client-url.js URL/scroll helpers: updateUrlForConversation, saveScrollPosition, restoreScrollPosition, setupScrollTracking (prototype extension)
80
- static/js/client-ui.js setupUI (modified, calls _setupUIButtonEvents/_setupUIWindowEvents) + setupChatMicButton (prototype extension)
81
- static/js/client-ui-controls.js _setupUIButtonEvents + _setupUIWindowEvents extracted helpers (prototype extension)
82
- static/js/client-ws-msg.js connectWebSocket, handleWebSocketMessage, queueEvent (prototype extension)
83
- static/js/client-streaming.js handleStreamingStart (prototype extension)
84
- static/js/client-streaming2.js handleStreamingResumed, handleStreamingProgress, _handleStreamingProgressInner (prototype extension)
85
- static/js/client-streaming3.js renderBlockContent, scrollToBottom, _showNewContentPill, _removeNewContentPill, handleStreamingError (prototype extension)
86
- static/js/client-streaming4.js handleStreamingComplete, _promptPushIfWeOwnRemote, handleConversationCreated, handleMessageCreated, queue handlers (prototype extension)
87
- static/js/client-events.js fetchAndRenderQueue, handleRateLimitHit/Clear, handleAllConversationsDeleted, isHtmlContent, sanitizeHtml, parseMarkdownCodeBlocks (prototype extension)
88
- static/js/client-render.js renderCodeBlock, renderMessageContent (prototype extension)
89
- static/js/client-exec.js startExecution, optimistic message helpers, _subscribeToConversationUpdates, _flushBgCache (prototype extension)
90
- static/js/client-helpers.js _recoverMissedChunks, cache/placeholder/height/countdown/debug helpers, showLoadingSpinner/hideLoadingSpinner (prototype extension)
91
- static/js/client-ui2.js _showWelcomeScreen, _showSkeletonLoading, streamToConversation, _hydrateSessionBlocks (prototype extension)
92
- static/js/client-conv.js _getLazyObserver, _renderConversationContent, renderChunk, _renderChunkInner, loadAgents, loadSubAgentsForCli (prototype extension)
93
- static/js/client-agents.js checkSpeechStatus, loadModelsForAgent, _populateModelSelector, lock/unlockAgentAndModel, applyAgentAndModelSelection, loadConversations, updateConnectionStatus (prototype extension)
94
- static/js/client-status.js _updateConnectionIndicator, _handleModelDownloadProgress, _handleTTSSetupProgress, _toggleConnectionTooltip, updateMetrics, controls, toggleTheme, createNewConversation (prototype extension)
95
- static/js/client-cache.js cacheCurrentConversation, invalidateCache, loadConversationMessages (prototype extension)
96
- static/js/client-load.js _makeLoadRequest, _verifyRequestId, _completeLoadRequest, _loadConvRender (prototype extension)
97
- static/js/client-scroll.js syncPromptState, updateBusyPromptArea, removeScrollUpDetection, setupScrollUpDetection (prototype extension)
83
+ static/js/client.js AgentGUIClient class (constructor + _dbg + init); instantiation at bottom
84
+ static/js/client-ws.js WebSocket listeners, _convIsStreaming, _setConvStreaming, setupRendererListeners, restoreStateFromUrl, isValidId (prototype extension)
85
+ static/js/client-url.js URL/scroll helpers: updateUrlForConversation, saveScrollPosition, restoreScrollPosition, setupScrollTracking (prototype extension)
86
+ static/js/client-ui.js setupUI (modified, calls _setupUIButtonEvents/_setupUIWindowEvents) + setupChatMicButton (prototype extension)
87
+ static/js/client-ui-controls.js _setupUIButtonEvents + _setupUIWindowEvents extracted helpers (prototype extension)
88
+ static/js/client-ws-msg.js connectWebSocket, handleWebSocketMessage, queueEvent (prototype extension)
89
+ static/js/client-streaming.js handleStreamingStart (prototype extension)
90
+ static/js/client-streaming2.js handleStreamingResumed, handleStreamingProgress, _handleStreamingProgressInner (prototype extension)
91
+ static/js/client-streaming3.js renderBlockContent, scrollToBottom, _showNewContentPill, _removeNewContentPill, handleStreamingError (prototype extension)
92
+ static/js/client-streaming4.js handleStreamingComplete, _promptPushIfWeOwnRemote, handleConversationCreated, handleMessageCreated, queue handlers (prototype extension)
93
+ static/js/client-events.js fetchAndRenderQueue, handleRateLimitHit/Clear, handleAllConversationsDeleted, isHtmlContent, sanitizeHtml, parseMarkdownCodeBlocks (prototype extension)
94
+ static/js/client-render.js renderCodeBlock, renderMessageContent (prototype extension)
95
+ static/js/client-exec.js startExecution, optimistic message helpers, _subscribeToConversationUpdates, _flushBgCache (prototype extension)
96
+ static/js/client-helpers.js _recoverMissedChunks, cache/placeholder/height/countdown/debug helpers, showLoadingSpinner/hideLoadingSpinner (prototype extension)
97
+ static/js/client-ui2.js _showWelcomeScreen, _showSkeletonLoading, streamToConversation, _hydrateSessionBlocks (prototype extension)
98
+ static/js/client-conv.js _getLazyObserver, _renderConversationContent, renderChunk, _renderChunkInner, loadAgents, loadSubAgentsForCli (prototype extension)
99
+ static/js/client-agents.js checkSpeechStatus, loadModelsForAgent, _populateModelSelector, lock/unlockAgentAndModel, applyAgentAndModelSelection, loadConversations, updateConnectionStatus (prototype extension)
100
+ static/js/client-status.js _updateConnectionIndicator, _handleModelDownloadProgress, _handleTTSSetupProgress, _toggleConnectionTooltip, updateMetrics, controls, toggleTheme, createNewConversation (prototype extension)
101
+ static/js/client-cache.js cacheCurrentConversation, invalidateCache, loadConversationMessages (prototype extension)
102
+ static/js/client-load.js _makeLoadRequest, _verifyRequestId, _completeLoadRequest, _loadConvRender (prototype extension)
103
+ static/js/client-scroll.js syncPromptState, updateBusyPromptArea, removeScrollUpDetection, setupScrollUpDetection (prototype extension)
98
104
  static/js/client-utils.js renderMessagesFragment, renderMessages, escapeHtml, showError, on, emit, agent/model getters, draft/prompt helpers, destroy (prototype extension)
99
105
  static/js/conversations.js Conversation management (class definition)
100
106
  static/js/conv-list-renderer.js Conversation list render, CRUD, WS listener (prototype extension)
@@ -0,0 +1,117 @@
1
+ import os from 'os';
2
+ import { spawn } from 'child_process';
3
+
4
+ export function register(deps) {
5
+ const { sendJSON, queries, broadcastSync, discoveredAgents, activeScripts, startGeminiOAuth, startCodexOAuth, getGeminiOAuthState, getCodexOAuthState, modelCache, PORT, BASE_URL, rootDir } = deps;
6
+
7
+ const routes = {};
8
+
9
+ routes['_match'] = (method, pathOnly) => {
10
+ let m;
11
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/agents\/([^/]+)\/auth$/))) return (req, res) => handleAgentAuth(req, res, m[1]);
12
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/agents\/([^/]+)\/update$/))) return (req, res) => handleAgentUpdate(req, res, m[1]);
13
+ return null;
14
+ };
15
+
16
+ async function handleAgentAuth(req, res, agentId) {
17
+ const agent = discoveredAgents.find(a => a.id === agentId);
18
+ if (!agent) { sendJSON(req, res, 404, { error: 'Agent not found' }); return; }
19
+
20
+ if (agentId === 'codex' || agentId === 'cli-codex') {
21
+ try {
22
+ const result = await startCodexOAuth(req, { PORT, BASE_URL });
23
+ const conversationId = '__agent_auth__';
24
+ broadcastSync({ type: 'script_started', conversationId, script: 'auth-codex', agentId: 'codex', timestamp: Date.now() });
25
+ broadcastSync({ type: 'script_output', conversationId, data: `\x1b[36mOpening OpenAI OAuth in your browser...\x1b[0m\r\n\r\nIf it doesn't open automatically, visit:\r\n${result.authUrl}\r\n`, stream: 'stdout', timestamp: Date.now() });
26
+ const pollId = setInterval(() => {
27
+ const state = getCodexOAuthState();
28
+ if (state.status === 'success') {
29
+ clearInterval(pollId);
30
+ const email = state.email || '';
31
+ broadcastSync({ type: 'script_output', conversationId, data: `\r\n\x1b[32mAuthentication successful${email ? ' (' + email + ')' : ''}\x1b[0m\r\n`, stream: 'stdout', timestamp: Date.now() });
32
+ broadcastSync({ type: 'script_stopped', conversationId, code: 0, timestamp: Date.now() });
33
+ } else if (state.status === 'error') {
34
+ clearInterval(pollId);
35
+ broadcastSync({ type: 'script_output', conversationId, data: `\r\n\x1b[31mAuthentication failed: ${state.error}\x1b[0m\r\n`, stream: 'stderr', timestamp: Date.now() });
36
+ broadcastSync({ type: 'script_stopped', conversationId, code: 1, error: state.error, timestamp: Date.now() });
37
+ }
38
+ }, 1000);
39
+ setTimeout(() => clearInterval(pollId), 5 * 60 * 1000);
40
+ sendJSON(req, res, 200, { ok: true, agentId, authUrl: result.authUrl, mode: result.mode });
41
+ } catch (e) {
42
+ console.error('[codex-oauth] /api/agents/codex/auth failed:', e);
43
+ sendJSON(req, res, 500, { error: e.message });
44
+ }
45
+ return;
46
+ }
47
+
48
+ if (agentId === 'gemini') {
49
+ try {
50
+ const result = await startGeminiOAuth(req, { PORT, BASE_URL, rootDir });
51
+ const conversationId = '__agent_auth__';
52
+ broadcastSync({ type: 'script_started', conversationId, script: 'auth-gemini', agentId: 'gemini', timestamp: Date.now() });
53
+ broadcastSync({ type: 'script_output', conversationId, data: `\x1b[36mOpening Google OAuth in your browser...\x1b[0m\r\n\r\nIf it doesn't open automatically, visit:\r\n${result.authUrl}\r\n`, stream: 'stdout', timestamp: Date.now() });
54
+ const pollId = setInterval(() => {
55
+ const state = getGeminiOAuthState();
56
+ if (state.status === 'success') {
57
+ clearInterval(pollId);
58
+ const email = state.email || '';
59
+ broadcastSync({ type: 'script_output', conversationId, data: `\r\n\x1b[32mAuthentication successful${email ? ' (' + email + ')' : ''}\x1b[0m\r\n`, stream: 'stdout', timestamp: Date.now() });
60
+ broadcastSync({ type: 'script_stopped', conversationId, code: 0, timestamp: Date.now() });
61
+ } else if (state.status === 'error') {
62
+ clearInterval(pollId);
63
+ broadcastSync({ type: 'script_output', conversationId, data: `\r\n\x1b[31mAuthentication failed: ${state.error}\x1b[0m\r\n`, stream: 'stderr', timestamp: Date.now() });
64
+ broadcastSync({ type: 'script_stopped', conversationId, code: 1, error: state.error, timestamp: Date.now() });
65
+ }
66
+ }, 1000);
67
+ setTimeout(() => clearInterval(pollId), 5 * 60 * 1000);
68
+ sendJSON(req, res, 200, { ok: true, agentId, authUrl: result.authUrl, mode: result.mode });
69
+ } catch (e) {
70
+ console.error('[gemini-oauth] /api/agents/gemini/auth failed:', e);
71
+ sendJSON(req, res, 500, { error: e.message });
72
+ }
73
+ return;
74
+ }
75
+
76
+ const authCommands = {
77
+ 'claude-code': { cmd: 'claude', args: ['setup-token'] },
78
+ 'opencode': { cmd: 'opencode', args: ['auth', 'login'] },
79
+ };
80
+ const authCmd = authCommands[agentId];
81
+ if (!authCmd) { sendJSON(req, res, 400, { error: 'No auth command for this agent' }); return; }
82
+ const conversationId = '__agent_auth__';
83
+ if (activeScripts.has(conversationId)) { sendJSON(req, res, 409, { error: 'Auth process already running' }); return; }
84
+ const child = spawn(authCmd.cmd, authCmd.args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, FORCE_COLOR: '1' }, shell: os.platform() === 'win32' });
85
+ activeScripts.set(conversationId, { process: child, script: 'auth-' + agentId, startTime: Date.now() });
86
+ broadcastSync({ type: 'script_started', conversationId, script: 'auth-' + agentId, agentId, timestamp: Date.now() });
87
+ const onData = (stream) => (chunk) => broadcastSync({ type: 'script_output', conversationId, data: chunk.toString(), stream, timestamp: Date.now() });
88
+ child.stdout.on('data', onData('stdout'));
89
+ child.stderr.on('data', onData('stderr'));
90
+ child.stdout.on('error', () => {});
91
+ child.stderr.on('error', () => {});
92
+ child.on('error', (err) => { activeScripts.delete(conversationId); broadcastSync({ type: 'script_stopped', conversationId, code: 1, error: err.message, timestamp: Date.now() }); });
93
+ child.on('close', (code) => { activeScripts.delete(conversationId); broadcastSync({ type: 'script_stopped', conversationId, code: code || 0, timestamp: Date.now() }); });
94
+ sendJSON(req, res, 200, { ok: true, agentId, pid: child.pid });
95
+ }
96
+
97
+ async function handleAgentUpdate(req, res, agentId) {
98
+ const updateCommands = { 'claude-code': { cmd: 'claude', args: ['update', '--yes'] } };
99
+ const updateCmd = updateCommands[agentId];
100
+ if (!updateCmd) { sendJSON(req, res, 400, { error: 'No update command for this agent' }); return; }
101
+ const conversationId = '__agent_update__';
102
+ if (activeScripts.has(conversationId)) { sendJSON(req, res, 409, { error: 'Update already running' }); return; }
103
+ const child = spawn(updateCmd.cmd, updateCmd.args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, FORCE_COLOR: '1' }, shell: os.platform() === 'win32' });
104
+ activeScripts.set(conversationId, { process: child, script: 'update-' + agentId, startTime: Date.now() });
105
+ broadcastSync({ type: 'script_started', conversationId, script: 'update-' + agentId, agentId, timestamp: Date.now() });
106
+ const onData = (stream) => (chunk) => broadcastSync({ type: 'script_output', conversationId, data: chunk.toString(), stream, timestamp: Date.now() });
107
+ child.stdout.on('data', onData('stdout'));
108
+ child.stderr.on('data', onData('stderr'));
109
+ child.stdout.on('error', () => {});
110
+ child.stderr.on('error', () => {});
111
+ child.on('error', (err) => { activeScripts.delete(conversationId); broadcastSync({ type: 'script_stopped', conversationId, code: 1, error: err.message, timestamp: Date.now() }); });
112
+ child.on('close', (code) => { activeScripts.delete(conversationId); modelCache.delete(agentId); broadcastSync({ type: 'script_stopped', conversationId, code: code || 0, timestamp: Date.now() }); });
113
+ sendJSON(req, res, 200, { ok: true, agentId, pid: child.pid });
114
+ }
115
+
116
+ return routes;
117
+ }
@@ -0,0 +1,30 @@
1
+ export function register(deps) {
2
+ const { sendJSON, parseBody, getProviderConfigs, saveProviderConfig } = deps;
3
+
4
+ const routes = {};
5
+
6
+ routes['GET /api/auth/configs'] = (req, res) => {
7
+ sendJSON(req, res, 200, getProviderConfigs());
8
+ };
9
+
10
+ routes['POST /api/auth/save-config'] = async (req, res) => {
11
+ try {
12
+ const body = await parseBody(req);
13
+ const { providerId, apiKey, defaultModel } = body || {};
14
+ if (typeof providerId !== 'string' || !providerId.length || providerId.length > 100) { sendJSON(req, res, 400, { error: 'Invalid providerId' }); return; }
15
+ if (typeof apiKey !== 'string' || !apiKey.length || apiKey.length > 10000) { sendJSON(req, res, 400, { error: 'Invalid apiKey' }); return; }
16
+ if (defaultModel !== undefined && (typeof defaultModel !== 'string' || defaultModel.length > 200)) { sendJSON(req, res, 400, { error: 'Invalid defaultModel' }); return; }
17
+ const configPath = saveProviderConfig(providerId, apiKey, defaultModel || '');
18
+ sendJSON(req, res, 200, { success: true, path: configPath });
19
+ } catch (err) {
20
+ sendJSON(req, res, 400, { error: err.message });
21
+ }
22
+ };
23
+
24
+ routes['_match'] = (method, pathOnly) => {
25
+ const key = `${method} ${pathOnly}`;
26
+ return routes[key] || null;
27
+ };
28
+
29
+ return routes;
30
+ }
@@ -0,0 +1,139 @@
1
+ export function register(deps) {
2
+ const { queries, sendJSON, parseBody, broadcastSync, processMessageWithStreaming, activeExecutions, messageQueues, debugLog, logError } = deps;
3
+
4
+ const routes = {};
5
+
6
+ routes['_match'] = (method, pathOnly) => {
7
+ let m;
8
+
9
+ if ((m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/messages$/))) {
10
+ if (method === 'GET') return (req, res) => handleGetMessages(req, res, m[1]);
11
+ if (method === 'POST') return (req, res) => handlePostMessage(req, res, m[1]);
12
+ }
13
+
14
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/stream$/)))
15
+ return (req, res) => handleStream(req, res, m[1]);
16
+
17
+ if ((m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/queue$/))) {
18
+ if (method === 'GET') return (req, res) => handleGetQueue(req, res, m[1]);
19
+ }
20
+
21
+ if ((m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/queue\/([^/]+)$/))) {
22
+ if (method === 'DELETE') return (req, res) => handleDeleteQueueItem(req, res, m[1], m[2]);
23
+ if (method === 'PATCH') return (req, res) => handlePatchQueueItem(req, res, m[1], m[2]);
24
+ }
25
+
26
+ return null;
27
+ };
28
+
29
+ async function handleGetMessages(req, res, conversationId) {
30
+ const url = new URL(req.url, 'http://localhost');
31
+ const limit = Math.min(parseInt(url.searchParams.get('limit') || '50'), 500);
32
+ const offset = Math.max(parseInt(url.searchParams.get('offset') || '0'), 0);
33
+ const result = queries.getPaginatedMessages(conversationId, limit, offset);
34
+ sendJSON(req, res, 200, result);
35
+ }
36
+
37
+ async function handlePostMessage(req, res, conversationId) {
38
+ const conv = queries.getConversation(conversationId);
39
+ if (!conv) { sendJSON(req, res, 404, { error: 'Conversation not found' }); return; }
40
+ const body = await parseBody(req);
41
+ const agentId = body.agentId || conv.agentType || conv.agentId || 'claude-code';
42
+ const model = body.model || conv.model || null;
43
+ const subAgent = body.subAgent || conv.subAgent || null;
44
+ const idempotencyKey = body.idempotencyKey || null;
45
+ const message = queries.createMessage(conversationId, 'user', body.content, idempotencyKey);
46
+ queries.createEvent('message.created', { role: 'user', messageId: message.id }, conversationId);
47
+ broadcastSync({ type: 'message_created', conversationId, message, timestamp: Date.now() });
48
+
49
+ if (activeExecutions.has(conversationId)) {
50
+ if (!messageQueues.has(conversationId)) messageQueues.set(conversationId, []);
51
+ messageQueues.get(conversationId).push({ content: body.content, agentId, model, messageId: message.id, subAgent });
52
+ const queueLength = messageQueues.get(conversationId).length;
53
+ broadcastSync({ type: 'queue_status', conversationId, queueLength, messageId: message.id, timestamp: Date.now() });
54
+ sendJSON(req, res, 200, { message, queued: true, queuePosition: queueLength, idempotencyKey });
55
+ return;
56
+ }
57
+
58
+ const session = queries.createSession(conversationId);
59
+ queries.createEvent('session.created', { messageId: message.id, sessionId: session.id }, conversationId, session.id);
60
+ activeExecutions.set(conversationId, { pid: null, startTime: Date.now(), sessionId: session.id, lastActivity: Date.now() });
61
+ queries.setIsStreaming(conversationId, true);
62
+ broadcastSync({ type: 'streaming_start', sessionId: session.id, conversationId, messageId: message.id, agentId, timestamp: Date.now() });
63
+ sendJSON(req, res, 201, { message, session, idempotencyKey });
64
+
65
+ processMessageWithStreaming(conversationId, message.id, session.id, body.content, agentId, model, subAgent)
66
+ .catch(err => {
67
+ console.error(`[messages] Uncaught error for conv ${conversationId}:`, err.message);
68
+ debugLog(`[messages] Uncaught error: ${err.message}`);
69
+ logError('processMessageWithStreaming', err, { convId: conversationId });
70
+ });
71
+ }
72
+
73
+ async function handleStream(req, res, conversationId) {
74
+ const body = await parseBody(req);
75
+ const conv = queries.getConversation(conversationId);
76
+ if (!conv) { sendJSON(req, res, 404, { error: 'Conversation not found' }); return; }
77
+
78
+ const prompt = body.content || body.message || '';
79
+ const agentId = body.agentId || conv.agentType || conv.agentId || 'claude-code';
80
+ const model = body.model || conv.model || null;
81
+ const subAgent = body.subAgent || conv.subAgent || null;
82
+
83
+ const userMessage = queries.createMessage(conversationId, 'user', prompt);
84
+ queries.createEvent('message.created', { role: 'user', messageId: userMessage.id }, conversationId);
85
+ broadcastSync({ type: 'message_created', conversationId, message: userMessage, timestamp: Date.now() });
86
+
87
+ if (activeExecutions.has(conversationId)) {
88
+ debugLog(`[stream] Conversation ${conversationId} is busy, queuing message`);
89
+ if (!messageQueues.has(conversationId)) messageQueues.set(conversationId, []);
90
+ messageQueues.get(conversationId).push({ content: prompt, agentId, model, messageId: userMessage.id, subAgent });
91
+ const queueLength = messageQueues.get(conversationId).length;
92
+ broadcastSync({ type: 'queue_status', conversationId, queueLength, messageId: userMessage.id, timestamp: Date.now() });
93
+ sendJSON(req, res, 200, { message: userMessage, queued: true, queuePosition: queueLength });
94
+ return;
95
+ }
96
+
97
+ const session = queries.createSession(conversationId);
98
+ queries.createEvent('session.created', { messageId: userMessage.id, sessionId: session.id }, conversationId, session.id);
99
+ activeExecutions.set(conversationId, { pid: null, startTime: Date.now(), sessionId: session.id, lastActivity: Date.now() });
100
+ queries.setIsStreaming(conversationId, true);
101
+ broadcastSync({ type: 'streaming_start', sessionId: session.id, conversationId, messageId: userMessage.id, agentId, timestamp: Date.now() });
102
+ sendJSON(req, res, 200, { message: userMessage, session, streamId: session.id });
103
+
104
+ processMessageWithStreaming(conversationId, userMessage.id, session.id, prompt, agentId, model, subAgent)
105
+ .catch(err => debugLog(`[stream] Uncaught error: ${err.stack || err.message}`));
106
+ }
107
+
108
+ async function handleGetQueue(req, res, conversationId) {
109
+ const conv = queries.getConversation(conversationId);
110
+ if (!conv) { sendJSON(req, res, 404, { error: 'Conversation not found' }); return; }
111
+ const queue = messageQueues.get(conversationId) || [];
112
+ sendJSON(req, res, 200, { queue });
113
+ }
114
+
115
+ async function handleDeleteQueueItem(req, res, conversationId, messageId) {
116
+ const queue = messageQueues.get(conversationId);
117
+ if (!queue) { sendJSON(req, res, 404, { error: 'Queue not found' }); return; }
118
+ const index = queue.findIndex(q => q.messageId === messageId);
119
+ if (index === -1) { sendJSON(req, res, 404, { error: 'Queued message not found' }); return; }
120
+ queue.splice(index, 1);
121
+ if (queue.length === 0) messageQueues.delete(conversationId);
122
+ broadcastSync({ type: 'queue_status', conversationId, queueLength: queue?.length || 0, timestamp: Date.now() });
123
+ sendJSON(req, res, 200, { deleted: true });
124
+ }
125
+
126
+ async function handlePatchQueueItem(req, res, conversationId, messageId) {
127
+ const body = await parseBody(req);
128
+ const queue = messageQueues.get(conversationId);
129
+ if (!queue) { sendJSON(req, res, 404, { error: 'Queue not found' }); return; }
130
+ const item = queue.find(q => q.messageId === messageId);
131
+ if (!item) { sendJSON(req, res, 404, { error: 'Queued message not found' }); return; }
132
+ if (body.content !== undefined) item.content = body.content;
133
+ if (body.agentId !== undefined) item.agentId = body.agentId;
134
+ broadcastSync({ type: 'queue_updated', conversationId, messageId, content: item.content, agentId: item.agentId, timestamp: Date.now() });
135
+ sendJSON(req, res, 200, { updated: true, item });
136
+ }
137
+
138
+ return routes;
139
+ }
@@ -0,0 +1,156 @@
1
+ import os from 'os';
2
+
3
+ export function register(deps) {
4
+ const { sendJSON, parseBody, queries, broadcastSync, processMessageWithStreaming, activeExecutions, activeProcessesByRunId, discoveredAgents, STARTUP_CWD } = deps;
5
+
6
+ const routes = {};
7
+
8
+ routes['_match'] = (method, pathOnly) => {
9
+ const key = `${method} ${pathOnly}`;
10
+ if (routes[key]) return routes[key];
11
+ let m;
12
+ if ((m = pathOnly.match(/^\/api\/runs\/([^/]+)$/))) return (req, res) => handleRunById(req, res, m[1]);
13
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/runs\/([^/]+)\/wait$/))) return (req, res) => handleRunWait(req, res, m[1]);
14
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/runs\/([^/]+)\/stream$/))) return (req, res) => { res.writeHead(410); res.end(JSON.stringify({ error: 'SSE removed, use WebSocket' })); };
15
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/runs\/([^/]+)\/cancel$/))) return (req, res) => handleRunCancel(req, res, m[1]);
16
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/threads\/([^/]+)\/runs\/([^/]+)\/cancel$/))) return (req, res) => handleThreadRunCancel(req, res, m[1], m[2]);
17
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/threads\/([^/]+)\/runs\/([^/]+)\/wait$/))) return (req, res) => handleThreadRunWait(req, res, m[1], m[2]);
18
+ return null;
19
+ };
20
+
21
+ routes['POST /api/runs'] = async (req, res) => {
22
+ let body = '';
23
+ for await (const chunk of req) { body += chunk; }
24
+ let parsed = {};
25
+ try { parsed = body ? JSON.parse(body) : {}; } catch {}
26
+ const { input, agentId } = parsed;
27
+ if (!input) { sendJSON(req, res, 400, { error: 'Missing input in request body' }); return; }
28
+ const resolvedAgentId = agentId || 'claude-code';
29
+ const resolvedModel = parsed.model || null;
30
+ const cwd = parsed.workingDirectory || STARTUP_CWD;
31
+ const thread = queries.createConversation(resolvedAgentId, 'Stateless Run', cwd);
32
+ const session = queries.createSession(thread.id, resolvedAgentId, 'pending');
33
+ const content = typeof input === 'string' ? input : JSON.stringify(input);
34
+ const message = queries.createMessage(thread.id, 'user', content);
35
+ processMessageWithStreaming(thread.id, message.id, session.id, content, resolvedAgentId, resolvedModel);
36
+ sendJSON(req, res, 200, { id: session.id, status: 'pending', started_at: session.started_at, agentId: resolvedAgentId });
37
+ };
38
+
39
+ routes['POST /api/runs/search'] = async (req, res) => {
40
+ const sessions = queries.getAllSessions();
41
+ const runs = sessions.slice(0, 50).map(s => ({ id: s.id, status: s.status, started_at: s.started_at, completed_at: s.completed_at, agentId: s.agentId, input: null, output: null })).reverse();
42
+ sendJSON(req, res, 200, runs);
43
+ };
44
+
45
+ routes['POST /api/runs/stream'] = (req, res) => { res.writeHead(410); res.end(JSON.stringify({ error: 'SSE removed, use WebSocket' })); };
46
+
47
+ routes['POST /api/runs/wait'] = async (req, res) => {
48
+ const body = await parseBody(req);
49
+ const { agent_id, input, config } = body;
50
+ if (!agent_id) { sendJSON(req, res, 422, { error: 'agent_id is required' }); return; }
51
+ const agent = discoveredAgents.find(a => a.id === agent_id);
52
+ if (!agent) { sendJSON(req, res, 404, { error: 'Agent not found' }); return; }
53
+ const run = queries.createRun(agent_id, null, input, config);
54
+ sendJSON(req, res, 200, run);
55
+ };
56
+
57
+ async function handleRunById(req, res, runId) {
58
+ if (req.method === 'GET') {
59
+ const run = queries.getRun(runId);
60
+ if (!run) { sendJSON(req, res, 404, { error: 'Run not found' }); return; }
61
+ sendJSON(req, res, 200, run);
62
+ return;
63
+ }
64
+ if (req.method === 'POST') {
65
+ const run = queries.getRun(runId);
66
+ if (!run) { sendJSON(req, res, 404, { error: 'Run not found' }); return; }
67
+ if (run.status !== 'pending') { sendJSON(req, res, 409, { error: 'Run is not resumable' }); return; }
68
+ sendJSON(req, res, 200, run);
69
+ return;
70
+ }
71
+ if (req.method === 'DELETE') {
72
+ try { queries.deleteRun(runId); res.writeHead(204); res.end(); } catch { sendJSON(req, res, 404, { error: 'Run not found' }); }
73
+ }
74
+ }
75
+
76
+ async function handleRunWait(req, res, runId) {
77
+ const run = queries.getRun(runId);
78
+ if (!run) { sendJSON(req, res, 404, { error: 'Run not found' }); return; }
79
+ const startTime = Date.now();
80
+ const poll = setInterval(() => {
81
+ const cur = queries.getRun(runId);
82
+ const done = cur && ['success', 'error', 'cancelled'].includes(cur.status);
83
+ if (done) { clearInterval(poll); sendJSON(req, res, 200, cur); }
84
+ else if (Date.now() - startTime > 30000) { clearInterval(poll); sendJSON(req, res, 408, { error: 'Run still pending after 30s', run_id: runId, status: cur?.status || run.status }); }
85
+ }, 500);
86
+ req.on('close', () => clearInterval(poll));
87
+ }
88
+
89
+ async function handleRunCancel(req, res, runId) {
90
+ try {
91
+ const run = queries.getRun(runId);
92
+ if (!run) { sendJSON(req, res, 404, { error: 'Run not found' }); return; }
93
+ if (['success', 'error', 'cancelled'].includes(run.status)) { sendJSON(req, res, 409, { error: 'Run already completed or cancelled' }); return; }
94
+ const cancelled = queries.cancelRun(runId);
95
+ const threadId = run.thread_id;
96
+ if (threadId) {
97
+ const execution = activeExecutions.get(threadId);
98
+ if (execution?.pid) {
99
+ try { process.kill(-execution.pid, 'SIGTERM'); } catch { try { process.kill(execution.pid, 'SIGTERM'); } catch {} }
100
+ setTimeout(() => { try { process.kill(-execution.pid, 'SIGKILL'); } catch { try { process.kill(execution.pid, 'SIGKILL'); } catch {} } }, 3000);
101
+ }
102
+ if (execution?.sessionId) queries.updateSession(execution.sessionId, { status: 'error', error: 'Cancelled by user', completed_at: Date.now() });
103
+ activeExecutions.delete(threadId);
104
+ queries.setIsStreaming(threadId, false);
105
+ broadcastSync({ type: 'streaming_cancelled', sessionId: execution?.sessionId || runId, conversationId: threadId, runId, timestamp: Date.now() });
106
+ }
107
+ sendJSON(req, res, 200, cancelled);
108
+ } catch (err) {
109
+ if (err.message === 'Run not found') sendJSON(req, res, 404, { error: err.message });
110
+ else if (err.message.includes('already completed')) sendJSON(req, res, 409, { error: err.message });
111
+ else sendJSON(req, res, 500, { error: err.message });
112
+ }
113
+ }
114
+
115
+ async function handleThreadRunCancel(req, res, threadId, runId) {
116
+ try {
117
+ const run = queries.getRun(runId);
118
+ if (!run) { sendJSON(req, res, 404, { error: 'Run not found' }); return; }
119
+ if (run.thread_id !== threadId) { sendJSON(req, res, 400, { error: 'Run does not belong to specified thread' }); return; }
120
+ if (['success', 'error', 'cancelled'].includes(run.status)) { sendJSON(req, res, 409, { error: 'Run already completed or cancelled' }); return; }
121
+ const cancelled = queries.cancelRun(runId);
122
+ const execution = activeExecutions.get(threadId);
123
+ if (execution?.pid) {
124
+ try { process.kill(-execution.pid, 'SIGTERM'); } catch { try { process.kill(execution.pid, 'SIGTERM'); } catch {} }
125
+ setTimeout(() => { try { process.kill(-execution.pid, 'SIGKILL'); } catch { try { process.kill(execution.pid, 'SIGKILL'); } catch {} } }, 3000);
126
+ }
127
+ if (execution?.sessionId) queries.updateSession(execution.sessionId, { status: 'error', error: 'Cancelled by user', completed_at: Date.now() });
128
+ activeExecutions.delete(threadId);
129
+ activeProcessesByRunId.delete(runId);
130
+ queries.setIsStreaming(threadId, false);
131
+ broadcastSync({ type: 'run_cancelled', runId, threadId, sessionId: execution?.sessionId, timestamp: Date.now() });
132
+ broadcastSync({ type: 'streaming_cancelled', sessionId: execution?.sessionId || runId, conversationId: threadId, runId, timestamp: Date.now() });
133
+ sendJSON(req, res, 200, cancelled);
134
+ } catch (err) {
135
+ if (err.message === 'Run not found') sendJSON(req, res, 404, { error: err.message });
136
+ else if (err.message.includes('already completed')) sendJSON(req, res, 409, { error: err.message });
137
+ else sendJSON(req, res, 500, { error: err.message });
138
+ }
139
+ }
140
+
141
+ async function handleThreadRunWait(req, res, threadId, runId) {
142
+ const run = queries.getRun(runId);
143
+ if (!run) { sendJSON(req, res, 404, { error: 'Run not found' }); return; }
144
+ if (run.thread_id !== threadId) { sendJSON(req, res, 400, { error: 'Run does not belong to specified thread' }); return; }
145
+ const startTime = Date.now();
146
+ const poll = setInterval(() => {
147
+ const cur = queries.getRun(runId);
148
+ const done = cur && ['success', 'error', 'cancelled'].includes(cur.status);
149
+ if (done) { clearInterval(poll); sendJSON(req, res, 200, cur); }
150
+ else if (Date.now() - startTime > 30000) { clearInterval(poll); sendJSON(req, res, 408, { error: 'Run still pending after 30s', run_id: runId, status: cur?.status || run.status }); }
151
+ }, 500);
152
+ req.on('close', () => clearInterval(poll));
153
+ }
154
+
155
+ return routes;
156
+ }