@dudko.dev/agent-web 0.0.44 → 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/README.md +3 -2
- package/dist/agent-web.js +161 -151
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-236RCVAZ.js → chunk-PTJA7V23.js} +3 -2
- package/dist/chunk-PTJA7V23.js.map +1 -0
- package/dist/index.cjs +789 -129
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +312 -10
- package/dist/index.d.ts +312 -10
- package/dist/index.js +742 -101
- package/dist/index.js.map +1 -1
- package/dist/{sandbox-7CGSIIIZ.js → sandbox-ZXWD5IWZ.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-236RCVAZ.js.map +0 -1
- /package/dist/{sandbox-7CGSIIIZ.js.map → sandbox-ZXWD5IWZ.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -95,7 +95,7 @@ import {
|
|
|
95
95
|
toolRunContextOf,
|
|
96
96
|
withDeadline,
|
|
97
97
|
wrapToolsForRun
|
|
98
|
-
} from "./chunk-
|
|
98
|
+
} from "./chunk-PTJA7V23.js";
|
|
99
99
|
import {
|
|
100
100
|
FILES_STORE,
|
|
101
101
|
KEYS_STORE,
|
|
@@ -265,6 +265,16 @@ var BUDGET_SHARES = {
|
|
|
265
265
|
compaction: { num: 1, den: 125, min: 256, max: 4096 }
|
|
266
266
|
};
|
|
267
267
|
var share = (window, s) => Math.min(s.max, Math.max(s.min, Math.round(window * s.num / s.den)));
|
|
268
|
+
var reasoningStages = /* @__PURE__ */ new WeakMap();
|
|
269
|
+
var stageReasons = (c, stage) => reasoningStages.get(c)?.has(stage) === true;
|
|
270
|
+
var observeReasoning = (c, stage, contextWindowTokens, finishReason, reasoningTokens) => {
|
|
271
|
+
if (!(typeof reasoningTokens === "number" && reasoningTokens > 0)) return false;
|
|
272
|
+
const cap = stageOutputCap(c, stage, contextWindowTokens);
|
|
273
|
+
const seen = reasoningStages.get(c) ?? /* @__PURE__ */ new Set();
|
|
274
|
+
seen.add(stage);
|
|
275
|
+
reasoningStages.set(c, seen);
|
|
276
|
+
return finishReason === "length" && cap.derived && cap.tokens !== void 0;
|
|
277
|
+
};
|
|
268
278
|
var stageOutputCap = (c, stage, contextWindowTokens) => {
|
|
269
279
|
const set = c.limits?.perCall?.[stage] ?? c.budgets?.[stage];
|
|
270
280
|
if (typeof set === "number" && Number.isFinite(set)) {
|
|
@@ -272,6 +282,7 @@ var stageOutputCap = (c, stage, contextWindowTokens) => {
|
|
|
272
282
|
}
|
|
273
283
|
const thinking = resolveThinking(thinkingFor(stage, c.thinking, c.stageThinking));
|
|
274
284
|
if (thinking.reasoning && thinking.reasoning !== "none") return { derived: false };
|
|
285
|
+
if (stageReasons(c, stage)) return { derived: false };
|
|
275
286
|
return { tokens: share(contextWindowTokens, BUDGET_SHARES[stage]), derived: true };
|
|
276
287
|
};
|
|
277
288
|
var outputCapNotice = (c, stage, contextWindowTokens, finishReason) => {
|
|
@@ -1262,14 +1273,22 @@ var stateBlock = (state) => state && state.trim() ? `
|
|
|
1262
1273
|
|
|
1263
1274
|
STATE:
|
|
1264
1275
|
${state}` : "";
|
|
1265
|
-
var
|
|
1276
|
+
var ATTACHED_MARK = /\n\[attached: [^\]\n]*\]$/;
|
|
1277
|
+
var historyLine = (content, max) => {
|
|
1278
|
+
const mark = ATTACHED_MARK.exec(content)?.[0];
|
|
1279
|
+
if (!mark || content.length <= max) return clip(content, max);
|
|
1280
|
+
return `${clip(content.slice(0, -mark.length), Math.max(1, max - mark.length))}${mark}`;
|
|
1281
|
+
};
|
|
1282
|
+
var historyBlock = (history, perMessage = 400) => {
|
|
1266
1283
|
if (!history || history.length === 0) return "";
|
|
1267
|
-
const lines = history.slice(-8).map((m) => `${m.role}: ${
|
|
1284
|
+
const lines = history.slice(-8).map((m) => `${m.role}: ${historyLine(m.content, perMessage)}`);
|
|
1268
1285
|
return `
|
|
1269
1286
|
|
|
1270
1287
|
CONVERSATION SO FAR:
|
|
1271
1288
|
${lines.join("\n")}`;
|
|
1272
1289
|
};
|
|
1290
|
+
var hasAttachedMark = (content) => ATTACHED_MARK.test(content);
|
|
1291
|
+
var NO_ATTACHMENT_NOTE = `NOTE: nothing is attached to THIS message. The files of earlier messages (marked "[attached: ...]" in the conversation) are not visible to you now - only what was said about them then is. If this message is about a file you cannot see, say so and ask the user to attach it again; never describe a file you cannot see.`;
|
|
1273
1292
|
var section = (title, body) => body && body.trim() ? `
|
|
1274
1293
|
|
|
1275
1294
|
${title}:
|
|
@@ -1298,17 +1317,17 @@ var PLANNER_RULES = `- Act autonomously: whenever the TOOLS can do the work or l
|
|
|
1298
1317
|
- Never repeat or pad steps.`;
|
|
1299
1318
|
var PLANNER_NATIVE = `You are the PLANNER of an autonomous tool-using agent that works step by step.
|
|
1300
1319
|
Produce a brief "thought" and an ordered "steps" list (1\u20136 DISTINCT, self-contained steps).
|
|
1301
|
-
Return an EMPTY steps list ONLY for a pure greeting, thanks or small talk, or a question
|
|
1320
|
+
Return an EMPTY steps list ONLY for a pure greeting, thanks or small talk, or a question that can be answered completely from the conversation, the STATE, what is attached to the message and general knowledge without any tool. Do NOT write the answer yourself: it is written right after you, from the same message. "thought" is your private one-sentence note; the user never sees it.
|
|
1302
1321
|
${PLANNER_RULES}`;
|
|
1303
1322
|
var PLANNER_PROMPTED = `You are the PLANNER of an autonomous tool-using agent that works step by step.
|
|
1304
1323
|
|
|
1305
1324
|
Reply with a single JSON object, nothing else:
|
|
1306
1325
|
{ "reply": string, "plan": string[], "skills": string[] }
|
|
1307
|
-
-
|
|
1308
|
-
- Set "plan": [] ONLY for a pure greeting, thanks or small talk, or a question
|
|
1326
|
+
- "reply" is your private one-sentence note (the user never sees it); for a real goal "plan" is 1\u20136 DISTINCT, self-contained steps.
|
|
1327
|
+
- Set "plan": [] ONLY for a pure greeting, thanks or small talk, or a question that can be answered completely from the conversation, the STATE and general knowledge without any tool. Do NOT write the answer yourself: it is written right after you, from the same message.
|
|
1309
1328
|
${PLANNER_RULES}`;
|
|
1310
1329
|
var PLANNER_SKILLS = `
|
|
1311
|
-
|
|
1330
|
+
"skills" takes names from the SKILLS list ONLY - packaged instructions, not tools: list the ones that apply to this goal, or leave it empty. Never put a name from TOOLS there.`;
|
|
1312
1331
|
var COMPLEXITY_LEVELS = `low = mechanical work (a lookup, one obvious tool call, copying or reformatting data); medium = ordinary work (a few tool calls, some judgement); high = hard work (multi-part reasoning, analysis, writing or fixing code, weighing conflicting data). When unsure between two, choose the higher.`;
|
|
1313
1332
|
var PLANNER_TIERS_NATIVE = `
|
|
1314
1333
|
Steps run on models of different strength: set "complexity" on every step. ${COMPLEXITY_LEVELS}`;
|
|
@@ -1359,20 +1378,27 @@ var SYNTHESIZER_SYSTEM = `You are the SYNTHESIZER. Answer the user's goal from w
|
|
|
1359
1378
|
- Mention any assumption the agent made. If something could not be done, say so plainly and why.
|
|
1360
1379
|
- Do not ask follow-up questions unless the goal genuinely cannot be completed without the user.
|
|
1361
1380
|
- Be concise and friendly. Plain text (light markdown is fine) \u2014 no JSON, no code.`;
|
|
1381
|
+
var SYNTHESIZER_DIRECT = `You are the SYNTHESIZER of an autonomous tool-using agent. The planner found that this message needs no tool, so no tool was run: write the answer to the user yourself.
|
|
1382
|
+
- Answer the message under GOAL from the CONVERSATION SO FAR, the STATE, anything attached to this message and general knowledge.
|
|
1383
|
+
- Nothing was done in this turn: never say that something was looked up, changed or created now. If the message needs an action or data you do not have, say plainly what is missing.
|
|
1384
|
+
- Answer in the language of the user's message. Be concise and friendly. Plain text (light markdown is fine) \u2014 no JSON.`;
|
|
1385
|
+
var DIRECT_HISTORY_CHARS = 2e3;
|
|
1386
|
+
var noteLine = (note) => note && note.trim() ? `
|
|
1387
|
+
${note.trim()}` : "";
|
|
1362
1388
|
var defaultPrompts = {
|
|
1363
1389
|
planner: (ctx) => ({
|
|
1364
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 ? `
|
|
1365
|
-
${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) + `
|
|
1366
1392
|
|
|
1367
1393
|
TOOLS:
|
|
1368
1394
|
${ctx.toolCatalog}`,
|
|
1369
|
-
prompt: `GOAL: ${ctx.goal}${historyBlock(ctx.history)}${stateBlock(ctx.state)}`
|
|
1395
|
+
prompt: `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}${historyBlock(ctx.history)}${stateBlock(ctx.state)}`
|
|
1370
1396
|
}),
|
|
1371
1397
|
executor: (ctx) => ({
|
|
1372
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 ? `
|
|
1373
|
-
- ${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),
|
|
1374
1400
|
prompt: [
|
|
1375
|
-
`GOAL: ${ctx.goal}`,
|
|
1401
|
+
`GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
|
|
1376
1402
|
stateBlock(ctx.state).trimStart(),
|
|
1377
1403
|
ctx.mode === "prompted" ? `TOOLS:
|
|
1378
1404
|
${ctx.toolCatalog}` : "",
|
|
@@ -1396,10 +1422,16 @@ ${numbered(ctx.remaining, "(none)")}`,
|
|
|
1396
1422
|
].filter(Boolean).join("\n\n")
|
|
1397
1423
|
}),
|
|
1398
1424
|
synthesizer: (ctx) => ({
|
|
1399
|
-
system: SYNTHESIZER_SYSTEM + (ctx.sandbox ? `
|
|
1425
|
+
system: (ctx.direct ? SYNTHESIZER_DIRECT : SYNTHESIZER_SYSTEM) + (ctx.sandbox ? `
|
|
1400
1426
|
- ${ctx.sandbox}` : "") + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
|
|
1401
|
-
prompt: [
|
|
1402
|
-
`GOAL: ${ctx.goal}`,
|
|
1427
|
+
prompt: ctx.direct ? [
|
|
1428
|
+
`GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
|
|
1429
|
+
historyBlock(ctx.history, DIRECT_HISTORY_CHARS).trimStart(),
|
|
1430
|
+
stateBlock(ctx.state).trimStart(),
|
|
1431
|
+
updatesBlock(ctx.updates, 0, SYNTHESIZER_UPDATES_ADVICE),
|
|
1432
|
+
"Write the answer for the user."
|
|
1433
|
+
].filter(Boolean).join("\n\n") : [
|
|
1434
|
+
`GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
|
|
1403
1435
|
stateBlock(ctx.state).trimStart(),
|
|
1404
1436
|
updatesBlock(ctx.updates, 0, SYNTHESIZER_UPDATES_ADVICE),
|
|
1405
1437
|
`What was done:
|
|
@@ -3567,6 +3599,10 @@ var humanWaitOf = (event) => {
|
|
|
3567
3599
|
return { key: `${path}elicitation:${current.id}`, waiting: true };
|
|
3568
3600
|
case "mcp.elicitation-answered":
|
|
3569
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 };
|
|
3570
3606
|
default:
|
|
3571
3607
|
return void 0;
|
|
3572
3608
|
}
|
|
@@ -3600,6 +3636,425 @@ var followHumanWaits = (clock) => {
|
|
|
3600
3636
|
};
|
|
3601
3637
|
};
|
|
3602
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
|
+
|
|
3603
4058
|
// src/agent/control.ts
|
|
3604
4059
|
var ports = /* @__PURE__ */ new WeakMap();
|
|
3605
4060
|
var queuedEvent = (m) => ({
|
|
@@ -3849,7 +4304,8 @@ var parsePlainText = (raw) => {
|
|
|
3849
4304
|
const text = stripFences(raw);
|
|
3850
4305
|
const obj = asObject(text);
|
|
3851
4306
|
if (obj && typeof obj.reply === "string") return obj.reply.trim();
|
|
3852
|
-
|
|
4307
|
+
if (looksLikeJson(text)) return "";
|
|
4308
|
+
return stripThinking(raw || "").trim();
|
|
3853
4309
|
};
|
|
3854
4310
|
|
|
3855
4311
|
// src/llm/context-editing.ts
|
|
@@ -4113,6 +4569,7 @@ var imageRefusal = (ctx, err, model) => {
|
|
|
4113
4569
|
return unsupportedAttachment(modelLabel(model), kind, detail && `the provider said: ${detail}`);
|
|
4114
4570
|
};
|
|
4115
4571
|
var systemFor = (ctx, base) => withSystem(base, ctx.raw.systemPrompt);
|
|
4572
|
+
var aborted = (ctx) => ctx.signal?.aborted === true;
|
|
4116
4573
|
var stageCall = (ctx, stage, baseSystem) => {
|
|
4117
4574
|
const withMcp = ctx.mcpInstructions && (stage === "planner" || stage === "executor") ? `${baseSystem}
|
|
4118
4575
|
|
|
@@ -4124,23 +4581,44 @@ ${ctx.mcpInstructions}` : baseSystem;
|
|
|
4124
4581
|
cachingProviderOptions(caching, ctx.config.clientName, stage),
|
|
4125
4582
|
thinking.providerOptions
|
|
4126
4583
|
);
|
|
4584
|
+
const cap = stageReasons(ctx.raw, stage) ? stageOutputCap(ctx.raw, stage, capWindow(ctx, stage)).tokens ?? 0 : ctx.config.budgets[stage];
|
|
4127
4585
|
return {
|
|
4128
4586
|
system: cachedInstructions(system, caching),
|
|
4129
4587
|
...thinking.reasoning ? { reasoning: thinking.reasoning } : {},
|
|
4130
4588
|
...providerOptions ? { providerOptions } : {},
|
|
4131
|
-
...
|
|
4589
|
+
...cap > 0 ? { maxOutputTokens: cap } : {}
|
|
4132
4590
|
};
|
|
4133
4591
|
};
|
|
4134
|
-
var
|
|
4135
|
-
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
|
|
4139
|
-
)
|
|
4592
|
+
var capWindow = (ctx, stage) => (stage === "executor" ? ctx.executorWindowTokens : void 0) ?? ctx.config.compaction.contextWindowTokens;
|
|
4593
|
+
var cutWhileReasoning = (ctx, stage, finishReason, usage) => observeReasoning(ctx.raw, stage, capWindow(ctx, stage), finishReason, usage?.reasoningTokens);
|
|
4594
|
+
var withReasoningRoom = async (ctx, stage, phase, run, onWasted) => {
|
|
4595
|
+
const again = (why, spent2) => {
|
|
4596
|
+
onWasted(spent2);
|
|
4597
|
+
const message = `${why} - the model spent ${spent2.reasoningTokens ?? 0} of them reasoning: repeating the call without the default cap (this stage is not capped for this agent from now on)`;
|
|
4598
|
+
ctx.log.warn(message);
|
|
4599
|
+
ctx.emit({ type: "retry", phase, attempt: 1, error: message });
|
|
4600
|
+
return run();
|
|
4601
|
+
};
|
|
4602
|
+
let first;
|
|
4603
|
+
try {
|
|
4604
|
+
first = await run();
|
|
4605
|
+
} catch (err) {
|
|
4606
|
+
if (aborted(ctx) || !NoObjectGeneratedError.isInstance(err)) throw err;
|
|
4607
|
+
withCapHint(ctx, stage, err);
|
|
4608
|
+
const spent2 = usageOfError(err);
|
|
4609
|
+
if (!cutWhileReasoning(ctx, stage, err.finishReason, spent2)) throw err;
|
|
4610
|
+
return again(err.message, spent2);
|
|
4611
|
+
}
|
|
4612
|
+
const spent = normalizeUsage(first.usage);
|
|
4613
|
+
const notice = capNotice(ctx, stage, first.finishReason);
|
|
4614
|
+
if (!cutWhileReasoning(ctx, stage, first.finishReason, spent)) return first;
|
|
4615
|
+
return again(notice ?? `[${stage}] the model's output was cut off`, spent);
|
|
4616
|
+
};
|
|
4617
|
+
var capNotice = (ctx, stage, finishReason) => outputCapNotice(ctx.raw, stage, capWindow(ctx, stage), finishReason);
|
|
4140
4618
|
var withCapHint = (ctx, stage, err) => {
|
|
4141
4619
|
if (NoObjectGeneratedError.isInstance(err)) {
|
|
4142
4620
|
const notice = capNotice(ctx, stage, err.finishReason);
|
|
4143
|
-
if (notice) err.message = `${err.message} - ${notice}`;
|
|
4621
|
+
if (notice && !err.message.includes(notice)) err.message = `${err.message} - ${notice}`;
|
|
4144
4622
|
}
|
|
4145
4623
|
return err;
|
|
4146
4624
|
};
|
|
@@ -4369,14 +4847,14 @@ var shareSubagentBudget = (parent, running, settings) => {
|
|
|
4369
4847
|
var createSpawnGate = (max) => {
|
|
4370
4848
|
let active = 0;
|
|
4371
4849
|
const queue = [];
|
|
4372
|
-
const
|
|
4850
|
+
const aborted3 = () => {
|
|
4373
4851
|
const e = new Error("Aborted");
|
|
4374
4852
|
e.name = "AbortError";
|
|
4375
4853
|
return e;
|
|
4376
4854
|
};
|
|
4377
4855
|
return (signal) => new Promise((resolve, reject) => {
|
|
4378
4856
|
if (signal?.aborted) {
|
|
4379
|
-
reject(
|
|
4857
|
+
reject(aborted3());
|
|
4380
4858
|
return;
|
|
4381
4859
|
}
|
|
4382
4860
|
const grant = () => {
|
|
@@ -4397,7 +4875,7 @@ var createSpawnGate = (max) => {
|
|
|
4397
4875
|
if (i >= 0) {
|
|
4398
4876
|
queue.splice(i, 1);
|
|
4399
4877
|
}
|
|
4400
|
-
reject(
|
|
4878
|
+
reject(aborted3());
|
|
4401
4879
|
}
|
|
4402
4880
|
if (active < max) {
|
|
4403
4881
|
grant();
|
|
@@ -4486,6 +4964,7 @@ var executeStep = async (base, goal, step, index, total, done, attempt = {}) =>
|
|
|
4486
4964
|
const active = ctx.activeSkills?.() ?? [];
|
|
4487
4965
|
const parts = ctx.prompts.executor({
|
|
4488
4966
|
goal,
|
|
4967
|
+
...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
|
|
4489
4968
|
state,
|
|
4490
4969
|
step: step.description,
|
|
4491
4970
|
index,
|
|
@@ -4499,7 +4978,8 @@ var executeStep = async (base, goal, step, index, total, done, attempt = {}) =>
|
|
|
4499
4978
|
updates: ctx.userUpdates?.(),
|
|
4500
4979
|
...ctx.learning?.nudge ? { learning: { fetch: Boolean(ctx.tools[WEB_FETCH_TOOL]) } } : {},
|
|
4501
4980
|
...ctx.sandbox ? { sandbox: ctx.sandbox.executor } : {},
|
|
4502
|
-
...ctx.subagents ? { subagents: SPAWN_EXECUTOR_NOTE } : {}
|
|
4981
|
+
...ctx.subagents ? { subagents: SPAWN_EXECUTOR_NOTE } : {},
|
|
4982
|
+
...ctx.askUser ? { askUser: ASK_USER_EXECUTOR_NOTE } : {}
|
|
4503
4983
|
});
|
|
4504
4984
|
const prompt = attempt.earlier?.length ? `${parts.prompt}
|
|
4505
4985
|
|
|
@@ -4559,6 +5039,7 @@ ${renderEarlierAttempts(attempt.earlier)}` : parts.prompt;
|
|
|
4559
5039
|
ctx.log.debug("executor text:", loop.text);
|
|
4560
5040
|
const cut = capNotice(ctx, "executor", loop.finishReason);
|
|
4561
5041
|
if (cut) ctx.log.warn(cut);
|
|
5042
|
+
cutWhileReasoning(ctx, "executor", loop.finishReason, loop.usage);
|
|
4562
5043
|
const { summary, blocked } = splitBlocker(loop.text);
|
|
4563
5044
|
return {
|
|
4564
5045
|
result: {
|
|
@@ -4718,7 +5199,11 @@ var TieredPlanStepSchema = PlanStepSchema.extend({
|
|
|
4718
5199
|
complexity: z5.enum(["low", "medium", "high"]).optional()
|
|
4719
5200
|
});
|
|
4720
5201
|
var PlanSchema = z5.object({
|
|
4721
|
-
/**
|
|
5202
|
+
/**
|
|
5203
|
+
* The planner's private one-sentence note. Never shown as an answer: with an empty `steps` (a
|
|
5204
|
+
* greeting, small talk, a question that needs no tool) the answer is written by the answering
|
|
5205
|
+
* stage.
|
|
5206
|
+
*/
|
|
4722
5207
|
thought: z5.string(),
|
|
4723
5208
|
steps: z5.array(PlanStepSchema),
|
|
4724
5209
|
/** Names of the configured skills that apply to this goal. */
|
|
@@ -4755,10 +5240,12 @@ ${nudge}` : goal;
|
|
|
4755
5240
|
toolCatalog: ctx.toolCatalog,
|
|
4756
5241
|
mode,
|
|
4757
5242
|
history: ctx.history,
|
|
5243
|
+
...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
|
|
4758
5244
|
skills: skillIndex,
|
|
4759
5245
|
searchMode: ctx.strategy === "search",
|
|
4760
5246
|
...ctx.sandbox ? { sandbox: ctx.sandbox.planner } : {},
|
|
4761
5247
|
...ctx.subagents ? { subagents: SPAWN_PLANNER_NOTE } : {},
|
|
5248
|
+
...ctx.askUser ? { askUser: ASK_USER_PLANNER_NOTE } : {},
|
|
4762
5249
|
...ctx.tiers ? { tiers: true } : {}
|
|
4763
5250
|
});
|
|
4764
5251
|
return {
|
|
@@ -4784,15 +5271,23 @@ ${nudge}` : goal;
|
|
|
4784
5271
|
let wasted = normalizeUsage();
|
|
4785
5272
|
if (ctx.plannerMode === "native") {
|
|
4786
5273
|
try {
|
|
4787
|
-
const result2 = await
|
|
4788
|
-
ctx
|
|
4789
|
-
|
|
4790
|
-
|
|
5274
|
+
const result2 = await withReasoningRoom(
|
|
5275
|
+
ctx,
|
|
5276
|
+
"planner",
|
|
5277
|
+
"plan",
|
|
5278
|
+
() => generateStructured(
|
|
5279
|
+
ctx.plannerModel,
|
|
5280
|
+
ctx.tiers ? TieredPlanSchema : PlanSchema,
|
|
5281
|
+
commonFor("native")
|
|
5282
|
+
),
|
|
5283
|
+
(spent) => {
|
|
5284
|
+
wasted = addUsage(wasted, spent);
|
|
5285
|
+
}
|
|
4791
5286
|
);
|
|
4792
5287
|
ctx.log.debug("planner (native):", result2.object);
|
|
4793
5288
|
return {
|
|
4794
5289
|
plan: { thought: result2.object.thought, steps: toSteps(result2.object.steps, cap) },
|
|
4795
|
-
usage: normalizeUsage(result2.usage),
|
|
5290
|
+
usage: addUsage(wasted, normalizeUsage(result2.usage)),
|
|
4796
5291
|
skills: validSkills(result2.object.skills)
|
|
4797
5292
|
};
|
|
4798
5293
|
} catch (err) {
|
|
@@ -4801,16 +5296,26 @@ ${nudge}` : goal;
|
|
|
4801
5296
|
if (refused) throw refused;
|
|
4802
5297
|
const overflow = contextOverflowOf(err, ctx.plannerModel);
|
|
4803
5298
|
if (overflow) throw overflow;
|
|
4804
|
-
wasted = usageOfError(err);
|
|
5299
|
+
wasted = addUsage(wasted, usageOfError(err));
|
|
4805
5300
|
const why = asMessage(withCapHint(ctx, "planner", err));
|
|
4806
5301
|
ctx.log.warn("planner: native structured output failed, salvaging:", why);
|
|
4807
5302
|
ctx.emit({ type: "retry", phase: "plan", attempt: 1, error: why });
|
|
4808
5303
|
}
|
|
4809
5304
|
}
|
|
4810
|
-
const result = await
|
|
5305
|
+
const result = await withReasoningRoom(
|
|
5306
|
+
ctx,
|
|
5307
|
+
"planner",
|
|
5308
|
+
"plan",
|
|
5309
|
+
() => generate(ctx.plannerModel, commonFor("prompted")),
|
|
5310
|
+
(spent) => {
|
|
5311
|
+
wasted = addUsage(wasted, spent);
|
|
5312
|
+
}
|
|
5313
|
+
).catch((err) => {
|
|
4811
5314
|
throw imageRefusal(ctx, err, ctx.plannerModel) ?? contextOverflowOf(err, ctx.plannerModel) ?? err;
|
|
4812
5315
|
});
|
|
4813
5316
|
const parsed = parsePlannerResponse(result.text);
|
|
5317
|
+
const cut = result.finishReason === "length";
|
|
5318
|
+
const failed = parsed.plan.length === 0 && (cut || !result.text.trim()) ? capNotice(ctx, "planner", result.finishReason) ?? (cut ? "[planner] the model's output was cut off before it wrote a plan" : `[planner] the model returned no text (finish reason: ${result.finishReason})`) : void 0;
|
|
4814
5319
|
ctx.log.debug("planner (prompted) raw:", result.text);
|
|
4815
5320
|
ctx.log.debug("planner (prompted) parsed:", parsed);
|
|
4816
5321
|
return {
|
|
@@ -4825,7 +5330,8 @@ ${nudge}` : goal;
|
|
|
4825
5330
|
)
|
|
4826
5331
|
},
|
|
4827
5332
|
usage: addUsage(wasted, normalizeUsage(result.usage)),
|
|
4828
|
-
skills: validSkills(parsed.skills)
|
|
5333
|
+
skills: validSkills(parsed.skills),
|
|
5334
|
+
...failed ? { failed } : {}
|
|
4829
5335
|
};
|
|
4830
5336
|
};
|
|
4831
5337
|
var asMessage = (err) => err instanceof Error ? err.message : String(err);
|
|
@@ -4960,10 +5466,10 @@ var replanDecisionQuestion = (context) => ({
|
|
|
4960
5466
|
options: REPLAN_DECISION_OPTIONS,
|
|
4961
5467
|
context
|
|
4962
5468
|
});
|
|
4963
|
-
var routeDecisionQuestion = (
|
|
5469
|
+
var routeDecisionQuestion = (routes2, context) => ({
|
|
4964
5470
|
id: "route",
|
|
4965
5471
|
prompt: "One step of a pipeline has answered. Which ONE route does its answer take?",
|
|
4966
|
-
options:
|
|
5472
|
+
options: routes2.map((r) => ({
|
|
4967
5473
|
id: r.label,
|
|
4968
5474
|
...r.description ? { description: r.description } : {}
|
|
4969
5475
|
})),
|
|
@@ -5136,23 +5642,39 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
|
|
|
5136
5642
|
let wasted = normalizeUsage();
|
|
5137
5643
|
if (ctx.plannerMode === "native") {
|
|
5138
5644
|
try {
|
|
5139
|
-
const result = await
|
|
5645
|
+
const result = await withReasoningRoom(
|
|
5646
|
+
ctx,
|
|
5647
|
+
"replanner",
|
|
5648
|
+
"replan",
|
|
5649
|
+
() => generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native")),
|
|
5650
|
+
(spent) => {
|
|
5651
|
+
wasted = addUsage(wasted, spent);
|
|
5652
|
+
}
|
|
5653
|
+
);
|
|
5140
5654
|
return {
|
|
5141
5655
|
decision: result.object.decision,
|
|
5142
5656
|
reason: result.object.reason,
|
|
5143
5657
|
plan: result.object.plan ?? [],
|
|
5144
|
-
usage: normalizeUsage(result.usage)
|
|
5658
|
+
usage: addUsage(wasted, normalizeUsage(result.usage))
|
|
5145
5659
|
};
|
|
5146
5660
|
} catch (err) {
|
|
5147
5661
|
if (ctx.signal?.aborted) throw err;
|
|
5148
|
-
wasted = usageOfError(err);
|
|
5662
|
+
wasted = addUsage(wasted, usageOfError(err));
|
|
5149
5663
|
const why = asMessage2(withCapHint(ctx, "replanner", err));
|
|
5150
5664
|
ctx.log.warn("replanner: native structured output failed, salvaging:", why);
|
|
5151
5665
|
ctx.emit({ type: "retry", phase: "replan", attempt: 1, error: why });
|
|
5152
5666
|
}
|
|
5153
5667
|
}
|
|
5154
5668
|
try {
|
|
5155
|
-
const result = await
|
|
5669
|
+
const result = await withReasoningRoom(
|
|
5670
|
+
ctx,
|
|
5671
|
+
"replanner",
|
|
5672
|
+
"replan",
|
|
5673
|
+
() => generate(ctx.plannerModel, commonFor("prompted")),
|
|
5674
|
+
(spent) => {
|
|
5675
|
+
wasted = addUsage(wasted, spent);
|
|
5676
|
+
}
|
|
5677
|
+
);
|
|
5156
5678
|
const parsed = parseReplannerResponse(result.text);
|
|
5157
5679
|
return {
|
|
5158
5680
|
decision: parsed.decision,
|
|
@@ -5211,7 +5733,7 @@ var decideReplanWithDecisionModel = async (ctx, goal, done, remaining, onUsage)
|
|
|
5211
5733
|
var asMessage2 = (err) => err instanceof Error ? err.message : String(err);
|
|
5212
5734
|
|
|
5213
5735
|
// src/agent/synthesizer.ts
|
|
5214
|
-
var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
|
|
5736
|
+
var synthesizeAnswer = async (ctx, goal, done, findings = [], options = {}) => {
|
|
5215
5737
|
const state = await ctx.state();
|
|
5216
5738
|
const active = ctx.activeSkills?.() ?? [];
|
|
5217
5739
|
const parts = ctx.prompts.synthesizer({
|
|
@@ -5221,8 +5743,32 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
|
|
|
5221
5743
|
findings,
|
|
5222
5744
|
activeSkills: active.length ? renderActiveSkills(active) : void 0,
|
|
5223
5745
|
updates: ctx.userUpdates?.(),
|
|
5224
|
-
...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {}
|
|
5746
|
+
...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {},
|
|
5747
|
+
...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
|
|
5748
|
+
...options.direct ? { direct: true, history: ctx.history } : {}
|
|
5225
5749
|
});
|
|
5750
|
+
const first = await streamAnswer(ctx, parts);
|
|
5751
|
+
let last = first;
|
|
5752
|
+
let usage = first.usage;
|
|
5753
|
+
if (cutWhileReasoning(ctx, "synthesizer", first.finishReason, first.usage) && !first.shown) {
|
|
5754
|
+
const message = `${first.cut ?? "[synthesizer] the model's output was cut off"} - the model spent ${first.usage.reasoningTokens ?? 0} of them reasoning: repeating the call without the default cap`;
|
|
5755
|
+
ctx.log.warn(message);
|
|
5756
|
+
ctx.emit({ type: "retry", phase: "synthesize", attempt: 1, error: message });
|
|
5757
|
+
last = await streamAnswer(ctx, parts);
|
|
5758
|
+
usage = addUsage(usage, last.usage);
|
|
5759
|
+
} else if (first.cut) {
|
|
5760
|
+
ctx.log.warn(first.cut);
|
|
5761
|
+
}
|
|
5762
|
+
const text = parsePlainText(last.text);
|
|
5763
|
+
return {
|
|
5764
|
+
text,
|
|
5765
|
+
usage,
|
|
5766
|
+
...text ? {} : {
|
|
5767
|
+
empty: last.cut ?? `[synthesizer] the model returned no text (finish reason: ${last.finishReason ?? "unknown"})`
|
|
5768
|
+
}
|
|
5769
|
+
};
|
|
5770
|
+
};
|
|
5771
|
+
var streamAnswer = async (ctx, parts) => {
|
|
5226
5772
|
const result = stream(ctx.synthesizerModel, {
|
|
5227
5773
|
...stageCall(ctx, "synthesizer", parts.system),
|
|
5228
5774
|
...promptFor(ctx, parts.prompt),
|
|
@@ -5231,6 +5777,11 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
|
|
|
5231
5777
|
timeoutMs: ctx.config.chatTimeoutMs
|
|
5232
5778
|
});
|
|
5233
5779
|
let text = "";
|
|
5780
|
+
let shown = false;
|
|
5781
|
+
const show = (delta) => {
|
|
5782
|
+
shown = true;
|
|
5783
|
+
ctx.emit({ type: "final.text-delta", delta });
|
|
5784
|
+
};
|
|
5234
5785
|
let verdict = "unknown";
|
|
5235
5786
|
for await (const part of result.fullStream) {
|
|
5236
5787
|
if (part.type === "reasoning-delta") {
|
|
@@ -5251,19 +5802,19 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
|
|
|
5251
5802
|
verdict = looksLikeJson(lead) ? "suppress" : "emit";
|
|
5252
5803
|
if (verdict === "emit") {
|
|
5253
5804
|
const visible = text.includes("</think>") ? text.slice(text.lastIndexOf("</think>") + "</think>".length).trimStart() : text;
|
|
5254
|
-
if (visible)
|
|
5805
|
+
if (visible) show(visible);
|
|
5255
5806
|
}
|
|
5256
5807
|
} else if (verdict === "emit") {
|
|
5257
|
-
|
|
5808
|
+
show(delta);
|
|
5258
5809
|
}
|
|
5259
5810
|
}
|
|
5260
5811
|
const [usage, finishReason] = await Promise.all([result.usage, result.finishReason]);
|
|
5261
|
-
const cut = capNotice(ctx, "synthesizer", finishReason);
|
|
5262
|
-
if (cut) ctx.log.warn(cut);
|
|
5263
|
-
const clean = parsePlainText(text);
|
|
5264
5812
|
return {
|
|
5265
|
-
text
|
|
5266
|
-
usage: normalizeUsage(usage)
|
|
5813
|
+
text,
|
|
5814
|
+
usage: normalizeUsage(usage),
|
|
5815
|
+
finishReason,
|
|
5816
|
+
cut: capNotice(ctx, "synthesizer", finishReason),
|
|
5817
|
+
shown
|
|
5267
5818
|
};
|
|
5268
5819
|
};
|
|
5269
5820
|
|
|
@@ -5308,7 +5859,7 @@ var supportsPdf = (model) => {
|
|
|
5308
5859
|
};
|
|
5309
5860
|
|
|
5310
5861
|
// src/subagent/dynamic.ts
|
|
5311
|
-
import { jsonSchema as
|
|
5862
|
+
import { jsonSchema as jsonSchema4, tool as tool5 } from "ai";
|
|
5312
5863
|
var seeds = /* @__PURE__ */ new WeakMap();
|
|
5313
5864
|
var spawnSeedOf = (config) => seeds.get(config);
|
|
5314
5865
|
var createSpawnRun = (settings, seed, run) => ({
|
|
@@ -5328,12 +5879,12 @@ var abortError = () => {
|
|
|
5328
5879
|
return e;
|
|
5329
5880
|
};
|
|
5330
5881
|
var seq = 0;
|
|
5331
|
-
var
|
|
5882
|
+
var newId2 = () => globalThis.crypto?.randomUUID?.() ?? `helper-${Date.now().toString(36)}-${seq += 1}`;
|
|
5332
5883
|
var createDynamicSubagentTool = (deps) => {
|
|
5333
5884
|
const { settings } = deps;
|
|
5334
|
-
const t =
|
|
5885
|
+
const t = tool5({
|
|
5335
5886
|
description: spawnToolDescription(settings),
|
|
5336
|
-
inputSchema:
|
|
5887
|
+
inputSchema: jsonSchema4(SPAWN_INPUT_SCHEMA),
|
|
5337
5888
|
execute: async (raw, options) => {
|
|
5338
5889
|
const runCtx = toolRunContextOf(options);
|
|
5339
5890
|
const scope = runCtx?.spawn;
|
|
@@ -5361,7 +5912,7 @@ var createDynamicSubagentTool = (deps) => {
|
|
|
5361
5912
|
const depth = scope.depth + 1;
|
|
5362
5913
|
const maySpawn = depth < settings.maxDepth && deps.mayNest();
|
|
5363
5914
|
scope.root.spawned += 1;
|
|
5364
|
-
const id =
|
|
5915
|
+
const id = newId2();
|
|
5365
5916
|
const name = SPAWN_SUBAGENT_TOOL;
|
|
5366
5917
|
const emit = (e) => runCtx.emit(e);
|
|
5367
5918
|
const parentSignal = options?.abortSignal ?? runCtx.signal;
|
|
@@ -5402,6 +5953,9 @@ var createDynamicSubagentTool = (deps) => {
|
|
|
5402
5953
|
// is given them) or none. Left in, the helper's agent would mount its own from the
|
|
5403
5954
|
// config - tools it was not given, that spend money and write files.
|
|
5404
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,
|
|
5405
5959
|
availableTools: _available,
|
|
5406
5960
|
skills: _skills,
|
|
5407
5961
|
...inherited
|
|
@@ -5415,6 +5969,7 @@ var createDynamicSubagentTool = (deps) => {
|
|
|
5415
5969
|
_search,
|
|
5416
5970
|
_sandbox,
|
|
5417
5971
|
_media,
|
|
5972
|
+
_askUser,
|
|
5418
5973
|
_available
|
|
5419
5974
|
];
|
|
5420
5975
|
void _skills;
|
|
@@ -5445,7 +6000,8 @@ var createDynamicSubagentTool = (deps) => {
|
|
|
5445
6000
|
...runCtx.control ? { control: runCtx.control } : {},
|
|
5446
6001
|
...sandboxNotes && tools.run_js ? { sandboxNotes } : {},
|
|
5447
6002
|
...runCtx.elicitations ? { elicitations: runCtx.elicitations } : {},
|
|
5448
|
-
...runCtx.mcpSkills ? { mcpSkills: runCtx.mcpSkills } : {}
|
|
6003
|
+
...runCtx.mcpSkills ? { mcpSkills: runCtx.mcpSkills } : {},
|
|
6004
|
+
...runCtx.askUser ? { askUser: runCtx.askUser } : {}
|
|
5449
6005
|
});
|
|
5450
6006
|
parentSignal?.addEventListener("abort", onParentAbort, { once: true });
|
|
5451
6007
|
if (parentSignal?.aborted) controller.abort();
|
|
@@ -6062,6 +6618,9 @@ var createAgent = async (config) => {
|
|
|
6062
6618
|
}
|
|
6063
6619
|
const dynamicSubagents = resolveDynamicSubagents(config.subagents);
|
|
6064
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);
|
|
6065
6624
|
const buildStage = (override, stageName) => buildModelFromStage(
|
|
6066
6625
|
resolveStage(config.model, override, stageName),
|
|
6067
6626
|
config.credentials,
|
|
@@ -6169,7 +6728,7 @@ var createAgent = async (config) => {
|
|
|
6169
6728
|
config.availableTools,
|
|
6170
6729
|
config.excludedTools
|
|
6171
6730
|
);
|
|
6172
|
-
const sandbox = config.sandbox ? (await import("./sandbox-
|
|
6731
|
+
const sandbox = config.sandbox ? (await import("./sandbox-ZXWD5IWZ.js")).createSandbox(
|
|
6173
6732
|
config.sandbox === true ? {} : config.sandbox,
|
|
6174
6733
|
hostTools,
|
|
6175
6734
|
(m) => log.warn(m)
|
|
@@ -6210,7 +6769,8 @@ var createAgent = async (config) => {
|
|
|
6210
6769
|
const strategy = cfg.toolSelectionStrategy === "auto" ? catalog.length > cfg.toolSearchThreshold || toolTokens > cfg.compaction.contextWindowTokens * TOOL_SEARCH_WINDOW_SHARE ? "search" : "all" : cfg.toolSelectionStrategy;
|
|
6211
6770
|
const reserved = [
|
|
6212
6771
|
...skills.length || learning ? SKILL_TOOL_NAMES : [],
|
|
6213
|
-
...strategy === "search" ? [FIND_TOOLS_NAME] : []
|
|
6772
|
+
...strategy === "search" ? [FIND_TOOLS_NAME] : [],
|
|
6773
|
+
...askUserOn ? [ASK_USER_TOOL] : []
|
|
6214
6774
|
];
|
|
6215
6775
|
for (const name of reserved) {
|
|
6216
6776
|
if (Object.hasOwn(baseTools, name)) {
|
|
@@ -6220,6 +6780,10 @@ var createAgent = async (config) => {
|
|
|
6220
6780
|
}
|
|
6221
6781
|
}
|
|
6222
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;
|
|
6223
6787
|
const fixedPromptTokens = (active) => promptOverheadTokens({
|
|
6224
6788
|
systemPrompt: config.systemPrompt,
|
|
6225
6789
|
toolTokens: toolDefTokens,
|
|
@@ -6494,6 +7058,15 @@ ${renderActiveSkills(active)}`
|
|
|
6494
7058
|
)
|
|
6495
7059
|
);
|
|
6496
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;
|
|
6497
7070
|
if (strategy === "search") {
|
|
6498
7071
|
builtins[FIND_TOOLS_NAME] = createFindToolsTool(
|
|
6499
7072
|
() => catalog,
|
|
@@ -6531,7 +7104,8 @@ ${renderActiveSkills(active)}`
|
|
|
6531
7104
|
stepWrites: () => stepWrites,
|
|
6532
7105
|
clock,
|
|
6533
7106
|
mcpSkills: mcpSkillsActing,
|
|
6534
|
-
sessionLocks: () => sessionLocks
|
|
7107
|
+
sessionLocks: () => sessionLocks,
|
|
7108
|
+
...askChannel ? { askUser: askChannel } : {}
|
|
6535
7109
|
}
|
|
6536
7110
|
);
|
|
6537
7111
|
const deliver = (at) => {
|
|
@@ -6672,6 +7246,7 @@ ${renderActiveSkills(active)}`
|
|
|
6672
7246
|
} : {},
|
|
6673
7247
|
...sandboxNotes ? { sandbox: sandboxNotes } : {},
|
|
6674
7248
|
...spawnBuiltIn ? { subagents: true } : {},
|
|
7249
|
+
...askChannel ? { askUser: true } : {},
|
|
6675
7250
|
...mcpInstructions ? { mcpInstructions } : {},
|
|
6676
7251
|
discovered: () => discovered,
|
|
6677
7252
|
builtinTools,
|
|
@@ -6682,6 +7257,9 @@ ${renderActiveSkills(active)}`
|
|
|
6682
7257
|
currentStep = step;
|
|
6683
7258
|
},
|
|
6684
7259
|
images: images.length ? images : void 0,
|
|
7260
|
+
// No file now, but one in an earlier turn: the model is told, or it answers about a
|
|
7261
|
+
// picture it only read the name of.
|
|
7262
|
+
...!images.length && history.some((m) => m.role === "user" && hasAttachedMark(m.content)) ? { attachmentsNote: NO_ATTACHMENT_NOTE } : {},
|
|
6685
7263
|
userUpdates: () => userUpdates.map((u) => u.text),
|
|
6686
7264
|
...port ? { takeRoundUpdates: () => deliver("round") } : {}
|
|
6687
7265
|
};
|
|
@@ -6701,7 +7279,14 @@ ${renderActiveSkills(active)}`
|
|
|
6701
7279
|
let planned = resumed ? { plan: resumed.plan, usage: emptyUsage(), skills: [] } : await createPlan(ctx, text);
|
|
6702
7280
|
if (!resumed) bumpUsage(planned.usage, "plan");
|
|
6703
7281
|
if (isAborted()) return stop();
|
|
6704
|
-
if (planned.
|
|
7282
|
+
if (planned.failed) {
|
|
7283
|
+
log.warn("planner failed:", planned.failed);
|
|
7284
|
+
emit({ type: "error", phase: "run", error: planned.failed, code: "no-plan" });
|
|
7285
|
+
result.final = planned.failed;
|
|
7286
|
+
track.error = planned.failed;
|
|
7287
|
+
return result;
|
|
7288
|
+
}
|
|
7289
|
+
if (planned.plan.steps.length === 0 && plannerMode === "prompted" && catalog.length > 0 && text.split(/\s+/).length > 2) {
|
|
6705
7290
|
log.warn(
|
|
6706
7291
|
"planner returned no steps for a multi-word goal \u2014 retrying with a nudge. thought:",
|
|
6707
7292
|
planned.plan.thought
|
|
@@ -6718,10 +7303,27 @@ ${renderActiveSkills(active)}`
|
|
|
6718
7303
|
if (isAborted()) return stop();
|
|
6719
7304
|
if (planned.plan.steps.length === 0) {
|
|
6720
7305
|
log.info("no plan \u2014 answering directly (no tools will run)");
|
|
6721
|
-
|
|
6722
|
-
|
|
6723
|
-
|
|
6724
|
-
|
|
7306
|
+
deliver("final");
|
|
7307
|
+
let direct;
|
|
7308
|
+
try {
|
|
7309
|
+
direct = await synthesizeAnswer(ctx, text, [], [], { direct: true });
|
|
7310
|
+
} catch (err) {
|
|
7311
|
+
if (isAborted()) return stop();
|
|
7312
|
+
throw err;
|
|
7313
|
+
}
|
|
7314
|
+
bumpUsage(direct.usage, "synthesize");
|
|
7315
|
+
if (isAborted()) return stop();
|
|
7316
|
+
if (!direct.text) {
|
|
7317
|
+
const message = direct.empty ?? "[synthesizer] the model returned no answer";
|
|
7318
|
+
log.warn(message);
|
|
7319
|
+
emit({ type: "error", phase: "run", error: message, code: "no-answer" });
|
|
7320
|
+
result.final = message;
|
|
7321
|
+
track.error = message;
|
|
7322
|
+
return result;
|
|
7323
|
+
}
|
|
7324
|
+
emit({ type: "final", text: direct.text });
|
|
7325
|
+
await remember({ role: "assistant", content: direct.text });
|
|
7326
|
+
result.final = direct.text;
|
|
6725
7327
|
return result;
|
|
6726
7328
|
}
|
|
6727
7329
|
log.info(
|
|
@@ -6765,6 +7367,8 @@ ${renderActiveSkills(active)}`
|
|
|
6765
7367
|
...userUpdates.length ? { userUpdates: userUpdates.map((u) => ({ ...u })) } : {},
|
|
6766
7368
|
...escalationCount ? { escalations: escalationCount } : {},
|
|
6767
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 } : {},
|
|
6768
7372
|
attempt,
|
|
6769
7373
|
...extra
|
|
6770
7374
|
});
|
|
@@ -7310,6 +7914,7 @@ ${renderActiveSkills(active)}`
|
|
|
7310
7914
|
};
|
|
7311
7915
|
|
|
7312
7916
|
// src/pipeline/index.ts
|
|
7917
|
+
import { NoObjectGeneratedError as NoObjectGeneratedError2 } from "ai";
|
|
7313
7918
|
import { z as z6 } from "zod";
|
|
7314
7919
|
|
|
7315
7920
|
// src/pipeline/engine.ts
|
|
@@ -8045,7 +8650,7 @@ var PIPELINE_ROUTER_SYSTEM = "You are the Router of one step in a pipeline of ag
|
|
|
8045
8650
|
var ROUTER_HEAD_CHARS = 2e3;
|
|
8046
8651
|
var ROUTER_TAIL_CHARS = 6e3;
|
|
8047
8652
|
var renderPipelineRoutePrompt = (node, text) => {
|
|
8048
|
-
const
|
|
8653
|
+
const routes2 = (node.routes ?? []).map((r) => `- ${r.label}${r.description ? `: ${r.description}` : ""}`).join("\n");
|
|
8049
8654
|
const answer = text.length > ROUTER_HEAD_CHARS + ROUTER_TAIL_CHARS ? `${text.slice(0, ROUTER_HEAD_CHARS)}
|
|
8050
8655
|
[...]
|
|
8051
8656
|
${text.slice(-ROUTER_TAIL_CHARS)}` : text;
|
|
@@ -8054,7 +8659,7 @@ ${text.slice(-ROUTER_TAIL_CHARS)}` : text;
|
|
|
8054
8659
|
node.instructions ? `Its role:
|
|
8055
8660
|
${node.instructions}` : "",
|
|
8056
8661
|
`Routes:
|
|
8057
|
-
${
|
|
8662
|
+
${routes2}`,
|
|
8058
8663
|
`The step's answer:
|
|
8059
8664
|
${answer}`,
|
|
8060
8665
|
"Which route? Answer with one label from the list."
|
|
@@ -8393,51 +8998,63 @@ ${t.text}`).join("\n\n");
|
|
|
8393
8998
|
};
|
|
8394
8999
|
|
|
8395
9000
|
// src/pipeline/index.ts
|
|
8396
|
-
var
|
|
9001
|
+
var aborted2 = () => new DOMException("Aborted", "AbortError");
|
|
8397
9002
|
var pickRoute = async ({ agent, config }, node, text, signal) => {
|
|
8398
9003
|
const cfg = resolveConfig(config);
|
|
8399
9004
|
const labels = (node.routes ?? []).map((r) => r.label);
|
|
8400
|
-
const
|
|
8401
|
-
|
|
8402
|
-
|
|
8403
|
-
|
|
8404
|
-
|
|
8405
|
-
|
|
8406
|
-
|
|
8407
|
-
|
|
9005
|
+
const window = cfg.compaction.contextWindowTokens;
|
|
9006
|
+
const call = () => {
|
|
9007
|
+
const cap = stageOutputCap(config, "replanner", window).tokens;
|
|
9008
|
+
return {
|
|
9009
|
+
system: PIPELINE_ROUTER_SYSTEM,
|
|
9010
|
+
prompt: renderPipelineRoutePrompt(node, text),
|
|
9011
|
+
// No cap: the host turned it off, or the stage thinks.
|
|
9012
|
+
...cap ? { maxOutputTokens: cap } : {},
|
|
9013
|
+
temperature: cfg.temperature,
|
|
9014
|
+
abortSignal: signal,
|
|
9015
|
+
timeoutMs: cfg.chatTimeoutMs
|
|
9016
|
+
};
|
|
8408
9017
|
};
|
|
8409
9018
|
let wasted = normalizeUsage();
|
|
8410
|
-
|
|
8411
|
-
|
|
8412
|
-
|
|
8413
|
-
|
|
8414
|
-
|
|
8415
|
-
|
|
8416
|
-
|
|
8417
|
-
|
|
8418
|
-
|
|
9019
|
+
const schema = z6.object({
|
|
9020
|
+
route: z6.enum(labels).describe("The label of the chosen route")
|
|
9021
|
+
});
|
|
9022
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
9023
|
+
try {
|
|
9024
|
+
const r = await generateStructured(agent.models.planner, schema, call());
|
|
9025
|
+
return {
|
|
9026
|
+
route: matchPipelineRoute(node, r.object),
|
|
9027
|
+
usage: addUsage(wasted, normalizeUsage(r.usage))
|
|
9028
|
+
};
|
|
9029
|
+
} catch (err) {
|
|
9030
|
+
if (signal.aborted) throw aborted2();
|
|
9031
|
+
const spent = usageOfError(err);
|
|
9032
|
+
wasted = addUsage(wasted, spent);
|
|
9033
|
+
const finishReason = NoObjectGeneratedError2.isInstance(err) ? err.finishReason : void 0;
|
|
9034
|
+
if (!observeReasoning(config, "replanner", window, finishReason, spent.reasoningTokens)) break;
|
|
9035
|
+
}
|
|
8419
9036
|
}
|
|
8420
9037
|
try {
|
|
8421
|
-
const r = await generate(agent.models.planner, call);
|
|
9038
|
+
const r = await generate(agent.models.planner, call());
|
|
8422
9039
|
return {
|
|
8423
9040
|
route: matchPipelineRoute(node, r.text),
|
|
8424
9041
|
usage: addUsage(wasted, normalizeUsage(r.usage))
|
|
8425
9042
|
};
|
|
8426
9043
|
} catch {
|
|
8427
|
-
if (signal.aborted) throw
|
|
9044
|
+
if (signal.aborted) throw aborted2();
|
|
8428
9045
|
return { usage: wasted };
|
|
8429
9046
|
}
|
|
8430
9047
|
};
|
|
8431
9048
|
var pickRouteWithDecisionModel = async ({ agent, config }, node, text, signal, emit) => {
|
|
8432
9049
|
const model = agent.decisionModel;
|
|
8433
|
-
const
|
|
8434
|
-
if (!model || config.decision?.route === false ||
|
|
8435
|
-
const question = routeDecisionQuestion(
|
|
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));
|
|
8436
9053
|
let outcome;
|
|
8437
9054
|
try {
|
|
8438
9055
|
outcome = await askDecisionModel(model, question, config.decision, signal);
|
|
8439
9056
|
} catch (err) {
|
|
8440
|
-
if (signal.aborted) throw
|
|
9057
|
+
if (signal.aborted) throw aborted2();
|
|
8441
9058
|
throw err;
|
|
8442
9059
|
}
|
|
8443
9060
|
const usage = decisionUsageOf(outcome);
|
|
@@ -8494,7 +9111,7 @@ var createPipeline = (definition, options) => {
|
|
|
8494
9111
|
ctx.emit(event);
|
|
8495
9112
|
}
|
|
8496
9113
|
});
|
|
8497
|
-
if (result.stopped || ctx.signal.aborted) throw
|
|
9114
|
+
if (result.stopped || ctx.signal.aborted) throw aborted2();
|
|
8498
9115
|
if (failure !== void 0) throw new Error(failure);
|
|
8499
9116
|
if (!node.routes?.length) return { text: result.final, usage: result.usage };
|
|
8500
9117
|
const picked = await pickPipelineRoute(node, result.final, {
|
|
@@ -8554,7 +9171,7 @@ var nodeResolver = (options) => async (node) => {
|
|
|
8554
9171
|
};
|
|
8555
9172
|
|
|
8556
9173
|
// src/subagent/tool.ts
|
|
8557
|
-
import { asSchema, jsonSchema as
|
|
9174
|
+
import { asSchema, jsonSchema as jsonSchema5, tool as tool6 } from "ai";
|
|
8558
9175
|
|
|
8559
9176
|
// src/subagent/protocol.ts
|
|
8560
9177
|
var toCloneable = (value) => {
|
|
@@ -8698,12 +9315,16 @@ var createSubagentTool = (opts) => {
|
|
|
8698
9315
|
})
|
|
8699
9316
|
);
|
|
8700
9317
|
};
|
|
8701
|
-
const runInProcess = async (task, signal, forward, hostTools, profile, id, elicitations, sessionLocks) => {
|
|
9318
|
+
const runInProcess = async (task, signal, forward, hostTools, profile, id, elicitations, sessionLocks, askUser) => {
|
|
8702
9319
|
const config = { ...opts.config, ...profile?.config };
|
|
8703
|
-
const
|
|
9320
|
+
const childConfig = {
|
|
8704
9321
|
...config,
|
|
8705
9322
|
tools: { ...asSubagentCalls(config.tools, id, elicitations), ...hostTools }
|
|
8706
|
-
}
|
|
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);
|
|
8707
9328
|
let runError;
|
|
8708
9329
|
const result = await agent.run(
|
|
8709
9330
|
task,
|
|
@@ -8811,9 +9432,9 @@ var createSubagentTool = (opts) => {
|
|
|
8811
9432
|
|
|
8812
9433
|
Optional \`profile\` (omit it for the default):
|
|
8813
9434
|
${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : opts.description;
|
|
8814
|
-
const t =
|
|
9435
|
+
const t = tool6({
|
|
8815
9436
|
description,
|
|
8816
|
-
inputSchema:
|
|
9437
|
+
inputSchema: jsonSchema5({
|
|
8817
9438
|
type: "object",
|
|
8818
9439
|
properties: {
|
|
8819
9440
|
task: {
|
|
@@ -8893,7 +9514,11 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
|
|
|
8893
9514
|
profile,
|
|
8894
9515
|
id,
|
|
8895
9516
|
runCtx?.elicitations,
|
|
8896
|
-
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
|
|
8897
9522
|
)).catch((err) => {
|
|
8898
9523
|
if (stoppedByUser)
|
|
8899
9524
|
throw new Error(
|
|
@@ -8930,7 +9555,7 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
|
|
|
8930
9555
|
};
|
|
8931
9556
|
|
|
8932
9557
|
// src/subagent/worker.ts
|
|
8933
|
-
import { dynamicTool, jsonSchema as
|
|
9558
|
+
import { dynamicTool, jsonSchema as jsonSchema6 } from "ai";
|
|
8934
9559
|
|
|
8935
9560
|
// src/secrets/store.ts
|
|
8936
9561
|
var VaultCredentialStore = class {
|
|
@@ -8991,7 +9616,7 @@ var serveSubagentWorker = (opts = {}) => {
|
|
|
8991
9616
|
const proxy = (spec) => {
|
|
8992
9617
|
const t = dynamicTool({
|
|
8993
9618
|
description: spec.description,
|
|
8994
|
-
inputSchema:
|
|
9619
|
+
inputSchema: jsonSchema6(spec.inputSchema),
|
|
8995
9620
|
execute: (input, options) => new Promise((resolve, reject) => {
|
|
8996
9621
|
const callId = `call-${callSeq += 1}`;
|
|
8997
9622
|
const signal = options?.abortSignal;
|
|
@@ -9263,7 +9888,18 @@ export {
|
|
|
9263
9888
|
APP_SAMPLING_PER_MINUTE,
|
|
9264
9889
|
APP_SAMPLING_REASONING_TOKENS,
|
|
9265
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,
|
|
9266
9901
|
AppSamplingError,
|
|
9902
|
+
AskUserInputError,
|
|
9267
9903
|
AttachmentsNotSupportedError,
|
|
9268
9904
|
ContextWindowExceededError,
|
|
9269
9905
|
DECISION_PROVIDERS,
|
|
@@ -9319,6 +9955,7 @@ export {
|
|
|
9319
9955
|
MemoryRunStore,
|
|
9320
9956
|
MemorySkillStore,
|
|
9321
9957
|
MemoryStore,
|
|
9958
|
+
NO_ATTACHMENT_NOTE,
|
|
9322
9959
|
PIPELINE_LIMITS,
|
|
9323
9960
|
PIPELINE_ROUTER_SYSTEM,
|
|
9324
9961
|
PipelineNodeError,
|
|
@@ -9380,9 +10017,12 @@ export {
|
|
|
9380
10017
|
buildModelFromStage,
|
|
9381
10018
|
buildSearchRequest,
|
|
9382
10019
|
bytesToBase64,
|
|
10020
|
+
checkAskUserAnswer,
|
|
10021
|
+
checkAskUserInput,
|
|
9383
10022
|
checkEgressUrl,
|
|
9384
10023
|
checkLimits,
|
|
9385
10024
|
classifyAddress,
|
|
10025
|
+
cleanAskUserText,
|
|
9386
10026
|
compactHistory,
|
|
9387
10027
|
compactSteps,
|
|
9388
10028
|
compressHistory,
|
|
@@ -9513,6 +10153,7 @@ export {
|
|
|
9513
10153
|
sniffMediaType,
|
|
9514
10154
|
splitBlocker,
|
|
9515
10155
|
stageOutputCap,
|
|
10156
|
+
stageReasons,
|
|
9516
10157
|
stream,
|
|
9517
10158
|
supportsImages,
|
|
9518
10159
|
supportsNativeTools,
|