Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

10.8 KB
Raw Blame
import type { VaultRequest, WorkbenchMessage } from '@/context/ApiContext';
import { isDetachedCompletionMessage } from '@/lib/chatMessageTypes';
import { chatRowKind } from '@/lib/chatRowKind';
import { specFor } from '@/lib/messageTypes';
import { messageOrderTimeMs, timestampOrderTimeMs, transcriptOrderTimeMs } from '@/lib/transcriptOrder';

export type VaultRequestType = 'access' | 'sign' | 'provision' | 'delete' | 'other';

export function vaultRequestType(request: VaultRequest): VaultRequestType {
  const cardType = (request.card as { request_type?: unknown } | null)?.request_type;
  const type = typeof cardType === 'string' ? cardType : request.request_type;
  return type === 'access' || type === 'sign' || type === 'provision' || type === 'delete' ? type : 'other';
}

export function isVaultApprovalRequest(request: VaultRequest): boolean {
  const type = vaultRequestType(request);
  return type === 'access' || type === 'sign' || type === 'delete';
}

/**
 * Whether approving this request runs the sandbox's protected ceremony: a protected sign, or an
 * access whose fixed set includes protected members. Provision requests never approve.
 */
export function vaultApprovalNeedsPasskey(request: VaultRequest): boolean {
  const type = vaultRequestType(request);
  if (type === 'provision' || type === 'delete') return false;
  const card = (request.card ?? {}) as {
    protection?: string | null;
    protected_secret_names?: string[];
    grant_options?: Array<{ unlock_material?: unknown[] }>;
  };
  if (type === 'sign') return card.protection === 'protected';
  return (card.grant_options?.[0]?.unlock_material?.length ?? 0) > 0 || (card.protected_secret_names?.length ?? 0) > 0;
}

export type VaultProvisionPlacement = {
  byMessageId: Map<string, VaultRequest[]>;
  /** Requests of the transcript's latest turn whose owning reply has not landed. */
  awaitingReply: VaultRequest[];
};

function isAgentReplyWithExplicitProvenance(message: WorkbenchMessage): boolean {
  // Muted ``interim`` narration shares the boundary card but is not a reply that
  // owns the Turn's requests.
  if (specFor(message.type).render === 'muted') return false;
  const kind = chatRowKind(message).kind;
  return kind === 'agent' || kind === 'boundary';
}

function isInferredAgentReply(message: WorkbenchMessage): boolean {
  return !isDetachedCompletionMessage(message) && isAgentReplyWithExplicitProvenance(message);
}

function isInputTurn(message: WorkbenchMessage): boolean {
  return specFor(message.type).inputAuthors.includes(message.author);
}

function appendRequest(map: Map<string, VaultRequest[]>, messageId: string, request: VaultRequest): void {
  const current = map.get(messageId);
  if (current) current.push(request);
  else map.set(messageId, [request]);
}

function record(value: unknown): Record<string, unknown> {
  return value && typeof value === 'object' && !Array.isArray(value)
    ? value as Record<string, unknown>
    : {};
}

/** The transcript message that started the turn which created a request. */
export function vaultRequestSourceMessageId(request: VaultRequest): string | null {
  const requester = record(request.requester);
  const messageId = requester.message_id;
  return typeof messageId === 'string' && messageId.trim() ? messageId : null;
}

export function vaultRequestSourceTurnId(request: VaultRequest): string | null {
  const requester = record(request.requester);
  const turnId = requester.turn_id;
  return typeof turnId === 'string' && turnId.trim() ? turnId : null;
}

export function vaultRequestSourceRunId(request: VaultRequest): string | null {
  const requester = record(request.requester);
  const runId = requester.run_id;
  return typeof runId === 'string' && runId.trim() ? runId : null;
}

export function vaultRequestSourcePlatform(request: VaultRequest): string | null {
  const requester = record(request.requester);
  const platform = requester.platform;
  return typeof platform === 'string' && platform.trim() ? platform : null;
}

function sameRequestTurn(request: VaultRequest, message: WorkbenchMessage): boolean {
  const requester = record(request.requester);
  const metadata = record(message.metadata);
  for (const key of ['turn_id', 'run_id'] as const) {
    const requestId = typeof requester[key] === 'string' ? requester[key] : '';
    if (requestId && requestId === metadata[key]) return true;
  }
  return false;
}

function inferReplyWithinTurn(
  messages: WorkbenchMessage[],
  requestTime: number,
): WorkbenchMessage | undefined {
  for (const message of messages) {
    const messageTime = messageOrderTimeMs(message);
    if (Number.isNaN(messageTime) || messageTime < requestTime) continue;
    // An anchorless request belongs only to the turn that created it. Once a
    // later user/harness input starts another turn, no later Agent row can own it.
    if (isInputTurn(message)) return undefined;
    if (isInferredAgentReply(message)) return message;
  }
  return undefined;
}

// Either clock counts: a queued input can be authored before the request and
// still enter the transcript after it, starting the next turn.
function inputFollowsRequest(messages: WorkbenchMessage[], requestTime: number): boolean {
  return messages.some((message) => isInputTurn(message) && (
    messageOrderTimeMs(message) >= requestTime || transcriptOrderTimeMs(message) >= requestTime
  ));
}

function inferReplyFromSourceMessage(
  messages: WorkbenchMessage[],
  sourceMessageId: string,
  requestTime: number,
  sourcePlatform: string | null,
): WorkbenchMessage | undefined {
  const sourceIndex = messages.findIndex(
    (message) => message.id === sourceMessageId || (
      message.native_message_id === sourceMessageId &&
      (!sourcePlatform || message.platform === sourcePlatform)
    ),
  );
  if (sourceIndex < 0) return undefined;
  let replyBeforeRequest: WorkbenchMessage | undefined;

  for (const message of messages.slice(sourceIndex + 1)) {
    if (isInputTurn(message)) {
      // A request may be persisted after its reply but before the next input.
      // In that case the recorded pre-request reply is still the owner. Only
      // discard the source identity when the later input predates the request.
      const messageTime = transcriptOrderTimeMs(message);
      return replyBeforeRequest && !Number.isNaN(requestTime) &&
        !Number.isNaN(messageTime) && messageTime >= requestTime
        ? replyBeforeRequest
        : undefined;
    }
    if (!isInferredAgentReply(message)) continue;
    if (Number.isNaN(requestTime) || messageOrderTimeMs(message) >= requestTime) return message;
    // Some legacy request rows point at an older input even though the request
    // was persisted after that turn's reply. Keep it as a fallback only when
    // the source turn never crosses another input boundary.
    replyBeforeRequest ??= message;
  }
  return replyBeforeRequest;
}

/** Attach provision requests to the Agent reply that announced them.
 *
 * Newer producers can set `message_id` explicitly. Historical CLI-created rows
 * do not, so use the session's serialized turn order: the first Agent-authored
 * message created after the request is the reply that owns it. A request made
 * during a turn that is still running has no owner yet; it waits at the
 * transcript tail until its reply arrives or another input starts a new turn.
 */
export function placeVaultProvisionRequests(
  messages: WorkbenchMessage[],
  requests: VaultRequest[],
  sourceMessageIds: ReadonlyMap<string, string> = new Map(),
): VaultProvisionPlacement {
  const byMessageId = new Map<string, VaultRequest[]>();
  const awaitingReply: VaultRequest[] = [];
  const messagesById = new Map(messages.map((message) => [message.id, message]));
  const agentMessages = messages.filter(isAgentReplyWithExplicitProvenance);
  // Window coverage follows transcript-entry order. A queued row can be authored
  // before the request but only enter the visible transcript after it, so its
  // message-id clock must not make a trimmed request look loaded.
  const firstLoadedTime = messages.length > 0 ? transcriptOrderTimeMs(messages[0]) : Number.NaN;

  for (const request of requests) {
    if (vaultRequestType(request) !== 'provision') continue;

    const explicitReplyId = typeof request.message_id === 'string' && request.message_id.trim()
      ? request.message_id
      : null;
    const explicit = explicitReplyId ? messagesById.get(explicitReplyId) : undefined;
    if (explicit && isAgentReplyWithExplicitProvenance(explicit)) {
      appendRequest(byMessageId, explicit.id, request);
      continue;
    }
    const explicitReplyUnresolved = Boolean(
      explicitReplyId && (!explicit || !isAgentReplyWithExplicitProvenance(explicit))
    );

    const requestTime = timestampOrderTimeMs(request.created_at);
    const sameTurn = agentMessages.find((message) => sameRequestTurn(request, message));
    // The request row can be written after the Agent reply has already been
    // persisted, so its creation timestamp is not a reliable turn boundary.
    // Newer requesters carry the input message id; use that identity first.
    const explicitSource = vaultRequestSourceMessageId(request);
    const fromSource = explicitSource ?? sourceMessageIds.get(request.id) ?? null;
    const sourcePlatform = vaultRequestSourcePlatform(request);
    const sourceResolved = Boolean(fromSource && messages.some(
      (message) => message.id === fromSource || (
        message.native_message_id === fromSource &&
        (!sourcePlatform || message.platform === sourcePlatform)
      ),
    ));
    const sourceUnresolved = Boolean(explicitSource && !sourceResolved);
    // Do not guess when the request predates the retained message window: its
    // real owner may have been trimmed, and attaching it to the first visible
    // later reply would move the card to an unrelated turn.
    const windowCoversRequest = Number.isNaN(firstLoadedTime) || firstLoadedTime <= requestTime;
    const fromSourceReply = fromSource
      ? inferReplyFromSourceMessage(messages, fromSource, requestTime, sourcePlatform)
      : undefined;
    const inferred = explicitReplyUnresolved
      ? undefined
      : sameTurn ?? fromSourceReply
        ?? (sourceUnresolved || Number.isNaN(requestTime) || !windowCoversRequest
          ? undefined
          : inferReplyWithinTurn(messages, requestTime));
    if (inferred) {
      appendRequest(byMessageId, inferred.id, request);
      continue;
    }
    // Without an owner, only a request from the latest loaded turn belongs at the
    // tail. A named but unloaded anchor, an uncovered window, or a later input
    // means the request's turn has ended, so it must not sit below newer turns.
    if (
      !explicitReplyUnresolved && !sourceUnresolved &&
      !Number.isNaN(requestTime) && windowCoversRequest &&
      !inputFollowsRequest(messages, requestTime)
    ) {
      awaitingReply.push(request);
    }
  }

  return { byMessageId, awaitingReply };
}