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.

1.5 KB
Raw Blame
import { ownRetainedString } from './own-retained-string'

const OSC_TITLE_SCAN_TAIL_LIMIT = 4096
const OSC_TITLE_PREFIX_LENGTH = 4
const OSC_TITLE_CODES = new Set(['0', '1', '2'])

export function extractOscTitleScanTail(input: string): string {
  const lastOsc = input.lastIndexOf('\x1b]')
  if (lastOsc !== -1) {
    const suffix = input.slice(lastOsc)
    if (!suffix.includes('\x07') && !suffix.includes('\x1b\\')) {
      // Own the tail so it stops pinning the consumed chunk it was sliced from.
      return ownRetainedString(extractIncompleteTitleOscTail(suffix))
    }
    return input.endsWith('\x1b') ? '\x1b' : ''
  }
  return input.endsWith('\x1b') ? '\x1b' : ''
}

function extractIncompleteTitleOscTail(suffix: string): string {
  const parameterEnd = suffix.indexOf(';', 2)
  if (parameterEnd === -1) {
    const partialParameter = suffix.slice(2)
    return ['', '0', '1', '2'].includes(partialParameter) ? trimOscTitleScanTail(suffix) : ''
  }
  const parameter = suffix.slice(2, parameterEnd)
  return OSC_TITLE_CODES.has(parameter) ? trimOscTitleScanTail(suffix) : ''
}

function trimOscTitleScanTail(value: string): string {
  if (value.length <= OSC_TITLE_SCAN_TAIL_LIMIT) {
    return value
  }
  // Keep the OSC introducer plus newest payload to reconstruct split terminators within the tail cap.
  const prefix = value.slice(0, Math.min(OSC_TITLE_PREFIX_LENGTH, value.length))
  const suffixBudget = Math.max(0, OSC_TITLE_SCAN_TAIL_LIMIT - prefix.length)
  return `${prefix}${value.slice(-suffixBudget)}`
}