import { config } from '../config' import { log } from '../logger' import { getDb } from '../db/sqlite' import { resolveUserIdUuid } from '../auth/bridge-auth' import { storeCreateEnvironment, storeCreateSession, storeGetEnvironment, storeUpdateEnvironment, storeListActiveEnvironments, storeListActiveEnvironmentsWithTeam, storeListActiveEnvironmentsByUsername, storeListAcpAgentsByChannelGroup, storeListSessionsByEnvironment, storeBindSession, storeGetEnvironmentOwnership, storeClaimEnvironment, storeSetEnvironmentClaim, storeBindEnvSessionsToUser, storeListWorkItems, storeUpdateWorkItem, } from '../store' import { isSessionClosedStatus } from './session' import { normalizeWorkspaceDirs } from './paths' import type { RegisterEnvironmentRequest, EnvironmentResponse, } from '../types/api' import type { EnvironmentRecord } from '../store' function toResponse( row: EnvironmentRecord & { teamId?: string | null teamName?: string | null ownerUserId?: string | null ownerUsername?: string | null }, ): EnvironmentResponse { return { id: row.id, machine_name: row.machineName, directory: row.directory, workspace_dirs: row.workspaceDirs && row.workspaceDirs.length > 0 ? row.workspaceDirs : row.directory ? [row.directory] : [], max_sessions: row.maxSessions, active_sessions: storeListSessionsByEnvironment(row.id).filter( s => !isSessionClosedStatus(s.status), ).length, branch: row.branch, status: row.status, username: row.username, ip_address: row.ipAddress, last_poll_at: row.lastPollAt ? row.lastPollAt.getTime() / 1000 : null, created_at: row.createdAt ? row.createdAt.getTime() / 1000 : null, worker_type: row.workerType, channel_group_id: row.bridgeId, capabilities: row.capabilities, team_id: row.teamId ?? null, team_name: row.teamName ?? null, owner_user_id: row.ownerUserId ?? null, // Attribution: prefer the owning account's username; fall back to the // OS user the worker reported at registration. owner_username: row.ownerUsername ?? row.username ?? null, attach_waiting: row.sessionMode === 'attach' && !storeListSessionsByEnvironment(row.id).some( s => !isSessionClosedStatus(s.status), ), } } /** Shape returned by registerEnvironment; spread into the HTTP response. */ export interface RegisterEnvironmentResult { environment_id: string environment_secret: string status: 'active' session_id?: string /** Set when a reattach continued an existing (or adopted a fresh) claim. */ claim_token?: string } export function registerEnvironment( req: RegisterEnvironmentRequest & { environment_id?: string metadata?: { worker_type?: string } username?: string ipAddress?: string | null ownerUserId?: string | null teamId?: string | null claimToken?: string | null claimExpiresAt?: Date | null session_mode?: string | null }, ): RegisterEnvironmentResult { const secret = config.apiKeys[0] || '' const workerType = req.worker_type || req.metadata?.worker_type // Advisory quick-pick list, never an access-control list. Legacy workers // send no workspace_dirs → fall back to their single startup directory. const workspaceDirs = normalizeWorkspaceDirs( req.workspace_dirs, req.directory, ) // Session Attach wait mode: only 'attach' is meaningful today. const sessionMode = req.session_mode === 'attach' ? 'attach' : null // Idempotent re-registration: the CLI echoes back a backend-issued // environment_id on restart (bridge pointer / --session-id resume). // Reattach instead of creating a duplicate env on every restart. // Not found / deregistered falls through to fresh creation — the client // already handles receiving a fresh environment_id. Note: ACP workers // only send bridge_id today; if one ever sends environment_id, the // explicit id wins and the bridge_id group-reuse below is skipped. if (req.environment_id) { const existing = storeGetEnvironment(req.environment_id) if (existing && existing.status !== 'deregistered') { storeUpdateEnvironment(existing.id, { status: 'active', lastPollAt: new Date(), machineName: req.machine_name, directory: req.directory, workspaceDirs, maxSessions: req.max_sessions, capabilities: req.capabilities ?? null, // Refresh the peer address on every re-registration — a laptop that // hopped networks should report its new address, not a stale one. ...(req.ipAddress ? { ipAddress: req.ipAddress } : {}), sessionMode, }) // Ownership is backfill-only: a restart must not reassign the env // (the route layer already gated reattach on admin/owner/unowned). const ownership = storeGetEnvironmentOwnership(existing.id) if (req.ownerUserId && !ownership?.ownerUserId) { storeClaimEnvironment(existing.id, req.ownerUserId) storeBindEnvSessionsToUser(existing.id, req.ownerUserId) } // Claim continuation: an unowned, unteamed env keeps its claim URL // across restarts — reuse the unexpired token, or adopt the freshly // minted one (persisted) when the previous claim expired. Without // this, the worker would print a claim URL for a token that no // longer exists in the DB. let claimToken: string | undefined if (!req.teamId && !ownership?.ownerUserId) { const unexpired = ownership?.claimToken != null && (!ownership.claimExpiresAt || new Date(ownership.claimExpiresAt) > new Date()) if (unexpired && ownership?.claimToken) { claimToken = ownership.claimToken } else if (req.claimToken) { claimToken = req.claimToken storeSetEnvironmentClaim( existing.id, req.claimToken, req.claimExpiresAt ?? null, ) } } return { environment_id: existing.id, environment_secret: existing.secret, status: 'active', ...(claimToken ? { claim_token: claimToken } : {}), } } } // ACP agents with a bridge_id (channel group): reuse the most recent // offline env in the same group instead of creating a new one on every // reconnect. acp-link's WS gets closed by the inactivity timeout (or any // network blip), triggering REST re-registration — without reuse, each // reconnect created a fresh env with a new agentId, orphaning the old // one (marked offline but never deleted) and breaking // /acp/relay/ for any frontend that remembered the old id. // Reuse stabilizes the agentId across reconnects. Active envs in the // same group belong to other acp-link instances and are NOT reused. if (workerType === 'acp' && req.bridge_id) { const offline = storeListAcpAgentsByChannelGroup(req.bridge_id) .filter(e => e.status === 'offline') .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()) if (offline.length > 0) { const record = offline[0]! storeUpdateEnvironment(record.id, { status: 'active', lastPollAt: new Date(), capabilities: req.capabilities ?? null, machineName: req.machine_name, directory: req.directory, workspaceDirs, maxSessions: req.max_sessions, ...(req.ipAddress ? { ipAddress: req.ipAddress } : {}), }) // Backfill ownership: the reused env may still be unowned (claim flow // pending). Idempotent — storeClaimEnvironment only writes when // owner_user_id IS NULL, so a fresh ownerUserId never overwrites. if (req.ownerUserId) { const ownership = storeGetEnvironmentOwnership(record.id) if (!ownership?.ownerUserId) { storeClaimEnvironment(record.id, req.ownerUserId) } } const sessions = storeListSessionsByEnvironment(record.id) let sessionId: string if (sessions.length > 0) { sessionId = sessions[0]!.id } else { // Inherit ownership from the env (may still be null if the reused // offline env is in the claim flow — claim flow backfills later). const ownership = storeGetEnvironmentOwnership(record.id) const session = storeCreateSession({ environmentId: record.id, title: req.machine_name || 'ACP Agent', source: 'acp', username: req.username, visibility: ownership?.teamId ? 'team' : 'private', }) sessionId = session.id if (ownership?.ownerUserId) { storeBindSession(sessionId, ownership.ownerUserId, 'user') } if (ownership?.teamId) { storeBindSession(sessionId, ownership.teamId, 'team') } } return { environment_id: record.id, environment_secret: record.secret, status: 'active' as const, session_id: sessionId, } } } const record = storeCreateEnvironment({ secret, machineName: req.machine_name, directory: req.directory, workspaceDirs, branch: req.branch, gitRepoUrl: req.git_repo_url, maxSessions: req.max_sessions, workerType, bridgeId: req.bridge_id, username: req.username, ipAddress: req.ipAddress ?? undefined, capabilities: req.capabilities, ownerUserId: req.ownerUserId, claimToken: req.claimToken, claimExpiresAt: req.claimExpiresAt, sessionMode, }) let sessionId: string | undefined // ACP agents: reuse existing session or create one if (workerType === 'acp') { const existing = storeListSessionsByEnvironment(record.id) if (existing.length > 0) { sessionId = existing[0].id } else { const session = storeCreateSession({ environmentId: record.id, title: req.machine_name || 'ACP Agent', source: 'acp', username: req.username, visibility: req.teamId ? 'team' : 'private', }) sessionId = session.id // Inherit ownership from the env at creation time. If the env is // still unowned (claim flow pending), session_owners stays empty // and the claim flow backfills it when a user claims the env. if (req.ownerUserId) { storeBindSession(sessionId, req.ownerUserId, 'user') } if (req.teamId) { storeBindSession(sessionId, req.teamId, 'team') } } } return { environment_id: record.id, environment_secret: record.secret, status: record.status as 'active', session_id: sessionId, } } export function deregisterEnvironment(envId: string) { storeUpdateEnvironment(envId, { status: 'deregistered' }) // Complete the env's open work items. Without this, a clean CLI exit // leaves the acked item behind and isSessionOccupied keeps reporting // session_busy (the reclaim path only covers dispatched items on a LIVE // env). kill -9 crashes skip this — the env-status check in // isSessionOccupied is the recovery path for those. for (const item of storeListWorkItems()) { if (item.environmentId === envId && item.state !== 'completed') { storeUpdateWorkItem(item.id, { state: 'completed' }) log( `[RCS] Completed orphaned work item ${item.id} (session=${item.sessionId}) on deregistered env ${envId}`, ) } } } export function getEnvironment(envId: string) { return storeGetEnvironment(envId) } /** * Worker-traffic liveness signal: refresh lastPollAt and, when the disconnect * monitor had flipped the env to 'disconnected', reactivate it. * * The flip is based on a stale heartbeat — a worker actively hitting the env * (work poll, assignment poll, session-creation retry during claim wait, * work-item heartbeat while at capacity, v2 worker register/heartbeat) * proves it is alive. Without reactivation the CLI polls a zombie env * forever: the work-poll route never 404s, so the client's env-lost recovery * never fires, and any session created on the flipped env gets no work item * (createWorkItem rejects non-active envs) — a session that exists but can * never connect. 'deregistered' is terminal and stays dead. */ export function touchEnvironmentActivity(envId: string) { const env = storeGetEnvironment(envId) if (!env) return if (env.status === 'disconnected') { storeUpdateEnvironment(envId, { status: 'active', lastPollAt: new Date() }) log( `[RCS] Environment ${envId} reactivated by worker traffic (was disconnected)`, ) } else if (env.status === 'active') { storeUpdateEnvironment(envId, { lastPollAt: new Date() }) } } export function listActiveEnvironments() { return storeListActiveEnvironments() } export function listActiveEnvironmentsResponse( includeDisconnected = false, ): EnvironmentResponse[] { return storeListActiveEnvironmentsWithTeam(includeDisconnected).map(r => toResponse(r), ) } export function listActiveEnvironmentsByUsername( username: string, ): EnvironmentResponse[] { return storeListActiveEnvironmentsByUsername(username).map(r => toResponse(r)) } export function reconnectEnvironment(envId: string) { storeUpdateEnvironment(envId, { status: 'active' }) } /** * Whether a Web user may use an environment (create sessions on that * machine, list its recent directories). * * RCS authorization is machine-level: anyone who can use the environment may * start a session in any directory on it. The same visibility rules as * GET /web/environments apply: admin, direct owner, or a member of the team * the environment is linked to. Unowned environments are claim-flow pending * and intentionally invisible to non-admins. */ export function canUseEnvironment( envId: string, userId: string, isAdmin: boolean, ): boolean { if (isAdmin) return true const ownership = storeGetEnvironmentOwnership(envId) if (!ownership) return false // Authentication yields either a users.id UUID (SQLite session token) or a // username (legacy in-memory token). Normalize to both forms so an owned // machine is usable under either credential. let callerUuid: string | null = null try { callerUuid = resolveUserIdUuid(getDb(), userId) } catch { callerUuid = null } if ( ownership.ownerUserId && (ownership.ownerUserId === userId || ownership.ownerUserId === callerUuid) ) { return true } if (ownership.teamId) { try { const row = getDb() .query( `SELECT 1 FROM team_members WHERE team_id = $teamId AND user_id = $userId LIMIT 1`, ) .get({ $teamId: ownership.teamId, $userId: callerUuid ?? userId, }) return !!row } catch (err) { console.error('[RCS] team membership lookup failed:', err) return false } } return false }