-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathindex.ts
More file actions
326 lines (293 loc) · 13.9 KB
/
index.ts
File metadata and controls
326 lines (293 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1";
// Enrich process PATH at startup so binary resolution and `which` calls can find
// binaries installed via version managers (nvm, volta, fnm, etc.).
// Critical when running as a launchd/systemd service with a restricted PATH.
import { getEnrichedPath } from "./path-resolver.js";
process.env.PATH = getEnrichedPath();
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { serveStatic } from "hono/bun";
import { cacheControlMiddleware } from "./cache-headers.js";
import { createRoutes } from "./routes.js";
import { CliLauncher } from "./cli-launcher.js";
import { WsBridge } from "./ws-bridge.js";
import { SessionStore } from "./session-store.js";
import { WorktreeTracker } from "./worktree-tracker.js";
import { containerManager } from "./container-manager.js";
import { join } from "node:path";
import { homedir } from "node:os";
import { TerminalManager } from "./terminal-manager.js";
import { generateSessionTitle } from "./auto-namer.js";
import * as sessionNames from "./session-names.js";
import { getSettings } from "./settings-manager.js";
import { PRPoller } from "./pr-poller.js";
import { RecorderManager } from "./recorder.js";
import { CronScheduler } from "./cron-scheduler.js";
import { AgentExecutor } from "./agent-executor.js";
import { OrchestratorExecutor } from "./orchestrator-executor.js";
import { migrateCronJobsToAgents } from "./agent-cron-migrator.js";
import { startPeriodicCheck, setServiceMode } from "./update-checker.js";
import { imagePullManager } from "./image-pull-manager.js";
import { isRunningAsService } from "./service.js";
import { getToken, verifyToken } from "./auth-manager.js";
import { getCookie } from "hono/cookie";
import type { SocketData } from "./ws-bridge.js";
import type { ServerWebSocket } from "bun";
const __dirname = dirname(fileURLToPath(import.meta.url));
const packageRoot = process.env.__COMPANION_PACKAGE_ROOT || resolve(__dirname, "..");
import { DEFAULT_PORT_DEV, DEFAULT_PORT_PROD } from "./constants.js";
const defaultPort = process.env.NODE_ENV === "production" ? DEFAULT_PORT_PROD : DEFAULT_PORT_DEV;
const port = Number(process.env.PORT) || defaultPort;
const idleTimeoutSeconds = Number(process.env.COMPANION_IDLE_TIMEOUT_SECONDS || "120");
const sessionStore = new SessionStore(process.env.COMPANION_SESSION_DIR);
const wsBridge = new WsBridge();
const launcher = new CliLauncher(port);
const worktreeTracker = new WorktreeTracker();
const CONTAINER_STATE_PATH = join(homedir(), ".companion", "containers.json");
const terminalManager = new TerminalManager();
const prPoller = new PRPoller(wsBridge);
const recorder = new RecorderManager();
const cronScheduler = new CronScheduler(launcher, wsBridge);
const agentExecutor = new AgentExecutor(launcher, wsBridge);
const orchestratorExecutor = new OrchestratorExecutor(launcher, wsBridge);
// ── Restore persisted sessions from disk ────────────────────────────────────
wsBridge.setStore(sessionStore);
wsBridge.setRecorder(recorder);
launcher.setStore(sessionStore);
launcher.setRecorder(recorder);
launcher.restoreFromDisk();
wsBridge.restoreFromDisk();
containerManager.restoreState(CONTAINER_STATE_PATH);
// When the CLI reports its internal session_id, store it for --resume on relaunch
wsBridge.onCLISessionIdReceived((sessionId, cliSessionId) => {
launcher.setCLISessionId(sessionId, cliSessionId);
});
// When a Codex adapter is created, attach it to the WsBridge
launcher.onCodexAdapterCreated((sessionId, adapter) => {
wsBridge.attachCodexAdapter(sessionId, adapter);
});
// Start watching PRs when git info is resolved for a session
wsBridge.onSessionGitInfoReadyCallback((sessionId, cwd, branch) => {
prPoller.watch(sessionId, cwd, branch);
});
// Auto-relaunch CLI when a browser connects to a session with no CLI
const relaunchingSet = new Set<string>();
wsBridge.onCLIRelaunchNeededCallback(async (sessionId) => {
if (relaunchingSet.has(sessionId)) return;
const info = launcher.getSession(sessionId);
if (info?.archived) return;
if (info && info.state !== "starting") {
relaunchingSet.add(sessionId);
console.log(`[server] Auto-relaunching CLI for session ${sessionId}`);
try {
const result = await launcher.relaunch(sessionId);
if (!result.ok && result.error) {
wsBridge.broadcastToSession(sessionId, { type: "error", message: result.error });
}
} finally {
setTimeout(() => relaunchingSet.delete(sessionId), 5000);
}
}
});
// Auto-generate session title after first turn completes
wsBridge.onFirstTurnCompletedCallback(async (sessionId, firstUserMessage) => {
// Don't overwrite a name that was already set (manual rename or prior auto-name)
if (sessionNames.getName(sessionId)) return;
if (!getSettings().anthropicApiKey.trim()) return;
const info = launcher.getSession(sessionId);
const model = info?.model || "claude-sonnet-4-6";
console.log(`[server] Auto-naming session ${sessionId} via Anthropic with model ${model}...`);
const title = await generateSessionTitle(firstUserMessage, model);
// Re-check: a manual rename may have occurred while we were generating
if (title && !sessionNames.getName(sessionId)) {
console.log(`[server] Auto-named session ${sessionId}: "${title}"`);
sessionNames.setName(sessionId, title);
wsBridge.broadcastNameUpdate(sessionId, title);
}
});
console.log(`[server] Session persistence: ${sessionStore.directory}`);
if (recorder.isGloballyEnabled()) {
console.log(`[server] Recording enabled (dir: ${recorder.getRecordingsDir()}, max: ${recorder.getMaxLines()} lines)`);
}
const app = new Hono();
app.use("/api/*", cors());
app.route("/api", createRoutes(launcher, wsBridge, sessionStore, worktreeTracker, terminalManager, prPoller, recorder, cronScheduler, agentExecutor, orchestratorExecutor));
// Dynamic manifest — embeds auth token in start_url so PWA auto-authenticates
// on first launch. iOS gives standalone PWAs isolated storage from Safari,
// so this is the only way to bridge auth across the install boundary.
app.get("/manifest.json", (c) => {
const manifest = {
name: "The Companion",
short_name: "Companion",
description: "Web UI for Claude Code and Codex",
start_url: "/",
scope: "/",
display: "standalone" as const,
background_color: "#262624",
theme_color: "#d97757",
icons: [
{ src: "/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" },
{ src: "/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" },
],
};
// If the user has an auth cookie (set during login), embed token in start_url.
// Safari sends this cookie when fetching the manifest at "Add to Home Screen" time.
const authCookie = getCookie(c, "companion_auth");
if (authCookie && verifyToken(authCookie)) {
manifest.start_url = `/?token=${authCookie}`;
} else {
// Localhost bypass — always embed the token for same-machine installs
const bunServer = c.env as { requestIP?: (req: Request) => { address: string } | null };
const ip = bunServer?.requestIP?.(c.req.raw);
const addr = ip?.address ?? "";
if (addr === "127.0.0.1" || addr === "::1" || addr === "::ffff:127.0.0.1") {
manifest.start_url = `/?token=${getToken()}`;
}
}
c.header("Content-Type", "application/manifest+json");
return c.json(manifest);
});
// In production, serve built frontend using absolute path (works when installed as npm package)
if (process.env.NODE_ENV === "production") {
const distDir = resolve(packageRoot, "dist");
app.use("/*", cacheControlMiddleware());
app.use("/*", serveStatic({ root: distDir }));
app.get("/*", serveStatic({ path: resolve(distDir, "index.html") }));
}
const server = Bun.serve<SocketData>({
port,
idleTimeout: idleTimeoutSeconds,
async fetch(req, server) {
const url = new URL(req.url);
// ── CLI WebSocket — Claude Code CLI connects here via --sdk-url ────
const cliMatch = url.pathname.match(/^\/ws\/cli\/([a-f0-9-]+)$/);
if (cliMatch) {
const sessionId = cliMatch[1];
const upgraded = server.upgrade(req, {
data: { kind: "cli" as const, sessionId },
});
if (upgraded) return undefined;
return new Response("WebSocket upgrade failed", { status: 400 });
}
// Helper: check if request is from localhost (same machine)
const reqIp = server.requestIP(req);
const reqAddr = reqIp?.address ?? "";
const isLocalhost = reqAddr === "127.0.0.1" || reqAddr === "::1" || reqAddr === "::ffff:127.0.0.1";
// ── Browser WebSocket — connects to a specific session ─────────────
const browserMatch = url.pathname.match(/^\/ws\/browser\/([a-f0-9-]+)$/);
if (browserMatch) {
const wsToken = url.searchParams.get("token");
if (!isLocalhost && !verifyToken(wsToken)) {
return new Response("Unauthorized", { status: 401 });
}
const sessionId = browserMatch[1];
const upgraded = server.upgrade(req, {
data: { kind: "browser" as const, sessionId },
});
if (upgraded) return undefined;
return new Response("WebSocket upgrade failed", { status: 400 });
}
// ── Terminal WebSocket — embedded terminal PTY connection ─────────
const termMatch = url.pathname.match(/^\/ws\/terminal\/([a-f0-9-]+)$/);
if (termMatch) {
const wsToken = url.searchParams.get("token");
if (!isLocalhost && !verifyToken(wsToken)) {
return new Response("Unauthorized", { status: 401 });
}
const terminalId = termMatch[1];
const upgraded = server.upgrade(req, {
data: { kind: "terminal" as const, terminalId },
});
if (upgraded) return undefined;
return new Response("WebSocket upgrade failed", { status: 400 });
}
// Hono handles the rest
return app.fetch(req, server);
},
websocket: {
open(ws: ServerWebSocket<SocketData>) {
const data = ws.data;
if (data.kind === "cli") {
wsBridge.handleCLIOpen(ws, data.sessionId);
launcher.markConnected(data.sessionId);
} else if (data.kind === "browser") {
wsBridge.handleBrowserOpen(ws, data.sessionId);
} else if (data.kind === "terminal") {
terminalManager.addBrowserSocket(ws);
}
},
message(ws: ServerWebSocket<SocketData>, msg: string | Buffer) {
const data = ws.data;
if (data.kind === "cli") {
wsBridge.handleCLIMessage(ws, msg);
} else if (data.kind === "browser") {
wsBridge.handleBrowserMessage(ws, msg);
} else if (data.kind === "terminal") {
terminalManager.handleBrowserMessage(ws, msg);
}
},
close(ws: ServerWebSocket<SocketData>) {
const data = ws.data;
if (data.kind === "cli") {
wsBridge.handleCLIClose(ws);
} else if (data.kind === "browser") {
wsBridge.handleBrowserClose(ws);
} else if (data.kind === "terminal") {
terminalManager.removeBrowserSocket(ws);
}
},
},
});
const authToken = getToken();
console.log(`Server running on http://localhost:${server.port}`);
console.log();
console.log(` Auth token: ${authToken}`);
if (process.env.COMPANION_AUTH_TOKEN) {
console.log(" (using COMPANION_AUTH_TOKEN env var)");
}
console.log();
console.log(` CLI WebSocket: ws://localhost:${server.port}/ws/cli/:sessionId`);
console.log(` Browser WebSocket: ws://localhost:${server.port}/ws/browser/:sessionId`);
if (process.env.NODE_ENV !== "production") {
console.log("Dev mode: frontend at http://localhost:5174");
}
// ── Cron scheduler ──────────────────────────────────────────────────────────
cronScheduler.startAll();
// ── Agent system ────────────────────────────────────────────────────────────
migrateCronJobsToAgents();
agentExecutor.startAll();
// ── Image pull manager — pre-pull missing Docker images for environments ────
imagePullManager.initFromEnvironments();
// ── Update checker ──────────────────────────────────────────────────────────
startPeriodicCheck();
if (isRunningAsService()) {
setServiceMode(true);
console.log("[server] Running as background service (auto-update available)");
}
// ── Graceful shutdown — persist container state ──────────────────────────────
function gracefulShutdown() {
console.log("[server] Persisting container state before shutdown...");
containerManager.persistState(CONTAINER_STATE_PATH);
process.exit(0);
}
process.on("SIGTERM", gracefulShutdown);
process.on("SIGINT", gracefulShutdown);
// ── Reconnection watchdog ────────────────────────────────────────────────────
// After a server restart, restored CLI processes may not reconnect their
// WebSocket. Give them a grace period, then kill + relaunch any that are
// still in "starting" state (alive but no WS connection).
const RECONNECT_GRACE_MS = Number(process.env.COMPANION_RECONNECT_GRACE_MS || "30000");
const starting = launcher.getStartingSessions();
if (starting.length > 0) {
console.log(`[server] Waiting ${RECONNECT_GRACE_MS / 1000}s for ${starting.length} CLI process(es) to reconnect...`);
setTimeout(async () => {
const stale = launcher.getStartingSessions();
for (const info of stale) {
if (info.archived) continue;
console.log(`[server] CLI for session ${info.sessionId} did not reconnect, relaunching...`);
await launcher.relaunch(info.sessionId);
}
}, RECONNECT_GRACE_MS);
}