agentgui 1.0.931 → 1.0.933

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.
Files changed (129) hide show
  1. package/AGENTS.md +17 -12
  2. package/database.js +31 -2
  3. package/lib/http-handler.js +11 -25
  4. package/lib/routes-registry.js +4 -48
  5. package/lib/server-startup.js +3 -11
  6. package/lib/ws-setup.js +2 -1
  7. package/package.json +3 -3
  8. package/server.js +7 -1
  9. package/site/app/index.html +2 -2
  10. package/site/app/js/app.js +91 -86
  11. package/site/app/js/backend.js +1 -1
  12. package/static/lib/xstate.umd.min.js +1 -1
  13. package/lib/db-queries-chunks.js +0 -195
  14. package/lib/db-queries-chunks2.js +0 -82
  15. package/lib/db-queries-cleanup.js +0 -74
  16. package/lib/db-queries-del.js +0 -141
  17. package/lib/db-queries-events.js +0 -68
  18. package/lib/db-queries-import.js +0 -133
  19. package/lib/db-queries-messages.js +0 -102
  20. package/lib/db-queries-sessions.js +0 -112
  21. package/lib/db-queries-streams.js +0 -100
  22. package/lib/db-queries.js +0 -89
  23. package/lib/jsonl-parser.js +0 -190
  24. package/lib/jsonl-watcher.js +0 -64
  25. package/lib/routes-agent-actions.js +0 -61
  26. package/lib/routes-auth-config.js +0 -30
  27. package/lib/routes-conversations.js +0 -96
  28. package/lib/routes-debug.js +0 -119
  29. package/lib/routes-messages.js +0 -139
  30. package/lib/routes-runs.js +0 -156
  31. package/lib/routes-scripts.js +0 -135
  32. package/lib/routes-sessions.js +0 -144
  33. package/lib/routes-threads.js +0 -100
  34. package/lib/routes-util.js +0 -110
  35. package/lib/ws-handlers-conv.js +0 -138
  36. package/lib/ws-handlers-conv2.js +0 -169
  37. package/lib/ws-handlers-msg.js +0 -121
  38. package/lib/ws-handlers-queue.js +0 -56
  39. package/lib/ws-handlers-run.js +0 -182
  40. package/lib/ws-handlers-scripts.js +0 -66
  41. package/lib/ws-handlers-session.js +0 -105
  42. package/lib/ws-handlers-session2.js +0 -85
  43. package/lib/ws-legacy-handlers.js +0 -51
  44. package/static/app.js +0 -261
  45. package/static/css/app-shell.css +0 -419
  46. package/static/css/brand-bible.css +0 -591
  47. package/static/css/colors_and_type.css +0 -568
  48. package/static/css/gmail-skin.css +0 -663
  49. package/static/css/main.css +0 -4015
  50. package/static/css/tools-popup.css +0 -472
  51. package/static/index.html +0 -418
  52. package/static/js/agent-auth.js +0 -146
  53. package/static/js/app-shortcuts.js +0 -30
  54. package/static/js/audio-recorder-processor.js +0 -18
  55. package/static/js/client-agents.js +0 -155
  56. package/static/js/client-cache.js +0 -171
  57. package/static/js/client-conv.js +0 -198
  58. package/static/js/client-events.js +0 -164
  59. package/static/js/client-exec.js +0 -160
  60. package/static/js/client-helpers.js +0 -199
  61. package/static/js/client-load.js +0 -175
  62. package/static/js/client-render.js +0 -132
  63. package/static/js/client-scroll.js +0 -178
  64. package/static/js/client-status.js +0 -167
  65. package/static/js/client-streaming.js +0 -117
  66. package/static/js/client-streaming2.js +0 -116
  67. package/static/js/client-streaming3.js +0 -153
  68. package/static/js/client-streaming4.js +0 -194
  69. package/static/js/client-ui-controls.js +0 -170
  70. package/static/js/client-ui.js +0 -128
  71. package/static/js/client-ui2.js +0 -160
  72. package/static/js/client-url.js +0 -93
  73. package/static/js/client-utils.js +0 -174
  74. package/static/js/client-ws-msg.js +0 -88
  75. package/static/js/client-ws.js +0 -161
  76. package/static/js/client.js +0 -145
  77. package/static/js/codec.js +0 -4
  78. package/static/js/conv-list-machine.js +0 -145
  79. package/static/js/conv-list-renderer.js +0 -198
  80. package/static/js/conv-machine.js +0 -110
  81. package/static/js/conv-sidebar-actions.js +0 -188
  82. package/static/js/conv-sidebar-clone.js +0 -91
  83. package/static/js/conversations.js +0 -116
  84. package/static/js/dialogs-types.js +0 -111
  85. package/static/js/dialogs.js +0 -53
  86. package/static/js/event-filter-config.js +0 -36
  87. package/static/js/event-processor.js +0 -181
  88. package/static/js/features.js +0 -187
  89. package/static/js/image-loader-element.js +0 -76
  90. package/static/js/image-loader.js +0 -146
  91. package/static/js/prompt-machine.js +0 -108
  92. package/static/js/recording-machine.js +0 -49
  93. package/static/js/script-runner.js +0 -192
  94. package/static/js/state-barrier.js +0 -105
  95. package/static/js/streaming-renderer-dispatch.js +0 -144
  96. package/static/js/streaming-renderer-events.js +0 -163
  97. package/static/js/streaming-renderer-events2.js +0 -125
  98. package/static/js/streaming-renderer-params.js +0 -38
  99. package/static/js/streaming-renderer-render-misc.js +0 -107
  100. package/static/js/streaming-renderer-render.js +0 -181
  101. package/static/js/streaming-renderer-render2.js +0 -149
  102. package/static/js/streaming-renderer-render3.js +0 -142
  103. package/static/js/streaming-renderer-static.js +0 -181
  104. package/static/js/streaming-renderer-static2.js +0 -140
  105. package/static/js/streaming-renderer-stream.js +0 -170
  106. package/static/js/streaming-renderer-text.js +0 -185
  107. package/static/js/streaming-renderer-tools.js +0 -189
  108. package/static/js/streaming-renderer-tools2.js +0 -92
  109. package/static/js/streaming-renderer.js +0 -200
  110. package/static/js/syntax-highlighter-render.js +0 -72
  111. package/static/js/syntax-highlighter.js +0 -131
  112. package/static/js/terminal-machine.js +0 -51
  113. package/static/js/terminal.js +0 -178
  114. package/static/js/ui-components-rendering.js +0 -62
  115. package/static/js/ui-components.js +0 -88
  116. package/static/js/websocket-manager.js +0 -107
  117. package/static/js/ws-client.js +0 -87
  118. package/static/js/ws-core.js +0 -162
  119. package/static/js/ws-latency.js +0 -88
  120. package/static/js/ws-machine.js +0 -68
  121. package/static/lib/msgpackr.min.js +0 -2
  122. package/static/theme.js +0 -74
  123. package/static/vendor/highlight-js.css +0 -10
  124. package/static/vendor/highlight.min.js +0 -1244
  125. package/static/vendor/prism-dark.css +0 -129
  126. package/static/vendor/rippleui.css +0 -35
  127. package/static/vendor/xterm-addon-fit.min.js +0 -8
  128. package/static/vendor/xterm.css +0 -8
  129. package/static/vendor/xterm.min.js +0 -8
package/lib/db-queries.js DELETED
@@ -1,89 +0,0 @@
1
- import { createACPQueries } from '../acp-queries.js';
2
- import { addMessageQueries } from './db-queries-messages.js';
3
- import { addSessionQueries } from './db-queries-sessions.js';
4
- import { addEventQueries } from './db-queries-events.js';
5
- import { addDeleteQueries } from './db-queries-del.js';
6
- import { addCleanupQueries } from './db-queries-cleanup.js';
7
- import { addImportQueries } from './db-queries-import.js';
8
- import { addStreamQueries } from './db-queries-streams.js';
9
- import { addChunkQueries } from './db-queries-chunks.js';
10
- import { addChunkQueries2 } from './db-queries-chunks2.js';
11
-
12
- export function createQueries(db, prep, generateId) {
13
- const q = {
14
- _db: db,
15
- createConversation(agentType, title = null, workingDirectory = null, model = null, subAgent = null) {
16
- const id = generateId('conv');
17
- const now = Date.now();
18
- const stmt = prep(
19
- `INSERT INTO conversations (id, agentId, agentType, title, created_at, updated_at, status, workingDirectory, model, subAgent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
20
- );
21
- stmt.run(id, agentType, agentType, title, now, now, 'active', workingDirectory, model, subAgent);
22
- return { id, agentType, title, workingDirectory, model, subAgent, created_at: now, updated_at: now, status: 'active' };
23
- },
24
- getConversation(id) { return prep('SELECT * FROM conversations WHERE id = ?').get(id); },
25
- getAllConversations() { return prep('SELECT * FROM conversations WHERE status != ? ORDER BY updated_at DESC').all('deleted'); },
26
- getConversationsList() {
27
- return prep('SELECT id, agentId, title, agentType, created_at, updated_at, messageCount, workingDirectory, isStreaming, model, subAgent, pinned, sortOrder, tags FROM conversations WHERE status NOT IN (?, ?) ORDER BY pinned DESC, sortOrder ASC, updated_at DESC').all('deleted', 'archived');
28
- },
29
- getConversations() { return prep('SELECT * FROM conversations WHERE status NOT IN (?, ?) ORDER BY pinned DESC, sortOrder ASC, updated_at DESC').all('deleted', 'archived'); },
30
- updateConversationSortOrder(id, sortOrder) { prep('UPDATE conversations SET sortOrder = ? WHERE id = ?').run(sortOrder, id); },
31
- getArchivedConversations() { return prep('SELECT id, agentId, title, agentType, created_at, updated_at, messageCount, workingDirectory, model, subAgent FROM conversations WHERE status = ? ORDER BY updated_at DESC').all('archived'); },
32
- archiveConversation(id) {
33
- const conv = this.getConversation(id);
34
- if (!conv) return null;
35
- prep('UPDATE conversations SET status = ?, updated_at = ? WHERE id = ?').run('archived', Date.now(), id);
36
- return this.getConversation(id);
37
- },
38
- restoreConversation(id) {
39
- const conv = this.getConversation(id);
40
- if (!conv) return null;
41
- prep('UPDATE conversations SET status = ?, updated_at = ? WHERE id = ?').run('active', Date.now(), id);
42
- return this.getConversation(id);
43
- },
44
- updateConversation(id, data) {
45
- const conv = this.getConversation(id);
46
- if (!conv) return null;
47
- const now = Date.now();
48
- const title = data.title !== undefined ? data.title : conv.title;
49
- const status = data.status !== undefined ? data.status : conv.status;
50
- const agentId = data.agentId !== undefined ? data.agentId : conv.agentId;
51
- const agentType = data.agentType !== undefined ? data.agentType : conv.agentType;
52
- const model = data.model !== undefined ? data.model : conv.model;
53
- const subAgent = data.subAgent !== undefined ? data.subAgent : conv.subAgent;
54
- const pinned = data.pinned !== undefined ? (data.pinned ? 1 : 0) : (conv.pinned || 0);
55
- const tags = data.tags !== undefined ? (Array.isArray(data.tags) ? data.tags.join(',') : data.tags) : (conv.tags || null);
56
- prep(`UPDATE conversations SET title = ?, status = ?, agentId = ?, agentType = ?, model = ?, subAgent = ?, pinned = ?, tags = ?, updated_at = ? WHERE id = ?`).run(title, status, agentId, agentType, model, subAgent, pinned, tags, now, id);
57
- return { ...conv, title, status, agentId, agentType, model, subAgent, pinned, tags, updated_at: now };
58
- },
59
- setClaudeSessionId(conversationId, claudeSessionId, sessionId = null) {
60
- prep('UPDATE conversations SET claudeSessionId = ?, updated_at = ? WHERE id = ?').run(claudeSessionId, Date.now(), conversationId);
61
- if (sessionId) prep('UPDATE sessions SET claudeSessionId = ? WHERE id = ?').run(claudeSessionId, sessionId);
62
- },
63
- getConversationByClaudeSessionId(claudeSessionId) { return prep('SELECT * FROM conversations WHERE claudeSessionId = ? AND status NOT IN (?, ?) LIMIT 1').get(claudeSessionId, 'deleted', 'archived') || null; },
64
- getClaudeSessionId(conversationId) { const row = prep('SELECT claudeSessionId FROM conversations WHERE id = ?').get(conversationId); return row?.claudeSessionId || null; },
65
- setIsStreaming(conversationId, isStreaming) { prep('UPDATE conversations SET isStreaming = ?, updated_at = ? WHERE id = ?').run(isStreaming ? 1 : 0, Date.now(), conversationId); },
66
- getIsStreaming(conversationId) { const row = prep('SELECT isStreaming FROM conversations WHERE id = ?').get(conversationId); return row?.isStreaming === 1; },
67
- getStreamingConversations() { return prep('SELECT id, title, claudeSessionId, agentId, agentType, model, subAgent FROM conversations WHERE isStreaming = 1').all(); },
68
- getResumableConversations(withinMs = 600000) {
69
- const cutoff = Date.now() - withinMs;
70
- return prep(`SELECT DISTINCT c.id, c.title, c.claudeSessionId, c.agentId, c.agentType, c.workingDirectory, c.model, c.subAgent FROM conversations c WHERE EXISTS (SELECT 1 FROM sessions s WHERE s.conversationId = c.id AND s.status IN ('active', 'pending', 'interrupted') AND s.started_at > ?)`).all(cutoff);
71
- },
72
- clearAllStreamingFlags() { return prep('UPDATE conversations SET isStreaming = 0 WHERE isStreaming = 1').run().changes; },
73
- markSessionIncomplete(sessionId, errorMsg) { prep('UPDATE sessions SET status = ?, error = ?, completed_at = ? WHERE id = ?').run('incomplete', errorMsg || 'unknown', Date.now(), sessionId); },
74
- getSessionsProcessingLongerThan(minutes) { const cutoff = Date.now() - (minutes * 60 * 1000); return prep("SELECT * FROM sessions WHERE status IN ('active', 'pending') AND started_at < ?").all(cutoff); },
75
- cleanupOrphanedSessions(days) { const cutoff = Date.now() - (days * 24 * 60 * 60 * 1000); return prep("DELETE FROM sessions WHERE status IN ('active', 'pending') AND started_at < ?").run(cutoff).changes || 0; },
76
- };
77
-
78
- addMessageQueries(q, db, prep, generateId);
79
- addSessionQueries(q, db, prep, generateId);
80
- addEventQueries(q, db, prep, generateId);
81
- addDeleteQueries(q, db, prep, generateId);
82
- addCleanupQueries(q, db, prep, generateId);
83
- addImportQueries(q, db, prep, generateId);
84
- addStreamQueries(q, db, prep, generateId);
85
- addChunkQueries(q, db, prep, generateId);
86
- addChunkQueries2(q, db, prep, generateId);
87
- Object.assign(q, createACPQueries(db, prep));
88
- return q;
89
- }
@@ -1,190 +0,0 @@
1
- import path from 'path';
2
-
3
- export class JsonlParser {
4
- constructor({ broadcastSync, queries }) {
5
- this._bc = broadcastSync;
6
- this._q = queries;
7
- this._convMap = new Map();
8
- this._emitted = new Map();
9
- this._seqs = new Map();
10
- this._streaming = new Set();
11
- this._sessions = new Map();
12
- }
13
-
14
- /**
15
- * Pre-register a GUI-spawned session so _conv finds the right conversation
16
- * and _dbSession reuses the existing session ID instead of creating a new one.
17
- * Must be called as soon as session_id is obtained from Claude stdout, before
18
- * the 16ms file-watcher debounce fires.
19
- */
20
- registerSession(claudeSessionId, convId, dbSessionId) {
21
- this._convMap.set(claudeSessionId, convId);
22
- if (dbSessionId) this._sessions.set(claudeSessionId, dbSessionId);
23
- }
24
-
25
- clear() {
26
- this._convMap.clear();
27
- this._emitted.clear();
28
- this._seqs.clear();
29
- this._streaming.clear();
30
- this._sessions.clear();
31
- }
32
-
33
- removeSid(sid) {
34
- this._convMap.delete(sid);
35
- this._seqs.delete(sid);
36
- this._streaming.delete(sid);
37
- this._sessions.delete(sid);
38
- for (const key of [...this._emitted.keys()]) if (key.startsWith(`${sid}:`)) this._emitted.delete(key);
39
- }
40
-
41
- endAllStreaming() {
42
- for (const sid of [...this._streaming]) this._endStreaming(this._convMap.get(sid), sid);
43
- }
44
-
45
- _conv(sid, e, fp) {
46
- if (this._convMap.has(sid)) return this._convMap.get(sid);
47
- const found = this._q.getConversationByClaudeSessionId(sid);
48
- if (found) { this._convMap.set(sid, found.id); return found.id; }
49
- if (e.type === 'queue-operation' || e.type === 'last-prompt') return null;
50
- if (e.type === 'user' && e.isMeta) return null;
51
-
52
- // Resolve workingDirectory: event cwd → decode encoded directory name
53
- let cwd = e.cwd || null;
54
- if (!cwd && fp) {
55
- const projectDir = path.dirname(fp);
56
- // Decode encoded directory name (replace leading '-' with '/', rest '-' → '/')
57
- const dirName = path.basename(projectDir);
58
- if (dirName.startsWith('-')) cwd = '/' + dirName.slice(1).replace(/-/g, '/');
59
- }
60
- cwd = cwd || process.cwd();
61
-
62
- const branch = e.gitBranch || '';
63
- const base = path.basename(cwd);
64
- const title = branch ? `${branch} @ ${base}` : base;
65
- const conv = this._q.createConversation('claude-code', title, cwd);
66
- this._q.setClaudeSessionId(conv.id, sid);
67
- this._convMap.set(sid, conv.id);
68
- this._bc({ type: 'conversation_created', conversation: conv, timestamp: Date.now() });
69
- return conv.id;
70
- }
71
-
72
- _seq(sid) { const n = (this._seqs.get(sid) || 0) + 1; this._seqs.set(sid, n); return n; }
73
-
74
- _dbSession(cid, sid) {
75
- if (this._sessions.has(sid)) return this._sessions.get(sid);
76
- const sess = this._q.createSession(cid);
77
- this._q.updateSession(sess.id, { status: 'active' });
78
- this._sessions.set(sid, sess.id);
79
- return sess.id;
80
- }
81
-
82
- _emit(cid, sid, block, role, extra) {
83
- const dbSid = this._dbSession(cid, sid);
84
- const seq = this._seq(sid);
85
- try { this._q.createChunk(dbSid, cid, seq, block.type || 'unknown', block); } catch (_) {}
86
- this._bc({ type: 'streaming_progress', sessionId: dbSid, conversationId: cid, block, blockRole: role, seq, timestamp: Date.now(), ...extra });
87
- }
88
-
89
- _emitBlocks(cid, sid, blocks, role) {
90
- for (const b of blocks) {
91
- if (!b || !b.type) continue;
92
- this._emit(cid, sid, b, role);
93
- }
94
- }
95
-
96
- _startStreaming(cid, sid) {
97
- if (this._streaming.has(sid)) return;
98
- this._streaming.add(sid);
99
- const dbSid = this._dbSession(cid, sid);
100
- this._q.setIsStreaming(cid, true);
101
- this._bc({ type: 'streaming_start', sessionId: dbSid, conversationId: cid, agentId: 'cli-claude', timestamp: Date.now() });
102
- }
103
-
104
- _endStreaming(cid, sid) {
105
- if (!this._streaming.has(sid)) return;
106
- this._streaming.delete(sid);
107
- const dbSid = this._sessions.get(sid);
108
- if (dbSid) {
109
- try { this._q.updateSession(dbSid, { status: 'completed', completed_at: Date.now() }); } catch (_) {}
110
- }
111
- this._q.setIsStreaming(cid, false);
112
- this._bc({ type: 'streaming_complete', sessionId: dbSid || sid, conversationId: cid, agentId: 'cli-claude', eventCount: 0, seq: this._seq(sid), timestamp: Date.now() });
113
- this._sessions.delete(sid);
114
- }
115
-
116
- _route(cid, sid, e) {
117
- if (e.type === 'queue-operation' || e.type === 'last-prompt' || (e.type === 'user' && e.isMeta)) return;
118
-
119
- if (e.isApiErrorMessage && e.error === 'rate_limit') {
120
- this._bc({ type: 'streaming_error', sessionId: this._sessions.get(sid) || sid, conversationId: cid, error: 'Rate limit hit', recoverable: true, timestamp: Date.now() });
121
- return;
122
- }
123
-
124
- if (e.type === 'system') {
125
- if (e.subtype === 'init') { this._startStreaming(cid, sid); return; }
126
- if (e.subtype === 'turn_duration' || e.subtype === 'stop_hook_summary') { this._endStreaming(cid, sid); return; }
127
- this._startStreaming(cid, sid);
128
- this._emit(cid, sid, { type: 'system', subtype: e.subtype, model: e.model, cwd: e.cwd, tools: e.tools, preTokens: e.compactMetadata?.preTokens }, 'system');
129
- return;
130
- }
131
-
132
- if (e.type === 'assistant' && e.message?.content) {
133
- this._startStreaming(cid, sid);
134
- const key = `${sid}:${e.message.id}`;
135
- const prev = this._emitted.get(key) || 0;
136
- const content = e.message.content;
137
- const newBlocks = content.slice(prev);
138
- if (newBlocks.length > 0) {
139
- this._emitted.set(key, content.length);
140
- this._emitBlocks(cid, sid, newBlocks, 'assistant');
141
- }
142
- if (e.message.stop_reason) this._emitted.delete(key);
143
- return;
144
- }
145
-
146
- if (e.type === 'user' && e.message?.content) {
147
- if (e.isCompactSummary) { this._emit(cid, sid, { type: 'compact_summary', content: e.message.content }, 'system'); return; }
148
- this._startStreaming(cid, sid);
149
- const content = e.message.content;
150
- const textParts = Array.isArray(content)
151
- ? content.filter(b => b.type === 'text' && b.text && !b.text.startsWith('<task-notification>')).map(b => b.text).join('\n')
152
- : (typeof content === 'string' && !content.startsWith('<task-notification>') ? content : '');
153
- if (textParts) {
154
- try { this._q.createMessage(cid, 'user', textParts); } catch (_) {}
155
- }
156
- const blocks = Array.isArray(content) ? content : [];
157
- for (const b of blocks) if (b.type === 'tool_result') this._emit(cid, sid, b, 'tool_result');
158
- return;
159
- }
160
-
161
- if (e.type === 'progress') {
162
- this._startStreaming(cid, sid);
163
- const d = e.data || {};
164
- if (d.type === 'agent_progress') {
165
- const inner = d.message?.message || d.message;
166
- const content = inner?.content;
167
- if (Array.isArray(content)) {
168
- const role = inner.role === 'user' ? 'tool_result' : 'assistant';
169
- this._emitBlocks(cid, sid, content, role);
170
- }
171
- return;
172
- }
173
- if (d.type === 'hook_progress') {
174
- this._emit(cid, sid, { type: 'hook_progress', hookEvent: d.hookEvent, hookName: d.hookName }, 'system');
175
- return;
176
- }
177
- if (d.type === 'mcp_progress') {
178
- this._emit(cid, sid, { type: 'mcp_progress', status: d.status, serverName: d.serverName, toolName: d.toolName }, 'system');
179
- return;
180
- }
181
- this._emit(cid, sid, { type: d.type || e.subtype || 'progress', content: e.content || d }, 'progress');
182
- return;
183
- }
184
-
185
- if (e.type === 'result') {
186
- this._emit(cid, sid, { type: 'result', result: e.result, subtype: e.subtype, duration_ms: e.duration_ms, total_cost_usd: e.total_cost_usd, is_error: e.is_error || false }, 'result', { isResult: true });
187
- this._endStreaming(cid, sid);
188
- }
189
- }
190
- }
@@ -1,64 +0,0 @@
1
- import fs from 'fs';
2
- import { JsonlWatcher as CCFWatcher } from 'ccfollow';
3
- import { JsonlParser } from './jsonl-parser.js';
4
-
5
- export class JsonlWatcher extends CCFWatcher {
6
- constructor({ broadcastSync, queries }) {
7
- super();
8
- this._parser = new JsonlParser({ broadcastSync, queries });
9
- this._currentFp = null;
10
- }
11
-
12
- /** Override _read to capture the current file path for project-folder resolution in _conv */
13
- _read(fp) {
14
- this._currentFp = fp;
15
- super._read(fp);
16
- this._currentFp = null;
17
- }
18
-
19
- _line(line) {
20
- line = line.trim();
21
- if (!line) return;
22
- let e;
23
- try { e = JSON.parse(line); } catch (_) { return; }
24
- if (!e || !e.sessionId) return;
25
- const cid = this._parser._conv(e.sessionId, e, this._currentFp);
26
- if (cid) this._parser._route(cid, e.sessionId, e);
27
- }
28
-
29
- /**
30
- * Pre-register a GUI-spawned session so the parser uses the correct existing
31
- * conversation and session ID rather than creating duplicates.
32
- * Call this as soon as session_id is obtained from Claude stdout.
33
- */
34
- registerSession(claudeSessionId, convId, dbSessionId) {
35
- this._parser.registerSession(claudeSessionId, convId, dbSessionId);
36
- }
37
-
38
- stop() {
39
- super.stop();
40
- this._parser.endAllStreaming();
41
- }
42
-
43
- removeConversation(conversationId) {
44
- const sids = [...this._parser._convMap.entries()].filter(([, cid]) => cid === conversationId).map(([sid]) => sid);
45
- for (const sid of sids) {
46
- this._parser.removeSid(sid);
47
- for (const [fp, s] of this._tails.entries()) {
48
- if (!fp.includes(sid)) continue;
49
- if (s.fd !== null) try { fs.closeSync(s.fd); } catch (_) {}
50
- this._tails.delete(fp);
51
- const t = this._timers.get(fp);
52
- if (t) { clearTimeout(t); this._timers.delete(fp); }
53
- }
54
- }
55
- }
56
-
57
- removeAllConversations() {
58
- for (const s of this._tails.values()) if (s.fd !== null) try { fs.closeSync(s.fd); } catch (_) {}
59
- for (const t of this._timers.values()) clearTimeout(t);
60
- this._tails.clear();
61
- this._timers.clear();
62
- this._parser.clear();
63
- }
64
- }
@@ -1,61 +0,0 @@
1
- import os from 'os';
2
- import { spawn } from 'child_process';
3
-
4
- export function register(deps) {
5
- const { sendJSON, queries, broadcastSync, discoveredAgents, activeScripts, modelCache } = 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
- const authCommands = {
21
- 'claude-code': { cmd: 'claude', args: ['setup-token'] },
22
- 'opencode': { cmd: 'opencode', args: ['auth', 'login'] },
23
- };
24
- const authCmd = authCommands[agentId];
25
- if (!authCmd) { sendJSON(req, res, 400, { error: 'No auth command for this agent (OAuth flows removed; configure provider key via /api/auth/save-config)' }); return; }
26
- const conversationId = '__agent_auth__';
27
- if (activeScripts.has(conversationId)) { sendJSON(req, res, 409, { error: 'Auth process already running' }); return; }
28
- const child = spawn(authCmd.cmd, authCmd.args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, FORCE_COLOR: '1' }, shell: os.platform() === 'win32' });
29
- activeScripts.set(conversationId, { process: child, script: 'auth-' + agentId, startTime: Date.now() });
30
- broadcastSync({ type: 'script_started', conversationId, script: 'auth-' + agentId, agentId, timestamp: Date.now() });
31
- const onData = (stream) => (chunk) => broadcastSync({ type: 'script_output', conversationId, data: chunk.toString(), stream, timestamp: Date.now() });
32
- child.stdout.on('data', onData('stdout'));
33
- child.stderr.on('data', onData('stderr'));
34
- child.stdout.on('error', () => {});
35
- child.stderr.on('error', () => {});
36
- child.on('error', (err) => { activeScripts.delete(conversationId); broadcastSync({ type: 'script_stopped', conversationId, code: 1, error: err.message, timestamp: Date.now() }); });
37
- child.on('close', (code) => { activeScripts.delete(conversationId); broadcastSync({ type: 'script_stopped', conversationId, code: code || 0, timestamp: Date.now() }); });
38
- sendJSON(req, res, 200, { ok: true, agentId, pid: child.pid });
39
- }
40
-
41
- async function handleAgentUpdate(req, res, agentId) {
42
- const updateCommands = { 'claude-code': { cmd: 'claude', args: ['update', '--yes'] } };
43
- const updateCmd = updateCommands[agentId];
44
- if (!updateCmd) { sendJSON(req, res, 400, { error: 'No update command for this agent' }); return; }
45
- const conversationId = '__agent_update__';
46
- if (activeScripts.has(conversationId)) { sendJSON(req, res, 409, { error: 'Update already running' }); return; }
47
- const child = spawn(updateCmd.cmd, updateCmd.args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, FORCE_COLOR: '1' }, shell: os.platform() === 'win32' });
48
- activeScripts.set(conversationId, { process: child, script: 'update-' + agentId, startTime: Date.now() });
49
- broadcastSync({ type: 'script_started', conversationId, script: 'update-' + agentId, agentId, timestamp: Date.now() });
50
- const onData = (stream) => (chunk) => broadcastSync({ type: 'script_output', conversationId, data: chunk.toString(), stream, timestamp: Date.now() });
51
- child.stdout.on('data', onData('stdout'));
52
- child.stderr.on('data', onData('stderr'));
53
- child.stdout.on('error', () => {});
54
- child.stderr.on('error', () => {});
55
- child.on('error', (err) => { activeScripts.delete(conversationId); broadcastSync({ type: 'script_stopped', conversationId, code: 1, error: err.message, timestamp: Date.now() }); });
56
- child.on('close', (code) => { activeScripts.delete(conversationId); modelCache.delete(agentId); broadcastSync({ type: 'script_stopped', conversationId, code: code || 0, timestamp: Date.now() }); });
57
- sendJSON(req, res, 200, { ok: true, agentId, pid: child.pid });
58
- }
59
-
60
- return routes;
61
- }
@@ -1,30 +0,0 @@
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
- }
@@ -1,96 +0,0 @@
1
- import path from 'path';
2
- import os from 'os';
3
-
4
- function expandTilde(p) { return p && p.startsWith('~') ? path.join(os.homedir(), p.slice(1)) : p; }
5
-
6
- export function register(deps) {
7
- const { sendJSON, parseBody, queries, activeExecutions, broadcastSync } = deps;
8
- const routes = {};
9
-
10
- routes['GET /api/conversations'] = async (req, res) => {
11
- const conversations = queries.getConversationsList();
12
- for (const conv of conversations) {
13
- if (conv.isStreaming && !activeExecutions.has(conv.id)) {
14
- conv.isStreaming = 0;
15
- try {
16
- queries.setIsStreaming(conv.id, false);
17
- for (const s of queries.getSessionsByConversation(conv.id, 5)) {
18
- if (s.status === 'active' || s.status === 'pending') {
19
- queries.updateSession(s.id, { status: 'interrupted', error: 'Reconciled: no active execution', completed_at: Date.now() });
20
- }
21
- }
22
- } catch (err) { console.error(`[conv-list-reconcile] ${conv.id}:`, err.message); }
23
- }
24
- }
25
- sendJSON(req, res, 200, { conversations });
26
- };
27
-
28
- routes['POST /api/conversations'] = async (req, res) => {
29
- const body = await parseBody(req);
30
- const normalizedWorkingDir = body.workingDirectory ? path.resolve(expandTilde(body.workingDirectory)) : null;
31
- const conversation = queries.createConversation(body.agentId, body.title, normalizedWorkingDir, body.model || null);
32
- queries.createEvent('conversation.created', { agentId: body.agentId, workingDirectory: conversation.workingDirectory, model: conversation.model }, conversation.id);
33
- broadcastSync({ type: 'conversation_created', conversation });
34
- sendJSON(req, res, 201, { conversation });
35
- };
36
-
37
- routes['GET /api/conversations/archived'] = async (req, res) => {
38
- sendJSON(req, res, 200, { conversations: queries.getArchivedConversations() });
39
- };
40
-
41
- routes['_match'] = (method, pathOnly) => {
42
- const key = `${method} ${pathOnly}`;
43
- if (routes[key]) return routes[key];
44
- let m;
45
- if ((m = pathOnly.match(/^\/api\/conversations\/([^/]+)$/))) {
46
- if (method === 'GET') return (req, res) => handleGetConv(req, res, m[1]);
47
- if (method === 'POST' || method === 'PUT') return (req, res) => handleUpdateConv(req, res, m[1]);
48
- if (method === 'DELETE') return (req, res) => handleDeleteConv(req, res, m[1]);
49
- }
50
- if (method === 'POST' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/archive$/)))
51
- return (req, res) => handleArchive(req, res, m[1]);
52
- if (method === 'POST' && (m = pathOnly.match(/^\/api\/conversations\/([^/]+)\/restore$/)))
53
- return (req, res) => handleRestore(req, res, m[1]);
54
- return null;
55
- };
56
-
57
- async function handleGetConv(req, res, id) {
58
- const conv = queries.getConversation(id);
59
- if (!conv) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
60
- const latestSession = queries.getLatestSession(id);
61
- sendJSON(req, res, 200, { conversation: conv, isActivelyStreaming: activeExecutions.has(id), latestSession });
62
- }
63
-
64
- async function handleUpdateConv(req, res, id) {
65
- const body = await parseBody(req);
66
- if (body.workingDirectory) body.workingDirectory = path.resolve(expandTilde(body.workingDirectory));
67
- const conv = queries.updateConversation(id, body);
68
- if (!conv) { sendJSON(req, res, 404, { error: 'Conversation not found' }); return; }
69
- queries.createEvent('conversation.updated', body, id);
70
- broadcastSync({ type: 'conversation_updated', conversation: conv });
71
- sendJSON(req, res, 200, { conversation: conv });
72
- }
73
-
74
- async function handleDeleteConv(req, res, id) {
75
- const deleted = queries.deleteConversation(id);
76
- if (!deleted) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
77
- broadcastSync({ type: 'conversation_deleted', conversationId: id });
78
- sendJSON(req, res, 200, { deleted: true });
79
- }
80
-
81
- async function handleArchive(req, res, id) {
82
- const conv = queries.archiveConversation(id);
83
- if (!conv) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
84
- broadcastSync({ type: 'conversation_updated', conversation: conv, archived: true });
85
- sendJSON(req, res, 200, { conversation: conv });
86
- }
87
-
88
- async function handleRestore(req, res, id) {
89
- const conv = queries.restoreConversation(id);
90
- if (!conv) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
91
- broadcastSync({ type: 'conversation_updated', conversation: conv, restored: true });
92
- sendJSON(req, res, 200, { conversation: conv });
93
- }
94
-
95
- return routes;
96
- }
@@ -1,119 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import os from 'os';
4
- import * as execMachine from './execution-machine.js';
5
- import * as acpServerMachine from './acp-server-machine.js';
6
-
7
- function collectMachineSnapshots(activeExecutions) {
8
- const execution = {};
9
- for (const id of activeExecutions.keys()) {
10
- const s = execMachine.snapshot(id);
11
- if (s) execution[id] = { state: s.value, context: { pid: s.context.pid, sessionId: s.context.sessionId, queueLen: s.context.queue?.length } };
12
- }
13
- const acpServer = {};
14
- for (const [id, actor] of acpServerMachine.getMachineActors()) {
15
- const s = actor.getSnapshot();
16
- acpServer[id] = { state: s.value, context: { pid: s.context.pid, healthy: s.context.healthy, startedAt: s.context.startedAt, lastUsed: s.context.lastUsed, restarts: s.context.restarts?.length || 0, providerInfo: s.context.providerInfo } };
17
- }
18
- return { execution, acpServer };
19
- }
20
-
21
- function readRecentErrors(errLogPath, limit = 50) {
22
- try {
23
- const raw = fs.readFileSync(errLogPath, 'utf8');
24
- return raw.trim().split('\n').slice(-limit).map(l => { try { return JSON.parse(l); } catch { return l; } });
25
- } catch { return []; }
26
- }
27
-
28
- export function register(deps) {
29
- const { sendJSON, queries, activeExecutions, messageQueues, syncClients, wsOptimizer, _errLogPath } = deps;
30
- const routes = {};
31
-
32
- function snapshotExecutions() {
33
- const o = {};
34
- for (const [k, v] of activeExecutions) o[k] = { pid: v.pid, startTime: v.startTime, sessionId: v.sessionId, lastActivity: v.lastActivity };
35
- return o;
36
- }
37
- function snapshotQueues() {
38
- const o = {};
39
- for (const [k, v] of messageQueues) o[k] = { length: v.length, messageIds: v.map(m => m.messageId) };
40
- return o;
41
- }
42
- function snapshotWsClients() {
43
- const out = [];
44
- for (const ws of syncClients) out.push({ clientId: ws.clientId, subs: ws.subscriptions ? [...ws.subscriptions] : [] });
45
- return out;
46
- }
47
- function streamingConvs() {
48
- try { return queries.getConversationsList().filter(c => c.isStreaming).map(c => ({ id: c.id, isStreaming: c.isStreaming })); }
49
- catch { return []; }
50
- }
51
-
52
- routes['GET /api/debug'] = async (req, res) => {
53
- sendJSON(req, res, 200, {
54
- activeExecutions: snapshotExecutions(),
55
- messageQueues: snapshotQueues(),
56
- streamingConversations: streamingConvs(),
57
- wsClients: snapshotWsClients(),
58
- recentErrors: readRecentErrors(_errLogPath, 20),
59
- });
60
- };
61
-
62
- routes['GET /api/debug/state'] = async (req, res) => {
63
- if (!process.env.DEBUG) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
64
- sendJSON(req, res, 200, {
65
- activeExecutions: snapshotExecutions(),
66
- messageQueues: snapshotQueues(),
67
- streamingConversations: streamingConvs(),
68
- wsClients: snapshotWsClients(),
69
- machines: collectMachineSnapshots(activeExecutions),
70
- wsStats: wsOptimizer.getStats(),
71
- recentErrors: readRecentErrors(_errLogPath, 50),
72
- uptime: process.uptime(),
73
- memory: process.memoryUsage(),
74
- });
75
- };
76
-
77
- routes['GET /api/debug/machines'] = async (req, res) => {
78
- if (!process.env.DEBUG) { sendJSON(req, res, 404, { error: 'Not found' }); return; }
79
- sendJSON(req, res, 200, collectMachineSnapshots(activeExecutions));
80
- };
81
-
82
- routes['GET /api/ws-stats'] = async (req, res) => {
83
- sendJSON(req, res, 200, wsOptimizer.getStats());
84
- };
85
-
86
- routes['GET /api/debug/ws-stats'] = routes['GET /api/ws-stats'];
87
-
88
- routes['GET /api/backup'] = async (req, res) => {
89
- const dbPath = path.join(os.homedir(), '.gmgui', 'data.db');
90
- if (!fs.existsSync(dbPath)) { sendJSON(req, res, 404, { error: 'Database not found' }); return; }
91
- const stat = fs.statSync(dbPath);
92
- res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="agentgui-backup.db"', 'Content-Length': stat.size });
93
- fs.createReadStream(dbPath).pipe(res);
94
- };
95
-
96
- routes['POST /api/restore'] = async (req, res) => {
97
- const dbPath = path.join(os.homedir(), '.gmgui', 'data.db');
98
- const backupPath = dbPath + '.bak-' + Date.now();
99
- const chunks = [];
100
- req.on('data', (chunk) => chunks.push(chunk));
101
- req.on('end', () => {
102
- try {
103
- const body = Buffer.concat(chunks);
104
- if (body.length < 100 || body.slice(0, 16).toString() !== 'SQLite format 3\0') {
105
- sendJSON(req, res, 400, { error: 'Invalid SQLite database file' }); return;
106
- }
107
- fs.copyFileSync(dbPath, backupPath);
108
- fs.writeFileSync(dbPath, body);
109
- sendJSON(req, res, 200, { success: true, backupPath, size: body.length });
110
- } catch (e) {
111
- sendJSON(req, res, 500, { error: e.message });
112
- }
113
- });
114
- };
115
-
116
- routes['_match'] = (method, pathOnly) => routes[`${method} ${pathOnly}`] || null;
117
-
118
- return routes;
119
- }