blun-king-cli 9.1.646 → 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.646",
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",
@@ -48,7 +49,16 @@
48
49
  "tool-liveness642/",
49
50
  "versionierung/",
50
51
  "RELEASE-9.1.645.md",
51
- "RELEASE-9.1.646.md"
52
+ "RELEASE-9.1.646.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"
52
62
  ],
53
63
  "keywords": [
54
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;
@@ -229527,23 +229528,9 @@ var FullCompaction = class {
229527
229528
  if (this.requiresShrinkableHistory && !this.hasShrinkableHistory(messages)) return false;
229528
229529
  return this.beginAutoCompaction(throwOnLimit);
229529
229530
  }
229530
- shouldCompactRequestBody(endpoint, bytes, limit) {
229531
- if (bytes >= limit)
229532
- return true;
229533
- const attempts = this.t3458PressureAttempts ??= new Map();
229534
- const key = endpoint + "\0" + String(limit);
229535
- if (bytes < limit * 0.75) {
229536
- attempts.delete(key);
229537
- return false;
229531
+ shouldCompactRequestBody(_endpoint, bytes, limit) {
229532
+ return bytes >= limit;
229538
229533
  }
229539
- if (this.isSessionCompactionStopped || !this.hasShrinkableHistory(this.agent.context.history))
229540
- return false;
229541
- const previous = attempts.get(key);
229542
- if (previous !== undefined && bytes < previous + Math.ceil(previous / 10))
229543
- return false;
229544
- attempts.set(key, bytes);
229545
- return true;
229546
- }
229547
229534
  hasShrinkableHistory(messages) {
229548
229535
  if (messages.some((message) => message.role === "tool" || message.role === "assistant" && ((message.toolCalls?.length ?? 0) > 0 || message.content.some(part => part.type !== "text" || part.text.trim().length > 0))))
229549
229536
  return true;
@@ -265223,7 +265210,75 @@ const BLUN_LANGUAGE_REVIEW_TOOL_NAMES = new Set([
265223
265210
  const BLUN_LEAN_KEEP_RE = /(^|__|:)(reply|react|edit_message|download_attachment|memory_(?:status|settings_update|remember|list|threads_list|recall))$/i;
265224
265211
  /** Telegram writes require a real inbound user turn, never an internal nudge. */
265225
265212
  const BLUN_TELEGRAM_OUTBOUND_TOOL_RE = /^mcp__[^\s]*telegram[^\s]*__(?:reply|react|edit_message)$/i;
265226
- 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;
265227
265282
  if (origin.kind !== "system_trigger" && origin.kind !== "injection") return tools;
265228
265283
  return tools.filter((tool) => !BLUN_TELEGRAM_OUTBOUND_TOOL_RE.test(tool.name));
265229
265284
  }
@@ -265592,6 +265647,7 @@ cancel(turnId, reason) {
265592
265647
  continue;
265593
265648
  }
265594
265649
  this.agent.context.appendUserMessage(steer.input, steer.origin);
265650
+ blunUserReplyAuthorities.get(this)?.consumed(this, turnId, steer);
265595
265651
  this.agent.cron?.observeSteerConsumed(steer.origin, turnId);
265596
265652
  incorporated.push(steer);
265597
265653
  flushed = true;
@@ -265659,6 +265715,9 @@ cancel(turnId, reason) {
265659
265715
  * launch signal, so a superseding turn is never clobbered).
265660
265716
  */
265661
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);
265662
265721
  let terminal;
265663
265722
  const finish = (result) => {
265664
265723
  terminal = result.event;
@@ -265684,7 +265743,9 @@ cancel(turnId, reason) {
265684
265743
  this.agent.cron?.observeWorkerFailed(origin);
265685
265744
  throw error;
265686
265745
  } finally {
265687
- if (ownsActiveTurn()) this.activeTurn = null;
265746
+ replyAuthority.dispose();
265747
+ if (blunUserReplyAuthorities.get(this) === replyAuthority) blunUserReplyAuthorities.delete(this);
265748
+ if (ownsActiveTurn()) this.activeTurn = null;
265688
265749
  if (reportExecutionEnd && terminal !== void 0) this.agent.emitEvent({
265689
265750
  ...terminal,
265690
265751
  type: "turn.execution.ended",
@@ -266004,6 +266065,7 @@ cancel(turnId, reason) {
266004
266065
  const personalMemoryRecall = await this.agent.injection.injectPersonalMemoryForTurn(turnId, input, origin, signal);
266005
266066
  await this.agent.injection.injectGoal();
266006
266067
  this.setActiveSteerAcceptance(turnId, true);
266068
+ blunUserReplyAuthorities.get(this)?.enter(this, turnId, origin);
266007
266069
  const turnNeedsThinking = blunTurnNeedsTools(blunThinkingIntentInput(input), origin);
266008
266070
  let toolInput = input;
266009
266071
  let taskToolsNeeded = turnNeedsThinking || blunTurnHasAttachment(input);
@@ -266026,7 +266088,7 @@ cancel(turnId, reason) {
266026
266088
  const selectedTools = [];
266027
266089
  this.refreshSelectedTools = (snapshot) => {
266028
266090
  if (snapshot.messages.length > 0) toolInput = snapshot.messages.flatMap((message) => message.content);
266029
- 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);
266030
266092
  const intent = blunThinkingIntentInput(toolInput);
266031
266093
  taskToolsNeeded ||= blunTurnNeedsTools(intent, origin) || blunTurnHasAttachment(toolInput);
266032
266094
  const required = (0, import_turn_tool_performance_policy.mediaToolNamesForTurnText)(blunExtractText(toolInput));
@@ -270190,37 +270252,49 @@ var Agent$1 = class {
270190
270252
  const selectedAlias = this.config.model;
270191
270253
  const modelProvider = this.modelProvider;
270192
270254
  if (modelProvider === void 0) throw new BlunError(ErrorCodes.MODEL_NOT_CONFIGURED, "Provider not set");
270255
+ const turnId = this.turn.currentId;
270193
270256
  return new FallbackLLM(resolveModelFallbackCandidates(selectedAlias, modelProvider, (alias) => this.createKosongLLM(alias, thinkingEffort), this.allowModelFallback && !PINNED_MODEL_ALIASES.has(selectedAlias)), (alias) => {
270194
270257
  this.setActiveResponderModel(alias);
270195
270258
  }, async (_candidate, params, rebuildMessages) => {
270196
- const steers = this.turn.snapshotPendingSteers();
270197
- const requestTools = this.turn.refreshRequestTools(steers) ?? params.tools;
270198
- params = {
270199
- ...params,
270200
- tools: requestTools,
270201
- messages: await rebuildMessages()
270202
- };
270203
- let systemPrompt = this.effectiveSystemPrompt;
270204
- const compacted = await this.fullCompaction.beforeStep(params.boundarySignal ?? params.signal, {
270205
- messages: params.messages,
270206
- additionalMessages: steers.messages,
270207
- rebuildMessages,
270208
- systemPrompt,
270209
- rebuildSystemPrompt: () => systemPrompt = this.effectiveSystemPrompt,
270210
- tools: params.tools
270211
- });
270212
- const tools = params.tools.some((tool) => tool.name === "CompactConversation") && !this.fullCompaction.proactiveCompactionStatus({
270213
- messages: compacted ? await rebuildMessages() : params.messages,
270214
- additionalMessages: steers.messages,
270215
- systemPrompt,
270216
- tools: params.tools
270217
- }).eligible ? params.tools.filter((tool) => tool.name !== "CompactConversation") : params.tools;
270218
- this.turn.commitPendingSteers(steers);
270219
- return {
270220
- ...params,
270221
- systemPrompt,
270222
- tools
270223
- };
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
+ }
270224
270298
  }, (candidate, _params, error) => {
270225
270299
  this.fullCompaction.observeContextOverflow(error, candidate.alias);
270226
270300
  });
@@ -300847,7 +300921,7 @@ async function readMcpJson(filePath, options = {}) {
300847
300921
  if (text.trim().length === 0) return {};
300848
300922
  let data;
300849
300923
  try {
300850
- data = JSON.parse(text);
300924
+ data = JSON.parse(text.replace(/^\uFEFF/u, ''));
300851
300925
  } catch (error) {
300852
300926
  throw new BlunError(ErrorCodes.CONFIG_INVALID, `Invalid JSON in ${filePath}: ${describeError(error)}`, { cause: error });
300853
300927
  }
@@ -303323,7 +303397,7 @@ async function readInstalled(blunHomeDir) {
303323
303397
  throw error;
303324
303398
  }
303325
303399
  try {
303326
- const parsed = JSON.parse(text);
303400
+ const parsed = JSON.parse(text.replace(/^\uFEFF/u, ''));
303327
303401
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.plugins)) throw new Error("installed.json is not a valid InstalledFile object");
303328
303402
  return parsed;
303329
303403
  } catch (error) {
@@ -350515,60 +350589,68 @@ async function t3458WithConfigLock(filePath, action, learning = false) {
350515
350589
  }
350516
350590
  }
350517
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
+ }
350518
350612
  function t3458Store(filePath, parseToml, stringifyToml, atomicWrite) {
350519
- return {
350520
- async load(key) {
350521
- try {
350522
- return t3458Learned(parseToml(await t3458Fs.readFile(filePath, 'utf8')).request_body_byte_limits?.[key]);
350523
- }
350524
- catch (error) {
350525
- if (error.code === 'ENOENT')
350526
- return undefined;
350527
- throw error;
350528
- }
350529
- },
350530
- async save(key, value) {
350531
- if (!/^[a-f0-9]{64}$/.test(key) || t3458Learned(value) === undefined)
350532
- return;
350533
- await t3458WithConfigLock(filePath, async () => {
350534
- let data;
350535
- try {
350536
- data = parseToml(await t3458Fs.readFile(filePath, 'utf8'));
350537
- }
350538
- catch (error) {
350539
- if (error.code !== 'ENOENT')
350540
- throw error;
350541
- data = {};
350542
- }
350543
- const table = data.request_body_byte_limits ?? {};
350544
- const previous = t3458Learned(table[key]);
350545
- data.request_body_byte_limits = { ...table, [key]: previous === undefined ? value : Math.min(previous, value) };
350546
- await atomicWrite(filePath, `${stringifyToml(data)}\n`);
350547
- }, true);
350548
- }
350549
- };
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
+ };
350550
350635
  }
350551
350636
  async function t3458Measure(provider, params, options) {
350552
- const endpoint = t3458Endpoint(provider._baseUrl);
350553
- const key = t3458Key(provider._baseUrl);
350554
- const option = typeof provider._requestBodyByteLimit === 'function' ? provider._requestBodyByteLimit() : provider._requestBodyByteLimit;
350555
- const configured = t3458ValidLimit(options?.requestBodyBudget?.limitBytes) ?? t3458ValidLimit(option) ?? t3458ValidLimit(Number(process.env.BLUN_REQUEST_BODY_BYTE_LIMIT));
350556
- let persisted;
350557
- if (key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
350558
- try {
350559
- persisted = t3458Learned(await provider._requestBodyByteLimitStore.load(key));
350560
- }
350561
- catch { }
350562
- }
350563
- const learned = t3458Learned(provider._t3458ObservedLimit);
350564
- const observed = learned === undefined ? persisted : persisted === undefined ? learned : Math.min(learned, persisted);
350565
- const fallback = endpoint === 'https://api.blun.ai/coding/v1' ? 500000 : undefined;
350566
- const limit = configured === undefined ? observed ?? fallback : observed === undefined ? configured : Math.min(configured, observed);
350567
- const bytes = Buffer.byteLength(JSON.stringify(params), 'utf8');
350568
- options?.requestBodyBudget?.onMeasured?.(bytes, limit, endpoint);
350569
- if (!options?.isCompactionRequest && limit !== undefined && bytes >= limit)
350570
- throw t3458Pressure(bytes, limit, endpoint);
350571
- 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 };
350572
350654
  }
350573
350655
  function t3458Pressure(byteLength, limitBytes, endpoint) {
350574
350656
  const error = new ChatProviderError(`Request body ${byteLength} bytes reaches limit ${limitBytes} bytes.`);
@@ -350590,15 +350672,16 @@ function t3458Observed(error) {
350590
350672
  return match === null ? undefined : t3458Learned(Number(match[1]));
350591
350673
  }
350592
350674
  async function t3458Learn(provider, error, measured, options) {
350593
- const limit = t3458Observed(error);
350594
- if (limit === undefined)
350595
- return;
350596
- provider._t3458ObservedLimit = Math.min(t3458Learned(provider._t3458ObservedLimit) ?? Infinity, limit);
350597
- options?.requestBodyBudget?.onLimitObserved?.(limit);
350598
- if (measured.key !== undefined && provider._requestBodyByteLimitStore !== undefined) {
350599
- try {
350600
- await provider._requestBodyByteLimitStore.save(measured.key, limit);
350601
- }
350602
- catch { }
350603
- }
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
+ }
350604
350687
  }