@dudko.dev/agent-web 0.0.45 → 0.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -95,7 +95,7 @@ import {
95
95
  toolRunContextOf,
96
96
  withDeadline,
97
97
  wrapToolsForRun
98
- } from "./chunk-236RCVAZ.js";
98
+ } from "./chunk-PTJA7V23.js";
99
99
  import {
100
100
  FILES_STORE,
101
101
  KEYS_STORE,
@@ -1388,7 +1388,7 @@ ${note.trim()}` : "";
1388
1388
  var defaultPrompts = {
1389
1389
  planner: (ctx) => ({
1390
1390
  system: (ctx.mode === "prompted" ? PLANNER_PROMPTED : PLANNER_NATIVE) + (ctx.skills ? PLANNER_SKILLS : "") + (ctx.tiers ? ctx.mode === "prompted" ? PLANNER_TIERS_PROMPTED : PLANNER_TIERS_NATIVE : "") + (ctx.searchMode ? PLANNER_SEARCH : "") + (ctx.sandbox ? `
1391
- ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("SKILLS", ctx.skills) + `
1391
+ ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("ASKING THE USER", ctx.askUser) + section("SKILLS", ctx.skills) + `
1392
1392
 
1393
1393
  TOOLS:
1394
1394
  ${ctx.toolCatalog}`,
@@ -1396,7 +1396,7 @@ ${ctx.toolCatalog}`,
1396
1396
  }),
1397
1397
  executor: (ctx) => ({
1398
1398
  system: (ctx.mode === "prompted" ? EXECUTOR_PROMPTED : EXECUTOR_NATIVE) + (ctx.searchMode ? EXECUTOR_SEARCH : "") + (ctx.skills ? EXECUTOR_SKILLS : "") + (ctx.learning ? executorLearning(ctx.learning.fetch) : "") + (ctx.sandbox ? `
1399
- - ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("SKILLS", ctx.skills) + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
1399
+ - ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("ASKING THE USER", ctx.askUser) + section("SKILLS", ctx.skills) + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
1400
1400
  prompt: [
1401
1401
  `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
1402
1402
  stateBlock(ctx.state).trimStart(),
@@ -3599,6 +3599,10 @@ var humanWaitOf = (event) => {
3599
3599
  return { key: `${path}elicitation:${current.id}`, waiting: true };
3600
3600
  case "mcp.elicitation-answered":
3601
3601
  return { key: `${path}elicitation:${current.id}`, waiting: false };
3602
+ case "user.question-asked":
3603
+ return { key: `${path}question:${current.id}`, waiting: true };
3604
+ case "user.question-answered":
3605
+ return { key: `${path}question:${current.id}`, waiting: false };
3602
3606
  default:
3603
3607
  return void 0;
3604
3608
  }
@@ -3632,6 +3636,425 @@ var followHumanWaits = (clock) => {
3632
3636
  };
3633
3637
  };
3634
3638
 
3639
+ // src/tools/ask-user.ts
3640
+ import { jsonSchema as jsonSchema3, tool as tool4 } from "ai";
3641
+
3642
+ // src/tools/ask-user-shared.ts
3643
+ var ASK_USER_TOOL = "ask_user";
3644
+ var ASK_USER_TIMEOUT_MS = 3e5;
3645
+ var ASK_USER_TIMEOUT_MAX_MS = 2147483647;
3646
+ var ASK_USER_MAX_PER_RUN = 3;
3647
+ var ASK_USER_MIN_OPTIONS = 2;
3648
+ var ASK_USER_MAX_OPTIONS = 6;
3649
+ var ASK_USER_QUESTION_MAX_CHARS = 500;
3650
+ var ASK_USER_LABEL_MAX_CHARS = 80;
3651
+ var ASK_USER_DESCRIPTION_MAX_CHARS = 200;
3652
+ var ASK_USER_OTHER_MAX_CHARS = 2e3;
3653
+ var ASK_USER_TRUNCATED = "... [truncated]";
3654
+ var AskUserInputError = class extends Error {
3655
+ constructor(message) {
3656
+ super(message);
3657
+ this.name = "AskUserInputError";
3658
+ }
3659
+ toJSON() {
3660
+ return this.message;
3661
+ }
3662
+ };
3663
+ var shownValue = (value) => typeof value === "number" ? String(value) : JSON.stringify(value) ?? String(value);
3664
+ var timeoutOf = (value) => {
3665
+ if (value === void 0 || value === null) {
3666
+ return ASK_USER_TIMEOUT_MS;
3667
+ }
3668
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
3669
+ throw new Error(
3670
+ `askUser.timeoutMs must be a number of at least 0 (0 or Infinity: no limit) (got ${shownValue(value)})`
3671
+ );
3672
+ }
3673
+ return value === 0 || value > ASK_USER_TIMEOUT_MAX_MS ? 0 : Math.max(1, Math.floor(value));
3674
+ };
3675
+ var maxPerRunOf = (value) => {
3676
+ if (value === void 0 || value === null) {
3677
+ return ASK_USER_MAX_PER_RUN;
3678
+ }
3679
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
3680
+ throw new Error(
3681
+ `askUser.maxPerRun must be a whole number of at least 1 (got ${shownValue(value)})`
3682
+ );
3683
+ }
3684
+ return value;
3685
+ };
3686
+ var resolveAskUser = (raw) => {
3687
+ if (raw === void 0 || raw === null || raw === false) {
3688
+ return void 0;
3689
+ }
3690
+ if (raw === true) {
3691
+ return { timeoutMs: ASK_USER_TIMEOUT_MS, maxPerRun: ASK_USER_MAX_PER_RUN };
3692
+ }
3693
+ if (typeof raw !== "object" || Array.isArray(raw)) {
3694
+ throw new Error(`askUser must be true, false or { onQuestion?, timeoutMs?, maxPerRun? }`);
3695
+ }
3696
+ const o = raw;
3697
+ if (o.onQuestion !== void 0 && typeof o.onQuestion !== "function") {
3698
+ throw new Error(`askUser.onQuestion must be a function (got ${typeof o.onQuestion})`);
3699
+ }
3700
+ return {
3701
+ timeoutMs: timeoutOf(o.timeoutMs),
3702
+ maxPerRun: maxPerRunOf(o.maxPerRun),
3703
+ ...typeof o.onQuestion === "function" ? { onQuestion: o.onQuestion } : {}
3704
+ };
3705
+ };
3706
+ var INVISIBLE3 = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F​-‏‪-‮⁠-⁩]/g;
3707
+ var isPlainObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3708
+ var cleanAskUserText = (raw, oneLine = false) => {
3709
+ if (typeof raw !== "string") {
3710
+ return "";
3711
+ }
3712
+ const text = raw.replace(/\r\n?/g, "\n").replace(INVISIBLE3, "");
3713
+ return (oneLine ? text.replace(/\s+/g, " ") : text.replace(/\t/g, " ").replace(/\n{3,}/g, "\n\n")).trim();
3714
+ };
3715
+ var fix = (problem) => new AskUserInputError(
3716
+ `${ASK_USER_TOOL} was not asked: ${problem}. Fix the arguments and call ${ASK_USER_TOOL} again - or decide yourself, and say what you assumed.`
3717
+ );
3718
+ var flagOf = (value, name) => {
3719
+ if (value === void 0 || value === null) {
3720
+ return false;
3721
+ }
3722
+ if (typeof value !== "boolean") {
3723
+ throw fix(`"${name}" must be true or false`);
3724
+ }
3725
+ return value;
3726
+ };
3727
+ var checkAskUserInput = (raw) => {
3728
+ if (!isPlainObject2(raw)) {
3729
+ throw fix("the arguments must be an object { question, options, multiple?, allowOther? }");
3730
+ }
3731
+ const question = cleanAskUserText(raw.question);
3732
+ if (!question) {
3733
+ throw fix('"question" must be a non-empty text');
3734
+ }
3735
+ if (question.length > ASK_USER_QUESTION_MAX_CHARS) {
3736
+ throw fix(
3737
+ `"question" is ${question.length} characters; keep it to ${ASK_USER_QUESTION_MAX_CHARS}`
3738
+ );
3739
+ }
3740
+ if (!Array.isArray(raw.options)) {
3741
+ throw fix(`"options" must be a list of ${ASK_USER_MIN_OPTIONS}-${ASK_USER_MAX_OPTIONS} options`);
3742
+ }
3743
+ if (raw.options.length < ASK_USER_MIN_OPTIONS || raw.options.length > ASK_USER_MAX_OPTIONS) {
3744
+ throw fix(
3745
+ `give ${ASK_USER_MIN_OPTIONS} to ${ASK_USER_MAX_OPTIONS} options (got ${raw.options.length})`
3746
+ );
3747
+ }
3748
+ const options = [];
3749
+ const seen = /* @__PURE__ */ new Set();
3750
+ raw.options.forEach((item, i) => {
3751
+ const at = `option ${i + 1}`;
3752
+ const o = typeof item === "string" ? { label: item } : item;
3753
+ if (!isPlainObject2(o)) {
3754
+ throw fix(`${at} must be { label, description? }`);
3755
+ }
3756
+ const label = cleanAskUserText(o.label, true);
3757
+ if (!label) {
3758
+ throw fix(`${at} needs a non-empty "label"`);
3759
+ }
3760
+ if (label.length > ASK_USER_LABEL_MAX_CHARS) {
3761
+ throw fix(
3762
+ `the label of ${at} is ${label.length} characters; keep it to ${ASK_USER_LABEL_MAX_CHARS}`
3763
+ );
3764
+ }
3765
+ const key = label.toLowerCase();
3766
+ if (seen.has(key)) {
3767
+ throw fix(`two options have the label ${JSON.stringify(label)}; labels must differ`);
3768
+ }
3769
+ seen.add(key);
3770
+ if (o.description !== void 0 && o.description !== null && typeof o.description !== "string") {
3771
+ throw fix(`the description of ${at} must be a text`);
3772
+ }
3773
+ const description = cleanAskUserText(o.description, true);
3774
+ if (description.length > ASK_USER_DESCRIPTION_MAX_CHARS) {
3775
+ throw fix(
3776
+ `the description of ${at} is ${description.length} characters; keep it to ${ASK_USER_DESCRIPTION_MAX_CHARS}`
3777
+ );
3778
+ }
3779
+ options.push(description ? { label, description } : { label });
3780
+ });
3781
+ return {
3782
+ question,
3783
+ options,
3784
+ multiple: flagOf(raw.multiple, "multiple"),
3785
+ allowOther: flagOf(raw.allowOther, "allowOther")
3786
+ };
3787
+ };
3788
+ var checkAskUserAnswer = (q, raw) => {
3789
+ if (!isPlainObject2(raw)) {
3790
+ return { ok: false, reason: "the answer is not an object" };
3791
+ }
3792
+ const keys = ["choice", "other", "declined"].filter((k) => Object.hasOwn(raw, k));
3793
+ if (keys.length !== 1) {
3794
+ return { ok: false, reason: "an answer holds exactly one of choice, other or declined" };
3795
+ }
3796
+ if (keys[0] === "declined") {
3797
+ return raw.declined === true ? { ok: true, value: { kind: "declined" } } : { ok: false, reason: "declined must be true" };
3798
+ }
3799
+ if (keys[0] === "other") {
3800
+ if (!q.allowOther) {
3801
+ return { ok: false, reason: "the question did not allow an answer in the person\u2019s own words" };
3802
+ }
3803
+ const text = cleanAskUserText(raw.other);
3804
+ if (!text) {
3805
+ return { ok: false, reason: "other must be a non-empty text" };
3806
+ }
3807
+ return {
3808
+ ok: true,
3809
+ value: {
3810
+ kind: "other",
3811
+ text: text.length > ASK_USER_OTHER_MAX_CHARS ? `${text.slice(0, ASK_USER_OTHER_MAX_CHARS)}${ASK_USER_TRUNCATED}` : text
3812
+ }
3813
+ };
3814
+ }
3815
+ const choice = raw.choice;
3816
+ if (!Array.isArray(choice) || choice.length === 0) {
3817
+ return { ok: false, reason: "choice must be a non-empty list of labels" };
3818
+ }
3819
+ const offered = new Set(q.options.map((o) => o.label));
3820
+ const picked = [];
3821
+ for (const label of choice) {
3822
+ if (typeof label !== "string" || !offered.has(label)) {
3823
+ return { ok: false, reason: "choice holds a label that was not offered" };
3824
+ }
3825
+ if (picked.includes(label)) {
3826
+ return { ok: false, reason: "choice names a label twice" };
3827
+ }
3828
+ picked.push(label);
3829
+ }
3830
+ if (!q.multiple && picked.length > 1) {
3831
+ return { ok: false, reason: "the question allowed one option only" };
3832
+ }
3833
+ return { ok: true, value: { kind: "choice", choice: picked } };
3834
+ };
3835
+ var isAskUserPark = (value) => isPlainObject2(value) && value.park === true;
3836
+ var GO_ON = "Do not ask again: go on with your best judgment, and say in your answer what you assumed.";
3837
+ var askUserResultText = (r) => {
3838
+ switch (r.kind) {
3839
+ case "choice":
3840
+ return `The user chose: ${r.choice.map((c) => JSON.stringify(c)).join(", ")}. Go on with that.`;
3841
+ case "other":
3842
+ return `The user did not pick an option and answered in their own words: ${JSON.stringify(r.text)}. Go on with that.`;
3843
+ case "declined":
3844
+ return `The user chose not to answer. ${GO_ON}`;
3845
+ case "timeout":
3846
+ return `The user did not answer in time. ${GO_ON}`;
3847
+ case "no-answer":
3848
+ return `The question could not be put to the user or was not answered. ${GO_ON}`;
3849
+ case "cap":
3850
+ return `You have already asked the user ${r.maxPerRun} question(s) in this run - the most allowed. Do not ask again: decide yourself, and say in your answer what you assumed.`;
3851
+ }
3852
+ };
3853
+ var askUserNote = (q) => [
3854
+ `Question for the user: ${q.question}`,
3855
+ ...q.options.map((o, i) => `${i + 1}. ${o.label}${o.description ? ` - ${o.description}` : ""}`),
3856
+ ...q.multiple ? ["(several may be chosen)"] : [],
3857
+ ...q.allowOther ? ["(an answer in their own words is allowed)"] : [],
3858
+ 'Answer with { "output": { "choice": ["<label>"] } }, { "output": { "other": "<text>" } } or { "output": { "declined": true } }.'
3859
+ ].join("\n");
3860
+ var ASK_USER_INPUT_SCHEMA = {
3861
+ type: "object",
3862
+ properties: {
3863
+ question: {
3864
+ type: "string",
3865
+ description: `One short question for the user, at most ${ASK_USER_QUESTION_MAX_CHARS} characters.`
3866
+ },
3867
+ options: {
3868
+ type: "array",
3869
+ description: `${ASK_USER_MIN_OPTIONS} to ${ASK_USER_MAX_OPTIONS} options the user picks from.`,
3870
+ items: {
3871
+ type: "object",
3872
+ properties: {
3873
+ label: {
3874
+ type: "string",
3875
+ description: `What the user picks: short and distinct, at most ${ASK_USER_LABEL_MAX_CHARS} characters.`
3876
+ },
3877
+ description: {
3878
+ type: "string",
3879
+ description: `Optional: one line under the label, at most ${ASK_USER_DESCRIPTION_MAX_CHARS} characters.`
3880
+ }
3881
+ },
3882
+ required: ["label"],
3883
+ additionalProperties: false
3884
+ }
3885
+ },
3886
+ multiple: {
3887
+ type: "boolean",
3888
+ description: "true: the user may pick several options. Default false."
3889
+ },
3890
+ allowOther: {
3891
+ type: "boolean",
3892
+ description: "true: the user may answer in their own words instead. Default false."
3893
+ }
3894
+ },
3895
+ required: ["question", "options"],
3896
+ additionalProperties: false
3897
+ };
3898
+ var ASK_USER_PROMPT_HINT = "{ question: string, options: { label: string, description?: string }[], multiple?: boolean, allowOther?: boolean }";
3899
+ var askUserDescription = (s) => `Ask the user ONE closed question with ${ASK_USER_MIN_OPTIONS}-${ASK_USER_MAX_OPTIONS} options and wait for the answer. Use it only when the work cannot be done well without a choice only the user can make (the options change the result, and no sensible default exists) - never for what the tools, the conversation or a sensible default can settle. Give one short question and short, distinct labels (a one-line description under a label is optional); "multiple": true lets the user pick several, "allowOther": true lets them answer in their own words. The result says what the user chose, or that they did not answer - then go on with your best judgment and say what you assumed. At most ${s.maxPerRun} question(s) per run.`;
3900
+ var ASK_USER_PLANNER_NOTE = `The executor can ask the user ONE closed question with ${ASK_USER_MIN_OPTIONS}-${ASK_USER_MAX_OPTIONS} options (the ${ASK_USER_TOOL} tool). This is the one exception to "never ask the user": plan such a step only when the request leaves a choice that only the user can make (the options change the result, and no sensible default exists), as its own step before the work that depends on the answer. Anything the tools, the conversation or a sensible default can settle is not asked.`;
3901
+ var ASK_USER_EXECUTOR_NOTE = `If the current step cannot be done well without a choice only the user can make, call ${ASK_USER_TOOL} with one short question and ${ASK_USER_MIN_OPTIONS}-${ASK_USER_MAX_OPTIONS} short options instead of guessing, then go on with the answer. If the user declined or did not answer, go on with your best judgment and say what you assumed. Never ask what the tools, the conversation or a sensible default can settle, and never ask the same thing twice.`;
3902
+ var newId = () => {
3903
+ const c = globalThis.crypto;
3904
+ return typeof c?.randomUUID === "function" ? c.randomUUID() : `q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
3905
+ };
3906
+ var abortReason = (signal) => {
3907
+ if (signal?.reason !== void 0) {
3908
+ return signal.reason;
3909
+ }
3910
+ const err = new Error("Aborted");
3911
+ err.name = "AbortError";
3912
+ return err;
3913
+ };
3914
+ var namedError = (message, name) => Object.assign(new Error(message), { name });
3915
+ var askUserAnsweredEvent = (id, action, automatic, extra = {}) => ({
3916
+ type: "user.question-answered",
3917
+ id,
3918
+ action,
3919
+ automatic,
3920
+ ...extra.choice ? { choice: [...extra.choice] } : {},
3921
+ ...extra.reason ? { reason: extra.reason } : {}
3922
+ });
3923
+ var answeredWith = (id, answer) => answer.kind === "choice" ? askUserAnsweredEvent(id, "choice", false, { choice: answer.choice }) : askUserAnsweredEvent(id, answer.kind, false);
3924
+ var askTheUser = async (deps, call, raw) => {
3925
+ const q = checkAskUserInput(raw);
3926
+ const { settings } = deps;
3927
+ if (call.asked.count >= settings.maxPerRun) {
3928
+ deps.log?.(
3929
+ `[ask_user] not asked: ${settings.maxPerRun} question(s) were already asked in this run (askUser.maxPerRun)`
3930
+ );
3931
+ return { text: askUserResultText({ kind: "cap", maxPerRun: settings.maxPerRun }) };
3932
+ }
3933
+ if (call.signal?.aborted) {
3934
+ throw abortReason(call.signal);
3935
+ }
3936
+ call.asked.count += 1;
3937
+ const id = call.id ?? newId();
3938
+ const request = {
3939
+ id,
3940
+ ...q,
3941
+ options: q.options.map((o) => ({ ...o })),
3942
+ ...call.step !== void 0 ? { step: call.step } : {},
3943
+ ...call.runId ? { runId: call.runId } : {},
3944
+ ...call.subagent ? { subagent: { ...call.subagent } } : {}
3945
+ };
3946
+ call.emit?.({
3947
+ type: "user.question-asked",
3948
+ id,
3949
+ question: q.question,
3950
+ options: q.options.map((o) => ({ ...o })),
3951
+ multiple: q.multiple,
3952
+ allowOther: q.allowOther,
3953
+ ...call.step !== void 0 ? { step: call.step } : {},
3954
+ ...call.subagent ? { subagent: { ...call.subagent } } : {}
3955
+ });
3956
+ const controller = new AbortController();
3957
+ let timer;
3958
+ let onAbort;
3959
+ const resume = call.pause?.();
3960
+ const wait = await new Promise((resolve) => {
3961
+ if (settings.timeoutMs > 0) {
3962
+ timer = setTimeout(() => resolve({ kind: "timeout" }), settings.timeoutMs);
3963
+ }
3964
+ onAbort = () => resolve({ kind: "stopped" });
3965
+ call.signal?.addEventListener("abort", onAbort, { once: true });
3966
+ Promise.resolve().then(() => deps.handler(request, { signal: controller.signal })).then(
3967
+ (value) => resolve({ kind: "answer", value }),
3968
+ (error) => resolve({ kind: "error", error })
3969
+ );
3970
+ });
3971
+ resume?.();
3972
+ if (timer !== void 0) {
3973
+ clearTimeout(timer);
3974
+ }
3975
+ if (onAbort) {
3976
+ call.signal?.removeEventListener("abort", onAbort);
3977
+ }
3978
+ switch (wait.kind) {
3979
+ case "stopped":
3980
+ controller.abort(namedError("the run was stopped while the question waited", "AbortError"));
3981
+ call.emit?.(askUserAnsweredEvent(id, "stopped", true));
3982
+ throw abortReason(call.signal);
3983
+ case "timeout":
3984
+ controller.abort(
3985
+ namedError(`no answer within ${settings.timeoutMs} ms (askUser.timeoutMs)`, "TimeoutError")
3986
+ );
3987
+ call.emit?.(askUserAnsweredEvent(id, "timeout", true));
3988
+ return { text: askUserResultText({ kind: "timeout" }) };
3989
+ case "error": {
3990
+ controller.abort(wait.error);
3991
+ const name = wait.error?.name;
3992
+ deps.log?.(
3993
+ `[ask_user] the host's onQuestion failed (${typeof name === "string" ? name.slice(0, 40) : "error"}); the question counts as not answered`
3994
+ );
3995
+ call.emit?.(askUserAnsweredEvent(id, "declined", true, { reason: "handler-error" }));
3996
+ return { text: askUserResultText({ kind: "no-answer" }) };
3997
+ }
3998
+ }
3999
+ if (isAskUserPark(wait.value)) {
4000
+ if (call.mayPark) {
4001
+ return { park: { id, note: askUserNote(q) } };
4002
+ }
4003
+ deps.log?.(
4004
+ `[ask_user] { park: true } needs the Node package's persistence.journal and a tool call of the run; the question counts as not answered`
4005
+ );
4006
+ call.emit?.(askUserAnsweredEvent(id, "declined", true, { reason: "cannot-park" }));
4007
+ return { text: askUserResultText({ kind: "no-answer" }) };
4008
+ }
4009
+ const checked = checkAskUserAnswer(q, wait.value);
4010
+ if (!checked.ok) {
4011
+ deps.log?.(`[ask_user] the host's answer was not used: ${checked.reason}`);
4012
+ call.emit?.(askUserAnsweredEvent(id, "declined", true, { reason: "invalid-answer" }));
4013
+ return { text: askUserResultText({ kind: "no-answer" }) };
4014
+ }
4015
+ call.emit?.(answeredWith(id, checked.value));
4016
+ return { text: askUserResultText(checked.value) };
4017
+ };
4018
+
4019
+ // src/tools/ask-user.ts
4020
+ var routes = /* @__PURE__ */ new WeakMap();
4021
+ var routeAskUser = (config, channel, subagent) => {
4022
+ routes.set(config, { ...channel, subagent });
4023
+ };
4024
+ var askUserRouteOf = (config) => routes.get(config);
4025
+ var createAskUserTool = (settings, log) => {
4026
+ const t = tool4({
4027
+ description: askUserDescription(settings),
4028
+ inputSchema: jsonSchema3(
4029
+ ASK_USER_INPUT_SCHEMA
4030
+ ),
4031
+ execute: async (input, options) => {
4032
+ const run = toolRunContextOf(options);
4033
+ const channel = run?.askUser;
4034
+ if (!run || !channel) {
4035
+ throw new Error(`${ASK_USER_TOOL} can only be called inside a run`);
4036
+ }
4037
+ const subagent = run.subagent ?? channel.subagent;
4038
+ const out = await askTheUser(
4039
+ { handler: channel.handler, settings: channel.settings, log },
4040
+ {
4041
+ ...run.step ? { step: run.step } : {},
4042
+ ...run.runId ? { runId: run.runId } : {},
4043
+ ...subagent ? { subagent } : {},
4044
+ signal: options?.abortSignal ?? run.signal,
4045
+ emit: (event) => run.emit(event),
4046
+ asked: channel.asked,
4047
+ ...run.clock ? { pause: run.clock.pause } : {}
4048
+ },
4049
+ input
4050
+ );
4051
+ return "text" in out ? out.text : "";
4052
+ }
4053
+ });
4054
+ t.promptHint = ASK_USER_PROMPT_HINT;
4055
+ return t;
4056
+ };
4057
+
3635
4058
  // src/agent/control.ts
3636
4059
  var ports = /* @__PURE__ */ new WeakMap();
3637
4060
  var queuedEvent = (m) => ({
@@ -3881,7 +4304,8 @@ var parsePlainText = (raw) => {
3881
4304
  const text = stripFences(raw);
3882
4305
  const obj = asObject(text);
3883
4306
  if (obj && typeof obj.reply === "string") return obj.reply.trim();
3884
- return looksLikeJson(text) ? "" : text.trim();
4307
+ if (looksLikeJson(text)) return "";
4308
+ return stripThinking(raw || "").trim();
3885
4309
  };
3886
4310
 
3887
4311
  // src/llm/context-editing.ts
@@ -4554,7 +4978,8 @@ var executeStep = async (base, goal, step, index, total, done, attempt = {}) =>
4554
4978
  updates: ctx.userUpdates?.(),
4555
4979
  ...ctx.learning?.nudge ? { learning: { fetch: Boolean(ctx.tools[WEB_FETCH_TOOL]) } } : {},
4556
4980
  ...ctx.sandbox ? { sandbox: ctx.sandbox.executor } : {},
4557
- ...ctx.subagents ? { subagents: SPAWN_EXECUTOR_NOTE } : {}
4981
+ ...ctx.subagents ? { subagents: SPAWN_EXECUTOR_NOTE } : {},
4982
+ ...ctx.askUser ? { askUser: ASK_USER_EXECUTOR_NOTE } : {}
4558
4983
  });
4559
4984
  const prompt = attempt.earlier?.length ? `${parts.prompt}
4560
4985
 
@@ -4820,6 +5245,7 @@ ${nudge}` : goal;
4820
5245
  searchMode: ctx.strategy === "search",
4821
5246
  ...ctx.sandbox ? { sandbox: ctx.sandbox.planner } : {},
4822
5247
  ...ctx.subagents ? { subagents: SPAWN_PLANNER_NOTE } : {},
5248
+ ...ctx.askUser ? { askUser: ASK_USER_PLANNER_NOTE } : {},
4823
5249
  ...ctx.tiers ? { tiers: true } : {}
4824
5250
  });
4825
5251
  return {
@@ -5040,10 +5466,10 @@ var replanDecisionQuestion = (context) => ({
5040
5466
  options: REPLAN_DECISION_OPTIONS,
5041
5467
  context
5042
5468
  });
5043
- var routeDecisionQuestion = (routes, context) => ({
5469
+ var routeDecisionQuestion = (routes2, context) => ({
5044
5470
  id: "route",
5045
5471
  prompt: "One step of a pipeline has answered. Which ONE route does its answer take?",
5046
- options: routes.map((r) => ({
5472
+ options: routes2.map((r) => ({
5047
5473
  id: r.label,
5048
5474
  ...r.description ? { description: r.description } : {}
5049
5475
  })),
@@ -5433,7 +5859,7 @@ var supportsPdf = (model) => {
5433
5859
  };
5434
5860
 
5435
5861
  // src/subagent/dynamic.ts
5436
- import { jsonSchema as jsonSchema3, tool as tool4 } from "ai";
5862
+ import { jsonSchema as jsonSchema4, tool as tool5 } from "ai";
5437
5863
  var seeds = /* @__PURE__ */ new WeakMap();
5438
5864
  var spawnSeedOf = (config) => seeds.get(config);
5439
5865
  var createSpawnRun = (settings, seed, run) => ({
@@ -5453,12 +5879,12 @@ var abortError = () => {
5453
5879
  return e;
5454
5880
  };
5455
5881
  var seq = 0;
5456
- var newId = () => globalThis.crypto?.randomUUID?.() ?? `helper-${Date.now().toString(36)}-${seq += 1}`;
5882
+ var newId2 = () => globalThis.crypto?.randomUUID?.() ?? `helper-${Date.now().toString(36)}-${seq += 1}`;
5457
5883
  var createDynamicSubagentTool = (deps) => {
5458
5884
  const { settings } = deps;
5459
- const t = tool4({
5885
+ const t = tool5({
5460
5886
  description: spawnToolDescription(settings),
5461
- inputSchema: jsonSchema3(SPAWN_INPUT_SCHEMA),
5887
+ inputSchema: jsonSchema4(SPAWN_INPUT_SCHEMA),
5462
5888
  execute: async (raw, options) => {
5463
5889
  const runCtx = toolRunContextOf(options);
5464
5890
  const scope = runCtx?.spawn;
@@ -5486,7 +5912,7 @@ var createDynamicSubagentTool = (deps) => {
5486
5912
  const depth = scope.depth + 1;
5487
5913
  const maySpawn = depth < settings.maxDepth && deps.mayNest();
5488
5914
  scope.root.spawned += 1;
5489
- const id = newId();
5915
+ const id = newId2();
5490
5916
  const name = SPAWN_SUBAGENT_TOOL;
5491
5917
  const emit = (e) => runCtx.emit(e);
5492
5918
  const parentSignal = options?.abortSignal ?? runCtx.signal;
@@ -5527,6 +5953,9 @@ var createDynamicSubagentTool = (deps) => {
5527
5953
  // is given them) or none. Left in, the helper's agent would mount its own from the
5528
5954
  // config - tools it was not given, that spend money and write files.
5529
5955
  media: _media,
5956
+ // A helper asks the person only through its caller's channel (the seed), never through
5957
+ // a handler of its own.
5958
+ askUser: _askUser,
5530
5959
  availableTools: _available,
5531
5960
  skills: _skills,
5532
5961
  ...inherited
@@ -5540,6 +5969,7 @@ var createDynamicSubagentTool = (deps) => {
5540
5969
  _search,
5541
5970
  _sandbox,
5542
5971
  _media,
5972
+ _askUser,
5543
5973
  _available
5544
5974
  ];
5545
5975
  void _skills;
@@ -5570,7 +6000,8 @@ var createDynamicSubagentTool = (deps) => {
5570
6000
  ...runCtx.control ? { control: runCtx.control } : {},
5571
6001
  ...sandboxNotes && tools.run_js ? { sandboxNotes } : {},
5572
6002
  ...runCtx.elicitations ? { elicitations: runCtx.elicitations } : {},
5573
- ...runCtx.mcpSkills ? { mcpSkills: runCtx.mcpSkills } : {}
6003
+ ...runCtx.mcpSkills ? { mcpSkills: runCtx.mcpSkills } : {},
6004
+ ...runCtx.askUser ? { askUser: runCtx.askUser } : {}
5574
6005
  });
5575
6006
  parentSignal?.addEventListener("abort", onParentAbort, { once: true });
5576
6007
  if (parentSignal?.aborted) controller.abort();
@@ -6187,6 +6618,9 @@ var createAgent = async (config) => {
6187
6618
  }
6188
6619
  const dynamicSubagents = resolveDynamicSubagents(config.subagents);
6189
6620
  const seed = spawnSeedOf(config);
6621
+ const askUserSettings = resolveAskUser(config.askUser);
6622
+ const askUserRoute = askUserRouteOf(config);
6623
+ const askUserOn = seed ? seed.askUser !== void 0 : askUserSettings !== void 0 && (askUserRoute !== void 0 || askUserSettings.onQuestion !== void 0);
6190
6624
  const buildStage = (override, stageName) => buildModelFromStage(
6191
6625
  resolveStage(config.model, override, stageName),
6192
6626
  config.credentials,
@@ -6294,7 +6728,7 @@ var createAgent = async (config) => {
6294
6728
  config.availableTools,
6295
6729
  config.excludedTools
6296
6730
  );
6297
- const sandbox = config.sandbox ? (await import("./sandbox-7CGSIIIZ.js")).createSandbox(
6731
+ const sandbox = config.sandbox ? (await import("./sandbox-ZXWD5IWZ.js")).createSandbox(
6298
6732
  config.sandbox === true ? {} : config.sandbox,
6299
6733
  hostTools,
6300
6734
  (m) => log.warn(m)
@@ -6335,7 +6769,8 @@ var createAgent = async (config) => {
6335
6769
  const strategy = cfg.toolSelectionStrategy === "auto" ? catalog.length > cfg.toolSearchThreshold || toolTokens > cfg.compaction.contextWindowTokens * TOOL_SEARCH_WINDOW_SHARE ? "search" : "all" : cfg.toolSelectionStrategy;
6336
6770
  const reserved = [
6337
6771
  ...skills.length || learning ? SKILL_TOOL_NAMES : [],
6338
- ...strategy === "search" ? [FIND_TOOLS_NAME] : []
6772
+ ...strategy === "search" ? [FIND_TOOLS_NAME] : [],
6773
+ ...askUserOn ? [ASK_USER_TOOL] : []
6339
6774
  ];
6340
6775
  for (const name of reserved) {
6341
6776
  if (Object.hasOwn(baseTools, name)) {
@@ -6345,6 +6780,10 @@ var createAgent = async (config) => {
6345
6780
  }
6346
6781
  }
6347
6782
  const builtinTools = new Set(reserved);
6783
+ const askUserTool = askUserOn ? createAskUserTool(
6784
+ (seed?.askUser ?? askUserRoute)?.settings ?? askUserSettings,
6785
+ (m) => log.warn(m)
6786
+ ) : void 0;
6348
6787
  const fixedPromptTokens = (active) => promptOverheadTokens({
6349
6788
  systemPrompt: config.systemPrompt,
6350
6789
  toolTokens: toolDefTokens,
@@ -6619,6 +7058,15 @@ ${renderActiveSkills(active)}`
6619
7058
  )
6620
7059
  );
6621
7060
  }
7061
+ const askChannel = !askUserTool ? void 0 : seed ? seed.askUser : askUserRoute ?? {
7062
+ handler: askUserSettings.onQuestion,
7063
+ settings: {
7064
+ timeoutMs: askUserSettings.timeoutMs,
7065
+ maxPerRun: askUserSettings.maxPerRun
7066
+ },
7067
+ asked: { count: resumed?.questionsAsked ?? 0 }
7068
+ };
7069
+ if (askUserTool) builtins[ASK_USER_TOOL] = askUserTool;
6622
7070
  if (strategy === "search") {
6623
7071
  builtins[FIND_TOOLS_NAME] = createFindToolsTool(
6624
7072
  () => catalog,
@@ -6656,7 +7104,8 @@ ${renderActiveSkills(active)}`
6656
7104
  stepWrites: () => stepWrites,
6657
7105
  clock,
6658
7106
  mcpSkills: mcpSkillsActing,
6659
- sessionLocks: () => sessionLocks
7107
+ sessionLocks: () => sessionLocks,
7108
+ ...askChannel ? { askUser: askChannel } : {}
6660
7109
  }
6661
7110
  );
6662
7111
  const deliver = (at) => {
@@ -6797,6 +7246,7 @@ ${renderActiveSkills(active)}`
6797
7246
  } : {},
6798
7247
  ...sandboxNotes ? { sandbox: sandboxNotes } : {},
6799
7248
  ...spawnBuiltIn ? { subagents: true } : {},
7249
+ ...askChannel ? { askUser: true } : {},
6800
7250
  ...mcpInstructions ? { mcpInstructions } : {},
6801
7251
  discovered: () => discovered,
6802
7252
  builtinTools,
@@ -6917,6 +7367,8 @@ ${renderActiveSkills(active)}`
6917
7367
  ...userUpdates.length ? { userUpdates: userUpdates.map((u) => ({ ...u })) } : {},
6918
7368
  ...escalationCount ? { escalations: escalationCount } : {},
6919
7369
  ...spawnRun && !seed && spawnRun.root.spawned ? { subagentsSpawned: spawnRun.root.spawned } : {},
7370
+ // The run's own count only: a helper's and a routed subagent's are their caller's.
7371
+ ...askChannel && !seed && !askUserRoute && askChannel.asked.count ? { questionsAsked: askChannel.asked.count } : {},
6920
7372
  attempt,
6921
7373
  ...extra
6922
7374
  });
@@ -8198,7 +8650,7 @@ var PIPELINE_ROUTER_SYSTEM = "You are the Router of one step in a pipeline of ag
8198
8650
  var ROUTER_HEAD_CHARS = 2e3;
8199
8651
  var ROUTER_TAIL_CHARS = 6e3;
8200
8652
  var renderPipelineRoutePrompt = (node, text) => {
8201
- const routes = (node.routes ?? []).map((r) => `- ${r.label}${r.description ? `: ${r.description}` : ""}`).join("\n");
8653
+ const routes2 = (node.routes ?? []).map((r) => `- ${r.label}${r.description ? `: ${r.description}` : ""}`).join("\n");
8202
8654
  const answer = text.length > ROUTER_HEAD_CHARS + ROUTER_TAIL_CHARS ? `${text.slice(0, ROUTER_HEAD_CHARS)}
8203
8655
  [...]
8204
8656
  ${text.slice(-ROUTER_TAIL_CHARS)}` : text;
@@ -8207,7 +8659,7 @@ ${text.slice(-ROUTER_TAIL_CHARS)}` : text;
8207
8659
  node.instructions ? `Its role:
8208
8660
  ${node.instructions}` : "",
8209
8661
  `Routes:
8210
- ${routes}`,
8662
+ ${routes2}`,
8211
8663
  `The step's answer:
8212
8664
  ${answer}`,
8213
8665
  "Which route? Answer with one label from the list."
@@ -8595,9 +9047,9 @@ var pickRoute = async ({ agent, config }, node, text, signal) => {
8595
9047
  };
8596
9048
  var pickRouteWithDecisionModel = async ({ agent, config }, node, text, signal, emit) => {
8597
9049
  const model = agent.decisionModel;
8598
- const routes = node.routes ?? [];
8599
- if (!model || config.decision?.route === false || routes.length < 2) return void 0;
8600
- const question = routeDecisionQuestion(routes, renderPipelineRoutePrompt(node, text));
9050
+ const routes2 = node.routes ?? [];
9051
+ if (!model || config.decision?.route === false || routes2.length < 2) return void 0;
9052
+ const question = routeDecisionQuestion(routes2, renderPipelineRoutePrompt(node, text));
8601
9053
  let outcome;
8602
9054
  try {
8603
9055
  outcome = await askDecisionModel(model, question, config.decision, signal);
@@ -8719,7 +9171,7 @@ var nodeResolver = (options) => async (node) => {
8719
9171
  };
8720
9172
 
8721
9173
  // src/subagent/tool.ts
8722
- import { asSchema, jsonSchema as jsonSchema4, tool as tool5 } from "ai";
9174
+ import { asSchema, jsonSchema as jsonSchema5, tool as tool6 } from "ai";
8723
9175
 
8724
9176
  // src/subagent/protocol.ts
8725
9177
  var toCloneable = (value) => {
@@ -8863,12 +9315,16 @@ var createSubagentTool = (opts) => {
8863
9315
  })
8864
9316
  );
8865
9317
  };
8866
- const runInProcess = async (task, signal, forward, hostTools, profile, id, elicitations, sessionLocks) => {
9318
+ const runInProcess = async (task, signal, forward, hostTools, profile, id, elicitations, sessionLocks, askUser) => {
8867
9319
  const config = { ...opts.config, ...profile?.config };
8868
- const agent = await createAgent({
9320
+ const childConfig = {
8869
9321
  ...config,
8870
9322
  tools: { ...asSubagentCalls(config.tools, id, elicitations), ...hostTools }
8871
- });
9323
+ };
9324
+ if (askUser && config.askUser !== void 0 && config.askUser !== false) {
9325
+ routeAskUser(childConfig, askUser.channel, { id, depth: askUser.depth });
9326
+ }
9327
+ const agent = await createAgent(childConfig);
8872
9328
  let runError;
8873
9329
  const result = await agent.run(
8874
9330
  task,
@@ -8976,9 +9432,9 @@ var createSubagentTool = (opts) => {
8976
9432
 
8977
9433
  Optional \`profile\` (omit it for the default):
8978
9434
  ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : opts.description;
8979
- const t = tool5({
9435
+ const t = tool6({
8980
9436
  description,
8981
- inputSchema: jsonSchema4({
9437
+ inputSchema: jsonSchema5({
8982
9438
  type: "object",
8983
9439
  properties: {
8984
9440
  task: {
@@ -9058,7 +9514,11 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
9058
9514
  profile,
9059
9515
  id,
9060
9516
  runCtx?.elicitations,
9061
- runCtx?.sessionLocks?.() ?? []
9517
+ runCtx?.sessionLocks?.() ?? [],
9518
+ runCtx?.askUser ? {
9519
+ channel: runCtx.askUser,
9520
+ depth: (runCtx.subagent?.depth ?? runCtx.askUser.subagent?.depth ?? 0) + 1
9521
+ } : void 0
9062
9522
  )).catch((err) => {
9063
9523
  if (stoppedByUser)
9064
9524
  throw new Error(
@@ -9095,7 +9555,7 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
9095
9555
  };
9096
9556
 
9097
9557
  // src/subagent/worker.ts
9098
- import { dynamicTool, jsonSchema as jsonSchema5 } from "ai";
9558
+ import { dynamicTool, jsonSchema as jsonSchema6 } from "ai";
9099
9559
 
9100
9560
  // src/secrets/store.ts
9101
9561
  var VaultCredentialStore = class {
@@ -9156,7 +9616,7 @@ var serveSubagentWorker = (opts = {}) => {
9156
9616
  const proxy = (spec) => {
9157
9617
  const t = dynamicTool({
9158
9618
  description: spec.description,
9159
- inputSchema: jsonSchema5(spec.inputSchema),
9619
+ inputSchema: jsonSchema6(spec.inputSchema),
9160
9620
  execute: (input, options) => new Promise((resolve, reject) => {
9161
9621
  const callId = `call-${callSeq += 1}`;
9162
9622
  const signal = options?.abortSignal;
@@ -9428,7 +9888,18 @@ export {
9428
9888
  APP_SAMPLING_PER_MINUTE,
9429
9889
  APP_SAMPLING_REASONING_TOKENS,
9430
9890
  APP_SAMPLING_RPC_CODES,
9891
+ ASK_USER_DESCRIPTION_MAX_CHARS,
9892
+ ASK_USER_LABEL_MAX_CHARS,
9893
+ ASK_USER_MAX_OPTIONS,
9894
+ ASK_USER_MAX_PER_RUN,
9895
+ ASK_USER_MIN_OPTIONS,
9896
+ ASK_USER_OTHER_MAX_CHARS,
9897
+ ASK_USER_QUESTION_MAX_CHARS,
9898
+ ASK_USER_TIMEOUT_MAX_MS,
9899
+ ASK_USER_TIMEOUT_MS,
9900
+ ASK_USER_TOOL,
9431
9901
  AppSamplingError,
9902
+ AskUserInputError,
9432
9903
  AttachmentsNotSupportedError,
9433
9904
  ContextWindowExceededError,
9434
9905
  DECISION_PROVIDERS,
@@ -9546,9 +10017,12 @@ export {
9546
10017
  buildModelFromStage,
9547
10018
  buildSearchRequest,
9548
10019
  bytesToBase64,
10020
+ checkAskUserAnswer,
10021
+ checkAskUserInput,
9549
10022
  checkEgressUrl,
9550
10023
  checkLimits,
9551
10024
  classifyAddress,
10025
+ cleanAskUserText,
9552
10026
  compactHistory,
9553
10027
  compactSteps,
9554
10028
  compressHistory,