Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

4.1 KB
Raw Blame
import type { AgentSessionSubscribeEvent } from './agent-session-wire'
import {
  actionablePromptIdsAfterStructuredAgentSessionBatch,
  hostWorkingAfterStructuredAgentSessionBatch,
  latestTurnAfterStructuredAgentSessionBatch
} from './structured-agent-session-live-turn'

export const STRUCTURED_AGENT_SESSION_CLIENT_COALESCE_MS = 48

function bypassCoalescing(event: AgentSessionSubscribeEvent): boolean {
  return (
    event.type !== 'batch' ||
    // Deliver queue lists immediately or the queued response removes Sending before its replacement card arrives.
    event.queuedMessages !== undefined ||
    event.currentRequests !== undefined ||
    event.batch.removedItemIds.length > 0 ||
    event.batch.items.some((item) => item.body.kind !== 'message' || item.body.role !== 'assistant')
  )
}

function mergeBatch(
  left: Extract<AgentSessionSubscribeEvent, { type: 'batch' }>,
  right: Extract<AgentSessionSubscribeEvent, { type: 'batch' }>
): Extract<AgentSessionSubscribeEvent, { type: 'batch' }> {
  const items = new Map(left.batch.items.map((item) => [item.itemId, item]))
  for (const item of right.batch.items) {
    items.set(item.itemId, item)
  }
  const submissions = new Map(
    left.batch.submissions.map((submission) => [submission.clientMessageId, submission])
  )
  for (const submission of right.batch.submissions) {
    submissions.set(submission.clientMessageId, submission)
  }
  // Match sequential application, including older-host rows clearing stale claims.
  const latestTurn = latestTurnAfterStructuredAgentSessionBatch(left.latestTurn, right)
  const actionablePromptIds = actionablePromptIdsAfterStructuredAgentSessionBatch(
    left.actionablePromptIds,
    right
  )
  const working = hostWorkingAfterStructuredAgentSessionBatch(left.working, right)
  return {
    type: 'batch',
    ...(left.commandsChanged || right.commandsChanged ? { commandsChanged: true as const } : {}),
    ...(right.commands !== undefined || left.commands !== undefined
      ? { commands: right.commands !== undefined ? right.commands : left.commands }
      : {}),
    sessionId: right.sessionId,
    batch: {
      cursor: right.batch.cursor,
      items: [...items.values()],
      removedItemIds: [],
      submissions: [...submissions.values()]
    },
    ...(right.fence !== undefined || left.fence !== undefined
      ? { fence: right.fence ?? left.fence }
      : {}),
    ...(right.backgroundTasks !== undefined || left.backgroundTasks !== undefined
      ? {
          backgroundTasks:
            right.backgroundTasks !== undefined
              ? right.backgroundTasks
              : (left.backgroundTasks ?? null)
        }
      : {}),
    ...(right.activity !== undefined || left.activity !== undefined
      ? { activity: right.activity !== undefined ? right.activity : (left.activity ?? null) }
      : {}),
    ...(latestTurn !== undefined ? { latestTurn } : {}),
    ...(actionablePromptIds !== undefined ? { actionablePromptIds } : {}),
    ...(working !== undefined ? { working } : {}),
    // Only the final merged page can end catch-up.
    ...(right.hasNewer ? { hasNewer: true as const } : {})
  }
}

export function createStructuredAgentSessionEventCoalescer(
  emit: (event: AgentSessionSubscribeEvent) => void,
  delayMs = STRUCTURED_AGENT_SESSION_CLIENT_COALESCE_MS
): {
  push: (event: AgentSessionSubscribeEvent) => void
  flush: () => void
  dispose: () => void
} {
  let pending: Extract<AgentSessionSubscribeEvent, { type: 'batch' }> | null = null
  let timer: ReturnType<typeof setTimeout> | null = null
  const flush = (): void => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    if (pending) {
      const event = pending
      pending = null
      emit(event)
    }
  }
  return {
    push(event) {
      if (bypassCoalescing(event)) {
        flush()
        emit(event)
        return
      }
      if (event.type !== 'batch') {
        return
      }
      pending = pending ? mergeBatch(pending, event) : event
      timer ??= setTimeout(flush, delayMs)
    },
    flush,
    dispose() {
      if (timer) {
        clearTimeout(timer)
      }
      timer = null
      pending = null
    }
  }
}