@cydm/pie 4.8.0 → 4.9.0

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.
Files changed (49) hide show
  1. package/README.md +51 -27
  2. package/dist/builtin/extensions/ask-user/index.js +4 -4
  3. package/dist/builtin/extensions/cron/index.js +906 -158
  4. package/dist/builtin/extensions/im-forward/README.md +4 -2
  5. package/dist/builtin/extensions/im-forward/index.js +6822 -3951
  6. package/dist/builtin/extensions/memory/index.js +76 -28
  7. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  8. package/dist/builtin/extensions/pie-ipc/index.js +282 -58
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +227 -75
  11. package/dist/builtin/extensions/plan-mode/index.js +5 -5
  12. package/dist/builtin/extensions/subagent/index.js +8 -8
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +26 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
  18. package/dist/builtin/skills/chrome-devtools-axi/{cli-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +293 -64
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-4UIUMTHG.js} +993 -371
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BA4Z27XT.js} +4 -3
  26. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-DBDU3RRN.js} +1364 -446
  27. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-EEC5PJTC.js} +11 -9
  28. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  29. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-LRHNAG4V.js} +349 -288
  30. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  31. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-PN6B54VT.js} +104 -22
  32. package/dist/chunks/{chunk-NHV2CALB.js → chunk-WYXUF4MP.js} +388 -32
  33. package/dist/chunks/{chunk-4PR34UZF.js → chunk-Z5KL6AO2.js} +159 -145
  34. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-RASJSVZY.js} +1 -1
  35. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  36. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-5TLYILYR.js} +2 -2
  37. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-VPKDBV23.js} +5 -5
  38. package/dist/chunks/{src-B44QWSGM.js → src-2XI5P62J.js} +2 -2
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-6QGGDHIW.js} +3 -3
  40. package/dist/chunks/{src-Q7LU27C2.js → src-CCEENRKC.js} +31 -1
  41. package/dist/chunks/{src-CLE5ILN4.js → src-DI4MCAGT.js} +20 -4
  42. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-SYVWIPPW.js} +2 -2
  43. package/dist/cli.js +1890 -1489
  44. package/models.schema.json +271 -0
  45. package/package.json +2 -2
  46. package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
  47. package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
  48. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-WBL73KRI.js} +3 -3
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
@@ -13,19 +13,22 @@ import {
13
13
  parseEntryIdSeq,
14
14
  readAncestryPage,
15
15
  requestInteraction
16
- } from "./chunk-Y3I2UV5Y.js";
16
+ } from "./chunk-LRHNAG4V.js";
17
17
  import {
18
18
  Agent,
19
19
  getToolCallerIdentity
20
- } from "./chunk-5KI4Y4LA.js";
20
+ } from "./chunk-BA4Z27XT.js";
21
21
  import {
22
+ ALL_THINKING_LEVELS,
22
23
  AssistantMessageEventStream,
23
24
  completeSimple,
24
25
  detectPlatform,
25
26
  getFileSystem,
27
+ getSupportedThinkingLevels,
26
28
  hashText,
29
+ resolveThinkingSelection,
27
30
  streamSimple
28
- } from "./chunk-3W3SXVPB.js";
31
+ } from "./chunk-4UIUMTHG.js";
29
32
  import {
30
33
  Type
31
34
  } from "./chunk-XXGYUYXI.js";
@@ -607,7 +610,7 @@ function createSearchContextTool(getReader) {
607
610
  }
608
611
  scanned++;
609
612
  if (scanned % 16 === 0) {
610
- await new Promise((resolve5) => setTimeout(resolve5, 0));
613
+ await new Promise((resolve6) => setTimeout(resolve6, 0));
611
614
  if (signal?.aborted) throw new Error("History search aborted");
612
615
  if (reader.getActiveSessionId() !== session || reader.getHistoryBranchRevision() !== revision) throw new Error("History changed; restart search");
613
616
  }
@@ -1495,13 +1498,13 @@ function checkPlanScope(items, exists, isNew) {
1495
1498
  const seen = /* @__PURE__ */ new Set();
1496
1499
  for (const item of items) {
1497
1500
  for (const rawPath of item.files ?? []) {
1498
- const path9 = String(rawPath ?? "").trim();
1499
- if (!path9 || seen.has(path9)) continue;
1500
- seen.add(path9);
1501
- if (isNew(item, path9)) {
1502
- if (exists(path9)) warnings.push({ path: path9, kind: "exists" });
1503
- } else if (!exists(path9)) {
1504
- warnings.push({ path: path9, kind: "missing" });
1501
+ const path10 = String(rawPath ?? "").trim();
1502
+ if (!path10 || seen.has(path10)) continue;
1503
+ seen.add(path10);
1504
+ if (isNew(item, path10)) {
1505
+ if (exists(path10)) warnings.push({ path: path10, kind: "exists" });
1506
+ } else if (!exists(path10)) {
1507
+ warnings.push({ path: path10, kind: "missing" });
1505
1508
  }
1506
1509
  }
1507
1510
  }
@@ -1623,12 +1626,12 @@ Focus: ${request.question.trim()}` : ""}` },
1623
1626
  const capability = agentModel.fileCapabilities?.[request.kind];
1624
1627
  const audioSupported = request.kind !== "audio" || ["audio/wav", "audio/mpeg", "audio/mp3"].includes(request.mimeType);
1625
1628
  if (capability && typeof capability === "object" && capability.supported !== false && capability.nativeInline === true && audioSupported && (!capability.formats || capability.formats.includes(request.mimeType)) && capability.maxDurationSeconds === void 0) {
1626
- const fs7 = getFileSystem();
1627
- const size = (await fs7.stat(request.absolutePath)).size;
1629
+ const fs8 = getFileSystem();
1630
+ const size = (await fs8.stat(request.absolutePath)).size;
1628
1631
  const cap = Math.min(capability.maxFileSizeMb ?? 15, 15) * 1024 * 1024;
1629
1632
  if (size > 0 && size <= cap) {
1630
1633
  if (request.signal?.aborted) throw new Error("Operation aborted");
1631
- const data = await fs7.readFile(request.absolutePath, "base64");
1634
+ const data = await fs8.readFile(request.absolutePath, "base64");
1632
1635
  if (request.signal?.aborted) throw new Error("Operation aborted");
1633
1636
  const readBytes = Math.floor(data.length * 3 / 4) - (data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0);
1634
1637
  if (readBytes > 0 && readBytes <= cap && data) return {
@@ -1843,7 +1846,8 @@ function beginSubagentUsage(usage, model) {
1843
1846
  usage.reportedAttempts++;
1844
1847
  for (const key of Object.keys(usage.reportedTokens)) usage.reportedTokens[key] += values[key] ?? 0;
1845
1848
  } else usage.unknownAttempts++;
1846
- const priced = known && ["input", "output", "cacheRead", "cacheWrite"].every((key) => typeof model?.cost?.[key] === "number" && Number.isFinite(model.cost[key]) && model.cost[key] >= 0) && Object.values(model.cost).some((value) => typeof value === "number" && value > 0) && Number.isFinite(values.cost?.total) && values.cost.total >= 0;
1849
+ const costTable = model?.cost;
1850
+ const priced = known && costTable !== void 0 && ["input", "output", "cacheRead", "cacheWrite"].every((key) => typeof costTable[key] === "number" && Number.isFinite(costTable[key]) && costTable[key] >= 0) && Object.values(costTable).some((value) => typeof value === "number" && value > 0) && Number.isFinite(values.cost?.total) && values.cost.total >= 0;
1847
1851
  if (usage.attempts === 1 && priced) usage.estimatedCost = values.cost.total;
1848
1852
  else if (priced && usage.estimatedCost !== null) usage.estimatedCost += values.cost.total;
1849
1853
  else usage.estimatedCost = null;
@@ -1906,11 +1910,11 @@ function isRetryableSubagentFailureFrom(facts) {
1906
1910
  return remoteClosure || /Request timeout/i.test(message) || /econnreset|econnaborted|etimedout|eai_again|econnrefused|socket hang up|socket disconnected|secure TLS connection|fetch failed|network error|connection reset|premature close|\b50[0234]\b|bad gateway|service unavailable/i.test(message);
1907
1911
  }
1908
1912
  function cancellableBackoff(ms, signal) {
1909
- return new Promise((resolve5) => {
1913
+ return new Promise((resolve6) => {
1910
1914
  const finish = () => {
1911
1915
  clearTimeout(timer);
1912
1916
  signal?.removeEventListener("abort", finish);
1913
- resolve5();
1917
+ resolve6();
1914
1918
  };
1915
1919
  const timer = setTimeout(finish, ms);
1916
1920
  signal?.addEventListener("abort", finish, { once: true });
@@ -2029,9 +2033,9 @@ async function closeIterator(iterator, hooks, signal) {
2029
2033
  try {
2030
2034
  await Promise.race([
2031
2035
  cleanup,
2032
- new Promise((resolve5) => {
2033
- timer = setTimeout(resolve5, waitMs);
2034
- onAbort = () => resolve5();
2036
+ new Promise((resolve6) => {
2037
+ timer = setTimeout(resolve6, waitMs);
2038
+ onAbort = () => resolve6();
2035
2039
  signal?.addEventListener("abort", onAbort, { once: true });
2036
2040
  })
2037
2041
  ]);
@@ -2843,7 +2847,7 @@ function interpretShellExit(command, exitCode) {
2843
2847
  // ../../packages/shared-headless-capabilities/src/subagent.ts
2844
2848
  var DEFAULT_SUBAGENT_TIMEOUT_SECONDS = 1200;
2845
2849
  var DEFAULT_SUBAGENT_THINKING_LEVEL = "medium";
2846
- var SUBAGENT_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
2850
+ var SUBAGENT_THINKING_LEVELS = ALL_THINKING_LEVELS;
2847
2851
  var DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
2848
2852
  function formatHeartbeatElapsed(ms) {
2849
2853
  const totalSeconds = Math.floor(ms / 1e3);
@@ -2869,7 +2873,7 @@ function collectLastAssistantText(messages) {
2869
2873
  continue;
2870
2874
  }
2871
2875
  if (Array.isArray(message.content)) {
2872
- const realBlocks = message.content.filter((content) => content?.type === "text" && typeof content.text === "string").map((content) => content.text).filter((text) => !isSyntheticProviderText(text));
2876
+ const realBlocks = message.content.filter((content) => typeof content === "object" && content !== null && content.type === "text" && typeof content.text === "string").map((content) => content.text).filter((text) => !isSyntheticProviderText(text));
2873
2877
  const textContent = realBlocks.join("\n");
2874
2878
  if (textContent.trim()) {
2875
2879
  return textContent;
@@ -2882,15 +2886,17 @@ function collectLastAssistantText(messages) {
2882
2886
  return "";
2883
2887
  }
2884
2888
  function visibleTextBlocks(message) {
2885
- if (!Array.isArray(message.content)) return [];
2886
- return message.content.filter((content) => content?.type === "text" && typeof content.text === "string").map((content) => content.text).filter((text) => text.trim().length > 0 && !isSyntheticProviderText(text));
2889
+ const content = message?.content;
2890
+ if (!Array.isArray(content)) return [];
2891
+ return content.filter((item) => typeof item === "object" && item !== null && item.type === "text" && typeof item.text === "string").map((item) => item.text).filter((text) => text.trim().length > 0 && !isSyntheticProviderText(text));
2887
2892
  }
2888
2893
  function messageHasOwnText(message) {
2889
- if (!message) return false;
2890
- if (Array.isArray(message.content)) {
2891
- return visibleTextBlocks(message).length > 0;
2894
+ const msg = message;
2895
+ if (!msg) return false;
2896
+ if (Array.isArray(msg.content)) {
2897
+ return visibleTextBlocks(msg).length > 0;
2892
2898
  }
2893
- return typeof message.content === "string" && message.content.trim().length > 0 && !isSyntheticProviderText(message.content);
2899
+ return typeof msg.content === "string" && msg.content.trim().length > 0 && !isSyntheticProviderText(msg.content);
2894
2900
  }
2895
2901
  function inferComplexity(task, priority) {
2896
2902
  const normalized = task.toLowerCase();
@@ -2962,7 +2968,7 @@ function filterToolsForSubagent(runtimeTools, parentTools, plan, mode) {
2962
2968
  }
2963
2969
  return filtered;
2964
2970
  }
2965
- function buildSubagentPlan(deps, task, name, priority, timeoutSeconds, modelOverride, thinkingLevel = DEFAULT_SUBAGENT_THINKING_LEVEL, mode = "read") {
2971
+ function buildSubagentPlan(deps, task, name, priority, timeoutSeconds, modelOverride, thinkingLevel = DEFAULT_SUBAGENT_THINKING_LEVEL, mode = "read", explicitThinking = false) {
2966
2972
  const complexity = inferComplexity(task, priority);
2967
2973
  const modelClass = selectModelClass(complexity, priority);
2968
2974
  const overrideResolution = modelOverride ? deps.resolveModelRef?.(modelOverride) ?? { model: void 0, fallbackReason: `model override "${modelOverride}" is not supported by this host` } : void 0;
@@ -2973,6 +2979,11 @@ function buildSubagentPlan(deps, task, name, priority, timeoutSeconds, modelOver
2973
2979
  const apiKey = overridePair?.apiKey ?? resolvedPair?.apiKey ?? deps.apiKey;
2974
2980
  const overrideMissReason = overrideResolution?.fallbackReason ?? `model override "${modelOverride}" could not be resolved`;
2975
2981
  const modelFallbackReason = modelOverride ? overridePair ? void 0 : modelResolution?.fallbackReason ? `${overrideMissReason}; ${modelResolution.fallbackReason}` : overrideMissReason : modelResolution?.fallbackReason;
2982
+ if (explicitThinking && thinkingLevel === "max" && !getSupportedThinkingLevels(model).includes("max")) {
2983
+ const supported = getSupportedThinkingLevels(model);
2984
+ throw new Error(`Model "${model?.provider ? `${model.provider}/` : ""}${model?.id ?? "unknown"}" does not support native thinkingLevel "max".${supported.length > 0 ? ` Supported: ${supported.join(", ")}.` : ""}`);
2985
+ }
2986
+ const effectiveThinking = resolveThinkingSelection(model, thinkingLevel).effective;
2976
2987
  const partialPlan = {
2977
2988
  task,
2978
2989
  name,
@@ -2983,6 +2994,7 @@ function buildSubagentPlan(deps, task, name, priority, timeoutSeconds, modelOver
2983
2994
  modelOverride,
2984
2995
  modelOverrideApplied: Boolean(overridePair),
2985
2996
  thinkingLevel,
2997
+ ...effectiveThinking !== thinkingLevel ? { effectiveThinkingLevel: effectiveThinking } : {},
2986
2998
  modelId: `${model?.provider ? `${model.provider}/` : ""}${model?.id ?? "unknown"}`,
2987
2999
  modelFallbackReason,
2988
3000
  toolsExcluded: [],
@@ -3249,7 +3261,7 @@ async function runSubagentWithProgress(deps, task, reportProgress, signal, sessi
3249
3261
  let baseline = 0;
3250
3262
  let hardDeadlineAt;
3251
3263
  let pendingRun;
3252
- const isReportTerminal = (message) => ["stop", "length", "error", "aborted"].includes(message?.stopReason) && !(Array.isArray(message?.content) && message.content.some((block) => block?.type === "toolCall"));
3264
+ const isReportTerminal = (message) => message?.role === "assistant" && ["stop", "length", "error", "aborted"].includes(message.stopReason) && !(Array.isArray(message.content) && message.content.some((block) => block?.type === "toolCall"));
3253
3265
  const refreshReport = () => {
3254
3266
  if (!runStarted || !session?.agent) return;
3255
3267
  const last = [...session.agent.state.messages.slice(baseline)].reverse().find((m) => m?.role === "assistant");
@@ -3310,13 +3322,17 @@ async function runSubagentWithProgress(deps, task, reportProgress, signal, sessi
3310
3322
  subagent = session.agent;
3311
3323
  baseline = subagent.state.messages.length;
3312
3324
  } else {
3313
- let built = buildSubagentPlan(deps, session.originalTask, session.name, session.priority, session.timeoutSeconds, nextModelOverride, nextThinking, nextMode);
3325
+ const deferMaxCheck = task.thinkingLevel === "max" && Boolean(task.modelOverride && session.modelOverride && session.modelOverride !== task.modelOverride);
3326
+ let built = buildSubagentPlan(deps, session.originalTask, session.name, session.priority, session.timeoutSeconds, nextModelOverride, nextThinking, nextMode, task.thinkingLevel !== void 0 && !deferMaxCheck);
3314
3327
  let effectiveOverride = nextModelOverride;
3315
3328
  if (task.modelOverride && !built.plan.modelOverrideApplied && session.modelOverride && session.modelOverride !== task.modelOverride) {
3316
3329
  const missReason = built.plan.modelFallbackReason ?? `model override "${task.modelOverride}" could not be resolved`;
3317
- built = buildSubagentPlan(deps, session.originalTask, session.name, session.priority, session.timeoutSeconds, session.modelOverride, nextThinking, nextMode);
3330
+ built = buildSubagentPlan(deps, session.originalTask, session.name, session.priority, session.timeoutSeconds, session.modelOverride, nextThinking, nextMode, task.thinkingLevel !== void 0);
3318
3331
  built.plan.modelFallbackReason = built.plan.modelFallbackReason ? `${missReason}; ${built.plan.modelFallbackReason}` : missReason;
3319
3332
  effectiveOverride = session.modelOverride;
3333
+ } else if (deferMaxCheck && !getSupportedThinkingLevels(built.model).includes("max")) {
3334
+ const supported = getSupportedThinkingLevels(built.model);
3335
+ throw new Error(`Model "${built.plan.modelId}" does not support native thinkingLevel "max".${supported.length > 0 ? ` Supported: ${supported.join(", ")}.` : ""}`);
3320
3336
  }
3321
3337
  plan = built.plan;
3322
3338
  task.plan = plan;
@@ -3354,7 +3370,7 @@ async function runSubagentWithProgress(deps, task, reportProgress, signal, sessi
3354
3370
  task.mode = session.mode;
3355
3371
  deps.log(`[Subagent ${task.name}] Recalling session ${session.id} (run ${session.runCount + 1}, mode=${session.mode}${resolved.restored ? ", restored from disk" : ""}${mustRebuild ? ", reconfigured" : ""})`);
3356
3372
  } else {
3357
- const built = buildSubagentPlan(deps, task.task, task.name, task.priority, task.timeoutSeconds, task.modelOverride, task.thinkingLevel, task.mode);
3373
+ const built = buildSubagentPlan(deps, task.task, task.name, task.priority, task.timeoutSeconds, task.modelOverride, task.thinkingLevel, task.mode, task.thinkingLevel !== void 0);
3358
3374
  plan = built.plan;
3359
3375
  task.plan = plan;
3360
3376
  const { tools, apiKey, model } = built;
@@ -3527,7 +3543,7 @@ ${DELEGATION_REPORT_INSTRUCTION}`;
3527
3543
  if (graceMs > 0) {
3528
3544
  await Promise.race([
3529
3545
  settledRun,
3530
- new Promise((resolve5) => setTimeout(resolve5, graceMs))
3546
+ new Promise((resolve6) => setTimeout(resolve6, graceMs))
3531
3547
  ]);
3532
3548
  }
3533
3549
  }
@@ -3743,8 +3759,8 @@ function buildParallelResult(tasks, totalDuration) {
3743
3759
  return resultText.slice(0, 1e5);
3744
3760
  }
3745
3761
  var TASK_FIELD_ALIASES = ["task", "description", "prompt", "objective"];
3746
- function normalizeTaskDefs(args) {
3747
- const taskDefs = args?.tasks;
3762
+ function normalizeTaskDefs(rawArgs) {
3763
+ const taskDefs = rawArgs?.tasks;
3748
3764
  if (!Array.isArray(taskDefs) || taskDefs.length === 0 || taskDefs.length > 10) {
3749
3765
  return { error: "Invalid spawn_subagents_parallel arguments: tasks must be a non-empty array." };
3750
3766
  }
@@ -3897,7 +3913,7 @@ Default mode="read" is for investigation, search, review, or triage and cannot e
3897
3913
  mode: Type.Optional(Type.Union([Type.Literal("read"), Type.Literal("edit")], { description: "Default read (investigation only). Edit permits inherited file editing and tests; one edit task per call, parent review required." })),
3898
3914
  priority: Type.Optional(Type.Union([Type.Literal("fast"), Type.Literal("thorough")], { description: "fast uses lower-cost defaults; thorough raises model class when needed." })),
3899
3915
  model: Type.Optional(Type.String({ description: 'Explicit model override, e.g. "provider/model-id". Only when the user names a specific model; otherwise automatic.' })),
3900
- thinkingLevel: Type.Optional(Type.Union([Type.Literal("off"), Type.Literal("minimal"), Type.Literal("low"), Type.Literal("medium"), Type.Literal("high"), Type.Literal("xhigh")], { description: "off|minimal|low|medium|high|xhigh. Default medium; override only when the user asks or for cheap lookups (off)." })),
3916
+ thinkingLevel: Type.Optional(Type.Union([Type.Literal("off"), Type.Literal("minimal"), Type.Literal("low"), Type.Literal("medium"), Type.Literal("high"), Type.Literal("xhigh"), Type.Literal("max")], { description: "off|minimal|low|medium|high|xhigh|max. Default medium; max is valid only on models that declare it; override only when the user asks or for cheap lookups (off)." })),
3901
3917
  timeout: Type.Optional(Type.Number({ description: "Seconds. Default 1200; set higher for long tasks. Note: high/xhigh reasoning tasks can spend minutes per response on thinking alone \u2014 budget accordingly or the deadline will cut an in-flight response mid-thought." })),
3902
3918
  resumeMode: Type.Optional(Type.Union([Type.Literal("full"), Type.Literal("report")], { description: "Default full retains prior transcript. Explicit report rebuilds with current tools/model/credentials and only the latest valid historical report as data plus the new task; fails if unavailable." })),
3903
3919
  sessionId: Type.Optional(Type.String({ description: "Continue a previous subagent session by id (from an earlier result's Session line); full mode retains historical input with unknown cost. Optional mode/model/thinkingLevel reconfigure it; one task at a time; recalls never replay on failure and must target an idle session; prefer a fresh task for independent reviews." }))
@@ -3911,17 +3927,15 @@ Default mode="read" is for investigation, search, review, or triage and cannot e
3911
3927
  }, { additionalProperties: false }),
3912
3928
  async execute(first, second, third, fourth) {
3913
3929
  if (liveSessions.disposed) throw new Error("Subagent capability is disposed");
3930
+ const ctxArg = second;
3914
3931
  const args = typeof first === "string" ? second : first;
3915
- const parentSignal = typeof first === "string" ? third : second?.signal;
3932
+ const parentSignal = typeof first === "string" ? third : ctxArg?.signal;
3916
3933
  const signal = parentSignal ? AbortSignal.any([parentSignal, shutdown.signal]) : shutdown.signal;
3917
3934
  const reportProgress = typeof first === "string" ? fourth ? (update) => {
3918
- fourth({
3919
- content: update.message ? [{ type: "text", text: update.message }] : [],
3920
- details: { increment: update.increment }
3921
- });
3922
- } : () => void 0 : second?.reportProgress ?? (() => void 0);
3935
+ fourth({ content: update.message ? [{ type: "text", text: update.message }] : [], details: { increment: update.increment } });
3936
+ } : () => void 0 : ctxArg?.reportProgress ?? (() => void 0);
3923
3937
  const toolContext = {
3924
- log: typeof first === "string" ? deps.log : second?.log ?? deps.log,
3938
+ log: typeof first === "string" ? deps.log : ctxArg?.log ?? deps.log,
3925
3939
  reportProgress: (update) => safelyObserve(reportProgress, update)
3926
3940
  };
3927
3941
  const normalized = normalizeTaskDefs(args);
@@ -4515,21 +4529,23 @@ function normalizeQuestionObject(value, index) {
4515
4529
  placeholder: typeof value.placeholder === "string" ? value.placeholder : void 0
4516
4530
  };
4517
4531
  }
4518
- function normalizeAskUserArgs(args) {
4519
- if (typeof args === "string") {
4532
+ function normalizeAskUserArgs(rawArgs) {
4533
+ let parsed = rawArgs;
4534
+ if (typeof rawArgs === "string") {
4520
4535
  try {
4521
- args = JSON.parse(args);
4536
+ parsed = JSON.parse(rawArgs);
4522
4537
  } catch {
4523
- const preview = args.length > 200 ? `${args.slice(0, 200)}...` : args;
4538
+ const preview = rawArgs.length > 200 ? `${rawArgs.slice(0, 200)}...` : rawArgs;
4524
4539
  return { error: `Tool arguments must be an object or valid JSON object string (received string: ${preview})` };
4525
4540
  }
4526
4541
  }
4527
- const allowReview = args?.allowReview ?? true;
4542
+ const args = parsed && typeof parsed === "object" ? parsed : void 0;
4543
+ const allowReview = typeof args?.allowReview === "boolean" ? args.allowReview : true;
4528
4544
  const singleQuestionText = typeof args?.question === "string" && args.question.trim().length > 0 ? args.question.trim() : typeof args?.prompt === "string" && args.prompt.trim().length > 0 ? args.prompt.trim() : void 0;
4529
4545
  const normalizedSingleQuestion = singleQuestionText ? {
4530
4546
  id: "q1",
4531
4547
  question: singleQuestionText,
4532
- options: Array.isArray(args.options) ? args.options.filter((option) => typeof option === "string").map((option) => option.trim()).filter((option) => option.length > 0) : void 0,
4548
+ options: Array.isArray(args?.options) ? args.options.filter((option) => typeof option === "string").map((option) => option.trim()).filter((option) => option.length > 0) : void 0,
4533
4549
  placeholder: typeof args?.placeholder === "string" ? args.placeholder : void 0
4534
4550
  } : void 0;
4535
4551
  if (normalizedSingleQuestion && Array.isArray(args?.questions) && args.questions.length === 0) {
@@ -4691,6 +4707,7 @@ function createAskUserCapability() {
4691
4707
  text: `Error: ${normalized.error}. Use one of these shapes: {"question":"Choose a color","options":["Red","Blue","Green"]} or {"prompt":"Choose a color","options":["Red","Blue","Green"]} or {"questions":[{"question":"Choose a color","options":["Red","Blue","Green"]},{"question":"Describe why"}],"allowReview":true}`
4692
4708
  }
4693
4709
  ],
4710
+ details: { error: normalized.error },
4694
4711
  isError: true
4695
4712
  };
4696
4713
  }
@@ -4704,6 +4721,7 @@ function createAskUserCapability() {
4704
4721
  text: `Error: ${validationError}. Use one of these shapes: {"question":"Choose a color","options":["Red","Blue","Green"]} or {"prompt":"Choose a color","options":["Red","Blue","Green"]} or {"questions":["Choose a color|Red|Blue|Green","Describe why"],"allowReview":true}`
4705
4722
  }
4706
4723
  ],
4724
+ details: { error: validationError },
4707
4725
  isError: true
4708
4726
  };
4709
4727
  }
@@ -5007,11 +5025,11 @@ function formatCapabilityPolicySummary(tools, context = {}) {
5007
5025
  import * as nodePath from "node:path";
5008
5026
 
5009
5027
  // ../../packages/shared-headless-capabilities/src/builtin/fs/path-utils.ts
5010
- function isInAllowlist(path9, allowlistedDirs) {
5028
+ function isInAllowlist(path10, allowlistedDirs) {
5011
5029
  if (allowlistedDirs.some((dir) => isGlobalFilesystemSentinel(dir))) {
5012
5030
  return true;
5013
5031
  }
5014
- const normalized = normalizeForComparison(path9);
5032
+ const normalized = normalizeForComparison(path10);
5015
5033
  for (const dir of allowlistedDirs) {
5016
5034
  const normalizedDir = normalizeForComparison(dir);
5017
5035
  const dirWithSlash = withTrailingSep(normalizedDir);
@@ -5021,19 +5039,19 @@ function isInAllowlist(path9, allowlistedDirs) {
5021
5039
  }
5022
5040
  return false;
5023
5041
  }
5024
- function normalizeForComparison(path9) {
5025
- const slashNormalized = path9.replace(/\\/g, "/");
5042
+ function normalizeForComparison(path10) {
5043
+ const slashNormalized = path10.replace(/\\/g, "/");
5026
5044
  const isWindowsPath = /^[a-zA-Z]:($|\/)/.test(slashNormalized) || /^\/{2}[^/]+\/[^/]+/.test(slashNormalized);
5027
5045
  const normalized = slashNormalized.replace(/\/+/g, "/");
5028
5046
  if (normalized === "/") return normalized;
5029
5047
  const trimmed = normalized.replace(/\/+$/, "");
5030
5048
  return isWindowsPath ? trimmed.toLowerCase() : trimmed;
5031
5049
  }
5032
- function isGlobalFilesystemSentinel(path9) {
5033
- return normalizeForComparison(String(path9 || "").trim()) === "/";
5050
+ function isGlobalFilesystemSentinel(path10) {
5051
+ return normalizeForComparison(String(path10 || "").trim()) === "/";
5034
5052
  }
5035
- function isAbsoluteUserPath(path9) {
5036
- const normalized = path9.replace(/\\/g, "/");
5053
+ function isAbsoluteUserPath(path10) {
5054
+ const normalized = path10.replace(/\\/g, "/");
5037
5055
  return /^[a-zA-Z]:\//.test(normalized) || /^\/{2}[^/]+\/[^/]+/.test(normalized);
5038
5056
  }
5039
5057
  function validateToolPathArgument(filePath) {
@@ -5048,65 +5066,65 @@ function validateToolPathArgument(filePath) {
5048
5066
  throw new Error(`Invalid path "${filePath}". The path argument must be a single file path, not multi-line text.`);
5049
5067
  }
5050
5068
  }
5051
- function withTrailingSep(path9) {
5052
- return path9.endsWith("/") ? path9 : `${path9}/`;
5069
+ function withTrailingSep(path10) {
5070
+ return path10.endsWith("/") ? path10 : `${path10}/`;
5053
5071
  }
5054
- function isWithinRoot(path9, root) {
5072
+ function isWithinRoot(path10, root) {
5055
5073
  if (isGlobalFilesystemSentinel(root)) {
5056
5074
  return true;
5057
5075
  }
5058
- const normalizedPath = normalizeForComparison(path9);
5076
+ const normalizedPath = normalizeForComparison(path10);
5059
5077
  const normalizedRoot = normalizeForComparison(root);
5060
5078
  return normalizedPath === normalizedRoot || normalizedPath.startsWith(withTrailingSep(normalizedRoot));
5061
5079
  }
5062
5080
  function getAccessRoots(sandboxRoot, options) {
5063
- const fs7 = getFileSystem();
5081
+ const fs8 = getFileSystem();
5064
5082
  const roots = /* @__PURE__ */ new Set();
5065
- roots.add(fs7.normalize(sandboxRoot));
5083
+ roots.add(fs8.normalize(sandboxRoot));
5066
5084
  if (options?.accessRoot) {
5067
- roots.add(fs7.normalize(options.accessRoot));
5085
+ roots.add(fs8.normalize(options.accessRoot));
5068
5086
  }
5069
5087
  for (const root of options?.accessRoots ?? []) {
5070
5088
  const trimmed = String(root || "").trim();
5071
5089
  if (trimmed) {
5072
- roots.add(fs7.normalize(trimmed));
5090
+ roots.add(fs8.normalize(trimmed));
5073
5091
  }
5074
5092
  }
5075
5093
  return Array.from(roots);
5076
5094
  }
5077
- function isWithinAnyRoot(path9, roots) {
5078
- if (roots.some((root) => isWithinRoot(path9, root))) return true;
5079
- const fs7 = getFileSystem();
5080
- if (!fs7.realpathSync) return false;
5081
- const canonical = canonicalizeExistingPath(path9);
5095
+ function isWithinAnyRoot(path10, roots) {
5096
+ if (roots.some((root) => isWithinRoot(path10, root))) return true;
5097
+ const fs8 = getFileSystem();
5098
+ if (!fs8.realpathSync) return false;
5099
+ const canonical = canonicalizeExistingPath(path10);
5082
5100
  return roots.some((root) => isWithinRoot(canonical, canonicalizeExistingPath(root)));
5083
5101
  }
5084
5102
  function canonicalizeExistingPath(pathValue) {
5085
- const fs7 = getFileSystem();
5086
- if (!fs7.realpathSync) return fs7.normalize(pathValue);
5087
- let cursor = fs7.normalize(pathValue);
5103
+ const fs8 = getFileSystem();
5104
+ if (!fs8.realpathSync) return fs8.normalize(pathValue);
5105
+ let cursor = fs8.normalize(pathValue);
5088
5106
  const suffix = [];
5089
- while (!fs7.existsSync(cursor)) {
5090
- if (fs7.lstatSync) {
5107
+ while (!fs8.existsSync(cursor)) {
5108
+ if (fs8.lstatSync) {
5091
5109
  try {
5092
- if (fs7.lstatSync(cursor).isSymbolicLink) {
5110
+ if (fs8.lstatSync(cursor).isSymbolicLink) {
5093
5111
  throw new Error(`Path contains an unresolved symbolic link: ${cursor}`);
5094
5112
  }
5095
5113
  } catch (error) {
5096
5114
  if (error instanceof Error && error.message.startsWith("Path contains an unresolved symbolic link:")) throw error;
5097
5115
  }
5098
5116
  }
5099
- const parent = fs7.dirname(cursor);
5100
- if (parent === cursor) return fs7.normalize(pathValue);
5101
- suffix.unshift(fs7.basename(cursor));
5117
+ const parent = fs8.dirname(cursor);
5118
+ if (parent === cursor) return fs8.normalize(pathValue);
5119
+ suffix.unshift(fs8.basename(cursor));
5102
5120
  cursor = parent;
5103
5121
  }
5104
- const canonicalBase = fs7.normalize(fs7.realpathSync(cursor));
5105
- return suffix.length > 0 ? fs7.resolve(canonicalBase, ...suffix) : canonicalBase;
5122
+ const canonicalBase = fs8.normalize(fs8.realpathSync(cursor));
5123
+ return suffix.length > 0 ? fs8.resolve(canonicalBase, ...suffix) : canonicalBase;
5106
5124
  }
5107
5125
  function finalizeResolvedPath(resolved, sandboxRoot, options) {
5108
- const fs7 = getFileSystem();
5109
- if (!fs7.realpathSync || !fs7.isAbsolute(resolved)) return resolved;
5126
+ const fs8 = getFileSystem();
5127
+ if (!fs8.realpathSync || !fs8.isAbsolute(resolved)) return resolved;
5110
5128
  const allowlistedDirs = options?.allowlistedDirs ?? [];
5111
5129
  if (allowlistedDirs.some((dir) => isGlobalFilesystemSentinel(dir))) return resolved;
5112
5130
  const canonical = canonicalizeExistingPath(resolved);
@@ -5128,7 +5146,7 @@ function getAvailableRoots(options) {
5128
5146
  if (!options?.roots || options.roots.length === 0) {
5129
5147
  return [];
5130
5148
  }
5131
- const fs7 = getFileSystem();
5149
+ const fs8 = getFileSystem();
5132
5150
  const seen = /* @__PURE__ */ new Set();
5133
5151
  const results = [];
5134
5152
  for (const root of options.roots) {
@@ -5136,14 +5154,14 @@ function getAvailableRoots(options) {
5136
5154
  continue;
5137
5155
  }
5138
5156
  const name = root.name.trim();
5139
- const path9 = root.path.trim();
5140
- if (!name || !path9 || seen.has(name)) {
5157
+ const path10 = root.path.trim();
5158
+ if (!name || !path10 || seen.has(name)) {
5141
5159
  continue;
5142
5160
  }
5143
5161
  seen.add(name);
5144
5162
  results.push({
5145
5163
  name,
5146
- path: fs7.normalize(path9),
5164
+ path: fs8.normalize(path10),
5147
5165
  description: root.description?.trim() || void 0,
5148
5166
  defaultPrefixes: Array.isArray(root.defaultPrefixes) ? root.defaultPrefixes.map((prefix) => String(prefix || "").trim()).filter((prefix) => prefix.length > 0) : void 0
5149
5167
  });
@@ -5198,7 +5216,7 @@ function getResolutionRoot(filePath, sandboxRoot, options, rootName) {
5198
5216
  return findPrefixMatchedRoot(filePath, options) ?? getRootByName(void 0, sandboxRoot, options);
5199
5217
  }
5200
5218
  function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
5201
- const fs7 = getFileSystem();
5219
+ const fs8 = getFileSystem();
5202
5220
  const allowlistedDirs = options?.allowlistedDirs ?? [];
5203
5221
  const accessRoots = getAccessRoots(sandboxRoot, options);
5204
5222
  if (!filePath) {
@@ -5206,8 +5224,8 @@ function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
5206
5224
  }
5207
5225
  validateToolPathArgument(filePath);
5208
5226
  const cleaned = filePath.trim().startsWith("@") ? filePath.trim().slice(1) : filePath.trim();
5209
- if (fs7.isAbsolute(cleaned) || isAbsoluteUserPath(cleaned)) {
5210
- const normalized = fs7.normalize(cleaned);
5227
+ if (fs8.isAbsolute(cleaned) || isAbsoluteUserPath(cleaned)) {
5228
+ const normalized = fs8.normalize(cleaned);
5211
5229
  const selectedRoot2 = rootName ? getRootByName(rootName, sandboxRoot, options) : void 0;
5212
5230
  if (rootName && !selectedRoot2) {
5213
5231
  const available = getAvailableRoots(options).map((root) => root.name).join(", ");
@@ -5242,7 +5260,7 @@ function resolveInSandbox(filePath, sandboxRoot, options, rootName) {
5242
5260
  );
5243
5261
  }
5244
5262
  const resolvedBase = selectedRoot?.path ?? sandboxRoot;
5245
- const resolved = fs7.resolve(resolvedBase, cleaned);
5263
+ const resolved = fs8.resolve(resolvedBase, cleaned);
5246
5264
  if (selectedRoot) {
5247
5265
  if (!isWithinAnyRoot(resolved, [selectedRoot.path])) {
5248
5266
  throw new Error(`Path escapes root '${selectedRoot.name}': ${filePath}`);
@@ -5780,7 +5798,7 @@ function createReadErrorResult(message, details) {
5780
5798
  };
5781
5799
  }
5782
5800
  function createReadTool(cwd, options) {
5783
- const fs7 = getFileSystem();
5801
+ const fs8 = getFileSystem();
5784
5802
  const fileObservationState = options?.fileObservationState ?? createFileObservationState();
5785
5803
  const callerObservations = /* @__PURE__ */ new WeakMap();
5786
5804
  const rootSchema = buildRootParameterSchema(cwd, options);
@@ -5798,8 +5816,9 @@ function createReadTool(cwd, options) {
5798
5816
  label: "read",
5799
5817
  description: `Read a file's contents. Use this before editing, and use offset/limit for large files, or tail=N to read the last N lines when the line count is unknown. Images are attached for the current model when it supports vision; otherwise a configured file-understanding service analyzes them. Video, audio, and documents require a configured understanding service. Pass question to specify what to focus on; it does not force a separate model request. Example: read_file path='Scripts/PlayerController.cs' or read_file path='Data/config.json'. ${pathResolutionDescription} For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). When you need the full file, continue with a larger offset until complete.`,
5800
5818
  parameters: readSchema,
5801
- execute: async (_toolCallId, params, signal, _onUpdate) => {
5802
- const { path: path9, root, question } = params;
5819
+ execute: async (_toolCallId, rawParams, signal, _onUpdate) => {
5820
+ const params = rawParams ?? {};
5821
+ const { path: path10, root, question } = params;
5803
5822
  const tail = params.tail;
5804
5823
  let offset = params.offset;
5805
5824
  let limit = params.limit;
@@ -5820,7 +5839,7 @@ function createReadTool(cwd, options) {
5820
5839
  }
5821
5840
  let absolutePath;
5822
5841
  try {
5823
- absolutePath = resolveReadPath(path9, cwd, options, root);
5842
+ absolutePath = resolveReadPath(path10, cwd, options, root);
5824
5843
  } catch (error) {
5825
5844
  const message = error instanceof Error ? error.message : String(error);
5826
5845
  if (/outside sandbox|outside root|escapes sandbox/i.test(message)) {
@@ -5831,7 +5850,7 @@ function createReadTool(cwd, options) {
5831
5850
  return createReadErrorResult(message);
5832
5851
  }
5833
5852
  return new Promise(
5834
- (resolve5, reject) => {
5853
+ (resolve6, reject) => {
5835
5854
  if (signal?.aborted) {
5836
5855
  reject(new Error("Operation aborted"));
5837
5856
  return;
@@ -5846,26 +5865,26 @@ function createReadTool(cwd, options) {
5846
5865
  }
5847
5866
  (async () => {
5848
5867
  try {
5849
- await fs7.access(absolutePath);
5868
+ await fs8.access(absolutePath);
5850
5869
  if (isSpecialDevicePath(absolutePath)) {
5851
5870
  throw new Error(`Refusing to read special device path: ${absolutePath}`);
5852
5871
  }
5853
- const stat = await fs7.stat(absolutePath);
5872
+ const stat = await fs8.stat(absolutePath);
5854
5873
  if (!stat.isFile) {
5855
5874
  throw new Error(`Refusing to read non-regular file: ${absolutePath}`);
5856
5875
  }
5857
5876
  if (aborted) return;
5858
- const prefix = await fs7.readFilePrefix(absolutePath, BINARY_MAGIC_PREFIX_BYTES);
5877
+ const prefix = await fs8.readFilePrefix(absolutePath, BINARY_MAGIC_PREFIX_BYTES);
5859
5878
  const magicInfo = detectBinaryMagic(prefix);
5860
5879
  let binaryInfo = detectBinaryKind(absolutePath);
5861
5880
  if (options?.allowBinary === false) {
5862
5881
  binaryInfo = detectTextOnlyBinary(prefix, absolutePath, stat.size > prefix.length);
5863
5882
  }
5864
5883
  if (options?.allowBinary === false && binaryInfo) {
5865
- resolve5({
5884
+ resolve6({
5866
5885
  content: [{
5867
5886
  type: "text",
5868
- text: `Cannot read ${binaryInfo.kind} file ${path9}: this read_file instance accepts text files only.`
5887
+ text: `Cannot read ${binaryInfo.kind} file ${path10}: this read_file instance accepts text files only.`
5869
5888
  }],
5870
5889
  details: {
5871
5890
  understanding: {
@@ -5879,9 +5898,9 @@ function createReadTool(cwd, options) {
5879
5898
  return;
5880
5899
  }
5881
5900
  if (magicInfo?.kind === "image" && options?.understandFile && (!INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) || stat.size > MAX_INLINE_IMAGE_BYTES)) {
5882
- resolve5(await options.understandFile({
5901
+ resolve6(await options.understandFile({
5883
5902
  absolutePath,
5884
- displayPath: path9,
5903
+ displayPath: path10,
5885
5904
  mimeType: magicInfo.mimeType,
5886
5905
  kind: "image",
5887
5906
  question,
@@ -5890,14 +5909,14 @@ function createReadTool(cwd, options) {
5890
5909
  return;
5891
5910
  }
5892
5911
  if (magicInfo?.kind === "image" && INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) && stat.size > MAX_INLINE_IMAGE_BYTES) {
5893
- throw new Error(`Image file ${path9} is too large to attach (${formatSize(stat.size)}; maximum ${formatSize(MAX_INLINE_IMAGE_BYTES)}).`);
5912
+ throw new Error(`Image file ${path10} is too large to attach (${formatSize(stat.size)}; maximum ${formatSize(MAX_INLINE_IMAGE_BYTES)}).`);
5894
5913
  }
5895
- const imageInfo = options?.allowBinary === false || magicInfo?.kind !== "image" || !INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) ? void 0 : await readImageInfo(absolutePath, fs7);
5914
+ const imageInfo = options?.allowBinary === false || magicInfo?.kind !== "image" || !INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType) ? void 0 : await readImageInfo(absolutePath, fs8);
5896
5915
  if (imageInfo) {
5897
5916
  if (options?.understandFile) {
5898
- resolve5(await options.understandFile({
5917
+ resolve6(await options.understandFile({
5899
5918
  absolutePath,
5900
- displayPath: path9,
5919
+ displayPath: path10,
5901
5920
  mimeType: imageInfo.mimeType,
5902
5921
  kind: "image",
5903
5922
  question,
@@ -5907,7 +5926,7 @@ function createReadTool(cwd, options) {
5907
5926
  return;
5908
5927
  }
5909
5928
  const dimensionText = imageInfo.width && imageInfo.height ? `, ${imageInfo.width}x${imageInfo.height}` : "";
5910
- resolve5({
5929
+ resolve6({
5911
5930
  content: [
5912
5931
  { type: "text", text: `Read image file [${imageInfo.mimeType}${dimensionText}]. Original image attached as an image block; for very large images, prefer a smaller crop or resized copy before rereading.${question?.trim() ? `
5913
5932
  Focus: ${question.trim()}` : ""}` },
@@ -5925,8 +5944,8 @@ Focus: ${question.trim()}` : ""}` },
5925
5944
  }
5926
5945
  if (magicInfo?.kind === "image") {
5927
5946
  const inlineSupported = INLINE_IMAGE_MIME_TYPES.has(magicInfo.mimeType);
5928
- resolve5({
5929
- content: [{ type: "text", text: inlineSupported ? `Cannot attach image file ${path9}: the host filesystem bridge returned no usable image data for ${magicInfo.mimeType} (see logs for readImageInfo diagnostics).` : `Cannot attach image file ${path9}: unsupported image payload ${magicInfo.mimeType}.` }],
5947
+ resolve6({
5948
+ content: [{ type: "text", text: inlineSupported ? `Cannot attach image file ${path10}: the host filesystem bridge returned no usable image data for ${magicInfo.mimeType} (see logs for readImageInfo diagnostics).` : `Cannot attach image file ${path10}: unsupported image payload ${magicInfo.mimeType}.` }],
5930
5949
  details: { understanding: { kind: "image", mimeType: magicInfo.mimeType, fallbackReason: inlineSupported ? "image bridge read failed" : "unsupported inline image format" } },
5931
5950
  isError: true
5932
5951
  });
@@ -5934,9 +5953,9 @@ Focus: ${question.trim()}` : ""}` },
5934
5953
  }
5935
5954
  const mediaInfo = magicInfo ?? detectUnderstandingKind(absolutePath);
5936
5955
  if (mediaInfo && options?.understandFile) {
5937
- resolve5(await options.understandFile({
5956
+ resolve6(await options.understandFile({
5938
5957
  absolutePath,
5939
- displayPath: path9,
5958
+ displayPath: path10,
5940
5959
  mimeType: mediaInfo.mimeType,
5941
5960
  kind: mediaInfo.kind,
5942
5961
  question,
@@ -5945,10 +5964,10 @@ Focus: ${question.trim()}` : ""}` },
5945
5964
  return;
5946
5965
  }
5947
5966
  if (mediaInfo) {
5948
- resolve5({
5967
+ resolve6({
5949
5968
  content: [{
5950
5969
  type: "text",
5951
- text: `Cannot read ${mediaInfo.kind} file ${path9} semantically: no media understanding handler is configured for ${mediaInfo.mimeType}.`
5970
+ text: `Cannot read ${mediaInfo.kind} file ${path10} semantically: no media understanding handler is configured for ${mediaInfo.mimeType}.`
5952
5971
  }],
5953
5972
  details: {
5954
5973
  understanding: {
@@ -5963,10 +5982,10 @@ Focus: ${question.trim()}` : ""}` },
5963
5982
  }
5964
5983
  const textBinaryInfo = detectTextOnlyBinary(prefix, absolutePath, stat.size > prefix.length);
5965
5984
  if (textBinaryInfo) {
5966
- resolve5({
5985
+ resolve6({
5967
5986
  content: [{
5968
5987
  type: "text",
5969
- text: `Cannot read binary file ${path9}: ${textBinaryInfo.mimeType}. Use a file-understanding handler for supported media/documents, or inspect metadata with a bounded shell command.`
5988
+ text: `Cannot read binary file ${path10}: ${textBinaryInfo.mimeType}. Use a file-understanding handler for supported media/documents, or inspect metadata with a bounded shell command.`
5970
5989
  }],
5971
5990
  details: {
5972
5991
  understanding: {
@@ -5988,7 +6007,7 @@ Focus: ${question.trim()}` : ""}` },
5988
6007
  const effectiveTail = Math.max(1, Math.min(tail, DEFAULT_MAX_LINES - 1));
5989
6008
  translatedFromTail = true;
5990
6009
  tailEffectiveLines = effectiveTail;
5991
- range2 = await fs7.readTextRange(absolutePath, {
6010
+ range2 = await fs8.readTextRange(absolutePath, {
5992
6011
  tailLines: effectiveTail,
5993
6012
  maxOutputLines: DEFAULT_MAX_LINES,
5994
6013
  maxOutputBytes: DEFAULT_MAX_BYTES
@@ -6003,7 +6022,7 @@ Focus: ${question.trim()}` : ""}` },
6003
6022
  }
6004
6023
  } else {
6005
6024
  startLine = offset === void 0 ? 0 : offset - 1;
6006
- range2 = await fs7.readTextRange(absolutePath, {
6025
+ range2 = await fs8.readTextRange(absolutePath, {
6007
6026
  offsetLine: startLine,
6008
6027
  limitLines: limit,
6009
6028
  maxOutputLines: DEFAULT_MAX_LINES,
@@ -6015,8 +6034,8 @@ Focus: ${question.trim()}` : ""}` },
6015
6034
  const selectedLooksBinary = range2.selectedBytesLookBinary ?? (looksLikeBinaryText(range2.content) || range2.content.includes("\uFFFD"));
6016
6035
  const selectedBinary = selectedLooksBinary ? { kind: "document", mimeType: "application/octet-stream" } : void 0;
6017
6036
  if (selectedBinary) {
6018
- resolve5({
6019
- content: [{ type: "text", text: `Cannot read ${selectedBinary.kind} file ${path9}: this read_file instance accepts text files only.` }],
6037
+ resolve6({
6038
+ content: [{ type: "text", text: `Cannot read ${selectedBinary.kind} file ${path10}: this read_file instance accepts text files only.` }],
6020
6039
  details: { understanding: { ...selectedBinary, fallbackReason: "binary content is disabled for this tool" } },
6021
6040
  isError: true
6022
6041
  });
@@ -6069,7 +6088,7 @@ Focus: ${question.trim()}` : ""}` },
6069
6088
  if (signal) {
6070
6089
  signal.removeEventListener("abort", onAbort);
6071
6090
  }
6072
- resolve5({
6091
+ resolve6({
6073
6092
  content: [{
6074
6093
  type: "text",
6075
6094
  text: translatedFromTail ? `File unchanged since previous tail=${tailEffectiveLines} read (last ${tailWindowIncludesPhantom ? range2.selectedLines - 1 : range2.selectedLines} lines, ${range2.totalLines} lines total). Earlier reads still count toward write_file coverage of this file.` : `File unchanged since previous read of this range (offset=${startLineDisplay}${limit === void 0 ? ", no limit" : `, limit=${limit}`}). Earlier reads still count toward write_file coverage of this file. Use a different offset/limit if you need another section.`
@@ -6167,7 +6186,7 @@ Base directory: ${nodePath.dirname(absolutePath)}
6167
6186
  if (signal) {
6168
6187
  signal.removeEventListener("abort", onAbort);
6169
6188
  }
6170
- resolve5({
6189
+ resolve6({
6171
6190
  content: textContent,
6172
6191
  details
6173
6192
  });
@@ -6178,7 +6197,7 @@ Base directory: ${nodePath.dirname(absolutePath)}
6178
6197
  reject(error);
6179
6198
  return;
6180
6199
  }
6181
- resolve5(createReadErrorResult(message, { path: absolutePath }));
6200
+ resolve6(createReadErrorResult(message, { path: absolutePath }));
6182
6201
  }
6183
6202
  } finally {
6184
6203
  signal?.removeEventListener("abort", onAbort);
@@ -6189,8 +6208,8 @@ Base directory: ${nodePath.dirname(absolutePath)}
6189
6208
  }
6190
6209
  };
6191
6210
  }
6192
- function isSpecialDevicePath(path9) {
6193
- const normalized = nodePath.resolve(path9).replace(/\\/g, "/");
6211
+ function isSpecialDevicePath(path10) {
6212
+ const normalized = nodePath.resolve(path10).replace(/\\/g, "/");
6194
6213
  return /^\/dev\/(?:zero|random|urandom|full|stdin|stdout|stderr|tty|console)$/.test(normalized) || /^\/dev\/fd\/[0-2]$/.test(normalized) || /^\/proc\/(?:self|\d+)\/fd\/[0-2]$/.test(normalized);
6195
6214
  }
6196
6215
  function detectUnderstandingKind(filePath) {
@@ -6331,22 +6350,22 @@ function detectTextOnlyBinary(input, filePath, prefixMayBeTruncated) {
6331
6350
  if (!looksLikeBinary(input, prefixMayBeTruncated)) return void 0;
6332
6351
  return detectBinaryKind(filePath) ?? { kind: "document", mimeType: "application/octet-stream" };
6333
6352
  }
6334
- async function readImageInfo(path9, fs7) {
6353
+ async function readImageInfo(path10, fs8) {
6335
6354
  try {
6336
6355
  let base64 = "";
6337
- if (typeof fs7.readFile === "function") {
6338
- base64 = await fs7.readFile(path9, "base64").catch(() => "");
6356
+ if (typeof fs8.readFile === "function") {
6357
+ base64 = await fs8.readFile(path10, "base64").catch(() => "");
6339
6358
  }
6340
- if (!base64 && typeof fs7.readFileSync === "function") {
6341
- base64 = fs7.readFileSync(path9, "base64");
6359
+ if (!base64 && typeof fs8.readFileSync === "function") {
6360
+ base64 = fs8.readFileSync(path10, "base64");
6342
6361
  }
6343
6362
  if (!base64) {
6344
- console.error(`[pie] readImageInfo got empty base64 for ${path9}`);
6363
+ console.error(`[pie] readImageInfo got empty base64 for ${path10}`);
6345
6364
  return void 0;
6346
6365
  }
6347
6366
  const bytes = decodeBase64ToBytes(base64);
6348
6367
  if (bytes.length === 0) {
6349
- console.error(`[pie] readImageInfo decoded 0 bytes for ${path9} (base64 length ${base64.length})`);
6368
+ console.error(`[pie] readImageInfo decoded 0 bytes for ${path10} (base64 length ${base64.length})`);
6350
6369
  return void 0;
6351
6370
  }
6352
6371
  const pngMagic = [137, 80, 78, 71, 13, 10, 26, 10];
@@ -6365,10 +6384,10 @@ async function readImageInfo(path9, fs7) {
6365
6384
  if (bytes.length >= 12 && asciiAt(bytes, 0, 4) === "RIFF" && asciiAt(bytes, 8, 12 - 8) === "WEBP") {
6366
6385
  return { mimeType: "image/webp", base64, ...parseWebpDimensions(bytes) };
6367
6386
  }
6368
- console.error(`[pie] readImageInfo decoded ${bytes.length} bytes for ${path9} but no known image signature matched`);
6387
+ console.error(`[pie] readImageInfo decoded ${bytes.length} bytes for ${path10} but no known image signature matched`);
6369
6388
  return void 0;
6370
6389
  } catch (error) {
6371
- console.error(`[pie] readImageInfo failed for ${path9}: ${error instanceof Error ? error.message : String(error)}`);
6390
+ console.error(`[pie] readImageInfo failed for ${path10}: ${error instanceof Error ? error.message : String(error)}`);
6372
6391
  return void 0;
6373
6392
  }
6374
6393
  return void 0;
@@ -6500,7 +6519,7 @@ function parseWebpDimensions(bytes) {
6500
6519
 
6501
6520
  // ../../packages/shared-headless-capabilities/src/builtin/fs/write.ts
6502
6521
  function createWriteTool(cwd, options) {
6503
- const fs7 = getFileSystem();
6522
+ const fs8 = getFileSystem();
6504
6523
  const usesExternalFileObservationState = !!options?.fileObservationState;
6505
6524
  const fileObservationState = options?.fileObservationState ?? createFileObservationState();
6506
6525
  const rootSchema = buildRootParameterSchema(cwd, options);
@@ -6515,12 +6534,12 @@ function createWriteTool(cwd, options) {
6515
6534
  label: "write",
6516
6535
  description: `Write complete file contents. Use this to create a new file, or to intentionally replace an entire existing file after reading the latest full file with read_file. Do not use for targeted edits to existing files; use edit_file instead. For existing files, omitted content will be deleted. Automatically creates parent directories. ${pathResolutionDescription}`,
6517
6536
  parameters: writeSchema,
6518
- execute: async (_toolCallId, params, signal) => {
6519
- const { path: filePath, root, content } = params;
6537
+ execute: async (_toolCallId, rawParams, signal) => {
6538
+ const { path: filePath, root, content } = rawParams ?? {};
6520
6539
  const absolutePath = resolveToCwd(filePath, cwd, options, root);
6521
- const dir = fs7.dirname(absolutePath);
6540
+ const dir = fs8.dirname(absolutePath);
6522
6541
  return new Promise(
6523
- (resolve5, reject) => {
6542
+ (resolve6, reject) => {
6524
6543
  if (signal?.aborted) {
6525
6544
  reject(new Error("Operation aborted"));
6526
6545
  return;
@@ -6535,18 +6554,18 @@ function createWriteTool(cwd, options) {
6535
6554
  }
6536
6555
  (async () => {
6537
6556
  try {
6538
- await fs7.mkdir(dir, { recursive: true });
6557
+ await fs8.mkdir(dir, { recursive: true });
6539
6558
  if (aborted) return;
6540
6559
  let fileExists = false;
6541
6560
  try {
6542
- const stat = await fs7.stat(absolutePath);
6561
+ const stat = await fs8.stat(absolutePath);
6543
6562
  fileExists = stat.isFile;
6544
6563
  } catch {
6545
6564
  fileExists = false;
6546
6565
  }
6547
6566
  if (fileExists) {
6548
- const currentContent = String(await fs7.readFile(absolutePath, "utf-8"));
6549
- const currentStat = await fs7.stat(absolutePath);
6567
+ const currentContent = String(await fs8.readFile(absolutePath, "utf-8"));
6568
+ const currentStat = await fs8.stat(absolutePath);
6550
6569
  const currentSnapshot = snapshotFromStatAndContent(currentStat, currentContent);
6551
6570
  const observedSnapshot = fileObservationState.getCompleteTextSnapshot(absolutePath);
6552
6571
  if (!observedSnapshot) {
@@ -6562,8 +6581,8 @@ function createWriteTool(cwd, options) {
6562
6581
  );
6563
6582
  }
6564
6583
  }
6565
- await fs7.writeFile(absolutePath, content, "utf-8");
6566
- const writtenStat = await fs7.stat(absolutePath);
6584
+ await fs8.writeFile(absolutePath, content, "utf-8");
6585
+ const writtenStat = await fs8.stat(absolutePath);
6567
6586
  fileObservationState.recordCompleteTextWrite(
6568
6587
  absolutePath,
6569
6588
  snapshotFromStatAndContent(writtenStat, content)
@@ -6572,7 +6591,7 @@ function createWriteTool(cwd, options) {
6572
6591
  if (signal) {
6573
6592
  signal.removeEventListener("abort", onAbort);
6574
6593
  }
6575
- resolve5({
6594
+ resolve6({
6576
6595
  content: [{ type: "text", text: `Successfully wrote ${writtenStat.size} bytes to ${filePath}` }],
6577
6596
  details: void 0
6578
6597
  });
@@ -6691,16 +6710,16 @@ var Diff = class {
6691
6710
  }
6692
6711
  }
6693
6712
  }
6694
- addToPath(path9, added, removed, oldPosInc, options) {
6695
- const last = path9.lastComponent;
6713
+ addToPath(path10, added, removed, oldPosInc, options) {
6714
+ const last = path10.lastComponent;
6696
6715
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
6697
6716
  return {
6698
- oldPos: path9.oldPos + oldPosInc,
6717
+ oldPos: path10.oldPos + oldPosInc,
6699
6718
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
6700
6719
  };
6701
6720
  } else {
6702
6721
  return {
6703
- oldPos: path9.oldPos + oldPosInc,
6722
+ oldPos: path10.oldPos + oldPosInc,
6704
6723
  lastComponent: { count: 1, added, removed, previousComponent: last }
6705
6724
  };
6706
6725
  }
@@ -7572,8 +7591,8 @@ function generateDiffString(oldContent, newContent, contextLines = 4) {
7572
7591
  var MAX_EDIT_BLOCKS = 64;
7573
7592
  var MAX_EDIT_INPUT_CHARS = 256 * 1024;
7574
7593
  function validateEditArgs(params) {
7575
- const { path: path9, oldText, newText, replaceAll, edits } = params;
7576
- const filePath = typeof path9 === "string" ? path9.trim() : "";
7594
+ const { path: path10, oldText, newText, replaceAll, edits } = params;
7595
+ const filePath = typeof path10 === "string" ? path10.trim() : "";
7577
7596
  if (!filePath) {
7578
7597
  throw new Error("Invalid edit_file arguments: path cannot be empty. Pass the file path in path and the exact text to replace in oldText.");
7579
7598
  }
@@ -7655,14 +7674,14 @@ function createEditErrorResult(params) {
7655
7674
  isError: true
7656
7675
  };
7657
7676
  }
7658
- function createEditThrownErrorResult(message, path9) {
7677
+ function createEditThrownErrorResult(message, path10) {
7659
7678
  return {
7660
7679
  content: [{ type: "text", text: boundEditOutput(`edit_file failed: ${message}`).text }],
7661
7680
  details: {
7662
7681
  status: "error",
7663
7682
  matchKind: "none",
7664
7683
  changed: false,
7665
- path: path9,
7684
+ path: path10,
7666
7685
  diff: "",
7667
7686
  oldTextOccurrences: 0,
7668
7687
  newTextOccurrences: 0,
@@ -7675,7 +7694,7 @@ function createEditThrownErrorResult(message, path9) {
7675
7694
  };
7676
7695
  }
7677
7696
  function createEditTool(cwd, options) {
7678
- const fs7 = getFileSystem();
7697
+ const fs8 = getFileSystem();
7679
7698
  const fileObservationState = options?.fileObservationState ?? createFileObservationState();
7680
7699
  const usesExternalFileObservationState = !!options?.fileObservationState;
7681
7700
  const rootSchema = buildRootParameterSchema(cwd, options);
@@ -7698,18 +7717,19 @@ function createEditTool(cwd, options) {
7698
7717
  label: "edit",
7699
7718
  description: `Make precise exact-text replacements in one file. For multiple changes in the same file, put all replacements in one edits[] call \u2014 they apply in order, so later edits can target what earlier ones just changed. ${pathResolutionDescription}`,
7700
7719
  parameters: editSchema,
7701
- execute: async (_toolCallId, params, signal) => {
7702
- const { path: path9, root } = params;
7720
+ execute: async (_toolCallId, rawParams, signal) => {
7721
+ const params = rawParams ?? {};
7722
+ const { path: path10, root } = params;
7703
7723
  let replacements;
7704
7724
  let absolutePath;
7705
7725
  try {
7706
7726
  replacements = validateEditArgs(params);
7707
- absolutePath = resolveToCwd(path9, cwd, options, root);
7727
+ absolutePath = resolveToCwd(path10, cwd, options, root);
7708
7728
  } catch (error) {
7709
7729
  const message = error instanceof Error ? error.message : String(error);
7710
- return createEditThrownErrorResult(message, typeof path9 === "string" ? path9 : void 0);
7730
+ return createEditThrownErrorResult(message, typeof path10 === "string" ? path10 : void 0);
7711
7731
  }
7712
- return new Promise((resolve5, reject) => {
7732
+ return new Promise((resolve6, reject) => {
7713
7733
  if (signal?.aborted) {
7714
7734
  reject(new Error("Operation aborted"));
7715
7735
  return;
@@ -7730,10 +7750,10 @@ function createEditTool(cwd, options) {
7730
7750
  if (aborted || signal?.aborted) throw new Error("Operation aborted");
7731
7751
  };
7732
7752
  try {
7733
- await fs7.access(absolutePath);
7753
+ await fs8.access(absolutePath);
7734
7754
  } catch {
7735
7755
  if (signal) signal.removeEventListener("abort", onAbort);
7736
- resolve5(createEditThrownErrorResult(`File not found: ${path9}`, path9));
7756
+ resolve6(createEditThrownErrorResult(`File not found: ${path10}`, path10));
7737
7757
  return;
7738
7758
  }
7739
7759
  throwIfAborted();
@@ -7744,8 +7764,8 @@ function createEditTool(cwd, options) {
7744
7764
  const lastClear = fileObservationState.getLastClear?.();
7745
7765
  const resetNote = lastClear ? ` Note: the session's read ledger was reset by ${lastClear.reason} at ${new Date(lastClear.timestamp).toISOString()} \u2014 if you read this file before that reset, its content is no longer in your context and must be re-read.` : "";
7746
7766
  if (signal) signal.removeEventListener("abort", onAbort);
7747
- resolve5(createEditErrorResult({
7748
- message: `edit_file blocked: ${path9} has not been read in this session.${resetNote}`,
7767
+ resolve6(createEditErrorResult({
7768
+ message: `edit_file blocked: ${path10} has not been read in this session.${resetNote}`,
7749
7769
  matchKind: "none",
7750
7770
  errorReason: "old_text_not_found",
7751
7771
  oldTextOccurrences: 0,
@@ -7756,7 +7776,7 @@ function createEditTool(cwd, options) {
7756
7776
  return;
7757
7777
  }
7758
7778
  }
7759
- const rawContent = await fs7.readFile(absolutePath, "utf-8");
7779
+ const rawContent = await fs8.readFile(absolutePath, "utf-8");
7760
7780
  throwIfAborted();
7761
7781
  const { bom, text: content } = stripBom(rawContent);
7762
7782
  const originalEnding = detectLineEnding(content);
@@ -7783,8 +7803,8 @@ function createEditTool(cwd, options) {
7783
7803
  if (!matchResult.found) {
7784
7804
  if (matchResult.exhausted) {
7785
7805
  if (signal) signal.removeEventListener("abort", onAbort);
7786
- resolve5(createEditErrorResult({
7787
- message: `Could not match edit ${editIndex + 1} in ${path9} within the relaxed-match budget.`,
7806
+ resolve6(createEditErrorResult({
7807
+ message: `Could not match edit ${editIndex + 1} in ${path10} within the relaxed-match budget.`,
7788
7808
  matchKind: "none",
7789
7809
  errorReason: "match_budget_exhausted",
7790
7810
  oldTextOccurrences: 0,
@@ -7795,8 +7815,8 @@ function createEditTool(cwd, options) {
7795
7815
  return;
7796
7816
  }
7797
7817
  if (signal) signal.removeEventListener("abort", onAbort);
7798
- resolve5(createEditErrorResult({
7799
- message: `Could not find oldText for edit ${editIndex + 1} in ${path9}.`,
7818
+ resolve6(createEditErrorResult({
7819
+ message: `Could not find oldText for edit ${editIndex + 1} in ${path10}.`,
7800
7820
  matchKind: "none",
7801
7821
  errorReason: "old_text_not_found",
7802
7822
  oldTextOccurrences: 0,
@@ -7811,8 +7831,8 @@ function createEditTool(cwd, options) {
7811
7831
  }
7812
7832
  if (matchResult.occurrences > 1 && !replacement.replaceAll) {
7813
7833
  if (signal) signal.removeEventListener("abort", onAbort);
7814
- resolve5(createEditErrorResult({
7815
- message: `Found ${matchResult.occurrences}${matchResult.occurrencesAtLeast ? " or more" : ""} occurrences for edit ${editIndex + 1} in ${path9}.`,
7834
+ resolve6(createEditErrorResult({
7835
+ message: `Found ${matchResult.occurrences}${matchResult.occurrencesAtLeast ? " or more" : ""} occurrences for edit ${editIndex + 1} in ${path10}.`,
7816
7836
  matchKind: matchResult.matchKind,
7817
7837
  errorReason: "old_text_not_unique",
7818
7838
  oldTextOccurrences: matchResult.occurrences,
@@ -7828,8 +7848,8 @@ function createEditTool(cwd, options) {
7828
7848
  );
7829
7849
  if (changingMatches.length === 0) {
7830
7850
  if (signal) signal.removeEventListener("abort", onAbort);
7831
- resolve5(createEditErrorResult({
7832
- message: `No changes made for edit ${editIndex + 1} in ${path9}. Its replacement matches the current file content.`,
7851
+ resolve6(createEditErrorResult({
7852
+ message: `No changes made for edit ${editIndex + 1} in ${path10}. Its replacement matches the current file content.`,
7833
7853
  matchKind: matchResult.matchKind,
7834
7854
  errorReason: "replacement_no_change",
7835
7855
  oldTextOccurrences: matchResult.occurrences,
@@ -7850,9 +7870,9 @@ function createEditTool(cwd, options) {
7850
7870
  throwIfAborted();
7851
7871
  if (workingContent === normalizedContent) {
7852
7872
  if (signal) signal.removeEventListener("abort", onAbort);
7853
- resolve5(
7873
+ resolve6(
7854
7874
  createEditErrorResult({
7855
- message: `No changes made to ${path9}. The replacement produced identical content.`,
7875
+ message: `No changes made to ${path10}. The replacement produced identical content.`,
7856
7876
  matchKind: plannedKinds.size === 1 ? [...plannedKinds][0] : "mixed",
7857
7877
  errorReason: "replacement_no_change",
7858
7878
  oldTextOccurrences: totalOldOccurrences,
@@ -7870,12 +7890,12 @@ function createEditTool(cwd, options) {
7870
7890
  const diffResult = generateDiffString(normalizedContent, newContent);
7871
7891
  throwIfAborted();
7872
7892
  committing = true;
7873
- await fs7.writeFile(absolutePath, finalContent, "utf-8");
7893
+ await fs8.writeFile(absolutePath, finalContent, "utf-8");
7874
7894
  if (signal) signal.removeEventListener("abort", onAbort);
7875
7895
  let diagnosticWarning;
7876
7896
  try {
7877
7897
  if (usesExternalFileObservationState) {
7878
- const writtenStat = await fs7.stat(absolutePath);
7898
+ const writtenStat = await fs8.stat(absolutePath);
7879
7899
  const snapshot = snapshotFromStatAndContent(writtenStat, finalContent);
7880
7900
  fileObservationState.invalidate(absolutePath);
7881
7901
  fileObservationState.recordTextRead(
@@ -7894,10 +7914,10 @@ function createEditTool(cwd, options) {
7894
7914
  diagnosticWarning = "Edit saved, but file observation refresh failed; read the file before the next edit.";
7895
7915
  }
7896
7916
  const matchKind = plannedKinds.size === 1 ? [...plannedKinds][0] : "mixed";
7897
- const visible = boundEditOutput(`Changed ${path9}: ${replacements.length} edit block${replacements.length === 1 ? "" : "s"}, ${replacedOccurrences} replacement${replacedOccurrences === 1 ? "" : "s"}. First changed line: ${diffResult.firstChangedLine}.
7917
+ const visible = boundEditOutput(`Changed ${path10}: ${replacements.length} edit block${replacements.length === 1 ? "" : "s"}, ${replacedOccurrences} replacement${replacedOccurrences === 1 ? "" : "s"}. First changed line: ${diffResult.firstChangedLine}.
7898
7918
  ${diagnosticWarning ?? ""}
7899
7919
  ${diffResult.diff}`);
7900
- resolve5({
7920
+ resolve6({
7901
7921
  content: [
7902
7922
  {
7903
7923
  type: "text",
@@ -7908,7 +7928,7 @@ ${diffResult.diff}`);
7908
7928
  status: "success",
7909
7929
  matchKind,
7910
7930
  changed: true,
7911
- path: path9,
7931
+ path: path10,
7912
7932
  diff: diffResult.diff,
7913
7933
  diffTruncated: diffResult.truncated,
7914
7934
  contentTruncated: visible.truncated,
@@ -7932,7 +7952,7 @@ ${diffResult.diff}`);
7932
7952
  reject(error);
7933
7953
  return;
7934
7954
  }
7935
- resolve5(createEditThrownErrorResult(message, path9));
7955
+ resolve6(createEditThrownErrorResult(message, path10));
7936
7956
  }
7937
7957
  }
7938
7958
  })();
@@ -7945,7 +7965,7 @@ ${diffResult.diff}`);
7945
7965
  var DEFAULT_LIMIT = 500;
7946
7966
  var MAX_RESULT_LIMIT = 1e4;
7947
7967
  function createLsTool(cwd, options) {
7948
- const fs7 = getFileSystem();
7968
+ const fs8 = getFileSystem();
7949
7969
  const rootSchema = buildRootParameterSchema(cwd, options);
7950
7970
  const lsSchema = Type.Object({
7951
7971
  path: Type.Optional(Type.String({ description: "Directory to list (default: workspace root). Example: 'Scripts' or 'Data'." })),
@@ -7958,8 +7978,9 @@ function createLsTool(cwd, options) {
7958
7978
  label: "ls",
7959
7979
  description: `List directory contents. Use this to inspect folders before reading or writing files. Example: list_dir path='Scripts' or list_dir path='Data'. ${pathResolutionDescription} Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,
7960
7980
  parameters: lsSchema,
7961
- execute: async (_toolCallId, params, signal) => {
7962
- return new Promise((resolve5, reject) => {
7981
+ execute: async (_toolCallId, rawParams, signal) => {
7982
+ const params = rawParams ?? {};
7983
+ return new Promise((resolve6, reject) => {
7963
7984
  if (signal?.aborted) {
7964
7985
  reject(new Error("Operation aborted"));
7965
7986
  return;
@@ -7978,19 +7999,19 @@ function createLsTool(cwd, options) {
7978
7999
  if (!Number.isInteger(effectiveLimit) || effectiveLimit < 1 || effectiveLimit > MAX_RESULT_LIMIT) {
7979
8000
  throw new Error(`Invalid list_dir arguments: limit must be between 1 and ${MAX_RESULT_LIMIT}.`);
7980
8001
  }
7981
- if (!await fs7.exists(targetPath)) {
8002
+ if (!await fs8.exists(targetPath)) {
7982
8003
  reject(new Error(`Path not found: ${targetPath}`));
7983
8004
  return;
7984
8005
  }
7985
8006
  let entries;
7986
8007
  let directoryLimitReached = false;
7987
8008
  try {
7988
- const directoryRead = await fs7.readDirectoryBounded(targetPath, MAX_RESULT_LIMIT, signal);
8009
+ const directoryRead = await fs8.readDirectoryBounded(targetPath, MAX_RESULT_LIMIT, signal);
7989
8010
  entries = directoryRead.entries;
7990
8011
  directoryLimitReached = directoryRead.limitReached;
7991
8012
  } catch (e) {
7992
8013
  if (aborted) return;
7993
- const message = String(e?.message || e || "Unknown error");
8014
+ const message = e instanceof Error ? e.message : String(e || "Unknown error");
7994
8015
  if (/scandir/i.test(message) || /not a directory/i.test(message)) {
7995
8016
  reject(new Error(`Not a directory: ${targetPath}`));
7996
8017
  return;
@@ -8009,13 +8030,13 @@ function createLsTool(cwd, options) {
8009
8030
  entryLimitReached = true;
8010
8031
  break;
8011
8032
  }
8012
- const fullPath = fs7.join(targetPath, entry);
8033
+ const fullPath = fs8.join(targetPath, entry);
8013
8034
  let suffix = "";
8014
8035
  try {
8015
- const linkStat = fs7.lstatSync?.(fullPath);
8036
+ const linkStat = fs8.lstatSync?.(fullPath);
8016
8037
  if (linkStat?.isSymbolicLink) {
8017
8038
  suffix = "@";
8018
- } else if ((linkStat ?? await fs7.stat(fullPath)).isDirectory) {
8039
+ } else if ((linkStat ?? await fs8.stat(fullPath)).isDirectory) {
8019
8040
  suffix = "/";
8020
8041
  }
8021
8042
  } catch {
@@ -8028,7 +8049,7 @@ function createLsTool(cwd, options) {
8028
8049
  if (results.length === 0) {
8029
8050
  const listingIncomplete = skippedEntry || entryLimitReached;
8030
8051
  const emptyText = listingIncomplete ? "(no entries could be listed)\n\n[Listing incomplete: some directory entries could not be inspected. Retry or inspect a narrower path]" : "(empty directory)";
8031
- resolve5({
8052
+ resolve6({
8032
8053
  content: [{ type: "text", text: emptyText }],
8033
8054
  details: listingIncomplete ? {
8034
8055
  listingIncomplete: true,
@@ -8059,7 +8080,7 @@ function createLsTool(cwd, options) {
8059
8080
 
8060
8081
  [${notices.join(". ")}]`;
8061
8082
  }
8062
- resolve5({
8083
+ resolve6({
8063
8084
  content: [{ type: "text", text: output }],
8064
8085
  details: Object.keys(details).length > 0 ? details : void 0
8065
8086
  });
@@ -8141,17 +8162,17 @@ function parseGitignore(content) {
8141
8162
  function createEmptyGitignoreMatcher(incomplete = false) {
8142
8163
  return Object.assign((_relativePath, _isDirectory) => false, { incomplete, hasRules: false });
8143
8164
  }
8144
- async function loadGitignoreMatcher(rootPath, fs7, options) {
8165
+ async function loadGitignoreMatcher(rootPath, fs8, options) {
8145
8166
  let rules = [];
8146
8167
  let incomplete = false;
8147
- const filepath = fs7.join(rootPath, ".gitignore");
8168
+ const filepath = fs8.join(rootPath, ".gitignore");
8148
8169
  try {
8149
8170
  if (options?.signal?.aborted) throw new Error("Operation aborted");
8150
- if (!await fs7.exists(filepath)) return createEmptyGitignoreMatcher();
8171
+ if (!await fs8.exists(filepath)) return createEmptyGitignoreMatcher();
8151
8172
  options?.validatePath?.(filepath);
8152
- const stat = await fs7.stat(filepath);
8173
+ const stat = await fs8.stat(filepath);
8153
8174
  if (!stat.isFile || stat.size > MAX_GITIGNORE_BYTES) return createEmptyGitignoreMatcher(true);
8154
- const bytes = await fs7.readFilePrefix(filepath, MAX_GITIGNORE_BYTES + 1);
8175
+ const bytes = await fs8.readFilePrefix(filepath, MAX_GITIGNORE_BYTES + 1);
8155
8176
  if (options?.signal?.aborted) throw new Error("Operation aborted");
8156
8177
  if (bytes.byteLength > MAX_GITIGNORE_BYTES) return createEmptyGitignoreMatcher(true);
8157
8178
  const parsed = parseGitignore(new TextDecoder().decode(bytes));
@@ -10235,8 +10256,8 @@ function waitForFileCompletion(requestId) {
10235
10256
  if (existing) {
10236
10257
  return Promise.resolve(existing);
10237
10258
  }
10238
- return new Promise((resolve5) => {
10239
- store.waiters.set(requestId, resolve5);
10259
+ return new Promise((resolve6) => {
10260
+ store.waiters.set(requestId, resolve6);
10240
10261
  });
10241
10262
  }
10242
10263
  async function runNativeGrep(searchPath, pattern, globPattern, ignoreCase, literal, contextLines, limit, outputMode, offset, signal) {
@@ -10280,11 +10301,12 @@ async function runNativeGrep(searchPath, pattern, globPattern, ignoreCase, liter
10280
10301
  }
10281
10302
  function createNativeRegexSession(pattern, ignoreCase) {
10282
10303
  const bridge = getNativeFileBridge();
10283
- if (!bridge?.StartRegexLines) return void 0;
10304
+ const startRegexLines = bridge?.StartRegexLines?.bind(bridge);
10305
+ if (!bridge || !startRegexLines) return void 0;
10284
10306
  const active = /* @__PURE__ */ new Set();
10285
10307
  return {
10286
10308
  async matchLines(lines, signal) {
10287
- const requestId = bridge.StartRegexLines(pattern, ignoreCase, JSON.stringify({ Lines: lines }));
10309
+ const requestId = startRegexLines(pattern, ignoreCase, JSON.stringify({ Lines: lines }));
10288
10310
  active.add(requestId);
10289
10311
  const onAbort = () => bridge.CancelRequest(requestId);
10290
10312
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -10353,7 +10375,7 @@ function sortFileSummariesByMtime(files) {
10353
10375
  return left.relativePath.localeCompare(right.relativePath);
10354
10376
  });
10355
10377
  }
10356
- async function collectFilesForGrep(dirPath, globPattern, fs7, isGitignored = createEmptyGitignoreMatcher(), assertReadablePath = (path9) => path9, signal, fileGlobMatcher) {
10378
+ async function collectFilesForGrep(dirPath, globPattern, fs8, isGitignored = createEmptyGitignoreMatcher(), assertReadablePath = (path10) => path10, signal, fileGlobMatcher) {
10357
10379
  const matchesGlob = globPattern === void 0 ? void 0 : fileGlobMatcher ?? createGrepGlobMatcher(globPattern);
10358
10380
  const files = [];
10359
10381
  const queue = [{ dir: dirPath, relPrefix: "" }];
@@ -10368,7 +10390,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs7, isGitignored = cre
10368
10390
  if (signal?.aborted) throw new Error("Operation aborted");
10369
10391
  const { dir: requestedDir, relPrefix } = queue.pop();
10370
10392
  const dir = assertReadablePath(requestedDir);
10371
- const canonicalDir = fs7.realpathSync ? fs7.normalize(fs7.realpathSync(dir)) : fs7.normalize(dir);
10393
+ const canonicalDir = fs8.realpathSync ? fs8.normalize(fs8.realpathSync(dir)) : fs8.normalize(dir);
10372
10394
  if (visitedDirectories.has(canonicalDir)) continue;
10373
10395
  visitedDirectories.add(canonicalDir);
10374
10396
  if (++scannedDirectories > maxScannedDirectories) {
@@ -10379,7 +10401,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs7, isGitignored = cre
10379
10401
  }
10380
10402
  let entries;
10381
10403
  try {
10382
- const directoryRead = await fs7.readDirectoryBounded(dir, maxDirectoryEntries, signal);
10404
+ const directoryRead = await fs8.readDirectoryBounded(dir, maxDirectoryEntries, signal);
10383
10405
  entries = directoryRead.entries.slice().sort((left, right) => left.localeCompare(right));
10384
10406
  if (directoryRead.limitReached) {
10385
10407
  incomplete = true;
@@ -10392,12 +10414,12 @@ async function collectFilesForGrep(dirPath, globPattern, fs7, isGitignored = cre
10392
10414
  }
10393
10415
  for (const entry of entries) {
10394
10416
  if (signal?.aborted) throw new Error("Operation aborted");
10395
- const requestedPath = fs7.join(dir, entry);
10417
+ const requestedPath = fs8.join(dir, entry);
10396
10418
  const fullPath = assertReadablePath(requestedPath);
10397
10419
  const relPath = relPrefix ? `${relPrefix}/${entry}` : entry;
10398
10420
  let stat;
10399
10421
  try {
10400
- stat = await fs7.stat(fullPath);
10422
+ stat = await fs8.stat(fullPath);
10401
10423
  } catch {
10402
10424
  incomplete = true;
10403
10425
  continue;
@@ -10412,7 +10434,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs7, isGitignored = cre
10412
10434
  }
10413
10435
  } else if (stat.isFile) {
10414
10436
  if (isGitignored(relPath, false)) continue;
10415
- const ext2 = fs7.extname(entry).toLowerCase();
10437
+ const ext2 = fs8.extname(entry).toLowerCase();
10416
10438
  if (BINARY_EXTENSIONS.has(ext2)) continue;
10417
10439
  if (matchesGlob && !matchesGlob(relPath)) continue;
10418
10440
  files.push(fullPath);
@@ -10423,7 +10445,7 @@ async function collectFilesForGrep(dirPath, globPattern, fs7, isGitignored = cre
10423
10445
  return { files, truncated: traversalTruncated, incomplete, ...safetyLimit ? { safetyLimit } : {} };
10424
10446
  }
10425
10447
  function createGrepTextTool(cwd, options) {
10426
- const fs7 = getFileSystem();
10448
+ const fs8 = getFileSystem();
10427
10449
  const platform = detectPlatform();
10428
10450
  const rootSchema = buildRootParameterSchema(cwd, options);
10429
10451
  const grepSchema = Type.Object({
@@ -10464,7 +10486,7 @@ function createGrepTextTool(cwd, options) {
10464
10486
  outputMode: rawOutputMode,
10465
10487
  offset: rawOffset,
10466
10488
  limit
10467
- } = params;
10489
+ } = params ?? {};
10468
10490
  let fileGlobMatcher;
10469
10491
  try {
10470
10492
  assertGrepPatternLength(pattern);
@@ -10476,7 +10498,7 @@ function createGrepTextTool(cwd, options) {
10476
10498
  isError: true
10477
10499
  };
10478
10500
  }
10479
- return new Promise((resolve5, reject) => {
10501
+ return new Promise((resolve6, reject) => {
10480
10502
  if (signal?.aborted) {
10481
10503
  reject(new Error("Operation aborted"));
10482
10504
  return;
@@ -10494,10 +10516,10 @@ function createGrepTextTool(cwd, options) {
10494
10516
  const ctx = Math.min(normalizeNonNegativeInteger(contextLines, 0, "context"), MAX_GREP_CONTEXT_LINES);
10495
10517
  let isDir;
10496
10518
  try {
10497
- const stat = await fs7.stat(searchPath);
10519
+ const stat = await fs8.stat(searchPath);
10498
10520
  isDir = stat.isDirectory;
10499
10521
  } catch {
10500
- resolve5({
10522
+ resolve6({
10501
10523
  content: [{ type: "text", text: `grep_text failed: Path not found: ${searchPath}
10502
10524
  Check the path or search from the workspace root.` }],
10503
10525
  details: { searchIncomplete: true, safetyLimit: "io_error" },
@@ -10505,7 +10527,7 @@ Check the path or search from the workspace root.` }],
10505
10527
  });
10506
10528
  return;
10507
10529
  }
10508
- const isGitignored = await loadGitignoreMatcher(searchPath, fs7, {
10530
+ const isGitignored = await loadGitignoreMatcher(searchPath, fs8, {
10509
10531
  signal,
10510
10532
  validatePath: (candidate) => resolveToCwd(candidate, cwd, options, root)
10511
10533
  });
@@ -10528,7 +10550,7 @@ Check the path or search from the workspace root.` }],
10528
10550
  } else {
10529
10551
  }
10530
10552
  } catch (e) {
10531
- resolve5({
10553
+ resolve6({
10532
10554
  content: [{ type: "text", text: boundedErrorMessage("grep_text failed: invalid regex pattern", e, "Use literal=true for plain text, or simplify the regex.") }],
10533
10555
  details: { searchIncomplete: true, safetyLimit: "io_error" },
10534
10556
  isError: true
@@ -10581,7 +10603,7 @@ Check the path or search from the workspace root.` }],
10581
10603
  const collection = await collectFilesForGrep(
10582
10604
  searchPath,
10583
10605
  globPattern,
10584
- fs7,
10606
+ fs8,
10585
10607
  isGitignored,
10586
10608
  (filePath) => resolveToCwd(filePath, cwd, options, root),
10587
10609
  signal,
@@ -10605,7 +10627,7 @@ Check the path or search from the workspace root.` }],
10605
10627
  let content;
10606
10628
  let fileStatBefore;
10607
10629
  try {
10608
- fileStatBefore = await fs7.stat(filePath);
10630
+ fileStatBefore = await fs8.stat(filePath);
10609
10631
  if (textBytesScanned + fileStatBefore.size > MAX_TEXT_GREP_TOTAL_BYTES) {
10610
10632
  skippedUnboundedFile = true;
10611
10633
  safetyLimit = "total_bytes";
@@ -10617,7 +10639,7 @@ Check the path or search from the workspace root.` }],
10617
10639
  safetyLimit ??= "file_size";
10618
10640
  continue;
10619
10641
  }
10620
- const inspected = await fs7.readTextRange(filePath, {
10642
+ const inspected = await fs8.readTextRange(filePath, {
10621
10643
  offsetLine: 0,
10622
10644
  maxOutputLines: MAX_TEXT_GREP_FILE_LINES,
10623
10645
  maxOutputBytes: MAX_TEXT_GREP_FILE_BYTES
@@ -10645,7 +10667,7 @@ Check the path or search from the workspace root.` }],
10645
10667
  continue;
10646
10668
  }
10647
10669
  const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
10648
- const relativePath = isDir ? fs7.relative(searchPath, filePath) : fs7.basename(filePath);
10670
+ const relativePath = isDir ? fs8.relative(searchPath, filePath) : fs8.basename(filePath);
10649
10671
  filesScanned++;
10650
10672
  let fileMatchCount = 0;
10651
10673
  const pageMatchLines = [];
@@ -10674,7 +10696,7 @@ Check the path or search from the workspace root.` }],
10674
10696
  contentOutputBudgetReached ||= formatted.outputBudgetReached;
10675
10697
  }
10676
10698
  if (fileMatchCount > 0) {
10677
- const fileStat = fileStatBefore ?? await fs7.stat(filePath);
10699
+ const fileStat = fileStatBefore ?? await fs8.stat(filePath);
10678
10700
  fileSummaries.set(filePath, {
10679
10701
  filePath,
10680
10702
  relativePath,
@@ -10708,7 +10730,7 @@ Check the path or search from the workspace root.` }],
10708
10730
  signal?.removeEventListener("abort", onAbort);
10709
10731
  if (matchCount === 0) {
10710
10732
  const incompleteNotice = skippedUnboundedFile ? "\n\n[Search incomplete: a filesystem safety limit was reached. Narrow the path or glob and search again]" : "";
10711
- resolve5({
10733
+ resolve6({
10712
10734
  content: [{ type: "text", text: `No matches found${incompleteNotice}` }],
10713
10735
  details: {
10714
10736
  noMatches: true,
@@ -10763,7 +10785,7 @@ Check the path or search from the workspace root.` }],
10763
10785
 
10764
10786
  [${notices.join(". ")}]`;
10765
10787
  }
10766
- resolve5({
10788
+ resolve6({
10767
10789
  content: [{ type: "text", text: output }],
10768
10790
  details: Object.keys(details).length > 0 ? details : void 0
10769
10791
  });
@@ -10773,7 +10795,7 @@ Check the path or search from the workspace root.` }],
10773
10795
  reject(err);
10774
10796
  return;
10775
10797
  }
10776
- resolve5({
10798
+ resolve6({
10777
10799
  content: [{ type: "text", text: boundedErrorMessage("grep_text failed", err, "Check the path/pattern, use literal=true for plain text, or narrow the search.") }],
10778
10800
  details: { searchIncomplete: true, safetyLimit: "io_error" },
10779
10801
  isError: true
@@ -10850,8 +10872,8 @@ function waitForFileCompletion2(requestId) {
10850
10872
  if (existing) {
10851
10873
  return Promise.resolve(existing);
10852
10874
  }
10853
- return new Promise((resolve5) => {
10854
- store.waiters.set(requestId, resolve5);
10875
+ return new Promise((resolve6) => {
10876
+ store.waiters.set(requestId, resolve6);
10855
10877
  });
10856
10878
  }
10857
10879
  async function runNativeFind(searchPath, pattern, limit, signal) {
@@ -10883,7 +10905,7 @@ async function runNativeFind(searchPath, pattern, limit, signal) {
10883
10905
  bridge.ReleaseRequest(requestId);
10884
10906
  }
10885
10907
  }
10886
- async function globFiles(rootPath, matchesPattern, fs7, limit, signal, isGitignored = createEmptyGitignoreMatcher(), validatePath = () => {
10908
+ async function globFiles(rootPath, matchesPattern, fs8, limit, signal, isGitignored = createEmptyGitignoreMatcher(), validatePath = () => {
10887
10909
  }, incompleteState = { value: false }) {
10888
10910
  const results = [];
10889
10911
  const queue = [{ dir: rootPath, relPrefix: "" }];
@@ -10896,7 +10918,7 @@ async function globFiles(rootPath, matchesPattern, fs7, limit, signal, isGitigno
10896
10918
  }
10897
10919
  const { dir, relPrefix } = queue.shift();
10898
10920
  validatePath(dir);
10899
- const canonicalDir = fs7.realpathSync ? fs7.normalize(fs7.realpathSync(dir)) : fs7.normalize(dir);
10921
+ const canonicalDir = fs8.realpathSync ? fs8.normalize(fs8.realpathSync(dir)) : fs8.normalize(dir);
10900
10922
  if (visitedDirectories.has(canonicalDir)) continue;
10901
10923
  visitedDirectories.add(canonicalDir);
10902
10924
  if (++scannedDirectories > MAX_SCANNED_DIRECTORIES) {
@@ -10905,7 +10927,7 @@ async function globFiles(rootPath, matchesPattern, fs7, limit, signal, isGitigno
10905
10927
  }
10906
10928
  let entries;
10907
10929
  try {
10908
- const directoryRead = await fs7.readDirectoryBounded(dir, MAX_DIRECTORY_ENTRIES, signal);
10930
+ const directoryRead = await fs8.readDirectoryBounded(dir, MAX_DIRECTORY_ENTRIES, signal);
10909
10931
  entries = directoryRead.entries;
10910
10932
  if (directoryRead.limitReached) incompleteState.value = true;
10911
10933
  } catch {
@@ -10915,12 +10937,12 @@ async function globFiles(rootPath, matchesPattern, fs7, limit, signal, isGitigno
10915
10937
  for (const entry of entries) {
10916
10938
  if (signal?.aborted) throw new Error("Operation aborted");
10917
10939
  if (results.length >= limit) break;
10918
- const fullPath = fs7.join(dir, entry);
10940
+ const fullPath = fs8.join(dir, entry);
10919
10941
  const relPath = relPrefix ? relPrefix + "/" + entry : entry;
10920
10942
  validatePath(fullPath);
10921
10943
  let stat;
10922
10944
  try {
10923
- stat = await fs7.stat(fullPath);
10945
+ stat = await fs8.stat(fullPath);
10924
10946
  } catch {
10925
10947
  incompleteState.value = true;
10926
10948
  continue;
@@ -10948,7 +10970,7 @@ async function globFiles(rootPath, matchesPattern, fs7, limit, signal, isGitigno
10948
10970
  return results;
10949
10971
  }
10950
10972
  function createFindFilesTool(cwd, options) {
10951
- const fs7 = getFileSystem();
10973
+ const fs8 = getFileSystem();
10952
10974
  const platform = detectPlatform();
10953
10975
  const rootSchema = buildRootParameterSchema(cwd, options);
10954
10976
  const findSchema = Type.Object({
@@ -10967,7 +10989,7 @@ function createFindFilesTool(cwd, options) {
10967
10989
  description: `Search for files by glob pattern. ${pathResolutionDescription} Returns matching file paths relative to the search directory. Output is truncated to ${DEFAULT_LIMIT3} results or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,
10968
10990
  parameters: findSchema,
10969
10991
  execute: async (_toolCallId, params, signal) => {
10970
- const { pattern, path: searchDir, root, limit } = params;
10992
+ const { pattern, path: searchDir, root, limit } = params ?? {};
10971
10993
  let matchesPattern;
10972
10994
  try {
10973
10995
  matchesPattern = createFindFilesMatcher(pattern);
@@ -10978,7 +11000,7 @@ function createFindFilesTool(cwd, options) {
10978
11000
  isError: true
10979
11001
  };
10980
11002
  }
10981
- return new Promise((resolve5, reject) => {
11003
+ return new Promise((resolve6, reject) => {
10982
11004
  if (signal?.aborted) {
10983
11005
  reject(new Error("Operation aborted"));
10984
11006
  return;
@@ -10992,14 +11014,14 @@ function createFindFilesTool(cwd, options) {
10992
11014
  resolveToCwd(candidate, cwd, options, root);
10993
11015
  };
10994
11016
  const validateReturnedPath = (candidate) => {
10995
- validateResultPath(fs7.isAbsolute(candidate) ? candidate : fs7.join(searchPath, candidate));
11017
+ validateResultPath(fs8.isAbsolute(candidate) ? candidate : fs8.join(searchPath, candidate));
10996
11018
  };
10997
11019
  const effectiveLimit = limit ?? DEFAULT_LIMIT3;
10998
11020
  if (!Number.isInteger(effectiveLimit) || effectiveLimit < 1 || effectiveLimit > MAX_RESULT_LIMIT2) {
10999
11021
  throw new Error(`Invalid find_files arguments: limit must be between 1 and ${MAX_RESULT_LIMIT2}.`);
11000
11022
  }
11001
- if (!await fs7.exists(searchPath)) {
11002
- resolve5({
11023
+ if (!await fs8.exists(searchPath)) {
11024
+ resolve6({
11003
11025
  content: [{ type: "text", text: `find_files failed: Path not found: ${searchPath}
11004
11026
  Check the path or search from the workspace root.` }],
11005
11027
  details: { searchIncomplete: true },
@@ -11010,7 +11032,7 @@ Check the path or search from the workspace root.` }],
11010
11032
  let results;
11011
11033
  let resultLimitReached = false;
11012
11034
  const incompleteState = { value: false };
11013
- const isGitignored = await loadGitignoreMatcher(searchPath, fs7, { signal, validatePath: validateResultPath });
11035
+ const isGitignored = await loadGitignoreMatcher(searchPath, fs8, { signal, validatePath: validateResultPath });
11014
11036
  incompleteState.value ||= isGitignored.incomplete;
11015
11037
  if (platform === "puerts" && getNativeFileBridge2() && !isGitignored.hasRules) {
11016
11038
  const nativeResult = await runNativeFind(searchPath, pattern, effectiveLimit, signal);
@@ -11023,12 +11045,12 @@ Check the path or search from the workspace root.` }],
11023
11045
  `[find_files] path=${searchPath} pattern=${pattern} matches=${results.length} dirs=${nativeResult.ScannedDirectories ?? 0} files=${nativeResult.ScannedFiles ?? 0}`
11024
11046
  );
11025
11047
  } else if (platform === "node") {
11026
- const allResults = await globFiles(searchPath, matchesPattern, fs7, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
11048
+ const allResults = await globFiles(searchPath, matchesPattern, fs8, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
11027
11049
  incompleteState.value ||= isGitignored.incomplete;
11028
11050
  resultLimitReached = allResults.length > effectiveLimit;
11029
11051
  results = allResults.slice(0, effectiveLimit);
11030
11052
  } else {
11031
- const allResults = await globFiles(searchPath, matchesPattern, fs7, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
11053
+ const allResults = await globFiles(searchPath, matchesPattern, fs8, effectiveLimit + 1, signal, isGitignored, validateResultPath, incompleteState);
11032
11054
  incompleteState.value ||= isGitignored.incomplete;
11033
11055
  resultLimitReached = allResults.length > effectiveLimit;
11034
11056
  results = allResults.slice(0, effectiveLimit);
@@ -11036,7 +11058,7 @@ Check the path or search from the workspace root.` }],
11036
11058
  signal?.removeEventListener("abort", onAbort);
11037
11059
  if (results.length === 0) {
11038
11060
  const incompleteNotice = incompleteState.value ? "\n\n[Search incomplete: a filesystem safety limit or I/O error prevented some paths from being inspected. Narrow the path or pattern and search again]" : "";
11039
- resolve5({
11061
+ resolve6({
11040
11062
  content: [{ type: "text", text: `No files found matching pattern${incompleteNotice}` }],
11041
11063
  details: {
11042
11064
  noMatches: true,
@@ -11065,7 +11087,7 @@ Check the path or search from the workspace root.` }],
11065
11087
  if (notices.length > 0) {
11066
11088
  resultOutput += "\n\n[" + notices.join(". ") + "]";
11067
11089
  }
11068
- resolve5({
11090
+ resolve6({
11069
11091
  content: [{ type: "text", text: resultOutput }],
11070
11092
  details: Object.keys(details).length > 0 ? details : void 0
11071
11093
  });
@@ -11076,7 +11098,7 @@ Check the path or search from the workspace root.` }],
11076
11098
  reject(e);
11077
11099
  return;
11078
11100
  }
11079
- resolve5({
11101
+ resolve6({
11080
11102
  content: [{ type: "text", text: boundedFindError(e) }],
11081
11103
  details: { searchIncomplete: true },
11082
11104
  isError: true
@@ -11650,8 +11672,8 @@ function isSearchPageSource(source) {
11650
11672
  function isHomepageSource(source) {
11651
11673
  const parsed = sourceHostAndPath(source);
11652
11674
  if (!parsed) return false;
11653
- const path9 = parsed.path.replace(/\/+$/, "");
11654
- return path9 === "" || path9 === "/news" || path9 === "/sections/news";
11675
+ const path10 = parsed.path.replace(/\/+$/, "");
11676
+ return path10 === "" || path10 === "/news" || path10 === "/sections/news";
11655
11677
  }
11656
11678
  function evaluateSearchQuality(search) {
11657
11679
  const warnings = [];
@@ -11683,8 +11705,8 @@ async function runQueuedSearch(model, fn) {
11683
11705
  const key = `${model.provider}/${model.id}`;
11684
11706
  const previous = SEARCH_PROVIDER_QUEUE.get(key) ?? Promise.resolve();
11685
11707
  let release;
11686
- const next = new Promise((resolve5) => {
11687
- release = resolve5;
11708
+ const next = new Promise((resolve6) => {
11709
+ release = resolve6;
11688
11710
  });
11689
11711
  const queued = previous.catch(() => void 0).then(() => next);
11690
11712
  SEARCH_PROVIDER_QUEUE.set(key, queued);
@@ -12158,10 +12180,10 @@ function assistantText(message) {
12158
12180
  async function withAbort(promise, signal) {
12159
12181
  if (!signal) return promise;
12160
12182
  if (signal.aborted) throw signal.reason ?? new Error("operation aborted");
12161
- return await new Promise((resolve5, reject) => {
12183
+ return await new Promise((resolve6, reject) => {
12162
12184
  const onAbort = () => reject(signal.reason ?? new Error("operation aborted"));
12163
12185
  signal.addEventListener("abort", onAbort, { once: true });
12164
- promise.then(resolve5, reject).finally(() => signal.removeEventListener("abort", onAbort));
12186
+ promise.then(resolve6, reject).finally(() => signal.removeEventListener("abort", onAbort));
12165
12187
  });
12166
12188
  }
12167
12189
  async function cancelResponseBody(response) {
@@ -12172,13 +12194,13 @@ async function cancelResponseBody(response) {
12172
12194
  }
12173
12195
  var DISCARD_BODY_GRACE_MS = 250;
12174
12196
  async function discardResponseBody(response) {
12175
- await new Promise((resolve5) => {
12197
+ await new Promise((resolve6) => {
12176
12198
  let settled = false;
12177
12199
  const settle = () => {
12178
12200
  if (settled) return;
12179
12201
  settled = true;
12180
12202
  clearTimeout(timer);
12181
- resolve5();
12203
+ resolve6();
12182
12204
  };
12183
12205
  const timer = setTimeout(settle, DISCARD_BODY_GRACE_MS);
12184
12206
  try {
@@ -12893,13 +12915,13 @@ async function runWithDeadline(operation, timeoutMs, message, parentSignal) {
12893
12915
  const child = createChildSignal(parentSignal);
12894
12916
  let timer;
12895
12917
  try {
12896
- return await new Promise((resolve5, reject) => {
12918
+ return await new Promise((resolve6, reject) => {
12897
12919
  timer = setTimeout(() => {
12898
12920
  const error = new Error(message);
12899
12921
  child.abort(error);
12900
12922
  reject(error);
12901
12923
  }, timeoutMs);
12902
- operation(child.signal).then(resolve5, reject);
12924
+ operation(child.signal).then(resolve6, reject);
12903
12925
  });
12904
12926
  } finally {
12905
12927
  if (timer) clearTimeout(timer);
@@ -14016,39 +14038,184 @@ function redactBlockScalars(text, counts) {
14016
14038
  }
14017
14039
 
14018
14040
  // ../../packages/shared-headless-capabilities/src/memory/store.ts
14019
- import * as fs2 from "node:fs";
14041
+ import * as fs3 from "node:fs";
14020
14042
  import { createRequire } from "node:module";
14043
+ import * as path5 from "node:path";
14044
+
14045
+ // ../../packages/shared-headless-capabilities/src/memory/project-key.ts
14046
+ import * as fs2 from "node:fs";
14021
14047
  import * as path4 from "node:path";
14022
14048
  import { createHash } from "node:crypto";
14023
- var ENTRY_FILE = ".entries.json";
14024
- var STATE_FILE = ".state.json";
14025
- var SNAPSHOTS_DIR = ".snapshots";
14026
- var ARCHIVE_DIR = "archive";
14027
- var JOURNAL_DIR = "journal";
14028
- var KNOWLEDGE_DIR = "knowledge";
14029
- var PROJECTS_DIR = "projects";
14030
- function projectKeyFor(input) {
14049
+ var KNOWN_GIT_HOSTS = /* @__PURE__ */ new Set(["github.com", "gitlab.com", "bitbucket.org"]);
14050
+ var KNOWN_HOST_PROTOCOLS = /* @__PURE__ */ new Set(["https:", "http:", "ssh:", "git:"]);
14051
+ function normalizeGitUrl(raw) {
14052
+ const trimmed = raw.trim();
14053
+ const scp = !trimmed.includes("://") ? /^[^@:/\s]+@([^:/\s]+):(.+)$/.exec(trimmed) : null;
14054
+ if (scp) {
14055
+ const host = scp[1].toLowerCase();
14056
+ const rawPath = scp[2];
14057
+ if (KNOWN_GIT_HOSTS.has(host) && !/(?:^|\/)\.\.?(?:\/|$)/.test(rawPath)) {
14058
+ const repoPath = rawPath.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();
14059
+ if (repoPath) return `host\0${host}/${repoPath}`;
14060
+ }
14061
+ return `raw\0${trimmed}`;
14062
+ }
14063
+ const schemeMatch = /^([a-z][a-z0-9+.-]*):\/\/([^/?#]*)(\/[^?#]*)?/i.exec(trimmed);
14064
+ if (schemeMatch) {
14065
+ const protocol = `${schemeMatch[1].toLowerCase()}:`;
14066
+ const rawPath = schemeMatch[3] ?? "";
14067
+ if (KNOWN_HOST_PROTOCOLS.has(protocol) && !rawPath.includes("%") && !/(?:^|\/)\.\.?(?:\/|$)/.test(rawPath)) {
14068
+ try {
14069
+ const url = new URL(trimmed);
14070
+ const host = url.hostname.toLowerCase();
14071
+ const defaultPort = protocol === "https:" ? "443" : protocol === "http:" ? "80" : protocol === "ssh:" ? "22" : "9418";
14072
+ const hasNonDefaultPort = Boolean(url.port && url.port !== defaultPort);
14073
+ if (KNOWN_GIT_HOSTS.has(host) && !hasNonDefaultPort && !url.search && !url.hash) {
14074
+ const repoPath = rawPath.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();
14075
+ if (repoPath) return `host\0${host}/${repoPath}`;
14076
+ }
14077
+ } catch {
14078
+ }
14079
+ }
14080
+ }
14081
+ return `raw\0${trimmed}`;
14082
+ }
14083
+ function legacyProjectKeyFor(input) {
14031
14084
  const source = input.gitUrl?.trim() || input.cwd;
14032
14085
  return createHash("sha256").update(source).digest("hex").slice(0, 16);
14033
14086
  }
14087
+ function projectKeyFor(input) {
14088
+ const source = input.gitUrl?.trim() ? normalizeGitUrl(input.gitUrl) : input.cwd;
14089
+ return createHash("sha256").update(source).digest("hex").slice(0, 16);
14090
+ }
14091
+ function resolveGitRepoMeta(cwd) {
14092
+ try {
14093
+ let dir = path4.resolve(cwd);
14094
+ if (!fs2.existsSync(dir) || !fs2.statSync(dir).isDirectory()) return {};
14095
+ for (let depth = 0; depth < 64; depth += 1) {
14096
+ const dotGit = path4.join(dir, ".git");
14097
+ if (fs2.existsSync(dotGit)) {
14098
+ let gitDir = dotGit;
14099
+ const stat = fs2.statSync(dotGit);
14100
+ if (stat.isFile()) {
14101
+ const pointer = fs2.readFileSync(dotGit, "utf8");
14102
+ const match2 = /^gitdir:\s*(.+)$/im.exec(pointer);
14103
+ if (!match2) return {};
14104
+ gitDir = path4.resolve(dir, match2[1].trim());
14105
+ }
14106
+ let commonDir = gitDir;
14107
+ let configPath = path4.join(gitDir, "config");
14108
+ if (!fs2.existsSync(configPath)) {
14109
+ const commonDirFile = path4.join(gitDir, "commondir");
14110
+ if (fs2.existsSync(commonDirFile)) {
14111
+ commonDir = path4.resolve(gitDir, fs2.readFileSync(commonDirFile, "utf8").trim());
14112
+ configPath = path4.join(commonDir, "config");
14113
+ }
14114
+ }
14115
+ try {
14116
+ commonDir = fs2.realpathSync(commonDir);
14117
+ } catch {
14118
+ }
14119
+ if (!fs2.existsSync(configPath)) return { commonDir };
14120
+ const config = fs2.readFileSync(configPath, "utf8");
14121
+ const section = config.match(/\[remote "origin"\][^\[]*/)?.[0] ?? "";
14122
+ const url = section.match(/url\s*=\s*(\S+)/)?.[1];
14123
+ return { gitUrl: url || void 0, commonDir };
14124
+ }
14125
+ const parent = path4.dirname(dir);
14126
+ if (parent === dir) break;
14127
+ dir = parent;
14128
+ }
14129
+ return {};
14130
+ } catch {
14131
+ return {};
14132
+ }
14133
+ }
14034
14134
  function readGitOriginUrl(cwd) {
14135
+ return resolveGitRepoMeta(cwd).gitUrl;
14136
+ }
14137
+ function readRegisteredWorktreeDirs(commonDir) {
14138
+ if (!commonDir) return [];
14139
+ const worktreesDir = path4.join(commonDir, "worktrees");
14035
14140
  try {
14036
- const gitDir = path4.join(cwd, ".git");
14037
- if (!fs2.existsSync(gitDir)) return void 0;
14038
- const configPath = fs2.existsSync(path4.join(gitDir, "config")) ? path4.join(gitDir, "config") : void 0;
14039
- if (!configPath) return void 0;
14040
- const config = fs2.readFileSync(configPath, "utf8");
14041
- const section = config.match(/\[remote "origin"\][^\[]*/)?.[0] ?? "";
14042
- const url = section.match(/url\s*=\s*(\S+)/)?.[1];
14043
- return url || void 0;
14141
+ if (!fs2.existsSync(worktreesDir)) return [];
14142
+ const dirs = [];
14143
+ for (const name of fs2.readdirSync(worktreesDir)) {
14144
+ const gitdirFile = path4.join(worktreesDir, name, "gitdir");
14145
+ if (!fs2.existsSync(gitdirFile)) continue;
14146
+ const target = fs2.readFileSync(gitdirFile, "utf8").trim();
14147
+ if (!target) continue;
14148
+ const wtDotGit = path4.resolve(path4.dirname(gitdirFile), target);
14149
+ if (!fs2.existsSync(wtDotGit) || !fs2.statSync(wtDotGit).isFile()) continue;
14150
+ const wtRoot = path4.dirname(wtDotGit);
14151
+ const reciprocal = resolveGitRepoMeta(wtRoot);
14152
+ if (reciprocal.commonDir !== commonDir) continue;
14153
+ dirs.push(wtRoot);
14154
+ }
14155
+ return dirs;
14044
14156
  } catch {
14045
- return void 0;
14157
+ return [];
14046
14158
  }
14047
14159
  }
14048
14160
  function projectKeyForDir(cwd) {
14049
- const gitUrl = readGitOriginUrl(cwd);
14050
- return { key: projectKeyFor({ gitUrl, cwd }), gitUrl };
14161
+ const { gitUrl, commonDir } = resolveGitRepoMeta(cwd);
14162
+ const canonicalCwd = !gitUrl && commonDir ? path4.basename(commonDir) === ".git" ? path4.dirname(commonDir) : commonDir : cwd;
14163
+ const key = projectKeyFor({ gitUrl, cwd: canonicalCwd });
14164
+ const legacyUrl = gitUrl ? legacyProjectKeyFor({ gitUrl, cwd }) : void 0;
14165
+ const hasDirectDotGitConfig = fs2.existsSync(path4.join(cwd, ".git", "config"));
14166
+ const legacyCwd = !hasDirectDotGitConfig || canonicalCwd !== cwd ? legacyProjectKeyFor({ cwd }) : void 0;
14167
+ const legacyKey = legacyUrl && legacyUrl !== key ? legacyUrl : legacyCwd && legacyCwd !== key ? legacyCwd : void 0;
14168
+ const allKeys = [key];
14169
+ for (const candidate of [legacyUrl, legacyCwd]) {
14170
+ if (candidate && !allKeys.includes(candidate)) allKeys.push(candidate);
14171
+ }
14172
+ for (const wtDir of readRegisteredWorktreeDirs(commonDir)) {
14173
+ const wtLegacy = legacyProjectKeyFor({ cwd: wtDir });
14174
+ if (wtLegacy && !allKeys.includes(wtLegacy)) allKeys.push(wtLegacy);
14175
+ }
14176
+ return { key, ...legacyKey ? { legacyKey } : {}, allKeys, gitUrl };
14177
+ }
14178
+ function collectProjectKeyAliases(cwds) {
14179
+ const aliases = /* @__PURE__ */ new Map();
14180
+ const canonicalOwners = /* @__PURE__ */ new Set();
14181
+ const conflicting = /* @__PURE__ */ new Set();
14182
+ const seen = /* @__PURE__ */ new Set();
14183
+ for (const rawCwd of cwds) {
14184
+ if (!rawCwd || seen.has(rawCwd)) continue;
14185
+ seen.add(rawCwd);
14186
+ const info = projectKeyForDir(rawCwd);
14187
+ canonicalOwners.add(info.key);
14188
+ aliases.set(info.key, info.key);
14189
+ for (const alias of info.allKeys) {
14190
+ if (alias === info.key) continue;
14191
+ if (canonicalOwners.has(alias) || conflicting.has(alias)) {
14192
+ aliases.delete(alias);
14193
+ conflicting.add(alias);
14194
+ continue;
14195
+ }
14196
+ const existing = aliases.get(alias);
14197
+ if (existing && existing !== info.key) {
14198
+ aliases.delete(alias);
14199
+ conflicting.add(alias);
14200
+ } else {
14201
+ aliases.set(alias, info.key);
14202
+ }
14203
+ }
14204
+ }
14205
+ for (const owner of canonicalOwners) {
14206
+ aliases.set(owner, owner);
14207
+ }
14208
+ return aliases;
14051
14209
  }
14210
+
14211
+ // ../../packages/shared-headless-capabilities/src/memory/store.ts
14212
+ var ENTRY_FILE = ".entries.json";
14213
+ var STATE_FILE = ".state.json";
14214
+ var SNAPSHOTS_DIR = ".snapshots";
14215
+ var ARCHIVE_DIR = "archive";
14216
+ var JOURNAL_DIR = "journal";
14217
+ var KNOWLEDGE_DIR = "knowledge";
14218
+ var PROJECTS_DIR = "projects";
14052
14219
  function isEntryFile(value) {
14053
14220
  if (!value || typeof value !== "object") return false;
14054
14221
  const file = value;
@@ -14079,7 +14246,7 @@ function createPosixBackend(koffi) {
14079
14246
  const EWOULDBLOCK = koffi.os.errno.EWOULDBLOCK ?? koffi.os.errno.EAGAIN;
14080
14247
  return {
14081
14248
  open(lockPath) {
14082
- return fs2.openSync(lockPath, "a");
14249
+ return fs3.openSync(lockPath, "a");
14083
14250
  },
14084
14251
  lock(handle) {
14085
14252
  const fd = handle;
@@ -14094,7 +14261,7 @@ function createPosixBackend(koffi) {
14094
14261
  } catch {
14095
14262
  }
14096
14263
  try {
14097
- fs2.closeSync(handle);
14264
+ fs3.closeSync(handle);
14098
14265
  } catch {
14099
14266
  }
14100
14267
  }
@@ -14156,10 +14323,10 @@ function createMemoryLockBackend(koffi) {
14156
14323
  return process.platform === "win32" ? createWindowsBackend(koffi) : createPosixBackend(koffi);
14157
14324
  }
14158
14325
  function removeLegacyLockDirectory(lockPath) {
14159
- const entries = fs2.readdirSync(lockPath);
14160
- for (const name of entries) fs2.rmSync(path4.join(lockPath, name), { force: true });
14326
+ const entries = fs3.readdirSync(lockPath);
14327
+ for (const name of entries) fs3.rmSync(path5.join(lockPath, name), { force: true });
14161
14328
  try {
14162
- fs2.rmdirSync(lockPath);
14329
+ fs3.rmdirSync(lockPath);
14163
14330
  } catch (error) {
14164
14331
  const code = error.code;
14165
14332
  if (code !== "ENOTEMPTY" && code !== "ENOTDIR" && code !== "ENOENT") throw error;
@@ -14167,9 +14334,9 @@ function removeLegacyLockDirectory(lockPath) {
14167
14334
  }
14168
14335
  function acquireStoreWriteLock(lockPath) {
14169
14336
  const backend = storeLockBackendInstance();
14170
- fs2.mkdirSync(path4.dirname(lockPath), { recursive: true });
14337
+ fs3.mkdirSync(path5.dirname(lockPath), { recursive: true });
14171
14338
  try {
14172
- if (fs2.statSync(lockPath).isDirectory()) removeLegacyLockDirectory(lockPath);
14339
+ if (fs3.statSync(lockPath).isDirectory()) removeLegacyLockDirectory(lockPath);
14173
14340
  } catch {
14174
14341
  }
14175
14342
  let handle;
@@ -14247,7 +14414,7 @@ var MemoryStore = class _MemoryStore {
14247
14414
  transactionDepth = 0;
14248
14415
  /** Bounded-retry acquisition of the store's advisory write lock. */
14249
14416
  withStoreLock(fn) {
14250
- const lock = acquireStoreWriteLock(path4.join(this.root, "write.lock"));
14417
+ const lock = acquireStoreWriteLock(path5.join(this.root, "write.lock"));
14251
14418
  if (!lock) throw new Error("memory store is contended (write.lock); retry the operation");
14252
14419
  try {
14253
14420
  return fn();
@@ -14259,12 +14426,12 @@ var MemoryStore = class _MemoryStore {
14259
14426
  // Entries (canonical records)
14260
14427
  // ------------------------------------------------------------------
14261
14428
  entryPath() {
14262
- return path4.join(this.root, ENTRY_FILE);
14429
+ return path5.join(this.root, ENTRY_FILE);
14263
14430
  }
14264
14431
  loadEntries() {
14265
14432
  let raw;
14266
14433
  try {
14267
- raw = fs2.readFileSync(this.entryPath(), "utf8");
14434
+ raw = fs3.readFileSync(this.entryPath(), "utf8");
14268
14435
  } catch (error) {
14269
14436
  if (error.code === "ENOENT") return [];
14270
14437
  throw new Error(`memory entries unreadable: ${String(error)}`);
@@ -14294,14 +14461,40 @@ var MemoryStore = class _MemoryStore {
14294
14461
  }
14295
14462
  const file = { version: 1, entries };
14296
14463
  const target = this.entryPath();
14297
- fs2.mkdirSync(this.root, { recursive: true });
14464
+ fs3.mkdirSync(this.root, { recursive: true });
14298
14465
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
14299
- fs2.writeFileSync(tmp, JSON.stringify(file, null, " "));
14300
- fs2.renameSync(tmp, target);
14466
+ fs3.writeFileSync(tmp, JSON.stringify(file, null, " "));
14467
+ fs3.renameSync(tmp, target);
14301
14468
  }
14302
14469
  entryById(id) {
14303
14470
  return this.loadEntries().find((entry) => entry.id === id);
14304
14471
  }
14472
+ /** Atomically upgrade legacy `projectKey` values on active `kind === "project"`
14473
+ * entries to their canonical key under the store mutex, preserving entry ID,
14474
+ * provenance, evidence, and usage counters. Returns the count of migrated entries. */
14475
+ migrateProjectKeys(aliases) {
14476
+ if (aliases.size === 0) return 0;
14477
+ return this.transaction(() => {
14478
+ const entries = this.loadEntries();
14479
+ let migrated = 0;
14480
+ const updatedKeys = /* @__PURE__ */ new Set();
14481
+ for (const entry of entries) {
14482
+ if (entry.kind !== "project" || !entry.projectKey) continue;
14483
+ const canonical = aliases.get(entry.projectKey);
14484
+ if (canonical && canonical !== entry.projectKey) {
14485
+ updatedKeys.add(entry.projectKey);
14486
+ entry.projectKey = canonical;
14487
+ updatedKeys.add(canonical);
14488
+ migrated += 1;
14489
+ }
14490
+ }
14491
+ if (migrated > 0) {
14492
+ this.saveEntries(entries);
14493
+ this.renderSurfaces([...updatedKeys]);
14494
+ }
14495
+ return migrated;
14496
+ });
14497
+ }
14305
14498
  // ------------------------------------------------------------------
14306
14499
  // Surfaces (rendered views; entries are the source of truth)
14307
14500
  // ------------------------------------------------------------------
@@ -14314,13 +14507,13 @@ var MemoryStore = class _MemoryStore {
14314
14507
  case "threads":
14315
14508
  return "THREADS.md";
14316
14509
  case "knowledge":
14317
- return path4.join(KNOWLEDGE_DIR, "index.md");
14510
+ return path5.join(KNOWLEDGE_DIR, "index.md");
14318
14511
  case "project":
14319
- return path4.join(PROJECTS_DIR, "unknown", "MEMORY.md");
14512
+ return path5.join(PROJECTS_DIR, "unknown", "MEMORY.md");
14320
14513
  }
14321
14514
  }
14322
14515
  projectSurfacePath(projectKey) {
14323
- return path4.join(this.root, PROJECTS_DIR, projectKey, "MEMORY.md");
14516
+ return path5.join(this.root, PROJECTS_DIR, projectKey, "MEMORY.md");
14324
14517
  }
14325
14518
  entryLine(entry) {
14326
14519
  return `- ${entry.text} _(since ${dayOf(entry.created)}${entry.provenance === "user-attested" ? ", user-attested" : ""})_`;
@@ -14329,17 +14522,17 @@ var MemoryStore = class _MemoryStore {
14329
14522
  renderSurfaces(projectKeys = []) {
14330
14523
  const entries = this.loadEntries();
14331
14524
  const bySurface = (surface) => entries.filter((entry) => entry.surface === surface && !isRetired(entry));
14332
- fs2.mkdirSync(this.root, { recursive: true });
14525
+ fs3.mkdirSync(this.root, { recursive: true });
14333
14526
  const writeSurface = (file, title, list) => {
14334
14527
  const lines = [`# ${title}`, ""];
14335
14528
  if (list.length === 0) lines.push("_(empty)_", "");
14336
14529
  for (const entry of list) lines.push(this.entryLine(entry));
14337
- fs2.mkdirSync(path4.dirname(file), { recursive: true });
14338
- fs2.writeFileSync(file, lines.join("\n") + "\n");
14530
+ fs3.mkdirSync(path5.dirname(file), { recursive: true });
14531
+ fs3.writeFileSync(file, lines.join("\n") + "\n");
14339
14532
  };
14340
- writeSurface(path4.join(this.root, "USER.md"), "User", bySurface("user"));
14341
- writeSurface(path4.join(this.root, "MEMORY.md"), "Memory", bySurface("memory"));
14342
- writeSurface(path4.join(this.root, "THREADS.md"), "Threads", bySurface("threads"));
14533
+ writeSurface(path5.join(this.root, "USER.md"), "User", bySurface("user"));
14534
+ writeSurface(path5.join(this.root, "MEMORY.md"), "Memory", bySurface("memory"));
14535
+ writeSurface(path5.join(this.root, "THREADS.md"), "Threads", bySurface("threads"));
14343
14536
  for (const key of projectKeys) {
14344
14537
  const list = entries.filter(
14345
14538
  (entry) => (entry.kind === "project" || entry.surface === "project") && entry.projectKey === key && !isRetired(entry)
@@ -14353,16 +14546,16 @@ var MemoryStore = class _MemoryStore {
14353
14546
  static DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
14354
14547
  journalPath(date) {
14355
14548
  if (!_MemoryStore.DATE_RE.test(date)) throw new Error(`invalid journal date: ${JSON.stringify(date)}`);
14356
- return path4.join(this.root, JOURNAL_DIR, `${date}.md`);
14549
+ return path5.join(this.root, JOURNAL_DIR, `${date}.md`);
14357
14550
  }
14358
14551
  writeJournal(date, content) {
14359
14552
  const file = this.journalPath(date);
14360
- fs2.mkdirSync(path4.dirname(file), { recursive: true });
14361
- fs2.writeFileSync(file, content);
14553
+ fs3.mkdirSync(path5.dirname(file), { recursive: true });
14554
+ fs3.writeFileSync(file, content);
14362
14555
  }
14363
14556
  readJournal(date) {
14364
14557
  try {
14365
- return fs2.readFileSync(this.journalPath(date), "utf8");
14558
+ return fs3.readFileSync(this.journalPath(date), "utf8");
14366
14559
  } catch {
14367
14560
  return void 0;
14368
14561
  }
@@ -14372,7 +14565,7 @@ var MemoryStore = class _MemoryStore {
14372
14565
  * a persona is never mandatory). Read is size-capped defensively. */
14373
14566
  readSoul(maxChars = 4e3) {
14374
14567
  try {
14375
- const text = fs2.readFileSync(path4.join(this.root, "SOUL.md"), "utf8");
14568
+ const text = fs3.readFileSync(path5.join(this.root, "SOUL.md"), "utf8");
14376
14569
  const trimmed = text.trim();
14377
14570
  return trimmed.length > 0 ? trimmed.slice(0, maxChars) : void 0;
14378
14571
  } catch {
@@ -14381,7 +14574,7 @@ var MemoryStore = class _MemoryStore {
14381
14574
  }
14382
14575
  listJournalDates() {
14383
14576
  try {
14384
- return fs2.readdirSync(path4.join(this.root, JOURNAL_DIR)).filter((name) => /^\d{4}-\d{2}-\d{2}\.md$/.test(name)).map((name) => name.slice(0, -3)).sort();
14577
+ return fs3.readdirSync(path5.join(this.root, JOURNAL_DIR)).filter((name) => /^\d{4}-\d{2}-\d{2}\.md$/.test(name)).map((name) => name.slice(0, -3)).sort();
14385
14578
  } catch {
14386
14579
  return [];
14387
14580
  }
@@ -14391,18 +14584,18 @@ var MemoryStore = class _MemoryStore {
14391
14584
  // ------------------------------------------------------------------
14392
14585
  writeProjectMeta(meta) {
14393
14586
  this.transaction(() => {
14394
- const dir = path4.join(this.root, PROJECTS_DIR, meta.key);
14395
- fs2.mkdirSync(dir, { recursive: true });
14396
- const target = path4.join(dir, "meta.json");
14587
+ const dir = path5.join(this.root, PROJECTS_DIR, meta.key);
14588
+ fs3.mkdirSync(dir, { recursive: true });
14589
+ const target = path5.join(dir, "meta.json");
14397
14590
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
14398
- fs2.writeFileSync(tmp, JSON.stringify(meta, null, " "));
14399
- fs2.renameSync(tmp, target);
14591
+ fs3.writeFileSync(tmp, JSON.stringify(meta, null, " "));
14592
+ fs3.renameSync(tmp, target);
14400
14593
  });
14401
14594
  }
14402
14595
  readProjectMeta(projectKey) {
14403
14596
  try {
14404
- const raw = fs2.readFileSync(
14405
- path4.join(this.root, PROJECTS_DIR, projectKey, "meta.json"),
14597
+ const raw = fs3.readFileSync(
14598
+ path5.join(this.root, PROJECTS_DIR, projectKey, "meta.json"),
14406
14599
  "utf8"
14407
14600
  );
14408
14601
  return JSON.parse(raw);
@@ -14412,9 +14605,9 @@ var MemoryStore = class _MemoryStore {
14412
14605
  }
14413
14606
  listProjectKeys() {
14414
14607
  try {
14415
- return fs2.readdirSync(path4.join(this.root, PROJECTS_DIR)).filter((name) => {
14608
+ return fs3.readdirSync(path5.join(this.root, PROJECTS_DIR)).filter((name) => {
14416
14609
  try {
14417
- return fs2.statSync(path4.join(this.root, PROJECTS_DIR, name)).isDirectory();
14610
+ return fs3.statSync(path5.join(this.root, PROJECTS_DIR, name)).isDirectory();
14418
14611
  } catch {
14419
14612
  return false;
14420
14613
  }
@@ -14430,14 +14623,14 @@ var MemoryStore = class _MemoryStore {
14430
14623
  * Project surfaces are regenerated on rollback. Returns the snapshot id. */
14431
14624
  snapshot(label) {
14432
14625
  const id = `snap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}-${label.replace(/[^a-z0-9-]/gi, "")}`;
14433
- const dir = path4.join(this.root, SNAPSHOTS_DIR, id);
14434
- fs2.mkdirSync(dir, { recursive: true });
14626
+ const dir = path5.join(this.root, SNAPSHOTS_DIR, id);
14627
+ fs3.mkdirSync(dir, { recursive: true });
14435
14628
  for (const name of [ENTRY_FILE, STATE_FILE, "USER.md", "MEMORY.md", "THREADS.md"]) {
14436
- const from = path4.join(this.root, name);
14437
- if (fs2.existsSync(from)) {
14438
- fs2.copyFileSync(from, path4.join(dir, name));
14629
+ const from = path5.join(this.root, name);
14630
+ if (fs3.existsSync(from)) {
14631
+ fs3.copyFileSync(from, path5.join(dir, name));
14439
14632
  } else {
14440
- fs2.writeFileSync(path4.join(dir, `${name}.absent`), "");
14633
+ fs3.writeFileSync(path5.join(dir, `${name}.absent`), "");
14441
14634
  }
14442
14635
  }
14443
14636
  this.pruneSnapshots();
@@ -14445,7 +14638,7 @@ var MemoryStore = class _MemoryStore {
14445
14638
  }
14446
14639
  listSnapshots() {
14447
14640
  try {
14448
- return fs2.readdirSync(path4.join(this.root, SNAPSHOTS_DIR)).sort().reverse();
14641
+ return fs3.readdirSync(path5.join(this.root, SNAPSHOTS_DIR)).sort().reverse();
14449
14642
  } catch {
14450
14643
  return [];
14451
14644
  }
@@ -14453,17 +14646,17 @@ var MemoryStore = class _MemoryStore {
14453
14646
  /** Restore every snapshotted file (tombstones delete files created since). */
14454
14647
  rollback(snapshotId) {
14455
14648
  if (!/^snap-[a-z0-9]+-[a-z0-9]+(-[a-z0-9-]*)?$/.test(snapshotId)) throw new Error(`invalid snapshot id`);
14456
- const dir = path4.join(this.root, SNAPSHOTS_DIR, snapshotId);
14457
- if (!fs2.existsSync(dir)) throw new Error(`unknown memory snapshot: ${snapshotId}`);
14649
+ const dir = path5.join(this.root, SNAPSHOTS_DIR, snapshotId);
14650
+ if (!fs3.existsSync(dir)) throw new Error(`unknown memory snapshot: ${snapshotId}`);
14458
14651
  this.transaction(() => {
14459
- for (const name of fs2.readdirSync(dir)) {
14652
+ for (const name of fs3.readdirSync(dir)) {
14460
14653
  if (name.endsWith(".absent")) {
14461
- fs2.rmSync(path4.join(this.root, name.slice(0, -".absent".length)), { force: true });
14654
+ fs3.rmSync(path5.join(this.root, name.slice(0, -".absent".length)), { force: true });
14462
14655
  } else {
14463
- const dest = path4.join(this.root, name);
14656
+ const dest = path5.join(this.root, name);
14464
14657
  const temp = `${dest}.${process.pid}.${Date.now()}.tmp`;
14465
- fs2.copyFileSync(path4.join(dir, name), temp);
14466
- fs2.renameSync(temp, dest);
14658
+ fs3.copyFileSync(path5.join(dir, name), temp);
14659
+ fs3.renameSync(temp, dest);
14467
14660
  }
14468
14661
  }
14469
14662
  this.renderSurfaces(this.listProjectKeys());
@@ -14472,7 +14665,7 @@ var MemoryStore = class _MemoryStore {
14472
14665
  pruneSnapshots(keep = 30) {
14473
14666
  const ids = this.listSnapshots();
14474
14667
  for (const id of ids.slice(keep)) {
14475
- fs2.rmSync(path4.join(this.root, SNAPSHOTS_DIR, id), { recursive: true, force: true });
14668
+ fs3.rmSync(path5.join(this.root, SNAPSHOTS_DIR, id), { recursive: true, force: true });
14476
14669
  }
14477
14670
  }
14478
14671
  // ------------------------------------------------------------------
@@ -14480,7 +14673,7 @@ var MemoryStore = class _MemoryStore {
14480
14673
  // ------------------------------------------------------------------
14481
14674
  loadState() {
14482
14675
  try {
14483
- const raw = fs2.readFileSync(path4.join(this.root, STATE_FILE), "utf8");
14676
+ const raw = fs3.readFileSync(path5.join(this.root, STATE_FILE), "utf8");
14484
14677
  const parsed = JSON.parse(raw);
14485
14678
  if (parsed && parsed.version === 1 && parsed.runs && typeof parsed.runs === "object") {
14486
14679
  return parsed;
@@ -14490,11 +14683,11 @@ var MemoryStore = class _MemoryStore {
14490
14683
  return { version: 1, runs: {} };
14491
14684
  }
14492
14685
  writeState(state) {
14493
- const target = path4.join(this.root, STATE_FILE);
14494
- fs2.mkdirSync(this.root, { recursive: true });
14686
+ const target = path5.join(this.root, STATE_FILE);
14687
+ fs3.mkdirSync(this.root, { recursive: true });
14495
14688
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
14496
- fs2.writeFileSync(tmp, JSON.stringify(state, null, " "));
14497
- fs2.renameSync(tmp, target);
14689
+ fs3.writeFileSync(tmp, JSON.stringify(state, null, " "));
14690
+ fs3.renameSync(tmp, target);
14498
14691
  }
14499
14692
  hasRun(date) {
14500
14693
  const run = this.loadState().runs[date];
@@ -14559,6 +14752,7 @@ var MemoryStore = class _MemoryStore {
14559
14752
  if (!entry) continue;
14560
14753
  if (op.expectText !== void 0 && entry.text !== op.expectText) continue;
14561
14754
  if (op.op === "retire" && op.policy) {
14755
+ if (entry.provenance === "user-attested") continue;
14562
14756
  const cutoff = op.decidedCutoff ?? Date.now() - _MemoryStore.RETIRE_UNUSED_CUTOFF_MS;
14563
14757
  const lastUse = Math.max(entry.lastAccessed, entry.lastConsumedAt ?? 0);
14564
14758
  if (entry.usageCount !== 0 || lastUse >= cutoff) continue;
@@ -14603,6 +14797,7 @@ var MemoryStore = class _MemoryStore {
14603
14797
  const entry = entries.find((candidate) => candidate.id === op.id);
14604
14798
  if (entry) {
14605
14799
  entry.text = op.text;
14800
+ if (op.provenance) entry.provenance = op.provenance;
14606
14801
  for (const evidence of op.evidence) {
14607
14802
  const quote = redactText(evidence.quote).text;
14608
14803
  if (!quote) continue;
@@ -14622,9 +14817,9 @@ var MemoryStore = class _MemoryStore {
14622
14817
  }
14623
14818
  this.saveEntries(entries.filter((entry) => !archived.includes(entry)));
14624
14819
  if (archived.length > 0) {
14625
- const archivePath = path4.join(this.root, ARCHIVE_DIR, "retired.jsonl");
14626
- fs2.mkdirSync(path4.dirname(archivePath), { recursive: true });
14627
- fs2.appendFileSync(archivePath, archived.map((entry) => JSON.stringify(entry)).join("\n") + "\n");
14820
+ const archivePath = path5.join(this.root, ARCHIVE_DIR, "retired.jsonl");
14821
+ fs3.mkdirSync(path5.dirname(archivePath), { recursive: true });
14822
+ fs3.appendFileSync(archivePath, archived.map((entry) => JSON.stringify(entry)).join("\n") + "\n");
14628
14823
  }
14629
14824
  const projectKeys = /* @__PURE__ */ new Set([...this.listProjectKeys(), ...entries.filter((entry) => entry.projectKey).map((entry) => entry.projectKey)]);
14630
14825
  this.renderSurfaces([...projectKeys]);
@@ -14690,9 +14885,36 @@ function createMemoryEntry(init) {
14690
14885
  function normalizeForClustering(text) {
14691
14886
  return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
14692
14887
  }
14888
+ var CJK_RUN_RE = /[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]+/g;
14889
+ var HAS_CJK_RE = /[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/;
14890
+ function tokenizeForSimilarity(text) {
14891
+ const normalized = normalizeForClustering(text);
14892
+ const tokens = /* @__PURE__ */ new Set();
14893
+ for (const part of normalized.split(" ")) {
14894
+ if (!part) continue;
14895
+ const cjkRuns = part.match(CJK_RUN_RE);
14896
+ if (!cjkRuns) {
14897
+ tokens.add(part);
14898
+ continue;
14899
+ }
14900
+ for (const nonCjk of part.split(CJK_RUN_RE)) {
14901
+ if (nonCjk) tokens.add(nonCjk);
14902
+ }
14903
+ for (const run of cjkRuns) {
14904
+ if (run.length === 1) {
14905
+ tokens.add(run);
14906
+ } else {
14907
+ for (let i = 0; i < run.length - 1; i += 1) {
14908
+ tokens.add(run.slice(i, i + 2));
14909
+ }
14910
+ }
14911
+ }
14912
+ }
14913
+ return tokens;
14914
+ }
14693
14915
  function tokenJaccard(a, b) {
14694
- const tokensA = new Set(normalizeForClustering(a).split(" ").filter(Boolean));
14695
- const tokensB = new Set(normalizeForClustering(b).split(" ").filter(Boolean));
14916
+ const tokensA = tokenizeForSimilarity(a);
14917
+ const tokensB = tokenizeForSimilarity(b);
14696
14918
  if (tokensA.size === 0 || tokensB.size === 0) return 0;
14697
14919
  let shared = 0;
14698
14920
  for (const token of tokensA) if (tokensB.has(token)) shared += 1;
@@ -14722,9 +14944,13 @@ function polarity(text) {
14722
14944
  const tokens = normalized.split(" ").filter(Boolean);
14723
14945
  return tokens.some((token) => NEGATION_HEADS.includes(token)) ? "negated" : "affirmative";
14724
14946
  }
14725
- function containsWord(text, word) {
14947
+ function indexOfWord(text, word) {
14726
14948
  const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14727
- return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(text);
14949
+ const match2 = new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").exec(text);
14950
+ return match2 ? match2.index : -1;
14951
+ }
14952
+ function containsWord(text, word) {
14953
+ return indexOfWord(text, word) >= 0;
14728
14954
  }
14729
14955
  var ANTONYM_PAIRS = {
14730
14956
  ascii: [
@@ -14738,23 +14964,200 @@ var ANTONYM_PAIRS = {
14738
14964
  ],
14739
14965
  cjk: [
14740
14966
  ["\u6DF1\u8272", "\u6D45\u8272"],
14967
+ ["\u6697\u8272", "\u4EAE\u8272"],
14741
14968
  ["\u5F00\u542F", "\u5173\u95ED"],
14969
+ ["\u6253\u5F00", "\u5173\u95ED"],
14970
+ ["\u542F\u7528", "\u7981\u7528"],
14742
14971
  ["\u603B\u662F", "\u4ECE\u4E0D"],
14743
14972
  ["\u4E2D\u6587", "\u82F1\u6587"],
14744
- ["\u542F\u7528", "\u7981\u7528"]
14973
+ ["\u7B80\u6D01", "\u8BE6\u7EC6"],
14974
+ ["\u7B80\u77ED", "\u8BE6\u7EC6"],
14975
+ ["\u5141\u8BB8", "\u7981\u6B62"],
14976
+ ["\u559C\u6B22", "\u8BA8\u538C"],
14977
+ ["\u504F\u597D", "\u907F\u514D"]
14745
14978
  ]
14746
14979
  };
14980
+ var SENTENCE_STARTER_WORDS = /* @__PURE__ */ new Set([
14981
+ "user",
14982
+ "we",
14983
+ "prefer",
14984
+ "prefers",
14985
+ "always",
14986
+ "never",
14987
+ "use",
14988
+ "uses",
14989
+ "do",
14990
+ "does",
14991
+ "did",
14992
+ "enable",
14993
+ "disable",
14994
+ "keep",
14995
+ "keeps",
14996
+ "set",
14997
+ "sets",
14998
+ "read",
14999
+ "reads",
15000
+ "run",
15001
+ "runs",
15002
+ "build",
15003
+ "builds",
15004
+ "notify",
15005
+ "accepts",
15006
+ "resolves",
15007
+ "writes",
15008
+ "the",
15009
+ "my",
15010
+ "our",
15011
+ "default",
15012
+ "project",
15013
+ "editor",
15014
+ "terminal",
15015
+ "production",
15016
+ "staging",
15017
+ "theme",
15018
+ "mode"
15019
+ ]);
15020
+ function tokenizeCasePreserving(text) {
15021
+ const cleaned = text.trim().replace(/(?<=[\p{L}\p{N}])[.。]$/u, "");
15022
+ const tokens = cleaned.split(/\s+/).filter(Boolean);
15023
+ if (tokens.length > 0 && /^[A-Z][a-z]+$/.test(tokens[0]) && SENTENCE_STARTER_WORDS.has(tokens[0].toLowerCase())) {
15024
+ tokens[0] = tokens[0].toLowerCase();
15025
+ }
15026
+ return tokens;
15027
+ }
14747
15028
  function hasAntonymCross(a, b) {
15029
+ if (tokenizeCasePreserving(a).join(" ") === tokenizeCasePreserving(b).join(" ")) return false;
14748
15030
  const lowerA = a.toLowerCase();
14749
15031
  const lowerB = b.toLowerCase();
14750
15032
  for (const [x, y] of ANTONYM_PAIRS.ascii) {
14751
- if (containsWord(lowerA, x) && containsWord(lowerB, y) || containsWord(lowerA, y) && containsWord(lowerB, x)) {
14752
- return true;
15033
+ const aHasX = containsWord(lowerA, x);
15034
+ const aHasY = containsWord(lowerA, y);
15035
+ const bHasX = containsWord(lowerB, x);
15036
+ const bHasY = containsWord(lowerB, y);
15037
+ if (aHasX && bHasY || aHasY && bHasX) return true;
15038
+ }
15039
+ for (const [x, y] of ANTONYM_PAIRS.cjk) {
15040
+ const aHasX = a.includes(x);
15041
+ const aHasY = a.includes(y);
15042
+ const bHasX = b.includes(x);
15043
+ const bHasY = b.includes(y);
15044
+ if (aHasX && bHasY || aHasY && bHasX) return true;
15045
+ }
15046
+ return false;
15047
+ }
15048
+ var ASCII_INTERNAL_PUNCT_RE = /[.!?,;:]/;
15049
+ var ASCII_SUBORDINATE_RE = /\b(?:if|when|whenever|wherever|unless|until|while|whereas|although|though|because|since|after|before|where|which|that|who|whose|provided|providing|once|assuming|given|supposing|whether|as|in\s+case|in\s+the\s+event|so\s+long\s+as|on\s+condition|means|implies|triggers|causes|supports|allows|can|may|might)\b/i;
15050
+ var ASCII_EXCLUSIVE_VALUE_BEFORE_RE = /^(?:(?:(?:user|i|we)\s+)?(?:always\s+)?(?:prefer|prefers|use|uses|set|sets|keep|keeps)|(?:(?:the|my|our|default|project|repo|workspace|app|editor|terminal|ui|build|cli|ide)\s+){0,3}(?:theme|mode|style|output|language|cache)(?:\s+is)?)\s*$/i;
15051
+ var ASCII_VALUE_TAIL_RE = /^(?:\s+(?:theme|mode|colors?|output|language|style|please|now|currently|anymore)){0,2}$/i;
15052
+ var ASCII_QUANTIFIER_AFTER_RE = /^\s+(?:use|run|prefer|keep|squash|rebase|format|lint|write|reply|answer|respond|build|test)(?:\s+(?!(?:and|or|then)\b)[a-z0-9_-]+){1,6}$/i;
15053
+ function englishExclusiveSlotKind(text, word) {
15054
+ const trimmed = text.trim().replace(/[.!?]+$/, "").toLowerCase();
15055
+ if (!trimmed || ASCII_INTERNAL_PUNCT_RE.test(trimmed) || ASCII_SUBORDINATE_RE.test(trimmed)) return null;
15056
+ const pos = indexOfWord(trimmed, word);
15057
+ if (pos < 0) return null;
15058
+ const before = trimmed.slice(0, pos);
15059
+ const after = trimmed.slice(pos + word.length);
15060
+ if ((word === "always" || word === "never") && /^(?:(?:user|i|we)\s+)?$/.test(before)) {
15061
+ return ASCII_QUANTIFIER_AFTER_RE.test(after) ? "quantifier" : null;
15062
+ }
15063
+ return ASCII_EXCLUSIVE_VALUE_BEFORE_RE.test(before) && ASCII_VALUE_TAIL_RE.test(after) ? "value" : null;
15064
+ }
15065
+ function hasMatchingAsciiAntonymSwap(a, b) {
15066
+ if (hasTechnicalTokenMismatch(a, b)) return false;
15067
+ const lowerA = a.toLowerCase();
15068
+ const lowerB = b.toLowerCase();
15069
+ const maskWord = (text, word) => {
15070
+ const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15071
+ return text.replace(new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "giu"), "antonymslot");
15072
+ };
15073
+ const normalizeRemainder = (masked, slot) => {
15074
+ const tokens = tokenizeCasePreserving(masked);
15075
+ if (slot === "value" && tokens.length > 1) {
15076
+ const last = tokens[tokens.length - 1].toLowerCase();
15077
+ if (last === "now" || last === "currently" || last === "anymore") {
15078
+ tokens.pop();
15079
+ }
14753
15080
  }
15081
+ return tokens.join(" ");
15082
+ };
15083
+ const matchesPair = (first, second, w1, w2) => {
15084
+ const slot1 = englishExclusiveSlotKind(first, w1);
15085
+ const slot2 = englishExclusiveSlotKind(second, w2);
15086
+ if (!slot1 || slot1 !== slot2) return false;
15087
+ const masked1 = maskWord(first, w1);
15088
+ const masked2 = maskWord(second, w2);
15089
+ if (polarity(masked1) === "negated" || polarity(masked2) === "negated") return false;
15090
+ const rem1 = normalizeRemainder(masked1, slot1);
15091
+ const rem2 = normalizeRemainder(masked2, slot2);
15092
+ if (!rem1 || rem1 !== rem2) return false;
15093
+ return rem1.split(" ").filter(Boolean).length <= 8;
15094
+ };
15095
+ for (const [x, y] of ANTONYM_PAIRS.ascii) {
15096
+ const aHasX = containsWord(lowerA, x);
15097
+ const aHasY = containsWord(lowerA, y);
15098
+ const bHasX = containsWord(lowerB, x);
15099
+ const bHasY = containsWord(lowerB, y);
15100
+ if (aHasX && !aHasY && bHasY && !bHasX && matchesPair(a, b, x, y)) return true;
15101
+ if (aHasY && !aHasX && bHasX && !bHasY && matchesPair(a, b, y, x)) return true;
14754
15102
  }
15103
+ return false;
15104
+ }
15105
+ var CJK_CLAUSE_PUNCT_RE = /[,,;;。!?!?]/;
15106
+ var CJK_VALUE_ANTONYMS = /* @__PURE__ */ new Set([
15107
+ "\u6DF1\u8272",
15108
+ "\u6D45\u8272",
15109
+ "\u6697\u8272",
15110
+ "\u4EAE\u8272",
15111
+ "\u4E2D\u6587",
15112
+ "\u82F1\u6587",
15113
+ "\u7B80\u6D01",
15114
+ "\u8BE6\u7EC6",
15115
+ "\u7B80\u77ED"
15116
+ ]);
15117
+ var CJK_EXCLUSIVE_VALUE_BEFORE_RE = /^(?:(?:用户|我|系统|项目|编辑器|终端|默认)?(?:偏好|喜欢|使用|采用|设为|设置为|切换为|切换到)|(?:用户|我|系统|项目|编辑器|终端|默认|代码|界面|回答|回复|输出){0,2}(?:主题|模式|语言|风格|回答|输出)(?:是|为|[::=]))\s*$/;
15118
+ var CJK_VALUE_TAIL_RE = /^(?:的)?(?:主题|模式|风格|回答风格|回复风格|输出风格|回答|回复|输出|语言|界面|配色|外观)?$/;
15119
+ var CJK_QUANTIFIER_RE = /^(?:用户|我|项目|系统|编辑器|终端|默认)?(?:总是|从不)(?:使用|输出|回答|采用)(?:中文|英文)(?:回答|回复|输出)?$/;
15120
+ var CJK_TOGGLE_RE = /^(?:用户|我|项目|系统|编辑器|终端|默认)?(?:启用|禁用)(?:编辑器|终端|代码|系统|自动|实时|语法|行号|格式化|高亮|补全|保存|检查|缩进|换行|提示|预览|缓存|日志){1,4}$/;
15121
+ function isCjkValueOrPredicateSlot(text, token) {
15122
+ const trimmed = text.trim().replace(/[。!?!?]+$/, "");
15123
+ if (CJK_CLAUSE_PUNCT_RE.test(trimmed)) return false;
15124
+ const pos = trimmed.indexOf(token);
15125
+ if (pos < 0) return false;
15126
+ if (CJK_VALUE_ANTONYMS.has(token)) {
15127
+ const before = trimmed.slice(0, pos);
15128
+ const after = trimmed.slice(pos + token.length);
15129
+ return CJK_EXCLUSIVE_VALUE_BEFORE_RE.test(before) && CJK_VALUE_TAIL_RE.test(after);
15130
+ }
15131
+ if (token === "\u603B\u662F" || token === "\u4ECE\u4E0D") {
15132
+ return CJK_QUANTIFIER_RE.test(trimmed);
15133
+ }
15134
+ if (token === "\u542F\u7528" || token === "\u7981\u7528") {
15135
+ return CJK_TOGGLE_RE.test(trimmed);
15136
+ }
15137
+ return false;
15138
+ }
15139
+ function hasExactCjkAntonymSwap(a, b) {
15140
+ if (hasTechnicalTokenMismatch(a, b)) return false;
14755
15141
  for (const [x, y] of ANTONYM_PAIRS.cjk) {
14756
- if (a.includes(x) && b.includes(y) || a.includes(y) && b.includes(x)) {
14757
- return true;
15142
+ const aHasX = a.includes(x);
15143
+ const aHasY = a.includes(y);
15144
+ const bHasX = b.includes(x);
15145
+ const bHasY = b.includes(y);
15146
+ if (aHasX && !aHasY && bHasY && !bHasX) {
15147
+ if (!isCjkValueOrPredicateSlot(a, x) || !isCjkValueOrPredicateSlot(b, y)) continue;
15148
+ const maskedA = a.replaceAll(x, " ");
15149
+ const maskedB = b.replaceAll(y, " ");
15150
+ if (polarity(maskedA) === "affirmative" && polarity(maskedB) === "affirmative" && maskedA.replace(/[。!?!?]+$/, "").trim() === maskedB.replace(/[。!?!?]+$/, "").trim()) {
15151
+ return true;
15152
+ }
15153
+ }
15154
+ if (aHasY && !aHasX && bHasX && !bHasY) {
15155
+ if (!isCjkValueOrPredicateSlot(a, y) || !isCjkValueOrPredicateSlot(b, x)) continue;
15156
+ const maskedA = a.replaceAll(y, " ");
15157
+ const maskedB = b.replaceAll(x, " ");
15158
+ if (polarity(maskedA) === "affirmative" && polarity(maskedB) === "affirmative" && maskedA.replace(/[。!?!?]+$/, "").trim() === maskedB.replace(/[。!?!?]+$/, "").trim()) {
15159
+ return true;
15160
+ }
14758
15161
  }
14759
15162
  }
14760
15163
  return false;
@@ -14782,7 +15185,116 @@ var SUBJECT_DICTIONARY = [
14782
15185
  "eu",
14783
15186
  "us",
14784
15187
  "cn",
14785
- "apac"
15188
+ "apac",
15189
+ // Common lowercase technical/platform/component subjects so distinct
15190
+ // lowercase entities (e.g. redis vs postgres, python vs go, macos vs linux)
15191
+ // are not mistakenly collapsed as near-duplicates.
15192
+ "redis",
15193
+ "postgres",
15194
+ "postgresql",
15195
+ "mysql",
15196
+ "mariadb",
15197
+ "sqlite",
15198
+ "mongodb",
15199
+ "mongo",
15200
+ "nginx",
15201
+ "caddy",
15202
+ "apache",
15203
+ "haproxy",
15204
+ "docker",
15205
+ "kubernetes",
15206
+ "k8s",
15207
+ "python",
15208
+ "rust",
15209
+ "golang",
15210
+ "java",
15211
+ "kotlin",
15212
+ "swift",
15213
+ "ruby",
15214
+ "php",
15215
+ "typescript",
15216
+ "javascript",
15217
+ "react",
15218
+ "vue",
15219
+ "svelte",
15220
+ "angular",
15221
+ "nextjs",
15222
+ "unity",
15223
+ "godot",
15224
+ "unreal",
15225
+ "macos",
15226
+ "linux",
15227
+ "windows",
15228
+ "ubuntu",
15229
+ "debian",
15230
+ "ios",
15231
+ "android",
15232
+ "chrome",
15233
+ "chromium",
15234
+ "firefox",
15235
+ "safari",
15236
+ "edge",
15237
+ "frontend",
15238
+ "backend",
15239
+ "client",
15240
+ "worker",
15241
+ "manager",
15242
+ "daemon",
15243
+ "proxy",
15244
+ "gateway",
15245
+ "github",
15246
+ "gitlab",
15247
+ "bitbucket",
15248
+ "feishu",
15249
+ "lark",
15250
+ "slack",
15251
+ "discord"
15252
+ ];
15253
+ var CJK_SUBJECT_DICTIONARY = [
15254
+ // Environments & deployment stages
15255
+ "\u751F\u4EA7\u73AF\u5883",
15256
+ "\u7EBF\u4E0A\u73AF\u5883",
15257
+ "\u6D4B\u8BD5\u73AF\u5883",
15258
+ "\u5F00\u53D1\u73AF\u5883",
15259
+ "\u9884\u53D1\u73AF\u5883",
15260
+ "\u7070\u5EA6\u73AF\u5883",
15261
+ "\u672C\u5730\u73AF\u5883",
15262
+ "\u6C99\u76D2\u73AF\u5883",
15263
+ "\u751F\u4EA7",
15264
+ "\u7EBF\u4E0A",
15265
+ "\u6D4B\u8BD5",
15266
+ "\u9884\u53D1",
15267
+ "\u7070\u5EA6",
15268
+ "\u6C99\u76D2",
15269
+ "\u6F14\u7EC3",
15270
+ // Regions
15271
+ "\u56FD\u5185",
15272
+ "\u6D77\u5916",
15273
+ "\u5317\u7F8E",
15274
+ "\u6B27\u6D32",
15275
+ "\u4E9A\u592A",
15276
+ // Components & tiers
15277
+ "\u524D\u7AEF",
15278
+ "\u540E\u7AEF",
15279
+ "\u5BA2\u6237\u7AEF",
15280
+ "\u670D\u52A1\u7AEF",
15281
+ "\u79FB\u52A8\u7AEF",
15282
+ "\u684C\u9762\u7AEF",
15283
+ "\u7F51\u9875\u7AEF",
15284
+ "\u5C0F\u7A0B\u5E8F",
15285
+ "\u4E3B\u5E93",
15286
+ "\u4ECE\u5E93",
15287
+ "\u5907\u5E93",
15288
+ "\u7F13\u5B58",
15289
+ "\u6D88\u606F\u961F\u5217",
15290
+ // Time-scope qualifiers (avoid retiring daily/weekly/monthly independent facts)
15291
+ "\u6BCF\u65E5",
15292
+ "\u6BCF\u5929",
15293
+ "\u6BCF\u5468",
15294
+ "\u6BCF\u6708",
15295
+ "\u6BCF\u5E74",
15296
+ "\u5DE5\u4F5C\u65E5",
15297
+ "\u5468\u672B"
14786
15298
  ];
14787
15299
  function subjectsIn(text) {
14788
15300
  const lower = text.toLowerCase();
@@ -14790,6 +15302,9 @@ function subjectsIn(text) {
14790
15302
  for (const word of SUBJECT_DICTIONARY) {
14791
15303
  if (new RegExp(`(?<![\\p{L}\\p{N}])${word}(?![\\p{L}\\p{N}])`, "u").test(lower)) subjects.add(word);
14792
15304
  }
15305
+ for (const cjkSubject of CJK_SUBJECT_DICTIONARY) {
15306
+ if (text.includes(cjkSubject)) subjects.add(cjkSubject);
15307
+ }
14793
15308
  const raw = text.match(/\b(?:[A-Z][a-zA-Z0-9]{2,}|[a-z]+-[a-z][a-z-]+)\b/g) ?? [];
14794
15309
  for (const token of raw) {
14795
15310
  const lowered = token.toLowerCase();
@@ -14814,11 +15329,67 @@ function differentSubjects(a, b) {
14814
15329
  const exclusiveB = [...subjectsB].filter((token) => !subjectsA.has(token));
14815
15330
  return exclusiveA.some((token) => !GENERIC_SUBJECTS.has(token)) && exclusiveB.some((token) => !GENERIC_SUBJECTS.has(token));
14816
15331
  }
15332
+ function hasCjk(text) {
15333
+ return HAS_CJK_RE.test(text);
15334
+ }
15335
+ function isOrderedSubsequence(shorter, longer) {
15336
+ let i = 0;
15337
+ for (let j = 0; j < longer.length && i < shorter.length; j += 1) {
15338
+ if (shorter[i] === longer[j]) i += 1;
15339
+ }
15340
+ return i === shorter.length;
15341
+ }
15342
+ function orderPreservingOverlap(a, b, minRatio) {
15343
+ const stripClauseComma = (tok) => tok.replace(/(?<=[\p{L}\p{N}]),$/u, "");
15344
+ const toksA = tokenizeCasePreserving(a).map(stripClauseComma);
15345
+ const toksB = tokenizeCasePreserving(b).map(stripClauseComma);
15346
+ if (toksA.length === 0 || toksB.length === 0) return false;
15347
+ if (toksA.length === toksB.length) {
15348
+ return toksA.every((tok, idx) => tok === toksB[idx]);
15349
+ }
15350
+ const [shorter, longer] = toksA.length < toksB.length ? [toksA, toksB] : [toksB, toksA];
15351
+ if (shorter.length / longer.length < minRatio) return false;
15352
+ return isOrderedSubsequence(shorter, longer);
15353
+ }
15354
+ function canonicalCoreTokens(text) {
15355
+ const tokens = tokenizeCasePreserving(text);
15356
+ if (tokens.length > 1 && tokens[0].toLowerCase() === "user") tokens.shift();
15357
+ return tokens.join(" ");
15358
+ }
15359
+ function technicalTokensIn(text) {
15360
+ const out = [];
15361
+ const re = /(?<![A-Za-z0-9_.-])(--?[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9_])?|[A-Za-z0-9_-]+\.[A-Za-z](?:[A-Za-z0-9._-]*[A-Za-z0-9_])?|\.[A-Za-z0-9_](?:[A-Za-z0-9._-]*[A-Za-z0-9_])?)|(?<!\S)\.\.?(?!\S)/g;
15362
+ for (const match2 of text.matchAll(re)) {
15363
+ out.push(match2[1] ?? match2[0]);
15364
+ }
15365
+ return out;
15366
+ }
15367
+ function hasTechnicalTokenMismatch(a, b) {
15368
+ const toksA = technicalTokensIn(a);
15369
+ const toksB = technicalTokensIn(b);
15370
+ if (toksA.length === 0 && toksB.length === 0) return false;
15371
+ if (toksA.length !== toksB.length) return true;
15372
+ return toksA.some((tok, idx) => tok !== toksB[idx]);
15373
+ }
14817
15374
  function equivalentAssertions(a, b) {
14818
- return tokenJaccard(a, b) >= 0.5 && polarity(a) === polarity(b) && !hasAntonymCross(a, b) && !conflictingValues(a, b) && !differentSubjects(a, b);
15375
+ if (polarity(a) !== polarity(b) || hasAntonymCross(a, b) || conflictingValues(a, b) || differentSubjects(a, b) || hasTechnicalTokenMismatch(a, b)) {
15376
+ return false;
15377
+ }
15378
+ if (hasCjk(a) || hasCjk(b)) {
15379
+ return tokenizeCasePreserving(a).join(" ") === tokenizeCasePreserving(b).join(" ");
15380
+ }
15381
+ return orderPreservingOverlap(a, b, 0.5);
14819
15382
  }
14820
15383
  function nearDuplicate(a, b) {
14821
- return tokenJaccard(a, b) >= 0.7 && !conflictingValues(a, b) && !differentSubjects(a, b);
15384
+ if (polarity(a) !== polarity(b) || hasAntonymCross(a, b) || conflictingValues(a, b) || differentSubjects(a, b) || hasTechnicalTokenMismatch(a, b)) {
15385
+ return false;
15386
+ }
15387
+ if (hasCjk(a) || hasCjk(b)) {
15388
+ return tokenizeCasePreserving(a).join(" ") === tokenizeCasePreserving(b).join(" ");
15389
+ }
15390
+ const coreA = canonicalCoreTokens(a);
15391
+ const coreB = canonicalCoreTokens(b);
15392
+ return coreA.length > 0 && coreA === coreB;
14822
15393
  }
14823
15394
 
14824
15395
  // ../../packages/shared-headless-capabilities/src/memory/harvest.ts
@@ -14841,6 +15412,89 @@ var HARVEST_ROLES = /* @__PURE__ */ new Set(["user", "assistant"]);
14841
15412
  function storeSupportsSummaries(store) {
14842
15413
  return typeof store.getEntrySummaries === "function";
14843
15414
  }
15415
+ function stratifyRedactedMessages(allMessages, maxChars) {
15416
+ const totalChars = allMessages.reduce((sum, m) => sum + m.text.length, 0);
15417
+ if (totalChars <= maxChars) return allMessages;
15418
+ if (maxChars <= 0 || allMessages.length === 0) return [];
15419
+ if (allMessages.length === 1) {
15420
+ const single = allMessages[0];
15421
+ const marker = "\n[... truncated to harvest cap ...]\n";
15422
+ if (maxChars <= marker.length + 16) {
15423
+ return [{ role: single.role, text: single.text.slice(0, maxChars) }];
15424
+ }
15425
+ const avail = maxChars - marker.length;
15426
+ const headLen = Math.ceil(avail * 0.6);
15427
+ const tailLen = avail - headLen;
15428
+ return [{ role: single.role, text: single.text.slice(0, headLen) + marker + single.text.slice(-tailLen) }];
15429
+ }
15430
+ const reserveForMarker = maxChars >= 160 ? 80 : 0;
15431
+ const usable = Math.max(0, maxChars - reserveForMarker);
15432
+ const headBudget = Math.floor(usable * 0.6);
15433
+ const tailBudget = Math.max(0, usable - headBudget);
15434
+ const head = [];
15435
+ let headUsed = 0;
15436
+ let headIndex = 0;
15437
+ let partialBoundary = null;
15438
+ for (; headIndex < allMessages.length && headUsed < headBudget; headIndex += 1) {
15439
+ const msg = allMessages[headIndex];
15440
+ const remaining = headBudget - headUsed;
15441
+ if (msg.text.length <= remaining) {
15442
+ if (msg.text.trim()) {
15443
+ head.push({ role: msg.role, text: msg.text });
15444
+ headUsed += msg.text.length;
15445
+ }
15446
+ } else {
15447
+ const headSlice = msg.text.slice(0, remaining);
15448
+ if (headSlice.trim()) {
15449
+ head.push({ role: msg.role, text: headSlice });
15450
+ headUsed += headSlice.length;
15451
+ }
15452
+ partialBoundary = { index: headIndex, consumedHeadChars: remaining };
15453
+ headIndex += 1;
15454
+ break;
15455
+ }
15456
+ }
15457
+ const tail = [];
15458
+ let tailUsed = 0;
15459
+ let tailStart = allMessages.length;
15460
+ for (let i = allMessages.length - 1; i >= headIndex && tailUsed < tailBudget; i -= 1) {
15461
+ const msg = allMessages[i];
15462
+ const remaining = tailBudget - tailUsed;
15463
+ const text = msg.text.length <= remaining ? msg.text : msg.text.slice(-remaining);
15464
+ if (text.trim()) {
15465
+ tail.unshift({ role: msg.role, text });
15466
+ tailUsed += text.length;
15467
+ }
15468
+ tailStart = i;
15469
+ if (msg.text.length > remaining) break;
15470
+ }
15471
+ if (partialBoundary && tailUsed < tailBudget && tailStart === headIndex) {
15472
+ const boundaryMsg = allMessages[partialBoundary.index];
15473
+ const unconsumed = boundaryMsg.text.slice(partialBoundary.consumedHeadChars);
15474
+ const remaining = tailBudget - tailUsed;
15475
+ if (unconsumed.length > 0 && remaining > 0) {
15476
+ const tailSlice = unconsumed.length <= remaining ? unconsumed : unconsumed.slice(-remaining);
15477
+ if (tailSlice.trim()) {
15478
+ tail.unshift({ role: boundaryMsg.role, text: tailSlice });
15479
+ tailUsed += tailSlice.length;
15480
+ }
15481
+ }
15482
+ }
15483
+ const omitted = Math.max(0, tailStart - headIndex);
15484
+ const remainingBudget = Math.max(0, maxChars - headUsed - tailUsed);
15485
+ if (tail.length === 0) {
15486
+ const markerText2 = `[... ${omitted > 0 ? `${omitted} message(s) omitted` : "content truncated"} (harvest cap) ...]`;
15487
+ if (remainingBudget >= markerText2.length) {
15488
+ return [...head, { role: "system", text: markerText2 }];
15489
+ }
15490
+ return head;
15491
+ }
15492
+ const markerText = `[... ${omitted > 0 ? `${omitted} message(s) omitted` : "content truncated"} (harvest cap) ...]`;
15493
+ if (remainingBudget >= markerText.length) {
15494
+ return [...head, { role: "system", text: markerText }, ...tail];
15495
+ }
15496
+ return [...head, ...tail];
15497
+ }
14844
15498
  function harvestSessionByHeaders(store, sessionId, date, maxChars) {
14845
15499
  const matching = [];
14846
15500
  let afterSeq;
@@ -14857,25 +15511,57 @@ function harvestSessionByHeaders(store, sessionId, date, maxChars) {
14857
15511
  if (afterSeq === void 0) break;
14858
15512
  }
14859
15513
  if (matching.length === 0) return null;
14860
- const messages = [];
14861
15514
  let redactedAnything = false;
14862
- let used = 0;
14863
- for (const entryId of matching) {
14864
- if (used >= maxChars) break;
15515
+ const readRedacted = (entryId) => {
14865
15516
  const entry = store.readEntry(sessionId, entryId);
14866
- if (!entry) continue;
15517
+ if (!entry) return null;
14867
15518
  const message = entry.message;
14868
- if (!message || typeof message.role !== "string" || !HARVEST_ROLES.has(message.role)) continue;
15519
+ if (!message || typeof message.role !== "string" || !HARVEST_ROLES.has(message.role)) return null;
14869
15520
  const raw = messageText(message.content);
14870
- if (!raw.trim()) continue;
15521
+ if (!raw.trim()) return null;
14871
15522
  const { text, counts } = redactText(raw);
14872
15523
  if (Object.keys(counts).length > 0) redactedAnything = true;
14873
- const clipped = text.slice(0, maxChars - used);
14874
- if (!clipped.trim()) continue;
14875
- used += clipped.length;
14876
- messages.push({ role: message.role, text: clipped });
15524
+ return text.trim() ? { role: message.role, text } : null;
15525
+ };
15526
+ const headCollected = [];
15527
+ let used = 0;
15528
+ let stoppedAt = matching.length;
15529
+ for (let i = 0; i < matching.length; i += 1) {
15530
+ const msg = readRedacted(matching[i]);
15531
+ if (!msg) continue;
15532
+ headCollected.push(msg);
15533
+ used += msg.text.length;
15534
+ if (used > maxChars) {
15535
+ stoppedAt = i + 1;
15536
+ break;
15537
+ }
15538
+ }
15539
+ if (headCollected.length === 0) return null;
15540
+ if (used <= maxChars) {
15541
+ return { messages: headCollected, redacted: redactedAnything };
15542
+ }
15543
+ const tailBudget = Math.max(Math.ceil(maxChars * 0.4), 1);
15544
+ const tailCollected = [];
15545
+ let tailChars = 0;
15546
+ let tailStartIdx = matching.length;
15547
+ for (let i = matching.length - 1; i >= stoppedAt && tailChars < tailBudget; i -= 1) {
15548
+ const msg = readRedacted(matching[i]);
15549
+ if (!msg) continue;
15550
+ tailCollected.unshift(msg);
15551
+ tailChars += msg.text.length;
15552
+ tailStartIdx = i;
15553
+ }
15554
+ const skippedMiddleCount = Math.max(0, tailStartIdx - stoppedAt);
15555
+ const combined = [...headCollected, ...tailCollected];
15556
+ const messages = stratifyRedactedMessages(combined, maxChars);
15557
+ if (skippedMiddleCount > 0) {
15558
+ const marker = messages.find((m) => m.role === "system" && m.text.includes("harvest cap"));
15559
+ if (marker) {
15560
+ const match2 = /\[\.\.\.\s*(\d+)\s+message/.exec(marker.text);
15561
+ const existingOmitted = match2 ? Number(match2[1]) : 0;
15562
+ marker.text = `[... ${existingOmitted + skippedMiddleCount} message(s) omitted (harvest cap) ...]`;
15563
+ }
14877
15564
  }
14878
- if (messages.length === 0) return null;
14879
15565
  return { messages, redacted: redactedAnything };
14880
15566
  }
14881
15567
  function harvestSessionsForDate(store, date, options = {}) {
@@ -14893,14 +15579,63 @@ function harvestSessionsForDate(store, date, options = {}) {
14893
15579
  if (prefilter) {
14894
15580
  material = harvestSessionByHeaders(store, sessionId, date, maxChars);
14895
15581
  } else {
14896
- const messages = [];
15582
+ const reserveForMarker = maxChars >= 160 ? 80 : 0;
15583
+ const usableBudget = Math.max(1, maxChars - reserveForMarker);
15584
+ const headBudget = Math.max(1, Math.floor(usableBudget * 0.6));
15585
+ const tailBudget = Math.max(1, usableBudget - headBudget);
15586
+ const head = [];
15587
+ let headChars = 0;
15588
+ let overflowed = false;
15589
+ const tail = [];
15590
+ let tailChars = 0;
15591
+ let omitted = 0;
14897
15592
  let redactedAnything = false;
14898
- let used = 0;
14899
15593
  let afterSeq;
15594
+ const pushTail = (msg) => {
15595
+ if (msg.text.length > tailBudget) {
15596
+ omitted += tail.length;
15597
+ tail.length = 0;
15598
+ tail.push({ role: msg.role, text: msg.text.slice(-tailBudget) });
15599
+ tailChars = tail[0].text.length;
15600
+ return;
15601
+ }
15602
+ tail.push(msg);
15603
+ tailChars += msg.text.length;
15604
+ while (tail.length > 1 && tailChars > tailBudget) {
15605
+ const dropped = tail.shift();
15606
+ tailChars -= dropped.text.length;
15607
+ omitted += 1;
15608
+ }
15609
+ };
15610
+ const enterOverflow = (incoming) => {
15611
+ overflowed = true;
15612
+ const prior = head.splice(0, head.length);
15613
+ headChars = 0;
15614
+ let filled = false;
15615
+ for (const msg of [...prior, incoming]) {
15616
+ if (!filled) {
15617
+ if (headChars + msg.text.length <= headBudget) {
15618
+ head.push(msg);
15619
+ headChars += msg.text.length;
15620
+ } else {
15621
+ const rem = headBudget - headChars;
15622
+ const prefix = rem > 0 ? msg.text.slice(0, rem) : "";
15623
+ const suffix = rem > 0 ? msg.text.slice(rem) : msg.text;
15624
+ if (prefix.length > 0) {
15625
+ head.push({ role: msg.role, text: prefix });
15626
+ headChars += prefix.length;
15627
+ }
15628
+ filled = true;
15629
+ if (suffix.length > 0) pushTail({ role: msg.role, text: suffix });
15630
+ }
15631
+ } else {
15632
+ pushTail(msg);
15633
+ }
15634
+ }
15635
+ };
14900
15636
  for (; ; ) {
14901
15637
  const page = store.iterateEntries(sessionId, { limit: 50, afterSeq });
14902
15638
  for (const entry of page.entries) {
14903
- if (used >= maxChars) break;
14904
15639
  const timestamp = entry.timestamp ?? 0;
14905
15640
  if (dayOf(timestamp) !== date) continue;
14906
15641
  const message = entry.message;
@@ -14909,14 +15644,30 @@ function harvestSessionsForDate(store, date, options = {}) {
14909
15644
  if (!raw.trim()) continue;
14910
15645
  const { text, counts } = redactText(raw);
14911
15646
  if (Object.keys(counts).length > 0) redactedAnything = true;
14912
- const clipped = text.slice(0, maxChars - used);
14913
- if (!clipped.trim()) continue;
14914
- used += clipped.length;
14915
- messages.push({ role: message.role, text: clipped });
15647
+ if (!text.trim()) continue;
15648
+ if (!overflowed) {
15649
+ if (headChars + text.length <= maxChars) {
15650
+ head.push({ role: message.role, text });
15651
+ headChars += text.length;
15652
+ } else {
15653
+ enterOverflow({ role: message.role, text });
15654
+ }
15655
+ } else {
15656
+ pushTail({ role: message.role, text });
15657
+ }
14916
15658
  }
14917
- if (!page.hasMore || used >= maxChars) break;
15659
+ if (!page.hasMore) break;
14918
15660
  afterSeq = page.lastSeq;
14919
15661
  }
15662
+ const messages = [...head];
15663
+ if (overflowed) {
15664
+ const label = omitted > 0 ? `${omitted} message(s)` : "content";
15665
+ const marker = `[... ${label} omitted (harvest cap) ...]`;
15666
+ if (headChars + tailChars + marker.length <= maxChars) {
15667
+ messages.push({ role: "system", text: marker });
15668
+ }
15669
+ messages.push(...tail);
15670
+ }
14920
15671
  if (messages.length > 0) material = { messages, redacted: redactedAnything };
14921
15672
  }
14922
15673
  if (!material) continue;
@@ -14968,12 +15719,17 @@ var DISTILL_SYSTEM = "You are a precise extraction engine. Output JSON only.";
14968
15719
  function parseDistillResponse(response) {
14969
15720
  const jsonSlice = extractJsonArray(response);
14970
15721
  if (!jsonSlice) throw new Error("distill response contains no JSON array");
14971
- const parsed = JSON.parse(jsonSlice);
15722
+ let parsed;
15723
+ try {
15724
+ parsed = JSON.parse(jsonSlice);
15725
+ } catch {
15726
+ throw new Error("distill response contains invalid JSON");
15727
+ }
14972
15728
  if (!Array.isArray(parsed)) throw new Error("distill response is not an array");
14973
15729
  return parsed.map((value) => {
14974
15730
  if (!value || typeof value !== "object") throw new Error("distill candidate is not an object");
14975
15731
  const candidate = value;
14976
- if (!["preference", "fact", "project", "thread"].includes(String(candidate.kind)) || typeof candidate.text !== "string" || !candidate.text.trim() || !Array.isArray(candidate.quotes) || candidate.quotes.length === 0 || candidate.quotes.some((quote) => typeof quote !== "string" || !quote.trim())) {
15732
+ if (!["preference", "fact", "project", "thread"].includes(String(candidate.kind)) || typeof candidate.text !== "string" || !candidate.text.trim() || /[\r\n]/.test(candidate.text.trim()) || !Array.isArray(candidate.quotes) || candidate.quotes.length === 0 || candidate.quotes.some((quote) => typeof quote !== "string" || !quote.trim())) {
14977
15733
  throw new Error("distill candidate has invalid shape");
14978
15734
  }
14979
15735
  for (const quote of candidate.quotes) {
@@ -15095,14 +15851,28 @@ function surfaceForKind(kind) {
15095
15851
  }
15096
15852
  function synthesizePatch(input) {
15097
15853
  const limits = input.limits ?? DEFAULT_MEMORY_DISTILL_LIMITS;
15098
- const ops = [];
15854
+ const addOps = [];
15855
+ const updateOps = [];
15856
+ const refreshedIds = /* @__PURE__ */ new Set();
15857
+ const canonicalKey = (pk) => {
15858
+ if (!pk) return "";
15859
+ return input.projectKeyAliases?.get(pk) ?? pk;
15860
+ };
15099
15861
  for (const cluster of input.clusters) {
15100
- if (ops.length >= limits.maxPatchOps) break;
15862
+ const clusterProjectKey = canonicalKey(cluster.projectKey);
15101
15863
  const similar = input.existingEntries.find(
15102
- (entry2) => entry2.kind === cluster.kind && (entry2.projectKey ?? "") === (cluster.projectKey ?? "") && equivalentAssertions(entry2.text, cluster.text)
15864
+ (entry2) => entry2.kind === cluster.kind && canonicalKey(entry2.projectKey) === clusterProjectKey && equivalentAssertions(entry2.text, cluster.text)
15103
15865
  );
15104
15866
  if (similar) {
15105
- ops.push({ op: "update", id: similar.id, text: similar.text, evidence: evidenceFor(cluster), expectText: similar.text });
15867
+ refreshedIds.add(similar.id);
15868
+ const existingKeys = new Set(
15869
+ similar.evidence.map((ev) => `${ev.sessionId}\0${ev.quote.slice(0, 240)}`)
15870
+ );
15871
+ const newEvidence = evidenceFor(cluster).filter(
15872
+ (ev) => !existingKeys.has(`${ev.sessionId}\0${ev.quote.slice(0, 240)}`)
15873
+ );
15874
+ if (newEvidence.length === 0) continue;
15875
+ updateOps.push({ op: "update", id: similar.id, text: similar.text, evidence: newEvidence, expectText: similar.text });
15106
15876
  continue;
15107
15877
  }
15108
15878
  const firstSessionId = [...cluster.sessions.keys()][0] ?? "unknown";
@@ -15116,13 +15886,28 @@ function synthesizePatch(input) {
15116
15886
  ...cluster.projectKey ? { projectKey: cluster.projectKey } : {},
15117
15887
  now: input.now
15118
15888
  });
15119
- ops.push({ op: "add", entry });
15889
+ addOps.push({ op: "add", entry });
15120
15890
  }
15121
- return { date: input.date, ops };
15891
+ const prioritized = [...addOps, ...updateOps];
15892
+ const ops = prioritized.slice(0, limits.maxPatchOps);
15893
+ const overflowAddCount = Math.max(0, addOps.length - limits.maxPatchOps);
15894
+ return { date: input.date, ops, refreshedIds: [...refreshedIds], overflowAddCount };
15122
15895
  }
15123
15896
  function buildRetentionOps(entries, limits = DEFAULT_MEMORY_DISTILL_LIMITS, now = Date.now(), refreshedIds = /* @__PURE__ */ new Set()) {
15124
15897
  const cutoff = now - limits.retireUnusedAfterDays * 24 * 60 * 60 * 1e3;
15125
- return entries.filter((entry) => !refreshedIds.has(entry.id) && entry.usageCount === 0 && entry.lastAccessed < cutoff).map((entry) => ({ op: "retire", id: entry.id, reason: `unused since ${new Date(entry.lastAccessed).toISOString()}`, expectText: entry.text, policy: true, decidedCutoff: cutoff }));
15898
+ return entries.filter((entry) => {
15899
+ if (entry.provenance === "user-attested") return false;
15900
+ if (refreshedIds.has(entry.id)) return false;
15901
+ const lastUse = Math.max(entry.lastAccessed, entry.lastConsumedAt ?? 0);
15902
+ return entry.usageCount === 0 && lastUse < cutoff;
15903
+ }).map((entry) => ({
15904
+ op: "retire",
15905
+ id: entry.id,
15906
+ reason: `unused since ${new Date(Math.max(entry.lastAccessed, entry.lastConsumedAt ?? 0)).toISOString()}`,
15907
+ expectText: entry.text,
15908
+ policy: true,
15909
+ decidedCutoff: cutoff
15910
+ }));
15126
15911
  }
15127
15912
  var SYNTHESIZE_SYSTEM = "You are a memory consolidation engine. You write concise, factual, source-grounded prose in the requested language.";
15128
15913
  async function writeJournalNarrative(input) {
@@ -15159,8 +15944,8 @@ function detectLanguage(sessions) {
15159
15944
  }
15160
15945
 
15161
15946
  // ../../packages/shared-headless-capabilities/src/memory/save.ts
15162
- import * as fs3 from "node:fs";
15163
- import * as path5 from "node:path";
15947
+ import * as fs4 from "node:fs";
15948
+ import * as path6 from "node:path";
15164
15949
  function surfaceForKind2(kind) {
15165
15950
  switch (kind) {
15166
15951
  case "preference":
@@ -15173,14 +15958,59 @@ function surfaceForKind2(kind) {
15173
15958
  return "memory";
15174
15959
  }
15175
15960
  }
15176
- var SLOT_DOMAINS = ["theme", "\u4E3B\u9898", "editor", "\u7F16\u8F91\u5668", "shell", "\u7EC8\u7AEF", "language", "\u8BED\u8A00", "\u56DE\u7B54", "replies", "answers", "build", "\u6784\u5EFA", "highlighting", "\u9AD8\u4EAE"];
15961
+ var SLOT_DOMAINS = [
15962
+ "theme",
15963
+ "\u4E3B\u9898",
15964
+ "editor",
15965
+ "\u7F16\u8F91\u5668",
15966
+ "shell",
15967
+ "\u7EC8\u7AEF",
15968
+ "language",
15969
+ "\u8BED\u8A00",
15970
+ "\u56DE\u7B54",
15971
+ "\u56DE\u590D",
15972
+ "replies",
15973
+ "answers",
15974
+ "build",
15975
+ "\u6784\u5EFA",
15976
+ "highlighting",
15977
+ "\u9AD8\u4EAE",
15978
+ "\u98CE\u683C",
15979
+ "\u989C\u8272",
15980
+ "\u6A21\u5F0F",
15981
+ "\u8F93\u51FA",
15982
+ "\u683C\u5F0F",
15983
+ "\u5DE5\u5177"
15984
+ ];
15177
15985
  function slotOf(text) {
15178
15986
  const lower = text.toLowerCase();
15179
15987
  return SLOT_DOMAINS.find((domain) => containsWord(lower, domain) || text.includes(domain)) ?? "";
15180
15988
  }
15181
15989
  function oppositePreference(a, b) {
15990
+ if (hasTechnicalTokenMismatch(a, b)) return false;
15182
15991
  if (differentSubjects(a, b)) return false;
15183
- return hasAntonymCross(a, b) && slotOf(a) !== "" && slotOf(a) === slotOf(b);
15992
+ if (slotOf(a) === "" || slotOf(a) !== slotOf(b)) return false;
15993
+ if (hasCjk(a) || hasCjk(b)) {
15994
+ return hasExactCjkAntonymSwap(a, b);
15995
+ }
15996
+ return hasMatchingAsciiAntonymSwap(a, b);
15997
+ }
15998
+ function directNegationCorrection(existingText, nextText) {
15999
+ if (hasCjk(existingText) || hasCjk(nextText)) return false;
16000
+ if (hasTechnicalTokenMismatch(existingText, nextText)) return false;
16001
+ if (differentSubjects(existingText, nextText)) return false;
16002
+ if (conflictingValues(existingText, nextText)) return false;
16003
+ if (polarity(existingText) === polarity(nextText)) return false;
16004
+ const canonicalize = (text) => tokenizeCasePreserving(text).join(" ");
16005
+ const stripLeadingNeg = (text) => {
16006
+ const trimmed = text.trim().replace(/\s+/g, " ");
16007
+ const stripped = trimmed.replace(/^(?:do\s+not|does\s+not|did\s+not|don't|doesn't|didn't|never|not)\s+/i, "");
16008
+ if (stripped === trimmed || stripped.length === 0) return null;
16009
+ return canonicalize(stripped);
16010
+ };
16011
+ const normA = canonicalize(existingText);
16012
+ const normB = canonicalize(nextText);
16013
+ return stripLeadingNeg(existingText) === normB || stripLeadingNeg(nextText) === normA;
15184
16014
  }
15185
16015
  function saveAttestedEntry(store, input) {
15186
16016
  if (input.text.trim().length > 240) {
@@ -15195,19 +16025,33 @@ function saveAttestedEntry(store, input) {
15195
16025
  const rawQuote = input.quote.trim();
15196
16026
  if (!rawQuote) throw new Error("memory_save requires the user's verbatim quote as evidence");
15197
16027
  const quote = redactText(rawQuote).text;
15198
- const projectKey = input.kind === "project" && input.cwd ? projectKeyForDir(input.cwd).key : void 0;
16028
+ const projectInfo = input.kind === "project" && input.cwd ? projectKeyForDir(input.cwd) : void 0;
16029
+ const projectKey = projectInfo?.key;
16030
+ const matchingProjectKeys = new Set(projectInfo?.allKeys ?? []);
15199
16031
  if (input.kind === "project" && projectKey && input.cwd) {
15200
16032
  store.writeProjectMeta({ key: projectKey, path: redactText(input.cwd).text, readableName: redactText(input.cwd).text });
15201
16033
  }
15202
16034
  return store.transaction(() => {
15203
- const conflicting = store.loadEntries().filter((entry2) => {
16035
+ const activeEntries = store.loadEntries();
16036
+ const replaceId = input.replaces?.trim();
16037
+ let explicitTarget;
16038
+ if (replaceId) {
16039
+ explicitTarget = activeEntries.find((entry2) => entry2.id === replaceId);
16040
+ if (!explicitTarget) {
16041
+ throw new Error(`memory_save replaces target not found or already retired: ${replaceId}`);
16042
+ }
16043
+ }
16044
+ const conflicting = activeEntries.filter((entry2) => {
16045
+ if (explicitTarget && entry2.id === explicitTarget.id) return false;
15204
16046
  if (entry2.kind !== input.kind) return false;
15205
16047
  if (input.kind === "project") {
15206
- if (entry2.projectKey !== projectKey) return false;
15207
- return nearDuplicate(entry2.text, text) || oppositePreference(entry2.text, text);
16048
+ if (!entry2.projectKey || !matchingProjectKeys.has(entry2.projectKey)) return false;
16049
+ const allowOpposite2 = !hasCjk(entry2.text) && !hasCjk(text);
16050
+ return nearDuplicate(entry2.text, text) || allowOpposite2 && oppositePreference(entry2.text, text) || directNegationCorrection(entry2.text, text);
15208
16051
  }
15209
16052
  if (entry2.surface !== surfaceForKind2(input.kind)) return false;
15210
- return nearDuplicate(entry2.text, text) || oppositePreference(entry2.text, text);
16053
+ const allowOpposite = input.kind === "preference";
16054
+ return nearDuplicate(entry2.text, text) || allowOpposite && oppositePreference(entry2.text, text) || directNegationCorrection(entry2.text, text);
15211
16055
  });
15212
16056
  const entry = createMemoryEntry({
15213
16057
  kind: input.kind,
@@ -15219,6 +16063,9 @@ function saveAttestedEntry(store, input) {
15219
16063
  ...projectKey ? { projectKey } : {}
15220
16064
  });
15221
16065
  const ops = [{ op: "add", entry }];
16066
+ if (explicitTarget) {
16067
+ ops.push({ op: "retire", id: explicitTarget.id, reason: `explicitly replaced by attested entry ${entry.id}: ${text.slice(0, 80)}` });
16068
+ }
15222
16069
  for (const old of conflicting) {
15223
16070
  ops.push({ op: "retire", id: old.id, reason: `superseded by attested entry: ${text.slice(0, 80)}` });
15224
16071
  }
@@ -15239,10 +16086,10 @@ function recordAccess(store, entryIds) {
15239
16086
  }
15240
16087
  }
15241
16088
  if (!touched) return;
15242
- const target = path5.join(store.dir, ".entries.json");
16089
+ const target = path6.join(store.dir, ".entries.json");
15243
16090
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
15244
- fs3.writeFileSync(tmp, JSON.stringify({ version: 1, entries }, null, " "));
15245
- fs3.renameSync(tmp, target);
16091
+ fs4.writeFileSync(tmp, JSON.stringify({ version: 1, entries }, null, " "));
16092
+ fs4.renameSync(tmp, target);
15246
16093
  });
15247
16094
  }
15248
16095
  function recordInjection(store, entryIds) {
@@ -15257,10 +16104,10 @@ function recordInjection(store, entryIds) {
15257
16104
  }
15258
16105
  }
15259
16106
  if (!touched) return;
15260
- const target = path5.join(store.dir, ".entries.json");
16107
+ const target = path6.join(store.dir, ".entries.json");
15261
16108
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
15262
- fs3.writeFileSync(tmp, JSON.stringify({ version: 1, entries }, null, " "));
15263
- fs3.renameSync(tmp, target);
16109
+ fs4.writeFileSync(tmp, JSON.stringify({ version: 1, entries }, null, " "));
16110
+ fs4.renameSync(tmp, target);
15264
16111
  });
15265
16112
  }
15266
16113
  var GENERIC_ZH_WINDOWS = /* @__PURE__ */ new Set([
@@ -15415,10 +16262,10 @@ function recordConsumption(store, injectedIds, output) {
15415
16262
  }
15416
16263
  }
15417
16264
  if (!touched) return;
15418
- const target = path5.join(store.dir, ".entries.json");
16265
+ const target = path6.join(store.dir, ".entries.json");
15419
16266
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
15420
- fs3.writeFileSync(tmp, JSON.stringify({ version: 1, entries }, null, " "));
15421
- fs3.renameSync(tmp, target);
16267
+ fs4.writeFileSync(tmp, JSON.stringify({ version: 1, entries }, null, " "));
16268
+ fs4.renameSync(tmp, target);
15422
16269
  });
15423
16270
  return { consumed };
15424
16271
  }
@@ -15438,38 +16285,61 @@ function consumptionSummary(entries) {
15438
16285
  }
15439
16286
 
15440
16287
  // ../../packages/shared-headless-capabilities/src/memory/search.ts
15441
- import * as fs4 from "node:fs";
15442
- import * as path6 from "node:path";
16288
+ import * as fs5 from "node:fs";
16289
+ import * as path7 from "node:path";
15443
16290
  function searchMemory(store, query, options = {}) {
15444
16291
  const limit = options.limit ?? 20;
15445
- const hits = [];
16292
+ const candidates = [];
15446
16293
  const needle = options.caseInsensitive === false ? query : query.toLowerCase();
15447
16294
  const matches = (text) => (options.caseInsensitive === false ? text : text.toLowerCase()).includes(needle);
16295
+ const allowedProjectKeys = options.projectKey ? new Set(Array.isArray(options.projectKey) ? options.projectKey : [options.projectKey]) : void 0;
15448
16296
  for (const entry of store.loadEntries()) {
15449
16297
  if (options.kind && entry.kind !== options.kind) continue;
15450
- if (!matches(entry.text) && !entry.evidence.some((item) => matches(item.quote))) continue;
15451
- hits.push({
15452
- entryId: entry.id,
15453
- source: "entry",
15454
- path: entry.surface === "project" && entry.projectKey ? `projects/${entry.projectKey}/MEMORY.md` : surfaceFile(entry.surface),
15455
- kind: entry.kind,
15456
- text: entry.text
16298
+ if (allowedProjectKeys && entry.kind === "project" && (!entry.projectKey || !allowedProjectKeys.has(entry.projectKey))) continue;
16299
+ const textMatch = matches(entry.text);
16300
+ const quoteMatch = !textMatch && entry.evidence.some((item) => matches(item.quote));
16301
+ if (!textMatch && !quoteMatch) continue;
16302
+ const exactText = (options.caseInsensitive === false ? entry.text : entry.text.toLowerCase()) === needle;
16303
+ candidates.push({
16304
+ hit: {
16305
+ entryId: entry.id,
16306
+ source: "entry",
16307
+ path: (entry.surface === "project" || entry.kind === "project") && entry.projectKey ? `projects/${entry.projectKey}/MEMORY.md` : surfaceFile(entry.surface),
16308
+ kind: entry.kind,
16309
+ text: entry.text
16310
+ },
16311
+ tier: exactText ? 4 : textMatch ? 3 : 2,
16312
+ secondary: entry.usageCount + (entry.provenance === "user-attested" ? 1 : 0),
16313
+ recency: Math.max(entry.lastAccessed, entry.lastConsumedAt ?? 0, entry.created)
15457
16314
  });
15458
16315
  }
15459
- for (const date of store.listJournalDates().slice(-60)) {
15460
- const content = store.readJournal(date);
15461
- if (!content || !matches(content)) continue;
15462
- hits.push({
15463
- source: "journal",
15464
- path: `journal/${date}.md`,
15465
- kind: "fact",
15466
- text: `journal ${date} mentions "${query}"`
15467
- });
16316
+ if (!options.kind || options.kind === "fact") {
16317
+ for (const date of store.listJournalDates().slice(-60).reverse()) {
16318
+ const content = store.readJournal(date);
16319
+ if (!content || !matches(content)) continue;
16320
+ const dateTs = Date.parse(`${date}T00:00:00Z`) || 0;
16321
+ candidates.push({
16322
+ hit: {
16323
+ source: "journal",
16324
+ path: `journal/${date}.md`,
16325
+ kind: "fact",
16326
+ text: `journal ${date} mentions "${query}"`
16327
+ },
16328
+ tier: 1,
16329
+ secondary: 0,
16330
+ recency: dateTs
16331
+ });
16332
+ }
15468
16333
  }
15469
- const ranked = hits.sort((a, b) => rank(b) - rank(a)).slice(0, limit);
16334
+ const ranked = candidates.sort((a, b) => b.tier - a.tier || b.recency - a.recency || b.secondary - a.secondary).slice(0, limit).map((item) => item.hit);
15470
16335
  const accessedIds = ranked.map((hit) => hit.entryId).filter((id) => Boolean(id));
15471
- if (accessedIds.length > 0) recordAccess(store, accessedIds);
15472
- return { hits: ranked, truncated: hits.length > ranked.length };
16336
+ if (accessedIds.length > 0) {
16337
+ try {
16338
+ recordAccess(store, accessedIds);
16339
+ } catch {
16340
+ }
16341
+ }
16342
+ return { hits: ranked, truncated: candidates.length > ranked.length };
15473
16343
  }
15474
16344
  function surfaceFile(surface) {
15475
16345
  switch (surface) {
@@ -15485,26 +16355,29 @@ function surfaceFile(surface) {
15485
16355
  return "projects/";
15486
16356
  }
15487
16357
  }
15488
- function rank(hit) {
15489
- return hit.source === "entry" ? 1 : 0;
15490
- }
15491
16358
  function readMemoryFile(store, relativePath) {
15492
- const target = path6.resolve(store.dir, relativePath);
15493
- if (!target.startsWith(path6.resolve(store.dir))) return void 0;
16359
+ const root = path7.resolve(store.dir);
16360
+ const target = path7.resolve(root, relativePath);
16361
+ const rootWithSep = root.endsWith(path7.sep) ? root : root + path7.sep;
16362
+ if (target !== root && !target.startsWith(rootWithSep)) return void 0;
15494
16363
  try {
15495
- return fs4.readFileSync(target, "utf8");
16364
+ const realRoot = fs5.realpathSync(root);
16365
+ const realTarget = fs5.realpathSync(target);
16366
+ const realRootWithSep = realRoot.endsWith(path7.sep) ? realRoot : realRoot + path7.sep;
16367
+ if (realTarget !== realRoot && !realTarget.startsWith(realRootWithSep)) return void 0;
16368
+ return fs5.readFileSync(realTarget, "utf8");
15496
16369
  } catch {
15497
16370
  return void 0;
15498
16371
  }
15499
16372
  }
15500
16373
 
15501
16374
  // ../../packages/shared-headless-capabilities/src/memory/engine.ts
15502
- import * as fs6 from "node:fs";
15503
- import * as path8 from "node:path";
16375
+ import * as fs7 from "node:fs";
16376
+ import * as path9 from "node:path";
15504
16377
 
15505
16378
  // ../../packages/shared-headless-capabilities/src/memory/ledger.ts
15506
- import * as fs5 from "node:fs";
15507
- import * as path7 from "node:path";
16379
+ import * as fs6 from "node:fs";
16380
+ import * as path8 from "node:path";
15508
16381
  import { randomUUID } from "node:crypto";
15509
16382
  var FILE = "evidence-ledger.json";
15510
16383
  var DAYS = 7;
@@ -15536,12 +16409,16 @@ function encode(c) {
15536
16409
  sessions: [...c.sessions].slice(0, MAX_SESSIONS).map(([id, quotes]) => [id, [...new Set(quotes)].slice(0, 2).map((q) => redactText(q).text.slice(0, 240))])
15537
16410
  };
15538
16411
  }
15539
- function prepareEvidenceLedger(dir, date, today) {
16412
+ function canonicalProjectKey(key, aliases) {
16413
+ if (!key) return "";
16414
+ return aliases?.get(key) ?? key;
16415
+ }
16416
+ function prepareEvidenceLedger(dir, date, today, projectKeyAliases) {
15540
16417
  if (!validDate(date)) throw new Error("invalid evidence date");
15541
- const file = path7.join(dir, FILE);
16418
+ const file = path8.join(dir, FILE);
15542
16419
  let ledger = { version: 1, days: [] };
15543
16420
  try {
15544
- if (fs5.statSync(file).size <= MAX_BYTES) ledger = decode(JSON.parse(fs5.readFileSync(file, "utf8")));
16421
+ if (fs6.statSync(file).size <= MAX_BYTES) ledger = decode(JSON.parse(fs6.readFileSync(file, "utf8")));
15545
16422
  } catch (error) {
15546
16423
  if (!(error instanceof SyntaxError) && error.code !== "ENOENT") throw error;
15547
16424
  }
@@ -15549,21 +16426,22 @@ function prepareEvidenceLedger(dir, date, today) {
15549
16426
  const prior = ledger.days.filter((day) => day.date < date && day.date >= cutoff);
15550
16427
  const clusters = today.map((c) => ({ ...c, sessions: new Map([...c.sessions].map(([id, quotes]) => [id, [...quotes]])) }));
15551
16428
  for (const c of clusters) {
16429
+ const cKey = canonicalProjectKey(c.projectKey, projectKeyAliases);
15552
16430
  for (const day of prior) for (const old of day.clusters) {
15553
- if (old.kind !== c.kind || (old.projectKey ?? "") !== (c.projectKey ?? "") || !equivalentAssertions(old.text, c.text)) continue;
16431
+ if (old.kind !== c.kind || canonicalProjectKey(old.projectKey, projectKeyAliases) !== cKey || !equivalentAssertions(old.text, c.text)) continue;
15554
16432
  for (const [id, quotes] of old.sessions) c.sessions.set(id, [.../* @__PURE__ */ new Set([...c.sessions.get(id) ?? [], ...quotes])].slice(0, 2));
15555
16433
  }
15556
16434
  }
15557
16435
  const latest = ledger.days.reduce((max, day) => day.date > max ? day.date : max, date);
15558
16436
  const days = [...ledger.days.filter((day) => day.date !== date), { date, clusters: today.slice(0, MAX_CLUSTERS).map(encode) }].filter((day) => day.date >= cutoffFor(latest)).sort((a, b) => a.date.localeCompare(b.date));
15559
16437
  return { clusters, write() {
15560
- fs5.mkdirSync(dir, { recursive: true });
16438
+ fs6.mkdirSync(dir, { recursive: true });
15561
16439
  const tmp = `${file}.${randomUUID()}.tmp`;
15562
16440
  try {
15563
- fs5.writeFileSync(tmp, JSON.stringify({ version: 1, days }), { mode: 384 });
15564
- fs5.renameSync(tmp, file);
16441
+ fs6.writeFileSync(tmp, JSON.stringify({ version: 1, days }), { mode: 384 });
16442
+ fs6.renameSync(tmp, file);
15565
16443
  } finally {
15566
- fs5.rmSync(tmp, { force: true });
16444
+ fs6.rmSync(tmp, { force: true });
15567
16445
  }
15568
16446
  } };
15569
16447
  }
@@ -15575,12 +16453,12 @@ function boundedCall(call, timeoutMs, label) {
15575
16453
  return async (prompt, options) => {
15576
16454
  let timer;
15577
16455
  try {
15578
- return await new Promise((resolve5, reject) => {
16456
+ return await new Promise((resolve6, reject) => {
15579
16457
  timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
15580
16458
  Promise.resolve(call(prompt, options)).then(
15581
16459
  (value) => {
15582
16460
  clearTimeout(timer);
15583
- resolve5(value);
16461
+ resolve6(value);
15584
16462
  },
15585
16463
  (error) => {
15586
16464
  clearTimeout(timer);
@@ -15599,7 +16477,7 @@ function boundedCall(call, timeoutMs, label) {
15599
16477
  var GATED_PATCH_FILE = ".gated-patches.json";
15600
16478
  function loadGatedPatches(store) {
15601
16479
  try {
15602
- const raw = fs6.readFileSync(path8.join(store.dir, GATED_PATCH_FILE), "utf8");
16480
+ const raw = fs7.readFileSync(path9.join(store.dir, GATED_PATCH_FILE), "utf8");
15603
16481
  const parsed = JSON.parse(raw);
15604
16482
  return Array.isArray(parsed) ? parsed : [];
15605
16483
  } catch {
@@ -15616,7 +16494,7 @@ async function runDistillation(deps, date) {
15616
16494
  if (deps.memoryStore.hasRun(date)) {
15617
16495
  return { date, status: "skipped-ran", sessions: 0, patchOps: 0, journalWritten: false };
15618
16496
  }
15619
- const flightKey = path8.resolve(deps.memoryStore.dir);
16497
+ const flightKey = path9.resolve(deps.memoryStore.dir);
15620
16498
  if (inFlight.has(flightKey)) {
15621
16499
  return failure(date, new Error("distillation for this memory root is already running; retry dates oldest-first"), "busy");
15622
16500
  }
@@ -15636,6 +16514,24 @@ async function runDistillationInner(deps, date, log, now) {
15636
16514
  } catch (error) {
15637
16515
  return failure(date, error, "harvest");
15638
16516
  }
16517
+ const allObservedCwds = [];
16518
+ try {
16519
+ for (const sid of deps.sessionStore.list()) {
16520
+ const meta = deps.sessionStore.getMetadata(sid);
16521
+ if (typeof meta?.cwd === "string" && meta.cwd) allObservedCwds.push(meta.cwd);
16522
+ }
16523
+ } catch {
16524
+ }
16525
+ for (const s of sessions) {
16526
+ if (s.cwd) allObservedCwds.push(s.cwd);
16527
+ }
16528
+ const projectKeyAliases = collectProjectKeyAliases(allObservedCwds);
16529
+ try {
16530
+ if (projectKeyAliases.size > 0 && deps.memoryStore.loadEntries().some((e) => e.kind === "project")) {
16531
+ deps.memoryStore.migrateProjectKeys(projectKeyAliases);
16532
+ }
16533
+ } catch {
16534
+ }
15639
16535
  if (sessions.length === 0) {
15640
16536
  recordCheckpoint(deps.memoryStore, date, 0, false, now());
15641
16537
  return { date, status: "skipped-empty", sessions: 0, patchOps: 0, journalWritten: false };
@@ -15653,18 +16549,28 @@ async function runDistillationInner(deps, date, log, now) {
15653
16549
  const limits = deps.limits ?? DEFAULT_MEMORY_DISTILL_LIMITS;
15654
16550
  const projectKeys = /* @__PURE__ */ new Map();
15655
16551
  for (const { session } of distilled) {
15656
- if (session.cwd) projectKeys.set(session.sessionId, projectKeyForDir(session.cwd).key);
16552
+ if (session.cwd) {
16553
+ projectKeys.set(session.sessionId, projectKeyForDir(session.cwd).key);
16554
+ }
15657
16555
  }
15658
16556
  const clusters = clusterCandidates(distilled, projectKeys);
15659
16557
  const prepare = () => {
15660
- const ledger = prepareEvidenceLedger(deps.memoryStore.dir, date, clusters);
16558
+ const ledger = prepareEvidenceLedger(deps.memoryStore.dir, date, clusters, projectKeyAliases);
15661
16559
  const { passed: passed2, rejected: rejected2 } = gateClusters(ledger.clusters, limits);
15662
16560
  const entriesBefore = deps.memoryStore.loadEntries();
15663
- const synthesized = synthesizePatch({ date, clusters: passed2, existingEntries: entriesBefore, projectKeys, limits, now: now() });
15664
- const refreshedIds = new Set(synthesized.ops.filter((op) => op.op === "update").map((op) => op.id));
16561
+ const synthesized = synthesizePatch({
16562
+ date,
16563
+ clusters: passed2,
16564
+ existingEntries: entriesBefore,
16565
+ projectKeys,
16566
+ projectKeyAliases,
16567
+ limits,
16568
+ now: now()
16569
+ });
16570
+ const refreshedIds = new Set(synthesized.refreshedIds);
15665
16571
  const retention2 = buildRetentionOps(entriesBefore, limits, now(), refreshedIds);
15666
16572
  const ops = [...synthesized.ops, ...retention2].slice(0, Math.max(limits.maxPatchOps, 3));
15667
- return { ledger, passed: passed2, rejected: rejected2, retention: retention2, ops };
16573
+ return { ledger, passed: passed2, rejected: rejected2, retention: retention2, ops, overflowAddCount: synthesized.overflowAddCount };
15668
16574
  };
15669
16575
  let preview;
15670
16576
  try {
@@ -15672,7 +16578,10 @@ async function runDistillationInner(deps, date, log, now) {
15672
16578
  } catch (error) {
15673
16579
  return failure(date, error, "evidence");
15674
16580
  }
15675
- const { passed, rejected, retention } = preview;
16581
+ const { passed, rejected, retention, overflowAddCount } = preview;
16582
+ if (overflowAddCount > 0) {
16583
+ log(`[memory] ${date}: ${overflowAddCount} gated new candidate(s) exceeded maxPatchOps=${limits.maxPatchOps} and were deferred to journal`);
16584
+ }
15676
16585
  const language = detectLanguage(sessions);
15677
16586
  let journalWritten = false;
15678
16587
  const retiringNow = new Set(retention.filter((op) => op.op === "retire").map((op) => op.id));
@@ -15752,13 +16661,14 @@ function queueGatedPatch(store, patch) {
15752
16661
  });
15753
16662
  }
15754
16663
  function failure(date, error, stage) {
16664
+ const detail = error instanceof Error ? error.name && error.name !== "Error" ? `${error.name}: ${error.message}` : error.message : String(error);
15755
16665
  return {
15756
16666
  date,
15757
16667
  status: "failed",
15758
16668
  sessions: 0,
15759
16669
  patchOps: 0,
15760
16670
  journalWritten: false,
15761
- error: `${stage}: ${error instanceof Error ? error.message : String(error)}`
16671
+ error: `${stage}: ${detail}`
15762
16672
  };
15763
16673
  }
15764
16674
  function applyNextGatedPatch(store) {
@@ -15782,13 +16692,13 @@ function applyNextGatedPatch(store) {
15782
16692
  });
15783
16693
  }
15784
16694
  function persistQueue(store, queue) {
15785
- const target = path8.join(store.dir, GATED_PATCH_FILE);
16695
+ const target = path9.join(store.dir, GATED_PATCH_FILE);
15786
16696
  if (queue.length === 0) {
15787
- fs6.rmSync(target, { force: true });
16697
+ fs7.rmSync(target, { force: true });
15788
16698
  } else {
15789
16699
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
15790
- fs6.writeFileSync(tmp, JSON.stringify(queue, null, " "));
15791
- fs6.renameSync(tmp, target);
16700
+ fs7.writeFileSync(tmp, JSON.stringify(queue, null, " "));
16701
+ fs7.renameSync(tmp, target);
15792
16702
  }
15793
16703
  }
15794
16704
  async function runCatchUp(deps, days = 2) {
@@ -15977,9 +16887,12 @@ export {
15977
16887
  REDACTED,
15978
16888
  redactText,
15979
16889
  looksLikeSecretPresent,
16890
+ normalizeGitUrl,
16891
+ legacyProjectKeyFor,
15980
16892
  projectKeyFor,
15981
16893
  readGitOriginUrl,
15982
16894
  projectKeyForDir,
16895
+ collectProjectKeyAliases,
15983
16896
  createPosixBackend,
15984
16897
  createWindowsBackend,
15985
16898
  createMemoryLockBackend,
@@ -15993,9 +16906,14 @@ export {
15993
16906
  polarity,
15994
16907
  containsWord,
15995
16908
  ANTONYM_PAIRS,
16909
+ tokenizeCasePreserving,
15996
16910
  hasAntonymCross,
16911
+ hasMatchingAsciiAntonymSwap,
16912
+ hasExactCjkAntonymSwap,
15997
16913
  conflictingValues,
15998
16914
  differentSubjects,
16915
+ hasCjk,
16916
+ hasTechnicalTokenMismatch,
15999
16917
  equivalentAssertions,
16000
16918
  nearDuplicate,
16001
16919
  harvestSessionsForDate,