engine7 7.1.143 → 7.1.145

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.
@@ -632,7 +632,7 @@ function validateTravelChannelConfiguration(channels) {
632
632
  if (name === "emotion" || value?.enabled !== true) continue;
633
633
  if (!["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
634
634
  if (value.mode !== "remote-only") throw new Error("TRAVEL_REMOTE_ONLY_REQUIRED");
635
- const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key2, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key2) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
635
+ const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key4, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key4) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
636
636
  if (hasPlatformSecret(value)) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
637
637
  let url;
638
638
  try {
@@ -1378,15 +1378,15 @@ var init_sqlite_replication = __esm({
1378
1378
  requireForeignKeys(this.db);
1379
1379
  if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
1380
1380
  if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
1381
- const before = sequences(this.db, this.excludedTables), sessions = [];
1381
+ const before = sequences(this.db, this.excludedTables), sessions2 = [];
1382
1382
  try {
1383
- if (this.sessionTables) for (const table of this.sessionTables) sessions.push(this.db.createSession({ table }));
1384
- else sessions.push(this.db.createSession());
1383
+ if (this.sessionTables) for (const table of this.sessionTables) sessions2.push(this.db.createSession({ table }));
1384
+ else sessions2.push(this.db.createSession());
1385
1385
  } catch (error) {
1386
- for (const session of sessions) session.close();
1386
+ for (const session of sessions2) session.close();
1387
1387
  throw error;
1388
1388
  }
1389
- this.active = { sessions, sequences: before, closed: false };
1389
+ this.active = { sessions: sessions2, sequences: before, closed: false };
1390
1390
  return this.active;
1391
1391
  }
1392
1392
  appendCapture(capture) {
@@ -1849,10 +1849,10 @@ var init_live = __esm({
1849
1849
  /** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
1850
1850
  get(dotPath) {
1851
1851
  if (!this.current) return void 0;
1852
- return dotPath.split(".").reduce((acc, key2) => {
1852
+ return dotPath.split(".").reduce((acc, key4) => {
1853
1853
  if (acc == null) return void 0;
1854
- if (key2 === "__proto__" || key2 === "constructor" || key2 === "prototype") return void 0;
1855
- return acc[key2];
1854
+ if (key4 === "__proto__" || key4 === "constructor" || key4 === "prototype") return void 0;
1855
+ return acc[key4];
1856
1856
  }, this.current);
1857
1857
  }
1858
1858
  /** reload 时原地更新(Object.assign 保持引用不变)
@@ -2018,9 +2018,9 @@ function toWall(i = /* @__PURE__ */ new Date()) {
2018
2018
  return `${p.y}-${p2(p.mo)}-${p2(p.d)} ${p2(p.hh)}:${p2(p.mm)}:${p2(p.ss)}`;
2019
2019
  }
2020
2020
  function warnOnce(callSite, shape, sample) {
2021
- const key2 = `${callSite}:${shape}`;
2022
- if (warned.has(key2)) return;
2023
- warned.add(key2);
2021
+ const key4 = `${callSite}:${shape}`;
2022
+ if (warned.has(key4)) return;
2023
+ warned.add(key4);
2024
2024
  console.warn(`[clock] ${callSite} \u5951\u7EA6\u8FDD\u89C4(${shape})\uFF0C\u6837\u672C: ${String(sample).slice(0, 80)}`);
2025
2025
  }
2026
2026
  function zoneOffsetMs(d) {
@@ -2168,11 +2168,11 @@ var init_filters = __esm({
2168
2168
  import { createHash as createHash5 } from "node:crypto";
2169
2169
  function scopeId(scope) {
2170
2170
  if ([scope.ownerId, scope.appId, scope.projectId].some((value) => typeof value !== "string" || !value.trim())) throw new Error("Invalid memory scope");
2171
- const key2 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
2172
- const cached2 = scopeIdMemo.get(key2);
2171
+ const key4 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
2172
+ const cached2 = scopeIdMemo.get(key4);
2173
2173
  if (cached2) return cached2;
2174
2174
  const id3 = "scope_" + createHash5("sha256").update(JSON.stringify([scope.ownerId, scope.appId, scope.projectId])).digest("hex");
2175
- scopeIdMemo.set(key2, id3);
2175
+ scopeIdMemo.set(key4, id3);
2176
2176
  return id3;
2177
2177
  }
2178
2178
  var scopeIdMemo;
@@ -2185,10 +2185,14 @@ var init_scope = __esm({
2185
2185
 
2186
2186
  // src/mem7/core/state/temporal.ts
2187
2187
  function instant(value) {
2188
- if (!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)) throw new Error("TIME_REQUIRED: explicit UTC offset required");
2189
- if (!isCalendarDate(value.substring(0, 10))) throw new Error("INVALID_TIME");
2190
- const time = Date.parse(value);
2191
- if (!Number.isFinite(time)) throw new Error("INVALID_TIME");
2188
+ let text2 = value;
2189
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) {
2190
+ text2 = typeof value === "string" ? value.trim().replace(/^(\d{4}-\d{2}-\d{2}) /, "$1T").replace(/([+-]\d{2})(\d{2})$/, "$1:$2") : value;
2191
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) throw new Error(`TIME_REQUIRED: explicit UTC offset required \u2014 \u6536\u5230 ${received(value)}\uFF1B${INSTANT_FORMAT}`);
2192
+ }
2193
+ if (!isCalendarDate(text2.substring(0, 10))) throw new Error(`INVALID_TIME: \u4E0D\u662F\u6709\u6548\u7684\u65E5\u5386\u65E5\u671F \u2014 \u6536\u5230 ${received(value)}`);
2194
+ const time = Date.parse(text2);
2195
+ if (!Number.isFinite(time)) throw new Error(`INVALID_TIME \u2014 \u6536\u5230 ${received(value)}\uFF1B${INSTANT_FORMAT}`);
2192
2196
  return new Date(time).toISOString();
2193
2197
  }
2194
2198
  function isCalendarDate(value) {
@@ -2201,7 +2205,7 @@ function validateTimezone(timezone) {
2201
2205
  try {
2202
2206
  new Intl.DateTimeFormat("en", { timeZone: timezone });
2203
2207
  } catch {
2204
- throw new Error("INVALID_TIMEZONE");
2208
+ throw new Error(`INVALID_TIMEZONE: timezone \u7528 IANA \u65F6\u533A\u540D\uFF0C\u5982 Asia/Shanghai\uFF08\u6536\u5230 ${String(timezone).slice(0, 60)}\uFF09`);
2205
2209
  }
2206
2210
  }
2207
2211
  function localInstant(date, time, timezone) {
@@ -2233,10 +2237,13 @@ function localInstant(date, time, timezone) {
2233
2237
  return new Date([...matches][0]).toISOString();
2234
2238
  }
2235
2239
  function normalizeValidity(value) {
2240
+ for (const field of ["validFrom", "validTo"]) {
2241
+ if (value[field] === void 0) throw new Error(`TIME_REQUIRED: validity.${field} \u7F3A\u5931 \u2014 validFrom\u3001validTo\u3001precision \u4E09\u4E2A\u952E\u90FD\u8981\u5199\uFF1BvalidFrom\u3001validTo \u6CA1\u6709\u5C31\u5199 null\uFF0Cprecision \u53EA\u80FD\u662F exact/observed/unknown\uFF1B${INSTANT_FORMAT}`);
2242
+ }
2236
2243
  const validFrom = value.validFrom === null ? null : instant(value.validFrom);
2237
2244
  const validTo = value.validTo === null ? null : instant(value.validTo);
2238
- if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: expected [from,to)");
2239
- if (!["exact", "observed", "unknown"].includes(value.precision)) throw new Error("INVALID_PRECISION");
2245
+ if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: \u9700\u8981 [validFrom, validTo) \u4E14 validFrom \u65E9\u4E8E validTo\uFF1B\u6CA1\u6709\u8D77\u70B9\u586B null\uFF0C\u53EA\u7ED3\u675F\u5173\u7CFB\u7528 changeKind=close");
2246
+ if (!["exact", "observed", "unknown"].includes(value.precision)) throw new Error("INVALID_PRECISION: precision \u53EA\u80FD\u662F exact\uFF08\u786E\u5207\u65F6\u523B\uFF09\u3001observed\uFF08\u89C2\u5BDF\u5230\u7684\u5927\u81F4\u65F6\u95F4\uFF09\u3001unknown\uFF08\u65F6\u95F4\u4E0D\u660E\uFF09");
2240
2247
  if (value.timezone) validateTimezone(value.timezone);
2241
2248
  return { ...value, validFrom, validTo };
2242
2249
  }
@@ -2246,16 +2253,20 @@ function overlaps(a, b) {
2246
2253
  function canonicalJson(value) {
2247
2254
  const normalize6 = (input) => {
2248
2255
  if (Array.isArray(input)) return input.map(normalize6);
2249
- if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key2, entry]) => [key2, normalize6(entry)]));
2256
+ if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key4, entry]) => [key4, normalize6(entry)]));
2250
2257
  return input;
2251
2258
  };
2252
2259
  const json = JSON.stringify(normalize6(value));
2253
2260
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
2254
2261
  return json;
2255
2262
  }
2263
+ var INSTANT, INSTANT_FORMAT, received;
2256
2264
  var init_temporal = __esm({
2257
2265
  "src/mem7/core/state/temporal.ts"() {
2258
2266
  "use strict";
2267
+ INSTANT = /^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/;
2268
+ INSTANT_FORMAT = '\u65F6\u95F4\u7528\u5E26\u65F6\u533A\u504F\u79FB\u7684\u5B8C\u6574\u65F6\u523B\uFF0C\u5982 "2026-11-24T09:10:41+08:00"\uFF08\u65E5\u671F\u4E0E\u65F6\u95F4\u4E4B\u95F4\u7528 T \u6216\u7A7A\u683C\uFF0C\u7ED3\u5C3E\u662F Z \u6216 \xB1HH:MM\uFF09';
2269
+ received = (value) => (JSON.stringify(value) ?? String(value)).slice(0, 80);
2259
2270
  }
2260
2271
  });
2261
2272
 
@@ -2280,8 +2291,8 @@ function contextTimeKey(db2, scopeId2, validAt) {
2280
2291
  }
2281
2292
  return `valid-window:${from}:${to}`;
2282
2293
  }
2283
- function assertContextTime(key2, now2 = Date.now()) {
2284
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
2294
+ function assertContextTime(key4, now2 = Date.now()) {
2295
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
2285
2296
  if (!match || !Number.isSafeInteger(Number(match[1])) || !Number.isSafeInteger(Number(match[2])) || Number(match[1]) >= Number(match[2])) throw new Error("INVALID_CONTEXT_TIME_DEPENDENCY");
2286
2297
  if (now2 < Number(match[1]) || now2 >= Number(match[2])) throw new Error("CONTEXT_TIME_EXPIRED");
2287
2298
  }
@@ -2294,15 +2305,15 @@ var init_context_time = __esm({
2294
2305
  });
2295
2306
 
2296
2307
  // src/mem7/core/state/knowledge-history.ts
2297
- function knowledgeCutoff(db2, scope, request3) {
2298
- if (request3.knownAt === void 0 && request3.knownAtRevision === void 0) return void 0;
2299
- if (request3.knownAt !== void 0 && request3.knownAtRevision !== void 0) throw new Error("AMBIGUOUS_KNOWLEDGE_TIME");
2308
+ function knowledgeCutoff(db2, scope, request4) {
2309
+ if (request4.knownAt === void 0 && request4.knownAtRevision === void 0) return void 0;
2310
+ if (request4.knownAt !== void 0 && request4.knownAtRevision !== void 0) throw new Error("AMBIGUOUS_KNOWLEDGE_TIME");
2300
2311
  const id3 = scopeId(scope);
2301
- const time = request3.knownAt === void 0 ? null : instant(request3.knownAt);
2302
- const checkpoint = request3.knownAtRevision === void 0 ? void 0 : db2.prepare("SELECT history_id FROM memory_knowledge_checkpoints WHERE scope_id=? AND fact_revision=?").get(id3, request3.knownAtRevision);
2312
+ const time = request4.knownAt === void 0 ? null : instant(request4.knownAt);
2313
+ const checkpoint = request4.knownAtRevision === void 0 ? void 0 : db2.prepare("SELECT history_id FROM memory_knowledge_checkpoints WHERE scope_id=? AND fact_revision=?").get(id3, request4.knownAtRevision);
2303
2314
  const historyId = time ? Number(db2.prepare("SELECT COALESCE(MAX(history_id),0) history_id FROM memory_knowledge_history WHERE scope_id=? AND recorded_at<=?").get(id3, time).history_id) : Number(checkpoint?.history_id ?? 0);
2304
2315
  const baseline = db2.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='coverage' ORDER BY history_id LIMIT 1").get(id3);
2305
- return { historyId, time, complete: (!baseline || historyId >= baseline.history_id) && (request3.knownAtRevision === void 0 || request3.knownAtRevision === 0 || Boolean(checkpoint)) };
2316
+ return { historyId, time, complete: (!baseline || historyId >= baseline.history_id) && (request4.knownAtRevision === void 0 || request4.knownAtRevision === 0 || Boolean(checkpoint)) };
2306
2317
  }
2307
2318
  function journalEntityCutoff(db2, scope, revision) {
2308
2319
  const row = db2.prepare("SELECT history_id FROM memory_entity_checkpoints WHERE scope_id=? AND entity_revision<=? ORDER BY entity_revision DESC LIMIT 1").get(scopeId(scope), revision);
@@ -2386,9 +2397,9 @@ function append(db2, scope, kind, id3, payload) {
2386
2397
  return Number(result.lastInsertRowid);
2387
2398
  }
2388
2399
  function recordArtifactBasis(db2, scope, kind, id3, version, dependencies) {
2389
- const key2 = basisKey(kind, id3, version);
2390
- if (!db2.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key2)) {
2391
- append(db2, scope, "artifact.basis", key2, { dependencies });
2400
+ const key4 = basisKey(kind, id3, version);
2401
+ if (!db2.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key4)) {
2402
+ append(db2, scope, "artifact.basis", key4, { dependencies });
2392
2403
  }
2393
2404
  }
2394
2405
  var ARTIFACT_HISTORY_SCHEMA, hash3, basisKey, stateKey, generationKinds, normalizedRefs, ArtifactHistory;
@@ -2538,8 +2549,8 @@ END;
2538
2549
  if (cutoff) return historicalRow(this.db, scope, "artifact.basis", basisKey(kind, id3, version), cutoff)?.dependencies ?? null;
2539
2550
  return this.dependencies.version(scope, kind, id3) === version ? this.dependencies.refs(scope, kind, id3) : null;
2540
2551
  }
2541
- scopeContextRetained(scope, key2) {
2542
- const basis = this.db.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeId(scope), key2);
2552
+ scopeContextRetained(scope, key4) {
2553
+ const basis = this.db.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeId(scope), key4);
2543
2554
  if (!basis) return false;
2544
2555
  const atGeneration = historicalRow(this.db, scope, "scope", "state", { historyId: basis.history_id, time: null, complete: true });
2545
2556
  if (!atGeneration) return false;
@@ -2557,15 +2568,15 @@ END;
2557
2568
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
2558
2569
  const walk = (kind2, id4, version2) => {
2559
2570
  checkMemoryReadBudget(visited.size);
2560
- const key2 = basisKey(kind2, id4, version2);
2561
- if (memo.has(key2)) return memo.get(key2);
2562
- if (visited.has(key2)) return false;
2563
- visited.add(key2);
2571
+ const key4 = basisKey(kind2, id4, version2);
2572
+ if (memo.has(key4)) return memo.get(key4);
2573
+ if (visited.has(key4)) return false;
2574
+ visited.add(key4);
2564
2575
  try {
2565
- const basis = this.db.prepare("SELECT history_id,payload_json FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeKey, key2);
2576
+ const basis = this.db.prepare("SELECT history_id,payload_json FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeKey, key4);
2566
2577
  const refs = basis && JSON.parse(basis.payload_json).dependencies;
2567
2578
  if (!refs || this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeKey, kind2, id4)) return false;
2568
- if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key2)) return false;
2579
+ if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key4)) return false;
2569
2580
  const retained = refs.every((ref) => {
2570
2581
  checkMemoryReadBudget(visited.size);
2571
2582
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
@@ -2585,10 +2596,10 @@ END;
2585
2596
  }
2586
2597
  return true;
2587
2598
  });
2588
- memo.set(key2, retained);
2599
+ memo.set(key4, retained);
2589
2600
  return retained;
2590
2601
  } finally {
2591
- visited.delete(key2);
2602
+ visited.delete(key4);
2592
2603
  }
2593
2604
  };
2594
2605
  return walk(kind, id3, version);
@@ -2614,8 +2625,8 @@ END;
2614
2625
  };
2615
2626
  const walk = (parentKind, parentId, parentVersion, ancestors) => {
2616
2627
  checkMemoryReadBudget(ancestors.size);
2617
- const key2 = basisKey(parentKind, parentId, parentVersion);
2618
- if (ancestors.has(key2)) return false;
2628
+ const key4 = basisKey(parentKind, parentId, parentVersion);
2629
+ if (ancestors.has(key4)) return false;
2619
2630
  const state = this.state(scope, parentKind, parentId, cutoff);
2620
2631
  if (state?.state !== "current" || state.version !== parentVersion) return false;
2621
2632
  if (this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeId(scope), parentKind, parentId)) return false;
@@ -2630,9 +2641,9 @@ END;
2630
2641
  }
2631
2642
  }
2632
2643
  if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:"))) {
2633
- if (!this.scopeContextRetained(scope, key2)) return false;
2644
+ if (!this.scopeContextRetained(scope, key4)) return false;
2634
2645
  }
2635
- const next = new Set(ancestors).add(key2);
2646
+ const next = new Set(ancestors).add(key4);
2636
2647
  for (const ref of refs) {
2637
2648
  checkMemoryReadBudget(next.size);
2638
2649
  if (ref.parentKind === "source") {
@@ -2779,9 +2790,9 @@ function invalidateChildren(db2, scope, pending, reason) {
2779
2790
  let referencedPlan;
2780
2791
  while (pending.length) {
2781
2792
  const child = pending.shift();
2782
- const key2 = JSON.stringify([child.child_kind, child.child_id]);
2783
- if (visited.has(key2) && (visited.get(key2) || !child.deleted)) continue;
2784
- visited.set(key2, Boolean(child.deleted));
2793
+ const key4 = JSON.stringify([child.child_kind, child.child_id]);
2794
+ if (visited.has(key4) && (visited.get(key4) || !child.deleted)) continue;
2795
+ visited.set(key4, Boolean(child.deleted));
2785
2796
  if (child.child_kind === "graph_plan") {
2786
2797
  referencedPlan ??= db2.prepare(`SELECT 1 WHERE EXISTS (SELECT 1 FROM memory_dependencies
2787
2798
  WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?)
@@ -2862,8 +2873,8 @@ var init_dependencies = __esm({
2862
2873
  this.snapshotStamp = void 0;
2863
2874
  }
2864
2875
  }
2865
- observeTimeBoundary(key2) {
2866
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
2876
+ observeTimeBoundary(key4) {
2877
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
2867
2878
  if (!match) return;
2868
2879
  const now2 = Date.now();
2869
2880
  for (const boundary of [Number(match[1]), Number(match[2])]) {
@@ -2945,9 +2956,9 @@ var init_dependencies = __esm({
2945
2956
  }
2946
2957
  artifactTimeCurrent(scope, kind, id3, visited = /* @__PURE__ */ new Set(), memo) {
2947
2958
  checkMemoryReadBudget(visited.size);
2948
- const key2 = JSON.stringify([kind, id3]);
2949
- if (visited.has(key2)) return false;
2950
- visited.add(key2);
2959
+ const key4 = JSON.stringify([kind, id3]);
2960
+ if (visited.has(key4)) return false;
2961
+ visited.add(key4);
2951
2962
  try {
2952
2963
  const refs = this.refs(scope, kind, id3);
2953
2964
  for (const ref of refs.filter((ref2) => ref2.parentKind !== "artifact")) {
@@ -2982,7 +2993,7 @@ var init_dependencies = __esm({
2982
2993
  }
2983
2994
  return true;
2984
2995
  } finally {
2985
- visited.delete(key2);
2996
+ visited.delete(key4);
2986
2997
  }
2987
2998
  }
2988
2999
  version(scope, kind, id3) {
@@ -3181,6 +3192,28 @@ var init_timing = __esm({
3181
3192
  }
3182
3193
  });
3183
3194
 
3195
+ // src/mem7/core/lance-cache.ts
3196
+ function memoryLanceSession(lance) {
3197
+ if (typeof lance.Session !== "function") return void 0;
3198
+ let session = sessions.get(lance);
3199
+ if (!session) {
3200
+ session = new lance.Session(BigInt(LANCE_INDEX_CACHE_BYTES), BigInt(LANCE_METADATA_CACHE_BYTES));
3201
+ sessions.set(lance, session);
3202
+ }
3203
+ return session;
3204
+ }
3205
+ var LANCE_INDEX_CACHE_BYTES, LANCE_METADATA_CACHE_BYTES, key, globals, sessions;
3206
+ var init_lance_cache = __esm({
3207
+ "src/mem7/core/lance-cache.ts"() {
3208
+ "use strict";
3209
+ LANCE_INDEX_CACHE_BYTES = 256 * 1024 * 1024;
3210
+ LANCE_METADATA_CACHE_BYTES = 64 * 1024 * 1024;
3211
+ key = Symbol.for("engine7.mem7.lanceCacheSessions");
3212
+ globals = globalThis;
3213
+ sessions = globals[key] ??= /* @__PURE__ */ new WeakMap();
3214
+ }
3215
+ });
3216
+
3184
3217
  // src/mem7/core/vector-store.ts
3185
3218
  import { mkdirSync as mkdirSync5, existsSync as existsSync3 } from "node:fs";
3186
3219
  import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
@@ -3330,6 +3363,7 @@ var init_vector_store = __esm({
3330
3363
  init_read_guard();
3331
3364
  init_timing();
3332
3365
  init_runtime_authority();
3366
+ init_lance_cache();
3333
3367
  isIntelMac = process.platform === "darwin" && process.arch === "x64";
3334
3368
  lancePromise = null;
3335
3369
  mem7VectorWarning = null;
@@ -3416,7 +3450,7 @@ var init_vector_store = __esm({
3416
3450
  /** Reuse expensive dependency walks, but bind each verdict to SQL, time and the actual indexed body. */
3417
3451
  cachedRowVisible(ledger, kind, row, dependencies) {
3418
3452
  if (!dependencies) return vectorRowVisible(ledger, kind, row);
3419
- const key2 = kind + ":" + String(row.id);
3453
+ const key4 = kind + ":" + String(row.id);
3420
3454
  let signature2;
3421
3455
  try {
3422
3456
  signature2 = JSON.stringify([
@@ -3440,11 +3474,11 @@ var init_vector_store = __esm({
3440
3474
  this.visibleCacheVersion = version;
3441
3475
  this.visibleCache.clear();
3442
3476
  }
3443
- const cached2 = this.visibleCache.get(key2);
3477
+ const cached2 = this.visibleCache.get(key4);
3444
3478
  if (cached2?.signature === signature2) return cached2.verdict;
3445
3479
  const verdict = vectorRowVisible(ledger, kind, row, dependencies);
3446
3480
  if (dependencies.cacheRevision() !== version) return false;
3447
- this.visibleCache.set(key2, { signature: signature2, verdict });
3481
+ this.visibleCache.set(key4, { signature: signature2, verdict });
3448
3482
  return verdict;
3449
3483
  }
3450
3484
  visibleCache = /* @__PURE__ */ new Map();
@@ -3465,7 +3499,8 @@ var init_vector_store = __esm({
3465
3499
  assertRuntimeAuthority(this.stateDir, "WRITE");
3466
3500
  mkdirSync5(this.dir, { recursive: true });
3467
3501
  }
3468
- this.db = await lance.connect(this.dir);
3502
+ const session = memoryLanceSession(lance);
3503
+ this.db = await lance.connect(this.dir, session ? { session } : void 0);
3469
3504
  }
3470
3505
  return this.db;
3471
3506
  }
@@ -3942,11 +3977,11 @@ var init_vector_store = __esm({
3942
3977
  const rrf = /* @__PURE__ */ new Map();
3943
3978
  const add = (list) => {
3944
3979
  list.forEach((h, i) => {
3945
- const key2 = h.text.replace(/\s+/g, "");
3980
+ const key4 = h.text.replace(/\s+/g, "");
3946
3981
  const contrib = 1 / (RRF_K + i + 1);
3947
- const cur = rrf.get(key2);
3982
+ const cur = rrf.get(key4);
3948
3983
  if (cur) cur.score += contrib;
3949
- else rrf.set(key2, { hit: h, score: contrib });
3984
+ else rrf.set(key4, { hit: h, score: contrib });
3950
3985
  });
3951
3986
  };
3952
3987
  add(dense);
@@ -4174,8 +4209,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4174
4209
  * 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
4175
4210
  * 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
4176
4211
  reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
4177
- const key2 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
4178
- if (this.healedGaps.has(key2)) return;
4212
+ const key4 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
4213
+ if (this.healedGaps.has(key4)) return;
4179
4214
  const ledgerPath = this.gapHealLedgerPath;
4180
4215
  let ledger = {};
4181
4216
  if (ledgerPath) {
@@ -4183,8 +4218,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4183
4218
  ledger = JSON.parse(readFileSync4(ledgerPath, "utf8"))?.heals ?? {};
4184
4219
  } catch {
4185
4220
  }
4186
- if (Number.isFinite(ledger[key2])) {
4187
- this.healedGaps.add(key2);
4221
+ if (Number.isFinite(ledger[key4])) {
4222
+ this.healedGaps.add(key4);
4188
4223
  return;
4189
4224
  }
4190
4225
  }
@@ -4198,11 +4233,11 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4198
4233
  const count = Number(result?.changes ?? 0);
4199
4234
  if (count > 0) console.warn(`[mem7] \u5E8F\u5217\u7F3A\u53E3\u81EA\u6108\uFF1Ahead seq=${head.eventSeq} \u524D ${count} \u6761\u5DF2 ack \u6295\u9012\u884C\u91CD\u7F6E\u5F85\u6295\uFF08\u65B0\u56FE\u5982\u5B9E\u91CD\u653E / \u65E7\u56FE\u5E42\u7B49 duplicate-ack\uFF1B\u6B7B\u4FE1\u884C\u4FDD\u7559 attempts\uFF09`);
4200
4235
  });
4201
- this.healedGaps.add(key2);
4236
+ this.healedGaps.add(key4);
4202
4237
  if (!ledgerPath) return;
4203
4238
  const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
4204
4239
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
4205
- retained[key2] = now2;
4240
+ retained[key4] = now2;
4206
4241
  const temp = `${ledgerPath}.${randomUUID5()}.tmp`;
4207
4242
  try {
4208
4243
  writeFileSync4(temp, JSON.stringify({ version: 1, heals: retained }));
@@ -4327,7 +4362,7 @@ function validatePredicateValue(predicate, value) {
4327
4362
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("INVALID_FACT_VALUE");
4328
4363
  const object3 = value;
4329
4364
  const allowed = predicate === "activity.schedule" ? ["frequency", "weekday", "date", "localTime", "timezone", "durationMinutes"] : predicate === "person.residence" ? ["place"] : predicate === "relation.open" ? ["entityId", "label", "direction", "perspectiveEntityId", "relationshipId", "semanticVersion", "body", "contentKind", "temporalScope", "certainty", "observedAsCurrentAt", "attribution", "attributionQuote", "realm", "sensitivity"] : ["entityId"];
4330
- if (Object.keys(object3).some((key2) => !allowed.includes(key2))) throw new Error("INVALID_FACT_VALUE: unknown field");
4365
+ if (Object.keys(object3).some((key4) => !allowed.includes(key4))) throw new Error("INVALID_FACT_VALUE: unknown field");
4331
4366
  if (predicate === "activity.schedule") {
4332
4367
  const schedule = object3;
4333
4368
  if (!["weekly", "once"].includes(schedule.frequency) || !/^([01]\d|2[0-3]):[0-5]\d$/.test(schedule.localTime) || !Number.isInteger(schedule.durationMinutes) || schedule.durationMinutes <= 0 || schedule.durationMinutes > 1440) throw new Error("INVALID_SCHEDULE");
@@ -4549,8 +4584,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4549
4584
  ).all(scopeId(scope), `%${word.replace(/[!%_]/g, (character) => "!" + character)}%`, limit2);
4550
4585
  return rows.map((row) => this.source(row));
4551
4586
  }
4552
- snapshotRead(key2, load) {
4553
- return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key2), load) : load();
4587
+ snapshotRead(key4, load) {
4588
+ return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key4), load) : load();
4554
4589
  }
4555
4590
  receive(input, options = {}) {
4556
4591
  const id3 = scopeId(input.scope);
@@ -4731,8 +4766,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4731
4766
  const result = { applied: 0, needsReview: 0, failed: 0, received: 0 };
4732
4767
  const rows = cutoff ? historicalRows(this.db, scope, "source", cutoff).map((row) => ({ state: row.state, count: 1 })) : this.db.prepare("SELECT interpretation_status state,COUNT(*) count FROM memory_sources WHERE scope_id=? GROUP BY interpretation_status").all(scopeId(scope));
4733
4768
  for (const row of rows) {
4734
- const key2 = row.state === "needs_review" ? "needsReview" : row.state;
4735
- if (Object.hasOwn(result, key2)) result[key2] += Number(row.count);
4769
+ const key4 = row.state === "needs_review" ? "needsReview" : row.state;
4770
+ if (Object.hasOwn(result, key4)) result[key4] += Number(row.count);
4736
4771
  }
4737
4772
  return result;
4738
4773
  }
@@ -5156,13 +5191,13 @@ function purgeRecoveryEvidence(db2, graph) {
5156
5191
  db2.prepare("UPDATE e7_recovery_items SET result=? WHERE item_id=?").run(JSON.stringify(item), saved.item_id);
5157
5192
  }
5158
5193
  }
5159
- var text, key, RecoveryDeletionGraph;
5194
+ var text, key2, RecoveryDeletionGraph;
5160
5195
  var init_recovery_deletion = __esm({
5161
5196
  "src/continuity/recovery-deletion.ts"() {
5162
5197
  "use strict";
5163
5198
  init_recovery_deletion_sources();
5164
- text = (row, key2) => row[key2]?.[0] === "text" ? row[key2][1] : void 0;
5165
- key = (scope, kind, id3) => JSON.stringify([scope, kind, id3]);
5199
+ text = (row, key4) => row[key4]?.[0] === "text" ? row[key4][1] : void 0;
5200
+ key2 = (scope, kind, id3) => JSON.stringify([scope, kind, id3]);
5166
5201
  RecoveryDeletionGraph = class {
5167
5202
  edges = /* @__PURE__ */ new Map();
5168
5203
  roots = /* @__PURE__ */ new Set();
@@ -5175,10 +5210,10 @@ var init_recovery_deletion = __esm({
5175
5210
  constructor(deletions) {
5176
5211
  if (deletions.length > 1e5) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
5177
5212
  for (const d of deletions) {
5178
- this.roots.add(key(d.scopeId, "source", d.sourceId));
5213
+ this.roots.add(key2(d.scopeId, "source", d.sourceId));
5179
5214
  if (d.version !== void 0) {
5180
5215
  if (!Number.isSafeInteger(d.version) || d.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5181
- const sourceKey = key(d.scopeId, "source", d.sourceId), prior = this.deletionVersions.get(sourceKey);
5216
+ const sourceKey = key2(d.scopeId, "source", d.sourceId), prior = this.deletionVersions.get(sourceKey);
5182
5217
  if (prior !== void 0 && prior !== d.version) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5183
5218
  this.deletionVersions.set(sourceKey, d.version);
5184
5219
  }
@@ -5193,7 +5228,7 @@ var init_recovery_deletion = __esm({
5193
5228
  links(table, row) {
5194
5229
  const scope = text(row, "scope_id");
5195
5230
  if (!scope) return { owners: [], parents: [] };
5196
- const node = (kind2, id3) => id3 ? [key(scope, kind2, id3)] : [];
5231
+ const node = (kind2, id3) => id3 ? [key2(scope, kind2, id3)] : [];
5197
5232
  const source = text(row, "source_id"), fact = text(row, "assertion_id");
5198
5233
  const artifact = text(row, "artifact_id") ?? text(row, "child_id") ?? text(row, "entry_id");
5199
5234
  const owners = fact ? node("fact", fact) : artifact ? node("artifact", artifact) : source ? node("source", source) : node("entity", text(row, "entity_id"));
@@ -5217,19 +5252,19 @@ var init_recovery_deletion = __esm({
5217
5252
  if (!ref || typeof ref !== "object") continue;
5218
5253
  const refScope = typeof ref.scopeId === "string" ? ref.scopeId : typeof ref.scope_id === "string" ? ref.scope_id : scope;
5219
5254
  for (const [field2, kind2] of [["sourceId", "source"], ["source_id", "source"], ["assertionId", "fact"], ["assertion_id", "fact"], ["artifactId", "artifact"], ["artifact_id", "artifact"], ["entryId", "artifact"], ["entry_id", "artifact"]]) {
5220
- if (typeof ref[field2] === "string") parents.push(key(refScope, kind2, ref[field2]));
5255
+ if (typeof ref[field2] === "string") parents.push(key2(refScope, kind2, ref[field2]));
5221
5256
  }
5222
- if (typeof ref.parentId === "string" && ["source", "fact", "entity", "artifact"].includes(ref.parentKind)) parents.push(key(refScope, ref.parentKind, ref.parentId));
5257
+ if (typeof ref.parentId === "string" && ["source", "fact", "entity", "artifact"].includes(ref.parentKind)) parents.push(key2(refScope, ref.parentKind, ref.parentId));
5223
5258
  pending.push(...Object.values(ref).filter((value) => value && typeof value === "object"));
5224
5259
  }
5225
5260
  }
5226
5261
  if (table === "memory_knowledge_history") {
5227
5262
  const kind2 = text(row, "target_kind"), target = text(row, "target_id");
5228
- if (kind2 === "source" && target) parents.push(key(scope, "source", target));
5263
+ if (kind2 === "source" && target) parents.push(key2(scope, "source", target));
5229
5264
  if (kind2?.startsWith("artifact.") && target) {
5230
5265
  try {
5231
5266
  const parts = JSON.parse(target);
5232
- if (Array.isArray(parts) && typeof parts[1] === "string") parents.push(key(scope, "artifact", parts[1]));
5267
+ if (Array.isArray(parts) && typeof parts[1] === "string") parents.push(key2(scope, "artifact", parts[1]));
5233
5268
  } catch {
5234
5269
  }
5235
5270
  }
@@ -5237,7 +5272,7 @@ var init_recovery_deletion = __esm({
5237
5272
  if (table === "memory_sources" && source) {
5238
5273
  const origin = text(row, "origin_key");
5239
5274
  if (origin) {
5240
- const originNode = key(scope, "origin", origin), sourceNode = key(scope, "source", source);
5275
+ const originNode = key2(scope, "origin", origin), sourceNode = key2(scope, "source", source);
5241
5276
  this.edge(sourceNode, originNode);
5242
5277
  this.edge(originNode, sourceNode);
5243
5278
  const version = row.source_version?.[0] === "integer" ? Number(row.source_version[1]) : void 0;
@@ -5247,15 +5282,15 @@ var init_recovery_deletion = __esm({
5247
5282
  if (deletion.version === void 0) continue;
5248
5283
  if (!Number.isSafeInteger(deletion.version) || deletion.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5249
5284
  if (++this.deletionChecks > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
5250
- if (recoveryOriginalSourceId(scope, origin, deletion.version) === deletion.sourceId) this.edge(key(scope, "source", deletion.sourceId), originNode);
5285
+ if (recoveryOriginalSourceId(scope, origin, deletion.version) === deletion.sourceId) this.edge(key2(scope, "source", deletion.sourceId), originNode);
5251
5286
  }
5252
5287
  this.familyProofs.add(originNode);
5253
5288
  }
5254
- if (text(row, "interpretation_status") === "deleted") this.roots.add(key(scope, "source", source));
5289
+ if (text(row, "interpretation_status") === "deleted") this.roots.add(key2(scope, "source", source));
5255
5290
  }
5256
5291
  if (table === "memory_tombstones") {
5257
5292
  const target = text(row, "target_id"), kind2 = text(row, "target_kind");
5258
- if (target && kind2) this.roots.add(key(scope, kind2, target));
5293
+ if (target && kind2) this.roots.add(key2(scope, kind2, target));
5259
5294
  }
5260
5295
  return { owners, parents };
5261
5296
  }
@@ -5663,9 +5698,9 @@ ALTER TABLE memory_host_turns ADD COLUMN owner_id TEXT;
5663
5698
  }
5664
5699
  }
5665
5700
  recordCompleted(id3, sourceId, sourceVersion, now2) {
5666
- const key2 = JSON.stringify(["host.turn.completed", id3, sourceId]);
5701
+ const key4 = JSON.stringify(["host.turn.completed", id3, sourceId]);
5667
5702
  this.db.prepare(`INSERT OR IGNORE INTO ome_jobs(kind,payload,status,next_run_at,created_at,job_key,scope_id,completed_at)
5668
- VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id3, sourceId, sourceVersion }), now2, now2, key2, id3, now2);
5703
+ VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id3, sourceId, sourceVersion }), now2, now2, key4, id3, now2);
5669
5704
  }
5670
5705
  };
5671
5706
  }
@@ -6293,7 +6328,7 @@ function recoverLegacySession(db2, store, mapping, files, apply = false) {
6293
6328
  return report;
6294
6329
  }
6295
6330
  function recoverLegacyProjections(db2, store, input, apply = false) {
6296
- const key2 = scopeId(input.scope);
6331
+ const key4 = scopeId(input.scope);
6297
6332
  const root = realpathSync3(input.root);
6298
6333
  const report = { files: 0, entries: 0, recoverable: 0, alreadyMapped: 0, unavailable: 0, reasons: {}, applied: false };
6299
6334
  const gap = (reason) => {
@@ -6338,7 +6373,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6338
6373
  const block = match[0];
6339
6374
  const field = (name) => match[2].match(new RegExp(`^\\*\\*${name}\\*\\*: ([^\\n]*)$`, "m"))?.[1]?.trim();
6340
6375
  const parent = field("parent_id");
6341
- const mapping = db2.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key2);
6376
+ const mapping = db2.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key4);
6342
6377
  if (!mapping || field("parent_type") !== "memcell" || field("owner_id") !== input.scope.ownerId || field("session_id") !== mapping.session_id) {
6343
6378
  gap("projection_parent_provenance_missing");
6344
6379
  continue;
@@ -6355,7 +6390,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6355
6390
  gap("projection_body_missing");
6356
6391
  continue;
6357
6392
  }
6358
- const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key2, kind, match[1]);
6393
+ const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
6359
6394
  const target = join8(store.mem7RootPath(), path35);
6360
6395
  if (previous) {
6361
6396
  if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path35 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
@@ -6407,7 +6442,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6407
6442
  role: "supports"
6408
6443
  })));
6409
6444
  const digest7 = hash4(candidate.block.trim());
6410
- db2.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
6445
+ db2.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key4, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
6411
6446
  store.artifacts.publish(input.scope, {
6412
6447
  kind: candidate.kind,
6413
6448
  id: candidate.id,
@@ -6419,7 +6454,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6419
6454
  summary: candidate.summary,
6420
6455
  title: candidate.title
6421
6456
  });
6422
- db2.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
6457
+ db2.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key4, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
6423
6458
  }
6424
6459
  });
6425
6460
  report.applied = true;
@@ -6551,10 +6586,10 @@ var init_recall_sources = __esm({
6551
6586
  }
6552
6587
  const queue = db2.prepare("SELECT target_id FROM memory_tombstones WHERE scope_id=? AND target_kind='source'").all(id3).map((row) => `s:${row.target_id}`);
6553
6588
  for (let index = 0; index < queue.length; index++) {
6554
- const key2 = queue[index];
6555
- if (this.removed.has(key2)) continue;
6556
- this.removed.add(key2);
6557
- queue.push(...dependents.get(key2) ?? []);
6589
+ const key4 = queue[index];
6590
+ if (this.removed.has(key4)) continue;
6591
+ this.removed.add(key4);
6592
+ queue.push(...dependents.get(key4) ?? []);
6558
6593
  }
6559
6594
  }
6560
6595
  sources = /* @__PURE__ */ new Map();
@@ -6729,9 +6764,9 @@ CREATE TABLE memory_person_mentions (
6729
6764
  ])];
6730
6765
  if (ids.length > 8192 || this.snapshot.relationships.size > 8192) return result;
6731
6766
  const sourceIds = JSON.stringify(ids.sort());
6732
- const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key2) => {
6733
- const split = key2.lastIndexOf(":");
6734
- return [key2.slice(0, split), Number(key2.slice(split + 1))];
6767
+ const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key4) => {
6768
+ const split = key4.lastIndexOf(":");
6769
+ return [key4.slice(0, split), Number(key4.slice(split + 1))];
6735
6770
  }));
6736
6771
  this.snapshotBasis = this.readProvenanceBasis(this.snapshot, sourceIds, relationshipRefs);
6737
6772
  }
@@ -6779,19 +6814,19 @@ CREATE TABLE memory_person_mentions (
6779
6814
  const sourceChecks = new Map(sources.map((row) => [row.id, JSON.stringify(row)]));
6780
6815
  const relationshipRows = /* @__PURE__ */ new Map();
6781
6816
  for (const row of relationships) {
6782
- const key2 = `${row.id}:${row.version}`;
6783
- const rows = relationshipRows.get(key2) ?? [];
6817
+ const key4 = `${row.id}:${row.version}`;
6818
+ const rows = relationshipRows.get(key4) ?? [];
6784
6819
  rows.push(row);
6785
- relationshipRows.set(key2, rows);
6820
+ relationshipRows.set(key4, rows);
6786
6821
  }
6787
- const relationshipChecks = new Map([...relationshipRows].map(([key2, rows]) => [key2, createHash15("sha256").update(JSON.stringify(rows)).digest("hex")]));
6822
+ const relationshipChecks = new Map([...relationshipRows].map(([key4, rows]) => [key4, createHash15("sha256").update(JSON.stringify(rows)).digest("hex")]));
6788
6823
  checkMemoryReadBudget();
6789
6824
  return { sourceIds, relationshipRefs, digest: digest7, sources: sourceChecks, relationships: relationshipChecks };
6790
6825
  }
6791
6826
  provenanceSnapshot(scope, cutoff) {
6792
6827
  const stamp = this.provenanceStamp();
6793
- const key2 = JSON.stringify([scopeId(scope), cutoff ?? null]);
6794
- if (stamp !== this.snapshotStamp && this.snapshot?.key === key2 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
6828
+ const key4 = JSON.stringify([scopeId(scope), cutoff ?? null]);
6829
+ if (stamp !== this.snapshotStamp && this.snapshot?.key === key4 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
6795
6830
  const previous = this.snapshotBasis;
6796
6831
  const next = this.readProvenanceBasis(this.snapshot, previous.sourceIds, previous.relationshipRefs);
6797
6832
  if (next.digest !== previous.digest) {
@@ -6803,17 +6838,17 @@ CREATE TABLE memory_person_mentions (
6803
6838
  this.snapshot.metadata.delete(id3);
6804
6839
  this.snapshot.currentSources.delete(id3);
6805
6840
  }
6806
- for (const [key3, check] of previous.relationships) {
6807
- if (next.relationships.get(key3) !== check) this.snapshot.relationships.delete(key3);
6841
+ for (const [key5, check] of previous.relationships) {
6842
+ if (next.relationships.get(key5) !== check) this.snapshot.relationships.delete(key5);
6808
6843
  }
6809
6844
  }
6810
6845
  this.snapshotBasis = next;
6811
6846
  this.snapshotStamp = stamp;
6812
6847
  }
6813
- if (stamp !== this.snapshotStamp || this.snapshot?.key !== key2 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
6848
+ if (stamp !== this.snapshotStamp || this.snapshot?.key !== key4 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
6814
6849
  this.snapshotStamp = stamp;
6815
6850
  this.snapshotBasis = void 0;
6816
- this.snapshot = { key: key2, memo: /* @__PURE__ */ new Map(), grounds: /* @__PURE__ */ new Map(), currentSources: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map(), metadata: /* @__PURE__ */ new Map(), relationships: /* @__PURE__ */ new Map() };
6851
+ this.snapshot = { key: key4, memo: /* @__PURE__ */ new Map(), grounds: /* @__PURE__ */ new Map(), currentSources: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map(), metadata: /* @__PURE__ */ new Map(), relationships: /* @__PURE__ */ new Map() };
6817
6852
  }
6818
6853
  return this.snapshot;
6819
6854
  }
@@ -6944,21 +6979,21 @@ CREATE TABLE memory_person_mentions (
6944
6979
  provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot) {
6945
6980
  checkMemoryReadBudget(visited.size);
6946
6981
  if (ref.scopeId !== scopeId(scope) || visited.has(ref.sourceId) || ref.relationshipId && visited.has(`${ref.relationshipId}:${ref.semanticVersion}`)) return false;
6947
- const key2 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
6948
- if (snapshot.memo.has(key2)) return snapshot.memo.get(key2);
6982
+ const key4 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
6983
+ if (snapshot.memo.has(key4)) return snapshot.memo.get(key4);
6949
6984
  const retained = this.provenanceSource(scope, ref.sourceId, cutoff, snapshot)?.sourceVersion === ref.sourceVersion && this.provenanceRetained(scope, ref.sourceId, visited, cutoff, snapshot) && this.relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot);
6950
- snapshot.memo.set(key2, retained);
6985
+ snapshot.memo.set(key4, retained);
6951
6986
  return retained;
6952
6987
  }
6953
6988
  /** Authored thoughts remain historical memories when a cited source is corrected; deletion still wins. */
6954
6989
  provenanceRetained(scope, sourceId, visited, cutoff, snapshot) {
6955
6990
  checkMemoryReadBudget(visited.size);
6956
6991
  if (visited.has(sourceId)) return false;
6957
- const key2 = `source:${sourceId}`;
6992
+ const key4 = `source:${sourceId}`;
6958
6993
  const { memo } = snapshot;
6959
- if (memo.has(key2)) return memo.get(key2);
6994
+ if (memo.has(key4)) return memo.get(key4);
6960
6995
  if (!this.provenanceSource(scope, sourceId, cutoff, snapshot) || this.tombstoneRead.get(scopeId(scope), sourceId)) {
6961
- memo.set(key2, false);
6996
+ memo.set(key4, false);
6962
6997
  return false;
6963
6998
  }
6964
6999
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -6967,7 +7002,7 @@ CREATE TABLE memory_person_mentions (
6967
7002
  try {
6968
7003
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
6969
7004
  const retained = !metadata2 || metadata2.contextRefs.every(check) && metadata2.basisRefs.every(check);
6970
- memo.set(key2, retained);
7005
+ memo.set(key4, retained);
6971
7006
  return retained;
6972
7007
  } finally {
6973
7008
  visited.delete(sourceId);
@@ -7001,10 +7036,10 @@ CREATE TABLE memory_person_mentions (
7001
7036
  sourceGroundsCurrent(scope, sourceId, visited, cutoff, snapshot) {
7002
7037
  checkMemoryReadBudget(visited.size);
7003
7038
  if (visited.has(sourceId)) return false;
7004
- const key2 = `source:${sourceId}`;
7005
- if (snapshot.grounds.has(key2)) return snapshot.grounds.get(key2);
7039
+ const key4 = `source:${sourceId}`;
7040
+ if (snapshot.grounds.has(key4)) return snapshot.grounds.get(key4);
7006
7041
  if (!this.sourceCurrent(scope, sourceId, cutoff, snapshot) || !this.provenanceRetained(scope, sourceId, /* @__PURE__ */ new Set(), cutoff, snapshot)) {
7007
- snapshot.grounds.set(key2, false);
7042
+ snapshot.grounds.set(key4, false);
7008
7043
  return false;
7009
7044
  }
7010
7045
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -7012,7 +7047,7 @@ CREATE TABLE memory_person_mentions (
7012
7047
  visited.add(sourceId);
7013
7048
  try {
7014
7049
  const current2 = !metadata2 || metadata2.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
7015
- snapshot.grounds.set(key2, current2);
7050
+ snapshot.grounds.set(key4, current2);
7016
7051
  return current2;
7017
7052
  } finally {
7018
7053
  visited.delete(sourceId);
@@ -7022,46 +7057,46 @@ CREATE TABLE memory_person_mentions (
7022
7057
  checkMemoryReadBudget(visited.size);
7023
7058
  if (ref.scopeId !== scopeId(scope) || this.provenanceSource(scope, ref.sourceId, cutoff, snapshot)?.sourceVersion !== ref.sourceVersion || !this.sourceGroundsCurrent(scope, ref.sourceId, visited, cutoff, snapshot)) return false;
7024
7059
  if (!ref.relationshipId) return true;
7025
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
7026
- if (visited.has(key2)) return false;
7027
- const memoKey = `relationship:${key2}:${ref.purpose === "historical" ? "historical" : "current"}`;
7060
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
7061
+ if (visited.has(key4)) return false;
7062
+ const memoKey = `relationship:${key4}:${ref.purpose === "historical" ? "historical" : "current"}`;
7028
7063
  if (snapshot.grounds.has(memoKey)) return snapshot.grounds.get(memoKey);
7029
- if (!snapshot.relationships.has(key2)) {
7064
+ if (!snapshot.relationships.has(key4)) {
7030
7065
  this.snapshotBasis = void 0;
7031
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
7066
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
7032
7067
  }
7033
- const material = snapshot.relationships.get(key2);
7068
+ const material = snapshot.relationships.get(key4);
7034
7069
  if (!material || ["deleted", "retracted"].includes(material.state) || ref.purpose !== "historical" && !material.current) return false;
7035
- visited.add(key2);
7070
+ visited.add(key4);
7036
7071
  try {
7037
7072
  const current2 = material.evidenceSourceIds.every((id3) => this.sourceGroundsCurrent(scope, id3, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.currentReference(scope, basis, visited, cutoff, snapshot));
7038
7073
  snapshot.grounds.set(memoKey, current2);
7039
7074
  return current2;
7040
7075
  } finally {
7041
- visited.delete(key2);
7076
+ visited.delete(key4);
7042
7077
  }
7043
7078
  }
7044
7079
  relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot = this.provenanceSnapshot(scope, cutoff)) {
7045
7080
  checkMemoryReadBudget(visited.size);
7046
7081
  if (!ref.relationshipId) return true;
7047
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
7048
- if (visited.has(key2)) return false;
7049
- const memoKey = `relationship:${key2}`;
7082
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
7083
+ if (visited.has(key4)) return false;
7084
+ const memoKey = `relationship:${key4}`;
7050
7085
  const { memo } = snapshot;
7051
7086
  if (memo.has(memoKey)) return memo.get(memoKey);
7052
- if (!snapshot.relationships.has(key2)) {
7087
+ if (!snapshot.relationships.has(key4)) {
7053
7088
  this.snapshotBasis = void 0;
7054
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
7089
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
7055
7090
  }
7056
- const material = snapshot.relationships.get(key2);
7091
+ const material = snapshot.relationships.get(key4);
7057
7092
  if (!material) return false;
7058
- visited.add(key2);
7093
+ visited.add(key4);
7059
7094
  try {
7060
7095
  const retained = material.evidenceSourceIds.every((id3) => this.provenanceRetained(scope, id3, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.provenanceReferenceRetained(scope, basis, visited, cutoff, snapshot));
7061
7096
  memo.set(memoKey, retained);
7062
7097
  return retained;
7063
7098
  } finally {
7064
- visited.delete(key2);
7099
+ visited.delete(key4);
7065
7100
  }
7066
7101
  }
7067
7102
  relationshipReferenceMaterial(scope, ref, cutoff) {
@@ -7478,13 +7513,13 @@ CREATE TABLE memory_relationship_receipts (
7478
7513
  JOIN memory_relationship_versions r ON r.scope_id=h.scope_id AND r.relationship_id=h.relationship_id AND r.semantic_version=h.semantic_version
7479
7514
  JOIN fact_assertions a ON a.scope_id=r.scope_id AND a.assertion_id=r.assertion_id
7480
7515
  WHERE h.scope_id=? AND h.perspective_entity_id=? AND h.subject_id=? AND h.object_id=?`);
7481
- for (const request3 of requests) {
7482
- const endpoints = [[request3.subjectId, request3.objectId]];
7483
- if (request3.direction === "symmetric") endpoints.push([request3.objectId, request3.subjectId]);
7516
+ for (const request4 of requests) {
7517
+ const endpoints = [[request4.subjectId, request4.objectId]];
7518
+ if (request4.direction === "symmetric") endpoints.push([request4.objectId, request4.subjectId]);
7484
7519
  for (const [subject, object3] of endpoints) {
7485
- for (const row of query.all(scopeId(scope), request3.perspectiveEntityId, subject, object3)) {
7520
+ for (const row of query.all(scopeId(scope), request4.perspectiveEntityId, subject, object3)) {
7486
7521
  const value = JSON.parse(row.value_json);
7487
- if (value.contentKind === request3.contentKind && value.temporalScope === request3.temporalScope) ids.add(row.relationship_id);
7522
+ if (value.contentKind === request4.contentKind && value.temporalScope === request4.temporalScope) ids.add(row.relationship_id);
7488
7523
  }
7489
7524
  }
7490
7525
  }
@@ -7508,16 +7543,16 @@ CREATE TABLE memory_relationship_receipts (
7508
7543
  WHERE h.scope_id=? AND h.relationship_id=? AND r.semantic_version=COALESCE(?,h.semantic_version)`).get(...cutoff ? [revision, revision] : [], scopeId(scope), relationshipId, version ?? null);
7509
7544
  if (!row) return null;
7510
7545
  if (historicalVersion) Object.assign(row, historicalVersion);
7511
- const key2 = `${relationshipId}:${row.semantic_version}`;
7512
- if (visited.has(key2)) return null;
7513
- const next = new Set(visited).add(key2);
7546
+ const key4 = `${relationshipId}:${row.semantic_version}`;
7547
+ if (visited.has(key4)) return null;
7548
+ const next = new Set(visited).add(key4);
7514
7549
  const evidence = this.db.prepare("SELECT source_id sourceId,span_start start,span_end end,quote,relation FROM fact_evidence WHERE scope_id=? AND assertion_id=? AND added_revision<=?").all(scopeId(scope), row.assertion_id, revision ?? Number.MAX_SAFE_INTEGER).map((ref) => ({ ...ref }));
7515
7550
  const basisRefs = JSON.parse(row.basis_refs);
7516
7551
  const refs = [...evidence.map((ref) => ({ sourceId: ref.sourceId })), ...basisRefs];
7517
7552
  if (recall ? recall.deletedRelationship(relationshipId, row.semantic_version) : evidence.some((ref) => !this.socialSources.retained(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) || basisRefs.some((ref) => !this.socialSources.referenceRetained(scope, ref, /* @__PURE__ */ new Set(), cutoff))) return null;
7518
7553
  const value = JSON.parse(row.value_json);
7519
7554
  const current2 = (historicalHead ?? this.db.prepare("SELECT semantic_version FROM memory_relationship_heads WHERE scope_id=? AND relationship_id=?").get(scopeId(scope), relationshipId)).semantic_version === row.semantic_version;
7520
- const valid = recall ? evidence.length > 0 && evidence.every((ref) => recall.current(ref.sourceId)) && basisRefs.every((ref) => recall.referenceCurrent(ref)) && (cutoff || [void 0, null, "current"].includes(this.db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scopeId(scope), key2)?.state)) : refs.every((ref) => this.sources.isCurrent(scope, ref.sourceId, cutoff) && this.socialSources.groundsCurrent(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) && (cutoff || [void 0, null, "current"].includes(this.dependencies?.state(scope, "relationship", `${relationshipId}:${row.semantic_version}`))) && basisRefs.every((ref) => this.socialSources.referenceCurrent(scope, ref, next, cutoff));
7555
+ const valid = recall ? evidence.length > 0 && evidence.every((ref) => recall.current(ref.sourceId)) && basisRefs.every((ref) => recall.referenceCurrent(ref)) && (cutoff || [void 0, null, "current"].includes(this.db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scopeId(scope), key4)?.state)) : refs.every((ref) => this.sources.isCurrent(scope, ref.sourceId, cutoff) && this.socialSources.groundsCurrent(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) && (cutoff || [void 0, null, "current"].includes(this.dependencies?.state(scope, "relationship", `${relationshipId}:${row.semantic_version}`))) && basisRefs.every((ref) => this.socialSources.referenceCurrent(scope, ref, next, cutoff));
7521
7556
  return {
7522
7557
  relationshipId,
7523
7558
  semanticVersion: row.semantic_version,
@@ -7842,15 +7877,15 @@ var init_cutoff = __esm({
7842
7877
  // src/continuity/runtime-replication.ts
7843
7878
  import { constants as constants5, lstatSync as lstatSync6, realpathSync as realpathSync4, mkdirSync as mkdirSync6, openSync as openSync6, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5, fsyncSync as fsyncSync5 } from "node:fs";
7844
7879
  import { basename as basename2, dirname as dirname5, join as join10, resolve as resolve5 } from "node:path";
7845
- function checkKey(component, key2) {
7846
- if (component === "topics-vectors" && typeof key2 === "string" && /^[a-f0-9]{64}$/.test(key2)) return;
7847
- if (component === "legacy-memory" && typeof key2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key2) && !/[. ]$/.test(key2) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key2)) return;
7848
- if (["calendar", "proactive", "session-events"].includes(component) && key2 === void 0) return;
7880
+ function checkKey(component, key4) {
7881
+ if (component === "topics-vectors" && typeof key4 === "string" && /^[a-f0-9]{64}$/.test(key4)) return;
7882
+ if (component === "legacy-memory" && typeof key4 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key4) && !/[. ]$/.test(key4) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key4)) return;
7883
+ if (["calendar", "proactive", "session-events"].includes(component) && key4 === void 0) return;
7849
7884
  throw new Error("REPLICATION_REGISTRATION_INVALID");
7850
7885
  }
7851
- function location2(stateDir, component, key2) {
7852
- checkKey(component, key2);
7853
- return join10(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
7886
+ function location2(stateDir, component, key4) {
7887
+ checkKey(component, key4);
7888
+ return join10(stateDir, ".continuity", component + (key4 === void 0 ? "" : "-" + key4) + "-replication.json");
7854
7889
  }
7855
7890
  function normalize3(input) {
7856
7891
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -7861,8 +7896,8 @@ function directory(path35) {
7861
7896
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path35) !== resolve5(path35) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
7862
7897
  throw new Error("REPLICATION_REGISTRATION_INVALID");
7863
7898
  }
7864
- function readRuntimeReplicationRegistration(stateDir, component, key2) {
7865
- const file2 = location2(stateDir, component, key2);
7899
+ function readRuntimeReplicationRegistration(stateDir, component, key4) {
7900
+ const file2 = location2(stateDir, component, key4);
7866
7901
  try {
7867
7902
  lstatSync6(dirname5(file2));
7868
7903
  } catch (error) {
@@ -7925,8 +7960,8 @@ function checkRuntimeReplicationDatabase(db2, registration, component, version,
7925
7960
  }
7926
7961
  return requested ?? registration?.binding;
7927
7962
  }
7928
- function enrollRuntimeReplication(db2, stateDir, component, binding, key2) {
7929
- const file2 = location2(stateDir, component, key2), old = readRuntimeReplicationRegistration(stateDir, component, key2);
7963
+ function enrollRuntimeReplication(db2, stateDir, component, binding, key4) {
7964
+ const file2 = location2(stateDir, component, key4), old = readRuntimeReplicationRegistration(stateDir, component, key4);
7930
7965
  const version = readSchemaVersion(db2);
7931
7966
  if (version?.component !== component) throw new Error("REPLICATION_SCHEMA_MISMATCH");
7932
7967
  checkRuntimeReplicationDatabase(db2, old, component, version.version, binding);
@@ -7939,7 +7974,7 @@ function enrollRuntimeReplication(db2, stateDir, component, binding, key2) {
7939
7974
  writeFileSync5(file2, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
7940
7975
  } catch (error) {
7941
7976
  if (error.code !== "EEXIST") throw error;
7942
- if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key2)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
7977
+ if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key4)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
7943
7978
  }
7944
7979
  if (process.platform !== "win32") {
7945
7980
  const fd = openSync6(dirname5(file2), "r");
@@ -8373,10 +8408,10 @@ CREATE TABLE memory_relationship_cognition_results (
8373
8408
  const rows = this.db.prepare(`SELECT * FROM memory_relationship_coverage WHERE state='deferred'${scope ? " AND scope_id=?" : ""} ORDER BY scope_id,group_key,source_id`).all(...scope ? [scopeId(scope)] : []);
8374
8409
  const groups = /* @__PURE__ */ new Map();
8375
8410
  for (const row of rows) {
8376
- const key2 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8377
- const group = groups.get(key2) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8411
+ const key4 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8412
+ const group = groups.get(key4) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8378
8413
  if (group.sourceIds.length < 20) group.sourceIds.push(row.source_id);
8379
- groups.set(key2, group);
8414
+ groups.set(key4, group);
8380
8415
  }
8381
8416
  return [...groups.values()];
8382
8417
  }
@@ -8566,9 +8601,9 @@ var init_entities = __esm({
8566
8601
  aliasEvidence(scope, entityId, cutoff) {
8567
8602
  const seen = /* @__PURE__ */ new Set();
8568
8603
  return (cutoff ? historicalRows(this.db, scope, "alias", cutoff) : this.db.prepare("SELECT entity_id entityId,source_id sourceId,alias FROM entity_aliases WHERE scope_id=? AND entity_id=?").all(scopeId(scope), entityId)).filter((alias) => {
8569
- const key2 = normalizeAlias(alias.alias);
8570
- if (seen.has(key2) || alias.entityId !== entityId || !this.sources.isCurrent(scope, alias.sourceId, cutoff) || !this.aliasIsName(scope, entityId, alias.sourceId, alias.alias, cutoff) || this.aliasReadable && !this.aliasReadable(scope, entityId, alias.sourceId, alias.alias, cutoff)) return false;
8571
- seen.add(key2);
8604
+ const key4 = normalizeAlias(alias.alias);
8605
+ if (seen.has(key4) || alias.entityId !== entityId || !this.sources.isCurrent(scope, alias.sourceId, cutoff) || !this.aliasIsName(scope, entityId, alias.sourceId, alias.alias, cutoff) || this.aliasReadable && !this.aliasReadable(scope, entityId, alias.sourceId, alias.alias, cutoff)) return false;
8606
+ seen.add(key4);
8572
8607
  return true;
8573
8608
  }).map((alias) => ({ alias: alias.alias, sourceId: alias.sourceId, sourceVersion: this.sources.get(scope, alias.sourceId, cutoff).sourceVersion }));
8574
8609
  }
@@ -8767,12 +8802,12 @@ function checkNotice(db2, sources, social, scope, id3, options) {
8767
8802
  return Boolean(source && (version === void 0 || source.sourceVersion === version) && social.readable(memoryScope, sourceId) && social.groundsCurrent(memoryScope, sourceId));
8768
8803
  };
8769
8804
  const relationshipCurrent = (relationshipId, version) => {
8770
- const key2 = `${relationshipId}:${version}`;
8805
+ const key4 = `${relationshipId}:${version}`;
8771
8806
  const row = db2.prepare(`SELECT r.*,v.state FROM memory_relationship_versions r JOIN fact_versions v
8772
8807
  ON v.scope_id=r.scope_id AND v.assertion_id=r.assertion_id AND v.system_to_revision IS NULL
8773
8808
  WHERE r.scope_id=? AND r.relationship_id=? AND r.semantic_version=?`).get(scope, relationshipId, version);
8774
8809
  if (!row || ["deleted", "retracted"].includes(row.state)) return false;
8775
- const derivation = db2.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key2);
8810
+ const derivation = db2.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key4);
8776
8811
  if (derivation && derivation.state !== "current") return false;
8777
8812
  const evidence = db2.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, row.assertion_id);
8778
8813
  return evidence.length > 0 && evidence.every((ref) => sourceCurrent(ref.source_id)) && JSON.parse(row.basis_refs).every((ref) => social.referenceCurrent(memoryScope, ref));
@@ -8847,8 +8882,11 @@ CREATE TABLE memory_relationship_notice_versions (
8847
8882
  }
8848
8883
  get(scope, id3) {
8849
8884
  const row = this.db.prepare("SELECT * FROM memory_relationship_notices WHERE scope_id=? AND notice_id=?").get(scopeId(scope), id3);
8850
- return row ? {
8851
- id: id3,
8885
+ return row ? this.decode(scope, row) : null;
8886
+ }
8887
+ decode(scope, row) {
8888
+ return {
8889
+ id: row.notice_id,
8852
8890
  scope,
8853
8891
  kind: row.kind,
8854
8892
  targetId: row.target_id,
@@ -8858,10 +8896,25 @@ CREATE TABLE memory_relationship_notice_versions (
8858
8896
  state: row.state,
8859
8897
  attempts: row.attempts,
8860
8898
  reason: row.reason
8861
- } : null;
8899
+ };
8862
8900
  }
8863
- list(scope) {
8864
- return this.db.prepare("SELECT notice_id FROM memory_relationship_notices WHERE scope_id=? ORDER BY updated_at,notice_id").all(scopeId(scope)).map((row) => this.get(scope, row.notice_id));
8901
+ list(scope, includeTerminal = true) {
8902
+ return this.db.prepare(`SELECT * FROM memory_relationship_notices WHERE scope_id=?
8903
+ ${includeTerminal ? "" : "AND state NOT IN ('delivered','blocked')"} ORDER BY updated_at,notice_id`).all(scopeId(scope)).map((row) => this.decode(scope, row));
8904
+ }
8905
+ /** Quiet identity work is not notification work. Evidence-backed resolved identities can still be withdrawn. */
8906
+ clarificationCandidates(scope) {
8907
+ const rows = this.db.prepare(`SELECT m.mention_id,m.question,m.mention_kind,m.candidates,m.span_start,m.span_end,s.text
8908
+ FROM memory_person_mentions m JOIN memory_sources s ON s.scope_id=m.scope_id AND s.source_id=m.source_id
8909
+ WHERE m.scope_id=? AND m.question IS NOT NULL AND trim(m.question)<>''
8910
+ AND (m.state='unresolved' OR m.clarification_source_id IS NOT NULL OR m.basis_refs<>'[]')
8911
+ AND (m.mention_kind NOT IN ('description','reference') OR json_array_length(m.candidates)>=2)
8912
+ ORDER BY m.source_id,m.span_start`).all(scopeId(scope));
8913
+ return rows.filter((row) => hasIdentityQuestion(
8914
+ row.question,
8915
+ row.text.slice(row.span_start, row.span_end),
8916
+ { mentionKind: row.mention_kind, candidateEntityIds: JSON.parse(row.candidates) }
8917
+ )).map((row) => row.mention_id);
8865
8918
  }
8866
8919
  finish(scope, id3, state, reason = "", redact = false) {
8867
8920
  this.db.prepare(`UPDATE memory_relationship_notices SET state=?,reason=?,updated_at=?,message=CASE WHEN ? THEN '[memory unavailable]' ELSE message END WHERE scope_id=? AND notice_id=?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), Number(redact), scopeId(scope), id3);
@@ -8872,6 +8925,12 @@ CREATE TABLE memory_relationship_notice_versions (
8872
8925
  check(scope, id3, options = {}) {
8873
8926
  return checkRelationshipNotice(this.db, scopeId(scope), id3, options);
8874
8927
  }
8928
+ /** The caller holds one transaction; proofs are discarded before any later batch or write. */
8929
+ checkMany(scope, ids, options = {}) {
8930
+ if (!ids.length) return [];
8931
+ const check = createRelationshipNoticeChecker(this.db);
8932
+ return ids.map((id3) => check(scopeId(scope), id3, options));
8933
+ }
8875
8934
  queue(scope, id3) {
8876
8935
  return Boolean(this.db.prepare("UPDATE memory_relationship_notices SET state='queued',reason='accepted_by_durable_queue',updated_at=? WHERE scope_id=? AND notice_id=? AND state IN ('pending','failed')").run((/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), id3).changes);
8877
8936
  }
@@ -8883,6 +8942,7 @@ CREATE TABLE memory_relationship_notice_versions (
8883
8942
  importantRecords(scope) {
8884
8943
  return this.db.prepare(`SELECT v.relationship_id,v.semantic_version FROM memory_relationship_notice_versions v
8885
8944
  JOIN memory_relationship_cognition_results r ON r.scope_id=v.scope_id AND r.job_id=v.job_id
8945
+ JOIN memory_relationship_heads h ON h.scope_id=v.scope_id AND h.relationship_id=v.relationship_id AND h.semantic_version=v.semantic_version
8886
8946
  WHERE v.scope_id=? AND r.important=1`).all(scopeId(scope)).map((row) => ({ relationshipId: row.relationship_id, semanticVersion: row.semantic_version }));
8887
8947
  }
8888
8948
  recordRoute(scope, sourceId, input) {
@@ -8950,9 +9010,9 @@ function installRelationshipHistory(db2) {
8950
9010
  FROM memory_scopes s WHERE EXISTS (SELECT 1 FROM memory_relationship_heads h WHERE h.scope_id=s.scope_id)
8951
9011
  OR EXISTS (SELECT 1 FROM memory_person_sources p WHERE p.scope_id=s.scope_id)
8952
9012
  OR EXISTS (SELECT 1 FROM memory_person_mentions m WHERE m.scope_id=s.scope_id)`);
8953
- for (const { table, kind, key: key2, columns: columns2 } of tables) {
9013
+ for (const { table, kind, key: key4, columns: columns2 } of tables) {
8954
9014
  const payload = (prefix2) => `json_object(${columns2.map((column) => `'${column}',${prefix2}${column}`).join(",")})`;
8955
- const target = (prefix2) => key2.startsWith("json_array") ? `json_array(${key2.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key2}`;
9015
+ const target = (prefix2) => key4.startsWith("json_array") ? `json_array(${key4.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key4}`;
8956
9016
  db2.exec(`INSERT INTO memory_knowledge_history(scope_id,target_kind,target_id,entity_revision,fact_revision,context_revision,recorded_at,payload_json)
8957
9017
  SELECT t.scope_id,'${kind}',${target("t.")},s.entity_revision,s.fact_revision,s.context_revision,strftime('%Y-%m-%dT%H:%M:%fZ','now'),${payload("t.")}
8958
9018
  FROM ${table} t JOIN memory_scopes s ON s.scope_id=t.scope_id`);
@@ -9381,16 +9441,16 @@ var init_snapshot_reads = __esm({
9381
9441
  this.changes = -1;
9382
9442
  }
9383
9443
  }
9384
- read(key2, load) {
9444
+ read(key4, load) {
9385
9445
  if (!this.values || !this.db.isTransaction) return load();
9386
9446
  const changes = this.changesRead.get().n;
9387
9447
  if (changes !== this.changes) {
9388
9448
  this.values.clear();
9389
9449
  this.changes = changes;
9390
9450
  }
9391
- if (this.values.has(key2)) return this.values.get(key2);
9451
+ if (this.values.has(key4)) return this.values.get(key4);
9392
9452
  const value = load();
9393
- if (this.values.size < 8192) this.values.set(key2, value);
9453
+ if (this.values.size < 8192) this.values.set(key4, value);
9394
9454
  return value;
9395
9455
  }
9396
9456
  };
@@ -9516,7 +9576,7 @@ function classifyFactVersions(versions, predicate, time) {
9516
9576
  needsReview: disputed || hypotheses.some((fact) => fact.validFrom === null)
9517
9577
  };
9518
9578
  }
9519
- var hash6, makeSlotId, FactStore;
9579
+ var hash6, makeSlotId, CLOSE_VALIDITY, occurrences, CHANGE_KINDS, CLAIM_KINDS, normalizeChange, FactStore;
9520
9580
  var init_facts = __esm({
9521
9581
  "src/mem7/core/state/facts.ts"() {
9522
9582
  "use strict";
@@ -9528,6 +9588,15 @@ var init_facts = __esm({
9528
9588
  init_basis_check();
9529
9589
  hash6 = (value) => createHash18("sha256").update(canonicalJson(value)).digest("hex");
9530
9590
  makeSlotId = (subjectId, predicate, context) => `slot_${hash6([subjectId, predicate, context]).slice(0, 32)}`;
9591
+ CLOSE_VALIDITY = '{"validFrom":null,"validTo":"\u7ED3\u675F\u65F6\u523B","precision":"exact"}';
9592
+ occurrences = (text2, quote2) => {
9593
+ let count = 0;
9594
+ for (let at = text2.indexOf(quote2); quote2 && at >= 0; at = text2.indexOf(quote2, at + 1)) count++;
9595
+ return count;
9596
+ };
9597
+ CHANGE_KINDS = ["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"];
9598
+ CLAIM_KINDS = ["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"];
9599
+ normalizeChange = (proposal) => !["close", "retract"].includes(proposal.changeKind) || !proposal.validity || proposal.validity.validFrom !== void 0 ? proposal : { ...proposal, validity: { ...proposal.validity, validFrom: null } };
9531
9600
  FactStore = class {
9532
9601
  constructor(db2, entities, transaction, readTransaction = transaction) {
9533
9602
  this.db = db2;
@@ -9694,6 +9763,8 @@ var init_facts = __esm({
9694
9763
  applyChange(scope, proposal, expectedSlotRevision, requestKey, batch) {
9695
9764
  if (!requestKey || !Number.isSafeInteger(expectedSlotRevision) || expectedSlotRevision < 0) throw new Error("INVALID_FACT_REQUEST");
9696
9765
  const id3 = scopeId(scope);
9766
+ const located = this.locateEvidence(id3, normalizeChange(proposal));
9767
+ proposal = located.proposal;
9697
9768
  const requestHash = hash6([proposal, expectedSlotRevision]);
9698
9769
  const prior = this.db.prepare("SELECT request_hash,result_json FROM fact_changes WHERE scope_id=? AND request_key=?").get(id3, requestKey);
9699
9770
  if (prior) {
@@ -9702,21 +9773,22 @@ var init_facts = __esm({
9702
9773
  }
9703
9774
  this.validate(scope, proposal);
9704
9775
  const slot = this.slot(scope, proposal.subjectId, proposal.predicate, proposal.contextKey);
9705
- if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision}`);
9776
+ if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision} \u2014 ` + (slot.revision > expectedSlotRevision ? "\u8BE5\u69FD\u5728\u4F60\u8BFB\u53D6\u4E4B\u540E\u6709\u65B0\u7684\u4FEE\u6539" : "\u8FD9\u4E2A\u69FD\u7684\u5199\u5165\u6B21\u6570\u5C11\u4E8E\u4F60\u586B\u7684\u7248\u672C\uFF0C\u591A\u534A\u662F proposal \u6307\u5230\u4E86\u522B\u7684\u69FD") + "\uFF1Bexpected_slot_revision \u586B\u91CD\u65B0\u8BFB\u53D6\u5230\u7684 basis.slotRevision" + (slot.revision < expectedSlotRevision ? `\u3002\u672C\u6B21\u843D\u5230 subjectId=${proposal.subjectId} predicate=${proposal.predicate} contextKey=${proposal.contextKey}\uFF08\u4E09\u8005\u987B\u4E0E\u65AD\u8A00\u4E00\u81F4\uFF1Brelation.open \u505A state_change/correction \u65F6 value \u5E26\u4E0A\u539F\u8BB0\u5F55\u7684 relationshipId\uFF09` : ""));
9706
9777
  this.db.prepare("INSERT OR IGNORE INTO fact_slots(scope_id,slot_id,subject_id,predicate,context_key,cardinality) VALUES (?,?,?,?,?,?)").run(id3, slot.slotId, proposal.subjectId, proposal.predicate, proposal.contextKey, predicates[proposal.predicate].cardinality);
9707
9778
  const before = this.current(id3, slot.slotId);
9708
9779
  const targetIds = [...new Set(proposal.targetAssertionIds ?? [])];
9709
9780
  const targets = targetIds.map((targetId) => {
9710
9781
  const target = before.find((fact) => fact.assertionId === targetId);
9711
- if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error("FACT_TARGET_MISMATCH");
9782
+ if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error(`FACT_TARGET_MISMATCH: ${targetId} \u4E0D\u5728\u8FD9\u4E2A\u69FD\uFF08subject+predicate+contextKey\uFF09\u7684\u5F53\u524D\u65AD\u8A00\u91CC\uFF0C\u6216\u5DF2\u64A4\u56DE/\u5220\u9664\uFF1B\u91CD\u65B0\u8BFB\u53D6\u5E76\u590D\u5236\u4ECD\u6709\u6548\u7684 assertionId`);
9712
9783
  return target;
9713
9784
  });
9714
- if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error("FACT_TARGET_REQUIRED");
9785
+ if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error(`FACT_TARGET_REQUIRED: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26 targetAssertionIds\uFF08\u88AB\u4FEE\u8BA2\u7684 assertionId\uFF0C\u4ECE\u8BFB\u53D6\u7ED3\u679C\u91CC\u6284\uFF09`);
9715
9786
  if (proposal.changeKind === "reinforce" && targets.length !== 1) throw new Error("REINFORCE_REQUIRES_ONE_TARGET");
9716
9787
  if (["assert", "exception"].includes(proposal.changeKind) && targets.length) throw new Error("UNEXPECTED_FACT_TARGET");
9717
9788
  const validity = proposal.validity ? normalizeValidity(proposal.validity) : void 0;
9718
- if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error("CHANGE_TIME_REQUIRED");
9719
- if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error("CHANGE_TIME_REQUIRED");
9789
+ const received2 = JSON.stringify({ validFrom: proposal.validity?.validFrom, validTo: proposal.validity?.validTo, precision: proposal.validity?.precision });
9790
+ if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error(`CHANGE_TIME_REQUIRED: changeKind=state_change \u9700\u8981 validity.validFrom=\u53D8\u5316\u65F6\u523B \u4E14 precision="exact"\uFF08\u65E7\u503C\u5230\u8FD9\u4E00\u523B\u4E3A\u6B62\uFF0C\u65B0 value \u4ECE\u8FD9\u4E00\u523B\u751F\u6548\uFF09\uFF1B\u6536\u5230 ${received2}\u3002\u53EA\u662F\u7ED3\u675F\u5173\u7CFB\uFF1AchangeKind \u6539 "close"`);
9791
+ if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error(`CHANGE_TIME_REQUIRED: changeKind=close \u9700\u8981 validity=${CLOSE_VALIDITY}\uFF08validFrom \u586B null\uFF1Bprecision \u4E5F\u53EF\u7528 observed\uFF09\uFF1B\u6536\u5230 ${received2}`);
9720
9792
  if (proposal.changeKind === "reinforce" && (canonicalJson(proposal.value) !== canonicalJson(targets[0].value) || proposal.claimKind !== targets[0].claimKind)) throw new Error("REINFORCE_VALUE_MISMATCH");
9721
9793
  if (proposal.changeKind === "reinforce" && (validity.validFrom !== targets[0].validFrom || validity.validTo !== targets[0].validTo || proposal.evidence.some((evidence) => evidence.relation !== "supports"))) throw new Error("REINFORCE_INTERVAL_OR_EVIDENCE_MISMATCH");
9722
9794
  const timestamp = batch?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
@@ -9732,8 +9804,8 @@ var init_facts = __esm({
9732
9804
  let state = proposal.changeKind === "correction" || proposal.changeKind === "retract" ? "retracted" : "disputed";
9733
9805
  if (proposal.changeKind === "state_change" || proposal.changeKind === "close") {
9734
9806
  const end = proposal.changeKind === "close" ? validity.validTo : validity.validFrom;
9735
- if (target.validFrom !== null && target.validFrom >= end) throw new Error("CHANGE_BEFORE_TARGET_START: use correction");
9736
- if (target.validTo !== null && target.validTo <= end) throw new Error("CHANGE_AFTER_TARGET_END");
9807
+ if (target.validFrom !== null && target.validFrom >= end) throw new Error(`CHANGE_BEFORE_TARGET_START: \u7ED3\u675F\u65F6\u523B ${end} \u4E0D\u665A\u4E8E\u8BE5\u65AD\u8A00\u7684\u5F00\u59CB\u65F6\u95F4 ${target.validFrom}\uFF1B\u4ECE\u4E00\u5F00\u59CB\u5C31\u4E0D\u6210\u7ACB\u7528 changeKind=correction`);
9808
+ if (target.validTo !== null && target.validTo <= end) throw new Error(`CHANGE_AFTER_TARGET_END: \u8BE5\u65AD\u8A00\u5DF2\u4E8E ${target.validTo} \u7ED3\u675F\uFF0C\u65E0\u9700\u518D\u5173\u95ED\uFF08\u6536\u5230 ${end}\uFF09`);
9737
9809
  state = target.state;
9738
9810
  nextValidity = { ...target, validTo: end };
9739
9811
  }
@@ -9749,7 +9821,7 @@ var init_facts = __esm({
9749
9821
  }
9750
9822
  if (!["retract", "close"].includes(proposal.changeKind)) {
9751
9823
  let state = proposal.claimKind === "inference" ? "candidate" : proposal.changeKind === "dispute" ? "disputed" : "supported";
9752
- if (state === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED");
9824
+ if (state === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED: \u65B0\u767B\u8BB0\u7684\u65AD\u8A00\u81F3\u5C11\u8981\u4E00\u6761 relation=supports \u7684\u539F\u8BDD\u8BC1\u636E");
9753
9825
  const current2 = this.current(id3, slot.slotId);
9754
9826
  if (predicates[proposal.predicate].cardinality === "single" && state === "supported" && current2.some((fact) => ["supported", "disputed"].includes(fact.state) && overlaps(fact, validity))) throw new Error("FACT_INTERVAL_CONFLICT: explicit correction/change/dispute required");
9755
9827
  if (state === "supported" && validity.validFrom === null && !(proposal.predicate === "relation.open" && proposal.value.observedAsCurrentAt)) state = "candidate";
@@ -9781,7 +9853,8 @@ var init_facts = __esm({
9781
9853
  slotId: slot.slotId,
9782
9854
  slotRevision: slot.revision + Number(changed),
9783
9855
  assertionIds: changedIds,
9784
- outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied"
9856
+ outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied",
9857
+ ...located.aligned.length ? { evidenceAligned: located.aligned } : {}
9785
9858
  };
9786
9859
  this.db.prepare("INSERT INTO fact_changes(scope_id,request_key,request_hash,fact_revision,result_json,proposal_json,before_json,after_json,recorded_at) VALUES (?,?,?,?,?,?,?,?,?)").run(id3, requestKey, requestHash, committedRevision, canonicalJson(result), canonicalJson(proposal), canonicalJson(before), canonicalJson(after), timestamp);
9787
9860
  if (changed) {
@@ -9820,21 +9893,31 @@ var init_facts = __esm({
9820
9893
  });
9821
9894
  }
9822
9895
  validate(scope, proposal) {
9823
- if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error("UNKNOWN_PREDICATE");
9824
- if (!["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"].includes(proposal.changeKind) || !["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"].includes(proposal.claimKind) || !proposal.contextKey || !proposal.reason || !proposal.evidence.length) throw new Error("INVALID_FACT_PROPOSAL");
9825
- if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT");
9896
+ if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error(`UNKNOWN_PREDICATE: predicate \u53EA\u80FD\u662F ${Object.keys(predicates).join("/")}\uFF08\u6536\u5230 ${String(proposal.predicate)}\uFF09`);
9897
+ const invalid = [
9898
+ !CHANGE_KINDS.includes(proposal.changeKind) && "changeKind",
9899
+ !CLAIM_KINDS.includes(proposal.claimKind) && "claimKind",
9900
+ !proposal.contextKey && "contextKey",
9901
+ !proposal.reason && "reason",
9902
+ (!Array.isArray(proposal.evidence) || !proposal.evidence.length) && "evidence"
9903
+ ].filter(Boolean);
9904
+ if (invalid.length) throw new Error(`INVALID_FACT_PROPOSAL: ${invalid.join("\u3001")} \u7F3A\u5931\u6216\u65E0\u6548 \u2014 changeKind \u53D6 ${CHANGE_KINDS.join("/")}\uFF0CclaimKind \u53D6 ${CLAIM_KINDS.join("/")}\uFF1BcontextKey\u3001reason \u5FC5\u586B\uFF0Cevidence \u81F3\u5C11\u4E00\u6761\u539F\u8BDD\u5F15\u6587`);
9905
+ if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT: inference \u53EA\u80FD\u767B\u8BB0\u65B0\u65AD\u8A00\uFF08changeKind=assert\uFF09\uFF0C\u4E0D\u80FD\u4FEE\u8BA2\u5DF2\u6709\u65AD\u8A00");
9826
9906
  const subject = this.entities.get(scope, proposal.subjectId);
9827
- if (!subject || !matchesEntityKind(subject.kind, predicates[proposal.predicate].subjectKind)) throw new Error("ENTITY_SCOPE_MISMATCH");
9907
+ const subjectKind = predicates[proposal.predicate].subjectKind;
9908
+ if (!subject || !matchesEntityKind(subject.kind, subjectKind)) throw new Error(`ENTITY_SCOPE_MISMATCH: predicate=${proposal.predicate} \u7684\u4E3B\u4F53\u987B\u662F ${typeof subjectKind === "string" ? subjectKind : subjectKind.join("/")}\uFF1B\u6536\u5230 ${proposal.subjectId}`);
9828
9909
  if (proposal.predicate === "relation.family" && !familyRoles.includes(proposal.contextKey)) throw new Error("INVALID_FAMILY_ROLE");
9829
9910
  if (proposal.predicate === "relation.colleague" && (proposal.contextKey !== normalizeOrganization(proposal.contextKey) || proposal.contextKey.length > 200)) throw new Error("INVALID_ORGANIZATION_CONTEXT");
9830
9911
  if (proposal.changeKind === "close") {
9831
- if (!isRelationship(proposal.predicate) || proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE");
9832
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
9912
+ if (!isRelationship(proposal.predicate)) throw new Error(`INVALID_RELATION_CLOSE: close \u53EA\u80FD\u7ED3\u675F\u5173\u7CFB\uFF08relation.family/colleague/open\uFF09\uFF0Cpredicate=${proposal.predicate} \u4E0D\u80FD close\uFF1B\u5176\u5B83\u4E8B\u5B9E\u7528 state_change\uFF08\u5E26\u65B0 value\uFF09\u6216 retract`);
9913
+ if (proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE: close \u4E0D\u5E26 value \u2014 \u53BB\u6389 proposal.value\uFF08\u5B83\u53EA\u5199\u7ED3\u675F\u65F6\u523B\uFF0C\u4E0D\u767B\u8BB0\u65B0\u5185\u5BB9\uFF09");
9914
+ if (!proposal.validity) throw new Error(`FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 close \u7528 ${CLOSE_VALIDITY}`);
9833
9915
  normalizeValidity(proposal.validity);
9834
9916
  }
9835
9917
  if (!["retract", "close"].includes(proposal.changeKind)) {
9918
+ if (proposal.value === void 0 || proposal.value === null) throw new Error(isRelationship(proposal.predicate) ? `INVALID_FACT_VALUE: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26\u65B0 value\uFF08\u65E7\u503C\u5230 validity.validFrom \u4E3A\u6B62\u3001\u65B0 value \u4ECE\u8FD9\u4E00\u523B\u751F\u6548\uFF09\uFF1B\u53EA\u662F\u7ED3\u675F\u5173\u7CFB\uFF1AchangeKind \u6539 "close"\uFF0C\u53BB\u6389 value\uFF0Cvalidity \u7528 ${CLOSE_VALIDITY}` : `INVALID_FACT_VALUE: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26 value`);
9836
9919
  validatePredicateValue(proposal.predicate, proposal.value);
9837
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
9920
+ if (!proposal.validity) throw new Error('FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 {"validFrom":\u5F00\u59CB\u65F6\u523B\u6216null,"validTo":\u7ED3\u675F\u65F6\u523B\u6216null,"precision":"exact|observed|unknown"}');
9838
9921
  normalizeValidity(proposal.validity);
9839
9922
  const objectKind = predicates[proposal.predicate].objectKind;
9840
9923
  if (objectKind && !matchesEntityKind(this.entities.get(scope, proposal.value.entityId)?.kind, objectKind)) throw new Error("OBJECT_SCOPE_MISMATCH");
@@ -9849,7 +9932,7 @@ var init_facts = __esm({
9849
9932
  const targets = (proposal.targetAssertionIds ?? []).map((assertionId) => this.db.prepare(`SELECT a.claim_kind,a.value_json,s.subject_id
9850
9933
  FROM fact_assertions a JOIN fact_slots s ON s.scope_id=a.scope_id AND s.slot_id=a.slot_id WHERE a.scope_id=? AND a.assertion_id=?`).get(scopeId(scope), assertionId));
9851
9934
  const perspective = value?.relationshipId ? this.entities.get(scope, value.perspectiveEntityId) : subject;
9852
- if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value?.perspectiveEntityId !== perspective.entityId || targets.some((target) => !target || target.claim_kind !== "agent_statement" || target.subject_id !== subject.entityId || JSON.parse(target.value_json).perspectiveEntityId !== perspective.entityId)) throw new Error("INVALID_AGENT_PERSPECTIVE");
9935
+ if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value?.perspectiveEntityId !== perspective.entityId || targets.some((target) => target && (target.claim_kind !== "agent_statement" || target.subject_id !== subject.entityId || JSON.parse(target.value_json).perspectiveEntityId !== perspective.entityId))) throw new Error("INVALID_AGENT_PERSPECTIVE: agent_statement \u53EA\u80FD\u7528\u4E8E relation.open\u2014\u2014\u8BC1\u636E\u5FC5\u987B\u662F\u8FD9\u4E2A agent \u81EA\u5DF1\u8BF4\u7684\u8BDD\uFF0C\u76EE\u6807\u65AD\u8A00\u4E5F\u5FC5\u987B\u662F\u540C\u4E00 agent \u767B\u8BB0\u7684 agent_statement");
9853
9936
  }
9854
9937
  if (proposal.predicate === "activity.schedule" && proposal.changeKind !== "retract") {
9855
9938
  const schedule = proposal.value;
@@ -9857,26 +9940,53 @@ var init_facts = __esm({
9857
9940
  if (proposal.contextKey !== "baseline" && !exception) throw new Error("INVALID_SCHEDULE_CONTEXT");
9858
9941
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
9859
9942
  }
9860
- for (const evidence of proposal.evidence) {
9943
+ for (const [index, evidence] of proposal.evidence.entries()) {
9944
+ const path35 = `evidence[${index}]`;
9945
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path35} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
9861
9946
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
9862
9947
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
9863
- AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId);
9864
- if (!source || source.interpretation_status === "deleted" || !Number.isSafeInteger(evidence.start) || !Number.isSafeInteger(evidence.end) || evidence.start < 0 || evidence.end <= evidence.start || evidence.end > source.text.length || source.text.slice(evidence.start, evidence.end) !== evidence.quote || !["supports", "refutes"].includes(evidence.relation)) throw new Error("INVALID_EVIDENCE_SPAN");
9948
+ AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
9949
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.sourceId \u2014 \u672C\u6C60\u8BFB\u4E0D\u5230\u8FD9\u6761\u6765\u6E90\uFF08\u4E0D\u5B58\u5728\u3001\u5DF2\u5220\u9664\u6216\u5DF2\u6709\u65B0\u7248\u672C\uFF09\uFF1B\u7528 memory_get({source_id}) \u6838\u5BF9\u5E76\u590D\u5236\u771F\u5B9E\u6765\u6E90 ID`);
9950
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
9951
+ if (!Number.isSafeInteger(evidence.start) || !Number.isSafeInteger(evidence.end) || evidence.start < 0 || evidence.end <= evidence.start || evidence.end > source.text.length || source.text.slice(evidence.start, evidence.end) !== evidence.quote) {
9952
+ const count = occurrences(source.text, evidence.quote);
9953
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path35}.quote \u2014 \u5F15\u6587\u5FC5\u987B\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587\uFF08\u539F\u6587\u957F ${source.text.length}\uFF09\uFF1B\u7528 memory_get({source_id}) \u590D\u5236\u539F\u53E5\uFF0C\u4E0D\u8981\u6539\u5199` : `INVALID_EVIDENCE_SPAN: ${path35} \u2014 \u5F15\u6587\u5728\u539F\u6587\u4E2D\u51FA\u73B0 ${count} \u6B21\uFF0C\u8BF7\u7ED9\u51C6\u786E\u7684\u90A3\u4E00\u5904 start/end\uFF08UTF-16 \u4E0B\u6807\uFF0C\u539F\u6587\u957F ${source.text.length}\uFF09`);
9954
+ }
9955
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
9865
9956
  const relationValue = proposal.value;
9866
9957
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
9867
- throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED");
9958
+ throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED: attribution=reported \u65F6 claimKind \u987B\u4E3A reported_statement\uFF0C\u4E14 attributionQuote \u5FC5\u987B\u662F\u539F\u8BDD\u91CC\u9010\u5B57\u7684\u8F6C\u8FF0\u53E5\uFF08\u5982\u300C\u67D0\u67D0\u8BF4\uFF1A\u300D\uFF09");
9868
9959
  }
9960
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path35} \u7684\u4F5C\u8005/\u89D2\u8272\u4E0E claimKind=${proposal.claimKind} \u4E0D\u7B26\uFF08\u6765\u6E90 role=${source.role}, originClass=${source.origin_class}\uFF09 \u2014 \u7528\u6237\u539F\u8BDD\u914D user_statement\u3001\u5DE5\u5177\u7ED3\u679C\u914D tool_observation\u3001\u8F6C\u8FF0\u4ED6\u4EBA\u914D reported_statement\u3001\u4F60\u81EA\u5DF1\u8BF4\u7684\u8BDD\u914D agent_statement\uFF1B\u6362\u5339\u914D\u7684\u6765\u6E90\u6216\u6539 claimKind`);
9869
9961
  if (proposal.claimKind !== "inference") {
9870
- if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw new Error("EVIDENCE_ROLE_MISMATCH");
9871
- if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw new Error("EVIDENCE_ROLE_MISMATCH");
9962
+ if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
9963
+ if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
9872
9964
  if (proposal.claimKind === "reported_statement" && (source.role !== "user" || !["third_party_report", "legacy_import"].includes(source.origin_class))) {
9873
9965
  const value = proposal.value;
9874
9966
  const attributed = proposal.predicate === "relation.open" && value?.attribution === "reported" && ["user", "assistant"].includes(source.role) && ["host_user", "client_reported_user", "assistant"].includes(source.origin_class) && hasReportedAttribution(source.text, value, this.entities.sourceMentions(scope, evidence.sourceId));
9875
- if (!attributed) throw new Error("EVIDENCE_ROLE_MISMATCH");
9967
+ if (!attributed) throw roleMismatch();
9876
9968
  }
9877
- if (proposal.claimKind === "agent_statement" && (source.role !== "assistant" || source.origin_class !== "assistant" || this.entities.speaker(scope, evidence.sourceId)?.entityId !== (proposal.value?.perspectiveEntityId ?? subject.entityId))) throw new Error("EVIDENCE_ROLE_MISMATCH");
9878
- }
9879
- }
9969
+ if (proposal.claimKind === "agent_statement" && (source.role !== "assistant" || source.origin_class !== "assistant" || this.entities.speaker(scope, evidence.sourceId)?.entityId !== (proposal.value?.perspectiveEntityId ?? subject.entityId))) throw roleMismatch();
9970
+ }
9971
+ }
9972
+ }
9973
+ /** 1124:UTF-16 下标不是人能数准的——引文在原文中只出现一次时,start/end 可省略或写错,由引擎对齐;没有或重复的留给 validate() 说明。 */
9974
+ locateEvidence(scope, proposal) {
9975
+ const aligned = [];
9976
+ if (!Array.isArray(proposal.evidence)) return { proposal, aligned };
9977
+ const evidence = proposal.evidence.map((ref, index) => {
9978
+ const text2 = this.db.prepare("SELECT text FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, ref?.sourceId ?? null)?.text;
9979
+ if (typeof text2 !== "string" || typeof ref?.quote !== "string" || !ref.quote || occurrences(text2, ref.quote) !== 1) return ref;
9980
+ const start = text2.indexOf(ref.quote);
9981
+ if (Number.isSafeInteger(ref.start) && ref.start === start && ref.end === start + ref.quote.length) return ref;
9982
+ aligned.push({
9983
+ index,
9984
+ given: [Number.isSafeInteger(ref.start) ? ref.start : null, Number.isSafeInteger(ref.end) ? ref.end : null],
9985
+ located: [start, start + ref.quote.length]
9986
+ });
9987
+ return { ...ref, start, end: start + ref.quote.length };
9988
+ });
9989
+ return { proposal: { ...proposal, evidence }, aligned };
9880
9990
  }
9881
9991
  current(scope, slotId) {
9882
9992
  return this.versions(scope, slotId);
@@ -10019,7 +10129,7 @@ function summary(input) {
10019
10129
  try {
10020
10130
  const p = JSON.parse(input);
10021
10131
  if (!p || typeof p !== "object" || Array.isArray(p)) return input;
10022
- const small = Object.fromEntries(Object.entries(p).filter(([key2, value]) => routing.has(key2) || Buffer.byteLength(JSON.stringify(value)) <= 1024));
10132
+ const small = Object.fromEntries(Object.entries(p).filter(([key4, value]) => routing.has(key4) || Buffer.byteLength(JSON.stringify(value)) <= 1024));
10023
10133
  if (!Object.hasOwn(small, "basis") && p.basis?.scope) small.basis = { scope: p.basis.scope };
10024
10134
  return JSON.stringify(small);
10025
10135
  } catch {
@@ -10415,8 +10525,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10415
10525
  socialInterpretations;
10416
10526
  relationshipCognition;
10417
10527
  relationshipNotices;
10418
- knowledgeCutoff(scope, request3) {
10419
- return knowledgeCutoff(this.db, scope, request3);
10528
+ knowledgeCutoff(scope, request4) {
10529
+ return knowledgeCutoff(this.db, scope, request4);
10420
10530
  }
10421
10531
  knowledgeSnapshot(scope, cutoff) {
10422
10532
  return historicalRows(this.db, scope, "scope", cutoff)[0] ?? { entityRevision: 0, factRevision: 0, contextRevision: 0, sourceSeq: 0, interpretedSeq: 0 };
@@ -10649,6 +10759,35 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10649
10759
  };
10650
10760
  }, scope, version);
10651
10761
  }
10762
+ /** 1123 跨轮去重(md):entry id 由正文决定、所在文件由日期决定——日期判定跨轮漂移时新块落到
10763
+ * 另一个日期文件,appendMd 的原位替换只扫目标文件,旧块留成孤儿(妹妹 1122 重洗 44 处双份)。
10764
+ * 单遍扫 episodes:id 在本轮写入表里、但所在文件 ≠ 本轮目标日期的块删掉,entry_count 同步。
10765
+ * 不在本轮写入表里的条目不碰(别的来源/原生记忆)。 */
10766
+ purgeEpisodeEntries(ownerId, targetDateById) {
10767
+ if (!targetDateById.size) return 0;
10768
+ const dir = join11(this.root, "users", ownerId, "episodes");
10769
+ if (!existsSync5(dir)) return 0;
10770
+ let removed = 0;
10771
+ for (const name of readdirSync(dir)) {
10772
+ const fileDate = /^episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
10773
+ if (!fileDate) continue;
10774
+ const file2 = join11(dir, name);
10775
+ let text2 = readFileSync8(file2, "utf8"), hit = false;
10776
+ for (const m of text2.matchAll(/<!-- entry:(\S+) -->/g)) {
10777
+ const target = targetDateById.get(m[1]);
10778
+ if (target === void 0 || target === fileDate) continue;
10779
+ text2 = text2.replace(new RegExp(`\\n*<!-- entry:${m[1]} -->[\\s\\S]*?<!-- /entry:${m[1]} -->`), "");
10780
+ removed++;
10781
+ hit = true;
10782
+ }
10783
+ if (!hit) continue;
10784
+ text2 = text2.replace(/entry_count: \d+/, `entry_count: ${(text2.match(/<!-- entry:/g) ?? []).length}`);
10785
+ const tmp = `${file2}.${process.pid}.tmp`;
10786
+ writeFileSync6(tmp, text2);
10787
+ renameSync3(tmp, file2);
10788
+ }
10789
+ return removed;
10790
+ }
10652
10791
  appendAtomicFacts(ownerId, dateStr, entries, scope, version) {
10653
10792
  const flat2 = [];
10654
10793
  for (const e of entries) {
@@ -11549,10 +11688,10 @@ ${e.outcome}
11549
11688
  ];
11550
11689
  if (revalidationKinds.length === 0) return 0;
11551
11690
  for (const scope of this.sources.scopes()) {
11552
- const received = this.sources.interpretationProgress(scope).received;
11691
+ const received2 = this.sources.interpretationProgress(scope).received;
11553
11692
  for (const artifact of this.dependencies.dirty(scope)) {
11554
11693
  if (!revalidationKinds.includes(artifact.kind)) continue;
11555
- if (received > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11694
+ if (received2 > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11556
11695
  const previous = this.db.prepare("SELECT kind,payload FROM ome_jobs WHERE id=?").all(artifactGenerationJobId(this.db, scope, artifact.kind, artifact.id, artifact.version));
11557
11696
  for (const row of previous) {
11558
11697
  const payload = JSON.parse(row.payload);
@@ -12496,10 +12635,6 @@ var init_process_card = __esm({
12496
12635
  });
12497
12636
  return this.creation;
12498
12637
  }
12499
- /** Mode decisions can start native progress without awaiting any channel I/O. */
12500
- start() {
12501
- if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable())) this.beginInBackground();
12502
- }
12503
12638
  progressCapable() {
12504
12639
  return !!this.adapter.sendProgress && !!this.adapter.updateProgress && !!this.adapter.removeProgress;
12505
12640
  }
@@ -12640,8 +12775,7 @@ var init_process_card = __esm({
12640
12775
  }
12641
12776
  /** stream_event content_block_delta(thinking_delta):实时喂思考内容 */
12642
12777
  onThinkingDelta(chunk) {
12643
- if (!chunk || this.ended || this.disposed) return;
12644
- this.ensureStarted();
12778
+ if (!chunk || this.ended || this.disposed || !this.started) return;
12645
12779
  const lt = this.state.liveThink ??= { start: Date.now(), text: "" };
12646
12780
  lt.text += chunk;
12647
12781
  if (lt.text.length > 800) lt.text = lt.text.slice(-600);
@@ -12659,8 +12793,7 @@ var init_process_card = __esm({
12659
12793
  }
12660
12794
  /** assistant thinking 完整块(无增量流时的兜底;增量路径下与 Thought 行去重) */
12661
12795
  onThinking(text2) {
12662
- if (this.ended || this.disposed) return;
12663
- this.ensureStarted();
12796
+ if (this.ended || this.disposed || !this.started) return;
12664
12797
  if (this.state.liveThink) return;
12665
12798
  const last = this.state.rows[this.state.rows.length - 1];
12666
12799
  if (last?.kind === "think") return;
@@ -12672,10 +12805,10 @@ var init_process_card = __esm({
12672
12805
  const rid = this.nextRid("p");
12673
12806
  const preview = stripCardUnsafe(toolArgsSummary(toolName, input) || oneLine(JSON.stringify(input).slice(0, 200)));
12674
12807
  return new Promise((resolve12) => {
12675
- let settled = false;
12808
+ let settled2 = false;
12676
12809
  const settle = (v, message) => {
12677
- if (settled) return;
12678
- settled = true;
12810
+ if (settled2) return;
12811
+ settled2 = true;
12679
12812
  clearTimeout(timer);
12680
12813
  pendingPerms.delete(rid);
12681
12814
  this.currentPermRid = null;
@@ -12703,10 +12836,10 @@ var init_process_card = __esm({
12703
12836
  const rid = this.nextRid("q");
12704
12837
  const safeQ = questions.map((q) => ({ ...q, question: stripCardUnsafe(q.question), header: stripCardUnsafe(q.header), options: q.options.map((o) => ({ ...o, label: stripCardUnsafe(o.label) })) }));
12705
12838
  return new Promise((resolve12) => {
12706
- let settled = false;
12839
+ let settled2 = false;
12707
12840
  const settle = (answers, message) => {
12708
- if (settled) return;
12709
- settled = true;
12841
+ if (settled2) return;
12842
+ settled2 = true;
12710
12843
  clearTimeout(timer);
12711
12844
  pendingAsks.delete(rid);
12712
12845
  this.currentAskRid = null;
@@ -12797,7 +12930,7 @@ var init_process_card = __esm({
12797
12930
  return;
12798
12931
  }
12799
12932
  if (this.patchTimer) return;
12800
- const min = this.channelV === "cardkit" || this.channelV === "progress" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
12933
+ const min = this.channelV === "cardkit" || this.channelV === "progress" ? this.adapter.progressThrottleMs ?? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
12801
12934
  const wait2 = Math.max(0, min - (Date.now() - this.lastPatchAt));
12802
12935
  this.patchTimer = setTimeout(() => {
12803
12936
  this.patchTimer = null;
@@ -12812,10 +12945,6 @@ var init_process_card = __esm({
12812
12945
  await this.creation?.catch(() => {
12813
12946
  });
12814
12947
  if (this.disposed || this.ended && !final) return;
12815
- if (final && this.options.discardEmptyOnDone && this.state.status === "done" && !this.state.earlierSteps && !this.state.rows.some((row) => row.kind !== "think") && (!this.messageId || this.adapter.deletePreview || this.adapter.removeProgress)) {
12816
- await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
12817
- return;
12818
- }
12819
12948
  const pushed = await this.doPatch(final);
12820
12949
  if (final && !pushed && !this.disposed && this.options.sendSummary && !this.summarySent) {
12821
12950
  this.summarySent = true;
@@ -12839,8 +12968,8 @@ var init_process_card = __esm({
12839
12968
  }
12840
12969
  async doPatch(final = false) {
12841
12970
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
12842
- const key2 = this.pushKey();
12843
- if (key2 === this.lastPushKey) return true;
12971
+ const key4 = this.pushKey();
12972
+ if (key4 === this.lastPushKey) return true;
12844
12973
  this.lastPatchAt = Date.now();
12845
12974
  const card = this.channelV === "progress" ? null : this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
12846
12975
  if (this.channelV !== "preview" && this.channelV !== "progress" && !card) return false;
@@ -12856,7 +12985,7 @@ var init_process_card = __esm({
12856
12985
  await this.adapter.patchCard(this.messageId, card);
12857
12986
  } else return false;
12858
12987
  this.patchFailures = 0;
12859
- this.lastPushKey = key2;
12988
+ this.lastPushKey = key4;
12860
12989
  return true;
12861
12990
  } catch (err) {
12862
12991
  if (this.channelV === "cardkit" && isPermissionDenied(err)) {
@@ -12866,7 +12995,7 @@ var init_process_card = __esm({
12866
12995
  await this.removeCard();
12867
12996
  if (this.disposed) return false;
12868
12997
  await this.createLegacyCard();
12869
- this.lastPushKey = key2;
12998
+ this.lastPushKey = key4;
12870
12999
  this.patchFailures = 0;
12871
13000
  if (!this.ended) this.startHeartbeat();
12872
13001
  return true;
@@ -13001,23 +13130,23 @@ var init_session_map = __esm({
13001
13130
  this.map = {};
13002
13131
  }
13003
13132
  }
13004
- get(key2) {
13005
- return this.map[key2];
13133
+ get(key4) {
13134
+ return this.map[key4];
13006
13135
  }
13007
- set(key2, sessionId, workDir) {
13008
- this.map[key2] = { sessionId, workDir, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
13136
+ set(key4, sessionId, workDir) {
13137
+ this.map[key4] = { sessionId, workDir, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
13009
13138
  this.save();
13010
13139
  }
13011
13140
  /** 清掉 binding 的会话绑定(/cc-new)。返回是否真的清了。 */
13012
- clear(key2) {
13013
- if (!(key2 in this.map)) return false;
13014
- delete this.map[key2];
13141
+ clear(key4) {
13142
+ if (!(key4 in this.map)) return false;
13143
+ delete this.map[key4];
13015
13144
  this.save();
13016
13145
  return true;
13017
13146
  }
13018
13147
  /** /cc-switch 直写目标会话 */
13019
- switchTo(key2, sessionId, workDir) {
13020
- this.set(key2, sessionId, workDir);
13148
+ switchTo(key4, sessionId, workDir) {
13149
+ this.set(key4, sessionId, workDir);
13021
13150
  }
13022
13151
  save() {
13023
13152
  try {
@@ -13033,6 +13162,52 @@ var init_session_map = __esm({
13033
13162
  }
13034
13163
  });
13035
13164
 
13165
+ // src/cc-driver/long-http.ts
13166
+ import { request as request3 } from "node:http";
13167
+ function longPostJson(url, body, headers = {}, signal) {
13168
+ const data = Buffer.from(JSON.stringify(body));
13169
+ return new Promise((resolve12, reject) => {
13170
+ const req = request3(url, { method: "POST", headers: { ...headers, "Content-Length": String(data.byteLength) } }, (res) => {
13171
+ const chunks = [];
13172
+ res.on("data", (chunk) => chunks.push(chunk));
13173
+ res.on("error", reject);
13174
+ res.on("end", () => {
13175
+ cleanup();
13176
+ const text2 = Buffer.concat(chunks).toString("utf8");
13177
+ try {
13178
+ resolve12({ status: res.statusCode ?? 0, json: JSON.parse(text2) });
13179
+ } catch {
13180
+ reject(new Error(`\u5BF9\u7AEF\u8FD4\u56DE\u4E86\u975E JSON\uFF08HTTP ${res.statusCode}\uFF09\uFF1A${text2.slice(0, 200)}`));
13181
+ }
13182
+ });
13183
+ });
13184
+ req.on("error", (err) => {
13185
+ cleanup();
13186
+ reject(err);
13187
+ });
13188
+ const onAbort = () => {
13189
+ req.destroy();
13190
+ reject(signal.reason instanceof Error ? signal.reason : new Error("\u8BF7\u6C42\u5DF2\u53D6\u6D88"));
13191
+ };
13192
+ const cleanup = () => {
13193
+ signal?.removeEventListener("abort", onAbort);
13194
+ };
13195
+ if (signal) {
13196
+ if (signal.aborted) {
13197
+ onAbort();
13198
+ return;
13199
+ }
13200
+ signal.addEventListener("abort", onAbort, { once: true });
13201
+ }
13202
+ req.end(data);
13203
+ });
13204
+ }
13205
+ var init_long_http = __esm({
13206
+ "src/cc-driver/long-http.ts"() {
13207
+ "use strict";
13208
+ }
13209
+ });
13210
+
13036
13211
  // src/cc-driver/desktop.ts
13037
13212
  import fs4 from "node:fs";
13038
13213
  import os2 from "node:os";
@@ -13084,14 +13259,13 @@ async function findDesktopTargets(workDir, sessionId) {
13084
13259
  return targets;
13085
13260
  }
13086
13261
  async function askDesktop(target, prompt, source, signal) {
13087
- const response = await fetch(`http://127.0.0.1:${target.port}/ask`, {
13088
- method: "POST",
13089
- headers: { authorization: `Bearer ${target.token}`, "content-type": "application/json" },
13090
- signal,
13091
- body: JSON.stringify({ prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir })
13092
- });
13093
- const result = await response.json();
13094
- if (!response.ok) throw failure(result.error || `Desktop CC HTTP ${response.status}`, response.status);
13262
+ const { status, json: result } = await longPostJson(
13263
+ `http://127.0.0.1:${target.port}/ask`,
13264
+ { prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13265
+ { authorization: `Bearer ${target.token}` },
13266
+ signal
13267
+ );
13268
+ if (status !== 200) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
13095
13269
  if (result.sessionId !== target.sessionId || typeof result.text !== "string" || typeof result.isError !== "boolean") {
13096
13270
  throw failure("Desktop CC returned an invalid result");
13097
13271
  }
@@ -13101,6 +13275,7 @@ var registryDir, canonical2, failure, alive;
13101
13275
  var init_desktop = __esm({
13102
13276
  "src/cc-driver/desktop.ts"() {
13103
13277
  "use strict";
13278
+ init_long_http();
13104
13279
  registryDir = () => process.env.CC_DESKTOP_REGISTRY_DIR || path4.join(os2.homedir(), ".engine7", "cc-driver", "desktops");
13105
13280
  canonical2 = (dir) => {
13106
13281
  try {
@@ -13224,9 +13399,9 @@ function sharedNodeModules() {
13224
13399
  function pkgDir(name) {
13225
13400
  return path5.join(sharedNodeModules(), ...name.split("/"));
13226
13401
  }
13227
- function readConfig(key2) {
13402
+ function readConfig(key4) {
13228
13403
  try {
13229
- return liveConfig.get(key2);
13404
+ return liveConfig.get(key4);
13230
13405
  } catch {
13231
13406
  }
13232
13407
  }
@@ -13241,9 +13416,9 @@ function downloadsEnabled() {
13241
13416
  function currentPlatformKey() {
13242
13417
  return `${process.platform}-${process.arch}`;
13243
13418
  }
13244
- function featureSpec(key2) {
13245
- const spec = OPTIONAL_FEATURES[key2];
13246
- if (!spec) throw new Error(`[dep-downloader] optional-deps.json \u91CC\u6CA1\u6709\u952E\uFF1A${key2}`);
13419
+ function featureSpec(key4) {
13420
+ const spec = OPTIONAL_FEATURES[key4];
13421
+ if (!spec) throw new Error(`[dep-downloader] optional-deps.json \u91CC\u6CA1\u6709\u952E\uFF1A${key4}`);
13247
13422
  return spec;
13248
13423
  }
13249
13424
  function markerPath(spec) {
@@ -13256,8 +13431,8 @@ function isPkgInstalled(spec) {
13256
13431
  return false;
13257
13432
  }
13258
13433
  }
13259
- function isOptionalFeatureInstalled(key2) {
13260
- const spec = featureSpec(key2);
13434
+ function isOptionalFeatureInstalled(key4) {
13435
+ const spec = featureSpec(key4);
13261
13436
  if (!isPkgInstalled(spec.main)) return false;
13262
13437
  const plat = spec.platform?.[currentPlatformKey()];
13263
13438
  if (plat && !isPkgInstalled(plat)) return false;
@@ -13361,9 +13536,9 @@ function notInstalledError(spec) {
13361
13536
  err.code = "ERR_MODULE_NOT_FOUND";
13362
13537
  return err;
13363
13538
  }
13364
- async function ensureOptionalFeature(key2, onProgress) {
13365
- const spec = featureSpec(key2);
13366
- if (isOptionalFeatureInstalled(key2)) return pkgDir(spec.main.name);
13539
+ async function ensureOptionalFeature(key4, onProgress) {
13540
+ const spec = featureSpec(key4);
13541
+ if (isOptionalFeatureInstalled(key4)) return pkgDir(spec.main.name);
13367
13542
  if (!downloadsEnabled()) throw notInstalledError(spec);
13368
13543
  const plat = spec.platform?.[currentPlatformKey()];
13369
13544
  const pkgs = [spec.main, ...plat ? [plat] : [], ...spec.extra ?? []];
@@ -13374,17 +13549,17 @@ function requireFromShared(name) {
13374
13549
  const req = createRequire3(path5.join(sharedNodeModules(), ".e7-resolve.js"));
13375
13550
  return req(name);
13376
13551
  }
13377
- async function loadOptionalModule(key2, onProgress) {
13378
- const spec = featureSpec(key2);
13552
+ async function loadOptionalModule(key4, onProgress) {
13553
+ const spec = featureSpec(key4);
13379
13554
  const notFound = (err) => err?.code === "ERR_MODULE_NOT_FOUND" || err?.code === "MODULE_NOT_FOUND";
13380
13555
  try {
13381
13556
  return nodeRequire(spec.main.name);
13382
13557
  } catch (err) {
13383
13558
  if (!notFound(err)) throw err;
13384
13559
  }
13385
- if (!isOptionalFeatureInstalled(key2)) {
13560
+ if (!isOptionalFeatureInstalled(key4)) {
13386
13561
  if (!downloadsEnabled()) throw notInstalledError(spec);
13387
- await ensureOptionalFeature(key2, onProgress);
13562
+ await ensureOptionalFeature(key4, onProgress);
13388
13563
  }
13389
13564
  const dir = pkgDir(spec.main.name);
13390
13565
  try {
@@ -13414,11 +13589,11 @@ var init_dep_downloader = __esm({
13414
13589
  OPTIONAL_FEATURES = (() => {
13415
13590
  const raw = optional_deps_default;
13416
13591
  const out = {};
13417
- for (const [key2, v] of Object.entries(raw)) {
13418
- if (key2 === "//") continue;
13592
+ for (const [key4, v] of Object.entries(raw)) {
13593
+ if (key4 === "//") continue;
13419
13594
  const bad = !v?.main?.name || !v?.main?.version || !v?.main?.integrity?.startsWith("sha512-") || v.platform !== void 0 && Object.values(v.platform).some((p) => !p?.name || !p?.version || !p?.integrity?.startsWith("sha512-")) || v.extra !== void 0 && (!Array.isArray(v.extra) || v.extra.some((p) => !p?.name || !p?.version || !p?.integrity?.startsWith("sha512-")));
13420
- if (bad) throw new Error(`[dep-downloader] optional-deps.json \u6761\u76EE ${key2} \u7F3A name/version/integrity\uFF08integrity \u53D6 npm view <name>@<version> dist.integrity\uFF09`);
13421
- out[key2] = { key: key2, label: v.label ?? key2, main: v.main, platform: v.platform, extra: v.extra };
13595
+ if (bad) throw new Error(`[dep-downloader] optional-deps.json \u6761\u76EE ${key4} \u7F3A name/version/integrity\uFF08integrity \u53D6 npm view <name>@<version> dist.integrity\uFF09`);
13596
+ out[key4] = { key: key4, label: v.label ?? key4, main: v.main, platform: v.platform, extra: v.extra };
13422
13597
  }
13423
13598
  return out;
13424
13599
  })();
@@ -13428,6 +13603,8 @@ var init_dep_downloader = __esm({
13428
13603
  });
13429
13604
 
13430
13605
  // src/cc-driver/driver.ts
13606
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync8 } from "node:fs";
13607
+ import { extname, join as join14 } from "node:path";
13431
13608
  function requestError(message, status = 409) {
13432
13609
  return Object.assign(new Error(message), { status });
13433
13610
  }
@@ -14037,14 +14214,16 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14037
14214
  return task;
14038
14215
  }
14039
14216
  };
14040
- CcDriverHub = class {
14217
+ CcDriverHub = class _CcDriverHub {
14041
14218
  map;
14042
14219
  sessions = /* @__PURE__ */ new Map();
14043
14220
  cfg;
14044
14221
  cm;
14222
+ stateDir;
14045
14223
  constructor(cfg, cm, stateDir, predecessor) {
14046
14224
  this.cfg = cfg;
14047
14225
  this.cm = cm;
14226
+ this.stateDir = stateDir;
14048
14227
  this.map = new CcSessionMapStore(stateDir);
14049
14228
  for (const b of cfg.bindings) {
14050
14229
  this.sessions.set(bindingKey(b), new CcDriverSession(b, cm, this.map, predecessor));
@@ -14054,15 +14233,49 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14054
14233
  matches(inbound) {
14055
14234
  return findBinding(inbound, this.cfg) !== null;
14056
14235
  }
14057
- /** 路由一条命中消息(调用方已 matches 过)。附件消息 MVP 不支持,提示。 */
14236
+ /** 落盘附件的体积上限:这条通道只收图/文档,不让大视频把 stateDir 撑爆 */
14237
+ static MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
14238
+ /**
14239
+ * 入站附件落盘(1123 翀哥:「我给你发图片你现在收不到」):CC 会话靠工具读文件——
14240
+ * 图片用 Read 工具直接看,文档走对应 skill。只做落盘+正文附路径,不改 CC 的输入协议。
14241
+ * 落在 <stateDir>/media/inbound(与 my-eyes 等同目录惯例);单个附件失败不影响其它附件和正文。
14242
+ */
14243
+ async saveAttachments(inbound) {
14244
+ const lines = [];
14245
+ const dir = join14(this.stateDir, "media", "inbound");
14246
+ for (const [i, a] of (inbound.attachments ?? []).entries()) {
14247
+ const label = a.filename || `\u9644\u4EF6${i + 1}`;
14248
+ try {
14249
+ if (!a.loadBytes) throw new Error("\u9002\u914D\u5668\u672A\u63D0\u4F9B\u4E0B\u8F7D\u80FD\u529B");
14250
+ if (a.size > _CcDriverHub.MAX_ATTACHMENT_BYTES) throw new Error(`\u6587\u4EF6\u8FC7\u5927\uFF08${a.size} \u5B57\u8282\uFF09\uFF0C\u672A\u843D\u76D8`);
14251
+ const bytes2 = await a.loadBytes();
14252
+ const ext = extname(a.filename || "").toLowerCase().replace(/[^.a-z0-9]/g, "") || (a.contentType.startsWith("image/") ? "." + a.contentType.slice(6).replace("jpeg", "jpg") : "");
14253
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
14254
+ const tail = (inbound.messageId || "msg").replace(/\W/g, "").slice(-8);
14255
+ const file2 = join14(dir, `${stamp}-${tail}-${i + 1}${ext}`);
14256
+ mkdirSync9(dir, { recursive: true });
14257
+ writeFileSync8(file2, bytes2);
14258
+ const how = a.contentType.startsWith("image/") ? "\u56FE\u7247\u2014\u2014\u8FD9\u662F\u4E00\u6761\u5FC5\u987B\u56DE\u5E94\u7684\u6D88\u606F\uFF1A\u5148\u7528 Read \u5DE5\u5177\u6253\u5F00\u8FD9\u4E2A\u8DEF\u5F84\u67E5\u770B\u5185\u5BB9\uFF0C\u518D\u544A\u8BC9\u6211\u4F60\u770B\u5230\u4E86\u4EC0\u4E48" : `\u6587\u4EF6\uFF08${a.contentType || "\u672A\u77E5\u7C7B\u578B"}\uFF09\u2014\u2014\u7528\u5BF9\u5E94\u5DE5\u5177\u6253\u5F00\u8FD9\u4E2A\u8DEF\u5F84\u67E5\u770B\u5185\u5BB9\u540E\u56DE\u5E94`;
14259
+ lines.push(`${i + 1}. ${label}\uFF0C${how}\uFF1A${file2}`);
14260
+ } catch (err) {
14261
+ lines.push(`${i + 1}. ${label} \u843D\u76D8\u5931\u8D25\uFF1A${err?.message || String(err)}`);
14262
+ }
14263
+ }
14264
+ return `\uFF08\u6536\u5230 ${lines.length} \u4E2A\u9644\u4EF6\uFF0C\u5DF2\u4FDD\u5B58\u5230\u672C\u673A\uFF1A
14265
+ ${lines.join("\n")}\uFF09`;
14266
+ }
14267
+ /** 路由一条命中消息(调用方已 matches 过)。附件先落盘,路径随正文一起进会话(1123)。 */
14058
14268
  route(inbound) {
14059
14269
  const binding = findBinding(inbound, this.cfg);
14060
14270
  if (!binding) return;
14061
14271
  const session = this.sessions.get(bindingKey(binding));
14062
14272
  if (!session) return;
14063
14273
  if (inbound.attachments?.length) {
14064
- void session.enqueue(`${inbound.content}
14065
- \uFF08\u6536\u5230 ${inbound.attachments.length} \u4E2A\u9644\u4EF6\u2014\u2014CC \u7EC8\u7AEF\u6682\u4E0D\u652F\u6301\u9644\u4EF6\uFF0C\u53EA\u5904\u7406\u4E86\u6587\u5B57\u90E8\u5206\uFF09`);
14274
+ void this.saveAttachments(inbound).then((note) => session.enqueue(inbound.content.trim() ? `${inbound.content}
14275
+
14276
+ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
14277
+
14278
+ \uFF08\u9644\u4EF6\u5904\u7406\u5931\u8D25\uFF1A${err?.message || String(err)}\uFF09`));
14066
14279
  return;
14067
14280
  }
14068
14281
  session.enqueue(inbound.content);
@@ -14072,10 +14285,10 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14072
14285
  return this.sessions.get(`${channel}:${chatId}`);
14073
14286
  }
14074
14287
  /** 按 bindingKey(channel:chatId)找 session——卡片停止钮回调用(1119) */
14075
- forChatKey(key2) {
14076
- const idx = key2.indexOf(":");
14288
+ forChatKey(key4) {
14289
+ const idx = key4.indexOf(":");
14077
14290
  if (idx <= 0) return void 0;
14078
- return this.sessions.get(key2);
14291
+ return this.sessions.get(key4);
14079
14292
  }
14080
14293
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
14081
14294
  get bindingWorkDirs() {
@@ -14084,8 +14297,8 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14084
14297
  get bindings() {
14085
14298
  return [...this.sessions.values()].map((s) => ({ key: s.key, workDir: s.workDir, sessionId: s.currentSessionId, busy: s.busy }));
14086
14299
  }
14087
- ask(key2, workDir, prompt, source, expectedSessionId, signal) {
14088
- const session = this.sessions.get(key2);
14300
+ ask(key4, workDir, prompt, source, expectedSessionId, signal) {
14301
+ const session = this.sessions.get(key4);
14089
14302
  if (!session) return Promise.reject(requestError("CC binding not found", 404));
14090
14303
  if (session.workDir !== workDir) return Promise.reject(requestError("CC binding workDir changed"));
14091
14304
  return session.ask(prompt, source, expectedSessionId, signal);
@@ -14111,7 +14324,7 @@ function registerCcHub(hub2, stateDir, port) {
14111
14324
  const dir = registryDir2();
14112
14325
  fs6.mkdirSync(dir, { recursive: true, mode: 448 });
14113
14326
  const file2 = path6.join(dir, `${process.pid}.json`);
14114
- const endpoint = { pid: process.pid, stateDir, port, bindings: hub2.bindings.map(({ key: key2, workDir }) => ({ key: key2, workDir })) };
14327
+ const endpoint = { pid: process.pid, stateDir, port, bindings: hub2.bindings.map(({ key: key4, workDir }) => ({ key: key4, workDir })) };
14115
14328
  const tmp = `${file2}.tmp`;
14116
14329
  fs6.writeFileSync(tmp, JSON.stringify(endpoint), { mode: 384 });
14117
14330
  fs6.renameSync(tmp, file2);
@@ -14125,6 +14338,7 @@ function registerCcHub(hub2, stateDir, port) {
14125
14338
  var init_handoff = __esm({
14126
14339
  "src/cc-driver/handoff.ts"() {
14127
14340
  "use strict";
14341
+ init_long_http();
14128
14342
  init_router();
14129
14343
  }
14130
14344
  });
@@ -14350,11 +14564,11 @@ __export(dispatches_exports, {
14350
14564
  finishCalendarDispatch: () => finishCalendarDispatch,
14351
14565
  recoverCalendarDispatches: () => recoverCalendarDispatches
14352
14566
  });
14353
- function beginCalendarDispatch(db2, key2, binding, context) {
14567
+ function beginCalendarDispatch(db2, key4, binding, context) {
14354
14568
  if (context && (!context.scopeId || context.calendarBinding?.eventId !== binding.eventId || context.calendarBinding.version !== binding.version || context.calendarBinding.occurrenceId !== binding.occurrenceId || !Array.isArray(context.basisRefs) || context.basisRefs.some((ref) => ref.scopeId !== context.scopeId))) throw new Error("CALENDAR_DISPATCH_CONTEXT_INVALID");
14355
14569
  return Boolean(db2.prepare(`INSERT OR IGNORE INTO calendar_dispatches
14356
14570
  (dispatch_key,event_id,binding_version,occurrence_id,state,started_at,scope_id,context_json) VALUES (?,?,?,?,'started',?,?,?)`).run(
14357
- key2,
14571
+ key4,
14358
14572
  binding.eventId,
14359
14573
  binding.version,
14360
14574
  binding.occurrenceId,
@@ -14363,8 +14577,8 @@ function beginCalendarDispatch(db2, key2, binding, context) {
14363
14577
  context ? JSON.stringify(context) : null
14364
14578
  ).changes);
14365
14579
  }
14366
- function finishCalendarDispatch(db2, key2, state) {
14367
- db2.prepare("UPDATE calendar_dispatches SET state=?,finished_at=?,version=version+1 WHERE dispatch_key=? AND state='started'").run(state, Date.now(), key2);
14580
+ function finishCalendarDispatch(db2, key4, state) {
14581
+ db2.prepare("UPDATE calendar_dispatches SET state=?,finished_at=?,version=version+1 WHERE dispatch_key=? AND state='started'").run(state, Date.now(), key4);
14368
14582
  }
14369
14583
  function recoverCalendarDispatches(db2) {
14370
14584
  return Number(db2.prepare("UPDATE calendar_dispatches SET state='delivery_unknown',finished_at=?,receipt='process_interrupted_before_receipt',version=version+1 WHERE state='started'").run(Date.now()).changes);
@@ -14840,7 +15054,7 @@ var init_intent_state = __esm({
14840
15054
  // src/memory/proactive/mutation-service.ts
14841
15055
  function canonical3(value) {
14842
15056
  if (Array.isArray(value)) return value.map(canonical3);
14843
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical3(item)]));
15057
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key4, item]) => [key4, canonical3(item)]));
14844
15058
  return value;
14845
15059
  }
14846
15060
  var graphBasis;
@@ -15037,18 +15251,18 @@ function createGraphMemoryValidator(memory) {
15037
15251
  }
15038
15252
  const scope = memory?.sources.scope(scopeKey);
15039
15253
  if (!memory || !scope) throw new Error("GRAPH_MEMORY_READ_GUARD_REQUIRED");
15040
- const unseen = [...new Map(refs.map((ref) => [JSON.stringify([scopeKey, ref]), ref])).entries()].filter(([key2]) => !checkedRefs.has(key2));
15254
+ const unseen = [...new Map(refs.map((ref) => [JSON.stringify([scopeKey, ref]), ref])).entries()].filter(([key4]) => !checkedRefs.has(key4));
15041
15255
  memory.dependencies.assertReferences(scope, unseen.map(([, ref]) => ref));
15042
- for (const [key2] of unseen) checkedRefs.add(key2);
15256
+ for (const [key4] of unseen) checkedRefs.add(key4);
15043
15257
  const sourceIds = [.../* @__PURE__ */ new Set([
15044
15258
  ...refs.filter((ref) => ref.parentKind === "source").map((ref) => ref.parentId),
15045
15259
  ...typeof node.data.socialSourceId === "string" ? [node.data.socialSourceId] : []
15046
15260
  ])];
15047
15261
  for (const id3 of sourceIds) {
15048
- const key2 = JSON.stringify([scopeKey, id3]);
15049
- if (checkedSources.has(key2)) continue;
15262
+ const key4 = JSON.stringify([scopeKey, id3]);
15263
+ if (checkedSources.has(key4)) continue;
15050
15264
  if (!memory.socialSources.readable(scope, id3) || !memory.socialSources.groundsCurrent(scope, id3)) throw new Error("STALE_GRAPH_SOCIAL_SOURCE");
15051
- checkedSources.add(key2);
15265
+ checkedSources.add(key4);
15052
15266
  }
15053
15267
  const relation = node.data.relationshipRef;
15054
15268
  const relationshipKey = relation && JSON.stringify([scopeKey, relation]);
@@ -15081,7 +15295,7 @@ function digest5(value) {
15081
15295
  }
15082
15296
  function generationBasis(intent) {
15083
15297
  const data = { ...intent.data };
15084
- for (const key2 of ["status", "stateVersion", "reasonCode", "deferredReason", "waitingFor", "nextEligibleAt", "completedOccurrenceId"]) delete data[key2];
15298
+ for (const key4 of ["status", "stateVersion", "reasonCode", "deferredReason", "waitingFor", "nextEligibleAt", "completedOccurrenceId"]) delete data[key4];
15085
15299
  return graphBasis({ ...intent, data });
15086
15300
  }
15087
15301
  var IntentRunStore;
@@ -15285,9 +15499,9 @@ CREATE TABLE memory_projection_heads (
15285
15499
  }
15286
15500
  inspect(event2) {
15287
15501
  if (event2.schemaVersion !== 1 || !event2.eventId || !event2.scopeId || !event2.aggregateId || !Number.isSafeInteger(event2.eventSeq) || event2.eventSeq < 1 || !Number.isSafeInteger(event2.aggregateVersion) || event2.aggregateVersion < 1) throw new Error("INVALID_PROJECTION_EVENT");
15288
- const received = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15289
- if (received) {
15290
- if (received.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15502
+ const received2 = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15503
+ if (received2) {
15504
+ if (received2.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15291
15505
  return "duplicate";
15292
15506
  }
15293
15507
  if (event2.eventSeq !== this.position(event2.scopeId) + 1) throw new Error("PROJECTION_SEQUENCE_GAP");
@@ -15317,9 +15531,9 @@ CREATE TABLE memory_projection_heads (
15317
15531
  * 详见 docs/research/2026-10-20-mem7-poison-delivery-followup.md。 */
15318
15532
  skip(event2) {
15319
15533
  if (event2.schemaVersion !== 1 || !event2.eventId || !event2.scopeId || !Number.isSafeInteger(event2.eventSeq) || event2.eventSeq < 1) throw new Error("INVALID_PROJECTION_EVENT");
15320
- const received = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15321
- if (received) {
15322
- if (received.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15534
+ const received2 = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15535
+ if (received2) {
15536
+ if (received2.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15323
15537
  return;
15324
15538
  }
15325
15539
  if (event2.eventSeq !== this.position(event2.scopeId) + 1) throw new Error("PROJECTION_SEQUENCE_GAP");
@@ -15515,20 +15729,20 @@ CREATE INDEX idx_action_dispatch_state ON action_dispatches(state,started_at);
15515
15729
  constructor(db2) {
15516
15730
  this.db = db2;
15517
15731
  }
15518
- begin(key2, scopeId2, versions) {
15732
+ begin(key4, scopeId2, versions) {
15519
15733
  const result = this.db.prepare(`INSERT OR IGNORE INTO action_dispatches
15520
- (dispatch_key,scope_id,action_versions,state,started_at) VALUES (?,?,?,'started',?)`).run(key2, scopeId2, JSON.stringify(versions), Date.now());
15734
+ (dispatch_key,scope_id,action_versions,state,started_at) VALUES (?,?,?,'started',?)`).run(key4, scopeId2, JSON.stringify(versions), Date.now());
15521
15735
  if (!result.changes) return false;
15522
15736
  for (const id3 of Object.keys(versions)) this.db.prepare(`UPDATE actions SET dispatch_key=?,dispatch_state='started'
15523
- WHERE id=? AND scope_id=?`).run(key2, id3, scopeId2);
15737
+ WHERE id=? AND scope_id=?`).run(key4, id3, scopeId2);
15524
15738
  return true;
15525
15739
  }
15526
- finish(key2, state, receipt) {
15527
- const row = this.db.prepare("SELECT * FROM action_dispatches WHERE dispatch_key=?").get(key2);
15740
+ finish(key4, state, receipt) {
15741
+ const row = this.db.prepare("SELECT * FROM action_dispatches WHERE dispatch_key=?").get(key4);
15528
15742
  if (!row || row.state !== "started") return;
15529
- this.db.prepare("UPDATE action_dispatches SET state=?,finished_at=?,receipt=? WHERE dispatch_key=? AND state='started'").run(state, Date.now(), receipt ?? null, key2);
15743
+ this.db.prepare("UPDATE action_dispatches SET state=?,finished_at=?,receipt=? WHERE dispatch_key=? AND state='started'").run(state, Date.now(), receipt ?? null, key4);
15530
15744
  for (const id3 of Object.keys(JSON.parse(row.action_versions))) this.db.prepare(`UPDATE actions SET dispatch_state=?
15531
- WHERE id=? AND dispatch_key=?`).run(state, id3, key2);
15745
+ WHERE id=? AND dispatch_key=?`).run(state, id3, key4);
15532
15746
  }
15533
15747
  /** Called once by the owning plugin at startup, never by another connection's constructor. */
15534
15748
  recoverInterrupted() {
@@ -15555,15 +15769,15 @@ var init_host_deliveries = __esm({
15555
15769
  this.db = db2;
15556
15770
  }
15557
15771
  enqueue(actionId, version, blocks, context) {
15558
- const key2 = JSON.stringify(["proactive", actionId, version]);
15559
- this.db.prepare("INSERT OR IGNORE INTO proactive_host_deliveries(delivery_key,action_id,action_version,blocks_json,context_json,created_at) VALUES (?,?,?,?,?,?)").run(key2, actionId, version, JSON.stringify(blocks), JSON.stringify(context), (/* @__PURE__ */ new Date()).toISOString());
15560
- return key2;
15772
+ const key4 = JSON.stringify(["proactive", actionId, version]);
15773
+ this.db.prepare("INSERT OR IGNORE INTO proactive_host_deliveries(delivery_key,action_id,action_version,blocks_json,context_json,created_at) VALUES (?,?,?,?,?,?)").run(key4, actionId, version, JSON.stringify(blocks), JSON.stringify(context), (/* @__PURE__ */ new Date()).toISOString());
15774
+ return key4;
15561
15775
  }
15562
15776
  pending() {
15563
15777
  return this.db.prepare("SELECT * FROM proactive_host_deliveries WHERE state='pending' ORDER BY created_at").all().map((row) => ({ key: row.delivery_key, blocks: JSON.parse(row.blocks_json), context: JSON.parse(row.context_json) }));
15564
15778
  }
15565
- finish(key2, state, reason) {
15566
- this.db.prepare("UPDATE proactive_host_deliveries SET state=?,reason=?,finished_at=?,version=version+1 WHERE delivery_key=? AND state='pending'").run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), key2);
15779
+ finish(key4, state, reason) {
15780
+ this.db.prepare("UPDATE proactive_host_deliveries SET state=?,reason=?,finished_at=?,version=version+1 WHERE delivery_key=? AND state='pending'").run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), key4);
15567
15781
  }
15568
15782
  list(scope, options = {}) {
15569
15783
  const where = scope ? ["a.scope_id=? AND json_extract(h.context_json,'$.scopeId')=?"] : [];
@@ -15607,7 +15821,7 @@ __export(persistence_exports, {
15607
15821
  normalizeToUtcIso: () => normalizeToUtcIso
15608
15822
  });
15609
15823
  import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
15610
- import { mkdirSync as mkdirSync10 } from "node:fs";
15824
+ import { mkdirSync as mkdirSync11 } from "node:fs";
15611
15825
  import { basename as basename3, dirname as dirname7, resolve as resolve6 } from "node:path";
15612
15826
  function rowToAction(r) {
15613
15827
  return {
@@ -15745,7 +15959,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
15745
15959
  checkRuntimeReplicationFile(dbPath, registration, Boolean(options.replication));
15746
15960
  this.releaseRuntimeWriter = registration || options.replication ? registerRuntimeWriter(stateDir, "proactive") : void 0;
15747
15961
  try {
15748
- mkdirSync10(dirname7(dbPath), { recursive: true });
15962
+ mkdirSync11(dirname7(dbPath), { recursive: true });
15749
15963
  this.db = new DatabaseSync12(dbPath);
15750
15964
  } catch (error) {
15751
15965
  this.releaseRuntimeWriter?.();
@@ -15833,7 +16047,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
15833
16047
  this.replication = enrollRuntimeReplication(this.db, stateDir, "proactive", binding);
15834
16048
  this.capture = installSQLiteWriteCapture(this.db, this.replication);
15835
16049
  }
15836
- this.transaction(() => this.personNodes.rebuild(this.loadNodes()));
16050
+ if (!this.db.prepare("SELECT 1 FROM graph_person_nodes LIMIT 1").get())
16051
+ this.transaction(() => this.personNodes.rebuild(this.loadNodes()));
15837
16052
  } catch (error) {
15838
16053
  try {
15839
16054
  this.capture?.close();
@@ -15932,6 +16147,12 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
15932
16147
  graphRevision() {
15933
16148
  return Number(this.db.prepare("SELECT revision FROM graph_state WHERE id=1").get().revision);
15934
16149
  }
16150
+ graphCounts() {
16151
+ return {
16152
+ nodes: Number(this.db.prepare("SELECT COUNT(*) n FROM nodes").get().n),
16153
+ edges: Number(this.db.prepare("SELECT COUNT(*) n FROM edges").get().n)
16154
+ };
16155
+ }
15935
16156
  // B7.1(astra review):SQL 级联失效(invalidateGraphChildren/invalidateMemoryEvent)改动的
15936
16157
  // 节点不在调用方 delta 里——事务内收集,提交后由 GraphStore 逐 id 单行刷回缓存。
15937
16158
  cascadeTouched = [];
@@ -16024,6 +16245,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16024
16245
  const edges = new Map(keys.flatMap((id3) => this.loadIncidentEdges(id3)).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge]));
16025
16246
  return { nodes, edges: [...edges.values()], revision: this.graphRevision() };
16026
16247
  };
16248
+ return this.readGraphTransaction(read2);
16249
+ }
16250
+ readGraphTransaction(read2) {
16027
16251
  if (this.inTransaction) return read2();
16028
16252
  this.db.exec("BEGIN");
16029
16253
  try {
@@ -16035,9 +16259,18 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16035
16259
  throw error;
16036
16260
  }
16037
16261
  }
16038
- loadNodes() {
16039
- const rows = this.db.prepare("SELECT * FROM nodes").all();
16040
- return rows.map((r) => ({
16262
+ loadNodes(type, scope) {
16263
+ const clauses = [], values = [];
16264
+ if (type) {
16265
+ clauses.push("type=?");
16266
+ values.push(type);
16267
+ }
16268
+ if (scope !== void 0) {
16269
+ clauses.push("COALESCE(NULLIF(json_extract(data,'$.scopeId'),''),'legacy')=?");
16270
+ values.push(scope);
16271
+ }
16272
+ const rows = this.db.prepare("SELECT * FROM nodes" + (clauses.length ? " WHERE " + clauses.join(" AND ") : "")).iterate(...values);
16273
+ return Array.from(rows, (r) => ({
16041
16274
  id: r.id,
16042
16275
  type: r.type,
16043
16276
  data: JSON.parse(r.data),
@@ -16076,8 +16309,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16076
16309
  }));
16077
16310
  }
16078
16311
  loadEdges() {
16079
- const rows = this.db.prepare("SELECT * FROM edges").all();
16080
- return rows.map((r) => ({
16312
+ const rows = this.db.prepare("SELECT * FROM edges").iterate();
16313
+ return Array.from(rows, (r) => ({
16081
16314
  source: r.source,
16082
16315
  target: r.target,
16083
16316
  edgeType: r.edge_type,
@@ -16085,6 +16318,20 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16085
16318
  createdAt: r.created_at
16086
16319
  }));
16087
16320
  }
16321
+ /** One indexed read for a model snapshot, instead of one node/adjacency query per node. */
16322
+ loadEdgesAmong(ids) {
16323
+ if (!ids.size) return [];
16324
+ const keys = JSON.stringify([...ids]);
16325
+ const rows = this.db.prepare(`SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?))
16326
+ AND target IN (SELECT value FROM json_each(?))`).iterate(keys, keys);
16327
+ return Array.from(rows, (row) => ({
16328
+ source: row.source,
16329
+ target: row.target,
16330
+ edgeType: row.edge_type,
16331
+ weight: row.weight,
16332
+ createdAt: row.created_at
16333
+ }));
16334
+ }
16088
16335
  // === 图:写(GraphStore 镜像调用) ===
16089
16336
  insertNode(node) {
16090
16337
  this.transaction(() => {
@@ -16118,7 +16365,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16118
16365
  this.transaction(() => {
16119
16366
  const previous = knownPrevious ?? this.loadNodeById(node.id);
16120
16367
  if (!previous) throw new Error(`nodes row '${node.id}' missing on update (memory/DB divergence)`);
16121
- const changed = this.applyingMemoryInvalidation && knownPrevious ? previous.reasoning !== node.reasoning || previous.groundedIn !== node.groundedIn || [.../* @__PURE__ */ new Set([...Object.keys(previous.data), ...Object.keys(node.data)])].some((key2) => previous.data[key2] !== node.data[key2]) : graphBasis(previous) !== graphBasis(node);
16368
+ const changed = this.applyingMemoryInvalidation && knownPrevious ? previous.reasoning !== node.reasoning || previous.groundedIn !== node.groundedIn || [.../* @__PURE__ */ new Set([...Object.keys(previous.data), ...Object.keys(node.data)])].some((key4) => previous.data[key4] !== node.data[key4]) : graphBasis(previous) !== graphBasis(node);
16122
16369
  if (changed && previous.type === "intent") {
16123
16370
  patchIntentState(previous.data, node.data);
16124
16371
  if (stateVersion(node.data) !== stateVersion(previous.data) + 1) throw new Error("STALE_INTENT_VERSION");
@@ -16129,9 +16376,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16129
16376
  this.validateOutcomeEvidence(node.data, node.data.completionEvidence);
16130
16377
  }
16131
16378
  }
16132
- const keys = this.applyingMemoryInvalidation && knownPrevious && node.data.evidenceState !== "deleted" ? [.../* @__PURE__ */ new Set([...Object.keys(previous.data), ...Object.keys(node.data)])].filter((key2) => previous.data[key2] !== node.data[key2]) : void 0;
16133
- if (keys && keys.every((key2) => node.data[key2] !== void 0 && (node.data[key2] === null || typeof node.data[key2] !== "object"))) {
16134
- const patch = keys.flatMap((key2) => [`$.${JSON.stringify(key2)}`, JSON.stringify(node.data[key2])]);
16379
+ const keys = this.applyingMemoryInvalidation && knownPrevious && node.data.evidenceState !== "deleted" ? [.../* @__PURE__ */ new Set([...Object.keys(previous.data), ...Object.keys(node.data)])].filter((key4) => previous.data[key4] !== node.data[key4]) : void 0;
16380
+ if (keys && keys.every((key4) => node.data[key4] !== void 0 && (node.data[key4] === null || typeof node.data[key4] !== "object"))) {
16381
+ const patch = keys.flatMap((key4) => [`$.${JSON.stringify(key4)}`, JSON.stringify(node.data[key4])]);
16135
16382
  const data = keys.length ? `json_set(data,${keys.map(() => "?,json(?)").join(",")})` : "data";
16136
16383
  this.db.prepare(`UPDATE nodes SET data=${data}, reasoning=?, grounded_in=?, last_accessed=?, access_count=? WHERE id=?`).run(...patch, node.reasoning ?? null, JSON.stringify(node.groundedIn), node.lastAccessed, node.accessCount, node.id);
16137
16384
  } else this.db.prepare("UPDATE nodes SET data=?, reasoning=?, grounded_in=?, last_accessed=?, access_count=? WHERE id=?").run(JSON.stringify(node.data), node.reasoning ?? null, JSON.stringify(node.groundedIn), node.lastAccessed, node.accessCount, node.id);
@@ -16657,10 +16904,10 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16657
16904
  /** Close a held host turn after evidence-based review; never make the old outbox pending again. */
16658
16905
  reconcileHostDelivery(input, scope) {
16659
16906
  if (typeof input.requestKey !== "string" || !input.requestKey.trim() || !scope || !input.deliveryKey || !input.actionId || !input.evidence || typeof input.evidence.quote !== "string" || !input.evidence.quote.trim() || !input.evidence.eventId || !["delivered", "cancelled"].includes(input.outcome) || !Number.isSafeInteger(input.expectedActionVersion) || input.expectedActionVersion < 1 || !Number.isSafeInteger(input.expectedDeliveryVersion) || input.expectedDeliveryVersion < 1) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16660
- const versions = (provided, key2, version) => {
16907
+ const versions = (provided, key4, version) => {
16661
16908
  if (provided !== void 0 && (!provided || typeof provided !== "object" || Array.isArray(provided))) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16662
- if (provided && Object.hasOwn(provided, key2) && provided[key2] !== version) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16663
- const entries = Object.entries({ ...provided, [key2]: version }).sort(([a], [b]) => a.localeCompare(b));
16909
+ if (provided && Object.hasOwn(provided, key4) && provided[key4] !== version) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16910
+ const entries = Object.entries({ ...provided, [key4]: version }).sort(([a], [b]) => a.localeCompare(b));
16664
16911
  if (entries.some(([id3, value]) => !id3 || !Number.isSafeInteger(value) || value < 1)) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16665
16912
  return Object.fromEntries(entries);
16666
16913
  };
@@ -17298,17 +17545,17 @@ __export(paths_exports, {
17298
17545
  isAutoMemPath: () => isAutoMemPath,
17299
17546
  setMemoryDirOverride: () => setMemoryDirOverride
17300
17547
  });
17301
- import { join as join26, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve10 } from "node:path";
17548
+ import { join as join27, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve10 } from "node:path";
17302
17549
  function setMemoryDirOverride(dir) {
17303
17550
  _overrideMemoryDir = dir;
17304
17551
  }
17305
17552
  function getAutoMemPath(workspace) {
17306
- const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve10(workspace, _overrideMemoryDir) : join26(workspace, AUTO_MEM_DIRNAME);
17553
+ const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve10(workspace, _overrideMemoryDir) : join27(workspace, AUTO_MEM_DIRNAME);
17307
17554
  const normalized = normalize5(dir);
17308
17555
  return (normalized + sep4).normalize("NFC");
17309
17556
  }
17310
17557
  function getAutoMemEntrypoint(workspace) {
17311
- return join26(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17558
+ return join27(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17312
17559
  }
17313
17560
  function isAutoMemPath(absolutePath, workspace) {
17314
17561
  const normalizedPath = normalize5(absolutePath);
@@ -17499,7 +17746,7 @@ __export(memdir_exports, {
17499
17746
  truncateEntrypointContent: () => truncateEntrypointContent
17500
17747
  });
17501
17748
  import { readFileSync as readFileSync15 } from "node:fs";
17502
- import { join as join27 } from "node:path";
17749
+ import { join as join28 } from "node:path";
17503
17750
  function truncateEntrypointContent(raw) {
17504
17751
  const trimmed = raw.trim();
17505
17752
  const contentLines = trimmed.split("\n");
@@ -17592,7 +17839,7 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
17592
17839
  }
17593
17840
  function buildMemoryPrompt(params) {
17594
17841
  const { displayName, memoryDir, extraGuidelines } = params;
17595
- const entrypoint = join27(memoryDir, ENTRYPOINT_NAME);
17842
+ const entrypoint = join28(memoryDir, ENTRYPOINT_NAME);
17596
17843
  let entrypointContent = "";
17597
17844
  try {
17598
17845
  entrypointContent = readFileSync15(entrypoint, { encoding: "utf-8" });
@@ -18250,22 +18497,22 @@ var TravelAuthority = class {
18250
18497
  if (operation !== "CONTROL" && row.frozen) throw new Error("TRAVEL_HANDOFF_FROZEN");
18251
18498
  if (operation !== "CONTROL" && permit.deletionWatermark !== Number(row.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
18252
18499
  }
18253
- heartbeat(principal, request3) {
18500
+ heartbeat(principal, request4) {
18254
18501
  return this.transaction(() => {
18255
18502
  const node = this.principal(principal), text2 = identityText(principal), seat = this.seat(principal);
18256
- natural(request3.sequence);
18257
- if (request3.bootId !== node.boot) throw new Error("TRAVEL_BOOT_MISMATCH");
18258
- if (request3.sequence <= Number(node.sequence)) throw new Error("TRAVEL_HEARTBEAT_REPLAY");
18503
+ natural(request4.sequence);
18504
+ if (request4.bootId !== node.boot) throw new Error("TRAVEL_BOOT_MISMATCH");
18505
+ if (request4.sequence <= Number(node.sequence)) throw new Error("TRAVEL_HEARTBEAT_REPLAY");
18259
18506
  let permit;
18260
- if (request3.permit) {
18261
- this.assertPermit(request3.permit, "CONTROL");
18262
- if (request3.permit.nodeId !== principal.nodeId || !same(identityText(request3.permit), text2)) throw new Error("TRAVEL_AUTH_DENIED");
18263
- const floor = request3.deletionWatermark ?? request3.permit.deletionWatermark;
18507
+ if (request4.permit) {
18508
+ this.assertPermit(request4.permit, "CONTROL");
18509
+ if (request4.permit.nodeId !== principal.nodeId || !same(identityText(request4.permit), text2)) throw new Error("TRAVEL_AUTH_DENIED");
18510
+ const floor = request4.deletionWatermark ?? request4.permit.deletionWatermark;
18264
18511
  if (floor !== Number(seat.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
18265
18512
  this.deadlines.set(text2, this.monotonicNow() + this.leaseMs);
18266
18513
  permit = this.issue(principal, seat);
18267
18514
  }
18268
- this.db.prepare("UPDATE nodes SET sequence=? WHERE identity=? AND node_id=?").run(request3.sequence, text2, principal.nodeId);
18515
+ this.db.prepare("UPDATE nodes SET sequence=? WHERE identity=? AND node_id=?").run(request4.sequence, text2, principal.nodeId);
18269
18516
  this.healthy.set(text2 + principal.nodeId, this.monotonicNow() + this.leaseMs);
18270
18517
  return {
18271
18518
  authorityBootId: this.authorityBootId,
@@ -18700,15 +18947,15 @@ function validManagement(input) {
18700
18947
  if (input.action === "retire" && !(typeof input.jobId === "string" && identifier.test(input.jobId))) return false;
18701
18948
  if (!Object.hasOwn(managementFields, String(input.action))) return false;
18702
18949
  const fields = managementFields[String(input.action)];
18703
- if (!fields || Object.keys(input).some((key2) => !["version", "action", ...fields].includes(key2)) || fields.some((key2) => !Object.hasOwn(input, key2))) return false;
18704
- for (const key2 of ["ancestor", "descendant", "digest", "parent", "common", "local"]) if (Object.hasOwn(input, key2) && (typeof input[key2] !== "string" || !/^[a-f0-9]{64}$/.test(input[key2]))) return false;
18705
- for (const key2 of ["transferId", "targetNodeId"]) if (Object.hasOwn(input, key2) && (typeof input[key2] !== "string" || !identifier.test(input[key2]))) return false;
18950
+ if (!fields || Object.keys(input).some((key4) => !["version", "action", ...fields].includes(key4)) || fields.some((key4) => !Object.hasOwn(input, key4))) return false;
18951
+ for (const key4 of ["ancestor", "descendant", "digest", "parent", "common", "local"]) if (Object.hasOwn(input, key4) && (typeof input[key4] !== "string" || !/^[a-f0-9]{64}$/.test(input[key4]))) return false;
18952
+ for (const key4 of ["transferId", "targetNodeId"]) if (Object.hasOwn(input, key4) && (typeof input[key4] !== "string" || !identifier.test(input[key4]))) return false;
18706
18953
  if (input.action === "deletionsSince" && (!Number.isSafeInteger(input.after) || Number(input.after) < 0 || !Number.isSafeInteger(input.maximum) || Number(input.maximum) < 1 || Number(input.maximum) > 32)) return false;
18707
18954
  if (input.action === "recordRecoveryBranch" && (!Array.isArray(input.chain) || input.chain.length < 1 || input.chain.length > 4096 || input.chain.some((value) => typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) || !Array.isArray(input.proof) || input.proof.length !== input.chain.length)) return false;
18708
18955
  if (Object.hasOwn(input, "permit") && !record(input.permit)) return false;
18709
18956
  if (Object.hasOwn(input, "operation") && !["WRITE", "SEND", "TOOL", "INPUT", "PUBLISH", "CONTROL"].includes(String(input.operation))) return false;
18710
- if (Object.hasOwn(input, "ready") && (!record(input.ready) || Object.keys(input.ready).some((key2) => !["checkpointDigest", "deletionWatermark", "buildManifestId", "volumeVerified", "capabilitiesVerified", "effectsLoaded", "unresolvedCritical"].includes(key2)))) return false;
18711
- if (Object.hasOwn(input, "boundary") && (!record(input.boundary) || Object.keys(input.boundary).some((key2) => !["checkpointDigest", "safeBoundary", "effectsSettled"].includes(key2)))) return false;
18957
+ if (Object.hasOwn(input, "ready") && (!record(input.ready) || Object.keys(input.ready).some((key4) => !["checkpointDigest", "deletionWatermark", "buildManifestId", "volumeVerified", "capabilitiesVerified", "effectsLoaded", "unresolvedCritical"].includes(key4)))) return false;
18958
+ if (Object.hasOwn(input, "boundary") && (!record(input.boundary) || Object.keys(input.boundary).some((key4) => !["checkpointDigest", "safeBoundary", "effectsSettled"].includes(key4)))) return false;
18712
18959
  return true;
18713
18960
  }
18714
18961
  function createTravelAuthorityServer(options) {
@@ -18818,7 +19065,7 @@ function createTravelAuthorityServer(options) {
18818
19065
  return;
18819
19066
  }
18820
19067
  const input = envelope?.travel, keys = input?.action === "register" ? ["version", "action", "bootId"] : input?.action === "heartbeat" ? ["version", "action", "bootId", "sequence", "permit", "deletionWatermark"] : ["version", "action"];
18821
- const validAction = managing ? record(input) && validManagement(input) : ["register", "heartbeat", "status"].includes(input?.action) && Object.keys(input).every((key2) => keys.includes(key2)) && (input.action === "status" || typeof input.bootId === "string" && identifier.test(input.bootId));
19068
+ const validAction = managing ? record(input) && validManagement(input) : ["register", "heartbeat", "status"].includes(input?.action) && Object.keys(input).every((key4) => keys.includes(key4)) && (input.action === "status" || typeof input.bootId === "string" && identifier.test(input.bootId));
18822
19069
  if (!envelope || typeof envelope !== "object" || Array.isArray(envelope) || Object.keys(envelope).length !== 1 || !input || typeof input !== "object" || Array.isArray(input) || input.version !== 1 || !validAction) {
18823
19070
  reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
18824
19071
  return;
@@ -18832,7 +19079,7 @@ function createTravelAuthorityServer(options) {
18832
19079
  }
18833
19080
  let result;
18834
19081
  if (managing) {
18835
- if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => input.permit[key2] !== principal[key2])) throw new Error("TRAVEL_AUTH_DENIED");
19082
+ if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key4) => input.permit[key4] !== principal[key4])) throw new Error("TRAVEL_AUTH_DENIED");
18836
19083
  switch (input.action) {
18837
19084
  case "bindInitialCheckpoint":
18838
19085
  if (!bootstrapGrants.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
@@ -18993,12 +19240,12 @@ async function fetchTravelKey(options) {
18993
19240
  const wanted = options.identity;
18994
19241
  if (value?.protocolVersion !== 1 || !value.identity || ["tenantId", "companionId", "seatId", "keyId", "generation"].some((k) => value.identity[k] !== wanted[k]) || !Number.isSafeInteger(value.deletionWatermark) || value.deletionWatermark < options.minimumDeletionWatermark || typeof value.key !== "string" || !/^[A-Za-z0-9+/]{43}=$/.test(value.key))
18995
19242
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
18996
- const key2 = Buffer.from(value.key, "base64");
18997
- if (key2.length !== 32 || key2.toString("base64") !== value.key) {
18998
- key2.fill(0);
19243
+ const key4 = Buffer.from(value.key, "base64");
19244
+ if (key4.length !== 32 || key4.toString("base64") !== value.key) {
19245
+ key4.fill(0);
18999
19246
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
19000
19247
  }
19001
- return { key: key2, deletionWatermark: value.deletionWatermark };
19248
+ return { key: key4, deletionWatermark: value.deletionWatermark };
19002
19249
  }
19003
19250
 
19004
19251
  // src/continuity/gateway-store.ts
@@ -19016,6 +19263,13 @@ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
19016
19263
  init_store();
19017
19264
  init_mem7_replication();
19018
19265
 
19266
+ // src/travel/chunk-store.ts
19267
+ import { gunzipSync as gunzipSync2, gzip as gzip2 } from "node:zlib";
19268
+ import { promisify as promisify2 } from "node:util";
19269
+ var CHUNK_BYTES = 4 * 1024 * 1024;
19270
+ var DATABASE_CHUNK_BYTES = 64 * 1024;
19271
+ var compress2 = promisify2(gzip2);
19272
+
19019
19273
  // src/mem7/intake.ts
19020
19274
  init_system_filter();
19021
19275
  init_host_turns();
@@ -19671,7 +19925,7 @@ function createTravelGatewayServer(options) {
19671
19925
  reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
19672
19926
  return;
19673
19927
  }
19674
- if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key2) => !["permit", "options", "eventId", "input", "inputs", "effectId", "dispatchId", "resultBase64", "index", "finalOutput", "channel"].includes(key2))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19928
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key4) => !["permit", "options", "eventId", "input", "inputs", "effectId", "dispatchId", "resultBase64", "index", "finalOutput", "channel"].includes(key4))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19675
19929
  if (action === "preparation") {
19676
19930
  if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19677
19931
  reply(200, store.preparationEvidence(principal));
@@ -19723,7 +19977,7 @@ function createTravelGatewayServer(options) {
19723
19977
  const values = action === "produce" ? [input.input] : input.inputs;
19724
19978
  if (!Array.isArray(values) || !values.length || values.length > 100) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19725
19979
  const decoded = values.map((value) => {
19726
- if (!value || typeof value !== "object" || Object.keys(value).some((key2) => !["eventId", "kind", "ordinal", "version", "bodyBase64"].includes(key2))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19980
+ if (!value || typeof value !== "object" || Object.keys(value).some((key4) => !["eventId", "kind", "ordinal", "version", "bodyBase64"].includes(key4))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19727
19981
  return { ...value, body: decodeBody(value.bodyBase64) };
19728
19982
  });
19729
19983
  if (input.finalOutput !== void 0 && typeof input.finalOutput !== "boolean") throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
@@ -19999,14 +20253,14 @@ var AgentRegistryImpl = class {
19999
20253
  var agentRegistry = new AgentRegistryImpl();
20000
20254
 
20001
20255
  // src/channels/discord.ts
20002
- import { Client, GatewayIntentBits, Partials, ApplicationCommandOptionType } from "discord.js";
20256
+ import { Client, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20003
20257
  import { ProxyAgent as UndiciProxyAgent } from "undici";
20004
20258
  import { HttpsProxyAgent } from "https-proxy-agent";
20005
20259
 
20006
20260
  // src/memory/external-effect.ts
20007
20261
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20008
20262
  import { createHash as createHash25 } from "node:crypto";
20009
- import { join as join16 } from "node:path";
20263
+ import { join as join17 } from "node:path";
20010
20264
 
20011
20265
  // src/memory/execution-guard.ts
20012
20266
  init_db();
@@ -20016,7 +20270,7 @@ init_migrations();
20016
20270
  init_context_time();
20017
20271
  init_relationship_notice_check();
20018
20272
  init_dependencies();
20019
- import { join as join15 } from "node:path";
20273
+ import { join as join16 } from "node:path";
20020
20274
  var MemoryExecutionBlockedError = class extends Error {
20021
20275
  constructor(reason) {
20022
20276
  super(`MEMORY_EXECUTION_BLOCKED: ${reason}`);
@@ -20029,7 +20283,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20029
20283
  let calendar;
20030
20284
  try {
20031
20285
  if (!stateDir || !context.scopeId || !Array.isArray(context.basisRefs)) return { ok: false, reason: "EXECUTION_CONTEXT_INVALID" };
20032
- memory = new DatabaseSync11(join15(stateDir, "mem7", "index", "mem7.db"), { readOnly: true });
20286
+ memory = new DatabaseSync11(join16(stateDir, "mem7", "index", "mem7.db"), { readOnly: true });
20033
20287
  memory.exec("PRAGMA query_only=ON; BEGIN");
20034
20288
  const schema = readSchemaVersion(memory);
20035
20289
  if (schema?.component !== "mem7" || schema.version !== MEM7_SCHEMA_VERSION) return { ok: false, reason: "MEMORY_SCHEMA_UNSUPPORTED" };
@@ -20044,7 +20298,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20044
20298
  if (!result.ok) return result;
20045
20299
  }
20046
20300
  if (context.calendarBinding) {
20047
- calendar = new DatabaseSync11(join15(workspace, ".calendar", "calendar.db"), { readOnly: true });
20301
+ calendar = new DatabaseSync11(join16(workspace, ".calendar", "calendar.db"), { readOnly: true });
20048
20302
  calendar.exec("PRAGMA query_only=ON; BEGIN");
20049
20303
  const binding = calendar.prepare(`SELECT b.*,e.status event_status,e.memory_version current_event_version FROM calendar_memory_bindings b
20050
20304
  JOIN events e ON e.id=b.event_id WHERE b.event_id=?`).get(context.calendarBinding.eventId);
@@ -20062,7 +20316,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20062
20316
  if (!bound.ok) return bound;
20063
20317
  }
20064
20318
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
20065
- proactive = new DatabaseSync11(join15(workspace, ".proactive", "proactive.db"), { readOnly: true });
20319
+ proactive = new DatabaseSync11(join16(workspace, ".proactive", "proactive.db"), { readOnly: true });
20066
20320
  proactive.exec("PRAGMA query_only=ON; BEGIN");
20067
20321
  for (const [id3, version] of Object.entries(context.actionVersions)) {
20068
20322
  const action = proactive.prepare("SELECT * FROM actions WHERE id=?").get(id3);
@@ -20234,16 +20488,16 @@ async function guardedExternalEffect(run) {
20234
20488
  Promise.resolve().then(() => (init_dispatches(), dispatches_exports))
20235
20489
  ]);
20236
20490
  const db2 = openDb2(workspace);
20237
- const key3 = "calendar_" + createHash25("sha256").update(JSON.stringify([context.scopeId, context.calendarBinding, effectId])).digest("hex");
20491
+ const key5 = "calendar_" + createHash25("sha256").update(JSON.stringify([context.scopeId, context.calendarBinding, effectId])).digest("hex");
20238
20492
  try {
20239
20493
  assertMemoryExecution(stateDir, workspace, context);
20240
- if (!beginCalendarDispatch2(db2, key3, context.calendarBinding, context)) throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20494
+ if (!beginCalendarDispatch2(db2, key5, context.calendarBinding, context)) throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20241
20495
  try {
20242
- const result = await effects.run({ ...host, activeDispatchKey: key3 }, run);
20243
- finishCalendarDispatch2(db2, key3, "delivered");
20496
+ const result = await effects.run({ ...host, activeDispatchKey: key5 }, run);
20497
+ finishCalendarDispatch2(db2, key5, "delivered");
20244
20498
  return result;
20245
20499
  } catch (error) {
20246
- finishCalendarDispatch2(db2, key3, "delivery_unknown");
20500
+ finishCalendarDispatch2(db2, key5, "delivery_unknown");
20247
20501
  throw error;
20248
20502
  }
20249
20503
  } finally {
@@ -20254,23 +20508,23 @@ async function guardedExternalEffect(run) {
20254
20508
  assertMemoryExecution(stateDir, workspace, context);
20255
20509
  return run();
20256
20510
  }
20257
- const persist = new Persistence2(join16(workspace, ".proactive", "proactive.db"));
20258
- const key2 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20511
+ const persist = new Persistence2(join17(workspace, ".proactive", "proactive.db"));
20512
+ const key4 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20259
20513
  context.scopeId,
20260
20514
  Object.entries(versions).sort(([a], [b]) => a.localeCompare(b)),
20261
20515
  effectId
20262
20516
  ])).digest("hex");
20263
20517
  try {
20264
20518
  assertMemoryExecution(stateDir, workspace, context);
20265
- if (!persist.transaction(() => persist.dispatches.begin(key2, context.scopeId, versions))) {
20519
+ if (!persist.transaction(() => persist.dispatches.begin(key4, context.scopeId, versions))) {
20266
20520
  throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20267
20521
  }
20268
20522
  try {
20269
- const result = await effects.run({ ...host, activeDispatchKey: key2 }, run);
20270
- persist.transaction(() => persist.dispatches.finish(key2, "delivered", "adapter_acknowledged"));
20523
+ const result = await effects.run({ ...host, activeDispatchKey: key4 }, run);
20524
+ persist.transaction(() => persist.dispatches.finish(key4, "delivered", "adapter_acknowledged"));
20271
20525
  return result;
20272
20526
  } catch (error) {
20273
- persist.transaction(() => persist.dispatches.finish(key2, "delivery_unknown"));
20527
+ persist.transaction(() => persist.dispatches.finish(key4, "delivery_unknown"));
20274
20528
  throw error;
20275
20529
  }
20276
20530
  } finally {
@@ -20356,6 +20610,85 @@ function totalFromContentRange(header) {
20356
20610
  return Number.isFinite(n) && n >= 0 ? n : null;
20357
20611
  }
20358
20612
 
20613
+ // src/channels/discord-progress.ts
20614
+ init_folded_panel();
20615
+ init_process_card_model();
20616
+ init_process_card_render();
20617
+ import { ContainerBuilder, SeparatorBuilder, TextDisplayBuilder } from "@discordjs/builders";
20618
+ import { SeparatorSpacingSize } from "discord-api-types/v10";
20619
+ var SHOWN_STEPS_MAX = 8;
20620
+ var RESULT_LINE_MAX = 100;
20621
+ var SETTLED_TTL_MS = 30 * 60 * 1e3;
20622
+ function buildDiscordProgressContainer(state, accent) {
20623
+ const container = new ContainerBuilder().setAccentColor(accent);
20624
+ const context = state.presentation;
20625
+ const status = context?.statusLabels?.[state.status] ?? STATUS_META[state.status].suffix;
20626
+ container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`**${context?.title ?? state.repoName}** \xB7 ${status}`));
20627
+ container.addSeparatorComponents(new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true));
20628
+ const tools = state.rows.filter((row) => row.kind === "tool");
20629
+ const shown = tools.slice(-SHOWN_STEPS_MAX);
20630
+ const hidden = (state.earlierSteps || 0) + tools.length - shown.length;
20631
+ if (hidden > 0) container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`\u22EF \u524D\u9762\u8FD8\u6709 ${hidden} \u6B65`));
20632
+ for (const row of shown) {
20633
+ let content = toolRowTitle(row.name, row.args, row.state);
20634
+ if (row.state !== "run" && row.resultVisible !== false) {
20635
+ content += `
20636
+ \u23BF ${row.state === "err" ? "\u2717 " : ""}${clipCardText(oneLine(row.out.split("\n")[0] || "(\u65E0\u8F93\u51FA)"), RESULT_LINE_MAX)}`;
20637
+ }
20638
+ container.addTextDisplayComponents(new TextDisplayBuilder().setContent(content));
20639
+ }
20640
+ const thought = state.rows.findLast((row) => row.kind === "think");
20641
+ if (thought?.kind === "think") container.addTextDisplayComponents(new TextDisplayBuilder().setContent(thoughtLine(thought.preview)));
20642
+ return container;
20643
+ }
20644
+ var DiscordProgressCards = class {
20645
+ constructor(transport, accent) {
20646
+ this.transport = transport;
20647
+ this.accent = accent;
20648
+ }
20649
+ entries = /* @__PURE__ */ new Map();
20650
+ queues = /* @__PURE__ */ new Map();
20651
+ async sendProgress(target, state) {
20652
+ const container = buildDiscordProgressContainer(state, this.accent);
20653
+ const id3 = await this.transport.send(target, container);
20654
+ this.entries.set(id3, { channelId: target, sent: key3(container) });
20655
+ if (settled(state.status)) this.expire(id3);
20656
+ return id3;
20657
+ }
20658
+ /** 内容与上次发出的一致就不编辑(过程控制器的 5 秒活性桶会空推一轮);同一条消息的编辑按入队顺序串行 */
20659
+ updateProgress(id3, state) {
20660
+ const run = async () => {
20661
+ const entry = this.entries.get(id3);
20662
+ if (!entry) return;
20663
+ const container = buildDiscordProgressContainer(state, this.accent);
20664
+ const next = key3(container);
20665
+ if (next === entry.sent) return;
20666
+ await this.transport.edit(entry.channelId, id3, container);
20667
+ entry.sent = next;
20668
+ if (settled(state.status)) this.expire(id3);
20669
+ };
20670
+ const queued = (this.queues.get(id3) ?? Promise.resolve()).then(run, run);
20671
+ this.queues.set(id3, queued);
20672
+ const forget = () => {
20673
+ if (this.queues.get(id3) === queued) this.queues.delete(id3);
20674
+ };
20675
+ void queued.then(forget, forget);
20676
+ return queued;
20677
+ }
20678
+ async removeProgress(id3) {
20679
+ const entry = this.entries.get(id3);
20680
+ this.entries.delete(id3);
20681
+ if (entry) await this.transport.remove(entry.channelId, id3);
20682
+ }
20683
+ expire(id3) {
20684
+ setTimeout(() => {
20685
+ this.entries.delete(id3);
20686
+ }, SETTLED_TTL_MS).unref?.();
20687
+ }
20688
+ };
20689
+ var key3 = (container) => JSON.stringify(container.toJSON());
20690
+ var settled = (status) => status !== "run" && status !== "wait";
20691
+
20359
20692
  // src/channels/discord.ts
20360
20693
  var DISCORD_MSG_LIMIT = 2e3;
20361
20694
  var DiscordAdapter = class _DiscordAdapter {
@@ -20364,6 +20697,10 @@ var DiscordAdapter = class _DiscordAdapter {
20364
20697
  client;
20365
20698
  config;
20366
20699
  ownsClient;
20700
+ /** 1124:折叠过程卡只在折叠模式下出(没折叠维持逐步显示);编辑型消息的推送节奏 */
20701
+ progressRequiresCollapsed = true;
20702
+ progressThrottleMs = 2500;
20703
+ progressCards;
20367
20704
  messageHandler = null;
20368
20705
  commandHandler = null;
20369
20706
  registeredCommands = [];
@@ -20408,6 +20745,25 @@ var DiscordAdapter = class _DiscordAdapter {
20408
20745
  this.client = new Client(clientOptions);
20409
20746
  this.ownsClient = true;
20410
20747
  }
20748
+ this.progressCards = new DiscordProgressCards({
20749
+ send: async (channelId, container) => {
20750
+ const channel = await this.textChannel(channelId);
20751
+ assertExternalEffectCurrent();
20752
+ const sent = await channel.send({ flags: MessageFlags.IsComponentsV2, components: [container], allowedMentions: { parse: [] } });
20753
+ return sent.id;
20754
+ },
20755
+ edit: async (channelId, messageId, container) => {
20756
+ const channel = await this.textChannel(channelId);
20757
+ const message = channel.messages?.cache?.get(messageId) ?? await channel.messages.fetch(messageId);
20758
+ assertExternalEffectCurrent();
20759
+ await message.edit({ components: [container], allowedMentions: { parse: [] } });
20760
+ },
20761
+ // 删除与 deletePreview 同口径:不过 assertExternalEffectCurrent(删是减法)
20762
+ remove: async (channelId, messageId) => {
20763
+ const channel = await this.textChannel(channelId);
20764
+ await channel.messages.delete(messageId);
20765
+ }
20766
+ }, this.previewColor);
20411
20767
  }
20412
20768
  /** 暴露 discord.js Client(供 VisualTransport 等模块使用) */
20413
20769
  getClient() {
@@ -20779,6 +21135,23 @@ var DiscordAdapter = class _DiscordAdapter {
20779
21135
  } catch {
20780
21136
  }
20781
21137
  }
21138
+ // === 折叠过程卡(1124):Discord 卡片消息,每步带一行结果;没有按钮 ===
21139
+ async textChannel(channelId) {
21140
+ const channel = this.client.channels.cache.get(channelId) ?? await this.client.channels.fetch(channelId);
21141
+ if (!channel?.isTextBased() || !("send" in channel)) {
21142
+ throw new Error(`discord: \u8FC7\u7A0B\u5361: channel ${channelId} not found or not text-based`);
21143
+ }
21144
+ return channel;
21145
+ }
21146
+ async sendProgress(target, state) {
21147
+ return this.progressCards.sendProgress(target, state);
21148
+ }
21149
+ async updateProgress(id3, state) {
21150
+ await this.progressCards.updateProgress(id3, state);
21151
+ }
21152
+ async removeProgress(id3) {
21153
+ await this.progressCards.removeProgress(id3);
21154
+ }
20782
21155
  // === Streaming preview — 对齐 cc-connect Discord 的 SendPreviewStart/UpdateMessage/DeletePreviewMessage ===
20783
21156
  // 对齐 cc-connect platform/discord/progress.go:preview 消息用 Embed(彩色标题栏 + 内容)
20784
21157
  /** Embed 颜色常量 — 对齐 cc-connect discordProgressStateMeta */
@@ -21241,8 +21614,8 @@ var FeishuAdapter = class _FeishuAdapter {
21241
21614
  let durationMs = Math.round(fileBuffer.length / 3);
21242
21615
  try {
21243
21616
  const { execFile: execFile2 } = await import("node:child_process");
21244
- const { promisify: promisify3 } = await import("node:util");
21245
- const execFileAsync2 = promisify3(execFile2);
21617
+ const { promisify: promisify4 } = await import("node:util");
21618
+ const execFileAsync2 = promisify4(execFile2);
21246
21619
  const probe = await execFileAsync2("ffprobe", ["-v", "quiet", "-show_format", "-print_format", "json", attachment.path], { timeout: 1e4 });
21247
21620
  const fmt = JSON.parse(probe.stdout);
21248
21621
  if (fmt?.format?.duration) durationMs = Math.round(parseFloat(fmt.format.duration) * 1e3);
@@ -21337,8 +21710,8 @@ var FeishuAdapter = class _FeishuAdapter {
21337
21710
  return fileKey;
21338
21711
  }
21339
21712
  /** 消息资源 URL(三个下载方法 + Range 预探共用) */
21340
- _resourceUrl(messageId, key2, kind) {
21341
- return `https://open.feishu.cn/open-apis/im/v1/messages/${messageId}/resources/${key2}?type=${kind}`;
21713
+ _resourceUrl(messageId, key4, kind) {
21714
+ return `https://open.feishu.cn/open-apis/im/v1/messages/${messageId}/resources/${key4}?type=${kind}`;
21342
21715
  }
21343
21716
  /** 通过飞书API下载消息中的图片 */
21344
21717
  async _downloadImage(messageId, imageKey, tokenOverride, init) {
@@ -21407,7 +21780,7 @@ var FeishuAdapter = class _FeishuAdapter {
21407
21780
  let totalBytes = 0;
21408
21781
  let token;
21409
21782
  const nameCache = /* @__PURE__ */ new Map();
21410
- const fetchOne = async (msgId, key2, kind, nameHint, idx, notes) => {
21783
+ const fetchOne = async (msgId, key4, kind, nameHint, idx, notes) => {
21411
21784
  if (Date.now() - started > HISTORY_DOWNLOAD_BUDGET_MS) {
21412
21785
  notes.push(budgetNote(1));
21413
21786
  return null;
@@ -21415,7 +21788,7 @@ var FeishuAdapter = class _FeishuAdapter {
21415
21788
  try {
21416
21789
  token ??= await this._getTenantToken();
21417
21790
  try {
21418
- const probe = await fetch(this._resourceUrl(msgId, key2, kind === "image" ? "image" : "file"), {
21791
+ const probe = await fetch(this._resourceUrl(msgId, key4, kind === "image" ? "image" : "file"), {
21419
21792
  headers: { Authorization: `Bearer ${token}`, Range: "bytes=0-0" },
21420
21793
  signal: AbortSignal.timeout(5e3)
21421
21794
  });
@@ -21429,7 +21802,7 @@ var FeishuAdapter = class _FeishuAdapter {
21429
21802
  } catch {
21430
21803
  }
21431
21804
  const dlInit = { signal: AbortSignal.timeout(HISTORY_ATTACH_TIMEOUT_MS) };
21432
- const buf = kind === "image" ? await this._downloadImage(msgId, key2, token, dlInit) : kind === "video" ? await this._downloadVideo(msgId, key2, token, dlInit) : await this._downloadFile(msgId, key2, token, dlInit);
21805
+ const buf = kind === "image" ? await this._downloadImage(msgId, key4, token, dlInit) : kind === "video" ? await this._downloadVideo(msgId, key4, token, dlInit) : await this._downloadFile(msgId, key4, token, dlInit);
21433
21806
  if (buf.length > HISTORY_ATTACH_MAX_BYTES) {
21434
21807
  notes.push(skipNote(nameHint, buf.length));
21435
21808
  return null;
@@ -21479,9 +21852,9 @@ var FeishuAdapter = class _FeishuAdapter {
21479
21852
  if (r?.tag === "text") segs.push(String(r.text ?? ""));
21480
21853
  else if (r?.tag === "img") {
21481
21854
  segs.push("[\u56FE\u7247]");
21482
- const key2 = String(r?.image_key ?? "");
21483
- if (key2) {
21484
- const att = await fetchOne(msgId, key2, "image", `post-${msgId}-${imgIdx}.jpg`, imgIdx, notes);
21855
+ const key4 = String(r?.image_key ?? "");
21856
+ if (key4) {
21857
+ const att = await fetchOne(msgId, key4, "image", `post-${msgId}-${imgIdx}.jpg`, imgIdx, notes);
21485
21858
  if (att) attachments.push(att);
21486
21859
  imgIdx++;
21487
21860
  }
@@ -21490,18 +21863,18 @@ var FeishuAdapter = class _FeishuAdapter {
21490
21863
  content = segs.join("").trim() || "[\u56FE\u6587]";
21491
21864
  } else if (type === "image") {
21492
21865
  content = "[\u56FE\u7247]";
21493
- const key2 = String(body?.image_key ?? "");
21494
- if (key2) {
21495
- const att = await fetchOne(msgId, key2, "image", `img-${msgId}.jpg`, 0, notes);
21866
+ const key4 = String(body?.image_key ?? "");
21867
+ if (key4) {
21868
+ const att = await fetchOne(msgId, key4, "image", `img-${msgId}.jpg`, 0, notes);
21496
21869
  if (att) attachments.push(att);
21497
21870
  }
21498
21871
  } else if (type === "file" || type === "audio" || type === "media") {
21499
21872
  const name0 = String(body?.file_name ?? body?.file_key ?? "file");
21500
21873
  const label = type === "audio" ? "\u8BED\u97F3" : type === "media" ? "\u89C6\u9891" : "\u6587\u4EF6";
21501
21874
  content = `[${label}] ${name0}`;
21502
- const key2 = String(body?.file_key ?? "");
21503
- if (key2) {
21504
- const att = await fetchOne(msgId, key2, type === "media" ? "video" : "file", name0, 0, notes);
21875
+ const key4 = String(body?.file_key ?? "");
21876
+ if (key4) {
21877
+ const att = await fetchOne(msgId, key4, type === "media" ? "video" : "file", name0, 0, notes);
21505
21878
  if (att) attachments.push(att);
21506
21879
  }
21507
21880
  } else if (type === "sticker") {
@@ -21965,8 +22338,8 @@ var FeishuAdapter = class _FeishuAdapter {
21965
22338
  const earlyImageKeys = imageKeys.filter(Boolean);
21966
22339
  if (message.message_type === "image" && !earlyImageKeys.length) {
21967
22340
  try {
21968
- const key2 = JSON.parse(message.content || "{}").image_key;
21969
- if (key2) earlyImageKeys.push(key2);
22341
+ const key4 = JSON.parse(message.content || "{}").image_key;
22342
+ if (key4) earlyImageKeys.push(key4);
21970
22343
  } catch {
21971
22344
  }
21972
22345
  }
@@ -21982,12 +22355,12 @@ var FeishuAdapter = class _FeishuAdapter {
21982
22355
  messageId,
21983
22356
  recvAt: Date.now(),
21984
22357
  metadata: { chatId, chatType, ...parentId ? { parentId } : {} },
21985
- attachments: earlyImageKeys.map((key2) => ({
22358
+ attachments: earlyImageKeys.map((key4) => ({
21986
22359
  url: "",
21987
22360
  filename: "image.png",
21988
22361
  contentType: "image/png",
21989
22362
  size: 0,
21990
- loadBytes: (signal) => this._downloadImage(messageId, key2, void 0, { signal })
22363
+ loadBytes: (signal) => this._downloadImage(messageId, key4, void 0, { signal })
21991
22364
  })),
21992
22365
  prepareContext: async (signal) => {
21993
22366
  signal?.throwIfAborted();
@@ -22073,7 +22446,8 @@ var FeishuAdapter = class _FeishuAdapter {
22073
22446
  }
22074
22447
  }
22075
22448
  if (!cleanContent.trim() && !imageAttachments?.length && !fileAttachment && !videoAttachment && !attachNotes.length) return;
22076
- const senderName = await this._resolveSenderName(senderOpenId);
22449
+ const senderName = this.config?.nameMap?.[senderOpenId] || this._senderNameCache.get(senderOpenId)?.name || senderOpenId.slice(0, 8);
22450
+ void this._resolveSenderName(senderOpenId);
22077
22451
  const inbound = {
22078
22452
  // 1012 翀哥实测:引用原文和新正文挤一行会混——引用独占一行,正文(含附件留痕)另起一行。
22079
22453
  content: [
@@ -22181,8 +22555,8 @@ var FeishuAdapter = class _FeishuAdapter {
22181
22555
  } else if (block.tag === "at") {
22182
22556
  lines.push(block.user_name ? `@${block.user_name}` : "@user");
22183
22557
  } else if (block.tag === "img") {
22184
- const key2 = block.image_key;
22185
- if (key2) imageKeys.push(key2);
22558
+ const key4 = block.image_key;
22559
+ if (key4) imageKeys.push(key4);
22186
22560
  }
22187
22561
  }
22188
22562
  lines.push("\n");
@@ -22317,6 +22691,11 @@ function hasWechatPriorContact(stateDir, accountId, userId) {
22317
22691
  }
22318
22692
  }
22319
22693
 
22694
+ // src/auth/client.ts
22695
+ var DEFAULT_AUTH_BROKER = "https://auth.engine7.ai/auth/";
22696
+ var LEGACY_AUTH_BROKERS = ["https://www.twinsun.top/auth/"];
22697
+ var OFFICIAL_AUTH_BROKERS = /* @__PURE__ */ new Set([DEFAULT_AUTH_BROKER, ...LEGACY_AUTH_BROKERS]);
22698
+
22320
22699
  // src/config/features.ts
22321
22700
  init_live();
22322
22701
 
@@ -22385,13 +22764,13 @@ function pkcs7Unpad(data) {
22385
22764
  if (pad < 1 || pad > 16 || pad > data.length) return data;
22386
22765
  return data.subarray(0, data.length - pad);
22387
22766
  }
22388
- function aesEncrypt(plaintext, key2) {
22389
- const c = crypto2.createCipheriv("aes-128-ecb", key2, null);
22767
+ function aesEncrypt(plaintext, key4) {
22768
+ const c = crypto2.createCipheriv("aes-128-ecb", key4, null);
22390
22769
  c.setAutoPadding(false);
22391
22770
  return Buffer.concat([c.update(pkcs7Pad(plaintext)), c.final()]);
22392
22771
  }
22393
- function aesDecrypt(ciphertext, key2) {
22394
- const d = crypto2.createDecipheriv("aes-128-ecb", key2, null);
22772
+ function aesDecrypt(ciphertext, key4) {
22773
+ const d = crypto2.createDecipheriv("aes-128-ecb", key4, null);
22395
22774
  d.setAutoPadding(false);
22396
22775
  return pkcs7Unpad(Buffer.concat([d.update(ciphertext), d.final()]));
22397
22776
  }
@@ -22650,8 +23029,8 @@ var ContextTokenStore = class {
22650
23029
  this.save();
22651
23030
  }
22652
23031
  delete(a, p) {
22653
- const key2 = p !== void 0 ? this.k(a, p) : a;
22654
- this.cache.delete(key2);
23032
+ const key4 = p !== void 0 ? this.k(a, p) : a;
23033
+ this.cache.delete(key4);
22655
23034
  this.save();
22656
23035
  }
22657
23036
  };
@@ -23212,12 +23591,12 @@ import { WebSocketServer, WebSocket } from "ws";
23212
23591
  init_live();
23213
23592
  init_well_formed();
23214
23593
  import { execFile } from "node:child_process";
23215
- import { promisify as promisify2 } from "node:util";
23594
+ import { promisify as promisify3 } from "node:util";
23216
23595
  init_voice_chat_tts_daemon();
23217
23596
  import * as path14 from "node:path";
23218
23597
  import * as os6 from "node:os";
23219
23598
  import net2 from "net";
23220
- var execFileAsync = promisify2(execFile);
23599
+ var execFileAsync = promisify3(execFile);
23221
23600
  var VOICE_DIR = path14.join(os6.tmpdir(), "engine-voice");
23222
23601
  async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
23223
23602
  if (!isDaemonReady()) {
@@ -24183,10 +24562,10 @@ var PreviewEditThrottle = class {
24183
24562
  }
24184
24563
  st = /* @__PURE__ */ new Map();
24185
24564
  /** 提交一次编辑;返回的 promise 在"该内容(或其后覆盖它的更新内容)真实落盘"后 settle,失败 reject */
24186
- submit(key2, req, run) {
24187
- const s = this.st.get(key2) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24565
+ submit(key4, req, run) {
24566
+ const s = this.st.get(key4) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24188
24567
  const guardedRun = AsyncLocalStorage6.bind(run);
24189
- this.st.set(key2, s);
24568
+ this.st.set(key4, s);
24190
24569
  return new Promise((resolve12, reject) => {
24191
24570
  const waiter = { resolve: resolve12, reject };
24192
24571
  if (s.timer) {
@@ -24196,7 +24575,7 @@ var PreviewEditThrottle = class {
24196
24575
  return;
24197
24576
  }
24198
24577
  if (this.now() - s.lastEditAt >= this.minIntervalMs) {
24199
- this.fire(key2, req, [waiter], guardedRun);
24578
+ this.fire(key4, req, [waiter], guardedRun);
24200
24579
  return;
24201
24580
  }
24202
24581
  s.pending = req;
@@ -24210,12 +24589,12 @@ var PreviewEditThrottle = class {
24210
24589
  s.pending = null;
24211
24590
  s.pendingRun = null;
24212
24591
  s.waiters = [];
24213
- if (p && latestRun) this.fire(key2, p, w, latestRun);
24592
+ if (p && latestRun) this.fire(key4, p, w, latestRun);
24214
24593
  }, this.minIntervalMs - (this.now() - s.lastEditAt));
24215
24594
  });
24216
24595
  }
24217
- fire(key2, req, waiters, run) {
24218
- const s = this.st.get(key2);
24596
+ fire(key4, req, waiters, run) {
24597
+ const s = this.st.get(key4);
24219
24598
  if (s) s.lastEditAt = this.now();
24220
24599
  Promise.resolve().then(() => run(req)).then(
24221
24600
  () => {
@@ -24450,16 +24829,16 @@ var AlbumBuffer = class {
24450
24829
  }
24451
24830
  groups = /* @__PURE__ */ new Map();
24452
24831
  add(item) {
24453
- const key2 = item.mediaGroupId;
24454
- const g = this.groups.get(key2) ?? { items: [], lastAt: 0 };
24832
+ const key4 = item.mediaGroupId;
24833
+ const g = this.groups.get(key4) ?? { items: [], lastAt: 0 };
24455
24834
  g.items.push(item);
24456
24835
  g.lastAt = this.now();
24457
- this.groups.set(key2, g);
24836
+ this.groups.set(key4, g);
24458
24837
  }
24459
24838
  tick() {
24460
- for (const [key2, g] of this.groups) {
24839
+ for (const [key4, g] of this.groups) {
24461
24840
  if (this.now() - g.lastAt < this.timeoutMs) continue;
24462
- this.groups.delete(key2);
24841
+ this.groups.delete(key4);
24463
24842
  g.items.sort((a, b) => Number(a.inbound.messageId) - Number(b.inbound.messageId));
24464
24843
  this.flush(g.items);
24465
24844
  }
@@ -24899,9 +25278,9 @@ var TelegramAdapter = class {
24899
25278
  */
24900
25279
  async editPreview(handle, content, agentName, isFinal) {
24901
25280
  const chatId = Number(handle.channelId);
24902
- const key2 = `${handle.channelId}:${handle.messageId}`;
25281
+ const key4 = `${handle.channelId}:${handle.messageId}`;
24903
25282
  try {
24904
- await this.editThrottle.submit(key2, { content, agentName, isFinal: !!isFinal }, async (r) => {
25283
+ await this.editThrottle.submit(key4, { content, agentName, isFinal: !!isFinal }, async (r) => {
24905
25284
  await this.enqueueSend(chatId, async () => {
24906
25285
  if (r.isFinal) {
24907
25286
  const chunks = splitTextChunks(r.content, 4e3);
@@ -25019,11 +25398,11 @@ function inboundGate(inp) {
25019
25398
  if (!inp.hasUserContent) {
25020
25399
  return { pass: false, gate: 4, reason: "\u65E0 user \u53EF\u89C1\u5185\u5BB9\uFF08receipt/protocol \u7A7A\u6D88\u606F\uFF09" };
25021
25400
  }
25022
- const key2 = `${inp.jid}:${inp.messageId}`;
25023
- if (inp.seenKeys.has(key2)) {
25024
- return { pass: false, gate: 5, reason: `\u91CD\u590D\u6D88\u606F: ${key2}` };
25401
+ const key4 = `${inp.jid}:${inp.messageId}`;
25402
+ if (inp.seenKeys.has(key4)) {
25403
+ return { pass: false, gate: 5, reason: `\u91CD\u590D\u6D88\u606F: ${key4}` };
25025
25404
  }
25026
- inp.seenKeys.add(key2);
25405
+ inp.seenKeys.add(key4);
25027
25406
  return { pass: true };
25028
25407
  }
25029
25408
  var WRAPPERS = [
@@ -25376,14 +25755,14 @@ import { HttpsProxyAgent as HttpsProxyAgent2 } from "https-proxy-agent";
25376
25755
 
25377
25756
  // src/version.ts
25378
25757
  import { readFileSync as readFileSync12 } from "node:fs";
25379
- import { dirname as dirname10, join as join20 } from "node:path";
25758
+ import { dirname as dirname10, join as join21 } from "node:path";
25380
25759
  import { fileURLToPath as fileURLToPath2 } from "node:url";
25381
25760
  var _loaded = null;
25382
25761
  var _pkgDirOverride = null;
25383
25762
  function candidates() {
25384
- if (_pkgDirOverride !== null) return [join20(_pkgDirOverride, "package.json")];
25763
+ if (_pkgDirOverride !== null) return [join21(_pkgDirOverride, "package.json")];
25385
25764
  const here = dirname10(fileURLToPath2(import.meta.url));
25386
- return [join20(here, "..", "package.json"), join20(here, "..", "..", "package.json")];
25765
+ return [join21(here, "..", "package.json"), join21(here, "..", "..", "package.json")];
25387
25766
  }
25388
25767
  function readFromDisk() {
25389
25768
  for (const p of candidates()) {
@@ -26032,8 +26411,11 @@ function fitProtectedTail(suffix, budget) {
26032
26411
  function hasImage(m) {
26033
26412
  return "role" in m && Array.isArray(m.content) && m.content.some((b) => b.type === "image_ref" || b.type === "image");
26034
26413
  }
26414
+ function hasMedia(m) {
26415
+ return hasImage(m) || "role" in m && Array.isArray(m.content) && m.content.some((b) => b.type === "video");
26416
+ }
26035
26417
  function unobservedImageIndex(messages) {
26036
- return messages.findIndex((m) => hasImage(m) && !("role" in m && m.imageInput?.observed === true));
26418
+ return messages.findIndex((m) => hasMedia(m) && !("role" in m && m.imageInput?.observed === true));
26037
26419
  }
26038
26420
  function splitProtectedImages(messages, budget) {
26039
26421
  const index = unobservedImageIndex(messages);
@@ -26213,7 +26595,7 @@ ${archiveNotice(resultArchive)}`, resultArchive };
26213
26595
 
26214
26596
  // src/models/provider-errors.ts
26215
26597
  function isQuotaExhaustedError(message) {
26216
- return /\b(?:insufficient_quota|billing_hard_limit_reached|credit_balance_too_low)\b|exceeded your current quota|credit balance is too low|insufficient (?:credits|balance)|Token Plan[^\n]{0,60}(?:用量上限|额度(?:已)?用尽)/i.test(message);
26598
+ return /\b(?:insufficient_quota|billing_hard_limit_reached|credit_balance_too_low|free_pool_exhausted|free_quota_exhausted|vip_quota_exhausted|quota_exhausted)\b|subscription quota insufficient|订阅额度不足|exceeded your current quota|credit balance is too low|insufficient (?:credits|balance)|Token Plan[^\n]{0,60}(?:用量上限|额度(?:已)?用尽)/i.test(message);
26217
26599
  }
26218
26600
 
26219
26601
  // src/core/query.ts
@@ -26355,8 +26737,8 @@ function withTravelEventContext(context, run) {
26355
26737
  }
26356
26738
  function travelEventPermit(context) {
26357
26739
  const permit = context.permit(), original = context.originalPermit;
26358
- for (const key2 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
26359
- if (permit[key2] !== original[key2]) throw new Error("TRAVEL_GATEWAY_STALE_CONTEXT");
26740
+ for (const key4 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
26741
+ if (permit[key4] !== original[key4]) throw new Error("TRAVEL_GATEWAY_STALE_CONTEXT");
26360
26742
  }
26361
26743
  if (context.complete) throw new Error("TRAVEL_GATEWAY_EVENT_COMPLETED");
26362
26744
  return permit;
@@ -26501,7 +26883,10 @@ function isCpuModeHook(command) {
26501
26883
  return (tokens[0] === process.execPath || /^(?:node|python[\d.]*|py)(?:\.exe)?$/i.test(executable)) && /^emotion(?:_state_machine\.(?:mjs|py)|-hook-gate\.js)$/i.test(script);
26502
26884
  }
26503
26885
  function cpuModeHookOutput(command, input, workspace) {
26504
- if (!isCpuModeHook(command) || !["emotion", "work"].includes(input.cpu_router_mode)) return null;
26886
+ return isCpuModeHook(command) ? cpuModeOutput(input, workspace) : null;
26887
+ }
26888
+ function cpuModeOutput(input, workspace) {
26889
+ if (!["emotion", "work"].includes(input.cpu_router_mode)) return null;
26505
26890
  const text2 = typeof input.prompt === "string" ? input.prompt : "";
26506
26891
  const internal = ["heartbeat", "cron", "system", "inner-voice", "mem7"];
26507
26892
  const marks = ["\u3010", "[\u5B9A\u65F6", "\u5F53\u524D\u65F6\u95F4\uFF1A", "[inner-voice]", "<calendar-notification>", "<nudge-notification>", "<task-notification>", "<system-reminder>"];
@@ -26752,10 +27137,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
26752
27137
  hook
26753
27138
  };
26754
27139
  }
26755
- const cpuModeOutput = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
26756
- if (cpuModeOutput) {
26757
- const processed = processHookJSONOutput({ json: cpuModeOutput, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
26758
- console.log(`[cpu-router] mode-hook=${hookTimingLabel(hook, 0)} mode=${cpuModeOutput._mode ?? "skip"}`);
27140
+ const cpuModeOutput2 = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
27141
+ if (cpuModeOutput2) {
27142
+ const processed = processHookJSONOutput({ json: cpuModeOutput2, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
27143
+ console.log(`[cpu-router] mode-hook=${hookTimingLabel(hook, 0)} mode=${cpuModeOutput2._mode ?? "skip"}`);
26759
27144
  return { ...processed, outcome: "success", hook };
26760
27145
  }
26761
27146
  const jsonInput = JSON.stringify(hookInput);
@@ -26884,10 +27269,10 @@ function matchesPromptHookCondition(hook, input) {
26884
27269
  if (hook.when === void 0) return true;
26885
27270
  const when = hook.when;
26886
27271
  if (!when || typeof when !== "object" || Array.isArray(when) || input.hook_event_name !== "UserPromptSubmit") return false;
26887
- if (Object.keys(when).some((key2) => !["channel", "channelType", "source", "excludeSenderIds"].includes(key2))) return false;
27272
+ if (Object.keys(when).some((key4) => !["channel", "channelType", "source", "excludeSenderIds"].includes(key4))) return false;
26888
27273
  if (!input.prompt.trim()) return false;
26889
- for (const [key2, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
26890
- if (when[key2] !== void 0 && (typeof when[key2] !== "string" || when[key2] !== actual)) return false;
27274
+ for (const [key4, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
27275
+ if (when[key4] !== void 0 && (typeof when[key4] !== "string" || when[key4] !== actual)) return false;
26891
27276
  }
26892
27277
  if (when.excludeSenderIds !== void 0) {
26893
27278
  if (!Array.isArray(when.excludeSenderIds) || when.excludeSenderIds.some((id3) => typeof id3 !== "string")) return false;
@@ -27025,6 +27410,7 @@ async function executeStopHooks(ctx, signal, lastAssistantMessage) {
27025
27410
  cwd: ctx.cwd,
27026
27411
  stop_hook_active: false,
27027
27412
  last_assistant_message: lastAssistantMessage,
27413
+ turn_evidence: ctx.stopTurnEvidence,
27028
27414
  channel: ctx.channel,
27029
27415
  // 让 callback hook 能判断来源
27030
27416
  channelTarget: ctx.channelTarget,
@@ -27267,13 +27653,17 @@ init_read_guard();
27267
27653
  var OnDemandRecall = class {
27268
27654
  used = /* @__PURE__ */ new Set();
27269
27655
  cache = /* @__PURE__ */ new Map();
27656
+ /** Actual tool mutations invalidate this turn's snapshot without polling SQLite. */
27657
+ invalidate() {
27658
+ this.cache.clear();
27659
+ }
27270
27660
  // 1024 翀哥裁决:6 秒墙全撤。它界的是返回大小不是时延来源(检索耗时在 embedding/bm25/rerank),
27271
27661
  // 底层各有各的界(SQL overlay 死线 12s、embedding HTTP 30s、rerank 1500ms 竞速),1+1 配额防循环。
27272
27662
  // 这层墙当天制造了两次 timeout 假阴性 + 额度连坐,没拦住任何真问题。
27273
27663
  constructor(keywordAlreadySearched = false) {
27274
27664
  if (keywordAlreadySearched) this.used.add("keyword");
27275
27665
  }
27276
- async search(binding, args, captureGuard, run, signal) {
27666
+ async search(binding, args, run, signal) {
27277
27667
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
27278
27668
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
27279
27669
  if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
@@ -27285,17 +27675,12 @@ var OnDemandRecall = class {
27285
27675
  };
27286
27676
  for (const passthrough of ["known_at", "known_at_revision", "valid_at", "entity_ref", "after_receipt", "session_id"])
27287
27677
  if (args[passthrough] !== void 0) bounded[passthrough] = args[passthrough];
27288
- const key2 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
27289
- const cached2 = this.cache.get(key2);
27678
+ const key4 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
27679
+ const cached2 = this.cache.get(key4);
27290
27680
  if (cached2) {
27291
- const result2 = await cached2.result;
27681
+ const result2 = await cached2;
27292
27682
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
27293
- try {
27294
- cached2.assertCurrent();
27295
- return result2;
27296
- } catch {
27297
- return status("stale", "\u6765\u6E90\u5DF2\u53D8\u5316\uFF0C\u65E7\u7ED3\u679C\u4E0D\u53EF\u590D\u7528\uFF1B\u8BF7\u4F9D\u636E\u5F53\u524D\u6750\u6599\u6216\u6F84\u6E05\u3002");
27298
- }
27683
+ return result2;
27299
27684
  }
27300
27685
  const kind = bounded.view === "current" || bounded.mode === "keyword" ? "keyword" : "semantic";
27301
27686
  if (kind === "keyword" && this.used.has("keyword") && !this.used.has("semantic")) {
@@ -27304,7 +27689,6 @@ var OnDemandRecall = class {
27304
27689
  if (this.used.has(kind)) {
27305
27690
  return status("budget_exhausted", "\u672C\u8F6E\u5DF2\u7528\u5B8C\u8BE5\u7C7B\u8865\u67E5\uFF1B\u4E0D\u8981\u6362\u8BCD\u53CD\u590D\u67E5\uFF0C\u53EF\u8BE2\u95EE\u7EBF\u7D22\u3002");
27306
27691
  }
27307
- const assertCurrent = captureGuard();
27308
27692
  this.used.add(kind);
27309
27693
  if (kind === "semantic") this.used.add("keyword");
27310
27694
  const controller = new AbortController();
@@ -27334,7 +27718,7 @@ ${error.stack.split("\n").slice(0, 6).join("\n")}` : ""
27334
27718
  controller.abort();
27335
27719
  }
27336
27720
  })();
27337
- this.cache.set(key2, { result, assertCurrent });
27721
+ this.cache.set(key4, result);
27338
27722
  return result;
27339
27723
  }
27340
27724
  };
@@ -27395,13 +27779,13 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27395
27779
  continue;
27396
27780
  }
27397
27781
  if (!store) throw new Error("Image asset store is required to materialize image refs");
27398
- const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27399
- if (!cache.has(key2)) cache.set(key2, store.materialize(block.image).catch((error) => {
27782
+ const key4 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27783
+ if (!cache.has(key4)) cache.set(key4, store.materialize(block.image).catch((error) => {
27400
27784
  if (strict) throw error;
27401
27785
  console.warn(`[image-assets] \u5386\u53F2\u56FE\u7247\u4E0D\u53EF\u7528\uFF0C\u964D\u7EA7\u4E3A\u5360\u4F4D\uFF08sha256=${block.image.sha256.slice(0, 12)}\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}`);
27402
27786
  return null;
27403
27787
  }));
27404
- content.push(await cache.get(key2) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
27788
+ content.push(await cache.get(key4) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
27405
27789
  signal?.throwIfAborted();
27406
27790
  }
27407
27791
  output.push({ ...message, content });
@@ -27461,8 +27845,8 @@ var MAX_PENDING_BYTES = 512 * 1024;
27461
27845
  var SteerMailbox = class {
27462
27846
  constructor(stateDir, sessionId) {
27463
27847
  this.sessionId = sessionId;
27464
- const key2 = createHash31("sha256").update(sessionId).digest("hex");
27465
- this.path = path23.join(stateDir, "steer", `${key2}.json`);
27848
+ const key4 = createHash31("sha256").update(sessionId).digest("hex");
27849
+ this.path = path23.join(stateDir, "steer", `${key4}.json`);
27466
27850
  }
27467
27851
  path;
27468
27852
  list() {
@@ -27803,9 +28187,9 @@ function smartCompressToolResult(content, essentialFields, sizeLimit) {
27803
28187
  if (typeof item === "object" && item !== null && !Array.isArray(item)) {
27804
28188
  const extracted = {};
27805
28189
  if (fieldSet) {
27806
- for (const key2 of essentialFields) {
27807
- if (key2 in item) {
27808
- extracted[key2] = item[key2];
28190
+ for (const key4 of essentialFields) {
28191
+ if (key4 in item) {
28192
+ extracted[key4] = item[key4];
27809
28193
  }
27810
28194
  }
27811
28195
  } else {
@@ -29177,7 +29561,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29177
29561
  outputHandle.close().catch(() => {
29178
29562
  });
29179
29563
  let aborted = false;
29180
- let settled = false;
29564
+ let settled2 = false;
29181
29565
  const cleanup = () => {
29182
29566
  clearTimeout(timer);
29183
29567
  signal?.removeEventListener("abort", onAbort);
@@ -29186,8 +29570,8 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29186
29570
  child.removeListener("error", onError);
29187
29571
  };
29188
29572
  const done = async (code, error) => {
29189
- if (settled) return;
29190
- settled = true;
29573
+ if (settled2) return;
29574
+ settled2 = true;
29191
29575
  cleanup();
29192
29576
  let output = "";
29193
29577
  let truncated = false;
@@ -29221,12 +29605,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29221
29605
  void done(1, error.message);
29222
29606
  };
29223
29607
  const onAbort = () => {
29224
- if (settled || signal?.reason === "interrupt") return;
29608
+ if (settled2 || signal?.reason === "interrupt") return;
29225
29609
  aborted = true;
29226
29610
  killChild(child);
29227
29611
  };
29228
29612
  const onYield = () => {
29229
- if (settled) return;
29613
+ if (settled2) return;
29230
29614
  if (child.exitCode !== null || child.signalCode !== null) {
29231
29615
  void done(child.exitCode);
29232
29616
  return;
@@ -29243,12 +29627,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29243
29627
  channelTarget: ctx.channelTarget ?? "",
29244
29628
  queryAbortSignal: ctx.queryAbortSignal ?? signal
29245
29629
  });
29246
- settled = true;
29630
+ settled2 = true;
29247
29631
  cleanup();
29248
29632
  resolve12({ content: `Waiting yielded for new user input. Command running in background with ID: ${task.id}. Output is being written to: ${task.outputFile}. Use TaskOutput or Read to observe it; do not restart the command.` });
29249
29633
  };
29250
29634
  const timer = setTimeout(() => {
29251
- if (!settled) {
29635
+ if (!settled2) {
29252
29636
  aborted = true;
29253
29637
  killChild(child);
29254
29638
  }
@@ -29278,7 +29662,7 @@ init_dependencies();
29278
29662
  init_basis_check();
29279
29663
  init_relationship_notice_check();
29280
29664
  init_scope();
29281
- import { join as join24, resolve as resolve8 } from "node:path";
29665
+ import { join as join25, resolve as resolve8 } from "node:path";
29282
29666
  var contextIdentity = (context) => canonicalJson({
29283
29667
  scopeId: context.scopeId,
29284
29668
  basisRefs: context.basisRefs,
@@ -29291,17 +29675,17 @@ function createNotificationStateReader() {
29291
29675
  const databases = /* @__PURE__ */ new Map();
29292
29676
  const checkers = /* @__PURE__ */ new Map();
29293
29677
  const open3 = (path35) => {
29294
- const key2 = resolve8(path35);
29295
- let db2 = databases.get(key2);
29678
+ const key4 = resolve8(path35);
29679
+ let db2 = databases.get(key4);
29296
29680
  if (!db2) {
29297
- db2 = new DatabaseSync11(key2, { readOnly: true });
29681
+ db2 = new DatabaseSync11(key4, { readOnly: true });
29298
29682
  try {
29299
29683
  db2.exec("BEGIN");
29300
29684
  } catch (error) {
29301
29685
  db2.close();
29302
29686
  throw error;
29303
29687
  }
29304
- databases.set(key2, db2);
29688
+ databases.set(key4, db2);
29305
29689
  }
29306
29690
  return db2;
29307
29691
  };
@@ -29333,7 +29717,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29333
29717
  let proactive;
29334
29718
  let calendar;
29335
29719
  try {
29336
- memory = open3(join24(runtime.stateDir, "mem7", "index", "mem7.db"));
29720
+ memory = open3(join25(runtime.stateDir, "mem7", "index", "mem7.db"));
29337
29721
  const scope = memory.prepare("SELECT * FROM memory_scopes WHERE scope_id=?").get(context.scopeId);
29338
29722
  if (!scope) {
29339
29723
  return { state: "blocked", reason: "MEMORY_NOTIFICATION_SCOPE_MISSING", redact: true };
@@ -29360,7 +29744,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29360
29744
  }
29361
29745
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
29362
29746
  const ledgerDependencies = new MemoryDependencies(memory, (operation) => operation());
29363
- proactive = open3(join24(runtime.workspace, ".proactive", "proactive.db"));
29747
+ proactive = open3(join25(runtime.workspace, ".proactive", "proactive.db"));
29364
29748
  for (const id3 of Object.keys(context.actionVersions)) {
29365
29749
  const action = proactive.prepare("SELECT scope_id,intent_id FROM actions WHERE id=?").get(id3);
29366
29750
  if (!action || action.scope_id !== context.scopeId) return { state: "blocked", reason: "MEMORY_NOTIFICATION_ACTION_MISMATCH", redact: true };
@@ -29414,7 +29798,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29414
29798
  }
29415
29799
  if (route.hostDelivery) {
29416
29800
  if (!proactive) {
29417
- proactive = open3(join24(runtime.workspace, ".proactive", "proactive.db"));
29801
+ proactive = open3(join25(runtime.workspace, ".proactive", "proactive.db"));
29418
29802
  }
29419
29803
  const receipt = proactive.prepare("SELECT * FROM proactive_host_deliveries WHERE delivery_key=?").get(route.hostDelivery.key);
29420
29804
  if (!receipt || contextIdentity(JSON.parse(receipt.context_json)) !== contextIdentity(context)) {
@@ -29425,7 +29809,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29425
29809
  if (["blocked", "delivery_unknown"].includes(receipt.state)) return { state: receipt.state, reason: receipt.reason ?? receipt.state };
29426
29810
  }
29427
29811
  if (context.calendarBinding) {
29428
- calendar = open3(join24(runtime.workspace, ".calendar", "calendar.db"));
29812
+ calendar = open3(join25(runtime.workspace, ".calendar", "calendar.db"));
29429
29813
  const binding = context.calendarBinding;
29430
29814
  const rows = calendar.prepare("SELECT state,closure FROM calendar_dispatches WHERE scope_id=? AND event_id=? AND occurrence_id=?").all(context.scopeId, binding.eventId, binding.occurrenceId);
29431
29815
  if (rows.some((row) => ["started", "delivery_unknown"].includes(row.state) && !row.closure)) {
@@ -30162,6 +30546,7 @@ var QueryEngine = class _QueryEngine {
30162
30546
  const mailbox = this.steerMailbox;
30163
30547
  this.attachmentScopeId = perTurnOptions?.attachmentScopeId;
30164
30548
  const queryId = this.steerQueryId;
30549
+ const hasPendingUserInput = () => this.pendingSteers.some((input) => !input.attachment);
30165
30550
  this.steerHistoryIds = new Set(messages.flatMap((m) => "steerInput" in m && m.steerInput ? [m.steerInput.id] : "attachment" in m ? [m.uuid] : []));
30166
30551
  try {
30167
30552
  for (const input of mailbox?.pending(this.steerRoute ?? void 0) ?? []) {
@@ -30193,8 +30578,15 @@ var QueryEngine = class _QueryEngine {
30193
30578
  this.compactConfig.systemOverheadTokens = overhead ?? this.compactConfig.systemOverheadTokens;
30194
30579
  }
30195
30580
  const activeSystemStable = perTurnSystemStable || this.resolveOpt(this.options.systemStable) || this.resolveOpt(this.options.systemPrompt);
30196
- for (const m of messages) if ("role" in m && hasImage(m) && !m.imageInput) m.imageInput = { id: randomUUID16(), observed: true };
30581
+ for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID16(), observed: hasImage(m) };
30197
30582
  let currentMessages = [...messages];
30583
+ const stopUserMessages = [];
30584
+ const stopToolResults = [];
30585
+ const collectStopEvidence = !this.options.skipStopHook && !perTurnEmotion;
30586
+ const currentUser = collectStopEvidence ? messages.findLast((m) => "role" in m && m.role === "user") : void 0;
30587
+ if (currentUser && "role" in currentUser) {
30588
+ stopUserMessages.push(currentUser.memoryOriginalText ?? (typeof currentUser.content === "string" ? currentUser.content : currentUser.content.filter((b) => b.type === "text").map((b) => b.text).join("\n")));
30589
+ }
30198
30590
  const oldGatePattern = /^Tool "([^"]+)" is permanently unavailable in this channel\. Do NOT retry it or any other tool — answer the user directly in plain speech now\.$/;
30199
30591
  const historicalGateTools = new Set(currentMessages.flatMap((m) => {
30200
30592
  if (!("role" in m) || m.role !== "tool" || typeof m.content !== "string") return [];
@@ -30273,6 +30665,7 @@ var QueryEngine = class _QueryEngine {
30273
30665
  };
30274
30666
  let turnCount = 0;
30275
30667
  let recallContinuation = false;
30668
+ const stopReplies = [];
30276
30669
  let toolCalls = [];
30277
30670
  let streamRetries = 0;
30278
30671
  let maxTokensOverride = null;
@@ -30329,6 +30722,7 @@ var QueryEngine = class _QueryEngine {
30329
30722
  }
30330
30723
  const steerMsg = buildSteerMessage(input);
30331
30724
  currentMessages.push(steerMsg);
30725
+ if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
30332
30726
  this.steerHistoryIds.add(input.id);
30333
30727
  steerConsumedThisTurn = true;
30334
30728
  yield {
@@ -30584,9 +30978,13 @@ var QueryEngine = class _QueryEngine {
30584
30978
  try {
30585
30979
  wholeQueryAbort.signal.throwIfAborted();
30586
30980
  const view = normalizeMessagesForAPI(currentMessages).map((m) => {
30587
- if (!Array.isArray(m.content) || !m.imageInput?.observed || queryInputs?.includes("image") || !queryModelRef) return m;
30588
- const blocks = m.content.filter((b) => b.type !== "image" && b.type !== "image_ref");
30589
- return { ...m, content: blocks.length ? blocks : "[previous image omitted]" };
30981
+ if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
30982
+ const blocks = m.content.filter((b) => {
30983
+ if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
30984
+ if (b.type === "video") return !!queryInputs?.includes("video");
30985
+ return true;
30986
+ });
30987
+ return { ...m, content: blocks.length ? blocks : "[previous media omitted]" };
30590
30988
  });
30591
30989
  const apiMessages = await materializeImageMessages(view, this.options.imageAssets, wholeQueryAbort.signal);
30592
30990
  wholeQueryAbort.signal.throwIfAborted();
@@ -30614,7 +31012,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
30614
31012
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
30615
31013
 
30616
31014
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30617
- if (!this.options.agentLabel || this.options.agentLabel === "main") {
31015
+ if (process.env.ENGINE_DUMP_REQUEST === "1" && (!this.options.agentLabel || this.options.agentLabel === "main")) {
30618
31016
  try {
30619
31017
  const ws = process.env.ENGINE7_WORKSPACE;
30620
31018
  if (ws) {
@@ -30747,7 +31145,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30747
31145
  }
30748
31146
  });
30749
31147
  if (!requestComplete || (toolCalls.length ? !validToolCalls : !textContent.trim()) || ["length", "max_tokens", "MAX_TOKENS", "incomplete", "content_filter"].includes(responseStopReason ?? "")) return;
30750
- const inputs = currentMessages.filter((m) => "role" in m && hasImage(m) && !m.imageInput?.observed);
31148
+ const inputs = currentMessages.filter((m) => "role" in m && hasMedia(m) && !m.imageInput?.observed);
30751
31149
  if (!inputs.length) return;
30752
31150
  return {
30753
31151
  type: "image_observed",
@@ -30836,20 +31234,22 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30836
31234
  if (toolCalls.length === 0) {
30837
31235
  const carryReply = () => {
30838
31236
  if (!this.pendingSteers.some((input) => input.attachment)) return null;
31237
+ const replyId = randomUUID16();
30839
31238
  const reply = msg.assistant(textContent);
30840
31239
  if (turnThinking) reply.reasoning_content = turnThinking;
30841
31240
  if (turnThinkingSig) reply.thinking_signature = turnThinkingSig;
30842
31241
  if (turnResponsesReasoning) reply.responses_reasoning = turnResponsesReasoning;
30843
31242
  currentMessages.push(reply);
30844
- finalText = textContent;
31243
+ finalText = "";
31244
+ if (collectStopEvidence) stopReplies.push(textContent);
30845
31245
  recallContinuation = true;
30846
31246
  turnThinking = turnThinkingSig = turnResponsesReasoning = "";
30847
- return { type: "history", messages: [reply] };
31247
+ return [{ type: "history", messages: [reply], replyId }, { type: "reply", content: textContent, replyId }];
30848
31248
  };
30849
31249
  if (responseStopReason === "max_tokens" || responseStopReason === "length") {
30850
31250
  if (this.pendingSteers.length > 0) {
30851
31251
  const carried = carryReply();
30852
- if (carried) yield carried;
31252
+ if (carried) yield* carried;
30853
31253
  continue;
30854
31254
  }
30855
31255
  finalText = textContent;
@@ -30859,7 +31259,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30859
31259
  if (this.options.skipStopHook || perTurnEmotion) {
30860
31260
  if (this.pendingSteers.length > 0) {
30861
31261
  const carried = carryReply();
30862
- if (carried) yield carried;
31262
+ if (carried) yield* carried;
30863
31263
  continue;
30864
31264
  }
30865
31265
  finalText = textContent;
@@ -30876,9 +31276,14 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30876
31276
  // 'group' | 'dm',Stop hook 用来判断是否跳过 group
30877
31277
  cwd: context?.workspace || "",
30878
31278
  source: typeof context?.source === "string" ? context.source : "",
30879
- executionContext: context?.executionContext
31279
+ executionContext: context?.executionContext,
31280
+ stopTurnEvidence: { userMessages: stopUserMessages, toolResults: stopToolResults }
30880
31281
  };
30881
- const stopResult = await executeStopHooks(stopCtx, ac.signal, textContent);
31282
+ const stopResult = await executeStopHooks(
31283
+ stopCtx,
31284
+ ac.signal,
31285
+ stopReplies.length ? [...stopReplies, textContent].join("\n\n") : textContent
31286
+ );
30882
31287
  if (stopResult.preventContinuation) {
30883
31288
  console.log(`[hook] Stop blocked: ${stopResult.stopReason || "no reason"}`);
30884
31289
  if (stopResult.additionalContexts?.length) {
@@ -30893,7 +31298,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30893
31298
  }
30894
31299
  if (this.pendingSteers.length > 0) {
30895
31300
  const carried = carryReply();
30896
- if (carried) yield carried;
31301
+ if (carried) yield* carried;
30897
31302
  continue;
30898
31303
  }
30899
31304
  finalText = textContent;
@@ -30973,6 +31378,12 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30973
31378
  turnResponsesReasoning = "";
30974
31379
  currentMessages.push(gateAssistant);
30975
31380
  currentMessages.push(...blockResults);
31381
+ if (collectStopEvidence) for (let i = 0; i < toolCalls.length; i++) stopToolResults.push({
31382
+ tool: toolCalls[i].function.name,
31383
+ toolCallId: toolCalls[i].id,
31384
+ summary: String(blockResults[i].content),
31385
+ isError: true
31386
+ });
30976
31387
  for (const g of gatedCalls) {
30977
31388
  yield { type: "tool_result", tool: g.call.function?.name, tool_call_id: g.call.id, summary: g.text.slice(0, 200), isError: true };
30978
31389
  }
@@ -30993,7 +31404,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30993
31404
  try {
30994
31405
  this.phase = "tools";
30995
31406
  this.toolYield = new AbortController();
30996
- if (this.pendingSteers.length) this.toolYield.abort("steer");
31407
+ if (hasPendingUserInput()) this.toolYield.abort("steer");
30997
31408
  toolCtx.yieldSignal = this.toolYield.signal;
30998
31409
  toolRes = await executeTools(toolCalls, ac.signal, { ...toolCtx, toolResultHistory: currentMessages });
30999
31410
  } finally {
@@ -31002,6 +31413,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31002
31413
  if (vcDelivery) await vcDelivery;
31003
31414
  }
31004
31415
  const { messages: toolResults, summaries } = toolRes;
31416
+ if (collectStopEvidence) stopToolResults.push(...summaries);
31005
31417
  for (const s of summaries) {
31006
31418
  try {
31007
31419
  const postResult = await executePostToolUseHooks(s.tool, {}, s.summary, hookCtx, ac.signal);
@@ -31103,7 +31515,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31103
31515
  this.toolYield = null;
31104
31516
  this.phase = "idle";
31105
31517
  this.loopAlive = false;
31106
- if (this.pendingSteers.length > 0 && completionReason !== "aborted") {
31518
+ if (hasPendingUserInput() && completionReason !== "aborted") {
31107
31519
  console.warn(`${this.logPrefix} [steer] ${this.pendingSteers.length} pending input(s) retained for same-route recovery (completionReason=${completionReason ?? "completed"})`);
31108
31520
  }
31109
31521
  this.pendingSteers.length = 0;
@@ -31228,7 +31640,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31228
31640
  }
31229
31641
  }
31230
31642
  this.pendingSteers.push(receipt.input);
31231
- this.toolYield?.abort("steer");
31643
+ if (!receipt.input.attachment) this.toolYield?.abort("steer");
31232
31644
  if (opts.mode === "queue") {
31233
31645
  console.log(`${this.logPrefix} Steer queued (${this.pendingSteers.length} pending \u2014 next turn, no interrupt)`);
31234
31646
  return true;
@@ -31348,8 +31760,8 @@ function defaultWriteMemoryNote(workspace) {
31348
31760
  }
31349
31761
  function makeSubmitToMain(engineDeps) {
31350
31762
  return (text2) => {
31351
- const sessions = engineDeps.deps?.sessions;
31352
- const mainSessionId = sessions?.getSessionId?.("scope:main");
31763
+ const sessions2 = engineDeps.deps?.sessions;
31764
+ const mainSessionId = sessions2?.getSessionId?.("scope:main");
31353
31765
  if (!mainSessionId) {
31354
31766
  console.warn("[whatsapp/patrol] \u65E0\u4E3B session\uFF08scope:main \u672A\u5EFA\u7ACB\uFF09\uFF0C\u26A0\uFE0F \u5347\u7EA7\u6295\u9012\u4E22\u5F03");
31355
31767
  return;
@@ -31382,10 +31794,10 @@ function makeReadOnlyAgentRunner(engineDeps) {
31382
31794
  });
31383
31795
  const sessionId = base.sessions.getOrCreateSessionId(PATROL_SESSION_KEY);
31384
31796
  return new Promise((resolve12, reject) => {
31385
- let settled = false;
31797
+ let settled2 = false;
31386
31798
  const timeout = setTimeout(() => {
31387
- if (settled) return;
31388
- settled = true;
31799
+ if (settled2) return;
31800
+ settled2 = true;
31389
31801
  reject(new Error(`wa-patrol \u5DE1\u68C0\u8D85\u65F6\uFF08${PATROL_TIMEOUT_MS / 6e4}min\uFF09\u2014\u2014\u72B6\u6001\u4E0D\u63A8\u8FDB\uFF0C\u4E0B\u8F6E\u91CD\u5DE1`));
31390
31802
  }, PATROL_TIMEOUT_MS);
31391
31803
  const ok = engineDeps.dispatcher.submitMessage({
@@ -31399,21 +31811,21 @@ function makeReadOnlyAgentRunner(engineDeps) {
31399
31811
  deps: { ...base, engine: patrolEngine },
31400
31812
  callbacks: {
31401
31813
  onResult: (content) => {
31402
- if (settled) return;
31403
- settled = true;
31814
+ if (settled2) return;
31815
+ settled2 = true;
31404
31816
  clearTimeout(timeout);
31405
31817
  resolve12(content);
31406
31818
  },
31407
31819
  onError: (err) => {
31408
- if (settled) return;
31409
- settled = true;
31820
+ if (settled2) return;
31821
+ settled2 = true;
31410
31822
  clearTimeout(timeout);
31411
31823
  reject(new Error(err));
31412
31824
  }
31413
31825
  }
31414
31826
  });
31415
- if (ok === false && !settled) {
31416
- settled = true;
31827
+ if (ok === false && !settled2) {
31828
+ settled2 = true;
31417
31829
  clearTimeout(timeout);
31418
31830
  reject(new Error("dispatcher \u62D2\u7EDD wa-patrol \u63D0\u4EA4\uFF08guard \u5FD9\uFF09\u2014\u2014\u4E0B\u8F6E\u91CD\u5DE1"));
31419
31831
  }
@@ -32602,10 +33014,10 @@ var DingStreamClient = class extends EventEmitter {
32602
33014
  return;
32603
33015
  }
32604
33016
  this.ws = ws;
32605
- let settled = false;
33017
+ let settled2 = false;
32606
33018
  const settle = (err) => {
32607
- if (settled) return;
32608
- settled = true;
33019
+ if (settled2) return;
33020
+ settled2 = true;
32609
33021
  this.clearHeartbeat();
32610
33022
  if (err) reject(err);
32611
33023
  else resolve12();
@@ -32626,8 +33038,8 @@ var DingStreamClient = class extends EventEmitter {
32626
33038
  });
32627
33039
  ws.on("error", (err) => {
32628
33040
  this.emit("error", err instanceof Error ? err : new Error(String(err)));
32629
- if (!settled) {
32630
- settled = true;
33041
+ if (!settled2) {
33042
+ settled2 = true;
32631
33043
  this.clearHeartbeat();
32632
33044
  reject(err);
32633
33045
  return;
@@ -33302,18 +33714,18 @@ var DingTalkAdapter = class _DingTalkAdapter {
33302
33714
  /** per-card 流式串行链(无间隔闸)——throttle 保证 ≥300ms 节奏,但 HTTP 慢时相邻两次
33303
33715
  * fire 仍可能并发(后发先到→旧内容覆盖新内容);openclaw 的 in-flight 保护同语义 */
33304
33716
  cardStreamQueues = /* @__PURE__ */ new Map();
33305
- streamCardSerial(key2, outTrackId, content, isFinalize) {
33306
- const prev = this.cardStreamQueues.get(key2) ?? Promise.resolve();
33717
+ streamCardSerial(key4, outTrackId, content, isFinalize) {
33718
+ const prev = this.cardStreamQueues.get(key4) ?? Promise.resolve();
33307
33719
  const next = prev.then(
33308
33720
  () => this.streamCard(outTrackId, content, isFinalize),
33309
33721
  () => this.streamCard(outTrackId, content, isFinalize)
33310
33722
  );
33311
- this.cardStreamQueues.set(key2, next.then(() => {
33723
+ this.cardStreamQueues.set(key4, next.then(() => {
33312
33724
  }, () => {
33313
33725
  }));
33314
33726
  if (this.cardStreamQueues.size > 200) {
33315
33727
  const drop = this.cardStreamQueues.keys().next().value;
33316
- if (drop !== void 0 && drop !== key2) this.cardStreamQueues.delete(drop);
33728
+ if (drop !== void 0 && drop !== key4) this.cardStreamQueues.delete(drop);
33317
33729
  }
33318
33730
  return next;
33319
33731
  }
@@ -33322,10 +33734,10 @@ var DingTalkAdapter = class _DingTalkAdapter {
33322
33734
  * API,双重节流会把打字机压成"两秒一跳"(openclaw 实测:300ms 直打才流畅)。保序由
33323
33735
  * throttle(last-write-wins)+ per-card 串行链保证。 */
33324
33736
  async editPreview(handle, content, agentName, isFinal) {
33325
- const key2 = `${handle.channelId}:${handle.messageId}`;
33737
+ const key4 = `${handle.channelId}:${handle.messageId}`;
33326
33738
  try {
33327
- await this.editThrottle.submit(key2, { content, agentName, isFinal: !!isFinal }, async (r) => {
33328
- await this.streamCardSerial(key2, handle.messageId, r.content, r.isFinal);
33739
+ await this.editThrottle.submit(key4, { content, agentName, isFinal: !!isFinal }, async (r) => {
33740
+ await this.streamCardSerial(key4, handle.messageId, r.content, r.isFinal);
33329
33741
  if (r.isFinal) {
33330
33742
  await this.putCardData(handle.messageId, "3");
33331
33743
  await this.notifyGroupFinalized(handle.channelId, handle.messageId).catch(() => {
@@ -33628,10 +34040,10 @@ var WecomStreamClient = class extends EventEmitter2 {
33628
34040
  return;
33629
34041
  }
33630
34042
  this.ws = ws;
33631
- let settled = false;
34043
+ let settled2 = false;
33632
34044
  const settle = (err) => {
33633
- if (settled) return;
33634
- settled = true;
34045
+ if (settled2) return;
34046
+ settled2 = true;
33635
34047
  this.clearHeartbeat();
33636
34048
  const wasSubscribed = this.everSubscribed;
33637
34049
  this.subscribed = false;
@@ -33657,7 +34069,7 @@ var WecomStreamClient = class extends EventEmitter2 {
33657
34069
  ws.on("error", (err) => {
33658
34070
  const e = err instanceof Error ? err : new Error(String(err));
33659
34071
  this.emit("error", e);
33660
- if (!settled) {
34072
+ if (!settled2) {
33661
34073
  settle(e);
33662
34074
  return;
33663
34075
  }
@@ -33948,9 +34360,9 @@ function wecomTextFormat(text2, format2 = "markdown") {
33948
34360
  }
33949
34361
  function decryptWecomMedia(buf, aeskey) {
33950
34362
  const padded = aeskey + "=".repeat((4 - aeskey.length % 4) % 4);
33951
- const key2 = Buffer.from(padded, "base64");
33952
- if (key2.length !== 32) throw new Error(`wecom media aeskey \u89E3\u7801\u540E\u5E94\u4E3A 32 \u5B57\u8282\uFF0C\u5B9E\u5F97 ${key2.length}`);
33953
- const d = createDecipheriv3("aes-256-cbc", key2, key2.subarray(0, 16));
34363
+ const key4 = Buffer.from(padded, "base64");
34364
+ if (key4.length !== 32) throw new Error(`wecom media aeskey \u89E3\u7801\u540E\u5E94\u4E3A 32 \u5B57\u8282\uFF0C\u5B9E\u5F97 ${key4.length}`);
34365
+ const d = createDecipheriv3("aes-256-cbc", key4, key4.subarray(0, 16));
33954
34366
  d.setAutoPadding(false);
33955
34367
  const raw = Buffer.concat([d.update(buf), d.final()]);
33956
34368
  const pad = raw[raw.length - 1];
@@ -34249,22 +34661,22 @@ var WecomAdapter = class {
34249
34661
  this.emitInbound(parsed.inbound);
34250
34662
  return;
34251
34663
  }
34252
- const key2 = `${parsed.chatId}:${parsed.senderId}`;
34253
- const cur = this.pending.get(key2);
34664
+ const key4 = `${parsed.chatId}:${parsed.senderId}`;
34665
+ const cur = this.pending.get(key4);
34254
34666
  if (cur) {
34255
34667
  cur.parsed.inbound.content = `${cur.parsed.inbound.content}
34256
34668
  ${parsed.inbound.content}`;
34257
34669
  cur.version++;
34258
34670
  } else {
34259
- this.pending.set(key2, { parsed, version: 1 });
34671
+ this.pending.set(key4, { parsed, version: 1 });
34260
34672
  }
34261
- const entry = this.pending.get(key2);
34673
+ const entry = this.pending.get(key4);
34262
34674
  const v = entry.version;
34263
34675
  void this.sleepImpl(windowMs).then(() => {
34264
- const live = this.pending.get(key2);
34676
+ const live = this.pending.get(key4);
34265
34677
  if (!live) return;
34266
34678
  if (live.version !== v) return;
34267
- this.pending.delete(key2);
34679
+ this.pending.delete(key4);
34268
34680
  this.emitInbound(live.parsed.inbound);
34269
34681
  });
34270
34682
  }
@@ -34278,10 +34690,10 @@ ${parsed.inbound.content}`;
34278
34690
  }
34279
34691
  /** 立即投递并清空某会话挂起的合并片段(媒体直投前的顺序保护,review) */
34280
34692
  flushPending(chatId, senderId) {
34281
- const key2 = `${chatId}:${senderId}`;
34282
- const live = this.pending.get(key2);
34693
+ const key4 = `${chatId}:${senderId}`;
34694
+ const live = this.pending.get(key4);
34283
34695
  if (!live) return;
34284
- this.pending.delete(key2);
34696
+ this.pending.delete(key4);
34285
34697
  this.emitInbound(live.parsed.inbound);
34286
34698
  }
34287
34699
  // === 出站(spec §五) ===
@@ -34675,8 +35087,8 @@ import { randomUUID as randomUUID20 } from "node:crypto";
34675
35087
 
34676
35088
  // src/continuity/gateway-channel.ts
34677
35089
  init_gateway_media();
34678
- import { mkdtempSync, writeFileSync as writeFileSync13, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
34679
- import { join as join29 } from "node:path";
35090
+ import { mkdtempSync, writeFileSync as writeFileSync14, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
35091
+ import { join as join30 } from "node:path";
34680
35092
  import { tmpdir as tmpdir3 } from "node:os";
34681
35093
  function splitChannelGatewayText(text2, channel) {
34682
35094
  if (typeof text2 !== "string" || Buffer.byteLength(text2) > 1024 * 1024) throw new Error("TRAVEL_GATEWAY_REPLY_LIMIT");
@@ -34731,9 +35143,9 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
34731
35143
  if (!media) await adapter.send(packet.target, packet.text, { replyTo: packet.replyTo });
34732
35144
  else {
34733
35145
  if (!adapter.sendFile) throw new Error("TRAVEL_GATEWAY_MEDIA_UNAVAILABLE");
34734
- const directory2 = realpathSync5(mkdtempSync(join29(tmpdir3(), "e7-gateway-media-"))), file2 = join29(directory2, packet.filename);
35146
+ const directory2 = realpathSync5(mkdtempSync(join30(tmpdir3(), "e7-gateway-media-"))), file2 = join30(directory2, packet.filename);
34735
35147
  try {
34736
- writeFileSync13(file2, media.bytes, { mode: 384 });
35148
+ writeFileSync14(file2, media.bytes, { mode: 384 });
34737
35149
  await adapter.sendFile(packet.target, packet.text, { path: file2, filename: packet.filename, mimeType: packet.mimeType, voiceDurationSec: packet.voiceDurationSec });
34738
35150
  } finally {
34739
35151
  rmSync2(directory2, { recursive: true, force: true });
@@ -34790,8 +35202,8 @@ function createFeishuGatewayDispatcher(options) {
34790
35202
  const timestamp = Number(message.create_time);
34791
35203
  if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error("TRAVEL_FEISHU_INVALID_EVENT");
34792
35204
  const content = JSON.parse(String(message.content)), descriptors = [];
34793
- const add = (key2, type, filename, contentType) => {
34794
- if (typeof key2 === "string" && key2) descriptors.push({ key: key2, type, filename, contentType });
35205
+ const add = (key4, type, filename, contentType) => {
35206
+ if (typeof key4 === "string" && key4) descriptors.push({ key: key4, type, filename, contentType });
34795
35207
  };
34796
35208
  if (message.message_type === "image") add(content.image_key, "image", "image.jpg", "image/jpeg");
34797
35209
  if (["file", "audio", "media"].includes(message.message_type)) add(content.file_key, "file", basename6(String(content.file_name ?? (message.message_type === "audio" ? "audio.opus" : message.message_type === "media" ? "video.mp4" : "file"))), message.message_type === "audio" ? "audio/opus" : message.message_type === "media" ? "video/mp4" : "application/octet-stream");
@@ -34929,9 +35341,9 @@ function createFeishuGatewayPlatform(options) {
34929
35341
  return { messageId: result.data.message_id };
34930
35342
  });
34931
35343
  },
34932
- downloadResource: async (messageId, key2, type) => {
35344
+ downloadResource: async (messageId, key4, type) => {
34933
35345
  if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
34934
- const response = await client.im.messageResource.get({ path: { message_id: messageId, file_key: key2 }, params: { type } });
35346
+ const response = await client.im.messageResource.get({ path: { message_id: messageId, file_key: key4 }, params: { type } });
34935
35347
  const stream = response.getReadableStream(), chunks = [];
34936
35348
  let bytes2 = 0;
34937
35349
  try {
@@ -34966,7 +35378,7 @@ function createRemoteTravelChannel(block, stateDir, channel = "feishu") {
34966
35378
  if (!stateDir || !runtimeAuthorityFor(stateDir)) throw new Error("TRAVEL_GATEWAY_RUNTIME_REQUIRED");
34967
35379
  validateTravelChannels(stateDir, { [channel]: block });
34968
35380
  const tls2 = block.gatewayTls;
34969
- if (!tls2 || ["caFile", "certFile", "keyFile"].some((key2) => typeof tls2[key2] !== "string" || !tls2[key2])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35381
+ if (!tls2 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls2[key4] !== "string" || !tls2[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
34970
35382
  const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls2.caFile, 1024 * 1024), cert: readPrivateFile(tls2.certFile, 1024 * 1024), key: readPrivateFile(tls2.keyFile, 16384) });
34971
35383
  return new RemoteTravelChannel({ client, channel, permit: () => runtimeAuthorityFor(stateDir).assert("INPUT"), pollIntervalMs: block.gatewayPollIntervalMs });
34972
35384
  }
@@ -35172,9 +35584,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
35172
35584
  const adapter = manager.getAdapter("chan7");
35173
35585
  if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
35174
35586
  const safeName = path33.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
35175
- const key2 = createHash35("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
35587
+ const key4 = createHash35("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
35176
35588
  try {
35177
- adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key2);
35589
+ adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
35178
35590
  } catch (e) {
35179
35591
  console.warn("[library] delivered copy not archived: " + e.message);
35180
35592
  }
@@ -35408,7 +35820,7 @@ var ChannelManager = class {
35408
35820
  const changes = [];
35409
35821
  for (const name of MANAGED_CHANNEL_NAMES) {
35410
35822
  const block = config[name];
35411
- const key2 = JSON.stringify(block ?? null);
35823
+ const key4 = JSON.stringify(block ?? null);
35412
35824
  const cur = this.managed.get(name);
35413
35825
  const enabled = block?.enabled === true;
35414
35826
  if (!enabled && !cur) continue;
@@ -35417,7 +35829,7 @@ var ChannelManager = class {
35417
35829
  changes.push(`${name}: removed`);
35418
35830
  continue;
35419
35831
  }
35420
- if (cur && cur.key === key2) continue;
35832
+ if (cur && cur.key === key4) continue;
35421
35833
  if (cur) {
35422
35834
  if (runningQueries.includes(name)) {
35423
35835
  console.log(`[channels] ${name} rebuild deferred (query in flight)`);
@@ -35429,7 +35841,7 @@ var ChannelManager = class {
35429
35841
  const adapter = this.buildManagedAdapter(name, block);
35430
35842
  if (!adapter) continue;
35431
35843
  this.adapters.push(adapter);
35432
- this.managed.set(name, { adapter, key: key2 });
35844
+ this.managed.set(name, { adapter, key: key4 });
35433
35845
  this.wireAdapter(adapter);
35434
35846
  if (adapter.registerCommands && this.registeredCommands.size > 0) {
35435
35847
  void adapter.registerCommands([...this.registeredCommands.values()]).catch((e) => console.error(`[channels] ${name} registerCommands failed: ${e.message}`));
@@ -35672,7 +36084,7 @@ function tls(config) {
35672
36084
  return { ca: readPrivateFile(path34(config?.caFile), 1024 * 1024), cert: readPrivateFile(path34(config?.certFile), 1024 * 1024), key: readPrivateFile(path34(config?.keyFile), 16384) };
35673
36085
  }
35674
36086
  async function startTravelGateway(config) {
35675
- if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key2) => config.identity[key2] !== config.keyService.identity[key2])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36087
+ if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key4) => config.identity[key4] !== config.keyService.identity[key4])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
35676
36088
  if (!Number.isSafeInteger(config.port) || config.port < 0 || config.port > 65535 || typeof config.host !== "string" || !config.host) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
35677
36089
  for (const [name, value] of Object.entries(config.channels ?? {})) if (value?.enabled && !["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
35678
36090
  const feishuIngress = config.ingressEnabled !== false && config.feishu?.ingressEnabled !== false && config.channels?.feishu?.enabled !== false;
@@ -35725,7 +36137,7 @@ async function startTravelGateway(config) {
35725
36137
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
35726
36138
  for (const credential of Object.values(config.allowedPeers)) {
35727
36139
  const principal = authority.authenticate(String(credential));
35728
- if (["tenantId", "companionId", "seatId"].some((key2) => principal[key2] !== config.identity[key2]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36140
+ if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
35729
36141
  }
35730
36142
  store = new TravelGatewayStore({ directory: path34(config.gatewayDir), identity: config.identity, objects, authority });
35731
36143
  await store.migrateStoredInputs();
@@ -35775,9 +36187,9 @@ async function startTravelGateway(config) {
35775
36187
  assertIngress: assertKey,
35776
36188
  authorizeStop: (sender) => Array.isArray(config.feishu.stopAllowedUserIds) && config.feishu.stopAllowedUserIds.includes(sender.sender_id?.open_id),
35777
36189
  onReceivedTyping: (chatId, openId, messageId) => platform.startChatTyping(chatId, openId, messageId),
35778
- downloadResource: async (messageId, key2, type) => {
36190
+ downloadResource: async (messageId, key4, type) => {
35779
36191
  assertKey();
35780
- return platform.downloadResource(messageId, key2, type);
36192
+ return platform.downloadResource(messageId, key4, type);
35781
36193
  }
35782
36194
  });
35783
36195
  if (config.channels && config.ingressEnabled !== false) {