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.

8.0 KB
Raw Blame
import { pollCodexTranscriptStatus } from '../shared/agent-hook-listener/providers/codex-transcript-poll'
// Retry late transcript results against the same cached event; one owner cancels both timer families before cache teardown.
import {
  hasPendingAgentResultText,
  preparePendingGrokResultDiscovery
} from '../shared/agent-hook-listener/grok-result-discovery'
import { normalizeHookPayload } from '../shared/agent-hook-listener'
import type { AgentHookEventPayload } from '../shared/agent-hook-listener/listener-event'
import type { HookListenerState } from '../shared/agent-hook-listener/listener-state'
import type { AgentHookSource } from '../shared/agent-hook-relay'
import { pickHostTurnEnd } from '../shared/agent-status-types'
import {
  shouldPollHookTranscript,
  hookTranscriptWatchPath,
  transcriptPollUpdate
} from '../shared/agent-hook-listener/transcript-poll-policy'
import { AgentTranscriptPollScheduler } from '../shared/agent-transcript-poll-scheduler'
import { ClaudeOwedNotificationExpiryTimers } from '../shared/claude-owed-notification-expiry-timers'

const ASSISTANT_MESSAGE_RETRY_ATTEMPTS = 5
const ASSISTANT_MESSAGE_RETRY_MS = 50
const CODEX_SUBAGENT_POLL_MS = 1_000

type TranscriptPoll = {
  source: AgentHookSource
  body: unknown
  original: AgentHookEventPayload
  env?: string
  version?: string
}

export type AgentHookResultRetryHost = {
  state: HookListenerState
  env: string
  /** Why: must be read live — a retry armed before stop() must not resurrect on a downed server. */
  isListening: () => boolean
  applyEvent: (
    event: AgentHookEventPayload,
    source: AgentHookSource,
    env?: string,
    version?: string
  ) => AgentHookEventPayload | undefined
}

export class AgentHookResultRetryScheduler {
  private assistantMessageRetryTimers = new Map<string, ReturnType<typeof setTimeout>>()
  private transcriptPollScheduler: AgentTranscriptPollScheduler<TranscriptPoll>
  private host: AgentHookResultRetryHost
  private claudeOwedNotificationExpiry: ClaudeOwedNotificationExpiryTimers

  constructor(host: AgentHookResultRetryHost) {
    this.host = host
    this.claudeOwedNotificationExpiry = new ClaudeOwedNotificationExpiryTimers(host.state)
    this.transcriptPollScheduler = new AgentTranscriptPollScheduler(
      CODEX_SUBAGENT_POLL_MS,
      (paneKey, poll) => this.runTranscriptPoll(paneKey, poll)
    )
  }

  clearAll(): void {
    for (const timer of this.assistantMessageRetryTimers.values()) {
      clearTimeout(timer)
    }
    this.assistantMessageRetryTimers.clear()
    this.transcriptPollScheduler.clearAll()
    this.claudeOwedNotificationExpiry.clearAll()
  }

  /** No hook fires when Claude never sends an owed task notification; restate the row ourselves. */
  armClaudeOwedNotificationExpiry(
    source: AgentHookSource,
    paneKey: string,
    env?: string,
    version?: string
  ): void {
    this.claudeOwedNotificationExpiry.arm(paneKey, (row) => {
      if (this.host.isListening()) {
        this.host.applyEvent(row, source, env, version)
      }
    })
  }

  clearAssistantMessageRetry(paneKey: string): void {
    const timer = this.assistantMessageRetryTimers.get(paneKey)
    if (!timer) {
      return
    }
    clearTimeout(timer)
    this.assistantMessageRetryTimers.delete(paneKey)
  }

  clearTranscriptPoll(paneKey: string): void {
    this.transcriptPollScheduler.clear(paneKey)
  }

  scheduleTranscriptPoll(
    source: AgentHookSource,
    body: unknown,
    original: AgentHookEventPayload,
    env?: string,
    version?: string
  ): void {
    // Why: a nested CLI of another kind inherits ORCA_PANE_KEY, so clearing here would silently end a live poll.
    if (source !== 'codex' && source !== 'muse') {
      return
    }
    if (!shouldPollHookTranscript(this.host.state, source, original)) {
      this.transcriptPollScheduler.clear(original.paneKey)
      return
    }
    this.transcriptPollScheduler.schedule(
      original.paneKey,
      {
        source,
        body,
        original,
        env,
        version
      },
      hookTranscriptWatchPath(this.host.state, source, original.paneKey)
    )
  }

  private runTranscriptPoll(paneKey: string, poll: TranscriptPoll): void {
    const { source, body, original, env, version } = poll
    // Keep the identity check at callback time: a newer event supersedes this
    // payload even when its pane still has transcript children.
    if (
      paneKey !== original.paneKey ||
      !this.host.isListening() ||
      this.host.state.lastStatusByPaneKey.get(original.paneKey) !== original
    ) {
      return
    }
    const event =
      source === 'codex'
        ? pollCodexTranscriptStatus(this.host.state, original, body, this.host.env)
        : normalizeHookPayload(this.host.state, source, body, this.host.env)
    if (!event) {
      return
    }
    const update = transcriptPollUpdate(source, original, event)
    // Why: the next tick's identity check compares against the stored row, not the update it was copied from.
    const next = update ? this.host.applyEvent(update, source, env, version) : original
    if (next) {
      this.scheduleTranscriptPoll(source, body, next, env, version)
    }
  }

  scheduleAssistantMessageRetry(
    source: AgentHookSource,
    body: unknown,
    original: AgentHookEventPayload,
    env?: string,
    version?: string,
    attempt = 1,
    discoveryReady = false
  ): void {
    if (
      original.payload.lastAssistantMessage ||
      !hasPendingAgentResultText(source, body) ||
      attempt > ASSISTANT_MESSAGE_RETRY_ATTEMPTS
    ) {
      return
    }
    this.clearAssistantMessageRetry(original.paneKey)
    if (!discoveryReady) {
      const discovery = preparePendingGrokResultDiscovery(source, body)
      if (discovery) {
        // Why: slug-group discovery can outlive the bounded flush timers, so its completion drives the first retry.
        void discovery
          .then(() => {
            if (this.host.isListening()) {
              this.applyAssistantMessageRetry(source, body, original, env, version, 1, true)
            }
          })
          .catch((err) => {
            process.stderr.write(
              `[relay-hook-server] Grok result discovery failed: ${err instanceof Error ? err.message : String(err)}\n`
            )
          })
        return
      }
    }
    const timer = setTimeout(() => {
      try {
        this.assistantMessageRetryTimers.delete(original.paneKey)
        this.applyAssistantMessageRetry(
          source,
          body,
          original,
          env,
          version,
          attempt + 1,
          discoveryReady
        )
      } catch (err) {
        process.stderr.write(
          `[relay-hook-server] assistant message retry failed: ${err instanceof Error ? err.message : String(err)}\n`
        )
      }
    }, ASSISTANT_MESSAGE_RETRY_MS)
    this.assistantMessageRetryTimers.set(original.paneKey, timer)
    if (typeof timer.unref === 'function') {
      timer.unref()
    }
  }

  private applyAssistantMessageRetry(
    source: AgentHookSource,
    body: unknown,
    original: AgentHookEventPayload,
    env: string | undefined,
    version: string | undefined,
    nextAttempt: number,
    requireExactOriginal: boolean
  ): void {
    const current = this.host.state.lastStatusByPaneKey.get(original.paneKey)
    if (
      !current ||
      (requireExactOriginal && current !== original) ||
      current.payload.agentType !== original.payload.agentType ||
      current.payload.prompt !== original.payload.prompt ||
      current.payload.lastAssistantMessage
    ) {
      return
    }
    const event = normalizeHookPayload(this.host.state, source, body, this.host.env)
    if (!event?.payload.lastAssistantMessage) {
      this.scheduleAssistantMessageRetry(
        source,
        body,
        original,
        env,
        version,
        nextAttempt,
        requireExactOriginal
      )
      return
    }
    // Why: the retry only adds text to the same turn end, so it restates that end instead of minting one.
    this.host.applyEvent({ ...event, ...pickHostTurnEnd(current) }, source, env, version)
  }
}