/** * LangGraph adapter — interrupt/resume durable HITL. * * Two halves, deployed in two different processes (or two paths inside * one process): * * 1. **Inside a graph node** — call `awaitHuman(...)` from this * module. We POST the task to the awaithumans server, then call * `interrupt(...)` from `@langchain/langgraph`. The graph throws * a `GraphInterrupt`; the caller (your application) catches that * at the `graph.invoke()` boundary, persists nothing of its own * (LangGraph's checkpointer already saved state), and returns to * its event loop. The process can crash and the state survives. * * 2. **Inside the user's web server** — `createLangGraphCallbackHandler` * returns a framework-agnostic handler. It verifies the HMAC, * extracts the thread id from the request URL (which the * workflow encoded into `callbackUrl` when it called awaitHuman), * and re-invokes the graph with `new Command({resume})`. The * replayed `interrupt(...)` returns the response and the node * continues like nothing happened. * * Mirrors `awaithumans.adapters.langgraph` (Python). Wire format * matches the Temporal adapter so a single awaithumans server can * back any mix of frameworks. * * @example Graph-side * ```ts * import { awaitHuman } from "awaithumans/langgraph"; * import { z } from "zod"; * * async function approveNode(state: RefundState, config: RunnableConfig) { * const decision = await awaitHuman({ * task: "Approve refund?", * payloadSchema: z.object({ amount: z.number() }), * payload: { amount: state.amount }, * responseSchema: z.object({ approved: z.boolean() }), * timeoutMs: 15 * 60 * 1000, * callbackUrl: * "https://my-app.com/awaithumans/cb?thread=" + * config.configurable!.thread_id, * serverUrl: "http://localhost:3001", * apiKey: process.env.AWAITHUMANS_ADMIN_API_TOKEN, * }); * return { decision: decision.approved }; * } * ``` * * @example Callback-side (in your web server) * ```ts * import { Hono } from "hono"; * import { createLangGraphCallbackHandler } from "awaithumans/langgraph"; * * const app = new Hono(); * const handle = createLangGraphCallbackHandler({ * graph, * payloadKey: process.env.AWAITHUMANS_PAYLOAD_KEY!, * }); * * app.post("/awaithumans/cb", async (c) => { * const thread = c.req.query("thread"); * if (!thread) return c.text("missing thread", 400); * const body = await c.req.arrayBuffer(); * const sig = c.req.header("x-awaithumans-signature"); * const status = await handle({ threadId: thread, body, signatureHeader: sig }); * return c.text(status === 200 ? "ok" : "bad", status); * }); * ``` * * Requires: * npm install @langchain/langgraph * (peer dependency — declared as optional in this SDK so the base * install doesn't pull LangGraph in for users who don't need it.) */ import type { AwaitHumanOptions } from "../../types/index.js"; export interface AwaitHumanLangGraphOptions extends AwaitHumanOptions { /** * Where the awaithumans server should POST the completion webhook. * Encode the LangGraph thread id in this URL so the callback * handler can resume the right graph instance: * `https://my-app.com/awaithumans/cb?thread=${threadId}` */ callbackUrl: string; /** * Base URL of the awaithumans server. In dev: `http://localhost:3001`. * Required because nodes can't reach for env vars in a sandboxed * runtime — pass via your graph state, your runnable config, or * read once at module load. */ serverUrl: string; /** Bearer token for `serverUrl`. Same value the direct-mode SDK reads. */ apiKey?: string; } export interface AwaitHumanInterrupt { taskId: string; idempotencyKey: string; task: string; payload: unknown; callbackUrl: string; } export interface CompletionResume { task_id?: string; idempotency_key?: string; status?: string; response?: unknown; completed_at?: string | null; timed_out_at?: string | null; completed_by_email?: string | null; completed_via_channel?: string | null; verification_attempt?: number; } /** * Awaitable: pause the running graph until a human completes the task. * See module docstring for the architecture. * * @throws TaskCreateError if the awaithumans server rejects the create call. * @throws TaskTimeoutError if the server reports `timed_out` on resume. * @throws TaskCancelledError if the server reports `cancelled` on resume. * @throws VerificationExhaustedError if the verifier rejected every attempt. * @throws SchemaValidationError if the human's response doesn't match `responseSchema`. */ export declare function awaitHuman(options: AwaitHumanLangGraphOptions): Promise; /** * Minimal interface satisfied by `CompiledStateGraph` from * `@langchain/langgraph`. Typed structurally so the SDK doesn't pull * the heavy class for users who only call awaitHuman from a node and * never wire up the callback handler — and so tests can pass a fake. */ export interface LangGraphInvokable { invoke(input: unknown, config?: { configurable?: Record; } & Record): Promise; } /** * Minimal interface for the `Command` constructor we accept. Same * reason as above — structural so callers can pass either the real * `Command` from `@langchain/langgraph` or a wrapper. */ export interface CommandConstructorLike { new (params: { resume: unknown; }): unknown; } export interface CallbackHandlerOptions { /** * The compiled graph that runs your application. The handler * `invoke`s it once per webhook to resume the paused thread. */ graph: LangGraphInvokable; /** * The `Command` class from `@langchain/langgraph`. Pass it in * directly (`Command`) — we accept it as a parameter so the SDK * itself doesn't need to import the runtime symbol; that import * happens inside YOUR app, in YOUR module-resolution tree, which * sidesteps the dual-package hazard the Temporal adapter ran into. */ command: CommandConstructorLike; /** * The HMAC key the awaithumans server signs webhooks with. Read * from `AWAITHUMANS_PAYLOAD_KEY` on the server side; receivers * MUST have the same value. The server uses HKDF-SHA256 with * salt `b"awaithumans-webhook-v1"` and info `b"v1"` over this * key to derive the actual signing key — we mirror that derivation * below. */ payloadKey: string; } export interface HandleCallbackInput { /** The LangGraph thread id to resume. Read from a query param. */ threadId: string; /** 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; } export interface HandleCallbackResult { /** HTTP-status-shaped outcome — let the caller wire it to their framework. */ status: number; error?: string; } /** * Build a framework-agnostic webhook handler closed over your graph. * Wrap the returned function in a Hono / Express / Fastify route. * * The handler: * 1. Verifies the HMAC signature against `payloadKey`. Bad sig → 401. * 2. Parses the body. Bad JSON → 400. * 3. Calls `graph.invoke(new Command({resume: }), {configurable:{thread_id}})`. * 4. Returns 200 on success. Any thrown error → 500. * * We pass the FULL webhook body as the resume value (not just * `response`) so the node can branch on `status` and surface the * right typed error for timed-out / cancelled / verification-exhausted. */ export declare function createLangGraphCallbackHandler(options: CallbackHandlerOptions): (input: HandleCallbackInput) => 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; //# sourceMappingURL=index.d.ts.map