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.
@@ -0,0 +1,135 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { spawn } from 'child_process';
5
+
6
+ export function register(deps) {
7
+ const { sendJSON, parseBody, queries, broadcastSync, activeScripts, activeExecutions, processMessageWithStreaming, STARTUP_CWD } = deps;
8
+
9
+ const routes = {};
10
+
11
+ routes['_match'] = (method, pathOnly) => {
12
+ let m;
13
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/scripts$/))) return (req, res) => handleScripts(req, res, m[1]);
14
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/run-script$/))) return (req, res) => handleRunScript(req, res, m[1]);
15
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/stop-script$/))) return (req, res) => handleStopScript(req, res, m[1]);
16
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/script-status$/))) return (req, res) => handleScriptStatus(req, res, m[1]);
17
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/cancel$/))) return (req, res) => handleCancel(req, res, m[1]);
18
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/resume$/))) return (req, res) => handleResume(req, res, m[1]);
19
+ if (method === 'POST' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/inject$/))) return (req, res) => handleInject(req, res, m[1]);
20
+ return null;
21
+ };
22
+
23
+ async function handleScripts(req, res, conversationId) {
24
+ const conv = queries.getConversation(conversationId);
25
+ if (!conv) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
26
+ const wd = conv.workingDirectory || STARTUP_CWD;
27
+ let hasStart = false, hasDev = false;
28
+ try {
29
+ const pkg = JSON.parse(fs.readFileSync(path.join(wd, 'package.json'), 'utf-8'));
30
+ const scripts = pkg.scripts || {};
31
+ hasStart = !!scripts.start;
32
+ hasDev = !!scripts.dev;
33
+ } catch {}
34
+ const running = activeScripts.has(conversationId);
35
+ const runningScript = running ? activeScripts.get(conversationId).script : null;
36
+ sendJSON(req, res, 200, { hasStart, hasDev, running, runningScript });
37
+ }
38
+
39
+ async function handleRunScript(req, res, conversationId) {
40
+ const conv = queries.getConversation(conversationId);
41
+ if (!conv) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
42
+ if (activeScripts.has(conversationId)) { sendJSON(req, res, 409, { error: 'Script already running' }); return; }
43
+ const body = await parseBody(req);
44
+ const script = body.script;
45
+ if (script !== 'start' && script !== 'dev') { sendJSON(req, res, 400, { error: 'Invalid script' }); return; }
46
+ const wd = conv.workingDirectory || STARTUP_CWD;
47
+ try {
48
+ const pkg = JSON.parse(fs.readFileSync(path.join(wd, 'package.json'), 'utf-8'));
49
+ if (!pkg.scripts || !pkg.scripts[script]) { sendJSON(req, res, 400, { error: `Script "${script}" not found` }); return; }
50
+ } catch { sendJSON(req, res, 400, { error: 'No package.json' }); return; }
51
+ const childEnv = { ...process.env, FORCE_COLOR: '1' };
52
+ delete childEnv.PORT;
53
+ delete childEnv.BASE_URL;
54
+ delete childEnv.HOT_RELOAD;
55
+ const isWindows = os.platform() === 'win32';
56
+ const child = spawn('npm', ['run', script], { cwd: wd, stdio: ['ignore', 'pipe', 'pipe'], detached: true, env: childEnv, shell: isWindows });
57
+ activeScripts.set(conversationId, { process: child, script, startTime: Date.now() });
58
+ broadcastSync({ type: 'script_started', conversationId, script, timestamp: Date.now() });
59
+ const onData = (stream) => (chunk) => broadcastSync({ type: 'script_output', conversationId, data: chunk.toString(), stream, timestamp: Date.now() });
60
+ child.stdout.on('data', onData('stdout'));
61
+ child.stderr.on('data', onData('stderr'));
62
+ child.stdout.on('error', () => {});
63
+ child.stderr.on('error', () => {});
64
+ child.on('error', (err) => { activeScripts.delete(conversationId); broadcastSync({ type: 'script_stopped', conversationId, code: 1, error: err.message, timestamp: Date.now() }); });
65
+ child.on('close', (code) => { activeScripts.delete(conversationId); broadcastSync({ type: 'script_stopped', conversationId, code: code || 0, timestamp: Date.now() }); });
66
+ sendJSON(req, res, 200, { ok: true, script, pid: child.pid });
67
+ }
68
+
69
+ async function handleStopScript(req, res, conversationId) {
70
+ const entry = activeScripts.get(conversationId);
71
+ if (!entry) { sendJSON(req, res, 404, { error: 'No running script' }); return; }
72
+ try { process.kill(-entry.process.pid, 'SIGTERM'); } catch { try { entry.process.kill('SIGTERM'); } catch {} }
73
+ sendJSON(req, res, 200, { ok: true });
74
+ }
75
+
76
+ async function handleScriptStatus(req, res, conversationId) {
77
+ const entry = activeScripts.get(conversationId);
78
+ sendJSON(req, res, 200, { running: !!entry, script: entry?.script || null });
79
+ }
80
+
81
+ async function handleCancel(req, res, conversationId) {
82
+ const entry = activeExecutions.get(conversationId);
83
+ if (!entry) { sendJSON(req, res, 404, { error: 'No active execution to cancel' }); return; }
84
+ const { pid, sessionId } = entry;
85
+ if (pid) {
86
+ try { process.kill(-pid, 'SIGKILL'); } catch { try { process.kill(pid, 'SIGKILL'); } catch {} }
87
+ }
88
+ if (sessionId) queries.updateSession(sessionId, { status: 'interrupted', completed_at: Date.now() });
89
+ queries.setIsStreaming(conversationId, false);
90
+ activeExecutions.delete(conversationId);
91
+ broadcastSync({ type: 'streaming_complete', sessionId, conversationId, interrupted: true, timestamp: Date.now() });
92
+ sendJSON(req, res, 200, { ok: true, cancelled: true, conversationId, sessionId });
93
+ }
94
+
95
+ async function handleResume(req, res, conversationId) {
96
+ const conv = queries.getConversation(conversationId);
97
+ if (!conv) { sendJSON(req, res, 404, { error: 'Conversation not found' }); return; }
98
+ if (activeExecutions.get(conversationId)) { sendJSON(req, res, 409, { error: 'Conversation already has an active execution' }); return; }
99
+ let body = '';
100
+ for await (const chunk of req) { body += chunk; }
101
+ let parsed = {};
102
+ try { parsed = body ? JSON.parse(body) : {}; } catch {}
103
+ const { content, agentId } = parsed;
104
+ if (!content) { sendJSON(req, res, 400, { error: 'Missing content in request body' }); return; }
105
+ const resolvedAgentId = agentId || conv.agentId || 'claude-code';
106
+ const resolvedModel = parsed.model || conv.model || null;
107
+ const session = queries.createSession(conversationId, resolvedAgentId, 'pending');
108
+ const message = queries.createMessage(conversationId, 'user', content);
109
+ processMessageWithStreaming(conversationId, message.id, session.id, content, resolvedAgentId, resolvedModel);
110
+ sendJSON(req, res, 200, { ok: true, conversationId, sessionId: session.id, messageId: message.id, resumed: true });
111
+ }
112
+
113
+ async function handleInject(req, res, conversationId) {
114
+ const conv = queries.getConversation(conversationId);
115
+ if (!conv) { sendJSON(req, res, 404, { error: 'Conversation not found' }); return; }
116
+ let body = '';
117
+ for await (const chunk of req) { body += chunk; }
118
+ let parsed = {};
119
+ try { parsed = body ? JSON.parse(body) : {}; } catch {}
120
+ const { content, eager } = parsed;
121
+ if (!content) { sendJSON(req, res, 400, { error: 'Missing content in request body' }); return; }
122
+ const entry = activeExecutions.get(conversationId);
123
+ if (entry && eager) { sendJSON(req, res, 409, { error: 'Cannot eagerly inject while execution is running - message queued' }); return; }
124
+ const message = queries.createMessage(conversationId, 'user', '[INJECTED] ' + content);
125
+ if (!entry) {
126
+ const resolvedAgentId = conv.agentId || 'claude-code';
127
+ const resolvedModel = conv.model || null;
128
+ const session = queries.createSession(conversationId, resolvedAgentId, 'pending');
129
+ processMessageWithStreaming(conversationId, message.id, session.id, message.content, resolvedAgentId, resolvedModel);
130
+ }
131
+ sendJSON(req, res, 200, { ok: true, injected: true, conversationId, messageId: message.id });
132
+ }
133
+
134
+ return routes;
135
+ }
@@ -0,0 +1,144 @@
1
+ export function register(deps) {
2
+ const { queries, sendJSON, activeExecutions, rateLimitState, debugLog } = deps;
3
+
4
+ const routes = {};
5
+
6
+ routes['_match'] = (method, pathOnly) => {
7
+ let m;
8
+
9
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/messages\/([^/]+)$/)))
10
+ return (req, res) => handleGetMessage(req, res, m[1], m[2]);
11
+
12
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/sessions\/([^/]+)$/)))
13
+ return (req, res) => handleGetSession(req, res, m[1]);
14
+
15
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/full$/)))
16
+ return (req, res) => handleFullLoad(req, res, m[1]);
17
+
18
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/chunks$/)))
19
+ return (req, res) => handleConvChunks(req, res, m[1]);
20
+
21
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/sessions\/([^/]+)\/chunks$/)))
22
+ return (req, res) => handleSessionChunks(req, res, m[1]);
23
+
24
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/sessions\/latest$/)))
25
+ return (req, res) => handleLatestSession(req, res, m[1]);
26
+
27
+ if (method === 'GET' && (m = pathOnly.match(/^\/api\/sessions\/([^/]+)\/execution$/)))
28
+ return (req, res) => handleExecution(req, res, m[1]);
29
+
30
+ return null;
31
+ };
32
+
33
+ async function handleGetMessage(req, res, conversationId, msgId) {
34
+ const msg = queries.getMessage(msgId);
35
+ if (!msg || msg.conversationId !== conversationId) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
36
+ sendJSON(req, res, 200, { message: msg });
37
+ }
38
+
39
+ async function handleGetSession(req, res, sessionId) {
40
+ const sess = queries.getSession(sessionId);
41
+ if (!sess) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
42
+ const events = queries.getSessionEvents(sessionId);
43
+ sendJSON(req, res, 200, { session: sess, events });
44
+ }
45
+
46
+ async function handleFullLoad(req, res, conversationId) {
47
+ const conv = queries.getConversation(conversationId);
48
+ if (!conv) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
49
+ const latestSession = queries.getLatestSession(conversationId);
50
+ const isActivelyStreaming = activeExecutions.has(conversationId);
51
+ const url = new URL(req.url, 'http://localhost');
52
+ const chunkLimit = Math.min(parseInt(url.searchParams.get('chunkLimit') || '500'), 5000);
53
+ const allChunks = url.searchParams.get('allChunks') === '1';
54
+ const totalChunks = queries.getConversationChunkCount(conversationId);
55
+ let chunks;
56
+ if (allChunks || totalChunks <= chunkLimit) {
57
+ chunks = queries.getConversationChunks(conversationId);
58
+ } else {
59
+ chunks = queries.getRecentConversationChunks(conversationId, chunkLimit);
60
+ }
61
+ const msgResult = queries.getPaginatedMessages(conversationId, 100, 0);
62
+ const rateLimitInfo = rateLimitState.get(conversationId) || null;
63
+ sendJSON(req, res, 200, {
64
+ conversation: conv,
65
+ isActivelyStreaming,
66
+ latestSession,
67
+ chunks,
68
+ totalChunks,
69
+ messages: msgResult.messages,
70
+ rateLimitInfo
71
+ });
72
+ }
73
+
74
+ async function handleConvChunks(req, res, conversationId) {
75
+ const conv = queries.getConversation(conversationId);
76
+ if (!conv) { sendJSON(req, res, 404, { error: 'Conversation not found' }); return; }
77
+ const url = new URL(req.url, 'http://localhost');
78
+ const since = parseInt(url.searchParams.get('since') || '0');
79
+ const all = url.searchParams.get('all') === 'true';
80
+ const totalChunks = queries.getConversationChunkCount(conversationId);
81
+ let chunks;
82
+ if (since > 0) {
83
+ chunks = queries.getConversationChunksSince(conversationId, since);
84
+ } else if (all) {
85
+ chunks = queries.getConversationChunks(conversationId);
86
+ } else {
87
+ chunks = queries.getRecentConversationChunks(conversationId, 500);
88
+ }
89
+ debugLog(`[chunks] Conv ${conversationId}: ${chunks.length} chunks (total: ${totalChunks})`);
90
+ sendJSON(req, res, 200, { ok: true, chunks, totalChunks });
91
+ }
92
+
93
+ async function handleSessionChunks(req, res, sessionId) {
94
+ const sess = queries.getSession(sessionId);
95
+ if (!sess) { sendJSON(req, res, 404, { error: 'Session not found' }); return; }
96
+ const url = new URL(req.url, 'http://localhost');
97
+ const sinceSeq = parseInt(url.searchParams.get('sinceSeq') || '-1');
98
+ const since = parseInt(url.searchParams.get('since') || '0');
99
+ let chunks;
100
+ if (sinceSeq >= 0) {
101
+ chunks = queries.getChunksSinceSeq(sessionId, sinceSeq);
102
+ } else {
103
+ chunks = queries.getChunksSince(sessionId, since);
104
+ }
105
+ sendJSON(req, res, 200, { ok: true, chunks });
106
+ }
107
+
108
+ async function handleLatestSession(req, res, convId) {
109
+ const latestSession = queries.getLatestSession(convId);
110
+ if (!latestSession) { sendJSON(req, res, 200, { session: null }); return; }
111
+ const events = queries.getSessionEvents(latestSession.id);
112
+ sendJSON(req, res, 200, { session: latestSession, events });
113
+ }
114
+
115
+ async function handleExecution(req, res, sessionId) {
116
+ const url = new URL(req.url, 'http://localhost');
117
+ const limit = Math.min(parseInt(url.searchParams.get('limit') || '1000'), 5000);
118
+ const offset = Math.max(parseInt(url.searchParams.get('offset') || '0'), 0);
119
+ const filterType = url.searchParams.get('filterType');
120
+ try {
121
+ const session = queries.getSession(sessionId);
122
+ const allChunks = session ? (queries.getChunksSince(sessionId, 0) || []) : [];
123
+ const filtered = filterType ? allChunks.filter(e => e.type === filterType) : allChunks;
124
+ sendJSON(req, res, 200, {
125
+ sessionId,
126
+ events: filtered.slice(offset, offset + limit),
127
+ total: filtered.length,
128
+ limit,
129
+ offset,
130
+ hasMore: offset + limit < filtered.length,
131
+ metadata: {
132
+ status: session?.status || 'unknown',
133
+ startTime: session?.created_at || null,
134
+ duration: session?.completed_at && session?.created_at ? session.completed_at - session.created_at : 0,
135
+ eventCount: filtered.length
136
+ }
137
+ });
138
+ } catch (err) {
139
+ sendJSON(req, res, 400, { error: err.message });
140
+ }
141
+ }
142
+
143
+ return routes;
144
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentgui",
3
- "version": "1.0.838",
3
+ "version": "1.0.840",
4
4
  "description": "Multi-agent ACP client with real-time communication",
5
5
  "type": "module",
6
6
  "main": "electron/main.js",