blun-king-cli 9.1.647 → 9.1.648

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blun-king-cli",
3
- "version": "9.1.647",
3
+ "version": "9.1.648",
4
4
  "description": "BLUN CLI - your own AI agent with a Telegram channel. Get it done. With BLUN.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -29,7 +29,8 @@
29
29
  "node-pty": "1.2.0-beta.15"
30
30
  },
31
31
  "dependencies": {
32
- "quickjs-emscripten": "0.32.0"
32
+ "quickjs-emscripten": "0.32.0",
33
+ "smol-toml": "1.9.1"
33
34
  },
34
35
  "files": [
35
36
  "CHANGELOG.md",
@@ -49,7 +50,15 @@
49
50
  "versionierung/",
50
51
  "RELEASE-9.1.645.md",
51
52
  "RELEASE-9.1.646.md",
52
- "RELEASE-9.1.647.md"
53
+ "RELEASE-9.1.647.md",
54
+ "RELEASE-9.1.648.md",
55
+ "COMPACTION-STEER.md",
56
+ "GOAL-REPLY-TOOLS.md",
57
+ "ORIGINAL-HISTORY-BINDING.md",
58
+ "ORIGINAL-TOOL-OUTPUT.md",
59
+ "REQUEST-BODY-OBSERVATIONS.md",
60
+ "RETIRED-WORKER-DATA.md",
61
+ "RETIREMENT-COMPATIBILITY.md"
53
62
  ],
54
63
  "keywords": [
55
64
  "blun",
@@ -60183,9 +60183,10 @@ var BoundedChannelContextBuffer = class {
60183
60183
  * messages carry a hard silence instruction instead. DMs are always addressed.
60184
60184
  */
60185
60185
  function buildChannelTag(content, meta, addressed = true, inferAddressing = false) {
60186
+ const replyTo = meta.message_id === void 0 ? "" : ` und reply_to=${meta.message_id}`;
60186
60187
  const pairs = [["source", "telegram"]];
60187
60188
  for (const [key, value] of Object.entries(meta)) if (value !== void 0) pairs.push([key, String(value)]);
60188
- return `<channel ${pairs.map(([key, value]) => `${key}="${escapeAttr(value)}"`).join(" ")}>\n${content}\n</channel>\n${addressed ? `[REPLY-PFLICHT: Der Absender liest NUR Telegram. Sende deine Antwort mit dem telegram reply-Tool an chat_id=${meta.chat_id}. Sichtbarer Antworttext kann auch automatisch weitergeleitet werden; er ist kein privater Denkbereich.]` : inferAddressing ? `[SEMANTISCHE ADRESSIERUNG: Diese menschliche Gruppennachricht nennt dich nicht explizit. Entscheide anhand von Inhalt und Gesprächskontext, ob sie an dich gerichtet ist oder Arbeit von dir verlangt. Falls ja, antworte kurz mit dem telegram reply-Tool an chat_id=${meta.chat_id}. Falls nein, beende den Turn ohne Ausgabe; sende keine Bestätigung deiner Stille.]` : "[NUR MITLESEN — diese Nachricht ist NICHT an dich gerichtet (kein @King, keine Antwort an dich, sie spricht jemand anderen oder die Gruppe allgemein an). ANTWORTE NICHT: kein reply-Tool, keine Bestätigung, kein \"verstanden\", kein \"halte mich raus\" — beende den Turn einfach ohne Ausgabe. NUR wenn du ein echtes, konkretes Ergebnis oder einen echten Blocker beitragen kannst, antwortest du kurz. Im Zweifel: schweigen.]"}`;
60189
+ return `<channel ${pairs.map(([key, value]) => `${key}="${escapeAttr(value)}"`).join(" ")}>\n${content}\n</channel>\n${addressed ? `[REPLY-PFLICHT: Der Absender liest NUR Telegram. Sende deine Antwort mit dem telegram reply-Tool an chat_id=${meta.chat_id}${replyTo}. Sichtbarer Antworttext kann auch automatisch weitergeleitet werden; er ist kein privater Denkbereich.]` : inferAddressing ? `[SEMANTISCHE ADRESSIERUNG: Diese menschliche Gruppennachricht nennt dich nicht explizit. Entscheide anhand von Inhalt und Gesprächskontext, ob sie an dich gerichtet ist oder Arbeit von dir verlangt. Falls ja, antworte kurz mit dem telegram reply-Tool an chat_id=${meta.chat_id}${replyTo}. Falls nein, beende den Turn ohne Ausgabe; sende keine Bestätigung deiner Stille.]` : "[NUR MITLESEN — diese Nachricht ist NICHT an dich gerichtet (kein @King, keine Antwort an dich, sie spricht jemand anderen oder die Gruppe allgemein an). ANTWORTE NICHT: kein reply-Tool, keine Bestätigung, kein \"verstanden\", kein \"halte mich raus\" — beende den Turn einfach ohne Ausgabe. NUR wenn du ein echtes, konkretes Ergebnis oder einen echten Blocker beitragen kannst, antwortest du kurz. Im Zweifel: schweigen.]"}`;
60189
60190
  }
60190
60191
  /**
60191
60192
  * Sent once as the head of the first prompt of every bridged session —
@@ -60209,7 +60210,7 @@ function buildPreamble() {
60209
60210
  "user=\"...\" ts=\"...\">. Always pass chat_id back to the reply tool. If the tag has an",
60210
60211
  "image_path attribute, read that file — it is a photo the sender attached. If the tag",
60211
60212
  "has attachment_file_id, call download_attachment with that file_id, then read the",
60212
- "returned path. Use reply_to (a message_id) only when quoting an earlier message.",
60213
+ "returned path. When answering, use the chat_id and set reply_to to the message_id supplied by the bridge when present.",
60213
60214
  "Use edit_message for interim progress updates and finish long tasks with a fresh",
60214
60215
  "reply. Do not add a reaction or acknowledgement just to announce inactivity.",
60215
60216
  "",
@@ -73105,13 +73105,13 @@ function botToken() {
73105
73105
  return token;
73106
73106
  }
73107
73107
  /** Append one history entry (adds ts) to a .jsonl file. Never throws. */
73108
- function appendJsonl(file, entry) {
73108
+ function appendJsonl(file, entry, flush = false) {
73109
73109
  try {
73110
73110
  ensureStateDir();
73111
73111
  appendFileSync(file, `${JSON.stringify({
73112
73112
  ts: (/* @__PURE__ */ new Date()).toISOString(),
73113
73113
  ...entry
73114
- })}\n`);
73114
+ })}\n`, { flush });
73115
73115
  } catch (err) {
73116
73116
  process.stderr.write(`telegram channel: history append failed: ${String(err)}\n`);
73117
73117
  }
@@ -73503,7 +73503,7 @@ function isGroupNoiseReply(text) {
73503
73503
  const TOOL_DEFINITIONS = [
73504
73504
  {
73505
73505
  name: "reply",
73506
- description: "Reply on Telegram. Pass chat_id from the inbound message. Optionally pass reply_to (message_id) for threading, and files (absolute paths) to attach images or documents.",
73506
+ description: "Reply on Telegram. Use the inbound chat_id and pass its message_id as reply_to when present. Supply files as absolute paths to attach images or documents.",
73507
73507
  inputSchema: {
73508
73508
  type: "object",
73509
73509
  properties: {
@@ -73515,7 +73515,7 @@ const TOOL_DEFINITIONS = [
73515
73515
  },
73516
73516
  reply_to: {
73517
73517
  type: "string",
73518
- description: "Message ID to thread under. Use message_id from the inbound <channel> block."
73518
+ description: "Incoming message ID for correlation and, when enabled, Telegram threading."
73519
73519
  },
73520
73520
  files: {
73521
73521
  type: "array",
@@ -73629,7 +73629,7 @@ async function runTool(api, token, name, args) {
73629
73629
  */
73630
73630
  const DUPLICATE_WINDOW_MS = 3e5;
73631
73631
  const OUTBOX_TAIL_BYTES = 32768;
73632
- function isRecentDuplicate(chatId, text) {
73632
+ function isRecentDuplicate(chatId, text, replyTo) {
73633
73633
  try {
73634
73634
  const file = outboxLog();
73635
73635
  const size = statSync(file).size;
@@ -73643,6 +73643,7 @@ function isRecentDuplicate(chatId, text) {
73643
73643
  const entry = JSON.parse(line);
73644
73644
  if (entry.kind !== "reply" && entry.kind !== "reply-fallback") continue;
73645
73645
  if (String(entry.chat_id) !== String(chatId)) continue;
73646
+ if (replyTo !== void 0 && entry.reply_to_message_id !== replyTo) continue;
73646
73647
  if (entry.ts === void 0 || Date.parse(entry.ts) < cutoff) continue;
73647
73648
  if ((entry.text ?? "").trim() === wanted) return true;
73648
73649
  } catch {}
@@ -73654,7 +73655,11 @@ async function runReply(api, args) {
73654
73655
  const chatId = resolveAllowedChatId(args["chat_id"]);
73655
73656
  const text = typeof args["text"] === "string" ? args["text"].split("[[BLUN_TELEGRAM_SILENT]]").join("") : args["text"];
73656
73657
  if (typeof text === "string" && text.trim().length === 0) return "unterdrückt";
73657
- const replyTo = args["reply_to"] !== null && args["reply_to"] !== void 0 ? Number(args["reply_to"]) : void 0;
73658
+ const rawReplyTo = args["reply_to"];
73659
+ if (rawReplyTo != null && (typeof rawReplyTo !== "string" || !/^[1-9][0-9]{0,15}$/u.test(rawReplyTo) || !Number.isSafeInteger(Number(rawReplyTo)))) {
73660
+ throw new Error("invalid Telegram reply_to message ID");
73661
+ }
73662
+ const replyTo = rawReplyTo == null ? void 0 : Number(rawReplyTo);
73658
73663
  const files = args["files"] ?? [];
73659
73664
  const parseMode = args["format"] === "markdownv2" ? "MarkdownV2" : void 0;
73660
73665
  if (files.length === 0 && isGroupChat(chatId) && isGroupNoiseReply(text)) {
@@ -73666,7 +73671,7 @@ async function runReply(api, args) {
73666
73671
  });
73667
73672
  return "suppressed: group meta/acknowledgement noise — not sent (silence means silence)";
73668
73673
  }
73669
- if (files.length === 0 && isRecentDuplicate(chatId, text)) {
73674
+ if (files.length === 0 && isRecentDuplicate(chatId, text, replyTo)) {
73670
73675
  appendJsonl(outboxLog(), {
73671
73676
  direction: "out",
73672
73677
  kind: "reply-duplicate-suppressed",
@@ -73687,36 +73692,32 @@ async function runReply(api, args) {
73687
73692
  const replyMode = access.replyToMode ?? "first";
73688
73693
  const chunks = chunk(text, limit, mode);
73689
73694
  const sentIds = [];
73695
+ const receipt = { direction: "out", chat_id: chatId, reply_to_message_id: replyTo, message_ids: sentIds };
73696
+ const replyParameters = replyTo === void 0 ? void 0 : { message_id: replyTo, allow_sending_without_reply: true };
73690
73697
  try {
73691
73698
  for (let i = 0; i < chunks.length; i++) {
73692
73699
  const shouldReplyTo = replyTo !== void 0 && replyMode !== "off" && (replyMode === "all" || i === 0);
73693
73700
  const chunkText = chunks[i];
73694
73701
  if (chunkText === void 0) continue;
73695
73702
  const sent = await api.sendMessage(chatId, chunkText, {
73696
- ...shouldReplyTo ? { reply_parameters: { message_id: replyTo } } : {},
73703
+ ...shouldReplyTo ? { reply_parameters: replyParameters } : {},
73697
73704
  ...parseMode !== void 0 ? { parse_mode: parseMode } : {}
73698
73705
  });
73699
73706
  sentIds.push(sent.message_id);
73700
73707
  }
73708
+ for (const file of files) {
73709
+ const ext = extname(file).toLowerCase();
73710
+ const input = new import_out.InputFile(file);
73711
+ const opts = replyTo !== void 0 && replyMode !== "off" ? { reply_parameters: replyParameters } : void 0;
73712
+ const sent = PHOTO_EXTS.has(ext) ? await api.sendPhoto(chatId, input, opts) : await api.sendDocument(chatId, input, opts);
73713
+ sentIds.push(sent.message_id);
73714
+ }
73701
73715
  } catch (err) {
73716
+ if (sentIds.length > 0) appendJsonl(outboxLog(), { ...receipt, kind: "reply-partial" }, true);
73702
73717
  const msg = err instanceof Error ? err.message : String(err);
73703
- throw new Error(`reply failed after ${sentIds.length} of ${chunks.length} chunk(s) sent: ${msg}`);
73718
+ throw new Error(`reply failed after ${sentIds.length} of ${chunks.length + files.length} part(s) sent: ${msg}`);
73704
73719
  }
73705
- for (const file of files) {
73706
- const ext = extname(file).toLowerCase();
73707
- const input = new import_out.InputFile(file);
73708
- const opts = replyTo !== void 0 && replyMode !== "off" ? { reply_parameters: { message_id: replyTo } } : void 0;
73709
- const sent = PHOTO_EXTS.has(ext) ? await api.sendPhoto(chatId, input, opts) : await api.sendDocument(chatId, input, opts);
73710
- sentIds.push(sent.message_id);
73711
- }
73712
- appendJsonl(outboxLog(), {
73713
- direction: "out",
73714
- kind: "reply",
73715
- chat_id: chatId,
73716
- message_ids: sentIds,
73717
- text,
73718
- ...files.length > 0 ? { files } : {}
73719
- });
73720
+ appendJsonl(outboxLog(), { ...receipt, kind: "reply", text, ...files.length > 0 ? { files } : {} }, true);
73720
73721
  return sentIds.length === 1 ? `sent (id: ${sentIds[0]})` : `sent ${sentIds.length} parts (ids: ${sentIds.join(", ")})`;
73721
73722
  }
73722
73723
  async function runDownload(api, token, fileId) {
package/worker-host.mjs CHANGED
@@ -15454,6 +15454,7 @@ function peekTable(key, table, meta, type) {
15454
15454
  ];
15455
15455
  }
15456
15456
  function parse$6(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
15457
+ toml = toml.replace(/^\uFEFF/u, '');
15457
15458
  let res = {};
15458
15459
  let meta = {};
15459
15460
  let tbl = res;
@@ -265209,7 +265210,75 @@ const BLUN_LANGUAGE_REVIEW_TOOL_NAMES = new Set([
265209
265210
  const BLUN_LEAN_KEEP_RE = /(^|__|:)(reply|react|edit_message|download_attachment|memory_(?:status|settings_update|remember|list|threads_list|recall))$/i;
265210
265211
  /** Telegram writes require a real inbound user turn, never an internal nudge. */
265211
265212
  const BLUN_TELEGRAM_OUTBOUND_TOOL_RE = /^mcp__[^\s]*telegram[^\s]*__(?:reply|react|edit_message)$/i;
265212
- function blunToolsForOrigin(tools, origin) {
265213
+ const blunUserReplyAuthorities = new WeakMap();
265214
+ class UserReplyToolAuthority {
265215
+ #agent;
265216
+ #signal;
265217
+ #turnId;
265218
+ #goalId;
265219
+ #granted = false;
265220
+ #closed = false;
265221
+
265222
+ constructor(agent, signal) {
265223
+ if (!agent || typeof signal?.throwIfAborted !== 'function') throw new TypeError('INVALID_REPLY_TOOL_OWNER');
265224
+ this.#agent = agent;
265225
+ this.#signal = signal;
265226
+ }
265227
+
265228
+ #owns(flow, turnId) {
265229
+ return !this.#closed && !this.#signal.aborted && flow.agent === this.#agent &&
265230
+ Number.isSafeInteger(turnId) && turnId >= 0 && flow.currentId === turnId &&
265231
+ flow.activeTurn?.controller?.signal === this.#signal;
265232
+ }
265233
+
265234
+ #checkGoal(flow) {
265235
+ const goal = flow.agent.goal.getGoal().goal;
265236
+ const id = typeof goal?.goalId === 'string' ? goal.goalId : undefined;
265237
+ // A final answer may follow goal completion in the same turn. A different
265238
+ // goal must receive fresh user authority; the first created goal may adopt
265239
+ // authority already granted to its creating user turn.
265240
+ if (id !== undefined) {
265241
+ if (this.#goalId !== undefined && id !== this.#goalId) this.#granted = false;
265242
+ this.#goalId = id;
265243
+ }
265244
+ }
265245
+
265246
+ enter(flow, turnId, origin) {
265247
+ if (!this.#owns(flow, turnId)) return false;
265248
+ this.#checkGoal(flow);
265249
+ const firstEntry = this.#turnId !== turnId;
265250
+ this.#turnId = turnId;
265251
+ if (firstEntry && origin?.kind === 'user') this.#granted = true;
265252
+ return true;
265253
+ }
265254
+
265255
+ permits(flow, turnId, snapshot) {
265256
+ if (!this.#owns(flow, turnId) || this.#turnId !== turnId) return false;
265257
+ this.#checkGoal(flow);
265258
+ if (this.#granted) return true;
265259
+ const through = snapshot?.throughSequence;
265260
+ if (!Number.isSafeInteger(through) || through < 0) return false;
265261
+ return flow.matchingSteers(turnId).some(steer => Number.isSafeInteger(steer.sequence) &&
265262
+ steer.sequence >= 0 && steer.sequence <= through && steer.origin?.kind === 'user' &&
265263
+ (steer.targetTurnId === undefined || steer.targetTurnId === turnId));
265264
+ }
265265
+
265266
+ consumed(flow, turnId, steer) {
265267
+ if (!this.#owns(flow, turnId) || this.#turnId !== turnId) return;
265268
+ this.#checkGoal(flow);
265269
+ if (steer.origin?.kind === 'user' && (steer.targetTurnId === undefined || steer.targetTurnId === turnId)) {
265270
+ this.#granted = true;
265271
+ }
265272
+ }
265273
+
265274
+ dispose() {
265275
+ this.#closed = true;
265276
+ this.#granted = false;
265277
+ this.#agent = this.#signal = undefined;
265278
+ }
265279
+ }
265280
+ function blunToolsForOrigin(tools, origin, userReplyAllowed = false) {
265281
+ if (userReplyAllowed === true) return tools;
265213
265282
  if (origin.kind !== "system_trigger" && origin.kind !== "injection") return tools;
265214
265283
  return tools.filter((tool) => !BLUN_TELEGRAM_OUTBOUND_TOOL_RE.test(tool.name));
265215
265284
  }
@@ -265578,6 +265647,7 @@ cancel(turnId, reason) {
265578
265647
  continue;
265579
265648
  }
265580
265649
  this.agent.context.appendUserMessage(steer.input, steer.origin);
265650
+ blunUserReplyAuthorities.get(this)?.consumed(this, turnId, steer);
265581
265651
  this.agent.cron?.observeSteerConsumed(steer.origin, turnId);
265582
265652
  incorporated.push(steer);
265583
265653
  flushed = true;
@@ -265645,6 +265715,9 @@ cancel(turnId, reason) {
265645
265715
  * launch signal, so a superseding turn is never clobbered).
265646
265716
  */
265647
265717
  async turnWorker(firstTurnId, input, origin, signal, reportExecutionEnd = false) {
265718
+ const replyAuthority = new UserReplyToolAuthority(this.agent, signal);
265719
+ blunUserReplyAuthorities.get(this)?.dispose();
265720
+ blunUserReplyAuthorities.set(this, replyAuthority);
265648
265721
  let terminal;
265649
265722
  const finish = (result) => {
265650
265723
  terminal = result.event;
@@ -265670,7 +265743,9 @@ cancel(turnId, reason) {
265670
265743
  this.agent.cron?.observeWorkerFailed(origin);
265671
265744
  throw error;
265672
265745
  } finally {
265673
- if (ownsActiveTurn()) this.activeTurn = null;
265746
+ replyAuthority.dispose();
265747
+ if (blunUserReplyAuthorities.get(this) === replyAuthority) blunUserReplyAuthorities.delete(this);
265748
+ if (ownsActiveTurn()) this.activeTurn = null;
265674
265749
  if (reportExecutionEnd && terminal !== void 0) this.agent.emitEvent({
265675
265750
  ...terminal,
265676
265751
  type: "turn.execution.ended",
@@ -265990,6 +266065,7 @@ cancel(turnId, reason) {
265990
266065
  const personalMemoryRecall = await this.agent.injection.injectPersonalMemoryForTurn(turnId, input, origin, signal);
265991
266066
  await this.agent.injection.injectGoal();
265992
266067
  this.setActiveSteerAcceptance(turnId, true);
266068
+ blunUserReplyAuthorities.get(this)?.enter(this, turnId, origin);
265993
266069
  const turnNeedsThinking = blunTurnNeedsTools(blunThinkingIntentInput(input), origin);
265994
266070
  let toolInput = input;
265995
266071
  let taskToolsNeeded = turnNeedsThinking || blunTurnHasAttachment(input);
@@ -266012,7 +266088,7 @@ cancel(turnId, reason) {
266012
266088
  const selectedTools = [];
266013
266089
  this.refreshSelectedTools = (snapshot) => {
266014
266090
  if (snapshot.messages.length > 0) toolInput = snapshot.messages.flatMap((message) => message.content);
266015
- const eligibleTools = blunToolsForOrigin(this.agent.injection.filterPersonalMemoryToolsForTurn(turnId, input, origin, turnTools()), origin);
266091
+ const eligibleTools = blunToolsForOrigin(this.agent.injection.filterPersonalMemoryToolsForTurn(turnId, input, origin, turnTools()), origin, blunUserReplyAuthorities.get(this)?.permits(this, turnId, snapshot) === true);
266016
266092
  const intent = blunThinkingIntentInput(toolInput);
266017
266093
  taskToolsNeeded ||= blunTurnNeedsTools(intent, origin) || blunTurnHasAttachment(toolInput);
266018
266094
  const required = (0, import_turn_tool_performance_policy.mediaToolNamesForTurnText)(blunExtractText(toolInput));
@@ -270176,37 +270252,49 @@ var Agent$1 = class {
270176
270252
  const selectedAlias = this.config.model;
270177
270253
  const modelProvider = this.modelProvider;
270178
270254
  if (modelProvider === void 0) throw new BlunError(ErrorCodes.MODEL_NOT_CONFIGURED, "Provider not set");
270255
+ const turnId = this.turn.currentId;
270179
270256
  return new FallbackLLM(resolveModelFallbackCandidates(selectedAlias, modelProvider, (alias) => this.createKosongLLM(alias, thinkingEffort), this.allowModelFallback && !PINNED_MODEL_ALIASES.has(selectedAlias)), (alias) => {
270180
270257
  this.setActiveResponderModel(alias);
270181
270258
  }, async (_candidate, params, rebuildMessages) => {
270182
- const steers = this.turn.snapshotPendingSteers();
270183
- const requestTools = this.turn.refreshRequestTools(steers) ?? params.tools;
270184
- params = {
270185
- ...params,
270186
- tools: requestTools,
270187
- messages: await rebuildMessages()
270188
- };
270189
- let systemPrompt = this.effectiveSystemPrompt;
270190
- const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
270191
- messages: params.messages,
270192
- additionalMessages: steers.messages,
270193
- rebuildMessages,
270194
- systemPrompt,
270195
- rebuildSystemPrompt: () => systemPrompt = this.effectiveSystemPrompt,
270196
- tools: params.tools
270197
- });
270198
- const tools = params.tools.some((tool) => tool.name === "CompactConversation") && !this.fullCompaction.proactiveCompactionStatus({
270199
- messages: compacted ? await rebuildMessages() : params.messages,
270200
- additionalMessages: steers.messages,
270201
- systemPrompt,
270202
- tools: params.tools
270203
- }).eligible ? params.tools.filter((tool) => tool.name !== "CompactConversation") : params.tools;
270204
- this.turn.commitPendingSteers(steers);
270205
- return {
270206
- ...params,
270207
- systemPrompt,
270208
- tools
270209
- };
270259
+ for (;;) {
270260
+ params.signal.throwIfAborted();
270261
+ if (this.turn.currentId !== turnId) throw new Error("REQUEST_BOUNDARY_TURN_CHANGED");
270262
+ const steers = this.turn.snapshotPendingSteers(turnId);
270263
+ const requestTools = this.turn.refreshRequestTools(steers) ?? params.tools;
270264
+ params = {
270265
+ ...params,
270266
+ tools: requestTools,
270267
+ messages: await rebuildMessages()
270268
+ };
270269
+ let systemPrompt = this.effectiveSystemPrompt;
270270
+ const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
270271
+ messages: params.messages,
270272
+ additionalMessages: steers.messages,
270273
+ rebuildMessages,
270274
+ systemPrompt,
270275
+ rebuildSystemPrompt: () => systemPrompt = this.effectiveSystemPrompt,
270276
+ tools: params.tools
270277
+ });
270278
+ const messages = compacted ? await rebuildMessages() : params.messages;
270279
+ params.signal.throwIfAborted();
270280
+ if (this.turn.currentId !== turnId) throw new Error("REQUEST_BOUNDARY_TURN_CHANGED");
270281
+ if (this.turn.snapshotPendingSteers(turnId).throughSequence !== steers.throughSequence) {
270282
+ await new Promise(resolve => setImmediate(resolve));
270283
+ continue;
270284
+ }
270285
+ const tools = params.tools.some((tool) => tool.name === "CompactConversation") && !this.fullCompaction.proactiveCompactionStatus({
270286
+ messages,
270287
+ additionalMessages: steers.messages,
270288
+ systemPrompt,
270289
+ tools: params.tools
270290
+ }).eligible ? params.tools.filter((tool) => tool.name !== "CompactConversation") : params.tools;
270291
+ this.turn.commitPendingSteers(steers, turnId);
270292
+ return {
270293
+ ...params,
270294
+ systemPrompt,
270295
+ tools
270296
+ };
270297
+ }
270210
270298
  }, (candidate, _params, error) => {
270211
270299
  this.fullCompaction.observeContextOverflow(error, candidate.alias);
270212
270300
  });
@@ -300833,7 +300921,7 @@ async function readMcpJson(filePath, options = {}) {
300833
300921
  if (text.trim().length === 0) return {};
300834
300922
  let data;
300835
300923
  try {
300836
- data = JSON.parse(text);
300924
+ data = JSON.parse(text.replace(/^\uFEFF/u, ''));
300837
300925
  } catch (error) {
300838
300926
  throw new BlunError(ErrorCodes.CONFIG_INVALID, `Invalid JSON in ${filePath}: ${describeError(error)}`, { cause: error });
300839
300927
  }
@@ -303309,7 +303397,7 @@ async function readInstalled(blunHomeDir) {
303309
303397
  throw error;
303310
303398
  }
303311
303399
  try {
303312
- const parsed = JSON.parse(text);
303400
+ const parsed = JSON.parse(text.replace(/^\uFEFF/u, ''));
303313
303401
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.plugins)) throw new Error("installed.json is not a valid InstalledFile object");
303314
303402
  return parsed;
303315
303403
  } catch (error) {
@@ -350501,60 +350589,68 @@ async function t3458WithConfigLock(filePath, action, learning = false) {
350501
350589
  }
350502
350590
  }
350503
350591
  }
350592
+ function t3458KnownEndpoint(endpoint) {
350593
+ return endpoint === 'https://api.blun.ai/v1' || endpoint === 'https://api.blun.ai/coding/v1';
350594
+ }
350595
+ function t3458LimitEntry(value, endpoint, now = Date.now()) {
350596
+ if (value !== null && typeof value === 'object') {
350597
+ if (value.version !== 1 || t3458Learned(value.limit) === undefined ||
350598
+ !Number.isSafeInteger(value.observedAt) || value.observedAt <= 0 || value.observedAt > now ||
350599
+ now - value.observedAt >= 15 * 60 * 1000) return undefined;
350600
+ return { version: 1, limit: value.limit, observedAt: value.observedAt };
350601
+ }
350602
+ const limit = t3458Learned(value);
350603
+ if (limit === undefined || t3458KnownEndpoint(endpoint) && limit === 500000) return undefined;
350604
+ return { version: 0, limit, observedAt: 0 };
350605
+ }
350606
+ function t3458LatestEntry(left, right) {
350607
+ if (left === undefined) return right;
350608
+ if (right === undefined) return left;
350609
+ if (left.observedAt !== right.observedAt) return left.observedAt > right.observedAt ? left : right;
350610
+ return left.limit <= right.limit ? left : right;
350611
+ }
350504
350612
  function t3458Store(filePath, parseToml, stringifyToml, atomicWrite) {
350505
- return {
350506
- async load(key) {
350507
- try {
350508
- return t3458Learned(parseToml(await t3458Fs.readFile(filePath, 'utf8')).request_body_byte_limits?.[key]);
350509
- }
350510
- catch (error) {
350511
- if (error.code === 'ENOENT')
350512
- return undefined;
350513
- throw error;
350514
- }
350515
- },
350516
- async save(key, value) {
350517
- if (!/^[a-f0-9]{64}$/.test(key) || t3458Learned(value) === undefined)
350518
- return;
350519
- await t3458WithConfigLock(filePath, async () => {
350520
- let data;
350521
- try {
350522
- data = parseToml(await t3458Fs.readFile(filePath, 'utf8'));
350523
- }
350524
- catch (error) {
350525
- if (error.code !== 'ENOENT')
350526
- throw error;
350527
- data = {};
350528
- }
350529
- const table = data.request_body_byte_limits ?? {};
350530
- const previous = t3458Learned(table[key]);
350531
- data.request_body_byte_limits = { ...table, [key]: previous === undefined ? value : Math.min(previous, value) };
350532
- await atomicWrite(filePath, `${stringifyToml(data)}\n`);
350533
- }, true);
350534
- }
350535
- };
350613
+ return {
350614
+ async load(key) {
350615
+ try { return parseToml(await t3458Fs.readFile(filePath, 'utf8')).request_body_byte_limits?.[key]; }
350616
+ catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
350617
+ },
350618
+ async save(key, value) {
350619
+ const now = Date.now();
350620
+ const incoming = typeof value === 'number' ? t3458LimitEntry({ version: 1, limit: value, observedAt: now }, undefined, now) :
350621
+ t3458LimitEntry(value, undefined, now);
350622
+ if (!/^[a-f0-9]{64}$/.test(key) || incoming?.version !== 1) return;
350623
+ await t3458WithConfigLock(filePath, async () => {
350624
+ let data;
350625
+ try { data = parseToml(await t3458Fs.readFile(filePath, 'utf8')); }
350626
+ catch (error) { if (error.code !== 'ENOENT') throw error; data = {}; }
350627
+ const table = data.request_body_byte_limits ?? {};
350628
+ if (typeof table !== 'object' || table === null || Array.isArray(table)) throw new Error('INVALID_BYTE_LIMIT_TABLE');
350629
+ const previous = t3458LimitEntry(table[key], undefined, Date.now());
350630
+ data.request_body_byte_limits = { ...table, [key]: t3458LatestEntry(previous, incoming) };
350631
+ await atomicWrite(filePath, `${stringifyToml(data)}\n`);
350632
+ }, true);
350633
+ },
350634
+ };
350536
350635
  }
350537
350636
  async function t3458Measure(provider, params, options) {
350538
- const endpoint = t3458Endpoint(provider._baseUrl);
350539
- const key = t3458Key(provider._baseUrl);
350540
- const option = typeof provider._requestBodyByteLimit === 'function' ? provider._requestBodyByteLimit() : provider._requestBodyByteLimit;
350541
- const configured = t3458ValidLimit(options?.requestBodyBudget?.limitBytes) ?? t3458ValidLimit(option) ?? t3458ValidLimit(Number(process.env.BLUN_REQUEST_BODY_BYTE_LIMIT));
350542
- let persisted;
350543
- if (key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
350544
- try {
350545
- persisted = t3458Learned(await provider._requestBodyByteLimitStore.load(key));
350546
- }
350547
- catch { }
350548
- }
350549
- const learned = t3458Learned(provider._t3458ObservedLimit);
350550
- const observed = learned === undefined ? persisted : persisted === undefined ? learned : Math.min(learned, persisted);
350551
- const fallback = endpoint === 'https://api.blun.ai/coding/v1' ? 500000 : undefined;
350552
- const limit = configured === undefined ? observed ?? fallback : observed === undefined ? configured : Math.min(configured, observed);
350553
- const bytes = Buffer.byteLength(JSON.stringify(params), 'utf8');
350554
- options?.requestBodyBudget?.onMeasured?.(bytes, limit, endpoint);
350555
- if (!options?.isCompactionRequest && limit !== undefined && bytes >= limit)
350556
- throw t3458Pressure(bytes, limit, endpoint);
350557
- return { key, limit, bytes };
350637
+ const endpoint = t3458Endpoint(provider._baseUrl), key = t3458Key(provider._baseUrl);
350638
+ const option = typeof provider._requestBodyByteLimit === 'function' ? provider._requestBodyByteLimit() : provider._requestBodyByteLimit;
350639
+ const configured = t3458ValidLimit(options?.requestBodyBudget?.limitBytes) ?? t3458ValidLimit(option) ??
350640
+ t3458ValidLimit(Number(process.env.BLUN_REQUEST_BODY_BYTE_LIMIT));
350641
+ let saved;
350642
+ if (key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
350643
+ try { saved = await provider._requestBodyByteLimitStore.load(key); } catch { /* Best effort. */ }
350644
+ }
350645
+ const now = Date.now(), persisted = t3458LimitEntry(saved, endpoint, now);
350646
+ const runtimeValue = Object.hasOwn(provider, '_t3458ObservedLimitEntry') ? provider._t3458ObservedLimitEntry : provider._t3458ObservedLimit;
350647
+ const observed = t3458LatestEntry(t3458LimitEntry(runtimeValue, endpoint, now), persisted);
350648
+ const fallback = t3458KnownEndpoint(endpoint) ? 700000 : undefined;
350649
+ const limit = configured === undefined ? observed?.limit ?? fallback : observed === undefined ? configured : Math.min(configured, observed.limit);
350650
+ const bytes = Buffer.byteLength(JSON.stringify(params), 'utf8');
350651
+ options?.requestBodyBudget?.onMeasured?.(bytes, limit, endpoint);
350652
+ if (!options?.isCompactionRequest && limit !== undefined && bytes >= limit) throw t3458Pressure(bytes, limit, endpoint);
350653
+ return { key, limit, bytes };
350558
350654
  }
350559
350655
  function t3458Pressure(byteLength, limitBytes, endpoint) {
350560
350656
  const error = new ChatProviderError(`Request body ${byteLength} bytes reaches limit ${limitBytes} bytes.`);
@@ -350576,15 +350672,16 @@ function t3458Observed(error) {
350576
350672
  return match === null ? undefined : t3458Learned(Number(match[1]));
350577
350673
  }
350578
350674
  async function t3458Learn(provider, error, measured, options) {
350579
- const limit = t3458Observed(error);
350580
- if (limit === undefined)
350581
- return;
350582
- provider._t3458ObservedLimit = Math.min(t3458Learned(provider._t3458ObservedLimit) ?? Infinity, limit);
350583
- options?.requestBodyBudget?.onLimitObserved?.(limit);
350584
- if (measured.key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
350585
- try {
350586
- await provider._requestBodyByteLimitStore.save(measured.key, limit);
350587
- }
350588
- catch { }
350589
- }
350675
+ const limit = t3458Observed(error);
350676
+ if (limit === undefined) return;
350677
+ const now = Date.now(), incoming = { version: 1, limit, observedAt: now };
350678
+ const endpoint = t3458Endpoint(provider._baseUrl);
350679
+ const previous = Object.hasOwn(provider, '_t3458ObservedLimitEntry') ? provider._t3458ObservedLimitEntry : provider._t3458ObservedLimit;
350680
+ const entry = t3458LatestEntry(t3458LimitEntry(previous, endpoint, now), incoming);
350681
+ provider._t3458ObservedLimitEntry = entry;
350682
+ provider._t3458ObservedLimit = entry.limit;
350683
+ options?.requestBodyBudget?.onLimitObserved?.(limit);
350684
+ if (measured.key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
350685
+ try { await provider._requestBodyByteLimitStore.save(measured.key, incoming); } catch { /* Best effort. */ }
350686
+ }
350590
350687
  }