stratagate-dsh 0.3.36 → 0.3.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js CHANGED
@@ -5,7 +5,20 @@ import { dirname as dirname4 } from "node:path";
5
5
 
6
6
  // src/config.ts
7
7
  import z from "@deepseek-ai/schemastery";
8
+ var MemoryModelSelectionSchema = z.union([
9
+ z.object({ mode: z.const("auto").required() }),
10
+ z.object({ mode: z.const("custom").required(), provider: z.string().min(1).required(), model: z.string().min(1).required() })
11
+ ]);
12
+ function resolveMemoryModel(value) {
13
+ if (value === void 0) return void 0;
14
+ if (value.mode === "auto") return { mode: "auto" };
15
+ if (value.mode !== "custom" || !value.provider?.trim() || !value.model?.trim()) {
16
+ throw new TypeError("\u8BB0\u5FC6\u5904\u7406\u6A21\u578B\u9700\u8981\u540C\u65F6\u9009\u62E9\u670D\u52A1\u5546\u548C\u6A21\u578B");
17
+ }
18
+ return { mode: "custom", provider: value.provider.trim(), model: value.model.trim() };
19
+ }
8
20
  var StructuredReasoningEffortSettings = z.object({
21
+ memoryModel: MemoryModelSelectionSchema.description("\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"),
9
22
  structuredReasoningEffort: z.union(["auto", "force-off"]).default("auto").description("\u8BB0\u5FC6\u5904\u7406\u7ED3\u6784\u5316\u8C03\u7528\u7684\u63A8\u7406\u6863\u4F4D\u7B56\u7565").comment("auto\uFF1A\u4EC5\u5728\u6A21\u578B\u660E\u786E\u652F\u6301 off \u65F6\u4F7F\u7528\uFF1Bforce-off\uFF1A\u4F18\u5148\u4F7F\u7528 off\uFF0C\u4E0D\u652F\u6301\u6216\u80FD\u529B\u68C0\u67E5\u5931\u8D25\u65F6\u5B89\u5168\u964D\u7EA7\uFF0C\u5E76\u5BF9\u540C\u4E00\u6A21\u578B\u53EA\u544A\u8B66\u4E00\u6B21\u3002"),
10
23
  showStrataGateStatus: z.boolean().default(true).description("\u663E\u793A StrataGate \u72B6\u6001\u63D0\u793A").comment("\u5173\u95ED\u540E\u9690\u85CF\u804A\u5929\u754C\u9762\u4E2D\u7684 StrataGate \u72B6\u6001\u4FE1\u606F\uFF1B\u8BB0\u5FC6\u3001\u68C0\u7D22\u548C\u540E\u53F0\u5904\u7406\u4E0D\u53D7\u5F71\u54CD\u3002"),
11
24
  showShortTermStatus: z.boolean().default(true).description("\u663E\u793A\u4F1A\u8BDD\u8BB0\u5FC6\u72B6\u6001").comment("\u63A7\u5236\u4F1A\u8BDD\u8BB0\u5FC6\u8FDB\u5EA6\u3001Block \u5C01\u5B58\u4E0E\u6574\u7406\u72B6\u6001\u7684\u804A\u5929\u5185\u63D0\u793A\uFF1B\u540E\u53F0\u5904\u7406\u4E0D\u53D7\u5F71\u54CD\u3002"),
@@ -30,8 +43,17 @@ var Config = z.object({
30
43
  ingestSubagents: z.boolean().default(false),
31
44
  agentMemoryEnabled: z.boolean().default(true).description("\u542F\u7528 agent \u4E3B\u52A8\u8BB0\u5FC6\uFF08memory_remember\uFF09").comment("\u5F00\u542F\u540E agent \u53EF\u4EE5\u628A\u503C\u5F97\u8BB0\u5FC6\u7684\u4E8B\u5B9E\u5199\u5165\u957F\u671F\u8BB0\u5FC6 Event \u7BA1\u7EBF\uFF1A\u8FDB\u5165\u6570\u636E\u5E93\u3001\u53C2\u4E0E\u77E5\u8BC6\u56FE\u8C31\u3001\u8DE8\u4F1A\u8BDD\u5171\u4EAB\uFF1B\u5199\u5165\u524D\u4F1A\u81EA\u52A8\u68C0\u6D4B\u5E76\u6D88\u89E3\u91CD\u590D\u4E0E\u51B2\u7A81\u3002"),
32
45
  agentMemoryRetrievalWeight: z.number().step(0.05).min(0).max(5).default(1).description("\u4E3B\u52A8\u8BB0\u5FC6\u5728\u68C0\u7D22\u4E2D\u7684\u5360\u6BD4\u6743\u91CD").comment("agent \u8BB0\u5F55\u4E0E\u5BF9\u8BDD\u6D3E\u751F\u8BB0\u5FC6\u5206\u522B\u72EC\u7ACB\u6392\u5E8F\u540E\u6309\u6743\u91CD\u878D\u5408\uFF1A1 \u4E3A\u5E73\u6743\uFF0C0 \u4E3A\u4E0D\u6D6E\u73B0 agent \u8BB0\u5F55\uFF0C\u5927\u4E8E 1 \u5219\u63D0\u5347 agent \u8BB0\u5F55\u7684\u6392\u5E8F\u6743\u91CD\u3002"),
46
+ embeddingUrl: z.string().default("").description("Embedding API \u5730\u5740").comment("OpenAI \u517C\u5BB9\u63A5\u53E3\uFF0C\u4F8B\u5982 https://api.siliconflow.cn/v1\u3002\u7559\u7A7A = \u4E0D\u542F\u7528\u8BED\u4E49\u68C0\u7D22\uFF0C\u68C0\u7D22\u884C\u4E3A\u4E0E\u672A\u914D\u7F6E\u65F6\u5B8C\u5168\u4E00\u81F4\u3002"),
47
+ embeddingKey: z.string().default("").description("Embedding API Key").comment("\u4E0E embeddingUrl\u3001embeddingModel \u914D\u5957\uFF1B\u4E09\u8005\u90FD\u586B\u4E86\u624D\u542F\u7528\u3002"),
48
+ embeddingModel: z.string().default("").description("Embedding \u6A21\u578B\u540D").comment("\u4F8B\u5982 BAAI/bge-m3\u3002\u6362\u6A21\u578B\u540E\u65E7\u5411\u91CF\u4E0D\u4F1A\u88AB\u5220\u9664\uFF0C\u53EA\u662F\u4E0D\u518D\u53C2\u4E0E\u68C0\u7D22\u3002"),
49
+ vectorWeight: z.number().step(0.1).min(0).max(5).default(1).description("\u5411\u91CF\u53EC\u56DE\u5728\u68C0\u7D22\u4E2D\u7684\u5360\u6BD4\u6743\u91CD").comment("\u8BED\u4E49\u53EC\u56DE\u4E0E\u5173\u952E\u8BCD\u53EC\u56DE\u6309\u6743\u91CD\u878D\u5408\uFF1A1 \u4E3A\u5E73\u6743\uFF0C0 \u4E3A\u4E0D\u542F\u7528\u5411\u91CF\u8F66\u9053\u3002"),
50
+ embeddingMinScore: z.number().step(0.05).min(0).max(1).default(0.3).description("\u5411\u91CF\u53EC\u56DE\u7684\u6700\u4F4E\u76F8\u4F3C\u5EA6").comment("\u4F59\u5F26\u76F8\u4F3C\u5EA6\u4F4E\u4E8E\u8BE5\u503C\u7684\u4E8B\u4EF6\u4E0D\u8FDB\u5165\u8BED\u4E49\u53EC\u56DE\u7ED3\u679C\uFF1B0 \u8868\u793A\u4E0D\u8BBE\u95E8\u69DB\u3002\u9ED8\u8BA4 0.3 \u9AD8\u4E8E\u968F\u673A\u6587\u672C\u5BF9\u7684\u76F8\u4F3C\u5EA6\uFF0C\u907F\u514D\u300C\u6CA1\u627E\u5230\u300D\u53D8\u6210\u603B\u8981\u51D1\u51E0\u6761\u3002"),
51
+ rerankUrl: z.string().default("").description("Rerank API \u5730\u5740").comment("\u4E0E embedding \u72EC\u7ACB\u914D\u7F6E\uFF0C\u4F8B\u5982 https://api.siliconflow.cn/v1\u3002\u7559\u7A7A = \u4E0D\u7CBE\u6392\uFF0C\u53EC\u56DE\u987A\u5E8F\u4E0E\u672A\u914D\u7F6E\u65F6\u4E00\u81F4\u3002"),
52
+ rerankKey: z.string().default("").description("Rerank API Key").comment("\u4E0E rerankUrl\u3001rerankModel \u914D\u5957\uFF1B\u4E09\u8005\u90FD\u586B\u4E86\u624D\u542F\u7528\u3002"),
53
+ rerankModel: z.string().default("").description("Rerank \u6A21\u578B\u540D").comment("\u4F8B\u5982 BAAI/bge-reranker-v2-m3\u3002\u7CBE\u6392\u53EA\u4F5C\u7528\u4E8E\u88AB\u52A8\u53EC\u56DE\u7684\u5019\u9009\uFF0C\u8D85\u65F6\u6216\u62A5\u9519\u65F6\u9759\u9ED8\u56DE\u9000\u539F\u987A\u5E8F\u3002"),
33
54
  provider: z.string(),
34
55
  model: z.string(),
56
+ memoryModel: volatileIfSupported(MemoryModelSelectionSchema.description("\u8BB0\u5FC6\u5904\u7406\u6A21\u578B")),
35
57
  maxOutputTokens: z.natural().min(256).default(2048),
36
58
  structuredTaskTimeoutMs: z.natural().min(1e3).default(12e4),
37
59
  structuredReasoningEffort: volatileIfSupported(z.union(["auto", "force-off"]).default("auto")),
@@ -53,6 +75,7 @@ function resolveConfig(config) {
53
75
  const globalNamespace = config.globalNamespace?.trim() || "global";
54
76
  const provider = config.provider?.trim();
55
77
  const model = config.model?.trim();
78
+ const memoryModel = resolveMemoryModel(liveConfigValue(config.memoryModel));
56
79
  if (!database) throw new TypeError("StrataGate database path must not be empty");
57
80
  if (Boolean(provider) !== Boolean(model)) {
58
81
  throw new TypeError("StrataGate provider and model must be configured together");
@@ -75,7 +98,16 @@ function resolveConfig(config) {
75
98
  ingestSubagents: config.ingestSubagents ?? false,
76
99
  agentMemoryEnabled: config.agentMemoryEnabled ?? true,
77
100
  agentMemoryRetrievalWeight: Math.min(5, Math.max(0, config.agentMemoryRetrievalWeight ?? 1)),
101
+ ...config.embeddingUrl !== void 0 ? { embeddingUrl: config.embeddingUrl.trim() } : {},
102
+ ...config.embeddingKey !== void 0 ? { embeddingKey: config.embeddingKey.trim() } : {},
103
+ ...config.embeddingModel !== void 0 ? { embeddingModel: config.embeddingModel.trim() } : {},
104
+ ...config.vectorWeight !== void 0 ? { vectorWeight: Math.min(5, Math.max(0, config.vectorWeight)) } : {},
105
+ ...config.embeddingMinScore !== void 0 ? { embeddingMinScore: Math.min(1, Math.max(0, config.embeddingMinScore)) } : {},
106
+ ...config.rerankUrl !== void 0 ? { rerankUrl: config.rerankUrl.trim() } : {},
107
+ ...config.rerankKey !== void 0 ? { rerankKey: config.rerankKey.trim() } : {},
108
+ ...config.rerankModel !== void 0 ? { rerankModel: config.rerankModel.trim() } : {},
78
109
  ...provider && model ? { provider, model } : {},
110
+ ...memoryModel ? { memoryModel } : {},
79
111
  maxOutputTokens: Math.max(256, Math.floor(config.maxOutputTokens ?? 2048)),
80
112
  structuredTaskTimeoutMs: Math.max(1e3, Math.floor(config.structuredTaskTimeoutMs ?? 12e4)),
81
113
  structuredReasoningEffort: liveConfigValue(config.structuredReasoningEffort) ?? "auto",
@@ -4051,6 +4083,26 @@ CREATE TABLE IF NOT EXISTS agent_event_sources (
4051
4083
  FOREIGN KEY (namespace, message_id) REFERENCES messages(namespace, id)
4052
4084
  ) STRICT;
4053
4085
 
4086
+ -- Optional embedding vectors for semantic Event recall. A side table: it never
4087
+ -- touches the Event rows and never joins a snapshot save. Vectors are computed
4088
+ -- by the host layer and persisted here; model/dimension columns let several
4089
+ -- embedding models coexist, and queries filter by the configured model, so
4090
+ -- stale vectors from a previously used model are simply invisible.
4091
+ -- event_id deliberately carries NO FOREIGN KEY: a vector may belong to the
4092
+ -- passive events table OR the isolated agent_events table, and SQLite cannot
4093
+ -- retarget one constraint across both. Integrity is enforced by
4094
+ -- cleanupOrphanEventVectors (dual-pool orphan sweep) on every open.
4095
+ CREATE TABLE IF NOT EXISTS event_vectors (
4096
+ namespace TEXT NOT NULL,
4097
+ event_id TEXT NOT NULL,
4098
+ model TEXT NOT NULL,
4099
+ dimension INTEGER NOT NULL,
4100
+ vector_json TEXT NOT NULL,
4101
+ content_hash TEXT,
4102
+ created_at TEXT NOT NULL,
4103
+ PRIMARY KEY (namespace, event_id, model)
4104
+ ) STRICT;
4105
+
4054
4106
  CREATE TABLE IF NOT EXISTS elements (
4055
4107
  namespace TEXT NOT NULL,
4056
4108
  id TEXT NOT NULL,
@@ -6043,6 +6095,8 @@ var SqliteStorage = class _SqliteStorage {
6043
6095
  }
6044
6096
  this.database.exec(THREAD_INDEXES);
6045
6097
  this.rebuildLegacyElementSourceForeignKeys();
6098
+ this.rebuildLegacyEventVectorForeignKeys();
6099
+ this.cleanupOrphanEventVectors();
6046
6100
  this.enableRawSearchFts();
6047
6101
  this.database.prepare("INSERT INTO stratagate_graph_policy_migrations (id, completed_at) VALUES (1, ?) ON CONFLICT (id) DO NOTHING").run(nowUtc8());
6048
6102
  this.database.exec(`
@@ -6084,6 +6138,8 @@ var SqliteStorage = class _SqliteStorage {
6084
6138
  this.database.prepare("INSERT INTO stratagate_graph_policy_migrations (id, completed_at) VALUES (1, ?) ON CONFLICT (id) DO NOTHING").run(nowUtc8());
6085
6139
  this.database.exec(THREAD_INDEXES);
6086
6140
  this.rebuildLegacyElementSourceForeignKeys();
6141
+ this.rebuildLegacyEventVectorForeignKeys();
6142
+ this.cleanupOrphanEventVectors();
6087
6143
  this.enableRawSearchFts();
6088
6144
  });
6089
6145
  }
@@ -6100,8 +6156,20 @@ var SqliteStorage = class _SqliteStorage {
6100
6156
  `);
6101
6157
  this.database.exec("DELETE FROM persistent_profile_maintenance_baseline WHERE NOT EXISTS (SELECT 1 FROM persistent_profile WHERE value <> '')");
6102
6158
  });
6159
+ this.ensureEventVectorContentHashColumn();
6103
6160
  this.assertSchemaVersion();
6104
6161
  }
6162
+ /**
6163
+ * event_vectors gained `content_hash` — the fingerprint of the text the
6164
+ * vector was computed from. Without it a vector stayed "valid" forever after
6165
+ * a card body was rewritten (edit / merge), so facts merged into a kept card
6166
+ * were never semantically reachable.
6167
+ */
6168
+ ensureEventVectorContentHashColumn() {
6169
+ if (!this.hasColumn("event_vectors", "content_hash")) {
6170
+ this.database.exec("ALTER TABLE event_vectors ADD COLUMN content_hash TEXT");
6171
+ }
6172
+ }
6105
6173
  hasColumn(table, column) {
6106
6174
  return this.database.prepare(`PRAGMA table_info('${table}')`).all().some((row) => row.name === column);
6107
6175
  }
@@ -6188,6 +6256,59 @@ var SqliteStorage = class _SqliteStorage {
6188
6256
  `);
6189
6257
  }
6190
6258
  }
6259
+ /**
6260
+ * An early build of the embedding side table declared
6261
+ * `FOREIGN KEY (namespace, event_id) REFERENCES events(namespace, id)`, which
6262
+ * only covers the passive pool. Vectors may also belong to the isolated
6263
+ * agent_events pool, and SQLite cannot retarget one constraint across both,
6264
+ * so writing a vector for an agent-recorded Event always failed with
6265
+ * "FOREIGN KEY constraint failed" (measured: passive events fully
6266
+ * vectorized, agent events never). Tables still carrying that constraint are
6267
+ * rebuilt in place — same columns, same rows, same row order — without it,
6268
+ * exactly like rebuildLegacyElementSourceForeignKeys. Idempotent: a database
6269
+ * already free of the constraint is a no-op.
6270
+ */
6271
+ rebuildLegacyEventVectorForeignKeys() {
6272
+ const row = this.database.prepare(`
6273
+ SELECT sql FROM sqlite_master
6274
+ WHERE type = 'table' AND name = 'event_vectors'
6275
+ `).get();
6276
+ if (!row || typeof row.sql !== "string" || !row.sql.includes("REFERENCES events")) return;
6277
+ this.database.exec("PRAGMA defer_foreign_keys = ON");
6278
+ this.database.exec(`
6279
+ CREATE TABLE event_vectors_rebuild (
6280
+ namespace TEXT NOT NULL,
6281
+ event_id TEXT NOT NULL,
6282
+ model TEXT NOT NULL,
6283
+ dimension INTEGER NOT NULL,
6284
+ vector_json TEXT NOT NULL,
6285
+ created_at TEXT NOT NULL,
6286
+ PRIMARY KEY (namespace, event_id, model)
6287
+ ) STRICT;
6288
+ INSERT INTO event_vectors_rebuild (namespace, event_id, model, dimension, vector_json, created_at)
6289
+ SELECT namespace, event_id, model, dimension, vector_json, created_at FROM event_vectors;
6290
+ DROP TABLE event_vectors;
6291
+ ALTER TABLE event_vectors_rebuild RENAME TO event_vectors;
6292
+ `);
6293
+ }
6294
+ /**
6295
+ * With the cross-pool foreign key gone, an orphaned vector (its Event exists
6296
+ * in NEITHER the passive pool NOR agent_events) is no longer cascade-deleted.
6297
+ * This idempotent sweep removes those rows; a vector whose Event exists in
6298
+ * EITHER pool is preserved. Runs on every open, like the other rebuilds.
6299
+ */
6300
+ cleanupOrphanEventVectors() {
6301
+ this.database.exec(`
6302
+ DELETE FROM event_vectors
6303
+ WHERE NOT EXISTS (
6304
+ SELECT 1 FROM events
6305
+ WHERE events.namespace = event_vectors.namespace AND events.id = event_vectors.event_id
6306
+ ) AND NOT EXISTS (
6307
+ SELECT 1 FROM agent_events
6308
+ WHERE agent_events.namespace = event_vectors.namespace AND agent_events.id = event_vectors.event_id
6309
+ )
6310
+ `);
6311
+ }
6191
6312
  enableRawSearchFts() {
6192
6313
  try {
6193
6314
  const hadFts = this.database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'raw_message_fts'").get();
@@ -6327,6 +6448,86 @@ var SqliteStorage = class _SqliteStorage {
6327
6448
  this.assertOpen();
6328
6449
  return this.database.prepare("SELECT namespace, revision FROM memory_spaces ORDER BY namespace").all();
6329
6450
  }
6451
+ /**
6452
+ * Persist one embedding vector for an Event (semantic recall side table).
6453
+ * Works for both pools: the row is keyed by (namespace, event_id, model) and
6454
+ * deliberately has no foreign key, because an Event may live in the passive
6455
+ * `events` table or in the isolated `agent_events` table.
6456
+ */
6457
+ setEventVector(namespace, eventId, model, dimension, vector, contentHash) {
6458
+ this.assertOpen();
6459
+ this.database.prepare(`
6460
+ INSERT OR REPLACE INTO event_vectors (namespace, event_id, model, dimension, vector_json, content_hash, created_at)
6461
+ VALUES (?, ?, ?, ?, ?, ?, ?)
6462
+ `).run(namespace, eventId, model, dimension, JSON.stringify(vector), contentHash ?? null, (/* @__PURE__ */ new Date()).toISOString());
6463
+ }
6464
+ /**
6465
+ * Drop a stored vector. Used when a card body is rewritten (merge / edit):
6466
+ * the old vector no longer describes the text, so it must not stay valid.
6467
+ * Returns the number of deleted rows.
6468
+ */
6469
+ deleteEventVector(namespace, eventId, model) {
6470
+ this.assertOpen();
6471
+ const result = model === void 0 ? this.database.prepare("DELETE FROM event_vectors WHERE namespace = ? AND event_id = ?").run(namespace, eventId) : this.database.prepare("DELETE FROM event_vectors WHERE namespace = ? AND event_id = ? AND model = ?").run(namespace, eventId, model);
6472
+ return Number(result.changes);
6473
+ }
6474
+ /** Load one Event vector under a specific model, or null when absent. */
6475
+ getEventVector(namespace, eventId, model) {
6476
+ this.assertOpen();
6477
+ const columns = this.hasColumn("event_vectors", "content_hash") ? "dimension, vector_json, content_hash" : "dimension, vector_json, NULL AS content_hash";
6478
+ const row = this.database.prepare(
6479
+ `SELECT ${columns} FROM event_vectors WHERE namespace = ? AND event_id = ? AND model = ?`
6480
+ ).get(namespace, eventId, model);
6481
+ if (!row) return null;
6482
+ let vector;
6483
+ try {
6484
+ vector = JSON.parse(row.vector_json);
6485
+ } catch {
6486
+ return null;
6487
+ }
6488
+ return Array.isArray(vector) ? { dimension: row.dimension, vector, contentHash: row.content_hash ?? null } : null;
6489
+ }
6490
+ /**
6491
+ * Load every Event vector under one model in a namespace as a Map keyed by
6492
+ * event id. One query and one JSON.parse per row replaces N single-row
6493
+ * lookups for a retrieval pass. Malformed rows are skipped silently.
6494
+ */
6495
+ listEventVectors(namespace, model) {
6496
+ const records = this.listEventVectorRecords(namespace, model);
6497
+ const result = /* @__PURE__ */ new Map();
6498
+ for (const [id, record3] of records) result.set(id, record3.vector);
6499
+ return result;
6500
+ }
6501
+ /**
6502
+ * Like listEventVectors but also returns the content fingerprint the vector
6503
+ * was computed from. A row written before the fingerprint column existed has
6504
+ * a null hash and is treated as stale by the read path, which forces a
6505
+ * recompute instead of trusting a vector that may describe older text.
6506
+ */
6507
+ listEventVectorRecords(namespace, model) {
6508
+ this.assertOpen();
6509
+ const columns = this.hasColumn("event_vectors", "content_hash") ? "event_id, vector_json, content_hash" : "event_id, vector_json, NULL AS content_hash";
6510
+ const rows = this.database.prepare(
6511
+ `SELECT ${columns} FROM event_vectors WHERE namespace = ? AND model = ?`
6512
+ ).all(namespace, model);
6513
+ const result = /* @__PURE__ */ new Map();
6514
+ for (const row of rows) {
6515
+ try {
6516
+ const parsed = JSON.parse(row.vector_json);
6517
+ if (Array.isArray(parsed)) result.set(row.event_id, { vector: parsed, contentHash: row.content_hash ?? null });
6518
+ } catch {
6519
+ }
6520
+ }
6521
+ return result;
6522
+ }
6523
+ /** Event IDs that already carry a vector under one model in a namespace. */
6524
+ listEventVectorIds(namespace, model) {
6525
+ this.assertOpen();
6526
+ const rows = this.database.prepare(
6527
+ "SELECT event_id FROM event_vectors WHERE namespace = ? AND model = ?"
6528
+ ).all(namespace, model);
6529
+ return new Set(rows.map(({ event_id }) => event_id));
6530
+ }
6330
6531
  };
6331
6532
 
6332
6533
  // packages/core/src/store.ts
@@ -6422,6 +6623,22 @@ function duplicateUndoProjections(snapshot, ids2) {
6422
6623
  function duplicateUndoDerived(snapshot, ids2) {
6423
6624
  return undoHash([snapshot.elements, snapshot.graphNodes, snapshot.graphEdges].map((values) => values.filter((value) => value.sourceEventIds.some((id) => ids2.includes(id))).sort((a, b) => a.id.localeCompare(b.id))));
6424
6625
  }
6626
+ function eventMatchesSearchFilters(event, options) {
6627
+ if (options.eventIds !== void 0 && !options.eventIds.includes(event.id)) return false;
6628
+ const temporal = normalizeEventTemporal(event.temporal);
6629
+ const participants = (options.participants ?? []).map(normalizeSearchText).filter(Boolean);
6630
+ if (participants.length > 0 && !participants.every((person) => (temporal.participants ?? []).some((candidate) => fuzzySearchMatch(candidate, person)))) return false;
6631
+ const eventType = normalizeSearchText(options.eventType ?? "");
6632
+ if (eventType && !(fuzzySearchMatch(temporal.eventType ?? "", eventType) || fuzzySearchMatch(`${event.title} ${event.summary} ${event.tags.join(" ")}`, eventType))) return false;
6633
+ if (options.happenedFrom || options.happenedTo) {
6634
+ const from = options.happenedFrom ? Date.parse(options.happenedFrom) : Number.NEGATIVE_INFINITY;
6635
+ const to = options.happenedTo ? Date.parse(options.happenedTo) : Number.POSITIVE_INFINITY;
6636
+ const start = Date.parse(temporal.happenedStart ?? temporal.happenedEnd ?? "");
6637
+ const end = Date.parse(temporal.happenedEnd ?? temporal.happenedStart ?? "");
6638
+ if (!(Number.isFinite(start) && Number.isFinite(end) && start <= to && end >= from)) return false;
6639
+ }
6640
+ return true;
6641
+ }
6425
6642
  var StrataGate = class _StrataGate {
6426
6643
  blockTurnSizeValue;
6427
6644
  blockDecayLambdaValue;
@@ -6766,6 +6983,48 @@ var StrataGate = class _StrataGate {
6766
6983
  listAllEvents() {
6767
6984
  return [...this.events, ...this.agentEvents];
6768
6985
  }
6986
+ /**
6987
+ * Persist one embedding vector for an Event (the semantic-recall side table).
6988
+ * Covers both pools, because the table has no foreign key to either one.
6989
+ * A no-op when this space has no persistent storage or its adapter has no
6990
+ * vector support, so callers never branch on storage kind.
6991
+ */
6992
+ setEventVector(eventId, model, dimension, vector, contentHash) {
6993
+ const storage = this.eventVectorStorage();
6994
+ if (!storage?.setEventVector || !this.namespace) return;
6995
+ storage.setEventVector(this.namespace, eventId, model, dimension, vector, contentHash);
6996
+ }
6997
+ /** Drop one stored vector (body rewrite / merge invalidation). Returns deleted rows. */
6998
+ deleteEventVector(eventId, model) {
6999
+ const storage = this.eventVectorStorage();
7000
+ if (!storage?.deleteEventVector || !this.namespace) return 0;
7001
+ return storage.deleteEventVector(this.namespace, eventId, model);
7002
+ }
7003
+ /**
7004
+ * Every stored Event vector under one model in this namespace, keyed by
7005
+ * event id (one query for a whole retrieval pass). Empty when unavailable.
7006
+ */
7007
+ listEventVectors(model) {
7008
+ const records = this.listEventVectorRecords(model);
7009
+ const result = /* @__PURE__ */ new Map();
7010
+ for (const [id, record3] of records) result.set(id, record3.vector);
7011
+ return result;
7012
+ }
7013
+ /**
7014
+ * Same rows as listEventVectors, plus the content fingerprint each vector was
7015
+ * computed from. A row whose fingerprint no longer matches the current card
7016
+ * body describes text that has since been rewritten (edit / merge), so the
7017
+ * caller must treat it as missing and re-embed rather than score it.
7018
+ */
7019
+ listEventVectorRecords(model) {
7020
+ const storage = this.eventVectorStorage();
7021
+ if (!storage?.listEventVectorRecords || !this.namespace) return /* @__PURE__ */ new Map();
7022
+ return storage.listEventVectorRecords(this.namespace, model);
7023
+ }
7024
+ /** Event vectors are optional: adapters that cannot store them are skipped. */
7025
+ eventVectorStorage() {
7026
+ return this.storage;
7027
+ }
6769
7028
  findEvent(id) {
6770
7029
  return this.events.find((event) => event.id === id) ?? this.agentEvents.find((event) => event.id === id);
6771
7030
  }
@@ -7558,6 +7817,22 @@ var StrataGate = class _StrataGate {
7558
7817
  weights.push(agentWeight);
7559
7818
  }
7560
7819
  }
7820
+ const vectorWeight = Math.max(0, options.vectorWeight ?? 1);
7821
+ if (vectorWeight > 0 && options.vectorRanking !== void 0 && options.vectorRanking.length > 0) {
7822
+ const allEvents = new Map([...this.events, ...this.agentEvents].map((event) => [event.id, event]));
7823
+ const vectorLane = options.vectorRanking.map((id) => allEvents.get(id)).filter((event) => event !== void 0 && (event.status === "active" || event.status === "superseded") && (scopedIds === null || scopedIds.has(event.id)) && eventMatchesSearchFilters(event, options));
7824
+ const agentEventIds = new Set(this.agentEvents.map(({ id }) => id));
7825
+ const passiveVectorLane = vectorLane.filter(({ id }) => !agentEventIds.has(id));
7826
+ const agentVectorLane = vectorLane.filter(({ id }) => agentEventIds.has(id));
7827
+ if (passiveVectorLane.length > 0) {
7828
+ rankings.push(passiveVectorLane);
7829
+ weights.push(vectorWeight);
7830
+ }
7831
+ if (agentWeight > 0 && agentVectorLane.length > 0) {
7832
+ rankings.push(agentVectorLane);
7833
+ weights.push(vectorWeight * agentWeight);
7834
+ }
7835
+ }
7561
7836
  if (rankings.length === 0) return [];
7562
7837
  const ranked = rrfRank(rankings, weights).slice(offset, offset + limit).map(({ item: event, score }) => ({ event, score }));
7563
7838
  if (ranked.length > 0 && options.trackRetrieval !== false) {
@@ -8174,7 +8449,7 @@ var StrataGate = class _StrataGate {
8174
8449
  /** The server journals the inverse before the core commit, so a crash cannot lose undo evidence. */
8175
8450
  async reviewDuplicateEvents(pair, keepId, mode, prepareUndo, draft, origin = "automatic") {
8176
8451
  if (draft !== void 0 && !validEventMergeDraft(draft)) throw new TypeError("Invalid merged memory draft");
8177
- return this.commitMutation(() => {
8452
+ const applied = await this.commitMutation(() => {
8178
8453
  const before = this.exportSnapshot();
8179
8454
  const ok = mode === "select" ? this.selectDuplicateEventInMemory(pair, keepId) : this.archiveDuplicateEventInMemory(pair, keepId, true, true, draft, origin === "manual");
8180
8455
  if (!ok) return false;
@@ -8206,6 +8481,8 @@ var StrataGate = class _StrataGate {
8206
8481
  }
8207
8482
  return true;
8208
8483
  });
8484
+ if (applied && mode === "merge") this.deleteEventVector(keepId);
8485
+ return applied;
8209
8486
  }
8210
8487
  /** Restore only this operation's changed records. Unrelated writes and original evidence survive. */
8211
8488
  async undoDuplicateReview(undo) {
@@ -11401,11 +11678,13 @@ function parseTopicProjection(value, context) {
11401
11678
  var TOPIC_OUTPUT_TOKEN_BUDGET = 32768;
11402
11679
  var GRAPH_OUTPUT_TOKEN_BUDGET = 32768;
11403
11680
  var DshModelBridge = class {
11404
- constructor(ctx, config, liveStructuredReasoningEffort) {
11681
+ constructor(ctx, config, liveStructuredReasoningEffort, liveMemoryModel) {
11405
11682
  this.ctx = ctx;
11406
11683
  this.config = config;
11407
11684
  this.liveStructuredReasoningEffort = liveStructuredReasoningEffort;
11685
+ this.liveMemoryModel = liveMemoryModel;
11408
11686
  this.structuredReasoningEffort = config.structuredReasoningEffort ?? "auto";
11687
+ this.memoryModel = config.memoryModel;
11409
11688
  this.ctx.on?.("llm/adapters-updated", () => {
11410
11689
  this.offCapabilities.clear();
11411
11690
  this.contextWindows.clear();
@@ -11415,6 +11694,7 @@ var DshModelBridge = class {
11415
11694
  ctx;
11416
11695
  config;
11417
11696
  liveStructuredReasoningEffort;
11697
+ liveMemoryModel;
11418
11698
  extractionBudgets = new AsyncLocalStorage();
11419
11699
  diagnosticScopes = new AsyncLocalStorage();
11420
11700
  diagnostics;
@@ -11433,6 +11713,7 @@ var DshModelBridge = class {
11433
11713
  warnedOffFallbackRoutes = /* @__PURE__ */ new Set();
11434
11714
  adaptersUpdatedListeners = /* @__PURE__ */ new Set();
11435
11715
  structuredReasoningEffort;
11716
+ memoryModel;
11436
11717
  /** True only when the exact provider route has a registered DSH adapter. */
11437
11718
  isReady(session) {
11438
11719
  try {
@@ -11452,6 +11733,20 @@ var DshModelBridge = class {
11452
11733
  setStructuredReasoningEffort(mode) {
11453
11734
  this.structuredReasoningEffort = mode;
11454
11735
  }
11736
+ setMemoryModel(value) {
11737
+ this.memoryModel = resolveMemoryModel(value);
11738
+ for (const listener of this.adaptersUpdatedListeners) listener();
11739
+ }
11740
+ memoryModelSelection() {
11741
+ const selected = resolveMemoryModel(this.liveMemoryModel ? this.liveMemoryModel() : this.memoryModel);
11742
+ return selected ?? (this.config.provider && this.config.model ? { mode: "custom", provider: this.config.provider, model: this.config.model } : { mode: "auto" });
11743
+ }
11744
+ async memoryModelCatalog(provider) {
11745
+ const providers = this.ctx.llm.listProviders().map(({ id, name: name2 }) => ({ id, name: name2 }));
11746
+ if (provider && !providers.some((item) => item.id === provider)) throw new Error("\u670D\u52A1\u5546\u5F53\u524D\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5 DSH \u7684 API \u914D\u7F6E\u6216\u91CD\u65B0\u9009\u62E9");
11747
+ const models = provider ? (await this.ctx.llm.listModels(provider)).map(({ id, name: name2 }) => ({ id, name: name2 })) : [];
11748
+ return { selection: this.memoryModelSelection(), providers, models };
11749
+ }
11455
11750
  currentStructuredReasoningEffort() {
11456
11751
  return this.liveStructuredReasoningEffort?.() ?? this.structuredReasoningEffort;
11457
11752
  }
@@ -12216,8 +12511,9 @@ Correct the previous Topic output using these validation errors: ${JSON.stringif
12216
12511
  }
12217
12512
  resolveRoute(session) {
12218
12513
  const request = session?.requestHeader()?.config;
12219
- if (this.config.provider && this.config.model) {
12220
- return { provider: this.config.provider, model: this.config.model };
12514
+ const selected = this.memoryModelSelection();
12515
+ if (selected.mode === "custom") {
12516
+ return { provider: selected.provider, model: selected.model };
12221
12517
  }
12222
12518
  if (request) return { provider: request.provider, model: request.model };
12223
12519
  const fallback = this.ctx.agentDefaultModel.currentSelection();
@@ -12641,6 +12937,205 @@ import { createUserMessage as createUserMessage2 } from "@deepseek-ai/dsh-llm";
12641
12937
  import { openNativePath } from "@deepseek-ai/dsh-native-command";
12642
12938
  import { validateArgs as validateArgs2 } from "@deepseek-ai/dsh-tools";
12643
12939
 
12940
+ // src/embedding.ts
12941
+ var EmbeddingBridge = class _EmbeddingBridge {
12942
+ constructor(config) {
12943
+ this.config = config;
12944
+ }
12945
+ config;
12946
+ queryVectorCache = /* @__PURE__ */ new Map();
12947
+ queryVectorCacheOrder = [];
12948
+ static QUERY_CACHE_LIMIT = 32;
12949
+ /** True when embedding is configured (URL + key + model all present). */
12950
+ get embeddingReady() {
12951
+ return Boolean(this.config.embeddingUrl?.trim() && this.config.embeddingKey?.trim() && this.config.embeddingModel?.trim());
12952
+ }
12953
+ /**
12954
+ * Compute the embedding vector for a query string. Repeated queries hit an
12955
+ * in-memory LRU cache, so a session that keeps asking in the same shape pays
12956
+ * for one call, not one per turn. Returns null when embedding is not
12957
+ * configured, the query is blank, or the call fails.
12958
+ */
12959
+ /**
12960
+ * Cache identity: the endpoint and model the vector was computed with. Two
12961
+ * different models (or the same model behind a different endpoint) produce
12962
+ * incompatible vectors, so the query text alone is not a usable cache key —
12963
+ * switching models would otherwise keep serving the previous model's vector.
12964
+ */
12965
+ cacheIdentity() {
12966
+ return `${this.config.embeddingUrl?.trim() ?? ""}|${this.config.embeddingModel?.trim() ?? ""}`;
12967
+ }
12968
+ /** Drop every cached query vector (called when embedding settings change). */
12969
+ invalidateQueryCache() {
12970
+ this.queryVectorCache.clear();
12971
+ this.queryVectorCacheOrder.length = 0;
12972
+ }
12973
+ async embedQuery(query) {
12974
+ if (!this.embeddingReady || !query.trim()) return null;
12975
+ const identity = this.cacheIdentity();
12976
+ const key = `${identity}\0${query}`;
12977
+ const cached = this.queryVectorCache.get(key);
12978
+ if (cached) return cached;
12979
+ try {
12980
+ const vector = await this.callEmbeddingApi([query]);
12981
+ if (!vector || vector.length === 0) return null;
12982
+ const first = vector[0];
12983
+ if (!first || first.length === 0) return null;
12984
+ if (this.cacheIdentity() !== identity) return first;
12985
+ this.queryVectorCache.set(key, first);
12986
+ this.queryVectorCacheOrder.push(key);
12987
+ if (this.queryVectorCacheOrder.length > _EmbeddingBridge.QUERY_CACHE_LIMIT) {
12988
+ const evicted = this.queryVectorCacheOrder.shift();
12989
+ if (evicted !== void 0) this.queryVectorCache.delete(evicted);
12990
+ }
12991
+ return first;
12992
+ } catch {
12993
+ return null;
12994
+ }
12995
+ }
12996
+ /**
12997
+ * Compute embedding vectors for Event texts (write and backfill path).
12998
+ * Returns null when embedding is not configured or the call fails, so the
12999
+ * caller writes nothing and retries later.
13000
+ */
13001
+ /** True when rerank is configured (URL + key + model all present). */
13002
+ get rerankReady() {
13003
+ return Boolean(this.config.rerankUrl?.trim() && this.config.rerankKey?.trim() && this.config.rerankModel?.trim());
13004
+ }
13005
+ async embedEvents(texts) {
13006
+ if (!this.embeddingReady || texts.length === 0) return null;
13007
+ try {
13008
+ return await this.callEmbeddingApi(texts);
13009
+ } catch {
13010
+ return null;
13011
+ }
13012
+ }
13013
+ /**
13014
+ * Rerank documents against a query. Returns one relevance score per document
13015
+ * in input order (higher = more relevant), or null when rerank is not
13016
+ * configured or the call fails — the caller then keeps its original order.
13017
+ *
13018
+ * Hard 5-second timeout: this runs on the passive-recall request path, so a
13019
+ * slow rerank service must never delay the conversation. On timeout the
13020
+ * request is aborted and null is returned silently.
13021
+ */
13022
+ async rerank(query, documents) {
13023
+ if (!this.rerankReady || documents.length === 0 || !query.trim()) return null;
13024
+ const controller = new AbortController();
13025
+ const timer = setTimeout(() => controller.abort(), 5e3);
13026
+ try {
13027
+ const response = await fetch(`${this.config.rerankUrl.trim()}/rerank`, {
13028
+ method: "POST",
13029
+ headers: {
13030
+ "content-type": "application/json",
13031
+ authorization: `Bearer ${this.config.rerankKey.trim()}`
13032
+ },
13033
+ body: JSON.stringify({
13034
+ model: this.config.rerankModel.trim(),
13035
+ query,
13036
+ documents
13037
+ }),
13038
+ signal: controller.signal
13039
+ });
13040
+ if (!response.ok) return null;
13041
+ const data = await response.json();
13042
+ if (!data.results || data.results.length !== documents.length) return null;
13043
+ const scores = new Array(documents.length).fill(0);
13044
+ for (const { index, relevance_score } of data.results) {
13045
+ if (Number.isInteger(index) && index >= 0 && index < documents.length && Number.isFinite(relevance_score)) {
13046
+ scores[index] = relevance_score;
13047
+ }
13048
+ }
13049
+ return scores;
13050
+ } catch {
13051
+ return null;
13052
+ } finally {
13053
+ clearTimeout(timer);
13054
+ }
13055
+ }
13056
+ /**
13057
+ * List available models from the rerank endpoint (/models).
13058
+ * Accepts optional {url, key} overrides for pre-save validation.
13059
+ */
13060
+ async listRerankModels(override) {
13061
+ return listEndpointModels(
13062
+ (override?.url ?? this.config.rerankUrl ?? "").trim(),
13063
+ (override?.key ?? this.config.rerankKey ?? "").trim()
13064
+ );
13065
+ }
13066
+ /**
13067
+ * List available models from the embedding endpoint (/models).
13068
+ * Accepts optional {url, key} overrides so the settings UI can validate
13069
+ * credentials before saving them.
13070
+ */
13071
+ async listEmbeddingModels(override) {
13072
+ return listEndpointModels(
13073
+ (override?.url ?? this.config.embeddingUrl ?? "").trim(),
13074
+ (override?.key ?? this.config.embeddingKey ?? "").trim()
13075
+ );
13076
+ }
13077
+ /** Cosine similarity between two vectors; 0 for mismatched or empty input. */
13078
+ static cosineSimilarity(a, b) {
13079
+ if (a.length !== b.length || a.length === 0) return 0;
13080
+ let dot = 0;
13081
+ let normA = 0;
13082
+ let normB = 0;
13083
+ for (let i = 0; i < a.length; i++) {
13084
+ const left = a[i];
13085
+ const right = b[i];
13086
+ dot += left * right;
13087
+ normA += left * left;
13088
+ normB += right * right;
13089
+ }
13090
+ if (normA === 0 || normB === 0) return 0;
13091
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
13092
+ }
13093
+ async callEmbeddingApi(texts) {
13094
+ const controller = new AbortController();
13095
+ const timer = setTimeout(() => controller.abort(), 1e4);
13096
+ try {
13097
+ const response = await fetch(`${this.config.embeddingUrl.trim()}/embeddings`, {
13098
+ method: "POST",
13099
+ headers: {
13100
+ "content-type": "application/json",
13101
+ authorization: `Bearer ${this.config.embeddingKey.trim()}`
13102
+ },
13103
+ body: JSON.stringify({
13104
+ model: this.config.embeddingModel.trim(),
13105
+ input: texts
13106
+ }),
13107
+ signal: controller.signal
13108
+ });
13109
+ if (!response.ok) return null;
13110
+ const data = await response.json();
13111
+ if (!data.data || data.data.length !== texts.length) return null;
13112
+ return data.data.map(({ embedding }) => embedding);
13113
+ } catch {
13114
+ return null;
13115
+ } finally {
13116
+ clearTimeout(timer);
13117
+ }
13118
+ }
13119
+ };
13120
+ async function listEndpointModels(url, key) {
13121
+ if (!url || !key) return [];
13122
+ const controller = new AbortController();
13123
+ const timer = setTimeout(() => controller.abort(), 5e3);
13124
+ try {
13125
+ const response = await fetch(`${url}/models`, {
13126
+ headers: { authorization: `Bearer ${key}` },
13127
+ signal: controller.signal
13128
+ });
13129
+ if (!response.ok) return [];
13130
+ const data = await response.json();
13131
+ return (data.data ?? []).map(({ id }) => id).filter(Boolean);
13132
+ } catch {
13133
+ return [];
13134
+ } finally {
13135
+ clearTimeout(timer);
13136
+ }
13137
+ }
13138
+
12644
13139
  // src/fold.ts
12645
13140
  function renderBlocks(blocks) {
12646
13141
  const output = [];
@@ -13240,6 +13735,20 @@ function graphProjectionCanRun(job, now = Date.now()) {
13240
13735
  var AUTO_EVENT_LIMIT = 4;
13241
13736
  var AUTO_ELEMENT_LIMIT = 4;
13242
13737
  var AUTO_MEMORY_TOKEN_BUDGET = 900;
13738
+ function eventTextForEmbedding(event) {
13739
+ return `${event.title} ${event.summary}`;
13740
+ }
13741
+ var VECTOR_SETTING_KEYS = [
13742
+ "embeddingUrl",
13743
+ "embeddingKey",
13744
+ "embeddingModel",
13745
+ "vectorWeight",
13746
+ "embeddingMinScore",
13747
+ "rerankUrl",
13748
+ "rerankKey",
13749
+ "rerankModel"
13750
+ ];
13751
+ var VECTOR_SECRET_MASK = "********";
13243
13752
  function projectKey(cwd) {
13244
13753
  const canonical2 = resolve3(cwd ?? process.cwd()).replaceAll("\\", "/").toLowerCase();
13245
13754
  return createHash6("sha256").update(canonical2).digest("hex").slice(0, 20);
@@ -13337,7 +13846,10 @@ function feedbackDraftUrl(namespace, origin) {
13337
13846
  const route = `/?${params.toString()}`;
13338
13847
  return origin ? new URL(route, origin).href : route;
13339
13848
  }
13340
- var StrataGateRuntime = class {
13849
+ function eventContentHash(event) {
13850
+ return createHash6("sha256").update(`${event.title}\0${event.summary}`).digest("hex");
13851
+ }
13852
+ var StrataGateRuntime = class _StrataGateRuntime {
13341
13853
  constructor(config, models, onIngestError = () => {
13342
13854
  }, flushNativeSession = async () => {
13343
13855
  }, feedbackOrigin = () => void 0, openPath = openNativePath) {
@@ -13353,6 +13865,7 @@ var StrataGateRuntime = class {
13353
13865
  this.blockTurnSize = config.blockTurnSize;
13354
13866
  this.blockDecayLambda = config.blockDecayLambda;
13355
13867
  this.agentMemoryRetrievalWeight = config.agentMemoryRetrievalWeight ?? 1;
13868
+ this.embedding = new EmbeddingBridge(config);
13356
13869
  this.disposeAdaptersUpdated = this.models.onAdaptersUpdated(() => this.wakeModelWorkers());
13357
13870
  this.disposeWorkChanged = SqliteStorage.onBackgroundWorkChanged(config.database, () => this.wakeBackgroundWorker());
13358
13871
  this.scheduleBackgroundWorker(BACKGROUND_WORKER_INITIAL_DELAY_MS);
@@ -13432,6 +13945,12 @@ var StrataGateRuntime = class {
13432
13945
  blockTurnSize;
13433
13946
  blockDecayLambda;
13434
13947
  agentMemoryRetrievalWeight;
13948
+ /** Host-side embedding bridge: every embedding HTTP call lives behind it. */
13949
+ embedding;
13950
+ /** Event IDs currently being embedded, so one Event is never billed twice. */
13951
+ vectorBackfillInFlight = /* @__PURE__ */ new Set();
13952
+ /** Timestamp of the last successful vector write; see backfillEventVectors. */
13953
+ vectorBackfillLastRunAt = 0;
13435
13954
  graphMetadata;
13436
13955
  graphPreviews = /* @__PURE__ */ new Map();
13437
13956
  graphStore() {
@@ -13493,6 +14012,9 @@ var StrataGateRuntime = class {
13493
14012
  this.wakeBackgroundWorker();
13494
14013
  return this.adminGraphSettings();
13495
14014
  }
14015
+ adminMemoryModelCatalog(provider) {
14016
+ return this.models.memoryModelCatalog(provider);
14017
+ }
13496
14018
  get agentMemoryEnabled() {
13497
14019
  return this.config.agentMemoryEnabled !== false;
13498
14020
  }
@@ -14030,13 +14552,18 @@ var StrataGateRuntime = class {
14030
14552
  if (!query.trim() && searchOptions.temporalIntent === void 0) searchOptions.temporalIntent = "first";
14031
14553
  if (!query.trim() && !searchOptions.eventType && !searchOptions.participants?.length && !searchOptions.happenedFrom && !searchOptions.happenedTo) totalSourceEvents = eventIds.length;
14032
14554
  }
14555
+ const vectorRanking = query.trim() ? await this.computeVectorRanking(memory, query, {
14556
+ ...searchOptions,
14557
+ ...eventIds !== void 0 ? { eventIds } : {}
14558
+ }) : void 0;
14033
14559
  const results = await memory.searchEvents(query, {
14034
14560
  ...searchOptions,
14035
14561
  ...eventIds !== void 0 ? { eventIds } : {},
14036
14562
  // Agent-recorded events ride their own top-k lane and fuse with the
14037
14563
  // passive pool by the configured weight; they arrive as ordinary event
14038
14564
  // results with the same evidence refs and reinforcement path.
14039
- agentMemoryWeight: this.agentMemoryRetrievalWeight
14565
+ agentMemoryWeight: this.agentMemoryRetrievalWeight,
14566
+ ...vectorRanking ? { vectorRanking, vectorWeight: this.vectorWeight } : {}
14040
14567
  });
14041
14568
  return this.batch(
14042
14569
  session,
@@ -14419,9 +14946,11 @@ var StrataGateRuntime = class {
14419
14946
  await this.syncRequestSurface(session, memory);
14420
14947
  const openTail = memory.listOpenTail(threadId);
14421
14948
  const activationQuery = [currentUserMessage(session), renderMessages(recentTurns(openTail, 2))].filter(Boolean).join("\n\n");
14949
+ const vectorRanking = activationQuery ? await this.computeVectorRanking(memory, activationQuery) : void 0;
14422
14950
  const eventHits = activationQuery ? await memory.searchEvents(activationQuery, {
14423
14951
  limit: 20,
14424
- agentMemoryWeight: this.agentMemoryRetrievalWeight
14952
+ agentMemoryWeight: this.agentMemoryRetrievalWeight,
14953
+ ...vectorRanking ? { vectorRanking, vectorWeight: this.vectorWeight } : {}
14425
14954
  }) : [];
14426
14955
  let graphResults = [];
14427
14956
  if (this.graphEnabled && activationQuery && typeof memory.searchGraphNodes === "function") {
@@ -14452,7 +14981,124 @@ var StrataGateRuntime = class {
14452
14981
  const currentEventIds = new Set(memory.listAllEvents().filter((event) => event.sourceBlockId !== void 0 && currentBlockIds.has(event.sourceBlockId)).map(({ id }) => id));
14453
14982
  const longTermEvents = events.filter((event) => !currentEventIds.has(event.id)).slice(0, AUTO_EVENT_LIMIT);
14454
14983
  graphResults = graphResults.filter((result) => !(result.provenanceEventIds ?? result.node.sourceEventIds).some((id) => currentEventIds.has(id))).slice(0, AUTO_ELEMENT_LIMIT);
14455
- return renderActivatedMemory(longTermEvents, this.graphEnabled ? graphResults : []);
14984
+ let rankedLongTermEvents = longTermEvents;
14985
+ if (this.embedding.rerankReady && activationQuery && longTermEvents.length > 1) {
14986
+ const reranked = await this.rerankEvents(activationQuery, events.filter((event) => !currentEventIds.has(event.id)));
14987
+ if (reranked) rankedLongTermEvents = reranked.slice(0, AUTO_EVENT_LIMIT);
14988
+ }
14989
+ return renderActivatedMemory(rankedLongTermEvents, this.graphEnabled ? graphResults : []);
14990
+ }
14991
+ /**
14992
+ * Rerank Events against the query. Returns the reordered candidates, or null
14993
+ * on timeout/failure so the caller falls back to the fused order unchanged.
14994
+ * Only the first 20 candidates are sent: the request stays small and the
14995
+ * result only ever fills the handful of passive-recall slots.
14996
+ */
14997
+ async rerankEvents(query, candidates) {
14998
+ if (!this.embedding.rerankReady || candidates.length < 2) return null;
14999
+ const top = candidates.slice(0, 20);
15000
+ const scores = await this.embedding.rerank(query, top.map(eventTextForEmbedding));
15001
+ if (!scores) return null;
15002
+ const indexed = top.map((event, index) => ({ event, score: scores[index] ?? 0 }));
15003
+ indexed.sort((left, right) => right.score - left.score);
15004
+ return indexed.map(({ event }) => event);
15005
+ }
15006
+ /**
15007
+ * Compute the semantic ranking for one query against stored Event vectors.
15008
+ * Returns Event IDs in descending similarity order, or undefined when
15009
+ * embedding is not configured (retrieval then stays exactly lexical).
15010
+ *
15011
+ * The host computes the query embedding (in-memory cache) and the cosine
15012
+ * similarities; core only receives the finished ranking.
15013
+ *
15014
+ * Two behaviors worth keeping: the whole vector table is read with ONE query
15015
+ * per retrieval pass, and missing vectors trigger backfill regardless of
15016
+ * whether anything scored — otherwise a fresh or legacy database, which has
15017
+ * events but no vectors yet, could never start vectorizing at all.
15018
+ */
15019
+ async computeVectorRanking(memory, query, filters) {
15020
+ if ((this.config.vectorWeight ?? 1) <= 0) return void 0;
15021
+ if (!this.embedding.embeddingReady) return void 0;
15022
+ const queryTokens = query.trim().split(/[\s\p{P}\p{S}]+/u).filter(Boolean);
15023
+ if (queryTokens.length === 0) return void 0;
15024
+ const queryVector = await this.embedding.embedQuery(query);
15025
+ if (!queryVector) return void 0;
15026
+ const model = this.config.embeddingModel.trim();
15027
+ const activeEvents = memory.listAllEvents().filter((event) => event.status === "active" || event.status === "superseded").filter((event) => filters === void 0 || eventMatchesSearchFilters(event, filters));
15028
+ if (activeEvents.length === 0) return void 0;
15029
+ const records = memory.listEventVectorRecords(model);
15030
+ const scored = [];
15031
+ const missingVectorIds = [];
15032
+ for (const event of activeEvents) {
15033
+ const record3 = records.get(event.id);
15034
+ if (record3 && record3.contentHash === eventContentHash(event)) {
15035
+ scored.push({ id: event.id, score: EmbeddingBridge.cosineSimilarity(queryVector, record3.vector) });
15036
+ } else {
15037
+ missingVectorIds.push(event.id);
15038
+ }
15039
+ }
15040
+ if (missingVectorIds.length > 0) void this.backfillEventVectors(memory, missingVectorIds);
15041
+ const minScore = this.config.embeddingMinScore ?? 0.3;
15042
+ const relevant = scored.filter(({ score }) => score > minScore);
15043
+ if (relevant.length === 0) return void 0;
15044
+ relevant.sort((left, right) => right.score - left.score);
15045
+ return relevant.slice(0, _StrataGateRuntime.VECTOR_RANKING_TOP_K).map(({ id }) => id);
15046
+ }
15047
+ /** Cap on how many semantically ranked Events one retrieval pass may fuse. */
15048
+ static VECTOR_RANKING_TOP_K = 50;
15049
+ static VECTOR_BACKFILL_COOLDOWN_MS = 3e4;
15050
+ static VECTOR_BACKFILL_BATCH_LIMIT = 20;
15051
+ /** Vectorize freshly written Events (fire-and-forget; never blocks a write). */
15052
+ async vectorizeNewEvents(memory, eventIds) {
15053
+ if (!this.embedding.embeddingReady || eventIds.length === 0) return;
15054
+ this.vectorBackfillLastRunAt = 0;
15055
+ await this.backfillEventVectors(memory, eventIds);
15056
+ }
15057
+ /**
15058
+ * Compute and persist embeddings for Events that lack them. Fire-and-forget:
15059
+ * the caller never awaits retrieval latency on it, and every failure keeps
15060
+ * the old state so the next retrieval retries.
15061
+ *
15062
+ * In-flight tracking keeps one Event from being embedded twice concurrently;
15063
+ * a batch cap bounds the cost of one sweep. The cooldown is armed ONLY after
15064
+ * a successful write — arming it on entry meant a failed or hung API call
15065
+ * still renewed the window, and since retrieval fires every few seconds the
15066
+ * window was always fresh, so nothing was ever written again.
15067
+ */
15068
+ async backfillEventVectors(memory, eventIds) {
15069
+ try {
15070
+ if ((this.config.vectorWeight ?? 1) <= 0) return;
15071
+ if (!this.embedding.embeddingReady) return;
15072
+ if (Date.now() - this.vectorBackfillLastRunAt < _StrataGateRuntime.VECTOR_BACKFILL_COOLDOWN_MS) return;
15073
+ const model = this.config.embeddingModel.trim();
15074
+ const eventMap = new Map(memory.listAllEvents().map((event) => [event.id, event]));
15075
+ const toEmbed = eventIds.filter((id) => !this.vectorBackfillInFlight.has(id)).map((id) => eventMap.get(id)).filter((event) => event !== void 0).slice(0, _StrataGateRuntime.VECTOR_BACKFILL_BATCH_LIMIT);
15076
+ if (toEmbed.length === 0) return;
15077
+ for (const event of toEmbed) this.vectorBackfillInFlight.add(event.id);
15078
+ try {
15079
+ const work = toEmbed.map((event) => ({
15080
+ event,
15081
+ text: eventTextForEmbedding(event),
15082
+ contentHash: eventContentHash(event)
15083
+ }));
15084
+ const vectors = await this.embedding.embedEvents(work.map(({ text: text3 }) => text3));
15085
+ if (!vectors) return;
15086
+ let written = 0;
15087
+ for (let index = 0; index < work.length && index < vectors.length; index++) {
15088
+ const { event, contentHash } = work[index];
15089
+ const vector = vectors[index];
15090
+ if (!vector || vector.length === 0) continue;
15091
+ if (eventContentHash(event) !== contentHash) continue;
15092
+ memory.setEventVector(event.id, model, vector.length, vector, contentHash);
15093
+ written += 1;
15094
+ }
15095
+ if (written > 0) this.vectorBackfillLastRunAt = Date.now();
15096
+ } finally {
15097
+ for (const event of toEmbed) this.vectorBackfillInFlight.delete(event.id);
15098
+ }
15099
+ } catch (error) {
15100
+ this.onIngestError(error);
15101
+ }
14456
15102
  }
14457
15103
  /**
14458
15104
  * Replace the just-sealed DSH turns with one native surface message. The raw
@@ -15075,6 +15721,7 @@ var StrataGateRuntime = class {
15075
15721
  } : {}
15076
15722
  }));
15077
15723
  await this.persistSuccessfulResponses(memory);
15724
+ if (result.recorded && result.eventId) void this.vectorizeNewEvents(memory, [result.eventId]);
15078
15725
  return this.agentMemoryResultView(session, result);
15079
15726
  }
15080
15727
  agentMemoryResultView(session, result) {
@@ -15209,6 +15856,28 @@ var StrataGateRuntime = class {
15209
15856
  this.blockTurnSize = metadata2.blockTurnSize() ?? this.config.blockTurnSize;
15210
15857
  this.blockDecayLambda = metadata2.blockDecayLambda() ?? this.config.blockDecayLambda;
15211
15858
  this.agentMemoryRetrievalWeight = metadata2.agentMemoryRetrievalWeight() ?? this.config.agentMemoryRetrievalWeight ?? 1;
15859
+ const storedEmbeddingUrl = this.readVectorSetting("embeddingUrl");
15860
+ if (storedEmbeddingUrl !== null) this.config.embeddingUrl = storedEmbeddingUrl;
15861
+ const storedEmbeddingKey = this.readVectorSetting("embeddingKey");
15862
+ if (storedEmbeddingKey !== null) this.config.embeddingKey = storedEmbeddingKey;
15863
+ const storedEmbeddingModel = this.readVectorSetting("embeddingModel");
15864
+ if (storedEmbeddingModel !== null) this.config.embeddingModel = storedEmbeddingModel;
15865
+ const savedVectorWeight = this.readVectorSetting("vectorWeight");
15866
+ const storedVectorWeight = Number(savedVectorWeight);
15867
+ if (savedVectorWeight !== null && Number.isFinite(storedVectorWeight)) {
15868
+ this.config.vectorWeight = Math.min(5, Math.max(0, storedVectorWeight));
15869
+ }
15870
+ const savedMinScore = this.readVectorSetting("embeddingMinScore");
15871
+ const storedMinScore = Number(savedMinScore);
15872
+ if (savedMinScore !== null && Number.isFinite(storedMinScore)) {
15873
+ this.config.embeddingMinScore = Math.min(1, Math.max(0, storedMinScore));
15874
+ }
15875
+ const storedRerankUrl = this.readVectorSetting("rerankUrl");
15876
+ if (storedRerankUrl !== null) this.config.rerankUrl = storedRerankUrl;
15877
+ const storedRerankKey = this.readVectorSetting("rerankKey");
15878
+ if (storedRerankKey !== null) this.config.rerankKey = storedRerankKey;
15879
+ const storedRerankModel = this.readVectorSetting("rerankModel");
15880
+ if (storedRerankModel !== null) this.config.rerankModel = storedRerankModel;
15212
15881
  } finally {
15213
15882
  metadata2.close();
15214
15883
  }
@@ -15722,6 +16391,134 @@ var StrataGateRuntime = class {
15722
16391
  if (owned) await memory.close();
15723
16392
  }
15724
16393
  }
16394
+ /** Effective vector-lane weight; 0 keeps the lane out of retrieval entirely. */
16395
+ get vectorWeight() {
16396
+ return this.config.vectorWeight ?? 1;
16397
+ }
16398
+ /**
16399
+ * Settings-API read model for semantic recall. Returns the effective values
16400
+ * (persisted settings already merged over host config), never secrets that
16401
+ * are not already configured by the same user.
16402
+ */
16403
+ adminVectorSettings() {
16404
+ const embeddingKeyConfigured = Boolean(this.config.embeddingKey?.trim());
16405
+ const rerankKeyConfigured = Boolean(this.config.rerankKey?.trim());
16406
+ return {
16407
+ embeddingUrl: this.config.embeddingUrl ?? "",
16408
+ embeddingKey: embeddingKeyConfigured ? VECTOR_SECRET_MASK : "",
16409
+ embeddingKeyConfigured,
16410
+ embeddingModel: this.config.embeddingModel ?? "",
16411
+ vectorWeight: this.vectorWeight,
16412
+ embeddingMinScore: this.config.embeddingMinScore ?? 0.3,
16413
+ embeddingReady: this.embedding.embeddingReady,
16414
+ rerankUrl: this.config.rerankUrl ?? "",
16415
+ rerankKey: rerankKeyConfigured ? VECTOR_SECRET_MASK : "",
16416
+ rerankKeyConfigured,
16417
+ rerankModel: this.config.rerankModel ?? "",
16418
+ rerankReady: this.embedding.rerankReady
16419
+ };
16420
+ }
16421
+ /**
16422
+ * Persist embedding settings and hot-swap them into the running bridge.
16423
+ * Omitted fields keep their current value; an empty string clears a field,
16424
+ * which switches semantic recall off again without touching stored vectors.
16425
+ */
16426
+ adminSetVectorSettings(input) {
16427
+ const next = {};
16428
+ const text3 = (value, label2) => {
16429
+ if (value === void 0) return void 0;
16430
+ const trimmed = value.trim();
16431
+ if (trimmed.length > 2e3) throw new TypeError(`${label2} must not exceed 2000 characters`);
16432
+ if ((label2 === "embeddingKey" || label2 === "rerankKey") && trimmed === VECTOR_SECRET_MASK) return void 0;
16433
+ return trimmed;
16434
+ };
16435
+ for (const key of ["embeddingUrl", "embeddingKey", "embeddingModel", "rerankUrl", "rerankKey", "rerankModel"]) {
16436
+ const value = text3(input[key], key);
16437
+ if (value !== void 0) next[key] = value;
16438
+ }
16439
+ if (input.vectorWeight !== void 0) {
16440
+ if (!Number.isFinite(input.vectorWeight) || input.vectorWeight < 0 || input.vectorWeight > 5) {
16441
+ throw new TypeError("vectorWeight must be a finite number between 0 and 5");
16442
+ }
16443
+ next.vectorWeight = String(input.vectorWeight);
16444
+ }
16445
+ if (input.embeddingMinScore !== void 0) {
16446
+ if (!Number.isFinite(input.embeddingMinScore) || input.embeddingMinScore < 0 || input.embeddingMinScore > 1) {
16447
+ throw new TypeError("embeddingMinScore must be a finite number between 0 and 1");
16448
+ }
16449
+ next.embeddingMinScore = String(input.embeddingMinScore);
16450
+ }
16451
+ if (Object.keys(next).length === 0) {
16452
+ throw new TypeError("embeddingUrl, embeddingKey, embeddingModel, vectorWeight, embeddingMinScore, rerankUrl, rerankKey, or rerankModel is required");
16453
+ }
16454
+ this.writeVectorSettings(next);
16455
+ if (next.embeddingUrl !== void 0) this.config.embeddingUrl = next.embeddingUrl;
16456
+ if (next.embeddingKey !== void 0) this.config.embeddingKey = next.embeddingKey;
16457
+ if (next.embeddingModel !== void 0) this.config.embeddingModel = next.embeddingModel;
16458
+ if (next.rerankUrl !== void 0) this.config.rerankUrl = next.rerankUrl;
16459
+ if (next.rerankKey !== void 0) this.config.rerankKey = next.rerankKey;
16460
+ if (next.rerankModel !== void 0) this.config.rerankModel = next.rerankModel;
16461
+ if (next.vectorWeight !== void 0) this.config.vectorWeight = Number(next.vectorWeight);
16462
+ if (next.embeddingMinScore !== void 0) this.config.embeddingMinScore = Number(next.embeddingMinScore);
16463
+ if (next.embeddingUrl !== void 0 || next.embeddingKey !== void 0 || next.embeddingModel !== void 0) {
16464
+ this.embedding.invalidateQueryCache();
16465
+ }
16466
+ return this.adminVectorSettings();
16467
+ }
16468
+ /** List models from the configured (or supplied) embedding endpoint. */
16469
+ async adminListEmbeddingModels(override) {
16470
+ return this.embedding.listEmbeddingModels(override);
16471
+ }
16472
+ /** List models from the configured (or supplied) rerank endpoint. */
16473
+ async adminListRerankModels(override) {
16474
+ return this.embedding.listRerankModels(override);
16475
+ }
16476
+ /**
16477
+ * Read one persisted embedding/rerank setting, or null when it was never
16478
+ * saved. Kept next to the settings API instead of DshMetadataStore because
16479
+ * this group is written by the settings API and read at startup only.
16480
+ */
16481
+ readVectorSetting(key) {
16482
+ if (this.config.database === ":memory:" || !existsSync2(this.config.database)) return null;
16483
+ const database = new DatabaseSync5(this.config.database, { readOnly: true });
16484
+ try {
16485
+ const table = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_settings'").get();
16486
+ if (!table) return null;
16487
+ const row = database.prepare("SELECT value FROM stratagate_dsh_settings WHERE key = ?").get(`vector.${key}`);
16488
+ return row?.value ?? null;
16489
+ } catch {
16490
+ return null;
16491
+ } finally {
16492
+ database.close();
16493
+ }
16494
+ }
16495
+ /** Persist the supplied embedding/rerank settings; omitted keys keep their value. */
16496
+ writeVectorSettings(values) {
16497
+ if (this.config.database === ":memory:") return;
16498
+ const database = new DatabaseSync5(this.config.database);
16499
+ try {
16500
+ database.exec("PRAGMA busy_timeout = 5000");
16501
+ database.exec(`
16502
+ CREATE TABLE IF NOT EXISTS stratagate_dsh_settings (
16503
+ key TEXT PRIMARY KEY,
16504
+ value TEXT NOT NULL,
16505
+ updated_at TEXT NOT NULL
16506
+ ) STRICT
16507
+ `);
16508
+ const statement = database.prepare(`
16509
+ INSERT INTO stratagate_dsh_settings (key, value, updated_at)
16510
+ VALUES (?, ?, ?)
16511
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
16512
+ `);
16513
+ const now = (/* @__PURE__ */ new Date()).toISOString();
16514
+ for (const key of VECTOR_SETTING_KEYS) {
16515
+ const value = values[key];
16516
+ if (value !== void 0) statement.run(`vector.${key}`, value, now);
16517
+ }
16518
+ } finally {
16519
+ database.close();
16520
+ }
16521
+ }
15725
16522
  adminWorkspaceName(namespace) {
15726
16523
  const remembered = this.workspaceNames.get(namespace);
15727
16524
  if (remembered) return remembered;
@@ -17009,15 +17806,25 @@ ${profile}
17009
17806
  return result;
17010
17807
  }
17011
17808
  }));
17809
+ let assembledModel;
17012
17810
  scoped.on("system-prompt/assemble", async (_assembly, _context, next) => {
17811
+ const selected = this.modelOptions();
17013
17812
  const assembled = await next();
17813
+ assembledModel = selected;
17014
17814
  return {
17015
17815
  ...assembled,
17016
17816
  sections: [{ name: "stratagate:dreaming", text: this.systemPrompt(), interpolate: false }],
17017
17817
  contexts: [],
17818
+ variables: { ...assembled.variables, provider: selected.provider, model: selected.model },
17018
17819
  tools: modelTools
17019
17820
  };
17020
17821
  });
17822
+ scoped.on("agent/request", async (_payload, next) => {
17823
+ const resolved = await next();
17824
+ const selected = assembledModel ?? this.modelOptions();
17825
+ const { reasoningEffort: _effort, ...request } = resolved;
17826
+ return { ...request, provider: selected.provider, model: selected.model };
17827
+ });
17021
17828
  scoped.on("agent/pre-step", async (_payload, next) => {
17022
17829
  await binding.accounting;
17023
17830
  let run = await this.runtime.dreamingRun(binding.namespace, binding.id);
@@ -18314,18 +19121,65 @@ async function overview(runtime, cachedEntries) {
18314
19121
  readonly: true,
18315
19122
  settingsWritable: true,
18316
19123
  graphSettings: runtime.adminGraphSettings?.() ?? { enabled: false, paused: false, legacy: false, noticeSeen: true, everEnabled: false },
19124
+ // Semantic-recall settings are read back through the same PATCH endpoint
19125
+ // that writes them, so the panel never has to guess the effective values.
19126
+ vectorSettings: runtime.adminVectorSettings?.() ?? { embeddingUrl: "", embeddingKey: "", embeddingKeyConfigured: false, embeddingModel: "", vectorWeight: 1, embeddingMinScore: 0.3, embeddingReady: false, rerankUrl: "", rerankKey: "", rerankKeyConfigured: false, rerankModel: "", rerankReady: false },
18317
19127
  dataDirectory: runtime.adminDataDirectory?.() ?? null,
18318
19128
  pluginVersion: STRATAGATE_DSH_VERSION,
18319
19129
  harnessVersion: installedPackageVersion(["@deepseek-ai/dsh", "@deepseek-ai/dsh-session"]),
18320
19130
  namespaces: rows
18321
19131
  };
18322
19132
  }
18323
- async function updateSettings(runtime, url) {
19133
+ async function jsonBody(req, label2, limit = 16 * 1024) {
19134
+ let suppliedBody = req.body;
19135
+ if (suppliedBody === void 0 && typeof req[Symbol.asyncIterator] === "function") {
19136
+ const chunks = [];
19137
+ let size = 0;
19138
+ for await (const chunk of req) {
19139
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
19140
+ size += value.length;
19141
+ if (size > limit) throw new AdminHttpError(413, `${label2} exceeds ${limit} bytes`);
19142
+ chunks.push(value);
19143
+ }
19144
+ suppliedBody = Buffer.concat(chunks).toString("utf8");
19145
+ }
19146
+ let body = suppliedBody;
19147
+ if (typeof body === "string") {
19148
+ if (!body.trim()) return {};
19149
+ try {
19150
+ body = JSON.parse(body);
19151
+ } catch {
19152
+ throw new AdminHttpError(400, `${label2} must be valid JSON`);
19153
+ }
19154
+ }
19155
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
19156
+ throw new AdminHttpError(400, `${label2} must be a JSON object`);
19157
+ }
19158
+ return body;
19159
+ }
19160
+ async function updateSettings(runtime, url, req) {
18324
19161
  const rawTurnSize = url.searchParams.get("blockTurnSize")?.trim();
18325
19162
  const rawLambda = url.searchParams.get("blockDecayLambda")?.trim();
18326
19163
  const rawAgentWeight = url.searchParams.get("agentMemoryRetrievalWeight")?.trim();
18327
- if (rawTurnSize === void 0 && rawLambda === void 0 && rawAgentWeight === void 0) {
18328
- throw new AdminHttpError(400, "blockTurnSize, blockDecayLambda, or agentMemoryRetrievalWeight is required");
19164
+ const vectorParams = [
19165
+ "embeddingUrl",
19166
+ "embeddingKey",
19167
+ "embeddingModel",
19168
+ "vectorWeight",
19169
+ "embeddingMinScore",
19170
+ "rerankUrl",
19171
+ "rerankKey",
19172
+ "rerankModel"
19173
+ ];
19174
+ const queryVectorParams = vectorParams.filter((name2) => url.searchParams.has(name2));
19175
+ if (queryVectorParams.length > 0) {
19176
+ throw new AdminHttpError(400, "Embedding settings must be sent in a JSON body; credentials in the URL are not accepted");
19177
+ }
19178
+ const hasBody = req.body !== void 0 || typeof req[Symbol.asyncIterator] === "function";
19179
+ const body = hasBody ? await jsonBody(req, "Embedding settings") : {};
19180
+ const suppliedVectorParams = vectorParams.filter((name2) => Object.hasOwn(body, name2));
19181
+ if (rawTurnSize === void 0 && rawLambda === void 0 && rawAgentWeight === void 0 && suppliedVectorParams.length === 0) {
19182
+ throw new AdminHttpError(400, "blockTurnSize, blockDecayLambda, agentMemoryRetrievalWeight, or an embedding setting is required");
18329
19183
  }
18330
19184
  let turnSize;
18331
19185
  let lambda;
@@ -18355,6 +19209,35 @@ async function updateSettings(runtime, url) {
18355
19209
  if (turnSize !== void 0) result.blockTurnSize = await runtime.adminSetBlockTurnSize(turnSize);
18356
19210
  if (lambda !== void 0) result.blockDecayLambda = await runtime.adminSetBlockDecayLambda(lambda);
18357
19211
  if (agentWeight !== void 0) result.agentMemoryRetrievalWeight = runtime.adminSetAgentMemoryRetrievalWeight(agentWeight);
19212
+ if (suppliedVectorParams.length > 0) {
19213
+ const paramText = (name2) => {
19214
+ const value = body[name2];
19215
+ if (typeof value !== "string") throw new AdminHttpError(400, `${name2} must be a string`);
19216
+ return value.trim();
19217
+ };
19218
+ const paramNumber = (name2) => {
19219
+ const value = body[name2];
19220
+ if (typeof value !== "number" && typeof value !== "string") throw new AdminHttpError(400, `${name2} must be a number`);
19221
+ const parsed = Number(value);
19222
+ if (!Number.isFinite(parsed)) throw new AdminHttpError(400, `${name2} must be a finite number`);
19223
+ return parsed;
19224
+ };
19225
+ try {
19226
+ result.vectorSettings = runtime.adminSetVectorSettings({
19227
+ ...suppliedVectorParams.includes("embeddingUrl") ? { embeddingUrl: paramText("embeddingUrl") } : {},
19228
+ ...suppliedVectorParams.includes("embeddingKey") ? { embeddingKey: paramText("embeddingKey") } : {},
19229
+ ...suppliedVectorParams.includes("embeddingModel") ? { embeddingModel: paramText("embeddingModel") } : {},
19230
+ ...suppliedVectorParams.includes("vectorWeight") ? { vectorWeight: paramNumber("vectorWeight") } : {},
19231
+ ...suppliedVectorParams.includes("embeddingMinScore") ? { embeddingMinScore: paramNumber("embeddingMinScore") } : {},
19232
+ ...suppliedVectorParams.includes("rerankUrl") ? { rerankUrl: paramText("rerankUrl") } : {},
19233
+ ...suppliedVectorParams.includes("rerankKey") ? { rerankKey: paramText("rerankKey") } : {},
19234
+ ...suppliedVectorParams.includes("rerankModel") ? { rerankModel: paramText("rerankModel") } : {}
19235
+ });
19236
+ } catch (error) {
19237
+ if (error instanceof TypeError || error instanceof RangeError) throw new AdminHttpError(400, error.message);
19238
+ throw error;
19239
+ }
19240
+ }
18358
19241
  return result;
18359
19242
  }
18360
19243
  async function persistentProfile(runtime, req) {
@@ -19187,7 +20070,32 @@ async function handleAdminRequest(runtime, req, res) {
19187
20070
  sendJson(res, 200, await runtime.adminGraphControl(url.searchParams.get("action") ?? "", url.searchParams.get("token") ?? void 0));
19188
20071
  } else if (path === "/api/stratagate/settings") {
19189
20072
  if (req.method !== "PATCH") throw new AdminHttpError(405, "StrataGate settings require PATCH");
19190
- sendJson(res, 200, await updateSettings(runtime, url));
20073
+ sendJson(res, 200, await updateSettings(runtime, url, req));
20074
+ } else if (path === "/api/stratagate/models") {
20075
+ if (req.method === "GET" && url.searchParams.has("provider") && !url.searchParams.has("kind")) {
20076
+ sendJson(res, 200, await runtime.adminMemoryModelCatalog(url.searchParams.get("provider") || void 0));
20077
+ return;
20078
+ }
20079
+ if (req.method === "POST" && !url.searchParams.has("kind") && req.body === void 0 && typeof req[Symbol.asyncIterator] !== "function") {
20080
+ throw new AdminHttpError(405, "Memory models require GET");
20081
+ }
20082
+ if (req.method !== "GET" && req.method !== "POST") throw new AdminHttpError(405, "StrataGate model listing requires GET or POST");
20083
+ if (req.method === "GET" && (url.searchParams.has("url") || url.searchParams.has("key"))) {
20084
+ throw new AdminHttpError(400, "Model credentials must be sent in a JSON body; credentials in the URL are not accepted");
20085
+ }
20086
+ const body = req.method === "POST" ? await jsonBody(req, "Model listing") : {};
20087
+ const kindValue = req.method === "POST" ? body.kind : url.searchParams.get("kind");
20088
+ const kind = typeof kindValue === "string" && kindValue ? kindValue : "embedding";
20089
+ if (kind !== "embedding" && kind !== "rerank") throw new AdminHttpError(400, "Unsupported model list kind");
20090
+ if (req.method === "POST" && (body.url !== void 0 && typeof body.url !== "string" || body.key !== void 0 && typeof body.key !== "string")) {
20091
+ throw new AdminHttpError(400, "Model url and key must be strings");
20092
+ }
20093
+ const override = {
20094
+ ...typeof body.url === "string" ? { url: body.url } : {},
20095
+ ...typeof body.key === "string" ? { key: body.key } : {}
20096
+ };
20097
+ const models = kind === "rerank" ? await runtime.adminListRerankModels(override) : await runtime.adminListEmbeddingModels(override);
20098
+ sendJson(res, 200, { kind, models });
19191
20099
  } else if (["/api/stratagate/daily", "/api/stratagate/daily/note", "/api/stratagate/daily/open-directory"].includes(path)) {
19192
20100
  const namespace = url.searchParams.get("namespace")?.trim() ?? "";
19193
20101
  if (!namespace) throw new AdminHttpError(400, "namespace is required");
@@ -19774,7 +20682,8 @@ async function apply(ctx, config) {
19774
20682
  const models = new DshModelBridge(
19775
20683
  ctx,
19776
20684
  resolved,
19777
- isLiveConfigValue(config.structuredReasoningEffort) ? () => liveConfigValue(config.structuredReasoningEffort) ?? "auto" : void 0
20685
+ isLiveConfigValue(config.structuredReasoningEffort) ? () => liveConfigValue(config.structuredReasoningEffort) ?? "auto" : void 0,
20686
+ isLiveConfigValue(config.memoryModel) ? () => liveConfigValue(config.memoryModel) : void 0
19778
20687
  );
19779
20688
  const runtime = new StrataGateRuntime(resolved, models, (error) => {
19780
20689
  ctx.logger.error(`stratagate-memory ingestion failed: ${renderError(error)}`);
@@ -19785,6 +20694,7 @@ async function apply(ctx, config) {
19785
20694
  runtime.setDreamingHost(new DshDreamingSessions(ctx, runtime, () => models.dreamingModelOptions()));
19786
20695
  await runtime.syncConfiguredSettings();
19787
20696
  const effortEntry = {
20697
+ ...resolved.memoryModel ? { memoryModel: resolved.memoryModel } : {},
19788
20698
  structuredReasoningEffort: resolved.structuredReasoningEffort ?? "auto",
19789
20699
  showStrataGateStatus: resolved.showStrataGateStatus ?? true,
19790
20700
  showShortTermStatus: resolved.showShortTermStatus ?? true,
@@ -19799,7 +20709,10 @@ async function apply(ctx, config) {
19799
20709
  setSource: (current) => {
19800
20710
  effortSource = current;
19801
20711
  },
19802
- onChange: () => models.setStructuredReasoningEffort(effortSource().structuredReasoningEffort)
20712
+ onChange: () => {
20713
+ models.setStructuredReasoningEffort(effortSource().structuredReasoningEffort);
20714
+ models.setMemoryModel(effortSource().memoryModel);
20715
+ }
19803
20716
  });
19804
20717
  } else if (settings.configure) {
19805
20718
  settingsCtx.effect(() => settings.configure({ auto: false }, ctx.fiber));