agentgui 1.0.1126 → 1.0.1127
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.
Potentially problematic release.
This version of agentgui might be problematic. Click here for more details.
- package/.gm/browser-config.json +1 -0
- package/.gm/disciplines/agentgui/mem-1779277005143-0-1352.json +1 -0
- package/.gm/disciplines/agentgui/memories/.flat-export-done +0 -0
- package/.gm/disciplines/agentgui/memories/mem-c07fa3b0836edbe2-1352.md +8 -0
- package/.gm/gm.db +0 -0
- package/.gm/memories/.flat-export-done +1 -0
- package/.gm/memories/mem-0131ff4869d86085-370.md +10 -0
- package/.gm/memories/mem-04049d11cb8c1661-2135.md +8 -0
- package/.gm/memories/mem-069ff10372ed1770-1375.md +8 -0
- package/.gm/memories/mem-08a4a9e050a4deff-3048.md +8 -0
- package/.gm/memories/mem-09597ee0df9c9224-965.md +8 -0
- package/.gm/memories/mem-0993d156f571b619-1059.md +8 -0
- package/.gm/memories/mem-0b681bf2340c8df1-3170.md +8 -0
- package/.gm/memories/mem-0c444abde86202f6-1681.md +8 -0
- package/.gm/memories/mem-0d1408fa048b9923-1159.md +8 -0
- package/.gm/memories/mem-0dad5d82fec829ba-887.md +8 -0
- package/.gm/memories/mem-10a776effb7ce3a6-935.md +8 -0
- package/.gm/memories/mem-10d264b4f8e66fb4-1492.md +8 -0
- package/.gm/memories/mem-118c35ac67541d98-2909.md +8 -0
- package/.gm/memories/mem-119cf70dd19aa0a5-2225.md +8 -0
- package/.gm/memories/mem-15a07cd761b337c4-4320.md +8 -0
- package/.gm/memories/mem-15c73aca528535cb-2183.md +8 -0
- package/.gm/memories/mem-166f52796185e0e7-1487.md +8 -0
- package/.gm/memories/mem-1a148cf9c3126df5-3963.md +8 -0
- package/.gm/memories/mem-1a459001058f618e-567.md +8 -0
- package/.gm/memories/mem-1af3e13f7618e668-2146.md +8 -0
- package/.gm/memories/mem-1fd31d6873e9c164-794.md +8 -0
- package/.gm/memories/mem-21f551be092fd77d-2340.md +8 -0
- package/.gm/memories/mem-231ff5de003f20f0-586.md +8 -0
- package/.gm/memories/mem-2567393d3adb03ab-347.md +8 -0
- package/.gm/memories/mem-27faf41cdd050c80-1261.md +8 -0
- package/.gm/memories/mem-28889e43e8ce64cc-3663.md +8 -0
- package/.gm/memories/mem-2f4fd06515abf439-2562.md +8 -0
- package/.gm/memories/mem-34a749430303c5f7-544.md +8 -0
- package/.gm/memories/mem-3602d11d7bce9446-1057.md +8 -0
- package/.gm/memories/mem-38b7e24dbcba2f3e-639.md +8 -0
- package/.gm/memories/mem-39a7cc2f887a90b1-1079.md +8 -0
- package/.gm/memories/mem-40d6169c8759061d-806.md +8 -0
- package/.gm/memories/mem-4420e6d00e5c8632-2318.md +8 -0
- package/.gm/memories/mem-447e5a54ddc9357a-654.md +8 -0
- package/.gm/memories/mem-455b3beb4afabe14-591.md +8 -0
- package/.gm/memories/mem-4845ee594759151c-560.md +8 -0
- package/.gm/memories/mem-4a1254c60b868b88-374.md +8 -0
- package/.gm/memories/mem-4bafafa47a0e4b6c-3237.md +8 -0
- package/.gm/memories/mem-4c06c45b4d31bc60-1202.md +8 -0
- package/.gm/memories/mem-4dfac801d0378448-3676.md +8 -0
- package/.gm/memories/mem-4ecd3b713e384170-122.md +10 -0
- package/.gm/memories/mem-51d8992a3c6f6c9c-1073.md +8 -0
- package/.gm/memories/mem-539eee7e8c6c10ee-2557.md +8 -0
- package/.gm/memories/mem-559b8b2abc4b1091-1665.md +8 -0
- package/.gm/memories/mem-59dd73a463e54948-871.md +8 -0
- package/.gm/memories/mem-5b99b882ffe1a3c2-2262.md +8 -0
- package/.gm/memories/mem-5feb252a5244149c-1791.md +8 -0
- package/.gm/memories/mem-6224f8d185797f2b-1047.md +8 -0
- package/.gm/memories/mem-6434ee8261a6a6a2-3126.md +8 -0
- package/.gm/memories/mem-66b0947b946f3437-1155.md +8 -0
- package/.gm/memories/mem-6bdf783a1f6be7c2-1062.md +8 -0
- package/.gm/memories/mem-6d49f08bebac54c9-744.md +8 -0
- package/.gm/memories/mem-70d96acb736af2d7-685.md +8 -0
- package/.gm/memories/mem-70de7d5e71fcd439-2680.md +8 -0
- package/.gm/memories/mem-713614f12d7029da-1577.md +8 -0
- package/.gm/memories/mem-720d76c88e64f6ee-1967.md +8 -0
- package/.gm/memories/mem-7535f34f430fc196-1340.md +8 -0
- package/.gm/memories/mem-861a588d2773681a-1311.md +8 -0
- package/.gm/memories/mem-8af7980a92e09959-891.md +8 -0
- package/.gm/memories/mem-8b438ef4c609b7af-401.md +8 -0
- package/.gm/memories/mem-8f59884039787ef3-743.md +8 -0
- package/.gm/memories/mem-92b199c2024ee1aa-2513.md +8 -0
- package/.gm/memories/mem-9329105b05b9c0f6-324.md +10 -0
- package/.gm/memories/mem-94f30cec3c283f97-782.md +10 -0
- package/.gm/memories/mem-956d4813319f65a3-1710.md +8 -0
- package/.gm/memories/mem-96fffbb6615e031b-1263.md +8 -0
- package/.gm/memories/mem-993ab31f7a10aefa-718.md +8 -0
- package/.gm/memories/mem-a3e440db285f655a-995.md +8 -0
- package/.gm/memories/mem-a52933cd6495e6f5-2624.md +8 -0
- package/.gm/memories/mem-a86426ac44138c96-1606.md +8 -0
- package/.gm/memories/mem-a95b1d49d71133ce-1007.md +8 -0
- package/.gm/memories/mem-a9968a186368b022-1150.md +8 -0
- package/.gm/memories/mem-aaeae38d8eb01809-1076.md +8 -0
- package/.gm/memories/mem-ade01d9c02677c55-1557.md +8 -0
- package/.gm/memories/mem-b06b8c85b81663e6-1250.md +8 -0
- package/.gm/memories/mem-b451e5e17e555202-1490.md +8 -0
- package/.gm/memories/mem-b64ad00dcb6f909e-937.md +8 -0
- package/.gm/memories/mem-b7d6018ceca55b6f-2220.md +8 -0
- package/.gm/memories/mem-bdf466854032cac9-1509.md +8 -0
- package/.gm/memories/mem-c0482039e6ab4c50-2047.md +8 -0
- package/.gm/memories/mem-c4aaec5c4e6f80c2-920.md +8 -0
- package/.gm/memories/mem-c66976ddacb4fbe8-1454.md +8 -0
- package/.gm/memories/mem-c7c5bc263850c332-1844.md +8 -0
- package/.gm/memories/mem-cda639547932c796-713.md +8 -0
- package/.gm/memories/mem-cdf04ff6a6a0aa6f-671.md +8 -0
- package/.gm/memories/mem-cf8472c84d9e04c4-1883.md +8 -0
- package/.gm/memories/mem-cfd4d894370c63c3-1288.md +8 -0
- package/.gm/memories/mem-d060480435f92eec-1146.md +8 -0
- package/.gm/memories/mem-d347c921b79e6d44-1099.md +8 -0
- package/.gm/memories/mem-d3c8ea6c861bfbb8-1457.md +8 -0
- package/.gm/memories/mem-d5e928c552cd87f9-214.md +10 -0
- package/.gm/memories/mem-d63bc3b8a0269844-406.md +10 -0
- package/.gm/memories/mem-d9c19257abc2fa5e-1061.md +8 -0
- package/.gm/memories/mem-d9f26358a7cd3bb8-866.md +8 -0
- package/.gm/memories/mem-da1c91acf63d81d3-863.md +8 -0
- package/.gm/memories/mem-dc1ac3b04d22317e-664.md +8 -0
- package/.gm/memories/mem-dceeae20bc56d407-711.md +8 -0
- package/.gm/memories/mem-dd98b21c0896dc04-1557.md +8 -0
- package/.gm/memories/mem-df74674eec7745ac-178.md +10 -0
- package/.gm/memories/mem-dfe3b466fd5d1199-802.md +8 -0
- package/.gm/memories/mem-e0f9286aed2d5a06-1116.md +8 -0
- package/.gm/memories/mem-e1950b064099b7be-1895.md +8 -0
- package/.gm/memories/mem-e1d5431ae2542872-961.md +8 -0
- package/.gm/memories/mem-e490a181de6469fc-487.md +8 -0
- package/.gm/memories/mem-e72c6efbb27326fb-392.md +8 -0
- package/.gm/memories/mem-e943b58115a02b4c-593.md +8 -0
- package/.gm/memories/mem-e9bc5f9ed6edbcf7-1580.md +8 -0
- package/.gm/memories/mem-eae1e383927854fb-2649.md +8 -0
- package/.gm/memories/mem-ebbe6c0694c526f0-1392.md +8 -0
- package/.gm/memories/mem-ebf85becc23410b0-1633.md +8 -0
- package/.gm/memories/mem-ee0596fa17c7102e-362.md +10 -0
- package/.gm/memories/mem-ee4450fbc311b583-1361.md +8 -0
- package/.gm/memories/mem-ee8858162518f144-1252.md +8 -0
- package/.gm/memories/mem-f3297e82df622649-1166.md +8 -0
- package/.gm/memories/mem-f3f317c083d979ee-1210.md +8 -0
- package/.gm/memories/mem-f714a86465fba158-2041.md +8 -0
- package/.gm/memories/mem-f786bc1626d92845-204.md +10 -0
- package/.gm/memories/mem-f9f0dc8895b21e18-1217.md +8 -0
- package/.gm/memories/mem-fb3b2a7395800041-525.md +8 -0
- package/.gm/memories/mem-fc5753f92ee7d654-966.md +8 -0
- package/.gm/memories/mem-fe3faa1652f07239-480.md +8 -0
- package/.gm/memories/mem-ff8669e527e5c427-2788.md +8 -0
- package/.gm/mutables.yml +53 -0
- package/.gm/prd.yml +3342 -1
- package/AGENTS.md +122 -122
- package/UX_OPTIMIZATION_SUMMARY.md +238 -0
- 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 +28 -0
- package/database.js +110 -109
- package/design-reference.png +0 -0
- package/lib/acp-sdk-manager.js +9 -42
- package/lib/claude-runner-acp.js +155 -213
- package/lib/claude-runner-agents.js +157 -170
- package/lib/http-handler.js +931 -400
- package/lib/ws-handlers-util.js +466 -11
- package/package.json +1 -1
- package/site/app/js/app.js +4741 -4221
- package/site/app/js/backend.js +602 -621
- package/site/app/vendor/anentrypoint-design/247420.css +13673 -14799
- package/site/app/vendor/anentrypoint-design/247420.js +449 -735
- package/.gm/.embed-generation.code_chunks +0 -1
- package/.gm/.embed-generation.git_commit_vectors +0 -1
- package/.gm/.embed-generation.memories +0 -1
- package/.gm/.embed-generation.rssearch_vectors +0 -1
- package/lib/acp-http-protocol.js +0 -95
- package/lib/http-routes/mutations.js +0 -199
- package/lib/http-routes/reads.js +0 -212
- package/lib/http-routes/shared.js +0 -225
- package/lib/ws-handlers/agents.js +0 -137
- package/lib/ws-handlers/chat.js +0 -157
- package/lib/ws-handlers/git.js +0 -159
- package/lib/ws-handlers/misc.js +0 -36
- package/lib/ws-handlers/shared.js +0 -47
- package/lib/ws-handlers/terminal-state.js +0 -16
- package/site/app/js/chat-persistence.js +0 -123
- package/site/app/js/hash-routing.js +0 -62
- package/site/app/js/history.js +0 -435
- package/site/app/js/shortcuts.js +0 -128
package/lib/ws-handlers-util.js
CHANGED
|
@@ -1,11 +1,466 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import crypto from 'crypto';
|
|
5
|
+
import { execSync, spawnSync, execFile } from 'child_process';
|
|
6
|
+
import { runClaudeWithStreaming } from './claude-runner-run.js';
|
|
7
|
+
import { registry } from './claude-runner-agents.js';
|
|
8
|
+
import { confineToRoots, fsAllowRoots } from './http-handler.js';
|
|
9
|
+
import { restart as restartAcpAgent } from './acp-sdk-manager.js';
|
|
10
|
+
|
|
11
|
+
function err(code, message) { const e = new Error(message); e.code = code; throw e; }
|
|
12
|
+
|
|
13
|
+
// Promisified execFile — array-args form only, never a shell string, so a
|
|
14
|
+
// crafted branch/path/file value cannot be interpreted as a shell command.
|
|
15
|
+
function execFileP(cmd, args, opts) {
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
execFile(cmd, args, { encoding: 'utf-8', timeout: 30000, maxBuffer: 20 * 1024 * 1024, ...opts }, (e, stdout, stderr) => {
|
|
18
|
+
if (e) { e.stdout = stdout; e.stderr = stderr; reject(e); return; }
|
|
19
|
+
resolve({ stdout, stderr });
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Resolve + confine a client-supplied cwd to the same allowlist the file
|
|
25
|
+
// explorer / chat.sendMessage use (fsAllowRoots via confineToRoots). Falls
|
|
26
|
+
// back to STARTUP_CWD (itself an allowed root) when no cwd is given.
|
|
27
|
+
function resolveGitCwd(p, STARTUP_CWD) {
|
|
28
|
+
if (!p?.cwd) return STARTUP_CWD;
|
|
29
|
+
const conf = confineToRoots(p.cwd, fsAllowRoots());
|
|
30
|
+
if (!conf.ok) err(conf.reason === 'not found' ? 400 : 403, `cwd outside allowed roots: ${p.cwd}`);
|
|
31
|
+
return conf.realPath;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// A relative in-repo file path: no leading '-' (flag injection), no shell
|
|
35
|
+
// metacharacters, no absolute path (git resolves it relative to cwd already).
|
|
36
|
+
const SAFE_REL_PATH_RE = /^[^\0]{1,4096}$/;
|
|
37
|
+
function assertSafeRelPath(v, label) {
|
|
38
|
+
if (typeof v !== 'string' || !v.length) err(400, `${label} required`);
|
|
39
|
+
if (v.startsWith('-')) err(400, `${label} must not start with '-'`);
|
|
40
|
+
if (/[\0]/.test(v)) err(400, `${label} contains invalid characters`);
|
|
41
|
+
if (!SAFE_REL_PATH_RE.test(v)) err(400, `${label} invalid`);
|
|
42
|
+
return v;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// A git branch/ref name — conservative allowlist (git's own ref-format is
|
|
46
|
+
// more permissive, but this blocks every shell-metacharacter and flag-
|
|
47
|
+
// injection vector while still covering normal branch names).
|
|
48
|
+
const SAFE_BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9_.\/-]{0,199}$/;
|
|
49
|
+
function assertSafeBranch(v, label) {
|
|
50
|
+
if (typeof v !== 'string' || !v.length) err(400, `${label} required`);
|
|
51
|
+
if (v.startsWith('-') || v.includes('..') || v.includes('//')) err(400, `${label} invalid`);
|
|
52
|
+
if (!SAFE_BRANCH_RE.test(v)) err(400, `${label} invalid`);
|
|
53
|
+
return v;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const SUB_AGENT_MAP = {
|
|
57
|
+
'opencode': [{ id: 'gm-oc', name: 'GM OpenCode' }], 'cli-opencode': [{ id: 'gm-oc', name: 'GM OpenCode' }],
|
|
58
|
+
'gemini': [{ id: 'gm-gc', name: 'GM Gemini' }], 'cli-gemini': [{ id: 'gm-gc', name: 'GM Gemini' }],
|
|
59
|
+
'kilo': [{ id: 'gm-kilo', name: 'GM Kilo' }], 'cli-kilo': [{ id: 'gm-kilo', name: 'GM Kilo' }],
|
|
60
|
+
'codex': [], 'cli-codex': []
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export function register(router, deps) {
|
|
64
|
+
const { queries, wsOptimizer, broadcastSync, getProviderConfigs, saveProviderConfig, STARTUP_CWD, discoveredAgents, subscriptionIndex, activeChats, getModelsForAgent } = deps;
|
|
65
|
+
|
|
66
|
+
// Short-lived per-session terminal-event buffer (finding 35): a turn that
|
|
67
|
+
// completes/errors/cancels while a client ws is down would otherwise be a
|
|
68
|
+
// fire-and-forget broadcast the client never sees, hanging it busy forever.
|
|
69
|
+
// A re-subscribing client gets the buffered terminal frame replayed.
|
|
70
|
+
const TERMINAL_TTL_MS = 60000;
|
|
71
|
+
const terminalEvents = new Map(); // sessionId -> terminal event
|
|
72
|
+
function recordTerminal(sessionId, event) {
|
|
73
|
+
terminalEvents.set(sessionId, event);
|
|
74
|
+
const t = setTimeout(() => {
|
|
75
|
+
if (terminalEvents.get(sessionId) === event) terminalEvents.delete(sessionId);
|
|
76
|
+
}, TERMINAL_TTL_MS);
|
|
77
|
+
if (typeof t.unref === 'function') t.unref();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// --- agents.list: enumerate registered ACP agents + claude-code ---
|
|
81
|
+
router.handle('agents.list', () => {
|
|
82
|
+
const agents = registry.list().map(a => ({
|
|
83
|
+
id: a.id,
|
|
84
|
+
name: a.name,
|
|
85
|
+
protocol: a.protocol,
|
|
86
|
+
supportsStdin: !!a.supportsStdin,
|
|
87
|
+
features: a.supportedFeatures || [],
|
|
88
|
+
available: registry.isAvailable(a.id),
|
|
89
|
+
npxInstallable: !!a.npxPackage,
|
|
90
|
+
// The CLI binary name a manual (non-npx) install would need - lets the
|
|
91
|
+
// settings panel say what to install instead of just "not installed".
|
|
92
|
+
cmd: a.command || null,
|
|
93
|
+
}));
|
|
94
|
+
return { agents };
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// --- agents.models: model choices for a given agent ---
|
|
98
|
+
router.handle('agents.models', async (p) => {
|
|
99
|
+
const id = p?.id || p?.agentId;
|
|
100
|
+
if (!id) err(400, 'agent id required');
|
|
101
|
+
if (id === 'claude-code') {
|
|
102
|
+
return { models: [
|
|
103
|
+
{ id: 'sonnet', name: 'Claude Sonnet (latest)' },
|
|
104
|
+
{ id: 'opus', name: 'Claude Opus (latest)' },
|
|
105
|
+
{ id: 'haiku', name: 'Claude Haiku (latest)' },
|
|
106
|
+
] };
|
|
107
|
+
}
|
|
108
|
+
// Other agents: discover their models via getModelsForAgent (queries the
|
|
109
|
+
// running ACP server). Fail closed to an empty list on any error or when
|
|
110
|
+
// the dep isn't a function.
|
|
111
|
+
if (typeof getModelsForAgent === 'function') {
|
|
112
|
+
try {
|
|
113
|
+
const raw = await getModelsForAgent(id);
|
|
114
|
+
const list = Array.isArray(raw) ? raw : (raw?.models || []);
|
|
115
|
+
return { models: list.map(m => ({ id: m.id, name: m.name || m.label || m.id })) };
|
|
116
|
+
} catch { return { models: [] }; }
|
|
117
|
+
}
|
|
118
|
+
return { models: [] };
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// --- conversation.subscribe: register this ws for sessionId broadcasts ---
|
|
122
|
+
router.handle('conversation.subscribe', (p, ws) => {
|
|
123
|
+
const sid = p?.sessionId;
|
|
124
|
+
if (!sid || typeof sid !== 'string') err(400, 'sessionId required');
|
|
125
|
+
if (!subscriptionIndex.has(sid)) subscriptionIndex.set(sid, new Set());
|
|
126
|
+
subscriptionIndex.get(sid).add(ws);
|
|
127
|
+
ws.subscriptions = ws.subscriptions || new Set();
|
|
128
|
+
ws.subscriptions.add(sid);
|
|
129
|
+
// Replay a buffered terminal frame (complete/error/cancelled) so a client
|
|
130
|
+
// that re-subscribes after a ws drop learns the turn already ended.
|
|
131
|
+
const term = terminalEvents.get(sid);
|
|
132
|
+
if (term) { try { wsOptimizer.sendToClient(ws, { ...term, replayed: true }); } catch {} }
|
|
133
|
+
return { subscribed: true, sessionId: sid, replayedTerminal: !!term };
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// --- chat.sendMessage: start a one-shot streaming chat with an agent.
|
|
137
|
+
// Bypasses the gutted db-queries layer entirely; calls runClaudeWithStreaming
|
|
138
|
+
// directly and broadcasts streaming_* events scoped to an ephemeral sessionId.
|
|
139
|
+
router.handle('chat.sendMessage', async (p, ws) => {
|
|
140
|
+
let content = (p?.content || '').toString();
|
|
141
|
+
if (!content) err(400, 'content required');
|
|
142
|
+
const agentId = p?.agentId || 'claude-code';
|
|
143
|
+
// For non-resume agents (not claude-code which uses --resume), prepend prior
|
|
144
|
+
// conversation turns so the agent has context. claude-code handles multi-turn
|
|
145
|
+
// natively via resumeSessionId; direct runners (agy, etc.) get a preamble.
|
|
146
|
+
const priorMessages = Array.isArray(p?.messages) ? p.messages.filter(m => m?.role && m?.content) : [];
|
|
147
|
+
if (agentId !== 'claude-code' && !p?.resumeSid && !p?.resumeSessionId && priorMessages.length > 0) {
|
|
148
|
+
const preamble = priorMessages.map(m => (m.role === 'user' ? 'User: ' : 'Assistant: ') + (m.content || '').trim()).join('\n\n');
|
|
149
|
+
content = '[Prior conversation]\n' + preamble + '\n\n[Current message]\n' + content;
|
|
150
|
+
}
|
|
151
|
+
const model = p?.model || undefined;
|
|
152
|
+
const subAgent = p?.subAgent || undefined;
|
|
153
|
+
const cwd = p?.cwd || STARTUP_CWD;
|
|
154
|
+
const resumeSessionId = p?.resumeSid || p?.resumeSessionId || undefined;
|
|
155
|
+
if (!registry.has(agentId)) err(404, `Unknown agentId: ${agentId}`);
|
|
156
|
+
// A client-supplied cwd must be confined to the SAME allowlist as the Files
|
|
157
|
+
// routes (fsAllowRoots) - an unconfined cwd would let a client spawn the
|
|
158
|
+
// agent CLI anywhere on disk. Use the realpath-resolved value as the spawn
|
|
159
|
+
// cwd (defeats symlink escape, same as the HTTP file routes). No p.cwd ->
|
|
160
|
+
// STARTUP_CWD, which is itself an allowed root, so it needs no check.
|
|
161
|
+
let spawnCwd = STARTUP_CWD;
|
|
162
|
+
if (p?.cwd) {
|
|
163
|
+
const conf = confineToRoots(cwd, fsAllowRoots());
|
|
164
|
+
if (!conf.ok) err(conf.reason === 'not found' ? 400 : 403, `cwd outside allowed roots: ${cwd}`);
|
|
165
|
+
spawnCwd = conf.realPath;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const sessionId = 'chat-' + crypto.randomBytes(8).toString('hex');
|
|
169
|
+
// Auto-subscribe the originating ws so it receives its own broadcasts.
|
|
170
|
+
if (!subscriptionIndex.has(sessionId)) subscriptionIndex.set(sessionId, new Set());
|
|
171
|
+
subscriptionIndex.get(sessionId).add(ws);
|
|
172
|
+
ws.subscriptions = ws.subscriptions || new Set();
|
|
173
|
+
ws.subscriptions.add(sessionId);
|
|
174
|
+
|
|
175
|
+
const ctrl = { aborted: false, proc: null, agentId, model, cwd: spawnCwd, startedAt: Date.now() };
|
|
176
|
+
activeChats.set(sessionId, ctrl);
|
|
177
|
+
// Push-driven hint so clients refresh active-session state without
|
|
178
|
+
// waiting for the 3s chat.active poll (finding 48).
|
|
179
|
+
broadcastSync({ type: 'chat_active_changed', reason: 'started', sessionId, agentId, timestamp: Date.now() });
|
|
180
|
+
|
|
181
|
+
// Fire-and-forget. Errors broadcast as streaming_error.
|
|
182
|
+
(async () => {
|
|
183
|
+
let eventCount = 0;
|
|
184
|
+
broadcastSync({ type: 'streaming_start', sessionId, agentId, timestamp: Date.now() });
|
|
185
|
+
let claudeSessionBroadcast = false;
|
|
186
|
+
const onEvent = (parsed) => {
|
|
187
|
+
eventCount++;
|
|
188
|
+
// Surface claude's REAL session id (from the stream) once, so the client
|
|
189
|
+
// can --resume this conversation on its next turn. The ephemeral
|
|
190
|
+
// 'chat-...' sessionId is not a claude session id and cannot be resumed.
|
|
191
|
+
if (!claudeSessionBroadcast && parsed?.session_id) {
|
|
192
|
+
claudeSessionBroadcast = true;
|
|
193
|
+
ctrl.claudeSessionId = parsed.session_id;
|
|
194
|
+
broadcastSync({ type: 'streaming_session', sessionId, claudeSessionId: parsed.session_id, agentId, timestamp: Date.now() });
|
|
195
|
+
}
|
|
196
|
+
if (parsed?.type === 'assistant' && parsed.message?.content) {
|
|
197
|
+
for (const block of parsed.message.content) {
|
|
198
|
+
broadcastSync({ type: 'streaming_progress', sessionId, block, blockRole: 'assistant', seq: eventCount, timestamp: Date.now() });
|
|
199
|
+
}
|
|
200
|
+
} else if (parsed?.type === 'user' && parsed.message?.content) {
|
|
201
|
+
const blocks = Array.isArray(parsed.message.content) ? parsed.message.content : [];
|
|
202
|
+
for (const block of blocks) {
|
|
203
|
+
if (block?.type === 'tool_result') {
|
|
204
|
+
broadcastSync({ type: 'streaming_progress', sessionId, block, blockRole: 'tool_result', seq: eventCount, timestamp: Date.now() });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
} else if (parsed?.type === 'result') {
|
|
208
|
+
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 };
|
|
209
|
+
broadcastSync({ type: 'streaming_progress', sessionId, block, blockRole: 'result', seq: eventCount, isResult: true, timestamp: Date.now() });
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
try {
|
|
213
|
+
const config = {
|
|
214
|
+
verbose: true, outputFormat: 'stream-json', timeout: 1800000, print: true,
|
|
215
|
+
model, subAgent, onEvent, resumeSessionId,
|
|
216
|
+
onPid: () => {}, onProcess: (proc) => { ctrl.proc = proc; },
|
|
217
|
+
};
|
|
218
|
+
await runClaudeWithStreaming(content, spawnCwd, agentId, config);
|
|
219
|
+
if (!ctrl.aborted) {
|
|
220
|
+
const ev = { type: 'streaming_complete', sessionId, claudeSessionId: ctrl.claudeSessionId || null, agentId, eventCount, timestamp: Date.now() };
|
|
221
|
+
recordTerminal(sessionId, ev);
|
|
222
|
+
broadcastSync(ev);
|
|
223
|
+
}
|
|
224
|
+
} catch (e) {
|
|
225
|
+
if (!ctrl.aborted) {
|
|
226
|
+
const ev = { type: 'streaming_error', sessionId, claudeSessionId: ctrl.claudeSessionId || null, agentId, error: e.message || String(e), recoverable: false, timestamp: Date.now() };
|
|
227
|
+
recordTerminal(sessionId, ev);
|
|
228
|
+
broadcastSync(ev);
|
|
229
|
+
}
|
|
230
|
+
} finally {
|
|
231
|
+
activeChats.delete(sessionId);
|
|
232
|
+
broadcastSync({ type: 'chat_active_changed', reason: 'ended', sessionId, agentId, timestamp: Date.now() });
|
|
233
|
+
}
|
|
234
|
+
})();
|
|
235
|
+
|
|
236
|
+
return { sessionId, started: true };
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
// --- chat.active: list in-flight chats started via this server ---
|
|
240
|
+
router.handle('chat.active', () => {
|
|
241
|
+
const sessions = [];
|
|
242
|
+
for (const [sid, c] of activeChats) {
|
|
243
|
+
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 });
|
|
244
|
+
}
|
|
245
|
+
return { sessions };
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
// --- chat.cancel: abort an in-flight chat ---
|
|
249
|
+
router.handle('chat.cancel', (p) => {
|
|
250
|
+
const sid = p?.sessionId;
|
|
251
|
+
if (!sid) err(400, 'sessionId required');
|
|
252
|
+
const ctrl = activeChats.get(sid);
|
|
253
|
+
if (!ctrl) return { cancelled: false, reason: 'not-found' };
|
|
254
|
+
ctrl.aborted = true;
|
|
255
|
+
// Broadcast the terminal 'cancelled' frame BEFORE killing the proc so a
|
|
256
|
+
// remote cancellation (other tab, dashboard stop-all) does not read as a
|
|
257
|
+
// normal completion (finding 44). streaming_cancelled is in BROADCAST_TYPES
|
|
258
|
+
// so every connected client sees it; it is also buffered for re-subscribers.
|
|
259
|
+
const ev = { type: 'streaming_cancelled', sessionId: sid, claudeSessionId: ctrl.claudeSessionId || null, agentId: ctrl.agentId || null, cancelled: true, timestamp: Date.now() };
|
|
260
|
+
recordTerminal(sid, ev);
|
|
261
|
+
broadcastSync(ev);
|
|
262
|
+
try { ctrl.proc?.kill?.(); } catch {}
|
|
263
|
+
activeChats.delete(sid);
|
|
264
|
+
broadcastSync({ type: 'chat_active_changed', reason: 'cancelled', sessionId: sid, agentId: ctrl.agentId || null, timestamp: Date.now() });
|
|
265
|
+
return { cancelled: true };
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
router.handle('home', () => ({ home: os.homedir(), cwd: STARTUP_CWD }));
|
|
271
|
+
|
|
272
|
+
router.handle('folders', (p) => {
|
|
273
|
+
const folderPath = p.path || STARTUP_CWD;
|
|
274
|
+
try {
|
|
275
|
+
const raw = folderPath.startsWith('~') ? folderPath.replace('~', os.homedir()) : folderPath;
|
|
276
|
+
const entries = fs.readdirSync(path.resolve(raw), { withFileTypes: true });
|
|
277
|
+
return { folders: entries.filter(e => e.isDirectory() && !e.name.startsWith('.')).map(e => ({ name: e.name })).sort((a, b) => a.name.localeCompare(b.name)) };
|
|
278
|
+
} catch (e) { err(400, e.message); }
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
router.handle('clone', (p) => {
|
|
282
|
+
const repo = (p.repo || '').trim();
|
|
283
|
+
if (!repo || !/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo)) {
|
|
284
|
+
err(400, 'Invalid repo format. Use org/repo or user/repo');
|
|
285
|
+
}
|
|
286
|
+
const cloneDir = STARTUP_CWD || os.homedir();
|
|
287
|
+
const repoName = repo.split('/')[1];
|
|
288
|
+
const targetPath = path.join(cloneDir, repoName);
|
|
289
|
+
if (fs.existsSync(targetPath)) err(409, `Directory already exists: ${repoName}`);
|
|
290
|
+
try {
|
|
291
|
+
const isWindows = os.platform() === 'win32';
|
|
292
|
+
execSync('git clone https://github.com/' + repo + '.git', {
|
|
293
|
+
cwd: cloneDir, encoding: 'utf-8', timeout: 120000,
|
|
294
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
295
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
|
|
296
|
+
shell: isWindows
|
|
297
|
+
});
|
|
298
|
+
return { ok: true, repo, path: targetPath, name: repoName };
|
|
299
|
+
} catch (e) { err(500, (e.stderr || e.message || 'Clone failed').trim()); }
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
router.handle('git.check', () => {
|
|
303
|
+
try {
|
|
304
|
+
const isWindows = os.platform() === 'win32';
|
|
305
|
+
const devnull = isWindows ? '' : ' 2>/dev/null';
|
|
306
|
+
const remoteUrl = execSync('git remote get-url origin' + devnull, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows }).trim();
|
|
307
|
+
const statusResult = execSync('git status --porcelain' + devnull, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
|
|
308
|
+
const hasChanges = statusResult.trim().length > 0;
|
|
309
|
+
const unpushedResult = execSync('git rev-list --count --not --remotes' + devnull, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
|
|
310
|
+
const hasUnpushed = parseInt(unpushedResult.trim() || '0', 10) > 0;
|
|
311
|
+
const githubUser = process.env.GITHUB_USER;
|
|
312
|
+
const ownsRemote = !remoteUrl.includes('github.com/') || (!!githubUser && remoteUrl.includes(githubUser));
|
|
313
|
+
return { ownsRemote, hasChanges, hasUnpushed, remoteUrl };
|
|
314
|
+
} catch {
|
|
315
|
+
return { ownsRemote: false, hasChanges: false, hasUnpushed: false, remoteUrl: '' };
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
router.handle('git.push', () => {
|
|
320
|
+
try {
|
|
321
|
+
const isWindows = os.platform() === 'win32';
|
|
322
|
+
const cmd = isWindows
|
|
323
|
+
? 'git add -A & git commit -m "Auto-commit" & git push'
|
|
324
|
+
: 'git add -A && git commit -m "Auto-commit" && git push';
|
|
325
|
+
execSync(cmd, { encoding: 'utf-8', cwd: STARTUP_CWD, shell: isWindows });
|
|
326
|
+
return { success: true };
|
|
327
|
+
} catch (e) { err(500, e.message); }
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
// --- git.status: changed-file list (staged/unstaged/untracked) for
|
|
331
|
+
// GitStatusPanel. Porcelain=v1 line format "XY PATH" (rename: "XY OLD -> NEW"),
|
|
332
|
+
// X = index state, Y = worktree state, '?'/' ' = untouched/untracked.
|
|
333
|
+
router.handle('git.status', async (p) => {
|
|
334
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
335
|
+
try {
|
|
336
|
+
const { stdout } = await execFileP('git', ['status', '--porcelain=v1'], { cwd });
|
|
337
|
+
const files = [];
|
|
338
|
+
for (const line of stdout.split('\n')) {
|
|
339
|
+
if (!line) continue;
|
|
340
|
+
const x = line[0], y = line[1];
|
|
341
|
+
const path = line.slice(3);
|
|
342
|
+
if (x === '?' && y === '?') { files.push({ path, status: '?' }); continue; }
|
|
343
|
+
if (x !== ' ' && x !== '?') files.push({ path, status: x, staged: true });
|
|
344
|
+
else if (y !== ' ' && y !== '?') files.push({ path, status: y, staged: false });
|
|
345
|
+
}
|
|
346
|
+
return { files };
|
|
347
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git status failed').trim()); }
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
// --- git.diff: unified diff for a single file or the whole working tree.
|
|
351
|
+
// p.cwd (optional) is confined via confineToRoots/fsAllowRoots, same as
|
|
352
|
+
// chat.sendMessage; p.file (optional) is validated to reject flags/shell
|
|
353
|
+
// metacharacters. execFile array-args form only, never a shell string.
|
|
354
|
+
router.handle('git.diff', async (p) => {
|
|
355
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
356
|
+
const args = ['diff', '--no-color'];
|
|
357
|
+
if (p?.staged) args.push('--staged');
|
|
358
|
+
if (p?.file) args.push('--', assertSafeRelPath(p.file, 'file'));
|
|
359
|
+
try {
|
|
360
|
+
const { stdout } = await execFileP('git', args, { cwd });
|
|
361
|
+
// git prints "Binary files a/x and b/x differ" for binary paths instead
|
|
362
|
+
// of a unified diff - an empty `diff` string then reads to the client as
|
|
363
|
+
// "no diff to show" with no explanation. Detect it so the UI can say why.
|
|
364
|
+
const binary = /^Binary files .* differ$/m.test(stdout);
|
|
365
|
+
return { diff: stdout, binary, file: p?.file || null, staged: !!p?.staged };
|
|
366
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git diff failed').trim()); }
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
// --- git.log: recent commit list, limit param (default 20, capped 200).
|
|
370
|
+
router.handle('git.log', async (p) => {
|
|
371
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
372
|
+
const limit = Math.max(1, Math.min(200, parseInt(p?.limit, 10) || 20));
|
|
373
|
+
const FIELD_SEP = '\x1f';
|
|
374
|
+
const REC_SEP = '\x1e';
|
|
375
|
+
const args = ['log', `-n${limit}`, `--pretty=format:%H${FIELD_SEP}%an${FIELD_SEP}%ad${FIELD_SEP}%s${REC_SEP}`, '--date=iso-strict'];
|
|
376
|
+
try {
|
|
377
|
+
const { stdout } = await execFileP('git', args, { cwd });
|
|
378
|
+
const commits = stdout.split(REC_SEP).map(s => s.trim()).filter(Boolean).map(rec => {
|
|
379
|
+
const [hash, author, date, ...rest] = rec.split(FIELD_SEP);
|
|
380
|
+
return { hash, author, date, subject: rest.join(FIELD_SEP) };
|
|
381
|
+
});
|
|
382
|
+
return { commits };
|
|
383
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git log failed').trim()); }
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
// --- worktree.list / create / remove ---
|
|
387
|
+
router.handle('worktree.list', async (p) => {
|
|
388
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
389
|
+
try {
|
|
390
|
+
const { stdout } = await execFileP('git', ['worktree', 'list', '--porcelain'], { cwd });
|
|
391
|
+
// Parse the porcelain block format: records separated by blank lines,
|
|
392
|
+
// each line "key value" or a bare flag ("bare", "detached", "locked").
|
|
393
|
+
const worktrees = [];
|
|
394
|
+
let cur = null;
|
|
395
|
+
for (const line of stdout.split('\n')) {
|
|
396
|
+
if (!line.trim()) { if (cur) { worktrees.push(cur); cur = null; } continue; }
|
|
397
|
+
if (!cur) cur = {};
|
|
398
|
+
const sp = line.indexOf(' ');
|
|
399
|
+
if (sp === -1) { cur[line] = true; continue; }
|
|
400
|
+
cur[line.slice(0, sp)] = line.slice(sp + 1);
|
|
401
|
+
}
|
|
402
|
+
if (cur) worktrees.push(cur);
|
|
403
|
+
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 })) };
|
|
404
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git worktree list failed').trim()); }
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
router.handle('worktree.create', async (p) => {
|
|
408
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
409
|
+
const wtPath = assertSafeRelPath(p?.path, 'path');
|
|
410
|
+
const args = ['worktree', 'add'];
|
|
411
|
+
if (p?.newBranch) { args.push('-b', assertSafeBranch(p.newBranch, 'newBranch')); }
|
|
412
|
+
args.push(wtPath);
|
|
413
|
+
if (p?.branch) args.push(assertSafeBranch(p.branch, 'branch'));
|
|
414
|
+
try {
|
|
415
|
+
const { stdout, stderr } = await execFileP('git', args, { cwd });
|
|
416
|
+
return { ok: true, output: (stdout || stderr || '').trim(), path: wtPath };
|
|
417
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git worktree add failed').trim()); }
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
router.handle('worktree.remove', async (p) => {
|
|
421
|
+
const cwd = resolveGitCwd(p, STARTUP_CWD);
|
|
422
|
+
const wtPath = assertSafeRelPath(p?.path, 'path');
|
|
423
|
+
const args = ['worktree', 'remove'];
|
|
424
|
+
if (p?.force) args.push('--force');
|
|
425
|
+
args.push(wtPath);
|
|
426
|
+
try {
|
|
427
|
+
const { stdout, stderr } = await execFileP('git', args, { cwd });
|
|
428
|
+
return { ok: true, output: (stdout || stderr || '').trim() };
|
|
429
|
+
} catch (e) { err(500, (e.stderr || e.message || 'git worktree remove failed').trim()); }
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
router.handle('auth.configs', () => getProviderConfigs());
|
|
433
|
+
|
|
434
|
+
router.handle('auth.save', (p) => {
|
|
435
|
+
const { providerId, apiKey, defaultModel } = p;
|
|
436
|
+
if (typeof providerId !== 'string' || !providerId.length || providerId.length > 100) err(400, 'Invalid providerId');
|
|
437
|
+
if (typeof apiKey !== 'string' || !apiKey.length || apiKey.length > 10000) err(400, 'Invalid apiKey');
|
|
438
|
+
if (defaultModel !== undefined && (typeof defaultModel !== 'string' || defaultModel.length > 200)) err(400, 'Invalid defaultModel');
|
|
439
|
+
const configPath = saveProviderConfig(providerId, apiKey, defaultModel || '');
|
|
440
|
+
return { success: true, path: configPath };
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
router.handle('import.claude', () => ({ imported: queries.importClaudeCodeConversations() }));
|
|
444
|
+
|
|
445
|
+
router.handle('discover.claude', () => ({ discovered: queries.discoverClaudeCodeConversations() }));
|
|
446
|
+
|
|
447
|
+
router.handle('ws.stats', () => wsOptimizer.getStats());
|
|
448
|
+
|
|
449
|
+
router.handle('acp.restart', async (p) => {
|
|
450
|
+
if (!p.id) err(400, 'Missing agent id');
|
|
451
|
+
const ok = await restartAcpAgent(p.id);
|
|
452
|
+
return { ok: !!ok };
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
router.handle('agent.subagents', async (p) => {
|
|
456
|
+
if (!p.id) err(400, 'Missing agent id');
|
|
457
|
+
if (p.id === 'claude-code' || p.id === 'cli-claude') {
|
|
458
|
+
const spawnEnv = { ...process.env }; delete spawnEnv.CLAUDECODE;
|
|
459
|
+
const result = spawnSync('claude', ['agents', 'list'], { encoding: 'utf-8', timeout: 10000, stdio: ['pipe', 'pipe', 'pipe'], env: spawnEnv });
|
|
460
|
+
if (result.status !== 0 || !result.stdout) return { subAgents: [] };
|
|
461
|
+
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] }));
|
|
462
|
+
return { subAgents: agents };
|
|
463
|
+
}
|
|
464
|
+
return { subAgents: SUB_AGENT_MAP[p.id] || [] };
|
|
465
|
+
});
|
|
466
|
+
}
|