blun-king-cli 9.1.611 → 9.1.612

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/blun.mjs CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- // BLUN_BUILD_INPUT_SHA256:0533ca113dc07cc119988be5e76555dec986b6881903f8e2b537f5adf96cc2c5
2
+ // BLUN_BUILD_INPUT_SHA256:f9f2527561c5e5ec1afc53eef27313667c4d323a444532439e73a66865340f69
3
3
  import { fileURLToPath as __cjsShimFileURLToPath } from 'node:url';
4
4
  import { dirname as __cjsShimDirname } from 'node:path';
5
5
  const __filename = __cjsShimFileURLToPath(import.meta.url);
6
6
  const __dirname = __cjsShimDirname(__filename);
7
7
  import { createRequire } from "node:module";
8
- import crypto$1, { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
9
- import * as fs$16 from "node:fs";
8
+ import crypto$1, { createHash, createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
9
+ import * as fs$17 from "node:fs";
10
10
  import Kt, { accessSync, appendFileSync, chmodSync, closeSync, constants, copyFileSync, createReadStream, createWriteStream, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, opendirSync, promises, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
11
11
  import * as path$17 from "node:path";
12
12
  import path, { basename, dirname, extname, isAbsolute, join, normalize, parse, posix, relative, resolve, sep, win32 } from "node:path";
13
13
  import { Blob as Blob$1, Buffer as Buffer$1, File as File$1 } from "node:buffer";
14
- import ro, { access, appendFile, chmod, constants as constants$1, copyFile, cp, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
14
+ import fs, { access, appendFile, chmod, constants as constants$1, copyFile, cp, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
15
15
  import * as nodeOs from "node:os";
16
16
  import os, { arch, homedir, hostname, networkInterfaces, platform, release, tmpdir, type, userInfo } from "node:os";
17
17
  import { execFile, execFileSync, execSync, spawn, spawnSync } from "node:child_process";
@@ -2077,6 +2077,9 @@ var init_fetch_http_client = __esmMin((() => {
2077
2077
  const maxRetries = normalizeMaxRetries(requestOptions?.maxRetries);
2078
2078
  const requestBytes = exactBodyBytes(init.body);
2079
2079
  const requestBreakdown = pathname === "/chat/completions" && requestOptions?.onTransportAttempt !== void 0 && typeof init.body === "string" && requestBytes !== void 0 ? measureSerializedRequest(init.body, requestBytes) : void 0;
2080
+ if (pathname === "/chat/completions" && typeof init.body === "string") try {
2081
+ requestOptions?.onSerializedRequest?.(init.body);
2082
+ } catch {}
2080
2083
  let attempt = 0;
2081
2084
  while (true) {
2082
2085
  const headers = new Headers(init.headers);
@@ -2085,6 +2088,9 @@ var init_fetch_http_client = __esmMin((() => {
2085
2088
  const startedAt = performance.now();
2086
2089
  const startedAtMs = Date.now();
2087
2090
  try {
2091
+ try {
2092
+ requestOptions?.onRequestSent?.();
2093
+ } catch {}
2088
2094
  const response = await this.fetch(`${this.baseUrl}${pathname}`, {
2089
2095
  ...init,
2090
2096
  headers
@@ -2236,11 +2242,11 @@ var init_blun_files = __esmMin((() => {
2236
2242
  async uploadVideo(input, options) {
2237
2243
  let file;
2238
2244
  if (typeof input === "string") {
2239
- if (!fs$16.existsSync(input)) throw new ChatProviderError(`Video file not found: ${input}`);
2245
+ if (!fs$17.existsSync(input)) throw new ChatProviderError(`Video file not found: ${input}`);
2240
2246
  const filename = path$17.basename(input);
2241
2247
  const mimeType = guessMimeTypeFromExt(filename);
2242
2248
  if (mimeType === void 0 || !mimeType.startsWith("video/")) throw new ChatProviderError(`BlunFiles.uploadVideo: file extension does not indicate a video type: ${filename}`);
2243
- const data = await fs$16.promises.readFile(input);
2249
+ const data = await fs$17.promises.readFile(input);
2244
2250
  file = new File$1([new Blob$1([new Uint8Array(data)], { type: mimeType })], filename, { type: mimeType });
2245
2251
  } else {
2246
2252
  if (!input.mimeType.startsWith("video/")) throw new ChatProviderError(`Expected a video mime type, got ${input.mimeType}`);
@@ -2619,6 +2625,13 @@ function collectBlunVisionAttachments(messages) {
2619
2625
  }
2620
2626
  return attachments;
2621
2627
  }
2628
+ function estimateBlunRequestExtraBytes(tools, messages) {
2629
+ const attachments = collectBlunVisionAttachments(messages);
2630
+ return {
2631
+ toolsBytes: tools.length === 0 ? 0 : Buffer.byteLength(JSON.stringify({ tools: tools.map(convertTool) }), "utf8"),
2632
+ visionBytes: attachments.length === 0 ? 0 : Buffer.byteLength(JSON.stringify({ visionAttachments: attachments }), "utf8")
2633
+ };
2634
+ }
2622
2635
  function convertMessage(message) {
2623
2636
  let reasoningContent = "";
2624
2637
  const nonThinkParts = [];
@@ -2950,12 +2963,13 @@ var init_blun = __esmMin((() => {
2950
2963
  if (this._stream) createParams["stream_options"] = { include_usage: true };
2951
2964
  try {
2952
2965
  const client = this._createClient(options?.auth);
2953
- const requestOptions = options?.signal !== void 0 || options?.transportMaxRetries !== void 0 || options?.onTransportAttempt !== void 0 ? {
2966
+ const requestOptions = options?.signal !== void 0 || options?.transportMaxRetries !== void 0 || options?.onRequestSent !== void 0 || options?.onSerializedRequest !== void 0 || options?.onTransportAttempt !== void 0 ? {
2954
2967
  ...options.signal !== void 0 ? { signal: options.signal } : {},
2955
2968
  ...options.transportMaxRetries !== void 0 ? { maxRetries: options.transportMaxRetries } : {},
2969
+ ...options.onRequestSent !== void 0 ? { onRequestSent: options.onRequestSent } : {},
2970
+ ...options.onSerializedRequest !== void 0 ? { onSerializedRequest: options.onSerializedRequest } : {},
2956
2971
  ...options.onTransportAttempt !== void 0 ? { onTransportAttempt: options.onTransportAttempt } : {}
2957
2972
  } : void 0;
2958
- options?.onRequestSent?.();
2959
2973
  let response;
2960
2974
  try {
2961
2975
  response = await client.chat.completions.create(createParams, requestOptions);
@@ -2964,7 +2978,6 @@ var init_blun = __esmMin((() => {
2964
2978
  const cap = rejection instanceof APIContextOverflowError ? contextOverflowOutputCap(rejection, createParams["max_completion_tokens"]) : void 0;
2965
2979
  if (cap === void 0) throw rejection;
2966
2980
  options?.signal?.throwIfAborted();
2967
- options?.onRequestSent?.();
2968
2981
  response = await client.chat.completions.create({
2969
2982
  ...createParams,
2970
2983
  max_completion_tokens: cap
@@ -11897,7 +11910,7 @@ var require_clone$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
11897
11910
  //#endregion
11898
11911
  //#region ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js
11899
11912
  var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
11900
- var fs$15 = __require("fs");
11913
+ var fs$16 = __require("fs");
11901
11914
  var polyfills = require_polyfills();
11902
11915
  var legacy = require_legacy_streams();
11903
11916
  var clone = require_clone$1();
@@ -11926,36 +11939,36 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
11926
11939
  m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
11927
11940
  console.error(m);
11928
11941
  };
11929
- if (!fs$15[gracefulQueue]) {
11930
- publishQueue(fs$15, global[gracefulQueue] || []);
11931
- fs$15.close = (function(fs$close) {
11942
+ if (!fs$16[gracefulQueue]) {
11943
+ publishQueue(fs$16, global[gracefulQueue] || []);
11944
+ fs$16.close = (function(fs$close) {
11932
11945
  function close(fd, cb) {
11933
- return fs$close.call(fs$15, fd, function(err) {
11946
+ return fs$close.call(fs$16, fd, function(err) {
11934
11947
  if (!err) resetQueue();
11935
11948
  if (typeof cb === "function") cb.apply(this, arguments);
11936
11949
  });
11937
11950
  }
11938
11951
  Object.defineProperty(close, previousSymbol, { value: fs$close });
11939
11952
  return close;
11940
- })(fs$15.close);
11941
- fs$15.closeSync = (function(fs$closeSync) {
11953
+ })(fs$16.close);
11954
+ fs$16.closeSync = (function(fs$closeSync) {
11942
11955
  function closeSync(fd) {
11943
- fs$closeSync.apply(fs$15, arguments);
11956
+ fs$closeSync.apply(fs$16, arguments);
11944
11957
  resetQueue();
11945
11958
  }
11946
11959
  Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync });
11947
11960
  return closeSync;
11948
- })(fs$15.closeSync);
11961
+ })(fs$16.closeSync);
11949
11962
  if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) process.on("exit", function() {
11950
- debug(fs$15[gracefulQueue]);
11951
- __require("assert").equal(fs$15[gracefulQueue].length, 0);
11963
+ debug(fs$16[gracefulQueue]);
11964
+ __require("assert").equal(fs$16[gracefulQueue].length, 0);
11952
11965
  });
11953
11966
  }
11954
- if (!global[gracefulQueue]) publishQueue(global, fs$15[gracefulQueue]);
11955
- module.exports = patch(clone(fs$15));
11956
- if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$15.__patched) {
11957
- module.exports = patch(fs$15);
11958
- fs$15.__patched = true;
11967
+ if (!global[gracefulQueue]) publishQueue(global, fs$16[gracefulQueue]);
11968
+ module.exports = patch(clone(fs$16));
11969
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$16.__patched) {
11970
+ module.exports = patch(fs$16);
11971
+ fs$16.__patched = true;
11959
11972
  }
11960
11973
  function patch(fs) {
11961
11974
  polyfills(fs);
@@ -12210,23 +12223,23 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
12210
12223
  }
12211
12224
  function enqueue(elem) {
12212
12225
  debug("ENQUEUE", elem[0].name, elem[1]);
12213
- fs$15[gracefulQueue].push(elem);
12226
+ fs$16[gracefulQueue].push(elem);
12214
12227
  retry();
12215
12228
  }
12216
12229
  var retryTimer;
12217
12230
  function resetQueue() {
12218
12231
  var now = Date.now();
12219
- for (var i = 0; i < fs$15[gracefulQueue].length; ++i) if (fs$15[gracefulQueue][i].length > 2) {
12220
- fs$15[gracefulQueue][i][3] = now;
12221
- fs$15[gracefulQueue][i][4] = now;
12232
+ for (var i = 0; i < fs$16[gracefulQueue].length; ++i) if (fs$16[gracefulQueue][i].length > 2) {
12233
+ fs$16[gracefulQueue][i][3] = now;
12234
+ fs$16[gracefulQueue][i][4] = now;
12222
12235
  }
12223
12236
  retry();
12224
12237
  }
12225
12238
  function retry() {
12226
12239
  clearTimeout(retryTimer);
12227
12240
  retryTimer = void 0;
12228
- if (fs$15[gracefulQueue].length === 0) return;
12229
- var elem = fs$15[gracefulQueue].shift();
12241
+ if (fs$16[gracefulQueue].length === 0) return;
12242
+ var elem = fs$16[gracefulQueue].shift();
12230
12243
  var fn = elem[0];
12231
12244
  var args = elem[1];
12232
12245
  var err = elem[2];
@@ -12245,7 +12258,7 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
12245
12258
  if (sinceAttempt >= Math.min(sinceStart * 1.2, 100)) {
12246
12259
  debug("RETRY", fn.name, args);
12247
12260
  fn.apply(null, args.concat([startTime]));
12248
- } else fs$15[gracefulQueue].push(elem);
12261
+ } else fs$16[gracefulQueue].push(elem);
12249
12262
  }
12250
12263
  if (retryTimer === void 0) retryTimer = setTimeout(retry, 0);
12251
12264
  }
@@ -15089,7 +15102,7 @@ async function syncDir(dirPath) {
15089
15102
  */
15090
15103
  function syncFd(fd) {
15091
15104
  return new Promise((resolve, reject) => {
15092
- fs$16.fsync(fd, (err) => {
15105
+ fs$17.fsync(fd, (err) => {
15093
15106
  if (err) {
15094
15107
  reject(err);
15095
15108
  return;
@@ -22273,10 +22286,15 @@ async function loadAgentsMdForRoots(kaos, brandHome, workDirs) {
22273
22286
  const discovered = [];
22274
22287
  const emptySources = /* @__PURE__ */ new Map();
22275
22288
  const seen = /* @__PURE__ */ new Set();
22289
+ const notLoadedCandidates = /* @__PURE__ */ new Set();
22276
22290
  const collect = async (path) => {
22277
22291
  const file = await readAgentFile(kaos, path);
22278
- if (file === void 0) return false;
22292
+ if (file === void 0) {
22293
+ notLoadedCandidates.add(kaos.normpath(path));
22294
+ return false;
22295
+ }
22279
22296
  const key = kaos.normpath(file.path);
22297
+ notLoadedCandidates.delete(key);
22280
22298
  if (file.content.length === 0) {
22281
22299
  emptySources.set(key, InstructionText.file(file.path, "", file.sourceTextBytes));
22282
22300
  return false;
@@ -22312,7 +22330,10 @@ async function loadAgentsMdForRoots(kaos, brandHome, workDirs) {
22312
22330
  return {
22313
22331
  content,
22314
22332
  warning: totalBytes > AGENTS_MD_RECOMMENDED_MAX_BYTES ? `AGENTS.md total ${formatKB(totalBytes)} KB exceeds the recommended ${formatKB(AGENTS_MD_RECOMMENDED_MAX_BYTES)} KB. Large instruction files increase cost and may impact performance; consider trimming.` : void 0,
22315
- sources: rendered.measure()
22333
+ sources: {
22334
+ ...rendered.measure(),
22335
+ ...notLoadedCandidates.size === 0 ? {} : { notLoadedCandidates: [...notLoadedCandidates] }
22336
+ }
22316
22337
  };
22317
22338
  }
22318
22339
  async function loadAdditionalDirsInfo(kaos, additionalDirs) {
@@ -27708,7 +27729,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27708
27729
  };
27709
27730
  return _setPrototypeOf(o, p);
27710
27731
  }
27711
- var fs$14 = __require("fs");
27732
+ var fs$15 = __require("fs");
27712
27733
  var path$14 = __require("path");
27713
27734
  var Loader = require_loader();
27714
27735
  var PrecompiledLoader = require_precompiled_loader().PrecompiledLoader;
@@ -27732,7 +27753,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27732
27753
  } catch (e) {
27733
27754
  throw new Error("watch requires chokidar to be installed");
27734
27755
  }
27735
- var paths = _this.searchPaths.filter(fs$14.existsSync);
27756
+ var paths = _this.searchPaths.filter(fs$15.existsSync);
27736
27757
  var watcher = chokidar.watch(paths);
27737
27758
  watcher.on("all", function(event, fullname) {
27738
27759
  fullname = path$14.resolve(fullname);
@@ -27751,7 +27772,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27751
27772
  for (var i = 0; i < paths.length; i++) {
27752
27773
  var basePath = path$14.resolve(paths[i]);
27753
27774
  var p = path$14.resolve(paths[i], name);
27754
- if (p.indexOf(basePath) === 0 && fs$14.existsSync(p)) {
27775
+ if (p.indexOf(basePath) === 0 && fs$15.existsSync(p)) {
27755
27776
  fullpath = p;
27756
27777
  break;
27757
27778
  }
@@ -27759,7 +27780,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27759
27780
  if (!fullpath) return null;
27760
27781
  this.pathsToNames[fullpath] = name;
27761
27782
  var source = {
27762
- src: fs$14.readFileSync(fullpath, "utf-8"),
27783
+ src: fs$15.readFileSync(fullpath, "utf-8"),
27763
27784
  path: fullpath,
27764
27785
  noCache: this.noCache
27765
27786
  };
@@ -27807,7 +27828,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27807
27828
  }
27808
27829
  this.pathsToNames[fullpath] = name;
27809
27830
  var source = {
27810
- src: fs$14.readFileSync(fullpath, "utf-8"),
27831
+ src: fs$15.readFileSync(fullpath, "utf-8"),
27811
27832
  path: fullpath,
27812
27833
  noCache: this.noCache
27813
27834
  };
@@ -28551,7 +28572,7 @@ var require_precompile_global = /* @__PURE__ */ __commonJSMin(((exports, module)
28551
28572
  //#endregion
28552
28573
  //#region ../../node_modules/.pnpm/nunjucks@3.2.4_chokidar@4.0.3/node_modules/nunjucks/src/precompile.js
28553
28574
  var require_precompile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28554
- var fs$13 = __require("fs");
28575
+ var fs$14 = __require("fs");
28555
28576
  var path$12 = __require("path");
28556
28577
  var _prettifyError = require_lib$8()._prettifyError;
28557
28578
  var compiler = require_compiler();
@@ -28576,27 +28597,27 @@ var require_precompile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28576
28597
  var env = opts.env || new Environment([]);
28577
28598
  var wrapper = opts.wrapper || precompileGlobal;
28578
28599
  if (opts.isString) return precompileString(input, opts);
28579
- var pathStats = fs$13.existsSync(input) && fs$13.statSync(input);
28600
+ var pathStats = fs$14.existsSync(input) && fs$14.statSync(input);
28580
28601
  var precompiled = [];
28581
28602
  var templates = [];
28582
28603
  function addTemplates(dir) {
28583
- fs$13.readdirSync(dir).forEach(function(file) {
28604
+ fs$14.readdirSync(dir).forEach(function(file) {
28584
28605
  var filepath = path$12.join(dir, file);
28585
28606
  var subpath = filepath.substr(path$12.join(input, "/").length);
28586
- var stat = fs$13.statSync(filepath);
28607
+ var stat = fs$14.statSync(filepath);
28587
28608
  if (stat && stat.isDirectory()) {
28588
28609
  subpath += "/";
28589
28610
  if (!match(subpath, opts.exclude)) addTemplates(filepath);
28590
28611
  } else if (match(subpath, opts.include)) templates.push(filepath);
28591
28612
  });
28592
28613
  }
28593
- if (pathStats.isFile()) precompiled.push(_precompile(fs$13.readFileSync(input, "utf-8"), opts.name || input, env));
28614
+ if (pathStats.isFile()) precompiled.push(_precompile(fs$14.readFileSync(input, "utf-8"), opts.name || input, env));
28594
28615
  else if (pathStats.isDirectory()) {
28595
28616
  addTemplates(input);
28596
28617
  for (var i = 0; i < templates.length; i++) {
28597
28618
  var name = templates[i].replace(path$12.join(input, "/"), "");
28598
28619
  try {
28599
- precompiled.push(_precompile(fs$13.readFileSync(templates[i], "utf-8"), name, env));
28620
+ precompiled.push(_precompile(fs$14.readFileSync(templates[i], "utf-8"), name, env));
28600
28621
  } catch (e) {
28601
28622
  if (opts.force) console.error(e);
28602
28623
  else throw e;
@@ -29312,17 +29333,20 @@ function createSystemPromptRenderer(merged) {
29312
29333
  const counts = renderPromptContributions(merged.systemPromptTemplate, vars, rendered, true) ?? renderPromptContributions(merged.systemPromptTemplate, vars, rendered);
29313
29334
  const sources = context.agentsMdSources;
29314
29335
  const copies = counts?.instructionCopies ?? 0;
29315
- const sourceMatches = sources !== void 0 && sources.version === 1 && Number.isSafeInteger(sources.generatedBytes) && sources.generatedBytes >= 0 && sources.files.every((file) => typeof file.path === "string" && Number.isSafeInteger(file.bytes) && file.bytes >= 0) && sources.totalBytes === Buffer.byteLength(vars["BLUN_AGENTS_MD"] ?? "", "utf8") && sources.generatedBytes + sources.files.reduce((sum, file) => sum + file.bytes, 0) === sources.totalBytes;
29336
+ const sourceMatches = sources !== void 0 && sources.version === 1 && Number.isSafeInteger(sources.generatedBytes) && sources.generatedBytes >= 0 && sources.files.every((file) => typeof file.path === "string" && Number.isSafeInteger(file.bytes) && file.bytes >= 0) && (sources.notLoadedCandidates?.every((path) => typeof path === "string") ?? true) && sources.totalBytes === Buffer.byteLength(vars["BLUN_AGENTS_MD"] ?? "", "utf8") && sources.generatedBytes + sources.files.reduce((sum, file) => sum + file.bytes, 0) === sources.totalBytes;
29337
+ const notLoadedCandidates = sourceMatches && sources.notLoadedCandidates !== void 0 ? { notLoadedCandidates: [...sources.notLoadedCandidates] } : {};
29316
29338
  const instructionSources = copies === 0 ? {
29317
29339
  version: 1,
29318
29340
  totalBytes: 0,
29319
29341
  generatedBytes: 0,
29320
- files: sourceMatches ? sources.files.map((file) => copyInstructionFileBytes(file, 0)) : []
29342
+ files: sourceMatches ? sources.files.map((file) => copyInstructionFileBytes(file, 0)) : [],
29343
+ ...notLoadedCandidates
29321
29344
  } : !sourceMatches ? void 0 : {
29322
29345
  version: 1,
29323
29346
  totalBytes: sources.totalBytes * copies,
29324
29347
  generatedBytes: sources.generatedBytes * copies,
29325
- files: sources.files.map((file) => copyInstructionFileBytes(file, copies))
29348
+ files: sources.files.map((file) => copyInstructionFileBytes(file, copies)),
29349
+ ...notLoadedCandidates
29326
29350
  };
29327
29351
  const skillListingSources = counts === void 0 ? void 0 : scaleSkillListingSources(skillSources, vars["BLUN_SKILLS"] ?? "", counts.skillListingBytes);
29328
29352
  context.onContributions(counts === void 0 ? void 0 : {
@@ -191962,7 +191986,7 @@ var require_gifframe = /* @__PURE__ */ __commonJSMin(((exports) => {
191962
191986
  //#region ../../node_modules/.pnpm/gifwrap@0.10.1/node_modules/gifwrap/src/gifutil.js
191963
191987
  var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
191964
191988
  /** @namespace GifUtil */
191965
- const fs$12 = __require("fs");
191989
+ const fs$13 = __require("fs");
191966
191990
  const ImageQ = require_image_q();
191967
191991
  const BitmapImage = require_bitmapimage();
191968
191992
  const { GifFrame } = require_gifframe();
@@ -192229,7 +192253,7 @@ var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
192229
192253
  }
192230
192254
  function _readBinary(path) {
192231
192255
  return new Promise((resolve, reject) => {
192232
- fs$12.readFile(path, (err, buffer) => {
192256
+ fs$13.readFile(path, (err, buffer) => {
192233
192257
  if (err) return reject(err);
192234
192258
  return resolve(buffer);
192235
192259
  });
@@ -192237,7 +192261,7 @@ var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
192237
192261
  }
192238
192262
  function _writeBinary(path, buffer) {
192239
192263
  return new Promise((resolve, reject) => {
192240
- fs$12.writeFile(path, buffer, (err) => {
192264
+ fs$13.writeFile(path, buffer, (err) => {
192241
192265
  if (err) return reject(err);
192242
192266
  return resolve();
192243
192267
  });
@@ -218055,7 +218079,7 @@ var init_file_type = __esmMin((() => {
218055
218079
  }
218056
218080
  async fromFile(path) {
218057
218081
  this.options.signal?.throwIfAborted();
218058
- const fileHandle = await ro.open(path, constants.O_RDONLY | constants.O_NONBLOCK);
218082
+ const fileHandle = await fs.open(path, constants.O_RDONLY | constants.O_NONBLOCK);
218059
218083
  const fileStat = await fileHandle.stat();
218060
218084
  if (!fileStat.isFile()) {
218061
218085
  await fileHandle.close();
@@ -231014,16 +231038,19 @@ var init_full = __esmMin((() => {
231014
231038
  const projected = context.additionalMessages === void 0 ? messages : [...messages, ...context.additionalMessages];
231015
231039
  const historyBudget = this.requestHistoryByteBudget(projected);
231016
231040
  const historyThresholdReached = historyBudget !== void 0 && historyBudget.usedHistoryBytes >= historyBudget.thresholdHistoryBytes;
231041
+ const requestBudget = this.requestBodyByteBudget(projected, context);
231042
+ const requestThresholdReached = requestBudget !== void 0 && requestBudget.usedRequestBytesEstimate >= requestBudget.thresholdRequestBytes;
231017
231043
  if (this.sessionCompactionFailures >= MAX_SESSION_COMPACTION_FAILURES) reason = "session_stopped";
231018
231044
  else if (this.isCompacting) reason = "already_compacting";
231019
- else if (thresholdTokens === void 0 && historyBudget === void 0) reason = "no_budget";
231020
- else if (!historyThresholdReached && (thresholdTokens === void 0 || !Number.isFinite(usedTokens) || usedTokens < thresholdTokens)) reason = "below_threshold";
231045
+ else if (thresholdTokens === void 0 && historyBudget === void 0 && requestBudget === void 0) reason = "no_budget";
231046
+ else if (!historyThresholdReached && !requestThresholdReached && (thresholdTokens === void 0 || !Number.isFinite(usedTokens) || usedTokens < thresholdTokens)) reason = "below_threshold";
231021
231047
  else if (!this.hasShrinkableHistory(projected)) reason = "nothing_to_compact";
231022
231048
  return {
231023
231049
  eligible: reason === "eligible",
231024
231050
  usedTokens,
231025
231051
  thresholdTokens,
231026
231052
  ...historyBudget,
231053
+ ...requestBudget,
231027
231054
  reason
231028
231055
  };
231029
231056
  }
@@ -231045,6 +231072,35 @@ var init_full = __esmMin((() => {
231045
231072
  thresholdHistoryBytes: limit
231046
231073
  };
231047
231074
  }
231075
+ requestBodyByteBudget(messages, context) {
231076
+ const limit = this.agent.blunConfig?.loopControl?.maxRequestHistoryBytes;
231077
+ if (!this.agent.config.hasProvider || this.strategy.compactionBudgetTokens === void 0 || limit === void 0 || !Number.isSafeInteger(limit) || limit <= 0) return void 0;
231078
+ const model = this.agent.activeResponderModel ?? this.agent.config.modelAlias;
231079
+ if (model === void 0 || this.agent.config.runtimeModel(model).provider.name !== "blun") return void 0;
231080
+ const systemPrompt = context.systemPrompt ?? this.agent.effectiveSystemPrompt;
231081
+ const tools = (context.tools ?? this.agent.tools.loopTools).map((tool) => ({
231082
+ name: tool.name,
231083
+ description: tool.description,
231084
+ parameters: tool.parameters
231085
+ }));
231086
+ let extraBytes;
231087
+ try {
231088
+ extraBytes = estimateBlunRequestExtraBytes(tools, messages);
231089
+ } catch {
231090
+ return;
231091
+ }
231092
+ if (Buffer.byteLength(JSON.stringify({
231093
+ systemPrompt,
231094
+ messages: []
231095
+ }), "utf8") + extraBytes.toolsBytes >= BLUN_COMPACTION_REQUEST_BUDGET_BYTES) return void 0;
231096
+ return {
231097
+ usedRequestBytesEstimate: Buffer.byteLength(JSON.stringify({
231098
+ systemPrompt,
231099
+ messages
231100
+ }), "utf8") + extraBytes.toolsBytes + extraBytes.visionBytes,
231101
+ thresholdRequestBytes: BLUN_COMPACTION_REQUEST_BUDGET_BYTES
231102
+ };
231103
+ }
231048
231104
  requestProactiveCompaction(context = {}) {
231049
231105
  const status = this.proactiveCompactionStatus(context);
231050
231106
  if (status.eligible && !this.proactiveCompactionRequested) {
@@ -231053,7 +231109,9 @@ var init_full = __esmMin((() => {
231053
231109
  used_tokens: status.usedTokens,
231054
231110
  threshold_tokens: status.thresholdTokens,
231055
231111
  used_history_bytes: status.usedHistoryBytes,
231056
- threshold_history_bytes: status.thresholdHistoryBytes
231112
+ threshold_history_bytes: status.thresholdHistoryBytes,
231113
+ used_request_bytes_estimate: status.usedRequestBytesEstimate,
231114
+ threshold_request_bytes: status.thresholdRequestBytes
231057
231115
  });
231058
231116
  }
231059
231117
  return status;
@@ -231182,7 +231240,9 @@ var init_full = __esmMin((() => {
231182
231240
  const requestTokens = this.estimateCurrentRequestTokens(requestContext);
231183
231241
  const budget = this.getCompactionBudgetTokens();
231184
231242
  const historyBudget = this.requestHistoryByteBudget(projectedMessages);
231185
- const proactive = (historyBudget !== void 0 && historyBudget.usedHistoryBytes >= historyBudget.thresholdHistoryBytes || !this.isCompacting && budget !== void 0 && Number.isFinite(requestTokens) && requestTokens >= Math.max(1, Math.floor(budget * .9))) && this.hasShrinkableHistory(projectedMessages);
231243
+ const historyThresholdReached = historyBudget !== void 0 && historyBudget.usedHistoryBytes >= historyBudget.thresholdHistoryBytes;
231244
+ const requestBudget = this.requestBodyByteBudget(projectedMessages, requestContext);
231245
+ const proactive = (requestBudget !== void 0 && requestBudget.usedRequestBytesEstimate >= requestBudget.thresholdRequestBytes || historyThresholdReached || !this.isCompacting && budget !== void 0 && Number.isFinite(requestTokens) && requestTokens >= Math.max(1, Math.floor(budget * .9))) && this.hasShrinkableHistory(projectedMessages);
231186
231246
  if (this.checkAutoCompaction(true, requestTokens, projectedMessages, proactive) && (proactive || this.strategy.shouldBlock(requestTokens))) await this.block(signal);
231187
231247
  signal.throwIfAborted();
231188
231248
  const compacted = this.agent.context.history !== historyBefore;
@@ -239793,6 +239853,32 @@ var require_turn_tool_performance_policy = /* @__PURE__ */ __commonJSMin(((expor
239793
239853
  "suchen"
239794
239854
  ]);
239795
239855
  const TOOL_SEARCH_RELATED_TERM_GROUPS = Object.freeze([
239856
+ Object.freeze([
239857
+ "persist",
239858
+ "save",
239859
+ "speichere",
239860
+ "speichern",
239861
+ "store"
239862
+ ]),
239863
+ Object.freeze([
239864
+ "erinnerung",
239865
+ "erinnerungen",
239866
+ "fact",
239867
+ "facts",
239868
+ "fakt",
239869
+ "fakten",
239870
+ "memory",
239871
+ "memories",
239872
+ "merk",
239873
+ "merken",
239874
+ "remember"
239875
+ ]),
239876
+ Object.freeze([
239877
+ "note",
239878
+ "notes",
239879
+ "notiz",
239880
+ "notizen"
239881
+ ]),
239796
239882
  Object.freeze([
239797
239883
  "checklist",
239798
239884
  "list",
@@ -240051,7 +240137,7 @@ var require_turn_tool_performance_policy = /* @__PURE__ */ __commonJSMin(((expor
240051
240137
  if (document.nameTokens.has(token)) exactNameMatches += 1;
240052
240138
  else if (relatedSearchTerms(token).some((term) => document.nameTokens.has(term))) relatedNameMatches += 1;
240053
240139
  }
240054
- return matchedTokens >= 2 || exactNameMatches >= 1 && score >= 10 || relatedNameMatches >= 1 && score >= 5 ? {
240140
+ return matchedTokens >= 2 || exactNameMatches >= 1 && score >= 10 || queryTokens.length === 1 && relatedNameMatches >= 1 && score >= 5 ? {
240055
240141
  name: document.name,
240056
240142
  score,
240057
240143
  matchedTokens,
@@ -240072,11 +240158,11 @@ var require_turn_tool_performance_policy = /* @__PURE__ */ __commonJSMin(((expor
240072
240158
  function searchRelatedDeferredTools(tools, query, options = {}) {
240073
240159
  const normalized = normalizeDeferredToolQuery(query).toLowerCase();
240074
240160
  if (!normalized || normalized.startsWith("select:")) return [];
240075
- const tokens = normalized.split(/\s+/).filter(Boolean);
240161
+ const tokens = normalized.match(/\+?[\p{L}\p{N}_-]+/gu) || [];
240076
240162
  const requestedNameTokens = tokens.filter((token) => token.startsWith("+")).map((token) => token.slice(1)).filter(Boolean);
240077
240163
  const relaxRequiredNameTokens = options.relaxRequiredNameTokens === true && requestedNameTokens.length > 0;
240078
240164
  const requiredNameTokens = relaxRequiredNameTokens ? [] : requestedNameTokens;
240079
- const searchTokens = [...tokens.filter((token) => !token.startsWith("+")), ...relaxRequiredNameTokens ? requestedNameTokens : []].filter((token) => !TOOL_SEARCH_INTENT_WORDS.has(token));
240165
+ const searchTokens = [...tokens.filter((token) => !token.startsWith("+")), ...relaxRequiredNameTokens ? requestedNameTokens : []].filter((token) => !TOOL_SEARCH_INTENT_WORDS.has(token) && !TOOL_RANK_STOP_WORDS.has(token));
240080
240166
  if (searchTokens.length < 2 && !TOOL_SEARCH_SINGLE_TERM_RELATED_FALLBACKS.has(searchTokens[0])) return [];
240081
240167
  const minimumMatchedTokens = searchTokens.length === 1 ? 1 : Math.max(2, Math.ceil(searchTokens.length * .75));
240082
240168
  const ranked = tools.map((tool) => {
@@ -259155,7 +259241,7 @@ function Yn(s, t) {
259155
259241
  function Kn(s, t) {
259156
259242
  s.head = new ue$1(t, void 0, s.head, s), s.tail || (s.tail = s.head), s.length++;
259157
259243
  }
259158
- var zr, Ur, Ds, Wr, Gr, Zr, Q$1, J$1, nt$1, De$1, qt, Ne$1, Ns, Ae$1, As, z$1, Mt, g$1, Qt, Bt, b$1, N$1, _$1, bi, Ie$1, L$1, S, _i, Oi, Is, Ti, Z$1, xi, Ce$1, Jt$1, Rt, C, jt, Yr, Kr, Vr, $r, Fe$1, Li, Xr, qr, A$1, Jr, ht, H$1, te, m$1, Ni, tt$1, Ai, ki, vi, ie$1, ke$1, Ut$1, Ht, Ii, Pt, at, U$1, ot, Y$1, zt, Ci, j$1, ee$1, Fi, ve$1, gt$2, Me, bt, _t, Be$1, et$1, Wt$1, jr, Fs, ks, vs, Ms, Bs, tn, se$1, K$1, sn, M$1, rn, zs, nn, Bi, Tt, Gt, Pi, re, Pe$1, ze$1, Ue, He$1, We$1, Ge$1, Ze$1, Ye$1, Ke$1, Us, hn, an, Hs, ln, cn, Ws, Gs, Hi, ne, dn, Ui, oe$1, Ve$1, un, F$1, mn, xt, Wi, pn, lt, En, wn, Sn, ct, yn, Rn, gn, Gi, bn, Lt, ft, On, Tn, xn, f, $e$1, Dt, Nn, Xi, qi, An, B$1, Nt, it, Zi, Zs, V$1, he$1, dt, Ys, p, st$1, ut, Yi, At, w$1, Xe$1, qe$1, Ki, Ks, Vs, ae$1, Vi, Qe$1, Yt$1, $$1, Je$1, It, je$1, ti, $s, In, le$1, $i, Xs, Cn, rt$1, mt, vn, Qi, Mn, Bn, Ct, Ji, zn, qs, ce$1, ei, ji, Un, Hn, ts, Qs, rr, Wn, tr, er, ir, is$2, sr, fe$1, ii, ss, si, rs, ns, os$6, hs, pt, ri, as, es, q$1, de$1, ni, oi, Gn, hi, ue$1, pi, nr, li, me$1, W$1, pe$2, Et, Ft$1, Ee$1, ai, G, ls, ci, or, ds, us, fi, di, hr, cs, ui, lr, fs$11, wt, kt, Vn, $n, fr, dr, Xn, qn, Er, wr, ur, Sr, yr, Rr, jn, to, eo, mr, ms, ps, Ei, io, Es, so, ws, Se$1, St, no, gr, Ss, br, oo, _r, ys, Or, Vt$1, Tr, ao, lo, yi, Lr, Dr, _s, Nr, Os, P$1, Ts, xs, gi, Ar, Ir, Re, Cr, Fr, Rs, yt, O$1, Ri, kr, $t, gs, bs, Ls, ge$1, be, _e$1, Oe$1, Te$1, uo, mo, po, vr, Xt$1, ye$1, xe$1, Eo, wo, So, yo, Ro, go, bo, _o, vt, To;
259244
+ var zr, Ur, Ds, Wr, Gr, Zr, Q$1, J$1, nt$1, De$1, qt, Ne$1, Ns, Ae$1, As, z$1, Mt, g$1, Qt, Bt, b$1, N$1, _$1, bi, Ie$1, L$1, S, _i, Oi, Is, Ti, Z$1, xi, Ce$1, Jt$1, Rt, C, jt, Yr, Kr, Vr, $r, Fe$1, Li, Xr, qr, A$1, Jr, ht, H$1, te, m$1, Ni, tt$1, Ai, ki, vi, ie$1, ke$1, Ut$1, Ht, Ii, Pt, at, U$1, ot, Y$1, zt, Ci, j$1, ee$1, Fi, ve$1, gt$2, Me, bt, _t, Be$1, et$1, Wt$1, jr, Fs, ks, vs, Ms, Bs, tn, se$1, K$1, sn, M$1, rn, zs, nn, Bi, Tt, Gt, Pi, re, Pe$1, ze$1, Ue, He$1, We$1, Ge$1, Ze$1, Ye$1, Ke$1, Us, hn, an, Hs, ln, cn, Ws, Gs, Hi, ne, dn, Ui, oe$1, Ve$1, un, F$1, mn, xt, Wi, pn, lt, En, wn, Sn, ct, yn, Rn, gn, Gi, bn, Lt, ft, On, Tn, xn, f, $e$1, Dt, Nn, Xi, qi, An, B$1, Nt, it, Zi, Zs, V$1, he$1, dt, Ys, p, st$1, ut, Yi, At, w$1, Xe$1, qe$1, Ki, Ks, Vs, ae$1, Vi, Qe$1, Yt$1, $$1, Je$1, It, je$1, ti, $s, In, le$1, $i, Xs, Cn, rt$1, mt, vn, Qi, Mn, Bn, Ct, Ji, zn, qs, ce$1, ei, ji, Un, Hn, ts, Qs, rr, Wn, tr, er, ir, is$2, sr, fe$1, ii, ss, si, rs, ns, os$6, hs, pt, ri, as, es, q$1, de$1, ni, oi, Gn, hi, ue$1, pi, nr, li, me$1, W$1, pe$2, Et, Ft$1, Ee$1, ai, G, ls, ci, or, ds, us, fi, di, hr, cs, ui, lr, fs$12, wt, kt, Vn, $n, fr, dr, Xn, qn, Er, wr, ur, Sr, yr, Rr, jn, to, eo, mr, ms, ps, Ei, io, Es, so, ws, Se$1, St, no, gr, Ss, br, oo, _r, ys, Or, Vt$1, Tr, ao, lo, yi, Lr, Dr, _s, Nr, Os, P$1, Ts, xs, gi, Ar, Ir, Re, Cr, Fr, Rs, yt, O$1, Ri, kr, $t, gs, bs, Ls, ge$1, be, _e$1, Oe$1, Te$1, uo, mo, po, vr, Xt$1, ye$1, xe$1, Eo, wo, So, yo, Ro, go, bo, _o, vt, To;
259159
259245
  var init_index_min = __esmMin((() => {
259160
259246
  zr = Object.defineProperty;
259161
259247
  Ur = (s, t) => {
@@ -261125,7 +261211,7 @@ while (this[Zs](this[st$1].shift()));
261125
261211
  constructor(t, e) {
261126
261212
  this.path = t || "./", this.absolute = e;
261127
261213
  }
261128
- }, nr = Buffer.alloc(1024), li = Symbol("onStat"), me$1 = Symbol("ended"), W$1 = Symbol("queue"), pe$2 = Symbol("pendingLinks"), Et = Symbol("current"), Ft$1 = Symbol("process"), Ee$1 = Symbol("processing"), ai = Symbol("processJob"), G = Symbol("jobs"), ls = Symbol("jobDone"), ci = Symbol("addFSEntry"), or = Symbol("addTarEntry"), ds = Symbol("stat"), us = Symbol("readdir"), fi = Symbol("onreaddir"), di = Symbol("pipe"), hr = Symbol("entry"), cs = Symbol("entryOpt"), ui = Symbol("writeEntryClass"), lr = Symbol("write"), fs$11 = Symbol("ondrain"), wt = class extends A$1 {
261214
+ }, nr = Buffer.alloc(1024), li = Symbol("onStat"), me$1 = Symbol("ended"), W$1 = Symbol("queue"), pe$2 = Symbol("pendingLinks"), Et = Symbol("current"), Ft$1 = Symbol("process"), Ee$1 = Symbol("processing"), ai = Symbol("processJob"), G = Symbol("jobs"), ls = Symbol("jobDone"), ci = Symbol("addFSEntry"), or = Symbol("addTarEntry"), ds = Symbol("stat"), us = Symbol("readdir"), fi = Symbol("onreaddir"), di = Symbol("pipe"), hr = Symbol("entry"), cs = Symbol("entryOpt"), ui = Symbol("writeEntryClass"), lr = Symbol("write"), fs$12 = Symbol("ondrain"), wt = class extends A$1 {
261129
261215
  sync = !1;
261130
261216
  opt;
261131
261217
  cwd;
@@ -261158,8 +261244,8 @@ while (this[Zs](this[st$1].shift()));
261158
261244
  if ((t.gzip ? 1 : 0) + (t.brotli ? 1 : 0) + (t.zstd ? 1 : 0) > 1) throw new TypeError("gzip, brotli, zstd are mutually exclusive");
261159
261245
  if (t.gzip && (typeof t.gzip != "object" && (t.gzip = {}), this.portable && (t.gzip.portable = !0), this.zip = new ze$1(t.gzip)), t.brotli && (typeof t.brotli != "object" && (t.brotli = {}), this.zip = new We$1(t.brotli)), t.zstd && (typeof t.zstd != "object" && (t.zstd = {}), this.zip = new Ye$1(t.zstd)), !this.zip) throw new Error("impossible");
261160
261246
  let e = this.zip;
261161
- e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs$11]()), this.on("resume", () => e.resume());
261162
- } else this.on("drain", this[fs$11]);
261247
+ e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs$12]()), this.on("resume", () => e.resume());
261248
+ } else this.on("drain", this[fs$12]);
261163
261249
  this.noDirRecurse = !!t.noDirRecurse, this.follow = !!t.follow, this.noMtime = !!t.noMtime, t.mtime && (this.mtime = t.mtime), this.filter = typeof t.filter == "function" ? t.filter : () => !0, this[W$1] = new hi(), this[G] = 0, this.jobs = Number(t.jobs) || 4, this[Ee$1] = !1, this[me$1] = !1;
261164
261250
  }
261165
261251
  [lr](t) {
@@ -261286,7 +261372,7 @@ while (this[Zs](this[st$1].shift()));
261286
261372
  this.emit("error", e);
261287
261373
  }
261288
261374
  }
261289
- [fs$11]() {
261375
+ [fs$12]() {
261290
261376
  this[Et] && this[Et].entry && this[Et].entry.resume();
261291
261377
  }
261292
261378
  [di](t) {
@@ -261452,7 +261538,7 @@ while (this[Zs](this[st$1].shift()));
261452
261538
  E ? e(E) : x && a ? Es(x, o, h, (Le) => y(Le)) : n ? Kt.chmod(s, r, e) : e();
261453
261539
  };
261454
261540
  if (s === d) return no(s, y);
261455
- if (l) return ro.mkdir(s, {
261541
+ if (l) return fs.mkdir(s, {
261456
261542
  mode: r,
261457
261543
  recursive: !0
261458
261544
  }).then((E) => y(null, E ?? void 0), y);
@@ -262211,7 +262297,7 @@ var require_pend = /* @__PURE__ */ __commonJSMin(((exports, module) => {
262211
262297
  //#endregion
262212
262298
  //#region ../../node_modules/.pnpm/yauzl@3.3.0/node_modules/yauzl/fd-slicer.js
262213
262299
  var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262214
- var fs$10 = __require("fs");
262300
+ var fs$11 = __require("fs");
262215
262301
  var util$6 = __require("util");
262216
262302
  var stream$2 = __require("stream");
262217
262303
  var Readable = stream$2.Readable;
@@ -262236,7 +262322,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262236
262322
  FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
262237
262323
  var self = this;
262238
262324
  self.pend.go(function(cb) {
262239
- fs$10.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
262325
+ fs$11.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
262240
262326
  cb();
262241
262327
  callback(err, bytesRead, buffer);
262242
262328
  });
@@ -262245,7 +262331,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262245
262331
  FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
262246
262332
  var self = this;
262247
262333
  self.pend.go(function(cb) {
262248
- fs$10.write(self.fd, buffer, offset, length, position, function(err, written, buffer) {
262334
+ fs$11.write(self.fd, buffer, offset, length, position, function(err, written, buffer) {
262249
262335
  cb();
262250
262336
  callback(err, written, buffer);
262251
262337
  });
@@ -262265,7 +262351,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262265
262351
  self.refCount -= 1;
262266
262352
  if (self.refCount > 0) return;
262267
262353
  if (self.refCount < 0) throw new Error("invalid unref");
262268
- if (self.autoClose) fs$10.close(self.fd, onCloseDone);
262354
+ if (self.autoClose) fs$11.close(self.fd, onCloseDone);
262269
262355
  function onCloseDone(err) {
262270
262356
  if (err) self.emit("error", err);
262271
262357
  else self.emit("close");
@@ -262296,7 +262382,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262296
262382
  self.context.pend.go(function(cb) {
262297
262383
  if (self.destroyed) return cb();
262298
262384
  var buffer = Buffer.allocUnsafe(toRead);
262299
- fs$10.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
262385
+ fs$11.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
262300
262386
  if (err) self.destroy(err);
262301
262387
  else if (bytesRead === 0) {
262302
262388
  self.destroyed = true;
@@ -262342,7 +262428,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262342
262428
  }
262343
262429
  self.context.pend.go(function(cb) {
262344
262430
  if (self.destroyed) return cb();
262345
- fs$10.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) {
262431
+ fs$11.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) {
262346
262432
  if (err) {
262347
262433
  self.destroy();
262348
262434
  cb();
@@ -268826,6 +268912,7 @@ var init_turn = __esmMin((() => {
268826
268912
  const appendedMessage = this.agent.context.history.at(-1);
268827
268913
  const turnAnchor = appendedMessage !== previousLastMessage && appendedMessage?.role === "user" && appendedMessage.origin === origin ? appendedMessage : void 0;
268828
268914
  const startedAt = Date.now();
268915
+ const preRequestHookStartedAt = performance.now();
268829
268916
  let ended;
268830
268917
  let blockedByUserPromptHook = false;
268831
268918
  let completedStopReason;
@@ -268851,6 +268938,13 @@ var init_turn = __esmMin((() => {
268851
268938
  this.agent.log.warn("Turn-start observation failed");
268852
268939
  }
268853
268940
  signal.throwIfAborted();
268941
+ if (this.agent.type === "main" && process.env["BLUN_DIAG_PRE_REQUEST_PHASES"] === "1") try {
268942
+ this.agent.log.info("turn pre-request phase", {
268943
+ turnId,
268944
+ phase: "turn-hooks",
268945
+ durationMs: Math.max(0, Math.round(performance.now() - preRequestHookStartedAt))
268946
+ });
268947
+ } catch {}
268854
268948
  const stopReason = await this.runStepLoop(turnId, signal, input, origin, turnAnchor, (response) => {
268855
268949
  completedResponse = response;
268856
268950
  });
@@ -269020,9 +269114,26 @@ var init_turn = __esmMin((() => {
269020
269114
  let stopHookContinuationUsed = false;
269021
269115
  let goalOutcomeMessageContinuationUsed = false;
269022
269116
  const deduper = new ToolCallDeduplicator({ telemetry: this.agent.telemetry });
269117
+ const diagnosePreRequest = this.agent.type === "main" && process.env["BLUN_DIAG_PRE_REQUEST_PHASES"] === "1";
269118
+ const recordPreRequestPhase = (phase, startedAt) => {
269119
+ if (!diagnosePreRequest) return;
269120
+ try {
269121
+ this.agent.log.info("turn pre-request phase", {
269122
+ turnId,
269123
+ phase,
269124
+ durationMs: Math.max(0, Math.round(performance.now() - startedAt))
269125
+ });
269126
+ } catch {}
269127
+ };
269128
+ let phaseStartedAt = performance.now();
269023
269129
  await this.agent.mcp?.waitForInitialLoad(signal);
269130
+ recordPreRequestPhase("mcp-initial-load", phaseStartedAt);
269131
+ phaseStartedAt = performance.now();
269024
269132
  const personalMemoryRecall = await this.agent.injection.injectPersonalMemoryForTurn(turnId, input, origin, signal);
269133
+ recordPreRequestPhase("personal-memory-recall", phaseStartedAt);
269134
+ phaseStartedAt = performance.now();
269025
269135
  await this.agent.injection.injectGoal();
269136
+ recordPreRequestPhase("goal-injection", phaseStartedAt);
269026
269137
  this.setActiveSteerAcceptance(turnId, true);
269027
269138
  const turnNeedsThinking = blunTurnNeedsTools(blunThinkingIntentInput(input), origin);
269028
269139
  let toolInput = input;
@@ -269033,12 +269144,14 @@ var init_turn = __esmMin((() => {
269033
269144
  const raw = [...this.agent.context.history];
269034
269145
  const history = personalMemoryRecall === void 0 ? raw : [...raw, personalMemoryRecall];
269035
269146
  const selected = taskToolsNeeded ? history : greetingHistory(history, greetingAnchor);
269147
+ const projectionStartedAt = performance.now();
269036
269148
  const projected = await this.historicalToolProjection.project(selected, turnAnchor, tools, {
269037
269149
  turnId: String(turnId),
269038
269150
  stepNumber: this.currentStep,
269039
269151
  signal,
269040
269152
  llm: turnLLM
269041
269153
  });
269154
+ recordPreRequestPhase("historical-tool-projection", projectionStartedAt);
269042
269155
  const current = this.agent.context.history;
269043
269156
  if (current.length !== raw.length || current.some((message, index) => message !== raw[index])) {
269044
269157
  const latest = personalMemoryRecall === void 0 ? current : [...current, personalMemoryRecall];
@@ -269049,7 +269162,7 @@ var init_turn = __esmMin((() => {
269049
269162
  partialContext = selected.length < history.length || projected.changed;
269050
269163
  return projected.history;
269051
269164
  };
269052
- const turnLLM = this.agent.llmForTurn(turnNeedsThinking ? void 0 : "off");
269165
+ const turnLLM = this.agent.llmForTurn(turnNeedsThinking ? void 0 : "off", turnId);
269053
269166
  const turnTools = this.agent.tools.captureTurnTools();
269054
269167
  while (true) {
269055
269168
  signal.throwIfAborted();
@@ -269059,6 +269172,7 @@ var init_turn = __esmMin((() => {
269059
269172
  try {
269060
269173
  const selectedTools = [];
269061
269174
  this.refreshSelectedTools = (snapshot) => {
269175
+ const selectionStartedAt = performance.now();
269062
269176
  if (snapshot.messages.length > 0) toolInput = snapshot.messages.flatMap((message) => message.content);
269063
269177
  const eligibleTools = blunToolsForOrigin(this.agent.injection.filterPersonalMemoryToolsForTurn(turnId, input, origin, turnTools()), origin);
269064
269178
  const intent = blunThinkingIntentInput(toolInput);
@@ -269071,6 +269185,7 @@ var init_turn = __esmMin((() => {
269071
269185
  if (tool !== void 0 && !selectedTools.some((candidate) => candidate.name === name) && estimateTokensForTools([...selectedTools, tool]) <= (0, import_turn_tool_performance_policy.toolSchemaBudgetTokens)(this.agent.config.modelCapabilities?.max_context_tokens)) selectedTools.push(tool);
269072
269186
  }
269073
269187
  } else selectedTools.splice(0, selectedTools.length, ...eligibleTools.filter((tool) => BLUN_LANGUAGE_REVIEW_TOOL_NAMES.has(tool.name) || BLUN_TELEGRAM_OUTBOUND_TOOL_RE.test(tool.name)));
269188
+ recordPreRequestPhase("tool-selection", selectionStartedAt);
269074
269189
  return selectedTools;
269075
269190
  };
269076
269191
  return (await runTurn({
@@ -269083,14 +269198,24 @@ var init_turn = __esmMin((() => {
269083
269198
  }, completion);
269084
269199
  },
269085
269200
  llm: turnLLM,
269086
- buildMessages: async () => this.agent.context.project(await turnHistory(selectedTools), { dropOrphanResults: true }),
269087
- buildMessagesStrict: async () => this.agent.context.project(await turnHistory(selectedTools), {
269088
- synthesizeMissing: true,
269089
- dropOrphanResults: true,
269090
- dedupeDuplicateToolCalls: true,
269091
- dropLeadingNonUser: true,
269092
- mergeConsecutiveAssistants: true
269093
- }),
269201
+ buildMessages: async () => {
269202
+ const startedAt = performance.now();
269203
+ const messages = this.agent.context.project(await turnHistory(selectedTools), { dropOrphanResults: true });
269204
+ recordPreRequestPhase("message-build", startedAt);
269205
+ return messages;
269206
+ },
269207
+ buildMessagesStrict: async () => {
269208
+ const startedAt = performance.now();
269209
+ const messages = this.agent.context.project(await turnHistory(selectedTools), {
269210
+ synthesizeMissing: true,
269211
+ dropOrphanResults: true,
269212
+ dedupeDuplicateToolCalls: true,
269213
+ dropLeadingNonUser: true,
269214
+ mergeConsecutiveAssistants: true
269215
+ });
269216
+ recordPreRequestPhase("message-build-strict", startedAt);
269217
+ return messages;
269218
+ },
269094
269219
  dispatchEvent: this.buildDispatchEvent(turnId, signal, onFinalResponse, () => partialContext),
269095
269220
  tools: selectedTools,
269096
269221
  log: this.agent.log,
@@ -269107,8 +269232,10 @@ var init_turn = __esmMin((() => {
269107
269232
  },
269108
269233
  hooks: {
269109
269234
  beforeStep: async ({ signal: stepSignal, llm }) => {
269235
+ const injectionStartedAt = performance.now();
269110
269236
  this.agent.microCompaction.detect();
269111
269237
  await this.agent.injection.inject();
269238
+ recordPreRequestPhase("step-injection", injectionStartedAt);
269112
269239
  stepSignal.throwIfAborted();
269113
269240
  deduper.beginStep();
269114
269241
  },
@@ -272760,7 +272887,8 @@ function copyContributions(value) {
272760
272887
  version: source.version,
272761
272888
  totalBytes: source.totalBytes,
272762
272889
  generatedBytes: source.generatedBytes,
272763
- files: source.files.map((file) => copyInstructionFileBytes(file))
272890
+ files: source.files.map((file) => copyInstructionFileBytes(file)),
272891
+ ...source.notLoadedCandidates === void 0 ? {} : { notLoadedCandidates: [...source.notLoadedCandidates] }
272764
272892
  } }
272765
272893
  };
272766
272894
  }
@@ -272799,8 +272927,13 @@ var init_llm_request_logger = __esmMin((() => {
272799
272927
  toolsEstimatedTokens = 0;
272800
272928
  requestSequence = 0;
272801
272929
  lastTurnRequest;
272802
- constructor(log) {
272930
+ serializedPrefixKey;
272931
+ requestSignatures = /* @__PURE__ */ new Map();
272932
+ prefixComparisons = /* @__PURE__ */ new Map();
272933
+ lastSerializedRequest;
272934
+ constructor(log, serializedPrefixDiagnostic = process.env["BLUN_DIAG_SERIALIZED_PREFIX"] === "1") {
272803
272935
  this.log = log;
272936
+ this.serializedPrefixKey = serializedPrefixDiagnostic ? randomBytes(32) : void 0;
272804
272937
  }
272805
272938
  logRequest(input) {
272806
272939
  const sequence = ++this.requestSequence;
@@ -272817,6 +272950,10 @@ var init_llm_request_logger = __esmMin((() => {
272817
272950
  toolsHash: fingerprint(JSON.stringify(toolSignature(tools)))
272818
272951
  };
272819
272952
  const signature = JSON.stringify(config);
272953
+ if (this.serializedPrefixKey !== void 0) {
272954
+ this.requestSignatures.set(sequence, signature);
272955
+ if (this.requestSignatures.size > 32) this.requestSignatures.delete(this.requestSignatures.keys().next().value);
272956
+ }
272820
272957
  if (signature !== this.lastConfigLogSignature) {
272821
272958
  this.lastConfigLogSignature = signature;
272822
272959
  this.configRevision++;
@@ -272846,6 +272983,20 @@ var init_llm_request_logger = __esmMin((() => {
272846
272983
  }
272847
272984
  };
272848
272985
  if (partialMessageCount > 0) requestFields.partialMessageCount = partialMessageCount;
272986
+ const source = input.systemPromptContributions;
272987
+ if (source?.version === 1 && [
272988
+ source.totalBytes,
272989
+ source.instructionBytes,
272990
+ source.skillListingBytes,
272991
+ source.runtimeMemoryBytes,
272992
+ source.otherBytes
272993
+ ].every((value) => Number.isSafeInteger(value) && value >= 0) && source.instructionBytes + source.skillListingBytes + source.runtimeMemoryBytes + source.otherBytes === source.totalBytes && source.totalBytes === Buffer.byteLength(systemPrompt, "utf8")) requestFields.systemPromptSourceBytes = {
272994
+ totalBytes: source.totalBytes,
272995
+ instructionBytes: source.instructionBytes,
272996
+ skillListingBytes: source.skillListingBytes,
272997
+ runtimeMemoryBytes: source.runtimeMemoryBytes,
272998
+ otherBytes: source.otherBytes
272999
+ };
272849
273000
  this.log.info("llm request", requestFields);
272850
273001
  if (fields?.turnStep !== void 0 && /^\d+\.\d+$/.test(fields.turnStep)) {
272851
273002
  const historyTextOrigins = summarizeRequestTextOrigins(messages);
@@ -272871,10 +273022,51 @@ var init_llm_request_logger = __esmMin((() => {
272871
273022
  getLastTurnRequest() {
272872
273023
  return this.lastTurnRequest === void 0 ? void 0 : structuredClone(this.lastTurnRequest);
272873
273024
  }
273025
+ get serializedPrefixDiagnosticEnabled() {
273026
+ return this.serializedPrefixKey !== void 0;
273027
+ }
273028
+ observeSerializedRequest(body, fields, sequence) {
273029
+ const key = this.serializedPrefixKey;
273030
+ if (key === void 0 || !/^\d+\.\d+$/.test(fields?.turnStep ?? "")) return;
273031
+ const signature = this.requestSignatures.get(sequence);
273032
+ if (signature === void 0) return;
273033
+ try {
273034
+ const bytes = Buffer.from(body, "utf8");
273035
+ const granularityBytes = 1024;
273036
+ const chunks = [];
273037
+ for (let start = 0; start + granularityBytes <= bytes.length; start += granularityBytes) chunks.push(createHmac("sha256", key).update(bytes.subarray(start, start + granularityBytes)).digest("hex"));
273038
+ const previous = this.lastSerializedRequest;
273039
+ if (previous !== void 0 && previous.signature === signature) {
273040
+ let common = 0;
273041
+ while (common < previous.chunks.length && common < chunks.length && previous.chunks[common] === chunks[common]) common++;
273042
+ this.prefixComparisons.set(sequence, {
273043
+ version: 1,
273044
+ granularityBytes,
273045
+ previousBytes: previous.bytes,
273046
+ currentBytes: bytes.length,
273047
+ commonPrefixBytesLowerBound: common * granularityBytes,
273048
+ previousSequence: previous.sequence,
273049
+ currentSequence: sequence
273050
+ });
273051
+ if (this.prefixComparisons.size > 32) this.prefixComparisons.delete(this.prefixComparisons.keys().next().value);
273052
+ }
273053
+ this.lastSerializedRequest = {
273054
+ sequence,
273055
+ signature,
273056
+ bytes: bytes.length,
273057
+ chunks
273058
+ };
273059
+ } catch {
273060
+ this.lastSerializedRequest = void 0;
273061
+ }
273062
+ }
272874
273063
  logTransportAttempt(stats, fields, sequence) {
273064
+ const serializedPrefix = sequence === void 0 ? void 0 : this.prefixComparisons.get(sequence);
272875
273065
  this.log.info("llm transport attempt", {
272876
273066
  ...fields,
272877
- ...stats
273067
+ ...stats,
273068
+ ...this.serializedPrefixKey === void 0 || sequence === void 0 ? {} : { requestSequence: sequence },
273069
+ ...serializedPrefix === void 0 ? {} : { serializedPrefix }
272878
273070
  });
272879
273071
  if (sequence === void 0 || this.lastTurnRequest?.sequence !== sequence) return;
272880
273072
  const breakdown = stats.requestBreakdown;
@@ -273022,6 +273214,7 @@ var init_agent = __esmMin((() => {
273022
273214
  errorMemory;
273023
273215
  replayBuilder;
273024
273216
  additionalDirs;
273217
+ systemPromptStartedAt = /* @__PURE__ */ new Date();
273025
273218
  activeProfile;
273026
273219
  brandHome;
273027
273220
  _activeResponderModel;
@@ -273109,6 +273302,7 @@ var init_agent = __esmMin((() => {
273109
273302
  const retryScope = providerRetryScope(modelAlias, provider);
273110
273303
  await this.providerRetryWait.wait(retryScope, generateOptions?.signal);
273111
273304
  const callerTransportAttempt = generateOptions?.onTransportAttempt;
273305
+ const callerSerializedRequest = generateOptions?.onSerializedRequest;
273112
273306
  const ownedGenerateOptions = {
273113
273307
  ...generateOptions,
273114
273308
  transportMaxRetries: 0
@@ -273131,6 +273325,12 @@ var init_agent = __esmMin((() => {
273131
273325
  callerTransportAttempt?.(stats);
273132
273326
  this.llmRequestLogger.logTransportAttempt(stats, requestLogFields, requestSequence);
273133
273327
  },
273328
+ ...callerSerializedRequest !== void 0 || this.llmRequestLogger.serializedPrefixDiagnosticEnabled ? { onSerializedRequest: (body) => {
273329
+ try {
273330
+ callerSerializedRequest?.(body);
273331
+ } catch {}
273332
+ this.llmRequestLogger.observeSerializedRequest(body, requestLogFields, requestSequence);
273333
+ } } : {},
273134
273334
  onRequestStart: () => {
273135
273335
  requestOptions?.onRequestStart?.();
273136
273336
  requestStarted = true;
@@ -273156,7 +273356,7 @@ var init_agent = __esmMin((() => {
273156
273356
  get llm() {
273157
273357
  return this.llmForTurn();
273158
273358
  }
273159
- llmForTurn(thinkingEffort) {
273359
+ llmForTurn(thinkingEffort, diagnosticTurnId) {
273160
273360
  const selectedAlias = this.config.model;
273161
273361
  const modelProvider = this.modelProvider;
273162
273362
  if (modelProvider === void 0) throw new BlunError(ErrorCodes.MODEL_NOT_CONFIGURED, "Provider not set");
@@ -273171,6 +273371,7 @@ var init_agent = __esmMin((() => {
273171
273371
  messages: await rebuildMessages()
273172
273372
  };
273173
273373
  let systemPrompt = this.effectiveSystemPrompt;
273374
+ const preflightStartedAt = performance.now();
273174
273375
  const compacted = await this.fullCompaction.beforeStep(params.signal, {
273175
273376
  messages: params.messages,
273176
273377
  additionalMessages: steers.messages,
@@ -273179,6 +273380,13 @@ var init_agent = __esmMin((() => {
273179
273380
  rebuildSystemPrompt: () => systemPrompt = this.effectiveSystemPrompt,
273180
273381
  tools: params.tools
273181
273382
  });
273383
+ if (this.type === "main" && diagnosticTurnId !== void 0 && process.env["BLUN_DIAG_PRE_REQUEST_PHASES"] === "1") try {
273384
+ this.log.info("turn pre-request phase", {
273385
+ turnId: diagnosticTurnId,
273386
+ phase: "compaction-preflight",
273387
+ durationMs: Math.max(0, Math.round(performance.now() - preflightStartedAt))
273388
+ });
273389
+ } catch {}
273182
273390
  const tools = params.tools.some((tool) => tool.name === "CompactConversation") && !this.fullCompaction.proactiveCompactionStatus({
273183
273391
  messages: compacted ? await rebuildMessages() : params.messages,
273184
273392
  additionalMessages: steers.messages,
@@ -273283,6 +273491,7 @@ var init_agent = __esmMin((() => {
273283
273491
  let contributions;
273284
273492
  const systemPrompt = profile.systemPrompt({
273285
273493
  osEnv: this.kaos.osEnv,
273494
+ now: this.systemPromptStartedAt,
273286
273495
  cwd: this.config.cwd,
273287
273496
  skills: this.skills?.registry,
273288
273497
  cwdListing: context?.cwdListing,
@@ -303200,7 +303409,7 @@ var init_proxy = __esmMin((() => {
303200
303409
  var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303201
303410
  module.exports = isexe;
303202
303411
  isexe.sync = sync;
303203
- var fs$8 = __require("fs");
303412
+ var fs$9 = __require("fs");
303204
303413
  function checkPathExt(path, options) {
303205
303414
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
303206
303415
  if (!pathext) return true;
@@ -303217,12 +303426,12 @@ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303217
303426
  return checkPathExt(path, options);
303218
303427
  }
303219
303428
  function isexe(path, options, cb) {
303220
- fs$8.stat(path, function(er, stat) {
303429
+ fs$9.stat(path, function(er, stat) {
303221
303430
  cb(er, er ? false : checkStat(stat, path, options));
303222
303431
  });
303223
303432
  }
303224
303433
  function sync(path, options) {
303225
- return checkStat(fs$8.statSync(path), path, options);
303434
+ return checkStat(fs$9.statSync(path), path, options);
303226
303435
  }
303227
303436
  }));
303228
303437
  //#endregion
@@ -303230,14 +303439,14 @@ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303230
303439
  var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303231
303440
  module.exports = isexe;
303232
303441
  isexe.sync = sync;
303233
- var fs$7 = __require("fs");
303442
+ var fs$8 = __require("fs");
303234
303443
  function isexe(path, options, cb) {
303235
- fs$7.stat(path, function(er, stat) {
303444
+ fs$8.stat(path, function(er, stat) {
303236
303445
  cb(er, er ? false : checkStat(stat, options));
303237
303446
  });
303238
303447
  }
303239
303448
  function sync(path, options) {
303240
- return checkStat(fs$7.statSync(path), options);
303449
+ return checkStat(fs$8.statSync(path), options);
303241
303450
  }
303242
303451
  function checkStat(stat, options) {
303243
303452
  return stat.isFile() && checkMode(stat, options);
@@ -303452,16 +303661,16 @@ var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) =
303452
303661
  //#endregion
303453
303662
  //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
303454
303663
  var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303455
- const fs$6 = __require("fs");
303664
+ const fs$7 = __require("fs");
303456
303665
  const shebangCommand = require_shebang_command();
303457
303666
  function readShebang(command) {
303458
303667
  const size = 150;
303459
303668
  const buffer = Buffer.alloc(size);
303460
303669
  let fd;
303461
303670
  try {
303462
- fd = fs$6.openSync(command, "r");
303463
- fs$6.readSync(fd, buffer, 0, size, 0);
303464
- fs$6.closeSync(fd);
303671
+ fd = fs$7.openSync(command, "r");
303672
+ fs$7.readSync(fd, buffer, 0, size, 0);
303673
+ fs$7.closeSync(fd);
303465
303674
  } catch (e) {}
303466
303675
  return shebangCommand(buffer.toString());
303467
303676
  }
@@ -337623,7 +337832,7 @@ var require_dist$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
337623
337832
  //#endregion
337624
337833
  //#region ../../node_modules/.pnpm/yazl@3.3.1/node_modules/yazl/index.js
337625
337834
  var require_yazl = /* @__PURE__ */ __commonJSMin(((exports) => {
337626
- var fs$5 = __require("fs");
337835
+ var fs$6 = __require("fs");
337627
337836
  var Transform$2 = __require("stream").Transform;
337628
337837
  var PassThrough$2 = __require("stream").PassThrough;
337629
337838
  var zlib$1 = __require("zlib");
@@ -337652,14 +337861,14 @@ var require_yazl = /* @__PURE__ */ __commonJSMin(((exports) => {
337652
337861
  if (shouldIgnoreAdding(self)) return;
337653
337862
  var entry = new Entry(metadataPath, false, options);
337654
337863
  self.entries.push(entry);
337655
- fs$5.stat(realPath, function(err, stats) {
337864
+ fs$6.stat(realPath, function(err, stats) {
337656
337865
  if (err) return self.emit("error", err);
337657
337866
  if (!stats.isFile()) return self.emit("error", /* @__PURE__ */ new Error("not a file: " + realPath));
337658
337867
  entry.uncompressedSize = stats.size;
337659
337868
  if (options.mtime == null) entry.setLastModDate(stats.mtime);
337660
337869
  if (options.mode == null) entry.setFileAttributesMode(stats.mode);
337661
337870
  entry.setFileDataPumpFunction(function() {
337662
- var readStream = fs$5.createReadStream(realPath);
337871
+ var readStream = fs$6.createReadStream(realPath);
337663
337872
  entry.state = Entry.FILE_DATA_IN_PROGRESS;
337664
337873
  readStream.on("error", function(err) {
337665
337874
  self.emit("error", err);
@@ -353525,7 +353734,7 @@ var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
353525
353734
  const EventEmitter$12 = __require("node:events").EventEmitter;
353526
353735
  const childProcess = __require("node:child_process");
353527
353736
  const path$7 = __require("node:path");
353528
- const fs$4 = __require("node:fs");
353737
+ const fs$5 = __require("node:fs");
353529
353738
  const process$2 = __require("node:process");
353530
353739
  const { Argument, humanReadableArgName } = require_argument();
353531
353740
  const { CommanderError } = require_error$2();
@@ -354408,7 +354617,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
354408
354617
  * @param {string} subcommandName
354409
354618
  */
354410
354619
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
354411
- if (fs$4.existsSync(executableFile)) return;
354620
+ if (fs$5.existsSync(executableFile)) return;
354412
354621
  const executableMissing = `'${executableFile}' does not exist
354413
354622
  - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
354414
354623
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
@@ -354432,9 +354641,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
354432
354641
  ];
354433
354642
  function findFile(baseDir, baseName) {
354434
354643
  const localBin = path$7.resolve(baseDir, baseName);
354435
- if (fs$4.existsSync(localBin)) return localBin;
354644
+ if (fs$5.existsSync(localBin)) return localBin;
354436
354645
  if (sourceExt.includes(path$7.extname(baseName))) return void 0;
354437
- const foundExt = sourceExt.find((ext) => fs$4.existsSync(`${localBin}${ext}`));
354646
+ const foundExt = sourceExt.find((ext) => fs$5.existsSync(`${localBin}${ext}`));
354438
354647
  if (foundExt) return `${localBin}${foundExt}`;
354439
354648
  }
354440
354649
  this._checkForMissingMandatoryOptions();
@@ -354444,7 +354653,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
354444
354653
  if (this._scriptPath) {
354445
354654
  let resolvedScriptPath;
354446
354655
  try {
354447
- resolvedScriptPath = fs$4.realpathSync(this._scriptPath);
354656
+ resolvedScriptPath = fs$5.realpathSync(this._scriptPath);
354448
354657
  } catch {
354449
354658
  resolvedScriptPath = this._scriptPath;
354450
354659
  }
@@ -372961,7 +373170,7 @@ var require_atomic_sleep = /* @__PURE__ */ __commonJSMin(((exports, module) => {
372961
373170
  //#endregion
372962
373171
  //#region ../../node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js
372963
373172
  var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
372964
- const fs$3 = __require("fs");
373173
+ const fs$4 = __require("fs");
372965
373174
  const EventEmitter$10 = __require("events");
372966
373175
  const inherits$6 = __require("util").inherits;
372967
373176
  const path$6 = __require("path");
@@ -373004,17 +373213,17 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373004
373213
  const flags = sonic.append ? "a" : "w";
373005
373214
  const mode = sonic.mode;
373006
373215
  if (sonic.sync) try {
373007
- if (sonic.mkdir) fs$3.mkdirSync(path$6.dirname(file), { recursive: true });
373008
- fileOpened(null, fs$3.openSync(file, flags, mode));
373216
+ if (sonic.mkdir) fs$4.mkdirSync(path$6.dirname(file), { recursive: true });
373217
+ fileOpened(null, fs$4.openSync(file, flags, mode));
373009
373218
  } catch (err) {
373010
373219
  fileOpened(err);
373011
373220
  throw err;
373012
373221
  }
373013
- else if (sonic.mkdir) fs$3.mkdir(path$6.dirname(file), { recursive: true }, (err) => {
373222
+ else if (sonic.mkdir) fs$4.mkdir(path$6.dirname(file), { recursive: true }, (err) => {
373014
373223
  if (err) return fileOpened(err);
373015
- fs$3.open(file, flags, mode, fileOpened);
373224
+ fs$4.open(file, flags, mode, fileOpened);
373016
373225
  });
373017
- else fs$3.open(file, flags, mode, fileOpened);
373226
+ else fs$4.open(file, flags, mode, fileOpened);
373018
373227
  }
373019
373228
  function SonicBoom(opts) {
373020
373229
  if (!(this instanceof SonicBoom)) return new SonicBoom(opts);
@@ -373052,8 +373261,8 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373052
373261
  this.flush = flushBuffer;
373053
373262
  this.flushSync = flushBufferSync;
373054
373263
  this._actualWrite = actualWriteBuffer;
373055
- fsWriteSync = () => fs$3.writeSync(this.fd, this._writingBuf);
373056
- fsWrite = () => fs$3.write(this.fd, this._writingBuf, this.release);
373264
+ fsWriteSync = () => fs$4.writeSync(this.fd, this._writingBuf);
373265
+ fsWrite = () => fs$4.write(this.fd, this._writingBuf, this.release);
373057
373266
  } else if (contentMode === void 0 || contentMode === kContentModeUtf8) {
373058
373267
  this._writingBuf = "";
373059
373268
  this.write = write;
@@ -373061,12 +373270,12 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373061
373270
  this.flushSync = flushSync;
373062
373271
  this._actualWrite = actualWrite;
373063
373272
  fsWriteSync = () => {
373064
- if (Buffer.isBuffer(this._writingBuf)) return fs$3.writeSync(this.fd, this._writingBuf);
373065
- return fs$3.writeSync(this.fd, this._writingBuf, "utf8");
373273
+ if (Buffer.isBuffer(this._writingBuf)) return fs$4.writeSync(this.fd, this._writingBuf);
373274
+ return fs$4.writeSync(this.fd, this._writingBuf, "utf8");
373066
373275
  };
373067
373276
  fsWrite = () => {
373068
- if (Buffer.isBuffer(this._writingBuf)) return fs$3.write(this.fd, this._writingBuf, this.release);
373069
- return fs$3.write(this.fd, this._writingBuf, "utf8", this.release);
373277
+ if (Buffer.isBuffer(this._writingBuf)) return fs$4.write(this.fd, this._writingBuf, this.release);
373278
+ return fs$4.write(this.fd, this._writingBuf, "utf8", this.release);
373070
373279
  };
373071
373280
  } else throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`);
373072
373281
  if (typeof fd === "number") {
@@ -373111,7 +373320,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373111
373320
  return;
373112
373321
  }
373113
373322
  }
373114
- if (this._fsync) fs$3.fsyncSync(this.fd);
373323
+ if (this._fsync) fs$4.fsyncSync(this.fd);
373115
373324
  const len = this._len;
373116
373325
  if (this._reopening) {
373117
373326
  this._writing = false;
@@ -373208,7 +373417,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373208
373417
  this._flushPending = true;
373209
373418
  const onDrain = () => {
373210
373419
  if (!this._fsync) try {
373211
- fs$3.fsync(this.fd, (err) => {
373420
+ fs$4.fsync(this.fd, (err) => {
373212
373421
  this._flushPending = false;
373213
373422
  cb(err);
373214
373423
  });
@@ -373285,7 +373494,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373285
373494
  if (this._writing) return;
373286
373495
  const fd = this.fd;
373287
373496
  this.once("ready", () => {
373288
- if (fd !== this.fd) fs$3.close(fd, (err) => {
373497
+ if (fd !== this.fd) fs$4.close(fd, (err) => {
373289
373498
  if (err) return this.emit("error", err);
373290
373499
  });
373291
373500
  });
@@ -373316,7 +373525,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373316
373525
  while (this._bufs.length || buf.length) {
373317
373526
  if (buf.length <= 0) buf = this._bufs[0];
373318
373527
  try {
373319
- const n = Buffer.isBuffer(buf) ? fs$3.writeSync(this.fd, buf) : fs$3.writeSync(this.fd, buf, "utf8");
373528
+ const n = Buffer.isBuffer(buf) ? fs$4.writeSync(this.fd, buf) : fs$4.writeSync(this.fd, buf, "utf8");
373320
373529
  const releasedBufObj = releaseWritingBuf(buf, this._len, n);
373321
373530
  buf = releasedBufObj.writingBuf;
373322
373531
  this._len = releasedBufObj.len;
@@ -373327,7 +373536,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373327
373536
  }
373328
373537
  }
373329
373538
  try {
373330
- fs$3.fsyncSync(this.fd);
373539
+ fs$4.fsyncSync(this.fd);
373331
373540
  } catch {}
373332
373541
  }
373333
373542
  function flushBufferSync() {
@@ -373341,7 +373550,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373341
373550
  while (this._bufs.length || buf.length) {
373342
373551
  if (buf.length <= 0) buf = mergeBuf(this._bufs[0], this._lens[0]);
373343
373552
  try {
373344
- const n = fs$3.writeSync(this.fd, buf);
373553
+ const n = fs$4.writeSync(this.fd, buf);
373345
373554
  buf = buf.subarray(n);
373346
373555
  this._len = Math.max(this._len - n, 0);
373347
373556
  if (buf.length <= 0) {
@@ -373363,24 +373572,24 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373363
373572
  this._writing = true;
373364
373573
  this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || "";
373365
373574
  if (this.sync) try {
373366
- release(null, Buffer.isBuffer(this._writingBuf) ? fs$3.writeSync(this.fd, this._writingBuf) : fs$3.writeSync(this.fd, this._writingBuf, "utf8"));
373575
+ release(null, Buffer.isBuffer(this._writingBuf) ? fs$4.writeSync(this.fd, this._writingBuf) : fs$4.writeSync(this.fd, this._writingBuf, "utf8"));
373367
373576
  } catch (err) {
373368
373577
  release(err);
373369
373578
  }
373370
- else fs$3.write(this.fd, this._writingBuf, release);
373579
+ else fs$4.write(this.fd, this._writingBuf, release);
373371
373580
  }
373372
373581
  function actualWriteBuffer() {
373373
373582
  const release = this.release;
373374
373583
  this._writing = true;
373375
373584
  this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift());
373376
373585
  if (this.sync) try {
373377
- release(null, fs$3.writeSync(this.fd, this._writingBuf));
373586
+ release(null, fs$4.writeSync(this.fd, this._writingBuf));
373378
373587
  } catch (err) {
373379
373588
  release(err);
373380
373589
  }
373381
373590
  else {
373382
373591
  if (kCopyBuffer) this._writingBuf = Buffer.from(this._writingBuf);
373383
- fs$3.write(this.fd, this._writingBuf, release);
373592
+ fs$4.write(this.fd, this._writingBuf, release);
373384
373593
  }
373385
373594
  }
373386
373595
  function actualClose(sonic) {
@@ -373394,10 +373603,10 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373394
373603
  sonic._lens = [];
373395
373604
  assert$8(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`);
373396
373605
  try {
373397
- fs$3.fsync(sonic.fd, closeWrapped);
373606
+ fs$4.fsync(sonic.fd, closeWrapped);
373398
373607
  } catch {}
373399
373608
  function closeWrapped() {
373400
- if (sonic.fd !== 1 && sonic.fd !== 2) fs$3.close(sonic.fd, done);
373609
+ if (sonic.fd !== 1 && sonic.fd !== 2) fs$4.close(sonic.fd, done);
373401
373610
  else done();
373402
373611
  }
373403
373612
  function done(err) {
@@ -416074,7 +416283,7 @@ var require_dist$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
416074
416283
  //#region ../../node_modules/.pnpm/@fastify+swagger@9.7.0/node_modules/@fastify/swagger/lib/mode/static.js
416075
416284
  var require_static = /* @__PURE__ */ __commonJSMin(((exports, module) => {
416076
416285
  const path$4 = __require("node:path");
416077
- const fs$2 = __require("node:fs");
416286
+ const fs$3 = __require("node:fs");
416078
416287
  const yaml = require_dist$1();
416079
416288
  module.exports = function(fastify, opts, done) {
416080
416289
  if (!opts.specification) return done(/* @__PURE__ */ new Error("specification is missing in the module options"));
@@ -416083,14 +416292,14 @@ var require_static = /* @__PURE__ */ __commonJSMin(((exports, module) => {
416083
416292
  if (!opts.specification.path && !opts.specification.document) return done(/* @__PURE__ */ new Error("both specification.path and specification.document are missing, should be path to the file or swagger document spec"));
416084
416293
  else if (opts.specification.path) {
416085
416294
  if (typeof opts.specification.path !== "string") return done(/* @__PURE__ */ new Error("specification.path is not a string"));
416086
- if (!fs$2.existsSync(path$4.resolve(opts.specification.path))) return done(/* @__PURE__ */ new Error(`${opts.specification.path} does not exist`));
416295
+ if (!fs$3.existsSync(path$4.resolve(opts.specification.path))) return done(/* @__PURE__ */ new Error(`${opts.specification.path} does not exist`));
416087
416296
  const extName = path$4.extname(opts.specification.path).toLowerCase();
416088
416297
  if ([".yaml", ".json"].indexOf(extName) === -1) return done(/* @__PURE__ */ new Error("specification.path extension name is not supported, should be one from ['.yaml', '.json']"));
416089
416298
  if (opts.specification.postProcessor && typeof opts.specification.postProcessor !== "function") return done(/* @__PURE__ */ new Error("specification.postProcessor should be a function"));
416090
416299
  if (opts.specification.baseDir && typeof opts.specification.baseDir !== "string") return done(/* @__PURE__ */ new Error("specification.baseDir should be string"));
416091
416300
  if (!opts.specification.baseDir) opts.specification.baseDir = path$4.resolve(path$4.dirname(opts.specification.path));
416092
416301
  else while (opts.specification.baseDir.endsWith("/")) opts.specification.baseDir = opts.specification.baseDir.slice(0, -1);
416093
- const source = fs$2.readFileSync(path$4.resolve(opts.specification.path), "utf8");
416302
+ const source = fs$3.readFileSync(path$4.resolve(opts.specification.path), "utf8");
416094
416303
  switch (extName) {
416095
416304
  case ".yaml":
416096
416305
  swaggerObject = yaml.parse(source);
@@ -416357,11 +416566,11 @@ var require_should_route_hide = /* @__PURE__ */ __commonJSMin(((exports, module)
416357
416566
  //#endregion
416358
416567
  //#region ../../node_modules/.pnpm/@fastify+swagger@9.7.0/node_modules/@fastify/swagger/lib/util/read-package-json.js
416359
416568
  var require_read_package_json = /* @__PURE__ */ __commonJSMin(((exports, module) => {
416360
- const fs$1 = __require("node:fs");
416569
+ const fs$2 = __require("node:fs");
416361
416570
  const path$3 = __require("node:path");
416362
416571
  function readPackageJson() {
416363
416572
  try {
416364
- return JSON.parse(fs$1.readFileSync(path$3.join(__dirname, "..", "..", "package.json")));
416573
+ return JSON.parse(fs$2.readFileSync(path$3.join(__dirname, "..", "..", "package.json")));
416365
416574
  } catch {
416366
416575
  return {};
416367
416576
  }
@@ -426195,7 +426404,11 @@ function createLocalToolEventRecorder(homeDir, sessionId, enabled = localToolEve
426195
426404
  if (event.type === "tool.call.started") {
426196
426405
  if (!TOOL_NAME.test(event.name) || !TOOL_NAME.test(event.agentId)) return;
426197
426406
  if (pending.size >= MAX_PENDING_CALLS) pending.delete(pending.keys().next().value);
426198
- pending.set(event.toolCallId, {
426407
+ pending.set(JSON.stringify([
426408
+ event.agentId,
426409
+ event.turnId,
426410
+ event.toolCallId
426411
+ ]), {
426199
426412
  agentId: event.agentId,
426200
426413
  turnId: event.turnId,
426201
426414
  tool: event.name,
@@ -426204,9 +426417,14 @@ function createLocalToolEventRecorder(homeDir, sessionId, enabled = localToolEve
426204
426417
  return;
426205
426418
  }
426206
426419
  if (event.type !== "tool.result") return;
426207
- const started = pending.get(event.toolCallId);
426420
+ const key = JSON.stringify([
426421
+ event.agentId,
426422
+ event.turnId,
426423
+ event.toolCallId
426424
+ ]);
426425
+ const started = pending.get(key);
426208
426426
  if (started === void 0 || started.agentId !== event.agentId || started.turnId !== event.turnId) return;
426209
- pending.delete(event.toolCallId);
426427
+ pending.delete(key);
426210
426428
  const record = {
426211
426429
  version: 1,
426212
426430
  sessionId,
@@ -426591,9 +426809,22 @@ const savedSearchResultSchema = object$1({ personal_memory: object$1({ saved: ar
426591
426809
  async function bindPersonalMemoryHostTools(session, harness, options = {}) {
426592
426810
  if (!supportsPersonalMemoryHostTools(session)) return;
426593
426811
  const binding = Object.prototype.hasOwnProperty.call(options, "binding") ? options.binding : personalMemoryHostBinding();
426594
- await clearPersonalMemoryHostTools(session);
426595
426812
  const localHistory = options.localHistory;
426596
426813
  const localOnlyEnabled = localHistory !== void 0 && localToolEventRecordingEnabled(localHistory.homeDir);
426814
+ const savedSearchEnabled = binding?.mode === "full" && binding.capabilities.recallEnabled;
426815
+ if (options.searchOnly) {
426816
+ await session.unregisterToolAndWait(PERSONAL_MEMORY_SEARCH_TOOL);
426817
+ if (localHistory === void 0 || !savedSearchEnabled && !localOnlyEnabled) return;
426818
+ const searchClient = savedSearchEnabled ? options.client ?? createPersonalMemoryBrokerClient(harness) : void 0;
426819
+ try {
426820
+ await registerPersonalMemorySearchTool(session, localHistory, searchClient, binding, savedSearchEnabled, localOnlyEnabled);
426821
+ } catch (error) {
426822
+ await session.unregisterToolAndWait(PERSONAL_MEMORY_SEARCH_TOOL).catch(() => {});
426823
+ throw error;
426824
+ }
426825
+ return;
426826
+ }
426827
+ await clearPersonalMemoryHostTools(session);
426597
426828
  if (binding === void 0 && !localOnlyEnabled) return;
426598
426829
  const client = binding === void 0 ? void 0 : options.client ?? createPersonalMemoryBrokerClient(harness);
426599
426830
  const context = binding === void 0 ? void 0 : {
@@ -426606,43 +426837,8 @@ async function bindPersonalMemoryHostTools(session, harness, options = {}) {
426606
426837
  const definition = personalMemoryToolDefinition(name);
426607
426838
  await session.registerToolAndWait(qualifiedPersonalMemoryToolName(name), definition.description, definition.parameters, createHostHandler(client, name, context, name === "memory_settings_update" ? () => refreshPersonalMemoryBinding(session, harness, client, localHistory) : void 0));
426608
426839
  }
426609
- const savedSearchEnabled = binding?.mode === "full" && binding.capabilities.recallEnabled;
426610
426840
  if (savedSearchEnabled) session.setHostToolCallHandler(PERSONAL_MEMORY_HOST_RECALL_HANDLER, createHostHandler(client, "memory_recall", context));
426611
- if (localHistory !== void 0 && (savedSearchEnabled || localOnlyEnabled)) await session.registerToolAndWait(PERSONAL_MEMORY_SEARCH_TOOL, "Search saved memories when enabled and this local profile's past work only when the user asks about prior work. Never use for routine recall.", toJSONSchema(searchInputSchema, { target: "draft-7" }), async (request) => {
426612
- const parsed = searchInputSchema.safeParse(request.args);
426613
- if (!parsed.success || !consumeWorkHistorySearchIntent(request)) return {
426614
- output: "EXPLICIT_HISTORY_REQUEST_REQUIRED",
426615
- isError: true
426616
- };
426617
- try {
426618
- const sessions = localHistory.listSessions({ includeArchive: true });
426619
- const [savedResult, workHistoryResult, toolEventsResult] = await Promise.allSettled([
426620
- savedSearchEnabled ? invokePersonalMemoryTool(client, "memory_recall", parsed.data, context) : Promise.resolve(void 0),
426621
- sessions.then((list) => searchLocalWorkHistory(localHistory.homeDir, list, parsed.data.query, parsed.data.limit)),
426622
- sessions.then((list) => searchLocalToolEvents(localHistory.homeDir, list, parsed.data.query, parsed.data.limit))
426623
- ]);
426624
- const saved = savedSearchEnabled && savedResult.status === "fulfilled" ? savedSearchResultSchema.safeParse(savedResult.value) : void 0;
426625
- const savedAvailable = saved?.success === true;
426626
- if (!savedAvailable && workHistoryResult.status === "rejected" && toolEventsResult.status === "rejected") return {
426627
- output: "MEMORY_SEARCH_UNAVAILABLE",
426628
- isError: true
426629
- };
426630
- return { output: JSON.stringify({
426631
- saved: savedAvailable ? previewSavedSearchResult(saved.data) : null,
426632
- savedAvailable,
426633
- workHistory: workHistoryResult.status === "fulfilled" ? workHistoryResult.value : null,
426634
- workHistoryAvailable: workHistoryResult.status === "fulfilled",
426635
- toolEvents: toolEventsResult.status === "fulfilled" ? toolEventsResult.value : null,
426636
- toolEventsAvailable: toolEventsResult.status === "fulfilled",
426637
- toolEventRecordingEnabled: localOnlyEnabled
426638
- }) };
426639
- } catch {
426640
- return {
426641
- output: "MEMORY_SEARCH_UNAVAILABLE",
426642
- isError: true
426643
- };
426644
- }
426645
- });
426841
+ if (localHistory !== void 0 && (savedSearchEnabled || localOnlyEnabled)) await registerPersonalMemorySearchTool(session, localHistory, client, binding, savedSearchEnabled, localOnlyEnabled);
426646
426842
  if (binding !== void 0) await session.setPersonalMemoryHostCapability(true);
426647
426843
  } catch (error) {
426648
426844
  resetPersonalMemorySession();
@@ -426650,6 +426846,47 @@ async function bindPersonalMemoryHostTools(session, harness, options = {}) {
426650
426846
  throw error;
426651
426847
  }
426652
426848
  }
426849
+ async function registerPersonalMemorySearchTool(session, localHistory, client, binding, savedSearchEnabled, localOnlyEnabled) {
426850
+ const context = binding === void 0 ? void 0 : {
426851
+ mode: binding.mode,
426852
+ capabilities: binding.capabilities
426853
+ };
426854
+ await session.registerToolAndWait(PERSONAL_MEMORY_SEARCH_TOOL, "Search saved memories when enabled and this local profile's past work only when the user asks about prior work. Never use for routine recall.", toJSONSchema(searchInputSchema, { target: "draft-7" }), async (request) => {
426855
+ const parsed = searchInputSchema.safeParse(request.args);
426856
+ if (!parsed.success || !consumeWorkHistorySearchIntent(request)) return {
426857
+ output: "EXPLICIT_HISTORY_REQUEST_REQUIRED",
426858
+ isError: true
426859
+ };
426860
+ try {
426861
+ const sessions = localHistory.listSessions({ includeArchive: true });
426862
+ const [savedResult, workHistoryResult, toolEventsResult] = await Promise.allSettled([
426863
+ savedSearchEnabled ? invokePersonalMemoryTool(client, "memory_recall", parsed.data, context) : Promise.resolve(void 0),
426864
+ sessions.then((list) => searchLocalWorkHistory(localHistory.homeDir, list, parsed.data.query, parsed.data.limit)),
426865
+ sessions.then((list) => searchLocalToolEvents(localHistory.homeDir, list, parsed.data.query, parsed.data.limit))
426866
+ ]);
426867
+ const saved = savedSearchEnabled && savedResult.status === "fulfilled" ? savedSearchResultSchema.safeParse(savedResult.value) : void 0;
426868
+ const savedAvailable = saved?.success === true;
426869
+ if (!savedAvailable && workHistoryResult.status === "rejected" && toolEventsResult.status === "rejected") return {
426870
+ output: "MEMORY_SEARCH_UNAVAILABLE",
426871
+ isError: true
426872
+ };
426873
+ return { output: JSON.stringify({
426874
+ saved: savedAvailable ? previewSavedSearchResult(saved.data) : null,
426875
+ savedAvailable,
426876
+ workHistory: workHistoryResult.status === "fulfilled" ? workHistoryResult.value : null,
426877
+ workHistoryAvailable: workHistoryResult.status === "fulfilled",
426878
+ toolEvents: toolEventsResult.status === "fulfilled" ? toolEventsResult.value : null,
426879
+ toolEventsAvailable: toolEventsResult.status === "fulfilled",
426880
+ toolEventRecordingEnabled: localOnlyEnabled
426881
+ }) };
426882
+ } catch {
426883
+ return {
426884
+ output: "MEMORY_SEARCH_UNAVAILABLE",
426885
+ isError: true
426886
+ };
426887
+ }
426888
+ });
426889
+ }
426653
426890
  function previewSavedSearchResult(result) {
426654
426891
  return { personal_memory: {
426655
426892
  saved: result.personal_memory.saved.map(({ text, confidence }) => {
@@ -433263,7 +433500,7 @@ var TUI = class TUI extends Container {
433263
433500
  if (!debugRedraw) return;
433264
433501
  const logPath = path$17.join(nodeOs.homedir(), ".pi", "agent", "pi-debug.log");
433265
433502
  const msg = `[${(/* @__PURE__ */ new Date()).toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
433266
- fs$16.appendFileSync(logPath, msg);
433503
+ fs$17.appendFileSync(logPath, msg);
433267
433504
  };
433268
433505
  if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
433269
433506
  logRedraw("first render");
@@ -433410,7 +433647,7 @@ var TUI = class TUI extends Container {
433410
433647
  buffer += "\x1B[?2026l";
433411
433648
  if (process.env["PI_TUI_DEBUG"] === "1") {
433412
433649
  const debugDir = "/tmp/tui";
433413
- fs$16.mkdirSync(debugDir, { recursive: true });
433650
+ fs$17.mkdirSync(debugDir, { recursive: true });
433414
433651
  const debugPath = path$17.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
433415
433652
  const debugData = [
433416
433653
  `firstChanged: ${firstChanged}`,
@@ -433434,7 +433671,7 @@ var TUI = class TUI extends Container {
433434
433671
  "=== buffer ===",
433435
433672
  JSON.stringify(buffer)
433436
433673
  ].join("\n");
433437
- fs$16.writeFileSync(debugPath, debugData);
433674
+ fs$17.writeFileSync(debugPath, debugData);
433438
433675
  }
433439
433676
  this.terminal.write(buffer);
433440
433677
  this.cursorRow = Math.max(0, newLines.length - 1);
@@ -438098,7 +438335,7 @@ var ProcessTerminal = class {
438098
438335
  const env = process.env["PI_TUI_WRITE_LOG"] || "";
438099
438336
  if (!env) return "";
438100
438337
  try {
438101
- if (fs$16.statSync(env).isDirectory()) {
438338
+ if (fs$17.statSync(env).isDirectory()) {
438102
438339
  const now = /* @__PURE__ */ new Date();
438103
438340
  const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}-${String(now.getMinutes()).padStart(2, "0")}-${String(now.getSeconds()).padStart(2, "0")}`;
438104
438341
  return path$17.join(env, `tui-${ts}-${process.pid}.log`);
@@ -438381,7 +438618,7 @@ var ProcessTerminal = class {
438381
438618
  write(data) {
438382
438619
  process.stdout.write(data);
438383
438620
  if (this.writeLogPath) try {
438384
- fs$16.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
438621
+ fs$17.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
438385
438622
  } catch {}
438386
438623
  }
438387
438624
  get columns() {
@@ -505477,11 +505714,15 @@ async function showContextReport(host, detailed) {
505477
505714
  const sources = detailed !== "map" && request?.systemPromptContributions?.version === 1 ? request.systemPromptContributions : void 0;
505478
505715
  const instructionSources = detailed === true && sources?.instructionSources?.version === 1 ? sources.instructionSources : void 0;
505479
505716
  const skillSources = detailed === true && sources?.skillListingSources?.version === 1 ? sources.skillListingSources : void 0;
505480
- const files = instructionSources?.files.map((file) => ({
505717
+ const files = instructionSources === void 0 ? void 0 : [...instructionSources.files.map((file) => ({
505481
505718
  path: diagnosticLabel(file.path),
505482
505719
  bytes: validTextSize(file.bytes),
505483
505720
  sourceTextBytes: validTextSize(file.sourceTextBytes)
505484
- }));
505721
+ })), ...(instructionSources.notLoadedCandidates ?? []).map((path) => ({
505722
+ path: diagnosticLabel(path),
505723
+ bytes: 0,
505724
+ sourceTextBytes: void 0
505725
+ }))];
505485
505726
  const memorySource = detailed === true ? sources?.runtimeMemorySource : void 0;
505486
505727
  const origins = detailed === true && request?.historyTextOrigins?.version === 1 && request.historyTextOrigins.unit === "utf8-text" ? request.historyTextOrigins : void 0;
505487
505728
  const lastRequest = request === void 0 ? void 0 : {
@@ -512178,7 +512419,8 @@ async function handleMemoryCommand(host, args, dependencies) {
512178
512419
  const enabled = parsed.action === "on";
512179
512420
  await setLocalToolEventRecordingEnabled(host.harness.homeDir, enabled);
512180
512421
  host.setLocalToolEventRecordingEnabled?.(enabled);
512181
- await host.refreshPersonalMemory?.(false);
512422
+ if (host.refreshLocalToolSearch !== void 0) await host.refreshLocalToolSearch();
512423
+ else await host.refreshPersonalMemory?.(false);
512182
512424
  }
512183
512425
  host.showStatus(`/memory tools ${localToolEventRecordingEnabled(host.harness.homeDir) ? "enabled" : "disabled"}`);
512184
512426
  return;
@@ -532647,6 +532889,28 @@ var PersonalMemoryController = class {
532647
532889
  this.queue = run.then(() => {}, () => {});
532648
532890
  return run;
532649
532891
  }
532892
+ refreshLocalToolSearch() {
532893
+ const generation = this.generation;
532894
+ const session = this.host.session;
532895
+ const refresh = async () => {
532896
+ if (!this.isCurrent(generation, session)) return "stale";
532897
+ if (session === void 0) return "unavailable";
532898
+ try {
532899
+ await this.dependencies.bindTools(session, this.host.harness, {
532900
+ binding: personalMemoryHostBinding(),
532901
+ localHistory: this.host.harness,
532902
+ searchOnly: true
532903
+ });
532904
+ return this.isCurrent(generation, session) ? "ready" : "stale";
532905
+ } catch {
532906
+ await this.dependencies.clearTools(session).catch(() => {});
532907
+ return "unavailable";
532908
+ }
532909
+ };
532910
+ const run = this.queue.then(refresh, refresh);
532911
+ this.queue = run.then(() => {}, () => {});
532912
+ return run;
532913
+ }
532650
532914
  clear(session = this.host.session) {
532651
532915
  ++this.generation;
532652
532916
  const run = this.queue.then(async () => {
@@ -544585,6 +544849,9 @@ var BlunTUI = class {
544585
544849
  async refreshPersonalMemory(promptIfNeverAsked = false) {
544586
544850
  await this.personalMemoryController.refresh({ promptIfNeverAsked });
544587
544851
  }
544852
+ async refreshLocalToolSearch() {
544853
+ await this.personalMemoryController.refreshLocalToolSearch();
544854
+ }
544588
544855
  setLocalToolEventRecordingEnabled(enabled) {
544589
544856
  this.sessionEventHandler.setLocalToolEventRecordingEnabled(enabled);
544590
544857
  }
@@ -546066,7 +546333,7 @@ var BlunTUI = class {
546066
546333
  //#endregion
546067
546334
  //#region src/constant/update.ts
546068
546335
  var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
546069
- const fs = __require("node:fs");
546336
+ const fs$1 = __require("node:fs");
546070
546337
  const os$1 = __require("node:os");
546071
546338
  const path$2 = __require("node:path");
546072
546339
  const DEFAULT_MAX_BYTES = 1024 * 1024;
@@ -546120,7 +546387,7 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546120
546387
  return record;
546121
546388
  }
546122
546389
  function directoryIdentity(directory) {
546123
- const stat = fs.lstatSync(directory, { bigint: true });
546390
+ const stat = fs$1.lstatSync(directory, { bigint: true });
546124
546391
  if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Unsafe exit directory");
546125
546392
  return stat;
546126
546393
  }
@@ -546132,16 +546399,16 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546132
546399
  return stat;
546133
546400
  }
546134
546401
  function trimLedger(descriptor, maxBytes, retainBytes, incomingBytes) {
546135
- const size = Number(regularLedger(fs.fstatSync(descriptor, { bigint: true })).size);
546402
+ const size = Number(regularLedger(fs$1.fstatSync(descriptor, { bigint: true })).size);
546136
546403
  if (!Number.isSafeInteger(size)) throw new Error("Invalid exit ledger size");
546137
546404
  if (size + incomingBytes <= maxBytes) return;
546138
546405
  const keepBytes = Math.max(0, Math.min(size, retainBytes, maxBytes - incomingBytes));
546139
546406
  const contents = Buffer.alloc(keepBytes);
546140
- const read = fs.readSync(descriptor, contents, 0, keepBytes, size - keepBytes);
546407
+ const read = fs$1.readSync(descriptor, contents, 0, keepBytes, size - keepBytes);
546141
546408
  const tail = contents.subarray(0, read);
546142
546409
  const lineStart = size > keepBytes ? tail.indexOf(10) + 1 : 0;
546143
- fs.ftruncateSync(descriptor, 0);
546144
- fs.writeFileSync(descriptor, lineStart > 0 || size === keepBytes ? tail.subarray(lineStart) : "");
546410
+ fs$1.ftruncateSync(descriptor, 0);
546411
+ fs$1.writeFileSync(descriptor, lineStart > 0 || size === keepBytes ? tail.subarray(lineStart) : "");
546145
546412
  }
546146
546413
  function recordRuntimeExit(input = {}) {
546147
546414
  let descriptor;
@@ -546149,7 +546416,7 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546149
546416
  try {
546150
546417
  const homeDir = typeof input.homeDir === "string" ? input.homeDir.trim() : "";
546151
546418
  if (!homeDir || !path$2.isAbsolute(homeDir)) return false;
546152
- fs.mkdirSync(homeDir, {
546419
+ fs$1.mkdirSync(homeDir, {
546153
546420
  recursive: true,
546154
546421
  mode: 448
546155
546422
  });
@@ -546157,21 +546424,21 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546157
546424
  const file = runtimeExitLedgerPath(homeDir);
546158
546425
  const directory = path$2.dirname(file);
546159
546426
  try {
546160
- fs.mkdirSync(directory, { mode: 448 });
546427
+ fs$1.mkdirSync(directory, { mode: 448 });
546161
546428
  } catch (error) {
546162
546429
  if (error.code !== "EEXIST") throw error;
546163
546430
  }
546164
546431
  const directoryStat = directoryIdentity(directory);
546165
546432
  let before;
546166
546433
  try {
546167
- before = regularLedger(fs.lstatSync(file, { bigint: true }));
546434
+ before = regularLedger(fs$1.lstatSync(file, { bigint: true }));
546168
546435
  } catch (error) {
546169
546436
  if (error.code !== "ENOENT") throw error;
546170
546437
  }
546171
- const flags = fs.constants.O_RDWR | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0) | (before ? 0 : fs.constants.O_CREAT | fs.constants.O_EXCL);
546172
- descriptor = fs.openSync(file, flags, 384);
546173
- const opened = regularLedger(fs.fstatSync(descriptor, { bigint: true }));
546174
- if (before && !sameIdentity(before, opened) || !sameIdentity(opened, regularLedger(fs.lstatSync(file, { bigint: true }))) || !sameIdentity(homeIdentity, directoryIdentity(homeDir)) || !sameIdentity(directoryStat, directoryIdentity(directory))) throw new Error("Exit ledger changed");
546438
+ const flags = fs$1.constants.O_RDWR | (fs$1.constants.O_NOFOLLOW ?? 0) | (fs$1.constants.O_NONBLOCK ?? 0) | (before ? 0 : fs$1.constants.O_CREAT | fs$1.constants.O_EXCL);
546439
+ descriptor = fs$1.openSync(file, flags, 384);
546440
+ const opened = regularLedger(fs$1.fstatSync(descriptor, { bigint: true }));
546441
+ if (before && !sameIdentity(before, opened) || !sameIdentity(opened, regularLedger(fs$1.lstatSync(file, { bigint: true }))) || !sameIdentity(homeIdentity, directoryIdentity(homeDir)) || !sameIdentity(directoryStat, directoryIdentity(directory))) throw new Error("Exit ledger changed");
546175
546442
  const maxBytes = Math.max(1024, Number.isInteger(input.maxBytes) ? input.maxBytes : DEFAULT_MAX_BYTES);
546176
546443
  const retainBytes = Math.max(0, Number.isInteger(input.retainBytes) ? input.retainBytes : DEFAULT_RETAIN_BYTES);
546177
546444
  const record = buildRuntimeExitRecord(input);
@@ -546194,21 +546461,21 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546194
546461
  line = `${JSON.stringify(record)}\n`;
546195
546462
  }
546196
546463
  trimLedger(descriptor, maxBytes, retainBytes, Buffer.byteLength(line));
546197
- appendDescriptor = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
546198
- if (!sameIdentity(opened, regularLedger(fs.fstatSync(appendDescriptor, { bigint: true }))) || !sameIdentity(opened, regularLedger(fs.lstatSync(file, { bigint: true }))) || !sameIdentity(homeIdentity, directoryIdentity(homeDir)) || !sameIdentity(directoryStat, directoryIdentity(directory))) throw new Error("Exit ledger changed");
546199
- fs.appendFileSync(appendDescriptor, line, { encoding: "utf8" });
546464
+ appendDescriptor = fs$1.openSync(file, fs$1.constants.O_WRONLY | fs$1.constants.O_APPEND | (fs$1.constants.O_NOFOLLOW ?? 0) | (fs$1.constants.O_NONBLOCK ?? 0));
546465
+ if (!sameIdentity(opened, regularLedger(fs$1.fstatSync(appendDescriptor, { bigint: true }))) || !sameIdentity(opened, regularLedger(fs$1.lstatSync(file, { bigint: true }))) || !sameIdentity(homeIdentity, directoryIdentity(homeDir)) || !sameIdentity(directoryStat, directoryIdentity(directory))) throw new Error("Exit ledger changed");
546466
+ fs$1.appendFileSync(appendDescriptor, line, { encoding: "utf8" });
546200
546467
  try {
546201
- fs.fchmodSync(descriptor, 384);
546468
+ fs$1.fchmodSync(descriptor, 384);
546202
546469
  } catch {}
546203
546470
  return true;
546204
546471
  } catch {
546205
546472
  return false;
546206
546473
  } finally {
546207
546474
  if (appendDescriptor !== void 0) try {
546208
- fs.closeSync(appendDescriptor);
546475
+ fs$1.closeSync(appendDescriptor);
546209
546476
  } catch {}
546210
546477
  if (descriptor !== void 0) try {
546211
- fs.closeSync(descriptor);
546478
+ fs$1.closeSync(descriptor);
546212
546479
  } catch {}
546213
546480
  }
546214
546481
  }
@@ -546346,6 +546613,7 @@ async function runShell(opts, version, updateStartupNotice) {
546346
546613
  }
546347
546614
  });
546348
546615
  log.info("blun starting", {
546616
+ pid: process.pid,
546349
546617
  version,
546350
546618
  uiMode: CLI_UI_MODE,
546351
546619
  nodeVersion: process.version,
@@ -546472,11 +546740,16 @@ async function runShell(opts, version, updateStartupNotice) {
546472
546740
  const initMs = Date.now() - initStartedAt;
546473
546741
  const startupSessionId = tui.getCurrentSessionId();
546474
546742
  const mcpMs = await tui.getStartupMcpMs();
546475
- trackLifecycleForSession(startupSessionId, "startup_perf", {
546743
+ const startupPerformance = {
546476
546744
  duration_ms: Date.now() - startedAt,
546477
546745
  config_ms: configMs,
546478
546746
  init_ms: initMs,
546479
546747
  mcp_ms: mcpMs
546748
+ };
546749
+ trackLifecycleForSession(startupSessionId, "startup_perf", startupPerformance);
546750
+ log.info("startup performance", {
546751
+ pid: process.pid,
546752
+ ...startupPerformance
546480
546753
  });
546481
546754
  } catch (error) {
546482
546755
  removeCrashHandlers();