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
@@ -1,141 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import os from 'os';
4
-
5
- export function addDeleteQueries(q, db, prep, generateId) {
6
- q.deleteConversation = function(id) {
7
- const conv = this.getConversation(id);
8
- if (!conv) return false;
9
-
10
- const sessionClaudeIds = prep('SELECT DISTINCT claudeSessionId FROM sessions WHERE conversationId = ? AND claudeSessionId IS NOT NULL').all(id).map(r => r.claudeSessionId);
11
- if (conv.claudeSessionId && !sessionClaudeIds.includes(conv.claudeSessionId)) {
12
- sessionClaudeIds.push(conv.claudeSessionId);
13
- }
14
- for (const csid of sessionClaudeIds) {
15
- this.deleteClaudeSessionFile(csid);
16
- }
17
-
18
- const deleteStmt = db.transaction(() => {
19
- const sessionIds = prep('SELECT id FROM sessions WHERE conversationId = ?').all(id).map(r => r.id);
20
- prep('DELETE FROM stream_updates WHERE conversationId = ?').run(id);
21
- prep('DELETE FROM chunks WHERE conversationId = ?').run(id);
22
- prep('DELETE FROM events WHERE conversationId = ?').run(id);
23
- if (sessionIds.length > 0) {
24
- const placeholders = sessionIds.map(() => '?').join(',');
25
- db.prepare(`DELETE FROM stream_updates WHERE sessionId IN (${placeholders})`).run(...sessionIds);
26
- db.prepare(`DELETE FROM chunks WHERE sessionId IN (${placeholders})`).run(...sessionIds);
27
- db.prepare(`DELETE FROM events WHERE sessionId IN (${placeholders})`).run(...sessionIds);
28
- }
29
- prep('DELETE FROM sessions WHERE conversationId = ?').run(id);
30
- prep('DELETE FROM messages WHERE conversationId = ?').run(id);
31
- prep('UPDATE conversations SET status = ?, updated_at = ? WHERE id = ?').run('deleted', Date.now(), id);
32
- });
33
-
34
- deleteStmt();
35
- return true;
36
- };
37
-
38
- q.deleteClaudeSessionFile = function(sessionId) {
39
- try {
40
- const claudeDir = path.join(os.homedir(), '.claude');
41
- const projectsDir = path.join(claudeDir, 'projects');
42
-
43
- if (!fs.existsSync(projectsDir)) {
44
- return false;
45
- }
46
-
47
- const projects = fs.readdirSync(projectsDir);
48
- for (const project of projects) {
49
- const projectPath = path.join(projectsDir, project);
50
- const sessionFile = path.join(projectPath, `${sessionId}.jsonl`);
51
-
52
- if (fs.existsSync(sessionFile)) {
53
- fs.unlinkSync(sessionFile);
54
- console.log(`[deleteClaudeSessionFile] Deleted Claude session file: ${sessionFile}`);
55
-
56
- const indexPath = path.join(projectPath, 'sessions-index.json');
57
- if (fs.existsSync(indexPath)) {
58
- try {
59
- const indexContent = fs.readFileSync(indexPath, 'utf8');
60
- const index = JSON.parse(indexContent);
61
- if (index.entries && Array.isArray(index.entries)) {
62
- const originalLength = index.entries.length;
63
- index.entries = index.entries.filter(entry => entry.sessionId !== sessionId);
64
- if (index.entries.length < originalLength) {
65
- fs.writeFileSync(indexPath, JSON.stringify(index, null, 2), { encoding: 'utf8' });
66
- console.log(`[deleteClaudeSessionFile] Removed session ${sessionId} from sessions-index.json in ${projectPath}`);
67
- }
68
- }
69
- } catch (indexErr) {
70
- console.error(`[deleteClaudeSessionFile] Failed to update sessions-index.json in ${projectPath}:`, indexErr.message);
71
- }
72
- }
73
-
74
- const sessionDir = path.join(projectPath, sessionId);
75
- if (fs.existsSync(sessionDir)) {
76
- try {
77
- fs.rmSync(sessionDir, { recursive: true, force: true });
78
- console.log(`[deleteClaudeSessionFile] Deleted Claude session dir: ${sessionDir}`);
79
- } catch (dirErr) {
80
- console.error(`[deleteClaudeSessionFile] Failed to delete session dir ${sessionDir}:`, dirErr.message);
81
- }
82
- }
83
-
84
- return true;
85
- }
86
- }
87
-
88
- return false;
89
- } catch (err) {
90
- console.error(`[deleteClaudeSessionFile] Error deleting session ${sessionId}:`, err.message);
91
- return false;
92
- }
93
- };
94
-
95
- q.deleteAllConversations = function() {
96
- try {
97
- const allClaudeSessionIds = prep('SELECT DISTINCT claudeSessionId FROM sessions WHERE claudeSessionId IS NOT NULL').all().map(r => r.claudeSessionId);
98
- const convClaudeIds = prep('SELECT DISTINCT claudeSessionId FROM conversations WHERE claudeSessionId IS NOT NULL').all().map(r => r.claudeSessionId);
99
- for (const csid of convClaudeIds) {
100
- if (!allClaudeSessionIds.includes(csid)) allClaudeSessionIds.push(csid);
101
- }
102
- for (const csid of allClaudeSessionIds) {
103
- this.deleteClaudeSessionFile(csid);
104
- }
105
-
106
- const deleteAllStmt = db.transaction(() => {
107
- prep('DELETE FROM stream_updates').run();
108
- prep('DELETE FROM chunks').run();
109
- prep('DELETE FROM events').run();
110
- prep('DELETE FROM sessions').run();
111
- prep('DELETE FROM messages').run();
112
- prep("UPDATE conversations SET status = 'deleted', updated_at = ? WHERE status != 'deleted'").run(Date.now());
113
- });
114
-
115
- deleteAllStmt();
116
- const projectsDir = path.join(os.homedir(), '.claude', 'projects');
117
- if (fs.existsSync(projectsDir)) {
118
- for (const project of fs.readdirSync(projectsDir)) {
119
- const pdir = path.join(projectsDir, project);
120
- try {
121
- if (!fs.statSync(pdir).isDirectory()) continue;
122
- for (const entry of fs.readdirSync(pdir, { withFileTypes: true })) {
123
- if (entry.isFile() && entry.name.endsWith('.jsonl')) {
124
- fs.unlinkSync(path.join(pdir, entry.name));
125
- } else if (entry.isDirectory()) {
126
- fs.rmSync(path.join(pdir, entry.name), { recursive: true, force: true });
127
- }
128
- }
129
- } catch (err) {
130
- console.error('[deleteAllConversations] Failed to clean project dir:', pdir, err.message);
131
- }
132
- }
133
- }
134
- console.log('[deleteAllConversations] Deleted all conversations and associated Claude Code files');
135
- return true;
136
- } catch (err) {
137
- console.error('[deleteAllConversations] Error deleting all conversations:', err.message);
138
- return false;
139
- }
140
- };
141
- }
@@ -1,68 +0,0 @@
1
- export function addEventQueries(q, db, prep, generateId) {
2
- q.createEvent = function(type, data, conversationId = null, sessionId = null, idempotencyKey = null) {
3
- if (idempotencyKey) {
4
- const cached = this.getIdempotencyKey(idempotencyKey);
5
- if (cached) {
6
- console.log(`[event-idempotency] Event already exists for key ${idempotencyKey}, returning cached`);
7
- return JSON.parse(cached);
8
- }
9
- }
10
-
11
- const id = generateId('evt');
12
- const now = Date.now();
13
-
14
- const stmt = prep(
15
- `INSERT INTO events (id, type, conversationId, sessionId, data, created_at) VALUES (?, ?, ?, ?, ?, ?)`
16
- );
17
- stmt.run(id, type, conversationId, sessionId, JSON.stringify(data), now);
18
-
19
- const event = {
20
- id,
21
- type,
22
- conversationId,
23
- sessionId,
24
- data,
25
- created_at: now
26
- };
27
-
28
- if (idempotencyKey) {
29
- this.setIdempotencyKey(idempotencyKey, event);
30
- }
31
-
32
- return event;
33
- };
34
-
35
- q.getEvent = function(id) {
36
- const stmt = prep('SELECT * FROM events WHERE id = ?');
37
- const row = stmt.get(id);
38
- if (row) {
39
- return {
40
- ...row,
41
- data: JSON.parse(row.data)
42
- };
43
- }
44
- return undefined;
45
- };
46
-
47
- q.getConversationEvents = function(conversationId) {
48
- const stmt = prep(
49
- 'SELECT * FROM events WHERE conversationId = ? ORDER BY created_at ASC'
50
- );
51
- const rows = stmt.all(conversationId);
52
- return rows.map(row => ({
53
- ...row,
54
- data: JSON.parse(row.data)
55
- }));
56
- };
57
-
58
- q.getSessionEvents = function(sessionId) {
59
- const stmt = prep(
60
- 'SELECT * FROM events WHERE sessionId = ? ORDER BY created_at ASC'
61
- );
62
- const rows = stmt.all(sessionId);
63
- return rows.map(row => ({
64
- ...row,
65
- data: JSON.parse(row.data)
66
- }));
67
- };
68
- }
@@ -1,133 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import os from 'os';
4
-
5
- export function addImportQueries(q, db, prep, generateId) {
6
- q.discoverClaudeCodeConversations = function() {
7
- const projectsDir = path.join(os.homedir(), '.claude', 'projects');
8
- if (!fs.existsSync(projectsDir)) return [];
9
-
10
- const discovered = [];
11
- try {
12
- const dirs = fs.readdirSync(projectsDir, { withFileTypes: true });
13
- for (const dir of dirs) {
14
- if (!dir.isDirectory()) continue;
15
- const dirPath = path.join(projectsDir, dir.name);
16
- const indexPath = path.join(dirPath, 'sessions-index.json');
17
- if (!fs.existsSync(indexPath)) continue;
18
-
19
- try {
20
- const index = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
21
- const projectPath = index.originalPath || dir.name.replace(/^-/, '/').replace(/-/g, '/');
22
- for (const entry of (index.entries || [])) {
23
- if (!entry.sessionId || entry.messageCount === 0) continue;
24
- discovered.push({
25
- id: entry.sessionId,
26
- jsonlPath: entry.fullPath || path.join(dirPath, `${entry.sessionId}.jsonl`),
27
- title: entry.summary || entry.firstPrompt || 'Claude Code Session',
28
- projectPath,
29
- created: entry.created ? new Date(entry.created).getTime() : entry.fileMtime,
30
- modified: entry.modified ? new Date(entry.modified).getTime() : entry.fileMtime,
31
- messageCount: entry.messageCount,
32
- gitBranch: entry.gitBranch,
33
- source: 'claude-code'
34
- });
35
- }
36
- } catch (e) {
37
- console.error(`Error reading index ${indexPath}:`, e.message);
38
- }
39
- }
40
- } catch (e) {
41
- console.error('Error discovering Claude Code conversations:', e.message);
42
- }
43
-
44
- return discovered;
45
- };
46
-
47
- q.parseJsonlMessages = function(jsonlPath) {
48
- if (!fs.existsSync(jsonlPath)) return [];
49
- const messages = [];
50
- try {
51
- const lines = fs.readFileSync(jsonlPath, 'utf-8').split('\n');
52
- for (const line of lines) {
53
- if (!line.trim()) continue;
54
- try {
55
- const obj = JSON.parse(line);
56
- if (obj.type === 'user' && obj.message?.content) {
57
- const content = typeof obj.message.content === 'string'
58
- ? obj.message.content
59
- : Array.isArray(obj.message.content)
60
- ? obj.message.content.filter(c => c.type === 'text').map(c => c.text).join('\n')
61
- : JSON.stringify(obj.message.content);
62
- if (content && !content.startsWith('[{"tool_use_id"')) {
63
- messages.push({ id: obj.uuid || generateId('msg'), role: 'user', content, created_at: new Date(obj.timestamp).getTime() });
64
- }
65
- } else if (obj.type === 'assistant' && obj.message?.content) {
66
- let text = '';
67
- const content = obj.message.content;
68
- if (Array.isArray(content)) {
69
- const textBlocks = [];
70
- for (const c of content) {
71
- if (c.type === 'text' && c.text) {
72
- textBlocks.push(c.text);
73
- }
74
- }
75
- text = textBlocks.join('\n\n');
76
- } else if (typeof content === 'string') {
77
- text = content;
78
- }
79
- if (text) {
80
- messages.push({ id: obj.uuid || generateId('msg'), role: 'assistant', content: text, created_at: new Date(obj.timestamp).getTime() });
81
- }
82
- }
83
- } catch (_) {}
84
- }
85
- } catch (e) {
86
- console.error(`Error parsing JSONL ${jsonlPath}:`, e.message);
87
- }
88
- return messages;
89
- };
90
-
91
- q.importClaudeCodeConversations = function() {
92
- const discovered = this.discoverClaudeCodeConversations();
93
- const imported = [];
94
-
95
- for (const conv of discovered) {
96
- try {
97
- const existingConv = prep('SELECT id, status FROM conversations WHERE id = ? OR externalId = ?').get(conv.id, conv.id);
98
- if (existingConv) {
99
- imported.push({ id: conv.id, status: 'skipped', reason: existingConv.status === 'deleted' ? 'deleted' : 'exists' });
100
- continue;
101
- }
102
-
103
- const projectName = conv.projectPath ? path.basename(conv.projectPath) : '';
104
- const title = conv.title || 'Claude Code Session';
105
- const displayTitle = projectName ? `[${projectName}] ${title}` : title;
106
-
107
- const messages = this.parseJsonlMessages(conv.jsonlPath);
108
-
109
- const importStmt = db.transaction(() => {
110
- prep(
111
- `INSERT INTO conversations (id, agentId, title, created_at, updated_at, status, claudeSessionId) VALUES (?, ?, ?, ?, ?, ?, ?)`
112
- ).run(conv.id, 'claude-code', displayTitle, conv.created, conv.modified, 'active', conv.id);
113
-
114
- for (const msg of messages) {
115
- try {
116
- prep(
117
- `INSERT INTO messages (id, conversationId, role, content, created_at) VALUES (?, ?, ?, ?, ?)`
118
- ).run(msg.id, conv.id, msg.role, msg.content, msg.created_at);
119
- } catch (_) {}
120
- }
121
- });
122
-
123
- importStmt();
124
- imported.push({ id: conv.id, status: 'imported', title: displayTitle, messages: messages.length });
125
- } catch (e) {
126
- imported.push({ id: conv.id, status: 'error', error: e.message });
127
- }
128
- }
129
-
130
- return imported;
131
- };
132
-
133
- }
@@ -1,102 +0,0 @@
1
- export function addMessageQueries(q, db, prep, generateId) {
2
- q.createMessage = function(conversationId, role, content, idempotencyKey = null) {
3
- if (idempotencyKey) {
4
- const cached = this.getIdempotencyKey(idempotencyKey);
5
- if (cached) return JSON.parse(cached);
6
- }
7
-
8
- const id = generateId('msg');
9
- const now = Date.now();
10
- const storedContent = typeof content === 'string' ? content : JSON.stringify(content);
11
-
12
- const stmt = prep(
13
- `INSERT INTO messages (id, conversationId, role, content, created_at) VALUES (?, ?, ?, ?, ?)`
14
- );
15
- stmt.run(id, conversationId, role, storedContent, now);
16
-
17
- try { prep('INSERT INTO messages_fts(rowid, content, conversationId, role) VALUES ((SELECT rowid FROM messages WHERE id = ?), ?, ?, ?)').run(id, storedContent, conversationId, role); } catch (_) {}
18
-
19
- const updateConvStmt = prep('UPDATE conversations SET updated_at = ? WHERE id = ?');
20
- updateConvStmt.run(now, conversationId);
21
-
22
- const message = {
23
- id,
24
- conversationId,
25
- role,
26
- content,
27
- created_at: now
28
- };
29
-
30
- if (idempotencyKey) {
31
- this.setIdempotencyKey(idempotencyKey, message);
32
- }
33
-
34
- return message;
35
- };
36
-
37
- q.getMessage = function(id) {
38
- const stmt = prep('SELECT * FROM messages WHERE id = ?');
39
- const msg = stmt.get(id);
40
- if (msg && typeof msg.content === 'string') {
41
- try {
42
- msg.content = JSON.parse(msg.content);
43
- } catch (_) {
44
- }
45
- }
46
- return msg;
47
- };
48
-
49
- q.getConversationMessages = function(conversationId) {
50
- const stmt = prep(
51
- 'SELECT * FROM messages WHERE conversationId = ? ORDER BY created_at ASC'
52
- );
53
- const messages = stmt.all(conversationId);
54
- return messages.map(msg => {
55
- if (typeof msg.content === 'string') {
56
- try {
57
- msg.content = JSON.parse(msg.content);
58
- } catch (_) {
59
- }
60
- }
61
- return msg;
62
- });
63
- };
64
-
65
- q.getLastUserMessage = function(conversationId) {
66
- const stmt = prep(
67
- "SELECT * FROM messages WHERE conversationId = ? AND role = 'user' ORDER BY created_at DESC LIMIT 1"
68
- );
69
- const msg = stmt.get(conversationId);
70
- if (msg && typeof msg.content === 'string') {
71
- try { msg.content = JSON.parse(msg.content); } catch (_) {}
72
- }
73
- return msg || null;
74
- };
75
-
76
- q.getPaginatedMessages = function(conversationId, limit = 50, offset = 0) {
77
- const countStmt = prep('SELECT COUNT(*) as count FROM messages WHERE conversationId = ?');
78
- const total = countStmt.get(conversationId).count;
79
-
80
- const stmt = prep(
81
- 'SELECT * FROM messages WHERE conversationId = ? ORDER BY created_at ASC LIMIT ? OFFSET ?'
82
- );
83
- const messages = stmt.all(conversationId, limit, offset);
84
-
85
- return {
86
- messages: messages.map(msg => {
87
- if (typeof msg.content === 'string') {
88
- try {
89
- msg.content = JSON.parse(msg.content);
90
- } catch (_) {
91
- }
92
- }
93
- return msg;
94
- }),
95
- total,
96
- limit,
97
- offset,
98
- hasMore: offset + limit < total
99
- };
100
- };
101
-
102
- }
@@ -1,112 +0,0 @@
1
- export function addSessionQueries(q, db, prep, generateId) {
2
- q.createSession = function(conversationId) {
3
- const id = generateId('sess');
4
- const now = Date.now();
5
-
6
- const stmt = prep(
7
- `INSERT INTO sessions (id, conversationId, status, started_at, completed_at, response, error) VALUES (?, ?, ?, ?, ?, ?, ?)`
8
- );
9
- stmt.run(id, conversationId, 'pending', now, null, null, null);
10
-
11
- return {
12
- id,
13
- conversationId,
14
- status: 'pending',
15
- started_at: now,
16
- completed_at: null,
17
- response: null,
18
- error: null
19
- };
20
- };
21
-
22
- q.getSession = function(id) {
23
- const stmt = prep('SELECT * FROM sessions WHERE id = ?');
24
- return stmt.get(id);
25
- };
26
-
27
- q.getConversationSessions = function(conversationId) {
28
- const stmt = prep(
29
- 'SELECT * FROM sessions WHERE conversationId = ? ORDER BY started_at DESC'
30
- );
31
- return stmt.all(conversationId);
32
- };
33
-
34
- q.updateSession = function(id, data) {
35
- const session = this.getSession(id);
36
- if (!session) return null;
37
-
38
- const status = data.status !== undefined ? data.status : session.status;
39
- const rawResponse = data.response !== undefined ? data.response : session.response;
40
- const response = rawResponse && typeof rawResponse === 'object' ? JSON.stringify(rawResponse) : rawResponse;
41
- const error = data.error !== undefined ? data.error : session.error;
42
- const completed_at = data.completed_at !== undefined ? data.completed_at : session.completed_at;
43
-
44
- const stmt = prep(
45
- `UPDATE sessions SET status = ?, response = ?, error = ?, completed_at = ? WHERE id = ?`
46
- );
47
-
48
- try {
49
- stmt.run(status, response, error, completed_at, id);
50
- return {
51
- ...session,
52
- status,
53
- response,
54
- error,
55
- completed_at
56
- };
57
- } catch (e) {
58
- throw e;
59
- }
60
- };
61
-
62
- q.getLatestSession = function(conversationId) {
63
- const stmt = prep(
64
- 'SELECT * FROM sessions WHERE conversationId = ? ORDER BY started_at DESC LIMIT 1'
65
- );
66
- return stmt.get(conversationId) || null;
67
- };
68
-
69
- q.getSessionsByStatus = function(conversationId, status) {
70
- const stmt = prep(
71
- 'SELECT * FROM sessions WHERE conversationId = ? AND status = ? ORDER BY started_at DESC'
72
- );
73
- return stmt.all(conversationId, status);
74
- };
75
-
76
- q.getActiveSessions = function() {
77
- const stmt = prep(
78
- "SELECT * FROM sessions WHERE status IN ('active', 'pending') ORDER BY started_at DESC"
79
- );
80
- return stmt.all();
81
- };
82
-
83
- q.getActiveSessionConversationIds = function() {
84
- const stmt = prep(
85
- "SELECT DISTINCT conversationId FROM sessions WHERE status IN ('active', 'pending')"
86
- );
87
- return stmt.all().map(r => r.conversationId);
88
- };
89
-
90
- q.getSessionsByConversation = function(conversationId, limit = 10, offset = 0) {
91
- const stmt = prep(
92
- 'SELECT * FROM sessions WHERE conversationId = ? ORDER BY started_at DESC LIMIT ? OFFSET ?'
93
- );
94
- return stmt.all(conversationId, limit, offset);
95
- };
96
-
97
- q.getAllSessions = function(limit = 100) {
98
- const stmt = prep(
99
- 'SELECT * FROM sessions ORDER BY started_at DESC LIMIT ?'
100
- );
101
- return stmt.all(limit);
102
- };
103
-
104
- q.deleteSession = function(id) {
105
- const stmt = prep('DELETE FROM sessions WHERE id = ?');
106
- const result = stmt.run(id);
107
- prep('DELETE FROM chunks WHERE sessionId = ?').run(id);
108
- prep('DELETE FROM events WHERE sessionId = ?').run(id);
109
- return result.changes || 0;
110
- };
111
-
112
- }
@@ -1,100 +0,0 @@
1
- export function addStreamQueries(q, db, prep, generateId) {
2
- q.createStreamUpdate = function(sessionId, conversationId, updateType, content) {
3
- const id = generateId('upd');
4
- const now = Date.now();
5
-
6
- const transaction = db.transaction(() => {
7
- const maxSequence = prep(
8
- 'SELECT MAX(sequence) as max FROM stream_updates WHERE sessionId = ?'
9
- ).get(sessionId);
10
- const sequence = (maxSequence?.max || -1) + 1;
11
-
12
- prep(
13
- `INSERT INTO stream_updates (id, sessionId, conversationId, updateType, content, sequence, created_at)
14
- VALUES (?, ?, ?, ?, ?, ?, ?)`
15
- ).run(id, sessionId, conversationId, updateType, JSON.stringify(content), sequence, now);
16
-
17
- return sequence;
18
- });
19
-
20
- const sequence = transaction();
21
-
22
- return {
23
- id,
24
- sessionId,
25
- conversationId,
26
- updateType,
27
- content,
28
- sequence,
29
- created_at: now
30
- };
31
- };
32
-
33
- q.getSessionStreamUpdates = function(sessionId) {
34
- const stmt = prep(
35
- `SELECT id, sessionId, conversationId, updateType, content, sequence, created_at
36
- FROM stream_updates WHERE sessionId = ? ORDER BY sequence ASC`
37
- );
38
- const rows = stmt.all(sessionId);
39
- return rows.map(row => ({
40
- ...row,
41
- content: JSON.parse(row.content)
42
- }));
43
- };
44
-
45
- q.clearSessionStreamUpdates = function(sessionId) {
46
- const stmt = prep('DELETE FROM stream_updates WHERE sessionId = ?');
47
- stmt.run(sessionId);
48
- };
49
-
50
- q.createImportedConversation = function(data) {
51
- const id = generateId('conv');
52
- const now = Date.now();
53
- const stmt = prep(
54
- `INSERT INTO conversations (
55
- id, agentId, title, created_at, updated_at, status,
56
- agentType, source, externalId, firstPrompt, messageCount,
57
- projectPath, gitBranch, sourcePath, lastSyncedAt
58
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
59
- );
60
- stmt.run(
61
- id,
62
- data.externalId || id,
63
- data.title,
64
- data.created || now,
65
- data.modified || now,
66
- 'active',
67
- data.agentType || 'claude-code',
68
- data.source || 'imported',
69
- data.externalId,
70
- data.firstPrompt,
71
- data.messageCount || 0,
72
- data.projectPath,
73
- data.gitBranch,
74
- data.sourcePath,
75
- now
76
- );
77
- return { id, ...data };
78
- };
79
-
80
- q.getConversationByExternalId = function(agentType, externalId) {
81
- const stmt = prep(
82
- 'SELECT * FROM conversations WHERE agentType = ? AND externalId = ?'
83
- );
84
- return stmt.get(agentType, externalId);
85
- };
86
-
87
- q.getConversationsByAgentType = function(agentType) {
88
- const stmt = prep(
89
- 'SELECT * FROM conversations WHERE agentType = ? AND status != ? ORDER BY updated_at DESC'
90
- );
91
- return stmt.all(agentType, 'deleted');
92
- };
93
-
94
- q.getImportedConversations = function() {
95
- const stmt = prep(
96
- 'SELECT * FROM conversations WHERE source = ? AND status != ? ORDER BY updated_at DESC'
97
- );
98
- return stmt.all('imported', 'deleted');
99
- };
100
- }