langchain 1.5.15 → 1.5.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/agents/ReactAgent.cjs +1 -1
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +1 -2
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +1 -2
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +2 -2
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/constants.d.cts +2 -3
- package/dist/agents/constants.d.cts.map +1 -1
- package/dist/agents/constants.d.ts +2 -3
- package/dist/agents/constants.d.ts.map +1 -1
- package/dist/agents/errors.d.cts +5 -6
- package/dist/agents/errors.d.cts.map +1 -1
- package/dist/agents/errors.d.ts +5 -6
- package/dist/agents/errors.d.ts.map +1 -1
- package/dist/agents/index.d.cts +14 -14
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +14 -14
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.cts +5 -6
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.ts +5 -6
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -3
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -3
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.cjs +24 -8
- package/dist/agents/middleware/hitl.cjs.map +1 -1
- package/dist/agents/middleware/hitl.d.cts +40 -30
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts +40 -30
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.js +24 -8
- package/dist/agents/middleware/hitl.js.map +1 -1
- package/dist/agents/middleware/index.d.cts +2 -2
- package/dist/agents/middleware/index.d.ts +2 -2
- package/dist/agents/middleware/llmToolSelector.d.cts +3 -4
- package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.ts +3 -4
- package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.cts +2 -3
- package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.ts +2 -3
- package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/modelFallback.d.cts +1 -2
- package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
- package/dist/agents/middleware/modelFallback.d.ts +1 -2
- package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
- package/dist/agents/middleware/modelRetry.d.cts +3 -4
- package/dist/agents/middleware/modelRetry.d.cts.map +1 -1
- package/dist/agents/middleware/modelRetry.d.ts +3 -4
- package/dist/agents/middleware/modelRetry.d.ts.map +1 -1
- package/dist/agents/middleware/pii.d.cts +17 -18
- package/dist/agents/middleware/pii.d.cts.map +1 -1
- package/dist/agents/middleware/pii.d.ts +17 -18
- package/dist/agents/middleware/pii.d.ts.map +1 -1
- package/dist/agents/middleware/piiRedaction.d.cts +2 -3
- package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
- package/dist/agents/middleware/piiRedaction.d.ts +2 -3
- package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +2 -3
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +2 -3
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
- package/dist/agents/middleware/provider/aws/promptCaching.d.cts +2 -3
- package/dist/agents/middleware/provider/aws/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/provider/aws/promptCaching.d.ts +2 -3
- package/dist/agents/middleware/provider/aws/promptCaching.d.ts.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.d.cts +2 -3
- package/dist/agents/middleware/provider/openai/moderation.d.cts.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.d.ts +2 -3
- package/dist/agents/middleware/provider/openai/moderation.d.ts.map +1 -1
- package/dist/agents/middleware/providerToolSearch.d.cts +3 -4
- package/dist/agents/middleware/providerToolSearch.d.cts.map +1 -1
- package/dist/agents/middleware/providerToolSearch.d.ts +3 -4
- package/dist/agents/middleware/providerToolSearch.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +7 -8
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +7 -8
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts +4 -5
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.ts +4 -5
- package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts +4 -5
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts +4 -5
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/toolEmulator.d.cts +2 -3
- package/dist/agents/middleware/toolEmulator.d.cts.map +1 -1
- package/dist/agents/middleware/toolEmulator.d.ts +2 -3
- package/dist/agents/middleware/toolEmulator.d.ts.map +1 -1
- package/dist/agents/middleware/toolError.d.cts +3 -4
- package/dist/agents/middleware/toolError.d.cts.map +1 -1
- package/dist/agents/middleware/toolError.d.ts +3 -4
- package/dist/agents/middleware/toolError.d.ts.map +1 -1
- package/dist/agents/middleware/toolRetry.d.cts +3 -4
- package/dist/agents/middleware/toolRetry.d.cts.map +1 -1
- package/dist/agents/middleware/toolRetry.d.ts +3 -4
- package/dist/agents/middleware/toolRetry.d.ts.map +1 -1
- package/dist/agents/middleware/types.d.cts +42 -43
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +42 -43
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/utils.d.cts +1 -2
- package/dist/agents/middleware/utils.d.cts.map +1 -1
- package/dist/agents/middleware/utils.d.ts +1 -2
- package/dist/agents/middleware/utils.d.ts.map +1 -1
- package/dist/agents/middleware.d.cts +1 -2
- package/dist/agents/middleware.d.cts.map +1 -1
- package/dist/agents/middleware.d.ts +1 -2
- package/dist/agents/middleware.d.ts.map +1 -1
- package/dist/agents/model.d.cts +1 -2
- package/dist/agents/model.d.cts.map +1 -1
- package/dist/agents/model.d.ts +1 -2
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/nodes/types.d.cts +1 -2
- package/dist/agents/nodes/types.d.cts.map +1 -1
- package/dist/agents/nodes/types.d.ts +1 -2
- package/dist/agents/nodes/types.d.ts.map +1 -1
- package/dist/agents/responses.d.cts +18 -19
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +18 -19
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/runtime.d.cts +6 -6
- package/dist/agents/runtime.d.cts.map +1 -1
- package/dist/agents/runtime.d.ts +6 -6
- package/dist/agents/runtime.d.ts.map +1 -1
- package/dist/agents/tests/utils.d.cts +1 -2
- package/dist/agents/tests/utils.d.cts.map +1 -1
- package/dist/agents/tests/utils.d.ts +1 -2
- package/dist/agents/tests/utils.d.ts.map +1 -1
- package/dist/agents/transformers/subagent.d.cts +1 -2
- package/dist/agents/transformers/subagent.d.cts.map +1 -1
- package/dist/agents/transformers/subagent.d.ts +1 -2
- package/dist/agents/transformers/subagent.d.ts.map +1 -1
- package/dist/agents/transformers/tool-call.d.cts +1 -2
- package/dist/agents/transformers/tool-call.d.cts.map +1 -1
- package/dist/agents/transformers/tool-call.d.ts +1 -2
- package/dist/agents/transformers/tool-call.d.ts.map +1 -1
- package/dist/agents/transformers/types.d.cts +4 -5
- package/dist/agents/transformers/types.d.cts.map +1 -1
- package/dist/agents/transformers/types.d.ts +4 -5
- package/dist/agents/transformers/types.d.ts.map +1 -1
- package/dist/agents/types.d.cts +30 -30
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +30 -30
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/browser.d.cts +2 -2
- package/dist/browser.d.ts +2 -2
- package/dist/chat_models/universal.d.cts +11 -12
- package/dist/chat_models/universal.d.cts.map +1 -1
- package/dist/chat_models/universal.d.ts +11 -12
- package/dist/chat_models/universal.d.ts.map +1 -1
- package/dist/hub/base.d.cts +1 -2
- package/dist/hub/base.d.cts.map +1 -1
- package/dist/hub/base.d.ts +1 -2
- package/dist/hub/base.d.ts.map +1 -1
- package/dist/hub/index.d.cts +2 -2
- package/dist/hub/index.d.cts.map +1 -1
- package/dist/hub/index.d.ts +2 -2
- package/dist/hub/index.d.ts.map +1 -1
- package/dist/hub/node.d.cts +3 -3
- package/dist/hub/node.d.cts.map +1 -1
- package/dist/hub/node.d.ts +3 -3
- package/dist/hub/node.d.ts.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/load/import_type.d.cts +1 -2
- package/dist/load/import_type.d.cts.map +1 -1
- package/dist/load/import_type.d.ts +1 -2
- package/dist/load/import_type.d.ts.map +1 -1
- package/dist/load/index.d.cts +1 -2
- package/dist/load/index.d.cts.map +1 -1
- package/dist/load/index.d.ts +1 -2
- package/dist/load/index.d.ts.map +1 -1
- package/dist/storage/encoder_backed.d.cts +2 -3
- package/dist/storage/encoder_backed.d.cts.map +1 -1
- package/dist/storage/encoder_backed.d.ts +2 -3
- package/dist/storage/encoder_backed.d.ts.map +1 -1
- package/dist/storage/file_system.d.cts +1 -2
- package/dist/storage/file_system.d.cts.map +1 -1
- package/dist/storage/file_system.d.ts +1 -2
- package/dist/storage/file_system.d.ts.map +1 -1
- package/dist/tools/headless.d.cts +4 -4
- package/dist/tools/headless.d.cts.map +1 -1
- package/dist/tools/headless.d.ts +4 -4
- package/dist/tools/headless.d.ts.map +1 -1
- package/package.json +19 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.cjs","names":["z","ToolMessage","createMiddleware","interopParse","AIMessage","interrupt"],"sources":["../../../src/agents/middleware/hitl.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v3\";\nimport { AIMessage, ToolMessage, ToolCall } from \"@langchain/core/messages\";\nimport {\n InferInteropZodInput,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport { interrupt } from \"@langchain/langgraph\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { ToolCallRequest } from \"./types.js\";\n\nconst WhenFunctionSchema = z\n .function()\n .args(z.custom<ToolCallRequest<AgentBuiltInState>>()) // request\n .returns(z.union([z.boolean(), z.promise(z.boolean())]));\n\n/**\n * Predicate controlling whether a given tool call triggers an interrupt.\n *\n * Receives a {@link ToolCallRequest} and returns `true` to interrupt or `false`\n * to auto-approve the tool call.\n *\n * The request is constructed with `tool` set to `undefined` and `runtime` set to\n * the node-level {@link Runtime}, so it reflects the batch (`afterModel`) context\n * rather than a per-call tool execution.\n *\n * @param request - The tool call request being evaluated\n * @returns `true` to interrupt for the tool call, `false` to auto-approve it.\n * May also return a promise resolving to a boolean.\n *\n * @example\n * ```typescript\n * import { type WhenPredicate } from \"langchain\";\n *\n * // Only interrupt delete_file calls targeting /etc\n * const when: WhenPredicate = (request) =>\n * String(request.toolCall.args.path ?? \"\").startsWith(\"/etc\");\n * ```\n */\nexport type WhenPredicate = z.infer<typeof WhenFunctionSchema>;\n\nconst DescriptionFunctionSchema = z\n .function()\n .args(\n z.custom<ToolCall>(), // toolCall\n z.custom<AgentBuiltInState>(), // state\n z.custom<Runtime<unknown>>() // runtime\n )\n .returns(z.union([z.string(), z.promise(z.string())]));\n\n/**\n * Function type that dynamically generates a description for a tool call approval request.\n *\n * @param toolCall - The tool call being reviewed\n * @param state - The current agent state\n * @param runtime - The agent runtime context\n * @returns A string description or Promise that resolves to a string description\n *\n * @example\n * ```typescript\n * import { type DescriptionFactory, type ToolCall } from \"langchain\";\n *\n * const descriptionFactory: DescriptionFactory = (toolCall, state, runtime) => {\n * return `Please review: ${toolCall.name}(${JSON.stringify(toolCall.args)})`;\n * };\n * ```\n */\nexport type DescriptionFactory = z.infer<typeof DescriptionFunctionSchema>;\n\n/**\n * The type of decision a human can make.\n */\nconst ALLOWED_DECISIONS = [\"approve\", \"edit\", \"reject\"] as const;\nconst DecisionType = z.enum(ALLOWED_DECISIONS);\nexport type DecisionType = z.infer<typeof DecisionType>;\n\nconst InterruptOnConfigSchema = z.object({\n /**\n * The decisions that are allowed for this action.\n */\n allowedDecisions: z.array(DecisionType),\n /**\n * The description attached to the request for human input.\n * Can be either:\n * - A static string describing the approval request\n * - A callable that dynamically generates the description based on agent state,\n * runtime, and tool call information\n *\n * @example\n * Static string description\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"Please review this tool execution\"\n * };\n * ```\n *\n * @example\n * Dynamic callable description\n * ```typescript\n * import type {\n * AgentBuiltInState,\n * Runtime,\n * DescriptionFactory,\n * ToolCall,\n * InterruptOnConfig\n * } from \"langchain\";\n *\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: formatToolDescription\n * };\n * ```\n */\n description: z.union([z.string(), DescriptionFunctionSchema]).optional(),\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema: z.record(z.any()).optional(),\n /**\n * Optional predicate controlling whether to interrupt for a given tool call.\n *\n * Receives a {@link ToolCallRequest} and returns `true` to interrupt or\n * `false` to auto-approve the tool call.\n *\n * The request is constructed with `tool` set to `undefined` and `runtime` set\n * to the node-level {@link Runtime}, so `request.tool` is not available.\n *\n * @example\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * // Only interrupt delete_file calls targeting /etc\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * when: (request) =>\n * String(request.toolCall.args.path ?? \"\").startsWith(\"/etc\"),\n * };\n * ```\n */\n when: WhenFunctionSchema.optional(),\n});\nexport type InterruptOnConfig = z.input<typeof InterruptOnConfigSchema>;\n\n/**\n * Represents an action with a name and arguments.\n */\nexport interface Action {\n /**\n * The type or name of action being requested (e.g., \"add_numbers\").\n */\n name: string;\n /**\n * Key-value pairs of arguments needed for the action (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n}\n\n/**\n * Represents an action request with a name, arguments, and description.\n */\nexport interface ActionRequest {\n /**\n * The name of the action being requested.\n */\n name: string;\n /**\n * Key-value pairs of arguments needed for the action (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n /**\n * The description of the action to be reviewed.\n */\n description?: string;\n}\n\n/**\n * Policy for reviewing a HITL request.\n */\nexport interface ReviewConfig {\n /**\n * Name of the action associated with this review configuration.\n */\n actionName: string;\n /**\n * The decisions that are allowed for this request.\n */\n allowedDecisions: DecisionType[];\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema?: Record<string, any>;\n}\n\n/**\n * Request for human feedback on a sequence of actions requested by a model.\n *\n * @example\n * ```ts\n * const hitlRequest: HITLRequest = {\n * actionRequests: [\n * { name: \"send_email\", args: { to: \"user@example.com\", subject: \"Hello\" } }\n * ],\n * reviewConfigs: [\n * {\n * actionName: \"send_email\",\n * allowedDecisions: [\"approve\", \"edit\", \"reject\"],\n * description: \"Please review the email before sending\"\n * }\n * ]\n * };\n * const response = interrupt(hitlRequest);\n * ```\n */\nexport interface HITLRequest {\n /**\n * A list of agent actions for human review.\n */\n actionRequests: ActionRequest[];\n /**\n * Review configuration for all possible actions.\n */\n reviewConfigs: ReviewConfig[];\n}\n\n/**\n * Response when a human approves the action.\n */\nexport interface ApproveDecision {\n type: \"approve\";\n}\n\n/**\n * Response when a human edits the action.\n */\nexport interface EditDecision {\n type: \"edit\";\n /**\n * Edited action for the agent to perform.\n * Ex: for a tool call, a human reviewer can edit the tool name and args.\n */\n editedAction: Action;\n}\n\n/**\n * Response when a human rejects the action.\n */\nexport interface RejectDecision {\n type: \"reject\";\n /**\n * The message sent to the model explaining why the action was rejected.\n */\n message?: string;\n}\n\n/**\n * Union of all possible decision types.\n */\nexport type Decision = ApproveDecision | EditDecision | RejectDecision;\n\n/**\n * Response payload for a HITLRequest.\n */\nexport interface HITLResponse {\n /**\n * The decisions made by the human.\n */\n decisions: Decision[];\n}\n\nconst contextSchema = z.object({\n /**\n * Mapping of tool name to allowed reviewer responses.\n * If a tool doesn't have an entry, it's auto-approved by default.\n *\n * - `true` -> pause for approval and allow approve/edit/reject decisions\n * - `false` -> auto-approve (no human review)\n * - `InterruptOnConfig` -> explicitly specify which decisions are allowed for this tool\n */\n interruptOn: z\n .record(z.union([z.boolean(), InterruptOnConfigSchema]))\n .optional(),\n /**\n * Prefix used when constructing human-facing approval messages.\n * Provides context about the tool call being reviewed; does not change the underlying action.\n *\n * Note: This prefix is only applied for tools that do not provide a custom\n * `description` via their {@link InterruptOnConfig}. If a tool specifies a custom\n * `description`, that per-tool text is used and this prefix is ignored.\n */\n descriptionPrefix: z.string().default(\"Tool execution requires approval\"),\n});\nexport type HumanInTheLoopMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * A invocation result that has been interrupted by the middleware will have a `__interrupt__`\n * property that contains the interrupt request.\n *\n * ```ts\n * import { type HITLRequest, type HITLResponse } from \"langchain\";\n * import { type Interrupt } from \"langchain\";\n *\n * const result = await agent.invoke(request);\n * const interruptRequest = result.__interrupt__?.[0] as Interrupt<HITLRequest>;\n *\n * // Examine the action requests and review configs\n * const actionRequests = interruptRequest.value.actionRequests;\n * const reviewConfigs = interruptRequest.value.reviewConfigs;\n *\n * // Create decisions for each action\n * const resume: HITLResponse = {\n * decisions: actionRequests.map((action, i) => {\n * if (action.name === \"calculator\") {\n * return { type: \"approve\" };\n * } else if (action.name === \"write_file\") {\n * return {\n * type: \"edit\",\n * editedAction: { name: \"write_file\", args: { filename: \"safe.txt\", content: \"Safe content\" } }\n * };\n * }\n * return { type: \"reject\", message: \"Action not allowed\" };\n * })\n * };\n *\n * // Resume with decisions\n * await agent.invoke(new Command({ resume }), config);\n * ```\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Decision Types**: Approve, edit, or reject tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Decision Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `approve`: Execute the tool with original arguments\n * - `edit`: Modify the tool name and/or arguments before execution\n * - `reject`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.interruptOn - Per-tool configuration mapping tool names to their settings\n * @param options.interruptOn[toolName].allowedDecisions - Array of decision types allowed for this tool (e.g., [\"approve\", \"edit\", \"reject\"])\n * @param options.interruptOn[toolName].description - Custom approval message for the tool. Can be either a static string or a callable that dynamically generates the description based on agent state, runtime, and tool call information\n * @param options.interruptOn[toolName].argsSchema - JSON schema for the arguments associated with the action, if edits are allowed\n * @param options.interruptOn[toolName].when - Optional predicate that dynamically controls whether a tool call triggers an interrupt. Returns `true` to interrupt or `false` to auto-approve the tool call.\n * @param options.descriptionPrefix - Default prefix for approval messages (default: \"Tool execution requires approval\"). Only used for tools that do not define a custom `description` in their InterruptOnConfig.\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * // Interrupt write_file tool and allow edits or approvals\n * \"write_file\": {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: \"⚠️ File write operation requires approval\"\n * },\n * // Auto-approve read_file tool\n * \"read_file\": false\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middleware: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { type HITLRequest, type HITLResponse, type Interrupt } from \"langchain\";\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * if (result.__interrupt__) {\n * const interruptRequest = result.__interrupt__?.[0] as Interrupt<HITLRequest>;\n *\n * // Show tool call details to user\n * console.log(\"Actions:\", interruptRequest.value.actionRequests);\n * console.log(\"Review configs:\", interruptRequest.value.reviewConfigs);\n *\n * // Resume with approval\n * const resume: HITLResponse = {\n * decisions: [{ type: \"approve\" }]\n * };\n * await agent.invoke(\n * new Command({ resume }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different decision types\n * ```typescript\n * import { type HITLResponse } from \"langchain\";\n *\n * // Approve the tool call as-is\n * const resume: HITLResponse = {\n * decisions: [{ type: \"approve\" }]\n * };\n *\n * // Edit the tool arguments\n * const resume: HITLResponse = {\n * decisions: [{\n * type: \"edit\",\n * editedAction: { name: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * };\n *\n * // Reject with feedback\n * const resume: HITLResponse = {\n * decisions: [{\n * type: \"reject\",\n * message: \"File operation not allowed in demo mode\"\n * }]\n * };\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"execute_sql\": {\n * allowedDecisions: [\"approve\", \"edit\", \"reject\"],\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": false, // Reading metadata is safe\n * \"delete_records\": {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * descriptionPrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @example\n * Using dynamic callable descriptions\n * ```typescript\n * import { type DescriptionFactory, type ToolCall } from \"langchain\";\n * import type { AgentBuiltInState, Runtime } from \"langchain/agents\";\n *\n * // Define a dynamic description factory\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"write_file\": {\n * allowedDecisions: [\"approve\", \"edit\"],\n * // Use dynamic description that can access tool call, state, and runtime\n * description: formatToolDescription\n * },\n * // Or use an inline function\n * \"send_email\": {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: (toolCall, state, runtime) => {\n * const { to, subject } = toolCall.args;\n * return `Email to ${to}\\nSubject: ${subject}\\n\\nRequires approval before sending`;\n * }\n * }\n * }\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt request\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport function humanInTheLoopMiddleware(\n options: NonNullable<HumanInTheLoopMiddlewareConfig>\n) {\n const createActionAndConfig = async (\n toolCall: ToolCall,\n config: InterruptOnConfig,\n state: AgentBuiltInState,\n runtime: Runtime<unknown>\n ): Promise<{\n actionRequest: ActionRequest;\n reviewConfig: ReviewConfig;\n }> => {\n const toolName = toolCall.name;\n const toolArgs = toolCall.args;\n\n // Generate description using the description field (str or callable)\n const descriptionValue = config.description;\n let description: string;\n if (typeof descriptionValue === \"function\") {\n description = await descriptionValue(toolCall, state, runtime);\n } else if (descriptionValue !== undefined) {\n description = descriptionValue;\n } else {\n description = `${\n options.descriptionPrefix ?? \"Tool execution requires approval\"\n }\\n\\nTool: ${toolName}\\nArgs: ${JSON.stringify(toolArgs, null, 2)}`;\n }\n\n /**\n * Create ActionRequest with description\n */\n const actionRequest: ActionRequest = {\n name: toolName,\n args: toolArgs,\n description,\n };\n\n /**\n * Create ReviewConfig\n */\n const reviewConfig: ReviewConfig = {\n actionName: toolName,\n allowedDecisions: config.allowedDecisions,\n };\n\n if (config.argsSchema) {\n reviewConfig.argsSchema = config.argsSchema;\n }\n\n return { actionRequest, reviewConfig };\n };\n\n /**\n * Return `false` if the `when` predicate rejects this tool call, `true` otherwise.\n *\n * When no `when` predicate is configured the tool call always interrupts.\n */\n const shouldInterrupt = async (\n toolCall: ToolCall,\n config: InterruptOnConfig,\n state: AgentBuiltInState,\n runtime: Runtime<unknown>\n ): Promise<boolean> => {\n const { when } = config;\n if (when == null) {\n return true;\n }\n const request: ToolCallRequest<AgentBuiltInState> = {\n toolCall,\n tool: undefined,\n state,\n runtime,\n };\n return when(request);\n };\n\n const processDecision = (\n decision: Decision,\n toolCall: ToolCall,\n config: InterruptOnConfig\n ): { revisedToolCall: ToolCall | null; toolMessage: ToolMessage | null } => {\n const allowedDecisions = config.allowedDecisions;\n if (decision.type === \"approve\" && allowedDecisions.includes(\"approve\")) {\n return { revisedToolCall: toolCall, toolMessage: null };\n }\n\n if (decision.type === \"edit\" && allowedDecisions.includes(\"edit\")) {\n const editedAction = decision.editedAction;\n\n /**\n * Validate edited action structure\n */\n if (!editedAction || typeof editedAction.name !== \"string\") {\n throw new Error(\n `Invalid edited action for tool \"${toolCall.name}\": name must be a string`\n );\n }\n if (!editedAction.args || typeof editedAction.args !== \"object\") {\n throw new Error(\n `Invalid edited action for tool \"${toolCall.name}\": args must be an object`\n );\n }\n\n return {\n revisedToolCall: {\n type: \"tool_call\",\n name: editedAction.name,\n args: editedAction.args,\n id: toolCall.id,\n },\n toolMessage: null,\n };\n }\n\n if (decision.type === \"reject\" && allowedDecisions.includes(\"reject\")) {\n /**\n * Validate that message is a string if provided\n */\n if (\n decision.message !== undefined &&\n typeof decision.message !== \"string\"\n ) {\n throw new Error(\n `Tool call response for \"${\n toolCall.name\n }\" must be a string, got ${typeof decision.message}`\n );\n }\n\n // Create a tool message with the human's text response\n const content =\n decision.message ??\n `User rejected the tool call for \\`${toolCall.name}\\` with id ${toolCall.id}`;\n\n const toolMessage = new ToolMessage({\n content,\n name: toolCall.name,\n tool_call_id: toolCall.id!,\n status: \"error\",\n });\n\n return { revisedToolCall: toolCall, toolMessage };\n }\n\n const msg = `Unexpected human decision: ${JSON.stringify(\n decision\n )}. Decision type '${decision.type}' is not allowed for tool '${\n toolCall.name\n }'. Expected one of ${JSON.stringify(\n allowedDecisions\n )} based on the tool's configuration.`;\n throw new Error(msg);\n };\n\n return createMiddleware({\n name: \"HumanInTheLoopMiddleware\",\n contextSchema,\n afterModel: {\n canJumpTo: [\"model\"],\n hook: async (state, runtime) => {\n const config = interopParse(contextSchema, {\n ...options,\n ...(runtime.context || {}),\n });\n if (!config) {\n return;\n }\n\n const { messages } = state;\n if (!messages.length) {\n return;\n }\n\n /**\n * Don't do anything if the last message isn't an AI message with tool calls.\n */\n const lastMessage = [...messages]\n .reverse()\n .find((msg) => AIMessage.isInstance(msg)) as AIMessage;\n if (!lastMessage || !lastMessage.tool_calls?.length) {\n return;\n }\n\n /**\n * If the user omits the interruptOn config, we don't do anything.\n */\n if (!config.interruptOn) {\n return;\n }\n\n /**\n * Resolve per-tool configs (boolean true -> all decisions allowed; false -> auto-approve)\n */\n const resolvedConfigs: Record<string, InterruptOnConfig> = {};\n for (const [toolName, toolConfig] of Object.entries(\n config.interruptOn\n )) {\n if (typeof toolConfig === \"boolean\") {\n if (toolConfig === true) {\n resolvedConfigs[toolName] = {\n allowedDecisions: [...ALLOWED_DECISIONS],\n };\n }\n } else if (toolConfig.allowedDecisions) {\n resolvedConfigs[toolName] = toolConfig as InterruptOnConfig;\n }\n }\n\n const interruptToolCalls: ToolCall[] = [];\n const autoApprovedToolCalls: ToolCall[] = [];\n\n for (const toolCall of lastMessage.tool_calls) {\n const interruptConfig = resolvedConfigs[toolCall.name];\n /**\n * A tool call is interrupted only when it has a resolved config and its\n * optional `when` predicate doesn't opt it out. Otherwise it is\n * auto-approved.\n */\n if (\n interruptConfig &&\n (await shouldInterrupt(toolCall, interruptConfig, state, runtime))\n ) {\n interruptToolCalls.push(toolCall);\n } else {\n autoApprovedToolCalls.push(toolCall);\n }\n }\n\n /**\n * No interrupt tool calls, so we can just return.\n */\n if (!interruptToolCalls.length) {\n return;\n }\n\n /**\n * Create action requests and review configs for all tools that need approval\n */\n const actionRequests: ActionRequest[] = [];\n const reviewConfigs: ReviewConfig[] = [];\n\n for (const toolCall of interruptToolCalls) {\n const interruptConfig = resolvedConfigs[toolCall.name]!;\n\n /**\n * Create ActionRequest and ReviewConfig using helper method\n */\n const { actionRequest, reviewConfig } = await createActionAndConfig(\n toolCall,\n interruptConfig,\n state,\n runtime\n );\n actionRequests.push(actionRequest);\n reviewConfigs.push(reviewConfig);\n }\n\n /**\n * Create single HITLRequest with all actions and configs\n */\n const hitlRequest: HITLRequest = {\n actionRequests,\n reviewConfigs,\n };\n\n /**\n * Send interrupt and get response\n */\n const hitlResponse = (await interrupt(hitlRequest)) as HITLResponse;\n const decisions = hitlResponse.decisions;\n\n /**\n * Validate that decisions is a valid array before checking length\n */\n if (!decisions || !Array.isArray(decisions)) {\n throw new Error(\n \"Invalid HITLResponse: decisions must be a non-empty array\"\n );\n }\n\n /**\n * Validate that the number of decisions matches the number of interrupt tool calls\n */\n if (decisions.length !== interruptToolCalls.length) {\n throw new Error(\n `Number of human decisions (${decisions.length}) does not match number of hanging tool calls (${interruptToolCalls.length}).`\n );\n }\n\n const revisedToolCalls: ToolCall[] = [...autoApprovedToolCalls];\n const artificialToolMessages: ToolMessage[] = [];\n const hasRejectedToolCalls = decisions.some(\n (decision) => decision.type === \"reject\"\n );\n\n /**\n * Process each decision using helper method\n */\n for (let i = 0; i < decisions.length; i++) {\n const decision = decisions[i]!;\n const toolCall = interruptToolCalls[i]!;\n const interruptConfig = resolvedConfigs[toolCall.name]!;\n\n const { revisedToolCall, toolMessage } = processDecision(\n decision,\n toolCall,\n interruptConfig\n );\n\n if (\n revisedToolCall &&\n /**\n * If any decision is a rejected, we are going back to the model\n * with only the tool calls that were rejected as we don't know\n * the results of the approved/updated tool calls at this point.\n */\n (!hasRejectedToolCalls || decision.type === \"reject\")\n ) {\n revisedToolCalls.push(revisedToolCall);\n }\n if (toolMessage) {\n artificialToolMessages.push(toolMessage);\n }\n }\n\n /**\n * Update the AI message to only include approved tool calls\n */\n if (AIMessage.isInstance(lastMessage)) {\n lastMessage.tool_calls = revisedToolCalls;\n }\n\n const jumpTo: JumpToTarget | undefined = hasRejectedToolCalls\n ? \"model\"\n : undefined;\n return {\n messages: [lastMessage, ...artificialToolMessages],\n jumpTo,\n };\n },\n },\n });\n}\n"],"mappings":";;;;;;AAcA,MAAM,qBAAqBA,OAAAA,EACxB,SAAS,CAAC,CACV,KAAKA,OAAAA,EAAE,OAA2C,CAAC,CAAC,CACpD,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KA,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;KACzC,MAAM,WAAW,UAAU;KAC3B,MAAM,WAAW,mBAAmB;KACpC,MAAM,kBAAkB,gBAAgB,SAAS;KAEjD,MAAM,EAAE,iBAAiB,gBAAgB,gBACvC,UACA,UACA,eACF;KAEA,IACE,oBAMC,CAAC,wBAAwB,SAAS,SAAS,WAE5C,iBAAiB,KAAK,eAAe;KAEvC,IAAI,aACF,uBAAuB,KAAK,WAAW;IAE3C;;;;IAKA,IAAID,yBAAAA,UAAU,WAAW,WAAW,GAClC,YAAY,aAAa;IAG3B,MAAM,SAAmC,uBACrC,UACA,KAAA;IACJ,OAAO;KACL,UAAU,CAAC,aAAa,GAAG,sBAAsB;KACjD;IACF;GACF;EACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"hitl.cjs","names":["z","ToolMessage","createMiddleware","interopParse","AIMessage","interrupt"],"sources":["../../../src/agents/middleware/hitl.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v3\";\nimport { AIMessage, ToolMessage, ToolCall } from \"@langchain/core/messages\";\nimport {\n InferInteropZodInput,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport { interrupt } from \"@langchain/langgraph\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { ToolCallRequest } from \"./types.js\";\n\nconst WhenFunctionSchema = z\n .function()\n .args(z.custom<ToolCallRequest<AgentBuiltInState>>()) // request\n .returns(z.union([z.boolean(), z.promise(z.boolean())]));\n\n/**\n * Predicate controlling whether a given tool call triggers an interrupt.\n *\n * Receives a {@link ToolCallRequest} and returns `true` to interrupt or `false`\n * to auto-approve the tool call.\n *\n * The request is constructed with `tool` set to `undefined` and `runtime` set to\n * the node-level {@link Runtime}, so it reflects the batch (`afterModel`) context\n * rather than a per-call tool execution.\n *\n * @param request - The tool call request being evaluated\n * @returns `true` to interrupt for the tool call, `false` to auto-approve it.\n * May also return a promise resolving to a boolean.\n *\n * @example\n * ```typescript\n * import { type WhenPredicate } from \"langchain\";\n *\n * // Only interrupt delete_file calls targeting /etc\n * const when: WhenPredicate = (request) =>\n * String(request.toolCall.args.path ?? \"\").startsWith(\"/etc\");\n * ```\n */\nexport type WhenPredicate = z.infer<typeof WhenFunctionSchema>;\n\nconst DescriptionFunctionSchema = z\n .function()\n .args(\n z.custom<ToolCall>(), // toolCall\n z.custom<AgentBuiltInState>(), // state\n z.custom<Runtime<unknown>>() // runtime\n )\n .returns(z.union([z.string(), z.promise(z.string())]));\n\n/**\n * Function type that dynamically generates a description for a tool call approval request.\n *\n * @param toolCall - The tool call being reviewed\n * @param state - The current agent state\n * @param runtime - The agent runtime context\n * @returns A string description or Promise that resolves to a string description\n *\n * @example\n * ```typescript\n * import { type DescriptionFactory, type ToolCall } from \"langchain\";\n *\n * const descriptionFactory: DescriptionFactory = (toolCall, state, runtime) => {\n * return `Please review: ${toolCall.name}(${JSON.stringify(toolCall.args)})`;\n * };\n * ```\n */\nexport type DescriptionFactory = z.infer<typeof DescriptionFunctionSchema>;\n\n/**\n * The type of decision a human can make.\n */\nconst ALLOWED_DECISIONS = [\"approve\", \"edit\", \"reject\", \"respond\"] as const;\nconst DecisionType = z.enum(ALLOWED_DECISIONS);\nexport type DecisionType = z.infer<typeof DecisionType>;\nconst DEFAULT_ALLOWED_DECISIONS: DecisionType[] = [\"approve\", \"edit\", \"reject\"];\n\nconst InterruptOnConfigSchema = z.object({\n /**\n * The decisions that are allowed for this action.\n */\n allowedDecisions: z.array(DecisionType),\n /**\n * The description attached to the request for human input.\n * Can be either:\n * - A static string describing the approval request\n * - A callable that dynamically generates the description based on agent state,\n * runtime, and tool call information\n *\n * @example\n * Static string description\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"Please review this tool execution\"\n * };\n * ```\n *\n * @example\n * Dynamic callable description\n * ```typescript\n * import type {\n * AgentBuiltInState,\n * Runtime,\n * DescriptionFactory,\n * ToolCall,\n * InterruptOnConfig\n * } from \"langchain\";\n *\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: formatToolDescription\n * };\n * ```\n */\n description: z.union([z.string(), DescriptionFunctionSchema]).optional(),\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema: z.record(z.any()).optional(),\n /**\n * Optional predicate controlling whether to interrupt for a given tool call.\n *\n * Receives a {@link ToolCallRequest} and returns `true` to interrupt or\n * `false` to auto-approve the tool call.\n *\n * The request is constructed with `tool` set to `undefined` and `runtime` set\n * to the node-level {@link Runtime}, so `request.tool` is not available.\n *\n * @example\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * // Only interrupt delete_file calls targeting /etc\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * when: (request) =>\n * String(request.toolCall.args.path ?? \"\").startsWith(\"/etc\"),\n * };\n * ```\n */\n when: WhenFunctionSchema.optional(),\n});\nexport type InterruptOnConfig = z.input<typeof InterruptOnConfigSchema>;\n\n/**\n * Represents an action with a name and arguments.\n */\nexport interface Action {\n /**\n * The type or name of action being requested (e.g., \"add_numbers\").\n */\n name: string;\n /**\n * Key-value pairs of arguments needed for the action (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n}\n\n/**\n * Represents an action request with a name, arguments, and description.\n */\nexport interface ActionRequest {\n /**\n * The name of the action being requested.\n */\n name: string;\n /**\n * Key-value pairs of arguments needed for the action (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n /**\n * The description of the action to be reviewed.\n */\n description?: string;\n}\n\n/**\n * Policy for reviewing a HITL request.\n */\nexport interface ReviewConfig {\n /**\n * Name of the action associated with this review configuration.\n */\n actionName: string;\n /**\n * The decisions that are allowed for this request.\n */\n allowedDecisions: DecisionType[];\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema?: Record<string, any>;\n}\n\n/**\n * Request for human feedback on a sequence of actions requested by a model.\n *\n * @example\n * ```ts\n * const hitlRequest: HITLRequest = {\n * actionRequests: [\n * { name: \"send_email\", args: { to: \"user@example.com\", subject: \"Hello\" } }\n * ],\n * reviewConfigs: [\n * {\n * actionName: \"send_email\",\n * allowedDecisions: [\"approve\", \"edit\", \"reject\"],\n * description: \"Please review the email before sending\"\n * }\n * ]\n * };\n * const response = interrupt(hitlRequest);\n * ```\n */\nexport interface HITLRequest {\n /**\n * A list of agent actions for human review.\n */\n actionRequests: ActionRequest[];\n /**\n * Review configuration for all possible actions.\n */\n reviewConfigs: ReviewConfig[];\n}\n\n/**\n * Response when a human approves the action.\n */\nexport interface ApproveDecision {\n type: \"approve\";\n}\n\n/**\n * Response when a human edits the action.\n */\nexport interface EditDecision {\n type: \"edit\";\n /**\n * Edited action for the agent to perform.\n * Ex: for a tool call, a human reviewer can edit the tool name and args.\n */\n editedAction: Action;\n}\n\n/**\n * Response when a human rejects the action.\n */\nexport interface RejectDecision {\n type: \"reject\";\n /**\n * The message sent to the model explaining why the action was rejected.\n */\n message?: string;\n}\n\n/**\n * Response when a human answers on behalf of the tool.\n */\nexport interface RespondDecision {\n type: \"respond\";\n /**\n * The message sent to the model as the tool result.\n */\n message: string;\n}\n\n/**\n * Union of all possible decision types.\n */\nexport type Decision =\n | ApproveDecision\n | EditDecision\n | RejectDecision\n | RespondDecision;\n\n/**\n * Response payload for a HITLRequest.\n */\nexport interface HITLResponse {\n /**\n * The decisions made by the human.\n */\n decisions: Decision[];\n}\n\nconst contextSchema = z.object({\n /**\n * Mapping of tool name to allowed reviewer responses.\n * If a tool doesn't have an entry, it's auto-approved by default.\n *\n * - `true` -> pause for approval and allow approve/edit/reject decisions\n * - `false` -> auto-approve (no human review)\n * - `InterruptOnConfig` -> explicitly specify which decisions are allowed for this tool\n */\n interruptOn: z\n .record(z.union([z.boolean(), InterruptOnConfigSchema]))\n .optional(),\n /**\n * Prefix used when constructing human-facing approval messages.\n * Provides context about the tool call being reviewed; does not change the underlying action.\n *\n * Note: This prefix is only applied for tools that do not provide a custom\n * `description` via their {@link InterruptOnConfig}. If a tool specifies a custom\n * `description`, that per-tool text is used and this prefix is ignored.\n */\n descriptionPrefix: z.string().default(\"Tool execution requires approval\"),\n});\nexport type HumanInTheLoopMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * A invocation result that has been interrupted by the middleware will have a `__interrupt__`\n * property that contains the interrupt request.\n *\n * ```ts\n * import { type HITLRequest, type HITLResponse } from \"langchain\";\n * import { type Interrupt } from \"langchain\";\n *\n * const result = await agent.invoke(request);\n * const interruptRequest = result.__interrupt__?.[0] as Interrupt<HITLRequest>;\n *\n * // Examine the action requests and review configs\n * const actionRequests = interruptRequest.value.actionRequests;\n * const reviewConfigs = interruptRequest.value.reviewConfigs;\n *\n * // Create decisions for each action\n * const resume: HITLResponse = {\n * decisions: actionRequests.map((action, i) => {\n * if (action.name === \"calculator\") {\n * return { type: \"approve\" };\n * } else if (action.name === \"write_file\") {\n * return {\n * type: \"edit\",\n * editedAction: { name: \"write_file\", args: { filename: \"safe.txt\", content: \"Safe content\" } }\n * };\n * }\n * return { type: \"reject\", message: \"Action not allowed\" };\n * })\n * };\n *\n * // Resume with decisions\n * await agent.invoke(new Command({ resume }), config);\n * ```\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Decision Types**: Approve, edit, or reject tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Decision Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `approve`: Execute the tool with original arguments\n * - `edit`: Modify the tool name and/or arguments before execution\n * - `reject`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.interruptOn - Per-tool configuration mapping tool names to their settings\n * @param options.interruptOn[toolName].allowedDecisions - Array of decision types allowed for this tool (e.g., [\"approve\", \"edit\", \"reject\"])\n * @param options.interruptOn[toolName].description - Custom approval message for the tool. Can be either a static string or a callable that dynamically generates the description based on agent state, runtime, and tool call information\n * @param options.interruptOn[toolName].argsSchema - JSON schema for the arguments associated with the action, if edits are allowed\n * @param options.interruptOn[toolName].when - Optional predicate that dynamically controls whether a tool call triggers an interrupt. Returns `true` to interrupt or `false` to auto-approve the tool call.\n * @param options.descriptionPrefix - Default prefix for approval messages (default: \"Tool execution requires approval\"). Only used for tools that do not define a custom `description` in their InterruptOnConfig.\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * // Interrupt write_file tool and allow edits or approvals\n * \"write_file\": {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: \"⚠️ File write operation requires approval\"\n * },\n * // Auto-approve read_file tool\n * \"read_file\": false\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middleware: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { type HITLRequest, type HITLResponse, type Interrupt } from \"langchain\";\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * if (result.__interrupt__) {\n * const interruptRequest = result.__interrupt__?.[0] as Interrupt<HITLRequest>;\n *\n * // Show tool call details to user\n * console.log(\"Actions:\", interruptRequest.value.actionRequests);\n * console.log(\"Review configs:\", interruptRequest.value.reviewConfigs);\n *\n * // Resume with approval\n * const resume: HITLResponse = {\n * decisions: [{ type: \"approve\" }]\n * };\n * await agent.invoke(\n * new Command({ resume }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different decision types\n * ```typescript\n * import { type HITLResponse } from \"langchain\";\n *\n * // Approve the tool call as-is\n * const resume: HITLResponse = {\n * decisions: [{ type: \"approve\" }]\n * };\n *\n * // Edit the tool arguments\n * const resume: HITLResponse = {\n * decisions: [{\n * type: \"edit\",\n * editedAction: { name: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * };\n *\n * // Reject with feedback\n * const resume: HITLResponse = {\n * decisions: [{\n * type: \"reject\",\n * message: \"File operation not allowed in demo mode\"\n * }]\n * };\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"execute_sql\": {\n * allowedDecisions: [\"approve\", \"edit\", \"reject\"],\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": false, // Reading metadata is safe\n * \"delete_records\": {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * descriptionPrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @example\n * Using dynamic callable descriptions\n * ```typescript\n * import { type DescriptionFactory, type ToolCall } from \"langchain\";\n * import type { AgentBuiltInState, Runtime } from \"langchain/agents\";\n *\n * // Define a dynamic description factory\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"write_file\": {\n * allowedDecisions: [\"approve\", \"edit\"],\n * // Use dynamic description that can access tool call, state, and runtime\n * description: formatToolDescription\n * },\n * // Or use an inline function\n * \"send_email\": {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: (toolCall, state, runtime) => {\n * const { to, subject } = toolCall.args;\n * return `Email to ${to}\\nSubject: ${subject}\\n\\nRequires approval before sending`;\n * }\n * }\n * }\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt request\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport function humanInTheLoopMiddleware(\n options: NonNullable<HumanInTheLoopMiddlewareConfig>\n) {\n const createActionAndConfig = async (\n toolCall: ToolCall,\n config: InterruptOnConfig,\n state: AgentBuiltInState,\n runtime: Runtime<unknown>\n ): Promise<{\n actionRequest: ActionRequest;\n reviewConfig: ReviewConfig;\n }> => {\n const toolName = toolCall.name;\n const toolArgs = toolCall.args;\n\n // Generate description using the description field (str or callable)\n const descriptionValue = config.description;\n let description: string;\n if (typeof descriptionValue === \"function\") {\n description = await descriptionValue(toolCall, state, runtime);\n } else if (descriptionValue !== undefined) {\n description = descriptionValue;\n } else {\n description = `${\n options.descriptionPrefix ?? \"Tool execution requires approval\"\n }\\n\\nTool: ${toolName}\\nArgs: ${JSON.stringify(toolArgs, null, 2)}`;\n }\n\n /**\n * Create ActionRequest with description\n */\n const actionRequest: ActionRequest = {\n name: toolName,\n args: toolArgs,\n description,\n };\n\n /**\n * Create ReviewConfig\n */\n const reviewConfig: ReviewConfig = {\n actionName: toolName,\n allowedDecisions: config.allowedDecisions,\n };\n\n if (config.argsSchema) {\n reviewConfig.argsSchema = config.argsSchema;\n }\n\n return { actionRequest, reviewConfig };\n };\n\n /**\n * Return `false` if the `when` predicate rejects this tool call, `true` otherwise.\n *\n * When no `when` predicate is configured the tool call always interrupts.\n */\n const shouldInterrupt = async (\n toolCall: ToolCall,\n config: InterruptOnConfig,\n state: AgentBuiltInState,\n runtime: Runtime<unknown>\n ): Promise<boolean> => {\n const { when } = config;\n if (when == null) {\n return true;\n }\n const request: ToolCallRequest<AgentBuiltInState> = {\n toolCall,\n tool: undefined,\n state,\n runtime,\n };\n return when(request);\n };\n\n const processDecision = (\n decision: Decision,\n toolCall: ToolCall,\n config: InterruptOnConfig\n ): { revisedToolCall: ToolCall | null; toolMessage: ToolMessage | null } => {\n const allowedDecisions = config.allowedDecisions;\n if (decision.type === \"approve\" && allowedDecisions.includes(\"approve\")) {\n return { revisedToolCall: toolCall, toolMessage: null };\n }\n\n if (decision.type === \"edit\" && allowedDecisions.includes(\"edit\")) {\n const editedAction = decision.editedAction;\n\n /**\n * Validate edited action structure\n */\n if (!editedAction || typeof editedAction.name !== \"string\") {\n throw new Error(\n `Invalid edited action for tool \"${toolCall.name}\": name must be a string`\n );\n }\n if (!editedAction.args || typeof editedAction.args !== \"object\") {\n throw new Error(\n `Invalid edited action for tool \"${toolCall.name}\": args must be an object`\n );\n }\n\n return {\n revisedToolCall: {\n type: \"tool_call\",\n name: editedAction.name,\n args: editedAction.args,\n id: toolCall.id,\n },\n toolMessage: null,\n };\n }\n\n if (decision.type === \"reject\" && allowedDecisions.includes(\"reject\")) {\n /**\n * Validate that message is a string if provided\n */\n if (\n decision.message !== undefined &&\n typeof decision.message !== \"string\"\n ) {\n throw new Error(\n `Tool call response for \"${\n toolCall.name\n }\" must be a string, got ${typeof decision.message}`\n );\n }\n\n // Create a tool message with the human's text response\n const content =\n decision.message ??\n `User rejected the tool call for \\`${toolCall.name}\\` with id ${toolCall.id}`;\n\n const toolMessage = new ToolMessage({\n content,\n name: toolCall.name,\n tool_call_id: toolCall.id!,\n status: \"error\",\n });\n\n return { revisedToolCall: toolCall, toolMessage };\n }\n\n if (decision.type === \"respond\" && allowedDecisions.includes(\"respond\")) {\n if (typeof decision.message !== \"string\") {\n throw new Error(\n `Tool call response for \"${\n toolCall.name\n }\" must be a string, got ${typeof decision.message}`\n );\n }\n\n const toolMessage = new ToolMessage({\n content: decision.message,\n name: toolCall.name,\n tool_call_id: toolCall.id!,\n status: \"success\",\n });\n\n return { revisedToolCall: toolCall, toolMessage };\n }\n\n const msg = `Unexpected human decision: ${JSON.stringify(\n decision\n )}. Decision type '${decision.type}' is not allowed for tool '${\n toolCall.name\n }'. Expected one of ${JSON.stringify(\n allowedDecisions\n )} based on the tool's configuration.`;\n throw new Error(msg);\n };\n\n return createMiddleware({\n name: \"HumanInTheLoopMiddleware\",\n contextSchema,\n afterModel: {\n canJumpTo: [\"model\"],\n hook: async (state, runtime) => {\n const config = interopParse(contextSchema, {\n ...options,\n ...(runtime.context || {}),\n });\n if (!config) {\n return;\n }\n\n const { messages } = state;\n if (!messages.length) {\n return;\n }\n\n /**\n * Don't do anything if the last message isn't an AI message with tool calls.\n */\n const lastMessage = [...messages]\n .reverse()\n .find((msg) => AIMessage.isInstance(msg)) as AIMessage;\n if (!lastMessage || !lastMessage.tool_calls?.length) {\n return;\n }\n\n /**\n * If the user omits the interruptOn config, we don't do anything.\n */\n if (!config.interruptOn) {\n return;\n }\n\n /**\n * Resolve per-tool configs (boolean true -> all decisions allowed; false -> auto-approve)\n */\n const resolvedConfigs: Record<string, InterruptOnConfig> = {};\n for (const [toolName, toolConfig] of Object.entries(\n config.interruptOn\n )) {\n if (typeof toolConfig === \"boolean\") {\n if (toolConfig === true) {\n resolvedConfigs[toolName] = {\n allowedDecisions: [...DEFAULT_ALLOWED_DECISIONS],\n };\n }\n } else if (toolConfig.allowedDecisions) {\n resolvedConfigs[toolName] = toolConfig as InterruptOnConfig;\n }\n }\n\n const interruptToolCalls: ToolCall[] = [];\n const autoApprovedToolCalls: ToolCall[] = [];\n\n for (const toolCall of lastMessage.tool_calls) {\n const interruptConfig = resolvedConfigs[toolCall.name];\n /**\n * A tool call is interrupted only when it has a resolved config and its\n * optional `when` predicate doesn't opt it out. Otherwise it is\n * auto-approved.\n */\n if (\n interruptConfig &&\n (await shouldInterrupt(toolCall, interruptConfig, state, runtime))\n ) {\n interruptToolCalls.push(toolCall);\n } else {\n autoApprovedToolCalls.push(toolCall);\n }\n }\n\n /**\n * No interrupt tool calls, so we can just return.\n */\n if (!interruptToolCalls.length) {\n return;\n }\n\n /**\n * Create action requests and review configs for all tools that need approval\n */\n const actionRequests: ActionRequest[] = [];\n const reviewConfigs: ReviewConfig[] = [];\n\n for (const toolCall of interruptToolCalls) {\n const interruptConfig = resolvedConfigs[toolCall.name]!;\n\n /**\n * Create ActionRequest and ReviewConfig using helper method\n */\n const { actionRequest, reviewConfig } = await createActionAndConfig(\n toolCall,\n interruptConfig,\n state,\n runtime\n );\n actionRequests.push(actionRequest);\n reviewConfigs.push(reviewConfig);\n }\n\n /**\n * Create single HITLRequest with all actions and configs\n */\n const hitlRequest: HITLRequest = {\n actionRequests,\n reviewConfigs,\n };\n\n /**\n * Send interrupt and get response\n */\n const hitlResponse = (await interrupt(hitlRequest)) as HITLResponse;\n const decisions = hitlResponse.decisions;\n\n /**\n * Validate that decisions is a valid array before checking length\n */\n if (!decisions || !Array.isArray(decisions)) {\n throw new Error(\n \"Invalid HITLResponse: decisions must be a non-empty array\"\n );\n }\n\n /**\n * Validate that the number of decisions matches the number of interrupt tool calls\n */\n if (decisions.length !== interruptToolCalls.length) {\n throw new Error(\n `Number of human decisions (${decisions.length}) does not match number of hanging tool calls (${interruptToolCalls.length}).`\n );\n }\n\n const revisedToolCalls: ToolCall[] = [...autoApprovedToolCalls];\n const artificialToolMessages: ToolMessage[] = [];\n const hasRejectedToolCalls = decisions.some(\n (decision) => decision.type === \"reject\"\n );\n const hasRespondedToolCalls = decisions.some(\n (decision) => decision.type === \"respond\"\n );\n\n /**\n * Process each decision using helper method\n */\n for (let i = 0; i < decisions.length; i++) {\n const decision = decisions[i]!;\n const toolCall = interruptToolCalls[i]!;\n const interruptConfig = resolvedConfigs[toolCall.name]!;\n\n const { revisedToolCall, toolMessage } = processDecision(\n decision,\n toolCall,\n interruptConfig\n );\n\n if (\n revisedToolCall &&\n /**\n * If any decision is a rejected, we are going back to the model\n * with only the tool calls that were rejected as we don't know\n * the results of the approved/updated tool calls at this point.\n */\n (!hasRejectedToolCalls ||\n decision.type === \"reject\" ||\n decision.type === \"respond\")\n ) {\n revisedToolCalls.push(revisedToolCall);\n }\n if (toolMessage) {\n artificialToolMessages.push(toolMessage);\n }\n }\n\n /**\n * Update the AI message to only include approved tool calls\n */\n if (AIMessage.isInstance(lastMessage)) {\n lastMessage.tool_calls = revisedToolCalls;\n }\n\n const hasPendingToolCalls = revisedToolCalls.some(\n (toolCall) =>\n !artificialToolMessages.some(\n (message) => message.tool_call_id === toolCall.id\n )\n );\n const jumpTo: JumpToTarget | undefined =\n hasRejectedToolCalls ||\n (hasRespondedToolCalls && !hasPendingToolCalls)\n ? \"model\"\n : undefined;\n return {\n messages: [lastMessage, ...artificialToolMessages],\n jumpTo,\n };\n },\n },\n });\n}\n"],"mappings":";;;;;;AAcA,MAAM,qBAAqBA,OAAAA,EACxB,SAAS,CAAC,CACV,KAAKA,OAAAA,EAAE,OAA2C,CAAC,CAAC,CACpD,QAAQA,OAAAA,EAAE,MAAM,CAACA,OAAAA,EAAE,QAAQ,GAAGA,OAAAA,EAAE,QAAQA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;AA2BzD,MAAM,4BAA4BA,OAAAA,EAC/B,SAAS,CAAC,CACV,KACCA,OAAAA,EAAE,OAAiB,GACnBA,OAAAA,EAAE,OAA0B,GAC5BA,OAAAA,EAAE,OAAyB,CAC7B,CAA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,MAAM,uBAAuB,UAAU,MACpC,aAAa,SAAS,SAAS,QAClC;IACA,MAAM,wBAAwB,UAAU,MACrC,aAAa,SAAS,SAAS,SAClC;;;;IAKA,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;KACzC,MAAM,WAAW,UAAU;KAC3B,MAAM,WAAW,mBAAmB;KACpC,MAAM,kBAAkB,gBAAgB,SAAS;KAEjD,MAAM,EAAE,iBAAiB,gBAAgB,gBACvC,UACA,UACA,eACF;KAEA,IACE,oBAMC,CAAC,wBACA,SAAS,SAAS,YAClB,SAAS,SAAS,YAEpB,iBAAiB,KAAK,eAAe;KAEvC,IAAI,aACF,uBAAuB,KAAK,WAAW;IAE3C;;;;IAKA,IAAID,yBAAAA,UAAU,WAAW,WAAW,GAClC,YAAY,aAAa;IAG3B,MAAM,sBAAsB,iBAAiB,MAC1C,aACC,CAAC,uBAAuB,MACrB,YAAY,QAAQ,iBAAiB,SAAS,EACjD,CACJ;IACA,MAAM,SACJ,wBACC,yBAAyB,CAAC,sBACvB,UACA,KAAA;IACN,OAAO;KACL,UAAU,CAAC,aAAa,GAAG,sBAAsB;KACjD;IACF;GACF;EACF;CACF,CAAC;AACH"}
|
|
@@ -28,7 +28,7 @@ declare const WhenFunctionSchema: z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCallRe
|
|
|
28
28
|
* String(request.toolCall.args.path ?? "").startsWith("/etc");
|
|
29
29
|
* ```
|
|
30
30
|
*/
|
|
31
|
-
type WhenPredicate = z.infer<typeof WhenFunctionSchema>;
|
|
31
|
+
export type WhenPredicate = z.infer<typeof WhenFunctionSchema>;
|
|
32
32
|
declare const DescriptionFunctionSchema: z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>;
|
|
33
33
|
/**
|
|
34
34
|
* Function type that dynamically generates a description for a tool call approval request.
|
|
@@ -47,14 +47,14 @@ declare const DescriptionFunctionSchema: z.ZodFunction<z.ZodTuple<[z.ZodType<Too
|
|
|
47
47
|
* };
|
|
48
48
|
* ```
|
|
49
49
|
*/
|
|
50
|
-
type DescriptionFactory = z.infer<typeof DescriptionFunctionSchema>;
|
|
51
|
-
declare const DecisionType: z.ZodEnum<["approve", "edit", "reject"]>;
|
|
50
|
+
export type DescriptionFactory = z.infer<typeof DescriptionFunctionSchema>;
|
|
51
|
+
declare const DecisionType: z.ZodEnum<["approve", "edit", "reject", "respond"]>;
|
|
52
52
|
type DecisionType = z.infer<typeof DecisionType>;
|
|
53
53
|
declare const InterruptOnConfigSchema: z.ZodObject<{
|
|
54
54
|
/**
|
|
55
55
|
* The decisions that are allowed for this action.
|
|
56
56
|
*/
|
|
57
|
-
allowedDecisions: z.ZodArray<z.ZodEnum<["approve", "edit", "reject"]>, "many">;
|
|
57
|
+
allowedDecisions: z.ZodArray<z.ZodEnum<["approve", "edit", "reject", "respond"]>, "many">;
|
|
58
58
|
/**
|
|
59
59
|
* The description attached to the request for human input.
|
|
60
60
|
* Can be either:
|
|
@@ -126,21 +126,21 @@ declare const InterruptOnConfigSchema: z.ZodObject<{
|
|
|
126
126
|
*/
|
|
127
127
|
when: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCallRequest<AgentBuiltInState, unknown>, z.ZodTypeDef, ToolCallRequest<AgentBuiltInState, unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodBoolean, z.ZodPromise<z.ZodBoolean>]>>>;
|
|
128
128
|
}, "strip", z.ZodTypeAny, {
|
|
129
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
129
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
130
130
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
131
131
|
argsSchema?: Record<string, any> | undefined;
|
|
132
132
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
133
133
|
}, {
|
|
134
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
134
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
135
135
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
136
136
|
argsSchema?: Record<string, any> | undefined;
|
|
137
137
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
138
138
|
}>;
|
|
139
|
-
type InterruptOnConfig = z.input<typeof InterruptOnConfigSchema>;
|
|
139
|
+
export type InterruptOnConfig = z.input<typeof InterruptOnConfigSchema>;
|
|
140
140
|
/**
|
|
141
141
|
* Represents an action with a name and arguments.
|
|
142
142
|
*/
|
|
143
|
-
interface Action {
|
|
143
|
+
export interface Action {
|
|
144
144
|
/**
|
|
145
145
|
* The type or name of action being requested (e.g., "add_numbers").
|
|
146
146
|
*/
|
|
@@ -153,7 +153,7 @@ interface Action {
|
|
|
153
153
|
/**
|
|
154
154
|
* Represents an action request with a name, arguments, and description.
|
|
155
155
|
*/
|
|
156
|
-
interface ActionRequest {
|
|
156
|
+
export interface ActionRequest {
|
|
157
157
|
/**
|
|
158
158
|
* The name of the action being requested.
|
|
159
159
|
*/
|
|
@@ -170,7 +170,7 @@ interface ActionRequest {
|
|
|
170
170
|
/**
|
|
171
171
|
* Policy for reviewing a HITL request.
|
|
172
172
|
*/
|
|
173
|
-
interface ReviewConfig {
|
|
173
|
+
export interface ReviewConfig {
|
|
174
174
|
/**
|
|
175
175
|
* Name of the action associated with this review configuration.
|
|
176
176
|
*/
|
|
@@ -204,7 +204,7 @@ interface ReviewConfig {
|
|
|
204
204
|
* const response = interrupt(hitlRequest);
|
|
205
205
|
* ```
|
|
206
206
|
*/
|
|
207
|
-
interface HITLRequest {
|
|
207
|
+
export interface HITLRequest {
|
|
208
208
|
/**
|
|
209
209
|
* A list of agent actions for human review.
|
|
210
210
|
*/
|
|
@@ -217,13 +217,13 @@ interface HITLRequest {
|
|
|
217
217
|
/**
|
|
218
218
|
* Response when a human approves the action.
|
|
219
219
|
*/
|
|
220
|
-
interface ApproveDecision {
|
|
220
|
+
export interface ApproveDecision {
|
|
221
221
|
type: "approve";
|
|
222
222
|
}
|
|
223
223
|
/**
|
|
224
224
|
* Response when a human edits the action.
|
|
225
225
|
*/
|
|
226
|
-
interface EditDecision {
|
|
226
|
+
export interface EditDecision {
|
|
227
227
|
type: "edit";
|
|
228
228
|
/**
|
|
229
229
|
* Edited action for the agent to perform.
|
|
@@ -234,21 +234,31 @@ interface EditDecision {
|
|
|
234
234
|
/**
|
|
235
235
|
* Response when a human rejects the action.
|
|
236
236
|
*/
|
|
237
|
-
interface RejectDecision {
|
|
237
|
+
export interface RejectDecision {
|
|
238
238
|
type: "reject";
|
|
239
239
|
/**
|
|
240
240
|
* The message sent to the model explaining why the action was rejected.
|
|
241
241
|
*/
|
|
242
242
|
message?: string;
|
|
243
243
|
}
|
|
244
|
+
/**
|
|
245
|
+
* Response when a human answers on behalf of the tool.
|
|
246
|
+
*/
|
|
247
|
+
export interface RespondDecision {
|
|
248
|
+
type: "respond";
|
|
249
|
+
/**
|
|
250
|
+
* The message sent to the model as the tool result.
|
|
251
|
+
*/
|
|
252
|
+
message: string;
|
|
253
|
+
}
|
|
244
254
|
/**
|
|
245
255
|
* Union of all possible decision types.
|
|
246
256
|
*/
|
|
247
|
-
type Decision = ApproveDecision | EditDecision | RejectDecision;
|
|
257
|
+
export type Decision = ApproveDecision | EditDecision | RejectDecision | RespondDecision;
|
|
248
258
|
/**
|
|
249
259
|
* Response payload for a HITLRequest.
|
|
250
260
|
*/
|
|
251
|
-
interface HITLResponse {
|
|
261
|
+
export interface HITLResponse {
|
|
252
262
|
/**
|
|
253
263
|
* The decisions made by the human.
|
|
254
264
|
*/
|
|
@@ -267,7 +277,7 @@ declare const contextSchema: z.ZodObject<{
|
|
|
267
277
|
/**
|
|
268
278
|
* The decisions that are allowed for this action.
|
|
269
279
|
*/
|
|
270
|
-
allowedDecisions: z.ZodArray<z.ZodEnum<["approve", "edit", "reject"]>, "many">;
|
|
280
|
+
allowedDecisions: z.ZodArray<z.ZodEnum<["approve", "edit", "reject", "respond"]>, "many">;
|
|
271
281
|
/**
|
|
272
282
|
* The description attached to the request for human input.
|
|
273
283
|
* Can be either:
|
|
@@ -339,12 +349,12 @@ declare const contextSchema: z.ZodObject<{
|
|
|
339
349
|
*/
|
|
340
350
|
when: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCallRequest<AgentBuiltInState, unknown>, z.ZodTypeDef, ToolCallRequest<AgentBuiltInState, unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodBoolean, z.ZodPromise<z.ZodBoolean>]>>>;
|
|
341
351
|
}, "strip", z.ZodTypeAny, {
|
|
342
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
352
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
343
353
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
344
354
|
argsSchema?: Record<string, any> | undefined;
|
|
345
355
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
346
356
|
}, {
|
|
347
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
357
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
348
358
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
349
359
|
argsSchema?: Record<string, any> | undefined;
|
|
350
360
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
@@ -360,7 +370,7 @@ declare const contextSchema: z.ZodObject<{
|
|
|
360
370
|
descriptionPrefix: z.ZodDefault<z.ZodString>;
|
|
361
371
|
}, "strip", z.ZodTypeAny, {
|
|
362
372
|
interruptOn?: Record<string, boolean | {
|
|
363
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
373
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
364
374
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
365
375
|
argsSchema?: Record<string, any> | undefined;
|
|
366
376
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
@@ -368,14 +378,14 @@ declare const contextSchema: z.ZodObject<{
|
|
|
368
378
|
descriptionPrefix: string;
|
|
369
379
|
}, {
|
|
370
380
|
interruptOn?: Record<string, boolean | {
|
|
371
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
381
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
372
382
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
373
383
|
argsSchema?: Record<string, any> | undefined;
|
|
374
384
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
375
385
|
}> | undefined;
|
|
376
386
|
descriptionPrefix?: string | undefined;
|
|
377
387
|
}>;
|
|
378
|
-
type HumanInTheLoopMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;
|
|
388
|
+
export type HumanInTheLoopMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;
|
|
379
389
|
/**
|
|
380
390
|
* Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.
|
|
381
391
|
*
|
|
@@ -586,7 +596,7 @@ type HumanInTheLoopMiddlewareConfig = InferInteropZodInput<typeof contextSchema>
|
|
|
586
596
|
* @see {@link Command} for resuming interrupted execution
|
|
587
597
|
* @public
|
|
588
598
|
*/
|
|
589
|
-
declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMiddlewareConfig>): AgentMiddleware<undefined, z.ZodObject<{
|
|
599
|
+
export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMiddlewareConfig>): AgentMiddleware<undefined, z.ZodObject<{
|
|
590
600
|
/**
|
|
591
601
|
* Mapping of tool name to allowed reviewer responses.
|
|
592
602
|
* If a tool doesn't have an entry, it's auto-approved by default.
|
|
@@ -599,7 +609,7 @@ declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMid
|
|
|
599
609
|
/**
|
|
600
610
|
* The decisions that are allowed for this action.
|
|
601
611
|
*/
|
|
602
|
-
allowedDecisions: z.ZodArray<z.ZodEnum<["approve", "edit", "reject"]>, "many">;
|
|
612
|
+
allowedDecisions: z.ZodArray<z.ZodEnum<["approve", "edit", "reject", "respond"]>, "many">;
|
|
603
613
|
/**
|
|
604
614
|
* The description attached to the request for human input.
|
|
605
615
|
* Can be either:
|
|
@@ -671,12 +681,12 @@ declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMid
|
|
|
671
681
|
*/
|
|
672
682
|
when: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCallRequest<AgentBuiltInState, unknown>, z.ZodTypeDef, ToolCallRequest<AgentBuiltInState, unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodBoolean, z.ZodPromise<z.ZodBoolean>]>>>;
|
|
673
683
|
}, "strip", z.ZodTypeAny, {
|
|
674
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
684
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
675
685
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
676
686
|
argsSchema?: Record<string, any> | undefined;
|
|
677
687
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
678
688
|
}, {
|
|
679
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
689
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
680
690
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
681
691
|
argsSchema?: Record<string, any> | undefined;
|
|
682
692
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
@@ -692,7 +702,7 @@ declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMid
|
|
|
692
702
|
descriptionPrefix: z.ZodDefault<z.ZodString>;
|
|
693
703
|
}, "strip", z.ZodTypeAny, {
|
|
694
704
|
interruptOn?: Record<string, boolean | {
|
|
695
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
705
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
696
706
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
697
707
|
argsSchema?: Record<string, any> | undefined;
|
|
698
708
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
@@ -700,7 +710,7 @@ declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMid
|
|
|
700
710
|
descriptionPrefix: string;
|
|
701
711
|
}, {
|
|
702
712
|
interruptOn?: Record<string, boolean | {
|
|
703
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
713
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
704
714
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
705
715
|
argsSchema?: Record<string, any> | undefined;
|
|
706
716
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
@@ -708,7 +718,7 @@ declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMid
|
|
|
708
718
|
descriptionPrefix?: string | undefined;
|
|
709
719
|
}>, {
|
|
710
720
|
interruptOn?: Record<string, boolean | {
|
|
711
|
-
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
721
|
+
allowedDecisions: ("approve" | "edit" | "reject" | "respond")[];
|
|
712
722
|
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
713
723
|
argsSchema?: Record<string, any> | undefined;
|
|
714
724
|
when?: ((args_0: ToolCallRequest<AgentBuiltInState, unknown>, ...args: unknown[]) => boolean | Promise<boolean>) | undefined;
|
|
@@ -716,5 +726,5 @@ declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMid
|
|
|
716
726
|
descriptionPrefix: string;
|
|
717
727
|
}, readonly (import("@langchain/core/tools").ServerTool | import("@langchain/core/tools").ClientTool)[], readonly []>;
|
|
718
728
|
//#endregion
|
|
719
|
-
export {
|
|
729
|
+
export { DecisionType };
|
|
720
730
|
//# sourceMappingURL=hitl.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.d.cts","names":[],"sources":["../../../src/agents/middleware/hitl.ts"],"mappings":";;;;;;cAcM,oBAAkB,EAAA,YAAA,EAAA,UAAA,EAAA,QAAA,gBAAA,6BAAA,EAAA,YAAA,gBAAA,+BAAA,EAAA,aAAA,EAAA,UAAA,EAAA,YAAA,EAAA,WAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"hitl.d.cts","names":["_$__types_js0.AgentMiddleware"],"sources":["../../../src/agents/middleware/hitl.ts"],"mappings":";;;;;;cAcM,oBAAkB,EAAA,YAAA,EAAA,UAAA,EAAA,QAAA,gBAAA,6BAAA,EAAA,YAAA,gBAAA,+BAAA,EAAA,aAAA,EAAA,UAAA,EAAA,YAAA,EAAA,WAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;YA4BZ,gBAAgB,EAAE,aAAa;cAErC,2BAAyB,EAAA,YAAA,EAAA,UAAA,EAAA,QAAA,iBAAA,sBAAA,EAAA,YAAA,iBAAA,uBAAA,EAAA,QAAA,mBAAA,EAAA,YAAA,oBAAA,EAAA,QAAA,kBAAA,EAAA,YAAA,oBAAA,EAAA,aAAA,EAAA,UAAA,EAAA,WAAA,EAAA,WAAA,EAAA;;;;;;;;;;;;;;;;;;YA0BnB,qBAAqB,EAAE,aAAa;cAM1C,cAAY,EAAA;KACN,eAAe,EAAE,aAAa;cAGpC,yBAAuB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA4EjB,oBAAoB,EAAE,aAAa;;;;iBAK9B;;;;EAIf;;;;EAIA,MAAM;;;;;iBAMS;;;;EAIf;;;;EAIA,MAAM;;;;EAIN;;;;;iBAMe;;;;EAIf;;;;EAIA,kBAAkB;;;;EAIlB,aAAa;;;;;;;;;;;;;;;;;;;;;;iBAuBE;;;;EAIf,gBAAgB;;;;EAIhB,eAAe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