officer's registration socket silently drops sends when it isn't OPEN (sidecar/connect.ts:send — no queue, no error, no return value). the agent pushed raw parser events over that socket and officer translated and persisted them, so everything a turn produced while officer was restarting went nowhere: the turn kept running, the output was gone, and a reconnecting client replayed a log that simply had no rows for those seconds. stage 1 kept the agent alive across a restart; this is what makes its output survive one too. move the translation and the write into the sidecar: - turn-stream.ts is the stateful ChatEvent -> browser-message translator lifted out of websocket.ts (delta buffering, flush before tool:start and result). pure and synchronous, so it is unit tested — 12 tests, 100% lines. - session-log.ts commits each message to chat_session_events and only then hands it to officer, with its cursor id attached. per-session promise chain: translation is synchronous and therefore in arrival order, and only the commit is queued, so cursor ids are assigned in the order events actually happened. a delta that overtook the assistant:text in front of it would make the client commit its stream buffer at the wrong point, so deltas go through the same queue even though they are never written. - claude:event on the wire becomes claude:message: a finished browser-facing message plus its seq. officer relays it verbatim and folds it into the in-memory session for sync:messages. it no longer builds or persists chat messages for this harness. gap detection, which is what the durable log is for. chat_session_events.id is a global bigserial, so two consecutive events of one session are not consecutive ids and a client cannot tell a contiguous replay from one with a hole in it. each durable message now carries prevSeq — the cursor of the previous message in the same session — which is inside the persisted payload, so it survives replay. useChat compares it against the cursor it holds before advancing, and surfaces a visible marker on a mismatch: a conversation that silently skips a tool call or half an answer reads as the assistant having done something inexplicable. only checked once a cursor exists, because opening a session from history legitimately starts mid-chain (events are swept after 7 days, the transcript is not). a failed write delivers live with no seq, so the client sees the message but does not advance past something it cannot replay, and the next successful write chains from the cursor the client still holds. pipeline steps pass durable: false. their sessionKey is a throwaway uuid no browser will ever replay and the job's own event log is its record, so writing those rows only grows the table. opencode still goes through officer's createEventHandler, now labelled as such. that is the sidecars-opencode branch. this fixes R4 from CLAUDE_SIDECAR_ISOLATION.md. R3 and R5 already worked. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
368 lines
12 KiB
TypeScript
368 lines
12 KiB
TypeScript
import type { ServerWebSocket } from 'bun';
|
|
import type {
|
|
SidecarCommand,
|
|
SidecarEvent,
|
|
ClaudeState,
|
|
ClaudeSpawnParams,
|
|
ClaudeSpawnStreamingParams,
|
|
ClaudeCodeResult,
|
|
OpenCodeRunParams,
|
|
PtyCommand,
|
|
PtyEvent,
|
|
VncStartParams,
|
|
VncSessionInfo,
|
|
} from './sidecar/protocol';
|
|
import type { SidecarRegistration } from './sidecar/registration-protocol';
|
|
import type { ChatEvent, TurnMessage } from './api/chat/types';
|
|
|
|
// ── Types ──
|
|
|
|
type RegisteredSidecar = {
|
|
id: string;
|
|
name: string;
|
|
capabilities: string[];
|
|
ws: ServerWebSocket<any>;
|
|
};
|
|
|
|
type PendingRequest = {
|
|
resolve: (value: any) => void;
|
|
reject: (error: Error) => void;
|
|
timer: Timer;
|
|
};
|
|
|
|
type EventHandler = (event: SidecarEvent | PtyEvent) => void;
|
|
|
|
// ── State ──
|
|
|
|
const sidecars = new Map<string, RegisteredSidecar>();
|
|
const pending = new Map<string, PendingRequest>();
|
|
const eventHandlers = new Map<string, Set<EventHandler>>();
|
|
let cachedState: ClaudeState | null = null;
|
|
let idCounter = 0;
|
|
|
|
function nextId(): string {
|
|
return `sr_${Date.now()}_${++idCounter}`;
|
|
}
|
|
|
|
// ── Registration ──
|
|
|
|
export function registerSidecar(ws: ServerWebSocket<any>, registration: SidecarRegistration): string {
|
|
// If a sidecar with the same name is already registered, unregister it first
|
|
for (const [id, sc] of sidecars) {
|
|
if (sc.name === registration.name) {
|
|
console.log(`[registry] replacing existing sidecar "${registration.name}" (id=${id})`);
|
|
unregisterSidecar(id);
|
|
break;
|
|
}
|
|
}
|
|
|
|
const id = `sc_${registration.name}_${Date.now()}`;
|
|
sidecars.set(id, {
|
|
id,
|
|
name: registration.name,
|
|
capabilities: registration.capabilities,
|
|
ws,
|
|
});
|
|
console.log(
|
|
`[registry] registered sidecar "${registration.name}" (id=${id}, capabilities=[${registration.capabilities.join(', ')}])`,
|
|
);
|
|
return id;
|
|
}
|
|
|
|
export function unregisterSidecar(id: string): void {
|
|
const sc = sidecars.get(id);
|
|
if (!sc) return;
|
|
sidecars.delete(id);
|
|
console.log(`[registry] unregistered sidecar "${sc.name}" (id=${id})`);
|
|
|
|
// Reject all pending requests for this sidecar
|
|
for (const [reqId, req] of pending) {
|
|
clearTimeout(req.timer);
|
|
req.reject(new Error(`Sidecar "${sc.name}" disconnected`));
|
|
pending.delete(reqId);
|
|
}
|
|
|
|
// Clear cached state if the claude sidecar disconnects
|
|
if (sc.capabilities.includes('proxy')) {
|
|
cachedState = null;
|
|
}
|
|
}
|
|
|
|
export function handleSidecarMessage(id: string, msg: SidecarEvent | PtyEvent): void {
|
|
// Check if this is a response to a pending request
|
|
if ('id' in msg && msg.id && pending.has(msg.id)) {
|
|
const req = pending.get(msg.id)!;
|
|
pending.delete(msg.id);
|
|
clearTimeout(req.timer);
|
|
req.resolve(msg);
|
|
return;
|
|
}
|
|
|
|
// Otherwise dispatch as event
|
|
dispatchEvent(msg);
|
|
}
|
|
|
|
// ── Lookup ──
|
|
|
|
function findSidecarByCapability(cap: string): RegisteredSidecar | undefined {
|
|
for (const sc of sidecars.values()) {
|
|
if (sc.capabilities.includes(cap)) return sc;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
// ── Event dispatch ──
|
|
|
|
function dispatchEvent(msg: SidecarEvent | PtyEvent) {
|
|
const handlers = eventHandlers.get(msg.type);
|
|
if (handlers) {
|
|
for (const handler of handlers) {
|
|
try {
|
|
handler(msg);
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export function on(eventType: string, handler: EventHandler): () => void {
|
|
if (!eventHandlers.has(eventType)) {
|
|
eventHandlers.set(eventType, new Set());
|
|
}
|
|
eventHandlers.get(eventType)!.add(handler);
|
|
return () => {
|
|
eventHandlers.get(eventType)?.delete(handler);
|
|
};
|
|
}
|
|
|
|
// ── Command sending ──
|
|
|
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
const LONG_TIMEOUT_MS = 6 * 60 * 1000;
|
|
|
|
function sendCommand(cap: string, cmd: SidecarCommand | PtyCommand, timeoutMs = DEFAULT_TIMEOUT_MS): Promise<any> {
|
|
return new Promise((resolve, reject) => {
|
|
const sc = findSidecarByCapability(cap);
|
|
if (!sc) {
|
|
reject(new Error(`No sidecar with capability "${cap}" is connected`));
|
|
return;
|
|
}
|
|
|
|
const timer = setTimeout(() => {
|
|
pending.delete((cmd as any).id);
|
|
reject(new Error(`Sidecar command ${cmd.type} timed out`));
|
|
}, timeoutMs);
|
|
|
|
pending.set((cmd as any).id, { resolve, reject, timer });
|
|
sc.ws.send(JSON.stringify(cmd));
|
|
});
|
|
}
|
|
|
|
function sendFire(cap: string, cmd: SidecarCommand | PtyCommand): void {
|
|
const sc = findSidecarByCapability(cap);
|
|
if (sc) {
|
|
sc.ws.send(JSON.stringify(cmd));
|
|
}
|
|
}
|
|
|
|
function sendCommandToSidecar(
|
|
sc: RegisteredSidecar,
|
|
cmd: SidecarCommand | PtyCommand,
|
|
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
): Promise<any> {
|
|
return new Promise((resolve, reject) => {
|
|
const timer = setTimeout(() => {
|
|
pending.delete((cmd as any).id);
|
|
reject(new Error(`Sidecar command ${cmd.type} timed out`));
|
|
}, timeoutMs);
|
|
|
|
pending.set((cmd as any).id, { resolve, reject, timer });
|
|
sc.ws.send(JSON.stringify(cmd));
|
|
});
|
|
}
|
|
|
|
function sendFireToSidecar(sc: RegisteredSidecar, cmd: SidecarCommand | PtyCommand): void {
|
|
sc.ws.send(JSON.stringify(cmd));
|
|
}
|
|
|
|
// ── Waiting for a sidecar to appear ──
|
|
|
|
// Officer no longer spawns any sidecar; PM2 owns every one of them. The only thing left to handle is
|
|
// startup order — PM2 brings `officer` and its peers up together, so the first request after a boot can
|
|
// arrive a beat before the sidecar has finished dialling in. Wait briefly rather than failing the
|
|
// request. (This replaces ~77 lines of spawn-and-poll: `ensureClaudeSidecar`,
|
|
// `spawnAndWaitForRegistration`, and the per-email `claudeProcs`/`claudeSpawnWaiters` maps.)
|
|
const CAPABILITY_WAIT_MS = 15_000;
|
|
const CAPABILITY_POLL_MS = 100;
|
|
|
|
async function waitForCapability(cap: string, timeoutMs = CAPABILITY_WAIT_MS): Promise<RegisteredSidecar> {
|
|
const existing = findSidecarByCapability(cap);
|
|
if (existing) return existing;
|
|
|
|
const deadline = Date.now() + timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
await Bun.sleep(CAPABILITY_POLL_MS);
|
|
const sc = findSidecarByCapability(cap);
|
|
if (sc) return sc;
|
|
}
|
|
throw new Error(`No sidecar with capability "${cap}" registered within ${timeoutMs}ms`);
|
|
}
|
|
|
|
// ── Public API ──
|
|
|
|
export function isConnected(): boolean {
|
|
return findSidecarByCapability('proxy') !== undefined;
|
|
}
|
|
|
|
export function getCachedState(): ClaudeState | null {
|
|
return cachedState;
|
|
}
|
|
|
|
export async function syncState(): Promise<ClaudeState> {
|
|
const res = await sendCommand('proxy', { type: 'state:sync', id: nextId() });
|
|
if (res.type === 'state:sync') {
|
|
cachedState = res.state;
|
|
return res.state;
|
|
}
|
|
throw new Error('Unexpected response');
|
|
}
|
|
|
|
export async function getProxySecret(): Promise<string> {
|
|
if (cachedState?.proxySecret) return cachedState.proxySecret;
|
|
const res = await sendCommand('proxy', { type: 'proxy:secret', id: nextId() });
|
|
if (res.type === 'proxy:secret') return res.secret;
|
|
throw new Error('Failed to get proxy secret');
|
|
}
|
|
|
|
export function getProxySecretSync(): string {
|
|
return cachedState?.proxySecret ?? '';
|
|
}
|
|
|
|
// ── Claude Code (the `officer-agent` sidecar, capability 'claude') ──
|
|
|
|
// Single-user platform, so there is exactly one agent sidecar and it is found by capability like every
|
|
// other one. The `email` on the params is still passed through to the sidecar — it needs it to resolve
|
|
// paths — but officer no longer uses it to *locate* anything.
|
|
|
|
export async function spawnClaude(params: ClaudeSpawnParams): Promise<ClaudeCodeResult> {
|
|
const sc = await waitForCapability('claude');
|
|
const res = await sendCommandToSidecar(sc, { type: 'claude:spawn', id: nextId(), params }, LONG_TIMEOUT_MS);
|
|
if (res.type === 'claude:result') return res.result;
|
|
if (res.type === 'claude:error') throw new Error(res.error);
|
|
throw new Error('Unexpected response');
|
|
}
|
|
|
|
export async function spawnClaudeStreaming(params: ClaudeSpawnStreamingParams): Promise<void> {
|
|
const sc = await waitForCapability('claude');
|
|
const res = await sendCommandToSidecar(sc, { type: 'claude:spawn-streaming', id: nextId(), params });
|
|
if (res.type === 'claude:spawned') return;
|
|
if (res.type === 'claude:error') throw new Error(res.error);
|
|
throw new Error('Unexpected response');
|
|
}
|
|
|
|
export function killClaude(sessionKey: string): void {
|
|
sendFire('claude', { type: 'claude:kill', id: nextId(), sessionKey });
|
|
}
|
|
|
|
// Interrupt the current turn but keep the persistent session warm (the "stop" button).
|
|
export function interruptClaude(sessionKey: string): void {
|
|
sendFire('claude', { type: 'claude:interrupt', id: nextId(), sessionKey });
|
|
}
|
|
|
|
export function clearClaudeSession(sessionKey: string): void {
|
|
sendFire('claude', { type: 'claude:clear-session', id: nextId(), sessionKey });
|
|
}
|
|
|
|
// Turn output arrives finished and already durable: the agent translated it and committed it to
|
|
// chat_session_events, and `seq` is its cursor id there. Officer relays it — it no longer builds or
|
|
// persists chat messages for this harness.
|
|
export function onClaudeMessage(handler: (sessionKey: string, msg: TurnMessage, seq?: number) => void): () => void {
|
|
return on('claude:message', (ev) => {
|
|
if (ev.type !== 'claude:message') return;
|
|
const msg = ev as SidecarEvent & { type: 'claude:message' };
|
|
handler(msg.sessionKey, msg.msg, msg.seq);
|
|
});
|
|
}
|
|
|
|
// ── OpenCode Code (single sidecar, capability 'opencode') ──
|
|
|
|
export async function spawnOpenCodeStreaming(params: OpenCodeRunParams): Promise<void> {
|
|
const res = await sendCommand('opencode', { type: 'opencode:run-streaming', id: nextId(), params });
|
|
if (res.type === 'opencode:spawned') return;
|
|
if (res.type === 'opencode:error') throw new Error(res.error);
|
|
throw new Error('Unexpected response');
|
|
}
|
|
|
|
export function killOpenCode(sessionKey: string): void {
|
|
sendFire('opencode', { type: 'opencode:kill', id: nextId(), sessionKey });
|
|
}
|
|
|
|
export function onOpenCodeEvent(handler: (sessionKey: string, event: ChatEvent) => void): () => void {
|
|
return on('opencode:event', (msg) => {
|
|
if (msg.type === 'opencode:event') {
|
|
handler(
|
|
(msg as SidecarEvent & { type: 'opencode:event' }).sessionKey,
|
|
(msg as SidecarEvent & { type: 'opencode:event' }).event,
|
|
);
|
|
}
|
|
});
|
|
}
|
|
|
|
export function onOpenCodeSession(handler: (sessionKey: string, sessionId: string) => void): () => void {
|
|
return on('opencode:session', (msg) => {
|
|
if (msg.type === 'opencode:session') {
|
|
handler(
|
|
(msg as SidecarEvent & { type: 'opencode:session' }).sessionKey,
|
|
(msg as SidecarEvent & { type: 'opencode:session' }).sessionId,
|
|
);
|
|
}
|
|
});
|
|
}
|
|
|
|
// ── Terminal (PTY sidecar) ──
|
|
|
|
export function sendPtyCommand(cmd: PtyCommand): void {
|
|
sendFire('terminal', cmd);
|
|
}
|
|
|
|
export async function sendPtyCommandAsync(cmd: PtyCommand, timeoutMs = DEFAULT_TIMEOUT_MS): Promise<PtyEvent> {
|
|
return sendCommand('terminal', cmd, timeoutMs);
|
|
}
|
|
|
|
export function isTerminalConnected(): boolean {
|
|
return findSidecarByCapability('terminal') !== undefined;
|
|
}
|
|
|
|
// ── VNC ──
|
|
|
|
export async function startVnc(params: VncStartParams): Promise<{ port: number; display: number }> {
|
|
const res = await sendCommand('vnc', { type: 'vnc:start', id: nextId(), params });
|
|
if (res.type === 'vnc:started') return { port: res.port, display: res.display };
|
|
if (res.type === 'vnc:error') throw new Error(res.error);
|
|
throw new Error('Unexpected response');
|
|
}
|
|
|
|
// Provision the VNC password without starting a server. The desktop UI needs it before it can open
|
|
// the WebSocket that would start one, so asking vnc:start here would be circular.
|
|
export async function ensureVncPassword(email: string): Promise<string> {
|
|
const res = await sendCommand('vnc', { type: 'vnc:ensure-password', id: nextId(), email });
|
|
if (res.type === 'vnc:password') return res.password;
|
|
if (res.type === 'vnc:error') throw new Error(res.error);
|
|
throw new Error('Unexpected response from VNC sidecar');
|
|
}
|
|
|
|
export function stopVnc(email: string): void {
|
|
sendFire('vnc', { type: 'vnc:stop', id: nextId(), email });
|
|
}
|
|
|
|
export async function getVncStatus(email: string): Promise<VncSessionInfo | null> {
|
|
const res = await sendCommand('vnc', { type: 'vnc:status', id: nextId(), email });
|
|
if (res.type === 'vnc:status') return res.session;
|
|
throw new Error('Unexpected response');
|
|
}
|
|
|
|
export function isVncConnected(): boolean {
|
|
return findSidecarByCapability('vnc') !== undefined;
|
|
}
|