import { log, error as logError } from '../../logger' import { Hono } from 'hono' import { randomUUID } from 'node:crypto' import { sessionAuth } from '../../auth/middleware' import { SYSTEM_USER_ID } from '../../auth/constants' import { getAutomationStateSnapshot } from '../../services/automationState' import { archiveSession, canManageSession, createSession, getSession, isSessionClosedStatus, isSessionVisibleToUser, listSessionSummaries, listSessions, listWebSessionSummariesByOwnerUuid, listWebSessionsByOwnerUuid, resolveOwnedWebSessionId, toWebSessionResponse, updateSessionTitle, } from '../../services/session' import { loadPersistedEvents } from '../../services/event-persistence' import { getDb } from '../../db/sqlite' import { storeBindSession, storeGetEnvironment, storeGetSessionWorker, storeGetActiveWorkItemBySession, storeIssueAttachCode, storeListSessionsByEnvironment, } from '../../store' import { createWorkItem, stopWork } from '../../services/work-dispatch' import { canUseEnvironment } from '../../services/environment' import { normalizeSessionCwd } from '../../services/paths' import { createSSEStream } from '../../transport/sse-writer' import { getEventBus, type SessionEvent } from '../../transport/event-bus' import { publishSessionEvent } from '../../services/transport' import { wipeSessionConversation } from '../../services/session-clear' import { searchSessions } from '../../services/search' const app = new Hono() /** * Resolve the user ID to bind a session to. * When the request comes via API key (userId = __system__), check the * X-User-Id header for a real user identity. If no valid identity is * found, returns null — the session will be orphaned (admin-visible). */ function resolveBindUserId(c: import('hono').Context): string | null { const userId = c.get('userId') if (!userId || userId === SYSTEM_USER_ID) { // API key auth — only admin can use X-User-Id to bind on behalf of a user const isAdmin = c.get('isAdmin') if (!isAdmin) { return null // non-admin API key cannot create sessions as another user } const headerUserId = c.req.header('X-User-Id') if (headerUserId && headerUserId !== SYSTEM_USER_ID) { console.log(`[audit] API key created session as user ${headerUserId}`) return headerUserId } return null // API key without X-User-Id → orphan session (admin-visible) } return userId } /** POST /web/sessions — Create a session from web UI */ app.post('/sessions', sessionAuth, async c => { const bindUserId = resolveBindUserId(c) const body = await c.req.json() const userId = c.get('userId')! const isAdmin = c.get('isAdmin') as boolean // Web callers may pick an approving mode, but never one that removes the // approval loop entirely: bypassPermissions / dontAsk / auto stay the // machine operator's startup decision (web sessions inherit it by // omitting permission_mode). const WEB_PERMISSION_MODES = new Set(['default', 'plan', 'acceptEdits']) if ( body.permission_mode !== undefined && body.permission_mode !== null && body.permission_mode !== '' ) { if ( typeof body.permission_mode !== 'string' || !WEB_PERMISSION_MODES.has(body.permission_mode) ) { return c.json( { error: { type: 'invalid_permission_mode', message: `permission_mode must be one of: ${[...WEB_PERMISSION_MODES].join(', ')}`, }, }, 400, ) } } // Session directory. The connection is machine-scoped, so any absolute // path (or ~/...) is accepted here; the worker is the authority on // existence/permission. Empty → the environment's startup directory. let cwd: string | undefined if (body.cwd !== undefined && body.cwd !== null && body.cwd !== '') { const parsed = normalizeSessionCwd(body.cwd) if (!parsed.ok) { return c.json( { error: { type: 'invalid_cwd', message: parsed.message } }, 400, ) } cwd = parsed.cwd } // Pre-validate BEFORE creating the session record. let env: ReturnType if (body.environment_id) { env = storeGetEnvironment(body.environment_id) if (!env) { return c.json( { error: { type: 'not_found', message: 'Environment not found' } }, 404, ) } // Machine-level authorization: the caller must own the environment or // belong to its team (admin bypasses). Without this, any logged-in user // who learned an environment id could dispatch work to someone else's // machine. if (!canUseEnvironment(env.id, userId, isAdmin)) { return c.json( { error: { type: 'forbidden', message: 'You do not have access to this machine', }, }, 403, ) } if (!cwd && env.directory) cwd = env.directory // ACP environments: registerEnvironment already auto-created a // source:'acp' session for this env. acp-link workers don't poll work // items (they hold a /acp/ws WebSocket long-connection), so creating a // source:'web' session + dispatching work would orphan it — the UI // would render native RCS chat instead of ACPSessionDetail and // messages would never reach the agent. Bind the existing ACP session // to this user and return it directly. if (env?.workerType === 'acp') { const existing = storeListSessionsByEnvironment(env.id).find( s => s.source === 'acp' && !isSessionClosedStatus(s.status), ) const sessionId = existing?.id ?? createSession({ environment_id: env.id, title: body.title || env.machineName || 'ACP Agent', source: 'acp', }).id if (bindUserId) { storeBindSession(sessionId, bindUserId) } const session = getSession(sessionId) return c.json(toWebSessionResponse(session!), 200) } // In-process (replBridge) workers register with workerType='repl' and // maxSessions=1 — they can only serve one session at a time. Reject // multi-session creation with a helpful error guiding the user to // `slz rc` (spawn mode). MUST run before createSession: the new session // is created WITH body.environment_id, so checking after would always // see the just-created session and 409 every request (leaving a stray // bound-but-never-dispatched session behind on each retry). if (env?.workerType === 'repl') { // In-process REPL workers cannot change directory: their QueryEngine // runs inside the terminal's process. A different cwd is rejected // instead of silently running in the wrong place. if (cwd && env.directory && cwd !== env.directory) { return c.json( { error: { type: 'cwd_not_supported', message: `该连接为 in-process 单目录模式(${env.directory}),不能在其他目录创建会话。请用 \`slz rc\` 或 \`slz daemon start\` 启动 spawn 模式 worker。`, }, }, 409, ) } const existing = storeListSessionsByEnvironment(env.id).filter( s => !isSessionClosedStatus(s.status), ) if (existing.length > 0) { return c.json( { error: { type: 'worker_at_capacity', message: '该 worker 为 in-process 模式(slz 默认),只支持单会话。请用 `slz rc` 启动 spawn 模式 worker 支持多会话。', }, }, 409, ) } } } const teamId = typeof body.team_id === 'string' ? body.team_id : null const spawnMode = body.spawn_mode === 'worktree' || body.spawn_mode === 'same-dir' ? body.spawn_mode : undefined // Omitted → the worker's startup --permission-mode applies. Do not // hardcode 'default' here: it would silently override an operator's // daemon-wide mode choice on every Web-created session. const permissionMode = typeof body.permission_mode === 'string' && body.permission_mode ? body.permission_mode : undefined const session = createSession({ environment_id: body.environment_id || null, title: body.title || 'New Session', source: 'web', permission_mode: permissionMode, cwd, spawn_mode: spawnMode, visibility: teamId ? 'team' : 'private', }) // Bind team owner first (if creating in team context), then user owner. // Team ownership makes the session visible to all team members; user // ownership gives the creator explicit access. if (teamId) { storeBindSession(session.id, teamId, 'team') } if (bindUserId) { storeBindSession(session.id, bindUserId) } // Dispatch work to environment if specified. A dispatch failure must not // leave a phantom session behind: archive it and surface the error, so the // Web UI never shows a session that no worker will ever pick up. if (body.environment_id) { try { await createWorkItem(body.environment_id, session.id) } catch (err) { const message = (err as Error).message logError(`[RCS] Failed to create work item: ${message}`) try { archiveSession(session.id) } catch (archiveErr) { logError( `[RCS] Failed to archive undispatched session ${session.id}: ${(archiveErr as Error).message}`, ) } return c.json({ error: { type: 'work_dispatch_failed', message } }, 409) } } return c.json(session, 200) }) /** GET /web/sessions — List sessions visible to the requesting user. * Admin bypasses scope and sees all sessions. Non-admin sees sessions * owned by them, owned by their teams, shared with them, or public. * Optional ?team_id= filters to a specific team's sessions (server-side * scope, mirrors GET /web/environments). */ app.get('/sessions', sessionAuth, async c => { const uuid = c.get('userId')! const isAdmin = c.get('isAdmin') as boolean if (isAdmin) { return c.json(listSessions(), 200) } const teamId = c.req.query('team_id') if (teamId) { const sessions = listWebSessionsByOwnerUuid(uuid).filter( s => s.owner_type === 'team' && s.owner_id === teamId, ) return c.json(sessions, 200) } const sessions = listWebSessionsByOwnerUuid(uuid) return c.json(sessions, 200) }) /** GET /web/sessions/all — Summary list, same visibility rules as /sessions */ app.get('/sessions/all', sessionAuth, async c => { const uuid = c.get('userId')! const isAdmin = c.get('isAdmin') as boolean if (isAdmin) { return c.json(listSessionSummaries(), 200) } const teamId = c.req.query('team_id') if (teamId) { const sessions = listWebSessionSummariesByOwnerUuid(uuid).filter( s => s.owner_type === 'team' && s.owner_id === teamId, ) return c.json(sessions, 200) } const sessions = listWebSessionSummariesByOwnerUuid(uuid) return c.json(sessions, 200) }) /** POST /web/sessions/:id/attach-code — Mint a one-time attach code (P3). * The session manager shows/copies `slz rc --attach `; the CLI * redeems it via POST /v1/sessions/attach-code/exchange. The code IS the * authorization (15-min TTL, single use) — the CLI needs no manage rights * of its own. */ app.post('/sessions/:id/attach-code', sessionAuth, async c => { const uuid = c.get('userId')! const sessionId = resolveOwnedWebSessionId(c.req.param('id')!, uuid) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } if (!canManageSession(sessionId, uuid, getDb())) { return c.json( { error: { type: 'forbidden', message: 'Only session owner or team admin can mint attach codes', }, }, 403, ) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } if (isSessionClosedStatus(session.status)) { return c.json( { error: { type: 'session_closed', message: `Session is ${session.status}`, }, }, 409, ) } if (session.source === 'acp') { return c.json( { error: { type: 'acp_session', message: 'ACP sessions cannot be attached to a bridge worker', }, }, 409, ) } const record = storeIssueAttachCode(sessionId) return c.json( { code: record.code, expires_at: record.expiresAt.getTime(), attach_command: `slz rc --attach ${record.code}`, }, 201, ) }) /** GET /web/sessions/:id — Session detail */ app.get('/sessions/:id', sessionAuth, async c => { const uuid = c.get('userId')! const sessionId = resolveOwnedWebSessionId(c.req.param('id')!, uuid) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } const worker = storeGetSessionWorker(sessionId) const workItem = storeGetActiveWorkItemBySession(sessionId) const env = session.environment_id ? storeGetEnvironment(session.environment_id) : null const automationState = getAutomationStateSnapshot(worker?.externalMetadata) const response = toWebSessionResponse(session) const accessLevel = isSessionVisibleToUser(sessionId, uuid, getDb()) return c.json( { ...response, access_level: accessLevel, ...(automationState !== undefined ? { automation_state: automationState } : {}), worker: worker ? { status: worker.workerStatus, last_heartbeat_at: worker.lastHeartbeatAt ? worker.lastHeartbeatAt.getTime() : null, } : null, work_item: workItem ? { id: workItem.id, state: workItem.state, spawn_mode: workItem.spawnMode ?? null, cwd: workItem.cwd ?? null, } : null, environment: env ? { id: env.id, machine_name: env.machineName, worker_type: env.workerType, } : null, }, 200, ) }) /** GET /web/sessions/:id/history — Historical events for session. * Merges the durable SQLite log (survives restarts, no eviction) with the * in-memory bus window (covers events from before persistence existed / * test runs). Deduped by event id, ordered chronologically. */ app.get('/sessions/:id/history', sessionAuth, async c => { const uuid = c.get('userId')! const sessionId = resolveOwnedWebSessionId(c.req.param('id')!, uuid) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } const persisted = loadPersistedEvents(sessionId) const inMemory = getEventBus(sessionId).getEventsSince(0) const byId = new Map() for (const event of persisted) byId.set(event.id, event) for (const event of inMemory) { if (!byId.has(event.id)) byId.set(event.id, event) } // createdAt is monotonic across bus restarts (unlike seqNum), so it is the // primary sort key; seqNum breaks ties within one bus generation. const events = [...byId.values()].sort( (a, b) => a.createdAt - b.createdAt || a.seqNum - b.seqNum, ) // models_state fallback: the worker reports the model list once per bridge // connect, so the event log can legitimately lack it (/clear before the // re-seed existed, event-window eviction, pre-persistence servers). The // bus keeps the latest snapshot out-of-band — merge it here so the web UI // can restore the model selector on every re-entry. if (!events.some(e => e.type === 'models_state')) { const snapshot = getEventBus(sessionId).modelsStateSnapshot if (snapshot) { const lastCreated = events[events.length - 1]?.createdAt ?? Date.now() events.push({ id: `models_state_snapshot_${sessionId}`, sessionId, seqNum: 0, type: 'models_state', payload: { models_state: snapshot }, direction: 'inbound', createdAt: lastCreated + 1, }) } } return c.json({ events }, 200) }) /** GET /web/sessions/:id/models — Worker models_state snapshot. * Serves the artifacts AI-generate dialog's model picker: generation runs * inside the target session, so switching slots means sending set_model to * that session. The snapshot lives on the EventBus out-of-band (survives * /clear and event-window eviction); null when the worker never reported * models_state — the UI hides the picker in that case. */ app.get('/sessions/:id/models', sessionAuth, async c => { const uuid = c.get('userId')! const sessionId = resolveOwnedWebSessionId(c.req.param('id')!, uuid) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } if (!getSession(sessionId)) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } return c.json({ models: getEventBus(sessionId).modelsStateSnapshot }, 200) }) /** GET /web/search — Cross-session full-text search over conversation text. * Dashboard's search box. Results are grouped by session, visibility-filtered * (ownership + shares + team), capped at `limit` (default 20). */ app.get('/search', sessionAuth, async c => { const userId = c.get('userId')! const query = c.req.query('q') ?? '' const limitParam = Number(c.req.query('limit')) const limit = Number.isFinite(limitParam) && limitParam > 0 ? Math.min(Math.floor(limitParam), 50) : 20 const results = searchSessions(userId, query, limit) return c.json({ results }, 200) }) /** POST /web/sessions/:id/clear — Clear a session's conversation history. * Web-side /clear previously only emptied the local entry list, so * re-entering the session (or another team member opening it) replayed the * full persisted history. This wipes the durable SQLite event log and the * in-memory replay window (wipeSessionConversation), notifies live viewers * via a transient session_status event, AND forwards a clear control_request * to the connected REPL worker — without that the worker keeps its full * message history and the next prompt continues the old conversation, * making web-side /clear a view-only no-op. */ app.post('/sessions/:id/clear', sessionAuth, async c => { const uuid = c.get('userId')! const sessionId = resolveOwnedWebSessionId(c.req.param('id')!, uuid) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } if (!canManageSession(sessionId, uuid, getDb())) { return c.json( { error: { type: 'forbidden', message: 'Only session owner or team admin can clear history', }, }, 403, ) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } wipeSessionConversation(sessionId) // Tell the live worker to run its own full clear (REPL message array, // caches, session ID regeneration). Published TRANSIENT (not via // publishSessionEvent) so it reaches live WS/SSE subscribers but is never // retained — a persisted clear request would be replayed to the worker on // every reconnect and wipe an already-fresh conversation. getEventBus(sessionId).publish( { id: randomUUID(), sessionId, type: 'control_request', payload: { type: 'control_request', request_id: randomUUID(), request: { subtype: 'clear' }, }, direction: 'outbound', }, { transient: true }, ) return c.json({ status: 'ok' }, 200) }) /** POST /web/sessions/:id/rewind — Rewind the conversation to a prior user * message (web「回退到这里」). Unlike /clear this does NOT delete the event * log: rewind is event-sourced — a persisted `conversation_rewound` marker * tells every viewer (live SSE + future history replays) to truncate * rendering at the target event. The marker carries the worker-side * message_uuid, which the server resolves from the target event's payload — * web clients only know server event ids. The worker rewind itself is a * TRANSIENT outbound control_request (same replay-safety reasoning as * /clear: a persisted control would re-rewind on every reconnect). */ app.post('/sessions/:id/rewind', sessionAuth, async c => { const uuid = c.get('userId')! const sessionId = resolveOwnedWebSessionId(c.req.param('id')!, uuid, true) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } if (isSessionClosedStatus(session.status)) { return c.json( { error: { type: 'session_closed', message: `Session is ${session.status}`, }, }, 409, ) } const body = (await c.req.json()) as { target_event_id?: unknown } const targetEventId = body.target_event_id if (typeof targetEventId !== 'string' || !targetEventId) { return c.json( { error: { type: 'bad_request', message: 'target_event_id is required' }, }, 400, ) } // Resolve the worker-side message uuid from the target event. Check the // in-memory replay window first, then the durable log (window eviction). const bus = getEventBus(sessionId) let targetEvent: SessionEvent | undefined = bus .getEventsSince(0) .find(e => e.id === targetEventId) if (!targetEvent) { targetEvent = loadPersistedEvents(sessionId).find( e => e.id === targetEventId, ) } if ( !targetEvent || (targetEvent.type !== 'user' && targetEvent.type !== 'user_message') ) { return c.json( { error: { type: 'bad_request', message: 'Target event not found or not a user message', }, }, 400, ) } const payload = (targetEvent.payload ?? {}) as Record const messageUuid = typeof payload.uuid === 'string' && payload.uuid ? payload.uuid : targetEvent.id // Persisted marker — every viewer (and future history loads) truncates // rendering at the target event. Published inbound so SSE subscribers // receive it like worker-side events. publishSessionEvent( sessionId, 'conversation_rewound', { target_event_id: targetEventId, message_uuid: messageUuid }, 'inbound', ) // Transient worker control — never replayed on reconnect. bus.publish( { id: randomUUID(), sessionId, type: 'control_request', payload: { type: 'control_request', request_id: randomUUID(), request: { subtype: 'rewind_conversation', message_uuid: messageUuid, }, }, direction: 'outbound', }, { transient: true }, ) return c.json({ status: 'ok', message_uuid: messageUuid }, 200) }) /** PATCH /web/sessions/:id — Rename a session (owner or team admin). */ app.patch('/sessions/:id', sessionAuth, async c => { const uuid = c.get('userId')! const sessionId = resolveOwnedWebSessionId(c.req.param('id')!, uuid) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } if (!canManageSession(sessionId, uuid, getDb())) { return c.json( { error: { type: 'forbidden', message: 'Only session owner or team admin can rename', }, }, 403, ) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } const body = await c.req.json() const title = typeof body.title === 'string' ? body.title.trim() : '' if (!title || title.length > 200) { return c.json( { error: { type: 'invalid_request', message: 'title must be a non-empty string of at most 200 chars', }, }, 400, ) } updateSessionTitle(sessionId, title) return c.json(getSession(sessionId), 200) }) /** SSE /web/sessions/:id/events — Real-time event stream */ app.get('/sessions/:id/events', sessionAuth, async c => { const uuid = c.get('userId')! const sessionId = resolveOwnedWebSessionId(c.req.param('id')!, uuid) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } if (isSessionClosedStatus(session.status)) { return c.json( { error: { type: 'session_closed', message: `Session is ${session.status}`, }, }, 409, ) } // Resume point: Last-Event-ID header (browser auto-reconnect) or // ?fromSeqNum= query param (client-forced reconnects — EventSource has no // API to set request headers). NaN/0 → fresh connect, no replay. const lastEventId = c.req.header('Last-Event-ID') const fromSeqNum = parseInt(lastEventId ?? c.req.query('fromSeqNum') ?? '', 10) || 0 return createSSEStream(c, sessionId, fromSeqNum) }) /** DELETE /web/sessions/:id — Archive (soft-delete) a session. * Archived sessions disappear from the list but remain in storage for audit. * Also stops the associated work item so the worker's heartbeat detects 410 * and kills the child process, releasing capacity. */ app.delete('/sessions/:id', sessionAuth, async c => { const uuid = c.get('userId')! const rawSessionId = c.req.param('id')! // Resolve the session ID first (handles web/code prefix variants) using // visibility check — read access is enough to discover the session, but // deletion requires management permission (owner or team admin). const sessionId = resolveOwnedWebSessionId(rawSessionId, uuid) if (!sessionId) { return c.json( { error: { type: 'forbidden', message: 'Not your session' } }, 403, ) } if (!canManageSession(sessionId, uuid, getDb())) { return c.json( { error: { type: 'forbidden', message: 'Only session owner or team admin can delete', }, }, 403, ) } const session = getSession(sessionId) if (!session) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } // Stop the work item first so the worker's next heartbeat gets a 410 and // tears down the child process. Without this the worker keeps the child // alive and capacity stays consumed until the session times out. const workItem = storeGetActiveWorkItemBySession(sessionId) if (workItem) { stopWork(workItem.id) log( `[RCS] Stopped work item ${workItem.id} for archived session ${sessionId}`, ) } archiveSession(sessionId) return c.json({ status: 'ok' }, 200) }) export default app