langchain 1.5.16 → 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 +10 -0
- package/dist/agents/middleware/hitl.cjs +24 -8
- package/dist/agents/middleware/hitl.cjs.map +1 -1
- package/dist/agents/middleware/hitl.d.cts +26 -16
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts +26 -16
- 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/browser.d.cts +2 -2
- package/dist/browser.d.ts +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# langchain
|
|
2
2
|
|
|
3
|
+
## 1.5.17
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#11956](https://github.com/langchain-ai/langchainjs/pull/11956) [`93d62b0`](https://github.com/langchain-ai/langchainjs/commit/93d62b008e13e10f28724a5ab09ab6eda584f1cb) Thanks [@hntrl](https://github.com/hntrl)! - Require langsmith >=0.11.0 to include the restored NullableHeaders type declarations.
|
|
8
|
+
|
|
9
|
+
- [#11498](https://github.com/langchain-ai/langchainjs/pull/11498) [`227f01c`](https://github.com/langchain-ai/langchainjs/commit/227f01c818996bf107dbcedc3e0ffa1620b7719e) Thanks [@xianjianlf2](https://github.com/xianjianlf2)! - feat(langchain): support HITL respond decisions
|
|
10
|
+
|
|
11
|
+
- [#11822](https://github.com/langchain-ai/langchainjs/pull/11822) [`d3e6fe6`](https://github.com/langchain-ai/langchainjs/commit/d3e6fe66a5f902fa615f076ca71d9541f1291166) Thanks [@dqbd](https://github.com/dqbd)! - Add explicit agent address support to `LangChainTracer`, inherit project and address destinations together, and delegate default destination resolution to the LangSmith SDK.
|
|
12
|
+
|
|
3
13
|
## 1.5.16
|
|
4
14
|
|
|
5
15
|
### Patch Changes
|
|
@@ -6,15 +6,17 @@ let zod_v3 = require("zod/v3");
|
|
|
6
6
|
//#region src/agents/middleware/hitl.ts
|
|
7
7
|
const WhenFunctionSchema = zod_v3.z.function().args(zod_v3.z.custom()).returns(zod_v3.z.union([zod_v3.z.boolean(), zod_v3.z.promise(zod_v3.z.boolean())]));
|
|
8
8
|
const DescriptionFunctionSchema = zod_v3.z.function().args(zod_v3.z.custom(), zod_v3.z.custom(), zod_v3.z.custom()).returns(zod_v3.z.union([zod_v3.z.string(), zod_v3.z.promise(zod_v3.z.string())]));
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
const DecisionType = zod_v3.z.enum([
|
|
10
|
+
"approve",
|
|
11
|
+
"edit",
|
|
12
|
+
"reject",
|
|
13
|
+
"respond"
|
|
14
|
+
]);
|
|
15
|
+
const DEFAULT_ALLOWED_DECISIONS = [
|
|
13
16
|
"approve",
|
|
14
17
|
"edit",
|
|
15
18
|
"reject"
|
|
16
19
|
];
|
|
17
|
-
const DecisionType = zod_v3.z.enum(ALLOWED_DECISIONS);
|
|
18
20
|
const InterruptOnConfigSchema = zod_v3.z.object({
|
|
19
21
|
/**
|
|
20
22
|
* The decisions that are allowed for this action.
|
|
@@ -405,6 +407,18 @@ function humanInTheLoopMiddleware(options) {
|
|
|
405
407
|
})
|
|
406
408
|
};
|
|
407
409
|
}
|
|
410
|
+
if (decision.type === "respond" && allowedDecisions.includes("respond")) {
|
|
411
|
+
if (typeof decision.message !== "string") throw new Error(`Tool call response for "${toolCall.name}" must be a string, got ${typeof decision.message}`);
|
|
412
|
+
return {
|
|
413
|
+
revisedToolCall: toolCall,
|
|
414
|
+
toolMessage: new _langchain_core_messages.ToolMessage({
|
|
415
|
+
content: decision.message,
|
|
416
|
+
name: toolCall.name,
|
|
417
|
+
tool_call_id: toolCall.id,
|
|
418
|
+
status: "success"
|
|
419
|
+
})
|
|
420
|
+
};
|
|
421
|
+
}
|
|
408
422
|
const msg = `Unexpected human decision: ${JSON.stringify(decision)}. Decision type '${decision.type}' is not allowed for tool '${toolCall.name}'. Expected one of ${JSON.stringify(allowedDecisions)} based on the tool's configuration.`;
|
|
409
423
|
throw new Error(msg);
|
|
410
424
|
};
|
|
@@ -435,7 +449,7 @@ function humanInTheLoopMiddleware(options) {
|
|
|
435
449
|
*/
|
|
436
450
|
const resolvedConfigs = {};
|
|
437
451
|
for (const [toolName, toolConfig] of Object.entries(config.interruptOn)) if (typeof toolConfig === "boolean") {
|
|
438
|
-
if (toolConfig === true) resolvedConfigs[toolName] = { allowedDecisions: [...
|
|
452
|
+
if (toolConfig === true) resolvedConfigs[toolName] = { allowedDecisions: [...DEFAULT_ALLOWED_DECISIONS] };
|
|
439
453
|
} else if (toolConfig.allowedDecisions) resolvedConfigs[toolName] = toolConfig;
|
|
440
454
|
const interruptToolCalls = [];
|
|
441
455
|
const autoApprovedToolCalls = [];
|
|
@@ -482,6 +496,7 @@ function humanInTheLoopMiddleware(options) {
|
|
|
482
496
|
const revisedToolCalls = [...autoApprovedToolCalls];
|
|
483
497
|
const artificialToolMessages = [];
|
|
484
498
|
const hasRejectedToolCalls = decisions.some((decision) => decision.type === "reject");
|
|
499
|
+
const hasRespondedToolCalls = decisions.some((decision) => decision.type === "respond");
|
|
485
500
|
/**
|
|
486
501
|
* Process each decision using helper method
|
|
487
502
|
*/
|
|
@@ -490,14 +505,15 @@ function humanInTheLoopMiddleware(options) {
|
|
|
490
505
|
const toolCall = interruptToolCalls[i];
|
|
491
506
|
const interruptConfig = resolvedConfigs[toolCall.name];
|
|
492
507
|
const { revisedToolCall, toolMessage } = processDecision(decision, toolCall, interruptConfig);
|
|
493
|
-
if (revisedToolCall && (!hasRejectedToolCalls || decision.type === "reject")) revisedToolCalls.push(revisedToolCall);
|
|
508
|
+
if (revisedToolCall && (!hasRejectedToolCalls || decision.type === "reject" || decision.type === "respond")) revisedToolCalls.push(revisedToolCall);
|
|
494
509
|
if (toolMessage) artificialToolMessages.push(toolMessage);
|
|
495
510
|
}
|
|
496
511
|
/**
|
|
497
512
|
* Update the AI message to only include approved tool calls
|
|
498
513
|
*/
|
|
499
514
|
if (_langchain_core_messages.AIMessage.isInstance(lastMessage)) lastMessage.tool_calls = revisedToolCalls;
|
|
500
|
-
const
|
|
515
|
+
const hasPendingToolCalls = revisedToolCalls.some((toolCall) => !artificialToolMessages.some((message) => message.tool_call_id === toolCall.id));
|
|
516
|
+
const jumpTo = hasRejectedToolCalls || hasRespondedToolCalls && !hasPendingToolCalls ? "model" : void 0;
|
|
501
517
|
return {
|
|
502
518
|
messages: [lastMessage, ...artificialToolMessages],
|
|
503
519
|
jumpTo
|
|
@@ -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,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,CAAC,CACA,QAAQA,OAAAA,EAAE,MAAM,CAACA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQA,OAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;;;;AAwBvD,MAAM,oBAAoB;CAAC;CAAW;CAAQ;AAAQ;AACtD,MAAM,eAAeA,OAAAA,EAAE,KAAK,iBAAiB;AAG7C,MAAM,0BAA0BA,OAAAA,EAAE,OAAO;;;;CAIvC,kBAAkBA,OAAAA,EAAE,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CtC,aAAaA,OAAAA,EAAE,MAAM,CAACA,OAAAA,EAAE,OAAO,GAAG,yBAAyB,CAAC,CAAC,CAAC,SAAS;;;;CAIvE,YAAYA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS;;;;;;;;;;;;;;;;;;;;;;CAsBvC,MAAM,mBAAmB,S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C;KACA;IAM8C,CAAC,EAAA,CAClB;;;;IAK/B,IAAI,CAAC,aAAa,CAAC,MAAM,QAAQ,SAAS,GACxC,MAAM,IAAI,MACR,2DACF;;;;IAMF,IAAI,UAAU,WAAW,mBAAmB,QAC1C,MAAM,IAAI,MACR,8BAA8B,UAAU,OAAO,iDAAiD,mBAAmB,OAAO,GAC5H;IAGF,MAAM,mBAA+B,CAAC,GAAG,qBAAqB;IAC9D,MAAM,yBAAwC,CAAC;IAC/C,MAAM,uBAAuB,UAAU,MACpC,aAAa,SAAS,SAAS,QAClC;;;;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,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,q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export type DescriptionFactory = z.infer<typeof DescriptionFunctionSchema>;
|
|
51
|
-
declare const DecisionType: z.ZodEnum<["approve", "edit", "reject"]>;
|
|
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,12 +126,12 @@ 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;
|
|
@@ -241,10 +241,20 @@ export interface RejectDecision {
|
|
|
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
|
-
export type Decision = ApproveDecision | EditDecision | RejectDecision;
|
|
257
|
+
export type Decision = ApproveDecision | EditDecision | RejectDecision | RespondDecision;
|
|
248
258
|
/**
|
|
249
259
|
* Response payload for a HITLRequest.
|
|
250
260
|
*/
|
|
@@ -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,7 +378,7 @@ 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;
|
|
@@ -599,7 +609,7 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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;
|
|
@@ -1 +1 @@
|
|
|
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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Me;EACf;;;;;EAKA,cAAc;;;;;iBAMC;EACf;;;;EAIA;;;;;iBAMe;EACf;;;;EAIA;;;;;YAMU,WACR,kBACA,eACA,iBACA;;;;iBAKa;;;;EAIf,WAAW;;cAGP,eAAa,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAsBP,iCAAiC,4BACpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAqNO,yBACd,SAAS,YAAY,6DAA+B,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6CAqXrD,6CAAA"}
|
|
@@ -48,13 +48,13 @@ declare const DescriptionFunctionSchema: z.ZodFunction<z.ZodTuple<[z.ZodType<Too
|
|
|
48
48
|
* ```
|
|
49
49
|
*/
|
|
50
50
|
export type DescriptionFactory = z.infer<typeof DescriptionFunctionSchema>;
|
|
51
|
-
declare const DecisionType: z.ZodEnum<["approve", "edit", "reject"]>;
|
|
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,12 +126,12 @@ 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;
|
|
@@ -241,10 +241,20 @@ export interface RejectDecision {
|
|
|
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
|
-
export type Decision = ApproveDecision | EditDecision | RejectDecision;
|
|
257
|
+
export type Decision = ApproveDecision | EditDecision | RejectDecision | RespondDecision;
|
|
248
258
|
/**
|
|
249
259
|
* Response payload for a HITLRequest.
|
|
250
260
|
*/
|
|
@@ -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,7 +378,7 @@ 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;
|
|
@@ -599,7 +609,7 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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 @@ export declare function humanInTheLoopMiddleware(options: NonNullable<HumanInThe
|
|
|
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;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.d.ts","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;
|
|
1
|
+
{"version":3,"file":"hitl.d.ts","names":["_$__types_js0.AgentMiddleware"],"sources":["../../../src/agents/middleware/hitl.ts"],"m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BACpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAqNO,yBACd,SAAS,YAAY,6DAA+B,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6CAqXrD,6CAAA"}
|
|
@@ -6,15 +6,17 @@ import { z } from "zod/v3";
|
|
|
6
6
|
//#region src/agents/middleware/hitl.ts
|
|
7
7
|
const WhenFunctionSchema = z.function().args(z.custom()).returns(z.union([z.boolean(), z.promise(z.boolean())]));
|
|
8
8
|
const DescriptionFunctionSchema = z.function().args(z.custom(), z.custom(), z.custom()).returns(z.union([z.string(), z.promise(z.string())]));
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
const DecisionType = z.enum([
|
|
10
|
+
"approve",
|
|
11
|
+
"edit",
|
|
12
|
+
"reject",
|
|
13
|
+
"respond"
|
|
14
|
+
]);
|
|
15
|
+
const DEFAULT_ALLOWED_DECISIONS = [
|
|
13
16
|
"approve",
|
|
14
17
|
"edit",
|
|
15
18
|
"reject"
|
|
16
19
|
];
|
|
17
|
-
const DecisionType = z.enum(ALLOWED_DECISIONS);
|
|
18
20
|
const InterruptOnConfigSchema = z.object({
|
|
19
21
|
/**
|
|
20
22
|
* The decisions that are allowed for this action.
|
|
@@ -405,6 +407,18 @@ function humanInTheLoopMiddleware(options) {
|
|
|
405
407
|
})
|
|
406
408
|
};
|
|
407
409
|
}
|
|
410
|
+
if (decision.type === "respond" && allowedDecisions.includes("respond")) {
|
|
411
|
+
if (typeof decision.message !== "string") throw new Error(`Tool call response for "${toolCall.name}" must be a string, got ${typeof decision.message}`);
|
|
412
|
+
return {
|
|
413
|
+
revisedToolCall: toolCall,
|
|
414
|
+
toolMessage: new ToolMessage({
|
|
415
|
+
content: decision.message,
|
|
416
|
+
name: toolCall.name,
|
|
417
|
+
tool_call_id: toolCall.id,
|
|
418
|
+
status: "success"
|
|
419
|
+
})
|
|
420
|
+
};
|
|
421
|
+
}
|
|
408
422
|
const msg = `Unexpected human decision: ${JSON.stringify(decision)}. Decision type '${decision.type}' is not allowed for tool '${toolCall.name}'. Expected one of ${JSON.stringify(allowedDecisions)} based on the tool's configuration.`;
|
|
409
423
|
throw new Error(msg);
|
|
410
424
|
};
|
|
@@ -435,7 +449,7 @@ function humanInTheLoopMiddleware(options) {
|
|
|
435
449
|
*/
|
|
436
450
|
const resolvedConfigs = {};
|
|
437
451
|
for (const [toolName, toolConfig] of Object.entries(config.interruptOn)) if (typeof toolConfig === "boolean") {
|
|
438
|
-
if (toolConfig === true) resolvedConfigs[toolName] = { allowedDecisions: [...
|
|
452
|
+
if (toolConfig === true) resolvedConfigs[toolName] = { allowedDecisions: [...DEFAULT_ALLOWED_DECISIONS] };
|
|
439
453
|
} else if (toolConfig.allowedDecisions) resolvedConfigs[toolName] = toolConfig;
|
|
440
454
|
const interruptToolCalls = [];
|
|
441
455
|
const autoApprovedToolCalls = [];
|
|
@@ -482,6 +496,7 @@ function humanInTheLoopMiddleware(options) {
|
|
|
482
496
|
const revisedToolCalls = [...autoApprovedToolCalls];
|
|
483
497
|
const artificialToolMessages = [];
|
|
484
498
|
const hasRejectedToolCalls = decisions.some((decision) => decision.type === "reject");
|
|
499
|
+
const hasRespondedToolCalls = decisions.some((decision) => decision.type === "respond");
|
|
485
500
|
/**
|
|
486
501
|
* Process each decision using helper method
|
|
487
502
|
*/
|
|
@@ -490,14 +505,15 @@ function humanInTheLoopMiddleware(options) {
|
|
|
490
505
|
const toolCall = interruptToolCalls[i];
|
|
491
506
|
const interruptConfig = resolvedConfigs[toolCall.name];
|
|
492
507
|
const { revisedToolCall, toolMessage } = processDecision(decision, toolCall, interruptConfig);
|
|
493
|
-
if (revisedToolCall && (!hasRejectedToolCalls || decision.type === "reject")) revisedToolCalls.push(revisedToolCall);
|
|
508
|
+
if (revisedToolCall && (!hasRejectedToolCalls || decision.type === "reject" || decision.type === "respond")) revisedToolCalls.push(revisedToolCall);
|
|
494
509
|
if (toolMessage) artificialToolMessages.push(toolMessage);
|
|
495
510
|
}
|
|
496
511
|
/**
|
|
497
512
|
* Update the AI message to only include approved tool calls
|
|
498
513
|
*/
|
|
499
514
|
if (AIMessage.isInstance(lastMessage)) lastMessage.tool_calls = revisedToolCalls;
|
|
500
|
-
const
|
|
515
|
+
const hasPendingToolCalls = revisedToolCalls.some((toolCall) => !artificialToolMessages.some((message) => message.tool_call_id === toolCall.id));
|
|
516
|
+
const jumpTo = hasRejectedToolCalls || hasRespondedToolCalls && !hasPendingToolCalls ? "model" : void 0;
|
|
501
517
|
return {
|
|
502
518
|
messages: [lastMessage, ...artificialToolMessages],
|
|
503
519
|
jumpTo
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.js","names":[],"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,qBAAqB,EACxB,SAAS,CAAC,CACV,KAAK,EAAE,OAA2C,CAAC,CAAC,CACpD,QAAQ,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;AA2BzD,MAAM,4BAA4B,EAC/B,SAAS,CAAC,CACV,KACC,EAAE,OAAiB,GACnB,EAAE,OAA0B,GAC5B,EAAE,OAAyB,CAC7B,CAAC,CACA,QAAQ,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;;;;AAwBvD,MAAM,oBAAoB;CAAC;CAAW;CAAQ;AAAQ;AACtD,MAAM,eAAe,EAAE,KAAK,iBAAiB;AAG7C,MAAM,0BAA0B,EAAE,OAAO;;;;CAIvC,kBAAkB,EAAE,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CtC,aAAa,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,yBAAyB,CAAC,CAAC,CAAC,SAAS;;;;CAIvE,YAAY,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS;;;;;;;;;;;;;;;;;;;;;;CAsBvC,MAAM,mBAAmB,SAAS;AACpC,CAAC;A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,UAAU,WAAW,mBAAmB,QAC1C,MAAM,IAAI,MACR,8BAA8B,UAAU,OAAO,iDAAiD,mBAAmB,OAAO,GAC5H;IAGF,MAAM,mBAA+B,CAAC,GAAG,qBAAqB;IAC9D,MAAM,yBAAwC,CAAC;IAC/C,MAAM,uBAAuB,UAAU,MACpC,aAAa,SAAS,SAAS,QAClC;;;;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,wBAAwB,SAAS,SAAS,WAE5C,iBAAiB,KAAK,eAAe;KAEvC,IAAI,aACF,uBAAuB,KAAK,WAAW;IAE3C;;;;IAKA,IAAI,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.js","names":[],"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,qBAAqB,EACxB,SAAS,CAAC,CACV,KAAK,EAAE,OAA2C,CAAC,CAAC,CACpD,QAAQ,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;AA2BzD,MAAM,4B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;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,IAAI,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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AgentMiddleware } from "./types.cjs";
|
|
2
|
-
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./hitl.cjs";
|
|
2
|
+
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, RespondDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./hitl.cjs";
|
|
3
3
|
import { SummarizationMiddlewareConfig, TokenCounter, summarizationMiddleware } from "./summarization.cjs";
|
|
4
4
|
import { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware } from "./dynamicSystemPrompt.cjs";
|
|
5
5
|
import { LLMToolSelectorConfig, llmToolSelectorMiddleware } from "./llmToolSelector.cjs";
|
|
@@ -19,4 +19,4 @@ import { OpenAIModerationMiddlewareOptions, openAIModerationMiddleware } from ".
|
|
|
19
19
|
import { PromptCachingMiddlewareConfig, anthropicPromptCachingMiddleware } from "./provider/anthropic/promptCaching.cjs";
|
|
20
20
|
import { BedrockConversePromptCachingMiddlewareConfig, bedrockPromptCachingMiddleware } from "./provider/aws/promptCaching.cjs";
|
|
21
21
|
import { countTokensApproximately } from "./utils.cjs";
|
|
22
|
-
export { Action, ActionRequest, ApproveDecision, type BedrockConversePromptCachingMiddlewareConfig, type BuiltInPIIType, ClearToolUsesEdit, type ClearToolUsesEditConfig, type ContextEdit, type ContextEditingMiddlewareConfig, Decision, DecisionType, DescriptionFactory, type DynamicSystemPromptMiddlewareConfig, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, type LLMToolSelectorConfig, type ModelCallLimitMiddlewareConfig, type ModelRetryMiddlewareConfig, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, type ProviderToolSearchMiddlewareConfig, type RedactionRuleConfig, RejectDecision, type ResolvedRedactionRule, ReviewConfig, type SummarizationMiddlewareConfig, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type Todo, type TodoListMiddlewareOptions, type TokenCounter, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, type ToolRetryMiddlewareConfig, WhenPredicate, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, contextEditingMiddleware, countTokensApproximately, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, humanInTheLoopMiddleware, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware };
|
|
22
|
+
export { Action, ActionRequest, ApproveDecision, type BedrockConversePromptCachingMiddlewareConfig, type BuiltInPIIType, ClearToolUsesEdit, type ClearToolUsesEditConfig, type ContextEdit, type ContextEditingMiddlewareConfig, Decision, DecisionType, DescriptionFactory, type DynamicSystemPromptMiddlewareConfig, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, type LLMToolSelectorConfig, type ModelCallLimitMiddlewareConfig, type ModelRetryMiddlewareConfig, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, type ProviderToolSearchMiddlewareConfig, type RedactionRuleConfig, RejectDecision, type ResolvedRedactionRule, RespondDecision, ReviewConfig, type SummarizationMiddlewareConfig, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type Todo, type TodoListMiddlewareOptions, type TokenCounter, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, type ToolRetryMiddlewareConfig, WhenPredicate, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, contextEditingMiddleware, countTokensApproximately, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, humanInTheLoopMiddleware, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AgentMiddleware } from "./types.js";
|
|
2
|
-
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./hitl.js";
|
|
2
|
+
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, RespondDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./hitl.js";
|
|
3
3
|
import { SummarizationMiddlewareConfig, TokenCounter, summarizationMiddleware } from "./summarization.js";
|
|
4
4
|
import { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware } from "./dynamicSystemPrompt.js";
|
|
5
5
|
import { LLMToolSelectorConfig, llmToolSelectorMiddleware } from "./llmToolSelector.js";
|
|
@@ -19,4 +19,4 @@ import { OpenAIModerationMiddlewareOptions, openAIModerationMiddleware } from ".
|
|
|
19
19
|
import { PromptCachingMiddlewareConfig, anthropicPromptCachingMiddleware } from "./provider/anthropic/promptCaching.js";
|
|
20
20
|
import { BedrockConversePromptCachingMiddlewareConfig, bedrockPromptCachingMiddleware } from "./provider/aws/promptCaching.js";
|
|
21
21
|
import { countTokensApproximately } from "./utils.js";
|
|
22
|
-
export { Action, ActionRequest, ApproveDecision, type BedrockConversePromptCachingMiddlewareConfig, type BuiltInPIIType, ClearToolUsesEdit, type ClearToolUsesEditConfig, type ContextEdit, type ContextEditingMiddlewareConfig, Decision, DecisionType, DescriptionFactory, type DynamicSystemPromptMiddlewareConfig, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, type LLMToolSelectorConfig, type ModelCallLimitMiddlewareConfig, type ModelRetryMiddlewareConfig, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, type ProviderToolSearchMiddlewareConfig, type RedactionRuleConfig, RejectDecision, type ResolvedRedactionRule, ReviewConfig, type SummarizationMiddlewareConfig, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type Todo, type TodoListMiddlewareOptions, type TokenCounter, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, type ToolRetryMiddlewareConfig, WhenPredicate, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, contextEditingMiddleware, countTokensApproximately, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, humanInTheLoopMiddleware, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware };
|
|
22
|
+
export { Action, ActionRequest, ApproveDecision, type BedrockConversePromptCachingMiddlewareConfig, type BuiltInPIIType, ClearToolUsesEdit, type ClearToolUsesEditConfig, type ContextEdit, type ContextEditingMiddlewareConfig, Decision, DecisionType, DescriptionFactory, type DynamicSystemPromptMiddlewareConfig, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, type LLMToolSelectorConfig, type ModelCallLimitMiddlewareConfig, type ModelRetryMiddlewareConfig, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, type ProviderToolSearchMiddlewareConfig, type RedactionRuleConfig, RejectDecision, type ResolvedRedactionRule, RespondDecision, ReviewConfig, type SummarizationMiddlewareConfig, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type Todo, type TodoListMiddlewareOptions, type TokenCounter, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, type ToolRetryMiddlewareConfig, WhenPredicate, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, contextEditingMiddleware, countTokensApproximately, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, humanInTheLoopMiddleware, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware };
|
package/dist/browser.d.cts
CHANGED
|
@@ -14,7 +14,7 @@ import { ReactAgent } from "./agents/ReactAgent.cjs";
|
|
|
14
14
|
import { createMiddleware } from "./agents/middleware.cjs";
|
|
15
15
|
import { FakeToolCallingModel } from "./agents/tests/utils.cjs";
|
|
16
16
|
import { createAgent } from "./agents/index.cjs";
|
|
17
|
-
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./agents/middleware/hitl.cjs";
|
|
17
|
+
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, RespondDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./agents/middleware/hitl.cjs";
|
|
18
18
|
import { SummarizationMiddlewareConfig, TokenCounter, summarizationMiddleware } from "./agents/middleware/summarization.cjs";
|
|
19
19
|
import { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware } from "./agents/middleware/dynamicSystemPrompt.cjs";
|
|
20
20
|
import { LLMToolSelectorConfig, llmToolSelectorMiddleware } from "./agents/middleware/llmToolSelector.cjs";
|
|
@@ -41,4 +41,4 @@ import { context } from "@langchain/core/utils/context";
|
|
|
41
41
|
import { InMemoryStore } from "@langchain/core/stores";
|
|
42
42
|
import { Document, DocumentInput } from "@langchain/core/documents";
|
|
43
43
|
import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
|
|
44
|
-
export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
|
44
|
+
export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
package/dist/browser.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { ReactAgent } from "./agents/ReactAgent.js";
|
|
|
14
14
|
import { createMiddleware } from "./agents/middleware.js";
|
|
15
15
|
import { FakeToolCallingModel } from "./agents/tests/utils.js";
|
|
16
16
|
import { createAgent } from "./agents/index.js";
|
|
17
|
-
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./agents/middleware/hitl.js";
|
|
17
|
+
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, RespondDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./agents/middleware/hitl.js";
|
|
18
18
|
import { SummarizationMiddlewareConfig, TokenCounter, summarizationMiddleware } from "./agents/middleware/summarization.js";
|
|
19
19
|
import { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware } from "./agents/middleware/dynamicSystemPrompt.js";
|
|
20
20
|
import { LLMToolSelectorConfig, llmToolSelectorMiddleware } from "./agents/middleware/llmToolSelector.js";
|
|
@@ -41,4 +41,4 @@ import { context } from "@langchain/core/utils/context";
|
|
|
41
41
|
import { InMemoryStore } from "@langchain/core/stores";
|
|
42
42
|
import { Document, DocumentInput } from "@langchain/core/documents";
|
|
43
43
|
import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
|
|
44
|
-
export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
|
44
|
+
export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
package/dist/index.d.cts
CHANGED
|
@@ -14,7 +14,7 @@ import { ReactAgent } from "./agents/ReactAgent.cjs";
|
|
|
14
14
|
import { createMiddleware } from "./agents/middleware.cjs";
|
|
15
15
|
import { FakeToolCallingModel } from "./agents/tests/utils.cjs";
|
|
16
16
|
import { createAgent } from "./agents/index.cjs";
|
|
17
|
-
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./agents/middleware/hitl.cjs";
|
|
17
|
+
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, RespondDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./agents/middleware/hitl.cjs";
|
|
18
18
|
import { SummarizationMiddlewareConfig, TokenCounter, summarizationMiddleware } from "./agents/middleware/summarization.cjs";
|
|
19
19
|
import { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware } from "./agents/middleware/dynamicSystemPrompt.cjs";
|
|
20
20
|
import { LLMToolSelectorConfig, llmToolSelectorMiddleware } from "./agents/middleware/llmToolSelector.cjs";
|
|
@@ -41,4 +41,4 @@ import { context } from "@langchain/core/utils/context";
|
|
|
41
41
|
import { InMemoryStore } from "@langchain/core/stores";
|
|
42
42
|
import { Document, DocumentInput } from "@langchain/core/documents";
|
|
43
43
|
import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
|
|
44
|
-
export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
|
44
|
+
export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
package/dist/index.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { ReactAgent } from "./agents/ReactAgent.js";
|
|
|
14
14
|
import { createMiddleware } from "./agents/middleware.js";
|
|
15
15
|
import { FakeToolCallingModel } from "./agents/tests/utils.js";
|
|
16
16
|
import { createAgent } from "./agents/index.js";
|
|
17
|
-
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./agents/middleware/hitl.js";
|
|
17
|
+
import { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, RespondDecision, ReviewConfig, WhenPredicate, humanInTheLoopMiddleware } from "./agents/middleware/hitl.js";
|
|
18
18
|
import { SummarizationMiddlewareConfig, TokenCounter, summarizationMiddleware } from "./agents/middleware/summarization.js";
|
|
19
19
|
import { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware } from "./agents/middleware/dynamicSystemPrompt.js";
|
|
20
20
|
import { LLMToolSelectorConfig, llmToolSelectorMiddleware } from "./agents/middleware/llmToolSelector.js";
|
|
@@ -41,4 +41,4 @@ import { context } from "@langchain/core/utils/context";
|
|
|
41
41
|
import { InMemoryStore } from "@langchain/core/stores";
|
|
42
42
|
import { Document, DocumentInput } from "@langchain/core/documents";
|
|
43
43
|
import { LangChainMatchers, fakeModel, langchainMatchers } from "@langchain/core/testing";
|
|
44
|
-
export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
|
44
|
+
export { AIMessage, AIMessageChunk, Action, ActionRequest, type AfterAgentHook, type AfterModelHook, type AgentMiddleware, type AgentRunStream, AgentTypeConfig, type AnyAgentMiddleware, type AnyAnnotationRoot, ApproveDecision, BaseMessage, BaseMessageChunk, type BedrockConversePromptCachingMiddlewareConfig, type BeforeAgentHook, type BeforeModelHook, type BuiltInPIIType, BuiltInState, ClearToolUsesEdit, type ClearToolUsesEditConfig, CombineStreamTransformers, CombineTools, type ContentBlock, type ContextEdit, type ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DefaultAgentTypeConfig, type DefaultMiddlewareTypeConfig, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, type DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, type HeadlessTool, type HeadlessToolFields, type HeadlessToolImplementation, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentStreamTransformers, InferAgentTools, InferAgentType, type InferChannelType, type InferContextInput, type InferMergedInputState, type InferMergedState, type InferMiddlewareContext, type InferMiddlewareContextInput, type InferMiddlewareContextInputs, type InferMiddlewareContextSchema, type InferMiddlewareContexts, type InferMiddlewareFullContext, type InferMiddlewareInputState, type InferMiddlewareInputStates, type InferMiddlewareSchema, type InferMiddlewareState, type InferMiddlewareStates, InferMiddlewareStreamTransformers, InferMiddlewareStreamTransformersArray, type InferMiddlewareStreamTransformersFromConfig, InferMiddlewareTools, InferMiddlewareToolsArray, type InferMiddlewareToolsFromConfig, type InferMiddlewareType, type InferSchemaInput, type InferSchemaUpdateType, type InferSchemaValue, type InferSchemaValueType, Interrupt, InterruptOnConfig, JumpTo, type JumpToTarget, type LLMToolSelectorConfig, type LangChainMatchers, MIDDLEWARE_BRAND, MiddlewareError, type MiddlewareResult, type MiddlewareTypeConfig, type ModelCallLimitMiddlewareConfig, ModelRequest, type ModelRetryMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, type NormalizedSchemaInput, type NormalizedSchemaUpdate, type OpenAIModerationMiddlewareOptions, PIIDetectionError, type PIIDetector, type PIIMatch, type PIIMiddlewareConfig, type PIIRedactionMiddlewareConfig, type PIIStrategy, type PromptCachingMiddlewareConfig, ProviderStrategy, type ProviderToolSearchMiddlewareConfig, type ReactAgent, type RedactionRuleConfig, RejectDecision, ResolveAgentTypeConfig, type ResolveMiddlewareTypeConfig, type ResolvedRedactionRule, RespondDecision, type ResponseFormat, type ResponseFormatUndefined, ReviewConfig, type Runtime, StructuredOutputParsingError, StructuredTool, type SubagentRunStream, type SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, type ToAnnotationRoot, type Todo, type TodoListMiddlewareOptions, type TokenCounter, Tool, ToolCall, type ToolCallHandler, type ToolCallLimitConfig, ToolCallLimitExceededError, type ToolCallRequest, type ToolCallStreamUnion, type ToolEmulatorOptions, type ToolErrorHandler, type ToolErrorMiddlewareConfig, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, type ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, ToolsToMessageToolSet, type TypedToolStrategy, UserInput, WhenPredicate, WithStateGraphNodes, type WrapModelCallHandler, type WrapModelCallHook, type WrapToolCallHook, anthropicPromptCachingMiddleware, applyStrategy, bedrockPromptCachingMiddleware, context, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, createSubagentTransformer, createToolCallTransformer, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, dynamicSystemPromptMiddleware, fakeModel, filterMessages, humanInTheLoopMiddleware, initChatModel, langchainMatchers, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, modelRetryMiddleware, openAIModerationMiddleware, piiMiddleware, piiRedactionMiddleware, providerStrategy, providerToolSearchMiddleware, resolveRedactionRule, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolEmulatorMiddleware, toolErrorMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "langchain",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.17",
|
|
4
4
|
"description": "Typescript bindings for langchain",
|
|
5
5
|
"author": "LangChain",
|
|
6
6
|
"license": "MIT",
|
|
@@ -54,19 +54,19 @@
|
|
|
54
54
|
"vitest": "^5.0.2",
|
|
55
55
|
"yaml": "^2.9.1",
|
|
56
56
|
"@langchain/anthropic": "1.5.12",
|
|
57
|
-
"@langchain/aws": "1.4.
|
|
58
|
-
"@langchain/core": "^1.2.
|
|
59
|
-
"@langchain/openai": "1.6.2",
|
|
57
|
+
"@langchain/aws": "1.4.7",
|
|
58
|
+
"@langchain/core": "^1.2.18",
|
|
60
59
|
"@langchain/fireworks": "0.2.17",
|
|
60
|
+
"@langchain/openai": "1.6.2",
|
|
61
61
|
"@langchain/tsconfig": "0.0.1"
|
|
62
62
|
},
|
|
63
63
|
"peerDependencies": {
|
|
64
|
-
"@langchain/core": "^1.2.
|
|
64
|
+
"@langchain/core": "^1.2.18"
|
|
65
65
|
},
|
|
66
66
|
"dependencies": {
|
|
67
67
|
"@langchain/langgraph": "^1.4.18",
|
|
68
68
|
"@langchain/langgraph-checkpoint": "^1.1.5",
|
|
69
|
-
"langsmith": ">=0.
|
|
69
|
+
"langsmith": ">=0.11.0 <1.0.0",
|
|
70
70
|
"zod": "^3.25.76 || ^4"
|
|
71
71
|
},
|
|
72
72
|
"publishConfig": {
|