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.

5.7 KB
Raw Blame
import type { ParsedAgentStatusPayload } from './agent-status-types'
import { parseAgentStatusPayload } from './agent-status-types'
import { ownRetainedString } from './own-retained-string'
import type { ProgramStatusFacet } from './program-status/facet'
import type { AgentStatus } from './agent-title-core'

const OSC_AGENT_STATUS_PREFIX = '\x1b]9999;'

/** Return a suffix that can only be the beginning of an OSC 9999 marker. */
function findAgentStatusPrefixCarry(data: string): string {
  const lastChar = data.charCodeAt(data.length - 1)
  if (lastChar !== 0x1b && lastChar !== 0x5d && lastChar !== 0x39 && lastChar !== 0x3b) {
    return ''
  }
  const maxCarryLength = Math.min(data.length, OSC_AGENT_STATUS_PREFIX.length - 1)
  for (let length = maxCarryLength; length > 0; length -= 1) {
    const suffix = data.slice(data.length - length)
    if (OSC_AGENT_STATUS_PREFIX.startsWith(suffix)) {
      return suffix
    }
  }
  return ''
}

export type ProcessedAgentStatusChunk = {
  cleanData: string
  payloads: ParsedAgentStatusPayload[]
  lastPayloadCleanOffset: number | null
  /** Each payload's end offset in `cleanData`, so other in-band status can merge in byte order. */
  payloadCleanOffsets?: number[]
  /** The subset of `payloads` projected from OSC 7501 records; these yield to the pane's hook row. */
  programStatusPayloads?: ReadonlySet<ParsedAgentStatusPayload>
  /** The subset of those whose program left no records (see ProgramStatusPayload.removesRow). */
  programStatusRowRemovals?: ReadonlySet<ParsedAgentStatusPayload>
  /** The chunk's net OSC 7501 facet change: new facet, `null` when cleared, absent when unchanged. */
  programStatusFacet?: ProgramStatusFacet | null
  /** Each change in the program's OSC 7501 activity, in byte order with `cleanData` offsets.
   *  Title trackers classify by it ahead of title glyphs while it is non-null. */
  programActivity?: readonly ProgramActivityChange[]
}

/** The program's OSC 7501 activity from `offset` on; `null` once it stops reporting. */
export type ProgramActivityChange = { offset: number; activity: AgentStatus | null }

function findAgentStatusTerminator(
  data: string,
  searchFrom: number,
  next: { belIndex: number; stIndex: number }
): { index: number; length: 1 | 2 } | null {
  // Cache forward matches (including absence) per chunk; searchFrom must increase or the cached match may no longer be earliest.
  if (next.belIndex !== -1 && next.belIndex < searchFrom) {
    next.belIndex = data.indexOf('\x07', searchFrom)
  }
  if (next.stIndex !== -1 && next.stIndex < searchFrom) {
    next.stIndex = data.indexOf('\x1b\\', searchFrom)
  }
  if (next.belIndex === -1 && next.stIndex === -1) {
    return null
  }
  if (next.stIndex === -1 || (next.belIndex !== -1 && next.belIndex < next.stIndex)) {
    return { index: next.belIndex, length: 1 }
  }
  return { index: next.stIndex, length: 2 }
}

/** Parse OSC 9999 for hidden/model-owned terminals as well as mounted views. */
export function createAgentStatusOscProcessor(): (data: string) => ProcessedAgentStatusChunk {
  const MAX_PENDING = 64 * 1024
  let pending = ''
  // Track searched pending bytes so split frames scan new bytes instead of the whole accumulation.
  let pendingSearched = 0

  return (data: string): ProcessedAgentStatusChunk => {
    // Keep ordinary output on the identity path unless it ends in a split marker, avoiding clean-string rebuilds per PTY chunk.
    if (pending.length === 0 && !data.includes(OSC_AGENT_STATUS_PREFIX)) {
      const carry = findAgentStatusPrefixCarry(data)
      if (carry.length === 0) {
        return { cleanData: data, payloads: [], lastPayloadCleanOffset: null }
      }
      pending = carry
      return {
        cleanData: data.slice(0, data.length - carry.length),
        payloads: [],
        lastPayloadCleanOffset: null
      }
    }

    const combined = pending + data
    const resumeFrom = pendingSearched
    pending = ''
    pendingSearched = 0

    const payloads: ParsedAgentStatusPayload[] = []
    let lastPayloadCleanOffset: number | null = null
    const payloadCleanOffsets: number[] = []
    let cleanData = ''
    let cursor = 0
    const nextTerminator = { belIndex: 0, stIndex: 0 }

    while (cursor < combined.length) {
      const start = combined.indexOf(OSC_AGENT_STATUS_PREFIX, cursor)
      if (start === -1) {
        const tail = combined.slice(cursor)
        const carry = findAgentStatusPrefixCarry(tail)
        if (carry.length > 0) {
          cleanData += tail.slice(0, tail.length - carry.length)
          pending = carry
        } else {
          cleanData += tail
        }
        break
      }

      cleanData += combined.slice(cursor, start)
      const payloadStart = start + OSC_AGENT_STATUS_PREFIX.length
      // Minus one so a `\x1b\\` straddling the previous chunk boundary is still found.
      const searchFrom =
        start === 0 && resumeFrom > 0 ? Math.max(payloadStart, resumeFrom - 1) : payloadStart
      const terminator = findAgentStatusTerminator(combined, searchFrom, nextTerminator)

      if (terminator === null) {
        const candidate = combined.slice(start)
        // Own the frame so it stops pinning the consumed chunk it was sliced from.
        pending = candidate.length > MAX_PENDING ? '' : ownRetainedString(candidate)
        pendingSearched = pending.length
        break
      }

      const parsed = parseAgentStatusPayload(combined.slice(payloadStart, terminator.index))
      if (parsed) {
        payloads.push(parsed)
        lastPayloadCleanOffset = cleanData.length
        payloadCleanOffsets.push(lastPayloadCleanOffset)
      }
      cursor = terminator.index + terminator.length
    }

    return {
      cleanData,
      payloads,
      lastPayloadCleanOffset,
      ...(payloads.length > 0 ? { payloadCleanOffsets } : {})
    }
  }
}