@librechat/agents 3.4.4 → 3.4.5

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.
@@ -0,0 +1,66 @@
1
+ const require_askUserQuestionsInterrupt = require("./askUserQuestionsInterrupt.cjs");
2
+ let _langchain_langgraph = require("@langchain/langgraph");
3
+ //#region src/hitl/askUserQuestions.ts
4
+ function validateQuestions(questions) {
5
+ if (questions.length === 0) throw new RangeError("askUserQuestions requires at least one question.");
6
+ if (questions.length > 4) throw new RangeError(`askUserQuestions accepts at most 4 questions.`);
7
+ const ids = /* @__PURE__ */ new Set();
8
+ for (const question of questions) {
9
+ if (!require_askUserQuestionsInterrupt.isAskUserQuestionRequest(question)) throw new TypeError("askUserQuestions requires each question and option to have valid string fields.");
10
+ if (!require_askUserQuestionsInterrupt.ASK_USER_QUESTION_ID_PATTERN.test(question.id)) throw new Error("askUserQuestions requires each question id to match [A-Za-z][A-Za-z0-9_-]{0,63}.");
11
+ if (ids.has(question.id)) throw new Error(`askUserQuestions requires unique question ids; received "${question.id}" more than once.`);
12
+ ids.add(question.id);
13
+ }
14
+ return questions[0];
15
+ }
16
+ function validateResolution(value, questions) {
17
+ if (typeof value !== "object" || value === null) throw new TypeError("askUserQuestions requires an answers object.");
18
+ const answers = value.answers;
19
+ if (typeof answers !== "object" || answers === null || Array.isArray(answers)) throw new TypeError("askUserQuestions requires an answers object.");
20
+ const validated = {};
21
+ for (const question of questions) {
22
+ const descriptor = Object.getOwnPropertyDescriptor(answers, question.id);
23
+ const answer = descriptor?.value;
24
+ if (descriptor == null || typeof answer !== "string") throw new TypeError(`askUserQuestions requires a string answer for question id "${question.id}".`);
25
+ validated[question.id] = answer;
26
+ }
27
+ return { answers: validated };
28
+ }
29
+ /**
30
+ * Suspend once to collect answers to several related questions. The first
31
+ * question is also included in the legacy `question` field so existing hosts
32
+ * can render a useful fallback during a staged rollout.
33
+ *
34
+ * Question ids must be non-empty and unique within the batch. The helper
35
+ * accepts at most four questions so hosts can render the interaction as one
36
+ * focused decision surface rather than an unbounded form.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const { answers } = askUserQuestions({
41
+ * questions: [
42
+ * { id: 'environment', question: 'Which environment?' },
43
+ * { id: 'region', question: 'Which region?' },
44
+ * ],
45
+ * });
46
+ * return `Deploy to ${answers.environment} in ${answers.region}`;
47
+ * ```
48
+ */
49
+ function askUserQuestions(request, options) {
50
+ const first = validateQuestions(request.questions);
51
+ return validateResolution((0, _langchain_langgraph.interrupt)({
52
+ type: "ask_user_question",
53
+ question: {
54
+ question: first.question,
55
+ ...first.description != null && { description: first.description },
56
+ ...first.options != null && { options: first.options },
57
+ ...first.multiSelect != null && { multiSelect: first.multiSelect }
58
+ },
59
+ questions: request.questions,
60
+ ...options?.toolCallId != null && options.toolCallId !== "" && { tool_call_id: options.toolCallId }
61
+ }), request.questions);
62
+ }
63
+ //#endregion
64
+ exports.askUserQuestions = askUserQuestions;
65
+
66
+ //# sourceMappingURL=askUserQuestions.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"askUserQuestions.cjs","names":["isAskUserQuestionRequest","ASK_USER_QUESTION_ID_PATTERN"],"sources":["../../../src/hitl/askUserQuestions.ts"],"sourcesContent":["import { interrupt } from '@langchain/langgraph';\nimport type {\n AskUserQuestionBatchItem,\n AskUserQuestionRequest,\n AskUserQuestionsInterruptPayload,\n AskUserQuestionsRequest,\n AskUserQuestionsResolution,\n} from '@/types/hitl';\nimport {\n ASK_USER_QUESTION_ID_PATTERN,\n isAskUserQuestionRequest,\n MAX_ASK_USER_QUESTIONS,\n} from './askUserQuestionsInterrupt';\n\nfunction validateQuestions(\n questions: readonly AskUserQuestionBatchItem[]\n): AskUserQuestionBatchItem {\n if (questions.length === 0) {\n throw new RangeError('askUserQuestions requires at least one question.');\n }\n if (questions.length > MAX_ASK_USER_QUESTIONS) {\n throw new RangeError(\n `askUserQuestions accepts at most ${MAX_ASK_USER_QUESTIONS} questions.`\n );\n }\n\n const ids = new Set<string>();\n for (const question of questions) {\n if (!isAskUserQuestionRequest(question)) {\n throw new TypeError(\n 'askUserQuestions requires each question and option to have valid string fields.'\n );\n }\n if (!ASK_USER_QUESTION_ID_PATTERN.test(question.id)) {\n throw new Error(\n 'askUserQuestions requires each question id to match [A-Za-z][A-Za-z0-9_-]{0,63}.'\n );\n }\n if (ids.has(question.id)) {\n throw new Error(\n `askUserQuestions requires unique question ids; received \"${question.id}\" more than once.`\n );\n }\n ids.add(question.id);\n }\n return questions[0];\n}\n\ninterface AskUserQuestionsResolutionCandidate {\n answers?: unknown;\n}\n\nfunction validateResolution(\n value: unknown,\n questions: readonly AskUserQuestionBatchItem[]\n): AskUserQuestionsResolution {\n if (typeof value !== 'object' || value === null) {\n throw new TypeError('askUserQuestions requires an answers object.');\n }\n const answers = (value as AskUserQuestionsResolutionCandidate).answers;\n if (\n typeof answers !== 'object' ||\n answers === null ||\n Array.isArray(answers)\n ) {\n throw new TypeError('askUserQuestions requires an answers object.');\n }\n\n const validated: Record<string, string> = {};\n for (const question of questions) {\n const descriptor = Object.getOwnPropertyDescriptor(answers, question.id);\n const answer: unknown = descriptor?.value;\n if (descriptor == null || typeof answer !== 'string') {\n throw new TypeError(\n `askUserQuestions requires a string answer for question id \"${question.id}\".`\n );\n }\n validated[question.id] = answer;\n }\n return { answers: validated };\n}\n\n/**\n * Suspend once to collect answers to several related questions. The first\n * question is also included in the legacy `question` field so existing hosts\n * can render a useful fallback during a staged rollout.\n *\n * Question ids must be non-empty and unique within the batch. The helper\n * accepts at most four questions so hosts can render the interaction as one\n * focused decision surface rather than an unbounded form.\n *\n * @example\n * ```ts\n * const { answers } = askUserQuestions({\n * questions: [\n * { id: 'environment', question: 'Which environment?' },\n * { id: 'region', question: 'Which region?' },\n * ],\n * });\n * return `Deploy to ${answers.environment} in ${answers.region}`;\n * ```\n */\nexport function askUserQuestions(\n request: AskUserQuestionsRequest,\n options?: { toolCallId?: string }\n): AskUserQuestionsResolution {\n const first = validateQuestions(request.questions);\n const fallback: AskUserQuestionRequest = {\n question: first.question,\n ...(first.description != null && { description: first.description }),\n ...(first.options != null && { options: first.options }),\n ...(first.multiSelect != null && { multiSelect: first.multiSelect }),\n };\n const payload: AskUserQuestionsInterruptPayload = {\n type: 'ask_user_question',\n question: fallback,\n questions: request.questions,\n ...(options?.toolCallId != null &&\n options.toolCallId !== '' && { tool_call_id: options.toolCallId }),\n };\n\n const resolution = interrupt<AskUserQuestionsInterruptPayload, unknown>(\n payload\n );\n return validateResolution(resolution, request.questions);\n}\n"],"mappings":";;;AAcA,SAAS,kBACP,WAC0B;CAC1B,IAAI,UAAU,WAAW,GACvB,MAAM,IAAI,WAAW,kDAAkD;CAEzE,IAAI,UAAU,SAAA,GACZ,MAAM,IAAI,WACR,+CACF;CAGF,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,CAACA,kCAAAA,yBAAyB,QAAQ,GACpC,MAAM,IAAI,UACR,iFACF;EAEF,IAAI,CAACC,kCAAAA,6BAA6B,KAAK,SAAS,EAAE,GAChD,MAAM,IAAI,MACR,kFACF;EAEF,IAAI,IAAI,IAAI,SAAS,EAAE,GACrB,MAAM,IAAI,MACR,4DAA4D,SAAS,GAAG,kBAC1E;EAEF,IAAI,IAAI,SAAS,EAAE;CACrB;CACA,OAAO,UAAU;AACnB;AAMA,SAAS,mBACP,OACA,WAC4B;CAC5B,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,MAAM,IAAI,UAAU,8CAA8C;CAEpE,MAAM,UAAW,MAA8C;CAC/D,IACE,OAAO,YAAY,YACnB,YAAY,QACZ,MAAM,QAAQ,OAAO,GAErB,MAAM,IAAI,UAAU,8CAA8C;CAGpE,MAAM,YAAoC,CAAC;CAC3C,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,aAAa,OAAO,yBAAyB,SAAS,SAAS,EAAE;EACvE,MAAM,SAAkB,YAAY;EACpC,IAAI,cAAc,QAAQ,OAAO,WAAW,UAC1C,MAAM,IAAI,UACR,8DAA8D,SAAS,GAAG,GAC5E;EAEF,UAAU,SAAS,MAAM;CAC3B;CACA,OAAO,EAAE,SAAS,UAAU;AAC9B;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,iBACd,SACA,SAC4B;CAC5B,MAAM,QAAQ,kBAAkB,QAAQ,SAAS;CAkBjD,OAAO,oBAAA,GAAA,qBAAA,UAAA,CAFL;EARA,MAAM;EACN,UAAU;GAPV,UAAU,MAAM;GAChB,GAAI,MAAM,eAAe,QAAQ,EAAE,aAAa,MAAM,YAAY;GAClE,GAAI,MAAM,WAAW,QAAQ,EAAE,SAAS,MAAM,QAAQ;GACtD,GAAI,MAAM,eAAe,QAAQ,EAAE,aAAa,MAAM,YAAY;EAIjD;EACjB,WAAW,QAAQ;EACnB,GAAI,SAAS,cAAc,QACzB,QAAQ,eAAe,MAAM,EAAE,cAAc,QAAQ,WAAW;CAI5D,CAE2B,GAAG,QAAQ,SAAS;AACzD"}
@@ -0,0 +1,46 @@
1
+ const require_hitl = require("../types/hitl.cjs");
2
+ //#region src/hitl/askUserQuestionsInterrupt.ts
3
+ /** Maximum questions supported by one batched clarification interaction. */
4
+ const MAX_ASK_USER_QUESTIONS = 4;
5
+ /** Safe identifier format for answer-map keys in a batched question. */
6
+ const ASK_USER_QUESTION_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
7
+ function isAskUserQuestionOption(value) {
8
+ if (typeof value !== "object" || value === null) return false;
9
+ const option = value;
10
+ return typeof option.label === "string" && typeof option.value === "string";
11
+ }
12
+ function isAskUserQuestionOptions(value) {
13
+ if (!Array.isArray(value)) return false;
14
+ for (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index) || !isAskUserQuestionOption(value[index])) return false;
15
+ return true;
16
+ }
17
+ function isAskUserQuestionRequest(value) {
18
+ if (typeof value !== "object" || value === null) return false;
19
+ const question = value;
20
+ return typeof question.question === "string" && (question.description === void 0 || typeof question.description === "string") && (question.options === void 0 || isAskUserQuestionOptions(question.options)) && (question.multiSelect === void 0 || typeof question.multiSelect === "boolean");
21
+ }
22
+ function isAskUserQuestionBatchItem(value) {
23
+ if (!isAskUserQuestionRequest(value)) return false;
24
+ const question = value;
25
+ return typeof question.id === "string" && ASK_USER_QUESTION_ID_PATTERN.test(question.id) && (question.header === void 0 || typeof question.header === "string");
26
+ }
27
+ /**
28
+ * Type guard for the batched form of an `ask_user_question` interrupt. Hosts
29
+ * use this to select the multi-question UI and `AskUserQuestionsResolution`.
30
+ */
31
+ function isAskUserQuestionsInterrupt(payload) {
32
+ if (!require_hitl.isAskUserQuestionInterrupt(payload) || !isAskUserQuestionRequest(payload.question) || payload.tool_call_id !== void 0 && typeof payload.tool_call_id !== "string" || !Array.isArray(payload.questions) || payload.questions.length === 0 || payload.questions.length > 4) return false;
33
+ const ids = /* @__PURE__ */ new Set();
34
+ for (const question of payload.questions) {
35
+ if (!isAskUserQuestionBatchItem(question) || ids.has(question.id)) return false;
36
+ ids.add(question.id);
37
+ }
38
+ return true;
39
+ }
40
+ //#endregion
41
+ exports.ASK_USER_QUESTION_ID_PATTERN = ASK_USER_QUESTION_ID_PATTERN;
42
+ exports.MAX_ASK_USER_QUESTIONS = MAX_ASK_USER_QUESTIONS;
43
+ exports.isAskUserQuestionRequest = isAskUserQuestionRequest;
44
+ exports.isAskUserQuestionsInterrupt = isAskUserQuestionsInterrupt;
45
+
46
+ //# sourceMappingURL=askUserQuestionsInterrupt.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"askUserQuestionsInterrupt.cjs","names":["isAskUserQuestionInterrupt"],"sources":["../../../src/hitl/askUserQuestionsInterrupt.ts"],"sourcesContent":["import type {\n AskUserQuestionBatchItem,\n AskUserQuestionOption,\n AskUserQuestionRequest,\n AskUserQuestionsInterruptPayload,\n} from '@/types/hitl';\nimport { isAskUserQuestionInterrupt } from '@/types/hitl';\n\n/** Maximum questions supported by one batched clarification interaction. */\nexport const MAX_ASK_USER_QUESTIONS = 4;\n\n/** Safe identifier format for answer-map keys in a batched question. */\nexport const ASK_USER_QUESTION_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n\ninterface AskUserQuestionOptionCandidate {\n label?: unknown;\n value?: unknown;\n}\n\ninterface AskUserQuestionCandidate {\n question?: unknown;\n description?: unknown;\n options?: unknown;\n multiSelect?: unknown;\n}\n\ninterface AskUserQuestionBatchItemCandidate extends AskUserQuestionCandidate {\n id?: unknown;\n header?: unknown;\n}\n\nfunction isAskUserQuestionOption(\n value: unknown\n): value is AskUserQuestionOption {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const option = value as AskUserQuestionOptionCandidate;\n return typeof option.label === 'string' && typeof option.value === 'string';\n}\n\nfunction isAskUserQuestionOptions(\n value: unknown\n): value is AskUserQuestionOption[] {\n if (!Array.isArray(value)) {\n return false;\n }\n for (let index = 0; index < value.length; index++) {\n if (!Object.hasOwn(value, index) || !isAskUserQuestionOption(value[index])) {\n return false;\n }\n }\n return true;\n}\n\nexport function isAskUserQuestionRequest(\n value: unknown\n): value is AskUserQuestionRequest {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const question = value as AskUserQuestionCandidate;\n return (\n typeof question.question === 'string' &&\n (question.description === undefined ||\n typeof question.description === 'string') &&\n (question.options === undefined ||\n isAskUserQuestionOptions(question.options)) &&\n (question.multiSelect === undefined ||\n typeof question.multiSelect === 'boolean')\n );\n}\n\nfunction isAskUserQuestionBatchItem(\n value: unknown\n): value is AskUserQuestionBatchItem {\n if (!isAskUserQuestionRequest(value)) {\n return false;\n }\n const question = value as AskUserQuestionBatchItemCandidate;\n return (\n typeof question.id === 'string' &&\n ASK_USER_QUESTION_ID_PATTERN.test(question.id) &&\n (question.header === undefined || typeof question.header === 'string')\n );\n}\n\n/**\n * Type guard for the batched form of an `ask_user_question` interrupt. Hosts\n * use this to select the multi-question UI and `AskUserQuestionsResolution`.\n */\nexport function isAskUserQuestionsInterrupt(\n payload: unknown\n): payload is AskUserQuestionsInterruptPayload {\n if (\n !isAskUserQuestionInterrupt(payload) ||\n !isAskUserQuestionRequest(payload.question) ||\n (payload.tool_call_id !== undefined &&\n typeof payload.tool_call_id !== 'string') ||\n !Array.isArray(payload.questions) ||\n payload.questions.length === 0 ||\n payload.questions.length > MAX_ASK_USER_QUESTIONS\n ) {\n return false;\n }\n\n const ids = new Set<string>();\n for (const question of payload.questions) {\n if (!isAskUserQuestionBatchItem(question) || ids.has(question.id)) {\n return false;\n }\n ids.add(question.id);\n }\n return true;\n}\n"],"mappings":";;;AASA,MAAa,yBAAyB;;AAGtC,MAAa,+BAA+B;AAmB5C,SAAS,wBACP,OACgC;CAChC,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,MAAM,SAAS;CACf,OAAO,OAAO,OAAO,UAAU,YAAY,OAAO,OAAO,UAAU;AACrE;AAEA,SAAS,yBACP,OACkC;CAClC,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,OAAO;CAET,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SACxC,IAAI,CAAC,OAAO,OAAO,OAAO,KAAK,KAAK,CAAC,wBAAwB,MAAM,MAAM,GACvE,OAAO;CAGX,OAAO;AACT;AAEA,SAAgB,yBACd,OACiC;CACjC,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,MAAM,WAAW;CACjB,OACE,OAAO,SAAS,aAAa,aAC5B,SAAS,gBAAgB,KAAA,KACxB,OAAO,SAAS,gBAAgB,cACjC,SAAS,YAAY,KAAA,KACpB,yBAAyB,SAAS,OAAO,OAC1C,SAAS,gBAAgB,KAAA,KACxB,OAAO,SAAS,gBAAgB;AAEtC;AAEA,SAAS,2BACP,OACmC;CACnC,IAAI,CAAC,yBAAyB,KAAK,GACjC,OAAO;CAET,MAAM,WAAW;CACjB,OACE,OAAO,SAAS,OAAO,YACvB,6BAA6B,KAAK,SAAS,EAAE,MAC5C,SAAS,WAAW,KAAA,KAAa,OAAO,SAAS,WAAW;AAEjE;;;;;AAMA,SAAgB,4BACd,SAC6C;CAC7C,IACE,CAACA,aAAAA,2BAA2B,OAAO,KACnC,CAAC,yBAAyB,QAAQ,QAAQ,KACzC,QAAQ,iBAAiB,KAAA,KACxB,OAAO,QAAQ,iBAAiB,YAClC,CAAC,MAAM,QAAQ,QAAQ,SAAS,KAChC,QAAQ,UAAU,WAAW,KAC7B,QAAQ,UAAU,SAAA,GAElB,OAAO;CAGT,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,YAAY,QAAQ,WAAW;EACxC,IAAI,CAAC,2BAA2B,QAAQ,KAAK,IAAI,IAAI,SAAS,EAAE,GAC9D,OAAO;EAET,IAAI,IAAI,SAAS,EAAE;CACrB;CACA,OAAO;AACT"}
@@ -1 +1,3 @@
1
1
  require("./askUserQuestion.cjs");
2
+ require("./askUserQuestionsInterrupt.cjs");
3
+ require("./askUserQuestions.cjs");
package/dist/cjs/main.cjs CHANGED
@@ -103,6 +103,8 @@ const require_handlers$2 = require("./session/handlers.cjs");
103
103
  const require_AgentSession = require("./session/AgentSession.cjs");
104
104
  require("./session/index.cjs");
105
105
  const require_askUserQuestion = require("./hitl/askUserQuestion.cjs");
106
+ const require_askUserQuestionsInterrupt = require("./hitl/askUserQuestionsInterrupt.cjs");
107
+ const require_askUserQuestions = require("./hitl/askUserQuestions.cjs");
106
108
  require("./hitl/index.cjs");
107
109
  require("./langchain/index.cjs");
108
110
  let _langchain_langgraph = require("@langchain/langgraph");
@@ -123,6 +125,7 @@ Object.defineProperty(exports, "AIMessageChunk", {
123
125
  }
124
126
  });
125
127
  exports.ANTHROPIC_TOOL_TOKEN_MULTIPLIER = require_constants.ANTHROPIC_TOOL_TOKEN_MULTIPLIER;
128
+ exports.ASK_USER_QUESTION_ID_PATTERN = require_askUserQuestionsInterrupt.ASK_USER_QUESTION_ID_PATTERN;
126
129
  exports.AgentSession = require_AgentSession.AgentSession;
127
130
  exports.BASH_SHELL_GUIDANCE = require_CodeExecutor.BASH_SHELL_GUIDANCE;
128
131
  Object.defineProperty(exports, "BaseCheckpointSaver", {
@@ -260,6 +263,7 @@ exports.LocalListDirectoryToolSchema = require_LocalCodingTools.LocalListDirecto
260
263
  exports.LocalReadFileToolSchema = require_LocalCodingTools.LocalReadFileToolSchema;
261
264
  exports.LocalWriteFileToolName = require_LocalCodingTools.LocalWriteFileToolName;
262
265
  exports.LocalWriteFileToolSchema = require_LocalCodingTools.LocalWriteFileToolSchema;
266
+ exports.MAX_ASK_USER_QUESTIONS = require_askUserQuestionsInterrupt.MAX_ASK_USER_QUESTIONS;
263
267
  exports.MAX_CACHE_SIZE = require_matchers.MAX_CACHE_SIZE;
264
268
  exports.MAX_PATTERN_LENGTH = require_matchers.MAX_PATTERN_LENGTH;
265
269
  Object.defineProperty(exports, "MemorySaver", {
@@ -391,6 +395,7 @@ exports.applyOutcome = require_intentArg.applyOutcome;
391
395
  exports.applyPreToolUseHooksForBridge = require_LocalProgrammaticToolCalling.applyPreToolUseHooksForBridge;
392
396
  exports.apportionTokenCounts = require_tokens.apportionTokenCounts;
393
397
  exports.askUserQuestion = require_askUserQuestion.askUserQuestion;
398
+ exports.askUserQuestions = require_askUserQuestions.askUserQuestions;
394
399
  exports.attemptInvoke = require_invoke.attemptInvoke;
395
400
  exports.bashAstFindingsToErrors = require_bashAst.bashAstFindingsToErrors;
396
401
  exports.buildAnthropicCacheControl = require_cache.buildAnthropicCacheControl;
@@ -577,6 +582,7 @@ Object.defineProperty(exports, "isAIMessage", {
577
582
  }
578
583
  });
579
584
  exports.isAnthropicLike = require_llm.isAnthropicLike;
585
+ exports.isAskUserQuestionsInterrupt = require_askUserQuestionsInterrupt.isAskUserQuestionsInterrupt;
580
586
  Object.defineProperty(exports, "isBaseMessage", {
581
587
  enumerable: true,
582
588
  get: function() {
@@ -0,0 +1,13 @@
1
+ //#region src/types/hitl.ts
2
+ /**
3
+ * Type guard narrowing an arbitrary value to an
4
+ * `AskUserQuestionInterruptPayload`. Same `unknown`-tolerant contract
5
+ * as `isToolApprovalInterrupt`.
6
+ */
7
+ function isAskUserQuestionInterrupt(payload) {
8
+ return typeof payload === "object" && payload !== null && payload.type === "ask_user_question";
9
+ }
10
+ //#endregion
11
+ exports.isAskUserQuestionInterrupt = isAskUserQuestionInterrupt;
12
+
13
+ //# sourceMappingURL=hitl.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hitl.cjs","names":[],"sources":["../../../src/types/hitl.ts"],"sourcesContent":["/**\n * First-class human-in-the-loop (HITL) types for `@librechat/agents`.\n * Surfaces the interrupt payload that `ToolNode` raises when a `PreToolUse`\n * hook returns `decision: 'ask'` and HITL is enabled on the run, plus the\n * resume-decision shape the host returns to continue or reject the tool.\n *\n * Mirrors the LangChain HITL middleware shape (action_requests /\n * review_configs) so hosts and clients can share rendering/UI semantics\n * across the langchain ecosystem.\n */\n\n/** Per-tool approval request emitted inside an interrupt payload. */\nexport interface ToolApprovalRequest {\n /** Stable id of the tool call (matches LangGraph `ToolCall.id`). */\n tool_call_id: string;\n /** Tool name being invoked. */\n name: string;\n /**\n * Arguments the tool is about to be invoked with — already resolved by\n * any `{{tool<i>turn<n>}}` references and any `updatedInput` returned\n * by the firing PreToolUse hook.\n */\n arguments: Record<string, unknown>;\n /**\n * Optional reason the hook supplied for asking (e.g., \"destructive\n * filesystem write\"). Hosts can render this verbatim.\n */\n description?: string;\n}\n\n/** Allowed host-side decisions for a `tool_approval` interrupt. */\nexport type ToolApprovalDecisionType =\n | 'approve'\n | 'reject'\n | 'edit'\n | 'respond';\n\n/** Per-action review configuration paired with each action_request. */\nexport interface ToolApprovalReviewConfig {\n /** Tool name (matches the `name` field on the corresponding action_request). */\n action_name: string;\n /**\n * Stable id of the tool call this review_config applies to (matches\n * the `tool_call_id` of the corresponding action_request). Lets a UI\n * map review_configs → action_requests directly when a batch\n * contains the same tool called more than once — by-position\n * mapping breaks down with duplicates.\n */\n tool_call_id: string;\n /** Decisions the host UI is allowed to surface for this action. */\n allowed_decisions: ToolApprovalDecisionType[];\n}\n\n/**\n * Resume value the host returns through `Run.resume(decisions)` after a\n * `tool_approval` interrupt. One entry per action_request, in the same\n * order. Hosts may also return a record keyed by `tool_call_id`; the SDK\n * handles either shape.\n *\n * Variants:\n * - `approve`: run the tool with its original (or hook-rewritten) args.\n * - `reject`: skip the tool, emit a blocked error `ToolMessage` with\n * `reason` surfaced to the model.\n * - `edit`: replace the tool's args with `updatedInput` (re-resolves\n * any `{{tool<i>turn<n>}}` placeholders) and run the tool.\n * - `respond`: skip the tool entirely and emit `responseText` as a\n * successful `ToolMessage`. Mirrors LangChain HITL middleware's\n * `respond` semantic — the human supplies the result the model sees,\n * bypassing tool execution. Useful when the user wants to short-circuit\n * a tool call with a hand-written answer (e.g., \"don't actually run\n * the search, just tell the model 'no relevant results'\").\n *\n * Note on hook semantics: `respond` does NOT fire the per-tool\n * `PostToolUse` hook (no real tool execution happened, so the\n * \"post-tool\" semantic doesn't apply). It DOES appear in the\n * `PostToolBatch` entry array with `status: 'success'` and the\n * user-supplied text as `toolOutput`, so batch-level audit /\n * convention hooks see the full set of outcomes.\n */\nexport type ToolApprovalDecision =\n | { type: 'approve' }\n | { type: 'reject'; reason?: string }\n | { type: 'edit'; updatedInput: Record<string, unknown> }\n | { type: 'respond'; responseText: string };\n\n/** Map form of resume decisions, keyed by tool call id. */\nexport type ToolApprovalDecisionMap = Record<string, ToolApprovalDecision>;\n\n/**\n * Categories of human-in-the-loop interrupts the SDK can raise. Hosts\n * narrow on `HumanInterruptPayload.type` to determine which payload\n * shape they're handling and which resume value to send back through\n * `Run.resume()`.\n *\n * Exported as a discrete type so downstream consumers (notably\n * LibreChat's wire types in `librechat-data-provider`) can mirror\n * the discriminator alongside their own host-side `PendingAction`\n * record without re-declaring the union themselves. Internal SDK\n * code narrows directly on the literal strings via the type guards\n * below; this type alias is primarily an integration-layer contract.\n */\nexport type HumanInterruptType = 'tool_approval' | 'ask_user_question';\n\n/** Identifies an interrupt that originated inside a checkpointed subagent. */\nexport interface SubagentInterruptScope {\n /** Child execution run id used by subagent update and usage events. */\n run_id: string;\n /** Child agent id that owns the interrupted tool call. */\n agent_id: string;\n /** Configured subagent type selected by the parent tool call. */\n subagent_type: string;\n /** Parent `subagent` tool call that launched this child. */\n parent_tool_call_id?: string;\n}\n\n/**\n * Structured payload the SDK passes to `interrupt()` when one or more\n * pending tool calls require host approval. All `ask`-decision tool calls\n * from a single ToolNode batch are bundled into one interrupt so the host\n * can render and resolve them together.\n *\n * Resume value: `ToolApprovalDecision[]` (in `action_requests` order) or\n * `ToolApprovalDecisionMap` (keyed by `tool_call_id`).\n */\nexport interface ToolApprovalInterruptPayload {\n type: 'tool_approval';\n action_requests: ToolApprovalRequest[];\n review_configs: ToolApprovalReviewConfig[];\n /** Hook-registry session whose policy raised this interrupt. */\n hook_session_id?: string;\n /** Present when the approval request was bridged from a child graph. */\n subagent?: SubagentInterruptScope;\n}\n\n/**\n * Pre-defined option the user can pick when answering an\n * `ask_user_question` interrupt. The selected option's `value` becomes\n * the resume value's `answer` field.\n */\nexport interface AskUserQuestionOption {\n /** Human-readable label rendered in the host UI. */\n label: string;\n /** Value returned via `AskUserQuestionResolution.answer` if picked. */\n value: string;\n}\n\n/** Question request emitted inside an `ask_user_question` interrupt. */\nexport interface AskUserQuestionRequest {\n /** The question to ask the human. */\n question: string;\n /** Optional context / description rendered alongside the question. */\n description?: string;\n /**\n * Optional pre-defined response options. When present, hosts can render\n * a picker; the user may still type a free-form answer when the host\n * UI allows it. Omit to require a free-form answer.\n */\n options?: AskUserQuestionOption[];\n /**\n * When `true`, the host UI may let the user pick several options; the\n * resulting `AskUserQuestionResolution.answer` is the selected option\n * values joined by `\", \"`. When omitted or `false`, hosts render a\n * single-select picker. Only meaningful alongside `options`.\n */\n multiSelect?: boolean;\n}\n\n/** One independently answerable question in a batched question request. */\nexport interface AskUserQuestionBatchItem extends AskUserQuestionRequest {\n /** Batch-unique identifier (`[A-Za-z][A-Za-z0-9_-]{0,63}`). */\n id: string;\n /** Optional short heading rendered above the question. */\n header?: string;\n}\n\n/** Input shape for one tool call that asks one to four questions together. */\nexport interface AskUserQuestionsRequest {\n questions: AskUserQuestionBatchItem[];\n}\n\n/**\n * Structured payload the SDK passes to `interrupt()` when an agent (or\n * a custom node) needs to ask the user a clarifying question. Mirrors\n * Claude Code's `AskUserQuestion` semantic. Resume value is\n * `AskUserQuestionResolution` for a single question, or\n * `AskUserQuestionsResolution` when `questions` is present.\n */\nexport interface AskUserQuestionInterruptPayload {\n type: 'ask_user_question';\n /**\n * Single-question request, or the first question as a compatibility\n * fallback when `questions` contains a batch. This lets existing hosts show\n * a useful preview during a staged rollout, but they must support `questions`\n * and `AskUserQuestionsResolution` before enabling a batched tool schema.\n */\n question: AskUserQuestionRequest;\n /** One to four questions collected by one `ask_user_question` tool call. */\n questions?: AskUserQuestionsRequest['questions'];\n /**\n * The `tool_call_id` of the ask-tool call that raised this interrupt,\n * when the tool body supplied it (see `askUserQuestion`'s `options`).\n * Lets hosts attribute the question — and later the answer — to the\n * exact tool-call content part instead of guessing by position, which\n * mislabels cards when a model emits several ask calls in one turn.\n */\n tool_call_id?: string;\n}\n\n/** Batch-specialized ask payload for hosts that render several questions. */\nexport interface AskUserQuestionsInterruptPayload\n extends AskUserQuestionInterruptPayload {\n questions: AskUserQuestionsRequest['questions'];\n}\n\n/**\n * Discriminated union of every interrupt payload the SDK raises. New\n * variants can be added without breaking existing handlers as long as\n * those handlers check `payload.type` before reading variant-specific\n * fields. Use the `isToolApprovalInterrupt` / `isAskUserQuestionInterrupt`\n * type guards for ergonomic narrowing.\n */\nexport type HumanInterruptPayload =\n | ToolApprovalInterruptPayload\n | AskUserQuestionInterruptPayload;\n\n/** Resume value the host returns for an `ask_user_question` interrupt. */\nexport interface AskUserQuestionResolution {\n /**\n * The human's answer. Free-form text, or — when `options` were\n * provided — one of the option `value`s (or, when the request set\n * `multiSelect`, several option `value`s joined by `\", \"`). Hosts may\n * also send any structured object their custom UI defines; see the\n * host docs for what your downstream consumer expects.\n */\n answer: string;\n}\n\n/** Resume value for a batched `ask_user_question` interrupt. */\nexport interface AskUserQuestionsResolution {\n /** Human answers keyed by each `AskUserQuestionBatchItem.id`. */\n answers: Record<string, string>;\n}\n\n/**\n * Type guard narrowing an arbitrary value to a `ToolApprovalInterruptPayload`.\n * Accepts `unknown` (not just `HumanInterruptPayload`) because hosts can\n * raise custom interrupt payloads from custom nodes — `getInterrupt()`\n * surfaces them as-is, and downstream code must validate the shape at\n * runtime before reading variant-specific fields.\n */\nexport function isToolApprovalInterrupt(\n payload: unknown\n): payload is ToolApprovalInterruptPayload {\n return (\n typeof payload === 'object' &&\n payload !== null &&\n (payload as { type?: unknown }).type === 'tool_approval'\n );\n}\n\n/**\n * Type guard narrowing an arbitrary value to an\n * `AskUserQuestionInterruptPayload`. Same `unknown`-tolerant contract\n * as `isToolApprovalInterrupt`.\n */\nexport function isAskUserQuestionInterrupt(\n payload: unknown\n): payload is AskUserQuestionInterruptPayload {\n return (\n typeof payload === 'object' &&\n payload !== null &&\n (payload as { type?: unknown }).type === 'ask_user_question'\n );\n}\n\n/**\n * Run-level configuration controlling HITL semantics. **HITL is OFF by\n * default** for now — the SDK ships the interrupt machinery, but the\n * default stays opt-in until host UIs (notably LibreChat) ship the\n * approval-rendering affordances needed to surface interrupts to end\n * users. Without that UI, an interrupt with no resolver looks like a\n * hung tool-call card. Hosts opt in explicitly with\n * `{ enabled: true }`. The intent is to flip this default to ON in a\n * future minor once the consumer ecosystem is ready to render\n * interrupts end-to-end.\n *\n * When enabled (`{ enabled: true }`):\n *\n * - `PreToolUse` hooks returning `decision: 'ask'` raise a real\n * LangGraph `interrupt()` instead of being treated as a synchronous\n * deny.\n * - `Run.create` installs a `MemorySaver` checkpointer fallback on the\n * run's compile options if the host did not provide one, since\n * LangGraph requires a checkpointer to suspend and resume.\n *\n * When disabled (the default — omitted, or `{ enabled: false }`):\n * `ask` decisions are fail-closed (blocked with an error\n * `ToolMessage`) and no checkpointer is implicitly attached. This\n * matches the pre-HITL behavior so existing hosts upgrading the SDK\n * see no change until they're ready to wire the resume UI.\n *\n * ## Scope: every tool the ToolNode runs\n *\n * The interrupt path is wired into both `dispatchToolEvents` (the\n * event-driven path) and `runDirectToolWithLifecycleHooks` (the\n * direct path used by `directToolNames` entries — graph-managed\n * handoff/subagent tools and every in-process `graphTool` instance).\n * `PreToolUse` hooks fire for every tool the ToolNode invokes, and\n * HITL approval gates every tool whose hook returns `'ask'` —\n * regardless of whether the tool is dispatched as an event or\n * invoked in-process. This convergence happened in two follow-up\n * commits to the original HITL surface (see `Graph.ts` —\n * `hookRegistry`/`humanInTheLoop` are passed in both\n * event-driven and legacy branches; and `ToolNode.runDirectToolWithLifecycleHooks`\n * — direct-path tools build their own single-tool `tool_approval`\n * payload and raise `interrupt()` the same way the event path does).\n *\n * Practical implications:\n * - Every host gets the full HITL surface across every tool the\n * model calls — event-dispatched, direct, mixed.\n * - `createToolPolicyHook` and `createWorkspacePolicyHook` apply\n * uniformly. A hook can be registered without knowing or caring\n * which path the tool will take.\n * - Direct tools that the host opted into via `directToolNames` no\n * longer bypass policy. If you need a tool to skip the hook\n * surface entirely, omit it from any registered matcher.\n *\n * ## Resume re-execution: every tool in the interrupted batch\n *\n * LangGraph rolls back to the start of the interrupted node on\n * resume. That means **every tool in the same batch as the one that\n * interrupted re-runs from the top on the resume pass**, not just\n * the interrupting tool, and not just the direct half (this used to\n * be framed as a direct-tool-specific concern; it is not — it\n * applies to event-dispatched siblings too). Practical contract:\n *\n * - The body of the interrupting tool itself runs **once** total\n * (the first pass interrupted *before* the body, the resume pass\n * ran the body after the host's decision was applied).\n * - The body of any sibling tool that already executed in the\n * same batch before the interrupting tool runs **twice** — once\n * on the first pass, once on the resume pass.\n * - `PreToolUse` hooks fire **once per pass per tool**. A hook\n * that always returns `'ask'` will loop forever on resume; real\n * hooks should be deterministic w.r.t. inputs and use the\n * `'ask' → host approves → resume → hook returns 'allow'`\n * pattern, where the second-pass `allow` reflects the host\n * having recorded the approval (e.g., a session-scoped approved-\n * paths set keyed by `runId`).\n *\n * Consequence: any tool with side effects MUST be idempotent if\n * there's any chance another tool in the same batch could trigger\n * an interrupt. This applies equally to direct tools (handoffs,\n * subagents) and to event tools.\n *\n * ### Guarding non-idempotent siblings via `interruptingToolNames`\n *\n * The \"must be idempotent\" rule above is unavoidable in the general\n * case, but the SDK can protect siblings against the one interrupt\n * shape it can predict: a tool whose *body* raises `interrupt()`\n * mid-execution — the `ask_user_question` shape, where the tool\n * suspends the run to collect a human answer. Declare such tools in\n * `RunConfig.interruptingToolNames`\n * ({@link ToolNodeOptions.interruptingToolNames}) and the ToolNode\n * schedules them, within each batch, **ahead of** their\n * non-interrupting direct siblings. When one interrupts, the batch\n * unwinds before any declared-safe sibling has run, so the sibling\n * executes exactly once (on resume) instead of twice. Empirically:\n *\n * - A **direct** sibling sharing the interrupter's in-process\n * `Promise.all` is the only shape that double-executes; declaring\n * the interrupter closes it.\n * - An **event-dispatched** sibling is already safe without any\n * config: the ToolNode awaits the whole direct group (where the\n * body interrupt unwinds) before it dispatches event tools, so a\n * dispatched sibling never runs on the first pass.\n *\n * This is a *scheduling* guard, not full resume idempotency: it only\n * covers tools that interrupt from their own body and only protects\n * siblings scheduled after them. It does not retroactively make a\n * `PreToolUse` `'ask'` gate on tool B stop tool A (already executed)\n * from re-running — unless B is itself declared interrupting, so it\n * runs first. Tools with side effects should still be written\n * idempotent as defense in depth.\n *\n * The guard only REORDERS the direct group — declaring a name does not\n * force it onto the direct path. The interrupting tool must already be a\n * real in-process graphTool (the only kind whose body can reach\n * `interrupt()`). A name that resolves to a schema-only event stub (an\n * inherited `toolDefinition` with no executable instance, e.g. in a\n * self-spawned child that scrubs `graphTools`) stays event-dispatched\n * and the ordering is a no-op for it.\n *\n * ## Note on idempotency\n *\n * Same root cause as the resume re-execution above: LangGraph\n * re-runs the interrupted node from the start on resume, which\n * fires `PreToolUse` hooks again. Hooks that produce side effects\n * (logging, external calls) will see at least two invocations per\n * paused turn — exactly two for the interrupting tool, possibly\n * more across siblings.\n */\nexport interface HumanInTheLoopConfig {\n /**\n * Master switch. Defaults to `false` — omit the field (or pass\n * `false`) to keep HITL off, or set `true` to opt in once the host\n * UI is ready to render and resolve `tool_approval` interrupts.\n */\n enabled?: boolean;\n}\n\n/**\n * Snapshot of an in-flight interrupt surfaced from `Run.processStream`\n * via `run.getInterrupt()`. Hosts persist this alongside their job\n * record so they can later call `Run.resume(decisions)` against a Run\n * compiled with the same `thread_id` / checkpointer.\n *\n * The `payload` type defaults to `HumanInterruptPayload` (the SDK's\n * built-in `tool_approval` / `ask_user_question` discriminated union)\n * for ergonomic narrowing in the common case. Hosts that raise custom\n * interrupt payloads from custom graph nodes can pass the type\n * parameter (`run.getInterrupt<MyCustom>()` or\n * `RunInterruptResult<MyCustom>`) — the SDK does not validate the\n * runtime shape, it just transports whatever the node passed to\n * `interrupt()`. Use the `isToolApprovalInterrupt` /\n * `isAskUserQuestionInterrupt` guards (which accept `unknown`) when\n * the source of the interrupt isn't statically known.\n */\nexport interface RunInterruptResult<TPayload = HumanInterruptPayload> {\n /** Stable id of the LangGraph interrupt (from `Interrupt.id`). */\n interruptId: string;\n /** `thread_id` the run was bound to — required to resume. */\n threadId?: string;\n /** LangGraph checkpoint id that contains the paused interrupt task. */\n checkpointId?: string;\n /** LangGraph checkpoint namespace for the paused interrupt task. */\n checkpointNs?: string;\n /** Structured payload describing what needs human input. */\n payload: TPayload;\n}\n"],"mappings":";;;;;;AAyQA,SAAgB,2BACd,SAC4C;CAC5C,OACE,OAAO,YAAY,YACnB,YAAY,QACX,QAA+B,SAAS;AAE7C"}
@@ -0,0 +1,66 @@
1
+ import { ASK_USER_QUESTION_ID_PATTERN, isAskUserQuestionRequest } from "./askUserQuestionsInterrupt.mjs";
2
+ import { interrupt } from "@langchain/langgraph";
3
+ //#region src/hitl/askUserQuestions.ts
4
+ function validateQuestions(questions) {
5
+ if (questions.length === 0) throw new RangeError("askUserQuestions requires at least one question.");
6
+ if (questions.length > 4) throw new RangeError(`askUserQuestions accepts at most 4 questions.`);
7
+ const ids = /* @__PURE__ */ new Set();
8
+ for (const question of questions) {
9
+ if (!isAskUserQuestionRequest(question)) throw new TypeError("askUserQuestions requires each question and option to have valid string fields.");
10
+ if (!ASK_USER_QUESTION_ID_PATTERN.test(question.id)) throw new Error("askUserQuestions requires each question id to match [A-Za-z][A-Za-z0-9_-]{0,63}.");
11
+ if (ids.has(question.id)) throw new Error(`askUserQuestions requires unique question ids; received "${question.id}" more than once.`);
12
+ ids.add(question.id);
13
+ }
14
+ return questions[0];
15
+ }
16
+ function validateResolution(value, questions) {
17
+ if (typeof value !== "object" || value === null) throw new TypeError("askUserQuestions requires an answers object.");
18
+ const answers = value.answers;
19
+ if (typeof answers !== "object" || answers === null || Array.isArray(answers)) throw new TypeError("askUserQuestions requires an answers object.");
20
+ const validated = {};
21
+ for (const question of questions) {
22
+ const descriptor = Object.getOwnPropertyDescriptor(answers, question.id);
23
+ const answer = descriptor?.value;
24
+ if (descriptor == null || typeof answer !== "string") throw new TypeError(`askUserQuestions requires a string answer for question id "${question.id}".`);
25
+ validated[question.id] = answer;
26
+ }
27
+ return { answers: validated };
28
+ }
29
+ /**
30
+ * Suspend once to collect answers to several related questions. The first
31
+ * question is also included in the legacy `question` field so existing hosts
32
+ * can render a useful fallback during a staged rollout.
33
+ *
34
+ * Question ids must be non-empty and unique within the batch. The helper
35
+ * accepts at most four questions so hosts can render the interaction as one
36
+ * focused decision surface rather than an unbounded form.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const { answers } = askUserQuestions({
41
+ * questions: [
42
+ * { id: 'environment', question: 'Which environment?' },
43
+ * { id: 'region', question: 'Which region?' },
44
+ * ],
45
+ * });
46
+ * return `Deploy to ${answers.environment} in ${answers.region}`;
47
+ * ```
48
+ */
49
+ function askUserQuestions(request, options) {
50
+ const first = validateQuestions(request.questions);
51
+ return validateResolution(interrupt({
52
+ type: "ask_user_question",
53
+ question: {
54
+ question: first.question,
55
+ ...first.description != null && { description: first.description },
56
+ ...first.options != null && { options: first.options },
57
+ ...first.multiSelect != null && { multiSelect: first.multiSelect }
58
+ },
59
+ questions: request.questions,
60
+ ...options?.toolCallId != null && options.toolCallId !== "" && { tool_call_id: options.toolCallId }
61
+ }), request.questions);
62
+ }
63
+ //#endregion
64
+ export { askUserQuestions };
65
+
66
+ //# sourceMappingURL=askUserQuestions.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"askUserQuestions.mjs","names":[],"sources":["../../../src/hitl/askUserQuestions.ts"],"sourcesContent":["import { interrupt } from '@langchain/langgraph';\nimport type {\n AskUserQuestionBatchItem,\n AskUserQuestionRequest,\n AskUserQuestionsInterruptPayload,\n AskUserQuestionsRequest,\n AskUserQuestionsResolution,\n} from '@/types/hitl';\nimport {\n ASK_USER_QUESTION_ID_PATTERN,\n isAskUserQuestionRequest,\n MAX_ASK_USER_QUESTIONS,\n} from './askUserQuestionsInterrupt';\n\nfunction validateQuestions(\n questions: readonly AskUserQuestionBatchItem[]\n): AskUserQuestionBatchItem {\n if (questions.length === 0) {\n throw new RangeError('askUserQuestions requires at least one question.');\n }\n if (questions.length > MAX_ASK_USER_QUESTIONS) {\n throw new RangeError(\n `askUserQuestions accepts at most ${MAX_ASK_USER_QUESTIONS} questions.`\n );\n }\n\n const ids = new Set<string>();\n for (const question of questions) {\n if (!isAskUserQuestionRequest(question)) {\n throw new TypeError(\n 'askUserQuestions requires each question and option to have valid string fields.'\n );\n }\n if (!ASK_USER_QUESTION_ID_PATTERN.test(question.id)) {\n throw new Error(\n 'askUserQuestions requires each question id to match [A-Za-z][A-Za-z0-9_-]{0,63}.'\n );\n }\n if (ids.has(question.id)) {\n throw new Error(\n `askUserQuestions requires unique question ids; received \"${question.id}\" more than once.`\n );\n }\n ids.add(question.id);\n }\n return questions[0];\n}\n\ninterface AskUserQuestionsResolutionCandidate {\n answers?: unknown;\n}\n\nfunction validateResolution(\n value: unknown,\n questions: readonly AskUserQuestionBatchItem[]\n): AskUserQuestionsResolution {\n if (typeof value !== 'object' || value === null) {\n throw new TypeError('askUserQuestions requires an answers object.');\n }\n const answers = (value as AskUserQuestionsResolutionCandidate).answers;\n if (\n typeof answers !== 'object' ||\n answers === null ||\n Array.isArray(answers)\n ) {\n throw new TypeError('askUserQuestions requires an answers object.');\n }\n\n const validated: Record<string, string> = {};\n for (const question of questions) {\n const descriptor = Object.getOwnPropertyDescriptor(answers, question.id);\n const answer: unknown = descriptor?.value;\n if (descriptor == null || typeof answer !== 'string') {\n throw new TypeError(\n `askUserQuestions requires a string answer for question id \"${question.id}\".`\n );\n }\n validated[question.id] = answer;\n }\n return { answers: validated };\n}\n\n/**\n * Suspend once to collect answers to several related questions. The first\n * question is also included in the legacy `question` field so existing hosts\n * can render a useful fallback during a staged rollout.\n *\n * Question ids must be non-empty and unique within the batch. The helper\n * accepts at most four questions so hosts can render the interaction as one\n * focused decision surface rather than an unbounded form.\n *\n * @example\n * ```ts\n * const { answers } = askUserQuestions({\n * questions: [\n * { id: 'environment', question: 'Which environment?' },\n * { id: 'region', question: 'Which region?' },\n * ],\n * });\n * return `Deploy to ${answers.environment} in ${answers.region}`;\n * ```\n */\nexport function askUserQuestions(\n request: AskUserQuestionsRequest,\n options?: { toolCallId?: string }\n): AskUserQuestionsResolution {\n const first = validateQuestions(request.questions);\n const fallback: AskUserQuestionRequest = {\n question: first.question,\n ...(first.description != null && { description: first.description }),\n ...(first.options != null && { options: first.options }),\n ...(first.multiSelect != null && { multiSelect: first.multiSelect }),\n };\n const payload: AskUserQuestionsInterruptPayload = {\n type: 'ask_user_question',\n question: fallback,\n questions: request.questions,\n ...(options?.toolCallId != null &&\n options.toolCallId !== '' && { tool_call_id: options.toolCallId }),\n };\n\n const resolution = interrupt<AskUserQuestionsInterruptPayload, unknown>(\n payload\n );\n return validateResolution(resolution, request.questions);\n}\n"],"mappings":";;;AAcA,SAAS,kBACP,WAC0B;CAC1B,IAAI,UAAU,WAAW,GACvB,MAAM,IAAI,WAAW,kDAAkD;CAEzE,IAAI,UAAU,SAAA,GACZ,MAAM,IAAI,WACR,+CACF;CAGF,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,CAAC,yBAAyB,QAAQ,GACpC,MAAM,IAAI,UACR,iFACF;EAEF,IAAI,CAAC,6BAA6B,KAAK,SAAS,EAAE,GAChD,MAAM,IAAI,MACR,kFACF;EAEF,IAAI,IAAI,IAAI,SAAS,EAAE,GACrB,MAAM,IAAI,MACR,4DAA4D,SAAS,GAAG,kBAC1E;EAEF,IAAI,IAAI,SAAS,EAAE;CACrB;CACA,OAAO,UAAU;AACnB;AAMA,SAAS,mBACP,OACA,WAC4B;CAC5B,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,MAAM,IAAI,UAAU,8CAA8C;CAEpE,MAAM,UAAW,MAA8C;CAC/D,IACE,OAAO,YAAY,YACnB,YAAY,QACZ,MAAM,QAAQ,OAAO,GAErB,MAAM,IAAI,UAAU,8CAA8C;CAGpE,MAAM,YAAoC,CAAC;CAC3C,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,aAAa,OAAO,yBAAyB,SAAS,SAAS,EAAE;EACvE,MAAM,SAAkB,YAAY;EACpC,IAAI,cAAc,QAAQ,OAAO,WAAW,UAC1C,MAAM,IAAI,UACR,8DAA8D,SAAS,GAAG,GAC5E;EAEF,UAAU,SAAS,MAAM;CAC3B;CACA,OAAO,EAAE,SAAS,UAAU;AAC9B;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,iBACd,SACA,SAC4B;CAC5B,MAAM,QAAQ,kBAAkB,QAAQ,SAAS;CAkBjD,OAAO,mBAHY,UACjB;EARA,MAAM;EACN,UAAU;GAPV,UAAU,MAAM;GAChB,GAAI,MAAM,eAAe,QAAQ,EAAE,aAAa,MAAM,YAAY;GAClE,GAAI,MAAM,WAAW,QAAQ,EAAE,SAAS,MAAM,QAAQ;GACtD,GAAI,MAAM,eAAe,QAAQ,EAAE,aAAa,MAAM,YAAY;EAIjD;EACjB,WAAW,QAAQ;EACnB,GAAI,SAAS,cAAc,QACzB,QAAQ,eAAe,MAAM,EAAE,cAAc,QAAQ,WAAW;CAI5D,CAE2B,GAAG,QAAQ,SAAS;AACzD"}
@@ -0,0 +1,43 @@
1
+ import { isAskUserQuestionInterrupt } from "../types/hitl.mjs";
2
+ //#region src/hitl/askUserQuestionsInterrupt.ts
3
+ /** Maximum questions supported by one batched clarification interaction. */
4
+ const MAX_ASK_USER_QUESTIONS = 4;
5
+ /** Safe identifier format for answer-map keys in a batched question. */
6
+ const ASK_USER_QUESTION_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
7
+ function isAskUserQuestionOption(value) {
8
+ if (typeof value !== "object" || value === null) return false;
9
+ const option = value;
10
+ return typeof option.label === "string" && typeof option.value === "string";
11
+ }
12
+ function isAskUserQuestionOptions(value) {
13
+ if (!Array.isArray(value)) return false;
14
+ for (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index) || !isAskUserQuestionOption(value[index])) return false;
15
+ return true;
16
+ }
17
+ function isAskUserQuestionRequest(value) {
18
+ if (typeof value !== "object" || value === null) return false;
19
+ const question = value;
20
+ return typeof question.question === "string" && (question.description === void 0 || typeof question.description === "string") && (question.options === void 0 || isAskUserQuestionOptions(question.options)) && (question.multiSelect === void 0 || typeof question.multiSelect === "boolean");
21
+ }
22
+ function isAskUserQuestionBatchItem(value) {
23
+ if (!isAskUserQuestionRequest(value)) return false;
24
+ const question = value;
25
+ return typeof question.id === "string" && ASK_USER_QUESTION_ID_PATTERN.test(question.id) && (question.header === void 0 || typeof question.header === "string");
26
+ }
27
+ /**
28
+ * Type guard for the batched form of an `ask_user_question` interrupt. Hosts
29
+ * use this to select the multi-question UI and `AskUserQuestionsResolution`.
30
+ */
31
+ function isAskUserQuestionsInterrupt(payload) {
32
+ if (!isAskUserQuestionInterrupt(payload) || !isAskUserQuestionRequest(payload.question) || payload.tool_call_id !== void 0 && typeof payload.tool_call_id !== "string" || !Array.isArray(payload.questions) || payload.questions.length === 0 || payload.questions.length > 4) return false;
33
+ const ids = /* @__PURE__ */ new Set();
34
+ for (const question of payload.questions) {
35
+ if (!isAskUserQuestionBatchItem(question) || ids.has(question.id)) return false;
36
+ ids.add(question.id);
37
+ }
38
+ return true;
39
+ }
40
+ //#endregion
41
+ export { ASK_USER_QUESTION_ID_PATTERN, MAX_ASK_USER_QUESTIONS, isAskUserQuestionRequest, isAskUserQuestionsInterrupt };
42
+
43
+ //# sourceMappingURL=askUserQuestionsInterrupt.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"askUserQuestionsInterrupt.mjs","names":[],"sources":["../../../src/hitl/askUserQuestionsInterrupt.ts"],"sourcesContent":["import type {\n AskUserQuestionBatchItem,\n AskUserQuestionOption,\n AskUserQuestionRequest,\n AskUserQuestionsInterruptPayload,\n} from '@/types/hitl';\nimport { isAskUserQuestionInterrupt } from '@/types/hitl';\n\n/** Maximum questions supported by one batched clarification interaction. */\nexport const MAX_ASK_USER_QUESTIONS = 4;\n\n/** Safe identifier format for answer-map keys in a batched question. */\nexport const ASK_USER_QUESTION_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n\ninterface AskUserQuestionOptionCandidate {\n label?: unknown;\n value?: unknown;\n}\n\ninterface AskUserQuestionCandidate {\n question?: unknown;\n description?: unknown;\n options?: unknown;\n multiSelect?: unknown;\n}\n\ninterface AskUserQuestionBatchItemCandidate extends AskUserQuestionCandidate {\n id?: unknown;\n header?: unknown;\n}\n\nfunction isAskUserQuestionOption(\n value: unknown\n): value is AskUserQuestionOption {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const option = value as AskUserQuestionOptionCandidate;\n return typeof option.label === 'string' && typeof option.value === 'string';\n}\n\nfunction isAskUserQuestionOptions(\n value: unknown\n): value is AskUserQuestionOption[] {\n if (!Array.isArray(value)) {\n return false;\n }\n for (let index = 0; index < value.length; index++) {\n if (!Object.hasOwn(value, index) || !isAskUserQuestionOption(value[index])) {\n return false;\n }\n }\n return true;\n}\n\nexport function isAskUserQuestionRequest(\n value: unknown\n): value is AskUserQuestionRequest {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const question = value as AskUserQuestionCandidate;\n return (\n typeof question.question === 'string' &&\n (question.description === undefined ||\n typeof question.description === 'string') &&\n (question.options === undefined ||\n isAskUserQuestionOptions(question.options)) &&\n (question.multiSelect === undefined ||\n typeof question.multiSelect === 'boolean')\n );\n}\n\nfunction isAskUserQuestionBatchItem(\n value: unknown\n): value is AskUserQuestionBatchItem {\n if (!isAskUserQuestionRequest(value)) {\n return false;\n }\n const question = value as AskUserQuestionBatchItemCandidate;\n return (\n typeof question.id === 'string' &&\n ASK_USER_QUESTION_ID_PATTERN.test(question.id) &&\n (question.header === undefined || typeof question.header === 'string')\n );\n}\n\n/**\n * Type guard for the batched form of an `ask_user_question` interrupt. Hosts\n * use this to select the multi-question UI and `AskUserQuestionsResolution`.\n */\nexport function isAskUserQuestionsInterrupt(\n payload: unknown\n): payload is AskUserQuestionsInterruptPayload {\n if (\n !isAskUserQuestionInterrupt(payload) ||\n !isAskUserQuestionRequest(payload.question) ||\n (payload.tool_call_id !== undefined &&\n typeof payload.tool_call_id !== 'string') ||\n !Array.isArray(payload.questions) ||\n payload.questions.length === 0 ||\n payload.questions.length > MAX_ASK_USER_QUESTIONS\n ) {\n return false;\n }\n\n const ids = new Set<string>();\n for (const question of payload.questions) {\n if (!isAskUserQuestionBatchItem(question) || ids.has(question.id)) {\n return false;\n }\n ids.add(question.id);\n }\n return true;\n}\n"],"mappings":";;;AASA,MAAa,yBAAyB;;AAGtC,MAAa,+BAA+B;AAmB5C,SAAS,wBACP,OACgC;CAChC,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,MAAM,SAAS;CACf,OAAO,OAAO,OAAO,UAAU,YAAY,OAAO,OAAO,UAAU;AACrE;AAEA,SAAS,yBACP,OACkC;CAClC,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,OAAO;CAET,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SACxC,IAAI,CAAC,OAAO,OAAO,OAAO,KAAK,KAAK,CAAC,wBAAwB,MAAM,MAAM,GACvE,OAAO;CAGX,OAAO;AACT;AAEA,SAAgB,yBACd,OACiC;CACjC,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,MAAM,WAAW;CACjB,OACE,OAAO,SAAS,aAAa,aAC5B,SAAS,gBAAgB,KAAA,KACxB,OAAO,SAAS,gBAAgB,cACjC,SAAS,YAAY,KAAA,KACpB,yBAAyB,SAAS,OAAO,OAC1C,SAAS,gBAAgB,KAAA,KACxB,OAAO,SAAS,gBAAgB;AAEtC;AAEA,SAAS,2BACP,OACmC;CACnC,IAAI,CAAC,yBAAyB,KAAK,GACjC,OAAO;CAET,MAAM,WAAW;CACjB,OACE,OAAO,SAAS,OAAO,YACvB,6BAA6B,KAAK,SAAS,EAAE,MAC5C,SAAS,WAAW,KAAA,KAAa,OAAO,SAAS,WAAW;AAEjE;;;;;AAMA,SAAgB,4BACd,SAC6C;CAC7C,IACE,CAAC,2BAA2B,OAAO,KACnC,CAAC,yBAAyB,QAAQ,QAAQ,KACzC,QAAQ,iBAAiB,KAAA,KACxB,OAAO,QAAQ,iBAAiB,YAClC,CAAC,MAAM,QAAQ,QAAQ,SAAS,KAChC,QAAQ,UAAU,WAAW,KAC7B,QAAQ,UAAU,SAAA,GAElB,OAAO;CAGT,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,YAAY,QAAQ,WAAW;EACxC,IAAI,CAAC,2BAA2B,QAAQ,KAAK,IAAI,IAAI,SAAS,EAAE,GAC9D,OAAO;EAET,IAAI,IAAI,SAAS,EAAE;CACrB;CACA,OAAO;AACT"}
@@ -1,2 +1,4 @@
1
1
  import "./askUserQuestion.mjs";
2
+ import "./askUserQuestionsInterrupt.mjs";
3
+ import "./askUserQuestions.mjs";
2
4
  export {};
package/dist/esm/main.mjs CHANGED
@@ -102,6 +102,8 @@ import { createRunHandlers } from "./session/handlers.mjs";
102
102
  import { AgentSession, createAgentSession } from "./session/AgentSession.mjs";
103
103
  import "./session/index.mjs";
104
104
  import { askUserQuestion } from "./hitl/askUserQuestion.mjs";
105
+ import { ASK_USER_QUESTION_ID_PATTERN, MAX_ASK_USER_QUESTIONS, isAskUserQuestionsInterrupt } from "./hitl/askUserQuestionsInterrupt.mjs";
106
+ import { askUserQuestions } from "./hitl/askUserQuestions.mjs";
105
107
  import "./hitl/index.mjs";
106
108
  import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, HumanMessage, SystemMessage, ToolMessage, getBufferString, isAIMessage, isBaseMessage, isToolMessage } from "./langchain/messages.mjs";
107
109
  import { PromptTemplate } from "./langchain/prompts.mjs";
@@ -109,4 +111,4 @@ import { Runnable, RunnableLambda, RunnableSequence } from "./langchain/runnable
109
111
  import { DynamicStructuredTool, StructuredTool, Tool, tool } from "./langchain/tools.mjs";
110
112
  import "./langchain/index.mjs";
111
113
  import { BaseCheckpointSaver, Command, INTERRUPT, MemorySaver, interrupt, isInterrupted } from "@langchain/langgraph";
112
- export { AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, ChatOpenRouter, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, CustomChatMistralAI, CustomOpenAIClient, DATE_RANGE, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_MAX_SEALS, DEFAULT_MAX_TOOL_CALL_ARG_BYTES, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_STREAM_DELAY, DEFAULT_SUBAGENT_DESCRIPTION, DEFAULT_TOOL_TOKEN_MULTIPLIER, DynamicStructuredTool, EnvVar, FAILED_EXECUTION_FILE_REMINDER, FakeChatModel, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HandlerRegistry, HookRegistry, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, INTERRUPT, JsonlSessionStore, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MemorySaver, ModelEndHandler, MultiAgentGraph, OPENAI_RESPONSES_REPLAY_POSITIONS_KEY, ORIGINAL_CONTENT_MAX_CHARS, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, Providers, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StreamLimitExceededError, StructuredTool, SubagentExecutor, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, UnsafeTokenMeasurementError, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendPredecessorHandoffCue, appendTmpScratchReminder, applyContextPruning, applyEdit, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, attemptInvoke, bashAstFindingsToErrors, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentToolParams, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, checkValidNumber, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, composeAbortSignals, composeEventHandlers, computeAdaptivePieceSize, convertInjectedMessages, convertMessagesToContent, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createFakeStreamingLLM, createGraph, createHandlers, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createSearchTool, createSubagentToolDefinition, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createWorkspacePolicyHook, dateSchema, decodeFile, defaultOmitOptions, deserializeMessage, dispatchesChatModelStream, emptyOutputMessage, encodeFile, encodingForModel, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fetchSessionFiles, filterBashToolsByUsage, filterGraphSubagentResult, filterSubagentResult, filterToolsByUsage, findLastIndex, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAssistantTextPhase, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageCreationContentMetadata, getMessageId, getMessagesWithinTokenLimit, getReadRoots, getSpawn, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasNestedQuantifier, hasNestedQuantifiers, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, imageAttachmentContent, imagesSchema, initializeModel, interrupt, isAIMessage, isAnthropicLike, isBaseMessage, isContextOverflowError, isDangerousPattern, isFromAnyMcpServer, isFromMcpServer, isGoogleLike, isGraphSubagentConfig, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLikelyContextOverflowError, isOpenAILike, isPresent, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, maskConsumedToolResults, matchesQuery, messagesStateReducer, modifyDeltaProperties, newsSchema, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeServerFilter, normalizeSubagentConfigEntries, normalizeSubagentConfigs, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolStreamContentForProvider, querySchema, readIntent, readOutcomeFields, removePredecessorHandoffCue, repairOrphanedToolMessages, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveFetchProxyAgent, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveSearchOutcome, resolveStreamDelay, resolveStreamLimits, resolveSubagentConfigEntries, resolveSubagentConfigs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, runBashAstChecks, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, serializeMessage, serializeToolCallInput, shellQuote, shiftIndexTokenCountMap, shouldBypassProxy, shouldTriggerSummarization, sleep, smoothStream, spawnLocalProcess, splitAssistantTextContentByPhase, splitAtRecencyBoundary, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, videosSchema, withClientTimeout, withIntent, withMessageRole, withoutIntent };
114
+ export { AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, ASK_USER_QUESTION_ID_PATTERN, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, ChatOpenRouter, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, CustomChatMistralAI, CustomOpenAIClient, DATE_RANGE, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_MAX_SEALS, DEFAULT_MAX_TOOL_CALL_ARG_BYTES, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_STREAM_DELAY, DEFAULT_SUBAGENT_DESCRIPTION, DEFAULT_TOOL_TOKEN_MULTIPLIER, DynamicStructuredTool, EnvVar, FAILED_EXECUTION_FILE_REMINDER, FakeChatModel, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HandlerRegistry, HookRegistry, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, INTERRUPT, JsonlSessionStore, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MAX_ASK_USER_QUESTIONS, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MemorySaver, ModelEndHandler, MultiAgentGraph, OPENAI_RESPONSES_REPLAY_POSITIONS_KEY, ORIGINAL_CONTENT_MAX_CHARS, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, Providers, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StreamLimitExceededError, StructuredTool, SubagentExecutor, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, UnsafeTokenMeasurementError, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendPredecessorHandoffCue, appendTmpScratchReminder, applyContextPruning, applyEdit, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, askUserQuestions, attemptInvoke, bashAstFindingsToErrors, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentToolParams, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, checkValidNumber, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, composeAbortSignals, composeEventHandlers, computeAdaptivePieceSize, convertInjectedMessages, convertMessagesToContent, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createFakeStreamingLLM, createGraph, createHandlers, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createSearchTool, createSubagentToolDefinition, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createWorkspacePolicyHook, dateSchema, decodeFile, defaultOmitOptions, deserializeMessage, dispatchesChatModelStream, emptyOutputMessage, encodeFile, encodingForModel, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fetchSessionFiles, filterBashToolsByUsage, filterGraphSubagentResult, filterSubagentResult, filterToolsByUsage, findLastIndex, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAssistantTextPhase, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageCreationContentMetadata, getMessageId, getMessagesWithinTokenLimit, getReadRoots, getSpawn, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasNestedQuantifier, hasNestedQuantifiers, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, imageAttachmentContent, imagesSchema, initializeModel, interrupt, isAIMessage, isAnthropicLike, isAskUserQuestionsInterrupt, isBaseMessage, isContextOverflowError, isDangerousPattern, isFromAnyMcpServer, isFromMcpServer, isGoogleLike, isGraphSubagentConfig, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLikelyContextOverflowError, isOpenAILike, isPresent, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, maskConsumedToolResults, matchesQuery, messagesStateReducer, modifyDeltaProperties, newsSchema, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeServerFilter, normalizeSubagentConfigEntries, normalizeSubagentConfigs, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolStreamContentForProvider, querySchema, readIntent, readOutcomeFields, removePredecessorHandoffCue, repairOrphanedToolMessages, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveFetchProxyAgent, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveSearchOutcome, resolveStreamDelay, resolveStreamLimits, resolveSubagentConfigEntries, resolveSubagentConfigs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, runBashAstChecks, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, serializeMessage, serializeToolCallInput, shellQuote, shiftIndexTokenCountMap, shouldBypassProxy, shouldTriggerSummarization, sleep, smoothStream, spawnLocalProcess, splitAssistantTextContentByPhase, splitAtRecencyBoundary, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, videosSchema, withClientTimeout, withIntent, withMessageRole, withoutIntent };
@@ -0,0 +1,13 @@
1
+ //#region src/types/hitl.ts
2
+ /**
3
+ * Type guard narrowing an arbitrary value to an
4
+ * `AskUserQuestionInterruptPayload`. Same `unknown`-tolerant contract
5
+ * as `isToolApprovalInterrupt`.
6
+ */
7
+ function isAskUserQuestionInterrupt(payload) {
8
+ return typeof payload === "object" && payload !== null && payload.type === "ask_user_question";
9
+ }
10
+ //#endregion
11
+ export { isAskUserQuestionInterrupt };
12
+
13
+ //# sourceMappingURL=hitl.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hitl.mjs","names":[],"sources":["../../../src/types/hitl.ts"],"sourcesContent":["/**\n * First-class human-in-the-loop (HITL) types for `@librechat/agents`.\n * Surfaces the interrupt payload that `ToolNode` raises when a `PreToolUse`\n * hook returns `decision: 'ask'` and HITL is enabled on the run, plus the\n * resume-decision shape the host returns to continue or reject the tool.\n *\n * Mirrors the LangChain HITL middleware shape (action_requests /\n * review_configs) so hosts and clients can share rendering/UI semantics\n * across the langchain ecosystem.\n */\n\n/** Per-tool approval request emitted inside an interrupt payload. */\nexport interface ToolApprovalRequest {\n /** Stable id of the tool call (matches LangGraph `ToolCall.id`). */\n tool_call_id: string;\n /** Tool name being invoked. */\n name: string;\n /**\n * Arguments the tool is about to be invoked with — already resolved by\n * any `{{tool<i>turn<n>}}` references and any `updatedInput` returned\n * by the firing PreToolUse hook.\n */\n arguments: Record<string, unknown>;\n /**\n * Optional reason the hook supplied for asking (e.g., \"destructive\n * filesystem write\"). Hosts can render this verbatim.\n */\n description?: string;\n}\n\n/** Allowed host-side decisions for a `tool_approval` interrupt. */\nexport type ToolApprovalDecisionType =\n | 'approve'\n | 'reject'\n | 'edit'\n | 'respond';\n\n/** Per-action review configuration paired with each action_request. */\nexport interface ToolApprovalReviewConfig {\n /** Tool name (matches the `name` field on the corresponding action_request). */\n action_name: string;\n /**\n * Stable id of the tool call this review_config applies to (matches\n * the `tool_call_id` of the corresponding action_request). Lets a UI\n * map review_configs → action_requests directly when a batch\n * contains the same tool called more than once — by-position\n * mapping breaks down with duplicates.\n */\n tool_call_id: string;\n /** Decisions the host UI is allowed to surface for this action. */\n allowed_decisions: ToolApprovalDecisionType[];\n}\n\n/**\n * Resume value the host returns through `Run.resume(decisions)` after a\n * `tool_approval` interrupt. One entry per action_request, in the same\n * order. Hosts may also return a record keyed by `tool_call_id`; the SDK\n * handles either shape.\n *\n * Variants:\n * - `approve`: run the tool with its original (or hook-rewritten) args.\n * - `reject`: skip the tool, emit a blocked error `ToolMessage` with\n * `reason` surfaced to the model.\n * - `edit`: replace the tool's args with `updatedInput` (re-resolves\n * any `{{tool<i>turn<n>}}` placeholders) and run the tool.\n * - `respond`: skip the tool entirely and emit `responseText` as a\n * successful `ToolMessage`. Mirrors LangChain HITL middleware's\n * `respond` semantic — the human supplies the result the model sees,\n * bypassing tool execution. Useful when the user wants to short-circuit\n * a tool call with a hand-written answer (e.g., \"don't actually run\n * the search, just tell the model 'no relevant results'\").\n *\n * Note on hook semantics: `respond` does NOT fire the per-tool\n * `PostToolUse` hook (no real tool execution happened, so the\n * \"post-tool\" semantic doesn't apply). It DOES appear in the\n * `PostToolBatch` entry array with `status: 'success'` and the\n * user-supplied text as `toolOutput`, so batch-level audit /\n * convention hooks see the full set of outcomes.\n */\nexport type ToolApprovalDecision =\n | { type: 'approve' }\n | { type: 'reject'; reason?: string }\n | { type: 'edit'; updatedInput: Record<string, unknown> }\n | { type: 'respond'; responseText: string };\n\n/** Map form of resume decisions, keyed by tool call id. */\nexport type ToolApprovalDecisionMap = Record<string, ToolApprovalDecision>;\n\n/**\n * Categories of human-in-the-loop interrupts the SDK can raise. Hosts\n * narrow on `HumanInterruptPayload.type` to determine which payload\n * shape they're handling and which resume value to send back through\n * `Run.resume()`.\n *\n * Exported as a discrete type so downstream consumers (notably\n * LibreChat's wire types in `librechat-data-provider`) can mirror\n * the discriminator alongside their own host-side `PendingAction`\n * record without re-declaring the union themselves. Internal SDK\n * code narrows directly on the literal strings via the type guards\n * below; this type alias is primarily an integration-layer contract.\n */\nexport type HumanInterruptType = 'tool_approval' | 'ask_user_question';\n\n/** Identifies an interrupt that originated inside a checkpointed subagent. */\nexport interface SubagentInterruptScope {\n /** Child execution run id used by subagent update and usage events. */\n run_id: string;\n /** Child agent id that owns the interrupted tool call. */\n agent_id: string;\n /** Configured subagent type selected by the parent tool call. */\n subagent_type: string;\n /** Parent `subagent` tool call that launched this child. */\n parent_tool_call_id?: string;\n}\n\n/**\n * Structured payload the SDK passes to `interrupt()` when one or more\n * pending tool calls require host approval. All `ask`-decision tool calls\n * from a single ToolNode batch are bundled into one interrupt so the host\n * can render and resolve them together.\n *\n * Resume value: `ToolApprovalDecision[]` (in `action_requests` order) or\n * `ToolApprovalDecisionMap` (keyed by `tool_call_id`).\n */\nexport interface ToolApprovalInterruptPayload {\n type: 'tool_approval';\n action_requests: ToolApprovalRequest[];\n review_configs: ToolApprovalReviewConfig[];\n /** Hook-registry session whose policy raised this interrupt. */\n hook_session_id?: string;\n /** Present when the approval request was bridged from a child graph. */\n subagent?: SubagentInterruptScope;\n}\n\n/**\n * Pre-defined option the user can pick when answering an\n * `ask_user_question` interrupt. The selected option's `value` becomes\n * the resume value's `answer` field.\n */\nexport interface AskUserQuestionOption {\n /** Human-readable label rendered in the host UI. */\n label: string;\n /** Value returned via `AskUserQuestionResolution.answer` if picked. */\n value: string;\n}\n\n/** Question request emitted inside an `ask_user_question` interrupt. */\nexport interface AskUserQuestionRequest {\n /** The question to ask the human. */\n question: string;\n /** Optional context / description rendered alongside the question. */\n description?: string;\n /**\n * Optional pre-defined response options. When present, hosts can render\n * a picker; the user may still type a free-form answer when the host\n * UI allows it. Omit to require a free-form answer.\n */\n options?: AskUserQuestionOption[];\n /**\n * When `true`, the host UI may let the user pick several options; the\n * resulting `AskUserQuestionResolution.answer` is the selected option\n * values joined by `\", \"`. When omitted or `false`, hosts render a\n * single-select picker. Only meaningful alongside `options`.\n */\n multiSelect?: boolean;\n}\n\n/** One independently answerable question in a batched question request. */\nexport interface AskUserQuestionBatchItem extends AskUserQuestionRequest {\n /** Batch-unique identifier (`[A-Za-z][A-Za-z0-9_-]{0,63}`). */\n id: string;\n /** Optional short heading rendered above the question. */\n header?: string;\n}\n\n/** Input shape for one tool call that asks one to four questions together. */\nexport interface AskUserQuestionsRequest {\n questions: AskUserQuestionBatchItem[];\n}\n\n/**\n * Structured payload the SDK passes to `interrupt()` when an agent (or\n * a custom node) needs to ask the user a clarifying question. Mirrors\n * Claude Code's `AskUserQuestion` semantic. Resume value is\n * `AskUserQuestionResolution` for a single question, or\n * `AskUserQuestionsResolution` when `questions` is present.\n */\nexport interface AskUserQuestionInterruptPayload {\n type: 'ask_user_question';\n /**\n * Single-question request, or the first question as a compatibility\n * fallback when `questions` contains a batch. This lets existing hosts show\n * a useful preview during a staged rollout, but they must support `questions`\n * and `AskUserQuestionsResolution` before enabling a batched tool schema.\n */\n question: AskUserQuestionRequest;\n /** One to four questions collected by one `ask_user_question` tool call. */\n questions?: AskUserQuestionsRequest['questions'];\n /**\n * The `tool_call_id` of the ask-tool call that raised this interrupt,\n * when the tool body supplied it (see `askUserQuestion`'s `options`).\n * Lets hosts attribute the question — and later the answer — to the\n * exact tool-call content part instead of guessing by position, which\n * mislabels cards when a model emits several ask calls in one turn.\n */\n tool_call_id?: string;\n}\n\n/** Batch-specialized ask payload for hosts that render several questions. */\nexport interface AskUserQuestionsInterruptPayload\n extends AskUserQuestionInterruptPayload {\n questions: AskUserQuestionsRequest['questions'];\n}\n\n/**\n * Discriminated union of every interrupt payload the SDK raises. New\n * variants can be added without breaking existing handlers as long as\n * those handlers check `payload.type` before reading variant-specific\n * fields. Use the `isToolApprovalInterrupt` / `isAskUserQuestionInterrupt`\n * type guards for ergonomic narrowing.\n */\nexport type HumanInterruptPayload =\n | ToolApprovalInterruptPayload\n | AskUserQuestionInterruptPayload;\n\n/** Resume value the host returns for an `ask_user_question` interrupt. */\nexport interface AskUserQuestionResolution {\n /**\n * The human's answer. Free-form text, or — when `options` were\n * provided — one of the option `value`s (or, when the request set\n * `multiSelect`, several option `value`s joined by `\", \"`). Hosts may\n * also send any structured object their custom UI defines; see the\n * host docs for what your downstream consumer expects.\n */\n answer: string;\n}\n\n/** Resume value for a batched `ask_user_question` interrupt. */\nexport interface AskUserQuestionsResolution {\n /** Human answers keyed by each `AskUserQuestionBatchItem.id`. */\n answers: Record<string, string>;\n}\n\n/**\n * Type guard narrowing an arbitrary value to a `ToolApprovalInterruptPayload`.\n * Accepts `unknown` (not just `HumanInterruptPayload`) because hosts can\n * raise custom interrupt payloads from custom nodes — `getInterrupt()`\n * surfaces them as-is, and downstream code must validate the shape at\n * runtime before reading variant-specific fields.\n */\nexport function isToolApprovalInterrupt(\n payload: unknown\n): payload is ToolApprovalInterruptPayload {\n return (\n typeof payload === 'object' &&\n payload !== null &&\n (payload as { type?: unknown }).type === 'tool_approval'\n );\n}\n\n/**\n * Type guard narrowing an arbitrary value to an\n * `AskUserQuestionInterruptPayload`. Same `unknown`-tolerant contract\n * as `isToolApprovalInterrupt`.\n */\nexport function isAskUserQuestionInterrupt(\n payload: unknown\n): payload is AskUserQuestionInterruptPayload {\n return (\n typeof payload === 'object' &&\n payload !== null &&\n (payload as { type?: unknown }).type === 'ask_user_question'\n );\n}\n\n/**\n * Run-level configuration controlling HITL semantics. **HITL is OFF by\n * default** for now — the SDK ships the interrupt machinery, but the\n * default stays opt-in until host UIs (notably LibreChat) ship the\n * approval-rendering affordances needed to surface interrupts to end\n * users. Without that UI, an interrupt with no resolver looks like a\n * hung tool-call card. Hosts opt in explicitly with\n * `{ enabled: true }`. The intent is to flip this default to ON in a\n * future minor once the consumer ecosystem is ready to render\n * interrupts end-to-end.\n *\n * When enabled (`{ enabled: true }`):\n *\n * - `PreToolUse` hooks returning `decision: 'ask'` raise a real\n * LangGraph `interrupt()` instead of being treated as a synchronous\n * deny.\n * - `Run.create` installs a `MemorySaver` checkpointer fallback on the\n * run's compile options if the host did not provide one, since\n * LangGraph requires a checkpointer to suspend and resume.\n *\n * When disabled (the default — omitted, or `{ enabled: false }`):\n * `ask` decisions are fail-closed (blocked with an error\n * `ToolMessage`) and no checkpointer is implicitly attached. This\n * matches the pre-HITL behavior so existing hosts upgrading the SDK\n * see no change until they're ready to wire the resume UI.\n *\n * ## Scope: every tool the ToolNode runs\n *\n * The interrupt path is wired into both `dispatchToolEvents` (the\n * event-driven path) and `runDirectToolWithLifecycleHooks` (the\n * direct path used by `directToolNames` entries — graph-managed\n * handoff/subagent tools and every in-process `graphTool` instance).\n * `PreToolUse` hooks fire for every tool the ToolNode invokes, and\n * HITL approval gates every tool whose hook returns `'ask'` —\n * regardless of whether the tool is dispatched as an event or\n * invoked in-process. This convergence happened in two follow-up\n * commits to the original HITL surface (see `Graph.ts` —\n * `hookRegistry`/`humanInTheLoop` are passed in both\n * event-driven and legacy branches; and `ToolNode.runDirectToolWithLifecycleHooks`\n * — direct-path tools build their own single-tool `tool_approval`\n * payload and raise `interrupt()` the same way the event path does).\n *\n * Practical implications:\n * - Every host gets the full HITL surface across every tool the\n * model calls — event-dispatched, direct, mixed.\n * - `createToolPolicyHook` and `createWorkspacePolicyHook` apply\n * uniformly. A hook can be registered without knowing or caring\n * which path the tool will take.\n * - Direct tools that the host opted into via `directToolNames` no\n * longer bypass policy. If you need a tool to skip the hook\n * surface entirely, omit it from any registered matcher.\n *\n * ## Resume re-execution: every tool in the interrupted batch\n *\n * LangGraph rolls back to the start of the interrupted node on\n * resume. That means **every tool in the same batch as the one that\n * interrupted re-runs from the top on the resume pass**, not just\n * the interrupting tool, and not just the direct half (this used to\n * be framed as a direct-tool-specific concern; it is not — it\n * applies to event-dispatched siblings too). Practical contract:\n *\n * - The body of the interrupting tool itself runs **once** total\n * (the first pass interrupted *before* the body, the resume pass\n * ran the body after the host's decision was applied).\n * - The body of any sibling tool that already executed in the\n * same batch before the interrupting tool runs **twice** — once\n * on the first pass, once on the resume pass.\n * - `PreToolUse` hooks fire **once per pass per tool**. A hook\n * that always returns `'ask'` will loop forever on resume; real\n * hooks should be deterministic w.r.t. inputs and use the\n * `'ask' → host approves → resume → hook returns 'allow'`\n * pattern, where the second-pass `allow` reflects the host\n * having recorded the approval (e.g., a session-scoped approved-\n * paths set keyed by `runId`).\n *\n * Consequence: any tool with side effects MUST be idempotent if\n * there's any chance another tool in the same batch could trigger\n * an interrupt. This applies equally to direct tools (handoffs,\n * subagents) and to event tools.\n *\n * ### Guarding non-idempotent siblings via `interruptingToolNames`\n *\n * The \"must be idempotent\" rule above is unavoidable in the general\n * case, but the SDK can protect siblings against the one interrupt\n * shape it can predict: a tool whose *body* raises `interrupt()`\n * mid-execution — the `ask_user_question` shape, where the tool\n * suspends the run to collect a human answer. Declare such tools in\n * `RunConfig.interruptingToolNames`\n * ({@link ToolNodeOptions.interruptingToolNames}) and the ToolNode\n * schedules them, within each batch, **ahead of** their\n * non-interrupting direct siblings. When one interrupts, the batch\n * unwinds before any declared-safe sibling has run, so the sibling\n * executes exactly once (on resume) instead of twice. Empirically:\n *\n * - A **direct** sibling sharing the interrupter's in-process\n * `Promise.all` is the only shape that double-executes; declaring\n * the interrupter closes it.\n * - An **event-dispatched** sibling is already safe without any\n * config: the ToolNode awaits the whole direct group (where the\n * body interrupt unwinds) before it dispatches event tools, so a\n * dispatched sibling never runs on the first pass.\n *\n * This is a *scheduling* guard, not full resume idempotency: it only\n * covers tools that interrupt from their own body and only protects\n * siblings scheduled after them. It does not retroactively make a\n * `PreToolUse` `'ask'` gate on tool B stop tool A (already executed)\n * from re-running — unless B is itself declared interrupting, so it\n * runs first. Tools with side effects should still be written\n * idempotent as defense in depth.\n *\n * The guard only REORDERS the direct group — declaring a name does not\n * force it onto the direct path. The interrupting tool must already be a\n * real in-process graphTool (the only kind whose body can reach\n * `interrupt()`). A name that resolves to a schema-only event stub (an\n * inherited `toolDefinition` with no executable instance, e.g. in a\n * self-spawned child that scrubs `graphTools`) stays event-dispatched\n * and the ordering is a no-op for it.\n *\n * ## Note on idempotency\n *\n * Same root cause as the resume re-execution above: LangGraph\n * re-runs the interrupted node from the start on resume, which\n * fires `PreToolUse` hooks again. Hooks that produce side effects\n * (logging, external calls) will see at least two invocations per\n * paused turn — exactly two for the interrupting tool, possibly\n * more across siblings.\n */\nexport interface HumanInTheLoopConfig {\n /**\n * Master switch. Defaults to `false` — omit the field (or pass\n * `false`) to keep HITL off, or set `true` to opt in once the host\n * UI is ready to render and resolve `tool_approval` interrupts.\n */\n enabled?: boolean;\n}\n\n/**\n * Snapshot of an in-flight interrupt surfaced from `Run.processStream`\n * via `run.getInterrupt()`. Hosts persist this alongside their job\n * record so they can later call `Run.resume(decisions)` against a Run\n * compiled with the same `thread_id` / checkpointer.\n *\n * The `payload` type defaults to `HumanInterruptPayload` (the SDK's\n * built-in `tool_approval` / `ask_user_question` discriminated union)\n * for ergonomic narrowing in the common case. Hosts that raise custom\n * interrupt payloads from custom graph nodes can pass the type\n * parameter (`run.getInterrupt<MyCustom>()` or\n * `RunInterruptResult<MyCustom>`) — the SDK does not validate the\n * runtime shape, it just transports whatever the node passed to\n * `interrupt()`. Use the `isToolApprovalInterrupt` /\n * `isAskUserQuestionInterrupt` guards (which accept `unknown`) when\n * the source of the interrupt isn't statically known.\n */\nexport interface RunInterruptResult<TPayload = HumanInterruptPayload> {\n /** Stable id of the LangGraph interrupt (from `Interrupt.id`). */\n interruptId: string;\n /** `thread_id` the run was bound to — required to resume. */\n threadId?: string;\n /** LangGraph checkpoint id that contains the paused interrupt task. */\n checkpointId?: string;\n /** LangGraph checkpoint namespace for the paused interrupt task. */\n checkpointNs?: string;\n /** Structured payload describing what needs human input. */\n payload: TPayload;\n}\n"],"mappings":";;;;;;AAyQA,SAAgB,2BACd,SAC4C;CAC5C,OACE,OAAO,YAAY,YACnB,YAAY,QACX,QAA+B,SAAS;AAE7C"}
@@ -0,0 +1,24 @@
1
+ import type { AskUserQuestionsRequest, AskUserQuestionsResolution } from '@/types/hitl';
2
+ /**
3
+ * Suspend once to collect answers to several related questions. The first
4
+ * question is also included in the legacy `question` field so existing hosts
5
+ * can render a useful fallback during a staged rollout.
6
+ *
7
+ * Question ids must be non-empty and unique within the batch. The helper
8
+ * accepts at most four questions so hosts can render the interaction as one
9
+ * focused decision surface rather than an unbounded form.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const { answers } = askUserQuestions({
14
+ * questions: [
15
+ * { id: 'environment', question: 'Which environment?' },
16
+ * { id: 'region', question: 'Which region?' },
17
+ * ],
18
+ * });
19
+ * return `Deploy to ${answers.environment} in ${answers.region}`;
20
+ * ```
21
+ */
22
+ export declare function askUserQuestions(request: AskUserQuestionsRequest, options?: {
23
+ toolCallId?: string;
24
+ }): AskUserQuestionsResolution;
@@ -0,0 +1,11 @@
1
+ import type { AskUserQuestionRequest, AskUserQuestionsInterruptPayload } from '@/types/hitl';
2
+ /** Maximum questions supported by one batched clarification interaction. */
3
+ export declare const MAX_ASK_USER_QUESTIONS = 4;
4
+ /** Safe identifier format for answer-map keys in a batched question. */
5
+ export declare const ASK_USER_QUESTION_ID_PATTERN: RegExp;
6
+ export declare function isAskUserQuestionRequest(value: unknown): value is AskUserQuestionRequest;
7
+ /**
8
+ * Type guard for the batched form of an `ask_user_question` interrupt. Hosts
9
+ * use this to select the multi-question UI and `AskUserQuestionsResolution`.
10
+ */
11
+ export declare function isAskUserQuestionsInterrupt(payload: unknown): payload is AskUserQuestionsInterruptPayload;
@@ -4,3 +4,5 @@
4
4
  * `askUserQuestion()`) live here.
5
5
  */
6
6
  export { askUserQuestion } from './askUserQuestion';
7
+ export { askUserQuestions } from './askUserQuestions';
8
+ export { ASK_USER_QUESTION_ID_PATTERN, isAskUserQuestionsInterrupt, MAX_ASK_USER_QUESTIONS, } from './askUserQuestionsInterrupt';