/** * Temporal adapter — signal-based durable HITL. * * Two halves, deployed in two different processes: * * 1. **Inside a Temporal workflow** — call `awaitHuman(...)` from * this module. We register a signal handler scoped to the task's * idempotency key, fire an activity that POSTs the task to the * awaithumans server, then `workflow.condition()` blocks on * either the signal arriving OR a workflow timer — both cost * zero compute under Temporal's "park the workflow" model. * * 2. **Inside the user's web server** — `dispatchSignal(...)` is * the framework-agnostic helper they wrap in a route. It * verifies the HMAC, parses the body, and signals the workflow * back to life. * * Mirrors `awaithumans.adapters.temporal` (Python). Wire format and * signal-name derivation are identical so a TypeScript workflow can * hand off a webhook to a Python receiver and vice versa. * * @example Workflow-side * ```ts * import { awaitHuman } from "awaithumans/temporal"; * import { z } from "zod"; * * export async function refundWorkflow(amount: number) { * const decision = await awaitHuman({ * task: "Approve refund?", * payloadSchema: z.object({ amount: z.number() }), * payload: { amount }, * responseSchema: z.object({ approved: z.boolean() }), * timeoutMs: 15 * 60 * 1000, * callbackUrl: "https://my-app.com/awaithumans/cb?wf=" + workflowInfo().workflowId, * serverUrl: "http://localhost:3001", * apiKey: process.env.AWAITHUMANS_ADMIN_API_TOKEN, * }); * return decision.approved; * } * ``` * * @example Callback-side (in your web server, NOT the workflow) * ```ts * import { Connection, Client } from "@temporalio/client"; * import { dispatchSignal } from "awaithumans/temporal"; * * const client = new Client({ connection: await Connection.connect() }); * * app.post("/awaithumans/cb", async (req, res) => { * const wf = req.query.wf as string; * try { * await dispatchSignal({ * temporalClient: client, * workflowId: wf, * body: req.rawBody, // raw bytes, not parsed * signatureHeader: req.header("x-awaithumans-signature"), * }); * res.sendStatus(200); * } catch (e) { * if (e instanceof Error && e.message.includes("signature")) res.sendStatus(401); * else res.sendStatus(400); * } * }); * ``` * * Requires: * npm install @temporalio/workflow @temporalio/client * (peer dependencies — declared as optional in this SDK so the * base install doesn't pull in Temporal for users who don't need * it.) */ import type { AwaitHumanOptions } from "../../types/index.js"; export interface AwaitHumanTemporalOptions extends AwaitHumanOptions { /** * URL where the awaithumans server should POST the completion * webhook. The user's web server must host the callback receiver * at this URL — see `dispatchSignal()` and the FastAPI/Express * snippet in `examples/temporal/`. */ callbackUrl: string; /** * Base URL of the awaithumans server (the human-facing one). * In dev: `http://localhost:3001`. Required because workflows * can't read environment variables directly — pass via input * args or a config object. */ serverUrl: string; /** Bearer token for `serverUrl`. Same value the direct-mode SDK reads. */ apiKey?: string; /** Per-attempt timeout for the create-task activity. Default: 30s. */ createActivityTimeoutMs?: number; } interface CreateTaskActivityInput { serverUrl: string; apiKey: string | undefined; body: Record; } interface CreateTaskActivityResult { id: string; idempotencyKey: string; status: string; response: unknown | null; completedAt: string | null; timedOutAt: string | null; verificationAttempt: number; } /** * Awaitable: suspend the running Temporal workflow until a human * completes the task. See module docstring for the architecture. * * @throws TaskTimeoutError if `timeoutMs` elapses with no completion. * @throws TaskCancelledError if the task was cancelled (server side). * @throws VerificationExhaustedError if the verifier rejected every attempt. * @throws SchemaValidationError if the human's response doesn't match `responseSchema`. */ export declare function awaitHuman(options: AwaitHumanTemporalOptions): Promise; /** * The activity that POSTs the task to the awaithumans server. * * Register this on your Temporal worker alongside any of your own * activities: * * ```ts * import { Worker } from "@temporalio/worker"; * import { awaithumansCreateTask } from "awaithumans/temporal"; * * const worker = await Worker.create({ * workflowsPath: require.resolve("./workflows"), * activities: { ...myActivities, awaithumansCreateTask }, * taskQueue: "my-q", * }); * ``` * * Activities run OUTSIDE the workflow sandbox — `fetch` and the * Node stdlib are available here. Temporal's automatic retries * cover transient server failures. */ export declare function awaithumansCreateTask(input: CreateTaskActivityInput): Promise; /** * Minimal interface satisfied by `Client` from `@temporalio/client`. * Typed as a structural interface so this module doesn't need to * import the heavy class — keeps `dispatchSignal` testable with a * fake. */ export interface TemporalClientLike { getHandle(workflowId: string): { signal(name: string, arg: unknown): Promise; }; } export interface DispatchSignalOptions { /** Connected `@temporalio/client` Client. */ temporalClient: TemporalClientLike; /** * The workflow ID to signal. Read from the request URL — typically * a query param (`?wf=...`) the workflow encoded into * `callbackUrl` when it called `awaitHuman`. */ workflowId: string; /** The raw request body bytes — needed for HMAC verification. */ body: ArrayBuffer | Uint8Array | string; /** The `X-Awaithumans-Signature` header value (or null/undefined). */ signatureHeader: string | null | undefined; /** * The HMAC key used to verify the signature. Must match * AWAITHUMANS_PAYLOAD_KEY on the awaithumans server (which * derives the webhook key from it via HKDF). Most users read * this from `process.env.AWAITHUMANS_PAYLOAD_KEY`. * * Cross-language note: the Python server uses HKDF with salt * `b"awaithumans-webhook-v1"` and info `b"v1"` over PAYLOAD_KEY * to derive the actual signing key. To verify here, do the same * HKDF-SHA256 on the Node side; helpers below. */ payloadKey: string; } /** * Verify a webhook signature and signal the matching workflow. * * Wraps a few lines of route boilerplate so the user's web server * stays small. See module docstring for the Express snippet. Throws: * * - `Error("Invalid awaithumans webhook signature.")` — wrap to 401 * - `Error("Webhook body is not JSON: ...")` — wrap to 400 * - `Error("Webhook missing idempotency_key: ...")` — wrap to 400 */ export declare function dispatchSignal(options: DispatchSignalOptions): Promise; /** * Compute the `sha256=` signature over `body`. Public so users * who want to drive the dispatch loop themselves can verify the * same way the SDK helper does. */ export declare function signBody(body: Uint8Array, payloadKey: string): Promise; export {}; //# sourceMappingURL=index.d.ts.map