import * as aws_lambda from 'aws-lambda'; import { DispatchOptions, DispatchResult } from './client.mjs'; export { DispatchQueueResult, SerializedContext, WorkerQueueRegistry, deriveWorkersApiKey, dispatch, dispatchLocal, dispatchQueue, dispatchWorker, getQueueStartUrl, getWorkersTriggerUrl, resolveWorkersConfigKey, resolveWorkersTriggerKey } from './client.mjs'; import { SQSMessageBody, JobRecord, JobStore, WorkerHandler } from './handler.mjs'; export { DispatchWorkerOptions, JobStoreKind, JobStoreUpdate, MapStepInputContext, QueueNextStep, QueueRuntime, SQS_MAX_DELAY_SECONDS, TokenBudgetExceededError, TokenBudgetState, TokenUsage, WebhookPayload, WorkerHandlerParams, WorkerLogger, createLambdaHandler, createWorkerLogger, getJobStoreKind, loadJobRecordById, wrapHandlerForQueue } from './handler.mjs'; import { S as SmartRetryConfig } from './queue-DaR2UuZi.mjs'; export { B as BuiltInRetryPattern, b as ChainContext, C as CustomRetryPattern, H as HitlResumeContext, L as LoopContext, c as QUEUE_ORCHESTRATION_KEYS, Q as QueueStepOutput, R as RetryContext, a as RetryPattern, d as WorkerQueueConfig, e as WorkerQueueContext, W as WorkerQueueStep, f as defineWorkerQueue, g as executeWithRetry, m as matchesRetryPattern, r as repeatStep } from './queue-DaR2UuZi.mjs'; import { ZodType, z } from 'zod'; export { WorkersConfig, clearWorkersConfigCache, getWorkersConfig, resolveQueueUrl } from './config.mjs'; export { QueueOrchestrationFields, queueOrchestrationFieldsSchema, withQueueOrchestrationEnvelope } from './queueInputEnvelope.mjs'; export { defaultMapChainContinueFromPrevious, defaultMapChainPassthrough } from './chainMapDefaults.mjs'; export { HitlStepConfig, HitlUiSpec, defineHitlConfig } from './hitlConfig.mjs'; /** * Local dispatch bridge — the seam the `ai-worker dev` server uses to intercept * worker-to-worker dispatch (and queue next-step sends) instead of SQS. * * Production safety: the bridge is only honored when BOTH conditions hold — * `process.env.AI_WORKER_LOCAL === '1'` AND a bridge object was installed on * `globalThis`. Nothing in a deployed Lambda sets either, so this path is * impossible to trip in production and adds zero dependencies. */ interface LocalDispatchBridge { /** * Hand a would-be SQS message to the local dev queue. * `delaySeconds` mirrors SQS DelaySeconds semantics (already clamped to 0–900 by the caller). * Must return a message id (used in place of the SQS MessageId). */ enqueue(workerId: string, messageBody: SQSMessageBody, delaySeconds?: number): Promise<{ messageId: string; }> | { messageId: string; }; } /** Install the bridge (called by the dev server before any worker code runs). */ declare function setLocalDispatchBridge(bridge: LocalDispatchBridge | undefined): void; /** * Returns the installed bridge, or undefined unless BOTH the env flag and the * global are set (see module doc). Checked on every dispatch — cheap (two lookups). */ declare function getLocalDispatchBridge(): LocalDispatchBridge | undefined; /** * Local job store (`WORKER_DATABASE_TYPE=local`) — in-memory Maps with debounced * JSON persistence, standing in for Upstash/Mongo when running `ai-worker dev`. * * Never a fallback: this store is only used when WORKER_DATABASE_TYPE is * explicitly 'local' (the dev server sets it; compile never writes it into a * deployed env.json unless the user set it themselves). * * State lives on `globalThis`, not module scope: tsup bundles each package * entry (index / handler / queueJobStore) separately, so module-level Maps * would be duplicated per bundle and the dev server would read different * state than the runtime writes. The global anchor makes every copy share * one store (same trick as the local dispatch bridge). */ /** Mirrors the queue job doc shape used by the redis/mongo queue stores. */ interface LocalQueueJobStep { workerId: string; workerJobId: string; status: 'queued' | 'running' | 'awaiting_approval' | 'completed' | 'failed'; input?: unknown; output?: unknown; error?: { message: string; }; startedAt?: string; completedAt?: string; } interface LocalQueueJobRecord { id: string; queueId: string; status: 'running' | 'completed' | 'failed' | 'partial'; steps: LocalQueueJobStep[]; metadata?: Record; userId?: string; createdAt: string; updatedAt: string; completedAt?: string; } declare function isLocalJobStoreEnabled(): boolean; /** Synchronously write pending state to disk (dev server calls this on shutdown). */ declare function flushLocalJobStore(): void; declare function loadLocalJob(jobId: string): Promise; declare function upsertLocalJob(jobId: string, workerId: string, input: any, metadata: Record, userId?: string): Promise; declare function createLocalJobStore(workerId: string, jobId: string, input: any, metadata: Record, userId?: string): JobStore; /** All job records (dev server observability route). */ declare function listLocalJobs(): JobRecord[]; /** Jobs for one worker, newest first (dev server /dev-store API). */ declare function listLocalJobsByWorker(workerId: string): JobRecord[]; /** * Shallow-merge a partial job record (upsert). Serves the dev server's * /dev-store API, which the app boilerplate's `local` adapter writes through * (setJob/updateJob) so console/webhook updates land in the same store the * workers use. */ declare function patchLocalJob(jobId: string, partial: Partial): Promise; /** Standalone appendInternalJob (dev server /dev-store API). */ declare function appendLocalInternalJob(parentJobId: string, entry: { jobId: string; workerId: string; awaited?: boolean; delaySeconds?: number; }): Promise; /** * Shallow-merge a partial queue job record (upsert). `steps`, when provided, * replaces the whole array — step-level merging is done by the dev server * route so this store stays a dumb record holder. */ declare function patchLocalQueueJob(queueJobId: string, partial: Partial): Promise; declare function upsertInitialLocalQueueJob(options: { queueJobId: string; queueId: string; firstWorkerId: string; firstWorkerJobId: string; metadata?: Record; userId?: string; }): Promise; declare function updateLocalQueueJobStep(options: { queueJobId: string; stepIndex: number; workerId: string; workerJobId: string; status: 'running' | 'awaiting_approval' | 'completed' | 'failed'; input?: unknown; output?: unknown; error?: { message: string; }; }): Promise; declare function appendLocalQueueJobStep(options: { queueJobId: string; workerId: string; workerJobId: string; }): Promise; declare function getLocalQueueJob(queueJobId: string): Promise; /** All queue job docs (dev server observability route). */ declare function listLocalQueueJobs(): LocalQueueJobRecord[]; /** * Schedule event configuration for a worker. * Supports both simple rate/cron strings and full configuration objects. * * @example Simple rate/cron * ```typescript * schedule: 'rate(2 hours)' * // or * schedule: 'cron(0 12 * * ? *)' * ``` * * @example Full configuration * ```typescript * schedule: { * rate: 'rate(10 minutes)', * enabled: true, * input: { key1: 'value1' } * } * ``` * * @example Multiple schedules * ```typescript * schedule: [ * 'rate(2 hours)', * { rate: 'cron(0 12 * * ? *)', enabled: false } * ] * ``` */ interface ScheduleEventConfig { /** * Schedule rate using either rate() or cron() syntax. * Can be a string or array of strings for multiple schedules. * * @example 'rate(2 hours)' or 'cron(0 12 * * ? *)' * @example ['cron(0 0/4 ? * MON-FRI *)', 'cron(0 2 ? * SAT-SUN *)'] */ rate: string | string[]; /** * Whether the schedule is enabled (default: true). */ enabled?: boolean; /** * Input payload to pass to the function. */ input?: Record; /** * JSONPath expression to select part of the event data as input. */ inputPath?: string; /** * Input transformer configuration for custom input mapping. */ inputTransformer?: { inputPathsMap?: Record; inputTemplate?: string; }; /** * Name of the schedule event. */ name?: string; /** * Description of the schedule event. */ description?: string; /** * Method to use: 'eventBus' (default) or 'scheduler'. * Use 'scheduler' for higher limits (1M events vs 300). */ method?: 'eventBus' | 'scheduler'; /** * Timezone for the schedule (only used with method: 'scheduler'). * @example 'America/New_York' */ timezone?: string; } type ScheduleConfig = string | ScheduleEventConfig | (string | ScheduleEventConfig)[]; /** * Configuration for a worker's Lambda function deployment. * * **Best Practice**: Export this as a separate const from your worker file: * ```typescript * export const workerConfig: WorkerConfig = { * timeout: 900, * memorySize: 2048, * layers: ['arn:aws:lambda:${aws:region}:${aws:accountId}:layer:ffmpeg:1'], * schedule: 'rate(2 hours)', * }; * ``` * * The CLI will automatically extract it from the export. You do not need to pass it to `createWorker()`. */ interface WorkerConfig { /** * Lambda function timeout in seconds (max 900). */ timeout?: number; /** * Lambda function memory size in MB (128-10240). */ memorySize?: number; /** * Optional Lambda layers ARNs to attach to this worker function. * * This is primarily used by @microfox/ai-worker-cli when generating serverless.yml. * Supports CloudFormation pseudo-parameters like ${aws:region} and ${aws:accountId}. * * Example: * layers: ['arn:aws:lambda:${aws:region}:${aws:accountId}:layer:ffmpeg:1'] */ layers?: string[]; /** * Schedule events configuration for this worker. * Allows multiple schedule events to be attached to the same function. * * @example Simple rate * ```typescript * schedule: 'rate(2 hours)' * ``` * * @example Multiple schedules * ```typescript * schedule: [ * 'rate(2 hours)', * { rate: 'cron(0 12 * * ? *)', enabled: true, input: { key: 'value' } } * ] * ``` * * @example Using scheduler method with timezone * ```typescript * schedule: { * method: 'scheduler', * rate: 'cron(0 0/4 ? * MON-FRI *)', * timezone: 'America/New_York', * input: { key1: 'value1' } * } * ``` */ schedule?: ScheduleConfig; /** * If set, this worker is deployed to the serverless project for this group. * Do not use 'core' (reserved). Max 12 characters (serverless service name limits). */ group?: string; /** * SQS queue settings for this worker (used by @microfox/ai-worker-cli when generating serverless.yml). * * Notes: * - To effectively disable retries, set `maxReceiveCount: 1` (requires DLQ; the CLI will create one). * - SQS does not support `maxReceiveCount: 0`. * - `messageRetentionPeriod` is in seconds (max 1209600 = 14 days). */ sqs?: { /** * How many receives before sending to DLQ. * Use 1 to avoid retries. */ maxReceiveCount?: number; /** * How long messages are retained in the main queue (seconds). */ messageRetentionPeriod?: number; /** * Visibility timeout for the main queue (seconds). * If not set, CLI defaults to (worker timeout + 60s). */ visibilityTimeout?: number; /** * DLQ message retention period (seconds). * Defaults to `messageRetentionPeriod` (or 14 days). */ deadLetterMessageRetentionPeriod?: number; }; } interface WorkerAgentConfig, OUTPUT> { id: string; inputSchema: INPUT_SCHEMA; outputSchema: ZodType; handler: WorkerHandler, OUTPUT>; /** * Smart retry configuration for this worker. * Applies whenever this worker runs (Lambda or local mode). * Can be overridden per queue step via WorkerQueueStep.retry. * Retries are in-process so ctx.retryContext is populated on each retry attempt. * * @example * ```ts * retry: { maxAttempts: 3, on: ['rate-limit', 'json-parse'] } * ``` */ retry?: SmartRetryConfig; /** * @deprecated Prefer exporting `workerConfig` as a separate const from your worker file. * The CLI will automatically extract it from the export. This parameter is kept for backward compatibility. */ workerConfig?: WorkerConfig; } interface WorkerAgent, OUTPUT> { id: string; dispatch: (input: z.input, options: DispatchOptions) => Promise; handler: WorkerHandler, OUTPUT>; inputSchema: INPUT_SCHEMA; outputSchema: ZodType; workerConfig?: WorkerConfig; /** Smart retry config set on this worker via createWorker({ retry }). */ retry?: SmartRetryConfig; } /** * Creates a worker agent that can be dispatched to SQS/Lambda. * * In development mode (NODE_ENV === 'development' and WORKERS_LOCAL_MODE !== 'false'), * dispatch() will run the handler immediately in the same process. * * In production, dispatch() sends a message to SQS which triggers a Lambda function. * * @template INPUT_SCHEMA - The Zod schema type (e.g., `typeof InputSchema`). * Used to derive both: * - Pre-parse input type via `z.input` for `dispatch()` (preserves optional fields) * - Parsed input type via `z.infer` for handler (defaults applied) * @template OUTPUT - The output type returned by the handler. Use `z.infer`. * * @param config - Worker agent configuration * @returns A worker agent object with a dispatch method * * @example * ```typescript * const InputSchema = z.object({ * url: z.string().url(), * timeout: z.number().optional().default(5000), // optional with default * }); * * export const worker = createWorker({ * // dispatch() accepts { url: string, timeout?: number } (pre-parse, optional preserved) * // handler receives { url: string, timeout: number } (parsed, default applied) * }); * ``` */ declare function createWorker, OUTPUT>(config: WorkerAgentConfig): WorkerAgent; /** * Creates a Lambda handler entrypoint for a worker agent. * This is used by the deployment script to generate Lambda entrypoints. * * @param agent - The worker agent * @returns A Lambda handler function */ declare function createLambdaEntrypoint, OUTPUT>(agent: WorkerAgent): (event: aws_lambda.SQSEvent, context: aws_lambda.Context) => Promise; export { DispatchOptions, DispatchResult, JobRecord, JobStore, type LocalDispatchBridge, type LocalQueueJobRecord, type LocalQueueJobStep, SQSMessageBody, type ScheduleConfig, type ScheduleEventConfig, SmartRetryConfig, type WorkerAgent, type WorkerAgentConfig, type WorkerConfig, WorkerHandler, appendLocalInternalJob, appendLocalQueueJobStep, createLambdaEntrypoint, createLocalJobStore, createWorker, flushLocalJobStore, getLocalDispatchBridge, getLocalQueueJob, isLocalJobStoreEnabled, listLocalJobs, listLocalJobsByWorker, listLocalQueueJobs, loadLocalJob, patchLocalJob, patchLocalQueueJob, setLocalDispatchBridge, updateLocalQueueJobStep, upsertInitialLocalQueueJob, upsertLocalJob };