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.

11.8 KB
Raw Blame
import type { AgentSessionOwnerObservation } from './agent-session-conversation-view'
/**
 * Single-writer lease adjudication.
 *
 * Every decision here fails closed: expiry alone never grants a second owner, and an
 * unverifiable process counts as possibly alive until recovery resolution concludes about it. A
 * lease that names no process at all is released: nothing was recorded that could be holding it.
 * This is the opposite polarity
 * from daemon adoption checks, which fail open on a missing start time — a wrong answer there
 * refuses an adoption, a wrong answer here creates two writers on one provider session.
 */

import { nextAgentSessionFence } from './agent-session-next-fence'
import type {
  AgentSessionDeathEvidence,
  AgentSessionHandoffStage,
  AgentSessionLease
} from './agent-session-record'
import type {
  AgentSessionOwnerVerdict,
  AgentSessionRefusalDetailsByCode
} from './agent-session-wire-refusals'

/** What a PID probe can compare against the recorded owner. */
export type AgentSessionProcessIdentityField = 'process-start-time' | 'spawn-token'

/** `held-child`: this runtime still holds the child at the record's fence and has not seen it exit.
 *  Only lease renewal in that runtime asserts it; restart and recovery probes never can. */
export type AgentSessionIdentityMatchField = AgentSessionProcessIdentityField | 'held-child'

export type AgentSessionOwnerProbe =
  /** Orca watched this exact process exit. */
  | { outcome: 'exit-observed' }
  /** The recorded pid is not present on the host. */
  | { outcome: 'pid-absent' }
  /** The pid is present but is a different process. */
  | { outcome: 'identity-mismatch'; field: AgentSessionProcessIdentityField | 'command-line' }
  /** The pid is present and at least one identity element was verified. */
  | { outcome: 'identity-matched'; matchedOn: readonly AgentSessionIdentityMatchField[] }
  /** No process carries the reserved spawn token and the provider saw no activity after it. */
  | { outcome: 'reservation-unused' }
  /** The host could not answer — restricted container, no start time, no token echo. */
  | { outcome: 'indeterminate'; reason: string }

export type AgentSessionLeaseRefusalCode =
  | 'agent_session_checkpoint_stale'
  | 'agent_session_conflict'
  | 'agent_session_ownership_unknown'
  | 'agent_session_operation_conflict'
  | 'execution_owner_reconciling'

export type AgentSessionAcquisitionDecision =
  | { decision: 'granted'; nextFence: number }
  /** The same acquisition operation re-entering its own reservation; no new fence, no new spawn. */
  | { decision: 'retry-reservation'; fence: number }
  | {
      [C in AgentSessionLeaseRefusalCode]: {
        decision: 'refused'
        code: C
        details: AgentSessionRefusalDetailsByCode[C]
      }
    }[AgentSessionLeaseRefusalCode]

export type AgentSessionRestartAdjudication =
  /** Nothing is outstanding — no owner, no reservation. Clear any latched stage; the fence stays. */
  | { disposition: 'free'; reason: string }
  /** `evidence` is null when nothing proved the owner gone: it was never recorded. */
  | { disposition: 'evicted'; nextFence: number; evidence: AgentSessionDeathEvidence | null }
  | { disposition: 'recovering'; stage: AgentSessionHandoffStage; reason: string }

export function isProvenDeadProbe(probe: AgentSessionOwnerProbe): boolean {
  return (
    probe.outcome === 'exit-observed' ||
    probe.outcome === 'pid-absent' ||
    probe.outcome === 'identity-mismatch'
  )
}

/** A PID match needs reuse-safe start-time/token evidence; otherwise liveness is indeterminate. */
export function isProvenAliveProbe(probe: AgentSessionOwnerProbe): boolean {
  return probe.outcome === 'identity-matched' && probe.matchedOn.length > 0
}

function deathEvidenceFor(
  probe: AgentSessionOwnerProbe,
  observedAt: number,
  lease: AgentSessionLease
): AgentSessionDeathEvidence | null {
  // Capped so a clock that stepped back across the restart still writes a valid interval.
  const interval = {
    observedAt,
    ownerFence: lease.runtimeFence,
    lastProvenAliveAt: Math.min(lease.lastRenewedAt, observedAt)
  }
  if (probe.outcome === 'exit-observed') {
    return { kind: 'exit-observed', detail: 'observed process exit', ...interval }
  }
  if (probe.outcome === 'pid-absent') {
    return { kind: 'pid-absent', detail: 'recorded pid absent on host', ...interval }
  }
  if (probe.outcome === 'identity-mismatch') {
    return { kind: 'identity-mismatch', detail: `mismatched ${probe.field}`, ...interval }
  }
  return null
}

/** `exited` only for a lease released on death evidence; one recovery released without proof, like
 *  anything held or mid-handoff, may still be running. */
export function agentSessionLeaseOwnerVerdict(lease: AgentSessionLease): AgentSessionOwnerVerdict {
  return agentSessionOwnerObservationVerdict(lease)
}

export function agentSessionOwnerObservationVerdict(
  lease: AgentSessionOwnerObservation
): AgentSessionOwnerVerdict {
  if (agentSessionOwnerObservationIsLive(lease)) {
    return 'live'
  }
  return lease.claimStatus === 'released' &&
    lease.handoffStage === null &&
    lease.ownerProcess === null &&
    lease.reservedSpawnToken === null &&
    lease.deathEvidence !== null
    ? 'exited'
    : 'unverifiable'
}

/** Founding is not an observed death; every reservation/recovery leaves a different tuple. */
export function agentSessionLeaseNeverAcquired(lease: AgentSessionLease): boolean {
  return (
    lease.runtimeKind === 'native' &&
    lease.runtimeFence === 1 &&
    lease.minimumNextFence === undefined &&
    !lease.unreconciled &&
    lease.claimStatus === 'released' &&
    lease.ownerProcess === null &&
    lease.reservedSpawnToken === null &&
    lease.handoffStage === null &&
    lease.handoffOperationId === null &&
    lease.provenHandleLinkId === null &&
    lease.deathEvidence === null
  )
}

export function agentSessionLeasePossiblyWriting(
  lease: AgentSessionLease | AgentSessionOwnerObservation
): boolean {
  return (
    !('runtimeKind' in lease && agentSessionLeaseNeverAcquired(lease)) &&
    agentSessionOwnerObservationVerdict(lease) !== 'exited'
  )
}

/** Nothing holds this lease: released, no handoff in flight, and reconciled since the last restart. */
export function agentSessionLeaseIsReleased(lease: AgentSessionLease): boolean {
  return !lease.unreconciled && lease.claimStatus === 'released' && lease.handoffStage === null
}

/** True when the recorded owner may write right now. Used by every mutating path in later parts. */
export function agentSessionLeaseAdmitsWriter(lease: AgentSessionLease): boolean {
  return agentSessionOwnerObservationIsLive(lease)
}

export function agentSessionOwnerObservationIsLive(lease: AgentSessionOwnerObservation): boolean {
  return (
    !lease.unreconciled &&
    lease.handoffStage === null &&
    lease.claimStatus === 'live' &&
    lease.ownerProcess !== null
  )
}

export function isAgentSessionFenceCurrent(lease: AgentSessionLease, fence: number): boolean {
  return Number.isSafeInteger(fence) && fence === lease.runtimeFence
}

/** CAS acquisition probes only when a recorded owner or unused reservation blocks the caller. */
export function evaluateAgentSessionAcquisition(args: {
  lease: AgentSessionLease
  expectedFence: number
  handoffOperationId: string | null
  probe: AgentSessionOwnerProbe
}): AgentSessionAcquisitionDecision {
  const { lease, expectedFence, handoffOperationId, probe } = args
  if (lease.unreconciled) {
    return {
      decision: 'refused',
      code: 'execution_owner_reconciling',
      details: { reason: 'hostReconciling' }
    }
  }
  if (!isAgentSessionFenceCurrent(lease, expectedFence)) {
    return {
      decision: 'refused',
      code: 'agent_session_checkpoint_stale',
      details: { reason: 'fenceStale' }
    }
  }
  if (lease.claimStatus === 'conflicted') {
    // Why: the user's own terminal agent; restart adjudication and recovery retire it once gone.
    return {
      decision: 'refused',
      code: 'agent_session_conflict',
      details: { reason: 'claimConflicted' }
    }
  }
  if (lease.handoffStage === 'recovering') {
    // Why: no stage expires into an owner; recovery resolution concludes about it first.
    return {
      decision: 'refused',
      code: 'agent_session_ownership_unknown',
      details: { reason: 'ownerUnproven' }
    }
  }
  if (lease.handoffStage !== null && lease.handoffOperationId !== null) {
    if (handoffOperationId !== lease.handoffOperationId) {
      // Why: the retry key is operation id + fence + stage; a different id is a different intent.
      return {
        decision: 'refused',
        code: 'agent_session_operation_conflict',
        details: { reason: 'handoffInFlight' }
      }
    }
    if (
      lease.ownerProcess === null &&
      lease.claimStatus === 'reserved' &&
      lease.reservedSpawnToken !== null
    ) {
      // Why: an idempotent re-run of a reservation that already exists at this fence.
      return { decision: 'retry-reservation', fence: lease.runtimeFence }
    }
  }
  if (lease.ownerProcess !== null) {
    if (!isProvenDeadProbe(probe)) {
      // Expiry means no renewal was heard, not that the child stopped editing files or spending tokens.
      return isProvenAliveProbe(probe)
        ? { decision: 'refused', code: 'agent_session_conflict', details: { reason: 'ownerAlive' } }
        : {
            decision: 'refused',
            code: 'agent_session_ownership_unknown',
            details: { reason: 'ownerUnproven' }
          }
    }
    return { decision: 'granted', nextFence: nextAgentSessionFence(lease) }
  }
  if (lease.claimStatus === 'reserved' && probe.outcome !== 'reservation-unused') {
    // An unproven reservation is not free: the crash may have followed the spawn.
    return {
      decision: 'refused',
      code: 'agent_session_ownership_unknown',
      details: { reason: 'ownerUnproven' }
    }
  }
  return { decision: 'granted', nextFence: nextAgentSessionFence(lease) }
}

/** Every loaded lease starts unreconciled and grants no writer until restart reconciliation finishes. */
export function adjudicateAgentSessionRestart(args: {
  lease: AgentSessionLease
  probe: AgentSessionOwnerProbe
  observedAt: number
}): AgentSessionRestartAdjudication {
  const { lease, probe, observedAt } = args
  if (lease.ownerProcess === null) {
    if (lease.reservedSpawnToken === null && lease.claimStatus === 'released') {
      // Without owner or pre-spawn token nothing can hold the lease; do not re-latch released records as unproven reservations.
      return { disposition: 'free', reason: 'lease has no owner and no reservation' }
    }
    // A child without recorded identity lost stdio in the crash; only a token scan can prove absence, but release even without proof. Never signal by token alone: descendants inherit it and cannot be distinguished from the provider.
    return {
      disposition: 'evicted',
      nextFence: nextAgentSessionFence(lease),
      evidence:
        probe.outcome === 'reservation-unused'
          ? {
              kind: 'pid-absent',
              detail: 'reservation never spawned',
              observedAt,
              ownerFence: lease.runtimeFence
            }
          : null
    }
  }
  if (isProvenAliveProbe(probe)) {
    // The crash lost native stdio: recovery stops the undrivable child and respawns at fence + 1 instead of readopting it.
    return {
      disposition: 'recovering',
      stage: 'recovering',
      reason: 'owner outlived the runtime that held its transport'
    }
  }
  const evidence = deathEvidenceFor(probe, observedAt, lease)
  if (evidence) {
    return { disposition: 'evicted', nextFence: nextAgentSessionFence(lease), evidence }
  }
  return {
    // Why: recovery resolution, which runs next, owns the verdict on a recorded identity.
    disposition: 'recovering',
    stage: 'recovering',
    reason:
      probe.outcome === 'indeterminate' ? probe.reason : 'process identity could not be verified'
  }
}