engine7 7.1.143 → 7.1.144

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.
@@ -7687,13 +7687,14 @@ function topicDateHeader(text2, dates = annotateTopicDates(text2)) {
7687
7687
  return (rendered.length ? `\u4E8B\u4EF6\u65E5\u671F\uFF1A${rendered.slice(0, 12).join("\uFF1B")}` : "\u4E8B\u4EF6\u65E5\u671F\uFF1A\u672A\u786E\u8BA4") + (recorded ? `
7688
7688
  \u8D44\u6599\u8BB0\u5F55/\u58F0\u660E\u65E5\u671F\uFF1A${recorded}\uFF08\u4E0D\u7B49\u4E8E\u4E8B\u4EF6\u65E5\u671F\uFF09` : "");
7689
7689
  }
7690
- var pad, LEGACY_TOPIC_YEAR;
7690
+ var pad, LEGACY_TOPIC_YEAR, TOPIC_DATE_RULES_VERSION;
7691
7691
  var init_dates = __esm({
7692
7692
  "src/memory/topics-history/dates.ts"() {
7693
7693
  "use strict";
7694
7694
  init_clock();
7695
7695
  pad = (n) => n.padStart(2, "0");
7696
7696
  LEGACY_TOPIC_YEAR = 2026;
7697
+ TOPIC_DATE_RULES_VERSION = 6;
7697
7698
  }
7698
7699
  });
7699
7700
 
@@ -7899,17 +7900,27 @@ function mem7StartDate(b) {
7899
7900
  }
7900
7901
  function topicBeforeMem7(text2, sourcePath, before, start = 0, end = text2.length) {
7901
7902
  if (!before) return true;
7902
- const events = historicalTopicDates(text2, start, end).map((date2) => date2.value).filter((date2) => !!date2 && validTopicDate(date2));
7903
- if (events.length) return events.some((date2) => date2 < before);
7904
7903
  const metadata2 = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text2)?.[1] ?? "";
7905
7904
  const kindRecorded = /^date_kind:\s*recorded/m.test(metadata2);
7905
+ const normalize5 = (raw2) => raw2 && /^\d{1,2}-\d{1,2}$/.test(raw2) ? `${LEGACY_TOPIC_YEAR}-${raw2.split("-").map((part) => part.padStart(2, "0")).join("-")}` : raw2;
7906
+ const events = historicalTopicDates(text2, start, end).map((date2) => date2.value).filter((date2) => !!date2 && validTopicDate(date2));
7907
+ if (events.length) {
7908
+ if (events.some((date2) => date2 < before)) return true;
7909
+ if (start === 0 && end >= text2.length && !kindRecorded) {
7910
+ const fm = normalize5(/^date:\s*['"]?([\d/-]+)/m.exec(metadata2)?.[1]?.replace(/\//g, "-"));
7911
+ if (fm && validTopicDate(fm) && fm < before) return true;
7912
+ }
7913
+ return false;
7914
+ }
7906
7915
  if (/^legacy_undated:[ \t]*true[ \t]*$/m.test(metadata2)) return true;
7907
7916
  const timestamp = topicRecordingTime(metadata2);
7908
7917
  const recordedAt = timestamp ? validTopicDate(timestamp) ? timestamp : todayKey(timestamp) : void 0;
7909
7918
  const raw = kindRecorded && recordedAt ? recordedAt : !kindRecorded ? /^date:\s*['"]?([\d/-]+)/m.exec(metadata2)?.[1]?.replace(/\//g, "-") : void 0;
7910
- const recorded = raw && /^\d{1,2}-\d{1,2}$/.test(raw) ? `${LEGACY_TOPIC_YEAR}-${raw.split("-").map((part) => part.padStart(2, "0")).join("-")}` : raw;
7919
+ const recorded = normalize5(raw);
7911
7920
  const filename = /(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/.exec(sourcePath)?.[0];
7912
- const date = recorded && validTopicDate(recorded) ? recorded : filename && validTopicDate(filename) ? filename : void 0;
7921
+ const recordedDate = recorded && validTopicDate(recorded) ? recorded : void 0;
7922
+ const filenameDate = filename && validTopicDate(filename) ? filename : void 0;
7923
+ const date = filenameDate && (!recordedDate || filenameDate < recordedDate) ? filenameDate : recordedDate;
7913
7924
  return !date || date < before;
7914
7925
  }
7915
7926
  var starts;
@@ -11677,6 +11688,35 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11677
11688
  };
11678
11689
  }, scope, version);
11679
11690
  }
11691
+ /** 1123 跨轮去重(md):entry id 由正文决定、所在文件由日期决定——日期判定跨轮漂移时新块落到
11692
+ * 另一个日期文件,appendMd 的原位替换只扫目标文件,旧块留成孤儿(妹妹 1122 重洗 44 处双份)。
11693
+ * 单遍扫 episodes:id 在本轮写入表里、但所在文件 ≠ 本轮目标日期的块删掉,entry_count 同步。
11694
+ * 不在本轮写入表里的条目不碰(别的来源/原生记忆)。 */
11695
+ purgeEpisodeEntries(ownerId, targetDateById) {
11696
+ if (!targetDateById.size) return 0;
11697
+ const dir = join14(this.root, "users", ownerId, "episodes");
11698
+ if (!existsSync7(dir)) return 0;
11699
+ let removed = 0;
11700
+ for (const name of readdirSync3(dir)) {
11701
+ const fileDate = /^episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
11702
+ if (!fileDate) continue;
11703
+ const file = join14(dir, name);
11704
+ let text2 = readFileSync11(file, "utf8"), hit = false;
11705
+ for (const m of text2.matchAll(/<!-- entry:(\S+) -->/g)) {
11706
+ const target = targetDateById.get(m[1]);
11707
+ if (target === void 0 || target === fileDate) continue;
11708
+ text2 = text2.replace(new RegExp(`\\n*<!-- entry:${m[1]} -->[\\s\\S]*?<!-- /entry:${m[1]} -->`), "");
11709
+ removed++;
11710
+ hit = true;
11711
+ }
11712
+ if (!hit) continue;
11713
+ text2 = text2.replace(/entry_count: \d+/, `entry_count: ${(text2.match(/<!-- entry:/g) ?? []).length}`);
11714
+ const tmp = `${file}.${process.pid}.tmp`;
11715
+ writeFileSync7(tmp, text2);
11716
+ renameSync5(tmp, file);
11717
+ }
11718
+ return removed;
11719
+ }
11680
11720
  appendAtomicFacts(ownerId, dateStr, entries, scope, version) {
11681
11721
  const flat = [];
11682
11722
  for (const e of entries) {
@@ -16480,7 +16520,6 @@ var init_anthropic_provider = __esm({
16480
16520
  PLACEHOLDER_THINKING_SIGNATURE = "00000000-0000-4000-8000-000000000000";
16481
16521
  MISSING_TOOL_RESULT_TEXT = "[tool result missing: this tool call has no recorded result in history]";
16482
16522
  AnthropicProvider = class {
16483
- // 模拟 CC 的 X-Claude-Code-Session-Id
16484
16523
  constructor(config) {
16485
16524
  this.config = config;
16486
16525
  let u = (config.baseUrl || "https://api.anthropic.com").trim();
@@ -16492,6 +16531,8 @@ var init_anthropic_provider = __esm({
16492
16531
  name = "anthropic";
16493
16532
  baseUrl;
16494
16533
  sessionId;
16534
+ // 模拟 CC 的 X-Claude-Code-Session-Id
16535
+ adaptiveModels = /* @__PURE__ */ new Set();
16495
16536
  /** Anthropic: system prompt 单独传,不在 messages 里
16496
16537
  * opts.thinkingEnabled:本次请求是否开着 thinking(streamChat 现算后传入)。
16497
16538
  * 只影响 requireThinkingBlocks 的占位块回填——那个约束只对 thinking 开启的请求成立。 */
@@ -16693,7 +16734,7 @@ var init_anthropic_provider = __esm({
16693
16734
  const stableText = params.systemStable || params.systemPrompt || "";
16694
16735
  const dynamicText = params.systemDynamic || "";
16695
16736
  const supportsThinking = !/haiku/i.test(params.model);
16696
- const adaptiveThinking = params.model.includes("M3.1-Flash");
16737
+ const adaptiveThinking = params.model.includes("M3.1-Flash") || this.adaptiveModels.has(params.model);
16697
16738
  const thinkingEnabled = adaptiveThinking || !params.disableThinking && (this.config.thinking?.enabled ?? supportsThinking);
16698
16739
  const thinkingBudget = this.config.thinking?.budgetTokens || 8192;
16699
16740
  const { messages: formatted } = this.formatMessages(
@@ -16806,6 +16847,12 @@ var init_anthropic_provider = __esm({
16806
16847
  }
16807
16848
  if (!response.ok) {
16808
16849
  const text2 = await response.text();
16850
+ if (response.status === 400 && !adaptiveThinking && /requires adaptive thinking|supports adaptive thinking only/i.test(text2)) {
16851
+ this.adaptiveModels.add(params.model);
16852
+ console.warn(`[anthropic] ${params.model} requires adaptive thinking; retrying the complete request once`);
16853
+ yield* this.streamChat(params);
16854
+ return;
16855
+ }
16809
16856
  yield { type: "error", error: `Anthropic API ${response.status}: ${text2}` };
16810
16857
  return;
16811
16858
  }
@@ -17495,6 +17542,8 @@ var init_features = __esm({
17495
17542
  installer: true,
17496
17543
  agentTeams: true,
17497
17544
  autoDream: true,
17545
+ /** 1122:cc_ask/cc_progress 默认开(存量配置 loader 就地补全);边缘功能,垫底 */
17546
+ "cc-driver": true,
17498
17547
  processOutput: "verbose",
17499
17548
  interrupt: "command",
17500
17549
  /** 1105:主 query 运行中用户消息的处理——'steer'(默认,注入当前 query)| 'queue'(旧行为,排队) */
@@ -19911,7 +19960,7 @@ init_dates();
19911
19960
  init_topics_history();
19912
19961
  init_vectors();
19913
19962
  import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
19914
- import { existsSync as existsSync11, renameSync as renameSync7, statSync as statSync3, writeFileSync as writeFileSync9 } from "node:fs";
19963
+ import { existsSync as existsSync11, readFileSync as readFileSync16, renameSync as renameSync7, statSync as statSync3, writeFileSync as writeFileSync9 } from "node:fs";
19915
19964
  import { join as join22 } from "node:path";
19916
19965
 
19917
19966
  // src/memory/topics-history/import-backups.ts
@@ -19939,7 +19988,11 @@ function topicsImported(binding) {
19939
19988
  let imported = false;
19940
19989
  try {
19941
19990
  const done = readJson(marker);
19942
- if ((done.report?.total ?? 0) > 0) imported = true;
19991
+ if (typeof done.rulesVersion === "number" && done.rulesVersion !== TOPIC_DATE_RULES_VERSION) {
19992
+ const retired = join22(topicsHistoryRoot(binding), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
19993
+ renameSync7(marker, retired);
19994
+ console.warn(`[topics-import] \u65E5\u671F\u89C4\u5219 v${done.rulesVersion}\u2192v${TOPIC_DATE_RULES_VERSION}\uFF0C\u65E7\u6E05\u5355\u4F5C\u5E9F\u91CD\u5F00 \u2192 ${retired}`);
19995
+ } else if ((done.report?.total ?? 0) > 0) imported = true;
19943
19996
  else {
19944
19997
  const retired = join22(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
19945
19998
  renameSync7(marker, retired);
@@ -766,7 +766,7 @@ var init_dates = __esm({
766
766
  init_clock();
767
767
  pad = (n) => n.padStart(2, "0");
768
768
  LEGACY_TOPIC_YEAR = 2026;
769
- TOPIC_DATE_RULES_VERSION = 4;
769
+ TOPIC_DATE_RULES_VERSION = 6;
770
770
  }
771
771
  });
772
772
 
@@ -1001,17 +1001,27 @@ function mem7StartDate(b) {
1001
1001
  }
1002
1002
  function topicBeforeMem7(text2, sourcePath, before, start = 0, end = text2.length) {
1003
1003
  if (!before) return true;
1004
- const events = historicalTopicDates(text2, start, end).map((date2) => date2.value).filter((date2) => !!date2 && validTopicDate(date2));
1005
- if (events.length) return events.some((date2) => date2 < before);
1006
1004
  const metadata2 = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text2)?.[1] ?? "";
1007
1005
  const kindRecorded = /^date_kind:\s*recorded/m.test(metadata2);
1006
+ const normalize5 = (raw2) => raw2 && /^\d{1,2}-\d{1,2}$/.test(raw2) ? `${LEGACY_TOPIC_YEAR}-${raw2.split("-").map((part) => part.padStart(2, "0")).join("-")}` : raw2;
1007
+ const events = historicalTopicDates(text2, start, end).map((date2) => date2.value).filter((date2) => !!date2 && validTopicDate(date2));
1008
+ if (events.length) {
1009
+ if (events.some((date2) => date2 < before)) return true;
1010
+ if (start === 0 && end >= text2.length && !kindRecorded) {
1011
+ const fm = normalize5(/^date:\s*['"]?([\d/-]+)/m.exec(metadata2)?.[1]?.replace(/\//g, "-"));
1012
+ if (fm && validTopicDate(fm) && fm < before) return true;
1013
+ }
1014
+ return false;
1015
+ }
1008
1016
  if (/^legacy_undated:[ \t]*true[ \t]*$/m.test(metadata2)) return true;
1009
1017
  const timestamp = topicRecordingTime(metadata2);
1010
1018
  const recordedAt = timestamp ? validTopicDate(timestamp) ? timestamp : todayKey(timestamp) : void 0;
1011
1019
  const raw = kindRecorded && recordedAt ? recordedAt : !kindRecorded ? /^date:\s*['"]?([\d/-]+)/m.exec(metadata2)?.[1]?.replace(/\//g, "-") : void 0;
1012
- const recorded = raw && /^\d{1,2}-\d{1,2}$/.test(raw) ? `${LEGACY_TOPIC_YEAR}-${raw.split("-").map((part) => part.padStart(2, "0")).join("-")}` : raw;
1020
+ const recorded = normalize5(raw);
1013
1021
  const filename = /(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/.exec(sourcePath)?.[0];
1014
- const date = recorded && validTopicDate(recorded) ? recorded : filename && validTopicDate(filename) ? filename : void 0;
1022
+ const recordedDate = recorded && validTopicDate(recorded) ? recorded : void 0;
1023
+ const filenameDate = filename && validTopicDate(filename) ? filename : void 0;
1024
+ const date = filenameDate && (!recordedDate || filenameDate < recordedDate) ? filenameDate : recordedDate;
1015
1025
  return !date || date < before;
1016
1026
  }
1017
1027
  var starts;
@@ -11200,6 +11210,35 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11200
11210
  };
11201
11211
  }, scope, version);
11202
11212
  }
11213
+ /** 1123 跨轮去重(md):entry id 由正文决定、所在文件由日期决定——日期判定跨轮漂移时新块落到
11214
+ * 另一个日期文件,appendMd 的原位替换只扫目标文件,旧块留成孤儿(妹妹 1122 重洗 44 处双份)。
11215
+ * 单遍扫 episodes:id 在本轮写入表里、但所在文件 ≠ 本轮目标日期的块删掉,entry_count 同步。
11216
+ * 不在本轮写入表里的条目不碰(别的来源/原生记忆)。 */
11217
+ purgeEpisodeEntries(ownerId, targetDateById) {
11218
+ if (!targetDateById.size) return 0;
11219
+ const dir = join18(this.root, "users", ownerId, "episodes");
11220
+ if (!existsSync10(dir)) return 0;
11221
+ let removed = 0;
11222
+ for (const name of readdirSync3(dir)) {
11223
+ const fileDate = /^episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
11224
+ if (!fileDate) continue;
11225
+ const file = join18(dir, name);
11226
+ let text2 = readFileSync13(file, "utf8"), hit = false;
11227
+ for (const m of text2.matchAll(/<!-- entry:(\S+) -->/g)) {
11228
+ const target = targetDateById.get(m[1]);
11229
+ if (target === void 0 || target === fileDate) continue;
11230
+ text2 = text2.replace(new RegExp(`\\n*<!-- entry:${m[1]} -->[\\s\\S]*?<!-- /entry:${m[1]} -->`), "");
11231
+ removed++;
11232
+ hit = true;
11233
+ }
11234
+ if (!hit) continue;
11235
+ text2 = text2.replace(/entry_count: \d+/, `entry_count: ${(text2.match(/<!-- entry:/g) ?? []).length}`);
11236
+ const tmp = `${file}.${process.pid}.tmp`;
11237
+ writeFileSync10(tmp, text2);
11238
+ renameSync6(tmp, file);
11239
+ }
11240
+ return removed;
11241
+ }
11203
11242
  appendAtomicFacts(ownerId, dateStr, entries, scope, version) {
11204
11243
  const flat = [];
11205
11244
  for (const e of entries) {
@@ -12921,35 +12960,45 @@ __export(import_mem7_exports, {
12921
12960
  topicsImported: () => topicsImported
12922
12961
  });
12923
12962
  import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
12924
- import { existsSync as existsSync12, renameSync as renameSync8, statSync as statSync2, writeFileSync as writeFileSync12 } from "node:fs";
12963
+ import { existsSync as existsSync12, readFileSync as readFileSync17, renameSync as renameSync8, statSync as statSync2, writeFileSync as writeFileSync12 } from "node:fs";
12925
12964
  import { join as join22 } from "node:path";
12965
+ function archiveDateOf(b) {
12966
+ const today = todayKey(), cache = /* @__PURE__ */ new Map();
12967
+ const filenameDate = (sourcePath) => {
12968
+ const name = sourcePath;
12969
+ const fromName = /(?<!\d)(\d{4}-\d{2}-\d{2})(?!\d)/.exec(name)?.[1];
12970
+ if (fromName && validTopicDate(fromName)) return fromName;
12971
+ const mmdd = /(?<=_)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])(?!\d)/.exec(name);
12972
+ const stamped = mmdd ? `${LEGACY_TOPIC_YEAR}-${mmdd[1]}-${mmdd[2]}` : null;
12973
+ return stamped && validTopicDate(stamped) ? stamped : null;
12974
+ };
12975
+ return (sourcePath) => {
12976
+ if (cache.has(sourcePath)) return cache.get(sourcePath);
12977
+ let event = null, recorded = null;
12978
+ try {
12979
+ const text2 = readFileSync17(join22(b.topicsDir, sourcePath), "utf8").slice(0, 6e3);
12980
+ const fm = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text2)?.[1] ?? "";
12981
+ const raw = /^date:\s*['"]?(\d{4}-\d{2}-\d{2})/m.exec(fm)?.[1];
12982
+ if (raw && validTopicDate(raw) && raw <= today) {
12983
+ if (/^date_kind:\s*recorded/m.test(fm)) recorded = raw;
12984
+ else event = raw;
12985
+ }
12986
+ } catch {
12987
+ }
12988
+ const date = event ?? filenameDate(sourcePath) ?? recorded;
12989
+ cache.set(sourcePath, date);
12990
+ return date;
12991
+ };
12992
+ }
12926
12993
  function loadIndexFragments(b) {
12994
+ if (!b.topicsDir) return [];
12927
12995
  const root = topicsHistoryRoot(b);
12928
12996
  const selected = readJson(join22(root, "current.json")).version;
12929
12997
  if (!/^[a-f0-9-]{36}$/.test(selected)) throw new Error("INVALID_HISTORY_VERSION");
12998
+ const archiveDate = archiveDateOf(b);
12930
12999
  const db = new DatabaseSync10(unlinked(join22(root, selected, "history.db")), { readOnly: true });
12931
13000
  try {
12932
- const rows = db.prepare("SELECT ref,body,title,source_path,dates FROM entries").all();
12933
- const explicitDate = (row) => {
12934
- try {
12935
- for (const d of JSON.parse(row.dates ?? "[]")) if (d.value && validTopicDate(d.value)) return d.value;
12936
- } catch {
12937
- }
12938
- return null;
12939
- };
12940
- const filenameDate = (row) => {
12941
- const name = row.source_path ?? "";
12942
- const fromName = /(?<!\d)(\d{4}-\d{2}-\d{2})(?!\d)/.exec(name)?.[1];
12943
- if (fromName && validTopicDate(fromName)) return fromName;
12944
- const mmdd = /(?<=_)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])(?!\d)/.exec(name);
12945
- const stamped = mmdd ? `${LEGACY_TOPIC_YEAR}-${mmdd[1]}-${mmdd[2]}` : null;
12946
- return stamped && validTopicDate(stamped) ? stamped : null;
12947
- };
12948
- const fileMin = /* @__PURE__ */ new Map();
12949
- for (const row of rows) {
12950
- const date = explicitDate(row);
12951
- if (date && (!fileMin.has(row.source_path) || date < fileMin.get(row.source_path))) fileMin.set(row.source_path, date);
12952
- }
13001
+ const rows = db.prepare("SELECT ref,body,title,source_path FROM entries").all();
12953
13002
  const byHash = /* @__PURE__ */ new Map();
12954
13003
  for (const row of rows) {
12955
13004
  const hash7 = digest(String(row.body ?? "").trim());
@@ -12960,7 +13009,7 @@ function loadIndexFragments(b) {
12960
13009
  body: String(row.body ?? ""),
12961
13010
  title: String(row.title || row.source_path || "\u65E7 topics \u6BB5\u843D"),
12962
13011
  sourcePath,
12963
- date: explicitDate(row) ?? fileMin.get(sourcePath) ?? filenameDate(row)
13012
+ date: archiveDate(sourcePath)
12964
13013
  };
12965
13014
  const existing = byHash.get(hash7);
12966
13015
  if (!existing || !!existing.date !== !!fragment.date && !!fragment.date || !!existing.date === !!fragment.date && existing.sourcePath.includes("_root_residue") && !fragment.sourcePath.includes("_root_residue"))
@@ -13007,12 +13056,16 @@ async function importTopicsLocked(b, options) {
13007
13056
  byDate.set(fragment.date, batch);
13008
13057
  }
13009
13058
  const idsByContent = /* @__PURE__ */ new Map();
13010
- if (byDate.size) {
13011
- const table = await store.vectorStore().table("episode");
13012
- const owner = scope.ownerId.replace(/'/g, "''");
13013
- const existing = await table.query().where(`owner_id='${owner}' AND app_id='default' AND project_id='default'`).select(["id", "content_sha256"]).toArray();
13014
- for (const row of existing) if (typeof row.id === "string" && /^tp_[a-f0-9]{12}$/.test(row.id))
13059
+ const existingById = /* @__PURE__ */ new Map();
13060
+ const staleRows = /* @__PURE__ */ new Map();
13061
+ const owner = scope.ownerId.replace(/'/g, "''");
13062
+ const episodeTable = byDate.size ? await store.vectorStore().table("episode") : void 0;
13063
+ if (episodeTable) {
13064
+ const existing = await episodeTable.query().where(`owner_id='${owner}' AND app_id='default' AND project_id='default'`).select(["id", "content_sha256", "md_path"]).toArray();
13065
+ for (const row of existing) if (typeof row.id === "string" && /^tp_[a-f0-9]{12}$/.test(row.id)) {
13015
13066
  idsByContent.set(String(row.content_sha256), row.id);
13067
+ existingById.set(row.id, { sha: String(row.content_sha256), date: /episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(String(row.md_path ?? ""))?.[1] ?? "" });
13068
+ }
13016
13069
  }
13017
13070
  const pendingEmbeddings = [];
13018
13071
  const pendingHashes = [];
@@ -13040,12 +13093,19 @@ async function importTopicsLocked(b, options) {
13040
13093
  }
13041
13094
  }
13042
13095
  }
13096
+ if (episodeTable) for (const r of slice) {
13097
+ const oldSha = staleRows.get(String(r.rowId));
13098
+ if (oldSha === void 0) continue;
13099
+ await episodeTable.delete(`id = '${String(r.rowId).replace(/'/g, "''")}' AND owner_id = '${owner}' AND app_id = 'default' AND project_id = 'default' AND content_sha256 = '${oldSha.replace(/'/g, "''")}'`);
13100
+ staleRows.delete(String(r.rowId));
13101
+ }
13043
13102
  await store.insertEmbeddings(slice);
13044
13103
  completed.push(...pendingHashes.slice(i, i + EMBED_SLICE));
13045
13104
  }
13046
13105
  pendingEmbeddings.length = 0;
13047
13106
  pendingHashes.length = 0;
13048
13107
  };
13108
+ const written = /* @__PURE__ */ new Map();
13049
13109
  for (const [date, batch] of byDate) {
13050
13110
  try {
13051
13111
  const built = batch.map((fragment) => {
@@ -13055,6 +13115,8 @@ async function importTopicsLocked(b, options) {
13055
13115
  ${fragment.body}`;
13056
13116
  const hash7 = contentHash(content);
13057
13117
  const id = idsByContent.get(hash7) ?? `tp_${fragment.hash.slice(0, 12)}`;
13118
+ const prior = existingById.get(id);
13119
+ if (prior && (prior.sha !== hash7 || prior.date !== date)) staleRows.set(id, prior.sha);
13058
13120
  const cached2 = vectors.get(fragment.hash);
13059
13121
  if (!cached2) report.zeroVector++;
13060
13122
  const row = {
@@ -13087,6 +13149,7 @@ ${fragment.body}`;
13087
13149
  return { hash: fragment.hash, row, entry };
13088
13150
  });
13089
13151
  store.appendEpisode(scope.ownerId, date, built.map((b2) => b2.entry));
13152
+ for (const b2 of built) written.set(String(b2.row.rowId), { date, contentHash: String(b2.row.contentHash) });
13090
13153
  report.imported += built.length;
13091
13154
  for (const b2 of built) {
13092
13155
  pendingEmbeddings.push(b2.row);
@@ -13100,9 +13163,12 @@ ${fragment.body}`;
13100
13163
  }
13101
13164
  }
13102
13165
  await flushEmbeddings();
13166
+ const purgedMd = store.purgeEpisodeEntries(scope.ownerId, new Map([...written].map(([id, w]) => [id, w.date])));
13167
+ const purgedVec = await purgeStaleVectorRows(store, scope.ownerId, written);
13168
+ if (purgedMd || purgedVec) console.log(`[topics-import] \u8DE8\u8F6E\u53BB\u91CD: md \u5B64\u513F\u5757 ${purgedMd}\uFF0C\u5411\u91CF\u65E7\u884C ${purgedVec}`);
13103
13169
  if (report.failed === 0 && report.total > 0) {
13104
13170
  const markerTemp = `${doneMarker}.${process.pid}.tmp`;
13105
- writeFileSync12(markerTemp, JSON.stringify({ hashes: [.../* @__PURE__ */ new Set([...done, ...completed])], completedAt: (/* @__PURE__ */ new Date()).toISOString(), report }, null, 1));
13171
+ writeFileSync12(markerTemp, JSON.stringify({ hashes: [.../* @__PURE__ */ new Set([...done, ...completed])], completedAt: (/* @__PURE__ */ new Date()).toISOString(), rulesVersion: TOPIC_DATE_RULES_VERSION, report }, null, 1));
13106
13172
  renameSync8(markerTemp, doneMarker);
13107
13173
  try {
13108
13174
  await completeTopicsImportBackup(b.stateDir, root);
@@ -13116,6 +13182,20 @@ ${fragment.body}`;
13116
13182
  } finally {
13117
13183
  }
13118
13184
  }
13185
+ async function purgeStaleVectorRows(store, ownerId, written) {
13186
+ if (!written.size) return 0;
13187
+ const table = await store.vectorStore().table("episode");
13188
+ const owner = ownerId.replace(/'/g, "''");
13189
+ const existing = await table.query().where(`owner_id='${owner}' AND app_id='default' AND project_id='default'`).select(["id", "content_sha256"]).toArray();
13190
+ let removed = 0;
13191
+ for (const row of existing) {
13192
+ const id = String(row.id), want = written.get(id);
13193
+ if (!want || String(row.content_sha256) === want.contentHash) continue;
13194
+ await table.delete(`id = '${id.replace(/'/g, "''")}' AND owner_id = '${owner}' AND app_id = 'default' AND project_id = 'default' AND content_sha256 = '${String(row.content_sha256).replace(/'/g, "''")}'`);
13195
+ removed++;
13196
+ }
13197
+ return removed;
13198
+ }
13119
13199
  function topicsImported(binding2) {
13120
13200
  if (!binding2.stateDir) return false;
13121
13201
  const marker = join22(topicsHistoryRoot(binding2), "topics-import.json");
@@ -13134,7 +13214,11 @@ function topicsImported(binding2) {
13134
13214
  let imported = false;
13135
13215
  try {
13136
13216
  const done = readJson(marker);
13137
- if ((done.report?.total ?? 0) > 0) imported = true;
13217
+ if (typeof done.rulesVersion === "number" && done.rulesVersion !== TOPIC_DATE_RULES_VERSION) {
13218
+ const retired = join22(topicsHistoryRoot(binding2), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
13219
+ renameSync8(marker, retired);
13220
+ console.warn(`[topics-import] \u65E5\u671F\u89C4\u5219 v${done.rulesVersion}\u2192v${TOPIC_DATE_RULES_VERSION}\uFF0C\u65E7\u6E05\u5355\u4F5C\u5E9F\u91CD\u5F00 \u2192 ${retired}`);
13221
+ } else if ((done.report?.total ?? 0) > 0) imported = true;
13138
13222
  else {
13139
13223
  const retired = join22(topicsHistoryRoot(binding2), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
13140
13224
  renameSync8(marker, retired);
@@ -13191,7 +13275,8 @@ async function backfillTopicsVectors(b, options) {
13191
13275
  contentHash: r.content_sha256 ? String(r.content_sha256) : contentHash(content),
13192
13276
  content,
13193
13277
  subject: r.subject ? String(r.subject) : void 0,
13194
- refDate: String(r.ref_date ?? todayKey()),
13278
+ refDate: /episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(String(r.md_path ?? ""))?.[1] ?? todayKey(),
13279
+ // 1123:表无 ref_date 列,原写法恒落今天;改从 md_path 取
13195
13280
  sessionId: r.session_id ? String(r.session_id) : "topics-import",
13196
13281
  parentId: r.parent_id ? String(r.parent_id) : void 0,
13197
13282
  senderIds: r.sender_ids ? Array.from(r.sender_ids).map(String) : [scope.ownerId],
@@ -13221,7 +13306,7 @@ var init_import_mem7 = __esm({
13221
13306
  });
13222
13307
 
13223
13308
  // src/memory/topics-history/worker.ts
13224
- import { readFileSync as readFileSync17 } from "node:fs";
13309
+ import { readFileSync as readFileSync18 } from "node:fs";
13225
13310
  import { setTimeout as delay } from "node:timers/promises";
13226
13311
 
13227
13312
  // src/config/secrets-env.ts
@@ -14783,7 +14868,6 @@ var PLACEHOLDER_THINKING_TEXT = "(no reasoning recorded)";
14783
14868
  var PLACEHOLDER_THINKING_SIGNATURE = "00000000-0000-4000-8000-000000000000";
14784
14869
  var MISSING_TOOL_RESULT_TEXT = "[tool result missing: this tool call has no recorded result in history]";
14785
14870
  var AnthropicProvider = class {
14786
- // 模拟 CC 的 X-Claude-Code-Session-Id
14787
14871
  constructor(config) {
14788
14872
  this.config = config;
14789
14873
  let u = (config.baseUrl || "https://api.anthropic.com").trim();
@@ -14795,6 +14879,8 @@ var AnthropicProvider = class {
14795
14879
  name = "anthropic";
14796
14880
  baseUrl;
14797
14881
  sessionId;
14882
+ // 模拟 CC 的 X-Claude-Code-Session-Id
14883
+ adaptiveModels = /* @__PURE__ */ new Set();
14798
14884
  /** Anthropic: system prompt 单独传,不在 messages 里
14799
14885
  * opts.thinkingEnabled:本次请求是否开着 thinking(streamChat 现算后传入)。
14800
14886
  * 只影响 requireThinkingBlocks 的占位块回填——那个约束只对 thinking 开启的请求成立。 */
@@ -14996,7 +15082,7 @@ var AnthropicProvider = class {
14996
15082
  const stableText = params.systemStable || params.systemPrompt || "";
14997
15083
  const dynamicText = params.systemDynamic || "";
14998
15084
  const supportsThinking = !/haiku/i.test(params.model);
14999
- const adaptiveThinking = params.model.includes("M3.1-Flash");
15085
+ const adaptiveThinking = params.model.includes("M3.1-Flash") || this.adaptiveModels.has(params.model);
15000
15086
  const thinkingEnabled = adaptiveThinking || !params.disableThinking && (this.config.thinking?.enabled ?? supportsThinking);
15001
15087
  const thinkingBudget = this.config.thinking?.budgetTokens || 8192;
15002
15088
  const { messages: formatted } = this.formatMessages(
@@ -15109,6 +15195,12 @@ var AnthropicProvider = class {
15109
15195
  }
15110
15196
  if (!response.ok) {
15111
15197
  const text2 = await response.text();
15198
+ if (response.status === 400 && !adaptiveThinking && /requires adaptive thinking|supports adaptive thinking only/i.test(text2)) {
15199
+ this.adaptiveModels.add(params.model);
15200
+ console.warn(`[anthropic] ${params.model} requires adaptive thinking; retrying the complete request once`);
15201
+ yield* this.streamChat(params);
15202
+ return;
15203
+ }
15112
15204
  yield { type: "error", error: `Anthropic API ${response.status}: ${text2}` };
15113
15205
  return;
15114
15206
  }
@@ -15788,7 +15880,7 @@ async function waitForIdle() {
15788
15880
  for (; ; ) {
15789
15881
  try {
15790
15882
  await waitForIdle();
15791
- const raw = JSON.parse(readFileSync17(configPath, "utf8").replace(/^\uFEFF/, ""));
15883
+ const raw = JSON.parse(readFileSync18(configPath, "utf8").replace(/^\uFEFF/, ""));
15792
15884
  loadSecretsEnvForConfig(configPath, { overwrite: true });
15793
15885
  const { liveConfig: liveConfig2 } = await Promise.resolve().then(() => (init_live(), live_exports));
15794
15886
  liveConfig2.init(raw);