engine7 7.1.142 → 7.1.144

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2294,15 +2294,15 @@ var init_context_time = __esm({
2294
2294
  });
2295
2295
 
2296
2296
  // 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");
2297
+ function knowledgeCutoff(db2, scope, request4) {
2298
+ if (request4.knownAt === void 0 && request4.knownAtRevision === void 0) return void 0;
2299
+ if (request4.knownAt !== void 0 && request4.knownAtRevision !== void 0) throw new Error("AMBIGUOUS_KNOWLEDGE_TIME");
2300
2300
  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);
2301
+ const time = request4.knownAt === void 0 ? null : instant(request4.knownAt);
2302
+ 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
2303
  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
2304
  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)) };
2305
+ return { historyId, time, complete: (!baseline || historyId >= baseline.history_id) && (request4.knownAtRevision === void 0 || request4.knownAtRevision === 0 || Boolean(checkpoint)) };
2306
2306
  }
2307
2307
  function journalEntityCutoff(db2, scope, revision) {
2308
2308
  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);
@@ -7478,13 +7478,13 @@ CREATE TABLE memory_relationship_receipts (
7478
7478
  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
7479
  JOIN fact_assertions a ON a.scope_id=r.scope_id AND a.assertion_id=r.assertion_id
7480
7480
  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]);
7481
+ for (const request4 of requests) {
7482
+ const endpoints = [[request4.subjectId, request4.objectId]];
7483
+ if (request4.direction === "symmetric") endpoints.push([request4.objectId, request4.subjectId]);
7484
7484
  for (const [subject, object3] of endpoints) {
7485
- for (const row of query.all(scopeId(scope), request3.perspectiveEntityId, subject, object3)) {
7485
+ for (const row of query.all(scopeId(scope), request4.perspectiveEntityId, subject, object3)) {
7486
7486
  const value = JSON.parse(row.value_json);
7487
- if (value.contentKind === request3.contentKind && value.temporalScope === request3.temporalScope) ids.add(row.relationship_id);
7487
+ if (value.contentKind === request4.contentKind && value.temporalScope === request4.temporalScope) ids.add(row.relationship_id);
7488
7488
  }
7489
7489
  }
7490
7490
  }
@@ -10415,8 +10415,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10415
10415
  socialInterpretations;
10416
10416
  relationshipCognition;
10417
10417
  relationshipNotices;
10418
- knowledgeCutoff(scope, request3) {
10419
- return knowledgeCutoff(this.db, scope, request3);
10418
+ knowledgeCutoff(scope, request4) {
10419
+ return knowledgeCutoff(this.db, scope, request4);
10420
10420
  }
10421
10421
  knowledgeSnapshot(scope, cutoff) {
10422
10422
  return historicalRows(this.db, scope, "scope", cutoff)[0] ?? { entityRevision: 0, factRevision: 0, contextRevision: 0, sourceSeq: 0, interpretedSeq: 0 };
@@ -10649,6 +10649,35 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10649
10649
  };
10650
10650
  }, scope, version);
10651
10651
  }
10652
+ /** 1123 跨轮去重(md):entry id 由正文决定、所在文件由日期决定——日期判定跨轮漂移时新块落到
10653
+ * 另一个日期文件,appendMd 的原位替换只扫目标文件,旧块留成孤儿(妹妹 1122 重洗 44 处双份)。
10654
+ * 单遍扫 episodes:id 在本轮写入表里、但所在文件 ≠ 本轮目标日期的块删掉,entry_count 同步。
10655
+ * 不在本轮写入表里的条目不碰(别的来源/原生记忆)。 */
10656
+ purgeEpisodeEntries(ownerId, targetDateById) {
10657
+ if (!targetDateById.size) return 0;
10658
+ const dir = join11(this.root, "users", ownerId, "episodes");
10659
+ if (!existsSync5(dir)) return 0;
10660
+ let removed = 0;
10661
+ for (const name of readdirSync(dir)) {
10662
+ const fileDate = /^episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
10663
+ if (!fileDate) continue;
10664
+ const file2 = join11(dir, name);
10665
+ let text2 = readFileSync8(file2, "utf8"), hit = false;
10666
+ for (const m of text2.matchAll(/<!-- entry:(\S+) -->/g)) {
10667
+ const target = targetDateById.get(m[1]);
10668
+ if (target === void 0 || target === fileDate) continue;
10669
+ text2 = text2.replace(new RegExp(`\\n*<!-- entry:${m[1]} -->[\\s\\S]*?<!-- /entry:${m[1]} -->`), "");
10670
+ removed++;
10671
+ hit = true;
10672
+ }
10673
+ if (!hit) continue;
10674
+ text2 = text2.replace(/entry_count: \d+/, `entry_count: ${(text2.match(/<!-- entry:/g) ?? []).length}`);
10675
+ const tmp = `${file2}.${process.pid}.tmp`;
10676
+ writeFileSync6(tmp, text2);
10677
+ renameSync3(tmp, file2);
10678
+ }
10679
+ return removed;
10680
+ }
10652
10681
  appendAtomicFacts(ownerId, dateStr, entries, scope, version) {
10653
10682
  const flat2 = [];
10654
10683
  for (const e of entries) {
@@ -13033,6 +13062,52 @@ var init_session_map = __esm({
13033
13062
  }
13034
13063
  });
13035
13064
 
13065
+ // src/cc-driver/long-http.ts
13066
+ import { request as request3 } from "node:http";
13067
+ function longPostJson(url, body, headers = {}, signal) {
13068
+ const data = Buffer.from(JSON.stringify(body));
13069
+ return new Promise((resolve12, reject) => {
13070
+ const req = request3(url, { method: "POST", headers: { ...headers, "Content-Length": String(data.byteLength) } }, (res) => {
13071
+ const chunks = [];
13072
+ res.on("data", (chunk) => chunks.push(chunk));
13073
+ res.on("error", reject);
13074
+ res.on("end", () => {
13075
+ cleanup();
13076
+ const text2 = Buffer.concat(chunks).toString("utf8");
13077
+ try {
13078
+ resolve12({ status: res.statusCode ?? 0, json: JSON.parse(text2) });
13079
+ } catch {
13080
+ reject(new Error(`\u5BF9\u7AEF\u8FD4\u56DE\u4E86\u975E JSON\uFF08HTTP ${res.statusCode}\uFF09\uFF1A${text2.slice(0, 200)}`));
13081
+ }
13082
+ });
13083
+ });
13084
+ req.on("error", (err) => {
13085
+ cleanup();
13086
+ reject(err);
13087
+ });
13088
+ const onAbort = () => {
13089
+ req.destroy();
13090
+ reject(signal.reason instanceof Error ? signal.reason : new Error("\u8BF7\u6C42\u5DF2\u53D6\u6D88"));
13091
+ };
13092
+ const cleanup = () => {
13093
+ signal?.removeEventListener("abort", onAbort);
13094
+ };
13095
+ if (signal) {
13096
+ if (signal.aborted) {
13097
+ onAbort();
13098
+ return;
13099
+ }
13100
+ signal.addEventListener("abort", onAbort, { once: true });
13101
+ }
13102
+ req.end(data);
13103
+ });
13104
+ }
13105
+ var init_long_http = __esm({
13106
+ "src/cc-driver/long-http.ts"() {
13107
+ "use strict";
13108
+ }
13109
+ });
13110
+
13036
13111
  // src/cc-driver/desktop.ts
13037
13112
  import fs4 from "node:fs";
13038
13113
  import os2 from "node:os";
@@ -13084,14 +13159,13 @@ async function findDesktopTargets(workDir, sessionId) {
13084
13159
  return targets;
13085
13160
  }
13086
13161
  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);
13162
+ const { status, json: result } = await longPostJson(
13163
+ `http://127.0.0.1:${target.port}/ask`,
13164
+ { prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13165
+ { authorization: `Bearer ${target.token}` },
13166
+ signal
13167
+ );
13168
+ if (status !== 200) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
13095
13169
  if (result.sessionId !== target.sessionId || typeof result.text !== "string" || typeof result.isError !== "boolean") {
13096
13170
  throw failure("Desktop CC returned an invalid result");
13097
13171
  }
@@ -13101,6 +13175,7 @@ var registryDir, canonical2, failure, alive;
13101
13175
  var init_desktop = __esm({
13102
13176
  "src/cc-driver/desktop.ts"() {
13103
13177
  "use strict";
13178
+ init_long_http();
13104
13179
  registryDir = () => process.env.CC_DESKTOP_REGISTRY_DIR || path4.join(os2.homedir(), ".engine7", "cc-driver", "desktops");
13105
13180
  canonical2 = (dir) => {
13106
13181
  try {
@@ -13428,6 +13503,8 @@ var init_dep_downloader = __esm({
13428
13503
  });
13429
13504
 
13430
13505
  // src/cc-driver/driver.ts
13506
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync8 } from "node:fs";
13507
+ import { extname, join as join14 } from "node:path";
13431
13508
  function requestError(message, status = 409) {
13432
13509
  return Object.assign(new Error(message), { status });
13433
13510
  }
@@ -14037,14 +14114,16 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14037
14114
  return task;
14038
14115
  }
14039
14116
  };
14040
- CcDriverHub = class {
14117
+ CcDriverHub = class _CcDriverHub {
14041
14118
  map;
14042
14119
  sessions = /* @__PURE__ */ new Map();
14043
14120
  cfg;
14044
14121
  cm;
14122
+ stateDir;
14045
14123
  constructor(cfg, cm, stateDir, predecessor) {
14046
14124
  this.cfg = cfg;
14047
14125
  this.cm = cm;
14126
+ this.stateDir = stateDir;
14048
14127
  this.map = new CcSessionMapStore(stateDir);
14049
14128
  for (const b of cfg.bindings) {
14050
14129
  this.sessions.set(bindingKey(b), new CcDriverSession(b, cm, this.map, predecessor));
@@ -14054,15 +14133,49 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14054
14133
  matches(inbound) {
14055
14134
  return findBinding(inbound, this.cfg) !== null;
14056
14135
  }
14057
- /** 路由一条命中消息(调用方已 matches 过)。附件消息 MVP 不支持,提示。 */
14136
+ /** 落盘附件的体积上限:这条通道只收图/文档,不让大视频把 stateDir 撑爆 */
14137
+ static MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
14138
+ /**
14139
+ * 入站附件落盘(1123 翀哥:「我给你发图片你现在收不到」):CC 会话靠工具读文件——
14140
+ * 图片用 Read 工具直接看,文档走对应 skill。只做落盘+正文附路径,不改 CC 的输入协议。
14141
+ * 落在 <stateDir>/media/inbound(与 my-eyes 等同目录惯例);单个附件失败不影响其它附件和正文。
14142
+ */
14143
+ async saveAttachments(inbound) {
14144
+ const lines = [];
14145
+ const dir = join14(this.stateDir, "media", "inbound");
14146
+ for (const [i, a] of (inbound.attachments ?? []).entries()) {
14147
+ const label = a.filename || `\u9644\u4EF6${i + 1}`;
14148
+ try {
14149
+ if (!a.loadBytes) throw new Error("\u9002\u914D\u5668\u672A\u63D0\u4F9B\u4E0B\u8F7D\u80FD\u529B");
14150
+ if (a.size > _CcDriverHub.MAX_ATTACHMENT_BYTES) throw new Error(`\u6587\u4EF6\u8FC7\u5927\uFF08${a.size} \u5B57\u8282\uFF09\uFF0C\u672A\u843D\u76D8`);
14151
+ const bytes2 = await a.loadBytes();
14152
+ const ext = extname(a.filename || "").toLowerCase().replace(/[^.a-z0-9]/g, "") || (a.contentType.startsWith("image/") ? "." + a.contentType.slice(6).replace("jpeg", "jpg") : "");
14153
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
14154
+ const tail = (inbound.messageId || "msg").replace(/\W/g, "").slice(-8);
14155
+ const file2 = join14(dir, `${stamp}-${tail}-${i + 1}${ext}`);
14156
+ mkdirSync9(dir, { recursive: true });
14157
+ writeFileSync8(file2, bytes2);
14158
+ const how = a.contentType.startsWith("image/") ? "\u56FE\u7247\u2014\u2014\u7528 Read \u5DE5\u5177\u6253\u5F00\u8FD9\u4E2A\u8DEF\u5F84\u5373\u53EF\u770B\u5230" : `\u6587\u4EF6\uFF08${a.contentType || "\u672A\u77E5\u7C7B\u578B"}\uFF09`;
14159
+ lines.push(`${i + 1}. ${label}\uFF0C${how}\uFF1A${file2}`);
14160
+ } catch (err) {
14161
+ lines.push(`${i + 1}. ${label} \u843D\u76D8\u5931\u8D25\uFF1A${err?.message || String(err)}`);
14162
+ }
14163
+ }
14164
+ return `\uFF08\u6536\u5230 ${lines.length} \u4E2A\u9644\u4EF6\uFF0C\u5DF2\u4FDD\u5B58\u5230\u672C\u673A\uFF1A
14165
+ ${lines.join("\n")}\uFF09`;
14166
+ }
14167
+ /** 路由一条命中消息(调用方已 matches 过)。附件先落盘,路径随正文一起进会话(1123)。 */
14058
14168
  route(inbound) {
14059
14169
  const binding = findBinding(inbound, this.cfg);
14060
14170
  if (!binding) return;
14061
14171
  const session = this.sessions.get(bindingKey(binding));
14062
14172
  if (!session) return;
14063
14173
  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`);
14174
+ void this.saveAttachments(inbound).then((note) => session.enqueue(inbound.content.trim() ? `${inbound.content}
14175
+
14176
+ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
14177
+
14178
+ \uFF08\u9644\u4EF6\u5904\u7406\u5931\u8D25\uFF1A${err?.message || String(err)}\uFF09`));
14066
14179
  return;
14067
14180
  }
14068
14181
  session.enqueue(inbound.content);
@@ -14125,6 +14238,7 @@ function registerCcHub(hub2, stateDir, port) {
14125
14238
  var init_handoff = __esm({
14126
14239
  "src/cc-driver/handoff.ts"() {
14127
14240
  "use strict";
14241
+ init_long_http();
14128
14242
  init_router();
14129
14243
  }
14130
14244
  });
@@ -15607,7 +15721,7 @@ __export(persistence_exports, {
15607
15721
  normalizeToUtcIso: () => normalizeToUtcIso
15608
15722
  });
15609
15723
  import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
15610
- import { mkdirSync as mkdirSync10 } from "node:fs";
15724
+ import { mkdirSync as mkdirSync11 } from "node:fs";
15611
15725
  import { basename as basename3, dirname as dirname7, resolve as resolve6 } from "node:path";
15612
15726
  function rowToAction(r) {
15613
15727
  return {
@@ -15745,7 +15859,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
15745
15859
  checkRuntimeReplicationFile(dbPath, registration, Boolean(options.replication));
15746
15860
  this.releaseRuntimeWriter = registration || options.replication ? registerRuntimeWriter(stateDir, "proactive") : void 0;
15747
15861
  try {
15748
- mkdirSync10(dirname7(dbPath), { recursive: true });
15862
+ mkdirSync11(dirname7(dbPath), { recursive: true });
15749
15863
  this.db = new DatabaseSync12(dbPath);
15750
15864
  } catch (error) {
15751
15865
  this.releaseRuntimeWriter?.();
@@ -17298,17 +17412,17 @@ __export(paths_exports, {
17298
17412
  isAutoMemPath: () => isAutoMemPath,
17299
17413
  setMemoryDirOverride: () => setMemoryDirOverride
17300
17414
  });
17301
- import { join as join26, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve10 } from "node:path";
17415
+ import { join as join27, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve10 } from "node:path";
17302
17416
  function setMemoryDirOverride(dir) {
17303
17417
  _overrideMemoryDir = dir;
17304
17418
  }
17305
17419
  function getAutoMemPath(workspace) {
17306
- const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve10(workspace, _overrideMemoryDir) : join26(workspace, AUTO_MEM_DIRNAME);
17420
+ const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve10(workspace, _overrideMemoryDir) : join27(workspace, AUTO_MEM_DIRNAME);
17307
17421
  const normalized = normalize5(dir);
17308
17422
  return (normalized + sep4).normalize("NFC");
17309
17423
  }
17310
17424
  function getAutoMemEntrypoint(workspace) {
17311
- return join26(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17425
+ return join27(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17312
17426
  }
17313
17427
  function isAutoMemPath(absolutePath, workspace) {
17314
17428
  const normalizedPath = normalize5(absolutePath);
@@ -17499,7 +17613,7 @@ __export(memdir_exports, {
17499
17613
  truncateEntrypointContent: () => truncateEntrypointContent
17500
17614
  });
17501
17615
  import { readFileSync as readFileSync15 } from "node:fs";
17502
- import { join as join27 } from "node:path";
17616
+ import { join as join28 } from "node:path";
17503
17617
  function truncateEntrypointContent(raw) {
17504
17618
  const trimmed = raw.trim();
17505
17619
  const contentLines = trimmed.split("\n");
@@ -17592,7 +17706,7 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
17592
17706
  }
17593
17707
  function buildMemoryPrompt(params) {
17594
17708
  const { displayName, memoryDir, extraGuidelines } = params;
17595
- const entrypoint = join27(memoryDir, ENTRYPOINT_NAME);
17709
+ const entrypoint = join28(memoryDir, ENTRYPOINT_NAME);
17596
17710
  let entrypointContent = "";
17597
17711
  try {
17598
17712
  entrypointContent = readFileSync15(entrypoint, { encoding: "utf-8" });
@@ -18250,22 +18364,22 @@ var TravelAuthority = class {
18250
18364
  if (operation !== "CONTROL" && row.frozen) throw new Error("TRAVEL_HANDOFF_FROZEN");
18251
18365
  if (operation !== "CONTROL" && permit.deletionWatermark !== Number(row.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
18252
18366
  }
18253
- heartbeat(principal, request3) {
18367
+ heartbeat(principal, request4) {
18254
18368
  return this.transaction(() => {
18255
18369
  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");
18370
+ natural(request4.sequence);
18371
+ if (request4.bootId !== node.boot) throw new Error("TRAVEL_BOOT_MISMATCH");
18372
+ if (request4.sequence <= Number(node.sequence)) throw new Error("TRAVEL_HEARTBEAT_REPLAY");
18259
18373
  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;
18374
+ if (request4.permit) {
18375
+ this.assertPermit(request4.permit, "CONTROL");
18376
+ if (request4.permit.nodeId !== principal.nodeId || !same(identityText(request4.permit), text2)) throw new Error("TRAVEL_AUTH_DENIED");
18377
+ const floor = request4.deletionWatermark ?? request4.permit.deletionWatermark;
18264
18378
  if (floor !== Number(seat.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
18265
18379
  this.deadlines.set(text2, this.monotonicNow() + this.leaseMs);
18266
18380
  permit = this.issue(principal, seat);
18267
18381
  }
18268
- this.db.prepare("UPDATE nodes SET sequence=? WHERE identity=? AND node_id=?").run(request3.sequence, text2, principal.nodeId);
18382
+ this.db.prepare("UPDATE nodes SET sequence=? WHERE identity=? AND node_id=?").run(request4.sequence, text2, principal.nodeId);
18269
18383
  this.healthy.set(text2 + principal.nodeId, this.monotonicNow() + this.leaseMs);
18270
18384
  return {
18271
18385
  authorityBootId: this.authorityBootId,
@@ -20006,7 +20120,7 @@ import { HttpsProxyAgent } from "https-proxy-agent";
20006
20120
  // src/memory/external-effect.ts
20007
20121
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20008
20122
  import { createHash as createHash25 } from "node:crypto";
20009
- import { join as join16 } from "node:path";
20123
+ import { join as join17 } from "node:path";
20010
20124
 
20011
20125
  // src/memory/execution-guard.ts
20012
20126
  init_db();
@@ -20016,7 +20130,7 @@ init_migrations();
20016
20130
  init_context_time();
20017
20131
  init_relationship_notice_check();
20018
20132
  init_dependencies();
20019
- import { join as join15 } from "node:path";
20133
+ import { join as join16 } from "node:path";
20020
20134
  var MemoryExecutionBlockedError = class extends Error {
20021
20135
  constructor(reason) {
20022
20136
  super(`MEMORY_EXECUTION_BLOCKED: ${reason}`);
@@ -20029,7 +20143,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20029
20143
  let calendar;
20030
20144
  try {
20031
20145
  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 });
20146
+ memory = new DatabaseSync11(join16(stateDir, "mem7", "index", "mem7.db"), { readOnly: true });
20033
20147
  memory.exec("PRAGMA query_only=ON; BEGIN");
20034
20148
  const schema = readSchemaVersion(memory);
20035
20149
  if (schema?.component !== "mem7" || schema.version !== MEM7_SCHEMA_VERSION) return { ok: false, reason: "MEMORY_SCHEMA_UNSUPPORTED" };
@@ -20044,7 +20158,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20044
20158
  if (!result.ok) return result;
20045
20159
  }
20046
20160
  if (context.calendarBinding) {
20047
- calendar = new DatabaseSync11(join15(workspace, ".calendar", "calendar.db"), { readOnly: true });
20161
+ calendar = new DatabaseSync11(join16(workspace, ".calendar", "calendar.db"), { readOnly: true });
20048
20162
  calendar.exec("PRAGMA query_only=ON; BEGIN");
20049
20163
  const binding = calendar.prepare(`SELECT b.*,e.status event_status,e.memory_version current_event_version FROM calendar_memory_bindings b
20050
20164
  JOIN events e ON e.id=b.event_id WHERE b.event_id=?`).get(context.calendarBinding.eventId);
@@ -20062,7 +20176,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20062
20176
  if (!bound.ok) return bound;
20063
20177
  }
20064
20178
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
20065
- proactive = new DatabaseSync11(join15(workspace, ".proactive", "proactive.db"), { readOnly: true });
20179
+ proactive = new DatabaseSync11(join16(workspace, ".proactive", "proactive.db"), { readOnly: true });
20066
20180
  proactive.exec("PRAGMA query_only=ON; BEGIN");
20067
20181
  for (const [id3, version] of Object.entries(context.actionVersions)) {
20068
20182
  const action = proactive.prepare("SELECT * FROM actions WHERE id=?").get(id3);
@@ -20254,7 +20368,7 @@ async function guardedExternalEffect(run) {
20254
20368
  assertMemoryExecution(stateDir, workspace, context);
20255
20369
  return run();
20256
20370
  }
20257
- const persist = new Persistence2(join16(workspace, ".proactive", "proactive.db"));
20371
+ const persist = new Persistence2(join17(workspace, ".proactive", "proactive.db"));
20258
20372
  const key2 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20259
20373
  context.scopeId,
20260
20374
  Object.entries(versions).sort(([a], [b]) => a.localeCompare(b)),
@@ -25376,14 +25490,14 @@ import { HttpsProxyAgent as HttpsProxyAgent2 } from "https-proxy-agent";
25376
25490
 
25377
25491
  // src/version.ts
25378
25492
  import { readFileSync as readFileSync12 } from "node:fs";
25379
- import { dirname as dirname10, join as join20 } from "node:path";
25493
+ import { dirname as dirname10, join as join21 } from "node:path";
25380
25494
  import { fileURLToPath as fileURLToPath2 } from "node:url";
25381
25495
  var _loaded = null;
25382
25496
  var _pkgDirOverride = null;
25383
25497
  function candidates() {
25384
- if (_pkgDirOverride !== null) return [join20(_pkgDirOverride, "package.json")];
25498
+ if (_pkgDirOverride !== null) return [join21(_pkgDirOverride, "package.json")];
25385
25499
  const here = dirname10(fileURLToPath2(import.meta.url));
25386
- return [join20(here, "..", "package.json"), join20(here, "..", "..", "package.json")];
25500
+ return [join21(here, "..", "package.json"), join21(here, "..", "..", "package.json")];
25387
25501
  }
25388
25502
  function readFromDisk() {
25389
25503
  for (const p of candidates()) {
@@ -26032,8 +26146,11 @@ function fitProtectedTail(suffix, budget) {
26032
26146
  function hasImage(m) {
26033
26147
  return "role" in m && Array.isArray(m.content) && m.content.some((b) => b.type === "image_ref" || b.type === "image");
26034
26148
  }
26149
+ function hasMedia(m) {
26150
+ return hasImage(m) || "role" in m && Array.isArray(m.content) && m.content.some((b) => b.type === "video");
26151
+ }
26035
26152
  function unobservedImageIndex(messages) {
26036
- return messages.findIndex((m) => hasImage(m) && !("role" in m && m.imageInput?.observed === true));
26153
+ return messages.findIndex((m) => hasMedia(m) && !("role" in m && m.imageInput?.observed === true));
26037
26154
  }
26038
26155
  function splitProtectedImages(messages, budget) {
26039
26156
  const index = unobservedImageIndex(messages);
@@ -29278,7 +29395,7 @@ init_dependencies();
29278
29395
  init_basis_check();
29279
29396
  init_relationship_notice_check();
29280
29397
  init_scope();
29281
- import { join as join24, resolve as resolve8 } from "node:path";
29398
+ import { join as join25, resolve as resolve8 } from "node:path";
29282
29399
  var contextIdentity = (context) => canonicalJson({
29283
29400
  scopeId: context.scopeId,
29284
29401
  basisRefs: context.basisRefs,
@@ -29333,7 +29450,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29333
29450
  let proactive;
29334
29451
  let calendar;
29335
29452
  try {
29336
- memory = open3(join24(runtime.stateDir, "mem7", "index", "mem7.db"));
29453
+ memory = open3(join25(runtime.stateDir, "mem7", "index", "mem7.db"));
29337
29454
  const scope = memory.prepare("SELECT * FROM memory_scopes WHERE scope_id=?").get(context.scopeId);
29338
29455
  if (!scope) {
29339
29456
  return { state: "blocked", reason: "MEMORY_NOTIFICATION_SCOPE_MISSING", redact: true };
@@ -29360,7 +29477,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29360
29477
  }
29361
29478
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
29362
29479
  const ledgerDependencies = new MemoryDependencies(memory, (operation) => operation());
29363
- proactive = open3(join24(runtime.workspace, ".proactive", "proactive.db"));
29480
+ proactive = open3(join25(runtime.workspace, ".proactive", "proactive.db"));
29364
29481
  for (const id3 of Object.keys(context.actionVersions)) {
29365
29482
  const action = proactive.prepare("SELECT scope_id,intent_id FROM actions WHERE id=?").get(id3);
29366
29483
  if (!action || action.scope_id !== context.scopeId) return { state: "blocked", reason: "MEMORY_NOTIFICATION_ACTION_MISMATCH", redact: true };
@@ -29414,7 +29531,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29414
29531
  }
29415
29532
  if (route.hostDelivery) {
29416
29533
  if (!proactive) {
29417
- proactive = open3(join24(runtime.workspace, ".proactive", "proactive.db"));
29534
+ proactive = open3(join25(runtime.workspace, ".proactive", "proactive.db"));
29418
29535
  }
29419
29536
  const receipt = proactive.prepare("SELECT * FROM proactive_host_deliveries WHERE delivery_key=?").get(route.hostDelivery.key);
29420
29537
  if (!receipt || contextIdentity(JSON.parse(receipt.context_json)) !== contextIdentity(context)) {
@@ -29425,7 +29542,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29425
29542
  if (["blocked", "delivery_unknown"].includes(receipt.state)) return { state: receipt.state, reason: receipt.reason ?? receipt.state };
29426
29543
  }
29427
29544
  if (context.calendarBinding) {
29428
- calendar = open3(join24(runtime.workspace, ".calendar", "calendar.db"));
29545
+ calendar = open3(join25(runtime.workspace, ".calendar", "calendar.db"));
29429
29546
  const binding = context.calendarBinding;
29430
29547
  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
29548
  if (rows.some((row) => ["started", "delivery_unknown"].includes(row.state) && !row.closure)) {
@@ -30193,7 +30310,7 @@ var QueryEngine = class _QueryEngine {
30193
30310
  this.compactConfig.systemOverheadTokens = overhead ?? this.compactConfig.systemOverheadTokens;
30194
30311
  }
30195
30312
  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 };
30313
+ for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID16(), observed: hasImage(m) };
30197
30314
  let currentMessages = [...messages];
30198
30315
  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
30316
  const historicalGateTools = new Set(currentMessages.flatMap((m) => {
@@ -30584,9 +30701,13 @@ var QueryEngine = class _QueryEngine {
30584
30701
  try {
30585
30702
  wholeQueryAbort.signal.throwIfAborted();
30586
30703
  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]" };
30704
+ if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
30705
+ const blocks = m.content.filter((b) => {
30706
+ if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
30707
+ if (b.type === "video") return !!queryInputs?.includes("video");
30708
+ return true;
30709
+ });
30710
+ return { ...m, content: blocks.length ? blocks : "[previous media omitted]" };
30590
30711
  });
30591
30712
  const apiMessages = await materializeImageMessages(view, this.options.imageAssets, wholeQueryAbort.signal);
30592
30713
  wholeQueryAbort.signal.throwIfAborted();
@@ -30747,7 +30868,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30747
30868
  }
30748
30869
  });
30749
30870
  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);
30871
+ const inputs = currentMessages.filter((m) => "role" in m && hasMedia(m) && !m.imageInput?.observed);
30751
30872
  if (!inputs.length) return;
30752
30873
  return {
30753
30874
  type: "image_observed",
@@ -34675,8 +34796,8 @@ import { randomUUID as randomUUID20 } from "node:crypto";
34675
34796
 
34676
34797
  // src/continuity/gateway-channel.ts
34677
34798
  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";
34799
+ import { mkdtempSync, writeFileSync as writeFileSync14, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
34800
+ import { join as join30 } from "node:path";
34680
34801
  import { tmpdir as tmpdir3 } from "node:os";
34681
34802
  function splitChannelGatewayText(text2, channel) {
34682
34803
  if (typeof text2 !== "string" || Buffer.byteLength(text2) > 1024 * 1024) throw new Error("TRAVEL_GATEWAY_REPLY_LIMIT");
@@ -34731,9 +34852,9 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
34731
34852
  if (!media) await adapter.send(packet.target, packet.text, { replyTo: packet.replyTo });
34732
34853
  else {
34733
34854
  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);
34855
+ const directory2 = realpathSync5(mkdtempSync(join30(tmpdir3(), "e7-gateway-media-"))), file2 = join30(directory2, packet.filename);
34735
34856
  try {
34736
- writeFileSync13(file2, media.bytes, { mode: 384 });
34857
+ writeFileSync14(file2, media.bytes, { mode: 384 });
34737
34858
  await adapter.sendFile(packet.target, packet.text, { path: file2, filename: packet.filename, mimeType: packet.mimeType, voiceDurationSec: packet.voiceDurationSec });
34738
34859
  } finally {
34739
34860
  rmSync2(directory2, { recursive: true, force: true });