agentgui 1.0.930 → 1.0.932

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 (128) hide show
  1. package/AGENTS.md +35 -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/js/app.js +64 -68
  10. package/site/app/js/backend.js +1 -1
  11. package/static/lib/xstate.umd.min.js +1 -1
  12. package/lib/db-queries-chunks.js +0 -195
  13. package/lib/db-queries-chunks2.js +0 -82
  14. package/lib/db-queries-cleanup.js +0 -74
  15. package/lib/db-queries-del.js +0 -141
  16. package/lib/db-queries-events.js +0 -68
  17. package/lib/db-queries-import.js +0 -133
  18. package/lib/db-queries-messages.js +0 -102
  19. package/lib/db-queries-sessions.js +0 -112
  20. package/lib/db-queries-streams.js +0 -100
  21. package/lib/db-queries.js +0 -89
  22. package/lib/jsonl-parser.js +0 -190
  23. package/lib/jsonl-watcher.js +0 -64
  24. package/lib/routes-agent-actions.js +0 -61
  25. package/lib/routes-auth-config.js +0 -30
  26. package/lib/routes-conversations.js +0 -96
  27. package/lib/routes-debug.js +0 -119
  28. package/lib/routes-messages.js +0 -139
  29. package/lib/routes-runs.js +0 -156
  30. package/lib/routes-scripts.js +0 -135
  31. package/lib/routes-sessions.js +0 -144
  32. package/lib/routes-threads.js +0 -100
  33. package/lib/routes-util.js +0 -110
  34. package/lib/ws-handlers-conv.js +0 -138
  35. package/lib/ws-handlers-conv2.js +0 -169
  36. package/lib/ws-handlers-msg.js +0 -121
  37. package/lib/ws-handlers-queue.js +0 -56
  38. package/lib/ws-handlers-run.js +0 -182
  39. package/lib/ws-handlers-scripts.js +0 -66
  40. package/lib/ws-handlers-session.js +0 -105
  41. package/lib/ws-handlers-session2.js +0 -85
  42. package/lib/ws-legacy-handlers.js +0 -51
  43. package/static/app.js +0 -261
  44. package/static/css/app-shell.css +0 -419
  45. package/static/css/brand-bible.css +0 -591
  46. package/static/css/colors_and_type.css +0 -568
  47. package/static/css/gmail-skin.css +0 -663
  48. package/static/css/main.css +0 -4015
  49. package/static/css/tools-popup.css +0 -472
  50. package/static/index.html +0 -418
  51. package/static/js/agent-auth.js +0 -146
  52. package/static/js/app-shortcuts.js +0 -30
  53. package/static/js/audio-recorder-processor.js +0 -18
  54. package/static/js/client-agents.js +0 -155
  55. package/static/js/client-cache.js +0 -171
  56. package/static/js/client-conv.js +0 -198
  57. package/static/js/client-events.js +0 -164
  58. package/static/js/client-exec.js +0 -160
  59. package/static/js/client-helpers.js +0 -199
  60. package/static/js/client-load.js +0 -175
  61. package/static/js/client-render.js +0 -132
  62. package/static/js/client-scroll.js +0 -178
  63. package/static/js/client-status.js +0 -167
  64. package/static/js/client-streaming.js +0 -117
  65. package/static/js/client-streaming2.js +0 -116
  66. package/static/js/client-streaming3.js +0 -153
  67. package/static/js/client-streaming4.js +0 -194
  68. package/static/js/client-ui-controls.js +0 -170
  69. package/static/js/client-ui.js +0 -128
  70. package/static/js/client-ui2.js +0 -160
  71. package/static/js/client-url.js +0 -93
  72. package/static/js/client-utils.js +0 -174
  73. package/static/js/client-ws-msg.js +0 -88
  74. package/static/js/client-ws.js +0 -161
  75. package/static/js/client.js +0 -145
  76. package/static/js/codec.js +0 -4
  77. package/static/js/conv-list-machine.js +0 -145
  78. package/static/js/conv-list-renderer.js +0 -198
  79. package/static/js/conv-machine.js +0 -110
  80. package/static/js/conv-sidebar-actions.js +0 -188
  81. package/static/js/conv-sidebar-clone.js +0 -91
  82. package/static/js/conversations.js +0 -116
  83. package/static/js/dialogs-types.js +0 -111
  84. package/static/js/dialogs.js +0 -53
  85. package/static/js/event-filter-config.js +0 -36
  86. package/static/js/event-processor.js +0 -181
  87. package/static/js/features.js +0 -187
  88. package/static/js/image-loader-element.js +0 -76
  89. package/static/js/image-loader.js +0 -146
  90. package/static/js/prompt-machine.js +0 -108
  91. package/static/js/recording-machine.js +0 -49
  92. package/static/js/script-runner.js +0 -192
  93. package/static/js/state-barrier.js +0 -105
  94. package/static/js/streaming-renderer-dispatch.js +0 -144
  95. package/static/js/streaming-renderer-events.js +0 -163
  96. package/static/js/streaming-renderer-events2.js +0 -125
  97. package/static/js/streaming-renderer-params.js +0 -38
  98. package/static/js/streaming-renderer-render-misc.js +0 -107
  99. package/static/js/streaming-renderer-render.js +0 -181
  100. package/static/js/streaming-renderer-render2.js +0 -149
  101. package/static/js/streaming-renderer-render3.js +0 -142
  102. package/static/js/streaming-renderer-static.js +0 -181
  103. package/static/js/streaming-renderer-static2.js +0 -140
  104. package/static/js/streaming-renderer-stream.js +0 -170
  105. package/static/js/streaming-renderer-text.js +0 -185
  106. package/static/js/streaming-renderer-tools.js +0 -189
  107. package/static/js/streaming-renderer-tools2.js +0 -92
  108. package/static/js/streaming-renderer.js +0 -200
  109. package/static/js/syntax-highlighter-render.js +0 -72
  110. package/static/js/syntax-highlighter.js +0 -131
  111. package/static/js/terminal-machine.js +0 -51
  112. package/static/js/terminal.js +0 -178
  113. package/static/js/ui-components-rendering.js +0 -62
  114. package/static/js/ui-components.js +0 -88
  115. package/static/js/websocket-manager.js +0 -107
  116. package/static/js/ws-client.js +0 -87
  117. package/static/js/ws-core.js +0 -162
  118. package/static/js/ws-latency.js +0 -88
  119. package/static/js/ws-machine.js +0 -68
  120. package/static/lib/msgpackr.min.js +0 -2
  121. package/static/theme.js +0 -74
  122. package/static/vendor/highlight-js.css +0 -10
  123. package/static/vendor/highlight.min.js +0 -1244
  124. package/static/vendor/prism-dark.css +0 -129
  125. package/static/vendor/rippleui.css +0 -35
  126. package/static/vendor/xterm-addon-fit.min.js +0 -8
  127. package/static/vendor/xterm.css +0 -8
  128. package/static/vendor/xterm.min.js +0 -8
@@ -1,56 +0,0 @@
1
- import * as execMachine from './execution-machine.js';
2
-
3
- function fail(code, message) { const e = new Error(message); e.code = code; throw e; }
4
- function notFound(msg = 'Not found') { fail(404, msg); }
5
-
6
- export function register(router, deps) {
7
- const { queries, messageQueues, broadcastSync } = deps;
8
-
9
- const queueSeqByConv = new Map();
10
- function getNextQueueSeq(conversationId) {
11
- const current = queueSeqByConv.get(conversationId) || 0;
12
- const next = current + 1;
13
- queueSeqByConv.set(conversationId, next);
14
- return next;
15
- }
16
-
17
- router.handle('q.ls', (p) => {
18
- if (!queries.getConversation(p.id)) notFound('Conversation not found');
19
- const machineQueue = execMachine.getQueue(p.id);
20
- return { queue: machineQueue.length > 0 ? machineQueue : (messageQueues.get(p.id) || []) };
21
- });
22
-
23
- router.handle('q.del', (p) => {
24
- const machineQueue = execMachine.getQueue(p.id);
25
- const mapQueue = messageQueues.get(p.id);
26
- if (!machineQueue.length && !mapQueue) notFound('Queue not found');
27
- const idx = machineQueue.findIndex(q => q.messageId === p.messageId);
28
- if (idx === -1 && (!mapQueue || mapQueue.findIndex(q => q.messageId === p.messageId) === -1)) notFound('Queued message not found');
29
- if (idx !== -1) {
30
- const newQueue = [...machineQueue];
31
- newQueue.splice(idx, 1);
32
- execMachine.send(p.id, { type: 'SET_QUEUE', queue: newQueue });
33
- }
34
- if (mapQueue) {
35
- const mi = mapQueue.findIndex(q => q.messageId === p.messageId);
36
- if (mi !== -1) mapQueue.splice(mi, 1);
37
- if (mapQueue.length === 0) messageQueues.delete(p.id);
38
- }
39
- const seq = getNextQueueSeq(p.id);
40
- broadcastSync({ type: 'queue_status', conversationId: p.id, queueLength: execMachine.getQueue(p.id).length, seq, timestamp: Date.now() });
41
- return { deleted: true };
42
- });
43
-
44
- router.handle('q.upd', (p) => {
45
- const machineQueue = execMachine.getQueue(p.id);
46
- const mapQueue = messageQueues.get(p.id);
47
- if (!machineQueue.length && !mapQueue) notFound('Queue not found');
48
- const item = machineQueue.find(q => q.messageId === p.messageId) || mapQueue?.find(q => q.messageId === p.messageId);
49
- if (!item) notFound('Queued message not found');
50
- if (p.content !== undefined) item.content = p.content;
51
- if (p.agentId !== undefined) item.agentId = p.agentId;
52
- const seq = getNextQueueSeq(p.id);
53
- broadcastSync({ type: 'queue_updated', conversationId: p.id, messageId: p.messageId, content: item.content, agentId: item.agentId, seq, timestamp: Date.now() });
54
- return { updated: true, item };
55
- });
56
- }
@@ -1,182 +0,0 @@
1
- function err(code, message) { const e = new Error(message); e.code = code; throw e; }
2
- function need(p, key) { if (!p[key]) err(400, `Missing required param: ${key}`); return p[key]; }
3
-
4
- function register(router, deps) {
5
- const { queries, discoveredAgents, activeExecutions, activeProcessesByRunId, broadcastSync, processMessageWithStreaming, cleanupExecution } = deps;
6
-
7
- function findAgent(id) { const a = discoveredAgents.find(x => x.id === id); if (!a) err(404, 'Agent not found'); return a; }
8
- function getRunOrThrow(id) { const r = queries.getRun(id); if (!r) err(404, 'Run not found'); return r; }
9
- function getThreadOrThrow(id) { const t = queries.getThread(id); if (!t) err(404, 'Thread not found'); return t; }
10
-
11
- function killExecution(threadId, runId) {
12
- const ex = activeExecutions.get(threadId);
13
- if (ex?.pid) {
14
- try { process.kill(-ex.pid, 'SIGTERM'); } catch { try { process.kill(ex.pid, 'SIGTERM'); } catch {} }
15
- setTimeout(() => { try { process.kill(-ex.pid, 'SIGKILL'); } catch { try { process.kill(ex.pid, 'SIGKILL'); } catch {} } }, 3000);
16
- }
17
- if (ex?.sessionId) queries.updateSession(ex.sessionId, { status: 'error', error: 'Cancelled by user', completed_at: Date.now() });
18
- cleanupExecution(threadId);
19
- activeProcessesByRunId.delete(runId);
20
- return ex;
21
- }
22
-
23
- function startExecution(runId, threadId, agentId, input, config) {
24
- const conv = queries.getConversation(threadId);
25
- if (!conv || !input?.content) return;
26
- const session = queries.createSession(threadId);
27
- queries.updateRunStatus(runId, 'active');
28
- activeExecutions.set(threadId, { pid: null, startTime: Date.now(), sessionId: session.id, lastActivity: Date.now() });
29
- activeProcessesByRunId.set(runId, { threadId, sessionId: session.id });
30
- queries.setIsStreaming(threadId, true);
31
- processMessageWithStreaming(threadId, null, session.id, input.content, agentId, config?.model || null)
32
- .then(() => { queries.updateRunStatus(runId, 'success'); activeProcessesByRunId.delete(runId); })
33
- .catch(() => { queries.updateRunStatus(runId, 'error'); activeProcessesByRunId.delete(runId); });
34
- }
35
-
36
- router.handle('run.new', async (p) => {
37
- findAgent(need(p, 'agent_id'));
38
- return queries.createRun(p.agent_id, p.thread_id || null, p.input || null, p.config || null, p.webhook_url || null);
39
- });
40
-
41
- router.handle('run.get', async (p) => getRunOrThrow(need(p, 'id')));
42
-
43
- router.handle('run.del', async (p) => {
44
- try { queries.deleteRun(need(p, 'id')); } catch { err(404, 'Run not found'); }
45
- return { deleted: true };
46
- });
47
-
48
- router.handle('run.resume', async (p) => {
49
- const id = need(p, 'id'), run = getRunOrThrow(id);
50
- if (run.status !== 'pending') err(409, 'Run is not resumable');
51
- if (run.thread_id) startExecution(id, run.thread_id, run.agent_id, p.input, p.config);
52
- return queries.getRun(id) || run;
53
- });
54
-
55
- router.handle('run.cancel', async (p) => {
56
- const id = need(p, 'id'), run = getRunOrThrow(id);
57
- if (['success', 'error', 'cancelled'].includes(run.status)) err(409, 'Run already completed or cancelled');
58
- const cancelled = queries.cancelRun(id);
59
- if (run.thread_id) {
60
- const ex = killExecution(run.thread_id, id);
61
- broadcastSync({ type: 'streaming_cancelled', sessionId: ex?.sessionId || id, conversationId: run.thread_id, runId: id, timestamp: Date.now() });
62
- }
63
- return cancelled;
64
- });
65
-
66
- router.handle('run.search', async (p) => queries.searchRuns(p));
67
-
68
- router.handle('run.wait', async (p) => {
69
- const id = need(p, 'id');
70
- getRunOrThrow(id);
71
- const timeout = p.timeout || 30000, start = Date.now();
72
- return new Promise((resolve) => {
73
- const poll = setInterval(() => {
74
- const cur = queries.getRun(id);
75
- if (cur && ['success', 'error', 'cancelled'].includes(cur.status)) { clearInterval(poll); resolve(cur); }
76
- else if (Date.now() - start > timeout) { clearInterval(poll); resolve({ error: 'Run still pending', run_id: id, status: cur?.status }); }
77
- }, 500);
78
- });
79
- });
80
-
81
- router.handle('run.stream', async (p) => {
82
- const agent_id = need(p, 'agent_id');
83
- findAgent(agent_id);
84
- const run = queries.createRun(agent_id, null, p.input, p.config);
85
- const threadId = queries.getRun(run.run_id)?.thread_id;
86
- if (threadId) startExecution(run.run_id, threadId, agent_id, p.input, p.config);
87
- return run;
88
- });
89
-
90
- router.handle('run.stream.get', async (p) => getRunOrThrow(need(p, 'id')));
91
-
92
- router.handle('thread.new', async (p) => queries.createThread(p.metadata || {}));
93
- router.handle('thread.search', async (p) => queries.searchThreads(p));
94
- router.handle('thread.get', async (p) => getThreadOrThrow(need(p, 'id')));
95
-
96
- router.handle('thread.upd', async (p) => {
97
- try { return queries.patchThread(need(p, 'id'), p); } catch (e) {
98
- if (e.message.includes('not found')) err(404, e.message);
99
- throw e;
100
- }
101
- });
102
-
103
- router.handle('thread.del', async (p) => {
104
- try { queries.deleteThread(need(p, 'id')); return { deleted: true }; } catch (e) {
105
- if (e.message.includes('not found')) err(404, e.message);
106
- if (e.message.includes('pending runs')) err(409, e.message);
107
- throw e;
108
- }
109
- });
110
-
111
- router.handle('thread.history', async (p) => {
112
- const id = need(p, 'id'), limit = p.limit || 50, offset = p.before ? parseInt(p.before, 10) : 0;
113
- const result = queries.getThreadHistory(id, limit, offset);
114
- return { states: result.states, next_cursor: result.hasMore ? String(offset + limit) : null };
115
- });
116
-
117
- router.handle('thread.copy', async (p) => {
118
- try {
119
- const nt = queries.copyThread(need(p, 'id'));
120
- return p.metadata ? queries.patchThread(nt.thread_id, { metadata: p.metadata }) : nt;
121
- } catch (e) {
122
- if (e.message.includes('not found')) err(404, e.message);
123
- throw e;
124
- }
125
- });
126
-
127
- router.handle('thread.run.stream', async (p) => {
128
- const threadId = need(p, 'id'), agent_id = need(p, 'agent_id');
129
- const thread = getThreadOrThrow(threadId);
130
- if (thread.status !== 'idle') err(409, 'Thread has pending runs');
131
- findAgent(agent_id);
132
- const run = queries.createRun(agent_id, threadId, p.input, p.config);
133
- startExecution(run.run_id, threadId, agent_id, p.input, p.config);
134
- return run;
135
- });
136
-
137
- router.handle('thread.run.cancel', async (p) => {
138
- const threadId = need(p, 'id'), runId = need(p, 'runId'), run = getRunOrThrow(runId);
139
- if (run.thread_id !== threadId) err(400, 'Run does not belong to specified thread');
140
- if (['success', 'error', 'cancelled'].includes(run.status)) err(409, 'Run already completed or cancelled');
141
- const cancelled = queries.cancelRun(runId);
142
- const ex = killExecution(threadId, runId);
143
- broadcastSync({ type: 'run_cancelled', runId, threadId, sessionId: ex?.sessionId, timestamp: Date.now() });
144
- return cancelled;
145
- });
146
-
147
- router.handle('thread.run.stream.get', async (p) => {
148
- const threadId = need(p, 'id'), runId = need(p, 'runId');
149
- getThreadOrThrow(threadId);
150
- const run = queries.getRun(runId);
151
- if (!run || run.thread_id !== threadId) err(404, 'Run not found on thread');
152
- return run;
153
- });
154
-
155
- router.handle('thread.run.steer', async (p) => {
156
- const threadId = need(p, 'id'), runId = need(p, 'runId'), instruction = need(p, 'instruction');
157
- const thread = getThreadOrThrow(threadId);
158
- const run = getRunOrThrow(runId);
159
- if (run.thread_id !== threadId) err(400, 'Run does not belong to specified thread');
160
- if (!['active', 'pending'].includes(run.status)) err(409, 'Run is not active or pending');
161
-
162
- // Cancel current run
163
- const cancelled = queries.cancelRun(runId);
164
- const ex = killExecution(threadId, runId);
165
- broadcastSync({ type: 'run_cancelled', runId, threadId, sessionId: ex?.sessionId, timestamp: Date.now() });
166
-
167
- // Create new run with steering instruction injected
168
- // The instruction will be processed as a follow-up in the same thread context
169
- const newRun = queries.createRun(run.agent_id, threadId, { content: instruction }, run.config);
170
- startExecution(newRun.run_id, threadId, run.agent_id, { content: instruction }, run.config);
171
-
172
- return {
173
- steered: true,
174
- cancelled_run: cancelled,
175
- new_run: newRun,
176
- instruction: instruction,
177
- message: 'Run interrupted and restarted with steering instruction'
178
- };
179
- });
180
- }
181
-
182
- export { register };
@@ -1,66 +0,0 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
- import { spawn } from 'child_process';
5
- import * as scriptMachine from './script-machine.js';
6
-
7
- function err(code, message) { const e = new Error(message); e.code = code; throw e; }
8
-
9
- export function register(router, deps) {
10
- const { queries, broadcastSync, STARTUP_CWD, activeScripts } = deps;
11
-
12
- router.handle('conv.scripts', (p) => {
13
- const conv = queries.getConversation(p.id);
14
- if (!conv) err(404, 'Not found');
15
- const wd = conv.workingDirectory || STARTUP_CWD;
16
- let hasStart = false, hasDev = false;
17
- try {
18
- const pkg = JSON.parse(fs.readFileSync(path.join(wd, 'package.json'), 'utf-8'));
19
- const scripts = pkg.scripts || {};
20
- hasStart = !!scripts.start;
21
- hasDev = !!scripts.dev;
22
- } catch {}
23
- const running = scriptMachine.isRunning(p.id);
24
- const ctx = scriptMachine.getContext(p.id);
25
- const runningScript = running ? ctx?.script : null;
26
- return { hasStart, hasDev, running, runningScript };
27
- });
28
-
29
- router.handle('conv.run-script', (p) => {
30
- const conv = queries.getConversation(p.id);
31
- if (!conv) err(404, 'Not found');
32
- if (scriptMachine.isRunning(p.id)) err(409, 'Script already running');
33
- const script = p.script;
34
- if (script !== 'start' && script !== 'dev') err(400, 'Invalid script');
35
- const wd = conv.workingDirectory || STARTUP_CWD;
36
- try {
37
- const pkg = JSON.parse(fs.readFileSync(path.join(wd, 'package.json'), 'utf-8'));
38
- if (!pkg.scripts || !pkg.scripts[script]) err(400, `Script "${script}" not found`);
39
- } catch (e) { if (e.code) throw e; err(400, 'No package.json'); }
40
- const childEnv = { ...process.env, FORCE_COLOR: '1' };
41
- delete childEnv.PORT; delete childEnv.BASE_URL; delete childEnv.HOT_RELOAD;
42
- const isWindows = os.platform() === 'win32';
43
- const child = spawn('npm', ['run', script], { cwd: wd, stdio: ['ignore', 'pipe', 'pipe'], detached: true, env: childEnv, shell: isWindows });
44
- scriptMachine.send(p.id, { type: 'START', process: child, script, pid: child.pid });
45
- activeScripts.set(p.id, { process: child, script, startTime: Date.now() });
46
- broadcastSync({ type: 'script_started', conversationId: p.id, script, timestamp: Date.now() });
47
- const onData = (stream) => (chunk) => broadcastSync({ type: 'script_output', conversationId: p.id, data: chunk.toString(), stream, timestamp: Date.now() });
48
- child.stdout.on('data', onData('stdout'));
49
- child.stderr.on('data', onData('stderr'));
50
- child.on('error', (e) => { scriptMachine.send(p.id, { type: 'ERROR' }); activeScripts.delete(p.id); broadcastSync({ type: 'script_stopped', conversationId: p.id, code: 1, error: e.message, timestamp: Date.now() }); });
51
- child.on('close', (code) => { scriptMachine.send(p.id, { type: 'CLOSE' }); activeScripts.delete(p.id); broadcastSync({ type: 'script_stopped', conversationId: p.id, code: code || 0, timestamp: Date.now() }); });
52
- return { ok: true, script, pid: child.pid };
53
- });
54
-
55
- router.handle('conv.stop-script', (p) => {
56
- if (!scriptMachine.isRunning(p.id)) err(404, 'No running script');
57
- const ctx = scriptMachine.getContext(p.id);
58
- const proc = ctx?.process;
59
- scriptMachine.send(p.id, { type: 'STOP' });
60
- if (proc) {
61
- try { process.kill(-proc.pid, 'SIGTERM'); } catch { try { proc.kill('SIGTERM'); } catch {} }
62
- setTimeout(() => { try { process.kill(-proc.pid, 'SIGKILL'); } catch { try { proc.kill('SIGKILL'); } catch {} } }, 5000);
63
- }
64
- return { ok: true };
65
- });
66
- }
@@ -1,105 +0,0 @@
1
- import { queryModels } from './acp-sdk-manager.js';
2
-
3
- const STATIC_MODELS = {
4
- 'claude-code': [
5
- { id: 'haiku', label: 'Haiku' },
6
- { id: 'sonnet', label: 'Sonnet' },
7
- { id: 'opus', label: 'Opus' }
8
- ],
9
- 'gemini': [
10
- { id: 'gemini-3-pro', label: 'Gemini 3 Pro' },
11
- { id: 'gemini-3-flash', label: 'Gemini 3 Flash' },
12
- { id: 'gemini-3.1-pro', label: 'Gemini 3.1 Pro' },
13
- { id: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
14
- { id: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
15
- { id: 'gemini-2.0-flash', label: 'Gemini 2.0 Flash' }
16
- ]
17
- };
18
-
19
- export function register(router, deps) {
20
- const { db, discoveredAgents, modelCache, getAgentDescriptor } = deps;
21
- console.log('[ws-handlers-session] register() called with discoveredAgents.length:', discoveredAgents.length);
22
-
23
- router.handle('sess.get', (p) => {
24
- const sess = db.getSession(p.id);
25
- if (!sess) throw { code: 404, message: 'Not found' };
26
- return { session: sess, events: db.getSessionEvents(p.id) };
27
- });
28
-
29
- router.handle('sess.latest', (p) => {
30
- const s = db.getLatestSession(p.id);
31
- if (!s) return { session: null };
32
- return { session: s, events: db.getSessionEvents(s.id) };
33
- });
34
-
35
- router.handle('sess.chunks', (p) => {
36
- if (!db.getSession(p.id)) throw { code: 404, message: 'Session not found' };
37
- const sinceSeq = parseInt(p.sinceSeq ?? '-1');
38
- const since = parseInt(p.since ?? '0');
39
- const chunks = sinceSeq >= 0 ? db.getChunksSinceSeq(p.id, sinceSeq) : db.getChunksSince(p.id, since);
40
- return { ok: true, chunks };
41
- });
42
-
43
- router.handle('sess.exec', (p) => {
44
- const limit = Math.min(parseInt(p.limit || '1000'), 5000);
45
- const offset = Math.max(parseInt(p.offset || '0'), 0);
46
- const session = db.getSession(p.id);
47
- const allChunks = session ? (db.getChunksSince(p.id, 0) || []) : [];
48
- const filterType = p.filterType;
49
- const filtered = filterType ? allChunks.filter(e => e.type === filterType) : allChunks;
50
- return {
51
- sessionId: p.id,
52
- events: filtered.slice(offset, offset + limit),
53
- total: filtered.length,
54
- limit,
55
- offset,
56
- hasMore: offset + limit < filtered.length,
57
- metadata: {
58
- status: session?.status || 'unknown',
59
- startTime: session?.created_at || null,
60
- duration: session?.completed_at && session?.created_at ? session.completed_at - session.created_at : 0,
61
- eventCount: filtered.length
62
- }
63
- };
64
- });
65
-
66
- router.handle('agent.ls', () => {
67
- console.log('[agent.ls] discoveredAgents.length:', discoveredAgents.length);
68
- console.log('[agent.ls] agent IDs:', discoveredAgents.map(a => a.id).join(', '));
69
- return {
70
- agents: discoveredAgents.map(a => ({
71
- id: a.id, name: a.name, icon: a.icon, path: a.path,
72
- protocol: a.protocol || 'unknown', description: a.description || '', status: 'available'
73
- }))
74
- };
75
- });
76
-
77
- router.handle('agent.get', (p) => {
78
- const a = discoveredAgents.find(x => x.id === p.id);
79
- if (!a) throw { code: 404, message: 'Agent not found' };
80
- return { id: a.id, name: a.name, description: a.description || '', icon: a.icon || null, status: 'available' };
81
- });
82
-
83
- router.handle('agent.desc', (p) => {
84
- const d = getAgentDescriptor(p.id);
85
- if (!d) throw { code: 404, message: 'Agent not found' };
86
- return d;
87
- });
88
-
89
- router.handle('agent.models', async (p) => {
90
- const cached = modelCache.get(p.id);
91
- if (cached && (Date.now() - cached.ts) < 300000) return { models: cached.models };
92
- let models = [];
93
- const agent = discoveredAgents.find(x => x.id === p.id);
94
- const targetId = agent?.protocol === 'cli-wrapper' && agent.acpId ? agent.acpId : p.id;
95
- if (p.id === 'cli-claude' || STATIC_MODELS[targetId]) {
96
- models = STATIC_MODELS[targetId] || STATIC_MODELS['claude-code'];
97
- } else if (agent?.protocol === 'acp' || (agent?.protocol === 'cli-wrapper' && agent.acpId)) {
98
- models = await queryModels(targetId);
99
- }
100
- if (models.length > 0) modelCache.set(p.id, { models, ts: Date.now() });
101
- return { models };
102
- });
103
-
104
- router.handle('agent.search', (p) => db.searchAgents(discoveredAgents, p.query || p));
105
- }
@@ -1,85 +0,0 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
- import { execSync, spawn } from 'child_process';
5
-
6
- function spawnScript(cmd, args, convId, scriptName, agentId, deps) {
7
- const { activeScripts, broadcastSync, modelCache } = deps;
8
- if (activeScripts.has(convId)) throw { code: 409, message: 'Process already running' };
9
- const child = spawn(cmd, args, {
10
- stdio: ['pipe', 'pipe', 'pipe'],
11
- env: { ...process.env, FORCE_COLOR: '1' },
12
- shell: os.platform() === 'win32'
13
- });
14
- activeScripts.set(convId, { process: child, script: scriptName, startTime: Date.now() });
15
- broadcastSync({ type: 'script_started', conversationId: convId, script: scriptName, agentId, timestamp: Date.now() });
16
- const relay = (stream) => (chunk) => {
17
- broadcastSync({ type: 'script_output', conversationId: convId, data: chunk.toString(), stream, timestamp: Date.now() });
18
- };
19
- child.stdout.on('data', relay('stdout'));
20
- child.stderr.on('data', relay('stderr'));
21
- child.on('error', (err) => {
22
- activeScripts.delete(convId);
23
- broadcastSync({ type: 'script_stopped', conversationId: convId, code: 1, error: err.message, timestamp: Date.now() });
24
- });
25
- child.on('close', (code) => {
26
- activeScripts.delete(convId);
27
- if (modelCache && agentId) modelCache.delete(agentId);
28
- broadcastSync({ type: 'script_stopped', conversationId: convId, code: code || 0, timestamp: Date.now() });
29
- });
30
- return child.pid;
31
- }
32
-
33
- function readJson(filePath) {
34
- try { return fs.existsSync(filePath) ? JSON.parse(fs.readFileSync(filePath, 'utf-8')) : null; } catch { return null; }
35
- }
36
-
37
- function checkAgentAuth(agent) {
38
- const s = { id: agent.id, name: agent.name, authenticated: false, detail: '' };
39
- try {
40
- if (agent.id === 'claude-code') {
41
- const creds = readJson(path.join(os.homedir(), '.claude', '.credentials.json'));
42
- if (creds?.claudeAiOauth?.expiresAt > Date.now()) {
43
- s.authenticated = true;
44
- s.detail = creds.claudeAiOauth.subscriptionType || 'authenticated';
45
- } else { s.detail = creds ? 'expired' : 'no credentials'; }
46
- } else if (agent.id === 'gemini') {
47
- const oauth = readJson(path.join(os.homedir(), '.gemini', 'oauth_creds.json'));
48
- const accts = readJson(path.join(os.homedir(), '.gemini', 'google_accounts.json'));
49
- const hasOAuth = !!(oauth?.refresh_token || oauth?.access_token);
50
- if (accts?.active) { s.authenticated = true; s.detail = accts.active; }
51
- else if (hasOAuth) { s.authenticated = true; s.detail = 'oauth'; }
52
- else { s.detail = accts ? 'logged out' : 'no credentials'; }
53
- } else if (agent.id === 'opencode') {
54
- const out = execSync('opencode auth list 2>&1', { encoding: 'utf-8', timeout: 5000 });
55
- const m = out.match(/(\d+)\s+credentials?/);
56
- if (m && parseInt(m[1], 10) > 0) { s.authenticated = true; s.detail = m[1] + ' credential(s)'; }
57
- else { s.detail = 'no credentials'; }
58
- } else { s.detail = 'unknown'; }
59
- } catch { s.detail = 'check failed'; }
60
- return s;
61
- }
62
-
63
- export function register(router, deps) {
64
- const { discoveredAgents, modelCache, activeScripts, broadcastSync } = deps;
65
-
66
- router.handle('agent.auth', async (p) => {
67
- const agentId = p.id;
68
- if (!discoveredAgents.find(a => a.id === agentId)) throw { code: 404, message: 'Agent not found' };
69
- const cmds = { 'claude-code': { cmd: 'claude', args: ['setup-token'] }, 'opencode': { cmd: 'opencode', args: ['auth', 'login'] } };
70
- const c = cmds[agentId];
71
- if (!c) throw { code: 400, message: 'No auth command for this agent (OAuth flows removed; configure provider key via /api/auth/save-config)' };
72
- const pid = spawnScript(c.cmd, c.args, '__agent_auth__', 'auth-' + agentId, agentId, { activeScripts, broadcastSync });
73
- return { ok: true, agentId, pid };
74
- });
75
-
76
- router.handle('agent.authstat', () => ({ agents: discoveredAgents.map(checkAgentAuth) }));
77
-
78
- router.handle('agent.update', (p) => {
79
- const cmds = { 'claude-code': { cmd: 'claude', args: ['update', '--yes'] } };
80
- const c = cmds[p.id];
81
- if (!c) throw { code: 400, message: 'No update command for this agent' };
82
- const pid = spawnScript(c.cmd, c.args, '__agent_update__', 'update-' + p.id, p.id, { activeScripts, broadcastSync, modelCache });
83
- return { ok: true, agentId: p.id, pid };
84
- });
85
- }
@@ -1,51 +0,0 @@
1
- export function registerLegacyHandler(wsRouter, { subscriptionIndex, execMachine, activeExecutions, messageQueues, queries, getSeq, sendWs, debugLog }) {
2
- wsRouter.onLegacy((data, ws) => {
3
- try {
4
- if (data.type === 'subscribe') {
5
- if (data.sessionId) {
6
- ws.subscriptions.add(data.sessionId);
7
- if (!subscriptionIndex.has(data.sessionId)) subscriptionIndex.set(data.sessionId, new Set());
8
- subscriptionIndex.get(data.sessionId).add(ws);
9
- }
10
- if (data.conversationId) {
11
- const key = `conv-${data.conversationId}`;
12
- ws.subscriptions.add(key);
13
- if (!subscriptionIndex.has(key)) subscriptionIndex.set(key, new Set());
14
- subscriptionIndex.get(key).add(ws);
15
- }
16
- const subTarget = data.sessionId || data.conversationId;
17
- debugLog(`[WebSocket] Client ${ws.clientId} subscribed to ${subTarget}`);
18
- sendWs(ws, { type: 'subscription_confirmed', sessionId: data.sessionId, conversationId: data.conversationId, timestamp: Date.now() });
19
- if (data.conversationId && execMachine.isActive(data.conversationId)) {
20
- const ctx = execMachine.getContext(data.conversationId);
21
- const execution = activeExecutions.get(data.conversationId);
22
- const sessionId = ctx?.sessionId || execution?.sessionId;
23
- const conv = queries.getConversation(data.conversationId);
24
- const queueLength = execMachine.getQueue(data.conversationId).length || messageQueues.get(data.conversationId)?.length || 0;
25
- sendWs(ws, { type: 'streaming_start', sessionId, conversationId: data.conversationId, agentId: conv?.agentType || conv?.agentId || 'claude-code', queueLength, resumed: true, seq: getSeq(), timestamp: Date.now() });
26
- }
27
- } else if (data.type === 'unsubscribe') {
28
- if (data.sessionId) {
29
- ws.subscriptions.delete(data.sessionId);
30
- const idx = subscriptionIndex.get(data.sessionId);
31
- if (idx) { idx.delete(ws); if (idx.size === 0) subscriptionIndex.delete(data.sessionId); }
32
- }
33
- if (data.conversationId) {
34
- const key = `conv-${data.conversationId}`;
35
- ws.subscriptions.delete(key);
36
- const idx = subscriptionIndex.get(key);
37
- if (idx) { idx.delete(ws); if (idx.size === 0) subscriptionIndex.delete(key); }
38
- }
39
- debugLog(`[WebSocket] Client ${ws.clientId} unsubscribed from ${data.sessionId || data.conversationId}`);
40
- } else if (data.type === 'get_subscriptions') {
41
- sendWs(ws, { type: 'subscriptions', subscriptions: Array.from(ws.subscriptions), timestamp: Date.now() });
42
- } else if (data.type === 'latency_report') {
43
- ws.latencyTier = data.quality || 'good';
44
- ws.latencyAvg = data.avg || 0;
45
- ws.latencyTrend = data.trend || 'stable';
46
- } else if (data.type === 'ping') {
47
- sendWs(ws, { type: 'pong', requestId: data.requestId, timestamp: Date.now() });
48
- }
49
- } catch (err) { console.error('[WS-LEGACY] Handler error (contained):', err.message); }
50
- });
51
- }