import { type Encodable, type ObjectProducingSchema, type ProducingSchema, type StructuralSensitivityMask } from "@automate.ax/codec"; import { automationInvocationInputSchema, automationInvocationOutputSchema, type ActionReplaySafety, type EvaluationInput, type EvaluationResult, type GenerationResult, type PlatformImageGenerationInput, type PlatformWebScrapeInput, type RuntimeGenerationInput } from "@automate.ax/api-contract/runtime"; import type { StandardSchemaV1 } from "@standard-schema/spec"; import type { RequireAtLeastOne } from "type-fest"; import * as z from "zod"; import { EMAIL_ORIGIN_TOKEN } from "../lib/email-origin.js"; import { type ActionAccountConnectionRequirements, type ActionAccountOption, type AccountAuthorizationAction, type IntegrationAccountReference, type IntegrationScopeRequirement, type ResolvedIntegrationAccount } from "./integrations.js"; import { signalValueType, type Signal } from "./signal-protocol.js"; declare const DEFAULT_ACTION_INPUT_SCHEMA: StandardSchemaV1>; declare const DEFAULT_ACTION_OUTPUT_SCHEMA: StandardSchemaV1; type ActionInputSignal = Signal & { readonly [signalValueType]: () => T; }; type JsonValue = StandardSchemaV1.InferOutput>; type DeepJsonActionInput = ActionInputSignal | boolean | null | number | string | DeepJsonActionInput[] | { [key: string]: DeepJsonActionInput; }; type DeepEncodableActionInput = ActionInputSignal | Encodable | DeepEncodableActionInput[] | readonly DeepEncodableActionInput[] | { readonly [key: string]: DeepEncodableActionInput; }; /** Object types kept atomic during deep action input traversal. */ type AtomicActionInput = ((...arguments_: never[]) => unknown) | ArrayBuffer | ArrayBufferView | Blob | Date | File | Headers | Map | RegExp | Request | Response | Set | URL | URLSearchParams; type ActionAccountOptionServiceId = TOption extends string ? TOption : TOption extends { serviceId: infer TServiceId extends string; } ? TServiceId : never; type HasMultipleAccountOptions = TOptions extends readonly [ActionAccountOption] ? false : true; /** One durable structured log written by an action handler. */ export interface ActionLogInput { /** * Structured values available to local SQL queries. Keys allow 128 * characters. */ fields?: Record; /** Severity used to filter the entry. */ level: "debug" | "info" | "warn" | "error"; /** Human-readable message, limited to 16,384 characters. */ message: string; /** Explicit policy for message and structured field values. */ sensitive?: StructuralSensitivityMask<{ fields?: Record; message: string; }>; } /** * Action-only platform capabilities available to handlers. * * These methods perform platform-managed effects without exposing credentials * or execution infrastructure to the action. */ export interface ActionRuntime { /** Internal signed provenance for email-sending actions. */ readonly [EMAIL_ORIGIN_TOKEN]?: string; /** Automation currently executing this action. */ readonly automationId: string; /** Durable context currently executing this action. */ readonly contextId: string; /** * Protects an HTTP callback endpoint with a signed, expiring capability. * * The endpoint must come from `onHttpRequest({ protection: "callback" })` in * the same automation. Each valid delivery still starts an independent root * context. */ createCallbackUrl(endpoint: string): Promise; /** * Evaluates typed questions through the platform AI Gateway. * * @param input - Shared state, questions, model, and evaluation settings. */ evaluate(input: EvaluationInput): Promise; /** * Generates text or structured data through the platform AI Gateway. * * @param input - Model, prompt, generation settings, and optional JSON * Schema. */ generate(input: RuntimeGenerationInput): Promise; /** * Queues image generation through the platform AI Gateway. * * @param input - Completion entrypoint and image-generation settings. */ startImageGeneration(input: PlatformImageGenerationInput): Promise<{ key: string; }>; /** Queues a scrape through the platform Browser Run account. */ startWebScrape(input: PlatformWebScrapeInput): Promise<{ key: string; }>; /** * Accepts an immediate or delayed invocation from the current action. * * @param input - Target automation, payload, and optional delivery timing. */ invokeAutomation(input: StandardSchemaV1.InferOutput): Promise>; /** * Persists one structured log entry with action-attempt provenance. * * Each action invocation can write at most 1,000 log entries. Field maps * accept codec values and are limited to 64 entries and 64 KiB encoded. * * @param input - Structured level, message, and optional fields. */ log(input: ActionLogInput): Promise; /** * Emits a typed value from the current action execution. * * @param output - Value and application-defined type used to classify it. * @param output.data - Encodable payload to emit. * @param output.type - Application-defined output type. */ sendOutput(output: { /** Encodable payload to emit. */ data: TData; /** Application-defined output type. */ type: string; }, options?: { /** Explicit policy for the emitted data value. */ sensitive: StructuralSensitivityMask; }): Promise; /** * Sends an email through the platform. * * Resolves with Resend's internal email resource ID when available. This is * not the RFC 5322 Message-ID used for email threading. To reply to a * received mailhook message, use its `messageId` for `In-Reply-To`. Build * `References` from its `references`, or its `inReplyTo` when references are * empty, followed by its `messageId`. * * @param input - Email fields. * @param input.attachments - Files attached to the message. * @param input.headers - Custom email headers. * @param input.html - HTML message body. * @param input.markdown - Markdown message body. * @param input.replyTo - Address that should receive replies. * @param input.subject - Email subject line. * @param input.text - Plain-text message body. * @param input.to - Recipient email address, or `"*"` for all organization * members. */ sendEmail(input: { /** Files attached to the message. */ attachments?: File[]; /** Custom email headers. */ headers?: Record; /** Address that should receive replies. */ replyTo?: string; /** Email subject line. */ subject: string; /** Recipient email address, or `"*"` for all organization members. */ to: string; } & RequireAtLeastOne<{ /** HTML message body. */ html?: string; /** Markdown message body. */ markdown?: string; /** Plain-text message body. */ text?: string; }>): Promise<{ /** * Resend internal email resource ID, or `null` when unavailable. This is * not an RFC 5322 Message-ID and is not a valid threading target. */ id: string | null; }>; } /** Optional diagnostics shared by explicit action-control failures. */ export interface ActionFailureOptions { /** Stable provider or application classification. */ code?: string; /** Original failure retained by normalized causal diagnostics. */ cause?: unknown; /** Structured author-safe provider details. */ details?: JsonValue; } /** * Marks an existing provider error as safe to retry without changing identity. * * @param error - Provider error to classify. * @param options - Optional provider-directed retry timing. * @param options.retryAt - Absolute earliest time for the next attempt. */ export declare function retryableActionError(error: TError, options?: { retryAt?: Date; }): TError; /** * Marks an existing provider error as terminal without changing identity. * * @param error - Provider error to classify. */ export declare function terminalActionError(error: TError): TError; /** * Marks an existing provider error as ambiguous without changing identity. * * @param error - Provider error to classify. */ export declare function indeterminateActionError(error: TError): TError; /** A failure known to be permanent for the current action input. */ export declare class TerminalActionError extends Error { readonly code?: string; readonly details?: JsonValue; name: string; /** * Creates a permanent action failure. * * @param message - Author-safe failure message. * @param options - Optional diagnostic classification and cause. */ constructor(message: string, options?: ActionFailureOptions); } /** A failure whose provider effect cannot be determined safely. */ export declare class IndeterminateActionError extends Error { readonly code?: string; readonly details?: JsonValue; name: string; /** * Creates a failure whose provider outcome cannot be determined. * * @param message - Author-safe failure message. * @param options - Optional diagnostic classification and cause. */ constructor(message: string, options?: ActionFailureOptions); } /** A failure known to permit a fresh logical action attempt. */ export declare class RetryableActionError extends Error { readonly code?: string; readonly details?: JsonValue; name: string; readonly retryAt?: Date; /** * Creates a failure that permits a fresh logical attempt. * * @param message - Author-safe failure message. * @param options - Optional diagnostic classification, cause, and timing. */ constructor(message: string, options?: ActionFailureOptions & { retryAt?: Date; }); } /** * Parses provider `Retry-After` seconds or an HTTP date into an absolute time. * Malformed and past hints are ignored so platform backoff remains in force. * * @param value - Raw provider header. * @param now - Current time, injectable for deterministic provider tests. */ export declare function parseRetryAfter(value: string | null | undefined, now?: Date): Date | undefined; /** Static retry bound and replay decision for one action definition. */ export interface ActionRetryPolicy { /** Maximum logical attempts, including the first. Defaults to three. */ maxAttempts?: number; /** Constant or validated-input-dependent ambiguous replay safety. */ replaySafety: ActionReplaySafety | ((input: TInput) => ActionReplaySafety | Promise); } /** * Implements an action after its input and account selection are materialized. * * The handler receives schema-validated input and, for account-backed actions, * the resolved account secret. Its result is subsequently validated by the * action's output schema. * * @template TInputSchema - Schema used to validate materialized action input. * @template TOutputSchema - Schema used to validate the handler result. * @template TAccountServiceId - Required integration service, or `never` when * the action does not use an account. */ export type ActionHandler = ObjectProducingSchema, TOutputSchema extends ProducingSchema = ProducingSchema, TAccountServiceId extends string = never, TDefaultAccount = never> = (options: { /** Parsed input produced by the action's input schema. */ input: StandardSchemaV1.InferOutput; /** Platform-managed capabilities available during execution. */ runtime: ActionRuntime; } & ([TAccountServiceId] extends [never] ? object : { /** * Resolved credentials for the integration service required by the * action. */ account: ResolvedIntegrationAccount | TDefaultAccount; })) => Promise> | StandardSchemaV1.InferInput; /** Display metadata attached to a defined action. */ export interface ActionMetadata { /** Optional explanation of what the action does. */ readonly description?: string; /** Human-readable action name. */ readonly name: string; } /** * Fluent definition state for an action. * * The generic state records the configured schemas and account requirement so * the final handler and callable action remain fully inferred. * * @template TInputSchema - Currently configured input schema. * @template TOutputSchema - Currently configured output schema. * @template TAccountServiceId - Required integration service, or `never` for an * action without an account requirement. */ export interface ActionBuilder = typeof DEFAULT_ACTION_INPUT_SCHEMA, TOutputSchema extends ProducingSchema = typeof DEFAULT_ACTION_OUTPUT_SCHEMA, TAccountServiceId extends string = never, TMultipleAccountServices extends boolean = false, TDefaultAccount = never> { /** * Requires an integration account when planning and executing the action. * * @template TNextAccountServiceId - Integration service required by the * resulting builder. * @param serviceId - Stable identifier of the required integration service. * @param requirement - Provider scope required through any connection, or * connection-specific alternatives. */ account(serviceId: TNextAccountServiceId, requirement?: ActionAccountConnectionRequirements | IntegrationScopeRequirement): ActionBuilder; /** * Requires an account for one of several alternative integration services. * * @template TOptions - Non-empty alternative service declaration tuple. * @param options - Service identifiers or service-specific scope objects. */ account(options: TOptions): ActionBuilder, HasMultipleAccountOptions>; /** * Requires one of several integration services while using a custom value * when the caller omits `account`. * * The default does not create a deployment account requirement. It is passed * directly to the action handler so platform-backed actions can branch away * from user-managed credentials. * * @template TOptions - Non-empty alternative service declaration tuple. * @template TNextDefaultAccount - Handler value used for omitted accounts. * @param options - Service identifiers or service-specific scope objects. * @param configuration - Omitted-account behavior. * @param configuration.default - Value passed to the action handler. */ account(options: TOptions, configuration: { default: TNextDefaultAccount; }): ActionBuilder, HasMultipleAccountOptions, TNextDefaultAccount>; /** * Adds a human-readable description to action metadata. * * @param description - Explanation shown to users and planning tools. */ describe(description: string): ActionBuilder; /** * Sets the schema used to validate materialized action input. * * @template TNextInputSchema - Input schema stored by the resulting builder. * @param schema - Standard Schema-compatible schema producing an object. */ input>(schema: TNextInputSchema): ActionBuilder; /** * Sets the schema used to validate the action handler's result. * * @template TNextOutputSchema - Output schema stored by the resulting * builder. * @param schema - Standard Schema-compatible output schema. * @param options - Optional explicit sensitivity policy for the result. * @param options.sensitive - Whole-value or structural policy to persist. */ output>(schema: TNextOutputSchema, options?: { sensitive: StructuralSensitivityMask>; }): ActionBuilder; /** * Declares the logical retry bound and ambiguous replay safety. * * The replay decision runs only after input validation and before the action * handler. Every action must declare this policy before `.handler()`. * * @param policy - Static attempt bound and constant or input-dependent * safety. */ retry(policy: ActionRetryPolicy>): ActionBuilder; /** * Completes the definition with its execution implementation. * * @param handler - Implementation invoked with validated input and runtime * capabilities. */ handler(handler: ActionHandler): DefinedAction; } /** * Object shape accepted from callers before action input is parsed. * * Schemas with an object-shaped declared input preserve that input type so * coercions and transforms remain callable. Schemas whose declared input is * broader use their known object output shape instead. * * @template TInputSchema - Object-producing action input schema. */ export type ActionSchemaInput> = StandardSchemaV1.InferInput extends Record ? StandardSchemaV1.InferInput : StandardSchemaV1.InferOutput; /** * Recursively signal-backed values accepted when invoking an action. * * A signal may supply the complete input, an object or array subtree, or one * leaf. Arrays and plain objects are traversed; other object types stay * atomic. * * @template T - Input value that may be supplied directly or by signal. */ export type DeepActionInput = ActionInputSignal | (0 extends 1 & T ? T : [T] extends [JsonValue] ? [JsonValue] extends [T] ? DeepJsonActionInput : DeepStructuredActionInput : [T] extends [Encodable] ? [Encodable] extends [T] ? DeepEncodableActionInput : DeepStructuredActionInput : DeepStructuredActionInput); type DeepStructuredActionInput = T extends AtomicActionInput ? T : T extends readonly unknown[] ? { [TKey in keyof T]: DeepActionInput; } : T extends object ? { [TKey in keyof T]: DeepActionInput; } : T; /** * Object form of an action input with signals accepted at every nested node. * Object union members remain distinct through the recursive transformation. */ export type ActionObjectInput> = DeepStructuredActionInput>; /** Whole-value or recursively signal-backed input accepted by an action. */ export type ActionCallInput> = ActionInputSignal> | ActionObjectInput; /** Whether the schema accepts an action invocation with no input properties. */ type AllowsEmptyActionInput> = Record extends StandardSchemaV1.InferInput ? true : false; /** Input tuple with omission allowed when the schema accepts an empty object. */ type ActionInputArguments, TRequired extends boolean> = AllowsEmptyActionInput extends true ? TRequired extends true ? [input: ActionCallInput | undefined] : [input?: ActionCallInput] : [input: ActionCallInput]; /** * Account selection added to account-backed action calls. * * Single-service actions accept an optional binding name, typed account * reference, or signal resolving to either. Multi-service actions require a * typed account reference so the provider is known before authorization. * * @template TAccountServiceId - Required integration service. */ type ActionAccountSelection = TMultipleAccountServices extends true ? IntegrationAccountReference : string | IntegrationAccountReference | ActionInputSignal>; type ActionAccountCallOptions = TMultipleAccountServices extends true ? [TDefaultAccount] extends [never] ? { /** Typed account reference that selects one allowed service. */ account: ActionAccountSelection; } : { /** Typed account reference, or omission for the action's custom default. */ account?: ActionAccountSelection; } : { /** Project account binding to use for this invocation. */ account?: ActionAccountSelection; }; /** Conditional invocation tuple that enforces account-selection requirements. */ type ActionInvocationArguments, TAccountServiceId extends string, TMultipleAccountServices extends boolean, TDefaultAccount> = [TAccountServiceId] extends [never] ? ActionInputArguments : TMultipleAccountServices extends true ? [TDefaultAccount] extends [never] ? [ ...ActionInputArguments, options: ActionAccountCallOptions ] : [ ...ActionInputArguments, options?: ActionAccountCallOptions ] : [ ...ActionInputArguments, options?: ActionAccountCallOptions ]; /** Action callable returned after binding an account selection. */ type AccountBoundAction, TOutputSchema extends ProducingSchema> = (...arguments_: ActionInputArguments) => Signal>; interface ActionAccountBinding, TOutputSchema extends ProducingSchema, TAccountServiceId extends string, TMultipleAccountServices extends boolean> { /** Creates an immutable action callable bound to one account selection. */ usingAccount(account: ActionAccountSelection): AccountBoundAction; } /** * Callable action produced by a completed action definition. * * Calling it registers an invocation and returns a signal for the eventual * validated output. Account-backed actions also carry their authorization * requirement for planning. * * @template TInputSchema - Schema governing invocation input. * @template TOutputSchema - Schema governing the resulting signal value. * @template TAccountServiceId - Required integration service, or `never` for * accountless actions. */ export type DefinedAction = ObjectProducingSchema, TOutputSchema extends ProducingSchema = ProducingSchema, TAccountServiceId extends string = never, TMultipleAccountServices extends boolean = false, TDefaultAccount = never> = { /** * Registers an invocation and exposes its eventual output. * * @param arguments_ - Signal-capable input followed by optional account * selection options. */ (...arguments_: ActionInvocationArguments): Signal>; /** Display metadata configured while defining the action. */ readonly meta: ActionMetadata; } & ([TAccountServiceId] extends [never] ? object : AccountAuthorizationAction & ActionAccountBinding); /** * Starts a fluent action definition. * * @param name - Human-readable action name. */ export declare function defineAction(name: string): ActionBuilder; /** * Creates a string signal by interpolating in-memory values and signals. * * @param strings - Static portions of the tagged template. * @param values - Dynamic values interleaved between static portions. * @throws {TypeError} When no interpolated value is a signal. */ export declare function t(strings: TemplateStringsArray, ...values: unknown[]): Signal; export {}; //# sourceMappingURL=actions.d.ts.map