@dudko.dev/agent-web 0.0.44 → 0.0.45

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.cjs CHANGED
@@ -3356,6 +3356,7 @@ __export(src_exports, {
3356
3356
  MemoryRunStore: () => MemoryRunStore,
3357
3357
  MemorySkillStore: () => MemorySkillStore,
3358
3358
  MemoryStore: () => MemoryStore,
3359
+ NO_ATTACHMENT_NOTE: () => NO_ATTACHMENT_NOTE,
3359
3360
  PIPELINE_LIMITS: () => PIPELINE_LIMITS,
3360
3361
  PIPELINE_ROUTER_SYSTEM: () => PIPELINE_ROUTER_SYSTEM,
3361
3362
  PipelineNodeError: () => PipelineNodeError,
@@ -3550,6 +3551,7 @@ __export(src_exports, {
3550
3551
  sniffMediaType: () => sniffMediaType,
3551
3552
  splitBlocker: () => splitBlocker,
3552
3553
  stageOutputCap: () => stageOutputCap,
3554
+ stageReasons: () => stageReasons,
3553
3555
  stream: () => stream,
3554
3556
  supportsImages: () => supportsImages,
3555
3557
  supportsNativeTools: () => supportsNativeTools,
@@ -3683,6 +3685,16 @@ var BUDGET_SHARES = {
3683
3685
  compaction: { num: 1, den: 125, min: 256, max: 4096 }
3684
3686
  };
3685
3687
  var share = (window, s) => Math.min(s.max, Math.max(s.min, Math.round(window * s.num / s.den)));
3688
+ var reasoningStages = /* @__PURE__ */ new WeakMap();
3689
+ var stageReasons = (c, stage) => reasoningStages.get(c)?.has(stage) === true;
3690
+ var observeReasoning = (c, stage, contextWindowTokens, finishReason, reasoningTokens) => {
3691
+ if (!(typeof reasoningTokens === "number" && reasoningTokens > 0)) return false;
3692
+ const cap2 = stageOutputCap(c, stage, contextWindowTokens);
3693
+ const seen = reasoningStages.get(c) ?? /* @__PURE__ */ new Set();
3694
+ seen.add(stage);
3695
+ reasoningStages.set(c, seen);
3696
+ return finishReason === "length" && cap2.derived && cap2.tokens !== void 0;
3697
+ };
3686
3698
  var stageOutputCap = (c, stage, contextWindowTokens) => {
3687
3699
  const set = c.limits?.perCall?.[stage] ?? c.budgets?.[stage];
3688
3700
  if (typeof set === "number" && Number.isFinite(set)) {
@@ -3690,6 +3702,7 @@ var stageOutputCap = (c, stage, contextWindowTokens) => {
3690
3702
  }
3691
3703
  const thinking = resolveThinking(thinkingFor(stage, c.thinking, c.stageThinking));
3692
3704
  if (thinking.reasoning && thinking.reasoning !== "none") return { derived: false };
3705
+ if (stageReasons(c, stage)) return { derived: false };
3693
3706
  return { tokens: share(contextWindowTokens, BUDGET_SHARES[stage]), derived: true };
3694
3707
  };
3695
3708
  var outputCapNotice = (c, stage, contextWindowTokens, finishReason) => {
@@ -4692,14 +4705,22 @@ var stateBlock = (state) => state && state.trim() ? `
4692
4705
 
4693
4706
  STATE:
4694
4707
  ${state}` : "";
4695
- var historyBlock = (history) => {
4708
+ var ATTACHED_MARK = /\n\[attached: [^\]\n]*\]$/;
4709
+ var historyLine = (content, max) => {
4710
+ const mark = ATTACHED_MARK.exec(content)?.[0];
4711
+ if (!mark || content.length <= max) return clip(content, max);
4712
+ return `${clip(content.slice(0, -mark.length), Math.max(1, max - mark.length))}${mark}`;
4713
+ };
4714
+ var historyBlock = (history, perMessage = 400) => {
4696
4715
  if (!history || history.length === 0) return "";
4697
- const lines = history.slice(-8).map((m) => `${m.role}: ${clip(m.content, 400)}`);
4716
+ const lines = history.slice(-8).map((m) => `${m.role}: ${historyLine(m.content, perMessage)}`);
4698
4717
  return `
4699
4718
 
4700
4719
  CONVERSATION SO FAR:
4701
4720
  ${lines.join("\n")}`;
4702
4721
  };
4722
+ var hasAttachedMark = (content) => ATTACHED_MARK.test(content);
4723
+ 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.`;
4703
4724
  var section = (title, body) => body && body.trim() ? `
4704
4725
 
4705
4726
  ${title}:
@@ -4728,17 +4749,17 @@ var PLANNER_RULES = `- Act autonomously: whenever the TOOLS can do the work or l
4728
4749
  - Never repeat or pad steps.`;
4729
4750
  var PLANNER_NATIVE = `You are the PLANNER of an autonomous tool-using agent that works step by step.
4730
4751
  Produce a brief "thought" and an ordered "steps" list (1\u20136 DISTINCT, self-contained steps).
4731
- Return an EMPTY steps list ONLY for a pure greeting, thanks or small talk, or a question you can answer completely from the STATE and general knowledge without any tool \u2014 then put the answer itself in "thought".
4752
+ 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.
4732
4753
  ${PLANNER_RULES}`;
4733
4754
  var PLANNER_PROMPTED = `You are the PLANNER of an autonomous tool-using agent that works step by step.
4734
4755
 
4735
4756
  Reply with a single JSON object, nothing else:
4736
4757
  { "reply": string, "plan": string[], "skills": string[] }
4737
- - For a real goal: "reply" is one short sentence; "plan" is 1\u20136 DISTINCT, self-contained steps.
4738
- - Set "plan": [] ONLY for a pure greeting, thanks or small talk, or a question you can answer completely from the STATE and general knowledge without any tool \u2014 then put the answer itself in "reply".
4758
+ - "reply" is your private one-sentence note (the user never sees it); for a real goal "plan" is 1\u20136 DISTINCT, self-contained steps.
4759
+ - 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.
4739
4760
  ${PLANNER_RULES}`;
4740
4761
  var PLANNER_SKILLS = `
4741
- If a SKILLS list is present, list the names of the skills that apply to this goal in "skills" (or leave it empty).`;
4762
+ "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.`;
4742
4763
  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.`;
4743
4764
  var PLANNER_TIERS_NATIVE = `
4744
4765
  Steps run on models of different strength: set "complexity" on every step. ${COMPLEXITY_LEVELS}`;
@@ -4789,6 +4810,13 @@ var SYNTHESIZER_SYSTEM = `You are the SYNTHESIZER. Answer the user's goal from w
4789
4810
  - Mention any assumption the agent made. If something could not be done, say so plainly and why.
4790
4811
  - Do not ask follow-up questions unless the goal genuinely cannot be completed without the user.
4791
4812
  - Be concise and friendly. Plain text (light markdown is fine) \u2014 no JSON, no code.`;
4813
+ 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.
4814
+ - Answer the message under GOAL from the CONVERSATION SO FAR, the STATE, anything attached to this message and general knowledge.
4815
+ - 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.
4816
+ - Answer in the language of the user's message. Be concise and friendly. Plain text (light markdown is fine) \u2014 no JSON.`;
4817
+ var DIRECT_HISTORY_CHARS = 2e3;
4818
+ var noteLine = (note) => note && note.trim() ? `
4819
+ ${note.trim()}` : "";
4792
4820
  var defaultPrompts = {
4793
4821
  planner: (ctx) => ({
4794
4822
  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 ? `
@@ -4796,13 +4824,13 @@ ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("SKILLS", ct
4796
4824
 
4797
4825
  TOOLS:
4798
4826
  ${ctx.toolCatalog}`,
4799
- prompt: `GOAL: ${ctx.goal}${historyBlock(ctx.history)}${stateBlock(ctx.state)}`
4827
+ prompt: `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}${historyBlock(ctx.history)}${stateBlock(ctx.state)}`
4800
4828
  }),
4801
4829
  executor: (ctx) => ({
4802
4830
  system: (ctx.mode === "prompted" ? EXECUTOR_PROMPTED : EXECUTOR_NATIVE) + (ctx.searchMode ? EXECUTOR_SEARCH : "") + (ctx.skills ? EXECUTOR_SKILLS : "") + (ctx.learning ? executorLearning(ctx.learning.fetch) : "") + (ctx.sandbox ? `
4803
4831
  - ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("SKILLS", ctx.skills) + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
4804
4832
  prompt: [
4805
- `GOAL: ${ctx.goal}`,
4833
+ `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
4806
4834
  stateBlock(ctx.state).trimStart(),
4807
4835
  ctx.mode === "prompted" ? `TOOLS:
4808
4836
  ${ctx.toolCatalog}` : "",
@@ -4826,10 +4854,16 @@ ${numbered(ctx.remaining, "(none)")}`,
4826
4854
  ].filter(Boolean).join("\n\n")
4827
4855
  }),
4828
4856
  synthesizer: (ctx) => ({
4829
- system: SYNTHESIZER_SYSTEM + (ctx.sandbox ? `
4857
+ system: (ctx.direct ? SYNTHESIZER_DIRECT : SYNTHESIZER_SYSTEM) + (ctx.sandbox ? `
4830
4858
  - ${ctx.sandbox}` : "") + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
4831
- prompt: [
4832
- `GOAL: ${ctx.goal}`,
4859
+ prompt: ctx.direct ? [
4860
+ `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
4861
+ historyBlock(ctx.history, DIRECT_HISTORY_CHARS).trimStart(),
4862
+ stateBlock(ctx.state).trimStart(),
4863
+ updatesBlock(ctx.updates, 0, SYNTHESIZER_UPDATES_ADVICE),
4864
+ "Write the answer for the user."
4865
+ ].filter(Boolean).join("\n\n") : [
4866
+ `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
4833
4867
  stateBlock(ctx.state).trimStart(),
4834
4868
  updatesBlock(ctx.updates, 0, SYNTHESIZER_UPDATES_ADVICE),
4835
4869
  `What was done:
@@ -7542,6 +7576,7 @@ init_tiers();
7542
7576
 
7543
7577
  // src/agent/internal.ts
7544
7578
  var import_ai11 = require("ai");
7579
+ init_util();
7545
7580
  init_images();
7546
7581
  var promptFor = (ctx, prompt) => ctx.images?.length ? {
7547
7582
  messages: [
@@ -7561,6 +7596,7 @@ var imageRefusal = (ctx, err, model) => {
7561
7596
  return unsupportedAttachment(modelLabel(model), kind, detail && `the provider said: ${detail}`);
7562
7597
  };
7563
7598
  var systemFor = (ctx, base) => withSystem(base, ctx.raw.systemPrompt);
7599
+ var aborted = (ctx) => ctx.signal?.aborted === true;
7564
7600
  var stageCall = (ctx, stage, baseSystem) => {
7565
7601
  const withMcp = ctx.mcpInstructions && (stage === "planner" || stage === "executor") ? `${baseSystem}
7566
7602
 
@@ -7572,23 +7608,44 @@ ${ctx.mcpInstructions}` : baseSystem;
7572
7608
  cachingProviderOptions(caching, ctx.config.clientName, stage),
7573
7609
  thinking.providerOptions
7574
7610
  );
7611
+ const cap2 = stageReasons(ctx.raw, stage) ? stageOutputCap(ctx.raw, stage, capWindow(ctx, stage)).tokens ?? 0 : ctx.config.budgets[stage];
7575
7612
  return {
7576
7613
  system: cachedInstructions(system, caching),
7577
7614
  ...thinking.reasoning ? { reasoning: thinking.reasoning } : {},
7578
7615
  ...providerOptions ? { providerOptions } : {},
7579
- ...ctx.config.budgets[stage] > 0 ? { maxOutputTokens: ctx.config.budgets[stage] } : {}
7616
+ ...cap2 > 0 ? { maxOutputTokens: cap2 } : {}
7580
7617
  };
7581
7618
  };
7582
- var capNotice = (ctx, stage, finishReason) => outputCapNotice(
7583
- ctx.raw,
7584
- stage,
7585
- (stage === "executor" ? ctx.executorWindowTokens : void 0) ?? ctx.config.compaction.contextWindowTokens,
7586
- finishReason
7587
- );
7619
+ var capWindow = (ctx, stage) => (stage === "executor" ? ctx.executorWindowTokens : void 0) ?? ctx.config.compaction.contextWindowTokens;
7620
+ var cutWhileReasoning = (ctx, stage, finishReason, usage) => observeReasoning(ctx.raw, stage, capWindow(ctx, stage), finishReason, usage?.reasoningTokens);
7621
+ var withReasoningRoom = async (ctx, stage, phase, run, onWasted) => {
7622
+ const again = (why, spent2) => {
7623
+ onWasted(spent2);
7624
+ 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)`;
7625
+ ctx.log.warn(message);
7626
+ ctx.emit({ type: "retry", phase, attempt: 1, error: message });
7627
+ return run();
7628
+ };
7629
+ let first;
7630
+ try {
7631
+ first = await run();
7632
+ } catch (err) {
7633
+ if (aborted(ctx) || !import_ai11.NoObjectGeneratedError.isInstance(err)) throw err;
7634
+ withCapHint(ctx, stage, err);
7635
+ const spent2 = usageOfError(err);
7636
+ if (!cutWhileReasoning(ctx, stage, err.finishReason, spent2)) throw err;
7637
+ return again(err.message, spent2);
7638
+ }
7639
+ const spent = normalizeUsage(first.usage);
7640
+ const notice = capNotice(ctx, stage, first.finishReason);
7641
+ if (!cutWhileReasoning(ctx, stage, first.finishReason, spent)) return first;
7642
+ return again(notice ?? `[${stage}] the model's output was cut off`, spent);
7643
+ };
7644
+ var capNotice = (ctx, stage, finishReason) => outputCapNotice(ctx.raw, stage, capWindow(ctx, stage), finishReason);
7588
7645
  var withCapHint = (ctx, stage, err) => {
7589
7646
  if (import_ai11.NoObjectGeneratedError.isInstance(err)) {
7590
7647
  const notice = capNotice(ctx, stage, err.finishReason);
7591
- if (notice) err.message = `${err.message} - ${notice}`;
7648
+ if (notice && !err.message.includes(notice)) err.message = `${err.message} - ${notice}`;
7592
7649
  }
7593
7650
  return err;
7594
7651
  };
@@ -7817,14 +7874,14 @@ var shareSubagentBudget = (parent, running, settings) => {
7817
7874
  var createSpawnGate = (max) => {
7818
7875
  let active = 0;
7819
7876
  const queue = [];
7820
- const aborted2 = () => {
7877
+ const aborted3 = () => {
7821
7878
  const e = new Error("Aborted");
7822
7879
  e.name = "AbortError";
7823
7880
  return e;
7824
7881
  };
7825
7882
  return (signal) => new Promise((resolve, reject) => {
7826
7883
  if (signal?.aborted) {
7827
- reject(aborted2());
7884
+ reject(aborted3());
7828
7885
  return;
7829
7886
  }
7830
7887
  const grant = () => {
@@ -7845,7 +7902,7 @@ var createSpawnGate = (max) => {
7845
7902
  if (i >= 0) {
7846
7903
  queue.splice(i, 1);
7847
7904
  }
7848
- reject(aborted2());
7905
+ reject(aborted3());
7849
7906
  }
7850
7907
  if (active < max) {
7851
7908
  grant();
@@ -7934,6 +7991,7 @@ var executeStep = async (base, goal, step, index, total, done, attempt = {}) =>
7934
7991
  const active = ctx.activeSkills?.() ?? [];
7935
7992
  const parts = ctx.prompts.executor({
7936
7993
  goal,
7994
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
7937
7995
  state,
7938
7996
  step: step.description,
7939
7997
  index,
@@ -8007,6 +8065,7 @@ ${renderEarlierAttempts(attempt.earlier)}` : parts.prompt;
8007
8065
  ctx.log.debug("executor text:", loop.text);
8008
8066
  const cut = capNotice(ctx, "executor", loop.finishReason);
8009
8067
  if (cut) ctx.log.warn(cut);
8068
+ cutWhileReasoning(ctx, "executor", loop.finishReason, loop.usage);
8010
8069
  const { summary, blocked } = splitBlocker(loop.text);
8011
8070
  return {
8012
8071
  result: {
@@ -8171,7 +8230,11 @@ var TieredPlanStepSchema = PlanStepSchema.extend({
8171
8230
  complexity: import_zod5.z.enum(["low", "medium", "high"]).optional()
8172
8231
  });
8173
8232
  var PlanSchema = import_zod5.z.object({
8174
- /** One short sentence. For a greeting/small talk, holds the answer and steps is empty. */
8233
+ /**
8234
+ * The planner's private one-sentence note. Never shown as an answer: with an empty `steps` (a
8235
+ * greeting, small talk, a question that needs no tool) the answer is written by the answering
8236
+ * stage.
8237
+ */
8175
8238
  thought: import_zod5.z.string(),
8176
8239
  steps: import_zod5.z.array(PlanStepSchema),
8177
8240
  /** Names of the configured skills that apply to this goal. */
@@ -8208,6 +8271,7 @@ ${nudge}` : goal;
8208
8271
  toolCatalog: ctx.toolCatalog,
8209
8272
  mode,
8210
8273
  history: ctx.history,
8274
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
8211
8275
  skills: skillIndex,
8212
8276
  searchMode: ctx.strategy === "search",
8213
8277
  ...ctx.sandbox ? { sandbox: ctx.sandbox.planner } : {},
@@ -8237,15 +8301,23 @@ ${nudge}` : goal;
8237
8301
  let wasted = normalizeUsage();
8238
8302
  if (ctx.plannerMode === "native") {
8239
8303
  try {
8240
- const result2 = await generateStructured(
8241
- ctx.plannerModel,
8242
- ctx.tiers ? TieredPlanSchema : PlanSchema,
8243
- commonFor("native")
8304
+ const result2 = await withReasoningRoom(
8305
+ ctx,
8306
+ "planner",
8307
+ "plan",
8308
+ () => generateStructured(
8309
+ ctx.plannerModel,
8310
+ ctx.tiers ? TieredPlanSchema : PlanSchema,
8311
+ commonFor("native")
8312
+ ),
8313
+ (spent) => {
8314
+ wasted = addUsage(wasted, spent);
8315
+ }
8244
8316
  );
8245
8317
  ctx.log.debug("planner (native):", result2.object);
8246
8318
  return {
8247
8319
  plan: { thought: result2.object.thought, steps: toSteps(result2.object.steps, cap2) },
8248
- usage: normalizeUsage(result2.usage),
8320
+ usage: addUsage(wasted, normalizeUsage(result2.usage)),
8249
8321
  skills: validSkills(result2.object.skills)
8250
8322
  };
8251
8323
  } catch (err) {
@@ -8254,16 +8326,26 @@ ${nudge}` : goal;
8254
8326
  if (refused) throw refused;
8255
8327
  const overflow = contextOverflowOf(err, ctx.plannerModel);
8256
8328
  if (overflow) throw overflow;
8257
- wasted = usageOfError(err);
8329
+ wasted = addUsage(wasted, usageOfError(err));
8258
8330
  const why = asMessage(withCapHint(ctx, "planner", err));
8259
8331
  ctx.log.warn("planner: native structured output failed, salvaging:", why);
8260
8332
  ctx.emit({ type: "retry", phase: "plan", attempt: 1, error: why });
8261
8333
  }
8262
8334
  }
8263
- const result = await generate(ctx.plannerModel, commonFor("prompted")).catch((err) => {
8335
+ const result = await withReasoningRoom(
8336
+ ctx,
8337
+ "planner",
8338
+ "plan",
8339
+ () => generate(ctx.plannerModel, commonFor("prompted")),
8340
+ (spent) => {
8341
+ wasted = addUsage(wasted, spent);
8342
+ }
8343
+ ).catch((err) => {
8264
8344
  throw imageRefusal(ctx, err, ctx.plannerModel) ?? contextOverflowOf(err, ctx.plannerModel) ?? err;
8265
8345
  });
8266
8346
  const parsed = parsePlannerResponse(result.text);
8347
+ const cut = result.finishReason === "length";
8348
+ 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;
8267
8349
  ctx.log.debug("planner (prompted) raw:", result.text);
8268
8350
  ctx.log.debug("planner (prompted) parsed:", parsed);
8269
8351
  return {
@@ -8278,7 +8360,8 @@ ${nudge}` : goal;
8278
8360
  )
8279
8361
  },
8280
8362
  usage: addUsage(wasted, normalizeUsage(result.usage)),
8281
- skills: validSkills(parsed.skills)
8363
+ skills: validSkills(parsed.skills),
8364
+ ...failed ? { failed } : {}
8282
8365
  };
8283
8366
  };
8284
8367
  var asMessage = (err) => err instanceof Error ? err.message : String(err);
@@ -8591,23 +8674,39 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
8591
8674
  let wasted = normalizeUsage();
8592
8675
  if (ctx.plannerMode === "native") {
8593
8676
  try {
8594
- const result = await generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native"));
8677
+ const result = await withReasoningRoom(
8678
+ ctx,
8679
+ "replanner",
8680
+ "replan",
8681
+ () => generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native")),
8682
+ (spent) => {
8683
+ wasted = addUsage(wasted, spent);
8684
+ }
8685
+ );
8595
8686
  return {
8596
8687
  decision: result.object.decision,
8597
8688
  reason: result.object.reason,
8598
8689
  plan: result.object.plan ?? [],
8599
- usage: normalizeUsage(result.usage)
8690
+ usage: addUsage(wasted, normalizeUsage(result.usage))
8600
8691
  };
8601
8692
  } catch (err) {
8602
8693
  if (ctx.signal?.aborted) throw err;
8603
- wasted = usageOfError(err);
8694
+ wasted = addUsage(wasted, usageOfError(err));
8604
8695
  const why = asMessage2(withCapHint(ctx, "replanner", err));
8605
8696
  ctx.log.warn("replanner: native structured output failed, salvaging:", why);
8606
8697
  ctx.emit({ type: "retry", phase: "replan", attempt: 1, error: why });
8607
8698
  }
8608
8699
  }
8609
8700
  try {
8610
- const result = await generate(ctx.plannerModel, commonFor("prompted"));
8701
+ const result = await withReasoningRoom(
8702
+ ctx,
8703
+ "replanner",
8704
+ "replan",
8705
+ () => generate(ctx.plannerModel, commonFor("prompted")),
8706
+ (spent) => {
8707
+ wasted = addUsage(wasted, spent);
8708
+ }
8709
+ );
8611
8710
  const parsed = parseReplannerResponse(result.text);
8612
8711
  return {
8613
8712
  decision: parsed.decision,
@@ -8669,7 +8768,7 @@ var asMessage2 = (err) => err instanceof Error ? err.message : String(err);
8669
8768
  init_context_window();
8670
8769
  init_generate();
8671
8770
  init_util();
8672
- var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
8771
+ var synthesizeAnswer = async (ctx, goal, done, findings = [], options = {}) => {
8673
8772
  const state = await ctx.state();
8674
8773
  const active = ctx.activeSkills?.() ?? [];
8675
8774
  const parts = ctx.prompts.synthesizer({
@@ -8679,8 +8778,32 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
8679
8778
  findings,
8680
8779
  activeSkills: active.length ? renderActiveSkills(active) : void 0,
8681
8780
  updates: ctx.userUpdates?.(),
8682
- ...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {}
8781
+ ...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {},
8782
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
8783
+ ...options.direct ? { direct: true, history: ctx.history } : {}
8683
8784
  });
8785
+ const first = await streamAnswer(ctx, parts);
8786
+ let last = first;
8787
+ let usage = first.usage;
8788
+ if (cutWhileReasoning(ctx, "synthesizer", first.finishReason, first.usage) && !first.shown) {
8789
+ 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`;
8790
+ ctx.log.warn(message);
8791
+ ctx.emit({ type: "retry", phase: "synthesize", attempt: 1, error: message });
8792
+ last = await streamAnswer(ctx, parts);
8793
+ usage = addUsage(usage, last.usage);
8794
+ } else if (first.cut) {
8795
+ ctx.log.warn(first.cut);
8796
+ }
8797
+ const text = parsePlainText(last.text);
8798
+ return {
8799
+ text,
8800
+ usage,
8801
+ ...text ? {} : {
8802
+ empty: last.cut ?? `[synthesizer] the model returned no text (finish reason: ${last.finishReason ?? "unknown"})`
8803
+ }
8804
+ };
8805
+ };
8806
+ var streamAnswer = async (ctx, parts) => {
8684
8807
  const result = stream(ctx.synthesizerModel, {
8685
8808
  ...stageCall(ctx, "synthesizer", parts.system),
8686
8809
  ...promptFor(ctx, parts.prompt),
@@ -8689,6 +8812,11 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
8689
8812
  timeoutMs: ctx.config.chatTimeoutMs
8690
8813
  });
8691
8814
  let text = "";
8815
+ let shown = false;
8816
+ const show = (delta) => {
8817
+ shown = true;
8818
+ ctx.emit({ type: "final.text-delta", delta });
8819
+ };
8692
8820
  let verdict = "unknown";
8693
8821
  for await (const part of result.fullStream) {
8694
8822
  if (part.type === "reasoning-delta") {
@@ -8709,19 +8837,19 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
8709
8837
  verdict = looksLikeJson(lead) ? "suppress" : "emit";
8710
8838
  if (verdict === "emit") {
8711
8839
  const visible = text.includes("</think>") ? text.slice(text.lastIndexOf("</think>") + "</think>".length).trimStart() : text;
8712
- if (visible) ctx.emit({ type: "final.text-delta", delta: visible });
8840
+ if (visible) show(visible);
8713
8841
  }
8714
8842
  } else if (verdict === "emit") {
8715
- ctx.emit({ type: "final.text-delta", delta });
8843
+ show(delta);
8716
8844
  }
8717
8845
  }
8718
8846
  const [usage, finishReason] = await Promise.all([result.usage, result.finishReason]);
8719
- const cut = capNotice(ctx, "synthesizer", finishReason);
8720
- if (cut) ctx.log.warn(cut);
8721
- const clean = parsePlainText(text);
8722
8847
  return {
8723
- text: clean || "Done \u2014 the changes have been applied.",
8724
- usage: normalizeUsage(usage)
8848
+ text,
8849
+ usage: normalizeUsage(usage),
8850
+ finishReason,
8851
+ cut: capNotice(ctx, "synthesizer", finishReason),
8852
+ shown
8725
8853
  };
8726
8854
  };
8727
8855
 
@@ -10239,6 +10367,9 @@ ${renderActiveSkills(active)}`
10239
10367
  currentStep = step;
10240
10368
  },
10241
10369
  images: images.length ? images : void 0,
10370
+ // No file now, but one in an earlier turn: the model is told, or it answers about a
10371
+ // picture it only read the name of.
10372
+ ...!images.length && history.some((m) => m.role === "user" && hasAttachedMark(m.content)) ? { attachmentsNote: NO_ATTACHMENT_NOTE } : {},
10242
10373
  userUpdates: () => userUpdates.map((u) => u.text),
10243
10374
  ...port ? { takeRoundUpdates: () => deliver("round") } : {}
10244
10375
  };
@@ -10258,7 +10389,14 @@ ${renderActiveSkills(active)}`
10258
10389
  let planned = resumed ? { plan: resumed.plan, usage: emptyUsage(), skills: [] } : await createPlan(ctx, text);
10259
10390
  if (!resumed) bumpUsage(planned.usage, "plan");
10260
10391
  if (isAborted()) return stop();
10261
- if (planned.plan.steps.length === 0 && text.split(/\s+/).length > 2) {
10392
+ if (planned.failed) {
10393
+ log.warn("planner failed:", planned.failed);
10394
+ emit({ type: "error", phase: "run", error: planned.failed, code: "no-plan" });
10395
+ result.final = planned.failed;
10396
+ track.error = planned.failed;
10397
+ return result;
10398
+ }
10399
+ if (planned.plan.steps.length === 0 && plannerMode === "prompted" && catalog.length > 0 && text.split(/\s+/).length > 2) {
10262
10400
  log.warn(
10263
10401
  "planner returned no steps for a multi-word goal \u2014 retrying with a nudge. thought:",
10264
10402
  planned.plan.thought
@@ -10275,10 +10413,27 @@ ${renderActiveSkills(active)}`
10275
10413
  if (isAborted()) return stop();
10276
10414
  if (planned.plan.steps.length === 0) {
10277
10415
  log.info("no plan \u2014 answering directly (no tools will run)");
10278
- const answer = planned.plan.thought.trim() || "Tell me what you'd like to do.";
10279
- emit({ type: "final", text: answer });
10280
- await remember({ role: "assistant", content: answer });
10281
- result.final = answer;
10416
+ deliver("final");
10417
+ let direct;
10418
+ try {
10419
+ direct = await synthesizeAnswer(ctx, text, [], [], { direct: true });
10420
+ } catch (err) {
10421
+ if (isAborted()) return stop();
10422
+ throw err;
10423
+ }
10424
+ bumpUsage(direct.usage, "synthesize");
10425
+ if (isAborted()) return stop();
10426
+ if (!direct.text) {
10427
+ const message = direct.empty ?? "[synthesizer] the model returned no answer";
10428
+ log.warn(message);
10429
+ emit({ type: "error", phase: "run", error: message, code: "no-answer" });
10430
+ result.final = message;
10431
+ track.error = message;
10432
+ return result;
10433
+ }
10434
+ emit({ type: "final", text: direct.text });
10435
+ await remember({ role: "assistant", content: direct.text });
10436
+ result.final = direct.text;
10282
10437
  return result;
10283
10438
  }
10284
10439
  log.info(
@@ -10870,6 +11025,7 @@ ${renderActiveSkills(active)}`
10870
11025
  init_tiers();
10871
11026
 
10872
11027
  // src/pipeline/index.ts
11028
+ var import_ai15 = require("ai");
10873
11029
  var import_zod6 = require("zod");
10874
11030
  init_generate();
10875
11031
  init_util();
@@ -11955,38 +12111,50 @@ ${t.text}`).join("\n\n");
11955
12111
  };
11956
12112
 
11957
12113
  // src/pipeline/index.ts
11958
- var aborted = () => new DOMException("Aborted", "AbortError");
12114
+ var aborted2 = () => new DOMException("Aborted", "AbortError");
11959
12115
  var pickRoute = async ({ agent, config }, node, text, signal) => {
11960
12116
  const cfg = resolveConfig(config);
11961
12117
  const labels = (node.routes ?? []).map((r) => r.label);
11962
- const call = {
11963
- system: PIPELINE_ROUTER_SYSTEM,
11964
- prompt: renderPipelineRoutePrompt(node, text),
11965
- // 0 = no cap (the host turned it off, or the stage thinks).
11966
- ...cfg.budgets.replanner > 0 ? { maxOutputTokens: cfg.budgets.replanner } : {},
11967
- temperature: cfg.temperature,
11968
- abortSignal: signal,
11969
- timeoutMs: cfg.chatTimeoutMs
12118
+ const window = cfg.compaction.contextWindowTokens;
12119
+ const call = () => {
12120
+ const cap2 = stageOutputCap(config, "replanner", window).tokens;
12121
+ return {
12122
+ system: PIPELINE_ROUTER_SYSTEM,
12123
+ prompt: renderPipelineRoutePrompt(node, text),
12124
+ // No cap: the host turned it off, or the stage thinks.
12125
+ ...cap2 ? { maxOutputTokens: cap2 } : {},
12126
+ temperature: cfg.temperature,
12127
+ abortSignal: signal,
12128
+ timeoutMs: cfg.chatTimeoutMs
12129
+ };
11970
12130
  };
11971
12131
  let wasted = normalizeUsage();
11972
- try {
11973
- const schema = import_zod6.z.object({
11974
- route: import_zod6.z.enum(labels).describe("The label of the chosen route")
11975
- });
11976
- const r = await generateStructured(agent.models.planner, schema, call);
11977
- return { route: matchPipelineRoute(node, r.object), usage: normalizeUsage(r.usage) };
11978
- } catch (err) {
11979
- if (signal.aborted) throw aborted();
11980
- wasted = usageOfError(err);
12132
+ const schema = import_zod6.z.object({
12133
+ route: import_zod6.z.enum(labels).describe("The label of the chosen route")
12134
+ });
12135
+ for (let attempt = 0; attempt < 2; attempt += 1) {
12136
+ try {
12137
+ const r = await generateStructured(agent.models.planner, schema, call());
12138
+ return {
12139
+ route: matchPipelineRoute(node, r.object),
12140
+ usage: addUsage(wasted, normalizeUsage(r.usage))
12141
+ };
12142
+ } catch (err) {
12143
+ if (signal.aborted) throw aborted2();
12144
+ const spent = usageOfError(err);
12145
+ wasted = addUsage(wasted, spent);
12146
+ const finishReason = import_ai15.NoObjectGeneratedError.isInstance(err) ? err.finishReason : void 0;
12147
+ if (!observeReasoning(config, "replanner", window, finishReason, spent.reasoningTokens)) break;
12148
+ }
11981
12149
  }
11982
12150
  try {
11983
- const r = await generate(agent.models.planner, call);
12151
+ const r = await generate(agent.models.planner, call());
11984
12152
  return {
11985
12153
  route: matchPipelineRoute(node, r.text),
11986
12154
  usage: addUsage(wasted, normalizeUsage(r.usage))
11987
12155
  };
11988
12156
  } catch {
11989
- if (signal.aborted) throw aborted();
12157
+ if (signal.aborted) throw aborted2();
11990
12158
  return { usage: wasted };
11991
12159
  }
11992
12160
  };
@@ -11999,7 +12167,7 @@ var pickRouteWithDecisionModel = async ({ agent, config }, node, text, signal, e
11999
12167
  try {
12000
12168
  outcome = await askDecisionModel(model, question, config.decision, signal);
12001
12169
  } catch (err) {
12002
- if (signal.aborted) throw aborted();
12170
+ if (signal.aborted) throw aborted2();
12003
12171
  throw err;
12004
12172
  }
12005
12173
  const usage = decisionUsageOf(outcome);
@@ -12056,7 +12224,7 @@ var createPipeline = (definition, options) => {
12056
12224
  ctx.emit(event);
12057
12225
  }
12058
12226
  });
12059
- if (result.stopped || ctx.signal.aborted) throw aborted();
12227
+ if (result.stopped || ctx.signal.aborted) throw aborted2();
12060
12228
  if (failure !== void 0) throw new Error(failure);
12061
12229
  if (!node.routes?.length) return { text: result.final, usage: result.usage };
12062
12230
  const picked = await pickPipelineRoute(node, result.final, {
@@ -12116,7 +12284,7 @@ var nodeResolver = (options) => async (node) => {
12116
12284
  };
12117
12285
 
12118
12286
  // src/subagent/tool.ts
12119
- var import_ai15 = require("ai");
12287
+ var import_ai16 = require("ai");
12120
12288
  init_util();
12121
12289
  init_approval();
12122
12290
  init_wrap();
@@ -12291,7 +12459,7 @@ var createSubagentTool = (opts) => {
12291
12459
  Object.entries(opts.tools ?? {}).map(async ([name, t2]) => ({
12292
12460
  name,
12293
12461
  description: typeof t2.description === "string" ? t2.description : "",
12294
- inputSchema: toCloneable(await (0, import_ai15.asSchema)(t2.inputSchema).jsonSchema),
12462
+ inputSchema: toCloneable(await (0, import_ai16.asSchema)(t2.inputSchema).jsonSchema),
12295
12463
  readOnly: isReadOnlyTool(t2)
12296
12464
  }))
12297
12465
  );
@@ -12376,9 +12544,9 @@ var createSubagentTool = (opts) => {
12376
12544
 
12377
12545
  Optional \`profile\` (omit it for the default):
12378
12546
  ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : opts.description;
12379
- const t = (0, import_ai15.tool)({
12547
+ const t = (0, import_ai16.tool)({
12380
12548
  description,
12381
- inputSchema: (0, import_ai15.jsonSchema)({
12549
+ inputSchema: (0, import_ai16.jsonSchema)({
12382
12550
  type: "object",
12383
12551
  properties: {
12384
12552
  task: {
@@ -12495,7 +12663,7 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
12495
12663
  };
12496
12664
 
12497
12665
  // src/subagent/worker.ts
12498
- var import_ai16 = require("ai");
12666
+ var import_ai17 = require("ai");
12499
12667
 
12500
12668
  // src/secrets/store.ts
12501
12669
  init_notices();
@@ -12653,9 +12821,9 @@ var serveSubagentWorker = (opts = {}) => {
12653
12821
  const caller = createWaitClock();
12654
12822
  let callerResume;
12655
12823
  const proxy = (spec) => {
12656
- const t = (0, import_ai16.dynamicTool)({
12824
+ const t = (0, import_ai17.dynamicTool)({
12657
12825
  description: spec.description,
12658
- inputSchema: (0, import_ai16.jsonSchema)(spec.inputSchema),
12826
+ inputSchema: (0, import_ai17.jsonSchema)(spec.inputSchema),
12659
12827
  execute: (input, options) => new Promise((resolve, reject) => {
12660
12828
  const callId = `call-${callSeq += 1}`;
12661
12829
  const signal = options?.abortSignal;
@@ -13031,6 +13199,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
13031
13199
  MemoryRunStore,
13032
13200
  MemorySkillStore,
13033
13201
  MemoryStore,
13202
+ NO_ATTACHMENT_NOTE,
13034
13203
  PIPELINE_LIMITS,
13035
13204
  PIPELINE_ROUTER_SYSTEM,
13036
13205
  PipelineNodeError,
@@ -13225,6 +13394,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
13225
13394
  sniffMediaType,
13226
13395
  splitBlocker,
13227
13396
  stageOutputCap,
13397
+ stageReasons,
13228
13398
  stream,
13229
13399
  supportsImages,
13230
13400
  supportsNativeTools,