Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
90.1 KB
Raw Blame
import {
  BrowserWindow,
  IpcMainInvokeEvent,
  Notification,
  app,
  clipboard,
  dialog,
  ipcMain,
} from 'electron'
import { randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { parseFileReferenceV1 } from '@clerum/gfs-interaction-policy'
import { AppService } from './appService.js'
import { runChatGetIndex } from './chatGetIndexHandler.js'
import {
  getChatStoreBindingGeneration,
  requireChatStore,
  requireChatStoreForBindingGeneration,
} from './chatStoreBinding.js'
import { GFS_DOWNLOAD_MAX_BYTES_CEILING } from './gfs/downloadLimits.js'
import { GFS_PREVIEW_MAX_BYTES } from './gfs/previewLimits.js'
import {
  abortZipJob,
  appendZipEntry,
  appendZipEntryStreaming,
  finishZipJob,
  startZipJob,
} from './gfs/zipStream.js'
import { assertSafeRouteSegment } from './pathSafety.js'
import {
  PLUGIN_SDK_CAPABILITIES_CHANNEL,
  PLUGIN_SDK_CONSENT_RESOLVE_CHANNEL,
  PLUGIN_SDK_PERMISSIONS_CHANNEL,
  PLUGIN_SDK_PERMISSION_STATE_CHANNEL,
  PLUGIN_SDK_REQUEST_CHANNEL,
} from './pluginSdkProtocol.js'
import {
  type ChatAuthorityScope,
  type ChatDeleteFence,
  DesktopRuntimeConfig,
  EntityChangeStreamEvent,
  HostActivityStreamEvent,
  HostMessageAttachment,
  HostMessageRequest,
  HostStatusStreamEvent,
  TaskProgressStreamEvent,
  WorkflowNotificationStreamEvent,
} from './types.js'

function sanitizeString(input: unknown): string {
  return String(input || '').trim()
}

// The renderer names each sandbox-ui open so it can tell events of the view
// that open mounted from those of a view it replaced (same appRef on a
// relaunch). Main outlives renderer reloads and keeps reporting views opened by
// an earlier renderer, so the id must be unique across renderer lifetimes: a
// random UUID, never a counter. It is echoed verbatim on IPC events.
const SANDBOX_UI_LAUNCH_ID_PATTERN =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

function parseSandboxUiLaunchId(input: unknown): string {
  if (typeof input !== 'string' || !SANDBOX_UI_LAUNCH_ID_PATTERN.test(input)) {
    throw new Error('launchId must be a UUID')
  }
  return input
}

function sanitizeChatAuthorityScope(input: unknown): ChatAuthorityScope {
  if (!input || typeof input !== 'object' || Array.isArray(input)) {
    throw new Error('Invalid chat deletion authority scope')
  }
  const value = input as Record<string, unknown>
  const environmentKey = sanitizeString(value.environmentKey)
  const userId = sanitizeString(value.userId)
  const teamId = value.teamId === null ? null : sanitizeString(value.teamId)
  if (!environmentKey || !userId || (value.teamId !== null && !teamId)) {
    throw new Error('Invalid chat deletion authority scope')
  }
  return { environmentKey, userId, teamId }
}

function sameChatAuthorityScope(left: ChatAuthorityScope, right: ChatAuthorityScope): boolean {
  return (
    left.environmentKey === right.environmentKey &&
    left.userId === right.userId &&
    left.teamId === right.teamId
  )
}

function sanitizeChatDeleteFence(input: unknown): ChatDeleteFence {
  if (!input || typeof input !== 'object' || Array.isArray(input)) {
    throw new Error('Scoped chat deletion is required')
  }
  const value = input as Record<string, unknown>
  const bindingGeneration = value.bindingGeneration
  const sessionGeneration = value.sessionGeneration
  if (
    value.version !== 1 ||
    typeof bindingGeneration !== 'number' ||
    !Number.isSafeInteger(bindingGeneration) ||
    bindingGeneration < 1 ||
    typeof sessionGeneration !== 'number' ||
    !Number.isSafeInteger(sessionGeneration) ||
    sessionGeneration < 0
  ) {
    throw new Error('Invalid chat deletion fence')
  }
  return {
    version: 1,
    authorityScope: sanitizeChatAuthorityScope(value.authorityScope),
    bindingGeneration,
    sessionGeneration,
  }
}

/**
 * Sanitize a bulk subject-key array (grant/share to many subjects in one call).
 * Fails loud on a non-array or empty payload rather than silently no-op'ing — an
 * empty selection is a renderer bug, and the server re-validates the 1..100 bound.
 */
function sanitizeSubjectKeys(input: unknown): string[] {
  if (!Array.isArray(input) || input.length === 0) {
    throw new Error('subjectKeys must be a non-empty array')
  }
  return input.map(sanitizeString)
}

function sanitizeOptionalInteger(input: unknown): number | undefined {
  if (input === undefined || input === null || input === '') return undefined
  if (typeof input !== 'number' || !Number.isSafeInteger(input)) {
    throw new Error('Invalid integer')
  }
  return input
}

function sanitizeOptionalPositiveInteger(input: unknown, label: string): number | undefined {
  if (input === undefined || input === null || input === '') return undefined
  if (typeof input !== 'number' || !Number.isSafeInteger(input) || input < 1) {
    throw new Error(`Invalid ${label}`)
  }
  return input
}

export function sanitizeChatLoadWindow(
  limitInput: unknown,
  offsetInput: unknown
): { limit?: number; offset?: number } {
  const limit = sanitizeOptionalInteger(limitInput)
  const offset = sanitizeOptionalInteger(offsetInput)
  if (limit !== undefined && (limit < 1 || limit > 1000)) {
    throw new Error('Invalid chat message limit')
  }
  if (offset !== undefined && offset < 0) {
    throw new Error('Invalid chat message offset')
  }
  return {
    ...(limit !== undefined ? { limit } : {}),
    ...(offset !== undefined ? { offset } : {}),
  }
}

function sanitizeSessionsListQuery(
  input: import('./types.js').SessionsListQuery | undefined
): import('./types.js').SessionsListQuery {
  const agent = sanitizeString(input?.agent)
  const cursor = sanitizeString(input?.cursor)
  if (agent && (agent.length > 200 || agent.includes(':'))) {
    throw new Error('Invalid session agent')
  }
  if (cursor.length > 2048) throw new Error('Invalid sessions cursor')
  const rawLimit = sanitizeOptionalInteger(input?.limit)
  if (rawLimit !== undefined && rawLimit < 1) throw new Error('Invalid sessions limit')
  return {
    ...(agent ? { agent } : {}),
    ...(rawLimit !== undefined ? { limit: Math.min(rawLimit, 100) } : {}),
    ...(cursor ? { cursor } : {}),
  }
}

function sanitizeSessionMessagesQuery(
  input: import('./types.js').SessionMessagesQuery | undefined
): import('./types.js').SessionMessagesQuery {
  const rawLimit = sanitizeOptionalInteger(input?.limit)
  const beforeTurn = sanitizeOptionalInteger(input?.beforeTurn)
  const afterTurn = sanitizeOptionalInteger(input?.afterTurn)
  if (rawLimit !== undefined && rawLimit < 1) throw new Error('Invalid messages limit')
  if (beforeTurn !== undefined && beforeTurn < 1) throw new Error('Invalid beforeTurn')
  if (afterTurn !== undefined && afterTurn < 0) throw new Error('Invalid afterTurn')
  if (beforeTurn !== undefined && afterTurn !== undefined) {
    throw new Error('beforeTurn and afterTurn are mutually exclusive')
  }
  return {
    ...(rawLimit !== undefined ? { limit: Math.min(rawLimit, 200) } : {}),
    ...(beforeTurn !== undefined ? { beforeTurn } : {}),
    ...(afterTurn !== undefined ? { afterTurn } : {}),
  }
}

function runScopedArtifactDownloadName(runId: string, artifactName: string): string {
  const rawName = path.basename(artifactName).replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
  const safeName = rawName || 'artifact'
  const prefix = runId.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 8)
  return prefix ? `${prefix}-${safeName}` : safeName
}

async function writeUniqueDownload(
  downloadsDir: string,
  filename: string,
  bytes: Uint8Array
): Promise<{ filePath: string; filename: string }> {
  const parsed = path.parse(filename)
  for (let attempt = 0; attempt < 100; attempt += 1) {
    const candidateName = attempt === 0 ? filename : `${parsed.name} (${attempt})${parsed.ext}`
    const candidatePath = path.join(downloadsDir, candidateName)
    try {
      const handle = await fs.open(candidatePath, 'wx')
      try {
        await handle.writeFile(bytes)
      } finally {
        await handle.close()
      }
      return { filePath: candidatePath, filename: candidateName }
    } catch (err) {
      if ((err as NodeJS.ErrnoException)?.code !== 'EEXIST') throw err
    }
  }
  throw new Error('Could not create a unique artifact download filename')
}

/** A model-selection revision (issue #654 CAS base): a non-negative integer. */
function isSelectionRevision(value: unknown): value is number {
  return Number.isSafeInteger(value) && (value as number) >= 0
}

const SHA256_HEX = /^[0-9a-f]{64}$/

function isPlainObject(value: unknown): value is Record<string, unknown> {
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
}

/**
 * Checks the shape of every `kind:'file'` attachment (#678). mcp-host enforces
 * the size limits and recomputes the size and the digest; an image entry keeps
 * the contract it always had and is not inspected here.
 */
function parseHostMessageAttachments(attachments: unknown): HostMessageAttachment[] {
  if (!Array.isArray(attachments)) {
    throw new Error('Invalid host message request: attachments')
  }
  attachments.forEach((entry, index) => {
    if (!isPlainObject(entry) || entry.kind !== 'file') return
    const digest = entry.digest
    const problem =
      typeof entry.id !== 'string' || !entry.id.trim()
        ? 'id'
        : typeof entry.filename !== 'string' || !entry.filename
          ? 'filename'
          : typeof entry.mimeType !== 'string'
            ? 'mimeType'
            : typeof entry.detectedMediaType !== 'string'
              ? 'detectedMediaType'
              : entry.encoding !== 'base64'
                ? 'encoding'
                : typeof entry.dataBase64 !== 'string'
                  ? 'dataBase64'
                  : !Number.isSafeInteger(entry.sizeBytes) || (entry.sizeBytes as number) < 0
                    ? 'sizeBytes'
                    : !isPlainObject(digest) ||
                        digest.algorithm !== 'sha256' ||
                        typeof digest.hex !== 'string' ||
                        !SHA256_HEX.test(digest.hex)
                      ? 'digest'
                      : null
    if (problem) {
      throw new Error(
        `Invalid host message request: COMPOSER_FILE_ATTACHMENT_INVALID attachments[${index}].${problem}`
      )
    }
  })
  return attachments as HostMessageAttachment[]
}

function parseHostMessageRequest(raw: unknown): HostMessageRequest {
  const parsed = raw as HostMessageRequest
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    throw new Error('Invalid host message request')
  }
  if (typeof parsed.content !== 'string' || !parsed.content.trim()) {
    throw new Error('Invalid host message request')
  }
  if (parsed.model !== undefined && (typeof parsed.model !== 'string' || !parsed.model.trim())) {
    throw new Error('Invalid host message request: model')
  }
  if (
    parsed.modelSelectionRevision !== undefined &&
    !isSelectionRevision(parsed.modelSelectionRevision)
  ) {
    throw new Error('Invalid host message request: modelSelectionRevision')
  }
  if (parsed.attachments != null) {
    parsed.attachments = parseHostMessageAttachments(parsed.attachments)
  }
  if (parsed.fileReferences !== undefined) {
    // Checks shape only; mcp-host enforces the count limit and resolves each reference.
    if (!Array.isArray(parsed.fileReferences)) {
      throw new Error('Invalid host message request: fileReferences')
    }
    const fileReferences = parsed.fileReferences.map((entry, index) => {
      const result = parseFileReferenceV1(entry)
      if (!result.ok) {
        throw new Error(
          `Invalid host message request: fileReferences[${index}] ${result.code}: ${result.message}`
        )
      }
      return result.value
    })
    return { ...parsed, fileReferences }
  }
  return parsed
}

export function assertTrustedSender(event: IpcMainInvokeEvent): void {
  const senderUrl = String(event.senderFrame?.url || '')
  const devUrl = String(process.env.EVENFIRE_RENDERER_URL || '').trim()
  const isFileSender = senderUrl.startsWith('file://')
  const isDevSender = Boolean(devUrl) && senderUrl.startsWith(devUrl)
  if (!isFileSender && !isDevSender) {
    throw new Error('Untrusted IPC sender')
  }
}

/**
 * The identity of the window that owns a ZIP job (R3-M2). A job is opened by
 * one window and may only be driven by that window: without this, any renderer
 * that got hold of a job id could append to, finish or abort another
 * window's archive.
 */
function zipJobOwnerId(event: IpcMainInvokeEvent): string {
  return String(event.sender?.id ?? 'unknown')
}

type DesktopNotificationActionInput = {
  action?: string
  title?: string
}

type DesktopNotificationInput = {
  id?: string
  title?: string
  body?: string
  tag?: string
  silent?: boolean
  actions?: DesktopNotificationActionInput[]
}

function sanitizeDesktopNotificationActions(
  actions: unknown
): Array<{ action: string; title: string }> {
  if (!Array.isArray(actions)) return []
  return actions
    .map(rawAction => {
      const action = rawAction as DesktopNotificationActionInput
      return {
        action: sanitizeString(action?.action),
        title: sanitizeString(action?.title),
      }
    })
    .filter(action => action.action && action.title)
    .slice(0, 3)
}

export function registerIpcHandlers(service: AppService): void {
  const streamOwnerCleanupRegistered = new Set<number>()
  const entityChangeOwnerCleanupRegistered = new Set<number>()
  const activeDesktopNotifications = new Map<string, Notification>()

  // Producer-side cancellation for cancellable GFS reads (folder-zip walk,
  // R1-M1): the renderer attaches a requestId to an invoke and fires
  // 'gfs:abort' on Stop; the in-flight request's AbortController ends the
  // producer fetch instead of leaving it to burn the read budget.
  const gfsRequestAborters = new Map<string, AbortController>()
  ipcMain.on('gfs:abort', (event, payload: { requestId?: string }) => {
    try {
      assertTrustedSender(event)
    } catch {
      return
    }
    const requestId = payload?.requestId ? sanitizeString(payload.requestId) : ''
    if (requestId) gfsRequestAborters.get(requestId)?.abort()
  })
  function runWithGfsAbortSignal<T>(
    requestId: string | undefined,
    run: (signal?: AbortSignal) => Promise<T>
  ): Promise<T> {
    if (!requestId) return run(undefined)
    const controller = new AbortController()
    gfsRequestAborters.set(requestId, controller)
    return run(controller.signal).finally(() => {
      gfsRequestAborters.delete(requestId)
    })
  }

  ipcMain.handle('auth:getSessionState', async event => {
    assertTrustedSender(event)
    return service.getSessionState()
  })
  ipcMain.handle('auth:getSessionGeneration', async event => {
    assertTrustedSender(event)
    return service.getSessionGeneration()
  })
  ipcMain.handle('auth:getDependenciesHealth', async event => {
    assertTrustedSender(event)
    return service.getDependenciesHealth()
  })
  ipcMain.handle('auth:getRuntimeConfigState', async event => {
    assertTrustedSender(event)
    return service.getRuntimeConfigState()
  })
  ipcMain.handle('auth:selectRuntimeConfig', async (event, payload: { optionId: string }) => {
    assertTrustedSender(event)
    return service.selectRuntimeConfig(sanitizeString(payload?.optionId))
  })
  ipcMain.handle(
    'auth:selectRuntimeConfigForHandoff',
    async (event, payload: { optionId: string; expectedSessionGeneration: unknown }) => {
      assertTrustedSender(event)
      const expectedSessionGeneration = payload?.expectedSessionGeneration
      if (
        typeof expectedSessionGeneration !== 'number' ||
        !Number.isSafeInteger(expectedSessionGeneration) ||
        expectedSessionGeneration < 0
      ) {
        throw new Error('Invalid session generation')
      }
      return service.selectRuntimeConfigForHandoff(
        sanitizeString(payload?.optionId),
        expectedSessionGeneration
      )
    }
  )
  ipcMain.handle('auth:clearRuntimeConfigSelection', async event => {
    assertTrustedSender(event)
    return service.clearRuntimeConfigSelection()
  })
  ipcMain.handle(
    'auth:saveRuntimeConfig',
    async (event, payload: DesktopRuntimeConfig & { expectedSessionGeneration?: unknown }) => {
      assertTrustedSender(event)
      const rawExpectedSessionGeneration = payload?.expectedSessionGeneration
      if (
        rawExpectedSessionGeneration !== undefined &&
        (typeof rawExpectedSessionGeneration !== 'number' ||
          !Number.isSafeInteger(rawExpectedSessionGeneration) ||
          rawExpectedSessionGeneration < 0)
      ) {
        throw new Error('Invalid session generation')
      }
      const runtimeConfig = {
        externalRestApiBaseUrl: sanitizeString(payload?.externalRestApiBaseUrl),
        rpcProxyBaseUrl: sanitizeString(payload?.rpcProxyBaseUrl),
        appName: sanitizeString(payload?.appName),
      }
      if (rawExpectedSessionGeneration === undefined) {
        return service.saveRuntimeConfig(runtimeConfig)
      }
      return service.saveRuntimeConfig(runtimeConfig, rawExpectedSessionGeneration)
    }
  )
  ipcMain.handle('auth:deleteRuntimeConfig', async (event, payload: { optionId: string }) => {
    assertTrustedSender(event)
    return service.deleteRuntimeConfig(sanitizeString(payload?.optionId))
  })
  ipcMain.handle('auth:googleLogin', async (event, payload: { idToken: string }) => {
    assertTrustedSender(event)
    return service.googleLogin(sanitizeString(payload?.idToken))
  })
  ipcMain.handle(
    'auth:passwordLogin',
    async (event, payload: { email: string; password: string }) => {
      assertTrustedSender(event)
      return service.passwordLogin(
        sanitizeString(payload?.email).toLowerCase(),
        String(payload?.password || '')
      )
    }
  )
  ipcMain.handle('auth:diagnoseLoginBackend', async event => {
    assertTrustedSender(event)
    return service.diagnoseLoginBackend()
  })
  ipcMain.handle('auth:probeLocalhostReachable', async event => {
    assertTrustedSender(event)
    return service.probeLocalhostReachable()
  })
  ipcMain.handle('auth:openDeploymentDocs', async event => {
    assertTrustedSender(event)
    return service.openDeploymentDocs()
  })
  ipcMain.handle('auth:openHostedSignup', async event => {
    assertTrustedSender(event)
    return service.openHostedSignup()
  })
  ipcMain.handle('auth:startDesktopSetup', async (event, payload: { email: string }) => {
    assertTrustedSender(event)
    return service.startDesktopSetup(sanitizeString(payload?.email).toLowerCase())
  })
  ipcMain.handle('auth:openForgotPassword', async (event, payload: { email?: string }) => {
    assertTrustedSender(event)
    return service.openForgotPassword(sanitizeString(payload?.email || '').toLowerCase())
  })
  ipcMain.handle(
    'auth:openProfileSettings',
    async (
      event,
      payload: { email?: string; section?: string; network?: string; action?: string }
    ) => {
      assertTrustedSender(event)
      const action = payload?.action === 'password' ? 'password' : undefined
      const section = payload?.section === 'social' ? 'social' : 'profile'
      return service.openProfileSettings(sanitizeString(payload?.email || '').toLowerCase(), {
        section,
        network: sanitizeString(payload?.network || '').toLowerCase(),
        action,
      })
    }
  )
  ipcMain.handle(
    'auth:completeDesktopSetup',
    async (event, payload: { email: string; authorizationToken: string }) => {
      assertTrustedSender(event)
      return service.completeDesktopSetup(
        sanitizeString(payload?.email).toLowerCase(),
        sanitizeString(payload?.authorizationToken)
      )
    }
  )
  ipcMain.handle('auth:getDesktopReleaseStatus', async event => {
    assertTrustedSender(event)
    return service.getDesktopReleaseStatus()
  })
  ipcMain.handle('auth:getDesktopAppInfo', async event => {
    assertTrustedSender(event)
    return service.getDesktopAppInfo()
  })
  ipcMain.handle('auth:openDesktopRelease', async (event, payload: { releaseUrl: string }) => {
    assertTrustedSender(event)
    return service.openDesktopRelease(sanitizeString(payload?.releaseUrl))
  })
  ipcMain.handle('auth:logout', async event => {
    assertTrustedSender(event)
    const sessionGeneration = await service.logout()
    return { ok: true, sessionGeneration }
  })

  ipcMain.handle('notifications:isSupported', async event => {
    assertTrustedSender(event)
    return Notification.isSupported()
  })

  ipcMain.handle('notifications:show', async (event, payload: DesktopNotificationInput) => {
    assertTrustedSender(event)
    if (!Notification.isSupported()) return { supported: false, id: '' }

    const id = sanitizeString(payload?.id) || randomUUID()
    const title = sanitizeString(payload?.title) || 'Evenfire'
    const body = String(payload?.body || '').trim()
    const actions = sanitizeDesktopNotificationActions(payload?.actions)
    const owner = BrowserWindow.fromWebContents(event.sender) ?? undefined
    const sendToRenderer = (channel: string, detail: Record<string, string>) => {
      if (event.sender.isDestroyed()) return
      event.sender.send(channel, detail)
    }
    const focusOwner = () => {
      if (!owner || owner.isDestroyed()) return
      if (owner.isMinimized()) owner.restore()
      owner.show()
      owner.focus()
    }

    const notification = new Notification({
      title,
      body,
      silent: payload?.silent === true,
      actions: actions.map(action => ({ type: 'button', text: action.title })),
      closeButtonText: 'Dismiss',
      timeoutType: actions.length > 0 ? 'never' : 'default',
    })

    activeDesktopNotifications.set(id, notification)
    notification.on('click', () => {
      focusOwner()
      sendToRenderer('notifications:click', { id })
    })
    notification.on('action', (details, actionIndex) => {
      focusOwner()
      const index =
        typeof details.actionIndex === 'number'
          ? details.actionIndex
          : typeof actionIndex === 'number'
            ? actionIndex
            : -1
      const action = actions[index]?.action
      if (action) {
        sendToRenderer('notifications:action', { id, action })
      }
    })
    notification.on('close', () => {
      activeDesktopNotifications.delete(id)
    })
    notification.on('failed', (_event, error) => {
      activeDesktopNotifications.delete(id)
      sendToRenderer('notifications:failed', { id, error: String(error || 'Notification failed') })
    })
    notification.show()
    return { supported: true, id }
  })

  ipcMain.handle('team:list', async event => {
    assertTrustedSender(event)
    return service.listTeams()
  })
  ipcMain.handle('team:members', async event => {
    assertTrustedSender(event)
    return service.listTeamMembers()
  })
  ipcMain.handle('gfs:resolve', async (event, payload: { uri: string }) => {
    assertTrustedSender(event)
    return service.resolveGfsUri(sanitizeString(payload?.uri))
  })
  ipcMain.handle(
    'gfs:download',
    async (event, payload: { uri: string; maxBytes?: number; requestId?: string }) => {
      assertTrustedSender(event)
      // Optional producer-side bound (folder-zip walk): when present it is
      // validated here in main so an over-large body is rejected before it
      // materializes in either process. Absent keeps the single-file
      // save-to-disk path uncapped.
      const maxBytes = sanitizeOptionalPositiveInteger(payload?.maxBytes, 'maxBytes')
      if (maxBytes !== undefined && maxBytes > GFS_DOWNLOAD_MAX_BYTES_CEILING) {
        throw new Error('download limit exceeds the allowed maximum')
      }
      const requestId = payload?.requestId ? sanitizeString(payload.requestId) : undefined
      return runWithGfsAbortSignal(requestId, signal =>
        service.downloadGfsUri(sanitizeString(payload?.uri), maxBytes, signal)
      )
    }
  )
  ipcMain.handle(
    'gfs:downloadPreview',
    async (event, payload: { uri: string; maxBytes: number }) => {
      assertTrustedSender(event)
      // The preview path is bounded: a required ceiling caps the download so an
      // oversized payload is rejected before it materializes (the save-to-disk
      // 'gfs:download' path above stays intentionally uncapped).
      const maxBytes = sanitizeOptionalPositiveInteger(payload?.maxBytes, 'maxBytes')
      if (maxBytes === undefined) {
        throw new Error('maxBytes is required for a preview download')
      }
      // The renderer is untrusted: it may ask for a smaller per-type limit, but
      // the ceiling is enforced here in main. Reject (not clamp) an over-cap
      // request — a value above the app maximum is a bug or a tampered payload,
      // consistent with the fail-loud missing-maxBytes guard above.
      if (maxBytes > GFS_PREVIEW_MAX_BYTES) {
        throw new Error('preview download limit exceeds the allowed maximum')
      }
      return service.downloadGfsUri(sanitizeString(payload?.uri), maxBytes)
    }
  )
  ipcMain.handle(
    'gfs:listAccessible',
    async (event, payload: { drive?: string; cursor?: string }) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      const cursor = payload?.cursor ? sanitizeString(payload.cursor) : undefined
      return service.listAccessibleGfsResources(drive, cursor)
    }
  )
  ipcMain.handle(
    'gfs:listChildren',
    async (
      event,
      payload: { resourceId: string; drive?: string; cursor?: string; requestId?: string }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      const cursor = payload?.cursor ? sanitizeString(payload.cursor) : undefined
      const requestId = payload?.requestId ? sanitizeString(payload.requestId) : undefined
      return runWithGfsAbortSignal(requestId, signal =>
        service.listGfsChildren(sanitizeString(payload?.resourceId), drive, cursor, signal)
      )
    }
  )
  ipcMain.handle(
    'gfs:affordances',
    async (event, payload: { resourceId: string; drive?: string }) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.gfsAffordances(sanitizeString(payload?.resourceId), drive)
    }
  )
  // Streamed, file-backed folder-zip assembly (R1-H2): entries append to a
  // main-process temp file, finish saves through a native dialog. All five
  // channels trust-check.
  //
  // The MAIN process owns the guarantees here (the renderer is untrusted):
  //   - every entry name is validated as a canonical relative path BEFORE a
  //     byte of entry data is written (R3-M1);
  //   - the aggregate byte/entry budget, the ZIP32 bounds, the job's owner and
  //     the concurrency bounds are enforced here, not only in the renderer
  //     (R3-M2);
  //   - the job owns its handle and its temp file until the save completes
  //     (R3-M3).
  //
  // The job is bound to the window that opened it: another window cannot
  // append to, finish or abort it.
  ipcMain.handle('gfs:zipStream:start', async event => {
    assertTrustedSender(event)
    return { jobId: await startZipJob(zipJobOwnerId(event)) }
  })
  ipcMain.handle(
    'gfs:zipStream:append',
    async (event, payload: { jobId: string; name: string; bytes: ArrayBuffer }) => {
      assertTrustedSender(event)
      const name = sanitizeString(payload?.name)
      if (!name) throw new Error('zipStream append requires an entry name')
      if (!(payload?.bytes instanceof ArrayBuffer)) {
        throw new Error('zipStream append requires entry bytes')
      }
      if (payload.bytes.byteLength > GFS_DOWNLOAD_MAX_BYTES_CEILING) {
        throw new Error('zip entry exceeds the allowed maximum')
      }
      const writtenName = await appendZipEntry(
        sanitizeString(payload.jobId),
        zipJobOwnerId(event),
        name,
        payload.bytes
      )
      return { name: writtenName }
    }
  )
  // The folder-zip transfer (R1-H2): the main process fetches the resource and
  // writes it straight into the temp file, chunk by chunk. The payload never
  // crosses the IPC boundary and never materializes as one buffer in either
  // process — the renderer only learns the entry's name and size.
  ipcMain.handle(
    'gfs:zipStream:appendFromUri',
    async (
      event,
      payload: { jobId: string; name: string; uri: string; maxBytes: number; requestId?: string }
    ) => {
      assertTrustedSender(event)
      const name = sanitizeString(payload?.name)
      if (!name) throw new Error('zipStream appendFromUri requires an entry name')
      const uri = sanitizeString(payload?.uri)
      if (!uri) throw new Error('zipStream appendFromUri requires a resource URI')
      const maxBytes = sanitizeOptionalPositiveInteger(payload?.maxBytes, 'maxBytes')
      if (maxBytes === undefined) {
        throw new Error('zipStream appendFromUri requires a positive maxBytes')
      }
      if (maxBytes > GFS_DOWNLOAD_MAX_BYTES_CEILING) {
        throw new Error('zip entry exceeds the allowed maximum')
      }
      const requestId = payload?.requestId ? sanitizeString(payload.requestId) : undefined
      const result = await runWithGfsAbortSignal(requestId, signal =>
        appendZipEntryStreaming(
          sanitizeString(payload.jobId),
          zipJobOwnerId(event),
          name,
          async sink => {
            await service.downloadGfsUriInto(uri, maxBytes, signal, chunk => sink.write(chunk))
          },
          {}
        )
      )
      return { name: result.name, bytes: result.bytes }
    }
  )
  ipcMain.handle(
    'gfs:zipStream:finish',
    async (event, payload: { jobId: string; suggestedName: string }) => {
      assertTrustedSender(event)
      return finishZipJob(
        sanitizeString(payload.jobId),
        zipJobOwnerId(event),
        sanitizeString(payload.suggestedName)
      )
    }
  )
  ipcMain.handle('gfs:zipStream:abort', async (event, payload: { jobId: string }) => {
    assertTrustedSender(event)
    await abortZipJob(sanitizeString(payload.jobId), zipJobOwnerId(event))
    return { aborted: true }
  })
  ipcMain.handle(
    'gfs:createFolder',
    async (event, payload: { parentResourceId: string; name: string; drive?: string }) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.createGfsFolder(
        sanitizeString(payload?.parentResourceId),
        sanitizeString(payload?.name),
        drive
      )
    }
  )
  ipcMain.handle(
    'gfs:createFile',
    async (
      event,
      payload: { parentResourceId: string; name: string; encodedData: string; drive?: string }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.createGfsFile(
        sanitizeString(payload?.parentResourceId),
        sanitizeString(payload?.name),
        sanitizeString(payload?.encodedData),
        drive
      )
    }
  )
  ipcMain.handle(
    'gfs:createFileFromPath',
    async (
      event,
      payload: { parentResourceId: string; name: string; filePath: string; drive?: string }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.createGfsFileFromPath(
        sanitizeString(payload?.parentResourceId),
        sanitizeString(payload?.name),
        sanitizeString(payload?.filePath),
        drive
      )
    }
  )
  ipcMain.handle(
    'gfs:startFileUpload',
    async (
      event,
      payload: {
        parentResourceId: string
        name: string
        filePath: string
        drive?: string
        resumeUploadId?: string
      }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      const resumeUploadId = payload?.resumeUploadId
        ? sanitizeString(payload.resumeUploadId)
        : undefined
      return service.startGfsFileUpload(
        sanitizeString(payload?.parentResourceId),
        sanitizeString(payload?.name),
        sanitizeString(payload?.filePath),
        drive,
        resumeUploadId
      )
    }
  )
  ipcMain.handle(
    'gfs:startFileReplace',
    async (
      event,
      payload: {
        resourceId: string
        filePath: string
        drive?: string
        ifMatch?: number
        resumeUploadId?: string
      }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      const resumeUploadId = payload?.resumeUploadId
        ? sanitizeString(payload.resumeUploadId)
        : undefined
      return service.startGfsFileReplace(
        sanitizeString(payload?.resourceId),
        sanitizeString(payload?.filePath),
        drive,
        sanitizeOptionalInteger(payload?.ifMatch),
        resumeUploadId
      )
    }
  )
  ipcMain.handle(
    'gfs:getUploadSnapshot',
    async (event, payload: { uploadId: string; drive?: string }) => {
      assertTrustedSender(event)
      return service.getGfsUploadSnapshot(
        sanitizeString(payload?.uploadId),
        payload?.drive ? sanitizeString(payload.drive) : undefined
      )
    }
  )
  ipcMain.handle('gfs:listUploadSessions', async (event, payload?: { drive?: string }) => {
    assertTrustedSender(event)
    return service.listGfsUploadSessions(payload?.drive ? sanitizeString(payload.drive) : undefined)
  })
  ipcMain.handle(
    'gfs:pauseUpload',
    async (event, payload: { uploadId: string; drive?: string }) => {
      assertTrustedSender(event)
      return service.pauseGfsUpload(
        sanitizeString(payload?.uploadId),
        payload?.drive ? sanitizeString(payload.drive) : undefined
      )
    }
  )
  ipcMain.handle(
    'gfs:resumeUpload',
    async (event, payload: { uploadId: string; drive?: string }) => {
      assertTrustedSender(event)
      return service.resumeGfsUpload(
        sanitizeString(payload?.uploadId),
        payload?.drive ? sanitizeString(payload.drive) : undefined
      )
    }
  )
  ipcMain.handle(
    'gfs:cancelUpload',
    async (event, payload: { uploadId: string; drive?: string }) => {
      assertTrustedSender(event)
      await service.cancelGfsUpload(
        sanitizeString(payload?.uploadId),
        payload?.drive ? sanitizeString(payload.drive) : undefined
      )
      return { ok: true }
    }
  )
  ipcMain.handle(
    'gfs:replaceFile',
    async (
      event,
      payload: { resourceId: string; encodedData: string; drive?: string; ifMatch?: number }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.replaceGfsFile(
        sanitizeString(payload?.resourceId),
        sanitizeString(payload?.encodedData),
        drive,
        sanitizeOptionalInteger(payload?.ifMatch)
      )
    }
  )
  ipcMain.handle(
    'gfs:replaceFileFromPath',
    async (
      event,
      payload: { resourceId: string; filePath: string; drive?: string; ifMatch?: number }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.replaceGfsFileFromPath(
        sanitizeString(payload?.resourceId),
        sanitizeString(payload?.filePath),
        drive,
        sanitizeOptionalInteger(payload?.ifMatch)
      )
    }
  )
  ipcMain.handle(
    'gfs:renameResource',
    async (
      event,
      payload: { resourceId: string; newName: string; drive?: string; ifMatch?: number }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.renameGfsResource(
        sanitizeString(payload?.resourceId),
        sanitizeString(payload?.newName),
        drive,
        sanitizeOptionalInteger(payload?.ifMatch)
      )
    }
  )
  ipcMain.handle(
    'gfs:moveResource',
    async (
      event,
      payload: {
        resourceId: string
        destinationId: string
        drive?: string
        ifMatch?: number
        newName?: string
      }
    ) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.moveGfsResource(
        sanitizeString(payload?.resourceId),
        sanitizeString(payload?.destinationId),
        drive,
        sanitizeOptionalInteger(payload?.ifMatch),
        payload?.newName !== undefined ? sanitizeString(payload.newName) : undefined
      )
    }
  )
  ipcMain.handle(
    'gfs:deleteResource',
    async (event, payload: { resourceId: string; drive?: string; ifMatch?: number }) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.deleteGfsResource(
        sanitizeString(payload?.resourceId),
        drive,
        sanitizeOptionalInteger(payload?.ifMatch)
      )
    }
  )
  ipcMain.handle(
    'gfs:grant',
    async (
      event,
      payload: {
        resourceId: string
        subjectKeys: string[]
        bits: string[]
        drive?: string
        inherit?: boolean
      }
    ) => {
      assertTrustedSender(event)
      const bits = Array.isArray(payload?.bits) ? payload.bits.map(sanitizeString) : []
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      const inherit = payload?.inherit
      if (inherit !== undefined && typeof inherit !== 'boolean') {
        throw new Error('inherit must be a boolean')
      }
      return service.grantGfs(
        sanitizeString(payload?.resourceId),
        sanitizeSubjectKeys(payload?.subjectKeys),
        bits,
        drive,
        inherit
      )
    }
  )
  ipcMain.handle(
    'gfs:listGrants',
    async (event, payload: { resourceId: string; drive?: string }) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.listGfsGrants(sanitizeString(payload?.resourceId), drive)
    }
  )
  ipcMain.handle('gfs:revokeGrant', async (event, payload: { grantId: string }) => {
    assertTrustedSender(event)
    return service.revokeGfsGrant(sanitizeString(payload?.grantId))
  })
  ipcMain.handle(
    'gfs:listShares',
    async (event, payload: { resourceId: string; drive?: string }) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.listGfsShares(sanitizeString(payload?.resourceId), drive)
    }
  )
  ipcMain.handle('gfs:revokeShare', async (event, payload: { shareId: string }) => {
    assertTrustedSender(event)
    return service.revokeGfsShare(sanitizeString(payload?.shareId))
  })
  ipcMain.handle(
    'gfs:createShare',
    async (event, payload: { resourceId: string; subjectKeys: string[]; drive?: string }) => {
      assertTrustedSender(event)
      const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
      return service.createGfsShare(
        sanitizeString(payload?.resourceId),
        sanitizeSubjectKeys(payload?.subjectKeys),
        drive
      )
    }
  )
  // The caller's own agents with canonical GFS host subjects (grant targets for
  // per-agent delegation). Dedicated channel: the cached AccessCatalog is
  // name-based and must not be reshaped to carry subjects.
  ipcMain.handle('agents:listMine', async event => {
    assertTrustedSender(event)
    return service.listMyAgents()
  })
  ipcMain.handle('approvals:listPending', async (event, payload?: { limit?: number }) => {
    assertTrustedSender(event)
    const limit = sanitizeOptionalPositiveInteger(payload?.limit, 'pending approvals limit')
    return service.listPendingWorkflowApprovals(limit ?? 20)
  })
  ipcMain.handle(
    'approvals:decide',
    async (
      event,
      payload: {
        approvalId: string
        decision: 'approve' | 'deny'
        note?: string
        teamId?: string
      }
    ) => {
      assertTrustedSender(event)
      const decision = payload?.decision
      if (decision !== 'approve' && decision !== 'deny') {
        throw new Error('decision must be approve or deny')
      }
      return service.decideWorkflowApproval(
        sanitizeString(payload?.approvalId),
        decision,
        sanitizeString(payload?.note) || undefined,
        { teamId: sanitizeString(payload?.teamId) || undefined }
      )
    }
  )
  ipcMain.handle('notifications:streamStart', async event => {
    assertTrustedSender(event)
    const streamId = randomUUID()
    const ownerId = event.sender.id

    service.startWorkflowNotificationStream(
      streamId,
      ownerId,
      (streamEvent: WorkflowNotificationStreamEvent) => {
        try {
          event.sender.send('notifications:streamEvent', { streamId, event: streamEvent })
        } catch {
          /* sender destroyed */
        }
      }
    )

    if (!streamOwnerCleanupRegistered.has(ownerId)) {
      streamOwnerCleanupRegistered.add(ownerId)
      event.sender.once('destroyed', () => {
        service.stopHostStatusStreamsForOwner(ownerId)
        service.stopHostActivityStreamsForOwner(ownerId)
        service.stopTaskProgressStreamsForOwner(ownerId)
        service.stopWorkflowNotificationStreamsForOwner(ownerId)
        streamOwnerCleanupRegistered.delete(ownerId)
      })
    }

    return { streamId }
  })

  ipcMain.handle('entityChanges:streamStart', async event => {
    assertTrustedSender(event)
    const streamId = randomUUID()
    const ownerId = event.sender.id
    service.startEntityChangeStream(streamId, ownerId, (streamEvent: EntityChangeStreamEvent) => {
      try {
        event.sender.send('entityChanges:streamEvent', { streamId, event: streamEvent })
      } catch {
        /* sender destroyed */
      }
    })
    if (!entityChangeOwnerCleanupRegistered.has(ownerId)) {
      entityChangeOwnerCleanupRegistered.add(ownerId)
      let cleanedUp = false
      const cleanup = () => {
        if (cleanedUp) return
        cleanedUp = true
        service.stopEntityChangeStreamsForOwner(ownerId)
        entityChangeOwnerCleanupRegistered.delete(ownerId)
        event.sender.removeListener('did-navigate', onMainFrameNavigation)
        event.sender.removeListener('render-process-gone', onRendererProcessGone)
        event.sender.removeListener('destroyed', cleanup)
      }
      const onMainFrameNavigation = (
        _navigationEvent: Electron.Event,
        _navigationUrl: string,
        _httpResponseCode: number,
        _httpStatusText: string
      ) => {
        cleanup()
      }
      const onRendererProcessGone = (_event: Electron.Event) => cleanup()
      // `did-navigate` is emitted after a committed main-frame navigation.
      // `did-start-navigation` also fires for cancelled and in-place changes,
      // which do not replace this renderer's stream owner.
      event.sender.on('did-navigate', onMainFrameNavigation)
      event.sender.on('render-process-gone', onRendererProcessGone)
      event.sender.once('destroyed', cleanup)
    }
    return { streamId }
  })

  ipcMain.handle('entityChanges:streamStop', async (event, payload: { streamId: string }) => {
    assertTrustedSender(event)
    const streamId = sanitizeString(payload?.streamId)
    if (!streamId) return { ok: true }
    const stopped = service.stopEntityChangeStream(streamId, event.sender.id)
    if (!stopped) throw new Error('Forbidden: cannot stop entity-change subscription')
    return { ok: true }
  })

  ipcMain.handle('notifications:streamStop', async (event, payload: { streamId: string }) => {
    assertTrustedSender(event)
    const streamId = sanitizeString(payload?.streamId)
    if (!streamId) return { ok: true }
    const stopped = service.stopWorkflowNotificationStream(streamId, event.sender.id)
    if (!stopped) {
      throw new Error('Forbidden: cannot stop stream owned by another renderer')
    }
    return { ok: true }
  })

  ipcMain.handle('notifications:streamStatus', async event => {
    assertTrustedSender(event)
    return service.getWorkflowNotificationStreamStatus()
  })
  ipcMain.handle('notifications:ack', async (event, payload: { notificationId?: string }) => {
    assertTrustedSender(event)
    const notificationId = sanitizeString(payload?.notificationId)
    if (!notificationId) throw new Error('notificationId is required')
    return service.acknowledgeNotificationDelivery(notificationId)
  })
  ipcMain.handle('notificationPreferences:get', async event => {
    assertTrustedSender(event)
    return service.getNotificationPreferences()
  })
  ipcMain.handle('socialChannels:getSummary', async event => {
    assertTrustedSender(event)
    return service.getExternalChannelsSummary()
  })
  ipcMain.handle(
    'notificationPreferences:update',
    async (
      event,
      payload: {
        preferredMedium: 'telegram' | 'slack' | null
        channelFallbackEnabled: boolean
      }
    ) => {
      assertTrustedSender(event)
      return service.updateNotificationPreferences({
        preferredMedium: payload.preferredMedium,
        channelFallbackEnabled: payload.channelFallbackEnabled,
      })
    }
  )
  ipcMain.handle('team:directory', async event => {
    assertTrustedSender(event)
    return service.getTeamsDirectory()
  })
  ipcMain.handle('team:initialDirectory', async event => {
    assertTrustedSender(event)
    return service.getInitialTeamsDirectory()
  })
  ipcMain.handle('team:switch', async (event, payload: { teamId: string }) => {
    assertTrustedSender(event)
    return service.switchTeam(sanitizeString(payload?.teamId))
  })

  ipcMain.handle('access:getCatalog', async event => {
    assertTrustedSender(event)
    return service.getAccessCatalog()
  })
  ipcMain.handle('access:refreshCatalog', async event => {
    assertTrustedSender(event)
    return service.refreshAccessCatalog()
  })

  ipcMain.handle('sharedFiles:listAttached', async (event, payload: { contextId: string }) => {
    assertTrustedSender(event)
    return service.listContextSharedFilesystems(sanitizeString(payload?.contextId))
  })
  ipcMain.handle(
    'sharedFiles:listDirectory',
    async (event, payload: { contextId: string; sfsName: string; path?: string }) => {
      assertTrustedSender(event)
      return service.listSharedFilesystemDirectory(
        sanitizeString(payload?.contextId),
        sanitizeString(payload?.sfsName),
        String(payload?.path || '/')
      )
    }
  )
  ipcMain.handle(
    'sharedFiles:download',
    async (event, payload: { contextId: string; sfsName: string; path: string }) => {
      assertTrustedSender(event)
      const contextId = sanitizeString(payload?.contextId)
      const sfsName = sanitizeString(payload?.sfsName)
      const relPath = String(payload?.path || '').trim()
      if (!relPath) throw new Error('path is required')

      const result = await service.downloadSharedFile(contextId, sfsName, relPath)
      const owner = BrowserWindow.fromWebContents(event.sender) ?? undefined
      const saveResult = await dialog.showSaveDialog(owner!, {
        defaultPath: result.filename,
        title: 'Save file',
      })
      if (saveResult.canceled || !saveResult.filePath) {
        return { saved: false, filePath: null }
      }
      await fs.writeFile(saveResult.filePath, result.bytes)
      return { saved: true, filePath: saveResult.filePath }
    }
  )

  ipcMain.handle(
    'rpc:invokeHostMessage',
    async (
      event,
      payload: {
        hostRef: string
        payload: HostMessageRequest
        hostRefs?: string[]
        options?: { async?: boolean }
      }
    ) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      const request = parseHostMessageRequest(payload?.payload)
      const hostRefs = Array.isArray(payload?.hostRefs)
        ? payload.hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      const options = payload?.options?.async ? { async: true as const } : undefined
      return service.invokeHostMessage(hostRef, request, hostRefs, options)
    }
  )

  ipcMain.handle(
    'rpc:getTaskResult',
    async (event, payload: { hostRef: string; taskId: string; hostRefs?: string[] }) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      const taskId = sanitizeString(payload?.taskId)
      if (!taskId) throw new Error('taskId is required')
      const hostRefs = Array.isArray(payload?.hostRefs)
        ? payload.hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      return service.getTaskResult(hostRef, taskId, hostRefs)
    }
  )

  ipcMain.handle(
    'rpc:getHostStatus',
    async (event, payload: { hostRef: string; hostRefs?: string[] }) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      const hostRefs = Array.isArray(payload?.hostRefs)
        ? payload.hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      return service.getHostStatus(hostRef, hostRefs)
    }
  )
  ipcMain.handle(
    'rpc:prewarmHost',
    async (event, payload: { hostRef: string; hostRefs?: string[] }) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      const hostRefs = Array.isArray(payload?.hostRefs)
        ? payload.hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      return service.prewarmHost(hostRef, hostRefs)
    }
  )
  ipcMain.handle(
    'rpc:getHostActivity',
    async (
      event,
      payload: { hostRef: string; limit?: number; sinceEventId?: string; hostRefs?: string[] }
    ) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      const hostRefs = Array.isArray(payload?.hostRefs)
        ? payload.hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      const limit = sanitizeOptionalPositiveInteger(payload?.limit, 'host activity limit')
      return service.getHostActivity(hostRef, {
        limit,
        sinceEventId: sanitizeString(payload?.sinceEventId) || undefined,
        hostRefs,
      })
    }
  )

  ipcMain.handle(
    'rpc:hostStatusStreamStart',
    async (event, payload: { hostRef: string; hostRefs?: string[] }) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      const hostRefs = Array.isArray(payload?.hostRefs)
        ? payload.hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      const streamId = randomUUID()
      const ownerId = event.sender.id

      service.startHostStatusStream(
        streamId,
        ownerId,
        hostRef,
        hostRefs,
        (streamEvent: HostStatusStreamEvent) => {
          try {
            event.sender.send('rpc:hostStatusStreamEvent', { streamId, event: streamEvent })
          } catch {
            /* sender destroyed */
          }
        }
      )

      if (!streamOwnerCleanupRegistered.has(ownerId)) {
        streamOwnerCleanupRegistered.add(ownerId)
        event.sender.once('destroyed', () => {
          service.stopHostStatusStreamsForOwner(ownerId)
          service.stopHostActivityStreamsForOwner(ownerId)
          service.stopTaskProgressStreamsForOwner(ownerId)
          service.stopWorkflowNotificationStreamsForOwner(ownerId)
          streamOwnerCleanupRegistered.delete(ownerId)
        })
      }

      return { streamId }
    }
  )

  ipcMain.handle('rpc:hostStatusStreamStop', async (event, payload: { streamId: string }) => {
    assertTrustedSender(event)
    const streamId = sanitizeString(payload?.streamId)
    if (!streamId) return { ok: true }
    const stopped = service.stopHostStatusStream(streamId, event.sender.id)
    if (!stopped) {
      throw new Error('Forbidden: cannot stop stream owned by another renderer')
    }
    return { ok: true }
  })

  ipcMain.handle(
    'rpc:hostActivityStreamStart',
    async (event, payload: { hostRef: string; hostRefs?: string[] }) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      const hostRefs = Array.isArray(payload?.hostRefs)
        ? payload.hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      const streamId = randomUUID()
      const ownerId = event.sender.id

      service.startHostActivityStream(
        streamId,
        ownerId,
        hostRef,
        hostRefs,
        (streamEvent: HostActivityStreamEvent) => {
          try {
            event.sender.send('rpc:hostActivityStreamEvent', { streamId, event: streamEvent })
          } catch {
            /* sender destroyed */
          }
        }
      )

      return { streamId }
    }
  )

  ipcMain.handle('rpc:hostActivityStreamStop', async (event, payload: { streamId: string }) => {
    assertTrustedSender(event)
    const streamId = sanitizeString(payload?.streamId)
    if (!streamId) return { ok: true }
    const stopped = service.stopHostActivityStream(streamId, event.sender.id)
    if (!stopped) {
      throw new Error('Forbidden: cannot stop stream owned by another renderer')
    }
    return { ok: true }
  })

  ipcMain.handle(
    'rpc:taskProgressStreamStart',
    async (event, payload: { hostRef: string; taskId: string; hostRefs?: string[] }) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      const taskId = sanitizeString(payload?.taskId)
      if (!taskId) throw new Error('taskId is required')
      const hostRefs = Array.isArray(payload?.hostRefs)
        ? payload.hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      const streamId = randomUUID()
      const ownerId = event.sender.id

      service.startTaskProgressStream(
        streamId,
        ownerId,
        hostRef,
        taskId,
        hostRefs,
        (streamEvent: TaskProgressStreamEvent) => {
          try {
            event.sender.send('rpc:taskProgressStreamEvent', { streamId, event: streamEvent })
          } catch {
            // renderer may be destroyed
          }
        }
      )

      if (!streamOwnerCleanupRegistered.has(ownerId)) {
        streamOwnerCleanupRegistered.add(ownerId)
        event.sender.once('destroyed', () => {
          service.stopHostStatusStreamsForOwner(ownerId)
          service.stopHostActivityStreamsForOwner(ownerId)
          service.stopTaskProgressStreamsForOwner(ownerId)
          service.stopWorkflowNotificationStreamsForOwner(ownerId)
          streamOwnerCleanupRegistered.delete(ownerId)
        })
      }

      return { streamId }
    }
  )

  ipcMain.handle('rpc:taskProgressStreamStop', async (event, payload: { streamId: string }) => {
    assertTrustedSender(event)
    const streamId = sanitizeString(payload?.streamId)
    if (!streamId) return { ok: true }
    const stopped = service.stopTaskProgressStream(streamId, event.sender.id)
    if (!stopped) {
      throw new Error('Forbidden: cannot stop stream owned by another renderer')
    }
    return { ok: true }
  })

  ipcMain.handle(
    'rpc:approveToolCall',
    async (event, { hostRef, taskId, toolCallId, hostRefs, teamId }) => {
      assertTrustedSender(event)
      const targetHostRef = sanitizeString(hostRef)
      const targetTaskId = sanitizeString(taskId)
      const targetToolCallId = sanitizeString(toolCallId)
      const targetHostRefs = Array.isArray(hostRefs)
        ? hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      return service.approveToolCall(
        targetHostRef,
        targetTaskId,
        targetToolCallId,
        targetHostRefs,
        { teamId: sanitizeString(teamId) || undefined }
      )
    }
  )

  ipcMain.handle(
    'rpc:denyToolCall',
    async (event, { hostRef, taskId, toolCallId, reason, hostRefs, teamId }) => {
      assertTrustedSender(event)
      const targetHostRef = sanitizeString(hostRef)
      const targetTaskId = sanitizeString(taskId)
      const targetToolCallId = sanitizeString(toolCallId)
      const denyReason = sanitizeString(reason) || 'User denied'
      const targetHostRefs = Array.isArray(hostRefs)
        ? hostRefs.map(v => String(v).trim()).filter(Boolean)
        : undefined
      return service.denyToolCall(
        targetHostRef,
        targetTaskId,
        targetToolCallId,
        denyReason,
        targetHostRefs,
        { teamId: sanitizeString(teamId) || undefined }
      )
    }
  )

  // U5 (mcp-oauth reactive consent): the renderer's "Connect <server>" button.
  // Fetches a fresh provider authorize-URL (host-bound to the suspended
  // conversation's hostRef) and opens it in the OS browser. The deep-link return
  // (`clerum://oauth-completed?…&source=mcp`) is routed by main.ts back to the
  // renderer to resume the suspended task.
  ipcMain.handle(
    'rpc:connectMcpServer',
    async (event, { mcpServerName, hostRef, contextId, options }) => {
      assertTrustedSender(event)
      const server = sanitizeString(mcpServerName)
      const targetHostRef = sanitizeString(hostRef)
      const ctx = sanitizeString(contextId) || undefined
      // `confirmShared` is a UX-only flag (the server-side authz per flavor is
      // authoritative). The panel sets it for `oauth-context` connectors so main
      // shows a team-wide confirm dialog; the reactive U5 path omits it.
      const confirmShared = options && typeof options === 'object' && options.confirmShared === true
      return service.requestMcpOauthAuthorize(server, targetHostRef, ctx, { confirmShared })
    }
  )

  // Proactive connectors panel (spec 11 U2): the classified per-agent fleet.
  ipcMain.handle('rpc:listConnectors', async event => {
    assertTrustedSender(event)
    return service.getConnectors()
  })

  // Proactive disconnect (spec 11 U4): revoke an mcp-server's OAuth grant. Main
  // shows an explicit confirm dialog before the DELETE (destructive; team-wide
  // for `oauth-context`). `shared` drives only the confirm copy.
  ipcMain.handle(
    'rpc:disconnectMcpServer',
    async (event, { mcpServerName, hostRef, contextId, options }) => {
      assertTrustedSender(event)
      const server = sanitizeString(mcpServerName)
      const targetHostRef = sanitizeString(hostRef)
      const ctx = sanitizeString(contextId) || undefined
      const shared = options && typeof options === 'object' && options.shared === true
      return service.disconnectMcpServer(server, targetHostRef, ctx, { shared })
    }
  )

  ipcMain.handle('rpc:listServers', async (event, { hostRefs }) => {
    assertTrustedSender(event)
    return service.listAccessibleMcpServers(hostRefs)
  })

  ipcMain.handle('rpc:cancelTask', async (event, { hostRef, taskId }) => {
    assertTrustedSender(event)
    const targetHostRef = sanitizeString(hostRef)
    const targetTaskId = sanitizeString(taskId)
    return service.cancelTask(targetHostRef, targetTaskId)
  })

  ipcMain.handle('rpc:listArtifacts', async (event, { hostRef, hostRefs }) => {
    assertTrustedSender(event)
    return service.listArtifacts(hostRef, hostRefs)
  })

  ipcMain.handle('rpc:downloadArtifact', async (event, { hostRef, filename, hostRefs }) => {
    assertTrustedSender(event)
    return service.downloadArtifact(hostRef, filename, hostRefs)
  })

  ipcMain.handle(
    'rpc:listSessions',
    async (
      event,
      payload: {
        hostRef: string
        hostRefs?: string[]
        query?: import('./types.js').SessionsListQuery
      }
    ) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      if (!hostRef) throw new Error('hostRef is required')
      return service.listSessions(
        hostRef,
        payload?.hostRefs,
        sanitizeSessionsListQuery(payload?.query)
      )
    }
  )

  ipcMain.handle(
    'rpc:loadSessionMessages',
    async (
      event,
      payload: {
        hostRef: string
        agent: string
        chatId: string
        hostRefs?: string[]
        query?: import('./types.js').SessionMessagesQuery
      }
    ) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      const agent = sanitizeString(payload?.agent)
      const chatId = sanitizeString(payload?.chatId)
      if (!hostRef || !agent || !chatId) {
        throw new Error('hostRef, agent, and chatId are required')
      }
      return service.loadSessionMessages(
        hostRef,
        agent,
        chatId,
        payload?.hostRefs,
        sanitizeSessionMessagesQuery(payload?.query)
      )
    }
  )

  ipcMain.handle(
    'rpc:getContextBreakdown',
    async (
      event,
      payload: { hostRef: string; agent: string; chatId: string; hostRefs?: string[] }
    ) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      const agent = sanitizeString(payload?.agent)
      const chatId = sanitizeString(payload?.chatId)
      if (!hostRef || !agent || !chatId) {
        throw new Error('hostRef, agent, and chatId are required')
      }
      return service.getContextBreakdown(hostRef, agent, chatId, payload?.hostRefs)
    }
  )

  ipcMain.handle(
    'rpc:getHostModels',
    async (event, payload: { hostRef: string; chatId: string; hostRefs?: string[] }) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      // `chatId` is optional for the model LIST (host-level allowlist). A new chat
      // has no id yet; the server returns the list with `sessionModel: null`.
      const chatId = sanitizeString(payload?.chatId)
      if (!hostRef) {
        throw new Error('hostRef is required')
      }
      return service.getHostModels(hostRef, chatId, payload?.hostRefs)
    }
  )

  ipcMain.handle(
    'rpc:setHostModel',
    async (
      event,
      payload: {
        hostRef: string
        chatId: string
        model: string
        hostRefs?: string[]
        expectedRevision?: number
      }
    ) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      const chatId = sanitizeString(payload?.chatId)
      const model = sanitizeString(payload?.model)
      if (!hostRef || !chatId || !model) {
        throw new Error('hostRef, chatId, and model are required')
      }
      // Optional CAS precondition (issue #654). Absent on hosts that do not
      // project `modelSelectionRevision`; the request then omits it entirely.
      // A present but invalid revision is refused: dropping it would turn a
      // conditional write into an unconditional one.
      const expectedRevision = payload?.expectedRevision
      if (expectedRevision !== undefined && !isSelectionRevision(expectedRevision)) {
        throw new Error('expectedRevision must be a non-negative integer')
      }
      return service.setHostModel(hostRef, chatId, model, payload?.hostRefs, expectedRevision)
    }
  )

  // Spec 15 Fase B — propagate an explicit user rename to the server.
  ipcMain.handle(
    'rpc:renameSession',
    async (event, payload: { hostRef: string; agent: string; chatId: string; title: string }) => {
      assertTrustedSender(event)
      const hostRef = sanitizeString(payload?.hostRef)
      const agent = sanitizeString(payload?.agent)
      const chatId = sanitizeString(payload?.chatId)
      // `sanitizeString` is only trim(); the authoritative title contract (NFC +
      // strip \p{C} + collapse + cap 120cp/512B) is enforced server-side by
      // mcp-host (spec 15 §5). A cheap trim + non-empty reject here just avoids a
      // round-trip for an obviously empty rename; content validity is the server.
      const title = sanitizeString(payload?.title)
      if (!hostRef || !agent || !chatId) {
        throw new Error('hostRef, agent, and chatId are required')
      }
      if (!title) throw new Error('title is required')
      // Never trust route segments minted by the renderer, and never accept a
      // `hostRefs` fleet list from it (the token is scoped to this single host).
      assertSafeRouteSegment('hostRef', hostRef)
      assertSafeRouteSegment('agent', agent, { maxLength: 200, allowColon: false })
      assertSafeRouteSegment('chatId', chatId)
      return service.renameSession(hostRef, agent, chatId, title)
    }
  )

  ipcMain.handle('rpc:getTokenMetadata', async event => {
    assertTrustedSender(event)
    return service.getTokenMetadata()
  })

  // ─── Chat persistence ───

  ipcMain.handle('chat:list', async (event, payload: { agentRef: string }) => {
    assertTrustedSender(event)
    const agentRef = sanitizeString(payload?.agentRef)
    if (!agentRef) throw new Error('agentRef is required')
    return requireChatStore().listChats(agentRef)
  })

  ipcMain.handle('chat:create', async (event, payload: { agentRef: string; chatId: string }) => {
    assertTrustedSender(event)
    const agentRef = sanitizeString(payload?.agentRef)
    const chatId = sanitizeString(payload?.chatId)
    if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
    return requireChatStore().createChat(agentRef, chatId)
  })

  ipcMain.handle(
    'chat:rename',
    async (
      event,
      payload: {
        agentRef: string
        chatId: string
        title: string
        bindingGeneration: number
      }
    ) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      const title = sanitizeString(payload?.title)
      if (!agentRef || !chatId || !title)
        throw new Error('agentRef, chatId, and title are required')
      const bindingGeneration = payload?.bindingGeneration
      if (typeof bindingGeneration !== 'number' || !Number.isSafeInteger(bindingGeneration)) {
        throw new Error('A valid chat store binding generation is required')
      }
      await requireChatStoreForBindingGeneration(bindingGeneration).renameChat(
        agentRef,
        chatId,
        title
      )
    }
  )

  ipcMain.handle('chat:bindingGeneration', event => {
    assertTrustedSender(event)
    return getChatStoreBindingGeneration()
  })

  ipcMain.handle(
    'chat:captureDeleteFence',
    (event, payload: { expectedAuthorityScope?: unknown }) => {
      assertTrustedSender(event)
      const expectedAuthorityScope = sanitizeChatAuthorityScope(payload?.expectedAuthorityScope)
      const authority = service.getChatDeletionFenceAuthority()
      if (!sameChatAuthorityScope(expectedAuthorityScope, authority.authorityScope)) {
        throw new Error('Chat deletion authority scope changed before confirmation')
      }
      return {
        version: 1,
        authorityScope: authority.authorityScope,
        bindingGeneration: getChatStoreBindingGeneration(),
        sessionGeneration: authority.sessionGeneration,
      } satisfies ChatDeleteFence
    }
  )

  ipcMain.handle(
    'chat:delete',
    async (
      event,
      payload: {
        version?: number
        fence?: unknown
        agentRef: string
        chatId: string
      }
    ) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      if (payload?.version !== 3) throw new Error('Scoped chat deletion is required')
      const fence = sanitizeChatDeleteFence(payload.fence)
      const authority = service.getChatDeletionFenceAuthority()
      if (
        !sameChatAuthorityScope(fence.authorityScope, authority.authorityScope) ||
        fence.sessionGeneration !== authority.sessionGeneration
      ) {
        throw new Error('Chat deletion authority changed before confirmation')
      }
      const store = requireChatStoreForBindingGeneration(fence.bindingGeneration)
      return await store.deleteChat(agentRef, chatId, fence.authorityScope)
    }
  )

  ipcMain.handle(
    'chat:loadMessages',
    async (
      event,
      payload: { agentRef: string; chatId: string; limit?: number; offset?: number }
    ) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      const { limit, offset } = sanitizeChatLoadWindow(payload?.limit, payload?.offset)
      return requireChatStore().loadMessages(agentRef, chatId, limit, offset)
    }
  )

  ipcMain.handle(
    'chat:appendMessages',
    async (event, payload: { agentRef: string; chatId: string; messages: unknown[] }) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      const messages = Array.isArray(payload?.messages) ? payload.messages : []
      await requireChatStore().appendMessages(
        agentRef,
        chatId,
        messages as import('./types.js').ChatMessage[]
      )
    }
  )

  ipcMain.handle(
    'chat:upsertMessages',
    async (event, payload: { agentRef: string; chatId: string; messages: unknown[] }) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      const messages = Array.isArray(payload?.messages) ? payload.messages : []
      await requireChatStore().upsertMessages(
        agentRef,
        chatId,
        messages as import('./types.js').ChatMessage[]
      )
    }
  )

  ipcMain.handle(
    'chat:replaceMessages',
    async (
      event,
      payload: {
        agentRef: string
        chatId: string
        messages: unknown[]
        options?: import('./types.js').ReplaceChatMessagesOptions
      }
    ) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      const messages = Array.isArray(payload?.messages) ? payload.messages : []
      const activeTaskIds = Array.isArray(payload?.options?.activeTaskIds)
        ? payload.options.activeTaskIds
            .filter((taskId): taskId is string => typeof taskId === 'string' && taskId.length > 0)
            .slice(0, 32)
        : undefined
      await requireChatStore().replaceMessages(
        agentRef,
        chatId,
        messages as import('./types.js').ChatMessage[],
        {
          activeTaskIds,
        }
      )
    }
  )

  ipcMain.handle(
    'chat:backfillCounters',
    async (event, payload: { agentRef: string; chatId: string; messages: unknown[] }) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      const messages = Array.isArray(payload?.messages) ? payload.messages : []
      await requireChatStore().backfillChatCounters(
        agentRef,
        chatId,
        messages as import('./types.js').ChatMessage[]
      )
    }
  )

  ipcMain.handle(
    'chat:markUnreadTerminal',
    async (event, payload: { agentRef: string; chatId: string }) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      await requireChatStore().markUnreadTerminal(agentRef, chatId)
    }
  )

  ipcMain.handle(
    'chat:clearUnreadTerminal',
    async (event, payload: { agentRef: string; chatId: string }) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      await requireChatStore().clearUnreadTerminal(agentRef, chatId)
    }
  )

  ipcMain.handle('chat:getLastActive', async (event, payload: { agentRef: string }) => {
    assertTrustedSender(event)
    const agentRef = sanitizeString(payload?.agentRef)
    if (!agentRef) throw new Error('agentRef is required')
    return requireChatStore().getLastActiveChatId(agentRef)
  })

  ipcMain.handle(
    'chat:setLastActive',
    async (event, payload: { agentRef: string; chatId: string }) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      const chatId = sanitizeString(payload?.chatId)
      if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
      await requireChatStore().setLastActiveChatId(agentRef, chatId)
    }
  )

  ipcMain.handle(
    'chat:reconcileSessions',
    async (
      event,
      payload: {
        agentRef: string
        sessions?: Array<{ chatId?: unknown; lastActivityAt?: unknown; title?: unknown }>
      }
    ) => {
      assertTrustedSender(event)
      const agentRef = sanitizeString(payload?.agentRef)
      if (!agentRef) throw new Error('agentRef is required')
      const sessions = Array.isArray(payload?.sessions)
        ? payload.sessions
            .map(session => ({
              chatId: sanitizeString(session?.chatId),
              lastActivityAt:
                typeof session?.lastActivityAt === 'string' ? session.lastActivityAt : undefined,
              title:
                typeof session?.title === 'string' ? session.title.trim() || undefined : undefined,
            }))
            .filter(session => Boolean(session.chatId))
        : []
      return requireChatStore().upsertServerSessions(agentRef, sessions)
    }
  )

  ipcMain.handle('chat:getIndex', async (event, payload: { agentRef: string }) => {
    assertTrustedSender(event)
    const agentRef = sanitizeString(payload?.agentRef)
    if (!agentRef) throw new Error('agentRef is required')
    return runChatGetIndex(
      {
        store: requireChatStore(),
        getChatDeletionFenceAuthority: () => service.getChatDeletionFenceAuthority(),
        warnCleanupFailure: error => {
          const code = (error as NodeJS.ErrnoException | undefined)?.code
          console.warn(
            `[chat:getIndex] Deleted-chat cleanup retry failed for agent "${agentRef}"${code ? ` (${code})` : ''}; returning the index with its tombstones`,
            error
          )
        },
      },
      agentRef
    )
  })

  ipcMain.handle('chat:dismissOnboarding', async (event, payload: { agentRef: string }) => {
    assertTrustedSender(event)
    const agentRef = sanitizeString(payload?.agentRef)
    if (!agentRef) throw new Error('agentRef is required')
    await requireChatStore().setOnboardingDismissed(agentRef, true)
  })

  // ─── Workflow triggers ───

  ipcMain.handle('workflows:list', async event => {
    assertTrustedSender(event)
    return service.listWorkflows()
  })

  ipcMain.handle('workflows:read', async (event, payload: { ns: string; name: string }) => {
    assertTrustedSender(event)
    const ns = sanitizeString(payload?.ns)
    const name = sanitizeString(payload?.name)
    if (!ns || !name) throw new Error('ns and name are required')
    return service.readWorkflow(ns, name)
  })

  ipcMain.handle('workflows:health', async (event, payload: { ns: string; name: string }) => {
    assertTrustedSender(event)
    const ns = sanitizeString(payload?.ns)
    const name = sanitizeString(payload?.name)
    if (!ns || !name) throw new Error('ns and name are required')
    return service.getWorkflowHealth(ns, name)
  })

  ipcMain.handle(
    'workflows:trigger',
    async (
      event,
      payload: {
        ns: string
        name: string
        inputs?: Record<string, unknown>
        idempotencyKey?: string
      }
    ) => {
      assertTrustedSender(event)
      const ns = sanitizeString(payload?.ns)
      const name = sanitizeString(payload?.name)
      const idempotencyKey = sanitizeString(payload?.idempotencyKey)
      if (!ns || !name) throw new Error('ns and name are required')
      return service.triggerWorkflow(ns, name, payload?.inputs, idempotencyKey || undefined)
    }
  )

  ipcMain.handle(
    'workflows:runs',
    async (event, payload: { ns: string; name: string; limit?: number }) => {
      assertTrustedSender(event)
      const ns = sanitizeString(payload?.ns)
      const name = sanitizeString(payload?.name)
      if (!ns || !name) throw new Error('ns and name are required')
      const limit = sanitizeOptionalPositiveInteger(payload?.limit, 'workflow runs limit')
      return service.listWorkflowRuns(ns, name, limit)
    }
  )

  ipcMain.handle(
    'workflows:runArtifacts',
    async (event, payload: { ns: string; name: string; runId: string }) => {
      assertTrustedSender(event)
      const ns = sanitizeString(payload?.ns)
      const name = sanitizeString(payload?.name)
      const runId = sanitizeString(payload?.runId)
      if (!ns || !name || !runId) throw new Error('ns, name, and runId are required')
      return service.listWorkflowRunArtifacts(ns, name, runId)
    }
  )

  ipcMain.handle(
    'workflows:downloadRunArtifact',
    async (event, payload: { ns: string; name: string; runId: string; artifactName: string }) => {
      assertTrustedSender(event)
      const ns = sanitizeString(payload?.ns)
      const name = sanitizeString(payload?.name)
      const runId = sanitizeString(payload?.runId)
      const artifactName = sanitizeString(payload?.artifactName)
      if (!ns || !name || !runId || !artifactName) {
        throw new Error('ns, name, runId, and artifactName are required')
      }
      const bytes = await service.downloadWorkflowRunArtifact(ns, name, runId, artifactName)
      const filename = runScopedArtifactDownloadName(runId, artifactName)
      const saved = await writeUniqueDownload(app.getPath('downloads'), filename, bytes)
      return { saved: true, ...saved }
    }
  )

  ipcMain.handle('app:openUrl', async (event, { url }: { url: string }) => {
    assertTrustedSender(event)
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      throw new Error('Only HTTP(S) URLs are allowed')
    }
    const { shell } = await import('electron')
    await shell.openExternal(url)
  })

  ipcMain.handle('desktop:openWindow', async (event, { hostRef }: { hostRef: string }) => {
    assertTrustedSender(event)
    if (!hostRef || typeof hostRef !== 'string') {
      throw new Error('hostRef is required')
    }
    await service.openDesktop(hostRef, closedHostRef => {
      const { BrowserWindow } = require('electron') as typeof import('electron')
      for (const w of BrowserWindow.getAllWindows()) {
        if (!w.isDestroyed()) {
          w.webContents.send('desktop:windowClosed', { hostRef: closedHostRef })
        }
      }
    })
  })

  ipcMain.handle('desktop:closeWindow', async (event, { hostRef }: { hostRef: string }) => {
    assertTrustedSender(event)
    if (!hostRef || typeof hostRef !== 'string') {
      throw new Error('hostRef is required')
    }
    await service.closeDesktop(hostRef)
  })

  ipcMain.handle('desktop:getStatus', async (event, { hostRef }: { hostRef: string }) => {
    assertTrustedSender(event)
    if (!hostRef || typeof hostRef !== 'string') {
      throw new Error('hostRef is required')
    }
    return service.getDesktopStatus(hostRef)
  })

  // ─── Sandbox UI ─────────────────────────────────────────────────

  ipcMain.handle('sandboxUi:listApps', async event => {
    assertTrustedSender(event)
    return service.listSandboxUiApps()
  })

  ipcMain.handle(
    'sandboxUi:mintSession',
    async (event, payload: { recipeNs: string; recipeName: string }) => {
      assertTrustedSender(event)
      const recipeNs = sanitizeString(payload?.recipeNs)
      const recipeName = sanitizeString(payload?.recipeName)
      if (!recipeNs || !recipeName) {
        throw new Error('recipeNs and recipeName are required')
      }
      return service.mintSandboxUiSession(recipeNs, recipeName)
    }
  )

  function parseBounds(raw: unknown): {
    x: number
    y: number
    width: number
    height: number
    dpr?: number
  } {
    const obj = (raw ?? {}) as Record<string, unknown>
    const x = Math.round(Number(obj.x))
    const y = Math.round(Number(obj.y))
    const width = Math.round(Number(obj.width))
    const height = Math.round(Number(obj.height))
    if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error('bounds.x/y must be numeric')
    if (!Number.isFinite(width) || width <= 0) throw new Error('bounds.width must be positive')
    if (!Number.isFinite(height) || height <= 0) throw new Error('bounds.height must be positive')
    const dprNum = Number(obj.dpr)
    const dpr = Number.isFinite(dprNum) && dprNum > 0 ? dprNum : undefined
    return { x, y, width, height, dpr }
  }

  // `sandboxUi:open` and `sandboxUi:close` must reach the AppService queue with
  // no `await` before it, in both handlers: a close the renderer sends right
  // after an open for the same launch would otherwise be enqueued first and
  // miss the view the open then mounts. `sandboxUi:reload` follows the same
  // rule, so main serves it in the order the renderer sent it.
  ipcMain.handle(
    'sandboxUi:open',
    async (
      event,
      payload: {
        recipeNs: string
        recipeName: string
        defaultPath?: string
        routePath?: string
        bounds: unknown
        launchId: unknown
      }
    ) => {
      assertTrustedSender(event)
      const recipeNs = sanitizeString(payload?.recipeNs)
      const recipeName = sanitizeString(payload?.recipeName)
      if (!recipeNs || !recipeName) {
        throw new Error('recipeNs and recipeName are required')
      }
      const launchId = parseSandboxUiLaunchId(payload?.launchId)
      const parentWindow = BrowserWindow.fromWebContents(event.sender)
      if (!parentWindow) {
        throw new Error('cannot resolve parent window from IPC sender')
      }
      const bounds = parseBounds(payload?.bounds)
      const appRef = `${recipeNs}/${recipeName}`
      await service.openSandboxUi({
        launchId,
        recipeNs,
        recipeName,
        // Human title from the installed recipe, used verbatim in consent
        // prompts and notification attribution. Comes from the trusted renderer's
        // app list — NEVER from anything the plugin itself can set.
        title: sanitizeString((payload as { title?: unknown })?.title) || undefined,
        defaultPath: typeof payload?.defaultPath === 'string' ? payload.defaultPath : undefined,
        routePath: typeof payload?.routePath === 'string' ? payload.routePath : undefined,
        bounds,
        parentWindow,
        // Only the window the view was mounted in owns it.
        onReleased: released => {
          if (parentWindow.isDestroyed()) return
          parentWindow.webContents.send('sandboxUi:released', {
            launchId: released.launchId,
            reason: released.reason,
            location: released.location,
          })
        },
        onRefreshError: message => {
          if (parentWindow.isDestroyed()) return
          parentWindow.webContents.send('sandboxUi:refreshError', { appRef, launchId, message })
        },
        onRefreshRecovered: () => {
          if (parentWindow.isDestroyed()) return
          parentWindow.webContents.send('sandboxUi:refreshRecovered', { appRef, launchId })
        },
        onTitleChanged: title => {
          if (parentWindow.isDestroyed()) return
          parentWindow.webContents.send('sandboxUi:titleChanged', { appRef, launchId, title })
        },
      })
    }
  )

  // The launch id is mandatory: a close that names no launch, or a malformed
  // one, must not degrade into closing whatever view is live, which another
  // launch may own by the time the queue reaches it.
  ipcMain.handle('sandboxUi:close', async (event, payload?: { launchId?: unknown } | null) => {
    assertTrustedSender(event)
    const launchId = parseSandboxUiLaunchId(payload?.launchId)
    await service.closeSandboxUi({ launchId })
  })

  // Same launch-id contract as close: a reload that names no launch must not
  // degrade into reloading whatever view is live.
  ipcMain.handle('sandboxUi:reload', async (event, payload?: { launchId?: unknown } | null) => {
    assertTrustedSender(event)
    const launchId = parseSandboxUiLaunchId(payload?.launchId)
    await service.reloadSandboxUi({ launchId })
  })

  ipcMain.handle('sandboxUi:copyDeepLink', async (event, payload: { teamId?: unknown }) => {
    assertTrustedSender(event)
    const teamId = sanitizeString(payload?.teamId)
    const result = await service.createSandboxUiDeepLink(teamId || undefined)
    clipboard.writeText(result.url)
    return result
  })

  ipcMain.handle('sandboxUi:setBounds', async (event, payload: { bounds: unknown }) => {
    assertTrustedSender(event)
    const bounds = parseBounds(payload?.bounds)
    await service.setSandboxUiBounds(bounds)
  })

  ipcMain.handle('sandboxUi:setVisible', async (event, payload: { visible?: unknown }) => {
    assertTrustedSender(event)
    if (typeof payload?.visible !== 'boolean') {
      throw new Error('visible must be boolean')
    }
    await service.setSandboxUiVisible(payload.visible)
  })

  ipcMain.handle('sandboxUi:capturePreview', async event => {
    assertTrustedSender(event)
    return service.captureSandboxUiPreview()
  })

  ipcMain.handle(
    'sandboxUi:findInPage',
    async (
      event,
      payload: {
        query?: unknown
        operation?: unknown
        clientRequestId?: unknown
      }
    ) => {
      assertTrustedSender(event)
      const query = typeof payload?.query === 'string' ? payload.query : ''
      if (!query.trim() || query.length > 500) {
        throw new Error('find query must contain 1 to 500 characters')
      }
      if (!['start', 'next', 'previous'].includes(String(payload?.operation))) {
        throw new Error('find operation must be start, next, or previous')
      }
      if (!Number.isSafeInteger(payload?.clientRequestId) || Number(payload.clientRequestId) <= 0) {
        throw new Error('find client request ID must be a positive safe integer')
      }
      const clientRequestId = Number(payload.clientRequestId)
      return service.findInActiveSandboxUi(
        query,
        payload.operation as 'start' | 'next' | 'previous',
        clientRequestId,
        result => {
          if (!event.sender.isDestroyed()) {
            event.sender.send('sandboxUi:findResult', { ...result, clientRequestId })
          }
        }
      )
    }
  )

  ipcMain.handle('sandboxUi:stopFindInPage', async event => {
    assertTrustedSender(event)
    await service.stopActiveSandboxUiFind()
  })

  ipcMain.handle('sandboxUi:focusActive', async event => {
    assertTrustedSender(event)
    return service.focusActiveSandboxUi()
  })

  // Embed-side refresh request. NOTE: this IPC is exposed to *untrusted*
  // recipe JS via the embed preload, so we deliberately do NOT call
  // `assertTrustedSender` (the embed loads from the rpc-proxy URL, not
  // file:// or the dev URL). The trust check is the pinning map owned by
  // the refresh module: an IPC from a webContents.id that is not in the
  // map is dropped with an error.
  ipcMain.handle('clerum:sandbox-ui:request-refresh', async event => {
    await service.requestSandboxUiRefresh(event.sender.id)
  })

  // ── Plugin UI SDK ────────────────────────────────────────────────────
  //
  // Same trust model as the refresh IPC above and for the same reason: these
  // four channels are reachable by untrusted plugin JS, so `assertTrustedSender`
  // cannot be the gate (the embed's origin is rpc-proxy). Identity comes from
  // the surface pinning map, and every other check — consent, rate limits,
  // response minimization, audit — happens inside the broker. Nothing is
  // enforced here; this layer only routes.

  // Lazily imported: `pluginSdkRuntime` pulls in `config`, whose module-level
  // profile load needs a real Electron `app`. Importing it at the top of this
  // file would make merely registering IPC handlers depend on an initialized
  // Electron runtime. Mirrors how `appService` defers `sandboxUiDriver`.
  const pluginSdk = async () => (await import('./pluginSdkRuntime.js')).getPluginSdkRuntime()

  ipcMain.handle(PLUGIN_SDK_CAPABILITIES_CHANNEL, async event =>
    (await pluginSdk()).broker.listCapabilities(event.sender.id)
  )

  ipcMain.handle(PLUGIN_SDK_PERMISSION_STATE_CHANNEL, async (event, payload: unknown) =>
    (await pluginSdk()).broker.permissionState(event.sender.id, payload)
  )

  ipcMain.handle(PLUGIN_SDK_PERMISSIONS_CHANNEL, async (event, payload: unknown) =>
    (await pluginSdk()).broker.requestPermissions(event.sender.id, payload)
  )

  ipcMain.handle(PLUGIN_SDK_REQUEST_CHANNEL, async (event, payload: unknown) =>
    (await pluginSdk()).broker.request(event.sender.id, payload)
  )

  // ── Plugin SDK, trusted-renderer half ────────────────────────────────
  //
  // The consent resolve channel IS trusted-sender guarded. That is what stops
  // an embed from answering its own permission prompt, and it pairs with the
  // main-generated `promptId` nonce: a resolve for an unknown or already-
  // answered prompt is dropped inside the gate.

  ipcMain.handle(
    PLUGIN_SDK_CONSENT_RESOLVE_CHANNEL,
    async (event, payload: { promptId?: unknown; allowed?: unknown }) => {
      assertTrustedSender(event)
      const promptId = sanitizeString(payload?.promptId)
      if (!promptId) throw new Error('promptId is required')
      const allowed = Array.isArray(payload?.allowed)
        ? payload.allowed.filter((entry): entry is string => typeof entry === 'string')
        : []
      return (await pluginSdk()).resolveConsentPrompt(promptId, allowed)
    }
  )

  ipcMain.handle('pluginSdk:listGrants', async event => {
    assertTrustedSender(event)
    return (await pluginSdk()).listGrants()
  })

  ipcMain.handle(
    'pluginSdk:revoke',
    async (event, payload: { pluginId?: unknown; capability?: unknown }) => {
      assertTrustedSender(event)
      const pluginId = sanitizeString(payload?.pluginId)
      const capability = sanitizeString(payload?.capability)
      if (!pluginId) throw new Error('pluginId is required')
      const runtime = await pluginSdk()
      if (capability) await runtime.revokeGrant(pluginId, capability)
      else await runtime.revokeAllForPlugin(pluginId)
    }
  )

  ipcMain.handle(
    'pluginSdk:activity',
    async (event, payload: { limit?: unknown; includeAmbient?: unknown }) => {
      assertTrustedSender(event)
      return (await pluginSdk()).readAudit({
        limit: sanitizeOptionalInteger(payload?.limit),
        includeAmbient: payload?.includeAmbient === true,
      })
    }
  )

  ipcMain.handle('pluginSdk:clearActivity', async event => {
    assertTrustedSender(event)
    await (await pluginSdk()).clearAudit()
  })

  ipcMain.handle('pluginSdk:setTheme', async (event, payload: { theme?: unknown }) => {
    assertTrustedSender(event)
    ;(await pluginSdk()).setTheme(payload?.theme)
  })
}