import { SQSEvent, Context } from 'aws-lambda'; import { ZodType } from 'zod'; import { R as RetryContext, S as SmartRetryConfig, Q as QueueStepOutput, b as ChainContext, H as HitlResumeContext, L as LoopContext } from './queue-B5n6YVQV.js'; export { B as BuiltInRetryPattern, C as CustomRetryPattern, a as RetryPattern } from './queue-B5n6YVQV.js'; import './hitlConfig.js'; /** * Token budget tracking for workers. * Workers report usage via ctx.reportTokenUsage(); the runtime accumulates * and throws TokenBudgetExceededError when the limit is reached. */ interface TokenUsage { inputTokens: number; outputTokens: number; } interface TokenBudgetState { inputTokens: number; outputTokens: number; /** null = no budget configured */ budget: number | null; } declare class TokenBudgetExceededError extends Error { readonly used: number; readonly budget: number; constructor(used: number, budget: number); } /** * Generic Lambda handler wrapper for worker agents. * Handles SQS events, executes user handlers, and sends webhook callbacks. * Job store: MongoDB only. Never uses HTTP/origin URL for job updates. */ interface JobStoreUpdate { status?: 'queued' | 'running' | 'completed' | 'failed'; metadata?: Record; progress?: number; progressMessage?: string; output?: any; error?: { message: string; stack?: string; name?: string; }; } interface JobRecord { jobId: string; workerId: string; status: 'queued' | 'running' | 'completed' | 'failed'; input: any; output?: any; error?: { message: string; stack?: string; }; metadata?: Record; internalJobs?: Array<{ jobId: string; workerId: string; awaited?: boolean; delaySeconds?: number; }>; userId?: string; createdAt: string; updatedAt: string; completedAt?: string; } interface JobStore { /** * Update job in job store. * @param update - Update object with status, metadata, progress, output, or error */ update(update: JobStoreUpdate): Promise; /** * Get current job record from job store. * @returns Job record or null if not found */ get(): Promise; /** * Append an internal (child) job to the current job's internalJobs list. * Used when this worker dispatches another worker. `awaited` records whether the parent * blocked on the child (dispatchWorker await:true) or fired it and moved on (await:false), * so observability can distinguish the two. */ appendInternalJob?(entry: { jobId: string; workerId: string; awaited?: boolean; delaySeconds?: number; }): Promise; /** * Get any job by jobId (e.g. to poll child job status when await: true). * @returns Job record or null if not found */ getJob?(jobId: string): Promise; } /** Max SQS delay in seconds (AWS limit). */ declare const SQS_MAX_DELAY_SECONDS = 900; /** Options for ctx.dispatchWorker (worker-to-worker). */ interface DispatchWorkerOptions { webhookUrl?: string; metadata?: Record; /** Optional job ID for the child job (default: generated). */ jobId?: string; /** If true, poll job store until child completes or fails; otherwise fire-and-forget. */ await?: boolean; pollIntervalMs?: number; pollTimeoutMs?: number; /** * Delay before the child is invoked (fire-and-forget only; ignored when await is true). * Uses SQS DelaySeconds (0–900). In local mode, waits this many seconds before sending the trigger request. */ delaySeconds?: number; } /** * Logger provided on ctx with prefixed levels: [INFO], [WARN], [ERROR], [DEBUG]. * Each method accepts a message and optional data (logged as JSON). */ interface WorkerLogger { info(message: string, data?: Record): void; warn(message: string, data?: Record): void; error(message: string, data?: Record): void; debug(message: string, data?: Record): void; } declare function createWorkerLogger(jobId: string, workerId: string): WorkerLogger; interface WorkerHandlerParams { input: INPUT; ctx: { jobId: string; workerId: string; requestId?: string; /** ID of the user who triggered this job. Pass via DispatchOptions.userId from your API route. */ userId?: string; /** * Job store interface for updating and retrieving job state. * Uses MongoDB directly when configured; never HTTP/origin URL. */ jobStore?: JobStore; /** * Logger with prefixed levels: ctx.logger.info(), .warn(), .error(), .debug(). */ logger: WorkerLogger; /** * Dispatch another worker (fire-and-forget or await). Uses WORKER_QUEUE_URL_ env. * Always provided by the runtime (Lambda and local). */ dispatchWorker: (workerId: string, input: unknown, options?: DispatchWorkerOptions) => Promise<{ jobId: string; messageId?: string; output?: unknown; }>; /** * Report token usage after an LLM call. Accumulates across all calls in this job. * Throws TokenBudgetExceededError if the configured maxTokens budget is exceeded. * Also persists usage to the job store for observability. * * @example * ```ts * const result = await anthropic.messages.create({ ... }); * await ctx.reportTokenUsage({ * inputTokens: result.usage.input_tokens, * outputTokens: result.usage.output_tokens, * }); * ``` */ reportTokenUsage: (usage: TokenUsage) => Promise; /** * Get the current token usage and remaining budget for this job. * Returns `{ used, budget: null, remaining: null }` when no maxTokens was set. */ getTokenBudget: () => { used: number; budget: number | null; remaining: number | null; }; /** * Populated on retry attempts (attempt >= 2). Contains info about the previous failure * so the handler can self-correct (e.g. inject the error message into the next prompt). * `undefined` on the first attempt — use `if (ctx.retryContext)` to detect retries. */ retryContext?: RetryContext; [key: string]: any; }; } type WorkerHandler = (params: WorkerHandlerParams) => Promise; /** Result of getNextStep for queue chaining. */ interface QueueNextStep { workerId: string; delaySeconds?: number; requiresApproval?: boolean; /** Whether this step has a `chain` function (or built-in string) defined. */ hasChain?: boolean; /** Whether this step has a `resume` function defined. */ hasResume?: boolean; /** Optional HITL metadata from queue step config (UI/tooling only). */ hitl?: { ui?: unknown; } | unknown; /** Smart retry config for this step. Overrides worker-level retry for this step only. */ retry?: SmartRetryConfig; } /** * @deprecated Use {@link ChainContext} for the normal chain path and * {@link HitlResumeContext} for the HITL resume path instead. * Kept for backwards compatibility with queue files written against the old API. */ interface MapStepInputContext { initialInput: unknown; previousOutputs: QueueStepOutput[]; /** @deprecated Use HitlResumeContext.reviewerInput instead. */ hitlInput?: unknown; /** @deprecated Use HitlResumeContext.pendingInput instead. */ pendingStepInput?: Record; } /** Runtime helpers for queue-aware wrappers (provided by generated registry). */ interface QueueRuntime { getNextStep(queueId: string, stepIndex: number): QueueNextStep | undefined; /** Step config at `stepIndex`. */ getStepAt?(queueId: string, stepIndex: number): QueueNextStep | undefined; /** Optional: when provided, mappers can use outputs from any previous step. */ getQueueJob?(queueJobId: string): Promise<{ steps: Array<{ workerId: string; output?: unknown; }>; } | null>; /** * Build the input for a step when the queue advances normally (no HITL resume). * Calls the step's `chain` function, or the built-in passthrough/continueFromPrevious. */ invokeChain?(queueId: string, stepIndex: number, ctx: ChainContext): Promise | unknown; /** * Build the domain input for a step when it resumes after HITL approval. * Calls the step's `resume` function, or merges pendingInput + reviewerInput by default. */ invokeResume?(queueId: string, stepIndex: number, ctx: HitlResumeContext): Promise | unknown; /** * Evaluate whether a looping step should run again. * Calls the step's `loop.shouldContinue` function. Returns false if none defined. */ invokeLoop?(queueId: string, stepIndex: number, ctx: LoopContext): Promise | boolean; } /** * Wraps a user handler so that when the job has `__workerQueue` context (from * `dispatchQueue` or queue cron), it dispatches the next worker in the sequence * **after** the handler completes. * * All queue/HITL envelope keys (`__workerQueue`, `__hitlInput`, `__hitlDecision`, * `__hitlPending`, `hitl`) are **stripped from `params.input` before the user handler * runs** — workers receive clean domain input and do not need to accept these keys * in their Zod schemas. * * **HITL resume:** When `__hitlInput` is present, `invokeResume` is called first to * produce the merged domain input. **Chain advancement:** After a step completes, * `invokeChain` is called to compute the next step's input. */ declare function wrapHandlerForQueue(handler: WorkerHandler, queueRuntime: QueueRuntime): WorkerHandler; interface SQSMessageBody { workerId: string; jobId: string; input: any; context: Record; webhookUrl?: string; /** @deprecated Never use. Job updates use MongoDB only. */ jobStoreUrl?: string; metadata?: Record; timestamp: string; /** ID of the user who triggered this job. Forwarded from dispatch options. */ userId?: string; /** Maximum total tokens (input + output) for this job. Forwarded from DispatchOptions.maxTokens. */ maxTokens?: number; } interface WebhookPayload { jobId: string; workerId: string; status: 'success' | 'error'; output?: any; error?: { message: string; stack?: string; name?: string; }; metadata?: Record; } /** Job store backend selected by WORKER_DATABASE_TYPE. 'local' must be set explicitly (dev server); it is never a fallback. */ type JobStoreKind = 'mongodb' | 'upstash-redis' | 'local'; declare function getJobStoreKind(): JobStoreKind; /** * Load any job record via the configured store. Selection mirrors createLambdaHandler: * explicit 'local' > redis (when selected AND configured) > mongo (when selected OR configured). */ declare function loadJobRecordById(jobId: string): Promise; /** * Creates a Lambda handler function that processes SQS events for workers. * Job store: MongoDB only. Never uses HTTP/origin URL for job updates. * * @param handler - The user's worker handler function * @param outputSchema - Optional Zod schema for output validation * @returns A Lambda handler function */ declare function createLambdaHandler(handler: WorkerHandler, outputSchema?: ZodType, options?: { retry?: SmartRetryConfig; }): (event: SQSEvent, context: Context) => Promise; export { ChainContext, type DispatchWorkerOptions, HitlResumeContext, type JobRecord, type JobStore, type JobStoreKind, type JobStoreUpdate, LoopContext, type MapStepInputContext, type QueueNextStep, type QueueRuntime, QueueStepOutput, RetryContext, type SQSMessageBody, SQS_MAX_DELAY_SECONDS, SmartRetryConfig, TokenBudgetExceededError, type TokenBudgetState, type TokenUsage, type WebhookPayload, type WorkerHandler, type WorkerHandlerParams, type WorkerLogger, createLambdaHandler, createWorkerLogger, getJobStoreKind, loadJobRecordById, wrapHandlerForQueue };