iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / lib / src / api.tsmain at 949894f

// api.ts — THE API AN APP DIALS: the shapes of a mind's `/api` session and a context's surface, as
// a capnweb client sees them. DECLARED here, never generated, and never the platform's classes:
// core/itx serves a context as `IterateContextRpcTarget` (core/itx/src/iterate-context.ts, served
// by core/itx/src/session.ts), so an app built against this package types against what the
// deployment answers. A context
// has ONE method — `invoke(call, ...args)`, a dotted itx expression — and a capnweb stub proxies the
// dotted spelling (`itx.repos.get(path).readFile(file)`) onto it. THIS FILE IS THE SOURCE OF TRUTH
// for every root app code reaches: core/itx derives its built-in record's type from these members
// (core/itx/src/context/built-ins.ts `BuiltInScope`), so a root or a verb the platform
// implements and this file does not declare — or declares differently — fails to typecheck there.
// The roots installed apps add are NOT here: each app registers its own on `InstalledAppRoots` from
// its package, and `IterateContextApiWith` spells a context that has them.

import type {
  Ai,
  AiGatewayLog,
  AiGatewayPatchLog,
  AIGatewayUniversalRequest,
  AiWebSearchRequest,
  ConversionRequestOptions,
  ConversionResponse,
  ImageDrawOptions,
  ImageInfoResponse,
  ImageInputOptions,
  ImageOutputOptions,
  ImageTransform,
  ImageTransformationOutputOptions,
  ImageTransformationResponseOptions,
  R2HTTPMetadata,
  R2Range,
  SupportedFileFormat,
  TextOptions,
  UniversalGatewayOptions,
} from "@cloudflare/workers-types";
import type { InvokeHandle, ItxExpression, ItxExpressionInput } from "./expression.ts";
import type { ActRule } from "./acts.ts";
import type { Principal } from "./principal.ts";
import type { Envelope } from "./signed.ts";
import type { StreamEvent, StreamEventInput } from "./stream/processor.ts";

/** One page of a context's durable log (`readEvents`). */
export interface StreamPage {
  events: StreamEvent[];
  scannedThroughOffset: number;
  /** True iff the scan reached the durable mark: nothing more to read until the next commit. */
  atHead: boolean;
  /** The context's version and the offset of that version's `itx/created`, from the second
   *  version on (`newVersion`); absent in a first version. A reader that holds one version of a
   *  log reads nothing below the offset. */
  version?: number;
  versionStartedAtOffset?: number;
}

/** `waitForEvent`'s filter: an event type (or one of a list), payload fields the event must carry
 *  with exactly these values (each a JSON primitive, compared with `===`), a floor, a timeout. With
 *  an explicit `afterOffset` the log after it is searched first. Large searches yield between
 *  pages; an older historical match takes precedence if found before the search deadline. */
export type WaitForEventFilter = {
  type?: string | string[];
  payload?: Record<string, string | number | boolean | null>;
  afterOffset?: number;
  /** The time budget for the historical search and subsequent wait. A live match received within
   *  the budget is kept if the historical search reaches its deadline. */
  timeoutMs?: number;
};

/** The `rewrite-rule-configured` event's payload — what `itx.append` writes durably and `provide`
 *  writes for its session: make `match` mean `target` (an expression, or `null` to deny). `description` is the one
 *  line a model reads for the name; it rides the row into `rewriteRules.list()`. */
export type RewriteRuleConfigured = {
  match: ItxExpressionInput;
  target: ItxExpressionInput | null;
  /** What the name means here, in one line (≤ 500 chars). */
  description?: string;
  /** On the rule of a lent stub, the grant of the session that lends it: a key's is `key:<id>`, a
   *  member's is the grant of their sign-in. `provide` sets it, and it rides the row into
   *  `rewriteRules.list()`. A lend by a caller with no grant has none. */
  lentBy?: string;
};

/** One row of `rewriteRules.list()` — the tree a context can spell. `context` is the path the row
 *  was read from: this context for its own rows and its implicit rows, the target context for the
 *  rows a bare hop row (`itx ⇒ itx.builtins.cd(path)`) reaches. A mask lists as `target: null`. */
export type RewriteRuleListEntry = {
  match: string;
  target: string | null;
  description?: string;
  /** Who lent the row's stub (`RewriteRuleConfigured.lentBy`). */
  lentBy?: string;
  context: string;
};

/** One row of `subscriptions.list()` / `processors.list()`. */
export type SubscriptionListEntry = {
  name: string;
  target: string;
  consumes?: string[];
  configuredAtOffset: number;
  afterOffset?: number;
  /** `false`: a FAN-OUT row — one event per call, in any order, each event retried on its own and
   *  dead-lettered alone (`itx/subscription-delivery-failed`). Its `cursor` is how far it has
   *  admitted events, `pending` how many events wait for a retry, and `paused` whether new events
   *  wait for the receiver (it failed the last few distinct events: one new event is let through at
   *  each rung of the row's own probe). */
  ordered?: false;
  pending?: number;
  paused?: boolean;
  /** Set on a copy row (one subscribed with an `EventCopyTarget`): which events it copies, and the
   *  target as it was written. Its `target` is then `itx.cd(path)`, which only checks that this
   *  context's rules still let it reach `path`. */
  filter?: string;
  copy?: EventCopyTarget;
  /** Set when this row hosts a facet (a processor). `restarts`: how many times the platform failed
   *  the facet at its start and the context restarted it under a fresh loaded identity (a platform
   *  defect the context works around; the count is the cheap way to ask "how often, here"). */
  hostedFacet?: {
    name: string;
    className: string;
    cacheKey?: string;
    mainModule?: string;
    /** The worker's name when the source is one (`FacetSpec`): any other source is not listed. */
    source?: unknown;
    restarts: number;
  };
  /** Set for a row the context delivers at-least-once (an itx expression target; a facet and a lent
   *  stub own their progress): the offset the last acked call confirmed, the retry ladder's attempt
   *  and when the next attempt is due. */
  cursor?: { confirmedOffset: number; attempt: number; nextAttemptAtMs?: number };
  /** Set once delivery exhausted its retries: the offset it stopped after, and why. */
  halted?: { afterOffset: number; attempts: number; error?: string };
  /** Set on a live-callback row (its target is `itx.builtins.rpcStubs.get("subscription:<name>")`):
   *  who lent the callback, by the platform's stamp on the row's event: `source.principal`, else
   *  `source.onBehalfOf.principal` of a person's one-context view (a stamp with neither `run` nor
   *  `call`), with how they came (`via`). Code that ran for someone (a script's run, a facet's
   *  call) names no holder. Never read from the payload. */
  heldBy?: { principal: Principal; via?: { appPage: string } };
};

/** A `subscribe` target that copies each event onto the log of the context at `path`. `type`
 *  replaces the event's type in the copy, and can't be an `itx/*` type, since a copy is never one of
 *  the platform's own events. `payload` is a JSONata expression evaluated against the original
 *  event, and the JSON object it answers is the copy's payload, for example
 *  `{ "title": $substring(payload.title, 0, 120) }`. Without it the copy's payload is empty: name
 *  the fields to keep, or write `payload` to keep them all. Quote keys as in JSON: an unquoted key
 *  is a path into the event. */
export type EventCopyTarget = { path: string; type?: string; payload?: string };

/** A loaded worker's source: its modules, literally, or an itx expression that produces them (then
 *  `cacheKey` names the build, and the caller owns "same key ⇒ same code"). */
export type WorkerSource = Record<string, string> | ItxExpressionInput;

/** What hosts a class as a durable facet — `facets.get(name, spec)`, `processors.enable(name, spec)`.
 *  `source` is the code (its modules, or an expression that produces them under `cacheKey`), or —
 *  an expression with NO `cacheKey` — the NAME of a loaded worker: one that resolves, as a call
 *  would, to `itx.builtins.workers.get(spec)` in the table of the context whose rule it is
 *  (`itx.cd('/').config`, the mind's published config). The facet loads that worker's source,
 *  its producer run with that context's authority. `mainModule` names the module of the source that
 *  exports `className` when it is not the source's entry (`agents.ts` of a config repo whose entry
 *  is `worker.ts`): the facet runs that module's own graph, and — named by the mind's published
 *  config — restarts in place, storage kept, only when that module's identity changes, never onto
 *  an older publication. */
export type FacetSpec = {
  source: WorkerSource;
  cacheKey?: string;
  className: string;
  mainModule?: string;
};

/** What `schedules.set` answers: the definition's identity, to cancel exactly it. */
export type ScheduleReceipt = { key: string; scheduledAtOffset: number };

/** A schedule's key: a string, or a pair that scopes a local key to its owner (a facet instance). */
export type ScheduleKey = string | [string, string];

/** When a schedule fires: at an instant (ISO, with offset), after a delay, or on an interval (at
 *  least a second; missed ticks coalesce). */
export type ScheduleWhen = { at: string } | { afterMs: number } | { everyMs: number };

/** What `schedules.set` takes: the key, when, and the events (one to a hundred) each occurrence
 *  appends — an event's type, payload and metadata only: identity and provenance are the firing's. */
export type ScheduledAppendInput = {
  key: ScheduleKey;
  when: ScheduleWhen;
  events: Pick<StreamEventInput, "type" | "payload" | "metadata">[];
};

/** One live schedule as `schedules.list()` / `get(key)` answer it: the definition (its key
 *  normalized to a string), when it fires next, the offset of the fact that set it, who set it, and
 *  the last failure until it is replaced or cancelled. */
export type ScheduledAppend = {
  key: string;
  when: ScheduleWhen;
  events: Pick<StreamEventInput, "type" | "payload" | "metadata">[];
  nextAt: string;
  scheduledAtOffset: number;
  source?: StreamEventInput["source"];
  failure?: { error: string; offset: number };
};

/** A secret's material: one string (`getSecret("/secrets/<name>")` is the whole value) or a JSON
 *  object whose string fields `getSecret("/secrets/<name>", { field: "a.b" })` picks — the
 *  multidimensional shape a credential exchange needs (`{ username, password, accessToken }`,
 *  `{ clientId, clientSecret, refreshToken, accessToken }`). A string is always the one value: it has
 *  no fields, whether or not it parses as JSON. `getSecret("/secrets/<name>", { appJwt: true })`, in
 *  the Authorization header of a request to https://api.github.com alone, is a GitHub App's JWT
 *  (RS256, ten minutes) made from the material's `appId` and `privateKey` (PEM): the key itself is
 *  not sent. */
export type SecretMaterial = string | Record<string, unknown>;

/** A SECRET THAT GOES BY PROXY holds no value: a request that names it goes, signed by this mind
 *  for `mind` (a control-plane hostname), to `<url>/<target host><path and query>`. THE PROXYING
 *  MIND SEES EVERY REQUEST AND ANSWER OF THIS SECRET. Whoever may `secrets.set` a path can point
 *  it at any https host this way: a jail grants no `set`. No approval rule holds one. */
export type SecretProxy = { mind: string; url: string };

/** How a token endpoint wants the client credential — the RFC 8414 `token_endpoint_auth_methods_supported`
 *  registry values, so a provider's discovery document pastes straight in: `client_secret_basic`
 *  (HTTP Basic — Google, Slack, the petshop; the default), `client_secret_post` (`client_id` +
 *  `client_secret` as form fields — GitHub, Linear), `none` (a public client: `client_id` alone,
 *  PKCE stands in for the secret). RFC 6749 §2.3.1 forbids sending two forms at once. */
export type ClientAuth = "client_secret_basic" | "client_secret_post" | "none";

/** ONE OF AN iterate Cloud's CLIENTS, as a secret names it: `cloud` is the Cloud's name for the
 *  client (`github`, `google`, `slack`, `x`), and `origin` is that Cloud's address, an exact
 *  `https:` origin with no path (`https://cloud.iterate.com`). No config of the stack names a
 *  Cloud: the code that makes the secret does, and the secret keeps the origin from then on.
 *  Everything that the secret later asks of a Cloud (the code's exchange, a refresh, an
 *  installation's token, an ask) goes to that origin and to no other. Another origin is another
 *  secret. */
export type CloudClientName = { cloud: string; origin: string };

/** A grant whose refresh names the stack's own OAuth client at Cloudflare. The stack makes no such
 *  client (a mind connects through Cloudflare's MCP server, as its own client), so such a grant
 *  does not refresh, and a member connects again. */
export type StackClientName = { stack: "cloudflare" };

/** CLOUDFLARE'S OWN OAUTH SERVER, the one behind its dashboard: where a connect through a client
 *  that a member made in the account asks and exchanges, and where its token may go. The default
 *  template connects through Cloudflare's MCP server instead (core/configs/default/cloudflare.ts);
 *  a config of a mind's own that still connects here is held to the vault's own ceiling for
 *  Cloudflare, reads alone, as every connect to Cloudflare is. */
export const CLOUDFLARE_OAUTH = {
  authorizationEndpoint: "https://dash.cloudflare.com/oauth2/auth",
  tokenEndpoint: "https://dash.cloudflare.com/oauth2/token",
  urls: ["https://api.cloudflare.com", "https://mcp.cloudflare.com"],
} as const;

/** WHAT A MIND'S CLOUDFLARE CONNECTION MAY READ: the OAuth scopes that a connect asks for, and
 *  outside which the vault keeps no grant from Cloudflare (`grantedWithin`, and the vault's own
 *  ceiling). The list is every read of Cloudflare's MCP server's "Read only" template
 *  (github.com/cloudflare/mcp at 19f7601: each scope whose last part is `read`, `metadata_read`,
 *  `monitoring` or `report`), so Cloudflare's consent screen shows standard Read-only access rather
 *  than a custom list. No write is in it: Cloudflare refuses every write. The MCP server adds
 *  `user:read`, `account:read` and `offline_access` to every grant; they are no part of the list.
 *  core/lib/src/cloudflare-read-scopes.test.ts holds the list to the rule. */
export const CLOUDFLARE_READ_SCOPES = [
  "access-acct.read",
  "access-app.read",
  "access-audit-log.read",
  "access-certificate.read",
  "access-custom-page.read",
  "access-device-posture.read",
  "access-group.read",
  "access-idp.read",
  "access-key.read",
  "access-org.read",
  "access-policy-test.read",
  "access-policy.read",
  "access-population.read",
  "access-saml-certificate.read",
  "access-scim-log.read",
  "access-service-token.read",
  "access-ssh-auditing.read",
  "access-tag.read",
  "access-users.read",
  "access.read",
  "account-analytics.read",
  "account-api-gateway.read",
  "account-custom-asset.read",
  "account-custom-error-rules.read",
  "account-custom-pages.read",
  "account-disable-esc.read",
  "account-dns-settings.read",
  "account-firewall-access-rules.read",
  "account-logs.read",
  "account-rule-lists.read",
  "account-rulesets.read",
  "account-security-center-insights.read",
  "account-security-center-partner-integrations.read",
  "account-settings.read",
  "account-ssl-and-certificates.read",
  "account-waf.read",
  "account-waiting-rooms.read",
  "address-maps.read",
  "agw.read",
  "ai-model.read",
  "ai-search.metadata_read",
  "ai-search.read",
  "ai.read",
  "aiaudit.read",
  "aig.metadata_read",
  "aig.read",
  "analytics.read",
  "api-gateway.read",
  "argotunnel.read",
  "artifacts.read",
  "bot-management-feedback.read",
  "bot-management.read",
  "browser-rendering.read",
  "cache-settings.read",
  "calls.read",
  "casb.read",
  "cf-agents.read",
  "cfspeed.read",
  "challenge-widgets.read",
  "chinanetwork-steering.read",
  "cloud-connector.read",
  "cloud-email-security.read",
  "cloudchamber.read",
  "cloudforce-one.read",
  "config-settings.read",
  "connectivity-directory.read",
  "constellation.read",
  "containers.read",
  "custom-errors.read",
  "custom-pages.read",
  "cws.read",
  "d1.metadata_read",
  "d1.read",
  "ddos-botnet-feed.read",
  "ddos-protection.read",
  "dls.read",
  "dns-firewall.read",
  "dns-view.read",
  "dns.read",
  "domain-page-shield.read",
  "dynamic-redirect.read",
  "email-routing-account-rule.read",
  "email-routing-address.read",
  "email-routing-rule.read",
  "email-routing-suppression.read",
  "email-security-dmarcreports.read",
  "email-sending.read",
  "fbm.read",
  "field-extractor.read",
  "firewall-for-ai.read",
  "firewall-services.read",
  "flagship.read",
  "fraud-detection-pii.read",
  "fraud-detection.read",
  "fraud-feedback.read",
  "healthcheck.read",
  "http-applications.read",
  "http-ddos-managed-ruleset.read",
  "images.metadata_read",
  "images.read",
  "intel.read",
  "iot.read",
  "ip-prefix-bgp-on-demand.read",
  "ip-prefix.read",
  "k2.read",
  "l4-ddos-managed-ruleset.read",
  "load-balancers-account.read",
  "load-balancers.read",
  "load-balancing-monitors-and-pools.read",
  "logs.read",
  "magic-firewall.read",
  "magic-transit.read",
  "magic-wan.read",
  "managed-headers.read",
  "mass-url-redirects.read",
  "mcp-portals.read",
  "memberships.read",
  "messaging.metadata_read",
  "messaging.read",
  "moq.read",
  "notifications.read",
  "origin.read",
  "page-rules.read",
  "page-shield.read",
  "page.read",
  "pages.metadata_read",
  "payments-gateway.read",
  "pcaps-api.read",
  "pipelines.read",
  "precursor.read",
  "pubsub.read",
  "query-cache.read",
  "queues.metadata_read",
  "queues.read",
  "r2-catalog-sql.read",
  "r2-catalog.read",
  "radar.read",
  "rag.read",
  "realtime.read",
  "registrar-domains.read",
  "registrar-sandbox-domains.read",
  "reports-application-security-report.read",
  "request-tracer.read",
  "resource-library.read",
  "resource-sharing.read",
  "response-compression.read",
  "sanitize.read",
  "secrets-store.read",
  "select-configuration.read",
  "snippets.read",
  "ssl-and-certificates.read",
  "stream.metadata_read",
  "stream.read",
  "tag.read",
  "teams-cds-compute-account.read",
  "teams-connector-cloudflared.monitoring",
  "teams-connector-cloudflared.read",
  "teams-connector-warp.read",
  "teams-connectors.read",
  "teams-dex.read",
  "teams-networks.read",
  "teams-pii.read",
  "teams-resilience.read",
  "teams.read",
  "teams.report",
  "transform-rules.read",
  "trust-and-safety.read",
  "url-scanner.read",
  "user-details.read",
  "vectorize.read",
  "waiting-rooms.read",
  "web3-hostnames.read",
  "websearch.metadata_read",
  "websearch.read",
  "workers-ci.read",
  "workers-kv-storage.metadata_read",
  "workers-kv-storage.read",
  "workers-observability.read",
  "workers-r2-bucket-item.read",
  "workers-r2.metadata_read",
  "workers-r2.read",
  "workers-routes.read",
  "workers-scripts.metadata_read",
  "workers-scripts.read",
  "workers-tail.read",
  "workers_ai.metadata_read",
  "zaraz.read",
  "zone-access.read",
  "zone-custom-asset.read",
  "zone-disable-esc.read",
  "zone-dns-settings.read",
  "zone-observability.read",
  "zone-security-center-insights.read",
  "zone-security-center-partner-assets.read",
  "zone-settings.read",
  "zone-transform-rules.read",
  "zone-versioning.read",
  "zone-waf.read",
  "zone.read",
] as const;

/** Reads excluded from `CLOUDFLARE_READ_SCOPES`: none — `CLOUDFLARE_READ_SCOPES` matches
 *  Cloudflare MCP's full "Read only" template so the consent page shows standard read-only access. */
export const CLOUDFLARE_READS_LEFT_OUT: Record<string, string> = {};

/** How the secret's facet re-mints an expired credential, in its own trusted code: the
 *  exchange reads this secret's own material, POSTs to an endpoint within the pin, and writes the
 *  answer back into the material — `accessToken` (and a rotated `refreshToken`). Triggered on a 401
 *  from the pinned host, and on first use when the placeholder's field is not there yet. An OAuth
 *  token whose endpoint said when it ends (`expires_in`, kept in the material as
 *  `accessTokenExpiresAt`) is also refreshed once that time has come, before the request goes:
 *  not every provider answers an ended token with 401. */
export type SecretRefresh =
  /** RFC 6749 §6, the refresh_token grant: `refreshToken` + `clientId` (+ `clientSecret` for a
   *  confidential client) from the material → `accessToken` (+ the newest `refreshToken`). Google,
   *  GitHub, an MCP server's authorization server, the petshop fixture. With `client`, the client is
   *  the deployment's own app at the provider (an integration connected through it): the material
   *  holds the tokens alone, and the refresh attaches the client's credentials inside the facet. */
  | {
      kind: "oauth-refresh-token";
      tokenEndpoint: string;
      clientAuth?: ClientAuth;
      /** The grant's scope ceiling (`SecretOAuthOptions.grantedWithin`), within the vault's own for
       *  the provider: a refresh whose answer names a scope outside it, or names none, is refused,
       *  and the new tokens are not kept. */
      grantedWithin?: string[];
      /** RFC 8707: the resource the grant is for (an MCP server's URL), as the authorization
       *  request named it in `extra.resource`. Each refresh sends it again: an issuer that serves
       *  more than one resource picks its authorization server by it. */
      resource?: string;
      /** `cloud`: the client is that of the iterate Cloud at `origin`, and `tokenEndpoint` is that
       *  Cloud's broker, which adds the client secret. The refresh token in the material is sealed
       *  for this deployment and means nothing anywhere else. `stack`: the stack's former client
       *  at Cloudflare (`StackClientName`): such a grant no longer refreshes. */
      client?: { platform: IntegrationProvider } | CloudClientName | StackClientName;
    }
  /** A GitHub App installation's token (`POST <apiOrigin>/app/installations/<id>/access_tokens`
   *  with an App JWT) → `accessToken`, minted on first use and on a 401. The App is iterate Cloud's
   *  (`{ cloud, origin }`) or one whose `appId` and `privateKey` the material holds (`{ mind: "github" }`,
   *  and `{ platform: "github" }` the same way); either of those two fields may be a
   *  `getSecret("/secrets/<name>", { field })` placeholder naming another of the owner's secrets
   *  pinned to `apiOrigin`, so one secret holding the App's key serves every installation's
   *  secret. */
  | {
      kind: "github-app-installation";
      apiOrigin: string;
      installationId: string;
      /** `cloud`: the GitHub App of that name of the iterate Cloud at `origin`, whose key stays
       *  at the Cloud. The Cloud mints the token, for an installation this deployment connected.
       *  The Cloud mints no token for a secret whose `urls` go beyond the hosts the Cloud names
       *  for the App. */
      client: { platform: "github" } | { mind: "github" } | CloudClientName;
    }
  /** EXCHANGE CODE: `source` is one ES module exporting `async function exchange(material, fetch)`,
   *  which logs in (any vendor's shape: a CSRF form and its cookie, a GraphQL mutation) and returns
   *  the NEXT material — keep what the next login needs (`{ ...material, accessToken }`). It runs
   *  only on first use and on a 401, in a jail the secret's facet loads: no bindings, `fetch` (the
   *  argument and the global alike) reaches the secret's pinned origins and nothing else — a
   *  request anywhere else fails the refresh — and `console` is silenced. Only the returned object
   *  is kept. The source is part of the record, so changing it is a `set` like the material's. */
  | { kind: "worker"; source: string };

/** A secret's catalog entry — `secrets.list()` — its path, the pin, the strategy's KIND, when it
 *  was first set and its public fields; never a secret value (the owner root's fold of the
 *  `secret/set` certificates). */
export type SecretCatalogEntry = {
  path: string;
  urls: string[];
  refresh?: SecretRefresh["kind"];
  /** The iterate Cloud's client that brokers the secret's refresh (`refresh.client.cloud`): an
   *  account that a member connected through iterate's own app at a provider. */
  cloud?: string;
  /** That Cloud's origin (`refresh.client.origin`), which the secret has kept since it was made. */
  cloudOrigin?: string;
  /** For exchange code (`refresh.kind` "worker"): the SHA-256 of its source, hex — which code it is. */
  refreshSourceSha256?: string;
  createdAt: string;
  /** The material's public fields (`set`'s `public`, a collection form's public parts), by name:
   *  an OAuth client's `clientId` beside the secret that holds its `clientSecret`. */
  public?: Record<string, string>;
  proxy?: SecretProxy;
  /** A path that forwards every use to a secret elsewhere, as a lend of the old platform left it:
   *  whose, under which lend, and the connection it is. packages/mind-backup reads it. */
  borrowed?: {
    lendId: string;
    lender: { userId: string; email?: string } | { instance: true };
    integration?: { provider: string; account: string; externalId: string };
  };
};

/** THE OPERATIONS a secret may answer, the vault used as a signer: none unless the secret is made
 *  with them (`SecretUses.operations`). */
export const SECRET_OPERATIONS = [
  "signHmac",
  "verifyHmac",
  "verifyEquals",
  "deriveSharedSecret",
  "publicKeyOf",
  "signWithKey",
  "signStatement",
  "seal",
  "unseal",
] as const;
export type SecretOperation = (typeof SECRET_OPERATIONS)[number];

/** ONE FIELD OF ONE REQUEST'S JSON BODY THAT A SECRET'S VALUE MAY GO INTO (`SecretUses.bodyFields`):
 *  the request's method, its exact URL (https, with no query, at an origin of the secret's `urls`),
 *  and the dotted name of a string field of the body's JSON object.
 *  `{ method: "POST", url: "https://api.example.com/v1/sinks", field: "config.token" }` */
export type SecretBodyField = { method: string; url: string; field: string };

/** WHAT A SECRET MAY BE USED FOR, fixed when it is made, kept by the secrets Worker and shown to the
 *  person who gives it on the collection form or the OAuth start page: the mind's code cannot
 *  widen it later. */
export type SecretUses = {
  /** Where its placeholder may sit in a request: in a header (`"header"`, the default; a `Basic`
   *  credential is a header), or also in the URL (`"url"`, a Telegram bot token in the path). */
  placement?: "header" | "url";
  /** The fields of JSON request bodies that its value may also go into, for an API that takes a
   *  token as a field: none by default, ten at most. In a request with that method to that URL,
   *  the placeholder as the WHOLE value of that field is filled:
   *  `JSON.stringify({ config: { token: 'getSecret("/secrets/<name>")' } })`. The request names
   *  the secret in a header too, which is how it reaches the secrets Worker. Such a request has a
   *  JSON body (`content-type: application/json`, UTF-8, at most 1 MiB) with the placeholder at
   *  one of those fields, or it is refused. The body is parsed and written again with the field
   *  set: its keys keep the order of the parse, of a key written twice the last one stays, a
   *  number that a double does not hold exactly changes, and one beyond a double's range leaves
   *  as `null`. Its content type leaves as the one JSON type that it names, with no parameter.
   *  So a caller that signs its body cannot use this. Nothing else is read: a placeholder at
   *  another place of that body, or in the body of any other request, leaves as written. The
   *  method and the URL are the request's as it is written: one with a query, with a header
   *  that names another method, or with a placeholder in its URL is another request. The fields
   *  are fixed when the value is given: to change them, give it again.
   *  A WEAKER USE THAN A HEADER: a secret that is sent in a body is NOT kept from this mind's own
   *  code if that service shows it back, in an answer to this secret or to another one. So give
   *  such a secret only the reach that you would give the mind itself. The rest of the body and
   *  the headers are the caller's too: they can tell the service what to do with the value, or
   *  which endpoint to take the request for. Where the secret has an approval rule, a request
   *  whose body is filled waits for a member, whatever the rule names. An approval is for the
   *  value that the secret holds then: when the secret is given again, each request that waits
   *  or was approved to fill a body ends, and the same request, sent again, waits anew. */
  bodyFields?: SecretBodyField[];
  /** The operations it answers (`SECRET_OPERATIONS`). Default: none. */
  operations?: SecretOperation[];
  /** The secrets whose refresh may borrow its material, by path: as a client secret or a GitHub
   *  App's key that their refresh names with `getSecret("/secrets/<name>", { field })`. Default:
   *  none. `null`: every secret of the mind, for a client secret whose accounts' paths are not
   *  known when it is made; it is what `describe` answers for such a secret. */
  lendTo?: string[] | null;
  /** For `signStatement`: the paths a statement it signs may name, each with everything under it
   *  (`["/integrations/"]`). Default: any path. */
  statementPaths?: string[];
};

/** What `secrets.signStatement(path, input)` signs: a statement to the mind at `mind` (its domain),
 *  for the context at `path`, of `type`, ending `expiresInSeconds` from now (default 300, at most a
 *  day, the most a mind takes). The secrets Worker adds `at` and the nonce. */
export type SecretStatementSigning = {
  mind: string;
  path: string;
  type: string;
  payload?: Record<string, unknown>;
  about?: string[];
  expiresInSeconds?: number;
};

/** The input an agent gives `itx.secrets.collectFromUser`: the write-only secret path, the
 * origins its material may reach, what the collection page shows the person, and, for a secret of
 * several parts, one field each. `description` is markdown: say where the value comes from, with
 * links (they open in a new tab). */
export type CollectSecretInput = {
  path: string;
  egress: { urls: string[] };
  description?: string;
  /** One input per field, saved as one JSON secret `{ [name]: value }`, whose parts are then
   *  `getSecret(path, { field: name })`: an OAuth app's `clientSecret` (which `beginOAuth` takes as
   *  a placeholder), a webhook's `signingSecret`. Without it, one Value. */
  fields?: CollectSecretField[];
  /** Where the page sends the person once the secret is saved, as an OAuth redirect does: an
   *  absolute http(s) URL without credentials, such as the mind's page that asked. The page
   *  shows its host before the person saves. Without it, the page says the tab can close. */
  redirectUrl?: string;
  /** Whoever holds the link may fill the form, signed in or not; the page says so. Without it, only
   *  a member of the mind, signed in. */
  anyoneWithLink?: boolean;
} & SecretUses;

/** One part of a secret a collection page asks for: its name in the JSON secret
 *  (`[A-Za-z_][A-Za-z0-9_]*`), the label the person reads, whether its value is several lines
 *  (a PEM private key), and whether it is PUBLIC. A public part is no secret (an OAuth client's
 *  ID, a GitHub App's ID and slug): it is entered on the same form as the parts that are, and the
 *  catalog answers its value (`SecretCatalogEntry.public`), so the code that needs it reads it
 *  there and keeps no copy. `placeholder` and `pattern` are the input's (HTML's `pattern`
 *  attribute: the whole value must match; it is compiled with the `v` flag). */
export type CollectSecretField = {
  name: string;
  label: string;
  multiline?: boolean;
  public?: boolean;
  placeholder?: string;
  pattern?: string;
};

/** A secret collection link. Sending this asks the person to authenticate to the intended
 * Iterate instance; it is not itself permission to write a secret. */
export type CollectSecretLink = { path: string; url: string };

/** What `secrets.verifyHmac(path, input)` checks: the bytes the provider signed (a string is its
 *  UTF-8 bytes), the hex HMAC-SHA256 it sent (either case, the scheme's prefix — `sha256=`, `v0=` —
 *  stripped), and which field of a JSON material is the key (the whole material when omitted).
 *  Stripe signs `${t}.${body}`, GitHub the body, Slack `v0:${t}:${body}`: the caller assembles them. */
export type SecretHmacVerification = {
  payload: string | Uint8Array;
  signature: string;
  field?: string;
  derive?: SecretKeyDerivation;
};

/** A key derived from the secret's for one purpose, so one secret serves several (`signHmac`,
 *  `verifyHmac`, `seal`, `unseal`): HKDF-SHA256 with an empty salt and `info`, 32 bytes, from a
 *  signing secret's private scalar `d` (its P-256 JWK), else from the UTF-8 bytes of the string at
 *  `field`. The iterate Cloud derives its proof key (`iterate-cloud/proof`) and its seal key
 *  (`iterate-cloud/seal`) from its P-256 key this way. */
export type SecretKeyDerivation = { info: string };

/** What `secrets.seal(path, input)` seals: `plaintext` under AES-256-GCM, with the key derived for
 *  `info` (`SecretKeyDerivation`). The answer is `sealed.<iv>.<ciphertext>`, each base64url. */
export type SecretSealing = { info: string; plaintext: string; field?: string };

/** What `secrets.unseal(path, input)` opens: a `seal` answer under the same `info`. */
export type SecretUnsealing = { info: string; sealed: string; field?: string };

/** What `secrets.signHmac(path, input)` signs: the bytes to sign (a string is its UTF-8 bytes),
 *  which field of a JSON material is the key (the whole material when omitted), and how the
 *  signature is written: `hex` (the default) or `base64`. X's webhook check wants
 *  `sha256=<base64>` of its `crc_token`. */
export type SecretHmacSigning = {
  payload: string | Uint8Array;
  field?: string;
  encoding?: "hex" | "base64";
  derive?: SecretKeyDerivation;
};

/** What `secrets.verifyEquals(path, input)` checks: the candidate string a request presented (a
 *  static header token, say), and which field of a JSON material is the secret (the whole
 *  material when omitted). */
export type SecretEqualsVerification = {
  value: string;
  field?: string;
};

/** EVERY PROVIDER AN INTEGRATION CONNECTS, spelled once: a connection to one is the log
 *  `/integrations/<provider>/<connection>` and the secret `/secrets/<provider>-<connection>`. The
 *  kinds below are read off it. */
export const INTEGRATION_PROVIDERS = ["slack", "google", "cloudflare", "github", "x"] as const;
export type IntegrationProvider = (typeof INTEGRATION_PROVIDERS)[number];

/** Each provider's name as a person reads it, wherever a page or a message names one. */
export const INTEGRATION_PROVIDER_NAMES = {
  slack: "Slack",
  google: "Google",
  cloudflare: "Cloudflare",
  github: "GitHub",
  x: "X",
} as const satisfies Record<IntegrationProvider, string>;

/** The providers a person signs in with, each through iterate's app there. */
export type SignInProvider = Exclude<IntegrationProvider, "slack" | "x">;

/** Whose OAuth app a secret's `beginOAuth` goes through when it is not a client passed in the
 *  clear: one of an iterate Cloud's by its name there (`github`, `google`, `x`) and that Cloud's
 *  `origin` (`CloudClientName`), the app every deployment shares. The Cloud keeps that app's secret and
 *  adds it to the exchange and to each refresh; the tokens stay in this secret. */
export type SecretOAuthClient = CloudClientName & {
  /** For a GitHub App of the Cloud's: the accounts (a person's or an organization's login)
   *  whose installations this mind asks to be connected to. The member's consent reaches
   *  every account they administer; the mind gets the events and the installation tokens
   *  of these alone, and the Cloud's page names them before the member approves. With none
   *  named it gets no installation, unless `install: true` sends the member to the App's
   *  install page, where the one they choose is connected. */
  accounts?: string[];
};

/** What `secrets.beginOAuth(path, options)` takes: the provider's two endpoints, the OAuth client
 *  (the mind's own in the clear, or an integration's `client`), the scope, the pin, and any extra
 *  authorize parameters the provider needs (Google: `access_type=offline`, `prompt=consent`). */
export type SecretOAuthOptions = {
  /** The provider's two endpoints. Absent with a Cloud client, which names them, the client's id
   *  and the pin itself. */
  authorizationEndpoint?: string;
  tokenEndpoint?: string;
  /** Exactly one of `clientId` and `client`. */
  clientId?: string;
  /** Absent for a public client (PKCE alone), and with `client`. The secret itself, or one
   *  placeholder naming the secret that holds it — `getSecret("/secrets/<name>")`, or
   *  `getSecret("/secrets/<name>", { field: "a.b" })` — so it never passes through your hands:
   *  collect it with `collectFromUser` into a secret pinned to the token endpoint's origin. The
   *  platform reads it from there at the code exchange and at every refresh, and stores only the
   *  placeholder, so rotating that secret takes effect at the next refresh. `beginOAuth` refuses
   *  a placeholder that names no such secret. */
  clientSecret?: string;
  client?: SecretOAuthClient;
  /** With a GitHub App of the Cloud's: the member goes to the App's install page first, and the
   *  installation they choose there is connected. */
  install?: boolean;
  /** Where the platform's callback sends the human once the tokens are stored: an absolute URL on
   *  a hostname of the mind's zones (a page of the mind's own is
   *  `await itx.url({ hostname, path })`). That page reads what the consent granted with
   *  `oauthResult`. Every attempt comes back to the platform's callback first
   *  (`oauthCallbackUrl`, the redirect URI to register for a client of your own), which completes
   *  it only in the browser that opened the start link. */
  next?: string;
  /** The one person who may complete the attempt, by their user id (`user_…`), when they need not
   *  reach this secret's owner: a customer of the mind's own app connecting their own account,
   *  whom the mind knows from a sign-in with this platform. The platform's callback then
   *  completes the attempt only in a browser signed in as that person, in place of one that reaches
   *  the owner; a member who is not that person is refused like anyone else. Only for a mind's
   *  secret, and only with a client of your own (`clientId`): the deployment's app is consented to
   *  by someone who reaches the owner. */
  completedByUserId?: string;
  /** How the token endpoint wants the client credential. */
  clientAuth?: ClientAuth;
  scope?: string;
  /** THE SCOPE CEILING: every scope that the grant may hold. With it the platform keeps a grant
   *  only when the token answer names the scopes it granted (`scope`) and each one is in the list:
   *  an answer that names one outside it, or names none, is refused before anything is kept, and
   *  the person's page says which scopes were too many. A refresh whose answer names a scope
   *  outside it, or names none, is refused the same way. `scope` itself must be within it. Not
   *  with `client`. THE VAULT'S OWN CEILING: for a provider that it holds to reads alone
   *  (Cloudflare: `CLOUDFLARE_READ_SCOPES` and the three scopes that its MCP server adds), a
   *  connect is held to that list with or without this one, and this one may only narrow it. */
  grantedWithin?: string[];
  /** RFC 7009's endpoint, within `urls`: a grant that the vault refuses (its ceiling, its account)
   *  goes back there, its refresh token and its access token, and the `secret/grant-refused` fact
   *  says whether the provider took them. */
  revocationEndpoint?: string;
  /** The origins the tokens may be sent to; defaults to the token endpoint's, which it must include. */
  urls?: string[];
  extra?: Record<string, string>;
  /** The account the tokens must be for — an existing connection's, asked for more: the provider's
   *  id for it (a Slack team, an OpenID `sub`), read off the token response, or off `account`'s
   *  endpoint when given. Another account's tokens are refused before anything is stored. */
  expectAccount?: string;
  /** Where the provider names the account the new tokens are for, when its token response does
   *  not (X; any provider without an ID token): a JSON endpoint within `urls`, which the secret's
   *  facet calls once with the new access token before anything is stored, and the paths of the
   *  account's id and, when it has one, its name (`data.id`, `data.username`). `completeOAuth`
   *  answers the account, and `expectAccount` is checked against its id: another account, no
   *  account, or an answer that is not 200 is refused, and nothing is kept. `method: "POST"` with
   *  `body` (JSON) asks a JSON-RPC endpoint, such as an MCP server's `tools/call`. A step of a path
   *  that ends in `@json` reads a string that holds JSON, as an MCP tool's text does:
   *  `result.content.0.text@json.id`. Not with `client`: the deployment's app names its own
   *  accounts. */
  account?: { url: string; id: string; name?: string; method?: "GET" | "POST"; body?: unknown };
  /** Whoever holds the start link may consent, signed in or not; the page says so. Without it, only
   *  a member of the mind, signed in. */
  anyoneWithLink?: boolean;
  /** The start link goes straight to the provider, whose consent is then the one page the person
   *  confirms on. Without it, the platform's page comes first and the person clicks Continue. That
   *  page still comes first when the secret has an unusual use (`placement: "url"`, `bodyFields`,
   *  `operations`, `lendTo`). With `client`, the Cloud's own page already comes in its place. */
  straightToProvider?: boolean;
} & SecretUses;

/** An `R2Object` as `itx.r2` answers it: every field the class carries, as data — the key with the
 *  owner prefix stripped, dates as ISO strings, checksums as hex. */
export type R2ObjectRecord = {
  key: string;
  version: string;
  size: number;
  etag: string;
  httpEtag: string;
  checksums: Record<string, string>;
  uploaded: string;
  httpMetadata: R2HTTPMetadata;
  customMetadata: Record<string, string>;
  range?: R2Range;
  storageClass: string;
};

/** A Browser Run quick-action name (`browser.quickAction`'s first argument): what to extract from
 *  the rendered page — content, screenshot, PDF, markdown, accessibility snapshot, scraped elements,
 *  structured JSON, links, or a crawl. */
export type CfBrowserQuickAction =
  | "content"
  | "screenshot"
  | "pdf"
  | "markdown"
  | "snapshot"
  | "scrape"
  | "json"
  | "links"
  | "crawl";

/** Options for a Browser Run quick action: the target page as a `url` or as inline `html`, plus the
 *  action's own pass-through options (e.g. `screenshotOptions`). */
export type CfBrowserQuickActionOptions = Record<string, unknown> &
  ({ url: string } | { html: string });

/** What a browser session is acquired with: how long it lives idle (`keepAlive`, 10 seconds to 20
 *  minutes, in milliseconds), whether it is recorded, the country its requests leave from (ISO
 *  3166 alpha-2), and the hosts it may reach. */
export type CfBrowserSessionOptions = {
  keepAlive?: number;
  recording?: boolean;
  location?: string;
  guardrails?: { allowedDomains?: string[]; allowedDomainSets?: string[] };
};

/** A tab (or worker, or frame) of a session's browser, as its DevTools endpoint lists it. */
export type CfBrowserTarget = {
  id: string;
  type: string;
  url: string;
  title?: string;
  description?: string;
  webSocketDebuggerUrl?: string;
  devtoolsFrontendUrl?: string;
};

/** A page a session has open, once it loaded (`loaded: false` when its load event did not arrive
 *  in time: the page may still be usable). */
export type CfBrowserPage = {
  sessionId: string;
  targetId: string;
  url: string;
  title: string;
  loaded: boolean;
};

/** Which of a session's targets a call is for: the session's first page when omitted, and
 *  `"browser"` for the browser's own endpoint (`Target.*`, `Browser.*`). `timeoutMs` bounds the
 *  command (30 seconds when omitted). */
export type CfBrowserCdpOptions = { targetId?: string; timeoutMs?: number };

/** `itx.ai`: the Workers AI binding's methods under their own names and shapes, as far as a call
 *  across RPC can carry them. No RPC carries a Blob, so a file for `toMarkdown` is its bytes; and a
 *  method whose binding answers a Response (`websearch`, a gateway's `run`) answers that Response's
 *  body. The binding's `aiSearch()` and `autorag(id)` are not here: Cloudflare deprecated both for
 *  the `ai_search` bindings, and both reach every instance on the deployment's account. Nor is
 *  `aiGatewayLogId`, which the binding sets after each `run` and so holds whichever call ended
 *  last. */
export type ItxAiApi = Pick<Ai, "run" | "models"> & {
  /** Documents, spreadsheets, web pages and pictures as Markdown: Cloudflare's `toMarkdown`. One
   *  file answers one result, a list a list; a file Cloudflare cannot convert answers
   *  `format: "error"` in its place. With no files, the service, for `supported()`. */
  toMarkdown(): ItxToMarkdownService;
  toMarkdown(
    files: ItxMarkdownDocument[],
    options?: ConversionRequestOptions,
  ): Promise<ConversionResponse[]>;
  toMarkdown(
    files: ItxMarkdownDocument,
    options?: ConversionRequestOptions,
  ): Promise<ConversionResponse>;
  /** AI Gateway `gatewayId` on the deployment's account. */
  gateway(gatewayId: string): ItxAiGateway;
  /** Cloudflare's Web Search API through AI Gateway `gatewayId`, billed to that gateway's
   *  credits (or a provider key stored on it): the answer's body. */
  websearch(request: AiWebSearchRequest): Promise<ItxWebSearchAnswer>;
};

/** A file for `itx.ai.toMarkdown`: Cloudflare's `{ name, blob }` with what the Blob is made of in
 *  place of the Blob, bytes or text (`new Blob([blob], { type })`), or `{ name, data }` with the
 *  bytes in base64. `name`'s extension tells Cloudflare the format; `type` is
 *  `application/octet-stream` when omitted. */
export type ItxMarkdownDocument =
  | { name: string; blob: Uint8Array | ArrayBuffer | string; type?: string }
  | { name: string; data: string; type?: string };

/** `itx.ai.toMarkdown()`: the binding's `ToMarkdownService`. */
export type ItxToMarkdownService = {
  transform(
    files: ItxMarkdownDocument[],
    options?: ConversionRequestOptions,
  ): Promise<ConversionResponse[]>;
  transform(
    files: ItxMarkdownDocument,
    options?: ConversionRequestOptions,
  ): Promise<ConversionResponse>;
  supported(): Promise<SupportedFileFormat[]>;
};

/** `itx.ai.gateway(id)`: the binding's `AiGateway`. `run` is the gateway's universal endpoint and
 *  answers the provider's body: parsed JSON, text, or bytes. `getLog` and `patchLog` take a log's
 *  id as the gateway's log list shows it; a gateway may log other minds' calls too, so nothing
 *  here lists them. */
export type ItxAiGateway = {
  getLog(logId: string): Promise<AiGatewayLog>;
  patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;
  getUrl(provider?: string): Promise<string>;
  run(
    data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[],
    options?: { gateway?: UniversalGatewayOptions; extraHeaders?: object },
  ): Promise<unknown>;
};

/** What `itx.ai.websearch` answers: the Web Search API's JSON. A result carries more fields when its
 *  provider gives them (Exa: `imageUrl`, `lastModifiedDate`). */
export type ItxWebSearchAnswer = {
  items: ({ url: string; title: string; description?: string } & Record<string, unknown>)[];
  metadata: { query: string; requestId: string; latencyMs: number } & Record<string, unknown>;
};

/** `itx.browser`: Cloudflare Browser Run.
 *
 *  ONE-SHOT: `quickAction` renders a page and answers the action's RESULT (a string, parsed JSON, or
 *  bytes for a screenshot or a PDF), not the binding's `{ success, result }` envelope; a failed
 *  action throws.
 *
 *  A SESSION is a browser that stays open between calls, with its pages, cookies and sign-ins:
 *  `openPage({ url })` starts one and answers once the page loaded, `cdp(sessionId, method, params)`
 *  runs one Chrome DevTools Protocol command on it (read with `Runtime.evaluate`, click by
 *  evaluating a script, type with `Input.insertText`, picture with `Page.captureScreenshot`),
 *  `navigate` loads another URL in the same page, and `closeSession` ends it. A session left open
 *  is billed until its `keepAlive` runs out. Every session call names a session by the id
 *  `openPage` or `acquire` answered, which is the capability: nothing here lists sessions.
 *
 *  `fetch` is the binding's raw endpoint, for a library that speaks CDP itself. */
export type CfBrowserApi = {
  fetch(input: Request | string | URL, init?: RequestInit): Promise<Response>;
  quickAction(action: CfBrowserQuickAction, options: CfBrowserQuickActionOptions): Promise<unknown>;
  /** A new session with `url` open in its page. `keepAlive` is five minutes when omitted. */
  openPage(input: { url: string } & CfBrowserSessionOptions): Promise<CfBrowserPage>;
  /** Another URL in a session's page (the first page, or `targetId`'s). */
  navigate(sessionId: string, url: string, options?: CfBrowserCdpOptions): Promise<CfBrowserPage>;
  /** One CDP command on a session's page, answered with the command's result. A CDP error throws. */
  cdp(
    sessionId: string,
    method: string,
    params?: Record<string, unknown>,
    options?: CfBrowserCdpOptions,
  ): Promise<unknown>;
  /** The binding's own `acquire`: a session with a blank page, and `targets` when asked for. */
  acquire(
    options?: CfBrowserSessionOptions & { targets?: boolean; liveViewUrlExpiresInMs?: number },
  ): Promise<{ sessionId: string; targets?: CfBrowserTarget[] }>;
  /** The session's times and state, or null when there is no such session. */
  getSession(sessionId: string): Promise<Record<string, unknown> | null>;
  closeSession(sessionId: string): Promise<{ status: "closing" | "closed" }>;
  /** A link a person opens to watch (or, without `guardrails`, drive) the session. The link is a
   *  credential. */
  getLiveView(
    sessionId: string,
    options?: {
      mode?: "devtools" | "tab" | "full";
      targetId?: string;
      expiresInMs?: number;
      guardrails?: { mode: "readonly" };
    },
  ): Promise<{ webSocketDebuggerUrl: string; devtoolsFrontendUrl: string; id: string }>;
  /** How many sessions the account may run and is running, and when the next may start. */
  limits(): Promise<{
    activeSessions: number;
    maxConcurrentSessions: number;
    allowedBrowserAcquisitions: number;
    timeUntilNextAllowedBrowserAcquisition: number;
    usedBrowserTimeSeconds?: number;
  }>;
  /** A session's tabs: list them, open one, bring one to the front, close one. */
  devtools: {
    getVersion(sessionId: string): Promise<Record<string, unknown>>;
    listTargets(sessionId: string): Promise<CfBrowserTarget[]>;
    getTarget(sessionId: string, targetId: string): Promise<CfBrowserTarget>;
    newTarget(sessionId: string, url?: string): Promise<CfBrowserTarget>;
    activateTarget(sessionId: string, targetId: string): Promise<{ message: string }>;
    closeTarget(sessionId: string, targetId: string): Promise<{ message: string }>;
  };
};

/** Where an `itx.images` image comes from: its bytes, a `ReadableStream` of them, an http(s) URL
 *  (fetched by the platform through the mind's egress, so the bytes never visit you), a mind
 *  file's path (`"/images/photo.jpg"`), or a file handle (`itx.files.get(path)`). A script uses the
 *  path: its `itx.files.get(path)` is a promise it must `await` before it can pass the handle on.
 *  At most 20 MB, the Images binding's own limit. */
export type CfImageSource =
  | Uint8Array
  | ArrayBuffer
  | ReadableStream<Uint8Array>
  | string
  | URL
  | Pick<FileHandle, "bytes">;

/** A file `itx.images` writes into: its path (`"/images/small.jpg"`) or `itx.files.get(path)`. */
export type CfImagesFile = Pick<FileHandle, "put"> | string;

/** What `itx.images.input(…)` and `.text(…)` answer, and every `.transform(…)` and `.draw(…)` on it:
 *  the Images binding's `ImageTransformer`, a plan nothing has run yet. `draw`'s overlay is any
 *  `CfImageSource`. Chain freely: `input(x).transform(a).output(o).response()` is one round trip. */
export type CfImageTransformer = {
  transform(transform: ImageTransform): CfImageTransformer;
  draw(image: CfImageSource, options?: ImageDrawOptions): CfImageTransformer;
  output(options: ImageOutputOptions): Promise<CfImageTransformationResult>;
};

/** The binding's `ImageTransformationResult`. The image is made when `response`, `image` or
 *  `writeTo` runs (and again each time you call one, which Images bills once per unique image and
 *  parameters per month); `contentType` is the output format and runs nothing. */
export type CfImageTransformationResult = {
  response(options?: ImageTransformationResponseOptions): Promise<Response>;
  contentType(): Promise<string>;
  image(options?: ImageTransformationOutputOptions): Promise<ReadableStream<Uint8Array>>;
  /** The image into a file, without visiting the caller; answers the stored file's record. */
  writeTo(file: CfImagesFile): Promise<FileRecord>;
};

/** `itx.images`: the Cloudflare Images binding (`env.IMAGES`), same method names and options, over
 *  `CfImageSource`s. `info` is free; every unique transformation is billed once a month. Not wrapped
 *  yet: `hosted`. A caller's non-image fails as `INVALID_INPUT`. */
export type CfImagesApi = {
  info(image: CfImageSource, options?: ImageInputOptions): Promise<ImageInfoResponse>;
  input(image: CfImageSource, options?: ImageInputOptions): CfImageTransformer;
  text(content: string, options: TextOptions): CfImageTransformer;
};

/** A token for an Artifacts repo's git remote. `id` names it to `revokeToken` and in
 *  `listTokens`, and opens nothing. */
export interface ArtifactToken {
  id?: string;
  plaintext: string;
  expiresAt?: string;
}

/** What Artifacts says of a token after the mint: never its text. */
export interface ArtifactTokenInfo {
  id: string;
  scope: "read" | "write";
  state: "active" | "expired" | "revoked";
  createdAt: string;
  expiresAt: string;
}

/** `itx.cfArtifacts.get(path)`: the repo's handle — a token for its remote, the tokens that
 *  Artifacts has for it, and the remote's git-over-HTTPS URL. A repo that does not exist fails at
 *  these, with the binding's own error. */
export interface CfArtifactRepoApi {
  createToken(scope: "read" | "write", ttlSeconds: number): Promise<ArtifactToken>;
  /** The tokens of this repo that still open it, with no token's text. One that ended, by its
   *  date or by `revokeToken`, is not listed. */
  listTokens(): Promise<{ tokens: ArtifactTokenInfo[]; total: number }>;
  /** Ends one token of this repo, by its id. A token's text is refused: pass none, a script's
   *  source is on its caller's log. True also for a token that has ended already; false when the
   *  repo never had a token of that id. */
  revokeToken(id: string): Promise<boolean>;
  remote(): Promise<string>;
}

/** `itx.cfArtifacts`: Cloudflare Artifacts, mind-scoped and addressed BY THE REPO'S PATH — the
 *  binding's own verbs. `repos` is the friendlier surface. */
export interface CfArtifactsApi {
  /** The Artifacts repo, `main` unborn until the first commit; false when it already existed. */
  create(path: string): Promise<{ created: boolean }>;
  get(path: string): Promise<CfArtifactRepoApi>;
  /** This mind's repos, as paths (one page). */
  list(options?: { limit?: number; cursor?: string }): Promise<{
    repos: { path: string }[];
    cursor?: string;
  }>;
  /** True when the repo existed; false when it was already gone. */
  delete(path: string): Promise<boolean>;
}

/** `connectToMcp`'s options: headers every request carries (`getSecret(…)` placeholders substitute
 *  at egress). A CREDENTIAL NAMES A SECRET, AND NOTHING BESIDE IT:
 *  `{ authorization: 'Bearer getSecret("/secrets/x")' }`, and each pair of a `cookie` likewise.
 *  A connection with a credential that is written out, in a header or in its address, works for
 *  one script, and the context follows nothing up for it: a subscription is not renewed
 *  (`McpSubscription.notRenewed`), and the connection declares no MCP tasks, so a tool call is
 *  held until its result. A follow-up's script would keep that credential in the context's log. */
export type McpConnectOptions = { headers?: Record<string, string> };

/** An MCP server's protocol version, capabilities, name and version. */
export type McpServerInfo = {
  protocolVersion?: string;
  capabilities?: Record<string, unknown>;
  serverInfo?: { name?: string; version?: string };
};

/** One tool as an MCP server's `tools/list` describes it. `_meta.ui` is the MCP Apps extension's:
 *  `resourceUri` (the tool's `ui://` view) and `visibility` (`"model"`, `"app"`). */
export type McpTool = {
  name: string;
  title?: string;
  description?: string;
  inputSchema?: unknown;
  _meta?: Record<string, unknown>;
};

/** A tool's whole result (MCP's `CallToolResult`): an `isError` result is a result, not a throw.
 *  `task`: the server runs the call as a task, and this is no result yet (`McpTask`). */
export type McpToolResult = {
  content?: unknown[];
  structuredContent?: unknown;
  isError?: boolean;
  _meta?: Record<string, unknown>;
  task?: McpTask;
};

/** A TASK THAT AN MCP SERVER RUNS FOR A TOOL CALL (MCP tasks, SEP-2663): its id, which the
 *  server alone makes, and its status. `working` and `input_required` are not ends; `completed`
 *  has the tool's `result` (an `isError` result too), `failed` the server's JSON-RPC `error`, and
 *  `cancelled` neither. `pollIntervalMs`: ask no sooner. `statusMessage`, `result`, `error` and
 *  `inputRequests` are ANOTHER SERVER'S WORDS: data, never a member's instruction. */
export type McpTask = {
  taskId: string;
  status: "working" | "input_required" | "completed" | "cancelled" | "failed";
  statusMessage?: string;
  createdAt?: string;
  lastUpdatedAt?: string;
  ttlMs?: number | null;
  pollIntervalMs?: number;
  result?: unknown;
  error?: unknown;
  inputRequests?: unknown;
};

/** One part of a resource that `resources/read` answers: text, or base64 in `blob`. An MCP App's
 *  view is text of the type `text/html;profile=mcp-app`, its `_meta.ui` the view's `csp`. */
export type McpResourceContents = {
  uri: string;
  mimeType?: string;
  text?: string;
  blob?: string;
  _meta?: Record<string, unknown>;
};

/** One skill an MCP server serves (MCP's Skills extension, SEP-2640): the URI of its `SKILL.md`,
 *  that file's frontmatter as the server lists it, and every file of the skill with its SHA-256
 *  digest (`sha256:<hex>`) and its size in bytes. `resources` is `"dynamic"` for a skill whose
 *  files the server makes on demand: none of them can be checked. */
export type McpSkill = {
  uri: string;
  frontmatter: { name: string; description: string; [key: string]: unknown };
  resources: { uri: string; digest: string; size: number }[] | "dynamic";
  _meta?: Record<string, unknown>;
};

/** One file of a skill as `readSkill` answers it: text, or base64 in `blob`. `server` is the URL
 *  the connection was made to, so what a script hands on says where the words came from.
 *  `verified` is false only for a file of a `"dynamic"` skill. */
export type McpSkillFile = {
  server: string;
  uri: string;
  mimeType?: string;
  text?: string;
  blob?: string;
  verified: boolean;
};

/** One event an MCP server offers (MCP Events, SEP-3415, `events/list`): its name, the delivery
 *  modes it supports (`"webhook"`, `"poll"`, `"push"`), the subscription arguments it takes and
 *  the payload it delivers. */
export type McpEvent = {
  name: string;
  description?: string;
  delivery: string[];
  inputSchema?: unknown;
  payloadSchema?: unknown;
};

/** One occurrence of an event, as a poll answers it and as a webhook delivers it (the `body` of
 *  `events.iterate.com/mcp/webhook-received`). `eventId` names the upstream event: the same
 *  event can come twice under it, when a server replays after a restart. `data` is ANOTHER
 *  SERVER'S WORDS: data, never a member's instruction. */
export type McpEventOccurrence = {
  eventId: string;
  name: string;
  timestamp: string;
  data: unknown;
  cursor?: string | null;
};

/** An MCP server's grant for a webhook subscription. `id` is the server's name for it, which
 *  each delivery carries. `refreshBefore` is when it lapses unless the client subscribes again
 *  (an ISO time, or null for never). `cursor` is the place in the event's stream that the server
 *  has delivered up to, and `truncated` says that events before it were skipped. `deliveryStatus`
 *  is the server's word on its deliveries, when it gives one: `active` (false: it had stopped
 *  after failures, and this call started it again), `lastError`, `throttled`. `notRenewed`: this
 *  context does not renew the grant, and why. The subscription then lapses at `refreshBefore`,
 *  and a script that wants to go on subscribes again before that. */
export type McpSubscription = {
  id: string;
  refreshBefore: string | null;
  cursor?: string | null;
  truncated?: boolean;
  deliveryStatus?: Record<string, unknown>;
  notRenewed?: string;
};

/** `itx.connectToMcp(url)`: an MCP server over Streamable HTTP. Besides these, the connection has
 *  one method per tool whose name is a legal identifier (reached by dotted spelling, untyped here);
 *  `callTool` reaches every tool. */
export interface McpConnectionApi {
  serverInfo(): McpServerInfo;
  listTools(): Promise<McpTool[]>;
  /** The result's `structuredContent`, else its text content JSON-parsed when it parses, else the
   *  text; an `isError` result throws with that text.
   *  A CALL THAT THE SERVER RUNS AS A TASK answers `{ content: [], task }` at once, from this
   *  verb, from `callToolResult` and from the tool's own method: the server decides that, call by
   *  call. The result comes later, and no script waits for it: the context's own schedule
   *  (`itx.schedules.list()`, key `["mcp-task", …]`) asks the server, after 5 seconds and then
   *  after three times as long each time, up to every ten minutes and for a day. The end lands
   *  on this context as `events.iterate.com/mcp/task-settled` `{ server, tool, taskId, status,
   *  statusMessage?, result?, error?, inputRequests? }`. `status` is the server's: `completed`
   *  (with `result`, the tool's whole result), `failed`, `cancelled`, or `input_required` (the
   *  server asks for input, which this client gives none: the asking ends there). Or it is
   *  `lost`: the mind stopped asking, and `error` says why (the server knows the task no more,
   *  it gave no answer twice, or the day is over). */
  callTool(name: string, args?: Record<string, unknown>): Promise<unknown>;
  /** The tool's whole result, `isError` included: what an MCP App's view is given. */
  callToolResult(name: string, args?: Record<string, unknown>): Promise<McpToolResult>;
  /** A task as the server states it now (`tasks/get`). */
  getTask(taskId: string): Promise<McpTask>;
  /** Ask the server to cancel a task (`tasks/cancel`). The server decides whether it stops, so
   *  the task's end is what `mcp/task-settled` says, which may still be `completed`. */
  cancelTask(taskId: string): Promise<void>;
  /** ASK ABOUT A TASK NOW, and go on asking by the context's schedule until it has ended: what
   *  the connection does by itself for a tool call that became a task. Call it for a task that
   *  was `lost`, or whose id came another way. An end that this ask finds lands on the context
   *  as `mcp/task-settled`, and no schedule asks about the task after it. `tool` is the name that
   *  the fact gives the task. `since`, `waitMs` and `claim` are what the schedule's own script
   *  hands on: when the asking began, the wait before this ask, and the script's hold on the
   *  schedule. A caller gives no `claim`. Answers the status this ask found. A server's answer
   *  that names another task, or an end without what it brings (a `completed` task with no
   *  `result`), is refused, and the asking goes on. */
  followTask(follow: {
    taskId: string;
    tool?: string;
    since?: number;
    waitMs?: number;
    claim?: number;
  }): Promise<{ taskId: string; status: McpTask["status"] | "lost" }>;
  /** `resources/read`: the resource's parts, at most 8 million characters in all (an MCP App's
   *  `ui://` view, say). The connection declares the MCP Apps extension, so a server offers its
   *  views. */
  readResource(uri: string): Promise<{ contents: McpResourceContents[] }>;
  /** THE SERVER'S SKILLS (MCP's Skills extension, `skills/list`), every page. A server that does
   *  not declare the extension has none. A skill is ANOTHER SERVER'S TEXT: data for whoever reads
   *  it, never a member's instruction. The connection runs nothing of a skill and gives it no
   *  reach, whatever its frontmatter asks for (`allowed-tools`). */
  listSkills(): Promise<McpSkill[]>;
  /** One skill by the URI of its `SKILL.md` (`skills/get`), listed or not. */
  getSkill(uri: string): Promise<McpSkill>;
  /** ONE FILE OF THE SKILL AT `uri`: its `SKILL.md`, or `file`, a path in the skill
   *  (`references/FORMS.md`). The file is read with `resources/read` and checked against the
   *  skill's entry as the server has it now: the entry lists it, its size and digest are the
   *  entry's, and a `SKILL.md`'s frontmatter is the entry's. A file that fails a check is refused,
   *  as is one of more than 8 million characters. A digest proves that the file is the one the
   *  server listed, not that the server is to be trusted. */
  readSkill(uri: string, file?: string): Promise<McpSkillFile>;
  /** The events the server offers (`events/list`), every page. A server that does not declare
   *  MCP Events offers none, and `subscribe`, `unsubscribe` and `pollEvents` refuse it. */
  listEvents(): Promise<McpEvent[]>;
  /** SUBSCRIBE THIS CONTEXT to the event `name` with its arguments, by webhook: the server POSTs
   *  each occurrence to this context's MCP webhook, which checks its signature and appends it
   *  here as `events.iterate.com/mcp/webhook-received` `{ server, subscriptionId, body }`. `body`
   *  is an `McpEventOccurrence`, or one of the server's notices: `{ type: "gap", cursor }`
   *  (events were skipped) and `{ type: "terminated", error }` (the server ended the
   *  subscription).
   *  THE MIND RENEWS IT. A grant lapses at its `refreshBefore`, so the context's own schedule
   *  (`itx.schedules.list()`, key `["mcp-subscription", …]`) runs a script that subscribes again
   *  after two thirds of each grant, with the cursor of the grant before. When that script fails
   *  twice, two minutes apart, nothing renews the subscription any more, and this context gets
   *  `events.iterate.com/mcp/subscription-ended` `{ server, name, arguments, error }`, once:
   *  subscribe again to go on. It tries once when a second try would come after the grant's
   *  lapse, and a renewal that begins after the lapse subscribes nothing and says that the grant
   *  lapsed. A GRANT THAT THE CONTEXT DOES NOT RENEW says so in `notRenewed`: one that is
   *  over within two minutes, the soonest a context renews, and one of a connection with a
   *  credential that is written out (`McpConnectOptions`). When a renewal gets such a grant, the
   *  context gets `mcp/subscription-ended` too. `cursor`: where delivery begins, for a
   *  subscription that lapsed; without it, now. `claim` is the renewal script's own, its hold on
   *  the schedule: a caller gives none. */
  subscribe(
    name: string,
    args?: Record<string, unknown>,
    options?: { cursor?: string; claim?: number },
  ): Promise<McpSubscription>;
  /** End the subscription `subscribe(name, args)` made, and its renewal. The renewal ends first:
   *  when the server does not answer, the subscription still lapses at its `refreshBefore`. A
   *  renewal that runs at that moment ends what it subscribed, and sets no next renewal. */
  unsubscribe(name: string, args?: Record<string, unknown>): Promise<void>;
  /** ONE POLL of the event `name` (`events/poll`), for an event that a server offers by poll
   *  alone: the occurrences after `cursor`, and the cursor to go on from. No cursor starts from
   *  now and answers no event. `hasMore`: poll again at once. Else wait `nextPollMs`, at least:
   *  nothing here polls again, so a script that wants more sets a schedule of its own. */
  pollEvents(
    name: string,
    args?: Record<string, unknown>,
    options?: { cursor?: string; maxEvents?: number },
  ): Promise<{
    events: McpEventOccurrence[];
    cursor?: string | null;
    truncated?: boolean;
    hasMore?: boolean;
    nextPollMs?: number;
  }>;
  close(): Promise<void>;
}

/** `connectToOpenApi`'s options: the base URL requests go to (default: the document's first
 *  server), and headers every request carries. */
export type OpenApiConnectOptions = { baseUrl?: string; headers?: Record<string, string> };

/** An OpenAPI 3 document — only `openapi`, `servers` and `paths` are read. */
export type OpenApiDocument = {
  openapi: string;
  servers?: Array<{ url?: string }>;
  paths?: Record<string, Record<string, unknown>>;
};

/** One operation an OpenAPI connection grew a method for. */
export type OpenApiOperation = {
  operationId: string;
  method: string;
  path: string;
  parameters: Array<{ name: string; in: string; required?: boolean }>;
  hasRequestBody: boolean;
  summary?: string;
};

/** `itx.connectToOpenApi(specOrUrl)`: an OpenAPI 3 service. Besides these, one method per
 *  `operationId` (dotted spelling, untyped here), each taking one input object. */
export interface OpenApiConnectionApi {
  operations(): OpenApiOperation[];
  /** The input object's fields become path, query and header parameters, the rest the JSON body;
   *  the answer is JSON when the response says so, else its text. */
  call(operationId: string, input?: Record<string, unknown>): Promise<unknown>;
}

/** `connectToCapnweb`'s options: headers for the session's requests, and the transport — a
 *  WebSocket session (default) or one HTTP batch per chain. */
export type CapnwebConnectOptions = {
  headers?: Record<string, string>;
  transport?: "websocket" | "batch";
};

/** `itx.connectToCapnweb(url)`: a remote capnweb API's main object as a pipelinable handle (its
 *  methods are the remote's, untyped here), and `close()` for the session (the next call reopens). */
export type CapnwebConnectionApi = InvokeHandle & { close(): void };

/** A stored file as `itx.files` answers it: its path, content type and size. */
export type FileRecord = { path: string; contentType: string; size: number };

/** `itx.files.get(path)`: a file's verbs. `put`'s string data is base64 or a `data:` URL; `url` is
 *  a signed URL on the mind host that downloads (`GET`, the default) or uploads (`PUT`) it. */
export type FileHandle = {
  put(input: {
    contentType?: string;
    data: Uint8Array | ArrayBuffer | string;
  }): Promise<FileRecord>;
  bytes(): Promise<Uint8Array>;
  head(): Promise<FileRecord | null>;
  delete(): Promise<void>;
  url(input?: {
    method?: "GET" | "PUT";
    expiresInSeconds?: number;
  }): Promise<{ url: string; expiresAt: string }>;
};

/** `itx.email.send`: one message from an address of the mind's. `inReplyToOffset` names a
 *  message on the mind's `/integrations/email` and answers it in its thread: its recipients,
 *  `Re:` subject and threading headers are the defaults. Each attachment is a mind file
 *  (`itx.files`). */
export type EmailSendInput = {
  /** The sender: any address at one of the mind's zones (`agent@example.com`). There is no
   *  default: a send that names none is refused, and so is any other address. */
  from: string;
  to?: string | string[];
  cc?: string | string[];
  subject?: string;
  text?: string;
  html?: string;
  inReplyToOffset?: number;
  attachments?: { path: string; filename?: string }[];
};

/** WHICH requests a fetch route takes — every field given must hold. A fetch route matches an HTTP
 *  request: `url` is a standard `URLPattern` over the real URL (hostname and path; its init's
 *  fields, each a pattern string: `url: { hostname: "here.tunnels.example.com" }`), `headers`
 *  exact values. It names at least one url field or header: `{}` is refused. */
export type FetchRouteRequestMatcher = {
  url?: {
    protocol?: string;
    username?: string;
    password?: string;
    hostname?: string;
    port?: string;
    pathname?: string;
    search?: string;
    hash?: string;
    baseURL?: string;
  };
  headers?: Record<string, string>;
};

/** A route as `itx.fetchRoutes.set(name, route)` takes it: the requests it takes, the itx
 *  expression they go to, who may use it (`mind-members`: the config worker answers anyone else
 *  the sign-in challenge; absent or null: public) and its priority (higher first, then by name). */
export type FetchRouteInput = {
  requestMatcher: FetchRouteRequestMatcher;
  target: ItxExpressionInput;
  authRequirement?: { visitors: "mind-members" } | null;
  priority?: number;
};

/** A live route as `list()` and `match` answer it, its target parsed, with the offset of the
 *  `itx/fetch-route-configured` fact that set it. */
export type FetchRouteEntry = {
  fetchRouteName: string;
  requestMatcher: FetchRouteRequestMatcher;
  target: ItxExpression;
  authRequirement: { visitors: "mind-members" } | null;
  priority: number;
  configuredOffset: number;
};

/** One change a repo commit applies: a file's new content, as text or as bytes, or its deletion. */
export type RepoFileChange =
  | { path: string; content: string }
  | { path: string; bytes: Uint8Array | ArrayBuffer }
  | { path: string; delete: true };
/** One commit as `log` lists it, newest first (`timestamp` is epoch milliseconds). */
export type RepoLogEntry = {
  oid: string;
  message: string;
  author: { name: string; email: string };
  /** who made the commit: `iterate` for every commit the platform makes, whoever wrote it */
  committer: { name: string; email: string };
  timestamp: number;
  parents: string[];
};
/** What a commit reports: the new tip (null on an unborn repo that stayed empty) and the paths it
 *  changed (none when the tree was already as asked). */
export type RepoCommitResult = { commitOid: string | null; changedPaths: string[] };
/** How a `pull` or `push` ended: `main` moved from `previousOid` to `commitOid` (`updated`), or both
 *  sides were already at `commitOid` (`up-to-date`). Pulling or pushing without `force` when neither
 *  side contains the other throws `NOT_FAST_FORWARD`, with `{ ours, theirs }` as its data. */
export type RepoSyncResult = {
  status: "updated" | "up-to-date";
  commitOid: string | null;
  previousOid: string | null;
};
/** `itx.repos.get(path)`: the repo's verbs, branch `main` only (core/mind-worker/src/repo). A
 *  `commitOid` pins a read to that commit; without one, a read is of the tip. */
export type RepoHandle = InvokeHandle & {
  tip(): Promise<string | null>;
  /** A text file's text; null when the repo has no such file. A file that is not text is refused:
   *  `readBytes` reads any file. */
  readFile(path: string, options?: { commitOid: string }): Promise<string | null>;
  /** Any file's bytes, as a stream with its size: `await new Response(file.data).bytes()`. */
  readBytes(
    path: string,
    options?: { commitOid: string },
  ): Promise<{ data: ReadableStream<Uint8Array>; size: number } | null>;
  /** The repo's text files by path, or with `dir` those under that folder. */
  modules(options?: { commitOid?: string; dir?: string }): Promise<Record<string, string>>;
  /** Every file, as the loader reads a worker's source: text, or `{ base64 }` for a file that is
   *  not text. */
  files(options?: {
    commitOid?: string;
    dir?: string;
  }): Promise<Record<string, string | { base64: string }>>;
  listFiles(): Promise<{ commitOid: string | null; paths: string[] }>;
  commitFiles(input: {
    message: string;
    changes: RepoFileChange[];
    author?: { name: string; email: string };
    parent?: string | null;
  }): Promise<RepoCommitResult>;
  writeFile(path: string, content: string): Promise<RepoCommitResult>;
  /** The newest commits, newest first, each step along the commit's first parent: from main's
   *  tip, or `from` any commit (a branch's tip, which reads a proposal's own commits). */
  log(options?: { limit?: number; from?: string }): Promise<RepoLogEntry[]>;
  /** Every branch with its newest commit. The mind reads and publishes `main`; a push to any
   *  other branch changes nothing that runs. */
  branches(): Promise<{ name: string; commitOid: string }[]>;
  /** Lands the tip's `repo/commit-completed` fact again, and answers the tip. On a stack whose
   *  queue has the repo's Artifacts subscription (the config repo's, made at each deploy), a
   *  `git push` to the repo's remote lands the fact by itself, so `/repos/config` publishes. Call
   *  this after a push to a repo with no subscription (one made after the deploy), and when a
   *  mind takes over an Artifacts repo that an older stack made. Null when the repo has no commit. */
  announceTip(): Promise<string | null>;
  /** The one remote the repo remembers, as git's `origin`: a git URL over HTTP(S) whose userinfo may
   *  hold a secret placeholder (`https://x-access-token:getSecret("/secrets/github-acme", { field:
   *  "accessToken" })@github.com/acme/config.git`, the placeholder percent-encoded or not), never a
   *  token; null when none. */
  origin(): Promise<string | null>;
  /** Remember `url` as origin, or forget it (`null`): a `repo/origin-set` fact on the repo's log. */
  setOrigin(url: string | null): Promise<{ origin: string | null }>;
  /** Bring the remote's `main` into this repo, the same commits and oids, fast-forward only unless
   *  `force` (which resets `main` to the remote's). A pull that moves `main` lands
   *  `repo/commit-completed` like a commit, so `/repos/config` publishes. `remote` defaults to origin. */
  pull(options?: { remote?: string; force?: boolean }): Promise<RepoSyncResult>;
  /** Send this repo's `main` to the remote's `main`, fast-forward only unless `force` (which
   *  overwrites the remote's). `remote` defaults to origin. */
  push(options?: { remote?: string; force?: boolean }): Promise<RepoSyncResult>;
  /** Append the repo's own events on its context; its lifecycle facts are the collection's. */
  append(...events: StreamEventInput[]): Promise<StreamEvent[]>;
};

/** One overlay entry as a workspace's `gitStatus` reports it, against its mount at HEAD. */
export type WorkspaceChange = { path: string; change: "added" | "deleted" | "modified" };
/** One mount as `gitStatus` reports it: its path, its repo, and the overlay's changes under it. */
export type WorkspaceMountStatus = { path: string; repo: string; changes: WorkspaceChange[] };
/** `itx.workspaces.get(path)`: a private overlay over the mind's repos, each repo mounted at its
 *  path (core/mind-worker/src/workspace). Reads see the overlay, then the mounted repo's tip. */
export type WorkspaceHandle = InvokeHandle & {
  mounts(): Promise<Record<string, { repo: string }>>;
  /** The overlay's copy (a deletion reads null), else the mounted repo's file at its tip. */
  readFile(path: string): Promise<string | null>;
  /** The mounted repo's file at its tip whatever the overlay says. */
  readBase(path: string): Promise<string | null>;
  writeFile(path: string, content: string): Promise<void>;
  /** False when the path was not a file of the merged view. */
  deleteFile(path: string): Promise<boolean>;
  /** Drop the overlay's entry at `path`. */
  revert(path: string): Promise<void>;
  listAllFiles(): Promise<string[]>;
  gitStatus(): Promise<{ mounts: WorkspaceMountStatus[]; unmounted: WorkspaceChange[] }>;
  /** Commit the overlay's changes under one mount (`scope`, needed when several are dirty). */
  gitCommit(input: {
    message: string;
    scope?: string;
    author?: { name: string; email: string };
  }): Promise<{ commitOid: string | null; mount: string; repo: string; changedPaths: string[] }>;
  gitLog(input?: { scope?: string; limit?: number }): Promise<RepoLogEntry[]>;
  /** Append the workspace's own events on its context; its lifecycle facts are the collection's. */
  append(...events: StreamEventInput[]): Promise<StreamEvent[]>;
};

/** Cloudflare's handle to a snapshot of the writable root filesystem, as `itx.sandboxes` records it. Opaque; valid only for the
 *  image it was taken from, and for 30 days after its last restore. */
export type SandboxSnapshot = { id: string; size: number; name?: string };

/** What the container API's `start` takes: `ctx.container.start`'s options, but for
 *  `enableInternet` (refused: a sandbox's only way out is the mind's egress) and a
 *  `containerSnapshot`, which can only be the snapshot the sandbox's own log records. A start that
 *  names a size (`instance`) is remembered: the sandbox starts on it again until one names another. */
export type SandboxContainerStartOptions = {
  image?: string;
  containerSnapshot?: { id: string };
  entrypoint?: string[];
  env?: Record<string, string>;
  instance?:
    | "lite"
    | "standard-1"
    | "standard-2"
    | "standard-3"
    | "standard-4"
    | { vcpu: number; memoryMib: number; diskMb: number };
  labels?: Record<string, string>;
};

/** What the sandbox's own `start` takes: the container API's, and `from`, which copies a sandbox:
 *  the path of another sandbox of this mind whose snapshot this one starts from (tools installed
 *  once, then started many times). That snapshot is this sandbox's own from then on. One of
 *  `image`, `containerSnapshot` and `from` at most. `image` is `"cloudflare/debian-trixie"` (the
 *  Cloudflare-managed image), the name of an image of the stack, or a digest-pinned image of the
 *  account's own registry (`registry.cloudflare.com/<account>/<repository>@sha256:<digest>`);
 *  anything else fails, since Cloudflare pulls from no other registry. */
export type SandboxStartOptions = SandboxContainerStartOptions & {
  from?: string;
  /** What answers the sandbox's requests in place of the mind's `itx.fetch`: a rule for `itx.fetch`
   *  on the sandbox's context, written as the caller's. It stays until another start names one. */
  egress?: ItxExpressionInput;
};

/** What a sandbox's `files.stat` and `files.lstat` answer (the `iterate fs` tool's, run in the
 *  container). */
export type SandboxFileStat = {
  type: "file" | "directory" | "symlink" | "other";
  size: number;
  mode: number;
  uid: number;
  gid: number;
  atimeMs: number;
  mtimeMs: number;
  ctimeMs: number;
};

/** `itx.sandboxes.get(path).files`: the Sandbox SDK's `Files`, over the sandbox's container, with
 *  `iterate fs` (the CLI's file tool) running inside it. A file is read and written as a stream. A
 *  failure carries the errno's name as `code`: `ENOENT`, `EISDIR`, `ENOTDIR`, … Each call starts the
 *  container first, from the snapshot last taken, as `exec` does. */
export type SandboxFilesApi = {
  /** A file's bytes. A missing file, or a directory, fails the call, never the stream half way. */
  read(path: string): Promise<ReadableStream<Uint8Array>>;
  /** `content` into a file, created or truncated; its directory must exist. A string is UTF-8. */
  write(
    path: string,
    content: string | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array>,
  ): Promise<void>;
  /** A path's metadata, a symbolic link followed. */
  stat(path: string): Promise<SandboxFileStat>;
  /** `stat` without following a symbolic link at the end of the path. */
  lstat(path: string): Promise<SandboxFileStat>;
  /** A directory's immediate entries, in the order it gives them. */
  readDirectory(path: string): Promise<{ name: string; type: SandboxFileStat["type"] }[]>;
  /** A directory; with `recursive`, its missing parents too, and no error when it exists. */
  mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;
  /** A file, directory or link renamed; an existing file at the destination is replaced. */
  rename(source: string, destination: string): Promise<void>;
  /** A file or link removed; a directory needs `recursive`, `force` makes a missing path no error. */
  remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void>;
};

/** `itx.sandboxes.get(path).container`: the Durable Object container API (`ctx.container`) itself,
 *  every member under its own name, replayed where the container lives. A member that answers data is
 *  a call: `container.inspect()`, `container.snapshotContainer()`, `container.destroy()`. A CHAIN is
 *  `container.invoke(steps)`: `container.invoke([["exec", argv, { stdin?: ReadableStream }], "stdout"])`
 *  is one call, and a `ReadableStream` comes back as it is; an `exec` chain ends in the process's
 *  `.stdout`, `.stderr`, `.exitCode`, `.pid`, `.output()` (plain `{ exitCode, stdout, stderr }`) or
 *  `.kill(signo?)`. A `start`, `snapshotContainer` or `destroy` lands on the sandbox's log, and a
 *  sandbox with a call running is not parked. Cloudflare's meaning holds: a raw `start` restores
 *  nothing by itself and a `destroy` saves nothing. Not reachable: `interceptOutbound*` (the
 *  mind's egress is the platform's alone). */
export type SandboxContainerApi = InvokeHandle & {
  readonly running: Promise<boolean>;
  readonly images: Promise<Record<string, string>>;
  start(options?: SandboxContainerStartOptions): Promise<void>;
  monitor(): Promise<void>;
  destroy(reason?: string): Promise<void>;
  signal(signo: number): Promise<void>;
  setInactivityTimeout(durationMs: number): Promise<void>;
  snapshotContainer(options?: { name?: string }): Promise<SandboxSnapshot>;
  inspect(): Promise<{ image: string; labels: Record<string, string> } | null>;
  /** The chain, replayed in one call: `[["exec", argv, options], "stdout"]`. */
  invoke(steps: ItxExpression): Promise<any>;
};

/** `itx.sandboxes.get(path)`: a Linux container whose writable root filesystem is kept as a
 *  snapshot (core/mind-worker/src/sandbox). `exec` and every call of `files` start the container
 *  when none runs, from the snapshot last taken, on `standard-1` unless `start({ instance })` says
 *  otherwise. Memory and running processes do not survive a stop; the snapshot does, for 30 days
 *  after its last restore and only on the image it was taken from. With no snapshot and no
 *  `image`, a start runs the image the mind names
 *  (`events.iterate.com/mind/sandbox-image-configured` on `/`), else the stack's named image when
 *  its config names exactly one (with several, the start must name one), else the
 *  Cloudflare-managed image `cloudflare/debian-trixie`:
 *  Node 24 and npm on Debian, with no git, no curl and no coding CLI
 *  (`start({ image: "cloudflare/debian-trixie" })` asks for it on any stack). iterate's own image,
 *  named `iterate-dev-image` on a stack that has it, is Node on Debian with git, gh, Chromium,
 *  ffmpeg, pnpm, the Claude, Codex and Grok CLIs, the cf CLI, doppler and the iterate CLI.
 *  INSTALL ONCE, THEN COPY THE SANDBOX: install what is missing in one sandbox, take a snapshot
 *  (`container.snapshotContainer({ name })`), and start every other sandbox with
 *  `start({ from: "<that sandbox's path>" })`. Do not use the first sandbox after its snapshot: its
 *  next idle save replaces the snapshot. NOTHING RUNS FOR NOTHING: a sandbox unused for
 *  `idleAfterMs` (five minutes by default; a command, a file call or a stream being read is use;
 *  a call left open counts for an hour at most; a background job is not use, and the stop kills
 *  it) is saved and stopped, a sandbox in use has a snapshot taken every 15 minutes, and
 *  Cloudflare stops the container two hours after it last answered, whatever else fails. THE ONLY WAY OUT IS THE
 *  MIND'S EGRESS: the container starts with the internet off, and every HTTP and HTTPS request it
 *  makes, to any name or address, WebSocket handshakes included, is answered by the mind's own
 *  `itx.fetch` (its rewrite rules;
 *  `getSecret("/secrets/…")` placeholders are substituted there). `apt-get` works through it. A
 *  mind's GitHub connection is in every command's environment as placeholders (`GH_TOKEN`, and a
 *  git credential helper that answers with it): with `git` and `gh` installed, cloning, pushing and
 *  opening pull requests need no setup, and no token ever enters the container. A call
 *  that does not answer within a minute fails: run longer work in the background, as Cloudflare's
 *  recipe does, and poll its files within the idle period:
 *  `container.invoke([["exec", ["setsid", "sh", "-c", "<command> > /tmp/job.log 2>&1; echo $? > /tmp/job.exit"], { stdout: "ignore", stderr: "ignore" }], "pid"])`
 *  answers the process id at once. A plain
 *  `exec(["bash", "-c", "setsid nohup <command> > /tmp/job.log 2>&1 < /dev/null & echo started"])`
 *  works too, joined with `;` and never `&&`. Where the sandbox stands is
 *  `(await handle.snapshot()).state`. */
export type SandboxHandle = InvokeHandle & {
  /** `container.start(options)` with the sandbox's snapshot: make the container run, from the
   *  snapshot last taken unless `image` asks for a fresh start (which leaves that snapshot behind).
   *  Running already: `start()` does nothing, and so does a start that names what the sandbox
   *  started on (a start asked again). A start that names another `image`, `containerSnapshot` or
   *  `from` FAILS, since it would change nothing (`container.destroy()` stops the sandbox first).
   *  A snapshot Cloudflare will not restore (the image was replaced, or 30 days passed)
   *  FAILS the start rather than start empty; `start({ image })` is the way out. */
  start(options?: SandboxStartOptions): Promise<void>;
  /** `container.exec(argv, options)` then `process.output()`: run a command and wait for it
   *  (a shell is `["bash", "-c", "…"]`). A nonzero exit is an answer, not a failure. Output over
   *  8 MiB fails (write it to a file, or stream it with `container.exec(argv).stdout`); take secrets
   *  from `env`, since the log keeps the first 500 characters of the command. The call fails when
   *  it has no answer within a minute; `timeoutMs` (ten minutes when absent) is when the command
   *  itself is stopped. */
  exec(
    command: string[],
    options?: {
      cwd?: string;
      env?: Record<string, string>;
      user?: string;
      stdin?: string | Uint8Array;
      timeoutMs?: number;
    },
  ): Promise<{ exitCode: number; stdout: Uint8Array; stderr: Uint8Array }>;
  /** The Sandbox SDK's `Files`. */
  files: SandboxFilesApi;
  /** The container API itself. `container.invoke([["getTcpPort", port], ["fetch", request]])` with a
   *  `Request` is a request to a server in the sandbox: it starts a stopped sandbox and runs the
   *  command of an exposed port that is closed. From a script or from an app's `fetch` it carries
   *  HTTP alone: no RPC answer holds a socket. A WebSocket needs the port's own host
   *  (`exposePort`), where the platform sends the request with no RPC in its way. */
  container: SandboxContainerApi;
  /** SERVE A PORT OF THE SANDBOX AT A HOST OF THE MIND, `https://<name>.<domain>/`: HTTP, streamed
   *  bodies and WebSockets. A request that finds the sandbox stopped starts it, as `exec` does,
   *  and one that finds the port closed runs `command` (detached, its output in
   *  `/var/log/iterate-port-<port>.log`) and waits for the port, 45 seconds at most in all. Members
   *  only, unless `public: true`. A PUBLIC PORT LETS ANY VISITOR START THAT ONE CONTAINER AND KEEP IT
   *  RUNNING, with no bound on how often: each request is a use. NEVER PUT A SECRET IN `command`: the
   *  sandbox's log keeps it. `name` is a DNS label that no other fetch route takes and is not
   *  `iterate`, `auth`, `dash`, `docs` or `voice`; a name that an app of the mind's own serves takes
   *  that host until `unexposePort`, because a fetch route is served before the mind's code. Only a
   *  context that the sandbox is beneath, and that may set a fetch route on `/`, exposes a port. A
   *  second call with the same port and name replaces the command and who may reach it. An idle
   *  stop keeps the host; deleting the sandbox removes it. */
  exposePort(
    port: number,
    options: { name: string; command?: string[]; public?: boolean },
  ): Promise<{ port: number; name: string; url: string; public: boolean }>;
  /** Stop serving the port at its host and free the name. `name` is null when it was not exposed. */
  unexposePort(port: number): Promise<{ port: number; name: string | null }>;
  /** The ports that a host serves now, read from the fetch routes on `/`. */
  getExposedPorts(): Promise<
    { port: number; name: string; url: string; public: boolean; command?: string[] }[]
  >;
  /** How long the sandbox may sit unused before it is saved and stopped: 1 second to 1 hour, five
   *  minutes by default. */
  configure(settings: { idleAfterMs?: number }): Promise<{ idleAfterMs: number }>;
  /** Append the sandbox's own events on its context; its lifecycle facts are the collection's. */
  append(...events: StreamEventInput[]): Promise<StreamEvent[]>;
};

export type ContextListOptions = {
  /** Words that must all occur in the path or in anything the context said about itself. */
  search?: string;
  /** Only this context and the contexts below it. */
  under?: string;
  /** Only the contexts that have work now. */
  awake?: boolean;
  /** At most this many, 200 when absent and never more than 1,000. */
  limit?: number;
};

/** One live in-flight activity on a context's activity stack (`itx.contexts.list`, `activities` live state). */
export type ContextActivity = {
  key: string;
  text: string;
  icon?: string;
  url?: string;
  tags?: string[];
  pushedAt?: string;
  expiresAt?: string;
};

/** One context as the mind's catalog lists it (`itx.contexts.list`). */
export type ContextListing = {
  path: string;
  /** Present while the context has work, and for about a second after: when it woke (ms). */
  awake?: { since: number };
  createdAt?: string;
  lastEventAt?: string;
  /** The newest event that is not the kernel's own (`itx/*`). */
  lastActivityAt?: string;
  /** How many durable events its log holds. */
  eventCount: number;
  /** How many of each type, by type. */
  eventTypes: Record<string, number>;
  /** The last few types that are not the kernel's own, newest last. */
  recentTypes: string[];
  /** The names of the processors it hosts. */
  processors: string[];
  /** The size of its storage, in bytes. */
  storageBytes?: number;
  /** What the context is for, in its own words: its newest `events.iterate.com/itx/described`. */
  description?: string;
  metadata?: Record<string, unknown>;
  /** Live in-flight activities on this context's stack while it is awake, newest first. */
  activities?: ContextActivity[];
};

/** THE ORDERS OF A WATCHED QUERY (`itx.contexts.watch`). Each is total: the path breaks a tie.
 *  - `active`: the newest activity first (`activeMs`, then the path, both descending).
 *  - `created`: the newest context first (`createdMs`, then the path, both descending).
 *  - `path`: by path, A to Z, as UTF-8 bytes. */
export type CatalogOrder = "active" | "created" | "path";

/** A QUERY OF THE MIND'S CATALOG THAT IS WATCHED (`itx.contexts.watch`). Nothing declares a query
 *  ahead of time: a watcher sends one at run time. One of three kinds:
 *  - a window: the contexts that hold every fact named (`where`, `under`, `childrenOf`), in one
 *    `order`, up to `limit`;
 *  - `keys`: exactly these paths, which is what a join asks for;
 *  - `awake`: the contexts that have work now.
 *
 *  A FACT is a scalar at the top of a context's `metadata` (its newest
 *  `events.iterate.com/itx/described`), or a scalar of a list there: `{ status: "open" }` matches
 *  `metadata.status === "open"`, and `{ tags: "pinned" }` matches a `metadata.tags` that holds
 *  `"pinned"`. A number or a boolean matches as its text. The kernel's own facts start with `$`:
 *  `$processor` is a processor that the context hosts. A query that the catalog cannot answer
 *  exactly is refused with the reason: nothing is dropped. So a query cannot name a fact that the
 *  index does not hold: a key of more than 80 characters, a value of more than 200, or another
 *  key that starts with `$`.
 *
 *  ONE KIND OF CONTEXT IS IN NO WATCHED ANSWER, and `contexts.list` has it: one whose row the
 *  catalog cannot order or index (a path that is not well-formed text, or more than 2,048
 *  facts). The catalog logs each (`context.reactive-catalog-row-refused`). */
export type CatalogQuery = {
  /** Every fact must hold. */
  where?: Record<string, string | number | boolean>;
  /** The context at this path and every context below it. */
  under?: string;
  /** The contexts one level below this path. */
  childrenOf?: string;
  /** `active` when absent. */
  order?: CatalogOrder;
  /** At most this many rows, 50 when absent and never more than 500. */
  limit?: number;
  /** Exactly these paths, at most 500, with no order and no limit. It stands alone. */
  keys?: string[];
  /** The contexts that are awake now. It stands alone. */
  awake?: true;
};

/** ONE CONTEXT AS A WATCH SENDS IT: its listing without `awake` and `activities` (the awake list
 *  is a watch of its own, `{ awake: true }`), the two values that the orders sort by, and the
 *  catalog's revision at which the row last changed. A ROW CHANGES WHEN ITS CONTEXT SENDS A
 *  SUMMARY THAT DIFFERS in something the row holds: the counts and times of its events, its
 *  storage, what it says of itself. A context that works sends a summary shortly after each
 *  burst of changes of its activity stack, once in 15 s with no such change, and once when it
 *  goes quiet. It gathers a burst for 100 ms, and that is no least time between two summaries.
 *  So the row of a context that does many short pieces of work, each of which adds to its log,
 *  changes about ten times a second: a watcher that draws should not draw at each frame. One
 *  long piece of work that only adds to the log changes the row once in 15 s. */
export type CatalogRow = Omit<ContextListing, "awake" | "activities"> & {
  /** What the order `active` sorts by, in milliseconds: when the context was last active
   *  (`lastActivityAt`, or `lastEventAt` when it has had no activity of its own). */
  activeMs: number;
  /** What the order `created` sorts by, in milliseconds: `createdAt`. */
  createdMs: number;
  rev: number;
};

/** One row of the awake list (`{ awake: true }`). It comes from the open sockets alone, so it has
 *  no revision. */
export type CatalogAwakeRow = { path: string; since: number; activities?: ContextActivity[] };

/** WHAT A WATCHER HOLDS OF A QUERY, for a watch that starts again (a page that reconnects): the
 *  catalog then sends every path of the answer and only the rows that the watcher lacks. `gen`,
 *  `rev` and `q` are those of the watcher's last frame. A cursor of another generation or another
 *  query gets every row. */
export type CatalogCursor = {
  gen: string;
  rev: number;
  q: string;
  /** Of a window: the sort key of the LAST row that the watcher holds, in the window's order
   *  (`[activeMs, path]`, `[createdMs, path]`, or `[0, path]` for the order `path`); null when it
   *  holds none. */
  bound?: [at: number, path: string] | null;
  /** Of a `keys` query: the paths that the watcher holds. */
  have?: string[];
};

/** WHAT A WATCH'S CALLBACK IS CALLED WITH. The first frame is the answer: `reset` holds every
 *  row; `resume` (the answer to a cursor) holds every path of the answer in `ids` and only the
 *  rows that the watcher lacks. Every later frame is a `change`: the paths that left the answer
 *  and the rows that came or changed. `from` is the revision of the frame before, so a watcher
 *  sees a gap; the session's end sees it first and sends a `reset`. A `reset` may come at any
 *  time (after a deploy, the catalog is asked again), and it is the whole truth: a watcher puts
 *  its rows in the place of what it holds, also where a row's `rev` is the one it has, since a
 *  new `gen` counts its revisions anew.
 *
 *  ONE WRITE IS ONE BATCH, of any size. A write that changes several watches of one session sends
 *  one frame to each, and every frame but the last says `more: true`: a watcher that joins two
 *  watches applies the frames of a batch together, and never sees half of a write. */
export type CatalogFrame<Row = CatalogRow> = { gen: string; rev: number; more?: true } & (
  | { type: "reset"; q: string; full: boolean; rows: Row[] }
  | { type: "resume"; q: string; full: boolean; ids: string[]; rows: Row[] }
  | { type: "change"; from: number; del: string[]; rows: Row[] }
);

/** What `itx.contexts.watches()` answers: the catalog's own account of who watches what. */
export type CatalogWatches = {
  /** False until the first watch: the catalog then copies each context's row and keeps the copy. */
  active: boolean;
  gen: string;
  rev: number;
  rows: number;
  sockets: number;
  awake: number;
  windows: {
    /** The query in the catalog's one form of it. */
    query: string;
    size: number;
    bound: [at: number, path: string] | null;
    rev: number;
    watchers: number;
  }[];
  /** How many contexts' rows the copy could not write, and still owes: each is made again from
   *  the catalog's own row, after a wait, eight times at most. 0 in a catalog that is whole. */
  owed: number;
  /** What the catalog did since it last woke: statements with the rows that SQLite read and
   *  wrote for them (what the object is billed by), writes, the writes that changed no window,
   *  seeks, messages and characters sent. */
  counters: Record<string, number>;
  /** With `{ verify: true }`: each window whose stored size or bound disagrees with the rows. */
  faults?: string[];
  /** With `{ plans: true }`: how SQLite reads each statement of the engine. */
  plans?: Record<string, string[]>;
};

/** An entity collection root (`itx.repos`, `itx.workspaces`, `itx.sandboxes`): `get(path)` the entity's handle,
 *  `list()` the mind catalog, `create(path)` the creation saga on that path (the parent link the
 *  caller's context writes first, then the processor row, the request, the terminal fact — created,
 *  or create-failed thrown), `delete(path)` the deletion saga (the request, `deleted` cross-posted to
 *  `/`, the row disabled). A relative `path` means the caller's. `get` and `list` reach the whole
 *  mind; `create` and `delete` only paths strictly beneath the caller's context (FORBIDDEN). An
 *  entity whose creation has not landed refuses its handle's verbs and `delete` (NOT_CREATED). */
export type EntityCollectionApi<Handle> = {
  get(path: string): Handle;
  list(): Promise<{ path: string; createdAt: string }[]>;
  create(path: string): Promise<{ path: string }>;
  delete(path: string): Promise<{ path: string }>;
};

/** The roots an installable app adds by rewrite rule — present only on a context whose table has
 *  the rule (a mind that installed the app), so never part of `IterateContextApi` itself. An
 *  installed app publishes its root by augmenting this interface from its own package
 *  (`declare module "iterate/api" { interface InstalledAppRoots { myApp: MyAppApi } }`), so a root
 *  the platform does not ship is never named here; a caller imports that module to spell
 *  `IterateContextApiWith<"myApp">`. */
export interface InstalledAppRoots {}

/** What `itx.telemetry.query` answers: the rows, the SQL that ran for the mind, and an optional
 *  plain notice (a table query on a stack with no telemetry tables answers no rows and a notice).
 *  `truncated` is there when the answer holds the 1,000 rows that are the most one query
 *  answers: more may match. `dataset` names the Cloudflare dataset that answered a query over one
 *  (`TELEMETRY_DATASETS`); the SQL that ran holds the cut's values as named parameters
 *  (`$itx_since`, `$itx_worker_0`, …). */
export type TelemetryRows = {
  rows: Record<string, unknown>[];
  sql: string;
  notice?: string;
  truncated?: true;
  dataset?: TelemetryDataset;
};

/** Cloudflare's own datasets that `itx.telemetry.query` reads with no token, each by the name
 *  Cloudflare's Analytics SQL gives it; `metrics` is the stack's own Analytics Engine dataset. */
export const TELEMETRY_DATASETS = [
  "logs.workersLogs",
  "logs.traces",
  "logs.issues",
  "events.workersInvocations",
  "metrics",
] as const;
export type TelemetryDataset = (typeof TELEMETRY_DATASETS)[number];

/** Whether a query goes to Cloudflare's datasets (`TELEMETRY_DATASETS`) and not to the telemetry
 *  tables (`events`, `logs`, `spans`): a FROM or a JOIN names one of them, or another dataset of
 *  Cloudflare's, which the query then refuses. The platform's `itx.telemetry.query` routes by it. */
export const isTelemetryDatasetQuery = (sql: string) =>
  /\b(?:FROM|JOIN)\s+(?:metrics\b|(?:logs|events)\s*\.)/i.test(sql);

/** A context whose mind installed the named apps: with the app's package imported,
 *  `IterateContextApiWith<"myApp">` spells `itx.myApp`. Code that holds a plain scope asserts it
 *  (`itx as IterateContextApiWith<"myApp">`) where it knows the app is installed. */
export type IterateContextApiWith<App extends keyof InstalledAppRoots> = IterateContextApi &
  Pick<InstalledAppRoots, App>;

/** THE ROOT OF EVERY SESSION AT `https://<controlPlaneHostname>/api`, the control plane's API: a
 *  capnweb session over a WebSocket, which the boundary ends (core/boundary-worker
 *  `ControlPlaneRpcTarget`). The root is small, after capnweb's own pattern of a root whose main
 *  method answers the real API (https://github.com/cloudflare/capnweb#more-complicated-example).
 *  Call `authenticate` at once and do not await it: capnweb sends the calls that are made on its
 *  answer in the same round trip (`root.authenticate(token).mind.whoami()`). */
export interface ControlPlaneApi {
  /** What anyone may know of this stack, asked with no credential. `stackKey` is the document
   *  that the stack publishes at `/keys/stack.json`. */
  about(): Promise<{
    controlPlaneHostname: string;
    topology: "full-cloudflare" | "external-mind-connects-into-cloudflare-boundary";
    stackKey: unknown;
  }>;
  /** ONE WAY IN FOR EVERY KIND OF CLIENT. With `token`: a token of this mind's issuer. With
   *  nothing: what the WebSocket's own request carried, its `Authorization` bearer, else (from a
   *  page of the control plane's own origin alone) the browser's session cookie. What the session
   *  offers follows from what the credential is for. The socket closes when the credential ends. */
  authenticate(token?: string): ControlPlaneSessionApi;
}

/** WHAT ONE AUTHENTICATED SESSION OF THE CONTROL PLANE'S API OFFERS A CLIENT. The whole session is
 *  iterate/workers `ControlPlaneSession`: its other method is for a mind that runs elsewhere, and
 *  its types are the stack's own, which a client does not load. */
export interface ControlPlaneSessionApi {
  /** A member's credential: the mind's root context, `/`, as that member. A key's token: the one
   *  lend that the key may make, `whoami` and `provide`, and nothing else of the mind. Any other
   *  credential: reading it is refused. */
  readonly mind: IterateContextApi;
}

/** A context (a mind, a user, an organization): every `itx` root, reached through `invoke`. */
export interface IterateContextApi {
  invoke(call: ItxExpressionInput, ...args: unknown[]): Promise<unknown>;
  /** Another context of this mind, by path (`..` and `/` allowed; the global namespace is not). */
  cd(path: string): IterateContextApi;
  /** Durable batches appended after a deadline (`afterMs`), at an instant (`at`) or on an interval
   *  (`everyMs`); a key set again is replaced, but an interval set again as it stands keeps its
   *  clock (a failed one is revived); a receipt cancels exactly the definition it names. */
  schedules: {
    set(
      input: ScheduledAppendInput,
      options?: { idempotencyKey?: string },
    ): Promise<ScheduleReceipt>;
    cancel(schedule: ScheduleKey | ScheduleReceipt): Promise<StreamEvent[]>;
    list(): ScheduledAppend[];
    get(key: ScheduleKey): ScheduledAppend | null;
  };
  /** `principal` is who is calling, when the call has one: a person through the mind's API. Code
   *  the mind loaded calls as itself and gets none. `mindId` is the mind's id, the hash of its
   *  signed genesis (./mind-identity.ts), which stays when its hostname changes; `mindSlug` is
   *  its control-plane hostname, the name that people read. */
  whoami():
    | {
        mindId?: string;
        path: string;
        mindSlug?: string;
        mindUrl?: string;
        principal?: Principal;
      }
    | Promise<{
        mindId?: string;
        path: string;
        mindSlug?: string;
        mindUrl?: string;
        principal?: Principal;
      }>;
  append(...events: StreamEventInput[]): Promise<StreamEvent[]>;
  /** `append`, answered with each event's offset alone: the events do not travel back. */
  appendOffsets(...events: StreamEventInput[]): Promise<number[]>;
  /** A public URL of this mind's own code over HTTP: `https://<hostname><path>`. `hostname` is a
   *  hostname of one of the mind's zones (the first zone when absent), and never the control-plane
   *  hostname, which the platform answers. `path` is "/" when absent. `await itx.url()` is how
   *  code learns a zone of the mind: an app at the label `blog` is at
   *  `blog.<new URL(await itx.url()).hostname>`. */
  url(target?: { hostname?: string; path?: string }): Promise<string>;
  /** RESET this context (Cloudflare's `ctx.abort`): its Durable Object drops everything it holds in
   *  memory and the next call starts a fresh incarnation from durable storage. Resolves with the
   *  `events.iterate.com/itx/aborted { reason?, callerPath?, app? }` event it recorded — durable
   *  and attributed to the caller before anything resets — and the reset follows the answer.
   *  SURVIVES: the log and everything derived from it (rewrite rules, subscriptions, schedules),
   *  every facet's storage, kv. GOES: in-memory state, every facet instance and its in-flight work,
   *  every socket on the context (a provider's re-dials), and every other call in flight there — it
   *  rejects with the reset's message (`itx.abort() reset the context <path>: <reason>`). A handle
   *  you kept names its target by expression, so its next call reaches the new incarnation.
   *  Another context of the mind: `itx.cd(path).abort()`. A rewrite rule masks it like any name
   *  (`provide("itx.abort", null)`). */
  abort(reason?: string): Promise<StreamEvent>;
  /** START THIS CONTEXT OVER at the same path, in the same Durable Object: it ends the context's
   *  version (a number that starts at 1) and starts the next. Resolves with the
   *  `events.iterate.com/itx/started-over { version, reason?, callerPath?, app?, held }` event it
   *  recorded, where `held` names the version's schedules, subscriptions and rewrite rules.
   *  `events.iterate.com/itx/created { path, version }` follows it, and the object restarts. The
   *  next incarnation empties what the earlier version left, and its first wake is the version's
   *  birth: `itx/woken`, then the host's birth events and its wake events. The answer waits until
   *  no other isolate holds the earlier version's rules (5 s at most), so no grant of the earlier
   *  version answers after it. An append that arrives between the capstone and the restart is
   *  refused as `UNAVAILABLE` and may be sent again.
   *  EACH CALL THAT RUNS STARTS A VERSION: a second call that reaches the context after the
   *  restart starts another, so call once for a path and do not send it again after an error.
   *  A LIVE CLIENT IS TOLD. A subscriber whose target is a client's live callback gets the capstone
   *  (`itx/started-over` and `itx/created`) as its last batch, whatever it consumes, since its row
   *  goes with the version; an event that its row does not take comes as the bare border, with the
   *  version alone. `iterate/client` then subscribes again and reads the new version from its
   *  start. A WebSocket that a client holds through the context to a provider (a fetch upgrade)
   *  dials again after the restart, as it does after `abort`, and goes on when its expression still
   *  resolves; a name that a client lent the earlier version goes with it. A write that another context makes in
   *  reaction to the earlier version and that arrives after the capstone lands in the new version:
   *  it is sent again like any write. A handle made with `facets.get(name, spec)` names a spec;
   *  called after a new version, it hosts that spec under the name again.
   *  GOES: every rewrite rule but the holds (below), subscriptions, schedules, fetch routes and pause, every open run
   *  (settled `interrupted`), every facet and its storage, every subscription's cursor and
   *  deliveries, the at-most-once send marks; then everything `abort` drops.
   *  STAYS: the log and its offsets, and what other objects keep under this path: child contexts,
   *  the parent's catalog row, secrets, the mind's kv, files, telemetry. A child announces itself
   *  to its ancestors once, so a new version of an ancestor holds no `itx/child-created` for the
   *  children that exist, and a catalog it folds from those facts starts empty. A read from the start
   *  begins at the current version (`allVersions: true` reads from the log's start); a read from
   *  a positive offset answers that offset's event whatever its version.
   *  An idempotency key counts within its version, so an event delivered again after a new version
   *  is taken as new. (No key begins with the control character U+001F: the kernel stores a later
   *  version's keys under it, and `append` refuses one.) WHAT HOLDS THE CONTEXT'S CODE STAYS: a
   *  mask (a rule with a null target, a jail's bare `itx ⇒ null` among them), and a rule at one of
   *  the context's own verbs (`itx.cd` pointed at a broker, `itx.run` at a jail); loaded code can
   *  remove neither. Every other rule goes (the parent link, and a rule at any other name; under a
   *  jail every rule with a target, since each is a grant there), so the config writes a jail's
   *  grants again. A context that masks a name takes a new version only
   *  from a member's session.
   *  Refused on `/` and on a context that hosts a first-party facet (a repo, a sandbox, a
   *  workspace, mail, integrations), whose resources are outside the context. Another context of
   *  the mind: `itx.cd(path).newVersion()`. A rewrite rule masks it like any name. */
  newVersion(reason?: string): Promise<StreamEvent>;
  readEvents(
    afterOffset?: number,
    limit?: number,
    /** A read from the start (`afterOffset` 0 or absent) begins at the current version
     *  (`newVersion`), unless `allVersions` is true. A positive `afterOffset` is taken as given,
     *  whatever version it is in. */
    options?: { includeEphemeral?: boolean; allVersions?: boolean },
  ): Promise<StreamPage>;
  waitForEvent(filter?: WaitForEventFilter): Promise<StreamEvent>;
  /** The request through this context's rule for `itx.fetch`. The method, headers and body go
   *  into the Request.
   *  THERE ARE TWO SIGNERS, AND NOTHING ELSE SIGNS. (1) The built-in fetch signs for the mind its
   *  caller names by argument: `{ signFor: "<another mind's control-plane hostname>" }` sends the
   *  request as this mind to that one (`minds.get(domain).fetch` asks so); its record is
   *  `events.iterate.com/itx/signed-request-sent`. (2) A request that uses a secret by proxy
   *  (`SecretProxy`) is signed by the secrets Worker for that secret's proxy alone, to that
   *  proxy's address, as the secret's `set` says; its record is the secret's own use fact, not
   *  that event.
   *  A rule's target gets the option as one more argument (a whole `@` hands on both): a narrow
   *  fetch passes the request on and nothing else, so the built-in does not sign what it sends. A
   *  request that names a by-proxy secret is still signed by the secrets Worker for that proxy,
   *  for any caller that may use that secret. For a jail's
   *  author: a narrowed fetch calls the mind's fetch with the request alone; it never hands on
   *  what else it was given. */
  fetch(request: Request, options?: { signFor: string }): Promise<Response>;
  kv: {
    get(key: string): Promise<string | null>;
    put(key: string, value: string): Promise<{ ok: true }>;
    delete(key: string): Promise<{ ok: true }>;
    list(prefix?: string): Promise<{ keys: string[] }>;
  };
  /** The object store: every write and delete lands `itx/file-set` or `itx/file-deleted` on the
   *  context that made it, so a file always has evidence on a log (a signed upload's is on `/`).
   *  The R2 binding's own verbs on the owner's slice of one bucket (every key
   *  prefixed, the prefix stripped from every key answered); what cannot cross the wire is answered
   *  as data — an `R2Object` as its fields, a body as its bytes. `list` is one page with its cursor.
   *  `presign` is a signed URL on the mind host, a download or an upload. `files` is the
   *  friendlier surface. */
  r2: {
    head(key: string): Promise<R2ObjectRecord | null>;
    get(
      key: string,
      options?: { range?: R2Range },
    ): Promise<(R2ObjectRecord & { data: Uint8Array }) | null>;
    put(
      key: string,
      value: ArrayBuffer | ArrayBufferView | string | null,
      options?: {
        httpMetadata?: R2HTTPMetadata;
        customMetadata?: Record<string, string>;
        storageClass?: string;
      },
    ): Promise<R2ObjectRecord>;
    delete(keys: string | string[]): Promise<void>;
    list(options?: {
      limit?: number;
      prefix?: string;
      cursor?: string;
      delimiter?: string;
      startAfter?: string;
      /** R2 lists neither unless asked. */
      include?: ("httpMetadata" | "customMetadata")[];
    }): Promise<{
      objects: R2ObjectRecord[];
      delimitedPrefixes: string[];
      truncated: boolean;
      cursor?: string;
    }>;
    presign(input: {
      key: string;
      method?: "GET" | "PUT";
      expiresInSeconds?: number;
    }): Promise<{ url: string; expiresAt: string }>;
  };
  /** The mind's secrets, WRITE-ONLY: a secret IS its path (`/secrets/<name>`, the name
   *  `[a-zA-Z0-9._-]+`), and the path is what an outbound request's placeholder spells —
   *  `getSecret("/secrets/<name>")` in a URL or a header substitutes to the value at egress, and only
   *  towards the ORIGINS in `urls` (required: a secret is always pinned). In a JSON body it does
   *  so only at a field that the secret names (`SecretUses.bodyFields`). `set` stores a string or a
   *  JSON object (`refresh` names the strategy that re-mints an expiring credential); `delete`
   *  forgets it (re-settable); `list` is the catalog — paths, pins, strategy kinds, when first set,
   *  public fields — never a secret value. Every change is one fact on the secret's path
   *  (`secret/set`, `secret/deleted`), attributed to the caller and cross-posted to the root, so the
   *  log says who set what and when. No fact carries the value, sealed or not. */
  secrets: {
    set(
      path: string,
      /** Null for a secret that goes by proxy (`options.proxy`), and only for one. */
      material: SecretMaterial | null,
      /** The material and its options replace the whole of what the secret held. `public`: the
       *  names of the material's top-level string fields that are no secret (an OAuth client's
       *  `clientId`): the `secret/set` fact carries their values and `describe` answers them.
       *  `placement`, `operations` and `lendTo` (`SecretUses`) fix what the secret may be used for:
       *  where its placeholder may sit, the operations it answers, and the secrets whose refresh may
       *  borrow it. */
      options: {
        urls: string[];
        refresh?: SecretRefresh;
        merge?: boolean;
        public?: string[];
        /** With it, `material` is null and only `urls` and `placement: "header"` go beside it. */
        proxy?: SecretProxy;
      } & SecretUses,
    ): Promise<{ path: string }>;
    /** OAuth's first tokens: the link to send a human to — the secrets Worker's start page on the
     *  platform's hostname, which shows the secret, the origins its tokens go to and what else they
     *  may be used for, and whose Continue sends the browser on to the provider's consent page. A
     *  signed-in member opens it, or anyone with `anyoneWithLink`. The provider redirects to the
     *  secrets Worker's callback, which completes only in the browser shown that page; the secret's
     *  object exchanges the code, `secret/set` lands, and the callback redirects to `next`. The
     *  provider's URL and the PKCE verifier stay in the secrets Worker. The attempt lasts an hour.
     *  `nonce` names it; a later `beginOAuth` on the same path replaces it. */
    beginOAuth(
      path: string,
      options: SecretOAuthOptions,
    ): Promise<{ authorizationUrl: string; nonce: string }>;
    /** What became of the attempt `nonce` (`beginOAuth`'s answer), for the page `next` lands on:
     *  `complete` with the scopes the provider granted and, with `account`, the account the tokens
     *  are for; `pending` while it is in flight; `declined` with the provider's `error`
     *  (`access_denied`) when the person said no at the provider, or `failed` with any other
     *  `error` it sent back (for example `server_error`), until a later consent on the same link
     *  completes it; `unavailable` once it expired, a newer attempt replaced it, or a write since
     *  superseded its tokens. Never a token. */
    oauthResult(
      path: string,
      input: { nonce: string },
    ): Promise<
      | { status: "pending" }
      | { status: "complete"; scopes: string[]; account?: { id: string; name: string | null } }
      | { status: "declined" | "failed"; error: string }
      | { status: "unavailable" }
    >;
    /** The redirect URI to register at a provider for a client of your own: the platform's one
     *  callback, `<platform origin>/secrets/oauth/callback`. */
    oauthCallbackUrl(): Promise<string>;
    delete(path: string): Promise<{ path: string }>;
    /** Deletes the secret at `path` only while it goes by proxy, with no write, live OAuth attempt
     *  or live key form in flight, all decided in one turn of the secret's object; else deletes
     *  nothing (`deleted: false`), with no throw. It names no proxy: none can be set over another
     *  without a delete between, so `describe` first tells whose proxy it is. A rule on the exact
     *  name `itx.secrets.delete` does not hold this verb; a rule on `itx.secrets.*` holds both. */
    deleteIfProxy(path: string): Promise<{ path: string; deleted: boolean }>;
    /** Whether the secret at `path` is set, never its value: by a value, or by proxy with
     *  `proxy` and no value here. `set` is false for a path that holds neither, one never set
     *  included. A read alone: no fact. The answer has more fields
     *  (`SecretDescription`, iterate/workers). */
    describe(path: string): Promise<{ path: string; set: boolean; proxy?: SecretProxy }>;
    list(): Promise<SecretCatalogEntry[]>;
    /** A secret's stored cell as text, for a backup: ciphertext that only the stack's at-rest key
     *  opens, handed to a caller whose `proof` is the HMAC-SHA256 of
     *  `[path, "exportSealed", until]` as JSON under that key. `until` is when the proof ends, in
     *  milliseconds since the epoch, five minutes ahead at most. One fact on the secret's path
     *  says that it left. */
    exportSealed(path: string, proof: string, until: number): Promise<{ sealed: string }>;
    /** A sealed cell, taken in once: one that `exportSealed` handed out on a stack with the same
     *  at-rest key, which comes back as it was. `proof`: the HMAC-SHA256 of `[path, cell]` as JSON
     *  under that key.
     *  AN OLDER CELL IS TAKEN OVER A NEWER VALUE, once: that is what a restore is for. A proxy's
     *  cell goes only over nothing, as its `set` does. An older genuine cell of the path still
     *  imports over nothing, so an archive can bring back a secret, or a proxy, that the owner
     *  has replaced since (main's behaviour for a value too). A cell of
     *  a grant whose refresh token works once holds a token that is spent by then. */
    importSealed(path: string, cell: string, proof: string): Promise<{ path: string }>;
    /** The persons' grants that the iterate Cloud brokers, refreshed now, whichever client of the
     *  Cloud a grant is of: one row for each. core/secrets-worker/src/grant-refresh.ts says why a
     *  mind asks for this, and when.
     *  `fresh`: refreshed within the last hour, and left alone. `failed`: the secret is as it
     *  was, and the person may have to connect again. `answerLost`: no answer came, so nobody
     *  refused; the next refresh tells if the grant still stands. */
    refreshGrants(): Promise<
      (
        | { path: string; outcome: "refreshed" | "fresh" }
        | { path: string; outcome: "failed"; error: string; answerLost?: true }
      )[]
    >;
    /** The iterate Cloud at `origin` (an exact `https:` origin, no path: iterate's own is
     *  `https://cloud.iterate.com`), and the names of the clients that Cloud publishes: each is a
     *  `client: { cloud: <name>, origin }` of `beginOAuth`. No client when the Cloud gave no
     *  list. */
    cloud(origin: string): Promise<{ origin: string; clients: string[] }>;
    /** Always false: the stack makes no OAuth client at Cloudflare. A config that asks connects
     *  with no stack client. */
    hasStackClient(name: StackClientName["stack"]): Promise<boolean>;
    /** The link to a form on the platform's own hostname where a person enters a value an agent
     *  must never see in chat. The form shows the secret's path, its pin, what it may be used for
     *  (`SecretUses`) and `description` as the requester's words, and answers a signed-in member
     *  alone unless `anyoneWithLink`. */
    collectFromUser(input: CollectSecretInput): Promise<CollectSecretLink>;
    /** A webhook's signature checked against a secret WITHOUT revealing it: one bit back,
     *  constant-time, run in the secrets Worker. A material with no key at the field answers false.
     *  Like every operation, only a secret made with it in `operations` answers, within a limit
     *  per minute (`SecretUses`). */
    verifyHmac(path: string, input: SecretHmacVerification): Promise<boolean>;
    /** The HMAC-SHA256 of `payload` under a secret, WITHOUT revealing it: the signature comes back,
     *  the key never does, run in the secrets Worker. For a provider that proves an endpoint by a
     *  challenge only the key's holder can answer (X's CRC). A secret never set, or a material with
     *  no key at the field, is refused (`SECRET_NOT_SET`); so is a secret not made with it in
     *  `operations` (`FORBIDDEN`). */
    signHmac(path: string, input: SecretHmacSigning): Promise<string>;
    /** A presented string compared with a secret WITHOUT revealing it, for a credential a caller can
     *  only send as it is (a webhook's static header token): one bit back, constant-time, run in the
     *  secrets Worker, for a secret made with it in `operations`. No string at the field answers
     *  false. A replayable token stays replayable: prefer `verifyHmac` wherever the sender signs. */
    verifyEquals(path: string, input: SecretEqualsVerification): Promise<boolean>;
    /** A P-256 key made in the secrets Worker and kept at `path`, its private half never outside
     *  it: not in `describe`, not through a placeholder (a signing secret is never sent), not lent.
     *  The answer and `describe`'s `public` give its public half (`publicKey`, SPKI DER as
     *  base64url) and `keyId` (`keyIdOf` of iterate/signed), what a mind's `auth.keys` trusts. It
     *  answers `signStatement`, with `statementPaths` as its limit. To keep a key made elsewhere,
     *  collect it instead (`collectFromUser` with one field `privateKey`, the private JWK as JSON,
     *  and `operations: ["signStatement"]`): a secret made to sign takes only such a material. */
    generateSigningKey(
      path: string,
      options?: Pick<SecretUses, "statementPaths">,
    ): Promise<{ path: string; publicKey: string; keyId: string }>;
    /** A signed statement under the secret's P-256 key, as a mind's `POST /statements` takes it
     *  (iterate/signed `Envelope`). Only a secret made with it in `operations` answers, within its
     *  limit per minute, and only for a `path` under its `statementPaths`; a secret with an
     *  approval rule signs nothing (`FORBIDDEN`). */
    signStatement(path: string, input: SecretStatementSigning): Promise<Envelope>;
    /** `plaintext` sealed under a key derived from the secret's (`SecretSealing`), the key never
     *  outside the secrets Worker; for a secret made with it in `operations`. A secret with an
     *  approval rule seals nothing (`FORBIDDEN`), as it signs nothing. */
    seal(path: string, input: SecretSealing): Promise<string>;
    /** A `seal` answer opened again, for a secret made with it in `operations`. A value that does
     *  not open under this secret and `info` is refused (`INVALID_INPUT`). */
    unseal(path: string, input: SecretUnsealing): Promise<string>;
  };
  /** The mind's fetch routes, on its root `/`: which itx expression, the route's `target`, a
   *  request on its hosts goes to. `set` appends one `itx/fetch-route-configured` fact (`null`
   *  deletes the route); `match` answers the route a request takes. The platform serves a request a
   *  route takes from `route.target` (a WebSocket upgrade included), before the config worker's
   *  fetch; a write answers once no host is served from the routes before it. */
  fetchRoutes: {
    set(fetchRouteName: string, route: FetchRouteInput | null): Promise<{ fetchRouteName: string }>;
    list(): Promise<FetchRouteEntry[]>;
    match(request: {
      url: string;
      headers: Headers | Record<string, string> | [string, string][];
    }): Promise<FetchRouteEntry | null>;
  };
  /** The table this context resolves against, described — the tree a model reads. `list()` follows a
   *  bare hop row into the context it names (a Durable Object hop, hence async). */
  rewriteRules: {
    /** `depth`: how many bare hop rows to follow (default: all). */
    list(depth?: number): Promise<RewriteRuleListEntry[]>;
    get(match: string): Promise<RewriteRuleListEntry | null>;
    resolve(call: ItxExpressionInput): string[];
  };
  /** A facet of this context: a caller reaches only what its class lists in `static publicMethods`
   *  (sdk/index.ts `FacetDurableObject`); anything else is refused FORBIDDEN. */
  facets: {
    /** The facet `name` — addressed when it is running (a processor, a named instance), loaded and
     *  hosted from `spec` otherwise. `Facet` types its methods for the caller
     *  (`facets.get<{ snapshot(): Promise<Snapshot> }>("x").snapshot()`): an UNCHECKED assertion,
     *  like a cast — nothing verifies the hosted class has them, so name the facet's own published
     *  type where there is one. A capnweb `RpcStub` of this interface erases the type parameter:
     *  there, cast the handle instead. */
    get<Facet = unknown>(name: string, spec?: FacetSpec): InvokeHandle & Facet;
    /** RESET one facet of this context, from the context that hosts it — any facet, whether or not
     *  it extends the SDK's host, including one that would never answer a call. Its instance and
     *  in-memory state go, and every call in flight on it rejects `FACET_ABORTED`; its storage
     *  stays, and its next call starts it fresh. The context itself is not reset. Resolves with the
     *  `events.iterate.com/itx/facet-aborted { name, reason?, callerPath?, app? }` event;
     *  `NO_FACET` for a name never hosted here. */
    abort(name: string, reason?: string): Promise<StreamEvent>;
  };
  subscriptions: {
    list(): SubscriptionListEntry[];
    get(name: string): SubscriptionListEntry | null;
  };
  /** The rpc stubs lent to this context right now, by key (a live session's `provide`): `get(key)`
   *  one, as a handle over its transport (offline ⇒ RPC_STUB_OFFLINE at call time). */
  rpcStubs: { get(rpcStubKey: string): InvokeHandle; list(): string[] };
  /** THE MIND'S CATALOG OF ITS CONTEXTS, on the mind's root: `list(options)` answers what each
   *  context last said about itself, the most recently active first, and which are awake now. A
   *  context says it when it has had work, so a row is at most one wake behind its log
   *  (core/itx/src/context/context-catalog.ts).
   *
   *  `watch(query, onFrame, options?)` keeps answering a query: the catalog calls `onFrame` with
   *  the answer, and then with each change to it, for as long as the handle lives
   *  (core/itx/src/context/reactive-catalog.ts). The call resolves when `onFrame` has returned
   *  from the answer. It rejects with the reason, and each reason has its code: `INVALID_INPUT`
   *  for a query that the catalog cannot answer exactly, `WATCH_LIMIT` when the session has 64
   *  watches or the mind 512 different live queries, `UNAVAILABLE` when the catalog could not be
   *  reached or did not answer, `FORBIDDEN` for loaded code. It is a session's call: the frames
   *  ride the session's own connection, and the session's end closes every watch. The handle's
   *  `ended()` settles with the reason when the watch ends: the watcher's own dispose, the
   *  session's end, or a catalog that could not be reached again, after which the watcher
   *  watches again. Who may `list` may `watch`. `options.cursor` says what the watcher holds
   *  already. `watches()` answers who watches what: it names the paths and the facts that other
   *  sessions ask for, so it is a session's call too, and loaded code is refused (`FORBIDDEN`). */
  contexts: {
    list(options?: ContextListOptions): Promise<ContextListing[]>;
    watch<Query extends CatalogQuery>(
      query: Query,
      onFrame: (
        frame: CatalogFrame<Query extends { awake: true } ? CatalogAwakeRow : CatalogRow>,
      ) => void,
      options?: { cursor?: CatalogCursor },
    ): Promise<{ ended(): Promise<string>; [Symbol.dispose](): void }>;
    watches(options?: { verify?: boolean; plans?: boolean }): Promise<CatalogWatches>;
  };
  processors: {
    enable(
      name: string,
      spec?: (FacetSpec & { consumes?: string[] }) | { consumes?: string[] },
    ): Promise<{ name: string }>;
    disable(name: string): Promise<void>;
    list(): SubscriptionListEntry[];
    /** A hosted processor's claim on this context's alarm: "revive me by `at`" (a facet with a
     *  `runInBackground` attempt in flight), or `null` to release it. */
    claim(name: string, at: number | null): Promise<void>;
  };
  workers: {
    /** A stateless worker loaded from `spec`: `mainModule` loads that module of the source as its
     *  entry in place of package.json's `main`. `source` is as `FacetSpec`'s: an expression with no
     *  `cacheKey` is the NAME of a loaded worker (`itx.cd('/').config`), whose code each call loads,
     *  `mainModule` as the mind's publication of it recorded it. */
    get(spec: {
      source: WorkerSource;
      cacheKey?: string;
      mainModule?: string;
      className?: string;
      props?: unknown;
    }): InvokeHandle;
  };
  /** HTTP WEBHOOKS, the target of a fan-out row that sends each event to another server, Stripe's
   *  way: `webhooks.get({ url, signingSecret? }).deliverEvent` POSTs the event as JSON from this
   *  context through its own `itx.fetch` (a context that may not fetch sends nothing), with
   *  `iterate-event-id: <mindId><path>@<offset>` (repeats share it) and, given a signing secret (a secret
   *  path pinned to `url`'s origin), `iterate-timestamp` and `iterate-signature: v1=<hex
   *  HMAC-SHA256 of "<timestamp>.<body>">`. A 2xx acks; any other status retries on the event's own
   *  ladder (~44 h); a 410 halts the row until a resume. `deliverEvent` is the delivery loop's call
   *  alone. A signature vouches for the MIND, not a context: a receiver checks the body's `path`,
   *  and loaded code names a signing secret only at the mind's root. */
  webhooks: {
    get(spec: {
      url: string;
      signingSecret?: string;
      /** The MCP Events subscription it delivers: each event as an `event.appended` occurrence,
       *  signed per Standard Webhooks with `signingSecret` (our MCP server's `events/subscribe`). */
      mcpSubscription?: string;
    }): InvokeHandle;
  };
  /** ANOTHER MIND THAT LETS THIS ONE IN (core/configs/default/minds.md), as a row's target:
   *  `minds.get("<domain>").deliverEvents` (or `deliverEvent` on a fan-out row) signs each event
   *  with this mind's key and posts it to that mind, which adds it under
   *  `/minds/<this mind><the event's path>`. `minds.get("<domain>").at("<path>").deliverEvents`
   *  adds each event at that one context of the other mind instead, when its rule lets this mind
   *  append there. `itx/*` and `mind-meld/*` events are not sent. Any
   *  answer but a 200 throws, so the row tries again and ends in a dead letter. The delivery
   *  loop's call alone.
   *  THE KERNEL'S LOOP COUNT DOES NOT CROSS A MIND'S EDGE: never answer another mind's request or
   *  event with one to that mind unless the app bounds the exchange itself. A nest of requests
   *  ends only at Cloudflare's limit (a 503 at about the 14th); a chain of events never ends. */
  minds: {
    /** `.fetch(request)`: an https request to that mind, signed as this mind. One Request and
     *  nothing more; no WebSocket. It is the `itx.fetch(request, { signFor: domain })` of the
     *  context where dispatch starts, so that context's rule for `itx.fetch` decides it. For loaded
     *  code that is the caller, wherever the call is spelled: `minds` is answered at the caller, so
     *  its `itx.cd(<a limited context>).minds.get(x).fetch(request)` signs when its own fetch is
     *  free. A member's `itx.cd(<context>)` handle starts dispatch at that context, so there that
     *  context's fetch decides. A mask refuses it, and a narrow fetch sends it on without the
     *  built-in's signature. A context signs wherever it can reach the built-in fetch unchanged, its own or
     *  another context's by `itx.cd`, exactly as it can fetch there: a table that masks its own
     *  fetch and leaves `itx.cd('/')` open has not narrowed fetch. Each try leaves `events.iterate.com/itx/signed-request-sent` on the
     *  calling context's log, written when egress settles, whether or not the caller waits for
     *  the answer; on a context's own object the local write runs before the caller goes on. It
     *  holds the URL's origin and path, never its query: a path can itself hold a token. Its `source` names who asked by
     *  the same fields as any event of that caller: the principal with its grant, and for loaded
     *  code the person it runs for (`onBehalfOf`); code that runs for nobody is named by nobody. When a
     *  member's page makes the call through a context's fetch channel, the source has the member
     *  and not `via.appPage`, because that channel carries no `via`; an ordinary append of the
     *  same page keeps it. */
    get(domain: string): InvokeHandle & { fetch(request: Request): Promise<Response> };
  };
  /** A subscription: a pure itx expression, or a live callback lent to the registry (what live state
   *  uses); `null` removes the row. The handle's dispose removes it too. */
  subscribe(input: {
    name?: string;
    target:
      | ItxExpressionInput
      | ((events: unknown[], range: unknown) => void)
      | EventCopyTarget
      | null;
    consumes?: string[];
    afterOffset?: number;
    /** `false`: FAN-OUT delivery — one event per call (`deliverEvent(event)`), in any order, each
     *  retried and dead-lettered on its own. Absent: the ordered queue, the one that may take a
     *  dead letter (`itx/subscription-delivery-failed`): alert on dead letters from an ordered row. */
    ordered?: false;
    /** With an `EventCopyTarget`, the row COPIES each event it takes onto the log at the target's
     *  `path`. It's always `ordered: false`, and each copy gets a `source.copiedFrom` saying which
     *  event it copies. `filter` is only for such a row: a JSONata expression over the event, and
     *  only events it answers exactly `true` for are copied.
     *
     *  An expression that doesn't compile, or uses something forbidden
     *  (core/itx/src/stream/event-expressions.ts), makes `subscribe` throw. One that throws on a
     *  particular event fails that event's delivery, which is retried like any other. `itx/*`
     *  events are never copied. Copies can land in any order, so read `copiedFrom` to see when and
     *  where each original happened. */
    filter?: string;
  }): Promise<{ [Symbol.dispose](): void }>;
  /** A rewrite rule of this context, session-scoped (the handle's dispose removes it): make `match`
   *  mean `target`, an expression, a live stub, or null to deny. `description` is the one line a
   *  model reads for the name. `fetchRoute` (a live stub, on the mind's root) is a fetch route to
   *  `match` that lives exactly as long as the lend: set with it, set again when the platform
   *  re-attaches it, removed when it ends however it ends. A live stub's handle answers
   *  `lendEnded()` with why the lend ended — it can end while the session lives (the platform lost
   *  its pager). The durable spelling is the rule's event (`RewriteRuleConfigured`) through
   *  `itx.append`. */
  provide(
    match: ItxExpressionInput,
    // Expressions, null, or live RPC references (RpcTarget / callable), serialized by capnweb.
    target: unknown,
    options?: {
      description?: string;
      fetchRoute?: Omit<FetchRouteInput, "target"> & { fetchRouteName: string };
      /** A live stub's lend takes the name only when no other lender (`lentBy`) holds it. */
      onlyFromItself?: true;
    },
  ): Promise<{ [Symbol.dispose](): void; lendEnded(): Promise<string> }>;
  /** A script — the text of `async (itx) => { … }` — run once against this context, on its log:
   *  `itx/run-requested` under the caller, the context's runner, `run-settled` (JSON in, JSON
   *  out); resolves with the result or rejects with the settlement's error. Never re-run. A script
   *  still running ten minutes after it started is settled failed (`failureKind: "deadline"`). */
  run(script: string): Promise<unknown>;
  /** The mind's repos and workspaces as domain objects — one shape each: `get(path)` is
   *  the entity's facet on the context at `path` (its verbs, plus the typed `append` on that
   *  context), `list()` the mind catalog, `create(path)` the creation saga on that path (the
   *  parent link the caller's context writes first, then the processor row, the request, the
   *  terminal fact — created, or create-failed thrown), `delete(path)` the deletion saga (the
   *  request, `deleted` cross-posted to `/`, the row disabled). A relative `path` means the caller's. */
  repos: EntityCollectionApi<RepoHandle>;
  workspaces: EntityCollectionApi<WorkspaceHandle>;
  /** Linux containers whose filesystem is kept as a snapshot: `create(path)` once, then `get(path).exec(["make", "test"])`. */
  sandboxes: EntityCollectionApi<SandboxHandle>;
  /** Workers AI's binding (`ItxAiApi`), under this context's capability rules. */
  ai: ItxAiApi;
  /** Cloudflare Browser Run. */
  browser: CfBrowserApi;
  /** Cloudflare Images: `info` and `transform` over image bytes. */
  images: CfImagesApi;
  /** Cloudflare Artifacts, mind-scoped (`repos` is the friendlier surface). */
  cfArtifacts: CfArtifactsApi;
  /** ONE COMMIT ON A GIT REMOTE'S `main`, with no repo of this mind: nothing is kept here, no
   *  context, no copy of the remote's files and no event. The tip is read, `changes` are applied
   *  to its files (whole files, as `repos.get(path).commitFiles` takes them), and the commit is
   *  pushed, compare-and-swapped on the tip that was read and never forced: a commit that landed
   *  meanwhile refuses it, and a second call reads the tip anew. `remote` is a git URL over
   *  HTTP(S) whose userinfo may hold a secret placeholder, never a token; the requests leave by the
   *  caller's own `itx.fetch`. A remote whose `main` has no commit is refused: the first commit of
   *  a repo is its owner's. With no path changed, nothing is pushed and `commitOid` is the tip. */
  git: {
    commitFiles(input: {
      remote: string;
      message: string;
      changes: RepoFileChange[];
      author?: { name: string; email: string };
    }): Promise<{ commitOid: string; parent: string; changedPaths: string[] }>;
  };
  /** Files stored in the mind's object store, by path (`r2` underneath). */
  files: {
    get(path: string): InvokeHandle & FileHandle;
    list(prefix?: string): Promise<FileRecord[]>;
  };
  /** THE MIND'S TELEMETRY (docs/telemetry.md): `query(sql, { hours })` runs one SELECT, cut to
   *  this mind's rows of the last `hours` (default 24), and answers the rows with the SQL that ran.
   *  Over one of Cloudflare's own datasets (`TELEMETRY_DATASETS`: `logs.workersLogs`,
   *  `logs.traces`, `logs.issues`, `events.workersInvocations`, and `metrics`, the stack's own
   *  Analytics Engine dataset) it needs no token: Cloudflare's Analytics SQL, as Cloudflare's
   *  docs write it, with no JOIN, subquery, UNION, CTE, comment or `$`; at most 168 hours over the
   *  three logs and 768 over the other two. It reads the log lines of every Worker of the
   *  mind's stack, and the spans of the mind's and the boundary's alone. Over the tables `events`, `logs` and `spans` (R2 SQL, at most 720
   *  hours) it needs the stack's telemetry token. A stack with no telemetry tables answers a
   *  notice for a table query, with no rows. `query` is the platform's alone, under this one
   *  name. */
  telemetry: {
    query(sql: string, options?: { hours?: number }): Promise<TelemetryRows>;
  };
  /** WHO IS A MEMBER OF THE MIND NOW, as the stack's sign-in knows it: the addresses its config
   *  names and the members an owner added. `has(email)` answers true or false. The mind's own
   *  code asks it to decide whose words from outside, such as a chat message, are a member's. */
  members: { has(email: string): Promise<boolean> };
  /** The mind's email, `<slug>@iterate.app` (core/lib/src/email.ts has its events and
   *  threads). `send` answers the `email/sent` event. */
  email: {
    send(input: EmailSendInput): Promise<StreamEvent>;
  };
  /** WHAT WAITS FOR A MEMBER'S SIGNED YES before it is done (./acts.ts): a mail, or a call of a
   *  verb, that a rule names. `setRules` replaces the rules while they are open; once a member
   *  locked them it is refused, and `propose` asks a member to sign one rule at `signAt`. A rule
   *  for a request with a secret is a member's alone to put in force: `propose` is the one way
   *  for code or an agent to ask for one. */
  approvals: {
    rules(): Promise<{ locked: boolean; rules: ActRule[] }>;
    setRules(rules: ActRule[]): Promise<ActRule[]>;
    /** With `secret`, a rule for a request with that secret is proposed: the mind's code sets no
     *  such rule, and a member signs the proposal into one or rejects it. */
    propose(
      rule:
        | ActRule
        | {
            secret: string;
            methods: string[];
            hosts: string[];
            jsonStrings?: string[];
            freePaths?: string[];
          },
    ): Promise<{ id: string; signAt: string }>;
    /** One event for a person to sign with a passkey at `signAt`, a page that needs no sign-in,
     *  for a day. Signed, it lands on `path` with the person as `event.source.signer`, whose
     *  `member` says whether a member signed. `next`: where the page goes then, an https URL on a
     *  host of the mind. `signerEmail`: the one person who signs; a non-member signs at
     *  `/people/<address>` alone. */
    proposeStatement(input: {
      path: string;
      type: string;
      payload?: Record<string, unknown>;
      signerEmail?: string;
      next?: string;
    }): Promise<{ draft: string; signAt: string; expires: number }>;
  };
  /** An MCP server over Streamable HTTP, through this context's egress; its events subscribed to
   *  land on this context. */
  connectToMcp(url: string, options?: McpConnectOptions): Promise<McpConnectionApi>;
  /** An OpenAPI 3 service from its document or the URL of one, through this context's egress. */
  connectToOpenApi(
    specOrUrl: string | OpenApiDocument,
    options?: OpenApiConnectOptions,
  ): Promise<OpenApiConnectionApi>;
  /** A remote capnweb API's main object — a WebSocket session through egress (default) or one
   *  HTTP batch per chain (`{ transport: "batch" }`). */
  connectToCapnweb(url: string, options?: CapnwebConnectOptions): Promise<CapnwebConnectionApi>;
}