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,100 +0,0 @@
1
- export function register(deps) {
2
- const { sendJSON, parseBody, queries } = deps;
3
- const routes = {};
4
-
5
- routes['POST /api/threads'] = async (req, res) => {
6
- try {
7
- const body = await parseBody(req);
8
- sendJSON(req, res, 201, queries.createThread(body.metadata || {}));
9
- } catch (err) {
10
- sendJSON(req, res, 422, { error: err.message, type: 'validation_error' });
11
- }
12
- };
13
-
14
- routes['POST /api/threads/search'] = async (req, res) => {
15
- try {
16
- sendJSON(req, res, 200, queries.searchThreads(await parseBody(req)));
17
- } catch (err) {
18
- sendJSON(req, res, 422, { error: err.message, type: 'validation_error' });
19
- }
20
- };
21
-
22
- routes['_match'] = (method, pathOnly) => {
23
- const key = `${method} ${pathOnly}`;
24
- if (routes[key]) return routes[key];
25
- let m;
26
- if ((m = pathOnly.match(/^\/api\/threads\/([a-f0-9-]{36})$/))) {
27
- if (method === 'GET') return (req, res) => handleGetThread(req, res, m[1]);
28
- if (method === 'PATCH') return (req, res) => handlePatchThread(req, res, m[1]);
29
- if (method === 'DELETE') return (req, res) => handleDeleteThread(req, res, m[1]);
30
- }
31
- if (method === 'GET' && (m = pathOnly.match(/^\/api\/threads\/([a-f0-9-]{36})\/history$/)))
32
- return (req, res) => handleThreadHistory(req, res, m[1]);
33
- if (method === 'POST' && (m = pathOnly.match(/^\/api\/threads\/([a-f0-9-]{36})\/copy$/)))
34
- return (req, res) => handleThreadCopy(req, res, m[1]);
35
- if (method === 'POST' && pathOnly.match(/^\/api\/threads\/([a-f0-9-]{36})\/runs\/stream$/))
36
- return (req, res) => { res.writeHead(410); res.end(JSON.stringify({ error: 'SSE removed, use WebSocket' })); };
37
- if (method === 'GET' && pathOnly.match(/^\/api\/threads\/([a-f0-9-]{36})\/runs\/([a-f0-9-]{36})\/stream$/))
38
- return (req, res) => { res.writeHead(410); res.end(JSON.stringify({ error: 'SSE removed, use WebSocket' })); };
39
- return null;
40
- };
41
-
42
- async function handleGetThread(req, res, threadId) {
43
- try {
44
- const thread = queries.getThread(threadId);
45
- if (!thread) sendJSON(req, res, 404, { error: 'Thread not found', type: 'not_found' });
46
- else sendJSON(req, res, 200, thread);
47
- } catch (err) {
48
- sendJSON(req, res, 500, { error: err.message, type: 'internal_error' });
49
- }
50
- }
51
-
52
- async function handlePatchThread(req, res, threadId) {
53
- try {
54
- sendJSON(req, res, 200, queries.patchThread(threadId, await parseBody(req)));
55
- } catch (err) {
56
- const code = err.message.includes('not found') ? 404 : 422;
57
- sendJSON(req, res, code, { error: err.message, type: code === 404 ? 'not_found' : 'validation_error' });
58
- }
59
- }
60
-
61
- async function handleDeleteThread(req, res, threadId) {
62
- try {
63
- queries.deleteThread(threadId);
64
- res.writeHead(204); res.end();
65
- } catch (err) {
66
- if (err.message.includes('not found')) sendJSON(req, res, 404, { error: err.message, type: 'not_found' });
67
- else if (err.message.includes('pending runs')) sendJSON(req, res, 409, { error: err.message, type: 'conflict' });
68
- else sendJSON(req, res, 500, { error: err.message, type: 'internal_error' });
69
- }
70
- }
71
-
72
- async function handleThreadHistory(req, res, threadId) {
73
- try {
74
- const url = new URL(req.url, `http://${req.headers.host}`);
75
- const limit = parseInt(url.searchParams.get('limit') || '50', 10);
76
- const before = url.searchParams.get('before') || null;
77
- let offset = 0;
78
- if (before) { const parsed = parseInt(before, 10); if (!isNaN(parsed)) offset = parsed; }
79
- const result = queries.getThreadHistory(threadId, limit, offset);
80
- sendJSON(req, res, 200, { states: result.states, next_cursor: result.hasMore ? String(offset + limit) : null });
81
- } catch (err) {
82
- const code = err.message.includes('not found') ? 404 : 422;
83
- sendJSON(req, res, code, { error: err.message, type: code === 404 ? 'not_found' : 'validation_error' });
84
- }
85
- }
86
-
87
- async function handleThreadCopy(req, res, sourceThreadId) {
88
- try {
89
- const body = await parseBody(req);
90
- const newThread = queries.copyThread(sourceThreadId);
91
- if (body.metadata) sendJSON(req, res, 201, queries.patchThread(newThread.thread_id, { metadata: body.metadata }));
92
- else sendJSON(req, res, 201, newThread);
93
- } catch (err) {
94
- const code = err.message.includes('not found') ? 404 : 500;
95
- sendJSON(req, res, code, { error: err.message, type: code === 404 ? 'not_found' : 'internal_error' });
96
- }
97
- }
98
-
99
- return routes;
100
- }
@@ -1,110 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import os from 'os';
4
- import { execSync } from 'child_process';
5
-
6
- export function register(deps) {
7
- const { sendJSON, parseBody, queries, STARTUP_CWD, PKG_VERSION } = deps;
8
- const routes = {};
9
-
10
- routes['GET /api/import/claude-code'] = async (req, res) => {
11
- const result = queries.importClaudeCodeConversations();
12
- sendJSON(req, res, 200, { imported: result });
13
- };
14
-
15
- routes['GET /api/discover/claude-code'] = async (req, res) => {
16
- const discovered = queries.discoverClaudeCodeConversations();
17
- sendJSON(req, res, 200, { discovered });
18
- };
19
-
20
- routes['GET /api/home'] = async (req, res) => {
21
- sendJSON(req, res, 200, { home: os.homedir(), cwd: STARTUP_CWD });
22
- };
23
-
24
- routes['GET /api/version'] = async (req, res) => {
25
- sendJSON(req, res, 200, { version: PKG_VERSION });
26
- };
27
-
28
- routes['POST /api/clone'] = async (req, res) => {
29
- const body = await parseBody(req);
30
- const repo = (body.repo || '').trim();
31
- if (!repo || !/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo)) {
32
- sendJSON(req, res, 400, { error: 'Invalid repo format. Use org/repo or user/repo' });
33
- return;
34
- }
35
- const cloneDir = STARTUP_CWD || os.homedir();
36
- const repoName = repo.split('/')[1];
37
- const targetPath = path.join(cloneDir, repoName);
38
- if (fs.existsSync(targetPath)) {
39
- sendJSON(req, res, 409, { error: `Directory already exists: ${repoName}`, path: targetPath });
40
- return;
41
- }
42
- try {
43
- const isWindows = os.platform() === 'win32';
44
- execSync('git clone https://github.com/' + repo + '.git', {
45
- cwd: cloneDir, encoding: 'utf-8', timeout: 120000,
46
- stdio: ['pipe', 'pipe', 'pipe'],
47
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
48
- shell: isWindows
49
- });
50
- sendJSON(req, res, 200, { ok: true, repo, path: targetPath, name: repoName });
51
- } catch (err) {
52
- sendJSON(req, res, 500, { error: (err.stderr || err.message || 'Clone failed').trim() });
53
- }
54
- };
55
-
56
- routes['POST /api/folders'] = async (req, res) => {
57
- const body = await parseBody(req);
58
- const folderPath = body.path || STARTUP_CWD;
59
- try {
60
- const expandedPath = path.resolve(folderPath.startsWith('~') ? folderPath.replace('~', os.homedir()) : folderPath);
61
- if (!expandedPath.startsWith(os.homedir()) && !expandedPath.startsWith(STARTUP_CWD) && expandedPath !== '/') {
62
- sendJSON(req, res, 403, { error: 'Path outside allowed directories' });
63
- return;
64
- }
65
- const entries = fs.readdirSync(expandedPath, { withFileTypes: true });
66
- const folders = entries
67
- .filter(e => e.isDirectory() && !e.name.startsWith('.'))
68
- .map(e => ({ name: e.name }))
69
- .sort((a, b) => a.name.localeCompare(b.name));
70
- sendJSON(req, res, 200, { folders });
71
- } catch (err) {
72
- sendJSON(req, res, 400, { error: err.message });
73
- }
74
- };
75
-
76
- routes['GET /api/git/check-remote-ownership'] = async (req, res) => {
77
- try {
78
- const isWindows = os.platform() === 'win32';
79
- const result = execSync('git remote get-url origin' + (isWindows ? '' : ' 2>/dev/null'), { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
80
- const remoteUrl = result.trim();
81
- const statusResult = execSync('git status --porcelain' + (isWindows ? '' : ' 2>/dev/null'), { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
82
- const hasChanges = statusResult.trim().length > 0;
83
- const unpushedResult = execSync('git rev-list --count --not --remotes' + (isWindows ? '' : ' 2>/dev/null'), { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
84
- const hasUnpushed = parseInt(unpushedResult.trim() || '0', 10) > 0;
85
- const ownsRemote = !remoteUrl.includes('github.com/') || remoteUrl.includes(process.env.GITHUB_USER || '');
86
- sendJSON(req, res, 200, { ownsRemote, hasChanges, hasUnpushed, remoteUrl });
87
- } catch {
88
- sendJSON(req, res, 200, { ownsRemote: false, hasChanges: false, hasUnpushed: false, remoteUrl: '' });
89
- }
90
- };
91
-
92
- routes['POST /api/git/push'] = async (req, res) => {
93
- try {
94
- const isWindows = os.platform() === 'win32';
95
- const gitCommand = isWindows
96
- ? 'git add -A & git commit -m "Auto-commit" & git push'
97
- : 'git add -A && git commit -m "Auto-commit" && git push';
98
- execSync(gitCommand, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
99
- sendJSON(req, res, 200, { success: true });
100
- } catch (err) {
101
- sendJSON(req, res, 500, { error: err.message });
102
- }
103
- };
104
-
105
- routes['_match'] = (method, pathOnly) => {
106
- return routes[`${method} ${pathOnly}`] || null;
107
- };
108
-
109
- return routes;
110
- }
@@ -1,138 +0,0 @@
1
- import path from 'path';
2
- import os from 'os';
3
- import { z } from 'zod';
4
- import * as execMachine from './execution-machine.js';
5
-
6
- function fail(code, message) { const e = new Error(message); e.code = code; throw e; }
7
- function notFound(msg = 'Not found') { fail(404, msg); }
8
- function expandTilde(p) { return p && p.startsWith('~') ? path.join(os.homedir(), p.slice(1)) : p; }
9
- function validate(schema, params) {
10
- const result = schema.safeParse(params);
11
- if (!result.success) fail(400, result.error.issues.map(i => i.message).join('; '));
12
- return result.data;
13
- }
14
-
15
- const ConvNewSchema = z.object({ agentId: z.string().optional(), title: z.string().optional(), workingDirectory: z.string().optional(), model: z.string().optional(), subAgent: z.string().optional() }).passthrough();
16
- const ConvUpdSchema = z.object({ id: z.string().min(1, 'id required') }).passthrough();
17
-
18
- export function register(router, deps) {
19
- const { queries, activeExecutions, rateLimitState,
20
- broadcastSync, processMessageWithStreaming, cleanupExecution,
21
- getJsonlWatcher = () => null } = deps;
22
-
23
- router.handle('conv.ls', (p) => {
24
- let conversations = queries.getConversationsList();
25
- for (const c of conversations) { if (c.isStreaming && !execMachine.isActive(c.id)) c.isStreaming = 0; }
26
- if (p && p.tag) conversations = conversations.filter(c => c.tags && c.tags.split(',').includes(p.tag));
27
- return { conversations };
28
- });
29
-
30
- router.handle('conv.tags', () => {
31
- const convs = queries.getConversationsList();
32
- const tagSet = new Set();
33
- for (const c of convs) { if (c.tags) c.tags.split(',').forEach(t => { if (t.trim()) tagSet.add(t.trim()); }); }
34
- return { tags: [...tagSet].sort() };
35
- });
36
-
37
- router.handle('conv.new', (p) => {
38
- p = validate(ConvNewSchema, p);
39
- const wd = p.workingDirectory ? path.resolve(expandTilde(p.workingDirectory)) : null;
40
- const conv = queries.createConversation(p.agentId, p.title, wd, p.model || null, p.subAgent || null);
41
- queries.createEvent('conversation.created', { agentId: p.agentId, workingDirectory: conv.workingDirectory, model: conv.model, subAgent: conv.subAgent }, conv.id);
42
- broadcastSync({ type: 'conversation_created', conversation: conv });
43
- return { conversation: conv };
44
- });
45
-
46
- router.handle('conv.get', (p) => {
47
- const conv = queries.getConversation(p.id);
48
- if (!conv) notFound();
49
- const machineSnap = execMachine.snapshot(p.id);
50
- return { conversation: conv, isActivelyStreaming: execMachine.isActive(p.id), latestSession: queries.getLatestSession(p.id), executionState: machineSnap?.value || 'idle' };
51
- });
52
-
53
- router.handle('conv.upd', (p) => {
54
- p = validate(ConvUpdSchema, p);
55
- const { id, ...data } = p;
56
- if (data.workingDirectory) data.workingDirectory = path.resolve(data.workingDirectory);
57
- const conv = queries.updateConversation(id, data);
58
- if (!conv) notFound('Conversation not found');
59
- queries.createEvent('conversation.updated', data, id);
60
- broadcastSync({ type: 'conversation_updated', conversation: conv });
61
- return { conversation: conv };
62
- });
63
-
64
- router.handle('conv.del', (p) => {
65
- cleanupExecution(p.id);
66
- execMachine.remove(p.id);
67
- if (!queries.deleteConversation(p.id)) notFound();
68
- getJsonlWatcher()?.removeConversation(p.id);
69
- broadcastSync({ type: 'conversation_deleted', conversationId: p.id });
70
- return { deleted: true };
71
- });
72
-
73
- router.handle('conv.del.all', (p) => {
74
- const convs = queries.getConversationsList();
75
- for (const c of convs) { cleanupExecution(c.id); execMachine.remove(c.id); }
76
- if (!queries.deleteAllConversations()) fail(500, 'Failed to delete all conversations');
77
- getJsonlWatcher()?.removeAllConversations();
78
- broadcastSync({ type: 'all_conversations_deleted', timestamp: Date.now() });
79
- return { deleted: true, message: 'All conversations deleted' };
80
- });
81
-
82
- router.handle('conv.full', (p) => {
83
- const conv = queries.getConversation(p.id);
84
- if (!conv) notFound();
85
- const chunkLimit = Math.min(p.chunkLimit || 500, 5000);
86
- const messageLimit = Math.min(p.messageLimit || 20, 100);
87
- const totalChunks = queries.getConversationChunkCount(p.id);
88
- const chunks = (p.allChunks || totalChunks <= chunkLimit)
89
- ? queries.getConversationChunks(p.id) : queries.getRecentConversationChunks(p.id, chunkLimit);
90
- const messagesResult = queries.getRecentMessages(p.id, messageLimit);
91
- const machineSnap = execMachine.snapshot(p.id);
92
- return {
93
- conversation: conv,
94
- isActivelyStreaming: execMachine.isActive(p.id),
95
- executionState: machineSnap?.value || 'idle',
96
- latestSession: queries.getLatestSession(p.id),
97
- chunks,
98
- totalChunks,
99
- hasMoreChunks: totalChunks > chunkLimit,
100
- messages: messagesResult.messages,
101
- totalMessages: messagesResult.total,
102
- hasMoreMessages: messagesResult.hasMore,
103
- rateLimitInfo: rateLimitState.get(p.id) || null
104
- };
105
- });
106
-
107
- router.handle('conv.chunks', (p) => {
108
- if (!queries.getConversation(p.id)) notFound('Conversation not found');
109
- const since = parseInt(p.since || '0');
110
- const all = p.all === true || p.all === 'true';
111
- const totalChunks = queries.getConversationChunkCount(p.id);
112
- let chunks;
113
- if (since > 0) {
114
- chunks = queries.getConversationChunksSince(p.id, since);
115
- } else if (all) {
116
- chunks = queries.getConversationChunks(p.id);
117
- } else {
118
- chunks = queries.getRecentConversationChunks(p.id, 500);
119
- }
120
- return { ok: true, chunks, totalChunks };
121
- });
122
-
123
- router.handle('conv.chunks.earlier', (p) => {
124
- if (!queries.getConversation(p.id)) notFound('Conversation not found');
125
- const beforeTimestamp = parseInt(p.before || Date.now());
126
- const limit = Math.min(p.limit || 500, 5000);
127
- const result = queries.getChunksBefore(p.id, beforeTimestamp, limit);
128
- return { ok: true, chunks: result.chunks, total: result.total, hasMore: result.hasMore, limit: result.limit };
129
- });
130
-
131
- router.handle('conv.reorder', (p) => {
132
- if (!Array.isArray(p.order)) throw Object.assign(new Error('order array required'), { code: 400 });
133
- for (let i = 0; i < p.order.length; i++) {
134
- queries.updateConversationSortOrder(p.order[i], i);
135
- }
136
- return { ok: true };
137
- });
138
- }
@@ -1,169 +0,0 @@
1
- import { z } from 'zod';
2
- import * as execMachine from './execution-machine.js';
3
-
4
- function fail(code, message) { const e = new Error(message); e.code = code; throw e; }
5
- function notFound(msg = 'Not found') { fail(404, msg); }
6
- function validate(schema, params) {
7
- const result = schema.safeParse(params);
8
- if (!result.success) fail(400, result.error.issues.map(i => i.message).join('; '));
9
- return result.data;
10
- }
11
-
12
- const ConvSteerSchema = z.object({ id: z.string().min(1, 'conversation id required'), content: z.union([z.string(), z.record(z.any())]).refine(v => v !== undefined && v !== null && v !== '', { message: 'content required' }) }).passthrough();
13
-
14
- export function register(router, deps) {
15
- const { queries, activeExecutions, rateLimitState,
16
- broadcastSync, processMessageWithStreaming, cleanupExecution,
17
- getJsonlWatcher = () => null, logError = () => {} } = deps;
18
-
19
- function startExecution(convId, message, agentId, model, content, subAgent) {
20
- const session = queries.createSession(convId);
21
- queries.createEvent('session.created', { messageId: message.id, sessionId: session.id }, convId, session.id);
22
- execMachine.send(convId, { type: 'START', sessionId: session.id });
23
- activeExecutions.set(convId, { pid: null, startTime: Date.now(), sessionId: session.id, lastActivity: Date.now() });
24
- queries.setIsStreaming(convId, true);
25
- broadcastSync({ type: 'streaming_start', sessionId: session.id, conversationId: convId, messageId: message.id, agentId, timestamp: Date.now() });
26
- processMessageWithStreaming(convId, message.id, session.id, content, agentId, model, subAgent).catch(e => logError('startExecution', e, { convId }));
27
- return session;
28
- }
29
-
30
- router.handle('conv.export', (p) => {
31
- const conv = queries.getConversation(p.id);
32
- if (!conv) notFound();
33
- const msgs = queries.getConversationMessages(p.id);
34
- const format = p.format || 'markdown';
35
- if (format === 'json') return { conversation: conv, messages: msgs };
36
- let md = `# ${conv.title || 'Conversation'}\n\n`;
37
- md += `Agent: ${conv.agentType || 'unknown'} | Created: ${new Date(conv.created_at).toISOString()}\n\n---\n\n`;
38
- for (const m of msgs) {
39
- const role = m.role === 'user' ? 'User' : 'Assistant';
40
- md += `## ${role}\n\n`;
41
- let content = m.content;
42
- try { const parsed = JSON.parse(content); if (Array.isArray(parsed)) { content = parsed.map(b => b.text || b.content || JSON.stringify(b)).join('\n'); } } catch {}
43
- md += content + '\n\n---\n\n';
44
- }
45
- return { markdown: md, title: conv.title };
46
- });
47
-
48
- router.handle('conv.import', (p) => {
49
- if (!p.conversation || !p.messages) throw Object.assign(new Error('Missing conversation or messages'), { code: 400 });
50
- const src = p.conversation;
51
- const conv = queries.createConversation(
52
- src.agentId || src.agentType || 'claude-code',
53
- src.title || 'Imported Conversation',
54
- src.workingDirectory || null,
55
- src.model || null
56
- );
57
- for (const msg of p.messages) {
58
- queries.createMessage(conv.id, msg.role || 'user', msg.content || '');
59
- }
60
- broadcastSync({ type: 'conversation_created', conversation: queries.getConversation(conv.id) });
61
- return { conversation: queries.getConversation(conv.id), importedMessages: p.messages.length };
62
- });
63
-
64
- router.handle('conv.sync', (p) => {
65
- const conv = queries.getConversation(p.id);
66
- if (!conv) notFound();
67
- const machineSnap = execMachine.snapshot(p.id);
68
- const executionState = machineSnap?.value || 'idle';
69
- const latestSession = queries.getLatestSession(p.id);
70
- const sinceSeq = parseInt(p.sinceSeq || '-1');
71
- const since = parseInt(p.since || '0');
72
- let missedChunks = [];
73
- if (latestSession && sinceSeq >= 0) {
74
- missedChunks = queries.getChunksSinceSeq(latestSession.id, sinceSeq);
75
- } else if (latestSession && since > 0) {
76
- missedChunks = queries.getConversationChunksSince(p.id, since);
77
- }
78
- return {
79
- conversation: conv,
80
- executionState,
81
- isActivelyStreaming: execMachine.isActive(p.id),
82
- latestSession,
83
- missedChunks,
84
- missedCount: missedChunks.length,
85
- queueLength: machineSnap?.context?.queue?.length || 0
86
- };
87
- });
88
-
89
- router.handle('conv.search', (p) => {
90
- if (!p.query || typeof p.query !== 'string' || p.query.trim().length < 2) return { results: [] };
91
- const limit = Math.min(parseInt(p.limit || '50'), 200);
92
- return { results: queries.searchMessages(p.query.trim(), limit) };
93
- });
94
-
95
- router.handle('conv.prune', (p) => {
96
- const conv = queries.getConversation(p.id);
97
- if (!conv) notFound();
98
- const keep = Math.max(parseInt(p.keep || '500'), 100);
99
- const sessions = queries.getConversationSessions(p.id);
100
- if (!sessions || sessions.length === 0) return { pruned: 0 };
101
- const latestSessionId = sessions[0]?.id;
102
- let pruned = 0;
103
- for (const sess of sessions) {
104
- if (sess.id === latestSessionId) continue;
105
- const count = queries.getSessionChunks(sess.id)?.length || 0;
106
- if (count > 0) { queries.deleteSessionChunks(sess.id); pruned += count; }
107
- }
108
- return { pruned, kept: latestSessionId, sessionsProcessed: sessions.length };
109
- });
110
-
111
- router.handle('conv.cancel', (p) => {
112
- if (!execMachine.isActive(p.id)) notFound('No active execution to cancel');
113
- const ctx = execMachine.getContext(p.id);
114
- const pid = ctx?.pid || activeExecutions.get(p.id)?.pid;
115
- const sessionId = ctx?.sessionId || activeExecutions.get(p.id)?.sessionId;
116
- if (pid) { try { process.kill(-pid, 'SIGKILL'); } catch { try { process.kill(pid, 'SIGKILL'); } catch {} } }
117
- if (sessionId) queries.updateSession(sessionId, { status: 'interrupted', completed_at: Date.now() });
118
- cleanupExecution(p.id, false);
119
- broadcastSync({ type: 'streaming_complete', sessionId, conversationId: p.id, interrupted: true, timestamp: Date.now() });
120
- return { ok: true, cancelled: true, conversationId: p.id, sessionId };
121
- });
122
-
123
- router.handle('conv.inject', (p) => {
124
- const conv = queries.getConversation(p.id);
125
- if (!conv) notFound('Conversation not found');
126
- if (!p.content) fail(400, 'Missing content');
127
- const message = queries.createMessage(p.id, 'user', '[INJECTED] ' + p.content);
128
- if (!execMachine.isActive(p.id)) {
129
- const agentId = conv.agentId || 'claude-code';
130
- const session = queries.createSession(p.id, agentId, 'pending');
131
- processMessageWithStreaming(p.id, message.id, session.id, message.content, agentId, conv.model || null, conv.subAgent || null);
132
- }
133
- return { ok: true, injected: true, conversationId: p.id, messageId: message.id };
134
- });
135
-
136
- router.handle('conv.steer', (p) => {
137
- p = validate(ConvSteerSchema, p);
138
- const conv = queries.getConversation(p.id);
139
- if (!conv) notFound('Conversation not found');
140
-
141
- if (!execMachine.isActive(p.id)) fail(409, 'No active execution to steer');
142
-
143
- const ctx = execMachine.getContext(p.id);
144
- const pid = ctx?.pid || activeExecutions.get(p.id)?.pid;
145
- const sessionId = ctx?.sessionId || activeExecutions.get(p.id)?.sessionId;
146
-
147
- if (pid) {
148
- try { process.kill(-pid, 'SIGKILL'); } catch { try { process.kill(pid, 'SIGKILL'); } catch (e) {} }
149
- }
150
-
151
- if (sessionId) queries.updateSession(sessionId, { status: 'interrupted', completed_at: Date.now() });
152
- cleanupExecution(p.id);
153
-
154
- queries.setClaudeSessionId(p.id, null);
155
-
156
- broadcastSync({ type: 'streaming_complete', sessionId, conversationId: p.id, interrupted: true, timestamp: Date.now() });
157
-
158
- const agentId = conv.agentType || conv.agentId || 'claude-code';
159
- const model = conv.model || null;
160
- const subAgent = conv.subAgent || null;
161
- const steerContent = typeof p.content === 'string' ? p.content : (p.content ? JSON.stringify(p.content) : '');
162
- const message = queries.createMessage(p.id, 'user', steerContent);
163
- queries.createEvent('message.created', { role: 'user', messageId: message.id }, p.id);
164
- broadcastSync({ type: 'message_created', conversationId: p.id, message, timestamp: Date.now() });
165
- startExecution(p.id, message, agentId, model, steerContent, subAgent);
166
-
167
- return { ok: true, steered: true, conversationId: p.id, messageId: message.id };
168
- });
169
- }
@@ -1,121 +0,0 @@
1
- import { z } from 'zod';
2
- import * as execMachine from './execution-machine.js';
3
-
4
- function fail(code, message) { const e = new Error(message); e.code = code; throw e; }
5
- function notFound(msg = 'Not found') { fail(404, msg); }
6
- function validate(schema, params) {
7
- const result = schema.safeParse(params);
8
- if (!result.success) fail(400, result.error.issues.map(i => i.message).join('; '));
9
- return result.data;
10
- }
11
-
12
- const MsgStreamSchema = z.object({
13
- id: z.string().min(1, 'conversation id required'),
14
- content: z.union([z.string(), z.any()]).optional(),
15
- message: z.union([z.string(), z.any()]).optional(),
16
- agentId: z.string().optional(),
17
- model: z.string().optional(),
18
- subAgent: z.string().optional(),
19
- }).passthrough();
20
-
21
- export function register(router, deps) {
22
- const { queries, activeExecutions, messageQueues,
23
- broadcastSync, processMessageWithStreaming, logError = () => {} } = deps;
24
-
25
- const queueSeqByConv = new Map();
26
- function getNextQueueSeq(conversationId) {
27
- const current = queueSeqByConv.get(conversationId) || 0;
28
- const next = current + 1;
29
- queueSeqByConv.set(conversationId, next);
30
- return next;
31
- }
32
-
33
- function startExecution(convId, message, agentId, model, content, subAgent) {
34
- const session = queries.createSession(convId);
35
- queries.createEvent('session.created', { messageId: message.id, sessionId: session.id }, convId, session.id);
36
- execMachine.send(convId, { type: 'START', sessionId: session.id });
37
- activeExecutions.set(convId, { pid: null, startTime: Date.now(), sessionId: session.id, lastActivity: Date.now() });
38
- queries.setIsStreaming(convId, true);
39
- broadcastSync({ type: 'streaming_start', sessionId: session.id, conversationId: convId, messageId: message.id, agentId, timestamp: Date.now() });
40
- processMessageWithStreaming(convId, message.id, session.id, content, agentId, model, subAgent).catch(e => logError('startExecution', e, { convId }));
41
- return session;
42
- }
43
-
44
- function enqueue(convId, content, agentId, model, messageId, subAgent) {
45
- const item = { content, agentId, model, messageId, subAgent };
46
- execMachine.send(convId, { type: 'ENQUEUE', item });
47
- if (!messageQueues.has(convId)) messageQueues.set(convId, []);
48
- messageQueues.get(convId).push(item);
49
- const queueLength = execMachine.getQueue(convId).length;
50
- broadcastSync({ type: 'queue_status', conversationId: convId, queueLength, messageId, timestamp: Date.now() });
51
- return queueLength;
52
- }
53
-
54
- function normalizeContent(rawContent, method) {
55
- if (rawContent !== undefined && typeof rawContent !== 'string') {
56
- console.warn(`[ws-validation] ${method} content is ${typeof rawContent}: ${JSON.stringify(rawContent).slice(0, 200)}`);
57
- logError('ws-content-type', new TypeError(`non-string content in ${method}`), { method, type: typeof rawContent });
58
- }
59
- return typeof rawContent === 'string' ? rawContent : (rawContent ? JSON.stringify(rawContent) : '');
60
- }
61
-
62
- router.handle('msg.ls', (p) => {
63
- return queries.getPaginatedMessages(p.id, Math.min(p.limit || 50, 100), Math.max(p.offset || 0, 0));
64
- });
65
-
66
- router.handle('msg.ls.earlier', (p) => {
67
- if (!p.id) fail(400, 'Missing conversation id');
68
- if (!p.before) fail(400, 'Missing before messageId parameter');
69
- const limit = Math.min(p.limit || 50, 100);
70
- const result = queries.getMessagesBefore(p.id, p.before, limit);
71
- return { ok: true, messages: result.messages, total: result.total, hasMore: result.hasMore, limit: result.limit };
72
- });
73
-
74
- router.handle('msg.get', (p) => {
75
- const msg = queries.getMessage(p.messageId);
76
- if (!msg || msg.conversationId !== p.id) notFound();
77
- return { message: msg };
78
- });
79
-
80
- router.handle('msg.send', (p) => {
81
- const conv = queries.getConversation(p.id);
82
- if (!conv) notFound('Conversation not found');
83
- const agentId = p.agentId || conv.agentType || conv.agentId || 'claude-code';
84
- const model = p.model || conv.model || null;
85
- const subAgent = p.subAgent || conv.subAgent || null;
86
- const idempotencyKey = p.idempotencyKey || null;
87
- p.content = normalizeContent(p.content, 'msg.send');
88
- const message = queries.createMessage(p.id, 'user', p.content, idempotencyKey);
89
- queries.createEvent('message.created', { role: 'user', messageId: message.id }, p.id);
90
- if (!execMachine.isActive(p.id)) {
91
- broadcastSync({ type: 'message_created', conversationId: p.id, message, timestamp: Date.now() });
92
- const session = startExecution(p.id, message, agentId, model, p.content, subAgent);
93
- return { message, session, idempotencyKey };
94
- }
95
- broadcastSync({ type: 'message_created', conversationId: p.id, message, timestamp: Date.now() });
96
- const qp = enqueue(p.id, p.content, agentId, model, message.id, subAgent);
97
- return { message, queued: true, queuePosition: qp, idempotencyKey };
98
- });
99
-
100
- router.handle('msg.stream', (p) => {
101
- p = validate(MsgStreamSchema, p);
102
- const conv = queries.getConversation(p.id);
103
- if (!conv) notFound('Conversation not found');
104
- const prompt = normalizeContent(p.content || p.message, 'msg.stream');
105
- const agentId = p.agentId || conv.agentType || conv.agentId || 'claude-code';
106
- const model = p.model || conv.model || null;
107
- const subAgent = p.subAgent || conv.subAgent || null;
108
- const userMessage = queries.createMessage(p.id, 'user', prompt);
109
- queries.createEvent('message.created', { role: 'user', messageId: userMessage.id }, p.id);
110
- if (!execMachine.isActive(p.id)) {
111
- broadcastSync({ type: 'message_created', conversationId: p.id, message: userMessage, timestamp: Date.now() });
112
- const session = startExecution(p.id, userMessage, agentId, model, prompt, subAgent);
113
- return { message: userMessage, session, streamId: session.id };
114
- }
115
- broadcastSync({ type: 'message_created', conversationId: p.id, message: userMessage, timestamp: Date.now() });
116
- const qp = enqueue(p.id, prompt, agentId, model, userMessage.id, subAgent);
117
- const seq = getNextQueueSeq(p.id);
118
- broadcastSync({ type: 'queue_status', conversationId: p.id, queueLength: execMachine.getQueue(p.id).length, seq, timestamp: Date.now() });
119
- return { message: userMessage, queued: true, queuePosition: qp };
120
- });
121
- }