blun-king-cli 9.1.612 → 9.1.614

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,27 +1,28 @@
1
1
  #!/usr/bin/env node
2
- // BLUN_BUILD_INPUT_SHA256:f9f2527561c5e5ec1afc53eef27313667c4d323a444532439e73a66865340f69
2
+ // BLUN_BUILD_INPUT_SHA256:8cd22e70289533171a13424a0ac5703315b0efc0c63f381d08987a054e6e2f00
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
8
  import crypto$1, { createHash, createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
9
- import * as fs$17 from "node:fs";
9
+ import * as fs$16 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
- import * as path$17 from "node:path";
11
+ import * as path$16 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 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";
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";
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";
18
18
  import { Worker } from "node:worker_threads";
19
19
  import * as sysPath from "path";
20
- import path$1, { basename as basename$1, dirname as dirname$1, join as join$1, parse as parse$1 } from "path";
20
+ import js, { basename as basename$1, dirname as dirname$1, join as join$1, parse as parse$1 } from "path";
21
21
  import I, { existsSync as existsSync$1, promises as promises$1, readdirSync as readdirSync$1, stat as stat$1, statSync as statSync$1, unwatchFile, watch, watchFile } from "fs";
22
22
  import { Readable } from "stream";
23
23
  import zi from "assert";
24
24
  import Qr, { EventEmitter } from "events";
25
+ import { StringDecoder } from "node:string_decoder";
25
26
  import { lstat as lstat$1, open as open$1, readdir as readdir$1, realpath as realpath$1, stat as stat$2 } from "fs/promises";
26
27
  import Cs, { PassThrough, Readable as Readable$1, Writable, pipeline } from "node:stream";
27
28
  import { homedir as homedir$1, type as type$1 } from "os";
@@ -37,7 +38,6 @@ import * as win32Path from "node:path/win32";
37
38
  import { createServer } from "node:http";
38
39
  import { pipeline as pipeline$1 } from "node:stream/promises";
39
40
  import { EventEmitter as EventEmitter$1 } from "node:events";
40
- import { StringDecoder } from "node:string_decoder";
41
41
  import co from "node:assert";
42
42
  import { fileURLToPath, pathToFileURL } from "node:url";
43
43
  import { QuickJSAsyncWASMModule, RELEASE_ASYNC, newQuickJSAsyncWASMModule, shouldInterruptAfterDeadline } from "quickjs-emscripten";
@@ -1211,7 +1211,7 @@ function normalizeBlunToolSchema(schema) {
1211
1211
  }
1212
1212
  function ensureBlunPropertyTypes(schema) {
1213
1213
  const normalized = cloneJsonValue(schema);
1214
- if (!isRecord$29(normalized)) throw new Error("JSON Schema root must normalize to an object.");
1214
+ if (!isRecord$33(normalized)) throw new Error("JSON Schema root must normalize to an object.");
1215
1215
  recurseSchema(normalized);
1216
1216
  return normalized;
1217
1217
  }
@@ -1272,7 +1272,7 @@ function resolveLocalJsonPointer(root, ref) {
1272
1272
  let current = root;
1273
1273
  for (const rawPart of ref.slice(2).split("/")) {
1274
1274
  const part = unescapeJsonPointerPart(rawPart);
1275
- if (isRecord$29(current)) {
1275
+ if (isRecord$33(current)) {
1276
1276
  if (!hasOwn(current, part)) return { found: false };
1277
1277
  current = current[part];
1278
1278
  } else if (Array.isArray(current)) {
@@ -1294,20 +1294,20 @@ function parseJsonPointerArrayIndex(part) {
1294
1294
  return Number(part);
1295
1295
  }
1296
1296
  function recurseSchema(node) {
1297
- if (!isRecord$29(node)) return;
1297
+ if (!isRecord$33(node)) return;
1298
1298
  visitChildSchemas(node, normalizeProperty);
1299
1299
  }
1300
1300
  function visitChildSchemas(node, visit) {
1301
1301
  for (const { key, kind } of CHILD_SCHEMA_SLOTS) {
1302
1302
  const value = node[key];
1303
1303
  if (kind === "single") {
1304
- if (isRecord$29(value)) visit(value);
1304
+ if (isRecord$33(value)) visit(value);
1305
1305
  } else if (kind === "array") {
1306
1306
  if (Array.isArray(value)) for (const item of value) visit(item);
1307
1307
  } else if (kind === "map") {
1308
- if (isRecord$29(value)) for (const item of Object.values(value)) visit(item);
1308
+ if (isRecord$33(value)) for (const item of Object.values(value)) visit(item);
1309
1309
  } else if (kind === "schema-or-array") {
1310
- if (isRecord$29(value)) visit(value);
1310
+ if (isRecord$33(value)) visit(value);
1311
1311
  else if (Array.isArray(value)) for (const item of value) visit(item);
1312
1312
  }
1313
1313
  }
@@ -1319,7 +1319,7 @@ function childSchemaKeysForParentType(parentType) {
1319
1319
  });
1320
1320
  }
1321
1321
  function normalizeProperty(node) {
1322
- if (!isRecord$29(node)) return;
1322
+ if (!isRecord$33(node)) return;
1323
1323
  if (!hasOwn(node, "type") && !hasAnyKey(node, TYPE_COMPLETION_SKIP_KEYS)) {
1324
1324
  const enumValues = node["enum"];
1325
1325
  if (Array.isArray(enumValues) && enumValues.length > 0) node["type"] = inferTypeFromValues(enumValues);
@@ -1403,14 +1403,14 @@ function hasAnyKey(obj, keys) {
1403
1403
  }
1404
1404
  function cloneJsonValue(value) {
1405
1405
  if (Array.isArray(value)) return value.map((item) => cloneJsonValue(item));
1406
- if (isRecord$29(value)) {
1406
+ if (isRecord$33(value)) {
1407
1407
  const cloned = {};
1408
1408
  for (const [key, child] of Object.entries(value)) cloned[key] = cloneJsonValue(child);
1409
1409
  return cloned;
1410
1410
  }
1411
1411
  return value;
1412
1412
  }
1413
- function isRecord$29(value) {
1413
+ function isRecord$33(value) {
1414
1414
  return typeof value === "object" && value !== null && !Array.isArray(value);
1415
1415
  }
1416
1416
  function hasOwn(obj, key) {
@@ -1819,16 +1819,6 @@ function measureSerializedRequest(body, requestBytes) {
1819
1819
  const payload = parsed;
1820
1820
  const messages = Array.isArray(payload["messages"]) ? payload["messages"] : [];
1821
1821
  const tools = Array.isArray(payload["tools"]) ? payload["tools"] : void 0;
1822
- let systemMessageBytes = 0;
1823
- let conversationMessageBytes = 0;
1824
- let toolResultMessageBytes = 0;
1825
- for (const message of messages) {
1826
- const size = Buffer.byteLength(JSON.stringify(message), "utf8");
1827
- const role = message !== null && typeof message === "object" ? message["role"] : void 0;
1828
- if (role === "system" || role === "developer") systemMessageBytes += size;
1829
- else if (role === "tool") toolResultMessageBytes += size;
1830
- else conversationMessageBytes += size;
1831
- }
1832
1822
  const toolDefinitions = Object.freeze((tools ?? []).map((tool, index) => {
1833
1823
  const entry = tool !== null && typeof tool === "object" ? tool : void 0;
1834
1824
  const fn = entry?.["function"];
@@ -1839,6 +1829,44 @@ function measureSerializedRequest(body, requestBytes) {
1839
1829
  ...typeof name === "string" && name.length > 0 && name.length <= 128 ? { name } : {}
1840
1830
  });
1841
1831
  }));
1832
+ const declaredNames = new Set(toolDefinitions.flatMap((tool) => tool.name === void 0 ? [] : [tool.name]));
1833
+ const callNames = /* @__PURE__ */ new Map();
1834
+ for (const message of messages) {
1835
+ if (message === null || typeof message !== "object" || message["role"] !== "assistant") continue;
1836
+ const calls = message["tool_calls"];
1837
+ if (!Array.isArray(calls)) continue;
1838
+ for (const call of calls) {
1839
+ if (call === null || typeof call !== "object") continue;
1840
+ const entry = call;
1841
+ const fn = entry["function"];
1842
+ const name = fn !== null && typeof fn === "object" ? fn["name"] : void 0;
1843
+ const id = entry["id"];
1844
+ if (typeof id !== "string" || id.length === 0) continue;
1845
+ callNames.set(id, callNames.has(id) ? void 0 : typeof name === "string" && declaredNames.has(name) ? name : void 0);
1846
+ }
1847
+ }
1848
+ let systemMessageBytes = 0;
1849
+ let conversationMessageBytes = 0;
1850
+ let toolResultMessageBytes = 0;
1851
+ const results = /* @__PURE__ */ new Map();
1852
+ for (const message of messages) {
1853
+ const size = Buffer.byteLength(JSON.stringify(message), "utf8");
1854
+ const role = message !== null && typeof message === "object" ? message["role"] : void 0;
1855
+ if (role === "system" || role === "developer") systemMessageBytes += size;
1856
+ else if (role === "tool") {
1857
+ toolResultMessageBytes += size;
1858
+ const id = message["tool_call_id"];
1859
+ const name = typeof id === "string" ? callNames.get(id) : void 0;
1860
+ const key = name ?? "";
1861
+ const previous = results.get(key);
1862
+ results.set(key, {
1863
+ ...name === void 0 ? {} : { name },
1864
+ count: (previous?.count ?? 0) + 1,
1865
+ bytes: (previous?.bytes ?? 0) + size
1866
+ });
1867
+ } else conversationMessageBytes += size;
1868
+ }
1869
+ const toolResultByTool = Object.freeze(Array.from(results.values(), (entry) => Object.freeze(entry)));
1842
1870
  const toolArrayOverheadBytes = tools === void 0 ? 0 : 2 + Math.max(0, tools.length - 1);
1843
1871
  const toolSchemaBytes = toolDefinitions.reduce((sum, tool) => sum + tool.bytes, toolArrayOverheadBytes);
1844
1872
  return Object.freeze({
@@ -1848,6 +1876,7 @@ function measureSerializedRequest(body, requestBytes) {
1848
1876
  systemMessageBytes,
1849
1877
  conversationMessageBytes,
1850
1878
  toolResultMessageBytes,
1879
+ ...toolResultByTool.length === 0 ? {} : { toolResultByTool },
1851
1880
  toolSchemaBytes,
1852
1881
  toolDefinitions,
1853
1882
  toolArrayOverheadBytes,
@@ -2242,11 +2271,11 @@ var init_blun_files = __esmMin((() => {
2242
2271
  async uploadVideo(input, options) {
2243
2272
  let file;
2244
2273
  if (typeof input === "string") {
2245
- if (!fs$17.existsSync(input)) throw new ChatProviderError(`Video file not found: ${input}`);
2246
- const filename = path$17.basename(input);
2274
+ if (!fs$16.existsSync(input)) throw new ChatProviderError(`Video file not found: ${input}`);
2275
+ const filename = path$16.basename(input);
2247
2276
  const mimeType = guessMimeTypeFromExt(filename);
2248
2277
  if (mimeType === void 0 || !mimeType.startsWith("video/")) throw new ChatProviderError(`BlunFiles.uploadVideo: file extension does not indicate a video type: ${filename}`);
2249
- const data = await fs$17.promises.readFile(input);
2278
+ const data = await fs$16.promises.readFile(input);
2250
2279
  file = new File$1([new Blob$1([new Uint8Array(data)], { type: mimeType })], filename, { type: mimeType });
2251
2280
  } else {
2252
2281
  if (!input.mimeType.startsWith("video/")) throw new ChatProviderError(`Expected a video mime type, got ${input.mimeType}`);
@@ -2350,6 +2379,9 @@ function extractChatCompletionUsage(usage) {
2350
2379
  const value = usage;
2351
2380
  const promptTokens = typeof value["prompt_tokens"] === "number" ? value["prompt_tokens"] : 0;
2352
2381
  const completionTokens = typeof value["completion_tokens"] === "number" ? value["completion_tokens"] : 0;
2382
+ const completionDetails = value["completion_tokens_details"];
2383
+ const reportedReasoning = completionDetails !== null && typeof completionDetails === "object" ? completionDetails["reasoning_tokens"] : void 0;
2384
+ const outputReasoning = typeof reportedReasoning === "number" && Number.isSafeInteger(reportedReasoning) && reportedReasoning >= 0 && reportedReasoning <= completionTokens ? reportedReasoning : void 0;
2353
2385
  let cachedTokens = 0;
2354
2386
  if (typeof value["cached_tokens"] === "number") cachedTokens = value["cached_tokens"];
2355
2387
  else if (value["prompt_tokens_details"] !== null && typeof value["prompt_tokens_details"] === "object") {
@@ -2359,6 +2391,7 @@ function extractChatCompletionUsage(usage) {
2359
2391
  return {
2360
2392
  inputOther: promptTokens - cachedTokens,
2361
2393
  output: completionTokens,
2394
+ ...outputReasoning === void 0 ? {} : { outputReasoning },
2362
2395
  inputCacheRead: cachedTokens,
2363
2396
  inputCacheCreation: 0
2364
2397
  };
@@ -2625,12 +2658,22 @@ function collectBlunVisionAttachments(messages) {
2625
2658
  }
2626
2659
  return attachments;
2627
2660
  }
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
- };
2661
+ function estimateBlunSerializedBodyBytes(systemPrompt, tools, history) {
2662
+ const normalizedHistory = normalizeToolCallIdsForProvider([...history], BLUN_TOOL_CALL_ID_POLICY);
2663
+ const messages = systemPrompt ? [{
2664
+ role: "system",
2665
+ content: systemPrompt
2666
+ }] : [];
2667
+ for (const message of normalizedHistory) if (!isEmptyAssistantHistoryMessage(message)) messages.push(convertMessage(message));
2668
+ const attachments = collectBlunVisionAttachments(normalizedHistory);
2669
+ return Buffer.byteLength(JSON.stringify({
2670
+ model: "king",
2671
+ messages,
2672
+ stream: true,
2673
+ ...tools.length > 0 ? { tools: tools.map(convertTool) } : {},
2674
+ ...attachments.length > 0 ? { visionAttachments: attachments } : {},
2675
+ stream_options: { include_usage: true }
2676
+ }), "utf8");
2634
2677
  }
2635
2678
  function convertMessage(message) {
2636
2679
  let reasoningContent = "";
@@ -3373,9 +3416,11 @@ function emptyUsage() {
3373
3416
  * Sum two TokenUsage values.
3374
3417
  */
3375
3418
  function addUsage$1(a, b) {
3419
+ const outputReasoning = a.outputReasoning !== void 0 && b.outputReasoning !== void 0 ? a.outputReasoning + b.outputReasoning : a.output === 0 ? b.outputReasoning : b.output === 0 ? a.outputReasoning : void 0;
3376
3420
  return {
3377
3421
  inputOther: a.inputOther + b.inputOther,
3378
3422
  output: a.output + b.output,
3423
+ ...outputReasoning === void 0 ? {} : { outputReasoning },
3379
3424
  inputCacheRead: a.inputCacheRead + b.inputCacheRead,
3380
3425
  inputCacheCreation: a.inputCacheCreation + b.inputCacheCreation
3381
3426
  };
@@ -10153,6 +10198,8 @@ var init_schema = __esmMin((() => {
10153
10198
  ProviderConfigSchema = object$1({
10154
10199
  type: ProviderTypeSchema,
10155
10200
  apiKey: string().optional(),
10201
+ memoryWorkspaceId: string().regex(/^blun-[0-9a-f]{64}$/u).optional(),
10202
+ memoryApiKeyHash: string().regex(/^[0-9a-f]{64}$/u).optional(),
10156
10203
  baseUrl: string().optional(),
10157
10204
  defaultModel: string().optional(),
10158
10205
  oauth: OAuthRefSchema.optional(),
@@ -10643,7 +10690,8 @@ function tokenToWire(token) {
10643
10690
  expires_at: token.expiresAt,
10644
10691
  scope: token.scope,
10645
10692
  token_type: token.tokenType,
10646
- expires_in: token.expiresIn
10693
+ expires_in: token.expiresIn,
10694
+ ...token.memoryWorkspaceId === void 0 ? {} : { memory_workspace_id: token.memoryWorkspaceId }
10647
10695
  };
10648
10696
  }
10649
10697
  function tokenFromWire(wire) {
@@ -10653,13 +10701,14 @@ function tokenFromWire(wire) {
10653
10701
  expiresAt: typeof wire.expires_at === "number" ? wire.expires_at : 0,
10654
10702
  scope: wire.scope ?? "",
10655
10703
  tokenType: wire.token_type ?? "",
10656
- expiresIn: typeof wire.expires_in === "number" ? wire.expires_in : 0
10704
+ expiresIn: typeof wire.expires_in === "number" ? wire.expires_in : 0,
10705
+ ...typeof wire.memory_workspace_id === "string" && wire.memory_workspace_id.length > 0 ? { memoryWorkspaceId: wire.memory_workspace_id } : {}
10657
10706
  };
10658
10707
  }
10659
10708
  var init_types$17 = __esmMin((() => {}));
10660
10709
  //#endregion
10661
10710
  //#region ../../packages/oauth/src/utils.ts
10662
- function isRecord$28(value) {
10711
+ function isRecord$32(value) {
10663
10712
  return typeof value === "object" && value !== null && !Array.isArray(value);
10664
10713
  }
10665
10714
  var init_utils$1 = __esmMin((() => {}));
@@ -11242,7 +11291,7 @@ var init_storage = __esmMin((() => {
11242
11291
  } catch {
11243
11292
  return;
11244
11293
  }
11245
- if (!isRecord$28(parsed)) return void 0;
11294
+ if (!isRecord$32(parsed)) return void 0;
11246
11295
  return tokenFromWire(parsed);
11247
11296
  }
11248
11297
  async save(name, token) {
@@ -11336,7 +11385,7 @@ function extractApiErrorMessage(value) {
11336
11385
  }
11337
11386
  return;
11338
11387
  }
11339
- if (!isRecord$28(value)) return void 0;
11388
+ if (!isRecord$32(value)) return void 0;
11340
11389
  for (const key of DIRECT_ERROR_KEYS) {
11341
11390
  const message = stringField$4(value, key);
11342
11391
  if (message !== void 0) return message;
@@ -11344,7 +11393,7 @@ function extractApiErrorMessage(value) {
11344
11393
  const error = value["error"];
11345
11394
  const errorString = nonEmptyString$7(error);
11346
11395
  if (errorString !== void 0) return errorString;
11347
- if (isRecord$28(error)) for (const key of NESTED_ERROR_KEYS) {
11396
+ if (isRecord$32(error)) for (const key of NESTED_ERROR_KEYS) {
11348
11397
  const message = stringField$4(error, key);
11349
11398
  if (message !== void 0) return message;
11350
11399
  }
@@ -11434,7 +11483,7 @@ async function postForm(url, params, deviceHeaders, options) {
11434
11483
  let data = {};
11435
11484
  try {
11436
11485
  const parsed = await response.json();
11437
- if (isRecord$28(parsed)) data = parsed;
11486
+ if (isRecord$32(parsed)) data = parsed;
11438
11487
  } catch {}
11439
11488
  return {
11440
11489
  status,
@@ -11910,7 +11959,7 @@ var require_clone$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
11910
11959
  //#endregion
11911
11960
  //#region ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js
11912
11961
  var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
11913
- var fs$16 = __require("fs");
11962
+ var fs$15 = __require("fs");
11914
11963
  var polyfills = require_polyfills();
11915
11964
  var legacy = require_legacy_streams();
11916
11965
  var clone = require_clone$1();
@@ -11939,36 +11988,36 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
11939
11988
  m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
11940
11989
  console.error(m);
11941
11990
  };
11942
- if (!fs$16[gracefulQueue]) {
11943
- publishQueue(fs$16, global[gracefulQueue] || []);
11944
- fs$16.close = (function(fs$close) {
11991
+ if (!fs$15[gracefulQueue]) {
11992
+ publishQueue(fs$15, global[gracefulQueue] || []);
11993
+ fs$15.close = (function(fs$close) {
11945
11994
  function close(fd, cb) {
11946
- return fs$close.call(fs$16, fd, function(err) {
11995
+ return fs$close.call(fs$15, fd, function(err) {
11947
11996
  if (!err) resetQueue();
11948
11997
  if (typeof cb === "function") cb.apply(this, arguments);
11949
11998
  });
11950
11999
  }
11951
12000
  Object.defineProperty(close, previousSymbol, { value: fs$close });
11952
12001
  return close;
11953
- })(fs$16.close);
11954
- fs$16.closeSync = (function(fs$closeSync) {
12002
+ })(fs$15.close);
12003
+ fs$15.closeSync = (function(fs$closeSync) {
11955
12004
  function closeSync(fd) {
11956
- fs$closeSync.apply(fs$16, arguments);
12005
+ fs$closeSync.apply(fs$15, arguments);
11957
12006
  resetQueue();
11958
12007
  }
11959
12008
  Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync });
11960
12009
  return closeSync;
11961
- })(fs$16.closeSync);
12010
+ })(fs$15.closeSync);
11962
12011
  if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) process.on("exit", function() {
11963
- debug(fs$16[gracefulQueue]);
11964
- __require("assert").equal(fs$16[gracefulQueue].length, 0);
12012
+ debug(fs$15[gracefulQueue]);
12013
+ __require("assert").equal(fs$15[gracefulQueue].length, 0);
11965
12014
  });
11966
12015
  }
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;
12016
+ if (!global[gracefulQueue]) publishQueue(global, fs$15[gracefulQueue]);
12017
+ module.exports = patch(clone(fs$15));
12018
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$15.__patched) {
12019
+ module.exports = patch(fs$15);
12020
+ fs$15.__patched = true;
11972
12021
  }
11973
12022
  function patch(fs) {
11974
12023
  polyfills(fs);
@@ -12223,23 +12272,23 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
12223
12272
  }
12224
12273
  function enqueue(elem) {
12225
12274
  debug("ENQUEUE", elem[0].name, elem[1]);
12226
- fs$16[gracefulQueue].push(elem);
12275
+ fs$15[gracefulQueue].push(elem);
12227
12276
  retry();
12228
12277
  }
12229
12278
  var retryTimer;
12230
12279
  function resetQueue() {
12231
12280
  var now = Date.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;
12281
+ for (var i = 0; i < fs$15[gracefulQueue].length; ++i) if (fs$15[gracefulQueue][i].length > 2) {
12282
+ fs$15[gracefulQueue][i][3] = now;
12283
+ fs$15[gracefulQueue][i][4] = now;
12235
12284
  }
12236
12285
  retry();
12237
12286
  }
12238
12287
  function retry() {
12239
12288
  clearTimeout(retryTimer);
12240
12289
  retryTimer = void 0;
12241
- if (fs$16[gracefulQueue].length === 0) return;
12242
- var elem = fs$16[gracefulQueue].shift();
12290
+ if (fs$15[gracefulQueue].length === 0) return;
12291
+ var elem = fs$15[gracefulQueue].shift();
12243
12292
  var fn = elem[0];
12244
12293
  var args = elem[1];
12245
12294
  var err = elem[2];
@@ -12258,7 +12307,7 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
12258
12307
  if (sinceAttempt >= Math.min(sinceStart * 1.2, 100)) {
12259
12308
  debug("RETRY", fn.name, args);
12260
12309
  fn.apply(null, args.concat([startTime]));
12261
- } else fs$16[gracefulQueue].push(elem);
12310
+ } else fs$15[gracefulQueue].push(elem);
12262
12311
  }
12263
12312
  if (retryTimer === void 0) retryTimer = setTimeout(retry, 0);
12264
12313
  }
@@ -12610,7 +12659,7 @@ var require_mtime_precision = /* @__PURE__ */ __commonJSMin(((exports, module) =
12610
12659
  //#endregion
12611
12660
  //#region ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js
12612
12661
  var require_lockfile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
12613
- const path$16 = __require("path");
12662
+ const path$15 = __require("path");
12614
12663
  const fs = require_graceful_fs();
12615
12664
  const retry = require_retry$3();
12616
12665
  const onExit = require_signal_exit();
@@ -12620,7 +12669,7 @@ var require_lockfile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
12620
12669
  return options.lockfilePath || `${file}.lock`;
12621
12670
  }
12622
12671
  function resolveCanonicalPath(file, options, callback) {
12623
- if (!options.realpath) return callback(null, path$16.resolve(file));
12672
+ if (!options.realpath) return callback(null, path$15.resolve(file));
12624
12673
  options.fs.realpath(file, callback);
12625
12674
  }
12626
12675
  function acquireLock(file, options, callback) {
@@ -13064,6 +13113,27 @@ var init_oauth_manager = __esmMin((() => {
13064
13113
  const state = await this.loadState();
13065
13114
  return state.kind === "valid" ? state.token.accessToken : void 0;
13066
13115
  }
13116
+ async getCachedMemoryWorkspaceId() {
13117
+ const state = await this.loadState();
13118
+ return state.kind === "valid" && state.token.expiresAt > this.now() ? state.token.memoryWorkspaceId : void 0;
13119
+ }
13120
+ async cacheMemoryWorkspaceId(workspaceId) {
13121
+ if (workspaceId.length === 0) return false;
13122
+ const release = await this.acquireRefreshLock();
13123
+ try {
13124
+ const state = await this.loadState();
13125
+ if (state.kind !== "valid" || state.token.expiresAt <= this.now()) return false;
13126
+ if (state.token.memoryWorkspaceId === workspaceId) return true;
13127
+ if (state.token.memoryWorkspaceId !== void 0) return false;
13128
+ await this.storage.save(this.config.name, {
13129
+ ...state.token,
13130
+ memoryWorkspaceId: workspaceId
13131
+ });
13132
+ return true;
13133
+ } finally {
13134
+ await release();
13135
+ }
13136
+ }
13067
13137
  async logout() {
13068
13138
  await this.inFlightRefresh?.promise.catch(() => void 0);
13069
13139
  const release = await this.acquireRefreshLock();
@@ -13131,7 +13201,10 @@ var init_oauth_manager = __esmMin((() => {
13131
13201
  if (activeToken.refreshToken.length === 0) throw new OAuthUnauthorizedError(`Token for "${this.config.name}" has no refresh_token; re-login required.`);
13132
13202
  try {
13133
13203
  const refreshed = await this.refreshImpl(this.config, activeToken.refreshToken);
13134
- await this.storage.save(this.config.name, refreshed);
13204
+ await this.storage.save(this.config.name, {
13205
+ ...refreshed,
13206
+ memoryWorkspaceId: activeToken.memoryWorkspaceId
13207
+ });
13135
13208
  this.notifyRefresh({ success: true });
13136
13209
  return refreshed.accessToken;
13137
13210
  } catch (error) {
@@ -13346,9 +13419,9 @@ function blunContextWindowsUrl(oauthHost) {
13346
13419
  return `${(oauthHost ?? process.env["BLUN_OAUTH_HOST"] ?? "https://account.blun.ai").replace(/\/+$/, "")}/api/verbrauch/tarife`;
13347
13420
  }
13348
13421
  function parseManagedContextWindow(payload, plan) {
13349
- if (!isRecord$28(payload)) return void 0;
13422
+ if (!isRecord$32(payload)) return void 0;
13350
13423
  const contextWindows = payload["kontext"];
13351
- if (!isRecord$28(contextWindows)) return void 0;
13424
+ if (!isRecord$32(contextWindows)) return void 0;
13352
13425
  const value = contextWindows[plan];
13353
13426
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
13354
13427
  }
@@ -13383,7 +13456,7 @@ function parseManagedUsagePayload(payload) {
13383
13456
  const plan = typeof rec["plan"] === "string" && rec["plan"].trim().length > 0 ? rec["plan"].trim() : void 0;
13384
13457
  const contextWindowTokens = managedContextWindowFrom(rec);
13385
13458
  const unlimited = rec["unlimited"] === true;
13386
- const stand = isRecord$28(rec["stand"]) ? rec["stand"] : void 0;
13459
+ const stand = isRecord$32(rec["stand"]) ? rec["stand"] : void 0;
13387
13460
  if (stand !== void 0) for (const [sourceKey, id, label] of ACCOUNT_USAGE_WINDOWS) {
13388
13461
  const row = toAccountUsageRow(stand[sourceKey], id, label, unlimited);
13389
13462
  if (row !== null) limits.push(row);
@@ -13393,9 +13466,9 @@ function parseManagedUsagePayload(payload) {
13393
13466
  const item = rawLimits[idx];
13394
13467
  if (!item || typeof item !== "object") continue;
13395
13468
  const detailRaw = item["detail"];
13396
- const detail = isRecord$28(detailRaw) ? detailRaw : item;
13469
+ const detail = isRecord$32(detailRaw) ? detailRaw : item;
13397
13470
  const windowRaw = item["window"];
13398
- const row = toUsageRow(detail, limitLabel(item, detail, isRecord$28(windowRaw) ? windowRaw : {}, idx));
13471
+ const row = toUsageRow(detail, limitLabel(item, detail, isRecord$32(windowRaw) ? windowRaw : {}, idx));
13399
13472
  if (row !== null) limits.push(row);
13400
13473
  }
13401
13474
  return {
@@ -13419,7 +13492,7 @@ function managedContextWindowFrom(payload) {
13419
13492
  return values.every((value) => value === first) ? first : void 0;
13420
13493
  }
13421
13494
  function toAccountUsageRow(raw, id, label, accountUnlimited) {
13422
- if (!isRecord$28(raw)) return null;
13495
+ if (!isRecord$32(raw)) return null;
13423
13496
  const used = toInt(raw["verbraucht"]);
13424
13497
  const unlimited = accountUnlimited || raw["unlimited"] === true;
13425
13498
  const fraction = raw["anteil"];
@@ -13452,7 +13525,7 @@ function toAccountUsageRow(raw, id, label, accountUnlimited) {
13452
13525
  };
13453
13526
  }
13454
13527
  function toUsageRow(raw, defaultLabel) {
13455
- if (!isRecord$28(raw)) return null;
13528
+ if (!isRecord$32(raw)) return null;
13456
13529
  const unlimited = raw["unlimited"] === true;
13457
13530
  const limit = toInt(raw["limit"]);
13458
13531
  let used = toInt(raw["used"]);
@@ -13573,7 +13646,7 @@ function isManagedQuotaErrorMessage(message) {
13573
13646
  return /you(?:'|’)?ve reached your usage limit/.test(normalized) && /billing cycle|quota will be (?:refreshed|reset)|purchase extra usage/.test(normalized);
13574
13647
  }
13575
13648
  function hasManagedUsageShape(payload) {
13576
- if (!isRecord$28(payload)) return false;
13649
+ if (!isRecord$32(payload)) return false;
13577
13650
  let recognized = false;
13578
13651
  if ("context_window_tokens" in payload || "contextWindowTokens" in payload) {
13579
13652
  recognized = true;
@@ -13589,15 +13662,15 @@ function hasManagedUsageShape(payload) {
13589
13662
  if (!Array.isArray(limits)) return false;
13590
13663
  for (let index = 0; index < limits.length; index++) {
13591
13664
  const item = limits[index];
13592
- if (!isRecord$28(item)) return false;
13593
- const detail = isRecord$28(item["detail"]) ? item["detail"] : item;
13594
- if (toUsageRow(detail, limitLabel(item, detail, isRecord$28(item["window"]) ? item["window"] : {}, index)) === null) return false;
13665
+ if (!isRecord$32(item)) return false;
13666
+ const detail = isRecord$32(item["detail"]) ? item["detail"] : item;
13667
+ if (toUsageRow(detail, limitLabel(item, detail, isRecord$32(item["window"]) ? item["window"] : {}, index)) === null) return false;
13595
13668
  }
13596
13669
  }
13597
13670
  if ("stand" in payload) {
13598
13671
  recognized = true;
13599
13672
  const stand = payload["stand"];
13600
- if (!isRecord$28(stand)) return false;
13673
+ if (!isRecord$32(stand)) return false;
13601
13674
  const windows = ACCOUNT_USAGE_WINDOWS.filter(([sourceKey]) => sourceKey in stand);
13602
13675
  if (windows.length === 0) return false;
13603
13676
  const unlimited = payload["unlimited"] === true;
@@ -13693,8 +13766,8 @@ function userExtras(existing, remoteOwnedFields) {
13693
13766
  return out;
13694
13767
  }
13695
13768
  function mergeRefreshedModelAlias(existing, remote, remoteOwnedFields) {
13696
- const current = isRecord$28(existing) ? existing : {};
13697
- const overrides = cloneOverrides(isRecord$28(current["overrides"]) ? current["overrides"] : void 0);
13769
+ const current = isRecord$32(existing) ? existing : {};
13770
+ const overrides = cloneOverrides(isRecord$32(current["overrides"]) ? current["overrides"] : void 0);
13698
13771
  return {
13699
13772
  ...userExtras(current, remoteOwnedFields),
13700
13773
  ...remote,
@@ -13883,7 +13956,7 @@ function parseModelContextLength(item, modelId) {
13883
13956
  return values[0];
13884
13957
  }
13885
13958
  function toModelInfo(item) {
13886
- if (!isRecord$28(item) || typeof item["id"] !== "string" || item["id"].length === 0) return;
13959
+ if (!isRecord$32(item) || typeof item["id"] !== "string" || item["id"].length === 0) return;
13887
13960
  const contextLength = parseModelContextLength(item, item["id"]);
13888
13961
  const displayName = item["display_name"];
13889
13962
  const normalizedDisplayName = typeof displayName === "string" && displayName.length > 0 ? displayName : void 0;
@@ -13970,7 +14043,7 @@ async function fetchManagedBlunCodeModels(options) {
13970
14043
  throw new Error(message);
13971
14044
  }
13972
14045
  const payload = await response.json();
13973
- if (!isRecord$28(payload) || !Array.isArray(payload["data"])) throw new Error(`Unexpected models response for ${baseUrl}.`);
14046
+ if (!isRecord$32(payload) || !Array.isArray(payload["data"])) throw new Error(`Unexpected models response for ${baseUrl}.`);
13974
14047
  return payload["data"].map((item) => toModelInfo(item)).filter((item) => item !== void 0);
13975
14048
  }
13976
14049
  throw new Error(`Failed to list BLUN models for ${baseUrl}.`);
@@ -14013,11 +14086,11 @@ function applyManagedBlunCodeConfig(config, options) {
14013
14086
  apiKey
14014
14087
  };
14015
14088
  const upstreamKeys = new Set(options.models.map((m) => managedModelKey(m.id)));
14016
- for (const [key, model] of Object.entries(existingModels)) if (RETIRED_BLUN_MODEL_KEYS.has(key) || isRecord$28(model) && model["provider"] === "managed:blun" && !upstreamKeys.has(key)) delete existingModels[key];
14089
+ for (const [key, model] of Object.entries(existingModels)) if (RETIRED_BLUN_MODEL_KEYS.has(key) || isRecord$32(model) && model["provider"] === "managed:blun" && !upstreamKeys.has(key)) delete existingModels[key];
14017
14090
  for (const model of options.models) {
14018
14091
  const capabilities = capabilitiesForModel(model);
14019
14092
  const key = managedModelKey(model.id);
14020
- const existing = isRecord$28(existingModels[key]) ? existingModels[key] : {};
14093
+ const existing = isRecord$32(existingModels[key]) ? existingModels[key] : {};
14021
14094
  const supportsAdaptiveThinking = capabilities?.includes("thinking") === true || capabilities?.includes("always_thinking") === true;
14022
14095
  existingModels[key] = mergeRefreshedModelAlias(existing, {
14023
14096
  provider: BLUN_PROVIDER_NAME$1,
@@ -14065,7 +14138,7 @@ function applyManagedBlunCodeLogoutConfig(config) {
14065
14138
  let removedDefaultModel = false;
14066
14139
  const existingModels = config.models ?? {};
14067
14140
  for (const [key, model] of Object.entries(existingModels)) {
14068
- if (!isRecord$28(model) || model["provider"] !== "managed:blun") continue;
14141
+ if (!isRecord$32(model) || model["provider"] !== "managed:blun") continue;
14069
14142
  delete existingModels[key];
14070
14143
  if (config.defaultModel === key) removedDefaultModel = true;
14071
14144
  }
@@ -14105,7 +14178,7 @@ function selectDefaultModel(config, models, options) {
14105
14178
  function canPreserveDefaultModel(existingModels, defaultModel, managedModels) {
14106
14179
  if (managedModels.has(defaultModel)) return true;
14107
14180
  const existing = existingModels[defaultModel];
14108
- return isRecord$28(existing) && existing["provider"] !== "managed:blun";
14181
+ return isRecord$32(existing) && existing["provider"] !== "managed:blun";
14109
14182
  }
14110
14183
  function assertPositiveContextLength(model) {
14111
14184
  if (!Number.isInteger(model.contextLength) || model.contextLength <= 0) throw new Error(`BLUN model "${model.id}" must include a positive context_length.`);
@@ -14181,13 +14254,13 @@ function blunManagedQuotaUrl(oauthHost) {
14181
14254
  return `${(oauthHost ?? process.env["BLUN_OAUTH_HOST"] ?? "https://account.blun.ai").replace(/\/+$/, "")}${MANAGED_QUOTA_PATH}`;
14182
14255
  }
14183
14256
  function parseManagedQuotaPayload(payload) {
14184
- if (!isRecord$28(payload)) return void 0;
14257
+ if (!isRecord$32(payload)) return void 0;
14185
14258
  const plan = nonEmptyString$6(payload["plan"]);
14186
14259
  const paid = payload["bezahlt"];
14187
14260
  const creditCents = payload["guthaben_cent"];
14188
14261
  const billingKind = nonEmptyString$6(payload["art"]);
14189
14262
  const globalUnlimited = payload["unlimited"];
14190
- if (plan === void 0 || typeof paid !== "boolean" || !Number.isSafeInteger(creditCents) || creditCents < 0 || billingKind === void 0 || globalUnlimited !== void 0 && typeof globalUnlimited !== "boolean" || !isRecord$28(payload["stand"])) return;
14263
+ if (plan === void 0 || typeof paid !== "boolean" || !Number.isSafeInteger(creditCents) || creditCents < 0 || billingKind === void 0 || globalUnlimited !== void 0 && typeof globalUnlimited !== "boolean" || !isRecord$32(payload["stand"])) return;
14191
14264
  if (!hasStrictQuotaStand(payload["stand"], globalUnlimited === true)) return void 0;
14192
14265
  const limits = parseManagedUsagePayload(payload).limits;
14193
14266
  if (limits.length !== REQUIRED_WINDOWS.length || REQUIRED_WINDOWS.some(([, id]) => limits.filter((row) => row.id === id).length !== 1)) return;
@@ -14257,7 +14330,7 @@ function nonEmptyString$6(value) {
14257
14330
  function hasStrictQuotaStand(stand, globalUnlimited) {
14258
14331
  return REQUIRED_WINDOWS.every(([sourceKey]) => {
14259
14332
  const row = stand[sourceKey];
14260
- if (!isRecord$28(row)) return false;
14333
+ if (!isRecord$32(row)) return false;
14261
14334
  const used = row["verbraucht"];
14262
14335
  const rowUnlimited = row["unlimited"];
14263
14336
  if (rowUnlimited !== void 0 && typeof rowUnlimited !== "boolean") return false;
@@ -14547,6 +14620,16 @@ var init_toolkit = __esmMin((() => {
14547
14620
  hasToken: await this.managerFor(name, oauthKey, oauthHost).hasToken()
14548
14621
  }] };
14549
14622
  }
14623
+ async getCachedMemoryWorkspaceId(oauthRef) {
14624
+ const oauthHost = this.oauthHostFor(oauthRef);
14625
+ const oauthKey = oauthRef?.key ?? this.defaultOAuthKey(void 0, oauthHost);
14626
+ return this.managerFor(BLUN_PROVIDER_NAME$1, oauthKey, oauthHost).getCachedMemoryWorkspaceId();
14627
+ }
14628
+ async cacheMemoryWorkspaceId(workspaceId, oauthRef) {
14629
+ const oauthHost = this.oauthHostFor(oauthRef);
14630
+ const oauthKey = oauthRef?.key ?? this.defaultOAuthKey(void 0, oauthHost);
14631
+ return this.managerFor(BLUN_PROVIDER_NAME$1, oauthKey, oauthHost).cacheMemoryWorkspaceId(workspaceId);
14632
+ }
14550
14633
  async login(providerName, options = {}) {
14551
14634
  const name = providerName ?? "managed:blun";
14552
14635
  const oauthHost = this.oauthHostFor(options.oauthRef, options.oauthHost);
@@ -15102,7 +15185,7 @@ async function syncDir(dirPath) {
15102
15185
  */
15103
15186
  function syncFd(fd) {
15104
15187
  return new Promise((resolve, reject) => {
15105
- fs$17.fsync(fd, (err) => {
15188
+ fs$16.fsync(fd, (err) => {
15106
15189
  if (err) {
15107
15190
  reject(err);
15108
15191
  return;
@@ -16687,6 +16770,8 @@ function providerToToml(provider, rawProvider) {
16687
16770
  for (const key of [
16688
16771
  "type",
16689
16772
  "apiKey",
16773
+ "memoryWorkspaceId",
16774
+ "memoryApiKeyHash",
16690
16775
  "baseUrl",
16691
16776
  "defaultModel",
16692
16777
  "oauth",
@@ -21772,7 +21857,7 @@ function parseSkillText(options) {
21772
21857
  throw error;
21773
21858
  }
21774
21859
  const frontmatter = parsed.data ?? {};
21775
- if (!isRecord$27(frontmatter)) throw new SkillParseError(`Frontmatter in ${options.skillMdPath} must be a mapping at the top level`);
21860
+ if (!isRecord$31(frontmatter)) throw new SkillParseError(`Frontmatter in ${options.skillMdPath} must be a mapping at the top level`);
21776
21861
  const metadata = normalizeMetadata(frontmatter);
21777
21862
  if (!isSupportedSkillType(metadata.type)) throw new UnsupportedSkillTypeError(metadata.type ?? String(frontmatter["type"]));
21778
21863
  const name = nonEmptyString$4(metadata.name);
@@ -21885,7 +21970,7 @@ function tokenizeArgs(raw) {
21885
21970
  function nonEmptyString$4(value) {
21886
21971
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
21887
21972
  }
21888
- function isRecord$27(value) {
21973
+ function isRecord$31(value) {
21889
21974
  return typeof value === "object" && value !== null && !Array.isArray(value);
21890
21975
  }
21891
21976
  var import_regexp_escape, FrontmatterError, SkillParseError, UnsupportedSkillTypeError, FENCE, METADATA_ALIASES;
@@ -21934,7 +22019,7 @@ var init_parser$1 = __esmMin((() => {
21934
22019
  function parseCommandText(input) {
21935
22020
  const { text, commandPath, pluginId } = input;
21936
22021
  const parsed = parseFrontmatter(text);
21937
- const frontmatter = isRecord$26(parsed.data) ? parsed.data : {};
22022
+ const frontmatter = isRecord$30(parsed.data) ? parsed.data : {};
21938
22023
  const baseName = input.fallbackName ?? path.basename(commandPath).replace(/\.md$/i, "");
21939
22024
  const name = nonEmptyString$3(frontmatter["name"]) ?? baseName;
21940
22025
  const body = parsed.body.trim();
@@ -21976,7 +22061,7 @@ function descriptionFromBody(body) {
21976
22061
  if (firstLine === void 0) return "No description provided.";
21977
22062
  return firstLine.length > 240 ? `${firstLine.slice(0, 239)}…` : firstLine;
21978
22063
  }
21979
- function isRecord$26(value) {
22064
+ function isRecord$30(value) {
21980
22065
  return typeof value === "object" && value !== null && !Array.isArray(value);
21981
22066
  }
21982
22067
  var init_commands = __esmMin((() => {
@@ -22211,6 +22296,31 @@ var init_instruction_provenance = __esmMin((() => {
22211
22296
  get content() {
22212
22297
  return this.pieces.map((piece) => piece.text).join("");
22213
22298
  }
22299
+ prefixUtf8(maxBytes) {
22300
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError("Invalid instruction byte budget");
22301
+ const kept = [];
22302
+ let remaining = maxBytes;
22303
+ let totalBytes = 0;
22304
+ let readBytes = 0;
22305
+ for (const piece of this.pieces) {
22306
+ const encoded = Buffer.from(piece.text, "utf8");
22307
+ totalBytes += encoded.length;
22308
+ if (remaining <= 0) continue;
22309
+ const content = encoded.length <= remaining ? piece.text : new StringDecoder("utf8").write(encoded.subarray(0, remaining));
22310
+ const bytes = Buffer.byteLength(content, "utf8");
22311
+ if (content.length > 0) kept.push({
22312
+ ...piece,
22313
+ text: content
22314
+ });
22315
+ readBytes += bytes;
22316
+ remaining -= bytes;
22317
+ if (bytes < encoded.length) remaining = 0;
22318
+ }
22319
+ return {
22320
+ text: new InstructionText(kept, new Map(this.sources)),
22321
+ omittedBytes: totalBytes - readBytes
22322
+ };
22323
+ }
22214
22324
  replaceFirst(needle, replacement) {
22215
22325
  const start = this.content.indexOf(needle);
22216
22326
  if (start >= 0) this.replaceRange(start, start + needle.length, replacement);
@@ -22264,6 +22374,64 @@ var init_instruction_provenance = __esmMin((() => {
22264
22374
  }));
22265
22375
  //#endregion
22266
22376
  //#region ../../packages/agent-core/src/profile/context.ts
22377
+ function fitAgentsMdContext(context, maxFixedRequestBytes, measureFixedRequestBytes) {
22378
+ if (!Number.isSafeInteger(maxFixedRequestBytes) || maxFixedRequestBytes <= 0) throw new RangeError("Invalid fixed request byte budget");
22379
+ const originalBytes = measureFixedRequestBytes(context);
22380
+ if (originalBytes <= maxFixedRequestBytes) return {
22381
+ context,
22382
+ fixedRequestBytes: originalBytes,
22383
+ omittedBytes: 0,
22384
+ fits: true
22385
+ };
22386
+ const source = context.agentsMdText;
22387
+ if (source === void 0) return {
22388
+ context,
22389
+ fixedRequestBytes: originalBytes,
22390
+ omittedBytes: 0,
22391
+ fits: false
22392
+ };
22393
+ const totalBytes = source.measure().totalBytes;
22394
+ const candidateAt = (maxBytes) => {
22395
+ const { text } = source.prefixUtf8(maxBytes);
22396
+ return {
22397
+ ...context,
22398
+ agentsMd: text.content,
22399
+ agentsMdSources: text.measure(),
22400
+ agentsMdText: text
22401
+ };
22402
+ };
22403
+ let low = 0;
22404
+ let high = totalBytes;
22405
+ let fitted = candidateAt(0);
22406
+ let fittedBytes = measureFixedRequestBytes(fitted);
22407
+ if (fittedBytes > maxFixedRequestBytes) {
22408
+ const omittedBytes = context.agentsMdSources?.files.reduce((sum, file) => sum + file.bytes, 0) ?? totalBytes;
22409
+ return {
22410
+ context: fitted,
22411
+ fixedRequestBytes: fittedBytes,
22412
+ omittedBytes,
22413
+ fits: false
22414
+ };
22415
+ }
22416
+ while (low < high) {
22417
+ const middle = Math.ceil((low + high) / 2);
22418
+ const candidate = candidateAt(middle);
22419
+ const bytes = measureFixedRequestBytes(candidate);
22420
+ if (bytes <= maxFixedRequestBytes) {
22421
+ low = middle;
22422
+ fitted = candidate;
22423
+ fittedBytes = bytes;
22424
+ } else high = middle - 1;
22425
+ }
22426
+ const omittedBytes = context.agentsMdSources?.files.reduce((sum, file) => sum + file.bytes, 0) ?? totalBytes;
22427
+ const retainedBytes = fitted.agentsMdSources?.files.reduce((sum, file) => sum + file.bytes, 0) ?? 0;
22428
+ return {
22429
+ context: fitted,
22430
+ fixedRequestBytes: fittedBytes,
22431
+ omittedBytes: omittedBytes - retainedBytes,
22432
+ fits: true
22433
+ };
22434
+ }
22267
22435
  async function prepareSystemPromptContext(kaos, brandHome, options) {
22268
22436
  const additionalDirs = normalizeAdditionalDirs(options?.additionalDirs ?? []);
22269
22437
  const [cwdListing, agentsMdResult, additionalDirsInfo] = await Promise.all([
@@ -22276,7 +22444,8 @@ async function prepareSystemPromptContext(kaos, brandHome, options) {
22276
22444
  agentsMd: agentsMdResult.content,
22277
22445
  additionalDirsInfo,
22278
22446
  agentsMdWarning: agentsMdResult.warning,
22279
- agentsMdSources: agentsMdResult.sources
22447
+ agentsMdSources: agentsMdResult.sources,
22448
+ agentsMdText: agentsMdResult.text
22280
22449
  };
22281
22450
  }
22282
22451
  async function loadAgentsMd(kaos, brandHome) {
@@ -22330,6 +22499,7 @@ async function loadAgentsMdForRoots(kaos, brandHome, workDirs) {
22330
22499
  return {
22331
22500
  content,
22332
22501
  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,
22502
+ text: rendered,
22333
22503
  sources: {
22334
22504
  ...rendered.measure(),
22335
22505
  ...notLoadedCandidates.size === 0 ? {} : { notLoadedCandidates: [...notLoadedCandidates] }
@@ -26065,7 +26235,7 @@ var require_loader = /* @__PURE__ */ __commonJSMin(((exports, module) => {
26065
26235
  };
26066
26236
  return _setPrototypeOf(o, p);
26067
26237
  }
26068
- var path$15 = __require("path");
26238
+ var path$14 = __require("path");
26069
26239
  module.exports = /* @__PURE__ */ function(_EmitterObj) {
26070
26240
  _inheritsLoose(Loader, _EmitterObj);
26071
26241
  function Loader() {
@@ -26073,7 +26243,7 @@ var require_loader = /* @__PURE__ */ __commonJSMin(((exports, module) => {
26073
26243
  }
26074
26244
  var _proto = Loader.prototype;
26075
26245
  _proto.resolve = function resolve(from, to) {
26076
- return path$15.resolve(path$15.dirname(from), to);
26246
+ return path$14.resolve(path$14.dirname(from), to);
26077
26247
  };
26078
26248
  _proto.isRelative = function isRelative(filename) {
26079
26249
  return filename.indexOf("./") === 0 || filename.indexOf("../") === 0;
@@ -27729,8 +27899,8 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27729
27899
  };
27730
27900
  return _setPrototypeOf(o, p);
27731
27901
  }
27732
- var fs$15 = __require("fs");
27733
- var path$14 = __require("path");
27902
+ var fs$14 = __require("fs");
27903
+ var path$13 = __require("path");
27734
27904
  var Loader = require_loader();
27735
27905
  var PrecompiledLoader = require_precompiled_loader().PrecompiledLoader;
27736
27906
  var chokidar;
@@ -27745,7 +27915,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27745
27915
  _this.noCache = !!opts.noCache;
27746
27916
  if (searchPaths) {
27747
27917
  searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];
27748
- _this.searchPaths = searchPaths.map(path$14.normalize);
27918
+ _this.searchPaths = searchPaths.map(path$13.normalize);
27749
27919
  } else _this.searchPaths = ["."];
27750
27920
  if (opts.watch) {
27751
27921
  try {
@@ -27753,10 +27923,10 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27753
27923
  } catch (e) {
27754
27924
  throw new Error("watch requires chokidar to be installed");
27755
27925
  }
27756
- var paths = _this.searchPaths.filter(fs$15.existsSync);
27926
+ var paths = _this.searchPaths.filter(fs$14.existsSync);
27757
27927
  var watcher = chokidar.watch(paths);
27758
27928
  watcher.on("all", function(event, fullname) {
27759
- fullname = path$14.resolve(fullname);
27929
+ fullname = path$13.resolve(fullname);
27760
27930
  if (event === "change" && fullname in _this.pathsToNames) _this.emit("update", _this.pathsToNames[fullname], fullname);
27761
27931
  });
27762
27932
  watcher.on("error", function(error) {
@@ -27770,9 +27940,9 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27770
27940
  var fullpath = null;
27771
27941
  var paths = this.searchPaths;
27772
27942
  for (var i = 0; i < paths.length; i++) {
27773
- var basePath = path$14.resolve(paths[i]);
27774
- var p = path$14.resolve(paths[i], name);
27775
- if (p.indexOf(basePath) === 0 && fs$15.existsSync(p)) {
27943
+ var basePath = path$13.resolve(paths[i]);
27944
+ var p = path$13.resolve(paths[i], name);
27945
+ if (p.indexOf(basePath) === 0 && fs$14.existsSync(p)) {
27776
27946
  fullpath = p;
27777
27947
  break;
27778
27948
  }
@@ -27780,7 +27950,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27780
27950
  if (!fullpath) return null;
27781
27951
  this.pathsToNames[fullpath] = name;
27782
27952
  var source = {
27783
- src: fs$15.readFileSync(fullpath, "utf-8"),
27953
+ src: fs$14.readFileSync(fullpath, "utf-8"),
27784
27954
  path: fullpath,
27785
27955
  noCache: this.noCache
27786
27956
  };
@@ -27828,7 +27998,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27828
27998
  }
27829
27999
  this.pathsToNames[fullpath] = name;
27830
28000
  var source = {
27831
- src: fs$15.readFileSync(fullpath, "utf-8"),
28001
+ src: fs$14.readFileSync(fullpath, "utf-8"),
27832
28002
  path: fullpath,
27833
28003
  noCache: this.noCache
27834
28004
  };
@@ -28130,13 +28300,13 @@ var require_globals = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28130
28300
  //#endregion
28131
28301
  //#region ../../node_modules/.pnpm/nunjucks@3.2.4_chokidar@4.0.3/node_modules/nunjucks/src/express-app.js
28132
28302
  var require_express_app = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28133
- var path$13 = __require("path");
28303
+ var path$12 = __require("path");
28134
28304
  module.exports = function express(env, app) {
28135
28305
  function NunjucksView(name, opts) {
28136
28306
  this.name = name;
28137
28307
  this.path = name;
28138
28308
  this.defaultEngine = opts.defaultEngine;
28139
- this.ext = path$13.extname(name);
28309
+ this.ext = path$12.extname(name);
28140
28310
  if (!this.ext && !this.defaultEngine) throw new Error("No default engine was specified and no extension was provided.");
28141
28311
  if (!this.ext) this.name += this.ext = (this.defaultEngine[0] !== "." ? "." : "") + this.defaultEngine;
28142
28312
  }
@@ -28572,8 +28742,8 @@ var require_precompile_global = /* @__PURE__ */ __commonJSMin(((exports, module)
28572
28742
  //#endregion
28573
28743
  //#region ../../node_modules/.pnpm/nunjucks@3.2.4_chokidar@4.0.3/node_modules/nunjucks/src/precompile.js
28574
28744
  var require_precompile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28575
- var fs$14 = __require("fs");
28576
- var path$12 = __require("path");
28745
+ var fs$13 = __require("fs");
28746
+ var path$11 = __require("path");
28577
28747
  var _prettifyError = require_lib$8()._prettifyError;
28578
28748
  var compiler = require_compiler();
28579
28749
  var Environment = require_environment().Environment;
@@ -28597,27 +28767,27 @@ var require_precompile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28597
28767
  var env = opts.env || new Environment([]);
28598
28768
  var wrapper = opts.wrapper || precompileGlobal;
28599
28769
  if (opts.isString) return precompileString(input, opts);
28600
- var pathStats = fs$14.existsSync(input) && fs$14.statSync(input);
28770
+ var pathStats = fs$13.existsSync(input) && fs$13.statSync(input);
28601
28771
  var precompiled = [];
28602
28772
  var templates = [];
28603
28773
  function addTemplates(dir) {
28604
- fs$14.readdirSync(dir).forEach(function(file) {
28605
- var filepath = path$12.join(dir, file);
28606
- var subpath = filepath.substr(path$12.join(input, "/").length);
28607
- var stat = fs$14.statSync(filepath);
28774
+ fs$13.readdirSync(dir).forEach(function(file) {
28775
+ var filepath = path$11.join(dir, file);
28776
+ var subpath = filepath.substr(path$11.join(input, "/").length);
28777
+ var stat = fs$13.statSync(filepath);
28608
28778
  if (stat && stat.isDirectory()) {
28609
28779
  subpath += "/";
28610
28780
  if (!match(subpath, opts.exclude)) addTemplates(filepath);
28611
28781
  } else if (match(subpath, opts.include)) templates.push(filepath);
28612
28782
  });
28613
28783
  }
28614
- if (pathStats.isFile()) precompiled.push(_precompile(fs$14.readFileSync(input, "utf-8"), opts.name || input, env));
28784
+ if (pathStats.isFile()) precompiled.push(_precompile(fs$13.readFileSync(input, "utf-8"), opts.name || input, env));
28615
28785
  else if (pathStats.isDirectory()) {
28616
28786
  addTemplates(input);
28617
28787
  for (var i = 0; i < templates.length; i++) {
28618
- var name = templates[i].replace(path$12.join(input, "/"), "");
28788
+ var name = templates[i].replace(path$11.join(input, "/"), "");
28619
28789
  try {
28620
- precompiled.push(_precompile(fs$14.readFileSync(templates[i], "utf-8"), name, env));
28790
+ precompiled.push(_precompile(fs$13.readFileSync(templates[i], "utf-8"), name, env));
28621
28791
  } catch (e) {
28622
28792
  if (opts.force) console.error(e);
28623
28793
  else throw e;
@@ -29835,7 +30005,7 @@ var init_per_id_json_store = __esmMin((() => {
29835
30005
  }));
29836
30006
  //#endregion
29837
30007
  //#region ../../packages/agent-core/src/agent/background/resume-store.ts
29838
- var BACKGROUND_TASK_ID, id, digest$2, timestamp$2, ResumeIntentSchema, hash$3, isRecord$25, TaskResumeStore;
30008
+ var BACKGROUND_TASK_ID, id, digest$2, timestamp$2, ResumeIntentSchema, hash$3, isRecord$29, TaskResumeStore;
29839
30009
  var init_resume_store = __esmMin((() => {
29840
30010
  init_zod$1();
29841
30011
  BACKGROUND_TASK_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-z]{8}$/;
@@ -29860,7 +30030,7 @@ var init_resume_store = __esmMin((() => {
29860
30030
  startedAt: timestamp$2.nullable()
29861
30031
  }).strict();
29862
30032
  hash$3 = (value) => createHash("sha256").update(value).digest("hex");
29863
- isRecord$25 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
30033
+ isRecord$29 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
29864
30034
  TaskResumeStore = class {
29865
30035
  home;
29866
30036
  constructor(home) {
@@ -29915,9 +30085,9 @@ var init_resume_store = __esmMin((() => {
29915
30085
  }
29916
30086
  async readOwnedTask(taskId) {
29917
30087
  const task = await this.read("tasks", taskId);
29918
- if (!isRecord$25(task)) throw new Error("Task has no persisted local record.");
30088
+ if (!isRecord$29(task)) throw new Error("Task has no persisted local record.");
29919
30089
  const owner = task["resumeOwnership"];
29920
- if (!isRecord$25(owner) || owner["version"] !== 1 || owner["scope"] !== hash$3(await this.root()) || owner["taskId"] !== taskId || task["taskId"] !== taskId || task["kind"] !== "agent" || owner["agentId"] !== task["agentId"] || owner["startedAt"] !== task["startedAt"]) throw new Error("Task ownership is unverified; historical or foreign records cannot be resumed automatically.");
30090
+ if (!isRecord$29(owner) || owner["version"] !== 1 || owner["scope"] !== hash$3(await this.root()) || owner["taskId"] !== taskId || task["taskId"] !== taskId || task["kind"] !== "agent" || owner["agentId"] !== task["agentId"] || owner["startedAt"] !== task["startedAt"]) throw new Error("Task ownership is unverified; historical or foreign records cannot be resumed automatically.");
29921
30091
  const { resumeOwnership: _ownership, ...info } = task;
29922
30092
  return info;
29923
30093
  }
@@ -30038,12 +30208,12 @@ function legacyStatusToCurrent$1(task) {
30038
30208
  return task.status;
30039
30209
  }
30040
30210
  function isReadablePersistedTask$1(obj) {
30041
- return isRecord$24(obj) && (typeof obj["taskId"] === "string" || typeof obj["task_id"] === "string");
30211
+ return isRecord$28(obj) && (typeof obj["taskId"] === "string" || typeof obj["task_id"] === "string");
30042
30212
  }
30043
30213
  function isLegacyPersistedTask$1(task) {
30044
30214
  return "task_id" in task;
30045
30215
  }
30046
- function isRecord$24(value) {
30216
+ function isRecord$28(value) {
30047
30217
  return typeof value === "object" && value !== null;
30048
30218
  }
30049
30219
  function optionalNonEmptyString$2(value) {
@@ -32658,7 +32828,7 @@ var require_buffer_from = /* @__PURE__ */ __commonJSMin(((exports, module) => {
32658
32828
  //#region ../../node_modules/.pnpm/source-map-support@0.5.21/node_modules/source-map-support/source-map-support.js
32659
32829
  var require_source_map_support = /* @__PURE__ */ __commonJSMin(((exports, module) => {
32660
32830
  var SourceMapConsumer = require_source_map().SourceMapConsumer;
32661
- var path$11 = __require("path");
32831
+ var path$10 = __require("path");
32662
32832
  var fs;
32663
32833
  try {
32664
32834
  fs = __require("fs");
@@ -32735,15 +32905,15 @@ var require_source_map_support = /* @__PURE__ */ __commonJSMin(((exports, module
32735
32905
  });
32736
32906
  function supportRelativeURL(file, url) {
32737
32907
  if (!file) return url;
32738
- var dir = path$11.dirname(file);
32908
+ var dir = path$10.dirname(file);
32739
32909
  var match = /^\w+:\/\/[^\/]*/.exec(dir);
32740
32910
  var protocol = match ? match[0] : "";
32741
32911
  var startPath = dir.slice(protocol.length);
32742
32912
  if (protocol && /^\/\w\:/.test(startPath)) {
32743
32913
  protocol += "/";
32744
- return protocol + path$11.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
32914
+ return protocol + path$10.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
32745
32915
  }
32746
- return protocol + path$11.resolve(dir.slice(protocol.length), url);
32916
+ return protocol + path$10.resolve(dir.slice(protocol.length), url);
32747
32917
  }
32748
32918
  function retrieveSourceMapURL(source) {
32749
32919
  var fileData;
@@ -191986,7 +192156,7 @@ var require_gifframe = /* @__PURE__ */ __commonJSMin(((exports) => {
191986
192156
  //#region ../../node_modules/.pnpm/gifwrap@0.10.1/node_modules/gifwrap/src/gifutil.js
191987
192157
  var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
191988
192158
  /** @namespace GifUtil */
191989
- const fs$13 = __require("fs");
192159
+ const fs$12 = __require("fs");
191990
192160
  const ImageQ = require_image_q();
191991
192161
  const BitmapImage = require_bitmapimage();
191992
192162
  const { GifFrame } = require_gifframe();
@@ -192253,7 +192423,7 @@ var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
192253
192423
  }
192254
192424
  function _readBinary(path) {
192255
192425
  return new Promise((resolve, reject) => {
192256
- fs$13.readFile(path, (err, buffer) => {
192426
+ fs$12.readFile(path, (err, buffer) => {
192257
192427
  if (err) return reject(err);
192258
192428
  return resolve(buffer);
192259
192429
  });
@@ -192261,7 +192431,7 @@ var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
192261
192431
  }
192262
192432
  function _writeBinary(path, buffer) {
192263
192433
  return new Promise((resolve, reject) => {
192264
- fs$13.writeFile(path, buffer, (err) => {
192434
+ fs$12.writeFile(path, buffer, (err) => {
192265
192435
  if (err) return reject(err);
192266
192436
  return resolve();
192267
192437
  });
@@ -218079,7 +218249,7 @@ var init_file_type = __esmMin((() => {
218079
218249
  }
218080
218250
  async fromFile(path) {
218081
218251
  this.options.signal?.throwIfAborted();
218082
- const fileHandle = await fs.open(path, constants.O_RDONLY | constants.O_NONBLOCK);
218252
+ const fileHandle = await ro.open(path, constants.O_RDONLY | constants.O_NONBLOCK);
218083
218253
  const fileStat = await fileHandle.stat();
218084
218254
  if (!fileStat.isFile()) {
218085
218255
  await fileHandle.close();
@@ -228584,7 +228754,7 @@ async function processBitmapFont(file, font) {
228584
228754
  ...font,
228585
228755
  chars,
228586
228756
  kernings,
228587
- pages: await Promise.all(font.pages.map(async (page) => CharacterJimp.read(path$1.join(path$1.dirname(file), page))))
228757
+ pages: await Promise.all(font.pages.map(async (page) => CharacterJimp.read(js.join(js.dirname(file), page))))
228588
228758
  };
228589
228759
  }
228590
228760
  var import_parse_bmfont_ascii, import_lib$1, import_parse_bmfont_binary, convertXML, isWebWorker, CharacterJimp, HEADER;
@@ -229641,7 +229811,7 @@ function escapeXml(value) {
229641
229811
  function locationKey(messageIndex, partIndex) {
229642
229812
  return `${String(messageIndex)}:${String(partIndex)}`;
229643
229813
  }
229644
- function isRecord$23(value) {
229814
+ function isRecord$27(value) {
229645
229815
  return value !== null && typeof value === "object" && !Array.isArray(value);
229646
229816
  }
229647
229817
  function isNonNegativeInteger$1(value) {
@@ -229842,7 +230012,7 @@ var init_vision_reader = __esmMin((() => {
229842
230012
  reason: "malformed"
229843
230013
  };
229844
230014
  }
229845
- if (!isRecord$23(payload) || payload["done"] !== true || typeof payload["response"] !== "string" || !isNonNegativeInteger$1(payload["prompt_eval_count"]) || !isNonNegativeInteger$1(payload["eval_count"])) return {
230015
+ if (!isRecord$27(payload) || payload["done"] !== true || typeof payload["response"] !== "string" || !isNonNegativeInteger$1(payload["prompt_eval_count"]) || !isNonNegativeInteger$1(payload["eval_count"])) return {
229846
230016
  ok: false,
229847
230017
  reason: "malformed"
229848
230018
  };
@@ -230922,7 +231092,7 @@ var init_full = __esmMin((() => {
230922
231092
  MAX_SESSION_COMPACTION_FAILURES = 2;
230923
231093
  DEFAULT_COMPACTION_MAX_COMPLETION_TOKENS = 128 * 1024;
230924
231094
  COMPACTION_SUMMARY_RESERVE_RATIO = .1;
230925
- BLUN_COMPACTION_REQUEST_BUDGET_BYTES = 75e4;
231095
+ BLUN_COMPACTION_REQUEST_BUDGET_BYTES = 48e4;
230926
231096
  MAX_HIERARCHICAL_COMPACTION_PASSES = 64;
230927
231097
  HIERARCHICAL_COMPACTION_PREFIX = "This is a complete summary of an earlier chronological segment. Preserve it as source material when merging it with the following conversation:";
230928
231098
  CompactionTruncatedError = class extends Error {
@@ -231074,30 +231244,14 @@ var init_full = __esmMin((() => {
231074
231244
  }
231075
231245
  requestBodyByteBudget(messages, context) {
231076
231246
  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;
231247
+ if (!this.agent.config.hasProvider || this.strategy.compactionBudgetTokens === void 0 || limit !== void 0 && (!Number.isSafeInteger(limit) || limit <= 0)) return void 0;
231078
231248
  const model = this.agent.activeResponderModel ?? this.agent.config.modelAlias;
231079
231249
  if (model === void 0 || this.agent.config.runtimeModel(model).provider.name !== "blun") return void 0;
231080
231250
  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;
231251
+ const tools = context.tools ?? this.agent.tools.loopTools;
231252
+ if (estimateBlunSerializedBodyBytes(systemPrompt, [], []) + 4096 >= BLUN_COMPACTION_REQUEST_BUDGET_BYTES) return void 0;
231096
231253
  return {
231097
- usedRequestBytesEstimate: Buffer.byteLength(JSON.stringify({
231098
- systemPrompt,
231099
- messages
231100
- }), "utf8") + extraBytes.toolsBytes + extraBytes.visionBytes,
231254
+ usedRequestBytesEstimate: estimateBlunSerializedBodyBytes(systemPrompt, tools, messages) + 4096,
231101
231255
  thresholdRequestBytes: BLUN_COMPACTION_REQUEST_BUDGET_BYTES
231102
231256
  };
231103
231257
  }
@@ -231452,7 +231606,7 @@ var init_full = __esmMin((() => {
231452
231606
  dropOrphanResults: true
231453
231607
  }), createUserMessage(requestInstruction)], capability));
231454
231608
  };
231455
- const estimateRequestBytes = (messages) => Buffer.byteLength(JSON.stringify(messages), "utf8") + Buffer.byteLength(this.agent.config.systemPrompt, "utf8");
231609
+ const estimateRequestBytes = (messages) => estimateBlunSerializedBodyBytes(this.agent.effectiveSystemPrompt, compactionTools, messages) + 4096;
231456
231610
  while (true) {
231457
231611
  signal.throwIfAborted();
231458
231612
  if (hierarchicalPassCount >= MAX_HIERARCHICAL_COMPACTION_PASSES) throw new BlunError(ErrorCodes.COMPACTION_FAILED, `Compaction stopped after ${String(MAX_HIERARCHICAL_COMPACTION_PASSES)} staged requests without reaching a final summary. The conversation history was not changed.`, { details: {
@@ -236173,7 +236327,7 @@ function structuredOutput(stdout, input) {
236173
236327
  return {
236174
236328
  ...result,
236175
236329
  additionalContext: input["hook_event_name"] === "UserPromptSubmit" && hookSpecificOutput?.hookEventName === "UserPromptSubmit" ? hookSpecificOutput.additionalContext : void 0,
236176
- updatedInput: input["hook_event_name"] === "PreToolUse" && hookSpecificOutput?.hookEventName === "PreToolUse" && isRecord$22(hookSpecificOutput.updatedInput) ? hookSpecificOutput.updatedInput : void 0
236330
+ updatedInput: input["hook_event_name"] === "PreToolUse" && hookSpecificOutput?.hookEventName === "PreToolUse" && isRecord$26(hookSpecificOutput.updatedInput) ? hookSpecificOutput.updatedInput : void 0
236177
236331
  };
236178
236332
  }
236179
236333
  return {
@@ -236242,7 +236396,7 @@ function killProcessTreeWindows(child, force) {
236242
236396
  } catch {}
236243
236397
  }
236244
236398
  }
236245
- function isRecord$22(value) {
236399
+ function isRecord$26(value) {
236246
236400
  return typeof value === "object" && value !== null && !Array.isArray(value);
236247
236401
  }
236248
236402
  function errorMessage$12(error) {
@@ -236259,7 +236413,7 @@ var init_runner = __esmMin((() => {
236259
236413
  if (typeof value === "string") return value;
236260
236414
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
236261
236415
  }, string().optional());
236262
- HookSpecificOutputSchema = preprocess((value) => isRecord$22(value) ? value : void 0, looseObject({
236416
+ HookSpecificOutputSchema = preprocess((value) => isRecord$26(value) ? value : void 0, looseObject({
236263
236417
  message: OptionalStringSchema,
236264
236418
  additionalContext: OptionalStringSchema,
236265
236419
  permissionDecision: unknown().optional(),
@@ -237547,7 +237701,7 @@ function parsePersonalMemoryRecall(output) {
237547
237701
  } catch {
237548
237702
  return { kind: "invalid" };
237549
237703
  }
237550
- if (!isRecord$21(parsed) || !isRecord$21(parsed["personal_memory"])) return { kind: "invalid" };
237704
+ if (!isRecord$25(parsed) || !isRecord$25(parsed["personal_memory"])) return { kind: "invalid" };
237551
237705
  const memory = parsed["personal_memory"];
237552
237706
  const savedRaw = memory["saved"];
237553
237707
  const threadsRaw = memory["threads"];
@@ -237556,7 +237710,7 @@ function parsePersonalMemoryRecall(output) {
237556
237710
  if (savedRaw.length > MAX_SAVED_MEMORIES || threadsRaw.length > MAX_THREADS || historyRaw.length > 0) return { kind: "invalid" };
237557
237711
  const saved = [];
237558
237712
  for (const value of savedRaw) {
237559
- if (!isRecord$21(value)) return { kind: "invalid" };
237713
+ if (!isRecord$25(value)) return { kind: "invalid" };
237560
237714
  const text = boundedTrimmedString(value["text"], MAX_MEMORY_TEXT_CHARS);
237561
237715
  const confidence = value["confidence"];
237562
237716
  if (text === void 0 || typeof confidence !== "string" || !CONFIDENCE_VALUES.has(confidence)) return { kind: "invalid" };
@@ -237567,7 +237721,7 @@ function parsePersonalMemoryRecall(output) {
237567
237721
  }
237568
237722
  const threads = [];
237569
237723
  for (const value of threadsRaw) {
237570
- if (!isRecord$21(value)) return { kind: "invalid" };
237724
+ if (!isRecord$25(value)) return { kind: "invalid" };
237571
237725
  const title = boundedTrimmedString(value["title"], MAX_THREAD_TITLE_CHARS);
237572
237726
  const summary = boundedTrimmedString(value["summary"], MAX_THREAD_SUMMARY_CHARS);
237573
237727
  if (title === void 0 || summary === void 0) return { kind: "invalid" };
@@ -237621,7 +237775,7 @@ function boundedTrimmedString(value, maxChars) {
237621
237775
  const trimmed = value.trim();
237622
237776
  return trimmed.length > 0 ? trimmed : void 0;
237623
237777
  }
237624
- function isRecord$21(value) {
237778
+ function isRecord$25(value) {
237625
237779
  return typeof value === "object" && value !== null && !Array.isArray(value);
237626
237780
  }
237627
237781
  var PERSONAL_MEMORY_HOST_RECALL_HANDLER$1, RECALL_LIMIT, RECALL_TIMEOUT_MS, MAX_QUERY_CHARS, MAX_WIRE_CHARS, MAX_SAVED_MEMORIES, MAX_THREADS, MAX_MEMORY_TEXT_CHARS, MAX_THREAD_TITLE_CHARS, MAX_THREAD_SUMMARY_CHARS, CONFIDENCE_VALUES, TELEGRAM_GROUP_MARKER_RE, TELEGRAM_MARKER_RE, TELEGRAM_CHANNEL_RE, TELEGRAM_SOURCE_RE, TELEGRAM_CHAT_ID_RE, TELEGRAM_SENDER_LINE_RE, TELEGRAM_ATTACHMENT_BLOCK_RE, TELEGRAM_ATTACHMENT_NOTICE_RE, TELEGRAM_IMAGE_ATTACHMENT_RE, GENERIC_IMAGE_QUERY, GENERIC_FILE_QUERY, GENERIC_EMPTY_QUERY, PERSONAL_MEMORY_RECALL_VARIANT, PersonalMemoryRecallInjector;
@@ -240076,10 +240230,27 @@ var require_turn_tool_performance_policy = /* @__PURE__ */ __commonJSMin(((expor
240076
240230
  function relatedSearchTerms(token) {
240077
240231
  return TOOL_SEARCH_RELATED_TERM_GROUPS.find((terms) => terms.includes(token)) || [token];
240078
240232
  }
240233
+ function withoutFencedCode(value) {
240234
+ const visibleLines = [];
240235
+ let fence = null;
240236
+ for (const line of String(value || "").split(/\r?\n/)) {
240237
+ const marker = line.match(/^ {0,3}(`{3,}|~{3,})/u)?.[1];
240238
+ if (fence) {
240239
+ if (marker?.[0] === fence[0] && marker.length >= fence.length && /^ {0,3}(?:`{3,}|~{3,})[ \t]*$/u.test(line)) fence = null;
240240
+ continue;
240241
+ }
240242
+ if (marker) {
240243
+ fence = marker;
240244
+ continue;
240245
+ }
240246
+ visibleLines.push(line);
240247
+ }
240248
+ return visibleLines.join("\n");
240249
+ }
240079
240250
  function rankingIntentTexts(value) {
240080
240251
  const text = String(value || "");
240081
240252
  const channelBodies = [...text.matchAll(/(?:^|\r?\n)<channel\b[^>]*>\r?\n([\s\S]*?)\r?\n<\/channel>(?=\r?\n|$)/giu)].map((match) => match[1]);
240082
- return (channelBodies.length > 0 ? channelBodies : [text]).map((intentText) => normalizeDeferredToolQuery(intentText.replace(TOOL_RANK_EMBEDDED_CONTENT_RE, " ")));
240253
+ return (channelBodies.length > 0 ? channelBodies : [text]).map((intentText) => normalizeDeferredToolQuery(withoutFencedCode(intentText.replace(TOOL_RANK_EMBEDDED_CONTENT_RE, " "))));
240083
240254
  }
240084
240255
  function rankingTokens(value) {
240085
240256
  return [...new Set(String(value || "").normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}]{3,}/gu) || [])].filter((token) => !TOOL_RANK_STOP_WORDS.has(token));
@@ -251175,7 +251346,8 @@ function logStepTiming(log, turnId, step, response) {
251175
251346
  inputOtherTokens: response.usage.inputOther,
251176
251347
  cacheReadTokens: response.usage.inputCacheRead,
251177
251348
  cacheCreationTokens: response.usage.inputCacheCreation,
251178
- outputTokens: response.usage.output
251349
+ outputTokens: response.usage.output,
251350
+ ...response.usage.outputReasoning === void 0 ? {} : { outputReasoningTokens: response.usage.outputReasoning }
251179
251351
  });
251180
251352
  }
251181
251353
  function deriveStepStopReason(response) {
@@ -252249,6 +252421,7 @@ var init_events$1 = __esmMin((() => {
252249
252421
  tokenUsageSchema = object$1({
252250
252422
  inputOther: number$1(),
252251
252423
  output: number$1(),
252424
+ outputReasoning: number$1().optional(),
252252
252425
  inputCacheRead: number$1(),
252253
252426
  inputCacheCreation: number$1()
252254
252427
  });
@@ -253429,7 +253602,7 @@ function createAsyncApiDocument(options = {}) {
253429
253602
  function buildMessages() {
253430
253603
  const messages = {};
253431
253604
  for (const operation of ASYNCAPI_OPERATIONS) {
253432
- const id = messageId$1(operation.type);
253605
+ const id = messageId$2(operation.type);
253433
253606
  messages[id] = asyncApiMessage(operation.type, operation.description, operation.messageSchema);
253434
253607
  if (operation.ackSchema !== void 0) {
253435
253608
  const ackId = `${id}_ack`;
@@ -253439,10 +253612,10 @@ function buildMessages() {
253439
253612
  return messages;
253440
253613
  }
253441
253614
  function operationMessageRefs(direction) {
253442
- return ASYNCAPI_OPERATIONS.filter((operation) => operation.direction === direction).map((operation) => ({ $ref: `#/components/messages/${messageId$1(operation.type)}` }));
253615
+ return ASYNCAPI_OPERATIONS.filter((operation) => operation.direction === direction).map((operation) => ({ $ref: `#/components/messages/${messageId$2(operation.type)}` }));
253443
253616
  }
253444
253617
  function ackMessageRefs() {
253445
- return ASYNCAPI_OPERATIONS.filter((operation) => operation.ackSchema !== void 0).map((operation) => ({ $ref: `#/components/messages/${messageId$1(operation.type)}_ack` }));
253618
+ return ASYNCAPI_OPERATIONS.filter((operation) => operation.ackSchema !== void 0).map((operation) => ({ $ref: `#/components/messages/${messageId$2(operation.type)}_ack` }));
253446
253619
  }
253447
253620
  function asyncApiMessage(name, summary, schema) {
253448
253621
  return {
@@ -253462,7 +253635,7 @@ function jsonSchema$1(schema) {
253462
253635
  delete converted["$schema"];
253463
253636
  return converted;
253464
253637
  }
253465
- function messageId$1(type) {
253638
+ function messageId$2(type) {
253466
253639
  return type.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
253467
253640
  }
253468
253641
  function titleFromName(name) {
@@ -259241,7 +259414,7 @@ function Yn(s, t) {
259241
259414
  function Kn(s, t) {
259242
259415
  s.head = new ue$1(t, void 0, s.head, s), s.tail || (s.tail = s.head), s.length++;
259243
259416
  }
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;
259417
+ 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;
259245
259418
  var init_index_min = __esmMin((() => {
259246
259419
  zr = Object.defineProperty;
259247
259420
  Ur = (s, t) => {
@@ -260769,7 +260942,7 @@ while (this[Zs](this[st$1].shift()));
260769
260942
  let [o, h] = ce$1(this.path);
260770
260943
  o && typeof h == "string" && (this.path = h, r = o);
260771
260944
  }
260772
- this.win32 = !!i.win32 || process.platform === "win32", this.win32 && (this.path = Qs(this.path.replaceAll(/\\/g, "/")), t = t.replaceAll(/\\/g, "/")), this.absolute = f(i.absolute || path$1.resolve(this.cwd, t)), this.path === "" && (this.path = "./"), r && this.warn("TAR_ENTRY_INFO", `stripping ${r} from absolute path`, {
260945
+ this.win32 = !!i.win32 || process.platform === "win32", this.win32 && (this.path = Qs(this.path.replaceAll(/\\/g, "/")), t = t.replaceAll(/\\/g, "/")), this.absolute = f(i.absolute || js.resolve(this.cwd, t)), this.path === "" && (this.path = "./"), r && this.warn("TAR_ENTRY_INFO", `stripping ${r} from absolute path`, {
260773
260946
  entry: this,
260774
260947
  path: r + this.path
260775
260948
  });
@@ -260852,7 +261025,7 @@ while (this[Zs](this[st$1].shift()));
260852
261025
  }
260853
261026
  [sr](t) {
260854
261027
  if (!this.stat) throw new Error("cannot create link entry without stat");
260855
- this.type = "Link", this.linkpath = f(path$1.relative(this.cwd, t)), this.stat.size = 0, this[fe$1](), this.end();
261028
+ this.type = "Link", this.linkpath = f(js.relative(this.cwd, t)), this.stat.size = 0, this[fe$1](), this.end();
260856
261029
  }
260857
261030
  [er]() {
260858
261031
  if (!this.stat) throw new Error("cannot create file entry without stat");
@@ -261211,7 +261384,7 @@ while (this[Zs](this[st$1].shift()));
261211
261384
  constructor(t, e) {
261212
261385
  this.path = t || "./", this.absolute = e;
261213
261386
  }
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 {
261387
+ }, 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 {
261215
261388
  sync = !1;
261216
261389
  opt;
261217
261390
  cwd;
@@ -261244,8 +261417,8 @@ while (this[Zs](this[st$1].shift()));
261244
261417
  if ((t.gzip ? 1 : 0) + (t.brotli ? 1 : 0) + (t.zstd ? 1 : 0) > 1) throw new TypeError("gzip, brotli, zstd are mutually exclusive");
261245
261418
  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");
261246
261419
  let e = this.zip;
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]);
261420
+ e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs$11]()), this.on("resume", () => e.resume());
261421
+ } else this.on("drain", this[fs$11]);
261249
261422
  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;
261250
261423
  }
261251
261424
  [lr](t) {
@@ -261262,7 +261435,7 @@ while (this[Zs](this[st$1].shift()));
261262
261435
  return typeof t == "string" ? this[ci](t) : this[or](t), this.flowing;
261263
261436
  }
261264
261437
  [or](t) {
261265
- let e = f(path$1.resolve(this.cwd, t.path));
261438
+ let e = f(js.resolve(this.cwd, t.path));
261266
261439
  if (!this.filter(t.path, t)) t.resume();
261267
261440
  else {
261268
261441
  let i = new pi(t.path, e);
@@ -261271,7 +261444,7 @@ while (this[Zs](this[st$1].shift()));
261271
261444
  this[Ft$1]();
261272
261445
  }
261273
261446
  [ci](t) {
261274
- let e = f(path$1.resolve(this.cwd, t));
261447
+ let e = f(js.resolve(this.cwd, t));
261275
261448
  this[W$1].push(new pi(t, e)), this[Ft$1]();
261276
261449
  }
261277
261450
  [ds](t) {
@@ -261372,7 +261545,7 @@ while (this[Zs](this[st$1].shift()));
261372
261545
  this.emit("error", e);
261373
261546
  }
261374
261547
  }
261375
- [fs$12]() {
261548
+ [fs$11]() {
261376
261549
  this[Et] && this[Et].entry && this[Et].entry.resume();
261377
261550
  }
261378
261551
  [di](t) {
@@ -261538,7 +261711,7 @@ while (this[Zs](this[st$1].shift()));
261538
261711
  E ? e(E) : x && a ? Es(x, o, h, (Le) => y(Le)) : n ? Kt.chmod(s, r, e) : e();
261539
261712
  };
261540
261713
  if (s === d) return no(s, y);
261541
- if (l) return fs.mkdir(s, {
261714
+ if (l) return ro.mkdir(s, {
261542
261715
  mode: r,
261543
261716
  recursive: !0
261544
261717
  }).then((E) => y(null, E ?? void 0), y);
@@ -262297,7 +262470,7 @@ var require_pend = /* @__PURE__ */ __commonJSMin(((exports, module) => {
262297
262470
  //#endregion
262298
262471
  //#region ../../node_modules/.pnpm/yauzl@3.3.0/node_modules/yauzl/fd-slicer.js
262299
262472
  var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262300
- var fs$11 = __require("fs");
262473
+ var fs$10 = __require("fs");
262301
262474
  var util$6 = __require("util");
262302
262475
  var stream$2 = __require("stream");
262303
262476
  var Readable = stream$2.Readable;
@@ -262322,7 +262495,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262322
262495
  FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
262323
262496
  var self = this;
262324
262497
  self.pend.go(function(cb) {
262325
- fs$11.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
262498
+ fs$10.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
262326
262499
  cb();
262327
262500
  callback(err, bytesRead, buffer);
262328
262501
  });
@@ -262331,7 +262504,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262331
262504
  FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
262332
262505
  var self = this;
262333
262506
  self.pend.go(function(cb) {
262334
- fs$11.write(self.fd, buffer, offset, length, position, function(err, written, buffer) {
262507
+ fs$10.write(self.fd, buffer, offset, length, position, function(err, written, buffer) {
262335
262508
  cb();
262336
262509
  callback(err, written, buffer);
262337
262510
  });
@@ -262351,7 +262524,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262351
262524
  self.refCount -= 1;
262352
262525
  if (self.refCount > 0) return;
262353
262526
  if (self.refCount < 0) throw new Error("invalid unref");
262354
- if (self.autoClose) fs$11.close(self.fd, onCloseDone);
262527
+ if (self.autoClose) fs$10.close(self.fd, onCloseDone);
262355
262528
  function onCloseDone(err) {
262356
262529
  if (err) self.emit("error", err);
262357
262530
  else self.emit("close");
@@ -262382,7 +262555,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262382
262555
  self.context.pend.go(function(cb) {
262383
262556
  if (self.destroyed) return cb();
262384
262557
  var buffer = Buffer.allocUnsafe(toRead);
262385
- fs$11.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
262558
+ fs$10.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
262386
262559
  if (err) self.destroy(err);
262387
262560
  else if (bytesRead === 0) {
262388
262561
  self.destroyed = true;
@@ -262428,7 +262601,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
262428
262601
  }
262429
262602
  self.context.pend.go(function(cb) {
262430
262603
  if (self.destroyed) return cb();
262431
- fs$11.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) {
262604
+ fs$10.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) {
262432
262605
  if (err) {
262433
262606
  self.destroy();
262434
262607
  cb();
@@ -266341,14 +266514,14 @@ async function readGitExecPath(deps, gitExe) {
266341
266514
  }
266342
266515
  }
266343
266516
  function gitBashCandidatesFromGitExe(gitExe) {
266344
- const normalizedGitExe = path$17.win32.normalize(normalizeWindowsPath(gitExe));
266345
- const gitDir = path$17.win32.dirname(normalizedGitExe);
266346
- const gitDirName = path$17.win32.basename(gitDir).toLowerCase();
266517
+ const normalizedGitExe = path$16.win32.normalize(normalizeWindowsPath(gitExe));
266518
+ const gitDir = path$16.win32.dirname(normalizedGitExe);
266519
+ const gitDirName = path$16.win32.basename(gitDir).toLowerCase();
266347
266520
  if (gitDirName !== "cmd" && gitDirName !== "bin") return;
266348
- return gitBashCandidatesFromGitRoot(path$17.win32.dirname(gitDir));
266521
+ return gitBashCandidatesFromGitRoot(path$16.win32.dirname(gitDir));
266349
266522
  }
266350
266523
  function gitBashCandidatesFromGitExecPath(execPath) {
266351
- const normalized = path$17.win32.normalize(normalizeWindowsPath(execPath));
266524
+ const normalized = path$16.win32.normalize(normalizeWindowsPath(execPath));
266352
266525
  const parts = normalized.split("\\");
266353
266526
  for (let i = parts.length - 1; i >= 0; i -= 1) {
266354
266527
  const segment = parts[i]?.toLowerCase();
@@ -266357,16 +266530,16 @@ function gitBashCandidatesFromGitExecPath(execPath) {
266357
266530
  if (root.length > 0) return gitBashCandidatesFromGitRoot(root);
266358
266531
  }
266359
266532
  }
266360
- return gitBashCandidatesFromGitRoot(path$17.win32.join(normalized, "..", ".."));
266533
+ return gitBashCandidatesFromGitRoot(path$16.win32.join(normalized, "..", ".."));
266361
266534
  }
266362
266535
  function gitBashCandidatesFromGitRoot(root) {
266363
- return [path$17.win32.normalize(path$17.win32.join(root, "bin", "bash.exe")), path$17.win32.normalize(path$17.win32.join(root, "usr", "bin", "bash.exe"))];
266536
+ return [path$16.win32.normalize(path$16.win32.join(root, "bin", "bash.exe")), path$16.win32.normalize(path$16.win32.join(root, "usr", "bin", "bash.exe"))];
266364
266537
  }
266365
266538
  function normalizeWindowsPath(path) {
266366
266539
  return path.replaceAll("/", "\\");
266367
266540
  }
266368
266541
  function isAbsoluteWindowsPath(path) {
266369
- return path$17.win32.isAbsolute(normalizeWindowsPath(path));
266542
+ return path$16.win32.isAbsolute(normalizeWindowsPath(path));
266370
266543
  }
266371
266544
  function dedupeWindowsPaths(paths) {
266372
266545
  const deduped = [];
@@ -269056,6 +269229,10 @@ var init_turn = __esmMin((() => {
269056
269229
  signal.throwIfAborted();
269057
269230
  const blockResult = renderUserPromptHookBlockResult(promptHookResults);
269058
269231
  if (blockResult !== void 0) {
269232
+ this.agent.log.warn("turn blocked by UserPromptSubmit hook", {
269233
+ turnId,
269234
+ reason: blockResult.message
269235
+ });
269059
269236
  this.agent.context.appendMessage({
269060
269237
  role: "assistant",
269061
269238
  content: [{
@@ -269273,6 +269450,17 @@ var init_turn = __esmMin((() => {
269273
269450
  signal.throwIfAborted();
269274
269451
  if (stopBlock !== void 0) {
269275
269452
  stopHookContinuationUsed = true;
269453
+ this.agent.log.warn("turn continuation blocked by Stop hook", {
269454
+ turnId,
269455
+ reason: stopBlock.reason
269456
+ });
269457
+ this.agent.emitEvent({
269458
+ type: "hook.result",
269459
+ turnId,
269460
+ hookEvent: "Stop",
269461
+ content: stopBlock.reason,
269462
+ blocked: true
269463
+ });
269276
269464
  this.agent.context.appendUserMessage([{
269277
269465
  type: "text",
269278
269466
  text: stopBlock.reason
@@ -272739,6 +272927,7 @@ var init_fallback_llm = __esmMin((() => {
272739
272927
  throw new Error("Fallback request preparation requires a fresh request boundary.");
272740
272928
  }
272741
272929
  let requestParams = params;
272930
+ let messagesReady = false;
272742
272931
  const rebuildRequestMessages = async () => {
272743
272932
  const messages = await rebuildMessages();
272744
272933
  const suffix = requestParams.boundaryMessageSuffix;
@@ -272747,7 +272936,14 @@ var init_fallback_llm = __esmMin((() => {
272747
272936
  while (true) {
272748
272937
  const candidate = this.current;
272749
272938
  try {
272750
- requestParams = await this.prepareRequest?.(candidate, requestParams, rebuildRequestMessages) ?? requestParams;
272939
+ const prepared = await this.prepareRequest?.(candidate, requestParams, rebuildRequestMessages);
272940
+ if (prepared !== void 0) if ("messagesReady" in prepared) {
272941
+ requestParams = prepared.params;
272942
+ messagesReady = true;
272943
+ } else {
272944
+ requestParams = prepared;
272945
+ messagesReady = false;
272946
+ }
272751
272947
  } catch (error) {
272752
272948
  if (!isFallbackCandidateError(error) && !isUnavailableFallbackCandidate(error)) throw error;
272753
272949
  const nextIndex = this.findNextCandidateIndex();
@@ -272757,13 +272953,14 @@ var init_fallback_llm = __esmMin((() => {
272757
272953
  ...requestParams,
272758
272954
  messages: await rebuildRequestMessages()
272759
272955
  };
272956
+ messagesReady = false;
272760
272957
  requestParams.signal.throwIfAborted();
272761
272958
  this.currentIndex = nextIndex;
272762
272959
  this.onModelChanged(this.current.alias);
272763
272960
  continue;
272764
272961
  }
272765
272962
  requestParams.signal.throwIfAborted();
272766
- const messages = await rebuildRequestMessages();
272963
+ const messages = messagesReady ? requestParams.messages : await rebuildRequestMessages();
272767
272964
  requestParams.signal.throwIfAborted();
272768
272965
  return {
272769
272966
  ...requestParams,
@@ -273088,6 +273285,11 @@ var init_llm_request_logger = __esmMin((() => {
273088
273285
  systemMessageBytes: breakdown.systemMessageBytes,
273089
273286
  conversationMessageBytes: breakdown.conversationMessageBytes,
273090
273287
  toolResultMessageBytes: breakdown.toolResultMessageBytes,
273288
+ ...breakdown.toolResultByTool === void 0 ? {} : { toolResultByTool: breakdown.toolResultByTool.map((tool) => ({
273289
+ count: tool.count,
273290
+ bytes: tool.bytes,
273291
+ ...tool.name === void 0 ? {} : { name: tool.name }
273292
+ })) },
273091
273293
  toolSchemaBytes: breakdown.toolSchemaBytes,
273092
273294
  otherBytes: breakdown.otherBytes,
273093
273295
  ...breakdown.toolArrayOverheadBytes === void 0 ? {} : { toolArrayOverheadBytes: breakdown.toolArrayOverheadBytes },
@@ -273130,6 +273332,7 @@ var init_agent = __esmMin((() => {
273130
273332
  init_errors$8();
273131
273333
  init_logger$1();
273132
273334
  init_src$4();
273335
+ init_blun();
273133
273336
  init_commands();
273134
273337
  init_flags();
273135
273338
  init_profile();
@@ -273216,6 +273419,9 @@ var init_agent = __esmMin((() => {
273216
273419
  additionalDirs;
273217
273420
  systemPromptStartedAt = /* @__PURE__ */ new Date();
273218
273421
  activeProfile;
273422
+ rawSystemPromptContext;
273423
+ profileSystemPromptText;
273424
+ agentsMdRequestWarningShown = false;
273219
273425
  brandHome;
273220
273426
  _activeResponderModel;
273221
273427
  allowModelFallback = true;
@@ -273370,6 +273576,7 @@ var init_agent = __esmMin((() => {
273370
273576
  tools: requestTools,
273371
273577
  messages: await rebuildMessages()
273372
273578
  };
273579
+ if (this.activeProfile !== void 0 && this.rawSystemPromptContext !== void 0 && this.config.systemPrompt === this.profileSystemPromptText) this.updateSystemPromptFromProfile(this.activeProfile, this.fitProfileInstructions(this.activeProfile, this.rawSystemPromptContext, requestTools, true));
273373
273580
  let systemPrompt = this.effectiveSystemPrompt;
273374
273581
  const preflightStartedAt = performance.now();
273375
273582
  const compacted = await this.fullCompaction.beforeStep(params.signal, {
@@ -273393,11 +273600,25 @@ var init_agent = __esmMin((() => {
273393
273600
  systemPrompt,
273394
273601
  tools: params.tools
273395
273602
  }).eligible ? params.tools.filter((tool) => tool.name !== "CompactConversation") : params.tools;
273396
- this.turn.commitPendingSteers(steers);
273397
- return {
273603
+ const steersCommitted = this.turn.commitPendingSteers(steers);
273604
+ if (compacted || steersCommitted) params = {
273398
273605
  ...params,
273399
- systemPrompt,
273400
- tools
273606
+ messages: await rebuildMessages()
273607
+ };
273608
+ if (this.config.runtimeModel(_candidate.alias).provider.name === "blun") {
273609
+ const requestBytes = estimateBlunSerializedBodyBytes(systemPrompt, tools, params.messages) + 4096;
273610
+ if (requestBytes >= 5e5) throw new BlunError(ErrorCodes.CONTEXT_OVERFLOW, "The BLUN request is too large after compaction. Shorten fixed instructions or tools.", { details: {
273611
+ estimatedRequestBytes: requestBytes,
273612
+ requestBudgetBytes: 5e5
273613
+ } });
273614
+ }
273615
+ return {
273616
+ params: {
273617
+ ...params,
273618
+ systemPrompt,
273619
+ tools
273620
+ },
273621
+ messagesReady: true
273401
273622
  };
273402
273623
  }, (candidate, _params, error) => {
273403
273624
  this.fullCompaction.observeContextOverflow(error, candidate.alias);
@@ -273469,8 +273690,14 @@ var init_agent = __esmMin((() => {
273469
273690
  }
273470
273691
  useProfile(profile, context, brandHome) {
273471
273692
  this.setActiveProfile(profile, brandHome);
273472
- this.updateSystemPromptFromProfile(profile, context);
273693
+ this.rawSystemPromptContext = context;
273694
+ if (context?.agentsMdText === void 0) {
273695
+ this.updateSystemPromptFromProfile(profile, context);
273696
+ this.tools.setActiveTools(profile.tools);
273697
+ return;
273698
+ }
273473
273699
  this.tools.setActiveTools(profile.tools);
273700
+ this.updateSystemPromptFromProfile(profile, this.fitProfileInstructions(profile, context));
273474
273701
  }
273475
273702
  setActiveProfile(profile, brandHome) {
273476
273703
  this.activeProfile = profile;
@@ -273485,7 +273712,46 @@ var init_agent = __esmMin((() => {
273485
273712
  async refreshSystemPrompt() {
273486
273713
  if (this.activeProfile === void 0) return;
273487
273714
  const context = this.systemPromptContextProvider === void 0 ? await prepareSystemPromptContext(this.kaos, this.brandHome, { additionalDirs: this.additionalDirs }) : await this.systemPromptContextProvider();
273488
- this.updateSystemPromptFromProfile(this.activeProfile, context);
273715
+ this.rawSystemPromptContext = context;
273716
+ this.updateSystemPromptFromProfile(this.activeProfile, this.fitProfileInstructions(this.activeProfile, context));
273717
+ }
273718
+ fitProfileInstructions(profile, context, tools = this.tools.loopTools, notify = false) {
273719
+ if (context?.agentsMdText === void 0 || this.config.modelAlias === void 0) return context;
273720
+ if (this.config.runtimeModel(this.config.modelAlias).provider.name !== "blun") return context;
273721
+ const fitted = fitAgentsMdContext(context, 4e5, (candidate) => {
273722
+ const rendered = profile.systemPrompt({
273723
+ osEnv: this.kaos.osEnv,
273724
+ now: this.systemPromptStartedAt,
273725
+ cwd: this.config.cwd,
273726
+ skills: this.skills?.registry,
273727
+ cwdListing: candidate.cwdListing,
273728
+ agentsMd: candidate.agentsMd,
273729
+ additionalDirsInfo: candidate.additionalDirsInfo
273730
+ });
273731
+ const compact = this.skills?.registry === void 0 ? rendered : compactLegacyModelSkillListing(rendered, this.skills.registry);
273732
+ return estimateBlunSerializedBodyBytes(this.runtimeSystemPromptAppend.length === 0 ? compact : compact.length === 0 ? this.runtimeSystemPromptAppend : `${compact}\n\n${this.runtimeSystemPromptAppend}`, tools, []) + 4096;
273733
+ });
273734
+ if (!fitted.fits) this.log.warn("fixed BLUN request exceeds 400000 bytes without AGENTS.md", { fixedRequestBytes: fitted.fixedRequestBytes });
273735
+ else if (fitted.omittedBytes > 0) {
273736
+ this.log.warn("AGENTS.md content shortened for BLUN request budget", {
273737
+ omittedBytes: fitted.omittedBytes,
273738
+ fixedRequestBytes: fitted.fixedRequestBytes
273739
+ });
273740
+ if (notify && !this.agentsMdRequestWarningShown) {
273741
+ this.agentsMdRequestWarningShown = true;
273742
+ const retained = new Map(fitted.context.agentsMdSources?.files.map((file) => [file.path, file.bytes]));
273743
+ const files = context.agentsMdSources?.files.flatMap((file) => {
273744
+ const read = retained.get(file.path) ?? 0;
273745
+ return read < file.bytes ? [`${file.path}: ${file.bytes} bytes, ${read} read, ${file.bytes - read} omitted`] : [];
273746
+ }) ?? [];
273747
+ this.emitEvent({
273748
+ type: "warning",
273749
+ code: "agents-md-request-truncated",
273750
+ message: `Instructions shortened for the request size limit: ${files.join("; ")}.`
273751
+ });
273752
+ }
273753
+ }
273754
+ return fitted.context;
273489
273755
  }
273490
273756
  updateSystemPromptFromProfile(profile, context) {
273491
273757
  let contributions;
@@ -273506,6 +273772,7 @@ var init_agent = __esmMin((() => {
273506
273772
  profileName: profile.name,
273507
273773
  systemPrompt
273508
273774
  });
273775
+ this.profileSystemPromptText = systemPrompt;
273509
273776
  this.renderedPromptContributions = contributions === void 0 ? void 0 : {
273510
273777
  text: systemPrompt,
273511
273778
  value: structuredClone(contributions)
@@ -303409,7 +303676,7 @@ var init_proxy = __esmMin((() => {
303409
303676
  var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303410
303677
  module.exports = isexe;
303411
303678
  isexe.sync = sync;
303412
- var fs$9 = __require("fs");
303679
+ var fs$8 = __require("fs");
303413
303680
  function checkPathExt(path, options) {
303414
303681
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
303415
303682
  if (!pathext) return true;
@@ -303426,12 +303693,12 @@ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303426
303693
  return checkPathExt(path, options);
303427
303694
  }
303428
303695
  function isexe(path, options, cb) {
303429
- fs$9.stat(path, function(er, stat) {
303696
+ fs$8.stat(path, function(er, stat) {
303430
303697
  cb(er, er ? false : checkStat(stat, path, options));
303431
303698
  });
303432
303699
  }
303433
303700
  function sync(path, options) {
303434
- return checkStat(fs$9.statSync(path), path, options);
303701
+ return checkStat(fs$8.statSync(path), path, options);
303435
303702
  }
303436
303703
  }));
303437
303704
  //#endregion
@@ -303439,14 +303706,14 @@ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303439
303706
  var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303440
303707
  module.exports = isexe;
303441
303708
  isexe.sync = sync;
303442
- var fs$8 = __require("fs");
303709
+ var fs$7 = __require("fs");
303443
303710
  function isexe(path, options, cb) {
303444
- fs$8.stat(path, function(er, stat) {
303711
+ fs$7.stat(path, function(er, stat) {
303445
303712
  cb(er, er ? false : checkStat(stat, options));
303446
303713
  });
303447
303714
  }
303448
303715
  function sync(path, options) {
303449
- return checkStat(fs$8.statSync(path), options);
303716
+ return checkStat(fs$7.statSync(path), options);
303450
303717
  }
303451
303718
  function checkStat(stat, options) {
303452
303719
  return stat.isFile() && checkMode(stat, options);
@@ -303510,7 +303777,7 @@ var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303510
303777
  //#region ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
303511
303778
  var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303512
303779
  const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
303513
- const path$10 = __require("path");
303780
+ const path$9 = __require("path");
303514
303781
  const COLON = isWindows ? ";" : ":";
303515
303782
  const isexe = require_isexe();
303516
303783
  const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -303540,7 +303807,7 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303540
303807
  if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
303541
303808
  const ppRaw = pathEnv[i];
303542
303809
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
303543
- const pCmd = path$10.join(pathPart, cmd);
303810
+ const pCmd = path$9.join(pathPart, cmd);
303544
303811
  resolve(subStep(!pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd, i, 0));
303545
303812
  });
303546
303813
  const subStep = (p, i, ii) => new Promise((resolve, reject) => {
@@ -303561,7 +303828,7 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303561
303828
  for (let i = 0; i < pathEnv.length; i++) {
303562
303829
  const ppRaw = pathEnv[i];
303563
303830
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
303564
- const pCmd = path$10.join(pathPart, cmd);
303831
+ const pCmd = path$9.join(pathPart, cmd);
303565
303832
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
303566
303833
  for (let j = 0; j < pathExt.length; j++) {
303567
303834
  const cur = p + pathExt[j];
@@ -303592,7 +303859,7 @@ var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303592
303859
  //#endregion
303593
303860
  //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
303594
303861
  var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303595
- const path$9 = __require("path");
303862
+ const path$8 = __require("path");
303596
303863
  const which = require_which();
303597
303864
  const getPathKey = require_path_key();
303598
303865
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -303607,12 +303874,12 @@ var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) =>
303607
303874
  try {
303608
303875
  resolved = which.sync(parsed.command, {
303609
303876
  path: env[getPathKey({ env })],
303610
- pathExt: withoutPathExt ? path$9.delimiter : void 0
303877
+ pathExt: withoutPathExt ? path$8.delimiter : void 0
303611
303878
  });
303612
303879
  } catch (e) {} finally {
303613
303880
  if (shouldSwitchCwd) process.chdir(cwd);
303614
303881
  }
303615
- if (resolved) resolved = path$9.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
303882
+ if (resolved) resolved = path$8.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
303616
303883
  return resolved;
303617
303884
  }
303618
303885
  function resolveCommand(parsed) {
@@ -303661,16 +303928,16 @@ var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) =
303661
303928
  //#endregion
303662
303929
  //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
303663
303930
  var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303664
- const fs$7 = __require("fs");
303931
+ const fs$6 = __require("fs");
303665
303932
  const shebangCommand = require_shebang_command();
303666
303933
  function readShebang(command) {
303667
303934
  const size = 150;
303668
303935
  const buffer = Buffer.alloc(size);
303669
303936
  let fd;
303670
303937
  try {
303671
- fd = fs$7.openSync(command, "r");
303672
- fs$7.readSync(fd, buffer, 0, size, 0);
303673
- fs$7.closeSync(fd);
303938
+ fd = fs$6.openSync(command, "r");
303939
+ fs$6.readSync(fd, buffer, 0, size, 0);
303940
+ fs$6.closeSync(fd);
303674
303941
  } catch (e) {}
303675
303942
  return shebangCommand(buffer.toString());
303676
303943
  }
@@ -303679,7 +303946,7 @@ var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303679
303946
  //#endregion
303680
303947
  //#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
303681
303948
  var require_parse$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303682
- const path$8 = __require("path");
303949
+ const path$7 = __require("path");
303683
303950
  const resolveCommand = require_resolveCommand();
303684
303951
  const escape = require_escape();
303685
303952
  const readShebang = require_readShebang();
@@ -303702,7 +303969,7 @@ var require_parse$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
303702
303969
  const needsShell = !isExecutableRegExp.test(commandFile);
303703
303970
  if (parsed.options.forceShell || needsShell) {
303704
303971
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
303705
- parsed.command = path$8.normalize(parsed.command);
303972
+ parsed.command = path$7.normalize(parsed.command);
303706
303973
  parsed.command = escape.command(parsed.command);
303707
303974
  parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
303708
303975
  parsed.args = [
@@ -304778,9 +305045,9 @@ function projectAgentSpinePrompt(input) {
304778
305045
  if (typeof input["hook_event_name"] !== "string" || !PROMPT_EVENTS.has(input["hook_event_name"]) || !Array.isArray(input["prompt"])) return input;
304779
305046
  let changed = false;
304780
305047
  const prompt = input["prompt"].map((part) => {
304781
- if (!isRecord$20(part)) return part;
305048
+ if (!isRecord$24(part)) return part;
304782
305049
  const field = part["type"] === "image_url" ? "imageUrl" : part["type"] === "audio_url" ? "audioUrl" : part["type"] === "video_url" ? "videoUrl" : void 0;
304783
- if (field === void 0 || !isRecord$20(part[field]) || typeof part[field]["url"] !== "string") return part;
305050
+ if (field === void 0 || !isRecord$24(part[field]) || typeof part[field]["url"] !== "string") return part;
304784
305051
  const serialized = JSON.stringify(part);
304785
305052
  changed = true;
304786
305053
  return {
@@ -304795,7 +305062,7 @@ function projectAgentSpinePrompt(input) {
304795
305062
  prompt
304796
305063
  } : input;
304797
305064
  }
304798
- function isRecord$20(value) {
305065
+ function isRecord$24(value) {
304799
305066
  return typeof value === "object" && value !== null && !Array.isArray(value);
304800
305067
  }
304801
305068
  var PROMPT_EVENTS, EMPTY_RUNTIME, AgentSpineSessionRuntime;
@@ -337832,7 +338099,7 @@ var require_dist$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
337832
338099
  //#endregion
337833
338100
  //#region ../../node_modules/.pnpm/yazl@3.3.1/node_modules/yazl/index.js
337834
338101
  var require_yazl = /* @__PURE__ */ __commonJSMin(((exports) => {
337835
- var fs$6 = __require("fs");
338102
+ var fs$5 = __require("fs");
337836
338103
  var Transform$2 = __require("stream").Transform;
337837
338104
  var PassThrough$2 = __require("stream").PassThrough;
337838
338105
  var zlib$1 = __require("zlib");
@@ -337861,14 +338128,14 @@ var require_yazl = /* @__PURE__ */ __commonJSMin(((exports) => {
337861
338128
  if (shouldIgnoreAdding(self)) return;
337862
338129
  var entry = new Entry(metadataPath, false, options);
337863
338130
  self.entries.push(entry);
337864
- fs$6.stat(realPath, function(err, stats) {
338131
+ fs$5.stat(realPath, function(err, stats) {
337865
338132
  if (err) return self.emit("error", err);
337866
338133
  if (!stats.isFile()) return self.emit("error", /* @__PURE__ */ new Error("not a file: " + realPath));
337867
338134
  entry.uncompressedSize = stats.size;
337868
338135
  if (options.mtime == null) entry.setLastModDate(stats.mtime);
337869
338136
  if (options.mode == null) entry.setFileAttributesMode(stats.mode);
337870
338137
  entry.setFileDataPumpFunction(function() {
337871
- var readStream = fs$6.createReadStream(realPath);
338138
+ var readStream = fs$5.createReadStream(realPath);
337872
338139
  entry.state = Entry.FILE_DATA_IN_PROGRESS;
337873
338140
  readStream.on("error", function(err) {
337874
338141
  self.emit("error", err);
@@ -339213,10 +339480,10 @@ async function appendForkedMarkers(state) {
339213
339480
  time: Date.now()
339214
339481
  };
339215
339482
  const agents = state["agents"];
339216
- if (!isRecord$19(agents)) return;
339483
+ if (!isRecord$23(agents)) return;
339217
339484
  const paths = /* @__PURE__ */ new Set();
339218
339485
  for (const agentMeta of Object.values(agents)) {
339219
- if (!isRecord$19(agentMeta)) continue;
339486
+ if (!isRecord$23(agentMeta)) continue;
339220
339487
  const homedir = agentMeta["homedir"];
339221
339488
  if (typeof homedir !== "string") continue;
339222
339489
  paths.add(join$4(homedir, "wire.jsonl"));
@@ -339228,7 +339495,7 @@ async function appendForkedMarkers(state) {
339228
339495
  }));
339229
339496
  }
339230
339497
  function customMetadataForFork(value) {
339231
- if (!isRecord$19(value)) return {};
339498
+ if (!isRecord$23(value)) return {};
339232
339499
  const custom = {};
339233
339500
  for (const [key, entry] of Object.entries(value)) {
339234
339501
  if (key === "goal" || key === "managedQuotaWarningThreshold") continue;
@@ -339283,10 +339550,10 @@ function normalizeForkTitle(title, fallback) {
339283
339550
  return typeof fallback === "string" && fallback.trim().length > 0 ? fallback : "New Session";
339284
339551
  }
339285
339552
  function rewriteAgentHomedirs(value, sourceDir, targetDir) {
339286
- if (!isRecord$19(value)) return {};
339553
+ if (!isRecord$23(value)) return {};
339287
339554
  const agents = {};
339288
339555
  for (const [agentId, agentMeta] of Object.entries(value)) {
339289
- if (!isRecord$19(agentMeta)) {
339556
+ if (!isRecord$23(agentMeta)) {
339290
339557
  agents[agentId] = agentMeta;
339291
339558
  continue;
339292
339559
  }
@@ -339304,7 +339571,7 @@ function remapSessionPath(value, sourceDir, targetDir) {
339304
339571
  if (rel.startsWith("..") || isAbsolute$2(rel)) return value;
339305
339572
  return join$4(targetDir, rel);
339306
339573
  }
339307
- function isRecord$19(value) {
339574
+ function isRecord$23(value) {
339308
339575
  return typeof value === "object" && value !== null && !Array.isArray(value);
339309
339576
  }
339310
339577
  async function statIfExists(path) {
@@ -339568,7 +339835,7 @@ var init_session_store$1 = __esmMin((() => {
339568
339835
  } catch (error) {
339569
339836
  throw new BlunError(ErrorCodes.SESSION_STATE_NOT_FOUND, `Session "${input.sourceId}" state.json was not found`, { cause: error });
339570
339837
  }
339571
- if (!isRecord$19(parsed)) throw new BlunError(ErrorCodes.SESSION_STATE_INVALID, `Session "${input.sourceId}" state.json is invalid`);
339838
+ if (!isRecord$23(parsed)) throw new BlunError(ErrorCodes.SESSION_STATE_INVALID, `Session "${input.sourceId}" state.json is invalid`);
339572
339839
  const title = normalizeForkTitle(input.title, parsed["title"]);
339573
339840
  const now = (/* @__PURE__ */ new Date()).toISOString();
339574
339841
  const next = {
@@ -350893,6 +351160,39 @@ var BlunAuthFacade = class {
350893
351160
  }
350894
351161
  return this.toolkit.status(providerName, this.resolveRuntimeManagedAuth(providerName).oauthRef);
350895
351162
  }
351163
+ async getCachedMemoryWorkspaceId() {
351164
+ const apiKey = nonEmpty(this.resolveManagedAuth(BLUN_PROVIDER_NAME$1).apiKey);
351165
+ if (apiKey !== void 0) {
351166
+ const provider = readConfigFileForUpdate(this.options.configPath).providers[BLUN_PROVIDER_NAME$1];
351167
+ if (provider?.apiKey !== apiKey || provider.memoryApiKeyHash !== memoryApiKeyHash(apiKey)) return;
351168
+ return provider.memoryWorkspaceId;
351169
+ }
351170
+ return this.toolkit.getCachedMemoryWorkspaceId(this.resolveRuntimeManagedAuth(BLUN_PROVIDER_NAME$1).oauthRef);
351171
+ }
351172
+ async cacheMemoryWorkspaceId(workspaceId) {
351173
+ const apiKey = nonEmpty(this.resolveManagedAuth(BLUN_PROVIDER_NAME$1).apiKey);
351174
+ if (apiKey !== void 0) {
351175
+ const hash = memoryApiKeyHash(apiKey);
351176
+ return mutateConfigFile(this.options.configPath, (config) => {
351177
+ const provider = config.providers[BLUN_PROVIDER_NAME$1];
351178
+ if (provider?.apiKey !== apiKey) return {
351179
+ config,
351180
+ result: false
351181
+ };
351182
+ if (provider.memoryApiKeyHash === hash && provider.memoryWorkspaceId !== void 0 && provider.memoryWorkspaceId !== workspaceId) return {
351183
+ config,
351184
+ result: false
351185
+ };
351186
+ provider.memoryApiKeyHash = hash;
351187
+ provider.memoryWorkspaceId = workspaceId;
351188
+ return {
351189
+ config,
351190
+ result: true
351191
+ };
351192
+ });
351193
+ }
351194
+ return this.toolkit.cacheMemoryWorkspaceId(workspaceId, this.resolveRuntimeManagedAuth(BLUN_PROVIDER_NAME$1).oauthRef);
351195
+ }
350896
351196
  async login(providerName = BLUN_PROVIDER_NAME$1, options = {}) {
350897
351197
  const auth = this.resolveManagedAuth(providerName);
350898
351198
  const loginAuth = resolveBlunCodeLoginAuth({
@@ -351198,6 +351498,9 @@ function nonEmpty(value) {
351198
351498
  const normalized = value?.trim();
351199
351499
  return normalized === void 0 || normalized.length === 0 ? void 0 : normalized;
351200
351500
  }
351501
+ function memoryApiKeyHash(apiKey) {
351502
+ return createHash("sha256").update(apiKey).digest("hex");
351503
+ }
351201
351504
  function transitionAggregateError(message, primary, secondary) {
351202
351505
  return new AggregateError([primary, secondary], message, { cause: primary });
351203
351506
  }
@@ -353733,8 +354036,8 @@ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
353733
354036
  var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
353734
354037
  const EventEmitter$12 = __require("node:events").EventEmitter;
353735
354038
  const childProcess = __require("node:child_process");
353736
- const path$7 = __require("node:path");
353737
- const fs$5 = __require("node:fs");
354039
+ const path$6 = __require("node:path");
354040
+ const fs$4 = __require("node:fs");
353738
354041
  const process$2 = __require("node:process");
353739
354042
  const { Argument, humanReadableArgName } = require_argument();
353740
354043
  const { CommanderError } = require_error$2();
@@ -354617,7 +354920,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
354617
354920
  * @param {string} subcommandName
354618
354921
  */
354619
354922
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
354620
- if (fs$5.existsSync(executableFile)) return;
354923
+ if (fs$4.existsSync(executableFile)) return;
354621
354924
  const executableMissing = `'${executableFile}' does not exist
354622
354925
  - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
354623
354926
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
@@ -354640,10 +354943,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
354640
354943
  ".cjs"
354641
354944
  ];
354642
354945
  function findFile(baseDir, baseName) {
354643
- const localBin = path$7.resolve(baseDir, baseName);
354644
- if (fs$5.existsSync(localBin)) return localBin;
354645
- if (sourceExt.includes(path$7.extname(baseName))) return void 0;
354646
- const foundExt = sourceExt.find((ext) => fs$5.existsSync(`${localBin}${ext}`));
354946
+ const localBin = path$6.resolve(baseDir, baseName);
354947
+ if (fs$4.existsSync(localBin)) return localBin;
354948
+ if (sourceExt.includes(path$6.extname(baseName))) return void 0;
354949
+ const foundExt = sourceExt.find((ext) => fs$4.existsSync(`${localBin}${ext}`));
354647
354950
  if (foundExt) return `${localBin}${foundExt}`;
354648
354951
  }
354649
354952
  this._checkForMissingMandatoryOptions();
@@ -354653,21 +354956,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
354653
354956
  if (this._scriptPath) {
354654
354957
  let resolvedScriptPath;
354655
354958
  try {
354656
- resolvedScriptPath = fs$5.realpathSync(this._scriptPath);
354959
+ resolvedScriptPath = fs$4.realpathSync(this._scriptPath);
354657
354960
  } catch {
354658
354961
  resolvedScriptPath = this._scriptPath;
354659
354962
  }
354660
- executableDir = path$7.resolve(path$7.dirname(resolvedScriptPath), executableDir);
354963
+ executableDir = path$6.resolve(path$6.dirname(resolvedScriptPath), executableDir);
354661
354964
  }
354662
354965
  if (executableDir) {
354663
354966
  let localFile = findFile(executableDir, executableFile);
354664
354967
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
354665
- const legacyName = path$7.basename(this._scriptPath, path$7.extname(this._scriptPath));
354968
+ const legacyName = path$6.basename(this._scriptPath, path$6.extname(this._scriptPath));
354666
354969
  if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
354667
354970
  }
354668
354971
  executableFile = localFile || executableFile;
354669
354972
  }
354670
- launchWithNode = sourceExt.includes(path$7.extname(executableFile));
354973
+ launchWithNode = sourceExt.includes(path$6.extname(executableFile));
354671
354974
  let proc;
354672
354975
  if (process$2.platform !== "win32") if (launchWithNode) {
354673
354976
  args.unshift(executableFile);
@@ -355371,7 +355674,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
355371
355674
  * @return {Command}
355372
355675
  */
355373
355676
  nameFromFilename(filename) {
355374
- this._name = path$7.basename(filename, path$7.extname(filename));
355677
+ this._name = path$6.basename(filename, path$6.extname(filename));
355375
355678
  return this;
355376
355679
  }
355377
355680
  /**
@@ -361563,6 +361866,49 @@ var AcpSession = class {
361563
361866
  }, event.message));
361564
361867
  return;
361565
361868
  }
361869
+ if (event.type === "hook.result") {
361870
+ if (!isFromMainAgent(event) || event.content.trim().length === 0) return;
361871
+ if (event.blocked === true) log.warn("acp: turn blocked by hook", {
361872
+ sessionId,
361873
+ hookEvent: event.hookEvent,
361874
+ reason: event.content
361875
+ });
361876
+ conn.sessionUpdate({
361877
+ sessionId,
361878
+ update: {
361879
+ sessionUpdate: "agent_message_chunk",
361880
+ content: {
361881
+ type: "text",
361882
+ text: `${event.content}\n`
361883
+ }
361884
+ }
361885
+ }).catch((err) => {
361886
+ log.warn("acp: failed to push hook result", {
361887
+ sessionId,
361888
+ error: err instanceof Error ? err.message : String(err)
361889
+ });
361890
+ });
361891
+ return;
361892
+ }
361893
+ if (event.type === "warning" && event.code === "agents-md-request-truncated") {
361894
+ if (!isFromMainAgent(event)) return;
361895
+ conn.sessionUpdate({
361896
+ sessionId,
361897
+ update: {
361898
+ sessionUpdate: "agent_message_chunk",
361899
+ content: {
361900
+ type: "text",
361901
+ text: `${event.message}\n`
361902
+ }
361903
+ }
361904
+ }).catch((err) => {
361905
+ log.warn("acp: failed to push instruction warning", {
361906
+ sessionId,
361907
+ error: err instanceof Error ? err.message : String(err)
361908
+ });
361909
+ });
361910
+ return;
361911
+ }
361566
361912
  if (event.type === "assistant.delta") {
361567
361913
  if (!isFromMainAgent(event)) return;
361568
361914
  conn.sessionUpdate(assistantDeltaToSessionUpdate(sessionId, event)).catch((err) => {
@@ -364331,8 +364677,8 @@ function createAccountMemoryClient(auth, options = {}) {
364331
364677
  }
364332
364678
  function readAccountMemoryConsentStatus(payload) {
364333
364679
  const settings = unwrapPayload(payload)?.["settings"];
364334
- const dataControls = isRecord$18(settings) ? settings["data_controls"] : void 0;
364335
- if (!isRecord$18(dataControls)) throw new Error("Account memory returned an invalid response.");
364680
+ const dataControls = isRecord$22(settings) ? settings["data_controls"] : void 0;
364681
+ if (!isRecord$22(dataControls)) throw new Error("Account memory returned an invalid response.");
364336
364682
  if (dataControls["memory_consent_asked"] !== true) return "never_asked";
364337
364683
  if (dataControls["allow_memory"] === true) return "enabled";
364338
364684
  if (dataControls["allow_memory"] === false) return "disabled";
@@ -364455,8 +364801,8 @@ function memoryContextSummary(facts, included) {
364455
364801
  })}`;
364456
364802
  }
364457
364803
  function unwrapPayload(value) {
364458
- if (!isRecord$18(value)) return void 0;
364459
- return isRecord$18(value["data"]) ? value["data"] : value;
364804
+ if (!isRecord$22(value)) return void 0;
364805
+ return isRecord$22(value["data"]) ? value["data"] : value;
364460
364806
  }
364461
364807
  function readFacts(root) {
364462
364808
  let rawFacts = [];
@@ -364464,7 +364810,7 @@ function readFacts(root) {
364464
364810
  else {
364465
364811
  const factsJson = parseFactsJson(root["facts_json"]);
364466
364812
  if (Array.isArray(factsJson)) rawFacts = factsJson;
364467
- else if (isRecord$18(factsJson) && Array.isArray(factsJson["facts"])) rawFacts = factsJson["facts"];
364813
+ else if (isRecord$22(factsJson) && Array.isArray(factsJson["facts"])) rawFacts = factsJson["facts"];
364468
364814
  }
364469
364815
  const facts = [];
364470
364816
  const seen = /* @__PURE__ */ new Set();
@@ -364493,7 +364839,7 @@ function parseFactsJson(value) {
364493
364839
  }
364494
364840
  }
364495
364841
  function normalizeFact(value) {
364496
- const raw = typeof value === "string" ? value : isRecord$18(value) && typeof value["text"] === "string" ? value["text"] : void 0;
364842
+ const raw = typeof value === "string" ? value : isRecord$22(value) && typeof value["text"] === "string" ? value["text"] : void 0;
364497
364843
  if (raw === void 0) return void 0;
364498
364844
  const normalized = raw.replaceAll(/\s+/gu, " ").trim();
364499
364845
  if (normalized.length === 0) return void 0;
@@ -364504,7 +364850,7 @@ function normalizeFact(value) {
364504
364850
  truncated: normalized.length > ACCOUNT_MEMORY_MAX_FACT_CHARS
364505
364851
  };
364506
364852
  }
364507
- function isRecord$18(value) {
364853
+ function isRecord$22(value) {
364508
364854
  return typeof value === "object" && value !== null && !Array.isArray(value);
364509
364855
  }
364510
364856
  //#endregion
@@ -364731,6 +365077,8 @@ registerUiCatalogFragment({
364731
365077
  "auth.logout.selectTitle": "Select a provider to log out",
364732
365078
  "auth.logout.none": "Nothing to log out.",
364733
365079
  "auth.logout.complete": "Logged out from {provider}.",
365080
+ "auth.warning.memoryRetractionOAuthPending": "Deletion has not been sent yet. It will be sent at your next sign-in.",
365081
+ "auth.warning.memoryRetractionApiKeyPending": "Deletion has not been sent yet. It will be sent once you reconnect.",
364734
365082
  "auth.warning.remoteRevokeFailed": "The local OAuth credentials were removed, but remote revocation could not be confirmed.",
364735
365083
  "auth.warning.oauthCleanupFailed": "The API key is active, but the previous OAuth credentials could not be fully removed."
364736
365084
  },
@@ -364763,6 +365111,8 @@ registerUiCatalogFragment({
364763
365111
  "auth.logout.selectTitle": "Anbieter zum Abmelden auswählen",
364764
365112
  "auth.logout.none": "Es gibt keine aktive Anmeldung.",
364765
365113
  "auth.logout.complete": "Von {provider} abgemeldet.",
365114
+ "auth.warning.memoryRetractionOAuthPending": "Löschen noch nicht übertragen – folgt bei deiner nächsten Anmeldung.",
365115
+ "auth.warning.memoryRetractionApiKeyPending": "Löschen noch nicht übertragen – folgt, sobald du wieder verbunden bist.",
364766
365116
  "auth.warning.remoteRevokeFailed": "Die lokalen OAuth-Zugangsdaten wurden entfernt, aber der Widerruf auf dem Server konnte nicht bestätigt werden.",
364767
365117
  "auth.warning.oauthCleanupFailed": "Der API-Schlüssel ist aktiv, aber die vorherigen OAuth-Zugangsdaten konnten nicht vollständig entfernt werden."
364768
365118
  },
@@ -364795,6 +365145,8 @@ registerUiCatalogFragment({
364795
365145
  "auth.logout.selectTitle": "Selecciona el proveedor cuya sesión quieres cerrar",
364796
365146
  "auth.logout.none": "No hay ninguna sesión que cerrar.",
364797
365147
  "auth.logout.complete": "Sesión cerrada en {provider}.",
365148
+ "auth.warning.memoryRetractionOAuthPending": "La eliminación aún no se ha enviado: se enviará en tu próximo inicio de sesión.",
365149
+ "auth.warning.memoryRetractionApiKeyPending": "La eliminación aún no se ha enviado: se enviará cuando se restablezca la conexión.",
364798
365150
  "auth.warning.remoteRevokeFailed": "Las credenciales OAuth locales se han eliminado, pero no se pudo confirmar su revocación en el servidor.",
364799
365151
  "auth.warning.oauthCleanupFailed": "La clave de API está activa, pero no se pudieron eliminar por completo las credenciales OAuth anteriores."
364800
365152
  },
@@ -364827,6 +365179,8 @@ registerUiCatalogFragment({
364827
365179
  "auth.logout.selectTitle": "Sélectionnez le fournisseur dont vous souhaitez vous déconnecter",
364828
365180
  "auth.logout.none": "Aucune session à fermer.",
364829
365181
  "auth.logout.complete": "Déconnexion de {provider} effectuée.",
365182
+ "auth.warning.memoryRetractionOAuthPending": "Suppression pas encore transmise – elle le sera à ta prochaine connexion.",
365183
+ "auth.warning.memoryRetractionApiKeyPending": "Suppression pas encore transmise – elle le sera dès que la connexion sera rétablie.",
364830
365184
  "auth.warning.remoteRevokeFailed": "Les identifiants OAuth locaux ont été supprimés, mais leur révocation sur le serveur n’a pas pu être confirmée.",
364831
365185
  "auth.warning.oauthCleanupFailed": "La clé API est active, mais les identifiants OAuth précédents n’ont pas pu être entièrement supprimés."
364832
365186
  },
@@ -364859,6 +365213,8 @@ registerUiCatalogFragment({
364859
365213
  "auth.logout.selectTitle": "Välj en leverantör att logga ut från",
364860
365214
  "auth.logout.none": "Det finns inget att logga ut från.",
364861
365215
  "auth.logout.complete": "Utloggad från {provider}.",
365216
+ "auth.warning.memoryRetractionOAuthPending": "Raderingen har inte överförts än – sker vid din nästa inloggning.",
365217
+ "auth.warning.memoryRetractionApiKeyPending": "Raderingen har inte överförts än – sker så snart du är ansluten igen.",
364862
365218
  "auth.warning.remoteRevokeFailed": "De lokala OAuth-uppgifterna har tagits bort, men det gick inte att bekräfta återkallelsen på servern.",
364863
365219
  "auth.warning.oauthCleanupFailed": "API-nyckeln är aktiv, men de tidigare OAuth-uppgifterna kunde inte tas bort helt."
364864
365220
  },
@@ -364891,6 +365247,8 @@ registerUiCatalogFragment({
364891
365247
  "auth.logout.selectTitle": "Vyberte poskytovatele, od kterého se chcete odhlásit",
364892
365248
  "auth.logout.none": "Nic k odhlášení.",
364893
365249
  "auth.logout.complete": "Odhlášeno od {provider}.",
365250
+ "auth.warning.memoryRetractionOAuthPending": "Smazání zatím nebylo přeneseno – proběhne při tvém příštím přihlášení.",
365251
+ "auth.warning.memoryRetractionApiKeyPending": "Smazání zatím nebylo přeneseno – proběhne, jakmile se obnoví připojení.",
364894
365252
  "auth.warning.remoteRevokeFailed": "Místní přihlašovací údaje OAuth byly odstraněny, ale jejich zneplatnění na serveru se nepodařilo potvrdit.",
364895
365253
  "auth.warning.oauthCleanupFailed": "Klíč API je aktivní, ale předchozí přihlašovací údaje OAuth nebyly zcela odstraněny."
364896
365254
  }
@@ -366022,7 +366380,7 @@ function formatErrorMessage$4(error, filePath) {
366022
366380
  function findValidationIssues(error) {
366023
366381
  if (!(error instanceof Error)) return void 0;
366024
366382
  const details = "details" in error ? error.details : void 0;
366025
- if (!isRecord$17(details)) return void 0;
366383
+ if (!isRecord$21(details)) return void 0;
366026
366384
  const validationIssues = details["validationIssues"];
366027
366385
  return isValidationIssueArray(validationIssues) ? validationIssues : void 0;
366028
366386
  }
@@ -366030,11 +366388,11 @@ function isValidationIssueArray(value) {
366030
366388
  return Array.isArray(value) && value.every(isValidationIssue);
366031
366389
  }
366032
366390
  function isValidationIssue(value) {
366033
- if (!isRecord$17(value) || typeof value["message"] !== "string") return false;
366391
+ if (!isRecord$21(value) || typeof value["message"] !== "string") return false;
366034
366392
  const path = value["path"];
366035
366393
  return Array.isArray(path) && path.every((segment) => typeof segment === "string" || typeof segment === "number");
366036
366394
  }
366037
- function isRecord$17(value) {
366395
+ function isRecord$21(value) {
366038
366396
  return typeof value === "object" && value !== null;
366039
366397
  }
366040
366398
  function findZodError(error) {
@@ -366529,7 +366887,7 @@ function assertEntryCount(value) {
366529
366887
  return value;
366530
366888
  }
366531
366889
  function parseMistakeRecordDeclarations(value, sourceId, declaredRecordTypes) {
366532
- if (!isRecord$16(value) || !hasOnlyKeys(value, [
366890
+ if (!isRecord$20(value) || !hasOnlyKeys(value, [
366533
366891
  "version",
366534
366892
  "records",
366535
366893
  "relations"
@@ -366542,7 +366900,7 @@ function parseMistakeRecordDeclarations(value, sourceId, declaredRecordTypes) {
366542
366900
  return {
366543
366901
  version: 1,
366544
366902
  records: value["records"].map((candidate, index) => {
366545
- if (!isRecord$16(candidate) || !hasOnlyKeys(candidate, [
366903
+ if (!isRecord$20(candidate) || !hasOnlyKeys(candidate, [
366546
366904
  "source_record_id",
366547
366905
  "type",
366548
366906
  "raw_locator"
@@ -366562,7 +366920,7 @@ function parseMistakeRecordDeclarations(value, sourceId, declaredRecordTypes) {
366562
366920
  };
366563
366921
  }),
366564
366922
  relations: value["relations"].map((candidate, index) => {
366565
- if (!isRecord$16(candidate) || !hasOnlyKeys(candidate, [
366923
+ if (!isRecord$20(candidate) || !hasOnlyKeys(candidate, [
366566
366924
  "from_source_record_id",
366567
366925
  "type",
366568
366926
  "to"
@@ -366572,7 +366930,7 @@ function parseMistakeRecordDeclarations(value, sourceId, declaredRecordTypes) {
366572
366930
  const target = candidate["to"];
366573
366931
  if (typeof fromRecordId !== "string" || !isValidRecordId(fromRecordId) || !recordIds.has(fromRecordId)) throw new Error(`record relation ${index} must start at a declared local record`);
366574
366932
  if (typeof type !== "string" || !MISTAKE_RELATION_TYPES.includes(type)) throw new Error(`record relation ${index} has an invalid relation type`);
366575
- if (!isRecord$16(target) || !hasOnlyKeys(target, ["source_id", "source_record_id"])) throw new Error(`record relation ${index} has an invalid target`);
366933
+ if (!isRecord$20(target) || !hasOnlyKeys(target, ["source_id", "source_record_id"])) throw new Error(`record relation ${index} has an invalid target`);
366576
366934
  const targetSourceId = target["source_id"];
366577
366935
  const targetRecordId = target["source_record_id"];
366578
366936
  if (typeof targetSourceId !== "string" || !isNormalizedSourceId(targetSourceId)) throw new Error(`record relation ${index} has an invalid target source id`);
@@ -366842,7 +367200,7 @@ function receiptsEqual(left, right) {
366842
367200
  return left.version === right.version && left.accepted === right.accepted && left.event_id === right.event_id && left.client_event_id === right.client_event_id && left.source_id === right.source_id && left.canonical_agent_id === right.canonical_agent_id && left.received_at === right.received_at && left.raw_count === right.raw_count && left.accepted_count === right.accepted_count && left.rejected_count === right.rejected_count && left.raw_bytes === right.raw_bytes && left.raw_sha256 === right.raw_sha256 && left.declared_entry_count === right.declared_entry_count;
366843
367201
  }
366844
367202
  function isStateActionReceipt(value) {
366845
- if (!isRecord$16(value) || !hasOnlyKeys(value, STATE_ACTION_KEYS)) return false;
367203
+ if (!isRecord$20(value) || !hasOnlyKeys(value, STATE_ACTION_KEYS)) return false;
366846
367204
  const reason = value["reason"];
366847
367205
  return value["version"] === 1 && typeof value["action_id"] === "string" && UUID_RE$1.test(value["action_id"]) && (value["action"] === "remove" || value["action"] === "restore") && typeof value["target_event_id"] === "string" && UUID_RE$1.test(value["target_event_id"]) && typeof value["acted_at"] === "string" && isIsoTimestamp(value["acted_at"]) && Number.isSafeInteger(value["server_sequence"]) && value["server_sequence"] >= 1 && typeof value["principal_id"] === "string" && isNormalizedSourceId(value["principal_id"]) && typeof reason === "string" && reason.trim() === reason && reason.length >= 3 && reason.length <= 500;
366848
367206
  }
@@ -366945,7 +367303,7 @@ function assertInventoryInvariants(bestandsstatus, aktualitaetsstatus, declaredE
366945
367303
  if (aktualitaetsstatus === "fresh" && lastRawObservedAt === null) throw new Error("fresh inventory requires a last raw observed timestamp");
366946
367304
  if (capturedAt !== void 0 && lastRawObservedAt !== null && Date.parse(lastRawObservedAt) > Date.parse(capturedAt)) throw new Error("last raw observed timestamp must not be later than captured at");
366947
367305
  }
366948
- function isRecord$16(value) {
367306
+ function isRecord$20(value) {
366949
367307
  return typeof value === "object" && value !== null && !Array.isArray(value);
366950
367308
  }
366951
367309
  function hasOnlyKeys(value, allowedKeys) {
@@ -367889,12 +368247,14 @@ const PERSONAL_MEMORY_EXPLICIT_CATEGORY = "user_explicit";
367889
368247
  const SAFE_BROKER_ERROR_CODES = new Set([
367890
368248
  "AUTHENTICATION_REQUIRED",
367891
368249
  "EXPLICIT_CONSENT_REQUIRED",
368250
+ "FORGET_GENERATION_CHANGED",
367892
368251
  "INTERNAL_ERROR",
367893
368252
  "INTERACTIVE_CONFIRMATION_REQUIRED",
367894
368253
  "INSUFFICIENT_SCOPE",
367895
368254
  "INVALID_PAYLOAD",
367896
368255
  "MEMORY_NOT_FOUND",
367897
368256
  "MEMORY_WRITE_DISABLED",
368257
+ "PAYLOAD_TOO_LARGE",
367898
368258
  "SECRET_REJECTED",
367899
368259
  "UNAVAILABLE"
367900
368260
  ]);
@@ -367909,7 +368269,7 @@ var PersonalMemoryBrokerError = class extends Error {
367909
368269
  }
367910
368270
  };
367911
368271
  function parsePersonalMemorySettings(payload) {
367912
- if (!isRecord$15(payload)) return void 0;
368272
+ if (!isRecord$19(payload)) return void 0;
367913
368273
  const status = payload["status"];
367914
368274
  if (status !== "configured" && status !== "never_asked") return void 0;
367915
368275
  const memoryEnabled = payload["memory_enabled"];
@@ -368018,21 +368378,23 @@ async function brokerHttpError(response) {
368018
368378
  const responseCode = await safeBrokerResponseCode(response);
368019
368379
  if (responseCode !== void 0) return new PersonalMemoryBrokerError(responseCode, status);
368020
368380
  if (status === 401) return new PersonalMemoryBrokerError("AUTHENTICATION_REQUIRED", status);
368381
+ if (status === 409) return new PersonalMemoryBrokerError("FORGET_GENERATION_CHANGED", status);
368382
+ if (status === 413) return new PersonalMemoryBrokerError("PAYLOAD_TOO_LARGE", status);
368021
368383
  if (status === 403) return new PersonalMemoryBrokerError("INSUFFICIENT_SCOPE", status);
368022
368384
  return new PersonalMemoryBrokerError("UNAVAILABLE", status);
368023
368385
  }
368024
368386
  async function safeBrokerResponseCode(response) {
368025
368387
  try {
368026
368388
  const payload = await response.json();
368027
- if (!isRecord$15(payload)) return void 0;
368028
- const nested = isRecord$15(payload["error"]) ? payload["error"]["code"] : void 0;
368389
+ if (!isRecord$19(payload)) return void 0;
368390
+ const nested = isRecord$19(payload["error"]) ? payload["error"]["code"] : void 0;
368029
368391
  const candidate = payload["code"] ?? payload["error_code"] ?? nested;
368030
368392
  return typeof candidate === "string" && SAFE_BROKER_ERROR_CODES.has(candidate) ? candidate : void 0;
368031
368393
  } catch {
368032
368394
  return;
368033
368395
  }
368034
368396
  }
368035
- function isRecord$15(value) {
368397
+ function isRecord$19(value) {
368036
368398
  return typeof value === "object" && value !== null && !Array.isArray(value);
368037
368399
  }
368038
368400
  function isAllowedBrokerRequest(method, path) {
@@ -368043,13 +368405,17 @@ function isAllowedBrokerRequest(method, path) {
368043
368405
  return false;
368044
368406
  }
368045
368407
  if (url.origin !== "https://personal-memory.invalid") return false;
368046
- if (url.search.length > 0 || url.hash.length > 0) return false;
368408
+ if (url.hash.length > 0) return false;
368409
+ if (url.pathname === "/api/memory/workspace" && url.search.length > 0) return method === "GET" && url.searchParams.size === 2 && url.searchParams.get("source") === "tui" && url.searchParams.has("sessionId") && (url.searchParams.get("sessionId")?.length ?? 0) > 0 && (url.searchParams.get("sessionId")?.length ?? 0) <= 200;
368410
+ if (url.search.length > 0) return false;
368047
368411
  const pathname = url.pathname;
368048
368412
  if (pathname === PERSONAL_MEMORY_SETTINGS_PATH) return method === "GET" || method === "PUT";
368049
368413
  if (pathname === "/api/account/consent") return method === "POST";
368050
368414
  if (pathname === PERSONAL_MEMORY_MEMORIES_PATH) return method === "GET" || method === "POST";
368051
368415
  if (/^\/v1\/me\/memories\/[0-9a-f-]{36}$/i.test(pathname)) return false;
368052
368416
  if (pathname === PERSONAL_MEMORY_RECALL_PATH) return method === PERSONAL_MEMORY_RECALL_METHOD;
368417
+ if (pathname === "/api/memory/workspace") return method === "GET";
368418
+ if (pathname === "/api/memory/capture" || pathname === "/api/memory/recall" || pathname === "/api/memory/search" || pathname === "/api/memory/retract") return method === "POST";
368053
368419
  return false;
368054
368420
  }
368055
368421
  //#endregion
@@ -368739,7 +369105,7 @@ function createAttestation(value, createdAt) {
368739
369105
  };
368740
369106
  }
368741
369107
  function parseProof(value) {
368742
- if (!isRecord$14(value) || value["schema"] !== "blun.proof" || value["schemaVersion"] !== 1) throw new Error("Unsupported proof document.");
369108
+ if (!isRecord$18(value) || value["schema"] !== "blun.proof" || value["schemaVersion"] !== 1) throw new Error("Unsupported proof document.");
368743
369109
  assertObjectKeys(value, [
368744
369110
  "schema",
368745
369111
  "schemaVersion",
@@ -368759,12 +369125,12 @@ function parseProof(value) {
368759
369125
  "incomplete",
368760
369126
  "failed"
368761
369127
  ].includes(proof.outcome)) throw new Error("Invalid proof outcome.");
368762
- if (!isRecord$14(proof.source) || proof.source.kind !== "workspace") throw new Error("Invalid proof source.");
369128
+ if (!isRecord$18(proof.source) || proof.source.kind !== "workspace") throw new Error("Invalid proof source.");
368763
369129
  assertObjectKeys(proof.source, ["kind"], ["git"], "proof source");
368764
369130
  if (proof.source.git !== void 0) validateGitSnapshot(proof.source.git);
368765
369131
  if (!Array.isArray(proof.checks) || !Array.isArray(proof.artifacts)) throw new TypeError("Invalid proof collections.");
368766
369132
  if (proof.checks.length > MAX_COMMANDS || proof.artifacts.length > MAX_ARTIFACTS) throw new Error("Proof collections exceed their limits.");
368767
- if (!isRecord$14(proof.attestation) || proof.attestation.algorithm !== "SHA-256" || proof.attestation.scope !== "content-integrity-only" || !SHA256_PATTERN.test(proof.attestation.hash)) throw new Error("Invalid proof attestation.");
369133
+ if (!isRecord$18(proof.attestation) || proof.attestation.algorithm !== "SHA-256" || proof.attestation.scope !== "content-integrity-only" || !SHA256_PATTERN.test(proof.attestation.hash)) throw new Error("Invalid proof attestation.");
368768
369134
  assertObjectKeys(proof.attestation, [
368769
369135
  "algorithm",
368770
369136
  "scope",
@@ -368779,7 +369145,7 @@ function parseProof(value) {
368779
369145
  screenshot: 0
368780
369146
  };
368781
369147
  for (const artifact of proof.artifacts) {
368782
- if (!isRecord$14(artifact) || artifact.kind !== "file" && artifact.kind !== "screenshot" || typeof artifact.id !== "string" || typeof artifact.size !== "number" || !Number.isSafeInteger(artifact.size) || artifact.size < 0 || typeof artifact.sha256 !== "string" || !SHA256_PATTERN.test(artifact.sha256)) throw new Error("Invalid proof artifact.");
369148
+ if (!isRecord$18(artifact) || artifact.kind !== "file" && artifact.kind !== "screenshot" || typeof artifact.id !== "string" || typeof artifact.size !== "number" || !Number.isSafeInteger(artifact.size) || artifact.size < 0 || typeof artifact.sha256 !== "string" || !SHA256_PATTERN.test(artifact.sha256)) throw new Error("Invalid proof artifact.");
368783
369149
  assertObjectKeys(artifact, [
368784
369150
  "id",
368785
369151
  "kind",
@@ -368796,14 +369162,14 @@ function parseProof(value) {
368796
369162
  return proof;
368797
369163
  }
368798
369164
  function validateGitSnapshot(value) {
368799
- if (!isRecord$14(value)) throw new Error("Invalid proof git snapshot.");
369165
+ if (!isRecord$18(value)) throw new Error("Invalid proof git snapshot.");
368800
369166
  assertObjectKeys(value, ["dirty", "changedCount"], [], "proof git snapshot");
368801
369167
  if (typeof value["dirty"] !== "boolean") throw new TypeError("Invalid proof git dirty flag.");
368802
369168
  if (typeof value["changedCount"] !== "number" || !Number.isSafeInteger(value["changedCount"]) || value["changedCount"] < 0) throw new Error("Invalid proof git changed count.");
368803
369169
  if (value["dirty"] !== value["changedCount"] > 0) throw new Error("Inconsistent proof git state.");
368804
369170
  }
368805
369171
  function validateProofCheck(value, index) {
368806
- if (!isRecord$14(value)) throw new Error("Invalid proof check.");
369172
+ if (!isRecord$18(value)) throw new Error("Invalid proof check.");
368807
369173
  assertObjectKeys(value, [
368808
369174
  "id",
368809
369175
  "outcome",
@@ -368815,13 +369181,13 @@ function validateProofCheck(value, index) {
368815
369181
  if (value["outcome"] !== expectedOutcome) throw new Error("Invalid proof check outcome.");
368816
369182
  }
368817
369183
  function attestedContent(value) {
368818
- if (!isRecord$14(value)) return value;
369184
+ if (!isRecord$18(value)) return value;
368819
369185
  const { attestation: _attestation, createdAt: _createdAt, ...content } = value;
368820
369186
  return content;
368821
369187
  }
368822
369188
  function canonicalize(value) {
368823
369189
  if (Array.isArray(value)) return value.map(canonicalize);
368824
- if (!isRecord$14(value)) return value;
369190
+ if (!isRecord$18(value)) return value;
368825
369191
  return Object.keys(value).toSorted().reduce((result, key) => {
368826
369192
  result[key] = canonicalize(value[key]);
368827
369193
  return result;
@@ -368898,7 +369264,7 @@ function sameFileIdentity$1(left, right) {
368898
369264
  function sameFileSnapshot(left, right) {
368899
369265
  return sameFileIdentity$1(left, right) && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
368900
369266
  }
368901
- function isRecord$14(value) {
369267
+ function isRecord$18(value) {
368902
369268
  return typeof value === "object" && value !== null && !Array.isArray(value);
368903
369269
  }
368904
369270
  //#endregion
@@ -373170,10 +373536,10 @@ var require_atomic_sleep = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373170
373536
  //#endregion
373171
373537
  //#region ../../node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js
373172
373538
  var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373173
- const fs$4 = __require("fs");
373539
+ const fs$3 = __require("fs");
373174
373540
  const EventEmitter$10 = __require("events");
373175
373541
  const inherits$6 = __require("util").inherits;
373176
- const path$6 = __require("path");
373542
+ const path$5 = __require("path");
373177
373543
  const sleep = require_atomic_sleep();
373178
373544
  const assert$8 = __require("assert");
373179
373545
  const BUSY_WRITE_TIMEOUT = 100;
@@ -373213,17 +373579,17 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373213
373579
  const flags = sonic.append ? "a" : "w";
373214
373580
  const mode = sonic.mode;
373215
373581
  if (sonic.sync) try {
373216
- if (sonic.mkdir) fs$4.mkdirSync(path$6.dirname(file), { recursive: true });
373217
- fileOpened(null, fs$4.openSync(file, flags, mode));
373582
+ if (sonic.mkdir) fs$3.mkdirSync(path$5.dirname(file), { recursive: true });
373583
+ fileOpened(null, fs$3.openSync(file, flags, mode));
373218
373584
  } catch (err) {
373219
373585
  fileOpened(err);
373220
373586
  throw err;
373221
373587
  }
373222
- else if (sonic.mkdir) fs$4.mkdir(path$6.dirname(file), { recursive: true }, (err) => {
373588
+ else if (sonic.mkdir) fs$3.mkdir(path$5.dirname(file), { recursive: true }, (err) => {
373223
373589
  if (err) return fileOpened(err);
373224
- fs$4.open(file, flags, mode, fileOpened);
373590
+ fs$3.open(file, flags, mode, fileOpened);
373225
373591
  });
373226
- else fs$4.open(file, flags, mode, fileOpened);
373592
+ else fs$3.open(file, flags, mode, fileOpened);
373227
373593
  }
373228
373594
  function SonicBoom(opts) {
373229
373595
  if (!(this instanceof SonicBoom)) return new SonicBoom(opts);
@@ -373261,8 +373627,8 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373261
373627
  this.flush = flushBuffer;
373262
373628
  this.flushSync = flushBufferSync;
373263
373629
  this._actualWrite = actualWriteBuffer;
373264
- fsWriteSync = () => fs$4.writeSync(this.fd, this._writingBuf);
373265
- fsWrite = () => fs$4.write(this.fd, this._writingBuf, this.release);
373630
+ fsWriteSync = () => fs$3.writeSync(this.fd, this._writingBuf);
373631
+ fsWrite = () => fs$3.write(this.fd, this._writingBuf, this.release);
373266
373632
  } else if (contentMode === void 0 || contentMode === kContentModeUtf8) {
373267
373633
  this._writingBuf = "";
373268
373634
  this.write = write;
@@ -373270,12 +373636,12 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373270
373636
  this.flushSync = flushSync;
373271
373637
  this._actualWrite = actualWrite;
373272
373638
  fsWriteSync = () => {
373273
- if (Buffer.isBuffer(this._writingBuf)) return fs$4.writeSync(this.fd, this._writingBuf);
373274
- return fs$4.writeSync(this.fd, this._writingBuf, "utf8");
373639
+ if (Buffer.isBuffer(this._writingBuf)) return fs$3.writeSync(this.fd, this._writingBuf);
373640
+ return fs$3.writeSync(this.fd, this._writingBuf, "utf8");
373275
373641
  };
373276
373642
  fsWrite = () => {
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);
373643
+ if (Buffer.isBuffer(this._writingBuf)) return fs$3.write(this.fd, this._writingBuf, this.release);
373644
+ return fs$3.write(this.fd, this._writingBuf, "utf8", this.release);
373279
373645
  };
373280
373646
  } else throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`);
373281
373647
  if (typeof fd === "number") {
@@ -373320,7 +373686,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373320
373686
  return;
373321
373687
  }
373322
373688
  }
373323
- if (this._fsync) fs$4.fsyncSync(this.fd);
373689
+ if (this._fsync) fs$3.fsyncSync(this.fd);
373324
373690
  const len = this._len;
373325
373691
  if (this._reopening) {
373326
373692
  this._writing = false;
@@ -373417,7 +373783,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373417
373783
  this._flushPending = true;
373418
373784
  const onDrain = () => {
373419
373785
  if (!this._fsync) try {
373420
- fs$4.fsync(this.fd, (err) => {
373786
+ fs$3.fsync(this.fd, (err) => {
373421
373787
  this._flushPending = false;
373422
373788
  cb(err);
373423
373789
  });
@@ -373494,7 +373860,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373494
373860
  if (this._writing) return;
373495
373861
  const fd = this.fd;
373496
373862
  this.once("ready", () => {
373497
- if (fd !== this.fd) fs$4.close(fd, (err) => {
373863
+ if (fd !== this.fd) fs$3.close(fd, (err) => {
373498
373864
  if (err) return this.emit("error", err);
373499
373865
  });
373500
373866
  });
@@ -373525,7 +373891,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373525
373891
  while (this._bufs.length || buf.length) {
373526
373892
  if (buf.length <= 0) buf = this._bufs[0];
373527
373893
  try {
373528
- const n = Buffer.isBuffer(buf) ? fs$4.writeSync(this.fd, buf) : fs$4.writeSync(this.fd, buf, "utf8");
373894
+ const n = Buffer.isBuffer(buf) ? fs$3.writeSync(this.fd, buf) : fs$3.writeSync(this.fd, buf, "utf8");
373529
373895
  const releasedBufObj = releaseWritingBuf(buf, this._len, n);
373530
373896
  buf = releasedBufObj.writingBuf;
373531
373897
  this._len = releasedBufObj.len;
@@ -373536,7 +373902,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373536
373902
  }
373537
373903
  }
373538
373904
  try {
373539
- fs$4.fsyncSync(this.fd);
373905
+ fs$3.fsyncSync(this.fd);
373540
373906
  } catch {}
373541
373907
  }
373542
373908
  function flushBufferSync() {
@@ -373550,7 +373916,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373550
373916
  while (this._bufs.length || buf.length) {
373551
373917
  if (buf.length <= 0) buf = mergeBuf(this._bufs[0], this._lens[0]);
373552
373918
  try {
373553
- const n = fs$4.writeSync(this.fd, buf);
373919
+ const n = fs$3.writeSync(this.fd, buf);
373554
373920
  buf = buf.subarray(n);
373555
373921
  this._len = Math.max(this._len - n, 0);
373556
373922
  if (buf.length <= 0) {
@@ -373572,24 +373938,24 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373572
373938
  this._writing = true;
373573
373939
  this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || "";
373574
373940
  if (this.sync) try {
373575
- release(null, Buffer.isBuffer(this._writingBuf) ? fs$4.writeSync(this.fd, this._writingBuf) : fs$4.writeSync(this.fd, this._writingBuf, "utf8"));
373941
+ release(null, Buffer.isBuffer(this._writingBuf) ? fs$3.writeSync(this.fd, this._writingBuf) : fs$3.writeSync(this.fd, this._writingBuf, "utf8"));
373576
373942
  } catch (err) {
373577
373943
  release(err);
373578
373944
  }
373579
- else fs$4.write(this.fd, this._writingBuf, release);
373945
+ else fs$3.write(this.fd, this._writingBuf, release);
373580
373946
  }
373581
373947
  function actualWriteBuffer() {
373582
373948
  const release = this.release;
373583
373949
  this._writing = true;
373584
373950
  this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift());
373585
373951
  if (this.sync) try {
373586
- release(null, fs$4.writeSync(this.fd, this._writingBuf));
373952
+ release(null, fs$3.writeSync(this.fd, this._writingBuf));
373587
373953
  } catch (err) {
373588
373954
  release(err);
373589
373955
  }
373590
373956
  else {
373591
373957
  if (kCopyBuffer) this._writingBuf = Buffer.from(this._writingBuf);
373592
- fs$4.write(this.fd, this._writingBuf, release);
373958
+ fs$3.write(this.fd, this._writingBuf, release);
373593
373959
  }
373594
373960
  }
373595
373961
  function actualClose(sonic) {
@@ -373603,10 +373969,10 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
373603
373969
  sonic._lens = [];
373604
373970
  assert$8(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`);
373605
373971
  try {
373606
- fs$4.fsync(sonic.fd, closeWrapped);
373972
+ fs$3.fsync(sonic.fd, closeWrapped);
373607
373973
  } catch {}
373608
373974
  function closeWrapped() {
373609
- if (sonic.fd !== 1 && sonic.fd !== 2) fs$4.close(sonic.fd, done);
373975
+ if (sonic.fd !== 1 && sonic.fd !== 2) fs$3.close(sonic.fd, done);
373610
373976
  else done();
373611
373977
  }
373612
373978
  function done(err) {
@@ -403246,7 +403612,7 @@ var import_multipart = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((
403246
403612
  const fp = require_plugin();
403247
403613
  const { createWriteStream: createWriteStream$1 } = __require("node:fs");
403248
403614
  const { unlink: unlink$1 } = __require("node:fs/promises");
403249
- const path$5 = __require("node:path");
403615
+ const path$4 = __require("node:path");
403250
403616
  const { generateId } = require_generateId();
403251
403617
  const createError = require_error$1();
403252
403618
  const streamToNull = require_stream_consumer();
@@ -403541,7 +403907,7 @@ var import_multipart = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((
403541
403907
  for await (const part of parts) {
403542
403908
  values = part.fields;
403543
403909
  if (!part.file) continue;
403544
- const filepath = path$5.join(tmpdir, generateId() + path$5.extname(part.filename || "file" + i++));
403910
+ const filepath = path$4.join(tmpdir, generateId() + path$4.extname(part.filename || "file" + i++));
403545
403911
  const target = createWriteStream$1(filepath);
403546
403912
  try {
403547
403913
  this.tmpUploads.push(filepath);
@@ -416282,8 +416648,8 @@ var require_dist$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
416282
416648
  //#endregion
416283
416649
  //#region ../../node_modules/.pnpm/@fastify+swagger@9.7.0/node_modules/@fastify/swagger/lib/mode/static.js
416284
416650
  var require_static = /* @__PURE__ */ __commonJSMin(((exports, module) => {
416285
- const path$4 = __require("node:path");
416286
- const fs$3 = __require("node:fs");
416651
+ const path$3 = __require("node:path");
416652
+ const fs$2 = __require("node:fs");
416287
416653
  const yaml = require_dist$1();
416288
416654
  module.exports = function(fastify, opts, done) {
416289
416655
  if (!opts.specification) return done(/* @__PURE__ */ new Error("specification is missing in the module options"));
@@ -416292,14 +416658,14 @@ var require_static = /* @__PURE__ */ __commonJSMin(((exports, module) => {
416292
416658
  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"));
416293
416659
  else if (opts.specification.path) {
416294
416660
  if (typeof opts.specification.path !== "string") return done(/* @__PURE__ */ new Error("specification.path is not a string"));
416295
- if (!fs$3.existsSync(path$4.resolve(opts.specification.path))) return done(/* @__PURE__ */ new Error(`${opts.specification.path} does not exist`));
416296
- const extName = path$4.extname(opts.specification.path).toLowerCase();
416661
+ if (!fs$2.existsSync(path$3.resolve(opts.specification.path))) return done(/* @__PURE__ */ new Error(`${opts.specification.path} does not exist`));
416662
+ const extName = path$3.extname(opts.specification.path).toLowerCase();
416297
416663
  if ([".yaml", ".json"].indexOf(extName) === -1) return done(/* @__PURE__ */ new Error("specification.path extension name is not supported, should be one from ['.yaml', '.json']"));
416298
416664
  if (opts.specification.postProcessor && typeof opts.specification.postProcessor !== "function") return done(/* @__PURE__ */ new Error("specification.postProcessor should be a function"));
416299
416665
  if (opts.specification.baseDir && typeof opts.specification.baseDir !== "string") return done(/* @__PURE__ */ new Error("specification.baseDir should be string"));
416300
- if (!opts.specification.baseDir) opts.specification.baseDir = path$4.resolve(path$4.dirname(opts.specification.path));
416666
+ if (!opts.specification.baseDir) opts.specification.baseDir = path$3.resolve(path$3.dirname(opts.specification.path));
416301
416667
  else while (opts.specification.baseDir.endsWith("/")) opts.specification.baseDir = opts.specification.baseDir.slice(0, -1);
416302
- const source = fs$3.readFileSync(path$4.resolve(opts.specification.path), "utf8");
416668
+ const source = fs$2.readFileSync(path$3.resolve(opts.specification.path), "utf8");
416303
416669
  switch (extName) {
416304
416670
  case ".yaml":
416305
416671
  swaggerObject = yaml.parse(source);
@@ -416566,11 +416932,11 @@ var require_should_route_hide = /* @__PURE__ */ __commonJSMin(((exports, module)
416566
416932
  //#endregion
416567
416933
  //#region ../../node_modules/.pnpm/@fastify+swagger@9.7.0/node_modules/@fastify/swagger/lib/util/read-package-json.js
416568
416934
  var require_read_package_json = /* @__PURE__ */ __commonJSMin(((exports, module) => {
416569
- const fs$2 = __require("node:fs");
416570
- const path$3 = __require("node:path");
416935
+ const fs$1 = __require("node:fs");
416936
+ const path$2 = __require("node:path");
416571
416937
  function readPackageJson() {
416572
416938
  try {
416573
- return JSON.parse(fs$2.readFileSync(path$3.join(__dirname, "..", "..", "package.json")));
416939
+ return JSON.parse(fs$1.readFileSync(path$2.join(__dirname, "..", "..", "package.json")));
416574
416940
  } catch {
416575
416941
  return {};
416576
416942
  }
@@ -423773,12 +424139,12 @@ function legacyStatusToCurrent(task) {
423773
424139
  return task.status;
423774
424140
  }
423775
424141
  function isReadablePersistedTask(obj) {
423776
- return isRecord$13(obj) && (typeof obj["taskId"] === "string" || typeof obj["task_id"] === "string");
424142
+ return isRecord$17(obj) && (typeof obj["taskId"] === "string" || typeof obj["task_id"] === "string");
423777
424143
  }
423778
424144
  function isLegacyPersistedTask(task) {
423779
424145
  return "task_id" in task;
423780
424146
  }
423781
- function isRecord$13(value) {
424147
+ function isRecord$17(value) {
423782
424148
  return typeof value === "object" && value !== null;
423783
424149
  }
423784
424150
  function optionalNonEmptyString(value) {
@@ -424187,11 +424553,11 @@ const WINDOWS_RESERVED_NAMES = new Set([
424187
424553
  ...Array.from({ length: 9 }, (_value, index) => `COM${String(index + 1)}`),
424188
424554
  ...Array.from({ length: 9 }, (_value, index) => `LPT${String(index + 1)}`)
424189
424555
  ]);
424190
- function isRecord$12(value) {
424556
+ function isRecord$16(value) {
424191
424557
  return typeof value === "object" && value !== null && !Array.isArray(value);
424192
424558
  }
424193
424559
  function assertRecord(value, label) {
424194
- if (!isRecord$12(value)) throw new Error(`${label} must be an object.`);
424560
+ if (!isRecord$16(value)) throw new Error(`${label} must be an object.`);
424195
424561
  }
424196
424562
  function assertExactKeys(value, required, optional, label) {
424197
424563
  const allowed = new Set([...required, ...optional]);
@@ -424482,7 +424848,7 @@ function currentArtifactRecord(artifacts) {
424482
424848
  return result;
424483
424849
  }
424484
424850
  function readAttestationHash(value) {
424485
- if (!isRecord$12(value) || !isRecord$12(value["attestation"])) return null;
424851
+ if (!isRecord$16(value) || !isRecord$16(value["attestation"])) return null;
424486
424852
  const hash = value["attestation"]["hash"];
424487
424853
  return typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash) ? hash : null;
424488
424854
  }
@@ -425254,21 +425620,21 @@ async function ensureSafeDirectory(path, create, recursive) {
425254
425620
  return true;
425255
425621
  }
425256
425622
  function validateRegistry(value, context) {
425257
- if (!isRecord$11(value) || value["version"] !== 1) throw new WorkspaceError("registry_invalid", "Unsupported workspace registry version.");
425623
+ if (!isRecord$15(value) || value["version"] !== 1) throw new WorkspaceError("registry_invalid", "Unsupported workspace registry version.");
425258
425624
  if (!hasExactKeys(value, REGISTRY_KEYS)) throw new WorkspaceError("registry_invalid", "Workspace registry contains unknown fields.");
425259
- if (value["repoFingerprint"] !== context.repoFingerprint || value["primaryRoot"] !== context.primaryRoot || !isRecord$11(value["workspaces"])) throw new WorkspaceError("registry_invalid", "Workspace registry does not match this repository.");
425625
+ if (value["repoFingerprint"] !== context.repoFingerprint || value["primaryRoot"] !== context.primaryRoot || !isRecord$15(value["workspaces"])) throw new WorkspaceError("registry_invalid", "Workspace registry does not match this repository.");
425260
425626
  for (const [name, record] of Object.entries(value["workspaces"])) if (!isWorkspaceRecord(record) || record.name !== name) throw new WorkspaceError("registry_invalid", "Workspace registry contains an invalid entry.");
425261
425627
  return value;
425262
425628
  }
425263
425629
  function isWorkspaceRecord(value) {
425264
- if (!isRecord$11(value) || !hasExactKeys(value, WORKSPACE_RECORD_KEYS)) return false;
425630
+ if (!isRecord$15(value) || !hasExactKeys(value, WORKSPACE_RECORD_KEYS)) return false;
425265
425631
  return typeof value["name"] === "string" && typeof value["path"] === "string" && typeof value["branch"] === "string" && typeof value["baseCommit"] === "string" && typeof value["repoFingerprint"] === "string" && isCanonicalIsoTimestamp(value["createdAt"]);
425266
425632
  }
425267
425633
  function isCanonicalIsoTimestamp(value) {
425268
425634
  if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return false;
425269
425635
  return new Date(value).toISOString() === value;
425270
425636
  }
425271
- function isRecord$11(value) {
425637
+ function isRecord$15(value) {
425272
425638
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
425273
425639
  const prototype = Object.getPrototypeOf(value);
425274
425640
  return prototype === Object.prototype || prototype === null;
@@ -425359,7 +425725,7 @@ async function readRegistryLockMetadata(lockPath) {
425359
425725
  if (error.code !== void 0) throw error;
425360
425726
  return;
425361
425727
  }
425362
- if (!isRecord$11(value) || !hasExactKeys(value, [
425728
+ if (!isRecord$15(value) || !hasExactKeys(value, [
425363
425729
  "version",
425364
425730
  "pid",
425365
425731
  "createdAt",
@@ -426068,7 +426434,7 @@ async function searchLocalWorkHistory(homeDir, sessions, query, limit = 8) {
426068
426434
  let skippedRecords = 0;
426069
426435
  for (const session of sessions) {
426070
426436
  const sessionDir = await realpath(session.sessionDir).catch(() => void 0);
426071
- if (sessionDir === void 0 || path.basename(sessionDir) !== session.id || !isInside(sessionsRoot, sessionDir)) {
426437
+ if (sessionDir === void 0 || path.basename(sessionDir) !== session.id || !isInside$1(sessionsRoot, sessionDir)) {
426072
426438
  skippedSessions++;
426073
426439
  continue;
426074
426440
  }
@@ -426090,7 +426456,7 @@ async function searchLocalWorkHistory(homeDir, sessions, query, limit = 8) {
426090
426456
  continue;
426091
426457
  }
426092
426458
  const canonicalWire = await realpath(wirePath).catch(() => void 0);
426093
- if (canonicalWire === void 0 || !isInside(sessionDir, canonicalWire)) {
426459
+ if (canonicalWire === void 0 || !isInside$1(sessionDir, canonicalWire)) {
426094
426460
  skippedSessions++;
426095
426461
  continue;
426096
426462
  }
@@ -426108,7 +426474,7 @@ async function searchLocalWorkHistory(homeDir, sessions, query, limit = 8) {
426108
426474
  skippedRecords++;
426109
426475
  continue;
426110
426476
  }
426111
- const event = isRecord$10(record) && record["type"] === "context.append_loop_event" && isRecord$10(record["event"]) ? record["event"] : void 0;
426477
+ const event = isRecord$14(record) && record["type"] === "context.append_loop_event" && isRecord$14(record["event"]) ? record["event"] : void 0;
426112
426478
  if (event?.["type"] === "step.end" && typeof event["uuid"] === "string") assistantSteps.delete(event["uuid"]);
426113
426479
  else if (event?.["type"] === "content.part" && typeof event["stepUuid"] === "string" && isTextPart(event["part"])) {
426114
426480
  const stepId = event["stepUuid"];
@@ -426185,11 +426551,11 @@ async function* boundedWireLines(wirePath, size) {
426185
426551
  }
426186
426552
  }
426187
426553
  function searchableText(record) {
426188
- if (!isRecord$10(record)) return void 0;
426189
- if (record["type"] === "context.append_message" && isRecord$10(record["message"])) {
426554
+ if (!isRecord$14(record)) return void 0;
426555
+ if (record["type"] === "context.append_message" && isRecord$14(record["message"])) {
426190
426556
  const message = record["message"];
426191
426557
  const origin = message["origin"];
426192
- if (message["role"] !== "user" && message["role"] !== "assistant" || message["role"] === "assistant" && origin !== void 0 || message["role"] === "user" && origin !== void 0 && (!isRecord$10(origin) || origin["kind"] !== "user")) return;
426558
+ if (message["role"] !== "user" && message["role"] !== "assistant" || message["role"] === "assistant" && origin !== void 0 || message["role"] === "user" && origin !== void 0 && (!isRecord$14(origin) || origin["kind"] !== "user")) return;
426193
426559
  const content = message["content"];
426194
426560
  if (!Array.isArray(content)) return void 0;
426195
426561
  const text = content.filter(isTextPart).map((part) => part.text).join(" ");
@@ -426211,12 +426577,12 @@ function snippet(text, firstTerm) {
426211
426577
  return `${start > 0 ? "..." : ""}${flattened.slice(start, end)}${end < flattened.length ? "..." : ""}`;
426212
426578
  }
426213
426579
  function isTextPart(value) {
426214
- return isRecord$10(value) && value["type"] === "text" && typeof value["text"] === "string";
426580
+ return isRecord$14(value) && value["type"] === "text" && typeof value["text"] === "string";
426215
426581
  }
426216
- function isRecord$10(value) {
426582
+ function isRecord$14(value) {
426217
426583
  return typeof value === "object" && value !== null && !Array.isArray(value);
426218
426584
  }
426219
- function isInside(parent, child) {
426585
+ function isInside$1(parent, child) {
426220
426586
  const relative = path.relative(parent, child);
426221
426587
  return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
426222
426588
  }
@@ -426309,7 +426675,7 @@ async function searchLocalToolEvents(homeDir, sessions, query, limit = 8) {
426309
426675
  };
426310
426676
  }
426311
426677
  function parseSavedEvent(value, sessionId) {
426312
- if (!isRecord$9(value) || value["version"] !== 1 || value["sessionId"] !== sessionId || typeof value["agentId"] !== "string" || !TOOL_NAME.test(value["agentId"]) || typeof value["tool"] !== "string" || !TOOL_NAME.test(value["tool"]) || typeof value["at"] !== "number" || !Number.isSafeInteger(value["at"]) || value["at"] < 0 || value["status"] !== "ok" && value["status"] !== "error" && value["status"] !== "synthetic") return;
426678
+ if (!isRecord$13(value) || value["version"] !== 1 || value["sessionId"] !== sessionId || typeof value["agentId"] !== "string" || !TOOL_NAME.test(value["agentId"]) || typeof value["tool"] !== "string" || !TOOL_NAME.test(value["tool"]) || typeof value["at"] !== "number" || !Number.isSafeInteger(value["at"]) || value["at"] < 0 || value["status"] !== "ok" && value["status"] !== "error" && value["status"] !== "synthetic") return;
426313
426679
  const filePath = value["filePath"];
426314
426680
  if (filePath !== void 0 && (typeof filePath !== "string" || filePath.length > 1024 || /[\u0000-\u001F\u007F]/u.test(filePath))) return void 0;
426315
426681
  return {
@@ -426341,7 +426707,7 @@ function localToolEventRecordingEnabled(homeDir) {
426341
426707
  }
426342
426708
  if (!info.isFile() || info.isSymbolicLink() || info.size > 1024) return false;
426343
426709
  const parsed = JSON.parse(readFileSync(settingsPath, "utf8"));
426344
- return isRecord$9(parsed) && parsed["version"] === 1 && parsed["enabled"] === true;
426710
+ return isRecord$13(parsed) && parsed["version"] === 1 && parsed["enabled"] === true;
426345
426711
  } catch {
426346
426712
  return false;
426347
426713
  }
@@ -426452,7 +426818,7 @@ function createLocalToolEventRecorder(homeDir, sessionId, enabled = localToolEve
426452
426818
  };
426453
426819
  }
426454
426820
  function filePathFor(tool, args) {
426455
- if (!FILE_TOOLS.has(tool) || !isRecord$9(args)) return {};
426821
+ if (!FILE_TOOLS.has(tool) || !isRecord$13(args)) return {};
426456
426822
  const value = args["path"];
426457
426823
  if (typeof value !== "string" || value.length === 0 || value.length > 1024 || /[\u0000-\u001F\u007F]/u.test(value)) return {};
426458
426824
  return { filePath: value };
@@ -426495,11 +426861,11 @@ async function assertPlainDirectory(directory) {
426495
426861
  function samePath(a, b) {
426496
426862
  return process.platform === "win32" ? path.resolve(a).toLocaleLowerCase() === path.resolve(b).toLocaleLowerCase() : path.resolve(a) === path.resolve(b);
426497
426863
  }
426498
- function isRecord$9(value) {
426864
+ function isRecord$13(value) {
426499
426865
  return typeof value === "object" && value !== null && !Array.isArray(value);
426500
426866
  }
426501
426867
  function isErrno$1(error, code) {
426502
- return isRecord$9(error) && error["code"] === code;
426868
+ return isRecord$13(error) && error["code"] === code;
426503
426869
  }
426504
426870
  //#endregion
426505
426871
  //#region src/personal-memory/session-mcp.ts
@@ -426681,12 +427047,12 @@ function isPersonalMemoryToolName(name) {
426681
427047
  return PERSONAL_MEMORY_TOOL_NAMES.includes(name);
426682
427048
  }
426683
427049
  function normalizePhaseOneRecall(payload, limit) {
426684
- if (!isRecord$8(payload) || !Array.isArray(payload["ergebnis"])) throw new PersonalMemoryBrokerError("INVALID_PAYLOAD");
427050
+ if (!isRecord$12(payload) || !Array.isArray(payload["ergebnis"])) throw new PersonalMemoryBrokerError("INVALID_PAYLOAD");
426685
427051
  const results = payload["ergebnis"];
426686
427052
  if (results.length > 100) throw new PersonalMemoryBrokerError("INVALID_PAYLOAD");
426687
427053
  return { personal_memory: {
426688
427054
  saved: results.map((entry) => {
426689
- if (!isRecord$8(entry)) throw new PersonalMemoryBrokerError("INVALID_PAYLOAD");
427055
+ if (!isRecord$12(entry)) throw new PersonalMemoryBrokerError("INVALID_PAYLOAD");
426690
427056
  const text = entry["inhalt"];
426691
427057
  if (typeof text !== "string" || text.trim().length === 0 || text.length > 4e3) throw new PersonalMemoryBrokerError("INVALID_PAYLOAD");
426692
427058
  return {
@@ -426698,7 +427064,46 @@ function normalizePhaseOneRecall(payload, limit) {
426698
427064
  chat_history_context: []
426699
427065
  } };
426700
427066
  }
426701
- function isRecord$8(value) {
427067
+ function isRecord$12(value) {
427068
+ return typeof value === "object" && value !== null && !Array.isArray(value);
427069
+ }
427070
+ //#endregion
427071
+ //#region src/personal-memory/account-memory-recall.ts
427072
+ function mergeAccountMemoryRecall(phaseOne, account) {
427073
+ const existing = parsePhaseOne(phaseOne);
427074
+ if (existing === void 0 && account === void 0) throw new PersonalMemoryBrokerError("UNAVAILABLE");
427075
+ const saved = [...(existing?.personal_memory.saved ?? []).slice(0, 4), ...(account?.profile.card ?? []).slice(0, 4).map((text) => ({
427076
+ text: text.slice(0, 1e3),
427077
+ confidence: "medium"
427078
+ }))];
427079
+ const threads = (existing?.personal_memory.threads ?? []).slice(0, 4);
427080
+ if (account?.profile.representation.trim()) threads.push({
427081
+ title: "Account memory profile",
427082
+ summary: account.profile.representation.slice(0, 1e3)
427083
+ });
427084
+ for (const item of account?.items ?? []) {
427085
+ if (threads.length >= 8) break;
427086
+ threads.push({
427087
+ title: `${item.source} / ${item.sessionId}`.slice(0, 200),
427088
+ summary: item.text.slice(0, 1e3)
427089
+ });
427090
+ }
427091
+ return { personal_memory: {
427092
+ saved,
427093
+ threads,
427094
+ chat_history_context: []
427095
+ } };
427096
+ }
427097
+ function parsePhaseOne(value) {
427098
+ if (!isRecord$11(value) || !isRecord$11(value["personal_memory"])) return void 0;
427099
+ const memory = value["personal_memory"];
427100
+ if (!Array.isArray(memory["saved"]) || !Array.isArray(memory["threads"]) || !Array.isArray(memory["chat_history_context"]) || memory["chat_history_context"].length > 0) return void 0;
427101
+ const saved = memory["saved"];
427102
+ const threads = memory["threads"];
427103
+ if (saved.length > 8 || threads.length > 8 || !saved.every((item) => isRecord$11(item) && typeof item["text"] === "string" && item["text"].length <= 1e3 && item["confidence"] === "medium") || !threads.every((item) => isRecord$11(item) && typeof item["title"] === "string" && item["title"].length <= 200 && typeof item["summary"] === "string" && item["summary"].length <= 1e3)) return void 0;
427104
+ return value;
427105
+ }
427106
+ function isRecord$11(value) {
426702
427107
  return typeof value === "object" && value !== null && !Array.isArray(value);
426703
427108
  }
426704
427109
  //#endregion
@@ -426817,7 +427222,7 @@ async function bindPersonalMemoryHostTools(session, harness, options = {}) {
426817
427222
  if (localHistory === void 0 || !savedSearchEnabled && !localOnlyEnabled) return;
426818
427223
  const searchClient = savedSearchEnabled ? options.client ?? createPersonalMemoryBrokerClient(harness) : void 0;
426819
427224
  try {
426820
- await registerPersonalMemorySearchTool(session, localHistory, searchClient, binding, savedSearchEnabled, localOnlyEnabled);
427225
+ await registerPersonalMemorySearchTool(session, localHistory, searchClient, binding, savedSearchEnabled, localOnlyEnabled, savedSearchEnabled ? options.accountMemory : void 0);
426821
427226
  } catch (error) {
426822
427227
  await session.unregisterToolAndWait(PERSONAL_MEMORY_SEARCH_TOOL).catch(() => {});
426823
427228
  throw error;
@@ -426835,10 +427240,10 @@ async function bindPersonalMemoryHostTools(session, harness, options = {}) {
426835
427240
  for (const name of binding === void 0 ? [] : personalMemoryToolNames(binding.mode, binding.capabilities)) {
426836
427241
  if (name === "memory_recall") continue;
426837
427242
  const definition = personalMemoryToolDefinition(name);
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));
427243
+ await session.registerToolAndWait(qualifiedPersonalMemoryToolName(name), definition.description, definition.parameters, createHostHandler(client, name, context, name === "memory_settings_update" ? () => refreshPersonalMemoryBinding(session, harness, client, localHistory, options.accountMemory) : void 0));
426839
427244
  }
426840
- if (savedSearchEnabled) session.setHostToolCallHandler(PERSONAL_MEMORY_HOST_RECALL_HANDLER, createHostHandler(client, "memory_recall", context));
426841
- if (localHistory !== void 0 && (savedSearchEnabled || localOnlyEnabled)) await registerPersonalMemorySearchTool(session, localHistory, client, binding, savedSearchEnabled, localOnlyEnabled);
427245
+ if (savedSearchEnabled) session.setHostToolCallHandler(PERSONAL_MEMORY_HOST_RECALL_HANDLER, createHostHandler(client, "memory_recall", context, void 0, options.accountMemory));
427246
+ if (localHistory !== void 0 && (savedSearchEnabled || localOnlyEnabled)) await registerPersonalMemorySearchTool(session, localHistory, client, binding, savedSearchEnabled, localOnlyEnabled, savedSearchEnabled ? options.accountMemory : void 0);
426842
427247
  if (binding !== void 0) await session.setPersonalMemoryHostCapability(true);
426843
427248
  } catch (error) {
426844
427249
  resetPersonalMemorySession();
@@ -426846,7 +427251,7 @@ async function bindPersonalMemoryHostTools(session, harness, options = {}) {
426846
427251
  throw error;
426847
427252
  }
426848
427253
  }
426849
- async function registerPersonalMemorySearchTool(session, localHistory, client, binding, savedSearchEnabled, localOnlyEnabled) {
427254
+ async function registerPersonalMemorySearchTool(session, localHistory, client, binding, savedSearchEnabled, localOnlyEnabled, accountMemory) {
426850
427255
  const context = binding === void 0 ? void 0 : {
426851
427256
  mode: binding.mode,
426852
427257
  capabilities: binding.capabilities
@@ -426859,14 +427264,15 @@ async function registerPersonalMemorySearchTool(session, localHistory, client, b
426859
427264
  };
426860
427265
  try {
426861
427266
  const sessions = localHistory.listSessions({ includeArchive: true });
426862
- const [savedResult, workHistoryResult, toolEventsResult] = await Promise.allSettled([
427267
+ const [savedResult, workHistoryResult, toolEventsResult, accountResult] = await Promise.allSettled([
426863
427268
  savedSearchEnabled ? invokePersonalMemoryTool(client, "memory_recall", parsed.data, context) : Promise.resolve(void 0),
426864
427269
  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))
427270
+ sessions.then((list) => searchLocalToolEvents(localHistory.homeDir, list, parsed.data.query, parsed.data.limit)),
427271
+ accountMemory?.search(parsed.data.query, Math.min(20, parsed.data.limit)) ?? Promise.resolve(void 0)
426866
427272
  ]);
426867
427273
  const saved = savedSearchEnabled && savedResult.status === "fulfilled" ? savedSearchResultSchema.safeParse(savedResult.value) : void 0;
426868
427274
  const savedAvailable = saved?.success === true;
426869
- if (!savedAvailable && workHistoryResult.status === "rejected" && toolEventsResult.status === "rejected") return {
427275
+ if (!savedAvailable && workHistoryResult.status === "rejected" && toolEventsResult.status === "rejected" && (accountResult.status === "rejected" || accountResult.value === void 0)) return {
426870
427276
  output: "MEMORY_SEARCH_UNAVAILABLE",
426871
427277
  isError: true
426872
427278
  };
@@ -426877,6 +427283,13 @@ async function registerPersonalMemorySearchTool(session, localHistory, client, b
426877
427283
  workHistoryAvailable: workHistoryResult.status === "fulfilled",
426878
427284
  toolEvents: toolEventsResult.status === "fulfilled" ? toolEventsResult.value : null,
426879
427285
  toolEventsAvailable: toolEventsResult.status === "fulfilled",
427286
+ accountHistory: accountResult.status === "fulfilled" ? accountResult.value?.items.slice(0, 8).map((item) => ({
427287
+ source: item.source,
427288
+ sessionId: item.sessionId,
427289
+ at: item.at,
427290
+ text: item.text.slice(0, 600)
427291
+ })) ?? null : null,
427292
+ accountHistoryAvailable: accountResult.status === "fulfilled" && accountResult.value !== void 0,
426880
427293
  toolEventRecordingEnabled: localOnlyEnabled
426881
427294
  }) };
426882
427295
  } catch {
@@ -426946,13 +427359,20 @@ function supportsPersonalMemoryHostTools(session) {
426946
427359
  function qualifiedPersonalMemoryToolName(name) {
426947
427360
  return `${PERSONAL_MEMORY_QUALIFIED_PREFIX}${name}`;
426948
427361
  }
426949
- function createHostHandler(client, name, context, afterSettingsUpdate) {
427362
+ function createHostHandler(client, name, context, afterSettingsUpdate, accountMemory) {
426950
427363
  return async (request) => {
426951
427364
  try {
426952
- const result = await invokePersonalMemoryTool(client, name, request.args, {
427365
+ const original = () => invokePersonalMemoryTool(client, name, request.args, {
426953
427366
  ...context,
426954
427367
  explicitRememberAttested: name === "memory_remember" ? consumePersonalMemoryRememberIntent(request) : void 0
426955
427368
  });
427369
+ let result;
427370
+ if (name === "memory_recall" && accountMemory !== void 0) {
427371
+ const parsed = searchInputSchema.safeParse(request.args);
427372
+ if (!parsed.success) throw new PersonalMemoryBrokerError("INVALID_PAYLOAD");
427373
+ const [phaseOne, account] = await Promise.all([original().catch(() => void 0), accountMemory.recall(parsed.data.query)]);
427374
+ result = mergeAccountMemoryRecall(phaseOne, account);
427375
+ } else result = await original();
426956
427376
  if (name === "memory_settings_update") await afterSettingsUpdate?.();
426957
427377
  return { output: JSON.stringify(result ?? null) };
426958
427378
  } catch (error) {
@@ -426963,7 +427383,7 @@ function createHostHandler(client, name, context, afterSettingsUpdate) {
426963
427383
  }
426964
427384
  };
426965
427385
  }
426966
- async function refreshPersonalMemoryBinding(session, harness, client, localHistory) {
427386
+ async function refreshPersonalMemoryBinding(session, harness, client, localHistory, accountMemory) {
426967
427387
  resetPersonalMemorySession();
426968
427388
  await clearPersonalMemoryHostTools(session);
426969
427389
  try {
@@ -426975,7 +427395,8 @@ async function refreshPersonalMemoryBinding(session, harness, client, localHisto
426975
427395
  await bindPersonalMemoryHostTools(session, harness, {
426976
427396
  binding,
426977
427397
  client,
426978
- localHistory
427398
+ localHistory,
427399
+ accountMemory
426979
427400
  });
426980
427401
  } catch (error) {
426981
427402
  resetPersonalMemorySession();
@@ -433498,9 +433919,9 @@ var TUI = class TUI extends Container {
433498
433919
  const debugRedraw = process.env["PI_DEBUG_REDRAW"] === "1";
433499
433920
  const logRedraw = (reason) => {
433500
433921
  if (!debugRedraw) return;
433501
- const logPath = path$17.join(nodeOs.homedir(), ".pi", "agent", "pi-debug.log");
433922
+ const logPath = path$16.join(nodeOs.homedir(), ".pi", "agent", "pi-debug.log");
433502
433923
  const msg = `[${(/* @__PURE__ */ new Date()).toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
433503
- fs$17.appendFileSync(logPath, msg);
433924
+ fs$16.appendFileSync(logPath, msg);
433504
433925
  };
433505
433926
  if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
433506
433927
  logRedraw("first render");
@@ -433647,8 +434068,8 @@ var TUI = class TUI extends Container {
433647
434068
  buffer += "\x1B[?2026l";
433648
434069
  if (process.env["PI_TUI_DEBUG"] === "1") {
433649
434070
  const debugDir = "/tmp/tui";
433650
- fs$17.mkdirSync(debugDir, { recursive: true });
433651
- const debugPath = path$17.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
434071
+ fs$16.mkdirSync(debugDir, { recursive: true });
434072
+ const debugPath = path$16.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
433652
434073
  const debugData = [
433653
434074
  `firstChanged: ${firstChanged}`,
433654
434075
  `viewportTop: ${viewportTop}`,
@@ -433671,7 +434092,7 @@ var TUI = class TUI extends Container {
433671
434092
  "=== buffer ===",
433672
434093
  JSON.stringify(buffer)
433673
434094
  ].join("\n");
433674
- fs$17.writeFileSync(debugPath, debugData);
434095
+ fs$16.writeFileSync(debugPath, debugData);
433675
434096
  }
433676
434097
  this.terminal.write(buffer);
433677
434098
  this.cursorRow = Math.max(0, newLines.length - 1);
@@ -438257,12 +438678,12 @@ function loadNativeModifiersHelper() {
438257
438678
  if (process.platform !== "darwin") return void 0;
438258
438679
  const arch = process.arch;
438259
438680
  if (arch !== "x64" && arch !== "arm64") return void 0;
438260
- const moduleDir = path$17.dirname(fileURLToPath(import.meta.url));
438261
- const nativePath = path$17.join("native", "darwin", "prebuilds", `darwin-${arch}`, "darwin-modifiers.node");
438681
+ const moduleDir = path$16.dirname(fileURLToPath(import.meta.url));
438682
+ const nativePath = path$16.join("native", "darwin", "prebuilds", `darwin-${arch}`, "darwin-modifiers.node");
438262
438683
  const candidates = [
438263
- path$17.join(moduleDir, "..", nativePath),
438264
- path$17.join(moduleDir, nativePath),
438265
- path$17.join(path$17.dirname(process.execPath), nativePath)
438684
+ path$16.join(moduleDir, "..", nativePath),
438685
+ path$16.join(moduleDir, nativePath),
438686
+ path$16.join(path$16.dirname(process.execPath), nativePath)
438266
438687
  ];
438267
438688
  for (const modulePath of candidates) try {
438268
438689
  const helper = cjsRequire$1(modulePath);
@@ -438335,10 +438756,10 @@ var ProcessTerminal = class {
438335
438756
  const env = process.env["PI_TUI_WRITE_LOG"] || "";
438336
438757
  if (!env) return "";
438337
438758
  try {
438338
- if (fs$17.statSync(env).isDirectory()) {
438759
+ if (fs$16.statSync(env).isDirectory()) {
438339
438760
  const now = /* @__PURE__ */ new Date();
438340
438761
  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")}`;
438341
- return path$17.join(env, `tui-${ts}-${process.pid}.log`);
438762
+ return path$16.join(env, `tui-${ts}-${process.pid}.log`);
438342
438763
  }
438343
438764
  } catch {}
438344
438765
  return env;
@@ -438541,12 +438962,12 @@ var ProcessTerminal = class {
438541
438962
  try {
438542
438963
  const arch = process.arch;
438543
438964
  if (arch !== "x64" && arch !== "arm64") return;
438544
- const moduleDir = path$17.dirname(fileURLToPath(import.meta.url));
438545
- const nativePath = path$17.join("native", "win32", "prebuilds", `win32-${arch}`, "win32-console-mode.node");
438965
+ const moduleDir = path$16.dirname(fileURLToPath(import.meta.url));
438966
+ const nativePath = path$16.join("native", "win32", "prebuilds", `win32-${arch}`, "win32-console-mode.node");
438546
438967
  const candidates = [
438547
- path$17.join(moduleDir, "..", nativePath),
438548
- path$17.join(moduleDir, nativePath),
438549
- path$17.join(path$17.dirname(process.execPath), nativePath)
438968
+ path$16.join(moduleDir, "..", nativePath),
438969
+ path$16.join(moduleDir, nativePath),
438970
+ path$16.join(path$16.dirname(process.execPath), nativePath)
438550
438971
  ];
438551
438972
  for (const modulePath of candidates) try {
438552
438973
  cjsRequire(modulePath).enableVirtualTerminalInput?.();
@@ -438618,7 +439039,7 @@ var ProcessTerminal = class {
438618
439039
  write(data) {
438619
439040
  process.stdout.write(data);
438620
439041
  if (this.writeLogPath) try {
438621
- fs$17.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
439042
+ fs$16.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
438622
439043
  } catch {}
438623
439044
  }
438624
439045
  get columns() {
@@ -438706,6 +439127,148 @@ function sanitizeTerminalText(value) {
438706
439127
  return value.replaceAll(OSC_SEQUENCE$1, "").replaceAll(CSI_SEQUENCE$1, "").replaceAll(ESC_SEQUENCE$1, "").replaceAll(CONTROL_CHARACTERS$1, " ");
438707
439128
  }
438708
439129
  //#endregion
439130
+ //#region src/tui/utils/export-markdown.copy.ts
439131
+ registerUiCatalogFragment({
439132
+ en: {
439133
+ "export.thinking": "Thinking",
439134
+ "export.image": "image",
439135
+ "export.audio": "audio",
439136
+ "export.video": "video",
439137
+ "export.toolCall": "Tool Call: {name}",
439138
+ "export.toolResult": "Tool Result: {name}",
439139
+ "export.turn": "Turn {number}",
439140
+ "export.user": "User",
439141
+ "export.assistant": "Assistant",
439142
+ "export.system": "System",
439143
+ "export.unknownTool": "unknown",
439144
+ "export.overview": "Overview",
439145
+ "export.topic": "Topic",
439146
+ "export.labelSeparator": ":",
439147
+ "export.empty": "empty",
439148
+ "export.conversation": "Conversation",
439149
+ "export.turnCount.one": "{count} turn",
439150
+ "export.turnCount.other": "{count} turns",
439151
+ "export.toolCallCount.one": "{count} tool call",
439152
+ "export.toolCallCount.other": "{count} tool calls",
439153
+ "export.title": "King Session Export"
439154
+ },
439155
+ de: {
439156
+ "export.thinking": "Denken",
439157
+ "export.image": "Bild",
439158
+ "export.audio": "Audio",
439159
+ "export.video": "Video",
439160
+ "export.toolCall": "Werkzeugaufruf: {name}",
439161
+ "export.toolResult": "Werkzeugergebnis: {name}",
439162
+ "export.turn": "Durchlauf {number}",
439163
+ "export.user": "Benutzer",
439164
+ "export.assistant": "Assistent",
439165
+ "export.system": "System",
439166
+ "export.unknownTool": "unbekannt",
439167
+ "export.overview": "Übersicht",
439168
+ "export.topic": "Thema",
439169
+ "export.labelSeparator": ":",
439170
+ "export.empty": "leer",
439171
+ "export.conversation": "Gespräch",
439172
+ "export.turnCount.one": "{count} Durchlauf",
439173
+ "export.turnCount.other": "{count} Durchläufe",
439174
+ "export.toolCallCount.one": "{count} Werkzeugaufruf",
439175
+ "export.toolCallCount.other": "{count} Werkzeugaufrufe",
439176
+ "export.title": "King-Sitzungsexport"
439177
+ },
439178
+ es: {
439179
+ "export.thinking": "Razonamiento",
439180
+ "export.image": "imagen",
439181
+ "export.audio": "audio",
439182
+ "export.video": "vídeo",
439183
+ "export.toolCall": "Llamada a herramienta: {name}",
439184
+ "export.toolResult": "Resultado de la herramienta: {name}",
439185
+ "export.turn": "Turno {number}",
439186
+ "export.user": "Usuario",
439187
+ "export.assistant": "Asistente",
439188
+ "export.system": "Sistema",
439189
+ "export.unknownTool": "desconocida",
439190
+ "export.overview": "Resumen",
439191
+ "export.topic": "Tema",
439192
+ "export.labelSeparator": ":",
439193
+ "export.empty": "vacío",
439194
+ "export.conversation": "Conversación",
439195
+ "export.turnCount.one": "{count} turno",
439196
+ "export.turnCount.other": "{count} turnos",
439197
+ "export.toolCallCount.one": "{count} llamada a herramienta",
439198
+ "export.toolCallCount.other": "{count} llamadas a herramientas",
439199
+ "export.title": "Exportación de la sesión de King"
439200
+ },
439201
+ fr: {
439202
+ "export.thinking": "Réflexion",
439203
+ "export.image": "image",
439204
+ "export.audio": "audio",
439205
+ "export.video": "vidéo",
439206
+ "export.toolCall": "Appel d’outil\xA0: {name}",
439207
+ "export.toolResult": "Résultat de l’outil\xA0: {name}",
439208
+ "export.turn": "Tour {number}",
439209
+ "export.user": "Utilisateur",
439210
+ "export.assistant": "Assistant",
439211
+ "export.system": "Système",
439212
+ "export.unknownTool": "inconnu",
439213
+ "export.overview": "Vue d’ensemble",
439214
+ "export.topic": "Sujet",
439215
+ "export.labelSeparator": "\xA0:",
439216
+ "export.empty": "vide",
439217
+ "export.conversation": "Conversation",
439218
+ "export.turnCount.one": "{count} tour",
439219
+ "export.turnCount.other": "{count} tours",
439220
+ "export.toolCallCount.one": "{count} appel d’outil",
439221
+ "export.toolCallCount.other": "{count} appels d’outil",
439222
+ "export.title": "Export de la session King"
439223
+ },
439224
+ sv: {
439225
+ "export.thinking": "Resonemang",
439226
+ "export.image": "bild",
439227
+ "export.audio": "ljud",
439228
+ "export.video": "video",
439229
+ "export.toolCall": "Verktygsanrop: {name}",
439230
+ "export.toolResult": "Verktygsresultat: {name}",
439231
+ "export.turn": "Omgång {number}",
439232
+ "export.user": "Användare",
439233
+ "export.assistant": "Assistent",
439234
+ "export.system": "System",
439235
+ "export.unknownTool": "okänt",
439236
+ "export.overview": "Översikt",
439237
+ "export.topic": "Ämne",
439238
+ "export.labelSeparator": ":",
439239
+ "export.empty": "tomt",
439240
+ "export.conversation": "Konversation",
439241
+ "export.turnCount.one": "{count} omgång",
439242
+ "export.turnCount.other": "{count} omgångar",
439243
+ "export.toolCallCount.one": "{count} verktygsanrop",
439244
+ "export.toolCallCount.other": "{count} verktygsanrop",
439245
+ "export.title": "Export av King-session"
439246
+ },
439247
+ cs: {
439248
+ "export.thinking": "Uvažování",
439249
+ "export.image": "obrázek",
439250
+ "export.audio": "zvuk",
439251
+ "export.video": "video",
439252
+ "export.toolCall": "Volání nástroje: {name}",
439253
+ "export.toolResult": "Výsledek nástroje: {name}",
439254
+ "export.turn": "Kolo {number}",
439255
+ "export.user": "Uživatel",
439256
+ "export.assistant": "Asistent",
439257
+ "export.system": "Systém",
439258
+ "export.unknownTool": "neznámý",
439259
+ "export.overview": "Přehled",
439260
+ "export.topic": "Téma",
439261
+ "export.labelSeparator": ":",
439262
+ "export.empty": "prázdné",
439263
+ "export.conversation": "Konverzace",
439264
+ "export.turnCount.one": "Kola: {count}",
439265
+ "export.turnCount.other": "Kola: {count}",
439266
+ "export.toolCallCount.one": "{count} volání nástroje",
439267
+ "export.toolCallCount.other": "{count} volání nástrojů",
439268
+ "export.title": "Export relace King"
439269
+ }
439270
+ });
439271
+ //#endregion
438709
439272
  //#region src/tui/components/messages/usage-panel.ts
438710
439273
  registerUiCatalogFragment({
438711
439274
  en: {
@@ -438874,6 +439437,11 @@ function usageNumber(value) {
438874
439437
  function usageInputTotal$2(usage) {
438875
439438
  return usageNumber(usage.inputOther) + usageNumber(usage.inputCacheRead) + usageNumber(usage.inputCacheCreation);
438876
439439
  }
439440
+ function knownReasoningTokens(usage) {
439441
+ const value = usage.outputReasoning;
439442
+ const output = usageNumber(usage.output);
439443
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= output ? value : void 0;
439444
+ }
438877
439445
  function managedUsageLabel(row) {
438878
439446
  switch (row.id) {
438879
439447
  case "five_hours": return uiText("usage.plan.window.fiveHours");
@@ -438922,14 +439490,23 @@ function buildSessionUsageSection(usage, error, value, muted, errorStyle) {
438922
439490
  const locale = getCurrentUiLocale();
438923
439491
  let totalInput = 0;
438924
439492
  let totalOutput = 0;
439493
+ let totalReasoning = 0;
439494
+ let reasoningComplete = true;
438925
439495
  for (const [model, row] of entries) {
438926
439496
  const input = usageInputTotal$2(row);
438927
439497
  const output = usageNumber(row.output);
439498
+ const reasoning = knownReasoningTokens(row);
438928
439499
  totalInput += input;
438929
439500
  totalOutput += output;
438930
- lines.push(` ${muted(sanitizeTerminalText(model))} ${uiText("usage.input")} ${value(formatExactTokenCount(input, locale))} ${uiText("usage.output")} ${value(formatExactTokenCount(output, locale))} ${uiText("usage.total")} ${value(formatExactTokenCount(input + output, locale))}`);
439501
+ if (reasoning !== void 0) totalReasoning += reasoning;
439502
+ else if (output > 0) reasoningComplete = false;
439503
+ const reasoningPart = reasoning === void 0 ? "" : ` ${uiText("export.thinking")} ${value(formatExactTokenCount(reasoning, locale))}`;
439504
+ lines.push(` ${muted(sanitizeTerminalText(model))} ${uiText("usage.input")} ${value(formatExactTokenCount(input, locale))} ${uiText("usage.output")} ${value(formatExactTokenCount(output, locale))}${reasoningPart} ${uiText("usage.total")} ${value(formatExactTokenCount(input + output, locale))}`);
439505
+ }
439506
+ if (entries.length > 1) {
439507
+ const reasoningPart = reasoningComplete && totalOutput > 0 ? ` ${uiText("export.thinking")} ${value(formatExactTokenCount(totalReasoning, locale))}` : "";
439508
+ lines.push(` ${muted(uiText("usage.total"))} ${uiText("usage.input")} ${value(formatExactTokenCount(totalInput, locale))} ${uiText("usage.output")} ${value(formatExactTokenCount(totalOutput, locale))}${reasoningPart} ${uiText("usage.total")} ${value(formatExactTokenCount(totalInput + totalOutput, locale))}`);
438931
439509
  }
438932
- if (entries.length > 1) lines.push(` ${muted(uiText("usage.total"))} ${uiText("usage.input")} ${value(formatExactTokenCount(totalInput, locale))} ${uiText("usage.output")} ${value(formatExactTokenCount(totalOutput, locale))} ${uiText("usage.total")} ${value(formatExactTokenCount(totalInput + totalOutput, locale))}`);
438933
439510
  return lines;
438934
439511
  }
438935
439512
  function buildManagedUsageSection(usage, error, accent, value, muted, errorStyle) {
@@ -502978,7 +503555,7 @@ function parsePluginMarketplace(raw, location) {
502978
503555
  } catch (error) {
502979
503556
  throw new Error(`Plugin marketplace is not valid JSON: ${formatParseError(error)}`, { cause: error });
502980
503557
  }
502981
- if (!isRecord$7(parsed)) throw new TypeError("Plugin marketplace must be an object.");
503558
+ if (!isRecord$10(parsed)) throw new TypeError("Plugin marketplace must be an object.");
502982
503559
  const rawPlugins = parsed["plugins"];
502983
503560
  if (!Array.isArray(rawPlugins)) throw new TypeError("Plugin marketplace must contain a \"plugins\" array.");
502984
503561
  return {
@@ -503022,7 +503599,7 @@ async function readMarketplaceText(location, fetchImpl) {
503022
503599
  return response.text();
503023
503600
  }
503024
503601
  function parseMarketplaceEntry(value, index, location) {
503025
- if (!isRecord$7(value)) throw new TypeError(`Plugin marketplace entry ${index + 1} must be an object.`);
503602
+ if (!isRecord$10(value)) throw new TypeError(`Plugin marketplace entry ${index + 1} must be an object.`);
503026
503603
  const id = requiredString(value, "id", index);
503027
503604
  validateMarketplaceEntryType(value, id);
503028
503605
  const source = stringField$2(value, "source") ?? stringField$2(value, "url") ?? stringField$2(value, "downloadUrl");
@@ -503158,7 +503735,7 @@ function stringArrayField(value, field) {
503158
503735
  const out = raw.filter((item) => typeof item === "string").map((item) => item.trim()).filter((item) => item.length > 0);
503159
503736
  return out.length > 0 ? out : void 0;
503160
503737
  }
503161
- function isRecord$7(value) {
503738
+ function isRecord$10(value) {
503162
503739
  return typeof value === "object" && value !== null && !Array.isArray(value);
503163
503740
  }
503164
503741
  function formatParseError(error) {
@@ -505260,6 +505837,7 @@ async function handleBlunApiKeyLogin(host, options, promptOptions) {
505260
505837
  provider: DEFAULT_OAUTH_PROVIDER_NAME,
505261
505838
  method: "api_key"
505262
505839
  });
505840
+ host.accountMemoryRuntime?.retryPending().catch(() => {});
505263
505841
  host.showStatus(uiText("auth.login.success"));
505264
505842
  return "authenticated";
505265
505843
  }
@@ -505302,6 +505880,7 @@ async function handleBlunCodeOAuthLogin(host, options = {}) {
505302
505880
  method: "oauth",
505303
505881
  already_logged_in: alreadyLoggedIn
505304
505882
  });
505883
+ host.accountMemoryRuntime?.retryPending().catch(() => {});
505305
505884
  if (alreadyLoggedIn) host.showStatus(uiText("auth.login.already"));
505306
505885
  return "authenticated";
505307
505886
  } catch (error) {
@@ -505346,11 +505925,16 @@ async function handleLogoutCommand(host) {
505346
505925
  const currentProvider = host.state.appState.availableModels[currentModel]?.provider;
505347
505926
  const target = await promptLogoutProviderSelection(host, options, currentProvider);
505348
505927
  if (target === void 0) return;
505928
+ const memoryRetractionPending = await host.accountMemoryRuntime?.flushRetractionsBeforeLogout() ?? false;
505349
505929
  showAuthWarnings(host, (await host.harness.auth.logout(DEFAULT_OAUTH_PROVIDER_NAME)).warnings);
505350
505930
  await host.authFlow.refreshConfigAfterLogout({ clearCustomerAccount: true });
505351
505931
  await host.authFlow.clearActiveSessionAfterLogout({ clearCustomerAccount: true });
505352
505932
  host.track("logout", { provider: target });
505353
505933
  host.showStatus(uiText("auth.logout.complete", { provider: PRODUCT_NAME }));
505934
+ if (memoryRetractionPending) {
505935
+ const key = hasManagedApiKey ? "auth.warning.memoryRetractionApiKeyPending" : "auth.warning.memoryRetractionOAuthPending";
505936
+ host.showStatus(uiText(key), "warning");
505937
+ }
505354
505938
  }
505355
505939
  function showAuthWarnings(host, warnings) {
505356
505940
  if (warnings?.some((warning) => warning.code === "remote_revoke_failed") === true) host.showStatus(uiText("auth.warning.remoteRevokeFailed"), "warning");
@@ -505782,6 +506366,11 @@ async function showContextReport(host, detailed) {
505782
506366
  name: tool.name === void 0 ? void 0 : diagnosticLabel(tool.name),
505783
506367
  bytes: validTextSize(tool.bytes)
505784
506368
  })) : void 0,
506369
+ toolResults: detailed === true ? breakdown?.toolResultByTool?.map((tool) => ({
506370
+ name: tool.name === void 0 ? void 0 : diagnosticLabel(tool.name),
506371
+ count: validTextSize(tool.count),
506372
+ bytes: validTextSize(tool.bytes)
506373
+ })) : void 0,
505785
506374
  toolArrayOverheadBytes: validTextSize(breakdown?.toolArrayOverheadBytes),
505786
506375
  historyOrigins: origins === void 0 ? void 0 : {
505787
506376
  totalBytes: validTextSize(origins.totalBytes),
@@ -505849,6 +506438,15 @@ async function showContextReport(host, detailed) {
505849
506438
  if (lastRequest.tools.length > 20) lines.push(`... (+${String(lastRequest.tools.length - 20)})`);
505850
506439
  lines.push(row("context.otherPart", lastRequest.toolArrayOverheadBytes));
505851
506440
  }
506441
+ if (lastRequest.toolResults !== void 0) {
506442
+ lines.push("", currentTheme.boldFg("primary", uiText("context.toolResultsPart")));
506443
+ for (const tool of lastRequest.toolResults.toSorted((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1)).slice(0, 20)) {
506444
+ const count = tool.count === void 0 ? "?" : formatExactTokenCount(tool.count, getCurrentUiLocale());
506445
+ const size = tool.bytes === void 0 ? uiText("context.unavailable") : formatExactTokenCount(tool.bytes, getCurrentUiLocale());
506446
+ lines.push(`${tool.name ?? "?"} (${count}): ${size}`);
506447
+ }
506448
+ if (lastRequest.toolResults.length > 20) lines.push(`... (+${String(lastRequest.toolResults.length - 20)})`);
506449
+ }
505852
506450
  lines.push("", currentTheme.boldFg("primary", uiText("context.promptTextBytes")), currentTheme.fg("textDim", uiText("context.sourceNote")), row("context.instructionPart", lastRequest.sources[0]), row("context.skillListingPart", lastRequest.sources[1]), row("context.runtimeMemoryPart", lastRequest.sources[2]), row("context.templatePart", lastRequest.sources[3]), row("context.totalPart", lastRequest.sources[4]), "", currentTheme.boldFg("primary", uiText("context.sourceFilesPart")), row("context.generatedPart", lastRequest.sources[5]));
505853
506451
  if (lastRequest.files === void 0) lines.push(uiText("context.unavailable"));
505854
506452
  else {
@@ -506235,7 +506833,7 @@ var ChannelCommandController = class {
506235
506833
  function requireValid(condition) {
506236
506834
  if (!condition) throw new Error("Invalid Telegram session queue state or transition");
506237
506835
  }
506238
- function isRecord$6(value) {
506836
+ function isRecord$9(value) {
506239
506837
  return typeof value === "object" && value !== null && !Array.isArray(value);
506240
506838
  }
506241
506839
  function isId(value) {
@@ -506245,7 +506843,7 @@ function isOffset(value) {
506245
506843
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
506246
506844
  }
506247
506845
  function readSpan(value) {
506248
- requireValid(isRecord$6(value));
506846
+ requireValid(isRecord$9(value));
506249
506847
  const { start, end } = value;
506250
506848
  requireValid(isOffset(start) && isOffset(end) && start < end);
506251
506849
  return {
@@ -506258,7 +506856,7 @@ function ownsRange(state, sessionId, span) {
506258
506856
  }
506259
506857
  /** Reject incompatible or corrupt state; never silently fall back to the profile cursor. */
506260
506858
  function parseSessionQueue(value) {
506261
- requireValid(isRecord$6(value));
506859
+ requireValid(isRecord$9(value));
506262
506860
  const { version, fileId, frontier, activeSessionId, sessions, spans, acknowledged } = value;
506263
506861
  requireValid(version === 1 && isId(fileId) && isOffset(frontier) && isId(activeSessionId));
506264
506862
  requireValid(Array.isArray(sessions) && sessions.every(isId));
@@ -506267,7 +506865,7 @@ function parseSessionQueue(value) {
506267
506865
  requireValid(Array.isArray(spans) && Array.isArray(acknowledged));
506268
506866
  const owned = spans.map((raw) => {
506269
506867
  const span = readSpan(raw);
506270
- requireValid(isRecord$6(raw));
506868
+ requireValid(isRecord$9(raw));
506271
506869
  const sessionId = raw["sessionId"];
506272
506870
  requireValid(sessionId === null || isId(sessionId) && known.has(sessionId));
506273
506871
  return {
@@ -508758,14 +509356,14 @@ function findGoalIndex(file, goalId) {
508758
509356
  return index;
508759
509357
  }
508760
509358
  function isGoalQueueFile(value) {
508761
- if (!isRecord$5(value)) return false;
509359
+ if (!isRecord$8(value)) return false;
508762
509360
  return value["version"] === GOAL_QUEUE_VERSION && Array.isArray(value["goals"]) && value["goals"].every(isUpcomingGoal);
508763
509361
  }
508764
509362
  function isUpcomingGoal(value) {
508765
- if (!isRecord$5(value)) return false;
509363
+ if (!isRecord$8(value)) return false;
508766
509364
  return isNonEmptyString(value["id"]) && isNonEmptyString(value["objective"]) && isNonEmptyString(value["createdAt"]) && isNonEmptyString(value["updatedAt"]);
508767
509365
  }
508768
- function isRecord$5(value) {
509366
+ function isRecord$8(value) {
508769
509367
  return typeof value === "object" && value !== null && !Array.isArray(value);
508770
509368
  }
508771
509369
  function isNonEmptyString(value) {
@@ -508778,7 +509376,7 @@ function timestampAfter(previous) {
508778
509376
  return now.toISOString();
508779
509377
  }
508780
509378
  function isErrno(error, code) {
508781
- return isRecord$5(error) && error["code"] === code;
509379
+ return isRecord$8(error) && error["code"] === code;
508782
509380
  }
508783
509381
  function describeError(error) {
508784
509382
  return error instanceof Error ? error.message : String(error);
@@ -513549,148 +514147,6 @@ function isAbortError$1(error) {
513549
514147
  return isAbortMessage(String(error));
513550
514148
  }
513551
514149
  //#endregion
513552
- //#region src/tui/utils/export-markdown.copy.ts
513553
- registerUiCatalogFragment({
513554
- en: {
513555
- "export.thinking": "Thinking",
513556
- "export.image": "image",
513557
- "export.audio": "audio",
513558
- "export.video": "video",
513559
- "export.toolCall": "Tool Call: {name}",
513560
- "export.toolResult": "Tool Result: {name}",
513561
- "export.turn": "Turn {number}",
513562
- "export.user": "User",
513563
- "export.assistant": "Assistant",
513564
- "export.system": "System",
513565
- "export.unknownTool": "unknown",
513566
- "export.overview": "Overview",
513567
- "export.topic": "Topic",
513568
- "export.labelSeparator": ":",
513569
- "export.empty": "empty",
513570
- "export.conversation": "Conversation",
513571
- "export.turnCount.one": "{count} turn",
513572
- "export.turnCount.other": "{count} turns",
513573
- "export.toolCallCount.one": "{count} tool call",
513574
- "export.toolCallCount.other": "{count} tool calls",
513575
- "export.title": "King Session Export"
513576
- },
513577
- de: {
513578
- "export.thinking": "Denken",
513579
- "export.image": "Bild",
513580
- "export.audio": "Audio",
513581
- "export.video": "Video",
513582
- "export.toolCall": "Werkzeugaufruf: {name}",
513583
- "export.toolResult": "Werkzeugergebnis: {name}",
513584
- "export.turn": "Durchlauf {number}",
513585
- "export.user": "Benutzer",
513586
- "export.assistant": "Assistent",
513587
- "export.system": "System",
513588
- "export.unknownTool": "unbekannt",
513589
- "export.overview": "Übersicht",
513590
- "export.topic": "Thema",
513591
- "export.labelSeparator": ":",
513592
- "export.empty": "leer",
513593
- "export.conversation": "Gespräch",
513594
- "export.turnCount.one": "{count} Durchlauf",
513595
- "export.turnCount.other": "{count} Durchläufe",
513596
- "export.toolCallCount.one": "{count} Werkzeugaufruf",
513597
- "export.toolCallCount.other": "{count} Werkzeugaufrufe",
513598
- "export.title": "King-Sitzungsexport"
513599
- },
513600
- es: {
513601
- "export.thinking": "Razonamiento",
513602
- "export.image": "imagen",
513603
- "export.audio": "audio",
513604
- "export.video": "vídeo",
513605
- "export.toolCall": "Llamada a herramienta: {name}",
513606
- "export.toolResult": "Resultado de la herramienta: {name}",
513607
- "export.turn": "Turno {number}",
513608
- "export.user": "Usuario",
513609
- "export.assistant": "Asistente",
513610
- "export.system": "Sistema",
513611
- "export.unknownTool": "desconocida",
513612
- "export.overview": "Resumen",
513613
- "export.topic": "Tema",
513614
- "export.labelSeparator": ":",
513615
- "export.empty": "vacío",
513616
- "export.conversation": "Conversación",
513617
- "export.turnCount.one": "{count} turno",
513618
- "export.turnCount.other": "{count} turnos",
513619
- "export.toolCallCount.one": "{count} llamada a herramienta",
513620
- "export.toolCallCount.other": "{count} llamadas a herramientas",
513621
- "export.title": "Exportación de la sesión de King"
513622
- },
513623
- fr: {
513624
- "export.thinking": "Réflexion",
513625
- "export.image": "image",
513626
- "export.audio": "audio",
513627
- "export.video": "vidéo",
513628
- "export.toolCall": "Appel d’outil\xA0: {name}",
513629
- "export.toolResult": "Résultat de l’outil\xA0: {name}",
513630
- "export.turn": "Tour {number}",
513631
- "export.user": "Utilisateur",
513632
- "export.assistant": "Assistant",
513633
- "export.system": "Système",
513634
- "export.unknownTool": "inconnu",
513635
- "export.overview": "Vue d’ensemble",
513636
- "export.topic": "Sujet",
513637
- "export.labelSeparator": "\xA0:",
513638
- "export.empty": "vide",
513639
- "export.conversation": "Conversation",
513640
- "export.turnCount.one": "{count} tour",
513641
- "export.turnCount.other": "{count} tours",
513642
- "export.toolCallCount.one": "{count} appel d’outil",
513643
- "export.toolCallCount.other": "{count} appels d’outil",
513644
- "export.title": "Export de la session King"
513645
- },
513646
- sv: {
513647
- "export.thinking": "Resonemang",
513648
- "export.image": "bild",
513649
- "export.audio": "ljud",
513650
- "export.video": "video",
513651
- "export.toolCall": "Verktygsanrop: {name}",
513652
- "export.toolResult": "Verktygsresultat: {name}",
513653
- "export.turn": "Omgång {number}",
513654
- "export.user": "Användare",
513655
- "export.assistant": "Assistent",
513656
- "export.system": "System",
513657
- "export.unknownTool": "okänt",
513658
- "export.overview": "Översikt",
513659
- "export.topic": "Ämne",
513660
- "export.labelSeparator": ":",
513661
- "export.empty": "tomt",
513662
- "export.conversation": "Konversation",
513663
- "export.turnCount.one": "{count} omgång",
513664
- "export.turnCount.other": "{count} omgångar",
513665
- "export.toolCallCount.one": "{count} verktygsanrop",
513666
- "export.toolCallCount.other": "{count} verktygsanrop",
513667
- "export.title": "Export av King-session"
513668
- },
513669
- cs: {
513670
- "export.thinking": "Uvažování",
513671
- "export.image": "obrázek",
513672
- "export.audio": "zvuk",
513673
- "export.video": "video",
513674
- "export.toolCall": "Volání nástroje: {name}",
513675
- "export.toolResult": "Výsledek nástroje: {name}",
513676
- "export.turn": "Kolo {number}",
513677
- "export.user": "Uživatel",
513678
- "export.assistant": "Asistent",
513679
- "export.system": "Systém",
513680
- "export.unknownTool": "neznámý",
513681
- "export.overview": "Přehled",
513682
- "export.topic": "Téma",
513683
- "export.labelSeparator": ":",
513684
- "export.empty": "prázdné",
513685
- "export.conversation": "Konverzace",
513686
- "export.turnCount.one": "Kola: {count}",
513687
- "export.turnCount.other": "Kola: {count}",
513688
- "export.toolCallCount.one": "{count} volání nástroje",
513689
- "export.toolCallCount.other": "{count} volání nástrojů",
513690
- "export.title": "Export relace King"
513691
- }
513692
- });
513693
- //#endregion
513694
514150
  //#region src/tui/utils/export-markdown.ts
513695
514151
  const HINT_KEYS = [
513696
514152
  "path",
@@ -520695,10 +521151,10 @@ function parseGoalValue(output) {
520695
521151
  } catch {
520696
521152
  return;
520697
521153
  }
520698
- if (!isRecord$4(parsed) || !("goal" in parsed)) return void 0;
521154
+ if (!isRecord$7(parsed) || !("goal" in parsed)) return void 0;
520699
521155
  const goal = parsed["goal"];
520700
521156
  if (goal === null) return null;
520701
- if (!isRecord$4(goal)) return void 0;
521157
+ if (!isRecord$7(goal)) return void 0;
520702
521158
  return goal;
520703
521159
  }
520704
521160
  function formatGoalStats(goal) {
@@ -520720,7 +521176,7 @@ function stringArg(args, key) {
520720
521176
  const value = args[key];
520721
521177
  return typeof value === "string" && value.length > 0 ? value : void 0;
520722
521178
  }
520723
- function isRecord$4(value) {
521179
+ function isRecord$7(value) {
520724
521180
  return typeof value === "object" && value !== null && !Array.isArray(value);
520725
521181
  }
520726
521182
  function stringField$1(record, key) {
@@ -524772,10 +525228,10 @@ var CustomerMistakeBrokerError = class extends Error {
524772
525228
  }
524773
525229
  };
524774
525230
  function parseMistakeConsent(payload) {
524775
- if (!isRecord$3(payload)) return void 0;
524776
- const settings = (isRecord$3(payload["data"]) ? payload["data"] : payload)["settings"];
524777
- const dataControls = isRecord$3(settings) ? settings["data_controls"] : void 0;
524778
- if (!isRecord$3(dataControls)) return void 0;
525231
+ if (!isRecord$6(payload)) return void 0;
525232
+ const settings = (isRecord$6(payload["data"]) ? payload["data"] : payload)["settings"];
525233
+ const dataControls = isRecord$6(settings) ? settings["data_controls"] : void 0;
525234
+ if (!isRecord$6(dataControls)) return void 0;
524779
525235
  const asked = dataControls["mistake_consent_asked"];
524780
525236
  const allowed = dataControls["allow_mistake"];
524781
525237
  if (typeof asked !== "boolean" || typeof allowed !== "boolean") return void 0;
@@ -524889,7 +525345,7 @@ function normalizeBaseUrl(value) {
524889
525345
  if (url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0 || url.search.length > 0 || url.hash.length > 0 || url.pathname !== "/" && url.pathname !== "") throw new CustomerMistakeBrokerError("INVALID_PAYLOAD");
524890
525346
  return url.origin;
524891
525347
  }
524892
- function isRecord$3(value) {
525348
+ function isRecord$6(value) {
524893
525349
  return typeof value === "object" && value !== null && !Array.isArray(value);
524894
525350
  }
524895
525351
  //#endregion
@@ -524981,6 +525437,902 @@ var CustomerMistakeHostController = class {
524981
525437
  }
524982
525438
  };
524983
525439
  //#endregion
525440
+ //#region src/personal-memory/account-memory-broker.ts
525441
+ const MAX_CAPTURE_BYTES = 1e6;
525442
+ const UUID_V4$1 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
525443
+ var AccountMemoryBroker = class {
525444
+ client;
525445
+ constructor(client) {
525446
+ this.client = client;
525447
+ }
525448
+ async workspace(sessionId) {
525449
+ if (sessionId !== void 0 && (!sessionId.trim() || sessionId.length > 200)) invalid();
525450
+ const path = sessionId === void 0 ? "/api/memory/workspace" : `/api/memory/workspace?source=tui&sessionId=${encodeURIComponent(sessionId)}`;
525451
+ const value = await this.client.request("GET", path);
525452
+ if (!isRecord$5(value) || typeof value["workspaceId"] !== "string" || !/^blun-[0-9a-f]{64}$/iu.test(value["workspaceId"]) || !generation(value["forgetGeneration"]) || sessionId !== void 0 && !generation(value["sessionEpoch"]) || value["forgetCutoff"] !== null && !isoTime$1(value["forgetCutoff"])) invalid();
525453
+ return {
525454
+ workspaceId: value["workspaceId"],
525455
+ forgetGeneration: value["forgetGeneration"],
525456
+ forgetCutoff: value["forgetCutoff"],
525457
+ sessionEpoch: sessionId === void 0 ? null : value["sessionEpoch"]
525458
+ };
525459
+ }
525460
+ async capture(input) {
525461
+ if (!UUID_V4$1.test(input.captureId) || !input.sessionId.trim() || !generation(input.forgetGeneration) || input.sessionEpoch !== null && !generation(input.sessionEpoch) || input.messages.length === 0 || input.messages.length > 200 || input.messages.some((message) => !messageId$1(message.id) || !["user", "assistant"].includes(message.role) || !message.content.trim() || !isoTime$1(message.at))) invalid();
525462
+ if (new Set(input.messages.map((message) => message.id)).size !== input.messages.length) invalid();
525463
+ const body = {
525464
+ captureId: input.captureId,
525465
+ source: "tui",
525466
+ sessionId: input.sessionId,
525467
+ forgetGeneration: input.forgetGeneration,
525468
+ sessionEpoch: input.sessionEpoch,
525469
+ messages: input.messages.map((message) => ({
525470
+ id: message.id,
525471
+ role: message.role,
525472
+ content: message.content,
525473
+ at: message.at
525474
+ }))
525475
+ };
525476
+ if (Buffer.byteLength(JSON.stringify(body), "utf8") > MAX_CAPTURE_BYTES) invalid();
525477
+ const value = await this.client.request("POST", "/api/memory/capture", body);
525478
+ if (isRecord$5(value) && value["accepted"] === 0 && value["reason"] === "memory_disabled") return {
525479
+ accepted: 0,
525480
+ reason: "memory_disabled"
525481
+ };
525482
+ if (isRecord$5(value) && value["accepted"] === 0 && value["reason"] === "session_retracted" && generation(value["skipped"]) && generation(value["sessionEpoch"])) return {
525483
+ accepted: 0,
525484
+ skipped: value["skipped"],
525485
+ reason: "session_retracted",
525486
+ sessionEpoch: value["sessionEpoch"]
525487
+ };
525488
+ if (!isRecord$5(value) || !generation(value["accepted"]) || !generation(value["skipped"]) || typeof value["duplicate"] !== "boolean" || !generation(value["forgetGeneration"]) || !generation(value["sessionEpoch"])) invalid();
525489
+ return {
525490
+ accepted: value["accepted"],
525491
+ skipped: value["skipped"],
525492
+ duplicate: value["duplicate"],
525493
+ forgetGeneration: value["forgetGeneration"],
525494
+ sessionEpoch: value["sessionEpoch"]
525495
+ };
525496
+ }
525497
+ async retract(input) {
525498
+ if (!UUID_V4$1.test(input.retractId) || !input.sessionId.trim() || input.sessionId.length > 200 || "wholeSession" in input && input.expectedEpoch !== null && !generation(input.expectedEpoch)) invalid();
525499
+ const body = "wholeSession" in input ? {
525500
+ retractId: input.retractId,
525501
+ source: "tui",
525502
+ sessionId: input.sessionId,
525503
+ wholeSession: true,
525504
+ expectedEpoch: input.expectedEpoch
525505
+ } : {
525506
+ retractId: input.retractId,
525507
+ source: "tui",
525508
+ sessionId: input.sessionId,
525509
+ messageIds: input.messageIds
525510
+ };
525511
+ if (!("wholeSession" in input) && (input.messageIds.length === 0 || input.messageIds.length > 200 || input.messageIds.some((id) => !messageId$1(id)) || new Set(input.messageIds).size !== input.messageIds.length)) invalid();
525512
+ const value = await this.client.request("POST", "/api/memory/retract", body);
525513
+ if ("wholeSession" in input && isRecord$5(value) && value["retracted"] === 0 && value["rederive"] === false && value["reason"] === "already_retracted" && generation(value["sessionEpoch"]) && input.expectedEpoch !== null && value["sessionEpoch"] >= input.expectedEpoch) return {
525514
+ retracted: 0,
525515
+ rederive: false,
525516
+ reason: "already_retracted",
525517
+ sessionEpoch: value["sessionEpoch"]
525518
+ };
525519
+ if (!isRecord$5(value) || !generation(value["retracted"]) || value["rederive"] !== "queued" || "wholeSession" in input && !generation(value["sessionEpoch"]) || value["sessionEpoch"] !== void 0 && !generation(value["sessionEpoch"])) invalid();
525520
+ return {
525521
+ retracted: value["retracted"],
525522
+ rederive: "queued",
525523
+ ...value["sessionEpoch"] === void 0 ? {} : { sessionEpoch: value["sessionEpoch"] }
525524
+ };
525525
+ }
525526
+ async recall(query, limit = 8, sources) {
525527
+ const body = queryBody(query, limit, sources);
525528
+ const value = await this.client.request("POST", "/api/memory/recall", body);
525529
+ if (!isRecord$5(value) || !isRecord$5(value["profile"]) || !Array.isArray(value["items"]) || !generation(value["forgetGeneration"])) invalid();
525530
+ const profile = value["profile"];
525531
+ if (!Array.isArray(profile["card"]) || profile["card"].length > 20 || !profile["card"].every((item) => typeof item === "string" && item.length <= 1e3) || typeof profile["representation"] !== "string" || profile["representation"].length > 4e3) invalid();
525532
+ return {
525533
+ profile: {
525534
+ card: profile["card"],
525535
+ representation: profile["representation"]
525536
+ },
525537
+ items: parseItems(value["items"]),
525538
+ forgetGeneration: value["forgetGeneration"]
525539
+ };
525540
+ }
525541
+ async search(query, options = {}) {
525542
+ const body = queryBody(query, options.limit ?? 20, options.sources);
525543
+ if (options.after !== void 0 && !isoTime$1(options.after) || options.before !== void 0 && !isoTime$1(options.before)) invalid();
525544
+ const value = await this.client.request("POST", "/api/memory/search", {
525545
+ ...body,
525546
+ ...options.after === void 0 ? {} : { after: options.after },
525547
+ ...options.before === void 0 ? {} : { before: options.before }
525548
+ });
525549
+ if (!isRecord$5(value) || !Array.isArray(value["items"]) || !generation(value["forgetGeneration"])) invalid();
525550
+ return {
525551
+ items: parseItems(value["items"]),
525552
+ forgetGeneration: value["forgetGeneration"]
525553
+ };
525554
+ }
525555
+ };
525556
+ function queryBody(query, limit, sources) {
525557
+ if (!query.trim() || query.length > 1e3 || !Number.isInteger(limit) || limit < 1 || limit > 20 || sources !== void 0 && (!Array.isArray(sources) || sources.some((source) => !/^(?:chat|tui|plugin:[a-z0-9_-]+)$/iu.test(source)))) invalid();
525558
+ return {
525559
+ query,
525560
+ limit,
525561
+ ...sources === void 0 ? {} : { sources }
525562
+ };
525563
+ }
525564
+ function parseItems(value) {
525565
+ if (value.length > 20) invalid();
525566
+ return value.map((item) => {
525567
+ if (!isRecord$5(item) || typeof item["id"] !== "string" || item["id"].length > 200 || typeof item["text"] !== "string" || item["text"].length > 2e3 || typeof item["source"] !== "string" || !/^(?:chat|tui|plugin:[a-z0-9_-]+)$/iu.test(item["source"]) || typeof item["sessionId"] !== "string" || item["sessionId"].length > 200 || !isoTime$1(item["at"]) || typeof item["score"] !== "number" || !Number.isFinite(item["score"]) || item["role"] !== void 0 && item["role"] !== "user" && item["role"] !== "assistant") invalid();
525568
+ return item;
525569
+ });
525570
+ }
525571
+ function generation(value) {
525572
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
525573
+ }
525574
+ function messageId$1(value) {
525575
+ return typeof value === "string" && value.length > 0 && value.length <= 200 && /^[a-z0-9][a-z0-9._:-]*$/iu.test(value);
525576
+ }
525577
+ function isoTime$1(value) {
525578
+ return typeof value === "string" && Number.isFinite(Date.parse(value)) && /(?:Z|[+-]\d\d:\d\d)$/u.test(value);
525579
+ }
525580
+ function isRecord$5(value) {
525581
+ return typeof value === "object" && value !== null && !Array.isArray(value);
525582
+ }
525583
+ function invalid() {
525584
+ throw new PersonalMemoryBrokerError("INVALID_PAYLOAD");
525585
+ }
525586
+ //#endregion
525587
+ //#region src/personal-memory/honcho-capture-source.ts
525588
+ const SECRET_PATTERN = /\b(?:password|passwort|api[-_ ]?key|secret|bearer|credential|cvv|cvc|iban)\b|sk-[a-z0-9_-]{20,}|ghp_[a-z0-9]{20,}|\b(?:\d[ -]?){13,19}\b/iu;
525589
+ const GROUP_MARKER = /^\[tg\s+(?:group|supergroup)\b/im;
525590
+ const MAX_WIRE_RECORD_CHARS = 4 * 1024 * 1024;
525591
+ async function readCompletedHonchoTurn(homeDir, session, turnId) {
525592
+ const sessionsRoot = await realpath(path.join(homeDir, "sessions"));
525593
+ const sessionDir = await realpath(session.sessionDir);
525594
+ if (path.basename(sessionDir) !== session.id || !isInside(sessionsRoot, sessionDir)) throw new Error("Honcho session path is outside this profile.");
525595
+ const canonicalWire = await realpath(path.join(sessionDir, "agents", "main", "wire.jsonl"));
525596
+ if (!isInside(sessionDir, canonicalWire)) throw new Error("Honcho Wire path escapes the session.");
525597
+ const wireStat = await stat(canonicalWire);
525598
+ if (!wireStat.isFile() || wireStat.size === 0) return void 0;
525599
+ const scanner = createTurnScanner(turnId);
525600
+ for await (const line of boundedLines(canonicalWire, wireStat.size)) scanner.accept(JSON.parse(line));
525601
+ return scanner.finish();
525602
+ }
525603
+ function createTurnScanner(completedTurnId) {
525604
+ let latestUserText;
525605
+ let latestUserTime;
525606
+ let userText;
525607
+ let occurredAt;
525608
+ let assistantText = "";
525609
+ let finalStepEnded = false;
525610
+ const targetTurnId = String(completedTurnId);
525611
+ const accept = (raw) => {
525612
+ if (!isRecord$4(raw)) return;
525613
+ if (raw["type"] === "turn.prompt") {
525614
+ const origin = raw["origin"];
525615
+ const input = raw["input"];
525616
+ const text = isRecord$4(origin) && origin["kind"] === "user" && Array.isArray(input) && input.every((part) => isRecord$4(part) && part["type"] === "text") ? textParts(input) : void 0;
525617
+ latestUserText = text && !GROUP_MARKER.test(text) && !SECRET_PATTERN.test(text) ? text : void 0;
525618
+ latestUserTime = latestUserText === void 0 ? void 0 : isoTime(raw["time"]);
525619
+ return;
525620
+ }
525621
+ if (raw["type"] !== "context.append_loop_event" || !isRecord$4(raw["event"])) return;
525622
+ const event = raw["event"];
525623
+ if (event["type"] === "step.begin" && event["turnId"] === targetTurnId) {
525624
+ userText ??= latestUserText;
525625
+ occurredAt ??= latestUserTime;
525626
+ assistantText = "";
525627
+ finalStepEnded = false;
525628
+ return;
525629
+ }
525630
+ if (event["type"] === "content.part" && event["turnId"] === targetTurnId && userText !== void 0 && isRecord$4(event["part"]) && event["part"]["type"] === "text" && typeof event["part"]["text"] === "string") {
525631
+ assistantText += event["part"]["text"];
525632
+ return;
525633
+ }
525634
+ if (event["type"] === "step.end" && event["turnId"] === targetTurnId) finalStepEnded = event["finishReason"] === "end_turn";
525635
+ };
525636
+ return {
525637
+ accept,
525638
+ finish: () => {
525639
+ const answer = assistantText.trim();
525640
+ return finalStepEnded && userText !== void 0 && occurredAt !== void 0 && answer.length > 0 && !SECRET_PATTERN.test(answer) ? {
525641
+ userText,
525642
+ assistantText: answer,
525643
+ occurredAt
525644
+ } : void 0;
525645
+ }
525646
+ };
525647
+ }
525648
+ function isoTime(value) {
525649
+ if (typeof value !== "string") return void 0;
525650
+ const timestamp = Date.parse(value);
525651
+ return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value ? value : void 0;
525652
+ }
525653
+ function textParts(parts) {
525654
+ return parts.filter((part) => isRecord$4(part) && part["type"] === "text" && typeof part["text"] === "string").map((part) => part.text).join("\n").trim() || void 0;
525655
+ }
525656
+ function isRecord$4(value) {
525657
+ return typeof value === "object" && value !== null && !Array.isArray(value);
525658
+ }
525659
+ function isInside(root, candidate) {
525660
+ const relative = path.relative(root, candidate);
525661
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
525662
+ }
525663
+ async function* boundedLines(wirePath, size) {
525664
+ const stream = createReadStream(wirePath, {
525665
+ encoding: "utf8",
525666
+ end: size - 1
525667
+ });
525668
+ let pending = "";
525669
+ try {
525670
+ for await (const chunk of stream) {
525671
+ let offset = 0;
525672
+ while (offset < chunk.length) {
525673
+ const newline = chunk.indexOf("\n", offset);
525674
+ const end = newline < 0 ? chunk.length : newline;
525675
+ pending += chunk.slice(offset, end);
525676
+ if (pending.length > MAX_WIRE_RECORD_CHARS) throw new Error("Honcho Wire record is too large.");
525677
+ if (newline < 0) break;
525678
+ if (pending.length > 0) yield pending.replace(/\r$/u, "");
525679
+ pending = "";
525680
+ offset = newline + 1;
525681
+ }
525682
+ }
525683
+ } finally {
525684
+ stream.destroy();
525685
+ }
525686
+ }
525687
+ //#endregion
525688
+ //#region src/personal-memory/account-memory-capture.ts
525689
+ const MAX_PENDING = 2e3;
525690
+ const MAX_COMPLETED = 1e4;
525691
+ const MAX_RETRACTIONS = 2e3;
525692
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
525693
+ var AccountMemoryCaptureQueue = class {
525694
+ homeDir;
525695
+ broker;
525696
+ readTurn;
525697
+ workspaceCache;
525698
+ work = Promise.resolve();
525699
+ constructor(homeDir, broker, readTurn = readCompletedHonchoTurn, workspaceCache) {
525700
+ this.homeDir = homeDir;
525701
+ this.broker = broker;
525702
+ this.readTurn = readTurn;
525703
+ this.workspaceCache = workspaceCache;
525704
+ }
525705
+ captureCompletedTurn(session, turnId) {
525706
+ return this.serial(async () => {
525707
+ if (!Number.isSafeInteger(turnId) || turnId < 0) return "unavailable";
525708
+ let state;
525709
+ try {
525710
+ state = await this.readSessionState(session.id);
525711
+ if (turnId <= state.blockedThroughTurnId) return "skipped";
525712
+ if (turnId > state.highestObservedTurnId) {
525713
+ state = {
525714
+ ...state,
525715
+ highestObservedTurnId: turnId
525716
+ };
525717
+ await this.writeSessionState(state);
525718
+ }
525719
+ } catch {
525720
+ return "unavailable";
525721
+ }
525722
+ let workspace;
525723
+ let turn;
525724
+ try {
525725
+ workspace = await this.broker.workspace(session.id);
525726
+ turn = await this.readTurn(this.homeDir, session, turnId);
525727
+ } catch {
525728
+ return "unavailable";
525729
+ }
525730
+ if (state.workspaceId !== null && state.workspaceId !== workspace.workspaceId) return "unavailable";
525731
+ if (state.workspaceId === null || state.sessionEpoch !== workspace.sessionEpoch) try {
525732
+ await this.writeSessionState({
525733
+ ...state,
525734
+ workspaceId: workspace.workspaceId,
525735
+ sessionEpoch: workspace.sessionEpoch
525736
+ });
525737
+ } catch {
525738
+ return "unavailable";
525739
+ }
525740
+ if (this.workspaceCache !== void 0) try {
525741
+ if (!await this.workspaceCache.set(workspace.workspaceId)) return "unavailable";
525742
+ } catch {
525743
+ return "unavailable";
525744
+ }
525745
+ if (turn === void 0 || beforeCutoff(turn.occurredAt, workspace.forgetCutoff)) return "skipped";
525746
+ const journalPath = this.journalPath(workspace.workspaceId);
525747
+ let journal;
525748
+ try {
525749
+ journal = await this.readJournal(journalPath, workspace.workspaceId);
525750
+ } catch {
525751
+ return "unavailable";
525752
+ }
525753
+ if (journal.suppressedTurns.includes(turnKey(session.id, turnId))) return "skipped";
525754
+ if (journal.known.some((entry) => entry.sessionId === session.id && entry.turnId === turnId)) return "skipped";
525755
+ const revision = journal.revisions[turnKey(session.id, turnId)] ?? 0;
525756
+ const messageIds = turnMessageIds(session.id, turnId, turn, revision);
525757
+ const key = captureKey(session.id, turnId, turn.occurredAt, messageIds);
525758
+ if (journal.completed.includes(key)) return "skipped";
525759
+ const old = journal.pending.find((entry) => entry.sessionId === session.id && entry.turnId === turnId);
525760
+ if (old !== void 0 && (old.occurredAt !== turn.occurredAt || old.messageIds.some((id, index) => id !== messageIds[index]))) return "skipped";
525761
+ if (old === void 0) {
525762
+ if (journal.pending.length >= MAX_PENDING) return "unavailable";
525763
+ journal = {
525764
+ ...journal,
525765
+ pending: [...journal.pending, {
525766
+ captureId: randomUUID(),
525767
+ sessionId: session.id,
525768
+ sessionDir: session.sessionDir,
525769
+ turnId,
525770
+ occurredAt: turn.occurredAt,
525771
+ messageIds,
525772
+ sessionEpoch: workspace.sessionEpoch,
525773
+ awaitingSessionRetract: journal.retractions.some((entry) => entry.sessionId === session.id && "wholeSession" in entry)
525774
+ }]
525775
+ };
525776
+ try {
525777
+ await this.writeJournal(journalPath, journal);
525778
+ } catch {
525779
+ return "unavailable";
525780
+ }
525781
+ }
525782
+ if (!await this.flushRetractions(journalPath, journal)) return "queued";
525783
+ journal = await this.readJournal(journalPath, workspace.workspaceId);
525784
+ return this.flushJournal(journalPath, journal, workspace, {
525785
+ sessionId: session.id,
525786
+ turnId,
525787
+ turn
525788
+ });
525789
+ });
525790
+ }
525791
+ retryPending() {
525792
+ return this.serial(async () => {
525793
+ try {
525794
+ const workspace = await this.broker.workspace();
525795
+ const journalPath = this.journalPath(workspace.workspaceId);
525796
+ let journal = await this.readJournal(journalPath, workspace.workspaceId);
525797
+ if (!await this.flushRetractions(journalPath, journal)) return "queued";
525798
+ journal = await this.readJournal(journalPath, workspace.workspaceId);
525799
+ return await this.flushJournal(journalPath, journal, workspace);
525800
+ } catch {
525801
+ return "unavailable";
525802
+ }
525803
+ });
525804
+ }
525805
+ retryRetractions() {
525806
+ return this.serial(async () => {
525807
+ try {
525808
+ const workspace = await this.broker.workspace();
525809
+ const journalPath = this.journalPath(workspace.workspaceId);
525810
+ const journal = await this.readJournal(journalPath, workspace.workspaceId);
525811
+ if (journal.retractions.length === 0) return "skipped";
525812
+ return await this.flushRetractions(journalPath, journal) ? "retracted" : "queued";
525813
+ } catch {
525814
+ return "unavailable";
525815
+ }
525816
+ });
525817
+ }
525818
+ flushRetractionsBeforeLogout() {
525819
+ return this.serial(async () => {
525820
+ try {
525821
+ const cachedWorkspaceId = await this.workspaceCache?.get();
525822
+ if (cachedWorkspaceId === void 0) return false;
525823
+ const journalPath = this.journalPath(cachedWorkspaceId);
525824
+ const journal = await this.readJournal(journalPath, cachedWorkspaceId);
525825
+ if (journal.retractions.length === 0) return false;
525826
+ if ((await this.broker.workspace()).workspaceId !== cachedWorkspaceId) return true;
525827
+ return !await this.flushRetractions(journalPath, journal);
525828
+ } catch {
525829
+ return true;
525830
+ }
525831
+ });
525832
+ }
525833
+ retractTurn(sessionId, turnId) {
525834
+ return this.serial(async () => {
525835
+ try {
525836
+ const workspace = await this.broker.workspace();
525837
+ const journalPath = this.journalPath(workspace.workspaceId);
525838
+ const journal = await this.readJournal(journalPath, workspace.workspaceId);
525839
+ const matching = [...journal.pending, ...journal.known].filter((entry) => entry.sessionId === sessionId && entry.turnId === turnId);
525840
+ const messageIds = [...new Set(matching.flatMap((entry) => entry.messageIds))];
525841
+ if (messageIds.length === 0) return "skipped";
525842
+ if (journal.retractions.length >= MAX_RETRACTIONS) return "unavailable";
525843
+ const next = {
525844
+ ...journal,
525845
+ pending: journal.pending.filter((entry) => entry.sessionId !== sessionId || entry.turnId !== turnId),
525846
+ known: journal.known.filter((entry) => entry.sessionId !== sessionId || entry.turnId !== turnId),
525847
+ retractions: [...journal.retractions, {
525848
+ retractId: randomUUID(),
525849
+ sessionId,
525850
+ messageIds
525851
+ }],
525852
+ revisions: {
525853
+ ...journal.revisions,
525854
+ [turnKey(sessionId, turnId)]: (journal.revisions[turnKey(sessionId, turnId)] ?? 0) + 1
525855
+ }
525856
+ };
525857
+ await this.writeJournal(journalPath, next);
525858
+ return await this.flushRetractions(journalPath, next) ? "retracted" : "queued";
525859
+ } catch {
525860
+ return "unavailable";
525861
+ }
525862
+ });
525863
+ }
525864
+ retractSession(sessionId, throughTurnId) {
525865
+ return this.serial(async () => {
525866
+ if (throughTurnId !== void 0 && (!Number.isSafeInteger(throughTurnId) || throughTurnId < 0)) return "unavailable";
525867
+ let state;
525868
+ try {
525869
+ state = await this.readSessionState(sessionId);
525870
+ } catch {
525871
+ return "unavailable";
525872
+ }
525873
+ let workspace;
525874
+ try {
525875
+ workspace = await this.broker.workspace(sessionId);
525876
+ } catch {
525877
+ if (state.workspaceId !== null) {
525878
+ let cachedWorkspaceId;
525879
+ try {
525880
+ cachedWorkspaceId = await this.workspaceCache?.get();
525881
+ } catch {
525882
+ return "unavailable";
525883
+ }
525884
+ if (cachedWorkspaceId !== state.workspaceId) {
525885
+ try {
525886
+ await this.writeSessionState({
525887
+ ...state,
525888
+ highestObservedTurnId: Math.max(state.highestObservedTurnId, throughTurnId ?? -1),
525889
+ blockedThroughTurnId: Math.max(state.blockedThroughTurnId, state.highestObservedTurnId, throughTurnId ?? -1)
525890
+ });
525891
+ } catch {
525892
+ return "unavailable";
525893
+ }
525894
+ return "unavailable";
525895
+ }
525896
+ return this.queueSessionRetraction(sessionId, state, cachedWorkspaceId, state.sessionEpoch, throughTurnId, false);
525897
+ }
525898
+ try {
525899
+ await this.writeSessionState({
525900
+ ...state,
525901
+ highestObservedTurnId: Math.max(state.highestObservedTurnId, throughTurnId ?? -1),
525902
+ blockedThroughTurnId: Math.max(state.blockedThroughTurnId, state.highestObservedTurnId, throughTurnId ?? -1)
525903
+ });
525904
+ return "retracted";
525905
+ } catch {
525906
+ return "unavailable";
525907
+ }
525908
+ }
525909
+ if (workspace.sessionEpoch === null) return "unavailable";
525910
+ if (state.workspaceId !== null && state.workspaceId !== workspace.workspaceId) return "unavailable";
525911
+ if (this.workspaceCache !== void 0) try {
525912
+ if (!await this.workspaceCache.set(workspace.workspaceId)) return "unavailable";
525913
+ } catch {
525914
+ return "unavailable";
525915
+ }
525916
+ return this.queueSessionRetraction(sessionId, state, workspace.workspaceId, workspace.sessionEpoch, throughTurnId, true);
525917
+ });
525918
+ }
525919
+ async queueSessionRetraction(sessionId, state, workspaceId, expectedEpoch, throughTurnId, sendNow) {
525920
+ try {
525921
+ const journalPath = this.journalPath(workspaceId);
525922
+ const journal = await this.readJournal(journalPath, workspaceId);
525923
+ if (journal.retractions.length >= MAX_RETRACTIONS) return "unavailable";
525924
+ const next = {
525925
+ ...journal,
525926
+ pending: journal.pending.filter((entry) => entry.sessionId !== sessionId),
525927
+ known: journal.known.filter((entry) => entry.sessionId !== sessionId),
525928
+ retractions: [...journal.retractions, {
525929
+ retractId: randomUUID(),
525930
+ sessionId,
525931
+ wholeSession: true,
525932
+ expectedEpoch
525933
+ }],
525934
+ suppressedTurns: [...new Set([...journal.suppressedTurns, ...[...journal.pending, ...journal.known].filter((entry) => entry.sessionId === sessionId).map((entry) => turnKey(entry.sessionId, entry.turnId))])].slice(-MAX_COMPLETED)
525935
+ };
525936
+ await this.writeJournal(journalPath, next);
525937
+ await this.writeSessionState({
525938
+ ...state,
525939
+ highestObservedTurnId: Math.max(state.highestObservedTurnId, throughTurnId ?? -1),
525940
+ blockedThroughTurnId: Math.max(state.blockedThroughTurnId, state.highestObservedTurnId, throughTurnId ?? -1),
525941
+ workspaceId,
525942
+ sessionEpoch: expectedEpoch
525943
+ });
525944
+ return sendNow && await this.flushRetractions(journalPath, next) ? "retracted" : "queued";
525945
+ } catch {
525946
+ return "unavailable";
525947
+ }
525948
+ }
525949
+ async flushRetractions(journalPath, journal) {
525950
+ if (this.broker.retract === void 0) return journal.retractions.length === 0;
525951
+ let current = journal;
525952
+ for (const entry of journal.retractions) {
525953
+ let response;
525954
+ try {
525955
+ response = await this.broker.retract(entry);
525956
+ } catch {
525957
+ return false;
525958
+ }
525959
+ if ("wholeSession" in entry && response.sessionEpoch !== void 0) try {
525960
+ const state = await this.readSessionState(entry.sessionId);
525961
+ await this.writeSessionState({
525962
+ ...state,
525963
+ sessionEpoch: response.sessionEpoch
525964
+ });
525965
+ } catch {
525966
+ return false;
525967
+ }
525968
+ current = {
525969
+ ...current,
525970
+ retractions: current.retractions.filter((item) => item !== entry),
525971
+ pending: "wholeSession" in entry && response.sessionEpoch !== void 0 ? response.rederive === false ? current.pending.filter((item) => item.sessionId !== entry.sessionId || !item.awaitingSessionRetract) : current.pending.map((item) => item.sessionId === entry.sessionId && item.awaitingSessionRetract ? {
525972
+ ...item,
525973
+ sessionEpoch: response.sessionEpoch,
525974
+ awaitingSessionRetract: false
525975
+ } : item) : current.pending
525976
+ };
525977
+ await this.writeJournal(journalPath, current);
525978
+ }
525979
+ return true;
525980
+ }
525981
+ discardPending() {
525982
+ return this.serial(async () => {
525983
+ const directory = path.join(this.homeDir, "memory");
525984
+ let names;
525985
+ try {
525986
+ names = await readdir(directory);
525987
+ } catch (error) {
525988
+ if (isMissing(error)) return;
525989
+ throw error;
525990
+ }
525991
+ for (const name of names) {
525992
+ if (!/^honcho-pending-[0-9a-f]{64}\.json$/u.test(name)) continue;
525993
+ const journalPath = path.join(directory, name);
525994
+ if (!(await lstat(journalPath)).isFile()) continue;
525995
+ const value = JSON.parse(await readFile(journalPath, "utf8"));
525996
+ if (!isRecord$3(value) || typeof value["workspaceId"] !== "string") continue;
525997
+ const journal = await this.readJournal(journalPath, value["workspaceId"]);
525998
+ if (journal.pending.length > 0) await this.writeJournal(journalPath, {
525999
+ ...journal,
526000
+ pending: []
526001
+ });
526002
+ }
526003
+ });
526004
+ }
526005
+ async flushJournal(journalPath, journal, workspace, fresh) {
526006
+ if (journal.pending.length === 0) return "skipped";
526007
+ let pending = [...journal.pending];
526008
+ let completed = [...journal.completed];
526009
+ let known = [...journal.known];
526010
+ let result = "skipped";
526011
+ for (const entry of journal.pending) {
526012
+ if (entry.awaitingSessionRetract) return "queued";
526013
+ const session = {
526014
+ id: entry.sessionId,
526015
+ sessionDir: entry.sessionDir
526016
+ };
526017
+ let turn;
526018
+ try {
526019
+ turn = fresh?.sessionId === entry.sessionId && fresh.turnId === entry.turnId ? fresh.turn : await this.readTurn(this.homeDir, session, entry.turnId);
526020
+ } catch {
526021
+ return "queued";
526022
+ }
526023
+ if (turn === void 0 || turn.occurredAt !== entry.occurredAt || beforeCutoff(entry.occurredAt, workspace.forgetCutoff)) {
526024
+ pending = pending.filter((item) => item.captureId !== entry.captureId);
526025
+ await this.writeJournal(journalPath, {
526026
+ ...journal,
526027
+ pending,
526028
+ completed,
526029
+ known
526030
+ });
526031
+ continue;
526032
+ }
526033
+ const revision = journal.revisions[turnKey(entry.sessionId, entry.turnId)] ?? 0;
526034
+ if (turnMessageIds(entry.sessionId, entry.turnId, turn, revision).some((id, index) => id !== entry.messageIds[index])) {
526035
+ pending = pending.filter((item) => item.captureId !== entry.captureId);
526036
+ await this.writeJournal(journalPath, {
526037
+ ...journal,
526038
+ pending,
526039
+ completed,
526040
+ known
526041
+ });
526042
+ continue;
526043
+ }
526044
+ try {
526045
+ const response = await this.broker.capture({
526046
+ captureId: entry.captureId,
526047
+ sessionId: entry.sessionId,
526048
+ forgetGeneration: workspace.forgetGeneration,
526049
+ sessionEpoch: entry.sessionEpoch,
526050
+ messages: [{
526051
+ id: entry.messageIds[0],
526052
+ role: "user",
526053
+ content: turn.userText,
526054
+ at: turn.occurredAt
526055
+ }, {
526056
+ id: entry.messageIds[1],
526057
+ role: "assistant",
526058
+ content: turn.assistantText,
526059
+ at: turn.occurredAt
526060
+ }]
526061
+ });
526062
+ const key = captureKey(entry.sessionId, entry.turnId, entry.occurredAt, entry.messageIds);
526063
+ if ("reason" in response && response.reason === "memory_disabled") {
526064
+ completed = [...completed, key].slice(-MAX_COMPLETED);
526065
+ await this.writeJournal(journalPath, {
526066
+ ...journal,
526067
+ pending: [],
526068
+ completed
526069
+ });
526070
+ return "skipped";
526071
+ }
526072
+ if ("reason" in response && response.reason === "session_retracted") {
526073
+ pending = pending.filter((item) => item.sessionId !== entry.sessionId || item.sessionEpoch !== entry.sessionEpoch);
526074
+ await this.writeJournal(journalPath, {
526075
+ ...journal,
526076
+ pending,
526077
+ completed,
526078
+ known
526079
+ });
526080
+ return "skipped";
526081
+ }
526082
+ pending = pending.filter((item) => item.captureId !== entry.captureId);
526083
+ completed = [...completed, key].slice(-MAX_COMPLETED);
526084
+ known = [...known, {
526085
+ key,
526086
+ sessionId: entry.sessionId,
526087
+ turnId: entry.turnId,
526088
+ occurredAt: entry.occurredAt,
526089
+ messageIds: entry.messageIds
526090
+ }].slice(-MAX_COMPLETED);
526091
+ await this.writeJournal(journalPath, {
526092
+ ...journal,
526093
+ pending,
526094
+ completed,
526095
+ known
526096
+ });
526097
+ result = "captured";
526098
+ } catch (error) {
526099
+ if (error instanceof PersonalMemoryBrokerError && error.status === 403) {
526100
+ const suppressedTurns = [...new Set([...journal.suppressedTurns, ...pending.map((item) => turnKey(item.sessionId, item.turnId))])].slice(-MAX_COMPLETED);
526101
+ try {
526102
+ await this.writeJournal(journalPath, {
526103
+ ...journal,
526104
+ pending: [],
526105
+ completed,
526106
+ known,
526107
+ suppressedTurns
526108
+ });
526109
+ } catch {
526110
+ return "unavailable";
526111
+ }
526112
+ return "skipped";
526113
+ }
526114
+ if (error instanceof PersonalMemoryBrokerError && (error.code === "INVALID_PAYLOAD" || error.code === "PAYLOAD_TOO_LARGE" || error.code === "SECRET_REJECTED")) {
526115
+ pending = pending.filter((item) => item.captureId !== entry.captureId);
526116
+ await this.writeJournal(journalPath, {
526117
+ ...journal,
526118
+ pending,
526119
+ completed,
526120
+ known
526121
+ });
526122
+ continue;
526123
+ }
526124
+ if (error instanceof PersonalMemoryBrokerError && error.code === "FORGET_GENERATION_CHANGED") return "queued";
526125
+ return "queued";
526126
+ }
526127
+ }
526128
+ return result;
526129
+ }
526130
+ journalPath(workspaceId) {
526131
+ const name = createHash("sha256").update(workspaceId).digest("hex");
526132
+ return path.join(this.homeDir, "memory", `honcho-pending-${name}.json`);
526133
+ }
526134
+ sessionStatePath(sessionId) {
526135
+ const name = createHash("sha256").update(sessionId).digest("hex");
526136
+ return path.join(this.homeDir, "memory", `honcho-session-${name}.json`);
526137
+ }
526138
+ async readSessionState(sessionId) {
526139
+ let value;
526140
+ try {
526141
+ value = JSON.parse(await readFile(this.sessionStatePath(sessionId), "utf8"));
526142
+ } catch (error) {
526143
+ if (isMissing(error)) return {
526144
+ version: 1,
526145
+ sessionId,
526146
+ highestObservedTurnId: -1,
526147
+ blockedThroughTurnId: -1,
526148
+ workspaceId: null,
526149
+ sessionEpoch: null
526150
+ };
526151
+ throw error;
526152
+ }
526153
+ if (!isRecord$3(value) || value["version"] !== 1 || value["sessionId"] !== sessionId || !Number.isSafeInteger(value["highestObservedTurnId"]) || value["highestObservedTurnId"] < -1 || !Number.isSafeInteger(value["blockedThroughTurnId"]) || value["blockedThroughTurnId"] < -1 || value["blockedThroughTurnId"] > value["highestObservedTurnId"] || value["workspaceId"] !== null && (typeof value["workspaceId"] !== "string" || value["workspaceId"].length === 0) || value["sessionEpoch"] !== null && (!Number.isSafeInteger(value["sessionEpoch"]) || value["sessionEpoch"] < 0)) throw new Error("Invalid account memory session state.");
526154
+ return value;
526155
+ }
526156
+ async writeSessionState(state) {
526157
+ const statePath = this.sessionStatePath(state.sessionId);
526158
+ const directory = path.dirname(statePath);
526159
+ await mkdir(directory, {
526160
+ recursive: true,
526161
+ mode: 448
526162
+ });
526163
+ const root = await realpath(this.homeDir);
526164
+ if (path.dirname(await realpath(directory)) !== root) throw new Error("Account memory session state escapes the BLUN profile.");
526165
+ const temporary = `${statePath}.${randomUUID()}.tmp`;
526166
+ try {
526167
+ await writeFile(temporary, JSON.stringify(state), {
526168
+ encoding: "utf8",
526169
+ mode: 384,
526170
+ flag: "wx"
526171
+ });
526172
+ await rename(temporary, statePath);
526173
+ } finally {
526174
+ await unlink(temporary).catch(() => {});
526175
+ }
526176
+ }
526177
+ async readJournal(journalPath, workspaceId) {
526178
+ let text;
526179
+ try {
526180
+ text = await readFile(journalPath, "utf8");
526181
+ } catch (error) {
526182
+ if (isMissing(error)) return {
526183
+ version: 2,
526184
+ workspaceId,
526185
+ pending: [],
526186
+ completed: [],
526187
+ known: [],
526188
+ retractions: [],
526189
+ suppressedTurns: [],
526190
+ revisions: {}
526191
+ };
526192
+ throw error;
526193
+ }
526194
+ const value = JSON.parse(text);
526195
+ if (!isRecord$3(value) || value["version"] !== 2 || value["workspaceId"] !== workspaceId || !Array.isArray(value["pending"]) || value["pending"].length > MAX_PENDING || !value["pending"].every(validPending) || !Array.isArray(value["completed"]) || value["completed"].length > MAX_COMPLETED || !value["completed"].every((item) => typeof item === "string" && /^[0-9a-f]{64}$/u.test(item)) || !Array.isArray(value["known"]) || value["known"].length > MAX_COMPLETED || !value["known"].every(validKnown) || !Array.isArray(value["retractions"]) || value["retractions"].length > MAX_RETRACTIONS || !value["retractions"].every(validRetraction) || !Array.isArray(value["suppressedTurns"]) || value["suppressedTurns"].length > MAX_COMPLETED || !value["suppressedTurns"].every((item) => typeof item === "string" && /^[0-9a-f]{64}$/u.test(item)) || !isRecord$3(value["revisions"]) || Object.keys(value["revisions"]).length > MAX_COMPLETED || !Object.entries(value["revisions"]).every(([key, revision]) => /^[0-9a-f]{64}$/u.test(key) && Number.isSafeInteger(revision) && revision >= 0)) throw new Error("Invalid account memory journal.");
526196
+ return value;
526197
+ }
526198
+ async writeJournal(journalPath, journal) {
526199
+ const directory = path.dirname(journalPath);
526200
+ await mkdir(directory, {
526201
+ recursive: true,
526202
+ mode: 448
526203
+ });
526204
+ const root = await realpath(this.homeDir);
526205
+ if (path.dirname(await realpath(directory)) !== root) throw new Error("Account memory journal escapes the BLUN profile.");
526206
+ const temporary = `${journalPath}.${randomUUID()}.tmp`;
526207
+ try {
526208
+ await writeFile(temporary, JSON.stringify(journal), {
526209
+ encoding: "utf8",
526210
+ mode: 384,
526211
+ flag: "wx"
526212
+ });
526213
+ await rename(temporary, journalPath);
526214
+ } finally {
526215
+ await unlink(temporary).catch(() => {});
526216
+ }
526217
+ }
526218
+ serial(run) {
526219
+ const task = this.work.then(run, run);
526220
+ this.work = task.then(() => void 0, () => void 0);
526221
+ return task;
526222
+ }
526223
+ };
526224
+ function beforeCutoff(occurredAt, cutoff) {
526225
+ return cutoff !== null && Date.parse(occurredAt) <= Date.parse(cutoff);
526226
+ }
526227
+ function captureKey(sessionId, turnId, occurredAt, messageIds) {
526228
+ return createHash("sha256").update(`${sessionId}\0${turnId}\0${occurredAt}\0${messageIds.join("\0")}`).digest("hex");
526229
+ }
526230
+ function turnKey(sessionId, turnId) {
526231
+ return createHash("sha256").update(`${sessionId}\0${turnId}`).digest("hex");
526232
+ }
526233
+ function turnMessageIds(sessionId, turnId, turn, revision) {
526234
+ return [stableMessageId(sessionId, turnId, revision, "user", turn.userText), stableMessageId(sessionId, turnId, revision, "assistant", turn.assistantText)];
526235
+ }
526236
+ function stableMessageId(sessionId, turnId, revision, role, content) {
526237
+ return `tui-${createHash("sha256").update(`${sessionId}\0${turnId}\0${revision}\0${role}\0${content}`).digest("hex")}`;
526238
+ }
526239
+ function validPending(value) {
526240
+ return isRecord$3(value) && typeof value["captureId"] === "string" && UUID_V4.test(value["captureId"]) && typeof value["sessionId"] === "string" && typeof value["sessionDir"] === "string" && Number.isSafeInteger(value["turnId"]) && value["turnId"] >= 0 && typeof value["occurredAt"] === "string" && Number.isFinite(Date.parse(value["occurredAt"])) && validMessageIds(value["messageIds"]) && typeof value["awaitingSessionRetract"] === "boolean" && (value["sessionEpoch"] === null || Number.isSafeInteger(value["sessionEpoch"]) && value["sessionEpoch"] >= 0);
526241
+ }
526242
+ function validKnown(value) {
526243
+ return isRecord$3(value) && typeof value["key"] === "string" && /^[0-9a-f]{64}$/u.test(value["key"]) && typeof value["sessionId"] === "string" && Number.isSafeInteger(value["turnId"]) && typeof value["occurredAt"] === "string" && Number.isFinite(Date.parse(value["occurredAt"])) && validMessageIds(value["messageIds"]);
526244
+ }
526245
+ function validRetraction(value) {
526246
+ return isRecord$3(value) && typeof value["retractId"] === "string" && UUID_V4.test(value["retractId"]) && typeof value["sessionId"] === "string" && value["sessionId"].length > 0 && (value["wholeSession"] === true && (value["expectedEpoch"] === null || Number.isSafeInteger(value["expectedEpoch"]) && value["expectedEpoch"] >= 0) || Array.isArray(value["messageIds"]) && value["messageIds"].length > 0 && value["messageIds"].length <= 200 && value["messageIds"].every(validMessageId));
526247
+ }
526248
+ function validMessageIds(value) {
526249
+ return Array.isArray(value) && value.length === 2 && value.every(validMessageId);
526250
+ }
526251
+ function validMessageId(value) {
526252
+ return typeof value === "string" && /^tui-[0-9a-f]{64}$/u.test(value);
526253
+ }
526254
+ function isRecord$3(value) {
526255
+ return typeof value === "object" && value !== null && !Array.isArray(value);
526256
+ }
526257
+ function isMissing(error) {
526258
+ return isRecord$3(error) && error["code"] === "ENOENT";
526259
+ }
526260
+ //#endregion
526261
+ //#region src/personal-memory/account-memory-runtime.ts
526262
+ var TuiAccountMemoryRuntime = class {
526263
+ client;
526264
+ broker;
526265
+ queue;
526266
+ getManagedQuota;
526267
+ constructor(client, broker, queue, getManagedQuota) {
526268
+ this.client = client;
526269
+ this.broker = broker;
526270
+ this.queue = queue;
526271
+ this.getManagedQuota = getManagedQuota;
526272
+ }
526273
+ async captureCompletedTurn(session, turnId) {
526274
+ const permission = await this.permission("write");
526275
+ if (permission === "unavailable") return "unavailable";
526276
+ if (permission === "denied") {
526277
+ await this.queue.discardPending().catch(() => {});
526278
+ return "skipped";
526279
+ }
526280
+ return this.queue.captureCompletedTurn(session, turnId).catch(() => "unavailable");
526281
+ }
526282
+ async retryPending() {
526283
+ const permission = await this.permission("write");
526284
+ if (permission === "denied") await this.queue.discardPending().catch(() => {});
526285
+ const retractions = await this.queue.retryRetractions().catch(() => "unavailable");
526286
+ if (retractions === "queued") return "queued";
526287
+ if (permission === "denied") return "skipped";
526288
+ if (permission === "unavailable" || retractions === "unavailable") return "unavailable";
526289
+ return this.queue.retryPending().catch(() => "unavailable");
526290
+ }
526291
+ retractTurn(sessionId, turnId) {
526292
+ return this.queue.retractTurn(sessionId, turnId).catch(() => "unavailable");
526293
+ }
526294
+ retractSession(sessionId, throughTurnId) {
526295
+ return (throughTurnId === void 0 ? this.queue.retractSession(sessionId) : this.queue.retractSession(sessionId, throughTurnId)).catch(() => "unavailable");
526296
+ }
526297
+ flushRetractionsBeforeLogout() {
526298
+ return this.queue.flushRetractionsBeforeLogout().catch(() => true);
526299
+ }
526300
+ async recall(query) {
526301
+ if (await this.permission("read") !== "allowed") return void 0;
526302
+ return this.broker.recall(query, 8).catch(() => void 0);
526303
+ }
526304
+ async search(query, limit = 20) {
526305
+ if (await this.permission("read") !== "allowed") return void 0;
526306
+ return this.broker.search(query, { limit }).catch(() => void 0);
526307
+ }
526308
+ async permission(operation) {
526309
+ let settings;
526310
+ try {
526311
+ const quota = await this.getManagedQuota();
526312
+ if (quota.kind !== "ok") return "unavailable";
526313
+ if (quota.paid !== true) return "denied";
526314
+ settings = await this.client.getSettings();
526315
+ } catch {
526316
+ return "unavailable";
526317
+ }
526318
+ if (settings.consentStatus !== "enabled" || !settings.memoryEnabled || !settings.useChatHistory) return "denied";
526319
+ return operation === "write" ? settings.allowNewMemories ? "allowed" : "denied" : settings.useSavedMemories ? "allowed" : "denied";
526320
+ }
526321
+ };
526322
+ function createTuiAccountMemoryRuntime(harness, env = process.env) {
526323
+ if (env["BLUN_ACCOUNT_MEMORY_BROKER_ENABLED"] !== "1") return void 0;
526324
+ try {
526325
+ const client = createPersonalMemoryBrokerClient(harness);
526326
+ const broker = new AccountMemoryBroker(client);
526327
+ return new TuiAccountMemoryRuntime(client, broker, new AccountMemoryCaptureQueue(harness.homeDir, broker, void 0, {
526328
+ get: () => harness.auth.getCachedMemoryWorkspaceId(),
526329
+ set: (workspaceId) => harness.auth.cacheMemoryWorkspaceId(workspaceId)
526330
+ }), () => harness.auth.getManagedQuota(DEFAULT_OAUTH_PROVIDER_NAME));
526331
+ } catch {
526332
+ return;
526333
+ }
526334
+ }
526335
+ //#endregion
524984
526336
  //#region src/utils/persistence.ts
524985
526337
  /**
524986
526338
  * Small persistence helpers for CLI-owned data files.
@@ -532899,7 +534251,8 @@ var PersonalMemoryController = class {
532899
534251
  await this.dependencies.bindTools(session, this.host.harness, {
532900
534252
  binding: personalMemoryHostBinding(),
532901
534253
  localHistory: this.host.harness,
532902
- searchOnly: true
534254
+ searchOnly: true,
534255
+ accountMemory: this.host.accountMemoryRuntime
532903
534256
  });
532904
534257
  return this.isCurrent(generation, session) ? "ready" : "stale";
532905
534258
  } catch {
@@ -532981,7 +534334,8 @@ var PersonalMemoryController = class {
532981
534334
  await this.dependencies.bindTools(session, this.host.harness, {
532982
534335
  binding,
532983
534336
  client,
532984
- localHistory: this.host.harness
534337
+ localHistory: this.host.harness,
534338
+ accountMemory: this.host.accountMemoryRuntime
532985
534339
  });
532986
534340
  return "ready";
532987
534341
  } catch {
@@ -535804,7 +537158,10 @@ var SessionEventHandler = class {
535804
537158
  this.showPendingCompactionRetry();
535805
537159
  this.goalCompletionTurnEnded = true;
535806
537160
  this.scheduleQueuedGoalPromotion();
535807
- if (event.reason === "completed") this.host.refreshManagedQuotaWindows();
537161
+ if (event.reason === "completed") {
537162
+ this.host.refreshManagedQuotaWindows();
537163
+ this.host.recordAccountMemoryTurn?.(event);
537164
+ }
535808
537165
  }
535809
537166
  handleStepBegin(event) {
535810
537167
  this.host.commitQueuedSteerAtStepStart(event.turnId);
@@ -543069,6 +544426,7 @@ var BlunTUI = class {
543069
544426
  editorKeyboard;
543070
544427
  scrollbackController;
543071
544428
  personalMemoryController;
544429
+ accountMemoryRuntime;
543072
544430
  customerMistakeController;
543073
544431
  managedQuotaWarningController;
543074
544432
  managedQuotaWarningPersistence = Promise.resolve();
@@ -543153,6 +544511,7 @@ var BlunTUI = class {
543153
544511
  this.loopCountdown = new LoopCountdownController(() => this.state.ui.requestRender());
543154
544512
  this.authFlow = new AuthFlowController(this);
543155
544513
  this.personalMemoryController = new PersonalMemoryController(this);
544514
+ this.accountMemoryRuntime = createTuiAccountMemoryRuntime(harness);
543156
544515
  this.customerMistakeController = new CustomerMistakeHostController();
543157
544516
  this.btwPanelController = new BtwPanelController(this);
543158
544517
  this.sessionEventHandler = new SessionEventHandler(this);
@@ -544846,6 +546205,15 @@ var BlunTUI = class {
544846
546205
  refreshManagedQuotaWindows() {
544847
546206
  this.authFlow.refreshManagedQuotaWindows();
544848
546207
  }
546208
+ recordAccountMemoryTurn(event) {
546209
+ const session = this.session;
546210
+ const sessionDir = session?.summary?.sessionDir;
546211
+ if (session === void 0 || sessionDir === void 0) return;
546212
+ this.accountMemoryRuntime?.captureCompletedTurn({
546213
+ id: session.id,
546214
+ sessionDir
546215
+ }, event.turnId).catch(() => {});
546216
+ }
544849
546217
  async refreshPersonalMemory(promptIfNeverAsked = false) {
544850
546218
  await this.personalMemoryController.refresh({ promptIfNeverAsked });
544851
546219
  }
@@ -544987,6 +546355,7 @@ var BlunTUI = class {
544987
546355
  await this.refreshManagedImageReaderAvailability(session);
544988
546356
  await this.authFlow.applyManagedAccountContextToSession();
544989
546357
  await this.personalMemoryController.refresh();
546358
+ this.accountMemoryRuntime?.retryPending().catch(() => {});
544990
546359
  this.telegramSessionScope = queueScope;
544991
546360
  this.telegramChannel?.bindSessionQueue(queueScope);
544992
546361
  if (selectionScope !== void 0 && this.session === session) {
@@ -545270,6 +546639,7 @@ var BlunTUI = class {
545270
546639
  this.registerSessionHandlers(session);
545271
546640
  await this.refreshManagedImageReaderAvailability(session);
545272
546641
  await this.personalMemoryController.refresh();
546642
+ this.accountMemoryRuntime?.retryPending().catch(() => {});
545273
546643
  await this.syncRuntimeState(session);
545274
546644
  this.updateTerminalTitle();
545275
546645
  try {
@@ -546333,13 +547703,13 @@ var BlunTUI = class {
546333
547703
  //#endregion
546334
547704
  //#region src/constant/update.ts
546335
547705
  var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
546336
- const fs$1 = __require("node:fs");
547706
+ const fs = __require("node:fs");
546337
547707
  const os$1 = __require("node:os");
546338
- const path$2 = __require("node:path");
547708
+ const path$1 = __require("node:path");
546339
547709
  const DEFAULT_MAX_BYTES = 1024 * 1024;
546340
547710
  const DEFAULT_RETAIN_BYTES = 512 * 1024;
546341
547711
  function runtimeExitLedgerPath(homeDir) {
546342
- return path$2.join(homeDir, "diagnostics", "runtime-exits.jsonl");
547712
+ return path$1.join(homeDir, "diagnostics", "runtime-exits.jsonl");
546343
547713
  }
546344
547714
  function sanitizeExitText(input, maxChars = 2048) {
546345
547715
  let value = String(input ?? "");
@@ -546348,7 +547718,7 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546348
547718
  process.env.USERPROFILE,
546349
547719
  process.env.HOME
546350
547720
  ].filter((entry) => typeof entry === "string" && entry.length > 2));
546351
- for (const home of homes) for (const variant of [path$2.normalize(home), home.replaceAll("\\", "/")]) {
547721
+ for (const home of homes) for (const variant of [path$1.normalize(home), home.replaceAll("\\", "/")]) {
546352
547722
  const escaped = variant.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
546353
547723
  value = value.replace(new RegExp(escaped, process.platform === "win32" ? "giu" : "gu"), "$HOME");
546354
547724
  }
@@ -546387,7 +547757,7 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546387
547757
  return record;
546388
547758
  }
546389
547759
  function directoryIdentity(directory) {
546390
- const stat = fs$1.lstatSync(directory, { bigint: true });
547760
+ const stat = fs.lstatSync(directory, { bigint: true });
546391
547761
  if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Unsafe exit directory");
546392
547762
  return stat;
546393
547763
  }
@@ -546399,46 +547769,46 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546399
547769
  return stat;
546400
547770
  }
546401
547771
  function trimLedger(descriptor, maxBytes, retainBytes, incomingBytes) {
546402
- const size = Number(regularLedger(fs$1.fstatSync(descriptor, { bigint: true })).size);
547772
+ const size = Number(regularLedger(fs.fstatSync(descriptor, { bigint: true })).size);
546403
547773
  if (!Number.isSafeInteger(size)) throw new Error("Invalid exit ledger size");
546404
547774
  if (size + incomingBytes <= maxBytes) return;
546405
547775
  const keepBytes = Math.max(0, Math.min(size, retainBytes, maxBytes - incomingBytes));
546406
547776
  const contents = Buffer.alloc(keepBytes);
546407
- const read = fs$1.readSync(descriptor, contents, 0, keepBytes, size - keepBytes);
547777
+ const read = fs.readSync(descriptor, contents, 0, keepBytes, size - keepBytes);
546408
547778
  const tail = contents.subarray(0, read);
546409
547779
  const lineStart = size > keepBytes ? tail.indexOf(10) + 1 : 0;
546410
- fs$1.ftruncateSync(descriptor, 0);
546411
- fs$1.writeFileSync(descriptor, lineStart > 0 || size === keepBytes ? tail.subarray(lineStart) : "");
547780
+ fs.ftruncateSync(descriptor, 0);
547781
+ fs.writeFileSync(descriptor, lineStart > 0 || size === keepBytes ? tail.subarray(lineStart) : "");
546412
547782
  }
546413
547783
  function recordRuntimeExit(input = {}) {
546414
547784
  let descriptor;
546415
547785
  let appendDescriptor;
546416
547786
  try {
546417
547787
  const homeDir = typeof input.homeDir === "string" ? input.homeDir.trim() : "";
546418
- if (!homeDir || !path$2.isAbsolute(homeDir)) return false;
546419
- fs$1.mkdirSync(homeDir, {
547788
+ if (!homeDir || !path$1.isAbsolute(homeDir)) return false;
547789
+ fs.mkdirSync(homeDir, {
546420
547790
  recursive: true,
546421
547791
  mode: 448
546422
547792
  });
546423
547793
  const homeIdentity = directoryIdentity(homeDir);
546424
547794
  const file = runtimeExitLedgerPath(homeDir);
546425
- const directory = path$2.dirname(file);
547795
+ const directory = path$1.dirname(file);
546426
547796
  try {
546427
- fs$1.mkdirSync(directory, { mode: 448 });
547797
+ fs.mkdirSync(directory, { mode: 448 });
546428
547798
  } catch (error) {
546429
547799
  if (error.code !== "EEXIST") throw error;
546430
547800
  }
546431
547801
  const directoryStat = directoryIdentity(directory);
546432
547802
  let before;
546433
547803
  try {
546434
- before = regularLedger(fs$1.lstatSync(file, { bigint: true }));
547804
+ before = regularLedger(fs.lstatSync(file, { bigint: true }));
546435
547805
  } catch (error) {
546436
547806
  if (error.code !== "ENOENT") throw error;
546437
547807
  }
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");
547808
+ 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);
547809
+ descriptor = fs.openSync(file, flags, 384);
547810
+ const opened = regularLedger(fs.fstatSync(descriptor, { bigint: true }));
547811
+ 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");
546442
547812
  const maxBytes = Math.max(1024, Number.isInteger(input.maxBytes) ? input.maxBytes : DEFAULT_MAX_BYTES);
546443
547813
  const retainBytes = Math.max(0, Number.isInteger(input.retainBytes) ? input.retainBytes : DEFAULT_RETAIN_BYTES);
546444
547814
  const record = buildRuntimeExitRecord(input);
@@ -546461,21 +547831,21 @@ var import_runtime_exit_ledger = (/* @__PURE__ */ __commonJSMin(((exports, modul
546461
547831
  line = `${JSON.stringify(record)}\n`;
546462
547832
  }
546463
547833
  trimLedger(descriptor, maxBytes, retainBytes, Buffer.byteLength(line));
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" });
547834
+ appendDescriptor = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
547835
+ 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");
547836
+ fs.appendFileSync(appendDescriptor, line, { encoding: "utf8" });
546467
547837
  try {
546468
- fs$1.fchmodSync(descriptor, 384);
547838
+ fs.fchmodSync(descriptor, 384);
546469
547839
  } catch {}
546470
547840
  return true;
546471
547841
  } catch {
546472
547842
  return false;
546473
547843
  } finally {
546474
547844
  if (appendDescriptor !== void 0) try {
546475
- fs$1.closeSync(appendDescriptor);
547845
+ fs.closeSync(appendDescriptor);
546476
547846
  } catch {}
546477
547847
  if (descriptor !== void 0) try {
546478
- fs$1.closeSync(descriptor);
547848
+ fs.closeSync(descriptor);
546479
547849
  } catch {}
546480
547850
  }
546481
547851
  }