@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.js CHANGED
@@ -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 historyBlock = (history) => {
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}: ${clip(m.content, 400)}`);
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 you can answer completely from the STATE and general knowledge without any tool \u2014 then put the answer itself in "thought".
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
- - For a real goal: "reply" is one short sentence; "plan" is 1\u20136 DISTINCT, self-contained steps.
1308
- - 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".
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
- If a SKILLS list is present, list the names of the skills that apply to this goal in "skills" (or leave it empty).`;
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,6 +1378,13 @@ 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 ? `
@@ -1366,13 +1392,13 @@ ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("SKILLS", ct
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
1399
  - ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + 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:
@@ -4113,6 +4145,7 @@ var imageRefusal = (ctx, err, model) => {
4113
4145
  return unsupportedAttachment(modelLabel(model), kind, detail && `the provider said: ${detail}`);
4114
4146
  };
4115
4147
  var systemFor = (ctx, base) => withSystem(base, ctx.raw.systemPrompt);
4148
+ var aborted = (ctx) => ctx.signal?.aborted === true;
4116
4149
  var stageCall = (ctx, stage, baseSystem) => {
4117
4150
  const withMcp = ctx.mcpInstructions && (stage === "planner" || stage === "executor") ? `${baseSystem}
4118
4151
 
@@ -4124,23 +4157,44 @@ ${ctx.mcpInstructions}` : baseSystem;
4124
4157
  cachingProviderOptions(caching, ctx.config.clientName, stage),
4125
4158
  thinking.providerOptions
4126
4159
  );
4160
+ const cap = stageReasons(ctx.raw, stage) ? stageOutputCap(ctx.raw, stage, capWindow(ctx, stage)).tokens ?? 0 : ctx.config.budgets[stage];
4127
4161
  return {
4128
4162
  system: cachedInstructions(system, caching),
4129
4163
  ...thinking.reasoning ? { reasoning: thinking.reasoning } : {},
4130
4164
  ...providerOptions ? { providerOptions } : {},
4131
- ...ctx.config.budgets[stage] > 0 ? { maxOutputTokens: ctx.config.budgets[stage] } : {}
4165
+ ...cap > 0 ? { maxOutputTokens: cap } : {}
4132
4166
  };
4133
4167
  };
4134
- var capNotice = (ctx, stage, finishReason) => outputCapNotice(
4135
- ctx.raw,
4136
- stage,
4137
- (stage === "executor" ? ctx.executorWindowTokens : void 0) ?? ctx.config.compaction.contextWindowTokens,
4138
- finishReason
4139
- );
4168
+ var capWindow = (ctx, stage) => (stage === "executor" ? ctx.executorWindowTokens : void 0) ?? ctx.config.compaction.contextWindowTokens;
4169
+ var cutWhileReasoning = (ctx, stage, finishReason, usage) => observeReasoning(ctx.raw, stage, capWindow(ctx, stage), finishReason, usage?.reasoningTokens);
4170
+ var withReasoningRoom = async (ctx, stage, phase, run, onWasted) => {
4171
+ const again = (why, spent2) => {
4172
+ onWasted(spent2);
4173
+ 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)`;
4174
+ ctx.log.warn(message);
4175
+ ctx.emit({ type: "retry", phase, attempt: 1, error: message });
4176
+ return run();
4177
+ };
4178
+ let first;
4179
+ try {
4180
+ first = await run();
4181
+ } catch (err) {
4182
+ if (aborted(ctx) || !NoObjectGeneratedError.isInstance(err)) throw err;
4183
+ withCapHint(ctx, stage, err);
4184
+ const spent2 = usageOfError(err);
4185
+ if (!cutWhileReasoning(ctx, stage, err.finishReason, spent2)) throw err;
4186
+ return again(err.message, spent2);
4187
+ }
4188
+ const spent = normalizeUsage(first.usage);
4189
+ const notice = capNotice(ctx, stage, first.finishReason);
4190
+ if (!cutWhileReasoning(ctx, stage, first.finishReason, spent)) return first;
4191
+ return again(notice ?? `[${stage}] the model's output was cut off`, spent);
4192
+ };
4193
+ var capNotice = (ctx, stage, finishReason) => outputCapNotice(ctx.raw, stage, capWindow(ctx, stage), finishReason);
4140
4194
  var withCapHint = (ctx, stage, err) => {
4141
4195
  if (NoObjectGeneratedError.isInstance(err)) {
4142
4196
  const notice = capNotice(ctx, stage, err.finishReason);
4143
- if (notice) err.message = `${err.message} - ${notice}`;
4197
+ if (notice && !err.message.includes(notice)) err.message = `${err.message} - ${notice}`;
4144
4198
  }
4145
4199
  return err;
4146
4200
  };
@@ -4369,14 +4423,14 @@ var shareSubagentBudget = (parent, running, settings) => {
4369
4423
  var createSpawnGate = (max) => {
4370
4424
  let active = 0;
4371
4425
  const queue = [];
4372
- const aborted2 = () => {
4426
+ const aborted3 = () => {
4373
4427
  const e = new Error("Aborted");
4374
4428
  e.name = "AbortError";
4375
4429
  return e;
4376
4430
  };
4377
4431
  return (signal) => new Promise((resolve, reject) => {
4378
4432
  if (signal?.aborted) {
4379
- reject(aborted2());
4433
+ reject(aborted3());
4380
4434
  return;
4381
4435
  }
4382
4436
  const grant = () => {
@@ -4397,7 +4451,7 @@ var createSpawnGate = (max) => {
4397
4451
  if (i >= 0) {
4398
4452
  queue.splice(i, 1);
4399
4453
  }
4400
- reject(aborted2());
4454
+ reject(aborted3());
4401
4455
  }
4402
4456
  if (active < max) {
4403
4457
  grant();
@@ -4486,6 +4540,7 @@ var executeStep = async (base, goal, step, index, total, done, attempt = {}) =>
4486
4540
  const active = ctx.activeSkills?.() ?? [];
4487
4541
  const parts = ctx.prompts.executor({
4488
4542
  goal,
4543
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
4489
4544
  state,
4490
4545
  step: step.description,
4491
4546
  index,
@@ -4559,6 +4614,7 @@ ${renderEarlierAttempts(attempt.earlier)}` : parts.prompt;
4559
4614
  ctx.log.debug("executor text:", loop.text);
4560
4615
  const cut = capNotice(ctx, "executor", loop.finishReason);
4561
4616
  if (cut) ctx.log.warn(cut);
4617
+ cutWhileReasoning(ctx, "executor", loop.finishReason, loop.usage);
4562
4618
  const { summary, blocked } = splitBlocker(loop.text);
4563
4619
  return {
4564
4620
  result: {
@@ -4718,7 +4774,11 @@ var TieredPlanStepSchema = PlanStepSchema.extend({
4718
4774
  complexity: z5.enum(["low", "medium", "high"]).optional()
4719
4775
  });
4720
4776
  var PlanSchema = z5.object({
4721
- /** One short sentence. For a greeting/small talk, holds the answer and steps is empty. */
4777
+ /**
4778
+ * The planner's private one-sentence note. Never shown as an answer: with an empty `steps` (a
4779
+ * greeting, small talk, a question that needs no tool) the answer is written by the answering
4780
+ * stage.
4781
+ */
4722
4782
  thought: z5.string(),
4723
4783
  steps: z5.array(PlanStepSchema),
4724
4784
  /** Names of the configured skills that apply to this goal. */
@@ -4755,6 +4815,7 @@ ${nudge}` : goal;
4755
4815
  toolCatalog: ctx.toolCatalog,
4756
4816
  mode,
4757
4817
  history: ctx.history,
4818
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
4758
4819
  skills: skillIndex,
4759
4820
  searchMode: ctx.strategy === "search",
4760
4821
  ...ctx.sandbox ? { sandbox: ctx.sandbox.planner } : {},
@@ -4784,15 +4845,23 @@ ${nudge}` : goal;
4784
4845
  let wasted = normalizeUsage();
4785
4846
  if (ctx.plannerMode === "native") {
4786
4847
  try {
4787
- const result2 = await generateStructured(
4788
- ctx.plannerModel,
4789
- ctx.tiers ? TieredPlanSchema : PlanSchema,
4790
- commonFor("native")
4848
+ const result2 = await withReasoningRoom(
4849
+ ctx,
4850
+ "planner",
4851
+ "plan",
4852
+ () => generateStructured(
4853
+ ctx.plannerModel,
4854
+ ctx.tiers ? TieredPlanSchema : PlanSchema,
4855
+ commonFor("native")
4856
+ ),
4857
+ (spent) => {
4858
+ wasted = addUsage(wasted, spent);
4859
+ }
4791
4860
  );
4792
4861
  ctx.log.debug("planner (native):", result2.object);
4793
4862
  return {
4794
4863
  plan: { thought: result2.object.thought, steps: toSteps(result2.object.steps, cap) },
4795
- usage: normalizeUsage(result2.usage),
4864
+ usage: addUsage(wasted, normalizeUsage(result2.usage)),
4796
4865
  skills: validSkills(result2.object.skills)
4797
4866
  };
4798
4867
  } catch (err) {
@@ -4801,16 +4870,26 @@ ${nudge}` : goal;
4801
4870
  if (refused) throw refused;
4802
4871
  const overflow = contextOverflowOf(err, ctx.plannerModel);
4803
4872
  if (overflow) throw overflow;
4804
- wasted = usageOfError(err);
4873
+ wasted = addUsage(wasted, usageOfError(err));
4805
4874
  const why = asMessage(withCapHint(ctx, "planner", err));
4806
4875
  ctx.log.warn("planner: native structured output failed, salvaging:", why);
4807
4876
  ctx.emit({ type: "retry", phase: "plan", attempt: 1, error: why });
4808
4877
  }
4809
4878
  }
4810
- const result = await generate(ctx.plannerModel, commonFor("prompted")).catch((err) => {
4879
+ const result = await withReasoningRoom(
4880
+ ctx,
4881
+ "planner",
4882
+ "plan",
4883
+ () => generate(ctx.plannerModel, commonFor("prompted")),
4884
+ (spent) => {
4885
+ wasted = addUsage(wasted, spent);
4886
+ }
4887
+ ).catch((err) => {
4811
4888
  throw imageRefusal(ctx, err, ctx.plannerModel) ?? contextOverflowOf(err, ctx.plannerModel) ?? err;
4812
4889
  });
4813
4890
  const parsed = parsePlannerResponse(result.text);
4891
+ const cut = result.finishReason === "length";
4892
+ 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
4893
  ctx.log.debug("planner (prompted) raw:", result.text);
4815
4894
  ctx.log.debug("planner (prompted) parsed:", parsed);
4816
4895
  return {
@@ -4825,7 +4904,8 @@ ${nudge}` : goal;
4825
4904
  )
4826
4905
  },
4827
4906
  usage: addUsage(wasted, normalizeUsage(result.usage)),
4828
- skills: validSkills(parsed.skills)
4907
+ skills: validSkills(parsed.skills),
4908
+ ...failed ? { failed } : {}
4829
4909
  };
4830
4910
  };
4831
4911
  var asMessage = (err) => err instanceof Error ? err.message : String(err);
@@ -5136,23 +5216,39 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
5136
5216
  let wasted = normalizeUsage();
5137
5217
  if (ctx.plannerMode === "native") {
5138
5218
  try {
5139
- const result = await generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native"));
5219
+ const result = await withReasoningRoom(
5220
+ ctx,
5221
+ "replanner",
5222
+ "replan",
5223
+ () => generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native")),
5224
+ (spent) => {
5225
+ wasted = addUsage(wasted, spent);
5226
+ }
5227
+ );
5140
5228
  return {
5141
5229
  decision: result.object.decision,
5142
5230
  reason: result.object.reason,
5143
5231
  plan: result.object.plan ?? [],
5144
- usage: normalizeUsage(result.usage)
5232
+ usage: addUsage(wasted, normalizeUsage(result.usage))
5145
5233
  };
5146
5234
  } catch (err) {
5147
5235
  if (ctx.signal?.aborted) throw err;
5148
- wasted = usageOfError(err);
5236
+ wasted = addUsage(wasted, usageOfError(err));
5149
5237
  const why = asMessage2(withCapHint(ctx, "replanner", err));
5150
5238
  ctx.log.warn("replanner: native structured output failed, salvaging:", why);
5151
5239
  ctx.emit({ type: "retry", phase: "replan", attempt: 1, error: why });
5152
5240
  }
5153
5241
  }
5154
5242
  try {
5155
- const result = await generate(ctx.plannerModel, commonFor("prompted"));
5243
+ const result = await withReasoningRoom(
5244
+ ctx,
5245
+ "replanner",
5246
+ "replan",
5247
+ () => generate(ctx.plannerModel, commonFor("prompted")),
5248
+ (spent) => {
5249
+ wasted = addUsage(wasted, spent);
5250
+ }
5251
+ );
5156
5252
  const parsed = parseReplannerResponse(result.text);
5157
5253
  return {
5158
5254
  decision: parsed.decision,
@@ -5211,7 +5307,7 @@ var decideReplanWithDecisionModel = async (ctx, goal, done, remaining, onUsage)
5211
5307
  var asMessage2 = (err) => err instanceof Error ? err.message : String(err);
5212
5308
 
5213
5309
  // src/agent/synthesizer.ts
5214
- var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
5310
+ var synthesizeAnswer = async (ctx, goal, done, findings = [], options = {}) => {
5215
5311
  const state = await ctx.state();
5216
5312
  const active = ctx.activeSkills?.() ?? [];
5217
5313
  const parts = ctx.prompts.synthesizer({
@@ -5221,8 +5317,32 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
5221
5317
  findings,
5222
5318
  activeSkills: active.length ? renderActiveSkills(active) : void 0,
5223
5319
  updates: ctx.userUpdates?.(),
5224
- ...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {}
5320
+ ...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {},
5321
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
5322
+ ...options.direct ? { direct: true, history: ctx.history } : {}
5225
5323
  });
5324
+ const first = await streamAnswer(ctx, parts);
5325
+ let last = first;
5326
+ let usage = first.usage;
5327
+ if (cutWhileReasoning(ctx, "synthesizer", first.finishReason, first.usage) && !first.shown) {
5328
+ 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`;
5329
+ ctx.log.warn(message);
5330
+ ctx.emit({ type: "retry", phase: "synthesize", attempt: 1, error: message });
5331
+ last = await streamAnswer(ctx, parts);
5332
+ usage = addUsage(usage, last.usage);
5333
+ } else if (first.cut) {
5334
+ ctx.log.warn(first.cut);
5335
+ }
5336
+ const text = parsePlainText(last.text);
5337
+ return {
5338
+ text,
5339
+ usage,
5340
+ ...text ? {} : {
5341
+ empty: last.cut ?? `[synthesizer] the model returned no text (finish reason: ${last.finishReason ?? "unknown"})`
5342
+ }
5343
+ };
5344
+ };
5345
+ var streamAnswer = async (ctx, parts) => {
5226
5346
  const result = stream(ctx.synthesizerModel, {
5227
5347
  ...stageCall(ctx, "synthesizer", parts.system),
5228
5348
  ...promptFor(ctx, parts.prompt),
@@ -5231,6 +5351,11 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
5231
5351
  timeoutMs: ctx.config.chatTimeoutMs
5232
5352
  });
5233
5353
  let text = "";
5354
+ let shown = false;
5355
+ const show = (delta) => {
5356
+ shown = true;
5357
+ ctx.emit({ type: "final.text-delta", delta });
5358
+ };
5234
5359
  let verdict = "unknown";
5235
5360
  for await (const part of result.fullStream) {
5236
5361
  if (part.type === "reasoning-delta") {
@@ -5251,19 +5376,19 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
5251
5376
  verdict = looksLikeJson(lead) ? "suppress" : "emit";
5252
5377
  if (verdict === "emit") {
5253
5378
  const visible = text.includes("</think>") ? text.slice(text.lastIndexOf("</think>") + "</think>".length).trimStart() : text;
5254
- if (visible) ctx.emit({ type: "final.text-delta", delta: visible });
5379
+ if (visible) show(visible);
5255
5380
  }
5256
5381
  } else if (verdict === "emit") {
5257
- ctx.emit({ type: "final.text-delta", delta });
5382
+ show(delta);
5258
5383
  }
5259
5384
  }
5260
5385
  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
5386
  return {
5265
- text: clean || "Done \u2014 the changes have been applied.",
5266
- usage: normalizeUsage(usage)
5387
+ text,
5388
+ usage: normalizeUsage(usage),
5389
+ finishReason,
5390
+ cut: capNotice(ctx, "synthesizer", finishReason),
5391
+ shown
5267
5392
  };
5268
5393
  };
5269
5394
 
@@ -6682,6 +6807,9 @@ ${renderActiveSkills(active)}`
6682
6807
  currentStep = step;
6683
6808
  },
6684
6809
  images: images.length ? images : void 0,
6810
+ // No file now, but one in an earlier turn: the model is told, or it answers about a
6811
+ // picture it only read the name of.
6812
+ ...!images.length && history.some((m) => m.role === "user" && hasAttachedMark(m.content)) ? { attachmentsNote: NO_ATTACHMENT_NOTE } : {},
6685
6813
  userUpdates: () => userUpdates.map((u) => u.text),
6686
6814
  ...port ? { takeRoundUpdates: () => deliver("round") } : {}
6687
6815
  };
@@ -6701,7 +6829,14 @@ ${renderActiveSkills(active)}`
6701
6829
  let planned = resumed ? { plan: resumed.plan, usage: emptyUsage(), skills: [] } : await createPlan(ctx, text);
6702
6830
  if (!resumed) bumpUsage(planned.usage, "plan");
6703
6831
  if (isAborted()) return stop();
6704
- if (planned.plan.steps.length === 0 && text.split(/\s+/).length > 2) {
6832
+ if (planned.failed) {
6833
+ log.warn("planner failed:", planned.failed);
6834
+ emit({ type: "error", phase: "run", error: planned.failed, code: "no-plan" });
6835
+ result.final = planned.failed;
6836
+ track.error = planned.failed;
6837
+ return result;
6838
+ }
6839
+ if (planned.plan.steps.length === 0 && plannerMode === "prompted" && catalog.length > 0 && text.split(/\s+/).length > 2) {
6705
6840
  log.warn(
6706
6841
  "planner returned no steps for a multi-word goal \u2014 retrying with a nudge. thought:",
6707
6842
  planned.plan.thought
@@ -6718,10 +6853,27 @@ ${renderActiveSkills(active)}`
6718
6853
  if (isAborted()) return stop();
6719
6854
  if (planned.plan.steps.length === 0) {
6720
6855
  log.info("no plan \u2014 answering directly (no tools will run)");
6721
- const answer = planned.plan.thought.trim() || "Tell me what you'd like to do.";
6722
- emit({ type: "final", text: answer });
6723
- await remember({ role: "assistant", content: answer });
6724
- result.final = answer;
6856
+ deliver("final");
6857
+ let direct;
6858
+ try {
6859
+ direct = await synthesizeAnswer(ctx, text, [], [], { direct: true });
6860
+ } catch (err) {
6861
+ if (isAborted()) return stop();
6862
+ throw err;
6863
+ }
6864
+ bumpUsage(direct.usage, "synthesize");
6865
+ if (isAborted()) return stop();
6866
+ if (!direct.text) {
6867
+ const message = direct.empty ?? "[synthesizer] the model returned no answer";
6868
+ log.warn(message);
6869
+ emit({ type: "error", phase: "run", error: message, code: "no-answer" });
6870
+ result.final = message;
6871
+ track.error = message;
6872
+ return result;
6873
+ }
6874
+ emit({ type: "final", text: direct.text });
6875
+ await remember({ role: "assistant", content: direct.text });
6876
+ result.final = direct.text;
6725
6877
  return result;
6726
6878
  }
6727
6879
  log.info(
@@ -7310,6 +7462,7 @@ ${renderActiveSkills(active)}`
7310
7462
  };
7311
7463
 
7312
7464
  // src/pipeline/index.ts
7465
+ import { NoObjectGeneratedError as NoObjectGeneratedError2 } from "ai";
7313
7466
  import { z as z6 } from "zod";
7314
7467
 
7315
7468
  // src/pipeline/engine.ts
@@ -8393,38 +8546,50 @@ ${t.text}`).join("\n\n");
8393
8546
  };
8394
8547
 
8395
8548
  // src/pipeline/index.ts
8396
- var aborted = () => new DOMException("Aborted", "AbortError");
8549
+ var aborted2 = () => new DOMException("Aborted", "AbortError");
8397
8550
  var pickRoute = async ({ agent, config }, node, text, signal) => {
8398
8551
  const cfg = resolveConfig(config);
8399
8552
  const labels = (node.routes ?? []).map((r) => r.label);
8400
- const call = {
8401
- system: PIPELINE_ROUTER_SYSTEM,
8402
- prompt: renderPipelineRoutePrompt(node, text),
8403
- // 0 = no cap (the host turned it off, or the stage thinks).
8404
- ...cfg.budgets.replanner > 0 ? { maxOutputTokens: cfg.budgets.replanner } : {},
8405
- temperature: cfg.temperature,
8406
- abortSignal: signal,
8407
- timeoutMs: cfg.chatTimeoutMs
8553
+ const window = cfg.compaction.contextWindowTokens;
8554
+ const call = () => {
8555
+ const cap = stageOutputCap(config, "replanner", window).tokens;
8556
+ return {
8557
+ system: PIPELINE_ROUTER_SYSTEM,
8558
+ prompt: renderPipelineRoutePrompt(node, text),
8559
+ // No cap: the host turned it off, or the stage thinks.
8560
+ ...cap ? { maxOutputTokens: cap } : {},
8561
+ temperature: cfg.temperature,
8562
+ abortSignal: signal,
8563
+ timeoutMs: cfg.chatTimeoutMs
8564
+ };
8408
8565
  };
8409
8566
  let wasted = normalizeUsage();
8410
- try {
8411
- const schema = z6.object({
8412
- route: z6.enum(labels).describe("The label of the chosen route")
8413
- });
8414
- const r = await generateStructured(agent.models.planner, schema, call);
8415
- return { route: matchPipelineRoute(node, r.object), usage: normalizeUsage(r.usage) };
8416
- } catch (err) {
8417
- if (signal.aborted) throw aborted();
8418
- wasted = usageOfError(err);
8567
+ const schema = z6.object({
8568
+ route: z6.enum(labels).describe("The label of the chosen route")
8569
+ });
8570
+ for (let attempt = 0; attempt < 2; attempt += 1) {
8571
+ try {
8572
+ const r = await generateStructured(agent.models.planner, schema, call());
8573
+ return {
8574
+ route: matchPipelineRoute(node, r.object),
8575
+ usage: addUsage(wasted, normalizeUsage(r.usage))
8576
+ };
8577
+ } catch (err) {
8578
+ if (signal.aborted) throw aborted2();
8579
+ const spent = usageOfError(err);
8580
+ wasted = addUsage(wasted, spent);
8581
+ const finishReason = NoObjectGeneratedError2.isInstance(err) ? err.finishReason : void 0;
8582
+ if (!observeReasoning(config, "replanner", window, finishReason, spent.reasoningTokens)) break;
8583
+ }
8419
8584
  }
8420
8585
  try {
8421
- const r = await generate(agent.models.planner, call);
8586
+ const r = await generate(agent.models.planner, call());
8422
8587
  return {
8423
8588
  route: matchPipelineRoute(node, r.text),
8424
8589
  usage: addUsage(wasted, normalizeUsage(r.usage))
8425
8590
  };
8426
8591
  } catch {
8427
- if (signal.aborted) throw aborted();
8592
+ if (signal.aborted) throw aborted2();
8428
8593
  return { usage: wasted };
8429
8594
  }
8430
8595
  };
@@ -8437,7 +8602,7 @@ var pickRouteWithDecisionModel = async ({ agent, config }, node, text, signal, e
8437
8602
  try {
8438
8603
  outcome = await askDecisionModel(model, question, config.decision, signal);
8439
8604
  } catch (err) {
8440
- if (signal.aborted) throw aborted();
8605
+ if (signal.aborted) throw aborted2();
8441
8606
  throw err;
8442
8607
  }
8443
8608
  const usage = decisionUsageOf(outcome);
@@ -8494,7 +8659,7 @@ var createPipeline = (definition, options) => {
8494
8659
  ctx.emit(event);
8495
8660
  }
8496
8661
  });
8497
- if (result.stopped || ctx.signal.aborted) throw aborted();
8662
+ if (result.stopped || ctx.signal.aborted) throw aborted2();
8498
8663
  if (failure !== void 0) throw new Error(failure);
8499
8664
  if (!node.routes?.length) return { text: result.final, usage: result.usage };
8500
8665
  const picked = await pickPipelineRoute(node, result.final, {
@@ -9319,6 +9484,7 @@ export {
9319
9484
  MemoryRunStore,
9320
9485
  MemorySkillStore,
9321
9486
  MemoryStore,
9487
+ NO_ATTACHMENT_NOTE,
9322
9488
  PIPELINE_LIMITS,
9323
9489
  PIPELINE_ROUTER_SYSTEM,
9324
9490
  PipelineNodeError,
@@ -9513,6 +9679,7 @@ export {
9513
9679
  sniffMediaType,
9514
9680
  splitBlocker,
9515
9681
  stageOutputCap,
9682
+ stageReasons,
9516
9683
  stream,
9517
9684
  supportsImages,
9518
9685
  supportsNativeTools,