agentgui 1.0.1117 → 1.0.1119
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.
- package/.gm/.embed-generation.code_chunks +1 -0
- package/.gm/.embed-generation.git_commit_vectors +1 -0
- package/.gm/.embed-generation.memories +1 -0
- package/.gm/.embed-generation.rssearch_vectors +1 -0
- package/.gm/prd.yml +10 -0
- package/AGENTS.md +1 -1
- package/lib/acp-http-protocol.js +91 -0
- package/lib/acp-sdk-manager.js +15 -2
- package/lib/claude-runner-agents.js +8 -1
- package/lib/http-handler.js +35 -566
- package/lib/http-routes/mutations.js +199 -0
- package/lib/http-routes/reads.js +212 -0
- package/lib/http-routes/shared.js +213 -0
- package/lib/ws-handlers/agents.js +137 -0
- package/lib/ws-handlers/chat.js +157 -0
- package/lib/ws-handlers/git.js +159 -0
- package/lib/ws-handlers/misc.js +36 -0
- package/lib/ws-handlers/shared.js +47 -0
- package/lib/ws-handlers/terminal-state.js +16 -0
- package/lib/ws-handlers-util.js +8 -526
- package/package.json +1 -1
- package/site/app/js/app.js +8 -103
- package/site/app/js/chat-persistence.js +123 -0
- package/site/app/vendor/anentrypoint-design/247420.css +1614 -488
- package/site/app/vendor/anentrypoint-design/247420.js +363 -77
- package/UX_OPTIMIZATION_SUMMARY.md +0 -238
- package/agentgui-after.png +0 -0
- package/agentgui-current.png +0 -0
- package/agentgui-final.png +0 -0
- package/agentgui-nobrand.png +0 -0
- package/agentgui-now.png +0 -0
- package/agentgui-v2.png +0 -0
- package/agentgui-v4.png +0 -0
- package/bash.exe.stackdump +0 -28
- package/design-reference.png +0 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { registry } from '../claude-runner-agents.js';
|
|
2
|
+
import { restart as restartAcpAgent } from '../acp-sdk-manager.js';
|
|
3
|
+
import { err } from './shared.js';
|
|
4
|
+
import { spawnSync } from 'child_process';
|
|
5
|
+
|
|
6
|
+
const SUB_AGENT_MAP = {
|
|
7
|
+
'opencode': [{ id: 'gm-oc', name: 'GM OpenCode' }], 'cli-opencode': [{ id: 'gm-oc', name: 'GM OpenCode' }],
|
|
8
|
+
'gemini': [{ id: 'gm-gc', name: 'GM Gemini' }], 'cli-gemini': [{ id: 'gm-gc', name: 'GM Gemini' }],
|
|
9
|
+
'kilo': [{ id: 'gm-kilo', name: 'GM Kilo' }], 'cli-kilo': [{ id: 'gm-kilo', name: 'GM Kilo' }],
|
|
10
|
+
'codex': [], 'cli-codex': []
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function register(router, deps) {
|
|
14
|
+
const { getProviderConfigs, getModelsForAgent } = deps;
|
|
15
|
+
|
|
16
|
+
// --- agents.list: enumerate registered ACP agents + claude-code ---
|
|
17
|
+
router.handle('agents.list', () => {
|
|
18
|
+
const agents = registry.list().map(a => ({
|
|
19
|
+
id: a.id,
|
|
20
|
+
name: a.name,
|
|
21
|
+
protocol: a.protocol,
|
|
22
|
+
supportsStdin: !!a.supportsStdin,
|
|
23
|
+
features: a.supportedFeatures || [],
|
|
24
|
+
available: registry.isAvailable(a.id),
|
|
25
|
+
npxInstallable: !!a.npxPackage,
|
|
26
|
+
// The CLI binary name a manual (non-npx) install would need - lets the
|
|
27
|
+
// settings panel say what to install instead of just "not installed".
|
|
28
|
+
cmd: a.command || null,
|
|
29
|
+
}));
|
|
30
|
+
return { agents };
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// --- agents.models: model choices for a given agent ---
|
|
34
|
+
router.handle('agents.models', async (p) => {
|
|
35
|
+
const id = p?.id || p?.agentId;
|
|
36
|
+
if (!id) err(400, 'agent id required');
|
|
37
|
+
if (id === 'claude-code') {
|
|
38
|
+
return { models: [
|
|
39
|
+
{ id: 'sonnet', name: 'Claude Sonnet (latest)' },
|
|
40
|
+
{ id: 'opus', name: 'Claude Opus (latest)' },
|
|
41
|
+
{ id: 'haiku', name: 'Claude Haiku (latest)' },
|
|
42
|
+
] };
|
|
43
|
+
}
|
|
44
|
+
// Other agents: discover their models via getModelsForAgent (queries the
|
|
45
|
+
// running ACP server). Fail closed to an empty list on any error or when
|
|
46
|
+
// the dep isn't a function.
|
|
47
|
+
if (typeof getModelsForAgent === 'function') {
|
|
48
|
+
try {
|
|
49
|
+
const raw = await getModelsForAgent(id);
|
|
50
|
+
const list = Array.isArray(raw) ? raw : (raw?.models || []);
|
|
51
|
+
return { models: list.map(m => ({ id: m.id, name: m.name || m.label || m.id })) };
|
|
52
|
+
} catch { return { models: [] }; }
|
|
53
|
+
}
|
|
54
|
+
return { models: [] };
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
router.handle('acp.restart', async (p) => {
|
|
58
|
+
if (!p.id) err(400, 'Missing agent id');
|
|
59
|
+
const ok = await restartAcpAgent(p.id);
|
|
60
|
+
return { ok: !!ok };
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
router.handle('agent.subagents', async (p) => {
|
|
64
|
+
if (!p.id) err(400, 'Missing agent id');
|
|
65
|
+
if (p.id === 'claude-code' || p.id === 'cli-claude') {
|
|
66
|
+
const spawnEnv = { ...process.env }; delete spawnEnv.CLAUDECODE;
|
|
67
|
+
const result = spawnSync('claude', ['agents', 'list'], { encoding: 'utf-8', timeout: 10000, stdio: ['pipe', 'pipe', 'pipe'], env: spawnEnv });
|
|
68
|
+
if (result.status !== 0 || !result.stdout) return { subAgents: [] };
|
|
69
|
+
const agents = result.stdout.trim().split('\n').filter(l => l.trim()).map(l => l.match(/^ (\S+)\s+·/)).filter(Boolean).map(m => ({ id: m[1], name: m[1] }));
|
|
70
|
+
return { subAgents: agents };
|
|
71
|
+
}
|
|
72
|
+
return { subAgents: SUB_AGENT_MAP[p.id] || [] };
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// --- models.availability: composes agentgui's REAL model surface into the
|
|
76
|
+
// ModelsConfig component's shape (design SDK's ModelsConfig.js). agentgui
|
|
77
|
+
// has no freddie-style probed-availability matrix (no /v1/models round-trip
|
|
78
|
+
// per mode) - what it actually has is: discovered agent CLIs (registry,
|
|
79
|
+
// same data agents.list already exposes), each agent's model choices
|
|
80
|
+
// (agents.models' getModelsForAgent), and per-provider API-key presence
|
|
81
|
+
// (auth.configs' getProviderConfigs). This handler is a read-only
|
|
82
|
+
// composition of those three real sources, not a new probe and not fake
|
|
83
|
+
// data - "usable_in_any_mode" is derived from registry.isAvailable(agentId)
|
|
84
|
+
// (the CLI binary was actually found on this server), and "key_present"
|
|
85
|
+
// comes straight from getProviderConfigs' filesystem check.
|
|
86
|
+
router.handle('models.availability', async () => {
|
|
87
|
+
const agents = registry.list();
|
|
88
|
+
const providerConfigs = typeof getProviderConfigs === 'function' ? getProviderConfigs() : {};
|
|
89
|
+
const providers = [];
|
|
90
|
+
for (const a of agents) {
|
|
91
|
+
const available = registry.isAvailable(a.id);
|
|
92
|
+
let models = [];
|
|
93
|
+
if (a.id === 'claude-code') {
|
|
94
|
+
models = [
|
|
95
|
+
{ id: 'sonnet', name: 'Claude Sonnet (latest)' },
|
|
96
|
+
{ id: 'opus', name: 'Claude Opus (latest)' },
|
|
97
|
+
{ id: 'haiku', name: 'Claude Haiku (latest)' },
|
|
98
|
+
];
|
|
99
|
+
} else if (typeof getModelsForAgent === 'function') {
|
|
100
|
+
try {
|
|
101
|
+
const raw = await getModelsForAgent(a.id);
|
|
102
|
+
const list = Array.isArray(raw) ? raw : (raw?.models || []);
|
|
103
|
+
models = list.map((m) => ({ id: m.id, name: m.name || m.label || m.id }));
|
|
104
|
+
} catch { models = []; }
|
|
105
|
+
}
|
|
106
|
+
// Map onto agentgui's one real signal per model: is the agent CLI itself
|
|
107
|
+
// available on this server (registry.isAvailable). agentgui does not
|
|
108
|
+
// probe individual (model, mode) cells the way freddie's matrix does,
|
|
109
|
+
// so every model under an available agent reports the same single
|
|
110
|
+
// 'cli' mode rather than fabricating per-mode probe results.
|
|
111
|
+
providers.push({
|
|
112
|
+
id: a.id,
|
|
113
|
+
key_present: !!(providerConfigs[a.id] && providerConfigs[a.id].hasKey) || available,
|
|
114
|
+
discovery_error: available ? null : ((a.name || a.id) + ' CLI not found on this server'),
|
|
115
|
+
models: models.map((m) => ({
|
|
116
|
+
id: m.id,
|
|
117
|
+
name: m.name,
|
|
118
|
+
discovered_via: a.protocol || 'cli',
|
|
119
|
+
modes: { cli: { ok: !!available, skipped: !available, reason: available ? undefined : 'agent_not_installed' } },
|
|
120
|
+
usable_in_any_mode: !!available,
|
|
121
|
+
})),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
const totalModels = providers.reduce((n, p) => n + p.models.length, 0);
|
|
125
|
+
const usableModels = providers.reduce((n, p) => n + p.models.filter((m) => m.usable_in_any_mode).length, 0);
|
|
126
|
+
return {
|
|
127
|
+
timestamp: new Date().toISOString(),
|
|
128
|
+
providers,
|
|
129
|
+
sampler: [],
|
|
130
|
+
summary: {
|
|
131
|
+
total_providers: providers.length,
|
|
132
|
+
total_models: totalModels,
|
|
133
|
+
usable_in_any_mode: usableModels,
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
});
|
|
137
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { runClaudeWithStreaming } from '../claude-runner-run.js';
|
|
3
|
+
import { registry } from '../claude-runner-agents.js';
|
|
4
|
+
import { confineToRoots, fsAllowRoots } from '../http-handler.js';
|
|
5
|
+
import { err } from './shared.js';
|
|
6
|
+
import { recordTerminal, getTerminal } from './terminal-state.js';
|
|
7
|
+
|
|
8
|
+
export function register(router, deps) {
|
|
9
|
+
const { wsOptimizer, broadcastSync, STARTUP_CWD, subscriptionIndex, activeChats } = deps;
|
|
10
|
+
|
|
11
|
+
// --- conversation.subscribe: register this ws for sessionId broadcasts ---
|
|
12
|
+
router.handle('conversation.subscribe', (p, ws) => {
|
|
13
|
+
const sid = p?.sessionId;
|
|
14
|
+
if (!sid || typeof sid !== 'string') err(400, 'sessionId required');
|
|
15
|
+
if (!subscriptionIndex.has(sid)) subscriptionIndex.set(sid, new Set());
|
|
16
|
+
subscriptionIndex.get(sid).add(ws);
|
|
17
|
+
ws.subscriptions = ws.subscriptions || new Set();
|
|
18
|
+
ws.subscriptions.add(sid);
|
|
19
|
+
// Replay a buffered terminal frame (complete/error/cancelled) so a client
|
|
20
|
+
// that re-subscribes after a ws drop learns the turn already ended.
|
|
21
|
+
const term = getTerminal(sid);
|
|
22
|
+
if (term) { try { wsOptimizer.sendToClient(ws, { ...term, replayed: true }); } catch {} }
|
|
23
|
+
return { subscribed: true, sessionId: sid, replayedTerminal: !!term };
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// --- chat.sendMessage: start a one-shot streaming chat with an agent.
|
|
27
|
+
// Bypasses the gutted db-queries layer entirely; calls runClaudeWithStreaming
|
|
28
|
+
// directly and broadcasts streaming_* events scoped to an ephemeral sessionId.
|
|
29
|
+
router.handle('chat.sendMessage', async (p, ws) => {
|
|
30
|
+
let content = (p?.content || '').toString();
|
|
31
|
+
if (!content) err(400, 'content required');
|
|
32
|
+
const agentId = p?.agentId || 'claude-code';
|
|
33
|
+
// For non-resume agents (not claude-code which uses --resume), prepend prior
|
|
34
|
+
// conversation turns so the agent has context. claude-code handles multi-turn
|
|
35
|
+
// natively via resumeSessionId; direct runners (agy, etc.) get a preamble.
|
|
36
|
+
const priorMessages = Array.isArray(p?.messages) ? p.messages.filter(m => m?.role && m?.content) : [];
|
|
37
|
+
if (agentId !== 'claude-code' && !p?.resumeSid && !p?.resumeSessionId && priorMessages.length > 0) {
|
|
38
|
+
const preamble = priorMessages.map(m => (m.role === 'user' ? 'User: ' : 'Assistant: ') + (m.content || '').trim()).join('\n\n');
|
|
39
|
+
content = '[Prior conversation]\n' + preamble + '\n\n[Current message]\n' + content;
|
|
40
|
+
}
|
|
41
|
+
const model = p?.model || undefined;
|
|
42
|
+
const subAgent = p?.subAgent || undefined;
|
|
43
|
+
const cwd = p?.cwd || STARTUP_CWD;
|
|
44
|
+
const resumeSessionId = p?.resumeSid || p?.resumeSessionId || undefined;
|
|
45
|
+
if (!registry.has(agentId)) err(404, `Unknown agentId: ${agentId}`);
|
|
46
|
+
// A client-supplied cwd must be confined to the SAME allowlist as the Files
|
|
47
|
+
// routes (fsAllowRoots) - an unconfined cwd would let a client spawn the
|
|
48
|
+
// agent CLI anywhere on disk. Use the realpath-resolved value as the spawn
|
|
49
|
+
// cwd (defeats symlink escape, same as the HTTP file routes). No p.cwd ->
|
|
50
|
+
// STARTUP_CWD, which is itself an allowed root, so it needs no check.
|
|
51
|
+
let spawnCwd = STARTUP_CWD;
|
|
52
|
+
if (p?.cwd) {
|
|
53
|
+
const conf = confineToRoots(cwd, fsAllowRoots());
|
|
54
|
+
if (!conf.ok) err(conf.reason === 'not found' ? 400 : 403, `cwd outside allowed roots: ${cwd}`);
|
|
55
|
+
spawnCwd = conf.realPath;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const sessionId = 'chat-' + crypto.randomBytes(8).toString('hex');
|
|
59
|
+
// Auto-subscribe the originating ws so it receives its own broadcasts.
|
|
60
|
+
if (!subscriptionIndex.has(sessionId)) subscriptionIndex.set(sessionId, new Set());
|
|
61
|
+
subscriptionIndex.get(sessionId).add(ws);
|
|
62
|
+
ws.subscriptions = ws.subscriptions || new Set();
|
|
63
|
+
ws.subscriptions.add(sessionId);
|
|
64
|
+
|
|
65
|
+
const ctrl = { aborted: false, proc: null, agentId, model, cwd: spawnCwd, startedAt: Date.now() };
|
|
66
|
+
activeChats.set(sessionId, ctrl);
|
|
67
|
+
// Push-driven hint so clients refresh active-session state without
|
|
68
|
+
// waiting for the 3s chat.active poll (finding 48).
|
|
69
|
+
broadcastSync({ type: 'chat_active_changed', reason: 'started', sessionId, agentId, timestamp: Date.now() });
|
|
70
|
+
|
|
71
|
+
// Fire-and-forget. Errors broadcast as streaming_error.
|
|
72
|
+
(async () => {
|
|
73
|
+
let eventCount = 0;
|
|
74
|
+
broadcastSync({ type: 'streaming_start', sessionId, agentId, timestamp: Date.now() });
|
|
75
|
+
let claudeSessionBroadcast = false;
|
|
76
|
+
const onEvent = (parsed) => {
|
|
77
|
+
eventCount++;
|
|
78
|
+
// Surface claude's REAL session id (from the stream) once, so the client
|
|
79
|
+
// can --resume this conversation on its next turn. The ephemeral
|
|
80
|
+
// 'chat-...' sessionId is not a claude session id and cannot be resumed.
|
|
81
|
+
if (!claudeSessionBroadcast && parsed?.session_id) {
|
|
82
|
+
claudeSessionBroadcast = true;
|
|
83
|
+
ctrl.claudeSessionId = parsed.session_id;
|
|
84
|
+
broadcastSync({ type: 'streaming_session', sessionId, claudeSessionId: parsed.session_id, agentId, timestamp: Date.now() });
|
|
85
|
+
}
|
|
86
|
+
if (parsed?.type === 'assistant' && parsed.message?.content) {
|
|
87
|
+
for (const block of parsed.message.content) {
|
|
88
|
+
broadcastSync({ type: 'streaming_progress', sessionId, block, blockRole: 'assistant', seq: eventCount, timestamp: Date.now() });
|
|
89
|
+
}
|
|
90
|
+
} else if (parsed?.type === 'user' && parsed.message?.content) {
|
|
91
|
+
const blocks = Array.isArray(parsed.message.content) ? parsed.message.content : [];
|
|
92
|
+
for (const block of blocks) {
|
|
93
|
+
if (block?.type === 'tool_result') {
|
|
94
|
+
broadcastSync({ type: 'streaming_progress', sessionId, block, blockRole: 'tool_result', seq: eventCount, timestamp: Date.now() });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
} else if (parsed?.type === 'result') {
|
|
98
|
+
const block = { type: 'result', result: parsed.result, subtype: parsed.subtype, duration_ms: parsed.duration_ms, total_cost_usd: parsed.total_cost_usd, is_error: !!parsed.is_error };
|
|
99
|
+
broadcastSync({ type: 'streaming_progress', sessionId, block, blockRole: 'result', seq: eventCount, isResult: true, timestamp: Date.now() });
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
try {
|
|
103
|
+
const config = {
|
|
104
|
+
verbose: true, outputFormat: 'stream-json', timeout: 1800000, print: true,
|
|
105
|
+
model, subAgent, onEvent, resumeSessionId,
|
|
106
|
+
onPid: () => {}, onProcess: (proc) => { ctrl.proc = proc; },
|
|
107
|
+
};
|
|
108
|
+
await runClaudeWithStreaming(content, spawnCwd, agentId, config);
|
|
109
|
+
if (!ctrl.aborted) {
|
|
110
|
+
const ev = { type: 'streaming_complete', sessionId, claudeSessionId: ctrl.claudeSessionId || null, agentId, eventCount, timestamp: Date.now() };
|
|
111
|
+
recordTerminal(sessionId, ev);
|
|
112
|
+
broadcastSync(ev);
|
|
113
|
+
}
|
|
114
|
+
} catch (e) {
|
|
115
|
+
if (!ctrl.aborted) {
|
|
116
|
+
const ev = { type: 'streaming_error', sessionId, claudeSessionId: ctrl.claudeSessionId || null, agentId, error: e.message || String(e), recoverable: false, timestamp: Date.now() };
|
|
117
|
+
recordTerminal(sessionId, ev);
|
|
118
|
+
broadcastSync(ev);
|
|
119
|
+
}
|
|
120
|
+
} finally {
|
|
121
|
+
activeChats.delete(sessionId);
|
|
122
|
+
broadcastSync({ type: 'chat_active_changed', reason: 'ended', sessionId, agentId, timestamp: Date.now() });
|
|
123
|
+
}
|
|
124
|
+
})();
|
|
125
|
+
|
|
126
|
+
return { sessionId, started: true };
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// --- chat.active: list in-flight chats started via this server ---
|
|
130
|
+
router.handle('chat.active', () => {
|
|
131
|
+
const sessions = [];
|
|
132
|
+
for (const [sid, c] of activeChats) {
|
|
133
|
+
sessions.push({ sessionId: sid, claudeSessionId: c.claudeSessionId || null, agentId: c.agentId || null, model: c.model || null, cwd: c.cwd || null, startedAt: c.startedAt || null, pid: c.proc?.pid || null });
|
|
134
|
+
}
|
|
135
|
+
return { sessions };
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// --- chat.cancel: abort an in-flight chat ---
|
|
139
|
+
router.handle('chat.cancel', (p) => {
|
|
140
|
+
const sid = p?.sessionId;
|
|
141
|
+
if (!sid) err(400, 'sessionId required');
|
|
142
|
+
const ctrl = activeChats.get(sid);
|
|
143
|
+
if (!ctrl) return { cancelled: false, reason: 'not-found' };
|
|
144
|
+
ctrl.aborted = true;
|
|
145
|
+
// Broadcast the terminal 'cancelled' frame BEFORE killing the proc so a
|
|
146
|
+
// remote cancellation (other tab, dashboard stop-all) does not read as a
|
|
147
|
+
// normal completion (finding 44). streaming_cancelled is in BROADCAST_TYPES
|
|
148
|
+
// so every connected client sees it; it is also buffered for re-subscribers.
|
|
149
|
+
const ev = { type: 'streaming_cancelled', sessionId: sid, claudeSessionId: ctrl.claudeSessionId || null, agentId: ctrl.agentId || null, cancelled: true, timestamp: Date.now() };
|
|
150
|
+
recordTerminal(sid, ev);
|
|
151
|
+
broadcastSync(ev);
|
|
152
|
+
try { ctrl.proc?.kill?.(); } catch {}
|
|
153
|
+
activeChats.delete(sid);
|
|
154
|
+
broadcastSync({ type: 'chat_active_changed', reason: 'cancelled', sessionId: sid, agentId: ctrl.agentId || null, timestamp: Date.now() });
|
|
155
|
+
return { cancelled: true };
|
|
156
|
+
});
|
|
157
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import os from 'os';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { execSync, execFileSync } from 'child_process';
|
|
5
|
+
import { err, execFileP, resolveGitCwd, assertSafeRelPath, assertSafeBranch } from './shared.js';
|
|
6
|
+
|
|
7
|
+
export function register(router, deps) {
|
|
8
|
+
const { STARTUP_CWD } = deps;
|
|
9
|
+
|
|
10
|
+
router.handle('clone', (p) => {
|
|
11
|
+
const repo = (p.repo || '').trim();
|
|
12
|
+
if (!repo || !/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo)) {
|
|
13
|
+
err(400, 'Invalid repo format. Use org/repo or user/repo');
|
|
14
|
+
}
|
|
15
|
+
const cloneDir = STARTUP_CWD || os.homedir();
|
|
16
|
+
const repoName = repo.split('/')[1];
|
|
17
|
+
const targetPath = path.join(cloneDir, repoName);
|
|
18
|
+
if (fs.existsSync(targetPath)) err(409, `Directory already exists: ${repoName}`);
|
|
19
|
+
try {
|
|
20
|
+
execFileSync('git', ['clone', 'https://github.com/' + repo + '.git'], {
|
|
21
|
+
cwd: cloneDir, encoding: 'utf-8', timeout: 120000,
|
|
22
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
23
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
|
|
24
|
+
});
|
|
25
|
+
return { ok: true, repo, path: targetPath, name: repoName };
|
|
26
|
+
} catch (e) { err(500, (e.stderr || e.message || 'Clone failed').trim()); }
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
router.handle('git.check', () => {
|
|
30
|
+
try {
|
|
31
|
+
const isWindows = os.platform() === 'win32';
|
|
32
|
+
const devnull = isWindows ? '' : ' 2>/dev/null';
|
|
33
|
+
const remoteUrl = execSync('git remote get-url origin' + devnull, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows }).trim();
|
|
34
|
+
const statusResult = execSync('git status --porcelain' + devnull, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
|
|
35
|
+
const hasChanges = statusResult.trim().length > 0;
|
|
36
|
+
const unpushedResult = execSync('git rev-list --count --not --remotes' + devnull, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
|
|
37
|
+
const hasUnpushed = parseInt(unpushedResult.trim() || '0', 10) > 0;
|
|
38
|
+
const githubUser = process.env.GITHUB_USER;
|
|
39
|
+
const ownsRemote = !remoteUrl.includes('github.com/') || (!!githubUser && remoteUrl.includes(githubUser));
|
|
40
|
+
return { ownsRemote, hasChanges, hasUnpushed, remoteUrl };
|
|
41
|
+
} catch {
|
|
42
|
+
return { ownsRemote: false, hasChanges: false, hasUnpushed: false, remoteUrl: '' };
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
router.handle('git.push', (p) => {
|
|
47
|
+
if (!p?.confirm) err(400, 'confirm required: git.push commits and pushes the entire working tree');
|
|
48
|
+
try {
|
|
49
|
+
const isWindows = os.platform() === 'win32';
|
|
50
|
+
const cmd = isWindows
|
|
51
|
+
? 'git add -A & git commit -m "Auto-commit" & git push'
|
|
52
|
+
: 'git add -A && git commit -m "Auto-commit" && git push';
|
|
53
|
+
execSync(cmd, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
|
|
54
|
+
return { success: true };
|
|
55
|
+
} catch (e) { err(500, e.message); }
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// --- git.status: changed-file list (staged/unstaged/untracked) for
|
|
59
|
+
// GitStatusPanel. Porcelain=v1 line format "XY PATH" (rename: "XY OLD -> NEW"),
|
|
60
|
+
// X = index state, Y = worktree state, '?'/' ' = untouched/untracked.
|
|
61
|
+
router.handle('git.status', async (p) => {
|
|
62
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
63
|
+
try {
|
|
64
|
+
const { stdout } = await execFileP('git', ['status', '--porcelain=v1'], { cwd });
|
|
65
|
+
const files = [];
|
|
66
|
+
for (const line of stdout.split('\n')) {
|
|
67
|
+
if (!line) continue;
|
|
68
|
+
const x = line[0], y = line[1];
|
|
69
|
+
const filePath = line.slice(3);
|
|
70
|
+
if (x === '?' && y === '?') { files.push({ path: filePath, status: '?' }); continue; }
|
|
71
|
+
if (x !== ' ' && x !== '?') files.push({ path: filePath, status: x, staged: true });
|
|
72
|
+
else if (y !== ' ' && y !== '?') files.push({ path: filePath, status: y, staged: false });
|
|
73
|
+
}
|
|
74
|
+
return { files };
|
|
75
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git status failed').trim()); }
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// --- git.diff: unified diff for a single file or the whole working tree.
|
|
79
|
+
// p.cwd (optional) is confined via confineToRoots/fsAllowRoots, same as
|
|
80
|
+
// chat.sendMessage; p.file (optional) is validated to reject flags/shell
|
|
81
|
+
// metacharacters. execFile array-args form only, never a shell string.
|
|
82
|
+
router.handle('git.diff', async (p) => {
|
|
83
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
84
|
+
const args = ['diff', '--no-color'];
|
|
85
|
+
if (p?.staged) args.push('--staged');
|
|
86
|
+
if (p?.file) args.push('--', assertSafeRelPath(p.file, 'file'));
|
|
87
|
+
try {
|
|
88
|
+
const { stdout } = await execFileP('git', args, { cwd });
|
|
89
|
+
// git prints "Binary files a/x and b/x differ" for binary paths instead
|
|
90
|
+
// of a unified diff - an empty `diff` string then reads to the client as
|
|
91
|
+
// "no diff to show" with no explanation. Detect it so the UI can say why.
|
|
92
|
+
const binary = /^Binary files .* differ$/m.test(stdout);
|
|
93
|
+
return { diff: stdout, binary, file: p?.file || null, staged: !!p?.staged };
|
|
94
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git diff failed').trim()); }
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// --- git.log: recent commit list, limit param (default 20, capped 200).
|
|
98
|
+
router.handle('git.log', async (p) => {
|
|
99
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
100
|
+
const limit = Math.max(1, Math.min(200, parseInt(p?.limit, 10) || 20));
|
|
101
|
+
const FIELD_SEP = '\x1f';
|
|
102
|
+
const REC_SEP = '\x1e';
|
|
103
|
+
const args = ['log', `-n${limit}`, `--pretty=format:%H${FIELD_SEP}%an${FIELD_SEP}%ad${FIELD_SEP}%s${REC_SEP}`, '--date=iso-strict'];
|
|
104
|
+
try {
|
|
105
|
+
const { stdout } = await execFileP('git', args, { cwd });
|
|
106
|
+
const commits = stdout.split(REC_SEP).map(s => s.trim()).filter(Boolean).map(rec => {
|
|
107
|
+
const [hash, author, date, ...rest] = rec.split(FIELD_SEP);
|
|
108
|
+
return { hash, author, date, subject: rest.join(FIELD_SEP) };
|
|
109
|
+
});
|
|
110
|
+
return { commits };
|
|
111
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git log failed').trim()); }
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// --- worktree.list / create / remove ---
|
|
115
|
+
router.handle('worktree.list', async (p) => {
|
|
116
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
117
|
+
try {
|
|
118
|
+
const { stdout } = await execFileP('git', ['worktree', 'list', '--porcelain'], { cwd });
|
|
119
|
+
// Parse the porcelain block format: records separated by blank lines,
|
|
120
|
+
// each line "key value" or a bare flag ("bare", "detached", "locked").
|
|
121
|
+
const worktrees = [];
|
|
122
|
+
let cur = null;
|
|
123
|
+
for (const line of stdout.split('\n')) {
|
|
124
|
+
if (!line.trim()) { if (cur) { worktrees.push(cur); cur = null; } continue; }
|
|
125
|
+
if (!cur) cur = {};
|
|
126
|
+
const sp = line.indexOf(' ');
|
|
127
|
+
if (sp === -1) { cur[line] = true; continue; }
|
|
128
|
+
cur[line.slice(0, sp)] = line.slice(sp + 1);
|
|
129
|
+
}
|
|
130
|
+
if (cur) worktrees.push(cur);
|
|
131
|
+
return { worktrees: worktrees.map(w => ({ path: w.worktree || null, head: w.HEAD || null, branch: w.branch || null, bare: !!w.bare, detached: !!w.detached, locked: !!w.locked })) };
|
|
132
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git worktree list failed').trim()); }
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
router.handle('worktree.create', async (p) => {
|
|
136
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
137
|
+
const wtPath = assertSafeRelPath(p?.path, 'path');
|
|
138
|
+
const args = ['worktree', 'add'];
|
|
139
|
+
if (p?.newBranch) { args.push('-b', assertSafeBranch(p.newBranch, 'newBranch')); }
|
|
140
|
+
args.push(wtPath);
|
|
141
|
+
if (p?.branch) args.push(assertSafeBranch(p.branch, 'branch'));
|
|
142
|
+
try {
|
|
143
|
+
const { stdout, stderr } = await execFileP('git', args, { cwd });
|
|
144
|
+
return { ok: true, output: (stdout || stderr || '').trim(), path: wtPath };
|
|
145
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git worktree add failed').trim()); }
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
router.handle('worktree.remove', async (p) => {
|
|
149
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
150
|
+
const wtPath = assertSafeRelPath(p?.path, 'path');
|
|
151
|
+
const args = ['worktree', 'remove'];
|
|
152
|
+
if (p?.force) args.push('--force');
|
|
153
|
+
args.push(wtPath);
|
|
154
|
+
try {
|
|
155
|
+
const { stdout, stderr } = await execFileP('git', args, { cwd });
|
|
156
|
+
return { ok: true, output: (stdout || stderr || '').trim() };
|
|
157
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git worktree remove failed').trim()); }
|
|
158
|
+
});
|
|
159
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { err } from './shared.js';
|
|
5
|
+
|
|
6
|
+
export function register(router, deps) {
|
|
7
|
+
const { queries, wsOptimizer, getProviderConfigs, saveProviderConfig, STARTUP_CWD } = deps;
|
|
8
|
+
|
|
9
|
+
router.handle('home', () => ({ home: os.homedir(), cwd: STARTUP_CWD }));
|
|
10
|
+
|
|
11
|
+
router.handle('folders', (p) => {
|
|
12
|
+
const folderPath = p.path || STARTUP_CWD;
|
|
13
|
+
try {
|
|
14
|
+
const raw = folderPath.startsWith('~') ? folderPath.replace('~', os.homedir()) : folderPath;
|
|
15
|
+
const entries = fs.readdirSync(path.resolve(raw), { withFileTypes: true });
|
|
16
|
+
return { folders: entries.filter(e => e.isDirectory() && !e.name.startsWith('.')).map(e => ({ name: e.name })).sort((a, b) => a.name.localeCompare(b.name)) };
|
|
17
|
+
} catch (e) { err(400, e.message); }
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
router.handle('auth.configs', () => getProviderConfigs());
|
|
21
|
+
|
|
22
|
+
router.handle('auth.save', (p) => {
|
|
23
|
+
const { providerId, apiKey, defaultModel } = p;
|
|
24
|
+
if (typeof providerId !== 'string' || !providerId.length || providerId.length > 100) err(400, 'Invalid providerId');
|
|
25
|
+
if (typeof apiKey !== 'string' || !apiKey.length || apiKey.length > 10000) err(400, 'Invalid apiKey');
|
|
26
|
+
if (defaultModel !== undefined && (typeof defaultModel !== 'string' || defaultModel.length > 200)) err(400, 'Invalid defaultModel');
|
|
27
|
+
const configPath = saveProviderConfig(providerId, apiKey, defaultModel || '');
|
|
28
|
+
return { success: true, path: configPath };
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
router.handle('import.claude', () => ({ imported: queries.importClaudeCodeConversations() }));
|
|
32
|
+
|
|
33
|
+
router.handle('discover.claude', () => ({ discovered: queries.discoverClaudeCodeConversations() }));
|
|
34
|
+
|
|
35
|
+
router.handle('ws.stats', () => wsOptimizer.getStats());
|
|
36
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { execFile } from 'child_process';
|
|
2
|
+
import { confineToRoots, fsAllowRoots } from '../http-handler.js';
|
|
3
|
+
|
|
4
|
+
export function err(code, message) { const e = new Error(message); e.code = code; throw e; }
|
|
5
|
+
|
|
6
|
+
// Promisified execFile — array-args form only, never a shell string, so a
|
|
7
|
+
// crafted branch/path/file value cannot be interpreted as a shell command.
|
|
8
|
+
export function execFileP(cmd, args, opts) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
execFile(cmd, args, { encoding: 'utf-8', timeout: 30000, maxBuffer: 20 * 1024 * 1024, ...opts }, (e, stdout, stderr) => {
|
|
11
|
+
if (e) { e.stdout = stdout; e.stderr = stderr; reject(e); return; }
|
|
12
|
+
resolve({ stdout, stderr });
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Resolve + confine a client-supplied cwd to the same allowlist the file
|
|
18
|
+
// explorer / chat.sendMessage use (fsAllowRoots via confineToRoots). Falls
|
|
19
|
+
// back to STARTUP_CWD (itself an allowed root) when no cwd is given.
|
|
20
|
+
export function resolveGitCwd(p, STARTUP_CWD) {
|
|
21
|
+
if (!p?.cwd) return STARTUP_CWD;
|
|
22
|
+
const conf = confineToRoots(p.cwd, fsAllowRoots());
|
|
23
|
+
if (!conf.ok) err(conf.reason === 'not found' ? 400 : 403, `cwd outside allowed roots: ${p.cwd}`);
|
|
24
|
+
return conf.realPath;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// A relative in-repo file path: no leading '-' (flag injection), no shell
|
|
28
|
+
// metacharacters, no absolute path (git resolves it relative to cwd already).
|
|
29
|
+
const SAFE_REL_PATH_RE = /^[^\0]{1,4096}$/;
|
|
30
|
+
export function assertSafeRelPath(v, label) {
|
|
31
|
+
if (typeof v !== 'string' || !v.length) err(400, `${label} required`);
|
|
32
|
+
if (v.startsWith('-')) err(400, `${label} must not start with '-'`);
|
|
33
|
+
if (/[\0]/.test(v)) err(400, `${label} contains invalid characters`);
|
|
34
|
+
if (!SAFE_REL_PATH_RE.test(v)) err(400, `${label} invalid`);
|
|
35
|
+
return v;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// A git branch/ref name — conservative allowlist (git's own ref-format is
|
|
39
|
+
// more permissive, but this blocks every shell-metacharacter and flag-
|
|
40
|
+
// injection vector while still covering normal branch names).
|
|
41
|
+
const SAFE_BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9_.\/-]{0,199}$/;
|
|
42
|
+
export function assertSafeBranch(v, label) {
|
|
43
|
+
if (typeof v !== 'string' || !v.length) err(400, `${label} required`);
|
|
44
|
+
if (v.startsWith('-') || v.includes('..') || v.includes('//')) err(400, `${label} invalid`);
|
|
45
|
+
if (!SAFE_BRANCH_RE.test(v)) err(400, `${label} invalid`);
|
|
46
|
+
return v;
|
|
47
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Short-lived per-session terminal-event buffer (finding 35): a turn that
|
|
2
|
+
// completes/errors/cancels while a client ws is down would otherwise be a
|
|
3
|
+
// fire-and-forget broadcast the client never sees, hanging it busy forever.
|
|
4
|
+
// A re-subscribing client gets the buffered terminal frame replayed.
|
|
5
|
+
const TERMINAL_TTL_MS = 60000;
|
|
6
|
+
const terminalEvents = new Map(); // sessionId -> terminal event
|
|
7
|
+
|
|
8
|
+
export function recordTerminal(sessionId, event) {
|
|
9
|
+
terminalEvents.set(sessionId, event);
|
|
10
|
+
const t = setTimeout(() => {
|
|
11
|
+
if (terminalEvents.get(sessionId) === event) terminalEvents.delete(sessionId);
|
|
12
|
+
}, TERMINAL_TTL_MS);
|
|
13
|
+
if (typeof t.unref === 'function') t.unref();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function getTerminal(sessionId) { return terminalEvents.get(sessionId); }
|