Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

38.3 KB
Raw Blame
import { unattendedGrantRefusal } from "../cron/authority.ts";
import { isDeepStrictEqual } from "node:util";
import type { Cron, CronFireLogEntry, CronSchedule, Destination, Webhook } from "../types.ts";
import type { CreateCronInput, CronPatch } from "../cron/cron-store.ts";
import type { CreateWebhookInput } from "../webhooks/webhook-store.ts";
import type { CapabilityClaims } from "../auth/capability-token.ts";
import {
  cronFireReadsNotes,
  describeRunNowRefusal,
  echoesCronContextMarkers,
  flattenFireNote,
  type Scheduler,
} from "../cron/scheduler.ts";
import { DEFAULT_CRON_TIMEZONE } from "../cron/schedule.ts";
import { resolveCapabilityDestination } from "./capability-destination.ts";
import { withSlackUnfurlOption, principalDestination } from "../reach/reach.ts";
import { notifyOwnerOfCronEdit, type CronEditDetail } from "../triggers/edit-notice.ts";
import { errMessage } from "../util/errors.ts";
import { SoulUpdateDeniedError, SoulVersionConflictError } from "./app-types.ts";
import { AdminError } from "../admin/admin-service.ts";
import type { AdminService } from "../admin/admin-service.ts";
import {
  livePersonCapability,
  resolveShareTarget,
  SHARED_SKILL_TRIGGER_REFUSAL,
  type ShareArtifactRequest,
  type ShareArtifactResult,
  isMultiMemberSkillScope,
} from "./artifact-share.ts";
import { actsAsScope, parseScopeId, type Permission, type ScopeId } from "../types.ts";
import { cronRef, encodeRef } from "../acl/resource-ref.ts";
import type { App, VisibleCron } from "./app.ts";

export interface CronCreateRequest {
  runtime?: Cron["runtime"];
  schedule: CronSchedule;
  title?: string;
  action?: string;
  text?: string;
  recipient?: string;
  channel?: string;
  participants?: string[];
  scope?: "personal";
  destinationKey?: string;
  unfurlLinks?: boolean;
  unattendedGrants?: string[];
  session?: boolean;
}

export type CronCreateResult =
  | {
      ok: true;
      cron: Cron;
      recipient?: { principalId: string; displayName: string };
      channel?: { channelId: string; name: string };
      group?: { groupId: string };
    }
  | {
      ok: false;
      code:
        | "bad_request"
        | "recipient_not_found"
        | "ambiguous_recipient"
        | "channel_not_found"
        | "ambiguous_channel"
        | "group_not_found"
        | "not_a_member"
        | "identity_unverified"
        | "unknown_destination"
        | "forbidden"
        | "cron_create_failed";
      message: string;
      candidates?: Array<{ id: string; label: string }>;
    };

export interface WebhookCreateRequest {
  action: string;
  verification: Webhook["verification"];
  filters?: Webhook["filters"];
  destinationKey?: string;
}

export type WebhookCreateResult =
  | { ok: true; webhook: Webhook; url: string; secret?: string }
  | { ok: false; code: "bad_request" | "forbidden" | "unknown_destination" | "webhook_create_failed"; message: string };

export interface CronPatchRequest {
  runtime?: Cron["runtime"];
  title?: string;
  action?: string;
  text?: string;
  schedule?: CronSchedule;
  enabled?: boolean;
  archived?: boolean;
  unfurlLinks?: boolean;
  unattendedGrants?: string[];
  session?: boolean;
}

export interface CronRunsRequest {
  limit?: number;
}

export interface CronRunsResult {
  cron: Cron;
  runs: CronFireLogEntry[];
  total: number;
}

export const CRON_PATCH_NOTHING_TO_CHANGE =
  "nothing to change — pass title, task, schedule, enabled, archived, unfurlLinks, unattendedGrants, or session";

export const CRON_FIRE_NOTE_MAX_CHARS = 400;

export type ControlOk<T> = { ok: true } & T;
export type ControlErr<C extends string> = { ok: false; code: C; message: string };

export interface ControlService {
  createCron(req: CronCreateRequest, claims: CapabilityClaims): Promise<CronCreateResult>;
  listCrons(claims: CapabilityClaims): Promise<{ crons: Cron[]; visible: VisibleCron[] }>;
  getCron(
    id: string,
    claims: CapabilityClaims,
  ): Promise<ControlOk<{ cron: Cron }> | ControlErr<"not_found" | "forbidden">>;
  getCronRuns(
    id: string,
    req: CronRunsRequest,
    claims: CapabilityClaims,
  ): Promise<ControlOk<CronRunsResult> | ControlErr<"not_found" | "forbidden" | "bad_request">>;
  patchCron(
    id: string,
    req: CronPatchRequest,
    claims: CapabilityClaims,
  ): Promise<ControlOk<{ cron: Cron }> | ControlErr<"not_found" | "forbidden" | "bad_request" | "cron_update_failed">>;
  noteCron(
    id: string,
    text: string,
    claims: CapabilityClaims,
  ): Promise<ControlOk<{ applied: boolean }> | ControlErr<"not_found" | "forbidden" | "bad_request">>;
  deleteCron(
    id: string,
    claims: CapabilityClaims,
  ): Promise<ControlOk<Record<never, never>> | ControlErr<"not_found" | "forbidden">>;
  setCronEnabled(
    id: string,
    enabled: boolean,
    claims: CapabilityClaims,
  ): Promise<ControlOk<{ cron: Cron }> | ControlErr<"not_found" | "forbidden">>;
  runCron(
    id: string,
    claims: CapabilityClaims,
  ): Promise<
    | ControlOk<{ fireKey: string }>
    | ControlErr<"not_found" | "forbidden" | "unavailable" | "bad_request" | "already_running">
  >;
  retargetCron(
    id: string,
    destinationKey: string,
    claims: CapabilityClaims,
  ): Promise<ControlOk<{ cron: Cron }> | ControlErr<"not_found" | "forbidden" | "unknown_destination">>;
  createWebhook(
    req: WebhookCreateRequest,
    claims: CapabilityClaims,
    publicBase: string | undefined,
  ): Promise<WebhookCreateResult>;
  listWebhooks(claims: CapabilityClaims): Promise<Webhook[]>;
  disableWebhook(
    id: string,
    claims: CapabilityClaims,
  ): Promise<ControlOk<Record<never, never>> | ControlErr<"not_found" | "forbidden">>;
  updateWebhook(
    id: string,
    patch: { action: string },
    claims: CapabilityClaims,
  ): Promise<ControlOk<{ webhook: Webhook }> | ControlErr<"not_found" | "forbidden" | "bad_request">>;
  readSoul(claims: CapabilityClaims): { effectiveSoul: string; soul: string | null; soulVersion: number };
  writeSoul(
    content: string,
    claims: CapabilityClaims,
    expectedVersion?: number,
  ): Promise<ControlOk<{ version: number }> | ControlErr<SoulWriteFailureCode>>;
  shareArtifact(req: ShareArtifactRequest, claims: CapabilityClaims): Promise<ShareArtifactResult>;
}

type SoulWriteFailureCode = "soul_update_denied" | "soul_version_conflict" | "soul_update_failed";

function soulWriteFailureCode(e: unknown): SoulWriteFailureCode {
  if (e instanceof SoulUpdateDeniedError) return "soul_update_denied";
  if (e instanceof SoulVersionConflictError) return "soul_version_conflict";
  return "soul_update_failed";
}

async function ownsCron(
  app: Pick<App, "samePerson" | "isCurrentSharedScopeMember" | "membershipControlsScope" | "managesScope">,
  cron: Cron,
  actorId: string,
  isActor?: (id: string) => Promise<boolean>,
): Promise<boolean> {
  if (actsAsScope(cron.owner, cron.ownerScopeId)) return app.isCurrentSharedScopeMember(actorId, cron.ownerScopeId);
  if (!(await (isActor ? isActor(cron.owner) : app.samePerson(cron.owner, actorId)))) return false;
  return !(await app.membershipControlsScope(cron.ownerScopeId)) || app.managesScope(actorId, cron.ownerScopeId);
}

export async function canAdministerCron(
  app: Pick<
    App,
    "samePerson" | "isCurrentSharedScopeMember" | "artifactGrantPermission" | "membershipControlsScope" | "managesScope"
  >,
  cron: Cron,
  actorId: string,
  isActor?: (id: string) => Promise<boolean>,
): Promise<boolean> {
  if (await ownsCron(app, cron, actorId, isActor)) return true;
  if (actsAsScope(cron.owner, cron.ownerScopeId) || cron.ownerScopeId.startsWith("personal:")) return false;
  return (await app.artifactGrantPermission(cron.ownerScopeId, encodeRef(cronRef(cron.id)), actorId)) === "write";
}

export async function editWebhookTask(
  app: App,
  id: string,
  action: string,
  principalId: string,
): Promise<ControlOk<{ webhook: Webhook }> | ControlErr<"not_found" | "forbidden" | "bad_request">> {
  if (!action.trim()) return { ok: false, code: "bad_request", message: "task cannot be empty" };
  const webhook = await app.getWebhook(id);
  if (!webhook) return { ok: false, code: "not_found", message: `no webhook ${id}` };
  if (!(await canAdministerWebhook(app, webhook, principalId)))
    return { ok: false, code: "forbidden", message: "not your webhook" };
  const updated = await app.updateWebhook(id, { action });
  return updated ? { ok: true, webhook: updated } : { ok: false, code: "not_found", message: `no webhook ${id}` };
}

export async function canAdministerWebhook(
  app: Pick<App, "membershipControlsScope" | "managesScope" | "samePerson">,
  webhook: Pick<Webhook, "ownerScopeId" | "owner">,
  actorId: string,
  isActor?: (id: string) => Promise<boolean>,
): Promise<boolean> {
  if (await app.membershipControlsScope(webhook.ownerScopeId)) {
    return app.managesScope(actorId, webhook.ownerScopeId);
  }
  return isActor ? isActor(webhook.owner) : app.samePerson(webhook.owner, actorId);
}

function withDefaultTimezone(schedule: CronSchedule, cap: CapabilityClaims): CronSchedule {
  if (schedule.cron === undefined || schedule.timezone !== undefined) return schedule;
  const tz = typeof cap.timezone === "string" && cap.timezone.trim() ? cap.timezone : DEFAULT_CRON_TIMEZONE;
  return { ...schedule, timezone: tz };
}

function hasCronPatchField(req: CronPatchRequest): boolean {
  return (
    req.runtime !== undefined ||
    req.title !== undefined ||
    req.action !== undefined ||
    req.text !== undefined ||
    req.schedule !== undefined ||
    req.enabled !== undefined ||
    req.archived !== undefined ||
    req.unfurlLinks !== undefined ||
    req.unattendedGrants !== undefined ||
    req.session !== undefined
  );
}

function liveSessionRef(
  capability: Pick<CapabilityClaims, "threadRef" | "triggered" | "scopeId">,
  cronScopeId: string,
): string | undefined {
  return capability.triggered || capability.scopeId !== cronScopeId ? undefined : capability.threadRef;
}

function cronPatchChanges(before: Cron, patch: CronPatch): boolean {
  return (Object.entries(patch) as Array<[keyof CronPatch, unknown]>).some(
    ([key, value]) => !isDeepStrictEqual(before[key as keyof Cron], value),
  );
}

function patchFromCronPatchRequest(
  before: Cron,
  req: CronPatchRequest,
  capability: CapabilityClaims,
): CronPatch | ControlErr<"bad_request"> {
  if (!hasCronPatchField(req)) {
    return {
      ok: false,
      code: "bad_request",
      message: CRON_PATCH_NOTHING_TO_CHANGE,
    };
  }
  if (req.unfurlLinks !== undefined && !before.destination) {
    return {
      ok: false,
      code: "bad_request",
      message: "unfurlLinks can only be set on a cron with a delivery destination",
    };
  }
  const sessionRef = req.session ? liveSessionRef(capability, before.ownerScopeId) : undefined;
  if (req.session && !sessionRef) {
    return {
      ok: false,
      code: "bad_request",
      message: "session:true needs a live conversation in the cron's own scope to tie it to",
    };
  }
  return {
    ...(req.session !== undefined && sessionRef !== before.sessionRef ? { sessionRef: sessionRef ?? null } : {}),
    ...(req.runtime !== undefined ? { runtime: req.runtime } : {}),
    ...(req.title !== undefined ? { title: req.title } : {}),
    ...(req.action !== undefined ? { action: req.action } : {}),
    ...(req.text !== undefined ? { message: req.text } : {}),
    ...(req.schedule !== undefined ? { schedule: withDefaultTimezone(req.schedule, capability) } : {}),
    ...(req.enabled !== undefined ? { enabled: req.enabled } : {}),
    ...(req.archived !== undefined ? { archived: req.archived } : {}),
    ...(req.unfurlLinks !== undefined && before.destination
      ? { destination: withSlackUnfurlOption(before.destination, req.unfurlLinks) }
      : {}),
  };
}

export const UNATTENDED_ADMIN_GRANTS = [
  "admin.sessions.read",
  "admin.audit.read",
  "admin.egress.read",
  "admin.files.read",
  "admin.spend.read",
  "admin.crons.read",
] as const;

function validateUnattendedGrants(grants: string[]): string | null {
  if (!grants.every((grant) => (UNATTENDED_ADMIN_GRANTS as readonly string[]).includes(grant)))
    return "unknown unattended grant";
  return null;
}

export function createControlService(app: App, scheduler?: Scheduler, admin?: AdminService): ControlService {
  const notifyEdit = (
    cron: Cron,
    cap: CapabilityClaims,
    changeSummary: string[],
    detail?: CronEditDetail,
  ): Promise<void> =>
    notifyOwnerOfCronEdit(app, {
      cron,
      editorId: cap.actorId,
      changeSummary,
      ...(detail ? { detail } : {}),
    });
  return {
    async createCron(req, capability): Promise<CronCreateResult> {
      if (req.unattendedGrants !== undefined) {
        const invalid = validateUnattendedGrants(req.unattendedGrants);
        if (invalid) return { ok: false, code: "bad_request", message: invalid };
      }
      if (req.action === undefined && req.text === undefined) {
        return { ok: false, code: "bad_request", message: "task (what to do) or text (exact text to send) required" };
      }
      const hasParticipants = Array.isArray(req.participants);
      const wantsGroup = hasParticipants && req.participants!.length > 0;
      const wantsPersonal = req.scope === "personal";
      if (
        [req.recipient !== undefined, req.channel !== undefined, wantsGroup, wantsPersonal].filter(Boolean).length > 1
      ) {
        return {
          ok: false,
          code: "bad_request",
          message:
            'specify at most one of scope:"personal", recipient (a teammate), channel, or participants (a group DM)',
        };
      }
      if (wantsPersonal && req.destinationKey !== undefined) {
        return {
          ok: false,
          code: "bad_request",
          message: 'scope:"personal" runs at your own scope — it can\'t also take a destinationKey',
        };
      }

      let destination: Destination | undefined;
      let ownerScopeId = capability.scopeId;
      let resolvedRecipient: { principalId: string; displayName: string } | undefined;
      let resolvedChannel: { channelId: string; name: string } | undefined;
      let resolvedGroup: { groupId: string } | undefined;

      if (wantsPersonal) {
        destination = principalDestination(capability.actorId, capability.actorId);
        ownerScopeId = destination.audienceScopeId ?? ownerScopeId;
      } else if (req.recipient !== undefined || req.channel !== undefined || hasParticipants) {
        const r = await app.resolveReachTarget(
          {
            ...(req.recipient !== undefined ? { recipient: req.recipient } : {}),
            ...(req.channel !== undefined ? { channel: req.channel } : {}),
            ...(hasParticipants ? { participants: req.participants } : {}),
          },
          capability.actorId,
        );
        if (!r.ok) {
          let code:
            | "bad_request"
            | "recipient_not_found"
            | "ambiguous_recipient"
            | "channel_not_found"
            | "ambiguous_channel"
            | "group_not_found"
            | "not_a_member"
            | "identity_unverified" = "bad_request";
          const RESOLVER_CODES = new Set(["recipient_not_found", "ambiguous_recipient", "group_not_found"]);
          if (RESOLVER_CODES.has(r.error)) {
            code = r.error as typeof code;
          } else if (r.status === 404) {
            if (req.recipient !== undefined) code = "recipient_not_found";
            else code = wantsGroup ? "group_not_found" : "channel_not_found";
          } else if (r.status === 409) {
            code = req.recipient !== undefined ? "ambiguous_recipient" : "ambiguous_channel";
          } else if (r.status === 403) {
            code = r.error === "identity_unverified" ? "identity_unverified" : "not_a_member";
          }
          return {
            ok: false,
            code,
            message:
              r.error === "not_a_member" && req.channel !== undefined
                ? "I can only schedule posts to a private channel you're in"
                : r.message,
            ...(r.candidates
              ? {
                  candidates: r.candidates.map((c) => ({
                    id: c.principalId ?? c.channelId ?? "",
                    label: c.displayName ?? c.name ?? "",
                  })),
                }
              : {}),
          };
        }
        destination = r.destination;
        if (r.recipient) resolvedRecipient = r.recipient;
        if (r.channel) {
          resolvedChannel = r.channel;
          ownerScopeId = r.destination.audienceScopeId ?? ownerScopeId;
        }
        if (r.group) {
          resolvedGroup = r.group;
          ownerScopeId = r.destination.audienceScopeId ?? ownerScopeId;
        }
      } else {
        const resolved = resolveCapabilityDestination(capability, req.destinationKey);
        if (!resolved.ok) {
          return {
            ok: false,
            code: "unknown_destination",
            message: "destinationKey is not one of the destinations available for this conversation",
          };
        }
        destination = resolved.destination;
      }

      if (req.unattendedGrants?.length) {
        const refusal = await unattendedGrantRefusal(
          app,
          admin,
          { owner: capability.actorId, ownerScopeId, ...(destination ? { destination } : {}) },
          capability,
        );
        if (refusal) return { ok: false, ...refusal };
      }

      if (req.unfurlLinks !== undefined && !destination) {
        return {
          ok: false,
          code: "bad_request",
          message: "unfurlLinks can only be set on a cron with a delivery destination",
        };
      }
      if (destination) destination = withSlackUnfurlOption(destination, req.unfurlLinks);

      const input: CreateCronInput = {
        schedule: withDefaultTimezone(req.schedule, capability),
        ...(req.runtime !== undefined ? { runtime: req.runtime } : {}),
        ...(req.action !== undefined ? { action: req.action } : {}),
        ...(req.text !== undefined ? { message: req.text } : {}),
        owner: capability.actorId,
        createdBy: capability.actorId,
        ownerScopeId,
        ...(typeof req.title === "string" ? { title: req.title } : {}),
        ...(destination ? { destination } : {}),
        ...(req.unattendedGrants !== undefined ? { unattendedGrants: req.unattendedGrants } : {}),
      };
      const sessionRef = req.session === false ? undefined : liveSessionRef(capability, ownerScopeId);
      if (sessionRef) input.sessionRef = sessionRef;
      try {
        const cron = await app.createCron(input);
        return {
          ok: true,
          cron,
          ...(resolvedRecipient ? { recipient: resolvedRecipient } : {}),
          ...(resolvedChannel ? { channel: resolvedChannel } : {}),
          ...(resolvedGroup ? { group: resolvedGroup } : {}),
        };
      } catch (e) {
        return { ok: false, code: "cron_create_failed", message: errMessage(e) };
      }
    },

    async listCrons(capability) {
      const { visible } = await app.listCronsForViewer(capability.actorId);
      const all = await app.listCrons();
      const isActor = await app.personMatcher(capability.actorId);
      const admits = await Promise.all(all.map((c) => canAdministerCron(app, c, capability.actorId, isActor)));
      const administered = all.filter((_, i) => admits[i]);
      const ids = new Set(administered.map((c) => c.id));
      return { crons: administered, visible: visible.filter((c) => !ids.has(c.id)) };
    },

    async getCron(id, capability) {
      const cron = await app.getCron(id);
      if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (await canAdministerCron(app, cron, capability.actorId)) return { ok: true, cron };
      const { visible } = await app.listCronsForViewer(capability.actorId);
      if (visible.some((c) => c.id === id)) return { ok: true, cron };
      return { ok: false, code: "forbidden", message: "not your cron" };
    },

    async getCronRuns(id, req, capability) {
      const cron = await app.getCron(id);
      if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (!(await canAdministerCron(app, cron, capability.actorId)))
        return { ok: false, code: "forbidden", message: "not your cron" };
      if (req.limit !== undefined && (!Number.isInteger(req.limit) || req.limit < 1)) {
        return { ok: false, code: "bad_request", message: "limit must be a positive integer" };
      }
      const { runs, total } = await app.listCronFires(id, req.limit !== undefined ? { limit: req.limit } : {});
      return { ok: true, cron, runs, total };
    },

    async patchCron(id, req, capability) {
      const before = await app.getCron(id);
      if (!before) return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (!(await canAdministerCron(app, before, capability.actorId)))
        return { ok: false, code: "forbidden", message: "not your cron" };
      if (req.unattendedGrants !== undefined) {
        const invalid = validateUnattendedGrants(req.unattendedGrants);
        if (invalid) return { ok: false, code: "bad_request", message: invalid };
      }
      const patch = patchFromCronPatchRequest(before, req, capability);
      if ("ok" in patch) return patch;
      if (req.unattendedGrants !== undefined) patch.unattendedGrants = req.unattendedGrants;
      else if ((before.unattendedGrants?.length ?? 0) > 0) patch.unattendedGrants = before.unattendedGrants;
      if (!cronPatchChanges(before, patch)) return { ok: true, cron: before };
      if ((patch.unattendedGrants?.length ?? 0) > 0) {
        const refusal = await unattendedGrantRefusal(app, admin, before, capability);
        if (refusal) return { ok: false, ...refusal };
      }
      try {
        const cron = await app.updateCron(id, patch);
        if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
        const changeSummary: string[] = [];
        if (req.runtime !== undefined) changeSummary.push("runtime");
        if (req.title !== undefined) changeSummary.push("title");
        if (req.action !== undefined || req.text !== undefined) changeSummary.push("task");
        if (req.schedule !== undefined) changeSummary.push("schedule");
        if (req.enabled !== undefined) changeSummary.push(`enabled=${req.enabled}`);
        if (req.archived !== undefined) changeSummary.push(`archived=${req.archived}`);
        if (req.unfurlLinks !== undefined) changeSummary.push(`unfurlLinks=${req.unfurlLinks}`);
        if (req.session !== undefined)
          changeSummary.push(req.session ? "tied to a session" : "untied from its session");
        const detail: CronEditDetail =
          req.schedule !== undefined ? { schedule: withDefaultTimezone(req.schedule, capability) } : {};
        await notifyEdit(cron, capability, changeSummary, detail);
        return { ok: true, cron };
      } catch (e) {
        return { ok: false, code: "cron_update_failed", message: errMessage(e) };
      }
    },

    async noteCron(id, text, capability) {
      const flattened = flattenFireNote(text);
      if (!flattened)
        return { ok: false, code: "bad_request", message: "the note is empty — say what the next fire should know" };
      const length = [...flattened].length;
      if (length > CRON_FIRE_NOTE_MAX_CHARS) {
        return {
          ok: false,
          code: "bad_request",
          message: `the note is ${length} chars — the cap is ${CRON_FIRE_NOTE_MAX_CHARS}. Trim it to the outcome plus what the next fire must know; publish longer state to this conversation's Files via the available Files API, verify success, and put the file ID in the note for GET /v1/files/:id/content. If publication is unavailable, report it and retain needed local state on a scoped computer.`,
        };
      }
      if (echoesCronContextMarkers(flattened)) {
        return {
          ok: false,
          code: "bad_request",
          message: "the note can't include the cron runtime context markers — write a plain report instead",
        };
      }
      const cron = await app.getCron(id);
      if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (!(await canAdministerCron(app, cron, capability.actorId)))
        return { ok: false, code: "forbidden", message: "not your cron" };
      if (cron.archived) {
        return {
          ok: false,
          code: "bad_request",
          message: `cron ${id} is archived — its fires won't run, so a note would never be read`,
        };
      }
      if (!cronFireReadsNotes(cron)) {
        return {
          ok: false,
          code: "bad_request",
          message: `cron ${id}'s fires don't read shift-change notes (it is loop-backed, one-shot, or runs a raw !run/!scratch task) — publish durable handoff state to this conversation's Files via the available Files API and verify success. Keep the published file ID in the consuming workflow for GET /v1/files/:id/content; these fires cannot recover it from a note. If publication is unavailable, report it and retain needed local state on a scoped computer.`,
        };
      }
      const ownFire = capability.threadRef?.startsWith(`cron:${id}:fire:`) === true;
      if (!ownFire && (cron.unattendedGrants?.length ?? 0) > 0) {
        const refusal = await unattendedGrantRefusal(app, admin, cron, capability);
        if (refusal) return { ok: false, code: "forbidden", message: refusal.message };
      }
      const fireEntry = ownFire ? await app.latestCronFireForThread(id, capability.threadRef!) : undefined;
      const outcome = await app.setCronFireNote(id, {
        text: flattened,
        at: fireEntry?.firedAt ?? Date.now(),
        ...(ownFire ? {} : { by: capability.actorId }),
      });
      if (outcome === "missing") return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (outcome === "applied" && !ownFire) await notifyEdit(cron, capability, ["note"]);
      return { ok: true, applied: outcome === "applied" };
    },

    async deleteCron(id, capability) {
      const cron = await app.getCron(id);
      if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (!(await canAdministerCron(app, cron, capability.actorId)))
        return { ok: false, code: "forbidden", message: "not your cron" };
      await app.deleteCron(id);
      await notifyEdit(cron, capability, ["deleted"]);
      return { ok: true };
    },

    async setCronEnabled(id, enabled, capability) {
      const cron = await app.getCron(id);
      if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (!(await canAdministerCron(app, cron, capability.actorId)))
        return { ok: false, code: "forbidden", message: "not your cron" };
      if (enabled && (cron.unattendedGrants?.length ?? 0) > 0) {
        const refusal = await unattendedGrantRefusal(app, admin, cron, capability);
        if (refusal) return { ok: false, code: "forbidden", message: refusal.message };
      }
      if (cron.enabled === enabled) return { ok: true, cron };
      await app.setCronEnabled(id, enabled);
      await notifyEdit(cron, capability, [`enabled=${enabled}`]);
      const after = await app.getCron(id);
      return { ok: true, cron: after ?? cron };
    },

    async runCron(id, capability) {
      const cron = await app.getCron(id);
      if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (!(await canAdministerCron(app, cron, capability.actorId)))
        return { ok: false, code: "forbidden", message: "not your cron" };
      if ((cron.unattendedGrants?.length ?? 0) > 0) {
        const refusal = await unattendedGrantRefusal(app, admin, cron, capability);
        if (refusal) return { ok: false, code: "forbidden", message: refusal.message };
      }
      if (!scheduler)
        return {
          ok: false,
          code: "unavailable",
          message: "the scheduler isn't running here, so a cron can't be fired on demand",
        };
      if (cron.archived || !cron.enabled)
        return {
          ok: false,
          code: "bad_request",
          message: `cron ${id} is ${cron.archived ? "archived" : "paused"} — enable it before firing it on demand`,
        };
      const result = await scheduler.runNow(id);
      if (!result.started) {
        const refusal = describeRunNowRefusal(id, result)!;
        return { ok: false, code: refusal.error, message: refusal.message };
      }
      return { ok: true, fireKey: result.fireKey };
    },

    async retargetCron(id, destinationKey, capability) {
      const cron = await app.getCron(id);
      if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
      if (!(await canAdministerCron(app, cron, capability.actorId)))
        return { ok: false, code: "forbidden", message: "not your cron" };
      const resolved = resolveCapabilityDestination(capability, destinationKey);
      if (!resolved.ok) {
        return {
          ok: false,
          code: "unknown_destination",
          message: "destinationKey is not one of the destinations available for this conversation",
        };
      }
      if ((cron.unattendedGrants?.length ?? 0) > 0) {
        const refusal = await unattendedGrantRefusal(
          app,
          admin,
          { ...cron, destination: resolved.destination },
          capability,
        );
        if (refusal) return { ok: false, code: "forbidden", message: refusal.message };
      }
      if (isDeepStrictEqual(cron.destination, resolved.destination)) return { ok: true, cron };
      const updated = await app.setCronDestination(id, resolved.destination);
      const destLabel = capability.destinations?.find((d) => d.key === destinationKey)?.label;
      await notifyEdit(cron, capability, ["destination"], destLabel ? { destinationLabel: destLabel } : undefined);
      return { ok: true, cron: updated ?? cron };
    },

    async createWebhook(req, capability, publicBase): Promise<WebhookCreateResult> {
      if (capability.triggered || !livePersonCapability(capability)) {
        return {
          ok: false,
          code: "forbidden",
          message: "webhook registration requires a live turn started by its owner",
        };
      }
      const resolved = resolveCapabilityDestination(capability, req.destinationKey);
      if (!resolved.ok) {
        return {
          ok: false,
          code: "unknown_destination",
          message: "destinationKey is not one of the destinations available for this conversation",
        };
      }
      const input: CreateWebhookInput = {
        action: req.action,
        verification: req.verification,
        owner: capability.actorId,
        createdBy: capability.actorId,
        ownerScopeId: capability.scopeId,
        ...(req.filters?.length ? { filters: req.filters } : {}),
        ...(resolved.destination ? { destination: resolved.destination } : {}),
      };
      try {
        const webhook = await app.createWebhook(input);
        const incomingPath = `/v1/webhooks/incoming/${webhook.id}`;
        const base = publicBase ? publicBase.replace(/\/$/, "") : "";
        return {
          ok: true,
          webhook,
          url: base ? `${base}${incomingPath}` : incomingPath,
          ...(webhook.verification.secret ? { secret: webhook.verification.secret } : {}),
        };
      } catch (e) {
        return { ok: false, code: "webhook_create_failed", message: errMessage(e) };
      }
    },

    async listWebhooks(capability) {
      const all = await app.listWebhooks();
      const isActor = await app.personMatcher(capability.actorId);
      const allowed = await Promise.all(
        all.map((webhook) => canAdministerWebhook(app, webhook, capability.actorId, isActor)),
      );
      return all.filter((_webhook, index) => allowed[index]);
    },

    async disableWebhook(id, capability) {
      const webhook = await app.getWebhook(id);
      if (!webhook) return { ok: false, code: "not_found", message: `no webhook ${id}` };
      if (!(await canAdministerWebhook(app, webhook, capability.actorId)))
        return { ok: false, code: "forbidden", message: "not your webhook" };
      await app.setWebhookEnabled(id, false);
      return { ok: true };
    },

    async updateWebhook(id, patch, capability) {
      if (capability.triggered || !livePersonCapability(capability))
        return { ok: false, code: "forbidden", message: "editing a webhook requires a live turn started by its owner" };
      return editWebhookTask(app, id, patch.action, capability.actorId);
    },

    readSoul(capability) {
      const { effectiveSoul, soul, soulVersion } = app.getSoul(capability.scopeId);
      return { effectiveSoul, soul, soulVersion };
    },

    async writeSoul(content, capability, expectedVersion) {
      try {
        const version = await app.updateSoul(capability.scopeId, content, capability.actorId, {
          allowSharedScope: true,
          expectedVersion,
        });
        return { ok: true, version };
      } catch (e) {
        return {
          ok: false,
          code: soulWriteFailureCode(e),
          message: errMessage(e),
        };
      }
    },

    async shareArtifact(req, capability): Promise<ShareArtifactResult> {
      const permission: Permission = req.permission === "write" ? "write" : "read";
      const home = await app.getArtifactHome(req.type, req.id);
      if (!home)
        return {
          ok: false,
          code: "not_found",
          message:
            req.type === "file"
              ? `no Files record "${req.id}"; put the file in Files first using POST /v1/files/uploads, then share its ID`
              : `no ${req.type} "${req.id}"`,
        };

      const target = await resolveArtifactTarget(app, req);
      if (target.kind === "invalid") return { ok: false, code: "bad_request", message: target.message };
      if (target.kind === "none")
        return { ok: false, code: "recipient_not_found", message: `no teammate matches "${String(req.recipient)}"` };
      if (target.kind === "ambiguous")
        return {
          ok: false,
          code: "ambiguous_recipient",
          message: "more than one teammate matches",
          candidates: target.candidates,
        };
      const toScope = target.scope;
      const toKind = parseScopeId(toScope).kind;

      const isOrg = toKind === "org";
      const orgSkillCede = isOrg && req.type === "skill";

      const cron = req.type === "cron" ? await app.getCron(home.id) : null;
      if (cron && permission === "write" && cron.ownerScopeId.startsWith("personal:"))
        return {
          ok: false,
          code: "bad_request",
          message: "a personal cron runs with your whole keychain, so it can't be shared for editing",
        };
      if (
        !orgSkillCede &&
        !(cron
          ? await ownsCron(app, cron, capability.actorId)
          : await app.canManageArtifactHome(home.ownerScopeId, home.createdBy, capability.actorId))
      ) {
        return {
          ok: false,
          code: "forbidden",
          message: cron
            ? "only the cron's owner can share it"
            : `only the ${req.type}'s owner (or a member of its shared home) can share or move it`,
        };
      }
      if (
        (toKind === "channel" || toKind === "group" || toKind === "team") &&
        !(await app.belongsToScope(capability.actorId, toScope))
      ) {
        return {
          ok: false,
          code: "forbidden",
          message: `you can't ${req.move ? "move" : "share"} into ${target.label} — you're not a member of that context`,
        };
      }

      try {
        if (orgSkillCede) {
          const promoted = await app.promoteSkill(home.id, toScope, capability.actorId, capability.liveActor === true);
          return {
            ok: true,
            verb: "promote",
            type: req.type,
            id: promoted.id,
            target: { scope: toScope, label: target.label },
            permission,
          };
        }

        if (req.move) {
          const deployPersonTransfer = req.type === "deploy" && toKind === "personal" && capability.liveActor === true;
          if (!deployPersonTransfer && !(await app.belongsToScope(capability.actorId, toScope))) {
            return {
              ok: false,
              code: "forbidden",
              message: `you can only move a ${req.type} into a context you belong to — to give it to a teammate, share it (a grant) instead`,
            };
          }
          if (
            req.type === "skill" &&
            !livePersonCapability(capability) &&
            (isMultiMemberSkillScope(home.ownerScopeId) || isMultiMemberSkillScope(toScope))
          ) {
            return { ok: false, code: "forbidden", message: SHARED_SKILL_TRIGGER_REFUSAL };
          }
          await app.moveArtifactHome(req.type, home.id, toScope, capability.actorId);
          return {
            ok: true,
            verb: "move",
            type: req.type,
            id: home.id,
            target: { scope: toScope, label: target.label },
            permission,
          };
        }

        const invite =
          req.type === "deploy" && req.email !== undefined && permission === "read"
            ? await app.inviteToDeployment(home.id, req.email, capability.actorId)
            : undefined;
        if (!invite)
          await app.grant({
            ownerScopeId: home.ownerScopeId,
            ref: home.grantRef,
            granteeScopeId: toScope,
            permission,
            grantedBy: capability.actorId,
          });
        return {
          ok: true,
          verb: "share",
          ...(invite ? { invitation: invite.invitation } : {}),
          type: req.type,
          id: home.id,
          target: { scope: toScope, label: target.label },
          permission,
        };
      } catch (e) {
        if (e instanceof AdminError) {
          return { ok: false, code: "forbidden", message: errMessage(e) };
        }
        return { ok: false, code: "share_failed", message: errMessage(e) };
      }
    },
  };
}

type ArtifactTarget =
  | { kind: "ok"; scope: ScopeId; label: string }
  | { kind: "none" }
  | { kind: "ambiguous"; candidates: Array<{ id: string; label: string }> }
  | { kind: "invalid"; message: string };

async function resolveArtifactTarget(app: App, req: ShareArtifactRequest): Promise<ArtifactTarget> {
  const r = await resolveShareTarget(
    app,
    { scope: req.scope, recipient: req.recipient, email: req.email },
    {
      allowEmail: req.type === "deploy" && !req.move,
      invalidScope: (scope) => `invalid scope "${scope}" — use "org" or a scope id like personal:<id> or channel:<id>`,
      targetRequired: 'a target is required: pass `toScope` ("org", a scope id, or a teammate\'s name)',
    },
  );
  return r.kind === "ambiguous"
    ? { kind: "ambiguous", candidates: r.candidates.map((c) => ({ id: c.principalId, label: c.displayName })) }
    : r;
}