import type {
  BillingEntitlements,
  IncludedCompute,
  BillingBenefitValues,
} from '../../shared_libs/integration-contracts/billing-entitlements';
export type {
  BillingEntitlements,
  IncludedCompute,
} from '../../shared_libs/integration-contracts/billing-entitlements';
import type {
  PlaySettingsResult,
  PlaySettingsPatch,
  PlaySettingsPathsPage,
} from '../../shared_libs/plays/settings-contract';
import type { PlaySandboxRuntimeDeclaration } from '../../shared_libs/plays/sandbox-runtime-limits';
import type {
  PlayTriggerConfigUpdate,
  PlayTriggerConfigUpdateResult,
  PlayTriggerConfigView,
} from '../../shared_libs/plays/trigger-config-contract';
// Value import from the dependency-free module: the client is bundled into
// authored Plays, where `zod` (the contract's schemas) cannot resolve.
import { playTriggerConfigPath } from '../../shared_libs/plays/trigger-config-route';
import { iterateCursorPages } from './pagination';
import {
  describePlayDetail,
  describePlayListItem,
  type PlayDescriptionOptions,
} from './plays/play-description';
/**
 * The main API client for interacting with the Deepline platform.
 *
 * `DeeplineClient` is the low-level workhorse — it maps 1:1 to the REST API
 * and handles authentication, retries, and response parsing. For a higher-level
 * interface with named play handles and tool shortcuts, use {@link Deepline.connect}
 * or {@link DeeplineContext} instead.
 *
 * ## Quick start
 *
 * ```typescript
 * import { DeeplineClient } from 'deepline';
 *
 * const client = new DeeplineClient();
 *
 * // List available tools
 * const tools = await client.listTools();
 *
 * // Execute a tool
 * const result = await client.executeTool('test_company_search', { domain: 'stripe.com' });
 *
 * // Run a play end-to-end
 * const playResult = await client.runPlay(bundledCode, null, 'my-play', {
 *   onProgress: (status) => console.log(status.progress?.logs),
 * });
 * ```
 *
 * ## Configuration
 *
 * All options are optional — the client resolves API keys and URLs automatically
 * from environment variables and CLI config files. See {@link resolveConfig} for
 * the full resolution order.
 *
 * @module
 */
import { DeeplineError } from './errors';
import { requireBillingIdempotencyKey as requireTargetBillingIdempotencyKey } from './billing-idempotency';
import {
  planCustomerDbQuery,
  queryCustomerDatabase,
  type CustomerDbQueryOptions,
  type CustomerDbQueryPlan,
} from './db/query';
import {
  ToolCalls,
  type ExecuteToolRawOptions,
  type ExecutionByKeyResult,
  type ToolExecution,
} from './tool-calls';
import { validateCliInvocationId } from './cli-invocation-id';
export type {
  ExecutionRecovery,
  ExecutionByKeyResult,
  ToolExecution,
} from './tool-calls';
import type { HttpClient } from './http-core';
import {
  PlayClient,
  type ClientEnvironment,
  normalizePlayRunIntegrationMode,
  normalizePlayStatus,
  resolveStartPlayRunRequest,
  runtimeSelectionHeaders,
} from './plays/client-core';
import { PRODUCT_NOTIFICATION_SLACK_OAUTH_SCOPES } from '../../shared_libs/product-notifications/contract.js';
import {
  DEFAULT_PRODUCT_NOTIFICATION_DELIVERY_TIMING,
  normalizeProductNotificationEmail,
} from '../../shared_libs/product-notifications/configuration.js';
import {
  type ProductNotificationConfigurationChange,
  type EffectiveProductNotificationDestination,
  type EffectiveProductNotificationGroup,
  type ProductNotificationGroupDraft,
} from '../../shared_libs/product-notifications/configuration.js';
import {
  watchRunEvents as pollRunSnapshotEvents,
  type WatchPollObservation,
} from './runs/watch-polling';
import { encodeRunLogsCursor, parseRunLogsCursor } from './runs/log-cursor';
import {
  normalizeRunEventOperationRequest,
  RunEventQueryInputError,
  type RunEventOperationRequest,
  type RunEventQueryCriteria,
  type RunEventQueryOptions,
  type RunEventSummaryOptions,
  type RunEventLogsResult,
  type RunEventEventsResult,
  type RunEventCountResult,
  type RunEventSummaryResult,
  type RunEventFieldsResult,
  type NormalizedRunEventQuery,
} from '../../shared_libs/play-runtime/run-event-query';
import type {
  ResolvedConfig,
  PlayRevisionSummary,
  PlayRunListItem,
  PlaysActivityResponse,
  PlayDetail,
  PlayCostEstimateResult,
  PlayCheckResult,
  PlayRunResult,
  PlayRunStart,
  PlayStatus,
  PlayLiveEvent,
  PlayListItem,
  ProductNotificationSettings,
  ProductNotificationConfigurationResponse,
  PlayDescription,
  StopPlayRunResult,
  StopAllPlayRunsResult,
  StopAllPlayRunsDryRunResult,
  StopAllPlayRunsStopResult,
  RerunOptions,
  RerunPlayRunResult,
  ResumePlayRunResult,
  ClearPlayHistoryRequest,
  ClearPlayHistoryResult,
  PublishPlayVersionRequest,
  PublishPlayVersionResult,
  StartPlayRunRequest,
  DeletePlayResult,
  RestorePlayResult,
  SharePageStatus,
  PublishSharePageRequest,
  UpdateSharePageRequest,
  ToolDefinition,
  ToolCategorySummary,
  ToolCategoryListing,
  ProviderDefinition,
  ToolSearchOptions,
  ToolSearchResult,
  ToolMetadata,
  CustomerDbQueryResult,
  DeeplineAgentModelDescription,
  InferenceQuote,
  ChildRunSummary,
  SearchOptions,
  SearchResult,
} from './types';
import { isStopAllPlayRunsDryRunResult } from './types';
import type { MonitorDefinition } from './monitors';
import type { MonitorFleetDefinition } from './monitor-fleets';
import type { PlayStagedFileRef } from './plays/local-file-discovery';
import type { RuntimeSheetRunRowMembershipPage } from '../../shared_libs/play-data-plane/runtime-sheet-storage-contract';
import {
  isPlayRunPackage,
  mintStagedPlayFileUploads,
  normalizePlayRunStart,
  CLI_PLAY_RUN_CALLER_INTENT_V2_START_STREAM_PATH,
  CLI_PLAY_RUN_START_STREAM_PATH,
  CliPlayAdmissionCallerIntentV2UnsupportedError,
  CLI_PLAY_RUN_SUPPORTED_HEADER,
  CliPlayAdmissionUnsupportedError,
  PLAY_RUN_START_STREAM_PATH,
  stagePlayFiles,
  preparePlayRunAdmission,
  submitPreparedPlayRunAdmission,
  readPlayRunAdmissionCapability,
  type MintStagedFileUpload,
  type PlayRunAdmissionCapability,
  type PlayRunStartOptions,
  type ResolvedStartPlayRunRequest,
} from './plays/run-request';
import { SDK_API_MAJOR } from './version';
import type { PlayCompilerManifest } from '../../shared_libs/plays/compiler-manifest.js';
import type { EnrichCompiledConfig } from './cli/enrich-play-compiler';
import { COORDINATOR_INTERNAL_TOKEN_HEADER } from '../../shared_libs/play-runtime/coordinator-headers.js';
import {
  normalizePlayRuntimeSelection,
  type PlayRuntimeSelection,
} from '../../shared_libs/play-runtime/runtime-environment.js';
import {
  decodePlayRunPublicStatus,
  isTerminalPlayRunLifecycleStatus,
  type PlayRunPublicStatus,
} from '../../shared_libs/play-runtime/run-lifecycle-policy.js';
export type SlackNotificationTarget =
  | { channel: string; memberId?: never }
  | { channel?: never; memberId: string };

type ToolDiscoveryResponse = {
  view?: string;
  categories?: unknown;
  tools?: ToolDefinition[];
};

function invalidToolDiscoveryResponse(): DeeplineError {
  return new DeeplineError(
    'The server returned an invalid tool discovery response.',
    502,
    'INVALID_TOOL_DISCOVERY_RESPONSE',
  );
}

function readToolCategorySummaries(value: unknown): ToolCategorySummary[] {
  if (!Array.isArray(value)) throw invalidToolDiscoveryResponse();
  const seen = new Set<string>();
  return value.map((item: unknown) => {
    if (
      !item ||
      typeof item !== 'object' ||
      !('name' in item) ||
      typeof item.name !== 'string' ||
      !item.name.trim() ||
      seen.has(item.name) ||
      !('count' in item) ||
      typeof item.count !== 'number' ||
      !Number.isSafeInteger(item.count) ||
      item.count < 0
    ) {
      throw invalidToolDiscoveryResponse();
    }
    seen.add(item.name);
    return { name: item.name, count: item.count };
  });
}

function summarizeToolCategories(
  tools: ToolDefinition[],
): ToolCategorySummary[] {
  const counts = new Map<string, number>();
  for (const tool of tools) {
    for (const category of tool.categories ?? []) {
      counts.set(category, (counts.get(category) ?? 0) + 1);
    }
  }
  return [...counts]
    .map(([name, count]) => ({ name, count }))
    .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
}

export type CreateNotificationInput = {
  name: string;
  provider: 'slack';
  eventTypes: string[];
} & SlackNotificationTarget;

export type UpdateNotificationInput =
  | { enabled: boolean }
  | ({ name: string; eventTypes: string[] } & SlackNotificationTarget);

export type CreateNotificationGroupInput = {
  name: string;
  targets: string[];
  legacyEvents?: string[];
  dryRun?: boolean;
};

export type CreateNotificationGroupResult =
  | {
      mode: 'dry_run';
      compatibilityMode: boolean;
      name: string;
      targets: string[];
      legacyEvents: string[];
    }
  | { mode: 'legacy'; notification: unknown }
  | {
      mode: 'native';
      groupKey: string;
      targets: string[];
      group: EffectiveProductNotificationGroup;
      destinations: EffectiveProductNotificationDestination[];
    };

type ParsedNotificationGroupTarget =
  | { kind: 'email'; email: string }
  | { kind: 'slack'; channel: string }
  | { kind: 'slack'; memberId: string };

const MAX_NOTIFICATION_GROUP_CREATE_TARGETS = 50;

function parseNotificationGroupTarget(
  value: string,
): ParsedNotificationGroupTarget {
  const normalized = value.trim();
  if (normalized.toLowerCase().startsWith('email:')) {
    const email = normalizeProductNotificationEmail(normalized.slice(6));
    if (!email) {
      throw new Error(
        `Invalid email notification target "${value}". Use --to email:name@example.com.`,
      );
    }
    return { kind: 'email', email };
  }
  const slack = /^slack:(.+)$/i.exec(normalized)?.[1]?.trim();
  if (!slack) {
    const provider = normalized.split(':', 1)[0] || normalized;
    throw new Error(
      `Unsupported notification destination "${provider}". Use email: or slack:.`,
    );
  }
  const member = /^member:([UW][A-Z0-9]{8,})$/i.exec(slack);
  if (member?.[1]) {
    return { kind: 'slack', memberId: member[1].toUpperCase() };
  }
  if (slack.toLowerCase().startsWith('member:')) {
    throw new Error(
      'Slack member IDs must look like slack:member:U0123456789.',
    );
  }
  if (!slack.replace(/^#/, '').trim()) {
    throw new Error('Use --to slack:#channel.');
  }
  return { kind: 'slack', channel: slack };
}

function notificationObjectKey(kind: 'group' | 'destination') {
  return `${kind}.${globalThis.crypto.randomUUID()}`;
}

const MONITOR_NON_RETRYABLE_MUTATION_OPTIONS = {
  maxRetries: 0,
  exactUrlOnly: true,
};
const COMPILE_MANIFEST_RETRY_DELAYS_MS = [250, 1_000];
const REGISTER_PLAY_ARTIFACTS_COMPILE_CONCURRENCY = 3;
const REGISTER_PLAY_ARTIFACTS_MAX_BATCH_COUNT = 3;
const REGISTER_PLAY_ARTIFACTS_MAX_BATCH_BYTES = 2_500_000;

export type IngestionStorageRepairResult = {
  status?: 'repaired';
  connection_grants: {
    runtime_role: string;
    customer_db_role: string;
  };
  repaired: unknown[];
  count: number;
  repair?: {
    location: { changed: boolean };
    storage_contract: { applied: boolean; current: boolean };
    runtime_migration: { current: boolean };
    runtime_capabilities: {
      before: {
        reachable: boolean;
        status: string;
        storage_contract_current: boolean;
        runtime_migration_current: boolean;
        runtime_capabilities_ready: boolean;
        capability_failures: string[];
      };
      after: {
        reachable: boolean;
        status: string;
        storage_contract_current: boolean;
        runtime_migration_current: boolean;
        runtime_capabilities_ready: boolean;
        capability_failures: string[];
      };
      runtime_role: {
        currentRole: string | null;
        dlMetaSchemaUsage: boolean;
        uuidFunctionExecute: boolean;
        enrichmentsSchemaUsage: boolean;
        enrichmentsWriteReady: boolean;
        storageSchemaUsage: boolean;
        storageSchemaCreate: boolean;
      };
      customer_db_role: {
        currentRole: string | null;
        dlMetaSchemaUsage: boolean;
        uuidFunctionExecute: boolean;
        enrichmentsSchemaUsage: boolean;
        enrichmentsWriteReady: boolean;
        storageSchemaUsage: boolean;
        storageSchemaCreate: boolean;
      };
    };
    internal_relations: { reconciled: boolean };
    materialized_tables: { repaired_count: number };
  };
};

/** The isolated PR estate needs its existing internal credential to read its pinned scheduler scope. */
function isolatedCiRuntimeEventReadHeaders(
  env: ClientEnvironment,
): Record<string, string> | undefined {
  const schema = env.DEEPLINE_RUNTIME_SCHEDULER_SCHEMA?.trim();
  if (
    env.DEEPLINE_SYNTHETIC_RUN?.trim() !== '1' ||
    !schema ||
    !/^fly_absurd_pr_\d+_\d+(?:_\d+)?$/.test(schema)
  ) {
    return undefined;
  }
  const token = env.DEEPLINE_INTERNAL_TOKEN?.trim();
  if (!token) {
    throw new DeeplineError(
      'DEEPLINE_INTERNAL_TOKEN is required for isolated CI runtime event reads.',
      undefined,
      'RUNTIME_EVENT_INTERNAL_TOKEN_REQUIRED',
    );
  }
  return { [COORDINATOR_INTERNAL_TOKEN_HEADER]: token };
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function isTransientCompileManifestError(error: unknown): boolean {
  if (error instanceof DeeplineError && typeof error.statusCode === 'number') {
    return (
      error.statusCode === 408 ||
      error.statusCode === 425 ||
      error.statusCode === 499 ||
      (error.statusCode >= 500 && error.statusCode < 600)
    );
  }
  const message = error instanceof Error ? error.message : String(error);
  return /fetch failed|connection (?:closed|reset|terminated)|socket hang up|econnreset|etimedout|eai_again|abort/i.test(
    message,
  );
}

function requireCompileManifestResponse(
  response: { compilerManifest?: PlayCompilerManifest } | null | undefined,
  playName: string,
): PlayCompilerManifest {
  const compilerManifest = response?.compilerManifest;
  if (
    !compilerManifest ||
    typeof compilerManifest !== 'object' ||
    Array.isArray(compilerManifest)
  ) {
    throw new DeeplineError(
      `Compile manifest response did not include compilerManifest for ${playName}.`,
      502,
      'API_RESPONSE_INVALID',
      { response: response ?? null },
    );
  }
  return compilerManifest;
}

async function mapWithConcurrency<T, U>(
  items: T[],
  concurrency: number,
  mapper: (item: T, index: number) => Promise<U>,
): Promise<U[]> {
  const results = new Array<U>(items.length);
  let nextIndex = 0;
  const workerCount = Math.min(Math.max(1, concurrency), items.length);
  await Promise.all(
    Array.from({ length: workerCount }, async () => {
      for (;;) {
        const index = nextIndex;
        nextIndex += 1;
        if (index >= items.length) {
          return;
        }
        results[index] = await mapper(items[index]!, index);
      }
    }),
  );
  return results;
}

function jsonUtf8Bytes(value: unknown): number {
  return new TextEncoder().encode(JSON.stringify(value)).length;
}

function chunkRegisterPlayArtifacts<T>(artifacts: T[]): T[][] {
  const chunks: T[][] = [];
  let current: T[] = [];

  for (const artifact of artifacts) {
    const candidate = [...current, artifact];
    const candidateTooLarge =
      candidate.length > REGISTER_PLAY_ARTIFACTS_MAX_BATCH_COUNT ||
      jsonUtf8Bytes({ artifacts: candidate }) >
        REGISTER_PLAY_ARTIFACTS_MAX_BATCH_BYTES;
    if (current.length > 0 && candidateTooLarge) {
      chunks.push(current);
      current = [artifact];
    } else {
      current = candidate;
    }
  }

  if (current.length > 0) {
    chunks.push(current);
  }

  return chunks;
}

/** Query parameters shared by every search route. */
function searchParams(options: ToolSearchOptions): URLSearchParams {
  const params = new URLSearchParams();
  params.set('q', options.query?.trim() ?? '');
  params.set(
    'include_search_debug',
    options.includeSearchDebug ? 'true' : 'false',
  );
  params.set('search_mode', options.searchMode ?? 'v2');
  if (options.limit !== undefined) params.set('limit', String(options.limit));
  if (options.offset !== undefined) {
    params.set('offset', String(options.offset));
  }
  if (options.categories?.trim()) {
    params.set('categories', options.categories.trim());
  }
  if (options.searchTerms?.trim()) {
    params.set('search_terms', options.searchTerms.trim());
  }
  if (options.task?.trim()) params.set('task', options.task.trim());
  return params;
}

/** Filters for `client.runs.list(...)`. */
export type RunsListOptions = {
  play?: string;
  status?: string;
  /** Mermaid node id; returns that node's latest settled input/output per run. Requires play. */
  node?: string;
  limit?: number;
  /** Zero-based page offset. Requires `play` because status-only inventory is not paginated. */
  offset?: number;
};

/** One server page; legacy runs.list continues to return an array. */
export type RunsListPage = {
  runs: PlayRunListItem[];
  total?: number;
  offset?: number;
  limit?: number;
  hasMore?: boolean;
};

/** Cursor-paged workspace run history, including runs of removed Plays. */
export type RunsHistoryOptions = {
  /** Case-insensitive Play/workflow name, run ID, or status substring. */
  search?: string;
  /** Search classification from recorded trigger metadata; requires search. */
  type?: 'all' | 'plays' | 'monitors';
  cursor?: string;
  limit?: number;
  /** Must match the workspace authorized by the credential. */
  orgId?: string;
  signal?: AbortSignal;
};

export type RunsHistoryItem = {
  runId: string;
  workflowId: string;
  workflowName: string;
  playScope: 'org' | 'system' | null;
  status: string;
  createdAt: number;
  updatedAt: number;
  callerName: string | null;
  callerEmail: string | null;
  authorName: string | null;
  authorEmail: string | null;
  callerAgent: string | null;
  executionMode: string | null;
  bindingId: string | null;
  parentWorkflowName: string | null;
  outputRowCount: number | null;
  hasOutput: boolean;
  billingTotalCredits?: number;
  triggerSource?: string;
};

/** An empty search page is incomplete while hasMore is true. */
export type RunsHistoryPage = {
  runs: RunsHistoryItem[];
  nextCursor: string | null;
  hasMore: boolean;
  avatarsByName?: Record<string, string>;
};

export type PlaysListOptions = {
  /** Load compact inventory metadata without authored source or revisions. */
  summaryOnly?: boolean;
  origin?: 'prebuilt' | 'owned';
  grep?: string;
  /**
   * @deprecated Grep is always evaluated by the Convex full-text index.
   * This retained option is ignored for source compatibility.
   */
  grepMode?: 'all' | 'any' | 'phrase';
  categories?: string | string[];
  /**
   * Keep only plays carrying one of these tags — the job a play does, not the
   * tools it calls. Deepline's closed vocabulary today: `smb`,
   * `find-prospects`, `qualify`, `contact-info`, `signals`. Several tags widen
   * the result rather than narrowing it, because a play carries exactly one.
   */
  tags?: string | string[];
  includeToolCategories?: boolean;
  includeArchived?: boolean;
  includeCostEstimates?: boolean;
};

export type PlaysListPage = {
  plays: PlayListItem[];
  cursor: string | null;
  hasMore: boolean;
};

/** Options for `client.runs.get(...)`. */
export type RunsGetOptions = {
  /** Return the raw status payload instead of the compact package. */
  full?: boolean;
  /** Explicitly read this run's recorded graph and source, without full results. */
  configuration?: boolean;
  /** Include terminal runtime diagnostics (`run.performance`) without full results. */
  performance?: boolean;
  /** Attach a bounded end-of-stream window for a failed run. */
  failedLogs?: boolean;
  /** Requested failed-log lines to attach (default 20, hard-capped at 20). */
  failedLogLimit?: number;
};

export type RunsChildrenOptions = {
  /** Required authored `deepline.runPlayAsync` launch key. */
  launchKey: string;
  /** Opaque cursor returned by the preceding page. */
  cursor?: string;
  /** Rows to request (1–50; defaults to 50). */
  limit?: number;
};

/** One bounded page of direct child Runs for one async launch. */
export type RunChildrenPage = {
  children: ChildRunSummary[];
  nextCursor: string | null;
  hasMore: boolean;
};

export type RunGetStatus =
  | {
      available: false;
      reason: 'not_projected' | 'read_failed';
    }
  | {
      available: true;
      observedAt: number;
      source: {
        ledgerNextSeq: number | null;
        runSnapshotLedgerNextSeq: number | null;
        aligned: boolean | null;
      };
      calls: {
        logicalCalls: { value: number | null; confirmed: boolean };
        toolDispatches: { value: number | null; confirmed: boolean };
        provider429s: { value: number | null; confirmed: boolean };
      };
      focusStep: {
        id: string;
        label: string | null;
        status: string | null;
        rows: {
          succeeded: number | null;
          failed: number | null;
          total: number | null;
        };
      } | null;
    };

const RUNS_FAILED_LOG_LIMIT = 20;

/** Options for `client.runs.watch(...)`. */
export type RunsWatchOptions = {
  signal?: AbortSignal;
  /** Observe each canonical event while `watch` waits for terminal state. */
  onEvent?: (event: PlayLiveEvent) => void;
  /**
   * Called once when a transient REST polling outage begins. Polling retries
   * on its normal fixed interval.
   */
  onRetry?: (info: {
    attempt: number;
    delayMs: number;
    reason: string;
  }) => void;
  /** @deprecated Use `onRetry`. */
  onReconnect?: (info: {
    attempt: number;
    delayMs: number;
    reason: string;
  }) => void;
  /**
   * Display-only notices for a transient snapshot polling outage or recovery.
   */
  onNotice?: (message: string) => void;
};

/** @deprecated Use `RunsWatchOptions`. */
export type RunsTailOptions = RunsWatchOptions;

/** Read retained text with `client.runs.logs(...)`; use `runs.searchEvents` for structured filters and payloads. */
export type RunsLogsOptions = {
  /** Return the last `limit` retained lines in sequence order; default 200. Ignored when `all` is true. */
  limit?: number;
  /** Page through every retained line. Cannot combine with `failed`; sampling or retention loss cannot be recovered. */
  all?: boolean;
  /** Read a terminal-failed run's last 20 retained lines, or fewer with `limit`. Retention loss returns an explicit association and warning. */
  failed?: boolean;
  /**
   * Continue with the next OLDER page: pass a prior result's `nextCursor`.
   * The page holds the last `limit` stored lines before that cursor (with
   * `all`, every stored line before it).
   */
  cursor?: string;
};

/** Retained text for one run. Counts and retention flags describe the stored stream, not every original console call. */
export type RunsLogsResult = {
  /** Public run identity. */
  runId: string;
  /** Count tracked by the log stream; may exceed available bodies after retention truncation. */
  totalCount: number;
  /** Number of line bodies returned in `entries`. */
  returnedCount: number;
  /** First returned stored sequence, or null for an empty view. */
  firstSequence: number | null;
  /** Last returned stored sequence, or null for an empty view. */
  lastSequence: number | null;
  /** Tail/all: returned count is below total count. Failed: the stream lost bodies to retention. Check `logsTruncated` to distinguish retention loss from a selected tail. */
  truncated: boolean;
  /** Older stored lines exist before this page; `nextCursor` reads them. */
  hasMore: boolean;
  /**
   * Opaque cursor for the next older page (`runs.logs(id, { cursor })`),
   * null when this page reaches the oldest stored line. Absent for the failed
   * view, which is a complete designed window rather than a pageable slice.
   */
  nextCursor?: string | null;
  /** Formatted text lines in stored sequence order; structured context is available through event search. */
  entries: string[];
  /** Selected public log view. */
  view?: 'tail' | 'failed' | 'all';
  /** Whether entries are terminal context or the last pre-truncation lines. */
  association?: 'terminal_failure_window' | 'retained_before_truncation';
  /** Loud explanation when the terminal failure window was not retained. */
  warning?: string;
  /** Exact follow-up command when the selected view is degraded. */
  next?: { logs: string };
  /**
   * True when the run crossed the Run Log Stream retention cap: `totalCount`
   * keeps counting, but stored line bodies end at a loud truncation marker.
   */
  logsTruncated?: boolean;
};

/** Search existing events in your organization, newest first. Discover kinds and filters with `deepline runs logs --help`. */
export type RunsEventSearchOptions = {
  /** Inclusive UTC timestamp; defaults to one hour before the request. */
  since?: string;
  /** Exclusive UTC timestamp; defaults to the request time. A window spans at most seven days; event retention is seven days. */
  until?: string;
  /** Optional run filter. Omit to search across the active organization. */
  runId?: string;
  /** Exact Play name; HTTP query parameter `playName`, CLI `--play`. */
  playName?: string;
  /** Exact dotted event kind, such as `step.failed`. The catalog is discoverable with `runs logs --help`; future stored kinds are accepted too. */
  kind?: string;
  /** JSONPath equality joined with `&&`, at most eight predicates and 512 bytes. `eventId` selects an exact returned event; add `payloads` to retrieve its saved details. See `runs logs --help` for fields and examples. Missing fields do not match; status is not inferred from kind. HTTP `jsonpath`, CLI `--where`. */
  jsonpath?: string;
  /** Include available `eventPayload` details and receipt `payload` results; maximum ten events and 16 MiB. HTTP `payloads=true`, CLI `--payloads`. */
  includePayloads?: boolean;
  /** Page size: default 100, maximum 200; with payloads, default and maximum ten. */
  limit?: number;
  /** Opaque `nextCursor` from the preceding page. Reuse that page's returned since/until and the same filters and runtime scope. */
  cursor?: string;
  /** Explicit Preview selection requires the existing runtime credential. */
  runtime?: PlayRuntimeSelection;
};

/** One matching event. Optional fields and details are present only when recorded. */
export type RunsEventSearchEntry = {
  /** Stable event identity; also breaks ties in newest-first pagination. */
  eventId: string;
  /** Producer occurrence time as a UTC timestamp string. */
  occurredAt: string;
  /** Index ingestion time as a UTC timestamp string; may be later than occurrence. */
  ingestedAt: string;
  /** Public run identity associated with this observation. */
  runId: string;
  /** Recorded Play name. */
  playName: string;
  /** Exact dotted event kind, such as `step.failed`. */
  kind: string;
  /** Recorded log severity, or null on older events. Filter with `$.level == "error"`. */
  level: string | null;
  /** Log message preview of at most 2,048 characters, or null. Use text logs/export for the full retained line. */
  message: string | null;
  /** Recorded filter fields. SDK/API keep this nested; the CLI places these fields directly on each event. */
  searchDoc: Record<string, unknown>;
  /** Available event details when requested with `includePayloads`; dataset events contain metadata, not dataset rows. */
  eventPayload?: Record<string, unknown>;
  /** Retained work result for a receipt match when payloads are requested; null if unavailable. Other events need not carry this field. */
  payload?: RunsEventPayload | null;
};

/** One bounded search page. Continue using `nextCursor` and these exact time bounds; CLI-only counts and follow-up commands are not SDK/API fields. */
export type RunsEventSearchResult = {
  /** Matching observations in descending occurredAt/eventId order. */
  events: RunsEventSearchEntry[];
  /** Opaque continuation token, or null when no further page exists. */
  nextCursor: string | null;
  /** Resolved inclusive UTC bound, including a defaulted bound. */
  since: string;
  /** Resolved exclusive UTC bound, including a defaulted bound. */
  until: string;
};

/** Saved work result returned for a receipt event. Reading it does not execute the work again. */
export type RunsEventPayload = {
  /** Recorded terminal work outcome. */
  status: 'completed' | 'failed' | 'skipped';
  /** Saved result, including available sanitized call input/output details; failed-call records use kind: tool_call_evidence. Null when no output was retained. */
  output: unknown | null;
  /** Stored failure message, or null when absent. */
  error: string | null;
  /** Stored structured failure details, or null when absent. */
  errorPayload: unknown | null;
};

/** Structured log criteria; relative `since` values such as `1h` are resolved once. */
export type RunsLogCriteria = Omit<RunEventQueryCriteria, 'runId'> & {
  /** Read an explicitly authorized Preview scope using its runtime credential. */
  runtime?: PlayRuntimeSelection;
};

/** One structured log page; filters are evaluated before the page limit. */
export type RunsLogsQueryOptions = RunsLogCriteria & RunEventQueryOptions;
type RunQueryResultWithRuntime<T extends { query: NormalizedRunEventQuery }> =
  Omit<T, 'query'> & {
    query: T['query'] & { runtime?: PlayRuntimeSelection };
  };
type RunLogQueryResult<T extends { query: NormalizedRunEventQuery }> = Omit<
  T,
  'query'
> & {
  query: Omit<T['query'], 'runId'> & { runtime?: PlayRuntimeSelection };
};
export type RunsLogsQueryResult = RunLogQueryResult<RunEventLogsResult>;
export type RunsLogsCountResult = RunLogQueryResult<RunEventCountResult>;
export type RunsLogsSummaryOptions = RunsLogCriteria & RunEventSummaryOptions;
export type RunsLogsSummaryResult = RunLogQueryResult<RunEventSummaryResult>;

/** Event criteria may span the active organization or target one run. */
export type RunsEventsCriteria = RunsLogCriteria & { runId?: string };
export type RunsEventsListOptions = RunsEventsCriteria & RunEventQueryOptions;
export type RunsEventsListResult =
  RunQueryResultWithRuntime<RunEventEventsResult>;
export type RunsEventsCountResult =
  RunQueryResultWithRuntime<RunEventCountResult>;
export type RunsEventsSummaryResult =
  RunQueryResultWithRuntime<RunEventSummaryResult>;
export type RunsEventsSummaryOptions = RunsEventsCriteria &
  RunEventSummaryOptions;
export type RunsEventsFieldsOptions = { runtime?: PlayRuntimeSelection };

/**
 * Use `client.runs.logs(runId, options)` for the established text reader, or
 * `client.runs.logs.query/count/summarize/fields` for structured retained logs.
 */
export type RunsLogsNamespace = {
  (runId: string, options?: RunsLogsOptions): Promise<RunsLogsResult>;
  /** Filter retained log records, newest first, in one server page. */
  query: (
    runId: string,
    options?: RunsLogsQueryOptions,
  ) => Promise<RunsLogsQueryResult>;
  /** Exact count of matching retained records; does not list or retrieve payloads. */
  count: (
    runId: string,
    criteria?: RunsLogCriteria,
  ) => Promise<RunsLogsCountResult>;
  /** Group matching retained records; groups have their own continuation cursor. */
  summarize: (
    runId: string,
    options: RunsLogsSummaryOptions,
  ) => Promise<RunsLogsSummaryResult>;
  /** Discover filter fields, operators, types and availability. */
  fields: (options?: RunsEventsFieldsOptions) => Promise<RunEventFieldsResult>;
};

/**
 * Use `client.runs.events` for lifecycle, receipt and organization-wide events.
 * Omit `runId` to query the active organization's retained events.
 */
export type RunsEventsNamespace = {
  /** Filter retained events, newest first, in one server page. */
  list: (options?: RunsEventsListOptions) => Promise<RunsEventsListResult>;
  /** Exact count of matching retained events without listing or payload reads. */
  count: (criteria?: RunsEventsCriteria) => Promise<RunsEventsCountResult>;
  /** Group matching retained events with an independent continuation cursor. */
  summarize: (
    options: RunsEventsSummaryOptions,
  ) => Promise<RunsEventsSummaryResult>;
  /** Discover declared filter fields, operators, types and availability. */
  fields: (options?: RunsEventsFieldsOptions) => Promise<RunEventFieldsResult>;
};

/** Server page cap for GET /api/v2/runs/:runId/logs (ADR-0009). */
const RUN_LOGS_PAGE_LIMIT = 1_000;

/** Wire shape of one GET /api/v2/runs/:runId/logs page. */
type RunLogsPageResponse = {
  runId: string;
  totalLogCount: number;
  logsTruncated: boolean;
  lastStoredSeq: number;
  afterSeq: number;
  entries: Array<{ seq: number; line: string }>;
  firstSeq: number | null;
  lastSeq: number | null;
  hasMore: boolean;
  nextAfterSeq: number | null;
  view?: 'failed';
  association?: 'terminal_failure_window' | 'retained_before_truncation';
  warning?: string;
  next?: { logs: string };
};

/** One persisted runtime-sheet row returned by `client.runs.exportDatasetRows(...)`. */
export type PlaySheetRow = {
  key?: string;
  status?: string;
  data?: Record<string, unknown>;
  [key: string]: unknown;
};

/** Runtime-sheet rows and aggregate progress for one dataset/table namespace. */
export type PlaySheetRowsResult = {
  rows: PlaySheetRow[];
  scope?: { kind: 'database' } | { kind: 'run'; runId: string };
  /** Present when the server applied the counts-only aggregate mode. */
  summaryMode?: 'counts';
  summary?: {
    stats?: {
      total?: number;
      queued?: number;
      running?: number;
      completed?: number;
      failed?: number;
      [key: string]: unknown;
    };
    columns?: Record<string, unknown>;
    [key: string]: unknown;
  };
  customerDbUrl?: string;
  deltaCursor?: number;
};

export type PlayRunRowHistoryOptions = {
  playName: string;
  runId: string;
  tableNamespace: string;
  limit?: number;
  cursor?: string;
};

export type PlaySecretMetadata = {
  _id: string;
  orgId: string;
  scope: 'org' | 'play';
  playName?: string;
  name: string;
  note?: string;
  status: string;
  hasValue: boolean;
  createdAt: number;
  updatedAt: number;
  lastUsedAt?: number;
};

export type PlaySecretCheck = {
  ok: boolean;
  name: string;
  playName: string | null;
  reason: 'active' | 'missing' | 'disabled' | 'empty' | 'invalid_version';
  secret: PlaySecretMetadata | null;
};

/**
 * Use `client.runs` to watch, stop, query logs/events, and export durable dataset rows.
 *
 * @sdkReference client 020 client.runs
 */
export type RunsNamespace = {
  /** Read retained tool results in supplied key order. Use keys returned in exported evidence or execution metadata; search does not expose receipt keys. Never executes tools. */
  getReceipts: (
    runId: string,
    options: { keys: string[] },
  ) => Promise<import('./runs/receipts').RunToolReceiptsResponse>;
  /** Get current run status by public run id. */
  get: (runId: string, options?: RunsGetOptions) => Promise<PlayStatus>;
  /** Read one bounded page of direct children for an async launch. */
  children: (
    parentRunId: string,
    options: RunsChildrenOptions,
  ) => Promise<RunChildrenPage>;
  /**
   * @deprecated Use `client.runs.get(runId)` for status, progress, logs, and results.
   * This scalar-only reader remains for compatibility with existing callers.
   */
  status: (runId: string) => Promise<RunLifecycleStatus>;
  /** Explicitly read the retained original input (may include customer data). */
  input: (runId: string) => Promise<{
    runId: string;
    input: Record<string, unknown> | unknown[];
    bytes: number;
    sha256: string | null;
    replayedFromRunId: string | null;
  }>;
  /** Start a fresh run from a prior run's retained input and pinned revision. */
  rerun: (runId: string, options?: RerunOptions) => Promise<RerunPlayRunResult>;
  /** Continue a failed or cancelled run as the same run, reusing its completed work. */
  resume: (runId: string) => Promise<ResumePlayRunResult>;
  /** List runs for one play, optionally filtered by status. */
  list: (options: RunsListOptions) => Promise<PlayRunListItem[]>;
  /** Read one run page with total, offset, limit and completeness metadata. */
  listPage: (options: RunsListOptions) => Promise<RunsListPage>;
  /** Search/page workspace run history newest first; follow empty continuing pages. */
  history: (options?: RunsHistoryOptions) => Promise<RunsHistoryPage>;
  /** Poll run snapshots every two seconds until terminal status. */
  watch: (runId: string, options?: RunsWatchOptions) => Promise<PlayStatus>;
  /** @deprecated Use `watch`; retained as a source-compatible alias. */
  tail: (runId: string, options?: RunsTailOptions) => Promise<PlayStatus>;
  /** Call for the retained text tail, full stream (`all`) or terminal failure window (`failed`). Use `logs.query/count/summarize/fields` for structured filters and exact aggregates; see [run logs and events](run-events.md). */
  logs: RunsLogsNamespace;
  /** Use `events.list/count/summarize/fields` for lifecycle, receipt and organization-wide events; see [run logs and events](run-events.md). */
  events: RunsEventsNamespace;
  /** Search existing events across the active organization; default last hour, up to 200 events per page (ten with payloads). See [run logs and events](run-events.md) for the catalog, query fields and response types. */
  searchEvents: (
    options?: RunsEventSearchOptions,
  ) => Promise<RunsEventSearchResult>;
  /** Export persisted rows for a runtime-sheet dataset/table namespace. */
  exportDatasetRows: (input: {
    playName: string;
    tableNamespace: string;
    runId?: string;
    limit?: number;
    offset?: number;
    rowMode?: 'output' | 'all' | 'live';
    /** Keep exact row counts while omitting column aggregates with `counts`. */
    summary?: 'full' | 'counts';
    /** Cancel the page request, including its response body and retry waits. */
    signal?: AbortSignal;
  }) => Promise<PlaySheetRowsResult>;
  /** One immutable history page; incomplete legacy coverage stays explicit. */
  rowHistory: (
    input: PlayRunRowHistoryOptions,
  ) => Promise<RuntimeSheetRunRowMembershipPage>;
  /** Stop a running/waiting run. */
  stop: (
    runId: string,
    options?: { reason?: string },
  ) => Promise<StopPlayRunResult>;
  /**
   * Stop active runs across the current workspace, or with `dryRun: true`
   * enumerate the exact candidates without cancelling anything.
   */
  stopAll: {
    (
      options: StopAllRunsOptions & { dryRun: true },
    ): Promise<StopAllPlayRunsDryRunResult>;
    (
      options?: StopAllRunsOptions & { dryRun?: false },
    ): Promise<StopAllPlayRunsStopResult>;
    (options?: StopAllRunsOptions): Promise<StopAllPlayRunsResult>;
  };
};

/** Result of the bounded `/api/v2/runs/:runId/status` endpoint. */
export type RunLifecycleStatus =
  | { available: false; runId: string }
  | {
      available: true;
      runId: string;
      lifecycle: {
        status: PlayRunPublicStatus;
        updatedAt: number;
        startedAt: number | null;
        finishedAt: number | null;
      };
      /** Null for scheduler-only admission or a pre-expansion projection row. */
      source?: { ledgerNextSeq: number | null };
      /** One durable current activity, not proof that every row is blocked. */
      activity?: {
        kind: string;
        reason: string | null;
        targetKind: string | null;
        observedAt: number | null;
        nextAt: number | null;
      } | null;
      calls?: {
        logicalCalls: { value: number | null; confirmed: boolean };
        providerRequests: { value: number | null; confirmed: boolean };
        provider429s: { value: number | null; confirmed: boolean };
      };
      steps: {
        observed: number;
        running: number;
        completed: number;
        failed: number;
        skipped: number;
        confirmed: boolean;
      };
      /** Sums across observed step.progress records, not unique output rows. */
      mapStepWork: {
        sourceSteps: number;
        completed: { value: number | null; confirmed: boolean };
        total: { value: number | null; confirmed: boolean };
        failed: { value: number | null; confirmed: boolean };
        startedRows: { value: number | null; confirmed: boolean };
        activeRows: { value: number | null; confirmed: boolean };
        waitingRows: { value: number | null; confirmed: boolean };
        completedRows: { value: number | null; confirmed: boolean };
        supersededRows: { value: number | null; confirmed: boolean };
      };
      datasets: {
        observed: number;
        persistedRows: { value: number | null; confirmed: boolean };
        succeededRows: { value: number | null; confirmed: boolean };
        failedRows: { value: number | null; confirmed: boolean };
        complete: { value: boolean | null; confirmed: boolean };
      };
      wait: { kind: string | null; until: number | null; confirmed: boolean };
    };

/** Options for {@link RunsNamespace.stopAll} / {@link DeeplineClient.stopAllRuns}. */
export type StopAllRunsOptions = {
  /** Enumerate the candidate runs without cancelling or mutating anything. */
  dryRun?: boolean;
  /** Reason recorded with each stop request. Ignored by a dry run. */
  reason?: string;
};

/** Current mutable customer database namespace exposed as `client.db`. */
export type DbNamespace = {
  /** Run bounded SQL; unkeyed requests run once, while keyed requests retain one recovery identity across safe retries. */
  query: (input: CustomerDbQueryOptions) => Promise<CustomerDbQueryResult>;
  /** Describe the request, effects and recovery policy without executing SQL. */
  planQuery: (input: CustomerDbQueryOptions) => CustomerDbQueryPlan;
};

/**
 * Whether the current workspace can use Deepline Monitors, from
 * `GET /api/v2/monitors/access`. Reachable without monitor access (requires
 * only an authenticated session/API key); a denial is a normal 200 body, not a
 * 403.
 */
export type MonitorsAccessStatus = {
  has_access: boolean;
  reason?: string;
};

/**
 * The monitor tools catalog (deployable monitor TYPES), from
 * `GET /api/v2/monitors/tools`. Server-owned shape: describing one tool returns
 * the full payload/stream contract, while list mode returns the compact
 * inventory. Kept as an open record so the SDK does not have to bump when the
 * server enriches the catalog.
 */
export type MonitorsAvailableResult = {
  tools?: Array<Record<string, unknown>>;
  total?: number;
  returned?: number;
  is_truncated?: boolean;
  [key: string]: unknown;
};

/** Options for `client.monitors.available(...)` (list or describe mode). */
export type MonitorsAvailableOptions = {
  provider?: string;
  search?: string;
  limit?: number | string;
  /**
   * Request the full catalog contract in LIST mode (payload schemas + streams).
   * List mode is compact by default; ignored when describing a single tool.
   */
  full?: boolean;
  /** Ask the server for high-signal fields only. */
  compact?: boolean;
};

/**
 * Stable customer-facing Monitor/Fleet state.
 *
 * `provisioning` is a monitor whose create was recorded but that the provider
 * has not confirmed yet; it delivers no events and does not bill until it
 * becomes `active`. A Fleet is never `provisioning`. Provider cleanup,
 * retries, and failures are Monitor Job progress and must never be added to
 * this union. The `status` and `active` fields below are retained only as
 * deprecated compatibility aliases for older API responses.
 */
export type MonitorState =
  | 'active'
  | 'provisioning'
  | 'billing_suspended'
  | 'disabled';

/** List filters accepted by the canonical state surface. */
export type MonitorStateFilter = MonitorState | 'all';

/** The pre-state list filter retained for installed-client compatibility. */
export type LegacyMonitorStatusFilter = 'active' | 'inactive' | 'all';

/** One deployed monitor row returned by `client.monitors.list(...)`. */
export type MonitorListEntry = {
  key?: string;
  monitor_key?: string;
  /** Canonical customer-facing lifecycle state. */
  state?: MonitorState;
  /** @deprecated Use state. `inactive` is projected as `disabled`. */
  status?: string;
  tool?: string;
  /** Generic provider-authored event category for this deployed monitor. */
  type?: string;
  name?: string;
  configured?: boolean;
  active?: boolean;
  provider?: string;
  output_table?: string | null;
  webhook_state?: string;
  last_received_event?: string | null;
  bound_plays?: Array<Record<string, unknown>>;
  consumer_health_truncated?: boolean;
  [key: string]: unknown;
};

/**
 * Deployed-monitor registry page from `GET /api/v2/monitors/deployed`. `total`
 * is the TRUE registry count for the status filter, not this page's size; page
 * past a truncated result with `next_cursor`.
 */
export type MonitorsListResult = {
  monitors?: MonitorListEntry[];
  total?: number;
  returned?: number;
  has_more?: boolean;
  /** @deprecated Use has_more. */
  is_truncated?: boolean;
  next_cursor?: string | null;
  /** Canonical state filter echoed by newer servers. */
  state_filter_applied?: MonitorStateFilter;
  /** Canonical state counts. */
  state_summary?: Array<{ state: MonitorState; count: number }>;
  /** Whether state_summary counts this page or the full applied state filter. */
  state_summary_scope?: 'page' | 'filter_total';
  /** @deprecated Use state_filter_applied. */
  status_filter_applied?: string;
  /** @deprecated Use state_summary. */
  status_summary?: Array<{ status: string; count: number }>;
  include_consumers?: boolean;
  [key: string]: unknown;
};

/** Options for `client.monitors.list(...)`. */
export type MonitorsListOptions = {
  /** Canonical customer state filter; active is the default. */
  state?: MonitorStateFilter;
  /** @deprecated Use state. `inactive` remains accepted for old servers. */
  status?: LegacyMonitorStatusFilter | (string & {});
  limit?: number | string;
  /** Page past a truncated result using a prior response's `next_cursor`. */
  cursor?: string;
  /** @deprecated Accepted as a no-op for compatibility. */
  compact?: boolean;
  /** Include bounded current SQL-listener delivery/run health (requires limit <= 20). */
  includeConsumers?: boolean;
};

/** Options for `client.monitors.ledger(...)`. */
export type MonitorsLedgerOptions = {
  /** Search name, key, subject, signal and deploy filters. */
  search?: string;
  /** Customer statuses to include; every status except `stopped` by default. */
  states?: string[];
  /** Signal keys, as the response's `signals[].key` lists them. */
  signals?: string[];
  /** A Play definition id, or `none` for monitors no Play listens to. */
  play?: string;
  /** `findings` orders by the most findings in `window`. */
  sort?: 'recent' | 'installed' | 'name' | 'findings';
  /** The span each row's findings count covers; `30d` by default. */
  window?: '1d' | '7d' | '30d' | '90d' | '1y';
  limit?: number | string;
  cursor?: string;
};

/** The Monitors list page: rows plus counts, options and failing Plays. */
export type MonitorsLedgerResult = Record<string, unknown> & {
  monitors?: Array<Record<string, unknown>>;
  total?: number;
  next_cursor?: string | null;
};

/**
 * Server-owned monitor payload shapes returned by the deploy/check/get/mutation
 * endpoints. Kept as open records because the render layer and the endpoints
 * own the exact field set (output contracts, pricing, reuse candidates, delete
 * plans, dependents) and it must not require an SDK bump to evolve.
 */
export type MonitorCheckResult = Record<string, unknown>;

export type MonitorPreviewOptions = {
  /** Sample size, 1-3. The server default is 3. */
  limit?: number;
  /** Reuse to recover one preview's result; a new key is a new, paid preview. */
  idempotencyKey?: string;
};

/** A preview's sample and charge, plus the key that identifies it. */
export type MonitorPreviewResult = Record<string, unknown> & {
  idempotency_key: string;
};
export type MonitorDeployResult = Record<string, unknown>;
/** Field-level monitor capability spec returned by `client.monitors.get(...)`. */
export type MonitorSpec = {
  /** Whether Deepline has a current capability spec for this deployed monitor. */
  available?: boolean;
  tool?: string;
  description?: string;
  fields?: Array<Record<string, unknown>>;
  conditional_requirements?: Array<Record<string, unknown>>;
  /** Present when a legacy monitor has no current capability spec. */
  message?: string;
};

/** One deployed-monitor read. The server may add monitor-specific fields. */
export type MonitorDetail = Record<string, unknown> & {
  /** Canonical customer-facing lifecycle state. */
  state?: MonitorState;
  /** @deprecated Use state. */
  status?: string;
  /** @deprecated Use state. */
  active?: boolean;
  monitor_spec?: MonitorSpec;
};
export type MonitorDependents = Record<string, unknown>;
export type MonitorUpdateChangeSummary = {
  definition: {
    changed: Array<{ path: string; before: unknown; after: unknown }>;
    unchanged: Array<{ path: string; value: unknown }>;
  };
  storage: {
    existing_rows_preserved: true;
    unchanged_destinations: Array<{
      output: string;
      table: string;
      row_type: string | null;
    }>;
    changed_destinations: Array<{
      output: string;
      before_table: string | null;
      after_table: string | null;
    }>;
  };
  upstream: {
    resource_replaced: boolean;
    strategy:
      | 'unchanged'
      | 'create_then_delete_previous'
      | 'deferred_until_reactivation';
  };
};
export type MonitorUpdateResult = {
  change_summary?: MonitorUpdateChangeSummary;
  [key: string]: unknown;
};
export type MonitorDeleteResult = Record<string, unknown>;
export type MonitorReactivateResult = Record<string, unknown>;
export type MonitorTestResult = Record<string, unknown>;

/**
 * @deprecated Monitor tests are always validation-only. `dispatch` and
 * `validationOnly: false` are rejected before a request is made.
 */
export type MonitorTestOptions = {
  validationOnly?: boolean;
  dispatch?: boolean;
};
export type MonitorValidateResult = Record<string, unknown>;

/**
 * Server-owned fleet response envelope.
 *
 * The server computes the canonical customer `state` and the SDK never
 * recomputes it. Transitional convergence details remain in the owning Fleet
 * Job; the deprecated `status` alias is retained only for installed clients.
 */
export type MonitorFleetResult = Record<string, unknown> & {
  /** Canonical customer-facing Fleet state. */
  state?: MonitorState;
  /** @deprecated Fleet operation/convergence status; use state + jobs. */
  status?: string;
};

/** Standalone SDK mirror of the server-owned Monitor Job contract. */
export const MONITOR_JOB_STATES = [
  'queued',
  'running',
  'cancelling',
  'succeeded',
  'failed',
  'cancelled',
] as const;
export type MonitorJobState = (typeof MONITOR_JOB_STATES)[number];

export const MONITOR_JOB_PHASES = [
  'queued',
  'provider_create',
  'provider_readback',
  'reconciliation',
  'completed',
] as const;
export type MonitorJobPhase = (typeof MONITOR_JOB_PHASES)[number];

export const MONITOR_JOB_RECONCILIATION_STATES = [
  'pending',
  'aligned',
  'partial',
  'mismatched',
] as const;
export type MonitorJobReconciliationState =
  (typeof MONITOR_JOB_RECONCILIATION_STATES)[number];

export type MonitorJobProjection = {
  id: string;
  /** Durable provider operation identity used to trace Fleet/deploy work. */
  operation_id?: string;
  kind: 'batch_deploy' | 'fleet_deploy';
  state: MonitorJobState;
  /** Terminal semantic result; `blocked` is a deterministic Fleet/input refusal, not a provider outage. */
  outcome?: 'blocked' | 'failed';
  phase: MonitorJobPhase;
  target: {
    monitor_key?: string;
    batch_id?: string;
    generation?: number;
    fleet_id?: string;
  };
  counts: {
    requested: number;
    valid: number;
    queued: number;
    running: number;
    created: number;
    updated: number;
    removed: number;
    unchanged: number;
    settled: number;
    verified: number;
    failed: number;
    cancelled_before_start: number;
  };
  reconciliation: {
    state: MonitorJobReconciliationState;
    expected_bindings: number;
    observed_bindings: number;
    active_mismatches: number;
    provider_only_matching_markers: number;
    next?: string;
  };
  error?: string;
};

export type MonitorNamedBatchProjection = {
  id: string;
  state: 'active' | 'stopped';
  generation: number;
  desired_count: number;
  retained_count: number;
  last_job_id: string;
  updated_at: string;
};

/** Shared typed envelope for immutable batch and desired-set Monitor Jobs. */
export type MonitorJobResult = {
  ok?: boolean;
  job?: MonitorJobProjection;
  batch?: MonitorNamedBatchProjection;
  /** Same durable operation identity as `job.operation_id`, for log reads. */
  operation_id?: string;
  logs?: Array<{
    level: string;
    phase: string;
    message: string;
    monitor_key?: string;
    at: string;
  }>;
  replayed?: boolean;
  already_terminal?: boolean;
  next?: string;
  [key: string]: unknown;
};

export type MonitorJobDeployOptions = {
  /** Stable retry key; the server binds it to the submitted immutable set. */
  idempotencyKey?: string;
};

export type MonitorLifecycleOptions = {
  /** Return the plan without changing provider state. */
  dryRun?: boolean;
  /** Stable retry key for durable start/stop work. */
  idempotencyKey?: string;
};

export type MonitorJobLogsOptions = { limit?: number };

export type MonitorJobWaitOptions = {
  timeoutMs?: number;
  pollIntervalMs?: number;
  onProgress?: (payload: MonitorJobResult) => void;
};

export type MonitorJobsNamespace = {
  get: (jobId: string) => Promise<MonitorJobResult>;
  logs: (
    jobId: string,
    options?: MonitorJobLogsOptions,
  ) => Promise<MonitorJobResult>;
  cancel: (jobId: string) => Promise<MonitorJobResult>;
  wait: (
    jobId: string,
    options?: MonitorJobWaitOptions,
  ) => Promise<MonitorJobResult>;
};

/** Server-computed fleet verdict. Never derived client-side. */
export type MonitorFleetStatus =
  | 'converging'
  | 'converged'
  | 'degraded'
  | 'deactivating'
  | 'deactivated'
  | 'billing_suspending'
  | 'billing_suspended'
  | 'billing_reactivating';

export type MonitorFleetSyncOptions = {
  /** Return the plan without changing fleet state (`dry_run: true`). */
  dryRun?: boolean;
  /** Optimistic concurrency: refuse the write unless the fleet is at this generation. */
  expectedGeneration?: number;
  /** Stable retry key; generated by the caller when omitted. */
  idempotencyKey?: string;
};

export type MonitorFleetGetOptions = {
  /** Include bounded per-member drift rows. */
  drift?: boolean;
  /** Maximum drift rows to return. */
  limit?: number;
};

export type MonitorFleetDeactivateOptions = {
  /** Return the blast radius without deactivating anything. */
  dryRun?: boolean;
  idempotencyKey?: string;
};

export type MonitorFleetReactivateOptions = {
  idempotencyKey?: string;
};

export type MonitorFleetWaitOptions = {
  /** Give up after this long. Default 10 minutes. */
  timeoutMs?: number;
  /** Poll cadence. Default 2 seconds. */
  pollIntervalMs?: number;
  /** Called with every polled snapshot, including the terminal one. */
  onProgress?: (payload: MonitorFleetResult) => void;
  /**
   * Which terminal state ends the wait. `converged` (default) also stops on
   * `degraded`, `deactivated`, and `billing_suspended`; `deactivated` stops on
   * `deactivated`, `degraded`, and `billing_suspended`. A timeout is not an
   * error: the last snapshot is returned and the caller reads `status` to
   * decide the verdict.
   */
  until?: 'converged' | 'deactivated';
};

/** A durable monitor batch can name a small key set, a query target, or one Fleet. */
export type MonitorBatchScope =
  | { kind: 'keys'; monitorKeys: string[] }
  | {
      kind: 'target';
      target: 'all' | 'all-active' | 'billing-suspended' | 'needs-repair';
    }
  | { kind: 'fleet'; fleetId: string };

export type MonitorBatchExistingSubmitOptions = {
  kind: 'audit' | 'deactivate' | 'reactivate' | 'repair';
  scope: MonitorBatchScope;
  dryRun?: boolean;
  /**
   * A declared policy reason for target deactivation. Omit it for an explicit
   * customer-owned key teardown; absent is the durable customer intent.
   */
  deactivationReason?: string;
  /** Stable retry key. Reusing it joins the original durable operation. */
  idempotencyKey: string;
};

/** Complete definitions, one JSON object per line; uploaded as bounded shards. */
export type MonitorBatchDeploySubmitOptions = {
  kind: 'deploy';
  manifestNdjson: string;
  dryRun?: boolean;
  /** Stable retry key. Reusing it joins the same content-addressed manifest. */
  idempotencyKey: string;
};

export type MonitorBatchSubmitOptions =
  | MonitorBatchExistingSubmitOptions
  | MonitorBatchDeploySubmitOptions;

export type MonitorBatchOperationResult = {
  ok?: boolean;
  rejoined?: boolean;
  operation: {
    runId: string;
    kind:
      | 'audit'
      | 'converge'
      | 'deactivate'
      | 'reactivate'
      | 'deploy'
      | 'repair'
      | 'named_batch';
    state: 'running' | 'retry_scheduled' | 'completed' | 'failed' | 'cancelled';
    dryRun: boolean;
    scope: unknown;
    submittedAt: number;
    updatedAt: number;
    deactivationReason?: string;
    nextAttemptAt?: number;
    completedAt?: number;
    summary?: Record<string, unknown>;
    lastError?: string;
  };
  results?: {
    page: Array<Record<string, unknown>>;
    isDone: boolean;
    continueCursor: string;
  };
};

export type MonitorFleetsNamespace = {
  /**
   * Primary table-backed Fleet command. It has the same idempotent PUT
   * contract as `sync`; `sync` remains for installed-client compatibility.
   */
  deploy: (
    definitionOrId: string | MonitorFleetDefinition,
    options?: MonitorFleetSyncOptions,
  ) => Promise<MonitorFleetResult>;
  /**
   * Compatibility alias for `deploy`. Pass a definition to admit new source
   * of truth; pass a fleet id to re-plan from the stored definition.
   */
  sync: (
    definitionOrId: string | MonitorFleetDefinition,
    options?: MonitorFleetSyncOptions,
  ) => Promise<MonitorFleetResult>;
  /** One fleet by id, or every fleet in the workspace when the id is omitted. */
  get: (
    fleetId?: string,
    options?: MonitorFleetGetOptions,
  ) => Promise<MonitorFleetResult>;
  /** Every fleet in the workspace. */
  list: () => Promise<MonitorFleetResult>;
  /** Deactivate a fleet and the monitors it owns. */
  deactivate: (
    fleetId: string,
    options?: MonitorFleetDeactivateOptions,
  ) => Promise<MonitorFleetResult>;
  /** Explicitly recreate a fleet after a credit-triggered suspension. */
  reactivate: (
    fleetId: string,
    options?: MonitorFleetReactivateOptions,
  ) => Promise<MonitorFleetResult>;
  /** Customer-facing alias for `reactivate`. */
  start: (
    fleetId: string,
    options?: MonitorFleetReactivateOptions,
  ) => Promise<MonitorFleetResult>;
  /** Customer-facing alias for `deactivate`. */
  stop: (
    fleetId: string,
    options?: MonitorFleetDeactivateOptions,
  ) => Promise<MonitorFleetResult>;
  /** Poll the fleet until the server reports a terminal status (or the timeout elapses). */
  waitForConvergence: (
    fleetId: string,
    options?: MonitorFleetWaitOptions,
  ) => Promise<MonitorFleetResult>;
};

export type MonitorBatchNamespace = {
  /** Deploy an immutable one-off list through the common Monitor Job engine. */
  deploy: (
    definitions: MonitorDefinition[],
    options?: MonitorJobDeployOptions,
  ) => Promise<MonitorJobResult>;
  submit: (
    options: MonitorBatchSubmitOptions,
  ) => Promise<MonitorBatchOperationResult>;
  get: (
    operationId: string,
    options?: { cursor?: string | null },
  ) => Promise<MonitorBatchOperationResult>;
};

export type MonitorNamedBatchOptions = {
  idempotencyKey?: string;
  expectedGeneration?: number;
};

export type MonitorNamedBatchesNamespace = {
  sync: (
    batchId: string,
    definitions: MonitorDefinition[],
    options?: MonitorNamedBatchOptions,
  ) => Promise<MonitorJobResult>;
  start: (
    batchId: string,
    options?: Pick<MonitorNamedBatchOptions, 'idempotencyKey'>,
  ) => Promise<MonitorJobResult>;
  stop: (
    batchId: string,
    options?: Pick<MonitorNamedBatchOptions, 'idempotencyKey'>,
  ) => Promise<MonitorJobResult>;
  get: (batchId: string) => Promise<MonitorJobResult>;
};

/**
 * Delivery and convergence health for a scope, from
 * `GET /api/v2/monitors/health`.
 *
 * Counts and bounded samples on purpose. It is also what `--watch` polls, so
 * its shape is fixed independently of the transport: phase 2b publishes the
 * same object over a reactive subscription without changing this contract.
 */
export type MonitorsHealth = {
  ok?: boolean;
  scope: { org_id: string; fleet_id?: string };
  scanned: number;
  /** True when the scope was larger than one bounded read; counts are partial. */
  truncated: boolean;
  /**
   * A durable whole-scope snapshot is rebuilding. Counts remain intentionally
   * partial until it completes; older servers omit this additive field.
   */
  refresh?: {
    state: 'running' | 'completed';
    started_at: number;
    updated_at: number;
    completed_at: number | null;
  };
  desired: { active: number; inactive: number; unset: number };
  observed: {
    active: number;
    inactive: number;
    missing: number;
    unknown: number;
    unset: number;
  };
  converged: number;
  needs_repair: number;
  /**
   * Unknown records without an upstream resource id. Use the exact inventory
   * reconciler to align them; ordinary repair never guesses an identity.
   */
  alignment_required: number;
  /** Observed active, but nothing delivered inside `silent_window_days`. */
  silent: number;
  silent_window_days: number;
  deactivation_reasons: Array<{
    reason: string;
    count: number;
    summary: string | null;
    resolution: string | null;
  }>;
  worst_offenders: Array<{
    monitor_key: string;
    tool: string;
    last_event_at: number | null;
    observed_at: number | null;
    provider_resource_id: string | null;
  }>;
  /** Bounded current durable monitor work, if the server supports it. */
  batch_operations?: Array<{
    run_id: string;
    kind:
      | 'audit'
      | 'converge'
      | 'deactivate'
      | 'named_batch'
      | 'reactivate'
      | 'repair'
      | 'deploy';
    state: 'running' | 'retry_scheduled';
    updated_at: number;
    next_attempt_at?: number;
    summary?: Record<string, unknown>;
  }>;
  /** Bounded sample explaining why normal audit did not settle the row. */
  unaudited_monitors: Array<{
    monitor_key: string;
    tool: string;
    observed: 'unknown' | null;
    observed_at: number | null;
    provider_resource_id: string | null;
    reason:
      | 'not_yet_audited'
      | 'missing_provider_resource_id'
      | 'provider_observation_unknown';
  }>;
};

/** One bounded audit pass, from `POST /api/v2/monitors/audit`. */
export type MonitorsAuditResult = {
  ok?: boolean;
  scope: { org_id: string; fleet_id?: string };
  audit: {
    scanned: number;
    asked: number;
    observed: {
      active: number;
      inactive: number;
      missing: number;
      unknown: number;
    };
    /** Observations a concurrent settle overtook. Not an error. */
    stale: number;
    absent: number;
    /** Capabilities that declare no batch read, so nothing could be asked. */
    unauditable_capabilities: string[];
    complete: boolean;
    /** Non-null when the scope was larger than one pass. Pass it back. */
    cursor: string | null;
  };
  health: MonitorsHealth;
};

/** One repair pass or plan, from `POST /api/v2/monitors/repair`. */
export type MonitorsRepairResult = {
  ok?: boolean;
  dry_run: boolean;
  scope: { org_id: string; fleet_id?: string };
  repair: {
    scanned: number;
    queued: number;
    plan: Array<{
      monitor_key: string;
      action: 'create' | 'remove';
      desired: 'active' | 'inactive';
      observed: 'active' | 'inactive' | 'missing';
      deactivation_reason?: string;
    }>;
    /** Disagreeing monitors no fleet owns; the convergence driver cannot move them. */
    unowned: string[];
    /** Monitors nobody has observed. Run audit first. */
    unaudited: string[];
    /**
     * Monitors with a provider operation still in flight. Deepline's own
     * convergence loop owns these; repair leaves them alone rather than risk
     * asking the provider to do the same work twice.
     */
    fenced: string[];
    refused: string[];
    complete: boolean;
  };
  health: MonitorsHealth;
};

/**
 * Use `client.monitors` for the /api/v2/monitors resource family.
 * Every `deepline monitors` verb maps here. Author a definition with {@link defineMonitor},
 * then check/deploy/list/get/update/delete/reactivate through this namespace.
 *
 * @sdkReference client 040 client.monitors
 */
export type MonitorsNamespace = {
  /** Whether the current workspace can use monitors (`{ has_access, reason }`). */
  status: () => Promise<MonitorsAccessStatus>;
  /**
   * The deployable monitor tools catalog. Call with no tool id for the list, or
   * with a tool id (positional or `{ tool }`) to describe one tool's full
   * payload/stream contract.
   */
  available: (
    toolIdOrOptions?: string | (MonitorsAvailableOptions & { tool?: string }),
    options?: MonitorsAvailableOptions,
  ) => Promise<MonitorsAvailableResult>;
  /** Validate a monitor definition without deploying it (no spend). */
  check: (definition: MonitorDefinition) => Promise<MonitorCheckResult>;
  /**
   * Sample a few recent matches for a definition before deploying it. Spends
   * Deepline credits per returned update. Reuse `idempotencyKey` to recover a
   * lost result without paying again; omit it for a new preview.
   */
  preview: (
    definition: MonitorDefinition,
    options?: MonitorPreviewOptions,
  ) => Promise<MonitorPreviewResult>;
  /** Deploy a monitor from a definition. May spend Deepline credits. */
  deploy: (
    definition: MonitorDefinition,
    options?: { dryRun?: boolean },
  ) => Promise<MonitorDeployResult>;
  /** Set the desired definition for one stable monitor key. */
  sync: (
    definition: MonitorDefinition,
    options?: MonitorLifecycleOptions,
  ) => Promise<MonitorJobResult | MonitorDeployResult>;
  /** List deployed monitors (active by default). Use `state` to filter the
   * four customer states (`active`, `provisioning`, `billing_suspended`,
   * `disabled`); `status` is retained for older servers.
   * `includeConsumers` requires a limit of 20 or fewer. */
  list: (options?: MonitorsListOptions) => Promise<MonitorsListResult>;
  /** Fetch one deployed monitor by public key with bounded current listener health. */
  get: (key: string) => Promise<MonitorDetail>;
  /** The Monitors list: monitors with status, radar filters and the Plays
   * each triggers, plus status counts and failing Plays. */
  ledger: (options?: MonitorsLedgerOptions) => Promise<MonitorsLedgerResult>;
  /** One monitor as its Monitors page shows it, with every Play it triggers. */
  ledgerGet: (key: string) => Promise<Record<string, unknown>>;
  /** One page of a monitor's delivered findings, newest first, with each
   * Play's recorded run per finding. */
  ledgerFindings: (
    key: string,
    options?: { cursor?: string },
  ) => Promise<Record<string, unknown>>;
  /** Test a deployed monitor's callback envelope without side effects. */
  test: (
    key: string,
    payload: Record<string, unknown>,
    options?: MonitorTestOptions,
  ) => Promise<MonitorTestResult>;
  validate: (key: string) => Promise<MonitorValidateResult>;
  /** List the published plays depending on one monitor's output streams. */
  dependents: (key: string) => Promise<MonitorDependents>;
  /** Update a deployed monitor by public key. */
  update: (
    key: string,
    patch: Record<string, unknown>,
  ) => Promise<MonitorUpdateResult>;
  /** Delete a deployed monitor and its upstream provider resource. `dryRun` returns the delete plan. */
  delete: (
    key: string,
    options?: { dryRun?: boolean },
  ) => Promise<MonitorDeleteResult>;
  /** Reactivate a disabled monitor. `dryRun` returns the reactivation cost. */
  reactivate: (
    key: string,
    options?: { dryRun?: boolean },
  ) => Promise<MonitorReactivateResult>;
  /** Explicitly apply the retained definition for a stopped monitor. */
  start: (
    key: string,
    options?: MonitorLifecycleOptions,
  ) => Promise<MonitorJobResult | MonitorBatchOperationResult>;
  /** Converge one monitor to inactive while retaining its definition. */
  stop: (
    key: string,
    options?: MonitorLifecycleOptions,
  ) => Promise<MonitorJobResult | MonitorBatchOperationResult>;
  /**
   * Re-read what the provider holds onto the monitors that claim it. Bounded
   * and idempotent: pass `cursor` back while `audit.cursor` is non-null.
   */
  audit: (options?: {
    fleetId?: string;
    cursor?: string | null;
  }) => Promise<MonitorsAuditResult>;
  /**
   * Converge the monitors whose desired and observed states disagree.
   * `dryRun` returns the same plan without queueing anything.
   */
  repair: (options?: {
    fleetId?: string;
    dryRun?: boolean;
  }) => Promise<MonitorsRepairResult>;
  /** Delivery and convergence health for the workspace or one fleet. */
  health: (options?: { fleetId?: string }) => Promise<MonitorsHealth>;
  /** Define, reconcile, and control table-backed monitor fleets. */
  fleets: MonitorFleetsNamespace;
  /** Deploy an immutable one-off list through the common Monitor Job engine. */
  batch: MonitorBatchNamespace;
  /** Reconcile and control a stable named static Batch. */
  batches: MonitorNamedBatchesNamespace;
  /** Read, wait for, inspect, or cancel Monitor Jobs. */
  jobs: MonitorJobsNamespace;
};

/** One credit grant pool reported by the billing subscription status endpoint. */
export type BillingCreditPool = {
  /** Stable grant identity; optional when talking to an older server. */
  grant_id?: string;
  pool: string;
  credits_remaining: number;
  credits_granted: number;
  source: string;
  cycle_key: string | null;
  effective_at: string;
};

/**
 * Subscription state for the active workspace, from
 * `GET /api/v2/billing/subscription/status`. All amounts are Deepline credits
 * and Deepline-facing USD — never provider spend.
 */
export type BillingSubscriptionStatus = {
  org_id: string;
  plan_version_id: string;
  plan_name: string;
  plan_family_id: string;
  /** Whether a Stripe subscription backs the active plan. */
  subscribed: boolean;
  price_usd: number | null;
  price_interval: string | null;
  monthly_grant_credits: number;
  assigned_by: string;
  assigned_at: string | null;
  credit_pools: BillingCreditPool[];
  pooled_credits_remaining: number;
  /** End of the current paid period (ISO timestamp), when Stripe is reachable. */
  current_period_end: string | null;
  /** True when a cancellation is already scheduled for period end. */
  cancel_at_period_end: boolean | null;
  stripe_status: string | null;
};

/**
 * Result of `POST /api/v2/billing/subscription/cancel`. Cancellation is always
 * at period end: the customer keeps the cycle they paid for and every
 * remaining credit. `undo_cancel` reverses a pending cancellation.
 */
export type BillingSubscriptionCancelResult = {
  org_id: string;
  subscription_id: string;
  cancel_at_period_end: boolean;
  current_period_end: string | null;
  status: string;
  message: string;
};

/**
 * One customer-facing billing history entry from
 * `GET /api/v2/billing/invoices`: a subscription invoice or a one-time credit
 * purchase receipt. Amounts are what the customer paid — never provider spend.
 */
export type BillingInvoiceEntry = {
  kind: 'invoice' | 'receipt';
  id: string;
  created_at: string;
  description: string;
  amount_cents: number;
  currency: string;
  status: string;
  /** Stripe-hosted page (invoice or card receipt). */
  url: string | null;
  /** Direct PDF when Stripe provides one (invoices only). */
  pdf_url: string | null;
  /** Stripe-hosted invoice page when this purchase has an invoice. */
  invoice_url?: string | null;
  /** Stripe-hosted card receipt when this purchase has one. */
  receipt_url?: string | null;
};

export type BillingInvoicesResult = {
  org_id: string;
  entries: BillingInvoiceEntry[];
};

export type TargetBillingOperation = {
  id: string;
  state: string;
  version: number;
  next_action?: string | null;
};

export type TargetBillingPlan = {
  sku:
    | 'payg-v1'
    | 'builder-v1'
    | 'growth-v1'
    | 'growth-canary-v1'
    | 'team-v1'
    | 'team-v2'
    | 'legacy-growth-v1';
  name: string;
  recurring_price_usd: number;
  /**
   * The first month's fee for switching to this plan when a first-month
   * discount is offered; null or absent means the list price.
   */
  first_month_price_usd?: number | null;
  interval: 'month' | 'year';
  included_credits: number;
  /** Offered benefit terms; omitted by older API deployments. */
  benefits?: Partial<BillingBenefitValues>;
  purchased_credit_price_usd: number;
  acquisition_enabled: boolean;
};

export type TargetBillingPlansResult = {
  org_id: string;
  plans: TargetBillingPlan[];
  current_plan_sku: string;
  pending_plan_sku: string | null;
  acquisition_enabled: boolean;
  enabled_offer_keys: TargetBillingPlan['sku'][];
};

export type TargetBillingStatusResult = {
  org_id: string;
  plan: {
    sku: string;
    name: string;
    recurring_price_usd: number | null;
    interval: string | null;
    included_credits: number | null;
  };
  state: string;
  changes_allowed: boolean;
  legacy_changes_allowed?: boolean;
  payment_state: string;
  recharge_state: string;
  billing_email?: string | null;
  /** Omitted when unavailable; null when no address has been saved. */
  billing_address?: {
    line1: string | null;
    line2: string | null;
    city: string | null;
    state: string | null;
    postal_code: string | null;
    country: string | null;
  } | null;
  collection_method?: 'charge_automatically' | 'send_invoice';
  payment_access_policy?: 'payment_required' | 'net_30' | 'net_60';
  plan_invoice?: {
    url: string | null;
    amount_usd: number;
    due_at: string | null;
    status: string | null;
  } | null;
  outstanding_invoice?: {
    amount_usd: number;
    due_at: string;
    state: 'open' | 'cancelling';
  } | null;
  next_action: string | null;
  pending_plan_sku: string | null;
  /** Saved transition boundary; optional for older servers. */
  pending_plan_starts_at?: string | null;
  /** Next cycle boundary from the current Contract’s retained cadence. */
  current_period_end?: string | null;
  as_of: string | null;
};

export type TargetAutoRechargeResult = {
  org_id: string;
  enabled: boolean;
  available: boolean;
  reason: string | null;
  threshold_credits: number | null;
  refill_to_credits: number | null;
  rolling_limit_cents: null;
  purchase_limit_cents?: number | null;
  purchase_limit_credits?: number | null;
  rolling_committed_cents?: number;
  rolling_committed_credits?: number;
};

export type TargetAutoRechargeUpdateOptions =
  | {
      enabled: false;
      idempotencyKey: string;
    }
  | {
      enabled: true;
      thresholdCredits: number;
      refillToCredits: number;
      /** @deprecated Converted to credits at the API boundary. Use purchaseLimitCredits. */
      purchaseLimitCents?: number | null;
      /** Maximum credits purchased automatically over rolling 30 days; zero stops purchases. */
      purchaseLimitCredits?: number | null;
      idempotencyKey: string;
    };

export type TargetBillingMutationResult = {
  data: Record<string, unknown>;
  operation: TargetBillingOperation;
  request_id?: string;
};

export type TargetBillingPlanTransitionOptions =
  | {
      action: 'start_or_change';
      targetPlanSku:
        | 'payg-v1'
        | 'builder-v1'
        | 'growth-v1'
        | 'growth-canary-v1'
        | 'team-v1';
      billingEmail?: string;
      idempotencyKey: string;
    }
  | {
      action: 'cancel' | 'undo_cancel';
      targetPlanSku?: never;
      idempotencyKey: string;
    };

/** Saved payment method details returned by one-click billing top-up. */
export type BillingPaymentMethodSummary = {
  brand?: string | null;
  last4?: string | null;
  exp_month?: number | null;
  exp_year?: number | null;
  label?: string | null;
};

/**
 * Result of `POST /api/v2/billing/top-up`: a saved-card charge and purchased
 * Deepline credit grant for the active workspace.
 */
export type BillingTopUpResult = {
  ok: true;
  credits: number;
  amount_cents: number;
  currency: string;
  balance: number;
  stripe_payment_intent_id: string;
  payment_method?: BillingPaymentMethodSummary | null;
};

/** Operation receipt for a top-up that may still be awaiting payment. */
export type BillingTopUpReceipt =
  | (BillingTopUpResult & { status?: undefined })
  | {
      status: 'pending';
      operation_id: string;
      operation_state: 'payment_pending';
      requested_credits: number;
      amount_cents: number;
      currency: string;
    }
  | {
      status: 'applied';
      operation_id: string;
      operation_state: 'applied';
      applied_credits: number;
      amount_cents: number;
      currency: string;
      balance?: number;
      stripe_payment_intent_id?: string;
    };

/** One published plan from `GET /api/v2/billing/catalog/current`. */
export type BillingPlanEntry = {
  plan_family_id: string;
  plan_version_id: string;
  public_name: string;
  price_usd: number | null;
  price_interval: string | null;
  monthly_grant_credits: number;
  rollover: { mode: string; max_credits?: number };
  /** Whether the plan can be purchased via subscription checkout. */
  acquirable: boolean;
};

/** One usage metric published in the billing catalog. */
export type BillingMeterEntry = {
  id: string;
  name: string;
};

/** @deprecated Use BillingMeterEntry. Retained for wire/API alias compatibility. */
export type BillingMetricEntry = BillingMeterEntry;

/** The caller's active plan as reported by the plans endpoint. */
export type BillingActivePlan = {
  plan_family_id: string;
  plan_version_id: string;
  public_name: string;
  rate_card_id: string;
  assigned_by: string;
  assigned_at: string | null;
  has_subscription: boolean;
};

/**
 * Published plans plus the caller's active plan, from
 * `GET /api/v2/billing/catalog/current`. Answers "what plans exist and what
 * am I on". All amounts are Deepline credits and Deepline-facing USD — never
 * provider spend.
 */
export type BillingPlansResult = {
  catalog_id: string;
  catalog_version: string;
  active_plan: BillingActivePlan;
  plans: BillingPlanEntry[];
  meters: BillingMeterEntry[];
  /** @deprecated Use meters. Retained for installed SDK compatibility. */
  metrics: BillingMetricEntry[];
};

export type WorkspaceCreateResult = {
  org_id: string;
  org_name: string;
  org_slug: string;
  plan_sku: 'payg-v1';
  /**
   * The PAYG rate policy the workspace was provisioned onto, taken from the
   * catalog revision its operation pinned: v4 bound payg-rates-v2, v5 binds
   * the flat payg-rates-v3.
   */
  rate_policy_ref: 'payg-rates-v2' | 'payg-rates-v3';
  operation: {
    id: string;
    state: 'completed';
    replayed: boolean;
  };
  request_id?: string;
};

/** Deliberate workspace lifecycle operations. */
export type WorkspacesNamespace = {
  /** One page of current workspace memberships and effective grants. */
  members: (options?: { cursor?: string }) => Promise<{
    members: { id: string; userId: string; role: string; grants: string[] }[];
    cursor: string | null;
  }>;
  /** Replace a member's grants. Requires admin; ownership changes require owner. */
  setMemberGrants: (
    memberId: string,
    grants: string[],
  ) => Promise<{
    ok: boolean;
    memberId: string;
    role: string;
  }>;
  /** Create an additional workspace and provision its active PAYG Contract. */
  create: (options: {
    name: string;
    idempotencyKey: string;
  }) => Promise<WorkspaceCreateResult>;
};

/** One authenticated per-request usage event from `/api/v2/usage/events`. */
export type BillingUsageEvent = {
  id: string | null;
  provider: string;
  operation: string;
  status: string;
  request_id: string;
  billing_outcome_reason: string | null;
  credits: number | null;
  billing_mode: string | null;
  pricing_model: string | null;
  policy_id: string | null;
  created_at: string;
  /** Present when the original request is resolved through its canonical charge. */
  charge_state?: BillingRecentUsageEntry['charge_state'];
  /** Pending/unknown amounts are null; a final amount can be zero. */
  charge_finality?: BillingRecentUsageEntry['charge_finality'];
};

/** One raw event-history entry, with its original run attribution. */
export type BillingUsageEventListEntry = BillingUsageEvent & {
  auth_type: string;
  user_id: string | null;
  api_key_id: string | null;
  workflow_id: string | null;
  run_id: string | null;
  billing_run_id: string | null;
  execution_run_id: string | null;
  included_in_run_id: string | null;
  billing_scope: string | null;
};

/** One page of event history; follow next_cursor until null, even for empty pages. */
export type BillingUsageEventsResult = {
  org_id: string;
  run_id: string | null;
  next_cursor: string | null;
  entries: BillingUsageEventListEntry[];
};

export type BillingUsageEventsOptions = {
  /** Page size, 1–500. The server default is 200. */
  limit?: number;
  /** Opaque continuation from the preceding event-history page. */
  cursor?: string;
  runId?: string;
};

/** One customer-facing recent billing operation from `/api/v2/billing/usage`. */
export type BillingRecentUsageEntry = {
  id: string;
  provider: string;
  operation: string;
  status: string;
  request_id: string;
  run_id: string | null;
  /** Play execution run for this charge, when the call ran inside a Play. */
  play_run_id?: string | null;
  workflow_id?: string | null;
  billing_run_id?: string | null;
  execution_run_id?: string | null;
  included_in_run_id?: string | null;
  billing_scope?: string | null;
  step_block_id?: string | null;
  step_alias?: string | null;
  credits: number;
  billing_mode: string | null;
  pricing_model: string | null;
  outcome: string | null;
  billing_note: string | null;
  charge_state:
    | 'posted'
    | 'temporary_hold'
    | 'hold_release'
    | 'pending'
    | 'free'
    | 'failed';
  /** Final billing truth may be unknown even after execution completes. */
  charge_finality?: 'final' | 'pending' | 'unknown';
  rough_usd_cost: number | null;
  created_at: string;
};

export type BillingUsageOptions = {
  /** Return the one exact call identified by `executeTool().job_id`. */
  requestId?: string;
  /** Return only the workspace identity and recent activity page. */
  recentOnly?: boolean;
  /** Bound the recent-call page. Ignored for an exact requestId lookup. */
  limit?: number;
  offset?: number;
  cursor?: string;
  runId?: string;
};

/** One run's billed credits and settlement state from `getRunBilling`. */
export type RunBillingResult = {
  runs: Array<{
    runId: string;
    /** Customer-visible billed credits so far; absent when unknown. */
    credits?: number;
    /** The run owns a charge reservation that has not settled yet. */
    settling: boolean;
  }>;
};

export type BillingUsageResult = {
  org_id: string;
  balance?: number;
  rough_usd_balance?: number;
  plan?: { usd_per_credit: number };
  usage?: {
    last_30_days_usage_credits: number;
    rough_usd_last_30_days_usage: number;
    temporary_hold_credits: number;
    rough_usd_temporary_holds: number;
  };
  recent: {
    run_id: string | null;
    request_id?: string;
    total: number;
    /** Only true when total covers the complete matching history. */
    total_is_exact?: boolean;
    /** Proven matching entries, without assuming unscanned rows match. */
    total_lower_bound?: number;
    offset: number;
    limit: number;
    next_offset: number;
    next_cursor: string | null;
    has_more: boolean;
    incomplete: boolean;
    entries: BillingRecentUsageEntry[];
  };
  [key: string]: unknown;
};

/**
 * Public `client.billing` namespace for CLI commands and programmatic callers.
 * Covers usage, plans, subscription state, cancellation, and invoice/receipt
 * history.
 *
 * @sdkReference client 030 client.billing
 */
export type BillingNamespace = {
  /** Read a bounded sandbox-session estimate; excludes tools and Customer DB. */
  quote: (input: BillingQuoteRequest) => Promise<BillingQuoteResult>;
  /** Current workspace provider benefits; discovery does not authorize a call. */
  entitlements: () => Promise<BillingEntitlements>;
  /** Play compute pricing and this period's sandbox minutes by day. */
  includedCompute: () => Promise<IncludedCompute>;
  /** Turn on included compute for the workspace. It cannot be turned off again. */
  enableIncludedCompute: () => Promise<IncludedCompute>;
  /** Charge the saved payment method and add Deepline credits to the active workspace. */
  topUp: (options: {
    credits: number;
    idempotencyKey?: string;
  }) => Promise<BillingTopUpResult>;
  /** Request a durable pending or applied receipt for a saved-card top-up. */
  topUpWithReceipt: (options: {
    credits: number;
    idempotencyKey?: string;
  }) => Promise<BillingTopUpReceipt>;
  /** Published plans plus the plan you are on ("what plans exist and what am I on"). */
  plans: () => Promise<BillingPlansResult>;
  subscription: {
    /** Active plan, Stripe subscription state, and remaining credit pools. */
    status: () => Promise<BillingSubscriptionStatus>;
    /**
     * Schedule cancellation at period end (credits are kept), or reverse a
     * pending cancellation with `{ undo: true }`.
     */
    cancel: (options?: {
      undo?: boolean;
    }) => Promise<BillingSubscriptionCancelResult>;
  };
  invoices: {
    /** Subscription invoices plus credit purchase receipts, newest first. */
    list: (options?: { limit?: number }) => Promise<BillingInvoicesResult>;
  };
  /** Read one exact execution outcome using the request_id returned by executeTool. */
  usageEvent: (requestId: string) => Promise<BillingUsageEvent>;
  /** Read one raw event-history page, without charge/ledger reconciliation. */
  usageEvents: (
    options?: BillingUsageEventsOptions,
  ) => Promise<BillingUsageEventsResult>;
  /** Read current billing usage, or look up one exact execution charge by request ID. */
  usage: (options?: BillingUsageOptions) => Promise<BillingUsageResult>;
  /** Metronome-authored target catalog and current Contract projection. */
  targetPlans: () => Promise<TargetBillingPlansResult>;
  /** Normalized target billing state. */
  targetStatus: () => Promise<TargetBillingStatusResult>;
  /** Read and manage the Metronome-backed automatic recharge configuration. */
  autoRecharge: {
    get: () => Promise<TargetAutoRechargeResult>;
    trigger: (options?: {
      idempotencyKey: string;
    }) => Promise<{ data: { status: string; operation_id?: string } }>;
    update: (
      options: TargetAutoRechargeUpdateOptions,
    ) => Promise<TargetAutoRechargeResult>;
  };
  /** Buy Deepline credits through a payment-gated Metronome commit. */
  purchaseCredits: (options: {
    credits: number;
    idempotencyKey: string;
  }) => Promise<TargetBillingMutationResult>;
  /** Inspect or retire the original purchase intent without starting a payment. */
  recoverCreditPurchase: (options: {
    credits: number;
    orgId: string;
    idempotencyKey: string;
  }) => Promise<TargetBillingMutationResult>;
  /** Start, change, cancel, or undo a target plan transition. */
  transitionPlan: (
    options: TargetBillingPlanTransitionOptions,
  ) => Promise<TargetBillingMutationResult>;
  /** Create a Stripe-hosted billing Portal session. */
  portalSession: (options?: {
    flow?: 'customer_update';
  }) => Promise<{ url: string }>;
};

export type BillingQuoteRequest = {
  quantity: number;
  sandbox_runtime: PlaySandboxRuntimeDeclaration;
};

export type BillingQuoteResult = {
  scope: 'sandbox_session';
  quantity: number;
  resources: {
    timeoutSeconds: number;
    memoryGiB: number;
    cpu: number;
    diskGiB: number;
  };
  maximum_backend?: 'daytona' | 'modal';
  priced_backends?: Array<'daytona' | 'modal'>;
  maximum_credits: number;
  maximum_billing_seconds: number;
  total_play_credits: null;
  total_budget_supported: false;
  unbounded_components: string[];
  explanation: string;
  plan_version_id: string;
  rate_card_id: string;
};

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

function isPrebuiltPlayDescription(
  play: Pick<PlayDescription, 'origin' | 'ownerType'>,
): boolean {
  return play.origin === 'prebuilt' || play.ownerType === 'deepline';
}

function preferPrebuiltPlayDescriptions<T extends PlayDescription>(
  plays: T[],
): T[] {
  return plays
    .map((play, index) => ({ play, index }))
    .sort(
      (left, right) =>
        Number(right.play.pinned) - Number(left.play.pinned) ||
        Number(isPrebuiltPlayDescription(right.play)) -
          Number(isPrebuiltPlayDescription(left.play)) ||
        left.index - right.index,
    )
    .map(({ play }) => play);
}

function readStringArray(value: unknown): string[] {
  return Array.isArray(value)
    ? value.filter((line): line is string => typeof line === 'string')
    : [];
}

type PlayLiveStatusState = {
  runId: string;
  status: PlayStatus['status'];
  logs: string[];
  /**
   * Absolute (1-based) sequence number of the last log line appended to
   * `logs`. play.run.log payloads carry `firstSeq` (ADR-0009), so overlapping
   * re-deliveries are skipped positionally — repeated identical lines are
   * preserved and snapshots never replace the accumulated log list.
   */
  lastLogSeq: number;
  result?: unknown;
  error?: string;
  latest: PlayStatus | null;
};

function getPlayLiveEventPayload(
  event: PlayLiveEvent,
): Record<string, unknown> {
  return event.payload && typeof event.payload === 'object'
    ? (event.payload as Record<string, unknown>)
    : {};
}

/** Run lifecycle events are the only events that can finish a watch. */
function playLiveRunStatus(event: PlayLiveEvent): PlayStatus['status'] | null {
  if (
    event.type !== 'play.run.snapshot' &&
    event.type !== 'play.run.status' &&
    event.type !== 'play.run.final_status'
  ) {
    return null;
  }
  const payload = getPlayLiveEventPayload(event);
  return (
    decodePlayRunPublicStatus(payload.status) ??
    (isPlayRunPackage(payload)
      ? decodePlayRunPublicStatus(payload.run.status)
      : null)
  );
}

function appendPlayLiveLogLines(
  state: PlayLiveStatusState,
  payload: Record<string, unknown>,
): void {
  const lines = readStringArray(payload.lines);
  if (lines.length === 0) {
    return;
  }
  const firstSeq =
    typeof payload.firstSeq === 'number' &&
    Number.isFinite(payload.firstSeq) &&
    payload.firstSeq >= 1
      ? Math.trunc(payload.firstSeq)
      : null;
  if (firstSeq === null) {
    // Marker payloads (gap/unavailable notices) and pre-ADR-0009 servers
    // carry no seq: append verbatim and advance the cursor by the payload's
    // cumulative count when present so later seq-stamped lines line up.
    state.logs.push(...lines);
    const totalLogCount =
      typeof payload.totalLogCount === 'number' &&
      Number.isFinite(payload.totalLogCount)
        ? Math.trunc(payload.totalLogCount)
        : null;
    if (totalLogCount !== null) {
      state.lastLogSeq = Math.max(state.lastLogSeq, totalLogCount);
    }
    return;
  }
  // Positional append: skip the already-seen prefix of overlapping
  // re-deliveries; repeated identical lines are preserved.
  const skip = Math.max(0, state.lastLogSeq + 1 - firstSeq);
  if (skip >= lines.length) {
    return;
  }
  state.logs.push(...lines.slice(skip));
  state.lastLogSeq = Math.max(state.lastLogSeq, firstSeq + lines.length - 1);
}

function updatePlayLiveStatusState(
  state: PlayLiveStatusState,
  event: PlayLiveEvent,
): PlayStatus | null {
  const payload = getPlayLiveEventPayload(event);
  if (event.type === 'play.run.log') {
    appendPlayLiveLogLines(state, payload);
    return null;
  }
  if (
    event.type !== 'play.run.snapshot' &&
    event.type !== 'play.run.status' &&
    event.type !== 'play.run.final_status'
  ) {
    return null;
  }

  const runId =
    typeof payload.runId === 'string' && payload.runId
      ? payload.runId
      : isPlayRunPackage(payload)
        ? payload.run.id
        : state.runId;
  const status = playLiveRunStatus(event) ?? state.status;
  const progressPayload = isRecord(payload.progress) ? payload.progress : {};
  // Snapshots no longer REPLACE accumulated logs (ADR-0009): the snapshot
  // only retains a bounded tail, so replacing would clobber the seq-keyed
  // log list built from play.run.log events (the stream differ always emits
  // log lines through play.run.log, snapshot ticks included). A terminal
  // final_status payload may still seed an EMPTY state — that is the only
  // event some non-stream flows ever see.
  if (
    event.type === 'play.run.final_status' &&
    state.logs.length === 0 &&
    state.lastLogSeq === 0
  ) {
    const payloadLogs = readStringArray(payload.logs);
    const progressLogs = readStringArray(progressPayload.logs);
    const seedLogs = payloadLogs.length > 0 ? payloadLogs : progressLogs;
    if (seedLogs.length > 0) {
      state.logs = seedLogs;
    }
  }
  if ('result' in payload) {
    state.result = payload.result;
  } else if (isPlayRunPackage(payload)) {
    state.result = payload;
  }
  if (typeof payload.error === 'string' && payload.error.trim()) {
    state.error = payload.error;
  }
  state.runId = runId;
  state.status = status;

  const progressRecord = progressPayload;
  const next: PlayStatus = {
    ...(payload as unknown as Omit<
      PlayStatus,
      'runId' | 'status' | 'progress'
    >),
    runId,
    status,
    ...(isPlayRunPackage(payload)
      ? { package: payload, outputs: payload.outputs }
      : {}),
    progress: {
      ...progressRecord,
      status:
        typeof progressRecord.status === 'string'
          ? progressRecord.status
          : status,
      logs: state.logs,
      ...(state.error ? { error: state.error } : {}),
    },
    ...('result' in state ? { result: state.result } : {}),
  };
  state.latest = next;
  return next;
}

function playRunResultFromStatus(
  status: PlayStatus,
  startedAt: number,
  fallbackRunId: string,
): PlayRunResult {
  return {
    success: status.status === 'completed',
    runId: status.runId || fallbackRunId,
    result: status.package ?? status.result,
    ...(status.package ? { package: status.package } : {}),
    logs: status.progress?.logs ?? [],
    durationMs: Date.now() - startedAt,
    error:
      status.progress?.error ??
      (status.status !== 'completed' ? status.status : undefined),
  };
}

export type HostedPage = {
  id: string;
  name: string;
  url: string;
  description: string | null;
  allowed_origins?: string[];
  public: boolean;
  state: 'active' | 'deleting';
  has_document: boolean;
  content_type: string | null;
  size_bytes: number | null;
  revision: number;
  created_at: number;
  updated_at: number;
  last_written_by_run_id: string | null;
};

export type HostedPageList = {
  pages: HostedPage[];
  next_cursor: string | null;
  page_limit: number;
  /** Whether this workspace may publish pages anyone can open. */
  public_allowed: boolean;
};

export type HostedPageWriteResult = {
  name: string;
  url: string;
  public: boolean;
  revision: number;
  created: boolean;
  warnings: string[];
};

export type HostedPageLink = {
  id: string;
  label: string | null;
  expires_at: number | null;
  created_at: number;
};

/**
 * Low-level typed REST client with authentication, retries, and localhost failover.
 *
 * @example
 * ```typescript
 * import { DeeplineClient } from 'deepline';
 *
 * // Zero-config (uses env vars / CLI auth):
 * const client = new DeeplineClient();
 *
 * // Explicit config:
 * const client2 = new DeeplineClient({
 *   apiKey: 'dl_test_...',
 *   baseUrl: 'http://localhost:3000',
 * });
 * ```
 *
 * @sdkReference client 010
 */
export class DeeplineClient {
  private readonly http: HttpClient;
  private readonly toolCalls: ToolCalls;
  private readonly playClient: PlayClient;
  private readonly config: ResolvedConfig;
  private readonly environment: ClientEnvironment;
  /** Canonical run lifecycle namespace backed by `/api/v2/runs`. */
  readonly runs: RunsNamespace;
  /** Current mutable customer database namespace backed by `/api/v2/db/query`. */
  readonly db: DbNamespace;
  /** Billing namespace: subscription status/cancel and invoice history. */
  readonly billing: BillingNamespace;
  /** Workspace lifecycle namespace. */
  readonly workspaces: WorkspacesNamespace;
  /** Monitors namespace: access, catalog, deploy/check, and lifecycle. */
  readonly monitors: MonitorsNamespace;

  /**
   * Create a low-level SDK client.
   *
   * Most callers can omit options and let the SDK resolve auth/config from
   * environment variables and CLI-managed credentials.
   *
   * @param options - Optional overrides for API key, base URL, timeout, and retries.
   * @throws {@link ConfigError} if no API key can be resolved from any source.
   */
  constructor(
    config: ResolvedConfig,
    http: HttpClient,
    explicitTimeout?: number,
  ) {
    this.config = config;
    this.environment = this.config.environment ?? process.env;
    this.http = http;
    this.playClient = new PlayClient(this.http, this.environment);
    this.toolCalls = new ToolCalls(
      this.http,
      this.config.timeout,
      explicitTimeout,
    );
    this.runs = {
      getReceipts: (runId, options) => this.getRunReceipts(runId, options),
      get: (runId, options) => this.getRunStatus(runId, options),
      children: (parentRunId, options) =>
        this.getRunChildren(parentRunId, options),
      status: (runId) => this.getRunLifecycleStatus(runId),
      list: (options) => this.listRuns(options),
      listPage: (options) => this.listRunsPage(options),
      history: (options) => this.getRunsHistory(options),
      watch: (runId, options) => this.watchRunToTerminal(runId, options),
      tail: (runId, options) => this.tailRun(runId, options),
      logs: Object.assign(
        (runId: string, options?: RunsLogsOptions) =>
          this.getRunLogs(runId, options),
        {
          query: (runId: string, options?: RunsLogsQueryOptions) =>
            this.queryRunLogs(runId, options),
          count: (runId: string, criteria?: RunsLogCriteria) =>
            this.countRunLogs(runId, criteria),
          summarize: (runId: string, options: RunsLogsSummaryOptions) =>
            this.summarizeRunLogs(runId, options),
          fields: (options?: RunsEventsFieldsOptions) =>
            this.getRunEventFields('logs', options),
        },
      ),
      events: {
        list: (options) => this.listRunEvents(options),
        count: (criteria) => this.countRunEvents(criteria),
        summarize: (options) => this.summarizeRunEvents(options),
        fields: (options) => this.getRunEventFields('events', options),
      },
      searchEvents: (options) => this.searchRunEvents(options),
      input: (runId) => this.getRunInput(runId),
      rerun: (runId, options) => this.rerun(runId, options),
      resume: (runId) => this.resumeRun(runId),
      exportDatasetRows: (input) => this.getPlaySheetRows(input),
      rowHistory: (input) => this.getPlayRunRowHistory(input),
      stop: (runId, options) => this.stopRun(runId, options),
      stopAll: ((options?: StopAllRunsOptions) =>
        this.stopAllRuns(options)) as RunsNamespace['stopAll'],
    };
    this.db = {
      query: (input) => this.queryDb(input),
      planQuery: (input) => planCustomerDbQuery(input, this.config.maxRetries),
    };
    this.billing = {
      quote: (input) =>
        this.http.post<BillingQuoteResult>('/api/v2/billing/quote', input),
      entitlements: () => this.http.get('/api/v2/billing/entitlements'),
      includedCompute: () => this.http.get('/api/v2/billing/included-compute'),
      enableIncludedCompute: () =>
        this.http.post<IncludedCompute>('/api/v2/billing/included-compute', {}),
      topUp: (options) => this.topUpBillingBalance(options),
      topUpWithReceipt: (options) =>
        this.topUpBillingBalanceWithReceipt(options),
      plans: () => this.getBillingPlans(),
      subscription: {
        status: () => this.getBillingSubscriptionStatus(),
        cancel: (options) => this.cancelBillingSubscription(options),
      },
      invoices: {
        list: (options) => this.listBillingInvoices(options),
      },
      usageEvent: (requestId) => this.getBillingUsageEvent(requestId),
      usageEvents: (options) => this.getBillingUsageEvents(options),
      usage: (options) => this.getBillingUsage(options),
      targetPlans: () => this.getTargetBillingPlans(),
      targetStatus: () => this.getTargetBillingStatus(),
      autoRecharge: {
        get: () => this.getTargetAutoRecharge(),
        trigger: (options) =>
          this.http.post(
            '/api/v2/billing/auto-recharge/trigger',
            {},
            {
              'Idempotency-Key': requireTargetBillingIdempotencyKey(
                options?.idempotencyKey ?? globalThis.crypto.randomUUID(),
              ),
            },
          ),
        update: (options) => this.updateTargetAutoRecharge(options),
      },
      purchaseCredits: (options) => this.purchaseTargetBillingCredits(options),
      recoverCreditPurchase: (options) =>
        this.recoverTargetBillingCreditPurchase(options),
      transitionPlan: (options) => this.transitionTargetBillingPlan(options),
      portalSession: (options) =>
        this.createTargetBillingPortalSession(options),
    };
    this.workspaces = {
      members: (options) => {
        const query = options?.cursor
          ? `?cursor=${encodeURIComponent(options.cursor)}`
          : '';
        return this.http.get(`/api/v2/auth/workspace/members${query}`);
      },
      setMemberGrants: (memberId, grants) =>
        this.http.patch(
          `/api/v2/auth/workspace/members/${encodeURIComponent(memberId)}/role`,
          { role: grants.join(',') },
        ),
      create: (options) => this.createWorkspace(options),
    };
    this.monitors = {
      status: () => this.getMonitorsAccess(),
      available: (toolIdOrOptions, options) =>
        this.getMonitorsAvailable(toolIdOrOptions, options),
      check: (definition) => this.checkMonitor(definition),
      preview: (definition, options) =>
        this.previewMonitor(definition, options),
      deploy: (definition, options) => this.deployMonitor(definition, options),
      sync: (definition, options) =>
        options?.dryRun
          ? this.deployMonitor(definition, { dryRun: true })
          : this.syncScalarMonitor(definition, options),
      list: (options) => this.listMonitors(options),
      ledger: (options) => this.listMonitorLedger(options),
      ledgerGet: (key) => this.getMonitorLedgerEntry(key),
      ledgerFindings: (key, options) =>
        this.listMonitorLedgerFindings(key, options),
      get: (key) => this.getMonitor(key),
      test: (key, payload, options) =>
        this.testMonitorWebhook(key, payload, options),
      validate: (key) => this.validateMonitor(key),
      dependents: (key) => this.getMonitorDependents(key),
      update: (key, patch) => this.updateMonitor(key, patch),
      delete: (key, options) => this.deleteMonitor(key, options),
      reactivate: (key, options) => this.reactivateMonitor(key, options),
      start: (key, options) =>
        options?.dryRun
          ? this.submitMonitorBatch({
              kind: 'reactivate',
              scope: { kind: 'keys', monitorKeys: [key] },
              dryRun: true,
              idempotencyKey:
                options.idempotencyKey ??
                this.monitorJobIdempotencyKey(`start-${key}`),
            })
          : this.submitScalarMonitorLifecycle(key, 'start', options),
      stop: (key, options) =>
        options?.dryRun
          ? this.submitMonitorBatch({
              kind: 'deactivate',
              scope: { kind: 'keys', monitorKeys: [key] },
              dryRun: true,
              idempotencyKey:
                options.idempotencyKey ??
                this.monitorJobIdempotencyKey(`stop-${key}`),
            })
          : this.submitScalarMonitorLifecycle(key, 'stop', options),
      audit: (options) => this.auditMonitors(options),
      repair: (options) => this.repairMonitors(options),
      health: (options) => this.readMonitorsHealth(options),
      batch: {
        deploy: (definitions, options) =>
          this.deployMonitorBatch(definitions, options),
        submit: (options) => this.submitMonitorBatch(options),
        get: (operationId, options) =>
          this.getMonitorBatch(operationId, options),
      },
      batches: {
        sync: (batchId, definitions, options) =>
          this.syncNamedMonitorBatch(batchId, definitions, options),
        start: (batchId, options) =>
          this.startNamedMonitorBatch(batchId, options),
        stop: (batchId, options) =>
          this.stopNamedMonitorBatch(batchId, options),
        get: (batchId) => this.getNamedMonitorBatch(batchId),
      },
      jobs: {
        get: (jobId) => this.getMonitorJob(jobId),
        logs: (jobId, options) => this.getMonitorJobLogs(jobId, options),
        cancel: (jobId) => this.cancelMonitorJob(jobId),
        wait: (jobId, options) => this.waitForMonitorJob(jobId, options),
      },
      fleets: {
        deploy: (definitionOrId, options) =>
          this.syncMonitorFleet(definitionOrId, options),
        sync: (definitionOrId, options) =>
          this.syncMonitorFleet(definitionOrId, options),
        get: (fleetId, options) =>
          fleetId === undefined
            ? this.listMonitorFleets()
            : this.getMonitorFleet(fleetId, options),
        list: () => this.listMonitorFleets(),
        deactivate: (fleetId, options) =>
          this.deactivateMonitorFleet(fleetId, options),
        reactivate: (fleetId, options) =>
          this.reactivateMonitorFleet(fleetId, options),
        start: (fleetId, options) =>
          this.reactivateMonitorFleet(fleetId, options),
        stop: (fleetId, options) =>
          this.deactivateMonitorFleet(fleetId, options),
        waitForConvergence: (fleetId, options) =>
          this.waitForMonitorFleetConvergence(fleetId, options),
      },
    };
  }

  /** The resolved base URL this client is targeting (e.g. `"http://localhost:3000"`). */
  get baseUrl(): string {
    return this.config.baseUrl;
  }

  // ——————————————————————————————————————————————————————————
  // Secrets
  // ——————————————————————————————————————————————————————————

  /** List this workspace's hosted pages, newest update first. */
  async listPages(input?: {
    cursor?: string;
    limit?: number;
  }): Promise<HostedPageList> {
    const params = new URLSearchParams();
    if (input?.cursor) params.set('cursor', input.cursor);
    if (input?.limit) params.set('limit', String(input.limit));
    const query = params.size > 0 ? `?${params}` : '';
    return await this.http.get<HostedPageList>(`/api/v2/pages${query}`);
  }

  /** Read one hosted page's metadata. */
  async getPage(name: string): Promise<HostedPage> {
    return await this.http.get<HostedPage>(
      `/api/v2/pages/${encodeURIComponent(name)}`,
    );
  }

  /** Replace a page's whole content. `public` says who the write is for. */
  async writePage(
    name: string,
    input: {
      public: boolean;
      contentBase64: string;
      contentType: string;
      description?: string;
    },
  ): Promise<HostedPageWriteResult> {
    return await this.http.put<HostedPageWriteResult>(
      `/api/v2/pages/${encodeURIComponent(name)}`,
      {
        public: input.public,
        content_base64: input.contentBase64,
        content_type: input.contentType,
        description: input.description,
      },
    );
  }

  /** Delete a page, its content, and its links. Safe to repeat. */
  async deletePage(name: string): Promise<{ name: string; deleted: boolean }> {
    return await this.http.delete<{ name: string; deleted: boolean }>(
      `/api/v2/pages/${encodeURIComponent(name)}`,
    );
  }

  /** Replace the origins allowed to read this page in a browser when public. */
  async setPageAllowedOrigins(
    name: string,
    origins: string[],
  ): Promise<{ allowed_origins: string[] }> {
    return await this.http.put<{ allowed_origins: string[] }>(
      `/api/v2/pages/${encodeURIComponent(name)}/origins`,
      { allowed_origins: origins },
    );
  }

  /** The explicit way to change who can see an existing page. */
  async setPageVisibility(
    name: string,
    isPublic: boolean,
  ): Promise<HostedPage> {
    return await this.http.post<HostedPage>(
      `/api/v2/pages/${encodeURIComponent(name)}/visibility`,
      { public: isPublic },
    );
  }

  /** List a page's links. Their URLs cannot be shown again. */
  async listPageLinks(name: string): Promise<{ links: HostedPageLink[] }> {
    return await this.http.get<{ links: HostedPageLink[] }>(
      `/api/v2/pages/${encodeURIComponent(name)}/links`,
    );
  }

  /** The returned URL is shown once. Either expiry or `permanent` is required. */
  async createPageLink(
    name: string,
    input: { expiresInSeconds?: number; permanent?: boolean; label?: string },
  ): Promise<HostedPageLink & { url: string }> {
    return await this.http.post<HostedPageLink & { url: string }>(
      `/api/v2/pages/${encodeURIComponent(name)}/links`,
      {
        expires_in_seconds: input.expiresInSeconds,
        permanent: input.permanent,
        label: input.label,
      },
    );
  }

  /** Stop a link working. Safe to repeat. */
  async revokePageLink(
    name: string,
    linkId: string,
  ): Promise<{ id: string; revoked: boolean }> {
    return await this.http.delete<{ id: string; revoked: boolean }>(
      `/api/v2/pages/${encodeURIComponent(name)}/links/${encodeURIComponent(linkId)}`,
    );
  }

  /** List secret metadata visible to the current workspace. */
  async listSecrets(): Promise<PlaySecretMetadata[]> {
    const response = await this.http.get<{ secrets?: PlaySecretMetadata[] }>(
      '/api/v2/secrets',
    );
    return Array.isArray(response.secrets) ? response.secrets : [];
  }

  /**
   * Check whether a named secret exists, is active, and has a stored value.
   *
   * @param name - Secret name. It is normalized to uppercase before lookup.
   * @returns Matching active secret metadata, or `null`.
   */
  async checkSecret(name: string): Promise<PlaySecretMetadata | null> {
    const normalized = name.trim().toUpperCase();
    const secrets = await this.listSecrets();
    return (
      secrets.find(
        (secret) =>
          secret.name === normalized &&
          secret.status === 'active' &&
          secret.hasValue,
      ) ?? null
    );
  }

  /** Check effective scope and active-version health without reading the value.
   * Without playName, checks the organization-scoped secret only. With a Play
   * name, an active Play secret takes precedence; a deleted/disabled Play
   * secret falls back to the organization-scoped secret.
   */
  async inspectSecret(
    name: string,
    options: { playName?: string } = {},
  ): Promise<PlaySecretCheck> {
    const params = new URLSearchParams({ name: name.trim().toUpperCase() });
    if (options.playName !== undefined) params.set('play', options.playName);
    return this.http.get(`/api/v2/secrets?${params.toString()}`);
  }

  /** Add, replace, or clear the non-sensitive note attached to one secret. */
  async updateSecretNote(
    secretId: string,
    note: string,
  ): Promise<PlaySecretMetadata> {
    const response = await this.http.patch<{ secret: PlaySecretMetadata }>(
      `/api/v2/secrets/${encodeURIComponent(secretId)}`,
      { note },
    );
    return response.secret;
  }

  // ——————————————————————————————————————————————————————————
  // Tools
  // ——————————————————————————————————————————————————————————

  /**
   * List all available tools.
   *
   * Returns tool definitions including ID, provider, description, input/output schemas,
   * and list extractor paths for automatic CSV conversion.
   *
   * @returns Array of tool definitions
   *
   * @example
   * ```typescript
   * const tools = await client.listTools();
   * const searchTools = tools.filter(t => t.categories.includes('search'));
   * console.log(`Found ${searchTools.length} search tools`);
   * ```
   */
  async listTools(options?: {
    categories?: string;
    tags?: string;
    grep?: string;
    grepMode?: 'all' | 'any' | 'phrase';
    compact?: boolean;
  }): Promise<ToolDefinition[]> {
    const params = new URLSearchParams();
    if (options?.categories?.trim()) {
      params.set('categories', options.categories.trim());
    }
    if (options?.tags?.trim()) {
      params.set('tags', options.tags.trim());
    }
    if (options?.grep?.trim()) {
      params.set('grep', options.grep.trim());
      params.set('grep_mode', options.grepMode ?? 'all');
    }
    params.set('compact', options?.compact === true ? 'true' : 'false');
    const suffix = params.toString() ? `?${params.toString()}` : '';
    const res = await this.http.get<{ tools: ToolDefinition[] }>(
      `/api/v2/tools${suffix}`,
    );
    return res.tools;
  }

  /** List category counts without downloading tool definitions. */
  async listToolCategories(): Promise<ToolCategorySummary[]> {
    const response = await this.http.get<ToolDiscoveryResponse>(
      '/api/v2/tools?view=categories&compact=true',
    );
    if (response.view === 'categories') {
      return readToolCategorySummaries(response.categories);
    }
    // Older servers ignore the additive view and return their existing list.
    if (response.view === undefined && Array.isArray(response.tools)) {
      return summarizeToolCategories(response.tools);
    }
    throw invalidToolDiscoveryResponse();
  }

  /** Read one complete category and its live category counts in one request. */
  async listToolsInCategory(
    category: string,
    options?: { compact?: boolean },
  ): Promise<ToolCategoryListing> {
    const normalizedCategory = category.trim();
    if (!normalizedCategory || category.includes(',')) {
      throw new DeeplineError(
        'Provide one non-empty tool category.',
        400,
        'INVALID_TOOL_CATEGORY',
      );
    }
    const params = new URLSearchParams({
      view: 'category',
      categories: normalizedCategory,
      compact: options?.compact === true ? 'true' : 'false',
    });
    const response = await this.http.get<ToolDiscoveryResponse>(
      `/api/v2/tools?${params}`,
    );
    if (
      !Array.isArray(response.tools) ||
      (response.view !== 'category' && response.view !== undefined)
    ) {
      throw invalidToolDiscoveryResponse();
    }
    return {
      tools: response.tools,
      categories:
        response.view === 'category'
          ? readToolCategorySummaries(response.categories)
          : await this.listToolCategories(),
    };
  }

  /** List discoverable providers without requiring a local plugin catalog. */
  async listProviders(options?: {
    changed?: boolean;
  }): Promise<ProviderDefinition[]> {
    const suffix = options?.changed ? '?changed=true' : '';
    const res = await this.http.get<{ providers: ProviderDefinition[] }>(
      `/api/v2/tools/providers${suffix}`,
    );
    return res.providers;
  }

  /**
   * Search available tools using Deepline's ranked backend search.
   *
   * The CLI uses the same search.
   * The search ranks tool metadata, categories, agent guidance, and input schema fields.
   */
  async searchTools(
    options: ToolSearchOptions = {},
  ): Promise<ToolSearchResult> {
    return this.http.get<ToolSearchResult>(
      `/api/v2/tools/search?${searchParams(options).toString()}`,
    );
  }

  /**
   * Search everything Deepline can run or deploy in one ranked list: tools,
   * monitor types, prebuilt plays, and your workspace's own plays.
   *
   * @example
   * ```typescript
   * const { results } = await client.search({
   *   query: 'find work email',
   *   types: ['tools', 'prebuilts'],
   * });
   * ```
   */
  async search(options: SearchOptions = {}): Promise<SearchResult> {
    const params = searchParams(options);
    if (options.types?.length) params.set('types', options.types.join(','));
    if (options.exclude?.length) {
      params.set('exclude', options.exclude.join(','));
    }
    return this.http.get<SearchResult>(`/api/v2/search?${params.toString()}`);
  }

  /**
   * Get detailed metadata for a single tool.
   *
   * Returns everything from {@link ToolDefinition} plus pricing info, sample
   * inputs/outputs, failure modes, and cost estimates.
   *
   * @param toolId - Tool identifier (e.g. `"dropleads_search_people"`)
   * @returns Full tool metadata
   *
   * @example
   * ```typescript
   * const meta = await client.getTool('dropleads_search_people');
   * console.log(`Cost: ${meta.estimatedCreditsRange} credits`);
   * console.log(`Input schema:`, meta.inputSchema);
   * ```
   */
  async getTool(
    toolId: string,
    options?: { cliInvocationId?: string },
  ): Promise<ToolMetadata> {
    if (options?.cliInvocationId !== undefined) {
      validateCliInvocationId(options.cliInvocationId);
    }
    return this.http.request<ToolMetadata>(
      `/api/v2/integrations/${encodeURIComponent(toolId)}/get`,
      {
        method: 'GET',
        // Tool metadata is a read-only catalog lookup. Keep the metadata
        // header while opting into the same transient edge-response retries as
        // other GET catalog methods such as searchTools().
        retryApiErrors: true,
        headers: {
          'x-deepline-tool-meta-only': '1',
          ...(options?.cliInvocationId !== undefined
            ? { 'x-deepline-cli-invocation-id': options.cliInvocationId }
            : {}),
        },
      },
    );
  }

  /**
   * Describe a Deepline Agent model and its provider-specific option surface.
   *
   * The method combines live AI Gateway model metadata with Deepline's generated registry of AI SDK provider options.
   * Agents can use this information to construct `providerOptions` payloads before they execute `deeplineagent`.
   *
   * The returned schemas describe accepted shapes for provider options.
   * These schemas do not guarantee that every model supports each option.
   * Runtime AI SDK and Gateway errors determine support for model-specific values.
   *
   * @param model - Exact-case Gateway model id such as `"openai/gpt-5.6-luna"`
   * @returns Model metadata, provider option shapes, and runnable examples
   */
  async describeModel(model: string): Promise<DeeplineAgentModelDescription> {
    return this.http.request<DeeplineAgentModelDescription>(
      `/api/v2/models/describe?model=${encodeURIComponent(model)}`,
      {
        method: 'GET',
      },
    );
  }

  /**
   * Quote dynamic AI inference pricing for a concrete payload.
   *
   * The result contains a planning estimate and a separate, proven authorization maximum.
   * Both values use Deepline credits.
   */
  async quoteInferenceTool(
    toolId: 'ai_evaluate' | 'ai_inference' | 'deeplineagent',
    payload: Record<string, unknown>,
  ): Promise<InferenceQuote> {
    return this.http.post<InferenceQuote>(
      `/api/v2/integrations/${encodeURIComponent(toolId)}/quote`,
      payload,
    );
  }

  /**
   * Execute a tool and return the standard execution envelope.
   *
   * The `toolResponse.rawV2` field contains the complete tool response,
   * preserving its original nesting. Inspect `getTool().examples` for a full
   * Deepline response example. Optional `toolResponse.responseMeta` contains
   * response metadata.
   * Top-level fields such as `status`, `job_id`, and `billing` describe the
   * Deepline execution envelope.
   */
  async executeTool<TData = unknown, TMeta = Record<string, unknown>>(
    toolId: string,
    input: Record<string, unknown>,
    options?: ExecuteToolRawOptions,
  ): Promise<ToolExecution<TData, TMeta>> {
    return this.toolCalls.call<TData, TMeta>(toolId, input, options);
  }

  /** Read the durable state of a keyed tool execution. */
  async getExecutionByKey(
    idempotencyKey: string,
  ): Promise<ExecutionByKeyResult> {
    return this.toolCalls.getByKey(idempotencyKey);
  }

  /** Public recovery namespace. */
  get executions(): {
    getByKey: (key: string) => Promise<ExecutionByKeyResult>;
  } {
    return { getByKey: (key) => this.getExecutionByKey(key) };
  }

  /**
   * Back-compatible alias for {@link executeTool}.
   *
   * Retained for callers that still use the older raw naming while the response
   * envelope remains the same.
   */
  async executeToolRaw<TData = unknown, TMeta = Record<string, unknown>>(
    toolId: string,
    input: Record<string, unknown>,
    options?: ExecuteToolRawOptions,
  ): Promise<ToolExecution<TData, TMeta>> {
    return this.executeTool<TData, TMeta>(toolId, input, options);
  }

  private async queryDb(
    input: CustomerDbQueryOptions,
  ): Promise<CustomerDbQueryResult> {
    return queryCustomerDatabase(this.http, input, this.config.maxRetries);
  }

  /**
   * Run a bounded SQL query against the current mutable customer database.
   *
   * This query is not scoped to one play run. Use `client.runs` export actions
   * when the caller needs the rows produced by a specific run.
   *
   * @deprecated Use {@link DeeplineClient.db} `.query(...)`.
   */
  async queryCustomerDb(
    input: CustomerDbQueryOptions,
  ): Promise<CustomerDbQueryResult> {
    return this.db.query(input);
  }

  /**
   * Re-establish this workspace's tenant storage contract: role/DB connect
   * grants plus materialized table grants. Org-admin only. Use when a run fails
   * with `WORKSPACE_STORAGE_NOT_READY`.
   */
  async repairIngestionStorage(input?: {
    provider?: string;
  }): Promise<IngestionStorageRepairResult> {
    return this.http.post<IngestionStorageRepairResult>(
      '/api/v2/ingestion/repair',
      {
        ...(input?.provider ? { provider: input.provider } : {}),
      },
    );
  }

  // ——————————————————————————————————————————————————————————
  // Plays — submission and lifecycle
  // ——————————————————————————————————————————————————————————

  /**
   * Start a play run.
   *
   * Internal/advanced primitive. For normal callers, prefer the public
   * entrypoints: the CLI, {@link Deepline.connect}, {@link submitPlay},
   * or {@link runPlay}.
   *
   * These interfaces share the run contract and return a workflow or run ID:
   *
   * - `deepline run`.
   * - Repository scripts such as `bun run deepline -- run`.
   * - SDK context calls such as `Deepline.connect().play(name).run()`.
   * - Direct `POST /api/v2/plays/run` calls.
   *
   * Read completed output from `getPlayStatus(runId).result`.
   * For SDK context calls, read output from `PlayJob.get()`.
   * Execution logs appear under `progress.logs`. The user output object does not contain these logs.
   *
   * @param request - Play run configuration (name, code, input, etc.)
   * @returns Run metadata including the public `workflowId`
   *
   * @example
   * ```typescript
   * // Run a live play by name:
   * const started = await client.startPlayRun({
   *   name: 'email-waterfall',
   *   input: { linkedin_url: 'https://linkedin.com/in/jdoe', domain: 'acme.com' },
   * });
   * console.log(`Workflow: ${started.workflowId}`);
   *
   * // Run an ad hoc artifact-backed play:
   * const started2 = await client.startPlayRun({
   *   artifactStorageKey: 'plays/v1/orgs/acme/plays/my-play/artifacts/playgraph_abc123.json',
   * });
   * ```
   */
  async startPlayRun(
    request: StartPlayRunRequest,
    options?: PlayRunStartOptions,
  ): Promise<PlayRunStart> {
    return this.playClient.startPlayRun(request, options);
  }

  /**
   * Prepare a tenant-scoped start intent without executing it. Its stream
   * sender retains the exact body and transport selected during preparation.
   */
  async preparePlayRunAdmission(
    request: StartPlayRunRequest,
    options?: PlayRunStartOptions,
  ) {
    const resolved = resolveStartPlayRunRequest(request, this.environment);
    const prepared = await preparePlayRunAdmission(
      this.http,
      resolved.request,
      options?.onSubmission,
      options,
    );
    const bodyJson = JSON.stringify(prepared.body);
    const runtimeHeaders = runtimeSelectionHeaders(
      resolved.runtime,
      this.environment,
    );
    const headers = options?.cliAdmission
      ? {
          ...runtimeHeaders,
          'X-Deepline-API-Major': String(SDK_API_MAJOR),
        }
      : runtimeHeaders;
    const http = this.http;
    let submitted = false;
    return {
      ...prepared,
      async start(
        startOptions?: Pick<PlayRunStartOptions, 'cliAdmission' | 'signal'>,
      ) {
        if (submitted && !prepared.supportsCallerIntent) {
          throw new DeeplineError(
            'This server has not enabled caller-owned admission recovery. Do not retry an ambiguous start.',
            409,
            'PLAY_RUN_ADMISSION_RECOVERY_UNSUPPORTED',
          );
        }
        if (submitted) {
          // Re-prove the pinned intent before retrying. Caller-intent v2 is
          // checked by the versioned POST response itself; legacy admission
          // uses the capability reader.
          if (!options?.callerIntentV2) {
            await preparePlayRunAdmission(
              http,
              JSON.parse(bodyJson) as ResolvedStartPlayRunRequest,
              undefined,
              { signal: startOptions?.signal ?? options?.signal },
            );
          }
        }
        submitted = true;
        try {
          return await submitPreparedPlayRunAdmission(
            http,
            JSON.parse(bodyJson) as Record<string, unknown>,
            prepared.workflowId,
            prepared.supportsCallerIntent,
            headers,
            {
              cliAdmission: startOptions?.cliAdmission ?? options?.cliAdmission,
              callerIntentV2: options?.callerIntentV2,
              signal: startOptions?.signal ?? options?.signal,
            },
          );
        } catch (error) {
          if (
            error instanceof CliPlayAdmissionUnsupportedError ||
            error instanceof CliPlayAdmissionCallerIntentV2UnsupportedError
          ) {
            // These errors are raised only after an authoritative 404/405
            // from the admission route, so the fallback route cannot create
            // a second run.
            submitted = false;
          }
          throw error;
        }
      },
      async *startStream(streamOptions?: { signal?: AbortSignal }) {
        if (submitted && !prepared.supportsCallerIntent) {
          throw new DeeplineError(
            'This server has not enabled caller-owned admission recovery. Do not retry an ambiguous start.',
            409,
            'PLAY_RUN_ADMISSION_RECOVERY_UNSUPPORTED',
          );
        }
        if (submitted) {
          // A later transport attempt may reach a rolled-back server or a
          // different workspace. Re-prove support for the pinned intent,
          // without rebuilding it or persisting another submission journal.
          if (!options?.callerIntentV2) {
            await preparePlayRunAdmission(
              http,
              JSON.parse(bodyJson) as ResolvedStartPlayRunRequest,
              undefined,
              { signal: streamOptions?.signal },
            );
          }
        }
        submitted = true;
        const streamPath = options?.callerIntentV2
          ? CLI_PLAY_RUN_CALLER_INTENT_V2_START_STREAM_PATH
          : options?.cliAdmission
            ? CLI_PLAY_RUN_START_STREAM_PATH
            : PLAY_RUN_START_STREAM_PATH;
        let cliAdmissionSupported = false;
        try {
          for await (const event of http.streamSse<PlayLiveEvent>(streamPath, {
            method: 'POST',
            body: JSON.parse(bodyJson),
            headers,
            signal: streamOptions?.signal,
            exactUrlOnly: true,
            ...(options?.cliAdmission
              ? {
                  onResponse: (response: Response) => {
                    cliAdmissionSupported =
                      response.headers.get(CLI_PLAY_RUN_SUPPORTED_HEADER) ===
                      'true';
                  },
                }
              : {}),
          })) {
            if (event.scope === 'play') yield event;
          }
        } catch (error) {
          if (
            options?.cliAdmission &&
            !cliAdmissionSupported &&
            error instanceof DeeplineError &&
            (error.statusCode === 404 || error.statusCode === 405)
          ) {
            if (options.callerIntentV2) {
              submitted = false;
              throw new CliPlayAdmissionCallerIntentV2UnsupportedError(
                error.statusCode,
              );
            }
            submitted = false;
            throw new CliPlayAdmissionUnsupportedError(error.statusCode);
          }
          throw error;
        }
      },
    };
  }

  /**
   * Internal CLI helper. Reads the server's admission contract before local
   * preparation so the network round trip can overlap with compilation.
   * @internal
   */
  async prefetchPlayRunAdmissionCapability(options?: {
    signal?: AbortSignal;
  }): Promise<PlayRunAdmissionCapability> {
    return readPlayRunAdmissionCapability(this.http, options);
  }

  /**
   * Submit a play run through the legacy event response.
   *
   * This reports admission from the start request; it does not watch an
   * existing run. Use `startPlayRun()` and `watchRunEvents(runId)` separately.
   *
   * @deprecated Use the separate start and watch methods.
   *
   * @param request - Play run configuration.
   * @param options - Optional compatibility response options.
   * @param options.signal - Abort the start response.
   * @returns Async generator of play-scoped live events.
   */
  async *startPlayRunStream(
    request: StartPlayRunRequest,
    options?: {
      signal?: AbortSignal;
      onSubmission?: (intent: {
        workflowId: string;
        orgId: string;
        request: Record<string, unknown>;
      }) => void | Promise<void>;
    },
  ): AsyncGenerator<PlayLiveEvent> {
    const prepared = await this.preparePlayRunAdmission(request, options);
    yield* prepared.startStream({ signal: options?.signal });
  }

  /**
   * Register a bundled play artifact.
   *
   * Internal/advanced primitive used by packaging flows. Public callers should
   * prefer the CLI, {@link submitPlay}, or {@link runPlay}.
   */
  async registerPlayArtifact(input: {
    name: string;
    sourceCode: string;
    sourceFiles?: Record<string, string>;
    description?: string;
    artifact: Record<string, unknown>;
    compilerManifest?: PlayCompilerManifest;
    publish?: boolean;
    /** Store execution content without changing a draft or live revision. */
    artifactOnly?: boolean;
    ownerType?: 'org' | 'deepline';
    scope?: 'org' | 'system';
    userId?: string;
  }): Promise<{
    success?: boolean;
    name?: string;
    artifactStorageKey: string;
    artifactMetadata?: Record<string, unknown> | null;
    staticPipeline?: unknown;
    definitionId?: string | null;
    revisionId?: string | null;
    version?: number | null;
    liveVersion?: number | null;
    triggerMetadata?: unknown;
    triggerBindings?: unknown;
  }> {
    const compilerManifest =
      input.compilerManifest ??
      (await this.compilePlayManifest({
        name: input.name,
        sourceCode: input.sourceCode,
        sourceFiles: input.sourceFiles,
        artifact: input.artifact,
      }));
    return this.http.post(
      input.artifactOnly === true
        ? '/api/v2/plays/artifacts/immutable'
        : '/api/v2/plays/artifacts',
      {
        ...input,
        compilerManifest,
      },
      undefined,
      { retryApiErrors: true },
    );
  }

  /**
   * Register multiple bundled play artifacts in one request.
   *
   * Used by packaging and prebuilt publication flows. Each artifact is compiled
   * first when a compiler manifest is not already supplied.
   */
  async registerPlayArtifacts(
    artifacts: Array<{
      name: string;
      sourceCode: string;
      sourceFiles?: Record<string, string>;
      description?: string;
      artifact: Record<string, unknown>;
      compilerManifest?: PlayCompilerManifest;
      publish?: boolean;
      ownerType?: 'org' | 'deepline';
      scope?: 'org' | 'system';
      userId?: string;
    }>,
  ): Promise<{
    success: boolean;
    artifacts: Array<{
      success?: boolean;
      name?: string;
      artifactStorageKey: string;
      artifactMetadata?: Record<string, unknown> | null;
      staticPipeline?: unknown;
      definitionId?: string | null;
      revisionId?: string | null;
      version?: number | null;
      liveVersion?: number | null;
      triggerMetadata?: unknown;
      triggerBindings?: unknown;
    }>;
  }> {
    if (artifacts.length === 0) {
      return this.http.post(
        '/api/v2/plays/artifacts',
        { artifacts },
        undefined,
        { retryApiErrors: true },
      );
    }
    const compiledArtifacts = await mapWithConcurrency(
      artifacts,
      REGISTER_PLAY_ARTIFACTS_COMPILE_CONCURRENCY,
      async (artifact) => ({
        ...artifact,
        compilerManifest:
          artifact.compilerManifest ??
          (await this.compilePlayManifest({
            name: artifact.name,
            sourceCode: artifact.sourceCode,
            sourceFiles: artifact.sourceFiles,
            artifact: artifact.artifact,
          })),
      }),
    );
    const responses = [];
    for (const chunk of chunkRegisterPlayArtifacts(compiledArtifacts)) {
      responses.push(
        await this.http.post<{
          success: boolean;
          artifacts: Array<{
            success?: boolean;
            name?: string;
            artifactStorageKey: string;
            artifactMetadata?: Record<string, unknown> | null;
            staticPipeline?: unknown;
            definitionId?: string | null;
            revisionId?: string | null;
            version?: number | null;
            liveVersion?: number | null;
            triggerMetadata?: unknown;
            triggerBindings?: unknown;
          }>;
        }>(
          '/api/v2/plays/artifacts',
          {
            artifacts: chunk,
          },
          undefined,
          { retryApiErrors: true },
        ),
      );
    }
    return {
      success: responses.every((response) => response.success),
      artifacts: responses.flatMap((response) => response.artifacts),
    };
  }

  /**
   * Compile a bundled play artifact into the server-side compiler manifest.
   *
   * The manifest records imports, trigger bindings, static pipeline shape, and runtime metadata.
   * The compiler needs these records before it checks, registers, or runs a Play artifact.
   */
  async compilePlayManifest(input: {
    name: string;
    sourceCode: string;
    sourceFiles?: Record<string, string>;
    artifact: Record<string, unknown>;
    importedPlayDependencies?: PlayCompilerManifest[];
  }): Promise<PlayCompilerManifest> {
    const retryDelays = COMPILE_MANIFEST_RETRY_DELAYS_MS.slice(
      0,
      Math.max(0, this.config.maxRetries),
    );
    for (let attempt = 0; ; attempt += 1) {
      try {
        const response = await this.http.post<{
          compilerManifest: PlayCompilerManifest;
        }>('/api/v2/plays/compile-manifest', input);
        return requireCompileManifestResponse(response, input.name);
      } catch (error) {
        const delayMs = retryDelays[attempt];
        if (delayMs === undefined || !isTransientCompileManifestError(error)) {
          throw error;
        }
        await sleep(delayMs);
      }
    }
  }

  /**
   * Check a bundled play artifact against the server's current play compiler.
   *
   * Unlike {@link registerPlayArtifact}, this does not store the artifact,
   * publish a revision, or start a run. It is the authoritative cloud validation
   * path used by `deepline plays check`.
   */
  async checkPlayArtifact(input: {
    name?: string;
    sourceCode: string;
    sourceFiles?: Record<string, string>;
    description?: string;
    artifact: Record<string, unknown>;
    /** Which exported play in `sourceCode` this artifact is, when the file
     *  exports more than one. Omit for the default export. */
    exportName?: string | null;
    integrationMode?: 'live' | 'eval_stub' | 'fixture';
    /**
     * Sibling plays from the same local bundle graph. Lets the server splice
     * unpublished local children into the checked plan and enforce the
     * row-scoped batch rule (ADR 0013).
     */
    importedPlays?: Array<{
      playName?: string | null;
      sourceCode: string;
      sourcePath?: string | null;
    }>;
  }): Promise<PlayCheckResult> {
    const integrationMode = normalizePlayRunIntegrationMode(
      input.integrationMode ?? this.environment.DEEPLINE_EVAL_INTEGRATION_MODE,
    );
    return this.http.post('/api/v2/plays/check', {
      ...input,
      ...(integrationMode ? { integrationMode } : {}),
    });
  }

  /**
   * Compile legacy enrich command arguments into a runtime plan.
   *
   * @deprecated Retained for older clients. Use Plays for new enrichment workflows.
   */
  async compileEnrichPlan(input: {
    plan_args?: string[];
    config?: unknown;
    native_play_materialization?: 'macro' | 'inline_prebuilt';
  }): Promise<{ config: EnrichCompiledConfig }> {
    return this.http.post('/api/v2/enrich/compile', input);
  }

  /**
   * Register an already-bundled play artifact and start a run from it.
   *
   * SDK and CLI packaging wrappers use this low-level run method for file-based Plays.
   * Local bundling must produce the runtime artifact first.
   */
  async startPlayRunFromBundle(input: {
    name: string;
    sourceCode: string;
    sourceFiles?: Record<string, string>;
    description?: string;
    artifact: Record<string, unknown>;
    compilerManifest?: PlayCompilerManifest;
    input?: Record<string, unknown>;
    inputFile?: PlayStagedFileRef | null;
    packagedFiles?: PlayStagedFileRef[];
    force?: boolean;
    forceToolRefresh?: boolean;
  }): Promise<PlayRunStart> {
    const compilerManifest =
      input.compilerManifest ??
      (await this.compilePlayManifest({
        name: input.name,
        sourceCode: input.sourceCode,
        sourceFiles: input.sourceFiles,
        artifact: input.artifact,
      }));
    const registeredArtifact = await this.registerPlayArtifact({
      name: input.name,
      sourceCode: input.sourceCode,
      sourceFiles: input.sourceFiles,
      description: input.description,
      artifact: input.artifact,
      compilerManifest,
      publish: false,
    });
    if (!registeredArtifact.artifactStorageKey) {
      throw new Error(
        'registerPlayArtifact did not return an artifactStorageKey.',
      );
    }

    return this.startPlayRun({
      name: input.name,
      artifactStorageKey: registeredArtifact.artifactStorageKey,
      description: input.description,
      compilerManifest,
      ...(input.input ? { input: input.input } : {}),
      ...(input.inputFile ? { inputFile: input.inputFile } : {}),
      ...(input.packagedFiles?.length
        ? { packagedFiles: input.packagedFiles }
        : {}),
      ...(input.force ? { force: true } : {}),
      ...(input.forceToolRefresh ? { forceToolRefresh: true } : {}),
    });
  }

  /**
   * Register a bundled play artifact and start a run from the live revision.
   *
   * This method wraps {@link registerPlayArtifact} and {@link startPlayRun}.
   * Packaging wrappers use this method for file-based Plays.
   * Pass the returned ID to {@link getPlayStatus}.
   * The method returns the same durable `{ result }` object that `deepline run` saves when it completes.
   *
   * @param code - Fallback source string. Pass the bundled artifact in `options.artifact`.
   * @param csvPath - Path to the input CSV file, or `null`.
   * @param name - Play name. The SDK derives it from the source when omitted.
   * @param options - Additional submission options.
   * @returns Workflow metadata with `workflowId`
   *
   * @example
   * ```typescript
   * const started = await client.submitPlay(
   *   originalSource,
   *   './leads.csv',
   *   'bulk-enrich',
   *   { artifact: bundledArtifact, input: { limit: 100 } },
   * );
   * ```
   */
  async submitPlay(
    code: string,
    csvPath: string | null,
    name?: string,
    options?: {
      sourceCode?: string;
      sourceFiles?: Record<string, string>;
      description?: string;
      artifact?: Record<string, unknown>;
      compilerManifest?: PlayCompilerManifest;
      input?: Record<string, unknown>;
      inputFile?: PlayStagedFileRef | null;
      packagedFiles?: PlayStagedFileRef[];
      force?: boolean;
      forceToolRefresh?: boolean;
    },
  ): Promise<PlayRunStart> {
    const runtimeInput = options?.input ? { ...options.input } : {};

    if (csvPath) {
      runtimeInput.file = csvPath;
    }

    const sourceCode = options?.sourceCode ?? code;
    const artifact = options?.artifact;
    if (!name?.trim()) {
      throw new Error('submitPlay requires a play name.');
    }
    if (!artifact) {
      throw new Error('submitPlay requires a bundled play artifact.');
    }
    const compilerManifest =
      options?.compilerManifest ??
      (await this.compilePlayManifest({
        name,
        sourceCode,
        sourceFiles: options?.sourceFiles,
        artifact,
      }));

    const registeredArtifact = await this.registerPlayArtifact({
      name,
      sourceCode,
      sourceFiles: options?.sourceFiles,
      description: options?.description,
      artifact,
      compilerManifest,
      publish: false,
    });
    if (!registeredArtifact.artifactStorageKey) {
      throw new Error(
        'registerPlayArtifact did not return an artifactStorageKey.',
      );
    }

    return this.startPlayRun({
      name,
      artifactStorageKey: registeredArtifact.artifactStorageKey,
      sourceCode,
      description: options?.description,
      staticPipeline: registeredArtifact.staticPipeline ?? null,
      artifactHash:
        typeof artifact.artifactHash === 'string'
          ? artifact.artifactHash
          : undefined,
      graphHash:
        typeof artifact.graphHash === 'string' ? artifact.graphHash : undefined,
      runtimeArtifact: artifact,
      compilerManifest,
      ...(Object.keys(runtimeInput).length > 0 ? { input: runtimeInput } : {}),
      ...(options?.inputFile ? { inputFile: options.inputFile } : {}),
      ...(options?.packagedFiles?.length
        ? { packagedFiles: options.packagedFiles }
        : {}),
      ...(options?.force ? { force: true } : {}),
      ...(options?.forceToolRefresh ? { forceToolRefresh: true } : {}),
    });
  }

  /**
   * Upload files to the staging area for use in play runs.
   *
   * Internal/advanced primitive used by packaging flows. Public callers should
   * prefer the CLI, {@link submitPlay}, or {@link runPlay}.
   *
   * Staged files are referenced by their returned {@link PlayStagedFileRef}
   * in subsequent {@link startPlayRun} calls via `inputFile` or `packagedFiles`.
   *
   * @param files - Array of files to stage (base64-encoded content)
   * @returns Array of staged file references
   *
   * @example
   * ```typescript
   * const staged = await client.stagePlayFiles([{
   *   logicalPath: 'data/leads.csv',
   *   contentBase64: Buffer.from(csvContent).toString('base64'),
   *   contentHash: sha256(csvContent),
   *   contentType: 'text/csv',
   *   bytes: csvContent.length,
   * }]);
   * // Use staged[0] as inputFile in startPlayRun
   * ```
   */
  async stagePlayFiles(
    files: Array<{
      logicalPath: string;
      contentBase64: string;
      contentHash: string;
      contentType: string;
      bytes: number;
    }>,
  ): Promise<PlayStagedFileRef[]> {
    return stagePlayFiles(this.http, files);
  }

  /**
   * Mint short-lived presigned upload targets for staged play files.
   *
   * Internal primitive used by {@link stagePlayFiles}. For a content-addressed file already in storage, the server returns a staged reference. That file needs no upload.
   * For other files, the server returns a presigned PUT URL. Upload the file body to that URL.
   */
  async mintStagedPlayFileUploads(
    files: Array<{
      logicalPath: string;
      contentHash: string;
      contentType: string;
      bytes: number;
    }>,
  ): Promise<MintStagedFileUpload[]> {
    return mintStagedPlayFileUploads(this.http, files);
  }

  /**
   * Resolve staged play files by content hash without uploading bytes.
   *
   * The response identifies missing files. Callers need to upload only these files.
   */
  async resolveStagedPlayFiles(
    files: Array<{
      logicalPath: string;
      contentHash: string;
      contentType: string;
      bytes: number;
    }>,
  ): Promise<{
    files: PlayStagedFileRef[];
    missing: Array<{ logicalPath: string; contentHash: string }>;
  }> {
    return this.http.post<{
      files: PlayStagedFileRef[];
      missing: Array<{ logicalPath: string; contentHash: string }>;
    }>('/api/v2/plays/files/stage', { files });
  }

  // ——————————————————————————————————————————————————————————
  // Plays — status and monitoring
  // ——————————————————————————————————————————————————————————

  /**
   * Get the current status of a play execution.
   *
   * Internal/advanced primitive. Public callers should usually prefer
   * {@link runPlay}, {@link PlayJob.get}, or `deepline run`.
   *
   * @param workflowId - Play-run id from {@link startPlayRun}
   * @returns Current status with progress logs and partial results
   *
   * @example
   * ```typescript
   * const status = await client.getPlayStatus('play-abc123');
   * console.log(`Status: ${status.status}`);
   * console.log(`Logs: ${status.progress?.logs.length ?? 0} lines`);
   * ```
   */
  async getPlayStatus(
    workflowId: string,
    options?: { billing?: boolean; full?: boolean; runStatus?: boolean },
  ): Promise<PlayStatus> {
    return this.playClient.getPlayStatus(workflowId, options);
  }

  /**
   * Poll authenticated snapshots and emit changes; `deferLogs` delays terminal logs; `omitTerminalLogs` skips them.
   */
  async *watchRunEvents(
    workflowId: string,
    options?: {
      signal?: AbortSignal;
      onNotice?: (message: string) => void;
      onRetry?: RunsWatchOptions['onRetry'];
      /** Defer log-store reads until the run is terminal; the final log tail is unchanged. */
      deferLogs?: boolean;
      /** Skip log-store reads entirely for consumers that never render run logs. */
      omitTerminalLogs?: boolean;
      /** @internal Exposes bounded request timing for CLI diagnostics. */
      onPoll?: (observation: WatchPollObservation) => void;
      /** @internal Receive the requested durable status before terminal events. */
      terminalStatus?: {
        full?: boolean;
        billing?: boolean;
        runStatus?: boolean;
        onStatus: (status: PlayStatus) => void | Promise<void>;
      };
    },
  ): AsyncGenerator<PlayLiveEvent> {
    for await (const event of pollRunSnapshotEvents({
      http: this.http,
      runId: workflowId,
      signal: options?.signal,
      onNotice: options?.onNotice,
      onRetry: options?.onRetry,
      deferLogs: options?.deferLogs,
      omitTerminalLogs: options?.omitTerminalLogs,
      onPoll: options?.onPoll,
      ...(options?.terminalStatus
        ? {
            terminalStatus: {
              ...options.terminalStatus,
              onStatus: async (
                raw: Record<string, unknown>,
                expectedStatus: string,
              ) => {
                const status = normalizePlayStatus(raw);
                if (
                  status.runId !== workflowId ||
                  status.status !== expectedStatus
                ) {
                  throw new Error(
                    `Run watch returned a mismatched terminal status for ${workflowId}.`,
                  );
                }
                await options.terminalStatus?.onStatus(status);
              },
            },
          }
        : {}),
    })) {
      yield event as PlayLiveEvent;
    }
  }

  /**
   * Read raw legacy SSE events for callers that explicitly require that
   * compatibility endpoint. Ordinary run watching uses REST snapshot polling.
   *
   * @deprecated Use `watchRunEvents` for ordinary run watching.
   */
  async *streamPlayRunEvents(
    workflowId: string,
    options?: {
      signal?: AbortSignal;
      lastEventId?: string;
      mode?: 'cli' | 'ui';
    },
  ): AsyncGenerator<PlayLiveEvent> {
    const headers =
      options?.lastEventId && options.lastEventId.trim()
        ? { 'Last-Event-ID': options.lastEventId.trim() }
        : undefined;
    const params = new URLSearchParams();
    params.set('mode', options?.mode ?? 'cli');
    for await (const event of this.http.streamSse<PlayLiveEvent>(
      `/api/v2/runs/${encodeURIComponent(workflowId)}/tail?${params.toString()}`,
      { signal: options?.signal, headers },
    )) {
      if (event.scope === 'play') {
        yield event;
      }
    }
  }

  /**
   * Compatibility alias for polling canonical run snapshots and emitting
   * their changed events.
   *
   * @deprecated Use `watchRunEvents`; kept as a source-compatible alias.
   * The `fallback` option is ignored because watching uses REST polling.
   */
  async *observeRunEvents(
    runId: string,
    options?: {
      signal?: AbortSignal;
      onNotice?: (message: string) => void;
      /** @deprecated Ignored; watching always uses REST snapshot polling. */
      fallback?: 'sse' | 'none';
    },
  ): AsyncGenerator<PlayLiveEvent> {
    yield* this.watchRunEvents(runId, {
      signal: options?.signal,
      onNotice: options?.onNotice,
    });
  }

  /** Poll snapshots to terminal status and return the durable package. */
  private async watchRunToTerminal(
    runId: string,
    options?: RunsWatchOptions,
  ): Promise<PlayStatus> {
    // Forward events without retaining their log history. Only lifecycle
    // evidence is needed here; the final package comes from the durable read.
    let terminalObserved = false;
    let terminalStatus: PlayStatus | null = null;
    for await (const event of this.watchRunEvents(runId, {
      signal: options?.signal,
      onNotice: options?.onNotice,
      onRetry: options?.onRetry ?? options?.onReconnect,
      terminalStatus: {
        runStatus: true,
        onStatus: (status) => {
          terminalStatus = status;
        },
      },
    })) {
      options?.onEvent?.(event);
      if (isTerminalPlayRunLifecycleStatus(playLiveRunStatus(event))) {
        terminalObserved = true;
      }
    }
    if (options?.signal?.aborted) {
      throw new DeeplineError('Run watch aborted.', undefined, 'ABORTED');
    }
    const refreshed = terminalStatus ?? (await this.getRunStatus(runId));
    if (
      terminalObserved ||
      isTerminalPlayRunLifecycleStatus(refreshed.status)
    ) {
      return refreshed;
    }
    throw new DeeplineError(
      `Run watch for ${runId} ended before a terminal status.`,
      undefined,
      'PLAY_WATCH_ENDED',
    );
  }

  /**
   * Wait for a run and return its terminal status.
   *
   * This source-compatible alias uses the same authenticated two-second REST
   * snapshot polling as `client.runs.watch`.
   *
   * @deprecated Use `client.runs.watch`; retained for SDK compatibility.
   * @param runId - Public Deepline play-run id.
   * @param options - Optional callbacks and cancellation signal.
   * @returns The final durable run status.
   */
  async tailRun(runId: string, options?: RunsTailOptions): Promise<PlayStatus> {
    return this.watchRunToTerminal(runId, options);
  }

  /**
   * Cancel a running play execution.
   *
   * Sends a stop request for the run.
   *
   * @param workflowId - Public Deepline play-run id to cancel
   *
   * @example
   * ```typescript
   * await client.cancelPlay('play-abc123');
   * ```
   */
  async cancelPlay(workflowId: string): Promise<void> {
    return this.playClient.cancelPlay(workflowId);
  }

  /**
   * Stop a running play execution, including open HITL waits.
   *
   * @param workflowId - Public Deepline play-run id to stop
   * @param options.reason - Optional audit/debug reason
   */
  async stopPlay(
    workflowId: string,
    options?: { reason?: string },
  ): Promise<StopPlayRunResult> {
    return this.playClient.stopPlay(workflowId, options);
  }

  /**
   * List recent runs for a named play.
   *
   * Returns runs sorted by start time (newest first), including workflow IDs,
   * status, timestamps, and metadata.
   *
   * @param playName - The play name to query
   * @returns Array of run summaries (empty array if no runs exist)
   *
   * @example
   * ```typescript
   * const runs = await client.listPlayRuns('email-waterfall');
   * for (const run of runs) {
   *   console.log(`${run.workflowId}: ${run.status} (${run.executionTime})`);
   * }
   * ```
   */
  async listPlayRuns(playName: string): Promise<PlayRunListItem[]> {
    return this.playClient.listPlayRuns(playName);
  }

  // ---------------------------------------------------------------------------
  // Legacy workflows (double-shipped). Thin pass-throughs over the live cloud
  // `/api/v2/workflows/*` API so the SDK CLI keeps existing cloud workflows
  // working while users migrate them to plays via `workflows transform`. Kept
  // intentionally minimal — workflows are a deprecated surface.
  // ---------------------------------------------------------------------------

  /** List the org's workflows. `GET /api/v2/workflows`. */
  async listWorkflows(options?: { limit?: number }): Promise<{
    workflows: Array<{
      id: string;
      name: string;
      status: string;
      current_published_version: number | null;
    }>;
  }> {
    const params = new URLSearchParams();
    if (typeof options?.limit === 'number') {
      params.set('limit', String(options.limit));
    }
    const query = params.size > 0 ? `?${params.toString()}` : '';
    return this.http.get(`/api/v2/workflows${query}`);
  }

  /**
   * Fetch a single workflow (including its published-revision config — the
   * input to `compileWorkflowConfigToPlay`). `GET /api/v2/workflows/:id`.
   */
  async getWorkflow(id: string): Promise<{
    workflow: {
      id: string;
      name: string;
      status: string;
      current_published_version: number | null;
      current_published_revision: {
        version: number;
        config: unknown;
      } | null;
    } | null;
    validation?: unknown;
  }> {
    return this.http.get(`/api/v2/workflows/${encodeURIComponent(id)}`);
  }

  /** Delete a workflow. `DELETE /api/v2/workflows/:id`. */
  async deleteWorkflow(id: string): Promise<unknown> {
    return this.http.delete(`/api/v2/workflows/${encodeURIComponent(id)}`);
  }

  /** Turn a workflow off. `POST /api/v2/workflows/:id/disable`. */
  async disableWorkflow(id: string): Promise<unknown> {
    return this.http.post(
      `/api/v2/workflows/${encodeURIComponent(id)}/disable`,
      {},
    );
  }

  /** Turn a workflow back on. `POST /api/v2/workflows/:id/enable`. */
  async enableWorkflow(id: string): Promise<unknown> {
    return this.http.post(
      `/api/v2/workflows/${encodeURIComponent(id)}/enable`,
      {},
    );
  }

  /** Create/update a workflow from config. `POST /api/v2/workflows/apply`. */
  async applyWorkflow(body: Record<string, unknown>): Promise<unknown> {
    return this.http.post('/api/v2/workflows/apply', body);
  }

  /** Validate a workflow config without saving. `POST /api/v2/workflows/lint`. */
  async lintWorkflow(body: Record<string, unknown>): Promise<unknown> {
    return this.http.post('/api/v2/workflows/lint', body);
  }

  /** Fetch live workflow request schemas. `GET /api/v2/workflows/schema`. */
  async getWorkflowSchema(subject?: string): Promise<unknown> {
    const params = new URLSearchParams();
    if (subject) params.set('subject', subject);
    const query = params.size > 0 ? `?${params.toString()}` : '';
    return this.http.get(`/api/v2/workflows/schema${query}`);
  }

  /** Queue a workflow run. `POST /api/v2/workflows/call`. */
  async callWorkflow(body: Record<string, unknown>): Promise<unknown> {
    return this.http.post('/api/v2/workflows/call', body);
  }

  /** List a workflow's runs. `GET /api/v2/workflows/:id/runs`. */
  async listWorkflowRuns(
    id: string,
    options?: { limit?: number },
  ): Promise<unknown> {
    const params = new URLSearchParams();
    if (typeof options?.limit === 'number') {
      params.set('limit', String(options.limit));
    }
    const query = params.size > 0 ? `?${params.toString()}` : '';
    return this.http.get(
      `/api/v2/workflows/${encodeURIComponent(id)}/runs${query}`,
    );
  }

  /** Fetch one workflow run. `GET /api/v2/workflows/:id/runs/:runId`. */
  async getWorkflowRun(id: string, runId: string): Promise<unknown> {
    return this.http.get(
      `/api/v2/workflows/${encodeURIComponent(id)}/runs/${encodeURIComponent(
        runId,
      )}`,
    );
  }

  /** Cancel a workflow run. `POST /api/v2/workflows/:id/runs/:runId/cancel`. */
  async cancelWorkflowRun(id: string, runId: string): Promise<unknown> {
    return this.http.post(
      `/api/v2/workflows/${encodeURIComponent(id)}/runs/${encodeURIComponent(
        runId,
      )}/cancel`,
      {},
    );
  }

  /**
   * Get a run by id using the public runs resource model.
   *
   * This is the SDK equivalent of:
   *
   * ```bash
   * deepline runs get <run-id>
   * ```
   */
  async getRunStatus(
    runId: string,
    options?: RunsGetOptions,
  ): Promise<PlayStatus> {
    const params = new URLSearchParams();
    if (options?.full === true) {
      params.set('full', 'true');
    }
    if (options?.configuration === true) {
      params.append('include', 'configuration');
    }
    if (options?.performance === true) {
      params.append('include', 'performance');
    }
    const query = params.size > 0 ? `?${params.toString()}` : '';
    const response = await this.http.get<Record<string, unknown>>(
      `/api/v2/runs/${encodeURIComponent(runId)}${query}`,
      { headers: { 'x-deepline-run-status': '1' } },
    );
    if (
      options?.configuration === true &&
      !Object.hasOwn(response, 'contract')
    ) {
      throw new DeeplineError(
        'This server does not support recorded configuration reads.',
        undefined,
        'RUN_CONFIGURATION_UNAVAILABLE',
      );
    }
    const status = normalizePlayStatus(response);
    if (options?.failedLogs !== true || status.status !== 'failed') {
      return status;
    }
    const requestedFailedLogLimit =
      typeof options.failedLogLimit === 'number' &&
      Number.isFinite(options.failedLogLimit)
        ? Math.max(1, Math.floor(options.failedLogLimit))
        : RUNS_FAILED_LOG_LIMIT;
    let failedLogs: RunsLogsResult;
    let failedLogsLoaded = true;
    try {
      failedLogs = await this.getRunLogs(runId, {
        failed: true,
        limit: Math.min(RUNS_FAILED_LOG_LIMIT, requestedFailedLogLimit),
      });
    } catch (error) {
      failedLogsLoaded = false;
      const retryCommand = `deepline runs logs ${runId} --failed`;
      const reason =
        error instanceof Error && error.message.trim()
          ? ` (${error.message.trim().slice(0, 500)})`
          : '';
      failedLogs = {
        runId,
        totalCount: 0,
        returnedCount: 0,
        firstSequence: null,
        lastSequence: null,
        truncated: false,
        hasMore: false,
        entries: [],
        view: 'failed',
        warning: `Failed logs could not be loaded${reason}. The run status and persisted datasets are still available.`,
        next: { logs: retryCommand },
      };
    }
    return {
      ...status,
      failedLogs: {
        ...failedLogs,
        view: 'failed' as const,
        ...(failedLogsLoaded
          ? {
              association: failedLogs.association ?? 'terminal_failure_window',
            }
          : {}),
      },
    };
  }

  /** Read one paginated, launch-scoped page of direct child Runs. */
  async getRunChildren(
    parentRunId: string,
    options: RunsChildrenOptions,
  ): Promise<RunChildrenPage> {
    const launchKey = options.launchKey.trim();
    if (!launchKey) {
      throw new DeeplineError(
        'runs.children requires a nonempty launchKey.',
        undefined,
        'INVALID_CHILD_RUN_LAUNCH_KEY',
      );
    }
    if (
      options.limit !== undefined &&
      (!Number.isInteger(options.limit) ||
        options.limit < 1 ||
        options.limit > 50)
    ) {
      throw new DeeplineError(
        'runs.children limit must be an integer from 1 to 50.',
        undefined,
        'INVALID_CHILD_RUN_PAGE_LIMIT',
      );
    }
    const params = new URLSearchParams({ launchKey });
    if (options.cursor !== undefined) params.set('cursor', options.cursor);
    if (options.limit !== undefined) params.set('limit', String(options.limit));
    return this.http.get<RunChildrenPage>(
      `/api/v2/runs/${encodeURIComponent(parentRunId)}/children?${params.toString()}`,
    );
  }

  /** Fetch only the legacy scalar lifecycle status for a run.
   *
   * @deprecated Use `client.runs.get(runId)` for the canonical run read.
   */
  async getRunLifecycleStatus(runId: string): Promise<RunLifecycleStatus> {
    const response = await this.http.get<RunLifecycleStatus>(
      `/api/v2/runs/${encodeURIComponent(runId)}/status`,
    );
    return response;
  }

  /**
   * List play runs using the public runs resource model.
   *
   * This is the SDK equivalent of:
   *
   * ```bash
   * deepline runs list --play <play-name> --status failed
   * ```
   */
  async listRuns(options: RunsListOptions): Promise<PlayRunListItem[]> {
    return (await this.listRunsPage(options)).runs;
  }

  /** The same tenant-scoped run history searched by the dashboard and CLI. */
  async getRunsHistory(
    options: RunsHistoryOptions = {},
  ): Promise<RunsHistoryPage> {
    const params = new URLSearchParams();
    const search = options.search?.trim();
    if (search && search.length > 200) {
      throw new Error('Run search must be at most 200 characters.');
    }
    if (options.type && options.type !== 'all' && !search) {
      throw new Error('runs.history options.type requires options.search.');
    }
    if (search) params.set('search', search);
    if (search && options.type) params.set('type', options.type);
    if (options.cursor) params.set('cursor', options.cursor);
    if (options.orgId) params.set('orgId', options.orgId);
    if (options.limit !== undefined) {
      if (!Number.isSafeInteger(options.limit) || options.limit < 1) {
        throw new Error(
          'runs.history options.limit must be a positive integer.',
        );
      }
      params.set('limit', String(options.limit));
    }
    return this.http.get<RunsHistoryPage>(
      `/api/v2/dashboard/runs-history?${params.toString()}`,
      { signal: options.signal },
    );
  }

  /** Read one run page without discarding server pagination metadata. */
  async listRunsPage(options: RunsListOptions): Promise<RunsListPage> {
    const playName = options.play?.trim();
    const params = new URLSearchParams();
    if (playName) {
      params.set('play', playName);
    }
    const status = options.status?.trim();
    if (status) {
      params.set('status', status);
    }
    const node = options.node?.trim();
    if (node) {
      if (!playName)
        throw new Error('runs.list options.node requires options.play.');
      if (node.length > 300)
        throw new Error(
          'runs.list options.node must be at most 300 characters.',
        );
      params.set('node', node);
    }
    if (typeof options.limit === 'number' && Number.isFinite(options.limit)) {
      params.set('limit', String(Math.max(1, Math.floor(options.limit))));
    }
    if (options.offset !== undefined) {
      if (
        !Number.isFinite(options.offset) ||
        !Number.isInteger(options.offset) ||
        options.offset < 0
      ) {
        throw new Error(
          'runs.list options.offset must be a non-negative integer.',
        );
      }
      if (!playName && options.offset > 0) {
        throw new Error('runs.list options.offset requires options.play.');
      }
      params.set('offset', String(options.offset));
    }
    if (!playName && !status) {
      throw new Error('runs.list requires options.play or options.status.');
    }
    params.set('compact', 'true');
    const response = await this.http.get<RunsListPage>(
      `/api/v2/runs?${params.toString()}`,
    );
    return { ...response, runs: response.runs ?? [] };
  }

  /** Read retained tool results without executing tools, preserving supplied key order and batching 100 keys per request. Obtain keys from exported evidence or execution metadata; each key must be nonempty, at most 2,048 characters and contain no CR, LF or NUL. Missing/expired results have an explicit per-key error. */
  async getRunReceipts(
    runId: string,
    options: { keys: string[] },
  ): Promise<import('./runs/receipts').RunToolReceiptsResponse> {
    if (
      !options.keys.length ||
      options.keys.some(
        (key) =>
          typeof key !== 'string' ||
          !key.trim() ||
          key.length > 2048 ||
          /[\r\n\0]/.test(key),
      )
    ) {
      throw Object.assign(
        new Error(
          'Supply nonempty receipt keys, at most 2048 characters each.',
        ),
        { exitCode: 2 },
      );
    }
    const receipts: import('./runs/receipts').RunToolReceiptResult[] = [];
    for (let offset = 0; offset < options.keys.length; offset += 100) {
      const keys = options.keys.slice(offset, offset + 100);
      const result = await this.http.post<
        import('./runs/receipts').RunToolReceiptsResponse
      >(`/api/v2/runs/${encodeURIComponent(runId)}/receipts/results`, { keys });
      if (
        result.runId !== runId ||
        result.receipts.length !== keys.length ||
        result.receipts.some(
          (receipt, index) => receipt.receiptKey !== keys[index],
        )
      ) {
        throw new Error(
          'Receipt response does not match the requested run and keys.',
        );
      }
      receipts.push(...result.receipts);
    }
    return { runId, receipts };
  }

  /** Get the exact original input retained for a run. This is intentionally separate from status. */
  async getRunInput(runId: string): Promise<{
    runId: string;
    input: Record<string, unknown> | unknown[];
    bytes: number;
    sha256: string | null;
    replayedFromRunId: string | null;
  }> {
    return this.http.get(`/api/v2/runs/${encodeURIComponent(runId)}/input`);
  }

  /**
   * Start a fresh run from a prior run's retained input and pinned revision.
   *
   * Every invocation sends an `Idempotency-Key`.
   * When the caller supplies no key, the SDK creates a fresh key once per call.
   * The transport reuses that key for network retries, so those retries produce one rerun.
   * Reuse an explicit key across separate invocations when the previous result is uncertain.
   * A different key starts another rerun.
   */
  async rerun(
    runId: string,
    options?: RerunOptions,
  ): Promise<RerunPlayRunResult> {
    const idempotencyKey = options?.idempotencyKey?.trim();
    if (options?.idempotencyKey !== undefined && !idempotencyKey) {
      throw new DeeplineError(
        'runs.rerun idempotencyKey must not be empty.',
        undefined,
        'INVALID_IDEMPOTENCY_KEY',
      );
    }
    return this.http.post<RerunPlayRunResult>(
      `/api/v2/runs/${encodeURIComponent(runId)}/rerun`,
      options?.inputOverrides ? { inputOverrides: options.inputOverrides } : {},
      { 'Idempotency-Key': idempotencyKey || globalThis.crypto.randomUUID() },
    );
  }

  /**
   * Continue a failed or cancelled run as the same run. Completed calls are
   * reused; only work the run had not finished runs. A run can be resumed for
   * 14 days after it stops. Refusals (still active, last attempt still
   * finishing, sandbox cleanup pending, window expired) throw a
   * {@link DeeplineError} with the server's code.
   */
  async resumeRun(runId: string): Promise<ResumePlayRunResult> {
    return this.http.post<ResumePlayRunResult>(
      `/api/v2/runs/${encodeURIComponent(runId)}/resume`,
      {},
    );
  }

  /**
   * Read a run's retained text tail (default 200), full retained stream (`all`), or terminal failure window (`failed`, at most 20). These are existing reads; sampling and retention loss cannot be recovered. See [run logs and events](run-events.md) for structured search and payload retrieval.
   *
   * This is the SDK equivalent of:
   *
   * ```bash
   * deepline runs logs <run-id> --limit 200
   * ```
   */
  async getRunLogs(
    runId: string,
    options?: RunsLogsOptions,
  ): Promise<RunsLogsResult> {
    if (options?.all === true && options.failed === true) {
      throw new DeeplineError(
        'runs.logs cannot combine all and failed views.',
        undefined,
        'INVALID_RUN_LOG_VIEW',
      );
    }
    if (options?.cursor !== undefined && options.failed === true) {
      throw new DeeplineError(
        'runs.logs cannot combine failed with cursor.',
        undefined,
        'INVALID_RUN_LOG_VIEW',
      );
    }
    if (options?.failed === true) {
      const requestedLimit =
        typeof options.limit === 'number' &&
        Number.isFinite(options.limit) &&
        options.limit > 0
          ? Math.trunc(options.limit)
          : RUNS_FAILED_LOG_LIMIT;
      const failedLimit = Math.min(RUNS_FAILED_LOG_LIMIT, requestedLimit);
      const page = await this.http.get<RunLogsPageResponse>(
        `/api/v2/runs/${encodeURIComponent(runId)}/logs?view=failed&limit=${failedLimit}`,
        { retryApiErrors: true },
      );
      return {
        runId: page.runId,
        totalCount: page.totalLogCount,
        returnedCount: page.entries.length,
        firstSequence: page.firstSeq,
        lastSequence: page.lastSeq,
        // The failed view is a complete designed window, not a pageable slice.
        // `truncated` means retention loss here; association/warning explain it.
        truncated: page.logsTruncated === true,
        hasMore: false,
        entries: page.entries.map((entry) => entry.line),
        view: page.view ?? 'failed',
        association: page.association ?? 'terminal_failure_window',
        ...(page.warning ? { warning: page.warning } : {}),
        ...(page.next ? { next: page.next } : {}),
        ...(page.logsTruncated ? { logsTruncated: true } : {}),
      };
    }
    const beforeSequence =
      options?.cursor !== undefined ? parseRunLogsCursor(options.cursor) : null;
    const limit = options?.all
      ? Number.MAX_SAFE_INTEGER
      : typeof options?.limit === 'number' &&
          Number.isFinite(options.limit) &&
          options.limit > 0
        ? Math.trunc(options.limit)
        : 200;
    const fetchPage = (afterSeq: number, pageLimit: number) =>
      this.http.get<RunLogsPageResponse>(
        `/api/v2/runs/${encodeURIComponent(runId)}/logs?afterSeq=${afterSeq}&limit=${pageLimit}`,
        { retryApiErrors: true },
      );
    // Probe for the run's stored extent, then read the LAST `limit` stored
    // lines (matching the historical tail-slice semantics) ending before the
    // cursor, paginating in server-capped pages until the window is exhausted.
    // Fence the read to this probe so concurrent appends cannot outgrow its count.
    const probe = await fetchPage(0, 1);
    const lastStoredSeq = probe.lastStoredSeq;
    const oldestStoredSeq = probe.entries[0]?.seq ?? null;
    const upperSeq =
      beforeSequence === null
        ? lastStoredSeq
        : Math.min(beforeSequence - 1, lastStoredSeq);
    const windowEndSeq = Math.min(upperSeq, lastStoredSeq);
    let afterSeq = options?.all ? 0 : Math.max(0, windowEndSeq - limit);
    const entries: Array<{ seq: number; line: string }> = [];
    while (entries.length < limit && afterSeq < upperSeq) {
      const page = await fetchPage(
        afterSeq,
        Math.min(
          RUN_LOGS_PAGE_LIMIT,
          limit - entries.length,
          upperSeq - afterSeq,
        ),
      );
      const inWindow = page.entries.filter((entry) => entry.seq <= upperSeq);
      if (inWindow.length === 0) {
        break;
      }
      entries.push(...inWindow);
      afterSeq = inWindow[inWindow.length - 1]!.seq;
      if (!page.hasMore || inWindow.length < page.entries.length) {
        break;
      }
    }
    const firstSequence = entries.length > 0 ? entries[0]!.seq : null;
    const lastSequence =
      entries.length > 0 ? entries[entries.length - 1]!.seq : null;
    const olderLinesExist =
      firstSequence !== null &&
      oldestStoredSeq !== null &&
      firstSequence > oldestStoredSeq;
    return {
      runId: probe.runId,
      totalCount: probe.totalLogCount,
      returnedCount: entries.length,
      firstSequence,
      lastSequence,
      truncated: entries.length < probe.totalLogCount,
      hasMore: olderLinesExist,
      nextCursor: olderLinesExist ? encodeRunLogsCursor(firstSequence) : null,
      entries: entries.map((entry) => entry.line),
      view: options?.all ? 'all' : 'tail',
      ...(probe.logsTruncated ? { logsTruncated: true } : {}),
    };
  }

  /** Query one page of this run's retained logs. `where` accepts typed objects or the shared filter language. */
  private async queryRunLogs(
    runId: string,
    options: RunsLogsQueryOptions = {},
  ): Promise<RunsLogsQueryResult> {
    this.assertRunLogQueryRunId(runId, options);
    const { runtime, ...query } = options;
    return this.postRunEventQuery(
      { ...query, operation: 'list', resource: 'logs', runId },
      runtime,
    );
  }

  /** Count matching retained logs exactly, without fetching list pages or saved results. */
  private async countRunLogs(
    runId: string,
    criteria: RunsLogCriteria = {},
  ): Promise<RunsLogsCountResult> {
    this.assertRunLogQueryRunId(runId, criteria);
    const { runtime, ...query } = criteria;
    return this.postRunEventQuery(
      { ...query, operation: 'count', resource: 'logs', runId },
      runtime,
    );
  }

  /** Summarize retained logs with explicit group pagination and count or numeric sums. */
  private async summarizeRunLogs(
    runId: string,
    options: RunsLogsSummaryOptions,
  ): Promise<RunsLogsSummaryResult> {
    this.assertRunLogQueryRunId(runId, options);
    const { runtime, ...query } = options;
    return this.postRunEventQuery(
      { ...query, operation: 'summarize', resource: 'logs', runId },
      runtime,
    );
  }

  /** Query one page of retained lifecycle, log and receipt events in the active organization. */
  private async listRunEvents(
    options: RunsEventsListOptions = {},
  ): Promise<RunsEventsListResult> {
    const { runtime, ...query } = options;
    return this.postRunEventQuery(
      { ...query, operation: 'list', resource: 'events' },
      runtime,
    );
  }

  /** Count matching retained events exactly in one server query. */
  private async countRunEvents(
    criteria: RunsEventsCriteria = {},
  ): Promise<RunsEventsCountResult> {
    const { runtime, ...query } = criteria;
    return this.postRunEventQuery(
      { ...query, operation: 'count', resource: 'events' },
      runtime,
    );
  }

  /**
   * Group retained events with exact counts, numeric sums and continuation.
   * Fractional sums use JavaScript number precision.
   */
  private async summarizeRunEvents(
    options: RunsEventsSummaryOptions,
  ): Promise<RunsEventsSummaryResult> {
    const { runtime, ...query } = options;
    return this.postRunEventQuery(
      { ...query, operation: 'summarize', resource: 'events' },
      runtime,
    );
  }

  /** Discover query fields and their recorded types; custom scalar fields use `context.<key>`. */
  private async getRunEventFields(
    resource: 'logs' | 'events' = 'events',
    options: RunsEventsFieldsOptions = {},
  ): Promise<RunEventFieldsResult> {
    const { runtime, ...query } = options;
    return this.postRunEventQuery(
      { ...query, operation: 'fields', resource },
      runtime,
    );
  }

  private async postRunEventQuery<T>(
    input: RunEventOperationRequest,
    selection?: PlayRuntimeSelection,
  ): Promise<T> {
    const request = normalizeRunEventOperationRequest(input);
    const params = new URLSearchParams();
    let headers: Record<string, string> | undefined;
    let selectedRuntime: PlayRuntimeSelection | undefined;
    if (selection !== undefined) {
      const runtime = normalizePlayRuntimeSelection(selection);
      if (!runtime) {
        throw new DeeplineError(
          'Run event queries require a valid Preview runtime selection.',
          undefined,
          'INVALID_RUNTIME_SELECTION',
        );
      }
      params.set('runtime', 'preview');
      params.set('namespace', runtime.namespace);
      if (runtime.backend) params.set('backend', runtime.backend);
      headers = runtimeSelectionHeaders(runtime, this.environment);
      selectedRuntime = runtime;
    } else {
      headers = isolatedCiRuntimeEventReadHeaders(this.environment);
    }
    const suffix = params.size > 0 ? `?${params.toString()}` : '';
    const result = await this.http.post<T>(
      `/api/v2/runs/events${suffix}`,
      request,
      headers,
      { retryApiErrors: true },
    );
    if (
      selectedRuntime &&
      result &&
      typeof result === 'object' &&
      'query' in result
    ) {
      return {
        ...result,
        query: {
          ...(result as { query: NormalizedRunEventQuery }).query,
          runtime: selectedRuntime,
        },
      };
    }
    return result;
  }

  private assertRunLogQueryRunId(runId: string, criteria: unknown): void {
    if (
      criteria &&
      typeof criteria === 'object' &&
      'runId' in criteria &&
      criteria.runId !== undefined &&
      criteria.runId !== runId
    ) {
      throw new RunEventQueryInputError(
        'Log criteria runId conflicts with the positional run ID. Pass the run ID only as the first argument.',
      );
    }
  }

  /** Read structured history across the active organization without requiring a run ID. Defaults to the last hour, newest first; use the returned cursor and exact time bounds to continue. See [run logs and events](run-events.md) for all kinds, indexed fields, payloads and SDK/API response types. */
  async searchRunEvents(
    options: RunsEventSearchOptions = {},
  ): Promise<RunsEventSearchResult> {
    const now = Date.now();
    const params = new URLSearchParams({
      since: options.since ?? new Date(now - 60 * 60 * 1000).toISOString(),
      until: options.until ?? new Date(now).toISOString(),
    });
    if (options.runId) params.set('runId', options.runId);
    if (options.playName) params.set('playName', options.playName);
    if (options.kind) params.set('kind', options.kind);
    if (options.jsonpath) params.set('jsonpath', options.jsonpath);
    if (options.includePayloads) params.set('payloads', 'true');
    if (options.limit !== undefined) params.set('limit', String(options.limit));
    if (options.cursor) params.set('cursor', options.cursor);
    let headers: Record<string, string> | undefined;
    if (options.runtime !== undefined) {
      const runtime = normalizePlayRuntimeSelection(options.runtime);
      if (!runtime) {
        throw new DeeplineError(
          'runs.searchEvents runtime must be a valid Preview selection.',
          undefined,
          'INVALID_RUNTIME_SELECTION',
        );
      }
      params.set('runtime', 'preview');
      params.set('namespace', runtime.namespace);
      if (runtime.backend) params.set('backend', runtime.backend);
      headers = runtimeSelectionHeaders(runtime, this.environment);
    } else {
      headers = isolatedCiRuntimeEventReadHeaders(this.environment);
    }
    return this.http.get<RunsEventSearchResult>(
      `/api/v2/runs/events?${params.toString()}`,
      { headers, retryApiErrors: true },
    );
  }

  /**
   * Read one page of immutable admitted and terminal rows for a Play Run dataset.
   * Follow nextCursor; coverage explicitly identifies unavailable or incomplete history.
   */
  async getPlayRunRowHistory(
    input: PlayRunRowHistoryOptions,
  ): Promise<RuntimeSheetRunRowMembershipPage> {
    const params = new URLSearchParams({
      runId: input.runId,
      tableNamespace: input.tableNamespace,
    });
    if (input.limit !== undefined) params.set('limit', String(input.limit));
    if (input.cursor !== undefined) params.set('cursor', input.cursor);
    return this.http.get(
      `/api/v2/plays/${encodeURIComponent(input.playName)}/sheet/history?${params}`,
    );
  }

  /**
   * Export persisted runtime-sheet rows for a play dataset/table namespace.
   *
   * This is the SDK form of exporting `deepline.dataset(...).run()` output for a
   * specific play and optional run id.
   */
  async getPlaySheetRows(input: {
    playName: string;
    tableNamespace: string;
    runId?: string;
    limit?: number;
    offset?: number;
    rowMode?: 'output' | 'all' | 'live';
    /** Keep exact row counts while omitting column aggregates with `counts`. */
    summary?: 'full' | 'counts';
    /** Cancel the page request, including its response body and retry waits. */
    signal?: AbortSignal;
  }): Promise<PlaySheetRowsResult> {
    const params = new URLSearchParams({
      tableNamespace: input.tableNamespace,
      limit: String(input.limit ?? 5000),
      offset: String(input.offset ?? 0),
    });
    if (input.runId?.trim()) {
      params.set('runId', input.runId.trim());
    }
    if (input.rowMode === 'all' || input.rowMode === 'live') {
      params.set('rowMode', input.rowMode);
    }
    if (input.summary === 'counts') {
      params.set('summary', 'counts');
    }
    const result = await this.http.get<PlaySheetRowsResult>(
      `/api/v2/plays/${encodeURIComponent(input.playName)}/sheet?${params.toString()}`,
      { signal: input.signal },
    );
    const requestedRunId = input.runId?.trim() || '';
    if (requestedRunId) {
      const confirmedRunId =
        result.scope?.kind === 'run' ? result.scope.runId.trim() : '';
      const foreignRowRunIds = [
        ...new Set(
          result.rows
            .map((row) =>
              typeof row.runId === 'string' ? row.runId.trim() : '',
            )
            .filter((runId) => runId && runId !== requestedRunId),
        ),
      ];
      if (
        result.scope?.kind !== 'run' ||
        confirmedRunId !== requestedRunId ||
        foreignRowRunIds.length > 0
      ) {
        throw new DeeplineError(
          `Run-scoped dataset export was not confirmed for ${requestedRunId}; no rows were returned to the caller. Update Deepline, then retry the same export command. Do not rerun the play.`,
          undefined,
          'RUN_EXPORT_SCOPE_MISMATCH',
          {
            requestedRunId,
            confirmedScope: result.scope ?? null,
            foreignRowRunIds,
            playName: input.playName,
            tableNamespace: input.tableNamespace,
          },
        );
      }
    }
    return result;
  }

  /**
   * Stop a run by id using the public runs resource model.
   *
   * This is the SDK equivalent of:
   *
   * ```bash
   * deepline runs stop <run-id> --reason "stale lock"
   * ```
   */
  async stopRun(
    runId: string,
    options?: { reason?: string },
  ): Promise<StopPlayRunResult> {
    return this.http.post<StopPlayRunResult>(
      `/api/v2/runs/${encodeURIComponent(runId)}/stop`,
      options?.reason ? { reason: options.reason } : {},
    );
  }

  /** Enumerate the runs a stop-all would target without cancelling any. */
  async stopAllRuns(
    options: StopAllRunsOptions & { dryRun: true },
  ): Promise<StopAllPlayRunsDryRunResult>;
  /** Stop every active run visible to the current workspace. */
  async stopAllRuns(
    options?: StopAllRunsOptions & { dryRun?: false },
  ): Promise<StopAllPlayRunsStopResult>;
  /** Stop, or with `dryRun: true` only enumerate, active workspace runs. */
  async stopAllRuns(
    options?: StopAllRunsOptions,
  ): Promise<StopAllPlayRunsResult>;
  /**
   * Stop every active run visible to the current workspace.
   * With `dryRun: true`, list the exact candidates without cancelling any run.
   *
   * This is the SDK equivalent of:
   *
   * ```bash
   * deepline runs stop-all --dry-run
   * deepline runs stop-all --reason "stale lock"
   * ```
   *
   * Use this method when a failed parent leaves active child or waiting runs.
   * The method clears workspace run-slot state without requiring each run ID.
   */
  async stopAllRuns(
    options?: StopAllRunsOptions,
  ): Promise<StopAllPlayRunsResult> {
    const dryRun = options?.dryRun === true;
    const result = await this.http.post<StopAllPlayRunsResult>(
      '/api/v2/runs/stop-all',
      {
        ...(options?.reason ? { reason: options.reason } : {}),
        ...(dryRun ? { dryRun: true } : {}),
      },
    );
    if (dryRun && !isStopAllPlayRunsDryRunResult(result)) {
      // An older server ignores unknown body fields and would have stopped
      // runs for real. It cannot un-stop them, so say exactly what happened.
      throw new DeeplineError(
        'This Deepline server does not support runs stop-all --dry-run and performed a real stop-all. Update the server before using --dry-run.',
        undefined,
        'STOP_ALL_DRY_RUN_UNSUPPORTED',
      );
    }
    return result;
  }

  /**
   * List one page of callable Plays. With grep, the method retains all matching results.
   * Use listPlaysPage for pagination metadata.
   *
   * Pass `origin: "prebuilt"` for Deepline-managed prebuilts or
   * `origin: "owned"` for org-owned plays.
   */
  async listPlays(options?: PlaysListOptions): Promise<PlayListItem[]> {
    if (!options?.grep?.trim()) {
      return (await this.requestPlaysPage(options, false)).plays;
    }
    const plays: PlayListItem[] = [];
    for await (const items of iterateCursorPages(async (cursor) => {
      const page = await this.listPlaysPage({ ...options, cursor });
      return { items: page.plays, cursor: page.cursor, hasMore: page.hasMore };
    })) {
      plays.push(...items);
    }
    return plays;
  }

  /** Read one bounded inventory page; cursor continues the same filters. */
  async listPlaysPage(
    options?: PlaysListOptions & {
      limit?: number;
      cursor?: string | null;
    },
  ): Promise<PlaysListPage> {
    return this.requestPlaysPage(options);
  }

  /** Count durable Play runs and Monitor deliveries in local calendar days. */
  async getPlaysActivity(
    options: {
      timeZone?: string;
      days?: number;
      endDate?: string;
      groupBy?: 'kind' | 'trigger_source';
    } = {},
  ): Promise<PlaysActivityResponse> {
    return this.http.post('/api/v2/plays/activity', options);
  }

  private async requestPlaysPage(
    options?: PlaysListOptions & {
      limit?: number;
      cursor?: string | null;
    },
    paginateInventory = true,
  ): Promise<PlaysListPage> {
    const params = new URLSearchParams();
    if (paginateInventory && !options?.grep?.trim())
      params.set('inventory_paginated', '1');
    if (options?.origin) params.set('origin', options.origin);
    if (options?.summaryOnly) params.set('summary_only', '1');
    if (options?.categories) {
      params.set(
        'categories',
        Array.isArray(options.categories)
          ? options.categories.join(',')
          : options.categories,
      );
    }
    if (options?.categories || options?.includeToolCategories) {
      params.set('include_tool_categories', '1');
    }
    if (options?.tags) {
      params.set(
        'tags',
        Array.isArray(options.tags) ? options.tags.join(',') : options.tags,
      );
    }
    if (options?.includeArchived) params.set('include_archived', '1');
    if (options?.includeCostEstimates) {
      params.set('include_cost_estimates', '1');
    }
    if (options?.grep?.trim()) {
      params.set('grep', options.grep.trim());
      params.set('limit', '60');
    }
    if (options?.limit !== undefined) {
      if (!Number.isSafeInteger(options.limit) || options.limit < 1) {
        throw new Error('Play page limit must be a positive integer');
      }
      params.set('limit', String(options.limit));
    }
    if (options?.cursor) params.set('cursor', options.cursor);
    const suffix = params.size ? `?${params.toString()}` : '';
    const response = await this.http.get<{
      plays?: PlayListItem[];
      cursor?: string | null;
      hasMore?: boolean;
      pagination?: { cursor?: string | null; hasMore?: boolean };
    }>(`/api/v2/plays${suffix}`);
    return {
      plays: response.plays ?? [],
      cursor: response.pagination?.cursor ?? response.cursor ?? null,
      hasMore: Boolean(response.pagination?.hasMore ?? response.hasMore),
    };
  }

  /** Read definition-level settings, independently of code revisions. */
  async getPlaySettings(playName: string): Promise<PlaySettingsResult> {
    return this.http.get(
      `/api/v2/plays/${encodeURIComponent(playName)}/settings`,
    );
  }

  /** Retry-safe field patch; omitted fields retain their current value. */
  async updatePlaySettings(
    playName: string,
    patch: PlaySettingsPatch,
  ): Promise<PlaySettingsResult> {
    return this.http.patch(
      `/api/v2/plays/${encodeURIComponent(playName)}/settings`,
      patch,
    );
  }

  /** Read a Play's cron and webhook triggers and their scheduler state. */
  async getPlayTriggerConfig(playName: string): Promise<PlayTriggerConfigView> {
    return this.http.get(playTriggerConfigPath(playName));
  }

  /**
   * Declare a Play's cron and/or webhook trigger (null removes it) and publish
   * the rewritten source as a new live revision. Retry-safe: a request the
   * live revision already satisfies returns `changed: false`.
   */
  async updatePlayTriggerConfig(
    playName: string,
    update: PlayTriggerConfigUpdate,
  ): Promise<PlayTriggerConfigUpdateResult> {
    return this.http.put(playTriggerConfigPath(playName), update);
  }

  /** List one bounded page of existing Play locations; continue with cursor. */
  async listPlaySettingsPaths(
    options: { root?: 'person' | 'team'; limit?: number; cursor?: string } = {},
  ): Promise<PlaySettingsPathsPage> {
    const query = new URLSearchParams();
    for (const [key, value] of Object.entries(options))
      if (value !== undefined) query.set(key, String(value));
    return this.http.get(`/api/v2/plays/settings/paths?${query}`);
  }

  /** Set whether an org-owned Play sorts before unpinned Plays. */
  async setPlayPinned(
    playName: string,
    pinned: boolean,
  ): Promise<{ name: string; pinned: boolean }> {
    return this.http.post(`/api/v2/plays/${encodeURIComponent(playName)}/pin`, {
      pinned,
    });
  }

  /** Read product-notification destinations, subscriptions, event catalog, and DLQ health. */
  async getNotificationSettings(): Promise<ProductNotificationSettings> {
    return this.http.get('/api/v2/settings/notifications');
  }

  /** Get the dashboard link where a workspace owner or admin can connect a provider. */
  async getIntegrationConnectLink(
    provider: string,
  ): Promise<{ provider: string; connect_url: string }> {
    const params = new URLSearchParams({ provider });
    return this.http.get(`/api/v2/integrations/connect?${params}`);
  }

  /** Save provider-owned credential fields without starting an OAuth browser flow. */
  async setIntegrationCredentials(
    provider: string,
    credentials: Record<string, string>,
  ): Promise<{ ok: boolean; credential_saved?: boolean }> {
    return this.http.post('/api/v2/integrations/connect', {
      provider,
      credentials,
    });
  }

  /** Start provider OAuth and return the URL to open in a browser. */
  async startIntegrationOAuth(
    provider: string,
    options: {
      preset?: string;
      scopes?: string[];
      optionalScopes?: string[];
    } = {},
  ): Promise<{ ok: boolean; redirect_url: string }> {
    const scopes = options.scopes?.map((scope) => scope.trim()).filter(Boolean);
    if (scopes !== undefined && scopes.length === 0) {
      throw new Error('scopes must contain at least one OAuth scope.');
    }
    return this.http.post('/api/v2/integrations/connect', {
      provider,
      ...(options.preset !== undefined ? { preset: options.preset } : {}),
      ...(scopes !== undefined ? { scopes } : {}),
      ...(options.optionalScopes !== undefined
        ? { optional_scopes: options.optionalScopes }
        : {}),
    });
  }

  /** Start the Slack OAuth flow required by product notifications. */
  async connectNotificationSlack(options?: {
    successUrl?: string;
    failureUrl?: string;
  }): Promise<{ ok: boolean; redirect_url: string }> {
    return this.http.post('/api/v2/integrations/connect', {
      provider: 'slack',
      scopes: [...PRODUCT_NOTIFICATION_SLACK_OAUTH_SCOPES],
      ...(options?.successUrl ? { success_url: options.successUrl } : {}),
      ...(options?.failureUrl ? { failure_url: options.failureUrl } : {}),
    });
  }

  /** List Slack channels visible to the connected Deepline Slack app. */
  async listNotificationSlackChannels(query?: string): Promise<{
    identity: { teamId: string; teamName?: string };
    channels: Array<{ id: string; name: string; isPrivate: boolean }>;
  }> {
    const suffix = query ? `?query=${encodeURIComponent(query)}` : '';
    return this.http.get(`/api/v2/settings/notifications/channels${suffix}`);
  }

  /** Select a Slack channel or direct member used for product notifications. */
  async setNotificationSlack(destination: string | { memberId: string }) {
    return this.http.put(
      '/api/v2/settings/notifications',
      typeof destination === 'string' ? { channel: destination } : destination,
    );
  }

  /** Send one synchronous test ping and return Slack's delivery result. */
  async testNotificationSlack(): Promise<{
    ok: boolean;
    deliveryId: string;
    state: string;
    message: string;
  }> {
    return this.http.post('/api/v2/settings/notifications/test', {});
  }

  /** Disable Slack product notifications without deleting the OAuth connection. */
  async disableNotificationSlack() {
    return this.http.delete('/api/v2/settings/notifications');
  }

  /** Enable or disable event IDs from the server-provided notification catalog. */
  async setNotificationSubscriptions(eventTypes: string[], enabled: boolean) {
    return this.http.patch('/api/v2/settings/notifications/subscriptions', {
      eventTypes,
      enabled,
    });
  }

  /** List exhausted deliveries. Dead-lettered messages never replay automatically. */
  async listNotificationDlq(limit = 25) {
    return this.http.get(
      `/api/v2/settings/notifications/dlq?limit=${encodeURIComponent(String(limit))}`,
    );
  }

  /** Inspect one exhausted notification delivery. */
  async getNotificationDlqDelivery(deliveryId: string) {
    return this.http.get(
      `/api/v2/settings/notifications/dlq/${encodeURIComponent(deliveryId)}`,
    );
  }

  /** Explicitly retry or archive one dead-lettered notification delivery. */
  async updateNotificationDlqDelivery(
    deliveryId: string,
    action: 'retry' | 'archive',
  ) {
    return this.http.post(
      `/api/v2/settings/notifications/dlq/${encodeURIComponent(deliveryId)}`,
      { action },
    );
  }

  /** List the workspace's named notification rules. */
  async getNotifications(): Promise<ProductNotificationSettings> {
    return this.http.get('/api/v2/notifications');
  }

  /** Read the group-based product-notification configuration and rule catalog. */
  async getNotificationConfiguration(): Promise<ProductNotificationConfigurationResponse> {
    return this.http.get('/api/v2/notifications/configuration');
  }

  /** Atomically apply one retry-safe desired configuration change. */
  async changeNotificationConfiguration(
    expectedWorkspaceVersion: number,
    change: ProductNotificationConfigurationChange,
  ): Promise<Pick<ProductNotificationConfigurationResponse, 'configuration'>> {
    return this.http.put('/api/v2/notifications/configuration', {
      expectedWorkspaceVersion,
      change,
    });
  }

  /** Create one notification group and its destinations as a retry-safe unit. */
  async createNotificationGroup(
    input: CreateNotificationGroupInput,
  ): Promise<CreateNotificationGroupResult> {
    const name = input.name.trim().replace(/\s+/g, ' ');
    if (!name) throw new Error('Notification group name is required.');
    if (
      input.targets.length < 1 ||
      input.targets.length > MAX_NOTIFICATION_GROUP_CREATE_TARGETS
    ) {
      throw new Error(
        `Choose between 1 and ${MAX_NOTIFICATION_GROUP_CREATE_TARGETS} notification targets.`,
      );
    }

    const targets = input.targets.map(parseNotificationGroupTarget);
    const legacyEvents = input.legacyEvents ?? [];
    const legacyTarget =
      targets.length === 1 &&
      targets[0]?.kind === 'slack' &&
      legacyEvents.length > 0
        ? targets[0]
        : null;
    if (legacyEvents.length > 0 && !legacyTarget) {
      throw new Error(
        '--for is supported only by the legacy one-Slack-target form. Create the group first, then add rules in notification configuration.',
      );
    }

    if (!legacyTarget && name.toLowerCase() === 'default') {
      throw new Error(
        'Default is reserved for the workspace default notification group.',
      );
    }

    const normalizedTargets = targets.map((target) =>
      target.kind === 'email'
        ? `email:${target.email}`
        : 'memberId' in target
          ? `slack:member:${target.memberId}`
          : `slack:${target.channel}`,
    );
    if (input.dryRun) {
      return {
        mode: 'dry_run' as const,
        compatibilityMode: legacyTarget !== null,
        name: legacyTarget ? input.name : name,
        targets: normalizedTargets,
        legacyEvents,
      };
    }

    if (legacyTarget) {
      const notification = await this.createNotification({
        name: input.name,
        provider: 'slack',
        ...('channel' in legacyTarget
          ? { channel: legacyTarget.channel }
          : { memberId: legacyTarget.memberId }),
        eventTypes: legacyEvents,
      });
      return { mode: 'legacy' as const, notification };
    }

    const current = await this.getNotificationConfiguration();
    const existingGroup = current.configuration.groups.find(
      (candidate) => candidate.name.toLowerCase() === name.toLowerCase(),
    );
    const groupKey = existingGroup?.groupKey ?? notificationObjectKey('group');
    const group: EffectiveProductNotificationGroup = existingGroup ?? {
      groupKey,
      name,
      enabled: true,
      deliveryTiming: DEFAULT_PRODUCT_NOTIFICATION_DELIVERY_TIMING,
      source: 'workspace',
      configMode: 'custom',
      version: 0,
    };
    const destinations = current.configuration.destinations.filter(
      (destination) => destination.groupKey === groupKey,
    );

    const emails = [
      ...new Set(
        targets.flatMap((target) =>
          target.kind === 'email' ? [target.email] : [],
        ),
      ),
    ].sort();
    const existingEmails = new Set(
      destinations.flatMap((destination) =>
        destination.settings.kind === 'email_addresses'
          ? destination.settings.to
          : [],
      ),
    );
    const newEmails = emails.filter((email) => !existingEmails.has(email));
    if (newEmails.length > 0) {
      destinations.push({
        destinationKey: notificationObjectKey('destination'),
        groupKey,
        name: 'Email recipients',
        enabled: true,
        source: 'workspace',
        configMode: 'custom',
        version: 0,
        status: 'active',
        settings: { kind: 'email_addresses', to: newEmails },
      });
    }

    const slackTargets = new Map<
      string,
      Extract<ParsedNotificationGroupTarget, { kind: 'slack' }>
    >();
    for (const target of targets) {
      if (target.kind !== 'slack') continue;
      const targetKey =
        'memberId' in target
          ? `member:${target.memberId}`
          : `channel:${target.channel.replace(/^#/, '').toLowerCase()}`;
      slackTargets.set(targetKey, target);
    }
    const connectionId = current.slackConnection.connectionId;
    if (slackTargets.size > 0 && !connectionId) {
      throw new Error(
        'Slack is not connected to this workspace. Connect it in Dashboard → Integrations, then retry.',
      );
    }
    const resolvedSlackTargets = await Promise.all(
      [...slackTargets.values()].map(async (target) => {
        if ('memberId' in target) {
          return {
            targetKind: 'member' as const,
            targetId: target.memberId,
            targetName: target.memberId,
          };
        }
        const channel = target.channel;
        const requested = channel.replace(/^#/, '');
        const response = await this.listNotificationChannels(channel);
        const matches = response.channels.filter(
          (candidate) =>
            candidate.id === requested ||
            candidate.name.toLowerCase() === requested.toLowerCase(),
        );
        if (matches.length !== 1) {
          throw new Error(
            matches.length === 0
              ? `Slack channel ${channel} was not found or is not visible to the Deepline app.`
              : `Slack channel ${channel} is ambiguous. Use its channel ID.`,
          );
        }
        return {
          targetKind: 'channel' as const,
          targetId: matches[0]!.id,
          targetName: matches[0]!.name,
        };
      }),
    );
    const uniqueSlackTargets = new Map(
      resolvedSlackTargets.map((target) => [
        `${target.targetKind}:${target.targetId}`,
        target,
      ]),
    );
    for (const target of uniqueSlackTargets.values()) {
      if (
        destinations.some(
          (destination) =>
            destination.settings.kind === 'slack' &&
            destination.settings.targetKind === target.targetKind &&
            destination.settings.targetId === target.targetId,
        )
      ) {
        continue;
      }
      destinations.push({
        destinationKey: notificationObjectKey('destination'),
        groupKey,
        name: `${target.targetKind === 'channel' ? '#' : '@'}${target.targetName}`,
        enabled: true,
        source: 'workspace',
        configMode: 'custom',
        version: 0,
        status: 'pending_verification',
        settings: {
          kind: 'slack',
          ...target,
          oauthConnectionId: connectionId!,
        },
      });
    }

    const draft: ProductNotificationGroupDraft = {
      group,
      destinations,
      rules: current.configuration.rules.filter(
        (rule) => rule.groupKey === groupKey,
      ),
    };
    const result = await this.changeNotificationConfiguration(
      current.configuration.workspaceVersion,
      { kind: 'save_group', draft },
    );
    const storedGroup = result.configuration.groups.find(
      (candidate) => candidate.groupKey === groupKey,
    );
    if (!storedGroup) {
      throw new Error('Notification group creation returned no saved group.');
    }
    return {
      mode: 'native' as const,
      groupKey,
      targets: normalizedTargets,
      group: storedGroup,
      destinations: result.configuration.destinations.filter(
        (destination) => destination.groupKey === groupKey,
      ),
    };
  }

  /** List Slack channels available to an already-connected Slack integration. */
  async listNotificationChannels(query?: string): Promise<{
    identity: { teamId: string; teamName?: string };
    channels: Array<{ id: string; name: string; isPrivate: boolean }>;
  }> {
    const suffix = query ? `?search=${encodeURIComponent(query)}` : '';
    return this.http.get(`/api/v2/notifications/slack/channels${suffix}`);
  }

  /** Create a named notification routed through an existing provider integration. */
  async createNotification(input: CreateNotificationInput) {
    return this.http.post('/api/v2/notifications', input);
  }

  /** Update a notification's target, event selection, or enabled state. */
  async updateNotification(
    notificationId: string,
    input: UpdateNotificationInput,
  ) {
    return this.http.patch(
      `/api/v2/notifications/${encodeURIComponent(notificationId)}`,
      input,
    );
  }

  /** Send a validation ping to one notification. */
  async testNotification(notificationId: string): Promise<{
    ok: boolean;
    deliveryId: string;
    state: string;
    message: string;
  }> {
    return this.http.post(
      `/api/v2/notifications/${encodeURIComponent(notificationId)}/test`,
      {},
    );
  }

  /** Archive one notification without touching its provider integration. */
  async deleteNotification(
    notificationId: string,
  ): Promise<{ deleted: boolean; id: string }> {
    return this.http.delete(
      `/api/v2/notifications/${encodeURIComponent(notificationId)}`,
    );
  }

  /**
   * Search callable plays and return compact play descriptions.
   *
   * Prebuilt plays are preferred by default because they have maintained
   * contracts and stable run behavior.
   */
  async searchPlays(options: {
    query: string;
    compact?: boolean;
    /** Include compiled pipelines. Defaults to true for compatibility. */
    pipeline?: boolean;
    scope?: 'prebuilt' | 'owned' | 'all';
    cliInvocationId?: string;
  }): Promise<PlayDescription[]> {
    if (options.cliInvocationId !== undefined) {
      validateCliInvocationId(options.cliInvocationId);
    }
    const params = new URLSearchParams();
    params.set('search', options.query.trim());
    const scope = options.scope ?? 'prebuilt';
    if (scope !== 'all') {
      params.set('origin', scope);
    }
    const response = await this.http.get<{ plays: PlayListItem[] }>(
      `/api/v2/plays?${params.toString()}`,
      {
        ...(options.cliInvocationId !== undefined
          ? {
              headers: {
                'x-deepline-cli-invocation-id': options.cliInvocationId,
              },
            }
          : {}),
      },
    );
    const plays = (response.plays ?? []).map((play) =>
      describePlayListItem(play, {
        ...options,
        pipeline: options.pipeline ?? true,
      }),
    );
    if (scope === 'prebuilt') {
      return plays.filter(isPrebuiltPlayDescription);
    }
    if (scope === 'owned') {
      return plays.filter((play) => !isPrebuiltPlayDescription(play));
    }
    return preferPrebuiltPlayDescriptions(plays);
  }

  /**
   * Get the full definition and state of a named play.
   *
   * The response includes revision state (draft or live), recent runs, a summary of sheet processing, and the database URL.
   *
   * @param name - Play name
   * @returns Complete play detail
   *
   * @example
   * ```typescript
   * const detail = await client.getPlay('email-waterfall');
   * console.log(`Live: v${detail.play.currentPublishedVersion}`);
   * console.log(`Draft dirty: ${detail.play.isDraftDirty}`);
   * console.log(`Total runs: ${detail.play.runCount}`);
   * ```
   */
  async getPlay(
    name: string,
    options?: {
      source?: 'working' | 'live' | `version:${number}`;
      guidance?: boolean;
    },
  ): Promise<PlayDetail> {
    return this.playClient.getPlay(name, options);
  }

  /** Estimate one Play without reading the rest of the workspace catalog. */
  async getPlayCostEstimate(name: string): Promise<PlayCostEstimateResult> {
    return this.http.get(`/api/v2/plays/${encodeURIComponent(name)}/cost`);
  }

  /** Read one trigger inventory page without loading run histories. */
  async listPlayTriggerInventory(options?: { cursor?: string }): Promise<{
    page: Array<{
      bindingId: string;
      name: string;
      type: string;
      status: string;
      cron: string | null;
      timezone: string | null;
      nextScheduledAt: number | null;
    }>;
    continueCursor: string;
    isDone: boolean;
  }> {
    const params = new URLSearchParams({ view: 'inventory' });
    if (options?.cursor) params.set('cursor', options.cursor);
    return this.http.get(`/api/v2/plays/triggers?${params}`);
  }

  /** Read one trigger's recent runs, with an explicit partial-history flag. */
  async getPlayTriggerHistory(
    bindingId: string,
    options?: { limit?: number },
  ): Promise<{
    recentRuns: Array<{
      workflowId: string;
      runId: string | null;
      status: string;
      createdAt: number;
      startedAt: number | null;
      finishedAt: number | null;
    }>;
    truncated: boolean;
    cronInput: Record<string, unknown> | null;
  }> {
    const params = new URLSearchParams({
      view: 'history',
      binding_id: bindingId,
    });
    if (options?.limit !== undefined)
      params.set('history_limit', String(options.limit));
    return this.http.get(`/api/v2/plays/triggers?${params}`);
  }

  /**
   * Get a normalized play description suitable for agents and CLIs.
   *
   * The description includes runnable examples, input and output summaries, clone guidance, and revision state.
   * It also includes metadata for the latest run when available.
   * Set `{ pipeline: true }` to include the compiled pipeline.
   * The pipeline can be hundreds of kilobytes. The response omits it by default.
   */
  async describePlay(
    name: string,
    options: PlayDescriptionOptions = {},
  ): Promise<PlayDescription> {
    if (options.pipeline) {
      return describePlayDetail(
        await this.getPlay(name, { guidance: true }),
        options,
      );
    }
    // The API describes the play itself, so only the description crosses
    // the wire; a definition carries source and pipelines on every revision.
    const params = new URLSearchParams({
      include: 'guidance',
      view: 'description',
      ...(options.compact ? { compact: '1' } : {}),
    });
    const body = await this.http.get<
      PlayDetail | { description: PlayDescription }
    >(`/api/v2/plays/${encodeURIComponent(name)}?${params.toString()}`);
    // An API without the description view answers with the definition.
    return 'description' in body
      ? body.description
      : describePlayDetail(body, options);
  }

  /**
   * Clear run history and durable sheet/result data for a play without deleting
   * the play definition or revisions.
   */
  async clearPlayHistory(
    name: string,
    request: ClearPlayHistoryRequest = {},
  ): Promise<ClearPlayHistoryResult> {
    return this.playClient.clearPlayHistory(name, request);
  }

  /**
   * List saved versions for a named play.
   *
   * Returns immutable revision snapshots newest-first, including the revision
   * id needed for exact-version runs and live-version switching.
   *
   * @param name - Play name
   * @returns Version list (newest first)
   */
  async listPlayVersions(
    name: string,
    options?: { full?: boolean },
  ): Promise<PlayRevisionSummary[]> {
    return this.playClient.listPlayVersions(name, options);
  }

  /**
   * Make a play revision live.
   *
   * When `revisionId` is omitted, the current working revision becomes live.
   * A call by Play name executes the live revision unless the caller specifies another revision.
   *
   * @param name - Play name
   * @param request - Optional explicit revision to make live
   * @returns Result with the new live version number
   *
   * @example
   * ```typescript
   * const result = await client.publishPlayVersion('email-waterfall');
   * if (result.success) {
   *   console.log(`Live v${result.liveVersion}`);
   * }
   * ```
   */
  async publishPlayVersion(
    name: string,
    request: PublishPlayVersionRequest = {},
  ): Promise<PublishPlayVersionResult> {
    return this.playClient.publishPlayVersion(name, request);
  }

  /**
   * Move an org-owned play to Trash. This disables its active triggers while
   * retaining its revisions and run history so it can be restored. Deepline
   * prebuilt plays are read-only.
   */
  async deletePlay(name: string): Promise<DeletePlayResult> {
    const encodedName = encodeURIComponent(name);
    return this.http.delete<DeletePlayResult>(`/api/v2/plays/${encodedName}`);
  }

  /** Restore an org-owned play that was previously moved to Trash. */
  async restorePlay(name: string): Promise<RestorePlayResult> {
    const encodedName = encodeURIComponent(name);
    return this.http.post<RestorePlayResult>(
      `/api/v2/plays/${encodedName}/restore`,
      {},
    );
  }

  // ——————————————————————————————————————————————————————————
  // Plays — public share pages
  // ——————————————————————————————————————————————————————————

  /**
   * Current share status for a play: the public page (if any), the published
   * copy, and the revision picker. Read-only.
   */
  async getSharePage(
    name: string,
    options: { revisionId?: string } = {},
  ): Promise<SharePageStatus> {
    const encodedName = encodeURIComponent(name);
    const revisionQuery = options.revisionId
      ? `?revisionId=${encodeURIComponent(options.revisionId)}`
      : '';
    return this.http.get<SharePageStatus>(
      `/api/v2/plays/${encodedName}/share${revisionQuery}`,
    );
  }

  /**
   * Publish (or repoint) the play's public share page to a revision. Requires
   * `acknowledgedUnlisted: true` — the page is publicly viewable. Org-admin only.
   */
  async publishSharePage(
    name: string,
    request: PublishSharePageRequest,
  ): Promise<SharePageStatus> {
    const encodedName = encodeURIComponent(name);
    return this.http.post<SharePageStatus>(
      `/api/v2/plays/${encodedName}/share`,
      request,
    );
  }

  /**
   * Update share-page settings (SEO indexing, credit-cost / latency display)
   * without moving the published pointer. Org-admin only.
   */
  async updateSharePage(
    name: string,
    request: UpdateSharePageRequest,
  ): Promise<SharePageStatus> {
    const encodedName = encodeURIComponent(name);
    return this.http.patch<SharePageStatus>(
      `/api/v2/plays/${encodedName}/share`,
      request,
    );
  }

  /**
   * Unshare: hard-delete the play's public page and its cards. Returns the
   * fresh status (now `share: null`). Org-admin only. Idempotent — a no-op when
   * the play was never published.
   */
  async unpublishSharePage(name: string): Promise<SharePageStatus> {
    const encodedName = encodeURIComponent(name);
    return this.http.delete<SharePageStatus>(
      `/api/v2/plays/${encodedName}/share`,
    );
  }

  /**
   * Regenerate the LLM landing-page copy for a revision (defaults to the
   * published one). Org-admin only.
   */
  async regenerateSharePage(
    name: string,
    request: { revisionId?: string } = {},
  ): Promise<SharePageStatus> {
    const encodedName = encodeURIComponent(name);
    return this.http.post<SharePageStatus>(
      `/api/v2/plays/${encodedName}/share/regenerate`,
      request,
    );
  }

  // ——————————————————————————————————————————————————————————
  // Plays — high-level orchestration
  // ——————————————————————————————————————————————————————————

  /**
   * Run a play end-to-end: submit, poll progress until terminal, return result.
   *
   * This is the highest-level play execution method. It submits the play,
   * reads the canonical run snapshot for status updates, and returns a structured
   * result with logs and timing. Supports cancellation via `AbortSignal`.
   *
   * @param code - Source string fallback; pass the bundled artifact in `options.artifact`
   * @param csvPath - Input CSV path, or `null`
   * @param name - Play name
   * @param options - Execution options
   * @returns Final execution result with success/failure, output, logs, and duration
   *
   * @example
   * ```typescript
   * const result = await client.runPlay(bundledCode, null, 'my-play', {
   *   input: { domain: 'stripe.com' },
   *   onProgress: (status) => {
   *     const logs = status.progress?.logs ?? [];
   *     console.log(`[${status.status}] ${logs.length} log lines`);
   *   },
   * });
   *
   * if (result.success) {
   *   console.log('Output:', result.result);
   * } else {
   *   console.error(`Failed after ${result.durationMs}ms:`, result.error);
   * }
   * ```
   *
   * @example Cancellation
   * ```typescript
   * const controller = new AbortController();
   * setTimeout(() => controller.abort(), 30_000); // 30s timeout
   *
   * const result = await client.runPlay(code, null, 'slow-play', {
   *   signal: controller.signal,
   * });
   * // result.success === false, result.error === 'Cancelled by user'
   * ```
   */
  async runPlay(
    code: string,
    csvPath: string | null,
    name?: string,
    options?: {
      /** Called for each status snapshot emitted by the run stream. */
      onProgress?: (status: PlayStatus) => void;
      /** Abort signal — triggers cancellation and immediate return. */
      signal?: AbortSignal;
      /** Runtime input for the play function. */
      input?: Record<string, unknown>;
      sourceCode?: string;
      artifact?: Record<string, unknown>;
      compilerManifest?: PlayCompilerManifest;
      inputFile?: PlayStagedFileRef | null;
      packagedFiles?: PlayStagedFileRef[];
      /** Compatibility flag; active sibling runs are allowed. */
      force?: boolean;
      /** Explicit cache-bypass flag for durable dataset and tool-call reuse. */
      forceToolRefresh?: boolean;
    },
  ): Promise<PlayRunResult> {
    const { workflowId } = await this.submitPlay(code, csvPath, name, {
      input: options?.input,
      sourceCode: options?.sourceCode,
      artifact: options?.artifact,
      compilerManifest: options?.compilerManifest,
      inputFile: options?.inputFile,
      packagedFiles: options?.packagedFiles,
      force: options?.force,
      forceToolRefresh: options?.forceToolRefresh,
    });
    const start = Date.now();
    const state: PlayLiveStatusState = {
      runId: workflowId,
      status: 'running',
      logs: [],
      lastLogSeq: 0,
      latest: null,
    };
    let terminalObserved: PlayStatus | null = null;

    if (options?.signal?.aborted) {
      await this.cancelPlay(workflowId);
      return {
        success: false,
        runId: workflowId,
        logs: [],
        durationMs: Date.now() - start,
        error: 'Cancelled by user',
      };
    }

    for await (const event of this.watchRunEvents(workflowId, {
      signal: options?.signal,
    })) {
      if (options?.signal?.aborted) {
        await this.cancelPlay(workflowId);
        return {
          success: false,
          runId: workflowId,
          logs: state.logs,
          durationMs: Date.now() - start,
          error: 'Cancelled by user',
        };
      }

      const previousStatus = state.latest?.status;
      const status = updatePlayLiveStatusState(state, event);
      if (!status) {
        continue;
      }
      if (
        event.type !== 'play.run.status' ||
        status.status !== previousStatus
      ) {
        options?.onProgress?.(status);
      }

      if (isTerminalPlayRunLifecycleStatus(status.status)) {
        terminalObserved = status;
      }
    }

    if (options?.signal?.aborted) {
      await this.cancelPlay(workflowId);
      return {
        success: false,
        runId: workflowId,
        logs: state.logs,
        durationMs: Date.now() - start,
        error: 'Cancelled by user',
      };
    }
    if (terminalObserved) {
      const finalStatus = await this.getPlayStatus(
        terminalObserved.runId || workflowId,
      ).catch(() => terminalObserved!);
      return playRunResultFromStatus(finalStatus, start, workflowId);
    }

    throw new DeeplineError(
      `Run watch for ${workflowId} ended before the run reached a terminal state.`,
      undefined,
      'PLAY_RUN_STREAM_ENDED',
      { runId: workflowId, workflowId },
    );
  }

  // ——————————————————————————————————————————————————————————
  // Health
  // ——————————————————————————————————————————————————————————

  /**
   * Published plans plus the caller's active plan: prices, monthly grant
   * credits, rollover policy, and which plans are open for subscription.
   * Prefer `client.billing.plans()`.
   *
   * @returns Snake_case catalog from `GET /api/v2/billing/catalog/current`
   */
  async getBillingPlans(): Promise<BillingPlansResult> {
    return this.http.get<BillingPlansResult>('/api/v2/billing/catalog/current');
  }

  /**
   * Read the authenticated usage record for one execution request. The
   * request id comes from the original `executeTool` result and is not a
   * retry or idempotency token.
   */
  async getBillingUsageEvent(requestId: string): Promise<BillingUsageEvent> {
    const normalizedRequestId = requestId.trim();
    if (
      normalizedRequestId.length === 0 ||
      normalizedRequestId.length > 200 ||
      normalizedRequestId !== requestId
    ) {
      throw new DeeplineError(
        'Usage request_id must contain 1–200 characters with no leading or trailing whitespace.',
        undefined,
        'INVALID_USAGE_REQUEST_ID',
      );
    }
    const response = await this.http.get<{
      entries?: BillingUsageEvent[];
    }>(
      `/api/v2/usage/events?request_id=${encodeURIComponent(normalizedRequestId)}`,
    );
    const event = response.entries?.[0];
    if (!event) {
      throw new DeeplineError(
        'No usage event was found for this request_id.',
        undefined,
        'USAGE_EVENT_NOT_FOUND',
      );
    }
    return event;
  }

  /**
   * Read one authenticated raw usage-event page. This history is not a final
   * charge or settlement oracle. Empty pages may still carry a continuation.
   */
  async getBillingUsageEvents(
    options: BillingUsageEventsOptions = {},
  ): Promise<BillingUsageEventsResult> {
    const invalid = (message: string): never => {
      throw new DeeplineError(
        message,
        undefined,
        'INVALID_USAGE_EVENTS_OPTIONS',
      );
    };
    if ('offset' in options) {
      invalid(
        'Usage events do not support offset; use the preceding next_cursor.',
      );
    }
    const params = new URLSearchParams();
    if (options.limit !== undefined) {
      if (
        !Number.isInteger(options.limit) ||
        options.limit < 1 ||
        options.limit > 500
      ) {
        invalid('Usage events limit must be an integer from 1 to 500.');
      }
      params.set('limit', String(options.limit));
    }
    for (const [name, value] of [
      ['cursor', options.cursor],
      ['run_id', options.runId],
    ] as const) {
      if (value !== undefined) {
        if (typeof value !== 'string' || !value || value !== value.trim()) {
          invalid(
            `Usage events ${name} must be a non-empty string without surrounding whitespace.`,
          );
        }
        params.set(name, value);
      }
    }
    const query = params.toString();
    const querySuffix = query ? `?${query}` : '';
    return this.http.get<BillingUsageEventsResult>(
      `/api/v2/usage/events${querySuffix}`,
    );
  }

  /**
   * Read Deepline credits billed to each run and whether charges are still settling.
   * The response never shows provider spend. The dashboard runs grid uses the same read.
   * HTTP endpoint: `GET /api/v2/runs/billing`.
   */
  async getRunBilling(runIds: readonly string[]): Promise<RunBillingResult> {
    const params = new URLSearchParams();
    for (const runId of runIds) params.append('runId', runId);
    return this.http.get<RunBillingResult>(`/api/v2/runs/billing?${params}`);
  }

  /**
   * Read workspace usage and recent customer-facing Deepline charges. Pass
   * the `job_id` from `executeTool` as `requestId` to retrieve one exact call,
   * including whether its charge is final or still a temporary hold. Exact
   * request lookups return only the `org_id` and `recent` result fields.
   */
  async getBillingUsage(
    options: BillingUsageOptions = {},
  ): Promise<BillingUsageResult> {
    const params = new URLSearchParams();
    if (options.requestId !== undefined) {
      const requestId = options.requestId.trim();
      if (
        requestId.length === 0 ||
        requestId.length > 200 ||
        requestId !== options.requestId
      ) {
        throw new DeeplineError(
          'Usage request_id must contain 1–200 characters with no leading or trailing whitespace.',
          undefined,
          'INVALID_USAGE_REQUEST_ID',
        );
      }
      if (
        options.runId !== undefined ||
        options.cursor !== undefined ||
        options.offset !== undefined
      ) {
        throw new DeeplineError(
          'requestId cannot be combined with runId, cursor, or offset.',
          undefined,
          'INVALID_USAGE_FILTERS',
        );
      }
      params.set('request_id', requestId);
    } else {
      if (options.recentOnly) params.set('recent_only', 'true');
      if (options.limit !== undefined) {
        params.set('recent_limit', String(options.limit));
      }
      if (options.offset !== undefined) {
        params.set('recent_offset', String(options.offset));
      }
      if (options.cursor !== undefined) {
        params.set('recent_cursor', options.cursor);
      }
      if (options.runId !== undefined) {
        params.set('run_id', options.runId);
      }
    }
    const serializedParams = params.toString();
    const query = serializedParams ? `?${serializedParams}` : '';
    return this.http.get<BillingUsageResult>(`/api/v2/billing/usage${query}`);
  }

  /**
   * Charge the saved payment method and add Deepline credits to the active
   * workspace. Prefer `client.billing.topUp(...)`.
   *
   * @throws {@link DeeplineError} with `statusCode: 409` when checkout is
   *   required because the workspace has no saved payment method or the card
   *   requires confirmation.
   */
  async topUpBillingBalance(options: {
    credits: number;
    idempotencyKey?: string;
  }): Promise<BillingTopUpResult> {
    const idempotencyKey =
      options.idempotencyKey === undefined
        ? undefined
        : requireTargetBillingIdempotencyKey(options.idempotencyKey);
    return this.http.post<BillingTopUpResult>(
      '/api/v2/billing/top-up',
      {
        credits: options.credits,
        ...(idempotencyKey !== undefined
          ? { idempotency_key: idempotencyKey }
          : {}),
      },
      idempotencyKey === undefined
        ? undefined
        : { 'Idempotency-Key': idempotencyKey },
      // The idempotency key makes a retry at the product layer safe, but the
      // CLI should not hide ambiguous local delivery failures behind implicit
      // transport retries for a payment mutation.
      { maxRetries: 0, exactUrlOnly: true },
    );
  }

  /**
   * Request a durable top-up operation receipt. A pending receipt does not
   * imply that payment or credit activation has completed. Prefer
   * `client.billing.topUpWithReceipt(...)`.
   */
  async topUpBillingBalanceWithReceipt(options: {
    credits: number;
    idempotencyKey?: string;
  }): Promise<BillingTopUpReceipt> {
    const idempotencyKey =
      options.idempotencyKey === undefined
        ? undefined
        : requireTargetBillingIdempotencyKey(options.idempotencyKey);
    return this.http.post<BillingTopUpReceipt>(
      '/api/v2/billing/top-up',
      {
        credits: options.credits,
        ...(idempotencyKey !== undefined
          ? { idempotency_key: idempotencyKey }
          : {}),
      },
      {
        'x-deepline-top-up-receipt': 'operation-v1',
        ...(idempotencyKey !== undefined
          ? { 'Idempotency-Key': idempotencyKey }
          : {}),
      },
      { maxRetries: 0, exactUrlOnly: true },
    );
  }

  /**
   * Subscription state for the active workspace: active plan, whether a
   * Stripe subscription backs it, renewal/cancellation facts, and remaining
   * Deepline credit pools. Prefer `client.billing.subscription.status()`.
   *
   * @returns Snake_case subscription status from `GET /api/v2/billing/subscription/status`
   */
  async getBillingSubscriptionStatus(): Promise<BillingSubscriptionStatus> {
    return this.http.get<BillingSubscriptionStatus>(
      '/api/v2/billing/subscription/status',
    );
  }

  /**
   * Schedule subscription cancellation at period end, or reverse a pending
   * cancellation with `{ undo: true }`. The customer keeps the cycle they
   * paid for and every remaining credit — cancellation never claws back
   * credits. Prefer `client.billing.subscription.cancel(...)`.
   *
   * @throws {@link DeeplineError} with `statusCode: 409` when the workspace
   *   has no active subscription, and `statusCode: 502` when Stripe rejects
   *   the update (the server message is preserved).
   */
  async cancelBillingSubscription(options?: {
    undo?: boolean;
  }): Promise<BillingSubscriptionCancelResult> {
    return this.http.post<BillingSubscriptionCancelResult>(
      '/api/v2/billing/subscription/cancel',
      { action: options?.undo ? 'undo_cancel' : 'cancel' },
    );
  }

  /**
   * Customer-facing billing history: subscription invoices plus one-time
   * credit purchase receipts, newest first, with Stripe-hosted links.
   * Prefer `client.billing.invoices.list(...)`.
   *
   * @param options.limit - Maximum entries to return (server clamps to 1–100, default 24).
   */
  async listBillingInvoices(options?: {
    limit?: number;
  }): Promise<BillingInvoicesResult> {
    const params = new URLSearchParams();
    if (options?.limit !== undefined) {
      params.set('limit', String(options.limit));
    }
    const suffix = Array.from(params).length > 0 ? `?${params.toString()}` : '';
    return this.http.get<BillingInvoicesResult>(
      `/api/v2/billing/invoices${suffix}`,
    );
  }

  /** List the reviewed target plans and whether new acquisition is enabled. */
  async getTargetBillingPlans(): Promise<TargetBillingPlansResult> {
    return this.http.get<TargetBillingPlansResult>('/api/v2/billing/plans');
  }

  /** Read the workspace's normalized target plan, payment, and balance state. */
  async getTargetBillingStatus(): Promise<TargetBillingStatusResult> {
    return this.http.get<TargetBillingStatusResult>('/api/v2/billing/status');
  }

  /** Read the canonical Metronome automatic recharge configuration. */
  async getTargetAutoRecharge(): Promise<TargetAutoRechargeResult> {
    return this.http.get<TargetAutoRechargeResult>(
      '/api/v2/billing/auto-recharge',
    );
  }

  /** Update automatic recharge and return the server-verified configuration. */
  async updateTargetAutoRecharge(
    options: TargetAutoRechargeUpdateOptions,
  ): Promise<TargetAutoRechargeResult> {
    const idempotencyKey = requireTargetBillingIdempotencyKey(
      options.idempotencyKey,
    );
    const response = await this.http.put<{
      data: TargetAutoRechargeResult;
      request_id?: string;
    }>(
      '/api/v2/billing/auto-recharge',
      options.enabled
        ? {
            enabled: true,
            threshold_credits: options.thresholdCredits,
            refill_to_credits: options.refillToCredits,
            ...(options.purchaseLimitCents !== undefined
              ? { purchase_limit_cents: options.purchaseLimitCents }
              : {}),
            ...(options.purchaseLimitCredits !== undefined
              ? { purchase_limit_credits: options.purchaseLimitCredits }
              : {}),
          }
        : { enabled: false },
      { 'Idempotency-Key': idempotencyKey },
    );
    return response.data;
  }

  /**
   * Purchase target-billing credits through the durable commercial operation
   * flow. The caller supplies an idempotency key for safe retries.
   */
  async purchaseTargetBillingCredits(options: {
    credits: number;
    idempotencyKey: string;
  }): Promise<TargetBillingMutationResult> {
    const idempotencyKey = requireTargetBillingIdempotencyKey(
      options.idempotencyKey,
    );
    return this.http.post<TargetBillingMutationResult>(
      '/api/v2/billing/credit-purchases',
      { credits: options.credits },
      { 'Idempotency-Key': idempotencyKey },
      { maxRetries: 0, exactUrlOnly: true },
    );
  }

  /** Recover only the original workspace, credit amount, and purchase key; never charge. */
  async recoverTargetBillingCreditPurchase(options: {
    credits: number;
    orgId: string;
    idempotencyKey: string;
  }): Promise<TargetBillingMutationResult> {
    if (typeof options.idempotencyKey !== 'string') {
      throw new DeeplineError(
        'The original billing idempotencyKey is required.',
        undefined,
        'INVALID_BILLING_IDEMPOTENCY_KEY',
      );
    }
    const idempotencyKey = requireTargetBillingIdempotencyKey(
      options.idempotencyKey,
    );
    if (!Number.isSafeInteger(options.credits) || options.credits <= 0) {
      throw new DeeplineError(
        'credits must be a positive safe integer.',
        undefined,
        'INVALID_CREDITS',
      );
    }
    if (
      typeof options.orgId !== 'string' ||
      !options.orgId.trim() ||
      options.orgId !== options.orgId.trim()
    ) {
      throw new DeeplineError(
        'The original orgId is required without surrounding whitespace.',
        undefined,
        'INVALID_ORG_ID',
      );
    }
    return this.http.post<TargetBillingMutationResult>(
      '/api/v2/billing/credit-purchases/recover',
      { credits: options.credits, org_id: options.orgId },
      { 'Idempotency-Key': idempotencyKey },
      { maxRetries: 0, exactUrlOnly: true },
    );
  }

  /**
   * Start, change, cancel, or restore a target plan through one idempotent
   * commercial operation.
   */
  async transitionTargetBillingPlan(
    options: TargetBillingPlanTransitionOptions,
  ): Promise<TargetBillingMutationResult> {
    const idempotencyKey = requireTargetBillingIdempotencyKey(
      options.idempotencyKey,
    );
    return this.http.post<TargetBillingMutationResult>(
      '/api/v2/billing/plan-transitions',
      {
        action: options.action,
        ...(options.action === 'start_or_change' && options.billingEmail
          ? { billing_email: options.billingEmail }
          : {}),
        ...(options.targetPlanSku
          ? { target_plan_sku: options.targetPlanSku }
          : {}),
      },
      { 'Idempotency-Key': idempotencyKey },
      { maxRetries: 0, exactUrlOnly: true },
    );
  }

  /** Create a Stripe-hosted portal session for payment recovery and invoices. */
  async createTargetBillingPortalSession(options?: {
    flow?: 'customer_update';
  }): Promise<{ url: string }> {
    const response = await this.http.post<{
      data: { url: string };
      request_id?: string;
    }>(
      options?.flow === 'customer_update'
        ? '/api/v2/billing/portal-sessions?flow=customer_update'
        : '/api/v2/billing/portal-sessions',
      {},
    );
    return response.data;
  }

  /** Create an additional workspace through the durable PAYG workflow. */
  async createWorkspace(options: {
    name: string;
    idempotencyKey: string;
  }): Promise<WorkspaceCreateResult> {
    const idempotencyKey = requireTargetBillingIdempotencyKey(
      options.idempotencyKey,
    );
    const response = await this.http.post<{
      data: Omit<WorkspaceCreateResult, 'operation' | 'request_id'>;
      operation: WorkspaceCreateResult['operation'];
      request_id?: string;
    }>(
      '/api/v2/workspaces',
      { name: options.name },
      { 'Idempotency-Key': idempotencyKey },
      { maxRetries: 0, exactUrlOnly: true },
    );
    return {
      ...response.data,
      operation: response.operation,
      ...(response.request_id ? { request_id: response.request_id } : {}),
    };
  }

  // ——————————————————————————————————————————————————————————
  // Monitors
  // ——————————————————————————————————————————————————————————

  /**
   * Whether the current workspace can use Deepline Monitors. Reachable without
   * monitor access; a denial is a normal 200 body, not a 403. Prefer
   * `client.monitors.status()`.
   */
  async getMonitorsAccess(): Promise<MonitorsAccessStatus> {
    // The endpoint answers 200 in both the granted and denied cases.
    const payload = await this.http.request<MonitorsAccessStatus>(
      '/api/v2/monitors/access',
      { method: 'GET' },
    );
    return {
      has_access: payload.has_access === true,
      ...(typeof payload.reason === 'string' && payload.reason.trim()
        ? { reason: payload.reason.trim() }
        : {}),
    };
  }

  /**
   * One bounded audit pass. Prefer `client.monitors.audit(...)`.
   *
   * Never auto-retried: it is idempotent, but a retry that races the caller's
   * own next pass would spend a provider slot to learn nothing new.
   */
  async auditMonitors(options?: {
    fleetId?: string;
    cursor?: string | null;
  }): Promise<MonitorsAuditResult> {
    return this.http.request<MonitorsAuditResult>('/api/v2/monitors/audit', {
      method: 'POST',
      body: {
        ...(options?.fleetId ? { fleet_id: options.fleetId } : {}),
        ...(options?.cursor ? { cursor: options.cursor } : {}),
      },
      maxRetries: 0,
    });
  }

  /** One repair pass or plan. Prefer `client.monitors.repair(...)`. */
  async repairMonitors(options?: {
    fleetId?: string;
    dryRun?: boolean;
  }): Promise<MonitorsRepairResult> {
    return this.http.request<MonitorsRepairResult>('/api/v2/monitors/repair', {
      method: 'POST',
      body: {
        ...(options?.fleetId ? { fleet_id: options.fleetId } : {}),
        ...(options?.dryRun === undefined ? {} : { dry_run: options.dryRun }),
      },
      maxRetries: 0,
    });
  }

  /** Delivery and convergence health. Prefer `client.monitors.health(...)`. */
  async readMonitorsHealth(options?: {
    fleetId?: string;
  }): Promise<MonitorsHealth> {
    const params = new URLSearchParams();
    if (options?.fleetId) params.set('fleet_id', options.fleetId);
    const query = params.toString();
    const suffix = query ? `?${query}` : '';
    return this.http.request<MonitorsHealth>(
      `/api/v2/monitors/health${suffix}`,
      { method: 'GET' },
    );
  }

  /** Submit durable monitor work; transport retries use the same idempotency key. */
  async submitMonitorBatch(
    options: MonitorBatchSubmitOptions,
  ): Promise<MonitorBatchOperationResult> {
    const idempotencyKey = options.idempotencyKey.trim();
    if (!idempotencyKey) {
      throw new DeeplineError(
        'Monitor batch idempotencyKey is required.',
        undefined,
        'INVALID_MONITOR_BATCH_IDEMPOTENCY_KEY',
      );
    }
    if (options.kind === 'deploy') {
      if (!options.manifestNdjson.trim()) {
        throw new DeeplineError(
          'Monitor batch deploy requires a non-empty NDJSON manifest.',
          undefined,
          'INVALID_MONITOR_BATCH_MANIFEST',
        );
      }
      return this.http.request<MonitorBatchOperationResult>(
        '/api/v2/monitors/batch',
        {
          method: 'POST',
          body: {
            kind: 'deploy',
            manifest_ndjson: options.manifestNdjson,
            dry_run: options.dryRun === true,
            idempotency_key: idempotencyKey,
          },
          headers: { 'Idempotency-Key': idempotencyKey },
          maxRetries: 0,
          exactUrlOnly: true,
        },
      );
    }
    const scope =
      options.scope.kind === 'keys'
        ? { kind: 'keys', monitor_keys: options.scope.monitorKeys }
        : options.scope.kind === 'fleet'
          ? { kind: 'fleet', fleet_id: options.scope.fleetId }
          : { kind: 'target', target: options.scope.target };
    return this.http.request<MonitorBatchOperationResult>(
      '/api/v2/monitors/batch',
      {
        method: 'POST',
        body: {
          kind: options.kind,
          scope,
          dry_run: options.dryRun === true,
          idempotency_key: idempotencyKey,
          ...(options.deactivationReason === undefined
            ? {}
            : { deactivation_reason: options.deactivationReason }),
        },
        headers: { 'Idempotency-Key': idempotencyKey },
        // Durable submission is itself idempotent, but an ambiguous local retry
        // must retain the exact key and never turn a CLI attempt into two runs.
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  /** Get durable batch progress and a bounded retained evidence page. */
  async getMonitorBatch(
    operationId: string,
    options?: { cursor?: string | null },
  ): Promise<MonitorBatchOperationResult> {
    const runId = operationId.trim();
    if (!runId) {
      throw new DeeplineError(
        'Monitor batch operation id is required.',
        undefined,
        'INVALID_MONITOR_BATCH_OPERATION_ID',
      );
    }
    const params = new URLSearchParams();
    if (options?.cursor) params.set('cursor', options.cursor);
    const suffix = params.size > 0 ? `?${params}` : '';
    return this.http.request<MonitorBatchOperationResult>(
      `/api/v2/monitors/batch/${encodeURIComponent(runId)}${suffix}`,
      { method: 'GET' },
    );
  }

  /**
   * The deployable monitor tools catalog. Pass a tool id (positional or
   * `{ tool }`) to describe one tool's full payload/stream contract, or no tool
   * id for the compact inventory. Prefer `client.monitors.available(...)`.
   */
  async getMonitorsAvailable(
    toolIdOrOptions?: string | (MonitorsAvailableOptions & { tool?: string }),
    maybeOptions?: MonitorsAvailableOptions,
  ): Promise<MonitorsAvailableResult> {
    const positionalTool =
      typeof toolIdOrOptions === 'string' ? toolIdOrOptions : undefined;
    // The first argument is either the tool id (string) or an options object.
    // When it is a string (or omitted), `maybeOptions` carries the options;
    // when it is an options object, use it directly.
    const options =
      toolIdOrOptions && typeof toolIdOrOptions === 'object'
        ? toolIdOrOptions
        : (maybeOptions ?? {});
    const optionTool =
      toolIdOrOptions && typeof toolIdOrOptions === 'object'
        ? toolIdOrOptions.tool
        : undefined;
    const tool = positionalTool ?? optionTool;
    const params = new URLSearchParams();
    if (options.provider) params.set('provider', options.provider);
    if (tool) params.set('tool', tool);
    if (options.search) params.set('search', options.search);
    if (options.limit !== undefined) params.set('limit', String(options.limit));
    // List mode is compact by default (id + name + deployed_count). `full`
    // restores the heavy catalog; `compact` stays an explicit alias. Describing
    // a single tool always returns the full contract, so this is skipped there.
    const compactList = !tool && options.full !== true;
    if (compactList || options.compact) params.set('compact', 'true');
    const query = params.toString();
    // Precompute the query suffix: a nested template literal in the request
    // path (`...tools${query ? `?...` : ''}`) breaks the SDK/API contract
    // checker's backtick path extraction. Keep the path a single interpolation.
    const suffix = query ? `?${query}` : '';
    return this.http.request<MonitorsAvailableResult>(
      `/api/v2/monitors/tools${suffix}`,
      { method: 'GET' },
    );
  }

  /** Validate a monitor definition without deploying it. Prefer `client.monitors.check(...)`. */
  async checkMonitor(
    definition: MonitorDefinition,
  ): Promise<MonitorCheckResult> {
    return this.http.request<MonitorCheckResult>('/api/v2/monitors/check', {
      method: 'POST',
      body: definition,
    });
  }

  /**
   * Run one paid preview. Prefer `client.monitors.preview(...)`.
   *
   * The key is fixed before the request is sent and returned on the result
   * and on any error (`error.idempotencyKey`), so a caller that loses the
   * response can repeat the call with it and get the original result without
   * a second charge. The submission is never replayed automatically.
   */
  async previewMonitor(
    definition: MonitorDefinition,
    options?: MonitorPreviewOptions,
  ): Promise<MonitorPreviewResult> {
    const idempotencyKey =
      options?.idempotencyKey ??
      `monitor-preview-${
        globalThis.crypto?.randomUUID?.() ??
        `${Date.now()}-${Math.random().toString(36).slice(2)}`
      }`;
    try {
      const result = await this.http.request<Record<string, unknown>>(
        '/api/v2/monitors/preview',
        {
          method: 'POST',
          body: {
            ...definition,
            ...(options?.limit === undefined ? {} : { limit: options.limit }),
          },
          headers: { 'Idempotency-Key': idempotencyKey },
          maxRetries: 0,
          exactUrlOnly: true,
          preserveRateLimitResponse: true,
        },
      );
      return { ...result, idempotency_key: idempotencyKey };
    } catch (error) {
      if (error && typeof error === 'object') {
        Object.assign(error, { idempotencyKey });
      }
      throw error;
    }
  }

  /**
   * Deploy a monitor from a definition. `dryRun` validates via the check
   * endpoint and returns the plan without deploying. Prefer
   * `client.monitors.deploy(...)`.
   */
  async deployMonitor(
    definition: MonitorDefinition,
    options?: { dryRun?: boolean },
  ): Promise<MonitorDeployResult> {
    if (options?.dryRun) {
      // The deploy plan is served by the CHECK endpoint. No deploy call is ever
      // made in dry-run mode.
      return this.http.request<MonitorDeployResult>('/api/v2/monitors/check', {
        method: 'POST',
        body: definition,
      });
    }
    const deployed = await this.http.request<MonitorDeployResult>(
      '/api/v2/monitors/deploy',
      {
        method: 'POST',
        body: definition,
        // A provider can reject a create with a 429 after Deepline has begun
        // the lifecycle request. Do not replay a mutation or hide the server's
        // monitor-specific recovery guidance behind a generic transport retry.
        maxRetries: 0,
        exactUrlOnly: true,
        preserveRateLimitResponse: true,
      },
    );
    if (definition.tool !== 'deepline.analytics') return deployed;

    // Analytics remains an ordinary monitor deploy. Its provider-specific
    // post-deploy work creates/reuses the tracker and returns the artifact a
    // caller needs to install it; there is intentionally no separate setup
    // command in the public monitor lifecycle.
    const setup = await this.setupMonitor(definition.tool, {
      ...definition.payload,
      monitor_key: definition.key,
    });
    return {
      ...deployed,
      monitor: {
        ...(deployed.monitor && typeof deployed.monitor === 'object'
          ? deployed.monitor
          : {}),
        tracking: setup.tracking ?? null,
        ip2company: setup.ip2company ?? null,
      },
    };
  }

  /** List deployed monitors. Prefer `client.monitors.list(...)`. */
  async listMonitors(
    options?: MonitorsListOptions,
  ): Promise<MonitorsListResult> {
    const params = new URLSearchParams();
    // `state` is the canonical filter. Keep sending the historical `status`
    // parameter when callers use it so installed clients continue to work
    // against older servers; never send both filters for one request.
    if (options?.state) params.set('state', options.state);
    else if (options?.status) params.set('status', options.status);
    if (options?.limit !== undefined)
      params.set('limit', String(options.limit));
    if (options?.cursor) params.set('cursor', options.cursor);
    // `compact` used to promise a semantic projection. It is deliberately a
    // no-op now: audit fields must never disappear from a list response.
    if (options?.includeConsumers) params.set('include_consumers', 'true');
    const query = params.toString();
    // Single interpolation only — see availableMonitors: a nested template in
    // the path confuses the SDK/API contract path extractor.
    const suffix = query ? `?${query}` : '';
    return this.http.request<MonitorsListResult>(
      `/api/v2/monitors/deployed${suffix}`,
      { method: 'GET' },
    );
  }

  /** The Monitors list. Prefer `client.monitors.ledger(...)`. */
  async listMonitorLedger(
    options?: MonitorsLedgerOptions,
  ): Promise<MonitorsLedgerResult> {
    const params = new URLSearchParams();
    if (options?.search) params.set('q', options.search);
    for (const state of options?.states ?? []) params.append('state', state);
    for (const signal of options?.signals ?? [])
      params.append('signal', signal);
    if (options?.play) params.set('play', options.play);
    if (options?.sort) params.set('sort', options.sort);
    if (options?.window) params.set('window', options.window);
    if (options?.limit !== undefined)
      params.set('limit', String(options.limit));
    if (options?.cursor) params.set('cursor', options.cursor);
    const query = params.toString();
    const suffix = query ? `?${query}` : '';
    return this.http.request<MonitorsLedgerResult>(
      `/api/v2/monitors/ledger${suffix}`,
      { method: 'GET' },
    );
  }

  /** One Monitors list entry. Prefer `client.monitors.ledgerGet(...)`. */
  async getMonitorLedgerEntry(key: string): Promise<Record<string, unknown>> {
    return this.http.request<Record<string, unknown>>(
      `/api/v2/monitors/ledger/${encodeURIComponent(key)}`,
      { method: 'GET' },
    );
  }

  /** A monitor's recent findings. Prefer `client.monitors.ledgerFindings(...)`. */
  async listMonitorLedgerFindings(
    key: string,
    options?: { cursor?: string },
  ): Promise<Record<string, unknown>> {
    const suffix = options?.cursor
      ? `?cursor=${encodeURIComponent(options.cursor)}`
      : '';
    return this.http.request<Record<string, unknown>>(
      `/api/v2/monitors/ledger/${encodeURIComponent(key)}/findings${suffix}`,
      { method: 'GET' },
    );
  }

  /** Fetch one deployed monitor by public key. Prefer `client.monitors.get(...)`. */
  async getMonitor(key: string): Promise<MonitorDetail> {
    return this.http.request<MonitorDetail>(
      `/api/v2/monitors/deployed/${encodeURIComponent(key)}`,
      { method: 'GET' },
    );
  }

  async testMonitorWebhook(
    key: string,
    payload: Record<string, unknown>,
    options?: MonitorTestOptions,
  ): Promise<MonitorTestResult> {
    if (options?.dispatch === true || options?.validationOnly === false) {
      throw new DeeplineError(
        'Monitor tests are validation-only and cannot dispatch events.',
        undefined,
        'MONITOR_TEST_DISPATCH_NOT_SUPPORTED',
      );
    }
    return this.http.request<MonitorTestResult>(
      `/api/v2/monitors/deployed/${encodeURIComponent(key)}/test`,
      {
        method: 'POST',
        body: {
          payload,
          // Send the legacy safe mode as well as accepting it server-side: an
          // upgraded SDK must be safe when it reaches a still-running server.
          mode: 'validation_only',
        },
      },
    );
  }

  async setupMonitor(
    tool: string,
    payload: Record<string, unknown>,
  ): Promise<Record<string, unknown>> {
    return this.http.request<Record<string, unknown>>(
      `/api/v2/monitors/setup/${encodeURIComponent(tool)}`,
      { method: 'POST', body: payload },
    );
  }

  async validateMonitor(key: string): Promise<MonitorValidateResult> {
    return this.http.request<MonitorValidateResult>(
      `/api/v2/monitors/deployed/${encodeURIComponent(key)}/validate`,
      { method: 'POST', body: {} },
    );
  }

  /** Published plays depending on one monitor. Prefer `client.monitors.dependents(...)`. */
  async getMonitorDependents(key: string): Promise<MonitorDependents> {
    return this.http.request<MonitorDependents>(
      `/api/v2/monitors/deployed/${encodeURIComponent(key)}/dependents`,
      { method: 'GET' },
    );
  }

  /** Update a deployed monitor by public key. Prefer `client.monitors.update(...)`. */
  async updateMonitor(
    key: string,
    patch: Record<string, unknown>,
  ): Promise<MonitorUpdateResult> {
    return this.http.request<MonitorUpdateResult>(
      `/api/v2/monitors/deployed/${encodeURIComponent(key)}`,
      {
        method: 'PATCH',
        body: patch,
        // A monitor write may have reached the control plane before a network
        // failure reaches the caller. Do not turn that unknown outcome into a
        // second mutation with a fresh snapshot.
        ...MONITOR_NON_RETRYABLE_MUTATION_OPTIONS,
      },
    );
  }

  /** Delete a deployed monitor and its upstream provider resource. `dryRun` returns the delete plan. Prefer `client.monitors.delete(...)`. */
  async deleteMonitor(
    key: string,
    options?: { dryRun?: boolean },
  ): Promise<MonitorDeleteResult> {
    // The public type intentionally excludes `localOnly`, but JavaScript
    // callers (and compiled older SDK clients) can still pass it at runtime.
    // Never silently reinterpret an old local-only request as an upstream
    // deletion. The server applies the same guard for direct API callers.
    if ((options as { localOnly?: unknown } | undefined)?.localOnly === true) {
      throw new DeeplineError(
        'localOnly monitor deletion is no longer supported. Monitor deletion always deprovisions the upstream provider resource.',
        undefined,
        'MONITOR_LOCAL_ONLY_DELETE_NOT_SUPPORTED',
      );
    }
    const params = new URLSearchParams();
    if (options?.dryRun) params.set('dry_run', 'true');
    const query = params.toString();
    return this.http.request<MonitorDeleteResult>(
      `/api/v2/monitors/deployed/${encodeURIComponent(key)}${query ? `?${query}` : ''}`,
      options?.dryRun
        ? { method: 'DELETE' }
        : {
            method: 'DELETE',
            // Deletion is a provider lifecycle operation. A timeout is an
            // unknown outcome, not authority to begin another delete attempt.
            ...MONITOR_NON_RETRYABLE_MUTATION_OPTIONS,
          },
    );
  }

  /**
   * Reactivate a disabled monitor. `dryRun` returns the reactivation cost.
   * Prefer `client.monitors.reactivate(...)`.
   */
  async reactivateMonitor(
    key: string,
    options?: { dryRun?: boolean },
  ): Promise<MonitorReactivateResult> {
    const query = options?.dryRun ? '?dry_run=true' : '';
    return this.http.request<MonitorReactivateResult>(
      `/api/v2/monitors/deployed/${encodeURIComponent(key)}/reactivate${query}`,
      options?.dryRun
        ? { method: 'POST', body: {} }
        : {
            method: 'POST',
            body: {},
            // Reactivation can create an upstream resource, so it must not use
            // the generic transport's automatic replay policy.
            ...MONITOR_NON_RETRYABLE_MUTATION_OPTIONS,
          },
    );
  }

  // ——————————————————————————————————————————————————————————
  // Monitor Jobs, Batches, and Fleets
  // ——————————————————————————————————————————————————————————

  private static readonly MONITOR_JOB_IDEMPOTENCY_KEY_MAX_LENGTH = 96;

  private monitorJobIdempotencyKey(operation: string): string {
    const uuid =
      globalThis.crypto?.randomUUID?.() ??
      `${Date.now()}-${Math.random().toString(36).slice(2)}`;
    const prefix = 'monitor-job-';
    const safeOperation = operation.replace(/[^A-Za-z0-9._-]/g, '-');
    const maxOperationLength = Math.max(
      0,
      DeeplineClient.MONITOR_JOB_IDEMPOTENCY_KEY_MAX_LENGTH -
        prefix.length -
        uuid.length -
        1,
    );
    return `${prefix}${safeOperation.slice(0, maxOperationLength)}-${uuid}`;
  }

  private monitorJobHeaders(
    operation: string,
    idempotencyKey?: string,
  ): Record<string, string> {
    return {
      'Idempotency-Key':
        idempotencyKey?.trim() || this.monitorJobIdempotencyKey(operation),
    };
  }

  async deployMonitorBatch(
    definitions: MonitorDefinition[],
    options?: MonitorJobDeployOptions,
  ): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>(
      '/api/v2/monitors/batch/deploy',
      {
        method: 'POST',
        body: { version: 1, kind: 'batch', monitors: definitions },
        headers: this.monitorJobHeaders(
          'batch-deploy',
          options?.idempotencyKey,
        ),
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  private namedMonitorBatchPath(batchId: string): string {
    return `/api/v2/monitors/batches/${encodeURIComponent(batchId)}`;
  }

  async syncNamedMonitorBatch(
    batchId: string,
    definitions: MonitorDefinition[],
    options?: MonitorNamedBatchOptions,
  ): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>(
      this.namedMonitorBatchPath(batchId),
      {
        method: 'PUT',
        body: {
          version: 1,
          kind: 'batch',
          monitors: definitions,
          ...(options?.expectedGeneration === undefined
            ? {}
            : { expected_generation: options.expectedGeneration }),
        },
        headers: this.monitorJobHeaders(
          `batch-sync-${batchId}`,
          options?.idempotencyKey,
        ),
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  async startNamedMonitorBatch(
    batchId: string,
    options?: Pick<MonitorNamedBatchOptions, 'idempotencyKey'>,
  ): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>(
      `${this.namedMonitorBatchPath(batchId)}/start`,
      {
        method: 'POST',
        body: {},
        headers: this.monitorJobHeaders(
          `batch-start-${batchId}`,
          options?.idempotencyKey,
        ),
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  async stopNamedMonitorBatch(
    batchId: string,
    options?: Pick<MonitorNamedBatchOptions, 'idempotencyKey'>,
  ): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>(
      this.namedMonitorBatchPath(batchId),
      {
        method: 'DELETE',
        body: {},
        headers: this.monitorJobHeaders(
          `batch-stop-${batchId}`,
          options?.idempotencyKey,
        ),
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  async getNamedMonitorBatch(batchId: string): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>(
      this.namedMonitorBatchPath(batchId),
      { method: 'GET' },
    );
  }

  async submitScalarMonitorLifecycle(
    monitorKey: string,
    action: 'start' | 'stop',
    options?: Pick<MonitorLifecycleOptions, 'idempotencyKey'>,
  ): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>(
      `/api/v2/monitors/deployed/${encodeURIComponent(monitorKey)}/${action}`,
      {
        method: 'POST',
        body: {},
        headers: this.monitorJobHeaders(
          `${action}-${monitorKey}`,
          options?.idempotencyKey,
        ),
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  async syncScalarMonitor(
    definition: MonitorDefinition,
    options?: Pick<MonitorLifecycleOptions, 'idempotencyKey'>,
  ): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>('/api/v2/monitors/sync', {
      method: 'POST',
      body: definition,
      headers: this.monitorJobHeaders(
        `sync-${definition.key}`,
        options?.idempotencyKey,
      ),
      maxRetries: 0,
      exactUrlOnly: true,
    });
  }

  async getMonitorJob(jobId: string): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>(
      `/api/v2/monitors/jobs/${encodeURIComponent(jobId)}`,
      { method: 'GET' },
    );
  }

  async getMonitorJobLogs(
    jobId: string,
    options?: MonitorJobLogsOptions,
  ): Promise<MonitorJobResult> {
    const query =
      options?.limit === undefined
        ? ''
        : `?limit=${encodeURIComponent(String(options.limit))}`;
    return this.http.request<MonitorJobResult>(
      `/api/v2/monitors/jobs/${encodeURIComponent(jobId)}/logs${query}`,
      { method: 'GET' },
    );
  }

  async cancelMonitorJob(jobId: string): Promise<MonitorJobResult> {
    return this.http.request<MonitorJobResult>(
      `/api/v2/monitors/jobs/${encodeURIComponent(jobId)}/cancel`,
      { method: 'POST', body: {}, maxRetries: 0, exactUrlOnly: true },
    );
  }

  async waitForMonitorJob(
    jobId: string,
    options?: MonitorJobWaitOptions,
  ): Promise<MonitorJobResult> {
    const timeoutMs = Math.max(1, options?.timeoutMs ?? 10 * 60_000);
    const pollIntervalMs = Math.max(1, options?.pollIntervalMs ?? 2_000);
    const terminal = new Set(['succeeded', 'failed', 'cancelled']);
    const startedAt = Date.now();
    let latest = await this.getMonitorJob(jobId);
    while (true) {
      options?.onProgress?.(latest);
      const job = latest.job as Record<string, unknown> | undefined;
      const state = typeof job?.state === 'string' ? job.state : undefined;
      if (state && terminal.has(state)) return latest;
      if (Date.now() - startedAt >= timeoutMs) return latest;
      await sleep(pollIntervalMs);
      latest = await this.getMonitorJob(jobId);
    }
  }

  // ——————————————————————————————————————————————————————————
  // Monitor Fleets
  // ——————————————————————————————————————————————————————————

  private monitorFleetIdempotencyKey(operation: string): string {
    const uuid = globalThis.crypto?.randomUUID?.();
    return `monitor-fleet-${operation}-${uuid ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`}`;
  }

  private monitorFleetHeaders(
    operation: string,
    idempotencyKey?: string,
  ): Record<string, string> {
    return {
      'Idempotency-Key':
        idempotencyKey?.trim() || this.monitorFleetIdempotencyKey(operation),
    };
  }

  private monitorFleetPath(fleetId: string): string {
    return `/api/v2/monitors/fleets/${encodeURIComponent(fleetId)}`;
  }

  /**
   * Create, update, or re-plan one fleet.
   *
   * The fleet id is always the resource path, so the same definition PUT twice
   * is the same operation and the server can answer `replayed: true` instead of
   * building a second set of monitors. Re-planning an existing fleet from its
   * stored definition sends an EMPTY body: there is no second definition to
   * send, and an empty body cannot be mistaken for "replace the definition with
   * nothing".
   */
  async syncMonitorFleet(
    definitionOrId: string | MonitorFleetDefinition,
    options?: MonitorFleetSyncOptions,
  ): Promise<MonitorFleetResult> {
    const fleetId =
      typeof definitionOrId === 'string' ? definitionOrId : definitionOrId.id;
    const body: Record<string, unknown> = {
      ...(typeof definitionOrId === 'string'
        ? {}
        : { definition: definitionOrId }),
      ...(options?.dryRun ? { dry_run: true } : {}),
      ...(options?.expectedGeneration !== undefined
        ? { expected_generation: options.expectedGeneration }
        : {}),
    };
    return this.http.request<MonitorFleetResult>(
      this.monitorFleetPath(fleetId),
      {
        method: 'PUT',
        body,
        headers: this.monitorFleetHeaders('sync', options?.idempotencyKey),
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  async listMonitorFleets(): Promise<MonitorFleetResult> {
    return this.http.request<MonitorFleetResult>('/api/v2/monitors/fleets', {
      method: 'GET',
    });
  }

  async getMonitorFleet(
    fleetId: string,
    options?: MonitorFleetGetOptions,
  ): Promise<MonitorFleetResult> {
    const params = new URLSearchParams();
    if (options?.drift) params.set('drift', '1');
    if (options?.limit !== undefined)
      params.set('limit', String(options.limit));
    const query = params.toString();
    return this.http.request<MonitorFleetResult>(
      `${this.monitorFleetPath(fleetId)}${query ? `?${query}` : ''}`,
      { method: 'GET' },
    );
  }

  async deactivateMonitorFleet(
    fleetId: string,
    options?: MonitorFleetDeactivateOptions,
  ): Promise<MonitorFleetResult> {
    return this.http.request<MonitorFleetResult>(
      this.monitorFleetPath(fleetId),
      {
        method: 'DELETE',
        body: options?.dryRun ? { dry_run: true } : {},
        headers: this.monitorFleetHeaders(
          'deactivate',
          options?.idempotencyKey,
        ),
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  async reactivateMonitorFleet(
    fleetId: string,
    options?: MonitorFleetReactivateOptions,
  ): Promise<MonitorFleetResult> {
    return this.http.request<MonitorFleetResult>(
      `${this.monitorFleetPath(fleetId)}/reactivate`,
      {
        method: 'POST',
        body: {},
        headers: this.monitorFleetHeaders(
          'reactivate',
          options?.idempotencyKey,
        ),
        maxRetries: 0,
        exactUrlOnly: true,
      },
    );
  }

  /**
   * Poll one fleet until the server reports a terminal status.
   *
   * Convergence is the server's verdict, read from `status`. The timeout is not
   * a failure and does not throw: a fleet still `converging` after ten minutes
   * is healthy and slow, not broken, so the caller gets the last snapshot and
   * decides what that means. Throwing here would have made "still working" look
   * identical to "the request failed".
   */
  async waitForMonitorFleetConvergence(
    fleetId: string,
    options?: MonitorFleetWaitOptions,
  ): Promise<MonitorFleetResult> {
    const timeoutMs = Math.max(1, options?.timeoutMs ?? 10 * 60_000);
    const pollIntervalMs = Math.max(1, options?.pollIntervalMs ?? 2_000);
    // The server's settled verdicts (`FLEET_SETTLED_VERDICTS` in
    // packages/monitors/fleets/verdict.ts): a fleet stays in each until someone
    // acts, so polling one only runs out the timeout. A deactivation wait does
    // not stop on `converged`. tests/sdk/monitor-fleets-namespace.test.ts
    // checks this against the server's list.
    const terminal: ReadonlySet<string> =
      options?.until === 'deactivated'
        ? new Set(['deactivated', 'degraded', 'billing_suspended'])
        : new Set([
            'converged',
            'degraded',
            'deactivated',
            'billing_suspended',
          ]);
    const startedAt = Date.now();
    let latest = await this.getMonitorFleet(fleetId);
    while (true) {
      options?.onProgress?.(latest);
      const status =
        typeof latest.status === 'string' ? latest.status : undefined;
      if (status && terminal.has(status)) return latest;
      if (Date.now() - startedAt >= timeoutMs) return latest;
      await sleep(pollIntervalMs);
      latest = await this.getMonitorFleet(fleetId);
    }
  }

  /**
   * The workspace and user this client's API key authenticates as.
   *
   * @example
   * ```typescript
   * const status = await client.authStatus();
   * ```
   */
  async authStatus(): Promise<Record<string, unknown>> {
    return this.http.post<Record<string, unknown>>('/api/v2/auth/cli/status', {
      api_key: this.config.apiKey,
    });
  }

  /**
   * Check API connectivity and server health.
   *
   * @returns Health status with API version
   *
   * @example
   * ```typescript
   * const health = await client.health();
   * console.log(`API: ${health.status} (${health.version})`);
   * // { status: "ok", version: "v2" }
   * ```
   */
  async health(): Promise<{
    status: string;
    version?: string;
    status_banner?: {
      message: string;
      updatedAt: number;
    };
  }> {
    return this.http.get<{
      status: string;
      version?: string;
      status_banner?: {
        message: string;
        updatedAt: number;
      };
    }>('/api/v2/health');
  }
}

export type { PlayRunListItem, PlayStatus } from './types';
