import "reflect-metadata";
import { ReadableStream } from "node:stream/web";
import { ZodType, z } from "zod";
import { DependencyContainer as Container, InjectionToken as TypeToken } from "tsyringe";

//#region ../core/src/contracts/testTriggerTypes.d.ts
/**
 * Identifier minted by the host (or in-memory test runner) for one execution of a test suite.
 * One TestSuiteRun produces N child workflow runs, one per item yielded by `generateItems`.
 */
type TestSuiteRunId = string;
//#endregion
//#region ../core/src/contracts/baseTypes.d.ts
/**
 * Minimal base types that have no dependencies on other contracts.
 * Used by credentialTypes, workflowTypes, and other contract layers
 * to avoid circular dependencies.
 */
type WorkflowId = string;
type NodeId = string;
type OutputPortKey = string;
type InputPortKey = string;
type PersistedTokenId = string;
type NodeConnectionName = string;
//#endregion
//#region ../core/src/contracts/CostTrackingTelemetryContract.d.ts
type CostTrackingComponent = "chat" | "ocr" | "rag";
interface CostTrackingUsageRecord {
  readonly component: CostTrackingComponent;
  readonly provider: string;
  readonly operation: string;
  readonly pricingKey: string;
  readonly usageUnit: string;
  readonly quantity: number;
  readonly modelName?: string;
  readonly attributes?: TelemetryAttributes;
}
interface CostTrackingPriceQuote {
  readonly currency: string;
  readonly currencyScale: number;
  readonly estimatedAmountMinor: number;
  readonly estimateKind: "catalog";
}
interface CostTrackingTelemetry {
  captureUsage(args: CostTrackingUsageRecord): Promise<CostTrackingPriceQuote | undefined>;
  forScope(scope: TelemetryScope): CostTrackingTelemetry;
}
//#endregion
//#region ../core/src/contracts/telemetryTypes.d.ts
type TelemetryAttributePrimitive = string | number | boolean | null;
interface TelemetryAttributes {
  readonly [key: string]: TelemetryAttributePrimitive | undefined;
}
interface TelemetryMetricRecord {
  readonly name: string;
  readonly value: number;
  readonly unit?: string;
  readonly attributes?: TelemetryAttributes;
}
interface TelemetrySpanEventRecord {
  readonly name: string;
  readonly occurredAt?: Date;
  readonly attributes?: TelemetryAttributes;
}
interface TelemetryArtifactAttachment {
  readonly kind: string;
  readonly contentType: string;
  readonly previewText?: string;
  readonly previewJson?: JsonValue;
  readonly payloadText?: string;
  readonly payloadJson?: JsonValue;
  readonly bytes?: number;
  readonly truncated?: boolean;
  readonly expiresAt?: Date;
}
interface TelemetryArtifactReference {
  readonly artifactId: string;
  readonly traceId?: string;
  readonly spanId?: string;
}
interface TelemetrySpanEnd {
  readonly status?: "ok" | "error";
  readonly statusMessage?: string;
  readonly endedAt?: Date;
  readonly attributes?: TelemetryAttributes;
}
interface TelemetryChildSpanStart {
  readonly name: string;
  readonly kind?: "internal" | "client";
  readonly startedAt?: Date;
  readonly attributes?: TelemetryAttributes;
}
interface TelemetryScope {
  readonly traceId?: string;
  readonly spanId?: string;
  readonly costTracking?: CostTrackingTelemetry;
  addSpanEvent(args: TelemetrySpanEventRecord): Promise<void> | void;
  recordMetric(args: TelemetryMetricRecord): Promise<void> | void;
  attachArtifact(args: TelemetryArtifactAttachment): Promise<TelemetryArtifactReference> | TelemetryArtifactReference;
}
interface TelemetrySpanScope extends TelemetryScope {
  readonly traceId: string;
  readonly spanId: string;
  end(args?: TelemetrySpanEnd): Promise<void> | void;
  /**
   * Lift this span into a {@link NodeExecutionTelemetry} scoped to a different (nodeId, activationId).
   * Children created via the returned telemetry's `startChildSpan` get this span as their parent.
   *
   * Used at the sub-agent boundary so that nested runtime telemetry parents under the agent.tool.call
   * span instead of the orchestrator's node-level span.
   */
  asNodeTelemetry(args: Readonly<{
    nodeId: NodeId;
    activationId: NodeActivationId;
  }>): NodeExecutionTelemetry;
}
interface NodeExecutionTelemetry extends ExecutionTelemetry, TelemetrySpanScope {
  startChildSpan(args: TelemetryChildSpanStart): TelemetrySpanScope;
}
interface ExecutionTelemetry extends TelemetryScope {
  readonly traceId: string;
  readonly spanId: string;
  forNode(args: Readonly<{
    nodeId: NodeId;
    activationId: NodeActivationId;
  }>): NodeExecutionTelemetry;
}
//#endregion
//#region ../core/src/contracts/itemExpr.d.ts
declare const ITEM_EXPR_BRAND: unique symbol;
type ItemExprResolvedContext = Readonly<{
  runId: RunId;
  workflowId: WorkflowId;
  nodeId: NodeId;
  activationId: NodeActivationId;
  data: RunDataSnapshot;
}>;
/**
 * Context aligned with former {@link ItemInputMapperContext} — use **`data`** to read any completed upstream node.
 */
type ItemExprContext = ItemExprResolvedContext;
type ItemExprArgs<TItemJson = unknown> = Readonly<{
  item: Item<TItemJson>;
  itemIndex: number;
  items: Items<TItemJson>;
  ctx: ItemExprContext;
}>;
type ItemExprCallback<T, TItemJson = unknown> = (args: ItemExprArgs<TItemJson>) => T | Promise<T>;
type ItemExpr<T, TItemJson = unknown> = Readonly<{
  readonly [ITEM_EXPR_BRAND]: true;
  readonly fn: ItemExprCallback<T, TItemJson>;
}>;
//#endregion
//#region ../core/src/contracts/params.d.ts
type Expr<T, TItemJson = unknown> = ItemExpr<T, TItemJson>;
type ParamDeep<T, TItemJson = unknown> = Expr<T, TItemJson> | (T extends readonly (infer U)[] ? ReadonlyArray<ParamDeep<U, TItemJson>> : never) | (T extends object ? { [K in keyof T]: ParamDeep<T[K], TItemJson> } : T);
//#endregion
//#region ../core/src/contracts/retryPolicySpec.types.d.ts
/**
 * In-process retry policy for runnable nodes. Serialized configs use the same
 * `kind` discriminator (`JSON.stringify` / persisted workflows).
 *
 * `maxAttempts` is the total number of tries including the first (e.g. 3 means up to 2 delays after failures).
 */
type RetryPolicySpec = NoneRetryPolicySpec | FixedRetryPolicySpec | ExponentialRetryPolicySpec;
interface NoneRetryPolicySpec {
  readonly kind: "none";
}
interface FixedRetryPolicySpec {
  readonly kind: "fixed";
  /** Total attempts including the first execution. Must be >= 1. */
  readonly maxAttempts: number;
  readonly delayMs: number;
}
interface ExponentialRetryPolicySpec {
  readonly kind: "exponential";
  /** Total attempts including the first execution. Must be >= 1. */
  readonly maxAttempts: number;
  readonly initialDelayMs: number;
  readonly multiplier: number;
  readonly maxDelayMs?: number;
  /** When true, each delay is multiplied by a random factor in [1, 1.2). */
  readonly jitter?: boolean;
}
//#endregion
//#region ../core/src/contracts/executionPersistenceContracts.d.ts
/** Canonical id for persisted execution rows (activation or connection invocation). */
type ExecutionInstanceId = string;
/** Batch grouping for planner activations. */
type BatchId = string;
type PersistedExecutionInstanceKind = "workflowNodeActivation" | "connectionInvocation";
type ConnectionInvocationKind = "languageModel" | "tool" | "nestedAgent";
interface WorkflowRunDetailDto {
  readonly runId: RunId;
  readonly workflowId: WorkflowId;
  readonly startedAt: string;
  readonly finishedAt?: string;
  readonly status: RunStatus;
  readonly workflowSnapshot?: PersistedWorkflowSnapshot;
  readonly mutableState?: PersistedMutableRunState;
  readonly slotStates: ReadonlyArray<SlotExecutionStateDto>;
  readonly executionInstances: ReadonlyArray<ExecutionInstanceDto>;
  readonly iterations?: ReadonlyArray<RunIterationDto>;
}
/**
 * Per-item iteration projected from connection invocations and node activations.
 *
 * One iteration = one item processed by an agent within an activation. Multiple invocations
 * (LLM rounds, tool calls) belonging to the same iteration share the iterationId.
 */
interface RunIterationDto {
  readonly iterationId: string;
  readonly agentNodeId: NodeId;
  readonly activationId: NodeActivationId;
  readonly itemIndex: number;
  readonly itemSummary?: string;
  readonly status: NodeExecutionStatus;
  readonly startedAt?: string;
  readonly finishedAt?: string;
  readonly invocationIds: ReadonlyArray<string>;
  readonly parentInvocationId?: string;
  /** Estimated cost rolled up from telemetry cost metric points, keyed by ISO currency code (e.g. "USD"). Values are minor units (cents-of-cents per the metric's `cost.currency_scale`). */
  readonly estimatedCostMinorByCurrency?: Readonly<Record<string, number>>;
  /** Currency scale (denominator) per currency, when present on the metric points. Joined with `estimatedCostMinorByCurrency` to format human-readable amounts. */
  readonly estimatedCostCurrencyScaleByCurrency?: Readonly<Record<string, number>>;
}
interface SlotExecutionStateDto {
  readonly slotNodeId: NodeId;
  readonly latestInstanceId?: ExecutionInstanceId;
  readonly latestTerminalInstanceId?: ExecutionInstanceId;
  readonly latestRunningInstanceId?: ExecutionInstanceId;
  readonly status?: NodeExecutionStatus;
  readonly invocationCount: number;
  readonly runCount: number;
}
interface ExecutionInstanceDto {
  readonly instanceId: ExecutionInstanceId;
  readonly slotNodeId: NodeId;
  readonly workflowNodeId: NodeId;
  readonly parentInstanceId?: ExecutionInstanceId;
  readonly kind: PersistedExecutionInstanceKind;
  readonly connectionKind?: ConnectionInvocationKind;
  readonly runIndex: number;
  readonly batchId: BatchId;
  readonly activationId?: NodeActivationId;
  readonly status: NodeExecutionStatus;
  readonly queuedAt?: string;
  readonly startedAt?: string;
  readonly finishedAt?: string;
  readonly itemCount: number;
  readonly inputJson?: JsonValue;
  readonly outputJson?: JsonValue;
  readonly error?: Readonly<NodeExecutionError>;
  /** Per-item iteration that produced this instance. Set on connectionInvocation rows produced inside per-item runnable loops. */
  readonly iterationId?: string;
  /** Item index (0-based) of the iteration. */
  readonly itemIndex?: number;
  /** Parent invocation id when this instance was emitted by a sub-agent triggered by an outer LLM/tool call. */
  readonly parentInvocationId?: string;
  /**
   * When this instance is a SubWorkflow node activation, the run id of the child run it spawned.
   * Used by the UI to deep-link directly to the child execution.
   */
  readonly childRunId?: string;
}
//#endregion
//#region ../core/src/contracts/webhookTypes.d.ts
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
/** Match for an incoming HTTP request: user-defined URL segment + workflow trigger node. */
interface WebhookInvocationMatch {
  /** Same value as the webhook trigger's configured endpoint key (URL segment under the webhook base path). */
  endpointPath: string;
  workflowId: WorkflowId;
  nodeId: NodeId;
  methods: ReadonlyArray<HttpMethod>;
  parseJsonBody?: (body: unknown) => unknown;
}
/** Result of resolving an HTTP method + endpoint path against the catalog webhook index (404 vs 405 vs match). */
type WebhookTriggerResolution = {
  status: "notFound";
} | {
  status: "methodNotAllowed";
  match: WebhookInvocationMatch;
} | {
  status: "ok";
  match: WebhookInvocationMatch;
};
/**
 * Resolves webhook routes from workflow definitions (catalog-backed index, no registration at trigger setup).
 */
interface WebhookTriggerMatcher {
  match(args: {
    endpointPath: string;
    method: HttpMethod;
  }): WebhookInvocationMatch | undefined;
  lookup(endpointPath: string): WebhookInvocationMatch | undefined;
  onEngineWorkflowsLoaded?(): void;
  onEngineStopped?(): void;
  /** Rebuild route index after activation changes without stopping the engine. */
  reloadWebhookRoutes?(): void;
}
//#endregion
//#region ../core/src/contracts/credentialTypes.d.ts
type CredentialTypeId = string;
type CredentialInstanceId = string;
type CredentialMaterialSourceKind = "db" | "env" | "code";
type CredentialSetupStatus = "draft" | "ready";
type CredentialHealthStatus = "unknown" | "healthy" | "failing";
type CredentialFieldSchema = Readonly<{
  key: string;
  label: string;
  type: "string" | "password" | "textarea" | "json" | "boolean";
  required?: true;
  order?: number;
  /**
   * Where this field appears in the credential dialog. Use `"advanced"` for optional or
   * power-user fields; they render inside a collapsible section (see `CredentialTypeDefinition.advancedSection`).
   * Defaults to `"default"` when omitted.
   */
  visibility?: "default" | "advanced";
  placeholder?: string;
  helpText?: string;
  /** When set, host resolves this field from process.env at runtime; env wins over stored values. */
  envVarName?: string;
  /**
   * When set, the dialog shows a copy action for this exact string (e.g. a static OAuth redirect URI
   * pattern or documentation URL). Do not use for secret values.
   */
  copyValue?: string;
  /** Accessible label for the copy control (default: Copy). */
  copyButtonLabel?: string;
}>;
type CredentialRequirement = Readonly<{
  slotKey: string;
  label: string;
  acceptedTypes: ReadonlyArray<CredentialTypeId>;
  optional?: true;
  helpText?: string;
  helpUrl?: string;
}>;
type CredentialBindingKey = Readonly<{
  workflowId: WorkflowId;
  nodeId: NodeId;
  slotKey: string;
}>;
type CredentialBinding = Readonly<{
  key: CredentialBindingKey;
  instanceId: CredentialInstanceId;
  updatedAt: string;
}>;
type CredentialHealth = Readonly<{
  status: CredentialHealthStatus;
  message?: string;
  testedAt?: string;
  expiresAt?: string;
  details?: Readonly<Record<string, unknown>>;
}>;
type OAuth2ProviderFromPublicConfig = Readonly<{
  authorizeUrlFieldKey: string;
  tokenUrlFieldKey: string;
  userInfoUrlFieldKey?: string;
}>;
type CredentialOAuth2ScopesFromPublicConfig = Readonly<{
  presetFieldKey: string;
  presetScopes: Readonly<Record<string, ReadonlyArray<string>>>;
  customPresetKey?: string;
  customScopesFieldKey?: string;
}>;
type CredentialOAuth2AuthDefinition = Readonly<{
  kind: "oauth2";
  providerId: string;
  scopes: ReadonlyArray<string>;
  scopesFromPublicConfig?: CredentialOAuth2ScopesFromPublicConfig;
  clientIdFieldKey?: string;
  clientSecretFieldKey?: string;
} | {
  kind: "oauth2";
  providerFromPublicConfig: OAuth2ProviderFromPublicConfig;
  scopes: ReadonlyArray<string>;
  scopesFromPublicConfig?: CredentialOAuth2ScopesFromPublicConfig;
  clientIdFieldKey?: string;
  clientSecretFieldKey?: string;
} | {
  kind: "oauth2";
  /**
   * Free-form provider identifier for telemetry, DB rows, and Better Auth provider naming.
   * Not used for any registry lookup — URLs come from {@link authorizeUrl} / {@link tokenUrl}.
   */
  providerId: string;
  /**
   * Authorization endpoint. May contain `{publicFieldKey}` placeholders that the runtime
   * substitutes from the credential's resolved public config (URL-encoded).
   * Example: `https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize`
   */
  authorizeUrl: string;
  /** Token endpoint. Same templating rules as {@link authorizeUrl}. */
  tokenUrl: string;
  /** Optional userinfo endpoint. Same templating rules as {@link authorizeUrl}. */
  userInfoUrl?: string;
  scopes: ReadonlyArray<string>;
  scopesFromPublicConfig?: CredentialOAuth2ScopesFromPublicConfig;
  clientIdFieldKey?: string;
  clientSecretFieldKey?: string;
}>;
type CredentialAuthDefinition = CredentialOAuth2AuthDefinition;
type CredentialAdvancedSectionPresentation = Readonly<{
  /** Collapsible section title (default: "Advanced"). */
  title?: string;
  /** Optional short helper text shown inside the section (above the fields). */
  description?: string;
  /** When true, the advanced section starts expanded. Default: false (collapsed). */
  defaultOpen?: boolean;
}>;
type CredentialTypeDefinition = Readonly<{
  typeId: CredentialTypeId;
  displayName: string;
  description?: string;
  publicFields?: ReadonlyArray<CredentialFieldSchema>;
  secretFields?: ReadonlyArray<CredentialFieldSchema>;
  /**
   * Optional labels for the collapsible block that contains every field with `visibility: "advanced"`.
   * If omitted, the UI still shows that block with defaults (title "Advanced", collapsed).
   */
  advancedSection?: CredentialAdvancedSectionPresentation;
  supportedSourceKinds?: ReadonlyArray<CredentialMaterialSourceKind>;
  auth?: CredentialAuthDefinition;
}>;
/**
 * JSON-shaped credential field bag (public config, resolved secret material, etc.).
 */
type CredentialJsonRecord = Readonly<Record<string, unknown>>;
/**
 * Persisted credential instance with typed `publicConfig`.
 * Hosts may specialize `secretRef` with a stricter union while remaining
 * assignable here for session/test callbacks.
 */
type CredentialInstanceRecord<TPublicConfig extends CredentialJsonRecord = CredentialJsonRecord> = Readonly<{
  instanceId: CredentialInstanceId;
  typeId: CredentialTypeId;
  displayName: string;
  sourceKind: CredentialMaterialSourceKind;
  publicConfig: TPublicConfig;
  secretRef: CredentialJsonRecord;
  tags: ReadonlyArray<string>;
  setupStatus: CredentialSetupStatus;
  createdAt: string;
  updatedAt: string;
  /**
   * Pointer to where the credential material bytes live. For OSS / standalone
   * rows this is `{source: "local", ref: instanceId}` and the bytes co-locate
   * with the row in the workspace DB. For managed-mode rows this is
   * `{source: "control-plane", ref: <cp_id>}` and the bytes live at CP.
   *
   * The seam is read through `CredentialMaterialProvider`. See
   * `docs/design/credentials-oauth-unification.md` ("Material provider seam").
   */
  material: Readonly<{
    source: "local" | "control-plane";
    ref: string;
  }>;
}>;
/**
 * Arguments passed to `CredentialType.createSession` and `CredentialType.test`.
 * Declare `TPublicConfig` / `TMaterial` on `CredentialType` so implementations are checked
 * against your credential shapes (similar to `NodeExecutionContext.config` for nodes).
 */
type CredentialSessionFactoryArgs<TPublicConfig extends CredentialJsonRecord = CredentialJsonRecord, TMaterial extends CredentialJsonRecord = CredentialJsonRecord> = Readonly<{
  instance: CredentialInstanceRecord<TPublicConfig>;
  material: TMaterial;
  publicConfig: TPublicConfig;
}>;
type CredentialSessionFactory<TPublicConfig extends CredentialJsonRecord = CredentialJsonRecord, TMaterial extends CredentialJsonRecord = CredentialJsonRecord, TSession = unknown> = (args: CredentialSessionFactoryArgs<TPublicConfig, TMaterial>) => Promise<TSession>;
type CredentialHealthTester<TPublicConfig extends CredentialJsonRecord = CredentialJsonRecord, TMaterial extends CredentialJsonRecord = CredentialJsonRecord> = (args: CredentialSessionFactoryArgs<TPublicConfig, TMaterial>) => Promise<CredentialHealth>;
/**
 * Full credential type implementation: `definition` (UI/schema), `createSession`, and `test`.
 * Use this at registration and config boundaries; `CredentialTypeDefinition` is only the schema slice.
 */
type CredentialType<TPublicConfig extends CredentialJsonRecord = CredentialJsonRecord, TMaterial extends CredentialJsonRecord = CredentialJsonRecord, TSession = unknown> = Readonly<{
  definition: CredentialTypeDefinition;
  createSession: CredentialSessionFactory<TPublicConfig, TMaterial, TSession>;
  test: CredentialHealthTester<TPublicConfig, TMaterial>;
}>;
/**
 * Credential type with unspecified generics — used for `CodemationConfig.credentialTypes`, the host registry,
 * and anywhere a concrete `CredentialType<YourPublic, YourMaterial, YourSession>` is placed in a heterogeneous list.
 * Using `any` here avoids unsafe `as` casts while keeping typed `satisfies CredentialType<…>` definitions.
 */
type AnyCredentialType = CredentialType<any, any, unknown>;
interface CredentialSessionService {
  getSession<TSession = unknown>(args: Readonly<{
    workflowId: WorkflowId;
    nodeId: NodeId;
    slotKey: string;
  }>): Promise<TSession>;
}
interface CredentialTypeRegistry {
  listTypes(): ReadonlyArray<CredentialTypeDefinition>;
  getType(typeId: CredentialTypeId): CredentialTypeDefinition | undefined;
}
//#endregion
//#region ../core/src/contracts/mcpTypes.d.ts
type McpServerTransport = "http";
interface McpServerDeclaration {
  /** Globally unique slug, e.g. "gmail". Workflow authors reference this. */
  id: string;
  displayName: string;
  description: string;
  transport: McpServerTransport;
  url: string;
  /**
   * Credential types accepted by this MCP server, matching CredentialRequirement.acceptedTypes.
   * Absent or empty means no credential is required.
   */
  acceptedCredentialTypes?: ReadonlyArray<string>;
  /**
   * Documentation only in MVP. The bind-time validator checks
   * requiredScopes ⊆ CredentialInstance.scopesGranted.
   */
  requiredScopes?: string[];
  /** Non-secret static headers merged onto every MCP request. */
  staticHeaders?: Record<string, string>;
  /**
   * Overrides for tool descriptions advertised by the MCP server.
   * Applied by the connection pool after tools/list.
   * Key: exact tool name as returned by the server.
   */
  toolDescriptionOverrides?: Record<string, string>;
}
//#endregion
//#region ../core/src/contracts/collectionTypes.d.ts
/**
 * Represents a typed store for a single collection.
 * All rows include auto-managed id, created_at, and updated_at fields.
 */
interface CollectionStore<TRow extends Record<string, unknown> = Record<string, unknown>> {
  /**
   * Insert a new row. id, created_at, and updated_at are auto-populated.
   */
  insert(row: TRow): Promise<TRow & {
    id: string;
    created_at: Date;
    updated_at: Date;
  }>;
  /**
   * Get a single row by id.
   */
  get(id: string): Promise<(TRow & {
    id: string;
    created_at: Date;
    updated_at: Date;
  }) | null>;
  /**
   * Find a single row matching the provided filter.
   */
  findOne(filter: Partial<TRow>): Promise<(TRow & {
    id: string;
    created_at: Date;
    updated_at: Date;
  }) | null>;
  /**
   * List rows with optional pagination and filtering.
   */
  list(opts?: {
    limit?: number;
    offset?: number;
    where?: Partial<TRow>;
  }): Promise<{
    rows: ReadonlyArray<TRow & {
      id: string;
      created_at: Date;
      updated_at: Date;
    }>;
    total: number;
  }>;
  /**
   * Update a row by id with partial data.
   */
  update(id: string, patch: Partial<TRow>): Promise<TRow & {
    id: string;
    created_at: Date;
    updated_at: Date;
  }>;
  /**
   * Delete a row by id. Hard delete only (no soft delete).
   */
  delete(id: string): Promise<{
    deleted: boolean;
  }>;
}
/**
 * Runtime collections context: keyed by collection name.
 */
type CollectionsContext = Readonly<Record<string, CollectionStore>>;
//#endregion
//#region ../core/src/contracts/workflowActivationPolicy.d.ts
/**
 * Host-controlled policy: when false, trigger {@link TriggerNode} setup is skipped and webhook routes
 * for that workflow are not registered (see engine trigger runtime + webhook matcher).
 */
interface WorkflowActivationPolicy {
  isActive(workflowId: WorkflowId): boolean;
}
//#endregion
//#region ../core/src/authoring/defineNode.types.d.ts
type ResolvableCredentialType = AnyCredentialType | CredentialTypeId;
type DefinedNodeCredentialBinding = ResolvableCredentialType | Readonly<{
  readonly type: ResolvableCredentialType | ReadonlyArray<ResolvableCredentialType>;
  readonly label?: string;
  readonly optional?: true;
  readonly helpText?: string;
  readonly helpUrl?: string;
}>;
type DefinedNodeCredentialBindings = Readonly<Record<string, DefinedNodeCredentialBinding>>;
type DefinedNodeConfigInput<TConfigResolved extends CredentialJsonRecord, TItemJson> = ParamDeep<TConfigResolved, TItemJson>;
interface DefinedNode<TKey$1 extends string, TConfig extends CredentialJsonRecord, TInputJson$1, TOutputJson$1, _TBindings extends DefinedNodeCredentialBindings | undefined = undefined> {
  readonly kind: "defined-node";
  readonly key: TKey$1;
  readonly title: string;
  readonly description?: string;
  create<TConfigItemJson = TInputJson$1>(config: DefinedNodeConfigInput<TConfig, TConfigItemJson>, name?: string, id?: string): RunnableNodeConfig<TInputJson$1, TOutputJson$1>;
  register(context: {
    registerNode<TValue>(token: TypeToken<TValue>, implementation?: TypeToken<TValue>): void;
  }): void;
}
//#endregion
//#region ../core/src/authoring/defineHumanApprovalNode.types.d.ts
/**
 * Decision shape merged into `item.json` after a HITL approval task resolves.
 *
 * - `"approved"` / `"rejected"` — from a human decision (uses `approvedPredicate`).
 * - `"timed-out"` — timeout fired with `onTimeout: "halt"`.
 * - `"auto-accepted"` — timeout fired with `onTimeout: "auto-accept"`.
 */
interface HumanApprovalDecisionResult {
  readonly status: "approved" | "rejected" | "timed-out" | "auto-accepted";
  /** Identity of the person who decided; absent for automated outcomes. */
  readonly actor?: HumanTaskActor;
  /** ISO 8601 timestamp of the decision. */
  readonly decidedAt?: Date;
  /** Optional free-text note from the reviewer. */
  readonly note?: string;
  /**
   * Full raw decision payload (only present for `"approved"` / `"rejected"`).
   * Shape is determined by the channel's `decisionSchema`.
   */
  readonly payload?: Record<string, unknown>;
}
/**
 * Output item shape emitted by a `defineHumanApprovalNode`-based node.
 * Original `item.json` fields are preserved and `decision` is merged in.
 * If the input `item.json` already contained a `decision` key it is **overwritten**.
 */
type HumanApprovalOutputJson<TInputJson$1 extends Record<string, unknown>> = TInputJson$1 & {
  readonly decision: HumanApprovalDecisionResult;
};
/**
 * Extends {@link DefinedNode} with the `humanApprovalToolBehavior` metadata marker.
 * Story 10 reads this field when attaching the node as an agent tool.
 */
interface DefinedHumanApprovalNode<TKey$1 extends string, TConfig extends CredentialJsonRecord, TInputJson$1 extends Record<string, unknown>, TBindings extends DefinedNodeCredentialBindings | undefined = undefined> extends DefinedNode<TKey$1, TConfig, TInputJson$1, HumanApprovalOutputJson<TInputJson$1>, TBindings> {
  /**
   * Behavior hint consumed by the agent runtime (story 10) when this node is attached as a tool.
   * `"return"` (default) — return the rejection to the agent as a tool result.
   * `"halt"` — halt the agent run on rejection.
   *
   * Standalone DSL usage ignores this field.
   */
  readonly humanApprovalToolBehavior: {
    onRejected: "return" | "halt";
  };
}
//#endregion
//#region ../core/src/workflow/dsl/workflowBuilderTypes.d.ts
type AnyRunnableNodeConfig = RunnableNodeConfig<any, any>;
type AnyTriggerNodeConfig = TriggerNodeConfig<any>;
type ValidStepSequence<TCurrentJson, TSteps extends ReadonlyArray<AnyRunnableNodeConfig>> = TSteps extends readonly [] ? readonly [] : TSteps extends readonly [infer TFirst, ...infer TRest] ? TFirst extends RunnableNodeConfig<TCurrentJson, infer TNextJson> ? TRest extends ReadonlyArray<AnyRunnableNodeConfig> ? readonly [TFirst, ...ValidStepSequence<TNextJson, TRest>] : never : never : TSteps;
type StepSequenceOutput<TCurrentJson, TSteps extends ReadonlyArray<AnyRunnableNodeConfig> | undefined> = TSteps extends ReadonlyArray<AnyRunnableNodeConfig> ? TSteps extends readonly [] ? TCurrentJson : TSteps extends readonly [infer TFirst, ...infer TRest] ? TFirst extends RunnableNodeConfig<TCurrentJson, infer TNextJson> ? TRest extends ReadonlyArray<AnyRunnableNodeConfig> ? StepSequenceOutput<TNextJson, TRest> : never : never : TCurrentJson : TCurrentJson;
type TypesMatch<TLeft, TRight> = [TLeft] extends [TRight] ? ([TRight] extends [TLeft] ? true : false) : false;
type BranchOutputGuard<TCurrentJson, TTrueSteps extends ReadonlyArray<AnyRunnableNodeConfig> | undefined, TFalseSteps extends ReadonlyArray<AnyRunnableNodeConfig> | undefined> = TypesMatch<StepSequenceOutput<TCurrentJson, TTrueSteps>, StepSequenceOutput<TCurrentJson, TFalseSteps>> extends true ? unknown : never;
type BranchStepsArg<TCurrentJson, TSteps extends ReadonlyArray<AnyRunnableNodeConfig>> = TSteps & ValidStepSequence<TCurrentJson, TSteps>;
type BranchMoreArgs<TCurrentJson, TFirstStep extends RunnableNodeConfig<TCurrentJson, any>, TRestSteps extends ReadonlyArray<AnyRunnableNodeConfig>> = TRestSteps & ValidStepSequence<RunnableNodeOutputJson<TFirstStep>, TRestSteps>;
type BooleanWhenOverloads<TCurrentJson, TReturn> = {
  <TSteps extends ReadonlyArray<AnyRunnableNodeConfig>>(branch: boolean, steps: BranchStepsArg<TCurrentJson, TSteps>): TReturn;
  <TFirstStep extends RunnableNodeConfig<TCurrentJson, any>, TRestSteps extends ReadonlyArray<AnyRunnableNodeConfig>>(branch: boolean, step: TFirstStep, ...more: BranchMoreArgs<TCurrentJson, TFirstStep, TRestSteps>): TReturn;
};
//#endregion
//#region ../core/src/workflow/dsl/WhenBuilder.d.ts
declare class WhenBuilder<TCurrentJson> {
  private readonly wf;
  private readonly from;
  private readonly branchPort;
  constructor(wf: WorkflowBuilder, from: NodeRef, branchPort: OutputPortKey);
  addBranch<TSteps extends ReadonlyArray<AnyRunnableNodeConfig>>(steps: TSteps & ValidStepSequence<TCurrentJson, TSteps>): this;
  readonly when: BooleanWhenOverloads<TCurrentJson, WhenBuilder<TCurrentJson>>;
  build(): WorkflowDefinition;
}
//#endregion
//#region ../core/src/workflow/dsl/ChainCursorResolver.d.ts
type ChainCursorEndpoint = Readonly<{
  node: NodeRef;
  output: OutputPortKey;
  inputPortHint?: InputPortKey;
}>;
type ChainCursorWhenOverloads<TCurrentJson> = BooleanWhenOverloads<TCurrentJson, WhenBuilder<TCurrentJson>> & {
  <TTrueSteps extends ReadonlyArray<AnyRunnableNodeConfig> | undefined, TFalseSteps extends ReadonlyArray<AnyRunnableNodeConfig> | undefined>(branches: Readonly<{
    true?: TTrueSteps extends ReadonlyArray<AnyRunnableNodeConfig> ? BranchStepsArg<TCurrentJson, TTrueSteps> : never;
    false?: TFalseSteps extends ReadonlyArray<AnyRunnableNodeConfig> ? BranchStepsArg<TCurrentJson, TFalseSteps> : never;
  }> & BranchOutputGuard<TCurrentJson, TTrueSteps, TFalseSteps>): ChainCursor<StepSequenceOutput<TCurrentJson, TTrueSteps>>;
};
declare class ChainCursor<TCurrentJson> {
  private readonly wf;
  private readonly endpoints;
  constructor(wf: WorkflowBuilder, endpoints: ReadonlyArray<ChainCursorEndpoint>);
  then<TOutputJson$1, TConfig extends RunnableNodeConfig<TCurrentJson, TOutputJson$1>>(config: TConfig): ChainCursor<RunnableNodeOutputJson<TConfig>>;
  thenIntoInputHints<TOutputJson$1, TConfig extends RunnableNodeConfig<any, TOutputJson$1>>(config: TConfig): ChainCursor<RunnableNodeOutputJson<TConfig>>;
  readonly when: ChainCursorWhenOverloads<TCurrentJson>;
  route<TNextJson$1>(branches: Readonly<Record<OutputPortKey, (branch: ChainCursor<TCurrentJson>) => ChainCursor<TNextJson$1> | undefined>>): ChainCursor<TNextJson$1>;
  /**
   * Chainable shorthand for `.then(node.create(config, metadata?.name, metadata?.nodeId))`.
   *
   * Signals to readers that this step suspends the run and waits for a human decision.
   * Throws at workflow-build time if `node` was not created via `defineHumanApprovalNode`.
   *
   * @example
   * ```ts
   * workflow
   *   .trigger(...)
   *   .humanApproval(inboxApproval, { title: "Approve?", body: "...", priority: "normal" })
   *   .then(nextStep.create(...))
   *   .build();
   * ```
   */
  humanApproval<TKey$1 extends string, TConfig extends Record<string, unknown>, TBindings extends DefinedNodeCredentialBindings | undefined = undefined>(node: DefinedHumanApprovalNode<TKey$1, TConfig, TCurrentJson & Record<string, unknown>, TBindings>, config: TConfig, metadata?: {
    name?: string;
    nodeId?: string;
  }): ChainCursor<HumanApprovalOutputJson<TCurrentJson & Record<string, unknown>>>;
  build(): WorkflowDefinition;
  private resolveSharedInputPortHint;
}
//#endregion
//#region ../core/src/workflow/dsl/WorkflowBuilder.d.ts
declare class WorkflowBuilder {
  private readonly meta;
  private readonly options?;
  private readonly nodes;
  private readonly edges;
  constructor(meta: {
    id: WorkflowId;
    name: string;
  }, options?: Readonly<Record<string, never>> | undefined);
  private add;
  private connect;
  trigger<TConfig extends AnyTriggerNodeConfig>(config: TConfig): ChainCursor<TriggerNodeOutputJson<TConfig>>;
  start<TConfig extends AnyRunnableNodeConfig>(config: TConfig): ChainCursor<RunnableNodeOutputJson<TConfig>>;
  build(): WorkflowDefinition;
  private validateNodeIds;
}
//#endregion
//#region ../core/src/events/runEvents.d.ts
/**
 * Outcome of a single test case (one workflow run dispatched by the test-suite orchestrator).
 * - `running`: workflow still in flight
 * - `succeeded`: workflow completed AND all assertions passed (or no assertions)
 * - `failed`: workflow failed OR (workflow completed but ≥1 assertion failed)
 * - `errored` / `cancelled`: workflow itself errored or was cancelled
 */
type TestCaseRunStatus = "running" | "succeeded" | "failed" | "errored" | "cancelled";
/** Aggregate outcome of a TestSuiteRun. */
type TestSuiteRunStatus = "succeeded" | "failed" | "partial" | "errored" | "cancelled";
type RunEvent = Readonly<{
  kind: "runCreated";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
}> | Readonly<{
  kind: "runSaved";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
  state: PersistedRunState;
}> | Readonly<{
  kind: "nodeQueued";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
  snapshot: NodeExecutionSnapshot;
}> | Readonly<{
  kind: "nodeStarted";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
  snapshot: NodeExecutionSnapshot;
}> | Readonly<{
  kind: "nodeCompleted";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
  snapshot: NodeExecutionSnapshot;
}> | Readonly<{
  kind: "nodeFailed";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
  snapshot: NodeExecutionSnapshot;
}> | Readonly<{
  kind: "connectionInvocationStarted";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
  record: ConnectionInvocationRecord;
}> | Readonly<{
  kind: "connectionInvocationCompleted";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
  record: ConnectionInvocationRecord;
}> | Readonly<{
  kind: "connectionInvocationFailed";
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  at: string;
  record: ConnectionInvocationRecord;
}> | Readonly<{
  kind: "testSuiteStarted";
  testSuiteRunId: TestSuiteRunId;
  workflowId: WorkflowId;
  triggerNodeId: string;
  triggerNodeName?: string;
  concurrency: number;
  at: string;
}> | Readonly<{
  kind: "testSuiteFinished";
  testSuiteRunId: TestSuiteRunId;
  workflowId: WorkflowId;
  status: TestSuiteRunStatus;
  totalCases: number;
  passedCases: number;
  failedCases: number;
  at: string;
}> | Readonly<{
  kind: "testCaseStarted";
  testSuiteRunId: TestSuiteRunId;
  testCaseIndex: number;
  runId: RunId;
  workflowId: WorkflowId;
  testCaseLabel?: string;
  at: string;
}> | Readonly<{
  kind: "testCaseCompleted";
  testSuiteRunId: TestSuiteRunId;
  testCaseIndex: number;
  runId: RunId;
  workflowId: WorkflowId;
  status: TestCaseRunStatus;
  at: string;
}>;
interface RunEventSubscription {
  close(): Promise<void>;
}
interface RunEventBus {
  publish(event: RunEvent): Promise<void>;
  subscribe(onEvent: (event: RunEvent) => void): Promise<RunEventSubscription>;
  subscribeToWorkflow(workflowId: WorkflowId, onEvent: (event: RunEvent) => void): Promise<RunEventSubscription>;
}
//#endregion
//#region ../core/src/policies/executionLimits/EngineExecutionLimitsPolicy.d.ts
interface EngineExecutionLimitsPolicyConfig {
  readonly defaultMaxNodeActivations: number;
  readonly hardMaxNodeActivations: number;
  readonly defaultMaxSubworkflowDepth: number;
  readonly hardMaxSubworkflowDepth: number;
}
//#endregion
//#region ../core/src/contracts/runTypes.d.ts
/**
 * Test-suite linkage for a run. When set, this run was started by a TestSuiteOrchestrator
 * as one test case inside a TestSuiteRun. The `IsTestRun` node and host-side persisters key
 * off the presence of this field. Subworkflow runs inherit it from their parent run.
 */
interface RunTestContext {
  readonly testSuiteRunId: string;
  readonly testCaseIndex: number;
  /**
   * Optional human-friendly label for this test case (e.g. an email subject when fixtures
   * are loaded from a mailbox). Resolved per item by `TestTrigger.caseLabel(item)` if set,
   * persisted on `Run.test_case_label` so the Tests-tab tree-table can show "RFQ for batch 14"
   * instead of "run_1777755971399_bbb86beac1396".
   */
  readonly testCaseLabel?: string;
}
interface RunExecutionOptions {
  /** Run-intent override: force the inline scheduler and bypass node-level offload decisions. */
  localOnly?: boolean;
  /** Marks runs started from webhook handling so orchestration can apply webhook-specific continuation rules. */
  webhook?: boolean;
  mode?: "manual" | "debug";
  sourceWorkflowId?: WorkflowId;
  sourceRunId?: RunId;
  derivedFromRunId?: RunId;
  isMutable?: boolean;
  /** Set by the engine for this run: 0 = root, 1 = first child subworkflow, … */
  subworkflowDepth?: number;
  /** Effective cap after engine policy merge (successful node completions per run). */
  maxNodeActivations?: number;
  /** Effective cap after engine policy merge (subworkflow nesting). */
  maxSubworkflowDepth?: number;
  /** Present iff started by a TestSuiteOrchestrator; propagates to subworkflow runs via {@link ParentExecutionRef.testContext}. */
  testContext?: RunTestContext;
}
/** Engine-owned counters persisted with the run (worker-safe). */
interface EngineRunCounters {
  completedNodeActivations: number;
}
type RunStopCondition = Readonly<{
  kind: "workflowCompleted";
}> | Readonly<{
  kind: "nodeCompleted";
  nodeId: NodeId;
}>;
interface RunStateResetRequest {
  clearFromNodeId: NodeId;
}
interface PersistedRunControlState {
  stopCondition?: RunStopCondition;
}
interface PersistedWorkflowSnapshotNode {
  id: NodeId;
  kind: NodeKind;
  name?: string;
  nodeTokenId: PersistedTokenId;
  configTokenId: PersistedTokenId;
  tokenName?: string;
  configTokenName?: string;
  config: unknown;
  /** Pre-computed static configuration summary; populated by WorkflowSnapshotCodec. */
  inspectorSummary?: ReadonlyArray<Readonly<{
    label: string;
    value: string;
  }>>;
}
interface PersistedWorkflowSnapshot {
  id: WorkflowId;
  name: string;
  nodes: ReadonlyArray<PersistedWorkflowSnapshotNode>;
  edges: ReadonlyArray<Edge>;
  /** When the snapshot was built from a live workflow definition that configured a workflow error handler. */
  workflowErrorHandlerConfigured?: boolean;
  /** Connection metadata for child nodes not in the execution graph (e.g. AI agent attachments). */
  connections?: ReadonlyArray<WorkflowNodeConnection>;
}
type PinnedNodeOutputsByPort = Readonly<Record<OutputPortKey, Items>>;
interface PersistedMutableNodeState {
  pinnedOutputsByPort?: PinnedNodeOutputsByPort;
  lastDebugInput?: Items;
}
interface PersistedMutableRunState {
  nodesById: Readonly<Record<NodeId, PersistedMutableNodeState>>;
}
type NodeInputsByPort = Readonly<Record<InputPortKey, Items>>;
interface RunQueueEntry {
  nodeId: NodeId;
  input: Items;
  toInput?: InputPortKey;
  batchId?: string;
  from?: Readonly<{
    nodeId: NodeId;
    output: OutputPortKey;
  }>;
  collect?: Readonly<{
    expectedInputs: ReadonlyArray<InputPortKey>;
    received: Readonly<Record<InputPortKey, Items>>;
  }>;
}
type NodeExecutionStatus = "pending" | "queued" | "running" | "completed" | "failed" | "skipped" | "hitl-approved" | "hitl-rejected" | "hitl-timeout" | "hitl-auto-accepted" | "hitl-cancelled";
interface NodeExecutionError {
  message: string;
  name?: string;
  stack?: string;
  details?: JsonValue;
}
interface NodeExecutionSnapshot {
  runId: RunId;
  workflowId: WorkflowId;
  nodeId: NodeId;
  activationId?: NodeActivationId;
  parent?: ParentExecutionRef;
  status: NodeExecutionStatus;
  usedPinnedOutput?: boolean;
  queuedAt?: string;
  startedAt?: string;
  finishedAt?: string;
  updatedAt: string;
  inputsByPort?: NodeInputsByPort;
  outputs?: NodeOutputs;
  error?: NodeExecutionError;
  /**
   * When the node is a SubWorkflow invocation, the run id of the child run it spawned.
   * Populated after the child run completes so the UI can deep-link to that specific execution.
   */
  childRunId?: RunId;
}
/** Stable id for a single connection invocation row in {@link ConnectionInvocationRecord}. */
type ConnectionInvocationId = string;
/**
 * One logical LLM or tool call under an owning workflow node (e.g. AI agent).
 * The owning node defines what {@link managedInput} and {@link managedOutput} contain.
 */
interface ConnectionInvocationRecord {
  readonly invocationId: ConnectionInvocationId;
  readonly runId: RunId;
  readonly workflowId: WorkflowId;
  readonly connectionNodeId: NodeId;
  readonly parentAgentNodeId: NodeId;
  readonly parentAgentActivationId: NodeActivationId;
  readonly status: NodeExecutionStatus;
  readonly managedInput?: JsonValue;
  readonly managedOutput?: JsonValue;
  /** Short human-readable description of what this invocation is doing right now (e.g. `"calling search_messages"`). Rendered as a sub-line on the canvas node card. */
  readonly statusLabel?: string;
  /** Stable identifier for the thing this invocation acts on (e.g. an MCP tool name like `"search_messages"`). Persists across status transitions so the inspector can show it on completed/failed entries too. Connection nodes that ARE the tool (e.g. node-backed agent tools) leave this unset — the parent node id already identifies the subject. */
  readonly subjectName?: string;
  readonly error?: NodeExecutionError;
  readonly queuedAt?: string;
  readonly startedAt?: string;
  readonly finishedAt?: string;
  readonly updatedAt: string;
  /** Per-item iteration id minted by the engine when this invocation occurred inside a runnable node's per-item loop. */
  readonly iterationId?: NodeIterationId;
  /** Item index (0-based) of the iteration that produced this invocation. */
  readonly itemIndex?: number;
  /** When set, this invocation was produced inside a sub-agent triggered by the named parent invocation. */
  readonly parentInvocationId?: ConnectionInvocationId;
}
/** Arguments for appending a {@link ConnectionInvocationRecord} (engine fills run/workflow ids and timestamps). */
type ConnectionInvocationAppendArgs = Readonly<{
  invocationId: ConnectionInvocationId;
  connectionNodeId: NodeId;
  parentAgentNodeId: NodeId;
  parentAgentActivationId: NodeActivationId;
  status: NodeExecutionStatus;
  managedInput?: JsonValue;
  managedOutput?: JsonValue;
  statusLabel?: string;
  subjectName?: string;
  error?: NodeExecutionError;
  queuedAt?: string;
  startedAt?: string;
  finishedAt?: string;
  iterationId?: NodeIterationId;
  itemIndex?: number;
  parentInvocationId?: ConnectionInvocationId;
}>;
interface RunCurrentState {
  outputsByNode: Record<NodeId, NodeOutputs>;
  nodeSnapshotsByNodeId: Record<NodeId, NodeExecutionSnapshot>;
  /** Append-only history of connection-scoped invocations (LLM/tool) for inspector and canvas. */
  connectionInvocations?: ReadonlyArray<ConnectionInvocationRecord>;
  mutableState?: PersistedMutableRunState;
}
interface CurrentStateExecutionRequest {
  workflow: WorkflowDefinition;
  items?: Items;
  parent?: ParentExecutionRef;
  executionOptions?: RunExecutionOptions;
  workflowSnapshot?: PersistedWorkflowSnapshot;
  mutableState?: PersistedMutableRunState;
  currentState?: RunCurrentState;
  stopCondition?: RunStopCondition;
  reset?: RunStateResetRequest;
}
type RunStatus = "running" | "pending" | "completed" | "failed" | "suspended" | "halted";
/** Reason a run transitioned to {@link RunStatus} `"halted"`. */
type RunHaltReason = "hitl-rejected" | "hitl-timeout" | "hitl-cancelled";
interface RunSummary {
  runId: RunId;
  workflowId: WorkflowId;
  startedAt: string;
  status: RunStatus;
  /**
   * Test-case status for runs dispatched as part of a TestSuiteRun. Carries the
   * assertion-rollup-corrected outcome the test orchestrator persists onto the row, so the
   * executions list can show "failed" for a run whose workflow completed cleanly but whose
   * assertions caught regressions. Absent for non-test runs and legacy rows.
   */
  testCaseStatus?: TestCaseRunStatus;
  /** ISO timestamp when the run finished (derived from node snapshots or store `updatedAt`); omit while running/pending. */
  finishedAt?: string;
  parent?: ParentExecutionRef;
  executionOptions?: RunExecutionOptions;
}
interface PendingNodeExecution {
  runId: RunId;
  activationId: NodeActivationId;
  workflowId: WorkflowId;
  nodeId: NodeId;
  itemsIn: number;
  inputsByPort: NodeInputsByPort;
  receiptId: string;
  queue?: string;
  batchId?: string;
  enqueuedAt: string;
}
interface PersistedRunSchedulingState {
  pending?: PendingNodeExecution;
  queue: RunQueueEntry[];
}
/** One persisted suspension entry per suspended item. */
interface PersistedSuspensionEntry {
  /** Opaque task identifier (UUID v4). */
  readonly taskId: string;
  readonly nodeId: NodeId;
  readonly activationId: NodeActivationId;
  readonly itemIndex: number;
  /** SHA-256 hex digest of the decision schema JSON (for schema-drift detection). */
  readonly decisionSchemaHash: string;
  /** Serialized return value from `SuspensionRequest.deliver` (stored on the HumanTask row). */
  readonly deliveryRef: JsonValue;
  /** ISO timestamp when the task expires. */
  readonly timeoutAt: string;
  readonly onTimeout: "halt" | "auto-accept";
}
/**
 * When a node is re-activated after suspension, the engine writes the resume context here
 * so `NodeExecutionRequestHandlerService` can splice `resumeContext` into ctx.
 * Cleared once the re-activation is consumed.
 */
interface PendingResumeEntry {
  readonly activationId: NodeActivationId;
  readonly nodeId: NodeId;
  /**
   * Typed as `unknown` here to avoid a circular import between runTypes ↔ runtimeTypes.
   * `NodeExecutionRequestHandlerService` casts this to `ResumeContext` from runtimeTypes.
   */
  readonly resumeContext: unknown;
}
interface PersistedRunState {
  runId: RunId;
  workflowId: WorkflowId;
  startedAt: string;
  /** Canonical terminal time for listings and retention when persisted on the run root. */
  finishedAt?: string;
  /** Optimistic concurrency / CAS on the run aggregate (repository may increment on save). */
  revision?: number;
  parent?: ParentExecutionRef;
  executionOptions?: RunExecutionOptions;
  control?: PersistedRunControlState;
  workflowSnapshot?: PersistedWorkflowSnapshot;
  mutableState?: PersistedMutableRunState;
  /** Frozen at createRun from workflow + runtime defaults for prune/storage decisions. */
  policySnapshot?: PersistedRunPolicySnapshot;
  /** Successful node completions so far (for activation budget). */
  engineCounters?: EngineRunCounters;
  status: RunStatus;
  /** Populated when `status === "halted"` to discriminate why the run was halted. */
  reason?: RunHaltReason;
  pending?: PendingNodeExecution;
  queue: RunQueueEntry[];
  outputsByNode: Record<NodeId, NodeOutputs>;
  nodeSnapshotsByNodeId: Record<NodeId, NodeExecutionSnapshot>;
  /** Append-only history of connection invocations (LLM/tool) nested under owning nodes. */
  connectionInvocations?: ReadonlyArray<ConnectionInvocationRecord>;
  /**
   * One entry per outstanding HITL suspension (per-item).
   * Present and non-empty iff `status === "suspended"`.
   */
  suspension?: ReadonlyArray<PersistedSuspensionEntry>;
  /**
   * Written by `resumeRun()` so `NodeExecutionRequestHandlerService` can splice `resumeContext`
   * into the ctx when re-executing the suspended node. Cleared once consumed.
   */
  pendingResume?: PendingResumeEntry;
}
interface WorkflowExecutionRepository {
  createRun(args: {
    runId: RunId;
    workflowId: WorkflowId;
    startedAt: string;
    parent?: ParentExecutionRef;
    executionOptions?: RunExecutionOptions;
    control?: PersistedRunControlState;
    workflowSnapshot?: PersistedWorkflowSnapshot;
    mutableState?: PersistedMutableRunState;
    policySnapshot?: PersistedRunPolicySnapshot;
    engineCounters?: EngineRunCounters;
  }): Promise<void>;
  load(runId: RunId): Promise<PersistedRunState | undefined>;
  loadSchedulingState(runId: RunId): Promise<PersistedRunSchedulingState | undefined>;
  save(state: PersistedRunState): Promise<void>;
  deleteRun?(runId: RunId): Promise<void>;
}
/** Runs eligible for retention-based pruning (completed or failed, older than cutoff). */
interface RunPruneCandidate {
  readonly runId: RunId;
  readonly workflowId: WorkflowId;
  readonly startedAt: string;
  readonly finishedAt: string;
}
type RunResult = {
  runId: RunId;
  workflowId: WorkflowId;
  startedAt: string;
  status: "completed";
  outputs: Items;
} | {
  runId: RunId;
  workflowId: WorkflowId;
  startedAt: string;
  status: "pending";
  pending: PendingNodeExecution;
} | {
  runId: RunId;
  workflowId: WorkflowId;
  startedAt: string;
  status: "failed";
  error: {
    message: string;
  };
} | {
  runId: RunId;
  workflowId: WorkflowId;
  startedAt: string;
  status: "halted";
  reason: RunHaltReason;
};
type WebhookRunResult = Readonly<{
  runId: RunId;
  workflowId: WorkflowId;
  startedAt: string;
  runStatus: "pending" | "completed";
  response: Items;
}>;
interface PersistedWorkflowTokenRegistryLike {
  register(type: TypeToken<unknown>, packageId: string, persistedNameOverride?: string): string;
  getTokenId(type: TypeToken<unknown>): string | undefined;
  resolve(tokenId: string): TypeToken<unknown> | undefined;
  registerFromWorkflows?(workflows: ReadonlyArray<WorkflowDefinition>): void;
}
//#endregion
//#region ../core/src/contracts/workflowTypes.d.ts
type NodeIdRef<TJson = unknown> = NodeId & Readonly<{
  __codemationNodeJson?: TJson;
}>;
type NodeKind = "trigger" | "node";
type JsonPrimitive = string | number | boolean | null;
interface JsonObject {
  readonly [key: string]: JsonValue;
}
type JsonValue = JsonPrimitive | JsonObject | JsonArray;
type JsonArray = ReadonlyArray<JsonValue>;
interface Edge {
  from: {
    nodeId: NodeId;
    output: OutputPortKey;
  };
  to: {
    nodeId: NodeId;
    input: InputPortKey;
  };
}
/**
 * Named connection from a parent node to child nodes that exist in {@link WorkflowDefinition.nodes}
 * but are not traversed by the main execution graph. Parents are commonly executable nodes, but may
 * also be connection-owned nodes for recursive agent attachments.
 */
interface WorkflowNodeConnection {
  readonly parentNodeId: NodeId;
  readonly connectionName: NodeConnectionName;
  readonly childNodeIds: ReadonlyArray<NodeId>;
}
interface WorkflowDefinition {
  id: WorkflowId;
  name: string;
  nodes: NodeDefinition[];
  edges: Edge[];
  /**
   * Optional metadata: which nodes are connection-owned children (e.g. AI agent `llm` / `tools` slots).
   * When omitted, all nodes in {@link nodes} are treated as executable for topology.
   */
  readonly connections?: ReadonlyArray<WorkflowNodeConnection>;
  /** Directory + file-stem path under a workflow discovery root (for UI grouping only). */
  discoveryPathSegments?: readonly string[];
  /** Retention for run JSON and binaries (seconds). Host/env may supply defaults when omitted. */
  readonly prunePolicy?: WorkflowPrunePolicySpec;
  /** Whether to keep run data after completion. Host/env may supply defaults when omitted. */
  readonly storagePolicy?: WorkflowStoragePolicySpec;
  /** Invoked after a node fails permanently (retries exhausted) and node error handler did not recover. */
  readonly workflowErrorHandler?: WorkflowErrorHandlerSpec;
}
interface NodeConfigBase {
  readonly kind: NodeKind;
  readonly type: TypeToken<unknown>;
  readonly name?: string;
  readonly id?: NodeId;
  readonly icon?: string;
  readonly execution?: Readonly<{
    hint?: "local" | "worker";
    queue?: string;
  }>;
  /** In-process execute retries (runnable nodes). Triggers typically omit this. */
  readonly retryPolicy?: RetryPolicySpec;
  /** Recover from execute failures; return outputs to continue, or rethrow to fail the node. */
  readonly nodeErrorHandler?: NodeErrorHandlerSpec;
  /**
   * When true, edges carrying zero items on an output port still schedule single-input downstream nodes.
   * Decided from the **source** node that produced the (empty) output. Default (false/undefined): empty
   * main batches skip downstream execution and propagate the empty path.
   */
  readonly continueWhenEmptyOutput?: boolean;
  /**
   * Declared I/O port names for canvas authoring (unioned with ports inferred from edges).
   * Use for dynamic routers (Switch) and future error ports.
   */
  readonly declaredOutputPorts?: ReadonlyArray<OutputPortKey>;
  readonly declaredInputPorts?: ReadonlyArray<InputPortKey>;
  getCredentialRequirements?(): ReadonlyArray<CredentialRequirement>;
  /**
   * Marker: this node emits {@link import("./assertionTypes").AssertionResult}-shaped items on its
   * `main` port. The TestSuiteOrchestrator (and host-side TestAssertionPersister) listen for
   * `nodeCompleted` events from nodes with this flag set, and persist their output items as
   * TestAssertion records (only when the run carries a `testContext`). Set on assertion node
   * configs (e.g. `AssertionNodeConfig`, `StringEqualsAssertionNodeConfig`).
   */
  readonly emitsAssertions?: true;
  /**
   * Static configuration summary surfaced in the workflow inspector — the design-time
   * "what does this node do" panel that renders before any run telemetry exists.
   *
   * Return 2–6 short label/value pairs derived from this config (method + url for an HTTP
   * call, model + tool list for an agent, schedule + timezone for a cron trigger, etc.).
   * Values are truncated by the UI; aim for one line each. Return `undefined` to opt out
   * — the inspector hides the section when no rows are produced.
   *
   * Implement on the config class instance so the function can read sibling config fields.
   * `defineNode({ inspectorSummary })` plumbs through to this.
   */
  inspectorSummary?(): ReadonlyArray<NodeInspectorSummaryRow> | undefined;
}
/**
 * One row of a node's static configuration summary. See {@link NodeConfigBase.inspectorSummary}.
 */
interface NodeInspectorSummaryRow {
  readonly label: string;
  readonly value: string;
}
declare const runnableNodeInputType: unique symbol;
declare const runnableNodeOutputType: unique symbol;
declare const triggerNodeOutputType: unique symbol;
/**
 * Runnable node: **`TInputJson`** is what **`inputSchema`** validates on **`item.json`** (the wire payload).
 * **`TOutputJson`** is emitted `item.json` on outputs.
 */
interface RunnableNodeConfig<TInputJson$1 = unknown, TOutputJson$1 = unknown> extends NodeConfigBase {
  readonly kind: "node";
  readonly [runnableNodeInputType]?: TInputJson$1;
  readonly [runnableNodeOutputType]?: TOutputJson$1;
  /**
   * Optional Zod input contract for {@link RunnableNode} when not set on the node class.
   * Resolution order: node instance `inputSchema`, then config `inputSchema`, then `z.unknown()`.
   */
  readonly inputSchema?: ZodType<TInputJson$1>;
  /**
   * When an activation receives **zero** input items, the engine normally runs `execute` zero times.
   * Set to **`runOnce`** to run `execute` once with an empty `items` batch (and a synthetic wire item for schema parsing).
   * Used by batch-style callback nodes (built-in `Callback`) so `callback([], ctx)` still runs.
   */
  readonly emptyBatchExecution?: "skip" | "runOnce";
}
declare const triggerNodeSetupStateType: unique symbol;
interface TriggerNodeConfig<TOutputJson$1 = unknown, TSetupState$1 extends JsonValue | undefined = undefined> extends NodeConfigBase {
  readonly kind: "trigger";
  readonly [triggerNodeOutputType]?: TOutputJson$1;
  readonly [triggerNodeSetupStateType]?: TSetupState$1;
  /**
   * Distinguishes triggers driven by the live activation policy (webhooks, cron, polling) from
   * triggers driven only by the {@link TestSuiteOrchestrator}. `WorkflowActivation` skips
   * `"test"` triggers; the orchestrator skips `"live"` triggers. Defaults to `"live"` when omitted.
   */
  readonly triggerKind?: "live" | "test";
}
type RunnableNodeOutputJson<TConfig extends RunnableNodeConfig<any, any>> = TConfig extends RunnableNodeConfig<any, infer TOutputJson> ? TOutputJson : never;
type TriggerNodeOutputJson<TConfig extends TriggerNodeConfig<any, any>> = TConfig extends TriggerNodeConfig<infer TOutputJson, any> ? TOutputJson : never;
interface NodeDefinition {
  id: NodeId;
  kind: NodeKind;
  type: TypeToken<unknown>;
  name?: string;
  config: NodeConfigBase;
}
interface NodeRef {
  id: NodeId;
  kind: NodeKind;
  name?: string;
}
type PairedItemRef = Readonly<{
  nodeId: NodeId;
  output: OutputPortKey;
  itemIndex: number;
}>;
type BinaryPreviewKind = "image" | "audio" | "video" | "download";
type BinaryAttachment = Readonly<{
  id: string;
  storageKey: string;
  mimeType: string;
  size: number;
  storageDriver: string;
  previewKind: BinaryPreviewKind;
  createdAt: string;
  runId: RunId;
  workflowId: WorkflowId;
  nodeId: NodeId;
  activationId: NodeActivationId;
  filename?: string;
  sha256?: string;
}>;
type ItemBinary = Readonly<Record<string, BinaryAttachment>>;
type Item<TJson = unknown> = Readonly<{
  json: TJson;
  binary?: ItemBinary;
  meta?: Readonly<Record<string, unknown>>;
  paired?: ReadonlyArray<PairedItemRef>;
}>;
type Items<TJson = unknown> = ReadonlyArray<Item<TJson>>;
type NodeOutputs = Partial<Record<OutputPortKey, Items>>;
type RunId = string;
type NodeActivationId = string;
/**
 * One per-item iteration of a runnable node's execute loop. Refines `NodeActivationId` for
 * per-item connection invocations and telemetry. Undefined when the executing node is a batch
 * node or trigger that does not iterate items.
 */
type NodeIterationId = string;
interface ParentExecutionRef {
  runId: RunId;
  workflowId: WorkflowId;
  nodeId: NodeId;
  /** Subworkflow depth of the **spawning** run (0 = root). Passed when starting a child run. */
  subworkflowDepth?: number;
  /** Effective max node activations from the parent run (propagated to child policy merge). */
  engineMaxNodeActivations?: number;
  /** Effective max subworkflow depth from the parent run (propagated to child policy merge). */
  engineMaxSubworkflowDepth?: number;
  /**
   * Test-suite linkage inherited by the child subworkflow run. Set by whichever node
   * spawns the subworkflow when its own `ctx.testContext` is present, so assertions
   * emitted inside a subworkflow land under the correct parent test case.
   */
  testContext?: RunTestContext;
}
interface RunDataSnapshot {
  getOutputs(nodeId: NodeId): NodeOutputs | undefined;
  getOutputItems<TJson = unknown>(nodeId: NodeId | NodeIdRef<TJson>, output?: OutputPortKey): Items<TJson>;
  getOutputItem<TJson = unknown>(nodeId: NodeId | NodeIdRef<TJson>, itemIndex: number, output?: OutputPortKey): Item<TJson> | undefined;
}
interface RunIdFactory {
  makeRunId(): RunId;
}
interface ActivationIdFactory {
  makeActivationId(): NodeActivationId;
}
/** Whether to persist run execution data after the workflow finishes. */
type WorkflowStoragePolicyMode = "ALL" | "SUCCESS" | "ERROR" | "NEVER";
type WorkflowStoragePolicySpec = WorkflowStoragePolicyMode | TypeToken<WorkflowStoragePolicyResolver>;
interface WorkflowStoragePolicyResolver {
  shouldPersist(args: WorkflowStoragePolicyDecisionArgs): boolean | Promise<boolean>;
}
interface WorkflowStoragePolicyDecisionArgs {
  readonly runId: RunId;
  readonly workflowId: WorkflowId;
  readonly workflow: WorkflowDefinition;
  readonly finalStatus: "completed" | "failed";
  readonly startedAt: string;
  readonly finishedAt: string;
}
interface WorkflowPrunePolicySpec {
  readonly runDataRetentionSeconds?: number;
  readonly binaryRetentionSeconds?: number;
  readonly telemetrySpanRetentionSeconds?: number;
  readonly telemetryArtifactRetentionSeconds?: number;
  readonly telemetryMetricRetentionSeconds?: number;
}
interface PersistedRunPolicySnapshot {
  readonly retentionSeconds?: number;
  readonly binaryRetentionSeconds?: number;
  readonly telemetrySpanRetentionSeconds?: number;
  readonly telemetryArtifactRetentionSeconds?: number;
  readonly telemetryMetricRetentionSeconds?: number;
  readonly storagePolicy: WorkflowStoragePolicyMode;
}
interface WorkflowErrorHandler {
  onError(ctx: WorkflowErrorContext): void | Promise<void>;
}
interface WorkflowErrorContext {
  readonly runId: RunId;
  readonly workflowId: WorkflowId;
  readonly workflow: WorkflowDefinition;
  readonly failedNodeId: NodeId;
  readonly error: Error;
  readonly startedAt: string;
  readonly finishedAt: string;
}
type WorkflowErrorHandlerSpec = TypeToken<WorkflowErrorHandler> | WorkflowErrorHandler;
interface NodeErrorHandlerArgs<TConfig extends NodeConfigBase = NodeConfigBase> {
  readonly kind: "single" | "multi";
  readonly items: Items;
  readonly inputsByPort: Readonly<Record<InputPortKey, Items>> | undefined;
  readonly ctx: NodeExecutionContext<TConfig>;
  readonly error: Error;
}
interface NodeErrorHandler {
  handle<TConfig extends NodeConfigBase>(args: NodeErrorHandlerArgs<TConfig>): Promise<NodeOutputs>;
}
type NodeErrorHandlerSpec = TypeToken<NodeErrorHandler> | NodeErrorHandler;
//#endregion
//#region ../core/src/contracts/runtimeTypes.d.ts
/** Opaque unique identifier for a single HumanTask instance. */
type HumanTaskId = string;
/**
 * Minimal handle handed to the `deliver` callback so it can route to the correct
 * inbox channel.
 */
interface HumanTaskHandle {
  readonly taskId: HumanTaskId;
  readonly runId: string;
  readonly nodeId: string;
  readonly expiresAt: Date;
  /** TODO: real signed URL; placeholder empty string for now. */
  readonly resumeUrl: string;
  /**
   * Arbitrary JSON metadata copied from `SuspensionRequest.request.metadata` at suspension time.
   * Used by the agent runtime to round-trip the `agentCheckpoint` back to the
   * resumed node via `ctx.resumeContext.task.metadata`.
   */
  readonly metadata?: Readonly<Record<string, JsonValue>>;
}
/** Identity of the person who made a decision on the task. */
interface HumanTaskActor {
  readonly actorId: string;
  readonly displayName?: string;
}
/**
 * Resume context injected into `NodeExecutionContext` when the engine re-activates
 * a previously suspended node. `defineHumanApprovalNode` wraps this with parsed
 * `TDecision`; at the engine layer `decision.value` is `unknown`.
 */
interface ResumeContext {
  readonly decision: Readonly<{
    kind: "decided";
    value: unknown;
    actor: HumanTaskActor;
    decidedAt: Date;
  }> | Readonly<{
    kind: "timed_out";
    at: Date;
  }> | Readonly<{
    kind: "auto_accepted";
    at: Date;
  }>;
  readonly delivery: JsonValue;
  readonly task: HumanTaskHandle;
}
interface WorkflowRepository {
  list(): ReadonlyArray<WorkflowDefinition>;
  get(workflowId: WorkflowId): WorkflowDefinition | undefined;
}
interface LiveWorkflowRepository extends WorkflowRepository {
  setWorkflows(workflows: ReadonlyArray<WorkflowDefinition>): void;
}
interface NodeExecutionStatePublisher {
  markQueued(args: {
    nodeId: NodeId;
    activationId?: NodeActivationId;
    inputsByPort?: NodeInputsByPort;
  }): Promise<void>;
  markRunning(args: {
    nodeId: NodeId;
    activationId?: NodeActivationId;
    inputsByPort?: NodeInputsByPort;
  }): Promise<void>;
  markCompleted(args: {
    nodeId: NodeId;
    activationId?: NodeActivationId;
    inputsByPort?: NodeInputsByPort;
    outputs?: NodeOutputs;
  }): Promise<void>;
  markFailed(args: {
    nodeId: NodeId;
    activationId?: NodeActivationId;
    inputsByPort?: NodeInputsByPort;
    error: Error;
  }): Promise<void>;
  appendConnectionInvocation(args: ConnectionInvocationAppendArgs): Promise<void>;
  /**
   * Annotates the current snapshot for `nodeId` with the id of the child run spawned by a
   * SubWorkflow invocation. Called from `SubWorkflowNode.execute` after `runById` resolves.
   * The engine's subsequent `markCompleted` call preserves the value via `previous.childRunId`.
   */
  setChildRunId?(args: {
    nodeId: NodeId;
    childRunId: RunId;
  }): Promise<void>;
}
type BinaryBody = ReadableStream<Uint8Array> | AsyncIterable<Uint8Array> | Uint8Array | ArrayBuffer;
interface BinaryStorageWriteRequest {
  storageKey: string;
  body: BinaryBody;
}
interface BinaryStorageWriteResult {
  storageKey: string;
  size: number;
  sha256?: string;
}
interface BinaryStorageReadResult {
  body: ReadableStream<Uint8Array>;
  size?: number;
}
interface BinaryStorageStatResult {
  exists: boolean;
  size?: number;
}
interface BinaryStorage {
  readonly driverName: string;
  write(args: BinaryStorageWriteRequest): Promise<BinaryStorageWriteResult>;
  openReadStream(storageKey: string): Promise<BinaryStorageReadResult | undefined>;
  stat(storageKey: string): Promise<BinaryStorageStatResult>;
  delete(storageKey: string): Promise<void>;
  /** Deletes multiple objects in bulk. Keys are batched internally. */
  deleteMany(storageKeys: ReadonlyArray<string>): Promise<void>;
  /** Lists all keys sharing a common prefix. Returns keys in arbitrary order. */
  listByPrefix(prefix: string): Promise<ReadonlyArray<string>>;
}
interface BinaryAttachmentCreateRequest {
  name: string;
  body: BinaryBody;
  mimeType: string;
  filename?: string;
  previewKind?: BinaryAttachment["previewKind"];
}
interface NodeBinaryAttachmentService extends ExecutionBinaryService {
  attach(args: BinaryAttachmentCreateRequest): Promise<BinaryAttachment>;
  withAttachment<TJson>(item: Item<TJson>, name: string, attachment: BinaryAttachment): Item<TJson>;
}
interface ExecutionBinaryService {
  forNode(args: {
    nodeId: NodeId;
    activationId: NodeActivationId;
  }): NodeBinaryAttachmentService;
  openReadStream(attachment: BinaryAttachment): Promise<BinaryStorageReadResult | undefined>;
}
interface ExecutionContext {
  runId: RunId;
  workflowId: WorkflowId;
  parent?: ParentExecutionRef;
  /** This run's subworkflow depth (0 = root). */
  subworkflowDepth: number;
  /** Effective activation budget cap for this run (after policy merge). */
  engineMaxNodeActivations: number;
  /** Effective subworkflow nesting cap for this run (after policy merge). */
  engineMaxSubworkflowDepth: number;
  now: () => Date;
  data: RunDataSnapshot;
  nodeState?: NodeExecutionStatePublisher;
  telemetry: ExecutionTelemetry;
  binary: ExecutionBinaryService;
  getCredential<TSession = unknown>(slotKey: string): Promise<TSession>;
  /** Per-item iteration id, set by {@link NodeExecutor} on the ctx passed into runnable `execute`. */
  iterationId?: NodeIterationId;
  /** Item index (0-based) within the current activation's batch; set alongside {@link iterationId}. */
  itemIndex?: number;
  /** When set, this ctx is executing inside a sub-agent triggered by the named parent invocation. */
  parentInvocationId?: ConnectionInvocationId;
  /**
   * Present iff the run was started by a TestSuiteOrchestrator. The {@link IsTestRunNode}
   * branches on this; assertion-emitting nodes use it to decide whether to record results.
   */
  testContext?: RunTestContext;
  /**
   * Collections registered in the codemation config, keyed by collection name.
   */
  readonly collections?: CollectionsContext;
  /**
   * Resolve a DI token from the host container.
   * Allows nodes to reach host-side services (e.g. `InboxChannelResolverToken`)
   * without importing host code. Wired by `DefaultExecutionContextFactory`; throws
   * a clear error when no resolver is configured (e.g. in unit tests that don't
   * set up the full container).
   */
  resolve<T>(token: TypeToken<T>): T;
}
interface NodeExecutionContext<TConfig extends NodeConfigBase = NodeConfigBase> extends ExecutionContext {
  nodeId: NodeId;
  activationId: NodeActivationId;
  config: TConfig;
  telemetry: NodeExecutionTelemetry;
  binary: NodeBinaryAttachmentService;
  /**
   * Present when this node activation is a HITL resume.
   * The node checks `ctx.resumeContext !== undefined` and takes the resume branch.
   */
  resumeContext?: ResumeContext;
}
interface NodeExecutionRequest {
  runId: RunId;
  activationId: NodeActivationId;
  workflowId: WorkflowId;
  nodeId: NodeId;
  input: Items;
  parent?: ParentExecutionRef;
  queue?: string;
  executionOptions?: RunExecutionOptions;
}
interface NodeExecutionScheduler {
  enqueue(request: NodeExecutionRequest): Promise<{
    receiptId: string;
  }>;
  cancel?(receiptId: string): Promise<void>;
}
interface NodeExecutionRequestHandler {
  handleNodeExecutionRequest(request: NodeExecutionRequest): Promise<void>;
}
interface NodeActivationContinuation {
  markNodeRunning(args: {
    runId: RunId;
    activationId: NodeActivationId;
    nodeId: NodeId;
    inputsByPort: NodeInputsByPort;
  }): Promise<void>;
  resumeFromNodeResult(args: {
    runId: RunId;
    activationId: NodeActivationId;
    nodeId: NodeId;
    outputs: NodeOutputs;
  }): Promise<RunResult>;
  resumeFromNodeError(args: {
    runId: RunId;
    activationId: NodeActivationId;
    nodeId: NodeId;
    error: Error;
  }): Promise<RunResult>;
}
interface WorkflowSnapshotResolver {
  resolve(args: {
    workflowId: WorkflowId;
    workflowSnapshot?: PersistedWorkflowSnapshot;
  }): WorkflowDefinition | undefined;
}
//#endregion
//#region ../core/src/ai/AiHost.d.ts
interface AgentCanvasPresentation<TIcon extends string = string> {
  readonly label?: string;
  readonly icon?: TIcon;
}
interface ToolConfig {
  readonly type: TypeToken<unknown>;
  readonly name: string;
  readonly description?: string;
  readonly presentation?: AgentCanvasPresentation;
  getCredentialRequirements?(): ReadonlyArray<CredentialRequirement>;
}
type AgentMessageRole = "system" | "user" | "assistant";
type AgentMessageBuildArgs<TInputJson$1 = unknown> = Readonly<{
  item: Item<TInputJson$1>;
  itemIndex: number;
  items: Items<TInputJson$1>;
  ctx: NodeExecutionContext<any>;
}>;
interface AgentMessageDto {
  readonly role: AgentMessageRole;
  readonly content: string;
}
type AgentMessageTemplateContent<TInputJson$1 = unknown> = string | ((args: AgentMessageBuildArgs<TInputJson$1>) => string);
interface AgentMessageTemplate<TInputJson$1 = unknown> {
  readonly role: AgentMessageRole;
  readonly content: AgentMessageTemplateContent<TInputJson$1>;
}
/** A single prompt line: fixed DTO or template with optional function `content`. */
type AgentMessageLine<TInputJson$1 = unknown> = AgentMessageDto | AgentMessageTemplate<TInputJson$1>;
/**
 * Message list for an agent. Prefer a **plain array** of `{ role, content }` (optionally with function `content` for templates).
 * Use the object form only when you need `buildMessages` to append messages after optional `prompt` lines.
 */
type AgentMessageConfig<TInputJson$1 = unknown> = Expr<ReadonlyArray<AgentMessageLine<TInputJson$1>>, TInputJson$1> | ReadonlyArray<AgentMessageLine<TInputJson$1>> | {
  readonly prompt?: ReadonlyArray<AgentMessageLine<TInputJson$1>>;
  readonly buildMessages?: (args: AgentMessageBuildArgs<TInputJson$1>) => ReadonlyArray<AgentMessageDto>;
};
type AgentTurnLimitBehavior = "error" | "respondWithLastMessage";
interface AgentModelInvocationOptions {
  readonly maxTokens?: number;
  readonly providerOptions?: Readonly<Record<string, JsonValue>>;
}
interface AgentGuardrailConfig {
  readonly maxTurns?: number;
  readonly onTurnLimitReached?: AgentTurnLimitBehavior;
  readonly modelInvocationOptions?: AgentModelInvocationOptions;
}
interface ChatModelConfig {
  readonly type: TypeToken<ChatModelFactory<ChatModelConfig>>;
  readonly name: string;
  readonly provider?: string;
  readonly modelName?: string;
  readonly presentation?: AgentCanvasPresentation;
  getCredentialRequirements?(): ReadonlyArray<CredentialRequirement>;
}
/**
 * Provider-neutral chat language model wrapper returned by a {@link ChatModelFactory}.
 *
 * Thin adapter around an AI SDK `LanguageModelV2` (from `@ai-sdk/provider`) plus the call-site
 * defaults Codemation needs at every generate/stream: the provider label, the model name used for
 * pricing / telemetry, and the default invocation options (max output tokens, temperature,
 * provider-specific overrides).
 *
 * The consumer (AIAgentNode / AgentStructuredOutputRunner) passes `languageModel` directly into
 * `generateText({ model, ... })` from the `ai` package.
 */
interface ChatLanguageModel {
  /** AI SDK `LanguageModelV2` instance (kept `unknown` to avoid leaking the SDK type into `@codemation/core`). */
  readonly languageModel: unknown;
  /** Stable pricing/telemetry key — e.g. `"gpt-4.1-nano"`. */
  readonly modelName: string;
  /** Provider label — e.g. `"openai"`. Used for cost tracking. */
  readonly provider?: string;
  /** Defaults merged into every call. Consumers may override per-invocation. */
  readonly defaultCallOptions?: ChatLanguageModelCallOptions;
}
interface ChatLanguageModelCallOptions {
  readonly maxOutputTokens?: number;
  readonly temperature?: number;
  readonly providerOptions?: Readonly<Record<string, Readonly<Record<string, JsonValue>>>>;
}
interface ChatModelFactory<TConfig extends ChatModelConfig = ChatModelConfig> {
  create(args: Readonly<{
    config: TConfig;
    ctx: NodeExecutionContext<any>;
  }>): Promise<ChatLanguageModel> | ChatLanguageModel;
}
//#endregion
export { DefinedNode as $, WorkflowDefinition as A, NodeId as At, RunStopCondition as B, NodeOutputs as C, WebhookTriggerMatcher as Ct, RunIdFactory as D, TelemetryAttributes as Dt, RunId as E, TelemetryArtifactAttachment as Et, RunCurrentState as F, TypeToken as G, WebhookRunResult as H, RunExecutionOptions as I, RunEventBus as J, EngineExecutionLimitsPolicyConfig as K, RunPruneCandidate as L, NodeInputsByPort as M, PersistedRunState as N, RunnableNodeConfig as O, TelemetryMetricRecord as Ot, PersistedWorkflowTokenRegistryLike as P, AnyRunnableNodeConfig as Q, RunResult as R, NodeInspectorSummaryRow as S, WebhookInvocationMatch as St, PersistedRunPolicySnapshot as T, WorkflowRunDetailDto as Tt, WorkflowExecutionRepository as U, RunSummary as V, Container as W, TestSuiteRunStatus as X, TestCaseRunStatus as Y, ChainCursor as Z, Item as _, CredentialType as _t, BinaryStorage as a, CredentialBindingKey as at, NodeActivationId as b, CredentialTypeRegistry as bt, NodeExecutionContext as c, CredentialInstanceId as ct, NodeExecutionScheduler as d, CredentialMaterialSourceKind as dt, DefinedNodeConfigInput as et, ResumeContext as f, CredentialOAuth2AuthDefinition as ft, BinaryAttachment as g, CredentialSetupStatus as gt, ActivationIdFactory as h, CredentialSessionService as ht, ToolConfig as i, CredentialBinding as it, CurrentStateExecutionRequest as j, WorkflowId as jt, RunnableNodeOutputJson as k, TelemetrySpanEventRecord as kt, NodeExecutionRequest as l, CredentialInstanceRecord as lt, WorkflowSnapshotResolver as m, CredentialSessionFactoryArgs as mt, AgentMessageConfig as n, McpServerDeclaration as nt, LiveWorkflowRepository as o, CredentialFieldSchema as ot, WorkflowRepository as p, CredentialRequirement as pt, RunEvent as q, ChatModelConfig as r, AnyCredentialType as rt, NodeActivationContinuation as s, CredentialHealth as st, AgentGuardrailConfig as t, WorkflowActivationPolicy as tt, NodeExecutionRequestHandler as u, CredentialJsonRecord as ut, Items as v, CredentialTypeDefinition as vt, ParentExecutionRef as w, WebhookTriggerResolution as wt, NodeDefinition as x, HttpMethod as xt, JsonValue as y, CredentialTypeId as yt, RunStatus as z };
//# sourceMappingURL=ItemsInputNormalizer-CFkfNMLt.d.ts.map