@dudko.dev/agent-web 0.0.45 → 0.0.47

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,426 @@ 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 toolResultForLog = (name, output) => name === ASK_USER_TOOL ? "[the answer to the question is not logged]" : output;
4021
+ var routes = /* @__PURE__ */ new WeakMap();
4022
+ var routeAskUser = (config, channel, subagent) => {
4023
+ routes.set(config, { ...channel, subagent });
4024
+ };
4025
+ var askUserRouteOf = (config) => routes.get(config);
4026
+ var createAskUserTool = (settings, log) => {
4027
+ const t = tool4({
4028
+ description: askUserDescription(settings),
4029
+ inputSchema: jsonSchema3(
4030
+ ASK_USER_INPUT_SCHEMA
4031
+ ),
4032
+ execute: async (input, options) => {
4033
+ const run = toolRunContextOf(options);
4034
+ const channel = run?.askUser;
4035
+ if (!run || !channel) {
4036
+ throw new Error(`${ASK_USER_TOOL} can only be called inside a run`);
4037
+ }
4038
+ const subagent = run.subagent ?? channel.subagent;
4039
+ const out = await askTheUser(
4040
+ { handler: channel.handler, settings: channel.settings, log },
4041
+ {
4042
+ ...run.step ? { step: run.step } : {},
4043
+ ...run.runId ? { runId: run.runId } : {},
4044
+ ...subagent ? { subagent } : {},
4045
+ signal: options?.abortSignal ?? run.signal,
4046
+ emit: (event) => run.emit(event),
4047
+ asked: channel.asked,
4048
+ ...run.clock ? { pause: run.clock.pause } : {}
4049
+ },
4050
+ input
4051
+ );
4052
+ return "text" in out ? out.text : "";
4053
+ }
4054
+ });
4055
+ t.promptHint = ASK_USER_PROMPT_HINT;
4056
+ return t;
4057
+ };
4058
+
3635
4059
  // src/agent/control.ts
3636
4060
  var ports = /* @__PURE__ */ new WeakMap();
3637
4061
  var queuedEvent = (m) => ({
@@ -3881,7 +4305,8 @@ var parsePlainText = (raw) => {
3881
4305
  const text = stripFences(raw);
3882
4306
  const obj = asObject(text);
3883
4307
  if (obj && typeof obj.reply === "string") return obj.reply.trim();
3884
- return looksLikeJson(text) ? "" : text.trim();
4308
+ if (looksLikeJson(text)) return "";
4309
+ return stripThinking(raw || "").trim();
3885
4310
  };
3886
4311
 
3887
4312
  // src/llm/context-editing.ts
@@ -4554,7 +4979,8 @@ var executeStep = async (base, goal, step, index, total, done, attempt = {}) =>
4554
4979
  updates: ctx.userUpdates?.(),
4555
4980
  ...ctx.learning?.nudge ? { learning: { fetch: Boolean(ctx.tools[WEB_FETCH_TOOL]) } } : {},
4556
4981
  ...ctx.sandbox ? { sandbox: ctx.sandbox.executor } : {},
4557
- ...ctx.subagents ? { subagents: SPAWN_EXECUTOR_NOTE } : {}
4982
+ ...ctx.subagents ? { subagents: SPAWN_EXECUTOR_NOTE } : {},
4983
+ ...ctx.askUser ? { askUser: ASK_USER_EXECUTOR_NOTE } : {}
4558
4984
  });
4559
4985
  const prompt = attempt.earlier?.length ? `${parts.prompt}
4560
4986
 
@@ -4599,7 +5025,10 @@ ${renderEarlierAttempts(attempt.earlier)}` : parts.prompt;
4599
5025
  if (attempt.calls) inFlight.push({ name, input });
4600
5026
  },
4601
5027
  onToolResult: (name, output, ok) => {
4602
- ctx.log.debug(`tool result: ${name} ${ok ? "ok" : "FAILED"}`, output);
5028
+ ctx.log.debug(
5029
+ `tool result: ${name} ${ok ? "ok" : "FAILED"}`,
5030
+ toolResultForLog(name, output)
5031
+ );
4603
5032
  ctx.emit({ type: "step.tool-result", step, name, output, ok });
4604
5033
  if (attempt.calls) {
4605
5034
  const at = inFlight.findIndex((c) => c.name === name);
@@ -4820,6 +5249,7 @@ ${nudge}` : goal;
4820
5249
  searchMode: ctx.strategy === "search",
4821
5250
  ...ctx.sandbox ? { sandbox: ctx.sandbox.planner } : {},
4822
5251
  ...ctx.subagents ? { subagents: SPAWN_PLANNER_NOTE } : {},
5252
+ ...ctx.askUser ? { askUser: ASK_USER_PLANNER_NOTE } : {},
4823
5253
  ...ctx.tiers ? { tiers: true } : {}
4824
5254
  });
4825
5255
  return {
@@ -5040,10 +5470,10 @@ var replanDecisionQuestion = (context) => ({
5040
5470
  options: REPLAN_DECISION_OPTIONS,
5041
5471
  context
5042
5472
  });
5043
- var routeDecisionQuestion = (routes, context) => ({
5473
+ var routeDecisionQuestion = (routes2, context) => ({
5044
5474
  id: "route",
5045
5475
  prompt: "One step of a pipeline has answered. Which ONE route does its answer take?",
5046
- options: routes.map((r) => ({
5476
+ options: routes2.map((r) => ({
5047
5477
  id: r.label,
5048
5478
  ...r.description ? { description: r.description } : {}
5049
5479
  })),
@@ -5433,7 +5863,7 @@ var supportsPdf = (model) => {
5433
5863
  };
5434
5864
 
5435
5865
  // src/subagent/dynamic.ts
5436
- import { jsonSchema as jsonSchema3, tool as tool4 } from "ai";
5866
+ import { jsonSchema as jsonSchema4, tool as tool5 } from "ai";
5437
5867
  var seeds = /* @__PURE__ */ new WeakMap();
5438
5868
  var spawnSeedOf = (config) => seeds.get(config);
5439
5869
  var createSpawnRun = (settings, seed, run) => ({
@@ -5453,12 +5883,12 @@ var abortError = () => {
5453
5883
  return e;
5454
5884
  };
5455
5885
  var seq = 0;
5456
- var newId = () => globalThis.crypto?.randomUUID?.() ?? `helper-${Date.now().toString(36)}-${seq += 1}`;
5886
+ var newId2 = () => globalThis.crypto?.randomUUID?.() ?? `helper-${Date.now().toString(36)}-${seq += 1}`;
5457
5887
  var createDynamicSubagentTool = (deps) => {
5458
5888
  const { settings } = deps;
5459
- const t = tool4({
5889
+ const t = tool5({
5460
5890
  description: spawnToolDescription(settings),
5461
- inputSchema: jsonSchema3(SPAWN_INPUT_SCHEMA),
5891
+ inputSchema: jsonSchema4(SPAWN_INPUT_SCHEMA),
5462
5892
  execute: async (raw, options) => {
5463
5893
  const runCtx = toolRunContextOf(options);
5464
5894
  const scope = runCtx?.spawn;
@@ -5486,7 +5916,7 @@ var createDynamicSubagentTool = (deps) => {
5486
5916
  const depth = scope.depth + 1;
5487
5917
  const maySpawn = depth < settings.maxDepth && deps.mayNest();
5488
5918
  scope.root.spawned += 1;
5489
- const id = newId();
5919
+ const id = newId2();
5490
5920
  const name = SPAWN_SUBAGENT_TOOL;
5491
5921
  const emit = (e) => runCtx.emit(e);
5492
5922
  const parentSignal = options?.abortSignal ?? runCtx.signal;
@@ -5527,6 +5957,9 @@ var createDynamicSubagentTool = (deps) => {
5527
5957
  // is given them) or none. Left in, the helper's agent would mount its own from the
5528
5958
  // config - tools it was not given, that spend money and write files.
5529
5959
  media: _media,
5960
+ // A helper asks the person only through its caller's channel (the seed), never through
5961
+ // a handler of its own.
5962
+ askUser: _askUser,
5530
5963
  availableTools: _available,
5531
5964
  skills: _skills,
5532
5965
  ...inherited
@@ -5540,6 +5973,7 @@ var createDynamicSubagentTool = (deps) => {
5540
5973
  _search,
5541
5974
  _sandbox,
5542
5975
  _media,
5976
+ _askUser,
5543
5977
  _available
5544
5978
  ];
5545
5979
  void _skills;
@@ -5570,7 +6004,8 @@ var createDynamicSubagentTool = (deps) => {
5570
6004
  ...runCtx.control ? { control: runCtx.control } : {},
5571
6005
  ...sandboxNotes && tools.run_js ? { sandboxNotes } : {},
5572
6006
  ...runCtx.elicitations ? { elicitations: runCtx.elicitations } : {},
5573
- ...runCtx.mcpSkills ? { mcpSkills: runCtx.mcpSkills } : {}
6007
+ ...runCtx.mcpSkills ? { mcpSkills: runCtx.mcpSkills } : {},
6008
+ ...runCtx.askUser ? { askUser: runCtx.askUser } : {}
5574
6009
  });
5575
6010
  parentSignal?.addEventListener("abort", onParentAbort, { once: true });
5576
6011
  if (parentSignal?.aborted) controller.abort();
@@ -6187,6 +6622,9 @@ var createAgent = async (config) => {
6187
6622
  }
6188
6623
  const dynamicSubagents = resolveDynamicSubagents(config.subagents);
6189
6624
  const seed = spawnSeedOf(config);
6625
+ const askUserSettings = resolveAskUser(config.askUser);
6626
+ const askUserRoute = askUserRouteOf(config);
6627
+ const askUserOn = seed ? seed.askUser !== void 0 : askUserSettings !== void 0 && (askUserRoute !== void 0 || askUserSettings.onQuestion !== void 0);
6190
6628
  const buildStage = (override, stageName) => buildModelFromStage(
6191
6629
  resolveStage(config.model, override, stageName),
6192
6630
  config.credentials,
@@ -6294,7 +6732,7 @@ var createAgent = async (config) => {
6294
6732
  config.availableTools,
6295
6733
  config.excludedTools
6296
6734
  );
6297
- const sandbox = config.sandbox ? (await import("./sandbox-7CGSIIIZ.js")).createSandbox(
6735
+ const sandbox = config.sandbox ? (await import("./sandbox-ZXWD5IWZ.js")).createSandbox(
6298
6736
  config.sandbox === true ? {} : config.sandbox,
6299
6737
  hostTools,
6300
6738
  (m) => log.warn(m)
@@ -6335,7 +6773,8 @@ var createAgent = async (config) => {
6335
6773
  const strategy = cfg.toolSelectionStrategy === "auto" ? catalog.length > cfg.toolSearchThreshold || toolTokens > cfg.compaction.contextWindowTokens * TOOL_SEARCH_WINDOW_SHARE ? "search" : "all" : cfg.toolSelectionStrategy;
6336
6774
  const reserved = [
6337
6775
  ...skills.length || learning ? SKILL_TOOL_NAMES : [],
6338
- ...strategy === "search" ? [FIND_TOOLS_NAME] : []
6776
+ ...strategy === "search" ? [FIND_TOOLS_NAME] : [],
6777
+ ...askUserOn ? [ASK_USER_TOOL] : []
6339
6778
  ];
6340
6779
  for (const name of reserved) {
6341
6780
  if (Object.hasOwn(baseTools, name)) {
@@ -6345,6 +6784,10 @@ var createAgent = async (config) => {
6345
6784
  }
6346
6785
  }
6347
6786
  const builtinTools = new Set(reserved);
6787
+ const askUserTool = askUserOn ? createAskUserTool(
6788
+ (seed?.askUser ?? askUserRoute)?.settings ?? askUserSettings,
6789
+ (m) => log.warn(m)
6790
+ ) : void 0;
6348
6791
  const fixedPromptTokens = (active) => promptOverheadTokens({
6349
6792
  systemPrompt: config.systemPrompt,
6350
6793
  toolTokens: toolDefTokens,
@@ -6619,6 +7062,15 @@ ${renderActiveSkills(active)}`
6619
7062
  )
6620
7063
  );
6621
7064
  }
7065
+ const askChannel = !askUserTool ? void 0 : seed ? seed.askUser : askUserRoute ?? {
7066
+ handler: askUserSettings.onQuestion,
7067
+ settings: {
7068
+ timeoutMs: askUserSettings.timeoutMs,
7069
+ maxPerRun: askUserSettings.maxPerRun
7070
+ },
7071
+ asked: { count: resumed?.questionsAsked ?? 0 }
7072
+ };
7073
+ if (askUserTool) builtins[ASK_USER_TOOL] = askUserTool;
6622
7074
  if (strategy === "search") {
6623
7075
  builtins[FIND_TOOLS_NAME] = createFindToolsTool(
6624
7076
  () => catalog,
@@ -6656,7 +7108,8 @@ ${renderActiveSkills(active)}`
6656
7108
  stepWrites: () => stepWrites,
6657
7109
  clock,
6658
7110
  mcpSkills: mcpSkillsActing,
6659
- sessionLocks: () => sessionLocks
7111
+ sessionLocks: () => sessionLocks,
7112
+ ...askChannel ? { askUser: askChannel } : {}
6660
7113
  }
6661
7114
  );
6662
7115
  const deliver = (at) => {
@@ -6797,6 +7250,7 @@ ${renderActiveSkills(active)}`
6797
7250
  } : {},
6798
7251
  ...sandboxNotes ? { sandbox: sandboxNotes } : {},
6799
7252
  ...spawnBuiltIn ? { subagents: true } : {},
7253
+ ...askChannel ? { askUser: true } : {},
6800
7254
  ...mcpInstructions ? { mcpInstructions } : {},
6801
7255
  discovered: () => discovered,
6802
7256
  builtinTools,
@@ -6917,6 +7371,8 @@ ${renderActiveSkills(active)}`
6917
7371
  ...userUpdates.length ? { userUpdates: userUpdates.map((u) => ({ ...u })) } : {},
6918
7372
  ...escalationCount ? { escalations: escalationCount } : {},
6919
7373
  ...spawnRun && !seed && spawnRun.root.spawned ? { subagentsSpawned: spawnRun.root.spawned } : {},
7374
+ // The run's own count only: a helper's and a routed subagent's are their caller's.
7375
+ ...askChannel && !seed && !askUserRoute && askChannel.asked.count ? { questionsAsked: askChannel.asked.count } : {},
6920
7376
  attempt,
6921
7377
  ...extra
6922
7378
  });
@@ -7075,7 +7531,13 @@ ${renderActiveSkills(active)}`
7075
7531
  log.warn(`step ${stepNo} made no tool calls \u2014 nothing changed in this step`);
7076
7532
  }
7077
7533
  stepResult.toolCalls.filter((c) => !c.ok).forEach((c) => log.warn(`tool ${c.name} failed:`, c.output));
7078
- log.debug(`step ${stepNo} detail:`, stepResult);
7534
+ log.debug(`step ${stepNo} detail:`, {
7535
+ ...stepResult,
7536
+ toolCalls: stepResult.toolCalls.map((c) => ({
7537
+ ...c,
7538
+ output: toolResultForLog(c.name, c.output)
7539
+ }))
7540
+ });
7079
7541
  emit({ type: "step.complete", step, result: stepResult });
7080
7542
  const counts = stepResult.toolCalls.length ? ` [${applied} tool call(s) ok${failed ? `, ${failed} failed` : ""}]` : "";
7081
7543
  done.push(
@@ -8198,7 +8660,7 @@ var PIPELINE_ROUTER_SYSTEM = "You are the Router of one step in a pipeline of ag
8198
8660
  var ROUTER_HEAD_CHARS = 2e3;
8199
8661
  var ROUTER_TAIL_CHARS = 6e3;
8200
8662
  var renderPipelineRoutePrompt = (node, text) => {
8201
- const routes = (node.routes ?? []).map((r) => `- ${r.label}${r.description ? `: ${r.description}` : ""}`).join("\n");
8663
+ const routes2 = (node.routes ?? []).map((r) => `- ${r.label}${r.description ? `: ${r.description}` : ""}`).join("\n");
8202
8664
  const answer = text.length > ROUTER_HEAD_CHARS + ROUTER_TAIL_CHARS ? `${text.slice(0, ROUTER_HEAD_CHARS)}
8203
8665
  [...]
8204
8666
  ${text.slice(-ROUTER_TAIL_CHARS)}` : text;
@@ -8207,7 +8669,7 @@ ${text.slice(-ROUTER_TAIL_CHARS)}` : text;
8207
8669
  node.instructions ? `Its role:
8208
8670
  ${node.instructions}` : "",
8209
8671
  `Routes:
8210
- ${routes}`,
8672
+ ${routes2}`,
8211
8673
  `The step's answer:
8212
8674
  ${answer}`,
8213
8675
  "Which route? Answer with one label from the list."
@@ -8595,9 +9057,9 @@ var pickRoute = async ({ agent, config }, node, text, signal) => {
8595
9057
  };
8596
9058
  var pickRouteWithDecisionModel = async ({ agent, config }, node, text, signal, emit) => {
8597
9059
  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));
9060
+ const routes2 = node.routes ?? [];
9061
+ if (!model || config.decision?.route === false || routes2.length < 2) return void 0;
9062
+ const question = routeDecisionQuestion(routes2, renderPipelineRoutePrompt(node, text));
8601
9063
  let outcome;
8602
9064
  try {
8603
9065
  outcome = await askDecisionModel(model, question, config.decision, signal);
@@ -8719,7 +9181,7 @@ var nodeResolver = (options) => async (node) => {
8719
9181
  };
8720
9182
 
8721
9183
  // src/subagent/tool.ts
8722
- import { asSchema, jsonSchema as jsonSchema4, tool as tool5 } from "ai";
9184
+ import { asSchema, jsonSchema as jsonSchema5, tool as tool6 } from "ai";
8723
9185
 
8724
9186
  // src/subagent/protocol.ts
8725
9187
  var toCloneable = (value) => {
@@ -8863,12 +9325,16 @@ var createSubagentTool = (opts) => {
8863
9325
  })
8864
9326
  );
8865
9327
  };
8866
- const runInProcess = async (task, signal, forward, hostTools, profile, id, elicitations, sessionLocks) => {
9328
+ const runInProcess = async (task, signal, forward, hostTools, profile, id, elicitations, sessionLocks, askUser) => {
8867
9329
  const config = { ...opts.config, ...profile?.config };
8868
- const agent = await createAgent({
9330
+ const childConfig = {
8869
9331
  ...config,
8870
9332
  tools: { ...asSubagentCalls(config.tools, id, elicitations), ...hostTools }
8871
- });
9333
+ };
9334
+ if (askUser && config.askUser !== void 0 && config.askUser !== false) {
9335
+ routeAskUser(childConfig, askUser.channel, { id, depth: askUser.depth });
9336
+ }
9337
+ const agent = await createAgent(childConfig);
8872
9338
  let runError;
8873
9339
  const result = await agent.run(
8874
9340
  task,
@@ -8976,9 +9442,9 @@ var createSubagentTool = (opts) => {
8976
9442
 
8977
9443
  Optional \`profile\` (omit it for the default):
8978
9444
  ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : opts.description;
8979
- const t = tool5({
9445
+ const t = tool6({
8980
9446
  description,
8981
- inputSchema: jsonSchema4({
9447
+ inputSchema: jsonSchema5({
8982
9448
  type: "object",
8983
9449
  properties: {
8984
9450
  task: {
@@ -9058,7 +9524,11 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
9058
9524
  profile,
9059
9525
  id,
9060
9526
  runCtx?.elicitations,
9061
- runCtx?.sessionLocks?.() ?? []
9527
+ runCtx?.sessionLocks?.() ?? [],
9528
+ runCtx?.askUser ? {
9529
+ channel: runCtx.askUser,
9530
+ depth: (runCtx.subagent?.depth ?? runCtx.askUser.subagent?.depth ?? 0) + 1
9531
+ } : void 0
9062
9532
  )).catch((err) => {
9063
9533
  if (stoppedByUser)
9064
9534
  throw new Error(
@@ -9095,7 +9565,7 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
9095
9565
  };
9096
9566
 
9097
9567
  // src/subagent/worker.ts
9098
- import { dynamicTool, jsonSchema as jsonSchema5 } from "ai";
9568
+ import { dynamicTool, jsonSchema as jsonSchema6 } from "ai";
9099
9569
 
9100
9570
  // src/secrets/store.ts
9101
9571
  var VaultCredentialStore = class {
@@ -9156,7 +9626,7 @@ var serveSubagentWorker = (opts = {}) => {
9156
9626
  const proxy = (spec) => {
9157
9627
  const t = dynamicTool({
9158
9628
  description: spec.description,
9159
- inputSchema: jsonSchema5(spec.inputSchema),
9629
+ inputSchema: jsonSchema6(spec.inputSchema),
9160
9630
  execute: (input, options) => new Promise((resolve, reject) => {
9161
9631
  const callId = `call-${callSeq += 1}`;
9162
9632
  const signal = options?.abortSignal;
@@ -9428,7 +9898,18 @@ export {
9428
9898
  APP_SAMPLING_PER_MINUTE,
9429
9899
  APP_SAMPLING_REASONING_TOKENS,
9430
9900
  APP_SAMPLING_RPC_CODES,
9901
+ ASK_USER_DESCRIPTION_MAX_CHARS,
9902
+ ASK_USER_LABEL_MAX_CHARS,
9903
+ ASK_USER_MAX_OPTIONS,
9904
+ ASK_USER_MAX_PER_RUN,
9905
+ ASK_USER_MIN_OPTIONS,
9906
+ ASK_USER_OTHER_MAX_CHARS,
9907
+ ASK_USER_QUESTION_MAX_CHARS,
9908
+ ASK_USER_TIMEOUT_MAX_MS,
9909
+ ASK_USER_TIMEOUT_MS,
9910
+ ASK_USER_TOOL,
9431
9911
  AppSamplingError,
9912
+ AskUserInputError,
9432
9913
  AttachmentsNotSupportedError,
9433
9914
  ContextWindowExceededError,
9434
9915
  DECISION_PROVIDERS,
@@ -9546,9 +10027,12 @@ export {
9546
10027
  buildModelFromStage,
9547
10028
  buildSearchRequest,
9548
10029
  bytesToBase64,
10030
+ checkAskUserAnswer,
10031
+ checkAskUserInput,
9549
10032
  checkEgressUrl,
9550
10033
  checkLimits,
9551
10034
  classifyAddress,
10035
+ cleanAskUserText,
9552
10036
  compactHistory,
9553
10037
  compactSteps,
9554
10038
  compressHistory,