Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

6.9 KB
Raw Blame
import { cronTriggerAuthority } from "../cron/authority.ts";
import type { Keychain, KeychainAsk, KeychainGrant } from "../credentials/keychain.ts";
import type { AuditLog } from "../audit/audit-log.ts";
import type { Cron, Destination, ScopeId } from "../types.ts";
import { runTrigger, destinationVisible, type TriggerDeps, type TriggerOutcome } from "./run-trigger.ts";
import { principalDestination, withWebTranscriptText } from "../reach/reach.ts";
import { swallow } from "../util/errors.ts";
import { cronIdOf } from "../sessions/session-store.ts";
import { samePerson } from "../directory/person.ts";

function resolutionInput(ask: KeychainAsk, grant?: KeychainGrant): string {
  if (ask.status === "approved") {
    const scope = grant?.mode === "once" ? "for one credential use" : "until revoked";
    return `The credential owner approved access ${scope}; it is now in this conversation's grants. Re-run the blocked command and continue. Tell the requester in one short line.`;
  }
  const what = ask.status === "declined" ? "declined" : "did not answer";
  return `The credential owner ${what} the access request. Tell the requester in one short line and offer to continue another way.`;
}

export interface AskResolutionDeps extends TriggerDeps {
  getCron?: (id: string) => Promise<Cron | null>;
  getAsk?: (id: string) => Promise<KeychainAsk | null>;
  getGrant?: (id: string) => Promise<KeychainGrant | null>;
}

function fallbackText(ask: KeychainAsk): string {
  if (ask.status === "approved")
    return "Access approved, but the task could not restart on its own. It will have access the next time it runs.";
  return ask.status === "declined" ? "Access was declined." : "The access request expired.";
}

export async function fireAskResolution(
  deps: AskResolutionDeps,
  ask: KeychainAsk,
  grant?: KeychainGrant,
): Promise<TriggerOutcome> {
  if (!grant && ask.status === "approved" && ask.grantId) {
    grant = (await deps.getGrant?.(ask.grantId)) ?? undefined;
  }
  const cronId = cronIdOf(ask.requesterThreadRef);
  const cron = cronId ? await deps.getCron?.(cronId) : undefined;
  if (
    cronId &&
    (!cron ||
      cron.archived ||
      (!cron.enabled && (cron.schedule.everyMs !== undefined || cron.schedule.cron !== undefined)) ||
      cron.ownerScopeId !== ask.requesterScopeId ||
      !samePerson(cron.owner, ask.requesterId))
  ) {
    return {
      ran: false,
      authzFailed: true,
      note: "the originating cron is unavailable or no longer authorizes this request",
    };
  }
  const destination = cron ? cron.destination : ask.requesterDestination;
  const outcome = await runTrigger(deps, {
    ...cronTriggerAuthority(cron ?? { owner: ask.requesterId, ownerScopeId: ask.requesterScopeId }),
    input: resolutionInput(ask, grant),
    fireKey: `ask:${ask.id}:${ask.status}`,
    surface: "keychain-ask",
    ...(cron?.runtime ? { runtime: cron.runtime } : {}),
    deferWhenBusy: true,
    ...(destination ? { destination } : {}),
    ...(ask.requesterThreadRef ? { threadRef: ask.requesterThreadRef } : {}),
  });
  if (
    outcome.deferred ||
    (!outcome.ran && !outcome.authzFailed && !(await deps.idempotency.committed(`ask:${ask.id}:${ask.status}`)))
  )
    throw new Error("credential approval resume is waiting for the original conversation to become idle");
  if (outcome.ran && outcome.status === "ok") return outcome;
  if (cronId && (!outcome.ran || outcome.status === "refused")) return outcome;
  if (!outcome.ran && !outcome.authzFailed) {
    const cur = await deps.getAsk?.(ask.id);
    if (cur?.notifiedAt !== undefined) return outcome;
  }
  const fallbackDestination = cronId ? principalDestination(ask.ownerId, ask.ownerId) : ask.requesterDestination;
  if (fallbackDestination && (await destinationVisible(deps, ask.requesterId, fallbackDestination))) {
    await deps.deliveries.enqueue({
      destination: withWebTranscriptText(fallbackDestination),
      text: fallbackText(ask),
      idempotencyKey: `ask:${ask.id}:${ask.status}:fallback`,
    });
  }
  return outcome;
}

export interface DropResolution {
  id: string;
  ownerId: string;
  service: string;
  purpose: string;
  audienceScopeId: ScopeId;
  destination?: Destination;
  threadRef?: string;
  grantId?: string;
  credentialHandle?: string;
  granted: boolean;
  pendingSiblings?: string[];
}

function dropResolutionInput(drop: DropResolution): string {
  const waiting = !!drop.pendingSiblings?.length;
  const where = drop.granted
    ? `now in the keychain and granted to this conversation — request \`${drop.credentialHandle}\` in execute.credentials${waiting ? " when the task runs" : " when resuming the task"}`
    : `now in your keychain and available here`;
  const next = waiting
    ? `Heads-up: other drop links from this conversation (${drop.pendingSiblings!.map((s) => `\`${s}\``).join(", ")}) haven't been filled yet — ` +
      `if the task still needs them, acknowledge and keep waiting; don't run it on partial credentials.`
    : `Pick the task back up.`;
  return (
    `Your \`${drop.service}\` credential was just supplied securely via a secret-drop link (for: "${drop.purpose}"). ` +
    `It is ${where}. ${next}`
  );
}

function dropFallbackText(drop: DropResolution): string {
  return (
    `Your \`${drop.service}\` credential was saved to the keychain${drop.granted ? " and granted to this conversation" : ""}, ` +
    `but I couldn't resume the task automatically. Mention me here to pick it up.`
  );
}

export async function fireDropResolution(deps: TriggerDeps, drop: DropResolution): Promise<TriggerOutcome> {
  const outcome = await runTrigger(deps, {
    owner: drop.ownerId,
    ownerScopeId: drop.audienceScopeId,
    input: dropResolutionInput(drop),
    fireKey: `drop:${drop.id}`,
    surface: "secret-drop",
    ...(drop.destination ? { destination: drop.destination } : {}),
    ...(drop.threadRef ? { threadRef: drop.threadRef } : {}),
  });
  if (outcome.ran && outcome.status === "ok") return outcome;
  if (drop.destination && (await destinationVisible(deps, drop.ownerId, drop.destination))) {
    await deps.deliveries.enqueue({
      destination: withWebTranscriptText(drop.destination),
      text: dropFallbackText(drop),
      idempotencyKey: `drop:${drop.id}:fallback`,
    });
  }
  return outcome;
}

export function createAskExpirySweep(deps: {
  keychain: Keychain;
  fire: (ask: KeychainAsk) => Promise<unknown>;
  auditLog?: AuditLog;
}): (now: number) => Promise<void> {
  return async (now) => {
    for (const ask of await deps.keychain.unnotifiedResolvedAsks(now)) {
      if (ask.status === "expired") {
        deps.auditLog?.record({
          at: now,
          principalId: ask.ownerId,
          action: "keychain.ask.expire",
          resource: ask.id,
          scopeLabel: ask.requesterScopeId,
        });
      }
      try {
        await deps.fire(ask);
        await deps.keychain.markAskNotified(ask.id, ask.status);
      } catch (e) {
        swallow(`keychain: ask sweep fire failed for ${ask.id} (will retry next tick)`, e);
      }
    }
  };
}