stratagate-dsh 0.3.55 → 0.3.56

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
@@ -3380,6 +3380,13 @@ var MemoryTopicDirectory = class _MemoryTopicDirectory {
3380
3380
  // packages/core/src/dreaming-v2.ts
3381
3381
  var DREAMING_AUTO_INTERVAL = 24 * 60 * 6e4;
3382
3382
  var DREAMING_IDLE_TIME = 30 * 6e4;
3383
+ function recordDreamingChange(run, delta) {
3384
+ const current = run.changes ??= { editedEvents: 0, deletedEvents: 0, experiences: 0, items: [] };
3385
+ current.editedEvents += delta.editedEvents ?? 0;
3386
+ current.deletedEvents += delta.deletedEvents ?? 0;
3387
+ current.experiences += delta.experiences ?? 0;
3388
+ current.items.push(...delta.items ?? []);
3389
+ }
3383
3390
  function dreamingEventVersion(event) {
3384
3391
  return memoryTopicEventFingerprint(event);
3385
3392
  }
@@ -3433,6 +3440,7 @@ function updateDreamingMemory(state, run, command, events) {
3433
3440
  if (trace.tool === "dreaming_daily_write" && result.date && result.version) {
3434
3441
  (run.discoveryVersions ??= {})[`note:${result.date}`] = result.version;
3435
3442
  run.changedBatches++;
3443
+ recordDreamingChange(run, { items: [{ kind: "daily-note", id: result.date, label: `${result.date} \u6BCF\u65E5\u7B14\u8BB0`, date: result.date }] });
3436
3444
  }
3437
3445
  if (trace.tool === "dreaming_read" && typeof result?.content === "string" && result.contentVersion && result.offset !== void 0) {
3438
3446
  const key = JSON.stringify([trace.args.kind, trace.args.id, trace.args.level ?? null]);
@@ -3641,10 +3649,16 @@ function updateDreaming(state, events, command, now) {
3641
3649
  }
3642
3650
  const finalUsage = run.status === "completed" && (command.kind === "model-step" || command.kind === "model-usage");
3643
3651
  const finalHeartbeat = run.status === "completed" && command.kind === "heartbeat";
3644
- if (run.owner !== command.owner || run.epoch !== command.epoch || !finalUsage && !finalHeartbeat && (!["running", "pausing"].includes(run.status) || !run.leaseUntil || Date.parse(run.leaseUntil) <= Date.parse(now))) throw new Error("Dreaming claim changed or expired");
3652
+ const finalLetter = run.status === "completed" && command.kind === "set-letter";
3653
+ if (run.owner !== command.owner || run.epoch !== command.epoch || !finalUsage && !finalHeartbeat && !finalLetter && (!["running", "pausing"].includes(run.status) || !run.leaseUntil || Date.parse(run.leaseUntil) <= Date.parse(now))) throw new Error("Dreaming claim changed or expired");
3645
3654
  if (finalHeartbeat) return structuredClone(run);
3646
3655
  run.updatedAt = now;
3647
- if (!finalUsage) run.leaseUntil = new Date(Date.parse(now) + DREAMING_LEASE_MS).toISOString();
3656
+ if (!finalUsage && !finalLetter) run.leaseUntil = new Date(Date.parse(now) + DREAMING_LEASE_MS).toISOString();
3657
+ if (command.kind === "set-letter") {
3658
+ if (run.status !== "completed") throw new Error("Dreaming run is not completed");
3659
+ run.letter = command.letter;
3660
+ return structuredClone(run);
3661
+ }
3648
3662
  if (command.kind === "heartbeat") return structuredClone(run);
3649
3663
  if (command.kind === "bind-session") {
3650
3664
  if (run.sessionId && run.sessionId !== command.sessionId) throw new Error("Dreaming session identity changed");
@@ -4540,6 +4554,16 @@ CREATE TABLE IF NOT EXISTS memory_topic_state (
4540
4554
  FOREIGN KEY (namespace) REFERENCES memory_spaces(namespace) ON DELETE CASCADE
4541
4555
  ) STRICT;
4542
4556
 
4557
+ CREATE TABLE IF NOT EXISTS dreaming_reports (
4558
+ namespace TEXT NOT NULL,
4559
+ run_id TEXT NOT NULL,
4560
+ finished_at INTEGER NOT NULL,
4561
+ changes_json TEXT NOT NULL,
4562
+ PRIMARY KEY (namespace, run_id),
4563
+ FOREIGN KEY (namespace) REFERENCES memory_spaces(namespace) ON DELETE CASCADE
4564
+ ) STRICT;
4565
+ CREATE INDEX IF NOT EXISTS dreaming_reports_date_idx ON dreaming_reports(namespace, finished_at);
4566
+
4543
4567
  CREATE TABLE IF NOT EXISTS usage_receipts (
4544
4568
  namespace TEXT NOT NULL,
4545
4569
  receipt_id TEXT NOT NULL,
@@ -5931,6 +5955,17 @@ var SqliteStorage = class _SqliteStorage {
5931
5955
  INSERT INTO memory_topic_state (namespace, state_json, updated_at) VALUES (?, ?, ?)
5932
5956
  ON CONFLICT (namespace) DO UPDATE SET state_json = excluded.state_json, updated_at = excluded.updated_at
5933
5957
  `).run(namespace, JSON.stringify(snapshot.memoryTopicState ?? { topics: [], jobs: [], projectedVersions: {} }), updatedAt);
5958
+ const dreaming = snapshot.memoryTopicState?.dreaming;
5959
+ if ((!changes || changes.topics) && dreaming?.changes && ["completed", "terminated"].includes(dreaming.status)) {
5960
+ const { editedEvents, deletedEvents, experiences } = dreaming.changes;
5961
+ const finishedAt = Date.parse(dreaming.updatedAt);
5962
+ if ((editedEvents || deletedEvents || experiences) && Number.isFinite(finishedAt)) {
5963
+ this.database.prepare(`
5964
+ INSERT INTO dreaming_reports (namespace, run_id, finished_at, changes_json) VALUES (?, ?, ?, ?)
5965
+ ON CONFLICT (namespace, run_id) DO NOTHING
5966
+ `).run(namespace, dreaming.id, finishedAt, JSON.stringify(dreaming.changes));
5967
+ }
5968
+ }
5934
5969
  const insertReceipt = this.database.prepare(`
5935
5970
  INSERT INTO usage_receipts (namespace, receipt_id, event_ids_json, element_ids_json, audit_json, created_at)
5936
5971
  VALUES (?, ?, ?, ?, ?, ?)
@@ -7637,10 +7672,13 @@ var StrataGate = class _StrataGate {
7637
7672
  return this.editDreaming(claim, ["event", edit], (run, now) => {
7638
7673
  const target = edit.kind === "create" ? void 0 : this.dreamingReadEvent(run, edit.id);
7639
7674
  if (target && !this.events.includes(target)) throw new Error("Only derived Events can be edited; explicitly recorded memories are read-only");
7675
+ const previousTitle = target?.title;
7676
+ const previousSummary = target?.summary;
7640
7677
  const ids2 = [...new Set(edit.sourceMessageIds ?? [])];
7641
7678
  const messages = this.dreamingReadMessages(run, ids2);
7642
7679
  const affected = /* @__PURE__ */ new Set();
7643
7680
  const removed = /* @__PURE__ */ new Set();
7681
+ const removedTitles = /* @__PURE__ */ new Map();
7644
7682
  const redirects = /* @__PURE__ */ new Map();
7645
7683
  let event = target;
7646
7684
  const requireBody = () => {
@@ -7724,6 +7762,7 @@ var StrataGate = class _StrataGate {
7724
7762
  }, keeper.id, false, true, body)) throw new Error("Events are incompatible or represent different points in history");
7725
7763
  redirects.set(id, keeper.id);
7726
7764
  removed.add(id);
7765
+ removedTitles.set(id, duplicate.title);
7727
7766
  affected.add(id);
7728
7767
  }
7729
7768
  if (!removed.size) throw new Error("Select at least one redundant Event");
@@ -7806,6 +7845,24 @@ var StrataGate = class _StrataGate {
7806
7845
  (run.discoveryVersions ??= {})[`event:${card.id}`] = dreamingEventVersion(card);
7807
7846
  delete run.readVersions?.[`event:${card.id}`];
7808
7847
  }
7848
+ if (edit.kind === "delete" && target) {
7849
+ recordDreamingChange(run, { deletedEvents: 1, items: [{ kind: "event-delete", id: target.id, label: target.title, detail: edit.reason.trim().slice(0, 400), deleted: true }] });
7850
+ } else if (edit.kind === "merge" && target) {
7851
+ recordDreamingChange(run, {
7852
+ editedEvents: 1,
7853
+ deletedEvents: removed.size,
7854
+ items: [
7855
+ { kind: "event-edit", id: target.id, label: target.title, detail: `\u5408\u5E76 ${removed.size} \u6761\u91CD\u590D\u8BB0\u5F55\u3002` },
7856
+ ...[...removedTitles].map(([id, label2]) => ({ kind: "event-delete", id, label: label2, detail: `\u5408\u5E76\u5230\u300C${target.title}\u300D\u3002`, deleted: true }))
7857
+ ]
7858
+ });
7859
+ } else if ((edit.kind === "create" || edit.kind === "update" || edit.kind === "supersede") && event) {
7860
+ const detail = edit.kind === "create" ? `\u65B0\u5EFA\u3002${event.summary.slice(0, 220)}` : edit.kind === "supersede" ? `\u6807\u8BB0\u4E3A\u66F4\u65B0\u7684\u8BB0\u5F55\u3002${edit.reason?.trim().slice(0, 220) ?? ""}` : [
7861
+ previousTitle !== event.title ? `\u539F\u540D\u300C${previousTitle}\u300D\u3002` : "",
7862
+ previousSummary !== event.summary ? `\u6458\u8981\u66F4\u65B0\u4E3A\uFF1A${event.summary.slice(0, 220)}` : ""
7863
+ ].join("") || "\u66F4\u65B0\u4E86\u4E8B\u4EF6\u7684\u6765\u6E90\u6216\u5C5E\u6027\u3002";
7864
+ recordDreamingChange(run, { editedEvents: 1, items: [{ kind: "event-edit", id: event.id, label: event.title, detail }] });
7865
+ }
7809
7866
  this.validateReferences();
7810
7867
  return { ...event ? { id: event.id } : {}, saved: true, ...experiencesToReview.length ? { experiencesToReview } : {} };
7811
7868
  });
@@ -7931,6 +7988,7 @@ var StrataGate = class _StrataGate {
7931
7988
  const remove = /* @__PURE__ */ new Set([old?.id, ...merged.map((item) => item.id)]);
7932
7989
  this.experiences.splice(0, this.experiences.length, ...this.experiences.filter((item) => !remove.has(item.id)), stored);
7933
7990
  run.searchedExperiences = false;
7991
+ recordDreamingChange(run, { experiences: 1, items: [{ kind: "experience", id: stored.id, label: stored.title }] });
7934
7992
  return { id: stored.id, saved: true };
7935
7993
  });
7936
7994
  }
@@ -11480,394 +11538,120 @@ function dreamingStatus(run) {
11480
11538
  changedBatches: run.changedBatches,
11481
11539
  calls: run.calls,
11482
11540
  estimatedTokens: run.estimatedTokens,
11541
+ changes: run.changes ?? { editedEvents: 0, deletedEvents: 0, experiences: 0, items: [] },
11542
+ letter: run.letter ?? null,
11483
11543
  updatedAt: run.updatedAt
11484
11544
  };
11485
11545
  }
11486
11546
 
11487
- // src/llm.ts
11488
- import { BlockAssembler, createUserMessage } from "@deepseek-ai/dsh-llm";
11489
- import { parameterSchemaSpecToJsonSchema, validateArgs } from "@deepseek-ai/dsh-tools";
11547
+ // src/letters.ts
11548
+ import { randomUUID as randomUUID6 } from "node:crypto";
11549
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
11490
11550
 
11491
- // src/dsh-compatibility.ts
11492
- import { readFileSync } from "node:fs";
11551
+ // src/daily-notes.ts
11552
+ import { mkdir, readFile, readdir, writeFile, rename, rm, stat } from "node:fs/promises";
11553
+ import { dirname, join, resolve as resolve2 } from "node:path";
11554
+ import { randomUUID as randomUUID5, createHash as createHash5 } from "node:crypto";
11555
+
11556
+ // src/diagnostics.ts
11557
+ import { randomUUID as randomUUID4 } from "node:crypto";
11493
11558
  import { createRequire } from "node:module";
11494
- import { satisfies } from "semver";
11495
- var nodeRequire = createRequire(import.meta.url);
11496
- var CORE_RUNTIME_PACKAGES = [
11497
- "@deepseek-ai/cordis",
11498
- "@deepseek-ai/dsh-agent-default-model",
11499
- "@deepseek-ai/dsh-client-ui-conversation",
11500
- "@deepseek-ai/dsh-llm",
11501
- "@deepseek-ai/dsh-native-command",
11502
- "@deepseek-ai/dsh-session",
11503
- "@deepseek-ai/dsh-settings",
11504
- "@deepseek-ai/dsh-system-prompt",
11505
- "@deepseek-ai/dsh-tools",
11506
- "@deepseek-ai/schemastery"
11507
- ];
11508
- var SESSION_FORMAT_PACKAGES = [
11509
- "@deepseek-ai/dsh-session-format",
11510
- "@deepseek-ai/dsh-session-format-catalog",
11511
- "@deepseek-ai/dsh-session-format-v0-to-v1"
11512
- ];
11513
- var RUNTIME_PACKAGES = [...CORE_RUNTIME_PACKAGES, ...SESSION_FORMAT_PACKAGES];
11514
- var STRATAGATE_MESSAGE_SOURCE_KIND = "plugin:stratagate-memory";
11515
- var DSH_RUNTIME_RANGE = "0.1.2-rc.1 || >=0.1.5-rc.2 <0.3.0-0";
11516
- var MODERN_API_RANGE = ">=0.1.7-rc.1";
11517
- var SESSION_FORMAT_RUNTIME_RANGE = ">=0.2.0-0";
11518
- var DSH_022_VENDOR_RUNTIME_RANGE = ">=0.2.2-0 <0.3.0-0";
11519
- var SEMVER_OPTIONS = { includePrerelease: true };
11520
- function assertDshMethods(scope, value, methods) {
11521
- const target = value;
11522
- const missing2 = methods.filter((method) => typeof target?.[method] !== "function");
11523
- if (missing2.length) {
11524
- throw new Error(`StrataGate cannot use this DSH host: missing required interface ${missing2.map((method) => `${scope}.${method}`).join(", ")}. Use a compatible host or plugin version.`);
11525
- }
11526
- }
11527
- function assertDshHostContract(ctx) {
11528
- assertDshMethods("tools", ctx.tools, ["register", "get"]);
11529
- assertDshMethods("systemPrompt", ctx.systemPrompt, ["section"]);
11530
- assertDshMethods("llm", ctx.llm, ["stream", "listProviders"]);
11531
- assertDshMethods("agentDefaultModel", ctx.agentDefaultModel, ["currentSelection"]);
11532
- }
11533
- function buildDshMessageSource(version, form) {
11534
- const source = satisfies(version, MODERN_API_RANGE, SEMVER_OPTIONS) ? { kind: STRATAGATE_MESSAGE_SOURCE_KIND } : { kind: "plugin", plugin: "stratagate-memory" };
11535
- return form ? { ...source, form } : source;
11536
- }
11537
- function installedVersion(packageName) {
11559
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
11560
+ var DAY = 864e5;
11561
+ var VERSION = (() => {
11538
11562
  try {
11539
- const manifestPath = nodeRequire.resolve(`${packageName}/package.json`);
11540
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
11541
- if (typeof manifest.version === "string" && manifest.version.length > 0) return manifest.version;
11563
+ return String(createRequire(import.meta.url)("../package.json").version);
11542
11564
  } catch {
11565
+ return "unknown";
11543
11566
  }
11544
- return "<missing>";
11545
- }
11546
- function buildDshReplaceSurfaceOp(version, start, end) {
11547
- return version === "0.1.2-rc.1" ? { op: "replace", start, end } : { op: "replace", startSeq: start, endSeq: end };
11548
- }
11549
- function dshReplaceSurfaceOp(start, end) {
11550
- return buildDshReplaceSurfaceOp(installedVersion("@deepseek-ai/dsh-session"), start, end);
11551
- }
11552
- function dshMessageSource(form) {
11553
- return buildDshMessageSource(installedVersion("@deepseek-ai/dsh-session"), form);
11554
- }
11555
- function isStrataGateMessageSource(source) {
11556
- if (!source || typeof source !== "object") return false;
11557
- const value = source;
11558
- return value.kind === STRATAGATE_MESSAGE_SOURCE_KIND || value.kind === "plugin" && value.plugin === "stratagate-memory";
11559
- }
11560
- function isCompatiblePatch(version, major, minor, minimumPatch) {
11561
- const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
11562
- return !!match && Number(match[1]) === major && Number(match[2]) === minor && Number(match[3]) >= minimumPatch;
11567
+ })();
11568
+ var DIAGNOSTIC_STAGES = ["summarizer", "extractor", "projector", "graphProjector", "topicProjector", "externalMemoryExtractor", "externalMemoryDecider", "profileMaintenance", "dreamingStep", "dailyLetter", "eventDuplicateDecider", "chat", "ingestion", "autoContext", "directory", "tools", "frontend", "retrieval"];
11569
+ function containsCredentials(value) {
11570
+ if (/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/.test(value)) return true;
11571
+ return value.replace(/\b(?:sk[-_]|gh[opasu]_|github_pat_)[A-Za-z0-9_-]{8,}\b/g, "[credential]").replace(/(["']?\b(?:api[_-]?key|token|password|passwd|secret|authorization|access[_-]?token|refresh[_-]?token)["']?\s*[:=]\s*)(["'])([\s\S]*?)\2/gi, "$1[credential]").replace(/\b(?:Bearer|Basic|Token)\s+[^\s,;}]+/gi, "[credential]").replace(/\b(?:api[_-]?key|token|password|passwd|secret|authorization)\s*[:=]\s*[^\s,;}]+/gi, "[credential]") !== value;
11563
11572
  }
11564
- function classifyDshRuntime(packageVersions) {
11565
- const dshVersion = packageVersions["@deepseek-ai/dsh-session"];
11566
- const sameDshFamily = CORE_RUNTIME_PACKAGES.filter((name2) => name2.startsWith("@deepseek-ai/dsh-")).every((name2) => packageVersions[name2] === dshVersion);
11567
- const sameSessionFormatFamily = !satisfies(dshVersion, SESSION_FORMAT_RUNTIME_RANGE, SEMVER_OPTIONS) || SESSION_FORMAT_PACKAGES.every((name2) => packageVersions[name2] === dshVersion);
11568
- const modernApi = satisfies(dshVersion, MODERN_API_RANGE, SEMVER_OPTIONS);
11569
- const dsh022VendorFamily = satisfies(dshVersion, DSH_022_VENDOR_RUNTIME_RANGE, SEMVER_OPTIONS);
11570
- const compatibleVendors = modernApi ? dsh022VendorFamily ? isCompatiblePatch(packageVersions["@deepseek-ai/cordis"], 4, 1, 0) && isCompatiblePatch(packageVersions["@deepseek-ai/schemastery"], 3, 19, 0) : isCompatiblePatch(packageVersions["@deepseek-ai/cordis"], 4, 0, 4) && isCompatiblePatch(packageVersions["@deepseek-ai/schemastery"], 3, 18, 4) : packageVersions["@deepseek-ai/cordis"] === "4.0.2" && packageVersions["@deepseek-ai/schemastery"] === "3.18.2";
11571
- if (satisfies(dshVersion, DSH_RUNTIME_RANGE, SEMVER_OPTIONS) && sameDshFamily && sameSessionFormatFamily && compatibleVendors) {
11572
- return { cliVersion: dshVersion === "0.1.5-rc.2" ? "0.1.5-rc.1" : dshVersion, packageVersions };
11573
- }
11574
- const found = RUNTIME_PACKAGES.map((name2) => `${name2}@${packageVersions[name2]}`).join(", ");
11575
- throw new Error(
11576
- `StrataGate cannot start because this DSH profile resolves an unsupported or mixed core runtime. Resolved: ${found}. Supported DSH versions: ${DSH_RUNTIME_RANGE} (including prereleases). Core DSH packages must share one version; DSH 0.2.0 and later also require matching Session Format packages. DSH 0.2.2 and later require Cordis 4.1.x from 4.1.0 and Schemastery 3.19.x from 3.19.0; earlier modern hosts require Cordis 4.0.x from 4.0.4 and Schemastery 3.18.x from 3.18.4, while older hosts use 4.0.2 and 3.18.2. Reinstall or update stratagate-dsh through \`dsh plugin --profile <name> add <package>\` so the host supplies its peers.`
11577
- );
11573
+ function diagnosticText(value, limit = 1500) {
11574
+ return String(value instanceof Error ? value.message : value ?? "").slice(0, 8e3).split(/\nRaw response(?: preview| \(full\))/i)[0].replace(/\b(?:sk[-_]|gh[opasu]_|github_pat_)[A-Za-z0-9_-]{8,}\b/g, "[credential]").replace(/(["']?\b(?:api[_-]?key|token|password|passwd|secret|authorization|access[_-]?token|refresh[_-]?token)["']?\s*[:=]\s*)(["'])([\s\S]*?)\2/gi, "$1[credential]").replace(/\b(?:Bearer|Basic|Token)\s+[^\s,;}]+/gi, "[credential]").replace(/\b(?:api[_-]?key|token|password|passwd|secret|authorization)\s*[:=]\s*[^\s,;}]+/gi, "[credential]").replace(/https?:\/\/[^\s<>"']+/gi, "[url]").replace(/[A-Z]:[\\/][^\s"'<>]+/gi, "[path]").replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi, "[email]").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "").slice(0, limit).replace(/[\uD800-\uDBFF]$/, "");
11578
11575
  }
11579
- function assertCompatibleDshRuntime() {
11580
- const packageVersions = Object.fromEntries(RUNTIME_PACKAGES.map((name2) => [name2, installedVersion(name2)]));
11581
- return classifyDshRuntime(packageVersions);
11576
+ function isAbortError(error) {
11577
+ return typeof error === "object" && error !== null && (error.name === "AbortError" || error.code === "ABORT_ERR");
11582
11578
  }
11583
-
11584
- // src/json-response.ts
11585
- var RESPONSE_PREVIEW_LIMIT = 500;
11586
- function truncateResponsePreview(value) {
11587
- return value.slice(0, RESPONSE_PREVIEW_LIMIT);
11579
+ function diagnosticCategory(error) {
11580
+ if (isAbortError(error)) return "cancelled";
11581
+ const text3 = String(error instanceof Error ? error.message : error ?? "");
11582
+ if (/timeout|timed out|超时/i.test(text3)) return "timeout";
11583
+ if (/429|rate.?limit/i.test(text3)) return "rate-limit";
11584
+ if (/401|403|unauthori|forbidden|credential/i.test(text3)) return "authentication";
11585
+ if (/token.*limit|truncat|max-tokens|context.*(window|length|limit)/i.test(text3)) return "token-limit";
11586
+ if (/json|schema|invalid|validation/i.test(text3)) return "validation";
11587
+ if (/sqlite|database|storage|EACCES|ENOSPC|write failed/i.test(text3)) return "storage";
11588
+ if (/abort|cancel/i.test(text3)) return "cancelled";
11589
+ if (/network|fetch|ECONN|ENOTFOUND/i.test(text3)) return "network";
11590
+ return "internal";
11588
11591
  }
11589
- var ModelJsonResponseError = class extends Error {
11590
- fullMessage;
11591
- response;
11592
- responsePreview;
11593
- constructor(message = "StrataGate model response was not valid JSON", options) {
11594
- const response = options?.response ?? options?.responsePreview;
11595
- const responsePreview = response ? truncateResponsePreview(response) : void 0;
11596
- const displayMessage = responsePreview ? `${message}
11597
- Raw response preview (first ${RESPONSE_PREVIEW_LIMIT} chars):
11598
- ${responsePreview}` : message;
11599
- super(displayMessage, options);
11600
- this.name = "ModelJsonResponseError";
11601
- const causeMessage = options?.cause instanceof Error ? options.cause.message.split("\nRaw response preview")[0] : "";
11602
- const causeDetail = causeMessage && causeMessage !== message ? `
11603
- Cause: ${causeMessage}` : "";
11604
- this.fullMessage = response ? `${message}${causeDetail}
11605
- Raw response (full):
11606
- ${response}` : `${displayMessage}${causeDetail}`;
11607
- this.response = response;
11608
- this.responsePreview = responsePreview;
11592
+ var SCHEMA2 = `
11593
+ CREATE TABLE IF NOT EXISTS stratagate_dsh_diagnostic_records (
11594
+ id TEXT PRIMARY KEY, at TEXT NOT NULL, namespace TEXT NOT NULL, record_json TEXT NOT NULL
11595
+ ) STRICT;
11596
+ CREATE INDEX IF NOT EXISTS stratagate_dsh_diagnostic_scope ON stratagate_dsh_diagnostic_records(namespace, at);
11597
+ CREATE TABLE IF NOT EXISTS stratagate_dsh_diagnostic_daily (
11598
+ namespace TEXT NOT NULL, day TEXT NOT NULL, stage TEXT NOT NULL, model TEXT NOT NULL,
11599
+ version TEXT NOT NULL, counters_json TEXT NOT NULL,
11600
+ PRIMARY KEY(namespace, day, stage, model, version)
11601
+ ) STRICT;
11602
+ CREATE TABLE IF NOT EXISTS stratagate_dsh_diagnostic_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT;
11603
+ `;
11604
+ var DiagnosticsRecorder = class {
11605
+ constructor(filename) {
11606
+ this.filename = filename;
11609
11607
  }
11610
- };
11611
- function isObject(value) {
11612
- return value !== null && typeof value === "object" && !Array.isArray(value);
11613
- }
11614
- function hasRequiredKeys(value, requiredKeys) {
11615
- return requiredKeys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
11616
- }
11617
- function balancedValueEnd(value, start) {
11618
- const opening = value[start];
11619
- if (opening !== "{" && opening !== "[") return null;
11620
- const stack = [opening];
11621
- let inString = false;
11622
- let escaped = false;
11623
- for (let index = start + 1; index < value.length; index += 1) {
11624
- const character = value[index];
11625
- if (inString) {
11626
- if (escaped) escaped = false;
11627
- else if (character === "\\") escaped = true;
11628
- else if (character === '"') inString = false;
11629
- continue;
11630
- }
11631
- if (character === '"') {
11632
- inString = true;
11633
- continue;
11608
+ filename;
11609
+ database;
11610
+ pending = [];
11611
+ timer;
11612
+ closed = false;
11613
+ dropped = 0;
11614
+ writeFailures = 0;
11615
+ startedAt = (/* @__PURE__ */ new Date()).toISOString();
11616
+ record(scope, counters, options = {}) {
11617
+ if (this.closed) return;
11618
+ const bounded2 = Object.fromEntries(Object.entries(counters).filter(([, n]) => Number.isFinite(n) && n >= 0));
11619
+ this.pending.push({
11620
+ id: `diag_${randomUUID4()}`,
11621
+ at: (/* @__PURE__ */ new Date()).toISOString(),
11622
+ namespace: scope.namespace,
11623
+ stage: scope.stage,
11624
+ model: diagnosticText(options.model ?? "", 160),
11625
+ version: VERSION,
11626
+ counters: bounded2,
11627
+ ...scope.taskId ? { taskId: scope.taskId } : {},
11628
+ ...options.error !== void 0 ? { category: diagnosticCategory(options.error), detail: diagnosticText(options.error) } : {}
11629
+ });
11630
+ if (this.pending.length > 256) {
11631
+ this.pending.shift();
11632
+ this.dropped++;
11634
11633
  }
11635
- if (character === "{" || character === "[") {
11636
- stack.push(character);
11637
- continue;
11634
+ if (!this.timer) {
11635
+ this.timer = setTimeout(() => {
11636
+ this.timer = void 0;
11637
+ this.flush();
11638
+ }, 5e3);
11639
+ this.timer.unref?.();
11638
11640
  }
11639
- if (character !== "}" && character !== "]") continue;
11640
- const expected = character === "}" ? "{" : "[";
11641
- if (stack.at(-1) !== expected) return null;
11642
- stack.pop();
11643
- if (stack.length === 0) return index;
11644
11641
  }
11645
- return null;
11646
- }
11647
- function parse(value) {
11648
- try {
11649
- return JSON.parse(value);
11650
- } catch {
11651
- return void 0;
11652
- }
11653
- }
11654
- function parseJsonResponse(value, requiredKeys = []) {
11655
- const trimmed = value.trim().replace(/^\uFEFF/, "");
11656
- const direct = parse(trimmed);
11657
- if (direct !== void 0) {
11658
- if (isObject(direct) && hasRequiredKeys(direct, requiredKeys)) return direct;
11659
- if (isObject(direct) && requiredKeys.length > 0) {
11660
- throw new ModelJsonResponseError(
11661
- `StrataGate model response JSON object was missing required fields: ${requiredKeys.join(", ")}`,
11662
- { response: value }
11663
- );
11664
- }
11665
- throw new ModelJsonResponseError("StrataGate model response was not a JSON object", { response: value });
11666
- }
11667
- const parsedValues = [];
11668
- for (let start = 0; start < trimmed.length; start += 1) {
11669
- const character = trimmed[start];
11670
- if (character !== "{" && character !== "[") continue;
11671
- const end = balancedValueEnd(trimmed, start);
11672
- if (end === null) continue;
11673
- const candidate = parse(trimmed.slice(start, end + 1));
11674
- if (candidate !== void 0) parsedValues.push({ value: candidate, start, end });
11675
- start = end;
11676
- }
11677
- if (parsedValues.length === 1) {
11678
- const only = parsedValues[0];
11679
- if (isObject(only.value) && hasRequiredKeys(only.value, requiredKeys)) return only.value;
11680
- if (isObject(only.value) && requiredKeys.length > 0) {
11681
- throw new ModelJsonResponseError(
11682
- `StrataGate model response JSON object was missing required fields: ${requiredKeys.join(", ")}`,
11683
- { response: value }
11684
- );
11685
- }
11686
- throw new ModelJsonResponseError("StrataGate model response did not contain a JSON object", { response: value });
11687
- }
11688
- if (parsedValues.length > 1) {
11689
- const first = parsedValues[0];
11690
- const last = parsedValues.at(-1);
11691
- const between = parsedValues.slice(0, -1).some((candidate, index) => {
11692
- const next = parsedValues[index + 1];
11693
- return trimmed.slice(candidate.end + 1, next.start).trim().length > 0;
11694
- });
11695
- const hasNonJsonPrefix = trimmed.slice(0, first.start).trim().length > 0;
11696
- const hasNonJsonSuffix = trimmed.slice(last.end + 1).trim().length > 0;
11697
- const final = last.value;
11698
- if ((between || hasNonJsonPrefix || hasNonJsonSuffix) && isObject(final) && hasRequiredKeys(final, requiredKeys)) return final;
11699
- if ((between || hasNonJsonPrefix || hasNonJsonSuffix) && isObject(final) && requiredKeys.length > 0) {
11700
- throw new ModelJsonResponseError(
11701
- `StrataGate model response JSON object was missing required fields: ${requiredKeys.join(", ")}`,
11702
- { response: value }
11703
- );
11704
- }
11705
- throw new ModelJsonResponseError("StrataGate model response contained multiple JSON values", { response: value });
11706
- }
11707
- throw new ModelJsonResponseError(void 0, { response: value });
11708
- }
11709
-
11710
- // src/extraction-batches.ts
11711
- var ExtractionCapacityError = class extends Error {
11712
- constructor(capacity) {
11713
- super(`Event extraction ${capacity} capacity exceeded; a smaller source batch is required`);
11714
- this.capacity = capacity;
11715
- }
11716
- capacity;
11717
- };
11718
- var CONTEXT_CHARS = 1200;
11719
- function splitExtractionSlice(slice) {
11720
- const messages = slice.messages;
11721
- let left;
11722
- let right;
11723
- if (messages.length > 1) {
11724
- const weights = messages.map((message) => estimateTokens(JSON.stringify(message)));
11725
- const half = weights.reduce((sum, size2) => sum + size2, 0) / 2;
11726
- let index = 1;
11727
- let size = weights[0];
11728
- while (index < messages.length - 1 && size < half) size += weights[index++];
11729
- left = messages.slice(0, index);
11730
- right = messages.slice(index);
11731
- } else {
11732
- const message = messages[0];
11733
- if (!message) throw new Error("Event extraction has no source to split");
11734
- const content = message.content + (message.toolCalls?.length ? `
11735
- [Tool evidence, JSON]
11736
- ${JSON.stringify(message.toolCalls)}` : "");
11737
- if (content.length < 2) throw new Error("Event extraction cannot split this source any further");
11738
- const middle = Math.floor(content.length / 2);
11739
- const boundary = content.lastIndexOf("\n", middle);
11740
- let cut = boundary >= middle / 2 ? boundary + 1 : middle;
11741
- if (/[\uD800-\uDBFF]/.test(content[cut - 1])) cut += 1;
11742
- if (cut >= content.length) throw new Error("Event extraction cannot split this source any further");
11743
- const { toolCalls: _tools, ...base } = message;
11744
- left = [{ ...base, content: content.slice(0, cut) }];
11745
- right = [{ ...base, content: content.slice(cut) }];
11746
- }
11747
- const excerpt = (items2) => items2.map((message) => JSON.stringify(message)).join("\n");
11748
- return [
11749
- { messages: left, before: slice.before, after: excerpt(right).slice(0, CONTEXT_CHARS), depth: slice.depth + 1 },
11750
- { messages: right, before: excerpt(left).slice(-CONTEXT_CHARS), after: slice.after, depth: slice.depth + 1 }
11751
- ];
11752
- }
11753
- function mergeExtractionEvents(events, exactKey) {
11754
- const unique3 = /* @__PURE__ */ new Map();
11755
- for (const event of events) {
11756
- const key = exactKey(event);
11757
- const prior = unique3.get(key);
11758
- if (!prior) {
11759
- unique3.set(key, structuredClone(event));
11760
- continue;
11761
- }
11762
- prior.sourceMessageIds = [.../* @__PURE__ */ new Set([...prior.sourceMessageIds, ...event.sourceMessageIds])];
11763
- prior.tags = [.../* @__PURE__ */ new Set([...prior.tags ?? [], ...event.tags ?? []])].slice(0, 16);
11764
- prior.quotes = [.../* @__PURE__ */ new Set([...prior.quotes ?? [], ...event.quotes ?? []])].slice(0, 12);
11765
- }
11766
- return [...unique3.values()];
11767
- }
11768
-
11769
- // src/llm.ts
11770
- import { randomUUID as randomUUID5 } from "node:crypto";
11771
-
11772
- // src/diagnostics.ts
11773
- import { randomUUID as randomUUID4 } from "node:crypto";
11774
- import { createRequire as createRequire2 } from "node:module";
11775
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
11776
- var DAY = 864e5;
11777
- var VERSION = (() => {
11778
- try {
11779
- return String(createRequire2(import.meta.url)("../package.json").version);
11780
- } catch {
11781
- return "unknown";
11782
- }
11783
- })();
11784
- var DIAGNOSTIC_STAGES = ["summarizer", "extractor", "projector", "graphProjector", "topicProjector", "externalMemoryExtractor", "externalMemoryDecider", "profileMaintenance", "dreamingStep", "eventDuplicateDecider", "chat", "ingestion", "autoContext", "directory", "tools", "frontend", "retrieval"];
11785
- function containsCredentials(value) {
11786
- if (/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/.test(value)) return true;
11787
- return value.replace(/\b(?:sk[-_]|gh[opasu]_|github_pat_)[A-Za-z0-9_-]{8,}\b/g, "[credential]").replace(/(["']?\b(?:api[_-]?key|token|password|passwd|secret|authorization|access[_-]?token|refresh[_-]?token)["']?\s*[:=]\s*)(["'])([\s\S]*?)\2/gi, "$1[credential]").replace(/\b(?:Bearer|Basic|Token)\s+[^\s,;}]+/gi, "[credential]").replace(/\b(?:api[_-]?key|token|password|passwd|secret|authorization)\s*[:=]\s*[^\s,;}]+/gi, "[credential]") !== value;
11788
- }
11789
- function diagnosticText(value, limit = 1500) {
11790
- return String(value instanceof Error ? value.message : value ?? "").slice(0, 8e3).split(/\nRaw response(?: preview| \(full\))/i)[0].replace(/\b(?:sk[-_]|gh[opasu]_|github_pat_)[A-Za-z0-9_-]{8,}\b/g, "[credential]").replace(/(["']?\b(?:api[_-]?key|token|password|passwd|secret|authorization|access[_-]?token|refresh[_-]?token)["']?\s*[:=]\s*)(["'])([\s\S]*?)\2/gi, "$1[credential]").replace(/\b(?:Bearer|Basic|Token)\s+[^\s,;}]+/gi, "[credential]").replace(/\b(?:api[_-]?key|token|password|passwd|secret|authorization)\s*[:=]\s*[^\s,;}]+/gi, "[credential]").replace(/https?:\/\/[^\s<>"']+/gi, "[url]").replace(/[A-Z]:[\\/][^\s"'<>]+/gi, "[path]").replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi, "[email]").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "").slice(0, limit).replace(/[\uD800-\uDBFF]$/, "");
11791
- }
11792
- function isAbortError(error) {
11793
- return typeof error === "object" && error !== null && (error.name === "AbortError" || error.code === "ABORT_ERR");
11794
- }
11795
- function diagnosticCategory(error) {
11796
- if (isAbortError(error)) return "cancelled";
11797
- const text3 = String(error instanceof Error ? error.message : error ?? "");
11798
- if (/timeout|timed out|超时/i.test(text3)) return "timeout";
11799
- if (/429|rate.?limit/i.test(text3)) return "rate-limit";
11800
- if (/401|403|unauthori|forbidden|credential/i.test(text3)) return "authentication";
11801
- if (/token.*limit|truncat|max-tokens|context.*(window|length|limit)/i.test(text3)) return "token-limit";
11802
- if (/json|schema|invalid|validation/i.test(text3)) return "validation";
11803
- if (/sqlite|database|storage|EACCES|ENOSPC|write failed/i.test(text3)) return "storage";
11804
- if (/abort|cancel/i.test(text3)) return "cancelled";
11805
- if (/network|fetch|ECONN|ENOTFOUND/i.test(text3)) return "network";
11806
- return "internal";
11807
- }
11808
- var SCHEMA2 = `
11809
- CREATE TABLE IF NOT EXISTS stratagate_dsh_diagnostic_records (
11810
- id TEXT PRIMARY KEY, at TEXT NOT NULL, namespace TEXT NOT NULL, record_json TEXT NOT NULL
11811
- ) STRICT;
11812
- CREATE INDEX IF NOT EXISTS stratagate_dsh_diagnostic_scope ON stratagate_dsh_diagnostic_records(namespace, at);
11813
- CREATE TABLE IF NOT EXISTS stratagate_dsh_diagnostic_daily (
11814
- namespace TEXT NOT NULL, day TEXT NOT NULL, stage TEXT NOT NULL, model TEXT NOT NULL,
11815
- version TEXT NOT NULL, counters_json TEXT NOT NULL,
11816
- PRIMARY KEY(namespace, day, stage, model, version)
11817
- ) STRICT;
11818
- CREATE TABLE IF NOT EXISTS stratagate_dsh_diagnostic_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT;
11819
- `;
11820
- var DiagnosticsRecorder = class {
11821
- constructor(filename) {
11822
- this.filename = filename;
11823
- }
11824
- filename;
11825
- database;
11826
- pending = [];
11827
- timer;
11828
- closed = false;
11829
- dropped = 0;
11830
- writeFailures = 0;
11831
- startedAt = (/* @__PURE__ */ new Date()).toISOString();
11832
- record(scope, counters, options = {}) {
11833
- if (this.closed) return;
11834
- const bounded2 = Object.fromEntries(Object.entries(counters).filter(([, n]) => Number.isFinite(n) && n >= 0));
11835
- this.pending.push({
11836
- id: `diag_${randomUUID4()}`,
11837
- at: (/* @__PURE__ */ new Date()).toISOString(),
11838
- namespace: scope.namespace,
11839
- stage: scope.stage,
11840
- model: diagnosticText(options.model ?? "", 160),
11841
- version: VERSION,
11842
- counters: bounded2,
11843
- ...scope.taskId ? { taskId: scope.taskId } : {},
11844
- ...options.error !== void 0 ? { category: diagnosticCategory(options.error), detail: diagnosticText(options.error) } : {}
11845
- });
11846
- if (this.pending.length > 256) {
11847
- this.pending.shift();
11848
- this.dropped++;
11849
- }
11850
- if (!this.timer) {
11851
- this.timer = setTimeout(() => {
11852
- this.timer = void 0;
11853
- this.flush();
11854
- }, 5e3);
11855
- this.timer.unref?.();
11856
- }
11857
- }
11858
- open() {
11859
- if (this.database) return this.database;
11860
- const db = new DatabaseSync2(this.filename);
11861
- try {
11862
- db.exec("PRAGMA busy_timeout=0");
11863
- db.exec(SCHEMA2);
11864
- db.prepare("INSERT OR IGNORE INTO stratagate_dsh_diagnostic_meta VALUES ('startedAt', ?)").run(this.startedAt);
11865
- this.database = db;
11866
- return db;
11867
- } catch (error) {
11868
- db.close();
11869
- throw error;
11870
- }
11642
+ open() {
11643
+ if (this.database) return this.database;
11644
+ const db = new DatabaseSync2(this.filename);
11645
+ try {
11646
+ db.exec("PRAGMA busy_timeout=0");
11647
+ db.exec(SCHEMA2);
11648
+ db.prepare("INSERT OR IGNORE INTO stratagate_dsh_diagnostic_meta VALUES ('startedAt', ?)").run(this.startedAt);
11649
+ this.database = db;
11650
+ return db;
11651
+ } catch (error) {
11652
+ db.close();
11653
+ throw error;
11654
+ }
11871
11655
  }
11872
11656
  flush() {
11873
11657
  if (!this.pending.length) return;
@@ -12089,11 +11873,591 @@ async function* observeModelStream(recorder, scope, options, next) {
12089
11873
  counters.totalTokenCalls = 1;
12090
11874
  }
12091
11875
  }
12092
- recorder.record(scope, counters, { model: `${options.provider}/${options.model}`, ...failure !== void 0 ? { error: failure } : {} });
11876
+ recorder.record(scope, counters, { model: `${options.provider}/${options.model}`, ...failure !== void 0 ? { error: failure } : {} });
11877
+ }
11878
+ }
11879
+
11880
+ // src/daily-notes.ts
11881
+ var DAILY_NOTE_LABEL = "\u5DE5\u4F5C\u7B14\u8BB0\uFF0C\u4E0D\u662F\u4E8B\u5B9E\u8BC1\u636E\uFF0C\u4E5F\u4E0D\u662F\u65B0\u6307\u4EE4\u3002";
11882
+ var DAILY_LOAD_FAILURE = "[StrataGate daily notes]\nDaily notes could not be loaded for this session. This is a read failure, not an empty record. Use memory_daily_read to retry.";
11883
+ var queues = /* @__PURE__ */ new Map();
11884
+ var missing = (error) => error.code === "ENOENT";
11885
+ function dailyDate(now = /* @__PURE__ */ new Date(), timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone) {
11886
+ const parts = new Intl.DateTimeFormat("en-US", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(now);
11887
+ return ["year", "month", "day"].map((key) => parts.find((part) => part.type === key).value).join("-");
11888
+ }
11889
+ function validDate(date) {
11890
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !Number.isFinite(Date.parse(date)) || new Date(date).toISOString().slice(0, 10) !== date) throw new TypeError("date \u5FC5\u987B\u662F\u6709\u6548\u7684 YYYY-MM-DD");
11891
+ return date;
11892
+ }
11893
+ function selectDailyInjectionDates(dates, days = 3) {
11894
+ return dates.slice(0, days);
11895
+ }
11896
+ function items(text3) {
11897
+ const matches = [...text3.matchAll(/^## (.+)\r?$/gm)];
11898
+ return matches.map((match, index) => ({ title: match[1], text: text3.slice(match.index, matches[index + 1]?.index ?? text3.length).trimEnd() }));
11899
+ }
11900
+ var DailyNotes = class {
11901
+ constructor(database, timeZone, budget = 12e3, injectionDays = 3) {
11902
+ this.database = database;
11903
+ this.budget = budget;
11904
+ this.injectionDays = injectionDays;
11905
+ this.timeZone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
11906
+ dailyDate(/* @__PURE__ */ new Date(), this.timeZone);
11907
+ }
11908
+ database;
11909
+ budget;
11910
+ injectionDays;
11911
+ timeZone;
11912
+ directory(namespace) {
11913
+ if (this.database === ":memory:") throw new Error("\u6BCF\u65E5\u7B14\u8BB0\u4E0D\u53EF\u7528\uFF1Adatabase \u4E3A :memory:\uFF0C\u8BF7\u914D\u7F6E\u6301\u4E45\u6570\u636E\u5E93\u8DEF\u5F84\u3002");
11914
+ return join(dirname(resolve2(this.database)), "daily", `ns-${createHash5("sha256").update(namespace).digest("hex")}`);
11915
+ }
11916
+ async dates(namespace) {
11917
+ try {
11918
+ return (await readdir(this.directory(namespace))).filter((name2) => /^\d{4}-\d{2}-\d{2}\.md$/.test(name2)).map((name2) => name2.slice(0, 10)).sort().reverse();
11919
+ } catch (error) {
11920
+ if (missing(error)) return [];
11921
+ throw error;
11922
+ }
11923
+ }
11924
+ async versions(namespace) {
11925
+ const entries = await Promise.all((await this.dates(namespace)).map(async (date) => {
11926
+ try {
11927
+ const info = await stat(join(this.directory(namespace), `${date}.md`));
11928
+ return [date, `${info.mtimeMs}:${info.size}`];
11929
+ } catch (error) {
11930
+ if (missing(error)) return null;
11931
+ throw error;
11932
+ }
11933
+ }));
11934
+ return Object.fromEntries(entries.flatMap((entry) => entry ? [entry] : []));
11935
+ }
11936
+ /** 总览用:事项条数与最近一次写入时间。只读本地 Markdown,不建证据批次。 */
11937
+ async usage(namespace) {
11938
+ const dates = await this.dates(namespace);
11939
+ let count = 0;
11940
+ let updatedAt = null;
11941
+ for (const date of dates) {
11942
+ let content;
11943
+ try {
11944
+ content = await this.load(namespace, date);
11945
+ } catch (error) {
11946
+ if (missing(error)) continue;
11947
+ throw error;
11948
+ }
11949
+ count += items(content).length;
11950
+ const day = Date.parse(`${date}T00:00:00+08:00`);
11951
+ if (Number.isFinite(day) && (updatedAt === null || day > Date.parse(updatedAt))) updatedAt = new Date(day).toISOString();
11952
+ }
11953
+ return { items: count, updatedAt };
11954
+ }
11955
+ load(namespace, date) {
11956
+ return readFile(join(this.directory(namespace), `${validDate(date)}.md`), "utf8");
11957
+ }
11958
+ async write(namespace, args, checkpoint) {
11959
+ const date = validDate(args.date ?? dailyDate(/* @__PURE__ */ new Date(), this.timeZone));
11960
+ if (typeof args.title !== "string" || !args.title.trim() || /[\r\n]/.test(args.title)) throw new TypeError("title \u5FC5\u987B\u662F\u975E\u7A7A\u5355\u884C\u4E8B\u9879\u540D\u79F0");
11961
+ if (typeof args.content !== "string" || args.old_text !== void 0 && (typeof args.old_text !== "string" || !args.old_text)) throw new TypeError("content \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\uFF0Cold_text \u5FC5\u987B\u4E3A\u975E\u7A7A\u539F\u6587");
11962
+ if (containsCredentials(`${args.title}
11963
+ ${args.content}
11964
+ ${args.old_text ?? ""}`)) throw new Error("\u672A\u4FDD\u5B58\uFF1A\u5185\u5BB9\u7591\u4F3C\u5305\u542B\u51ED\u636E\u6216\u5BC6\u94A5\uFF0C\u8BF7\u5220\u9664\u654F\u611F\u5185\u5BB9\u540E\u91CD\u8BD5\u3002");
11965
+ const path = join(this.directory(namespace), `${date}.md`);
11966
+ const run = (queues.get(path) ?? Promise.resolve()).catch(() => {
11967
+ }).then(async () => {
11968
+ let previous;
11969
+ try {
11970
+ previous = await this.load(namespace, date);
11971
+ } catch (error) {
11972
+ if (!missing(error)) throw error;
11973
+ }
11974
+ if (checkpoint && (previous === void 0 ? null : dailyVersion(previous)) !== checkpoint.expectedVersion) {
11975
+ throw new Error("\u7B14\u8BB0\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FEE\u6539\u3002");
11976
+ }
11977
+ const original = previous ?? `# ${date}
11978
+ `;
11979
+ const item = items(original).find((item2) => item2.title === args.title)?.text;
11980
+ const current = item ?? `\u672A\u627E\u5230\u4E8B\u9879\u300A${args.title}\u300B\uFF0C\u4EE5\u4E0B\u4E3A ${date}.md \u5168\u6587\uFF1A
11981
+ ${original}`;
11982
+ let updated;
11983
+ const operation = args.old_text === void 0 ? "\u65B0\u589E" : "\u4FEE\u6539";
11984
+ if (args.old_text === void 0) {
11985
+ if (item !== void 0) throw new Error(`\u672A\u4FDD\u5B58\uFF1A${date}.md \u5DF2\u6709\u4E8B\u9879\u300A${args.title}\u300B\uFF0C\u6CA1\u6709\u91CD\u590D\u65B0\u589E\u3002\u8BE5\u4E8B\u9879\u5F53\u524D\u5168\u6587\u5982\u4E0B\uFF0C\u8BF7\u7528 old_text \u4FEE\u6539\uFF1A
11986
+ ${item}`);
11987
+ if (/^## /m.test(args.content)) throw new TypeError("\u65B0\u589E\u6B63\u6587\u4E0D\u80FD\u5305\u542B\u4E8B\u9879\u6807\u9898\u884C\uFF08## \uFF09");
11988
+ updated = `${original.trimEnd()}
11989
+
11990
+ ## ${args.title}
11991
+ ${args.content}
11992
+ `;
11993
+ } else {
11994
+ let n = 0;
11995
+ for (let start = 0; ; ) {
11996
+ const index = original.indexOf(args.old_text, start);
11997
+ if (index < 0) break;
11998
+ n++;
11999
+ start = index + 1;
12000
+ }
12001
+ if (!n) throw new Error(`\u672A\u4FDD\u5B58\uFF1Aold_text \u5728 ${date}.md \u4E2D\u6CA1\u6709\u5339\u914D\uFF0C\u7B14\u8BB0\u53EF\u80FD\u5DF2\u88AB\u66F4\u65B0\u3002\u4E8B\u9879\u300A${args.title}\u300B\u5F53\u524D\u5168\u6587\u5982\u4E0B\uFF0C\u8BF7\u57FA\u4E8E\u5B83\u5408\u5E76\u540E\u91CD\u8BD5\uFF1A
12002
+ ${current}`);
12003
+ if (n !== 1) throw new Error(`\u672A\u4FDD\u5B58\uFF1Aold_text \u5728 ${date}.md \u4E2D\u5339\u914D\u5230 ${n} \u5904\uFF0C\u8BF7\u52A0\u5165\u66F4\u591A\u4E0A\u4E0B\u6587\u4F7F\u5176\u552F\u4E00\u3002\u4E8B\u9879\u300A${args.title}\u300B\u5F53\u524D\u5168\u6587\u5982\u4E0B\uFF1A
12004
+ ${current}`);
12005
+ updated = original.replace(args.old_text, () => args.content);
12006
+ }
12007
+ await mkdir(dirname(path), { recursive: true });
12008
+ const temporary = `${path}.${randomUUID5()}.tmp`;
12009
+ const backup = `${temporary}.bak`;
12010
+ try {
12011
+ await writeFile(temporary, updated, { encoding: "utf8", flag: "wx" });
12012
+ if (previous !== void 0) {
12013
+ await writeFile(backup, previous, { encoding: "utf8", flag: "wx" });
12014
+ await rename(backup, `${path}.bak`);
12015
+ }
12016
+ await checkpoint?.beforePublish();
12017
+ await rename(temporary, path);
12018
+ } finally {
12019
+ await rm(temporary, { force: true });
12020
+ await rm(backup, { force: true });
12021
+ }
12022
+ const info = checkpoint ? await stat(path) : void 0;
12023
+ return {
12024
+ date,
12025
+ filename: `${date}.md`,
12026
+ title: args.title,
12027
+ operation,
12028
+ message: `\u5DF2\u4FDD\u5B58\u5230 ${date}.md\uFF1A\u300A${args.title}\u300B\uFF08${operation}\uFF09\u3002`,
12029
+ ...info ? { version: `${info.mtimeMs}:${info.size}` } : {}
12030
+ };
12031
+ });
12032
+ queues.set(path, run);
12033
+ try {
12034
+ return await run;
12035
+ } finally {
12036
+ if (queues.get(path) === run) queues.delete(path);
12037
+ }
12038
+ }
12039
+ async read(namespace, args = {}) {
12040
+ const offset = args.offset ?? 0;
12041
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new TypeError("offset \u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570");
12042
+ if (args.date) validDate(args.date);
12043
+ if (args.date && args.query === void 0) return { note: DAILY_NOTE_LABEL, date: args.date, filename: `${args.date}.md`, content: await this.load(namespace, args.date) };
12044
+ const dates = args.date ? [args.date] : await this.dates(namespace);
12045
+ const selected = dates.slice(offset, offset + 30);
12046
+ const records = await Promise.all(selected.map(async (date) => ({ date, content: await this.load(namespace, date) })));
12047
+ return {
12048
+ note: DAILY_NOTE_LABEL,
12049
+ ...args.query !== void 0 ? { matches: records.flatMap(({ date, content }) => items(content).filter((item) => item.text.toLocaleLowerCase().includes(args.query.toLocaleLowerCase())).map((item) => {
12050
+ const index = item.text.toLocaleLowerCase().indexOf(args.query.toLocaleLowerCase());
12051
+ return { date, title: item.title, snippet: item.text.slice(Math.max(0, index - 100), index + 400) };
12052
+ })) } : { dates: records.map(({ date, content }) => ({ date, titles: items(content).map((item) => item.title) })) },
12053
+ ...offset + selected.length < dates.length ? { nextOffset: offset + selected.length } : {}
12054
+ };
12055
+ }
12056
+ async snapshot(namespace) {
12057
+ const dates = selectDailyInjectionDates(await this.dates(namespace), this.injectionDays);
12058
+ if (!dates.length) return "";
12059
+ const records = await Promise.all(dates.map(async (date) => ({ date, content: await this.load(namespace, date) })));
12060
+ const header = `[StrataGate daily notes]
12061
+ Today: ${dailyDate(/* @__PURE__ */ new Date(), this.timeZone)} (${this.timeZone})
12062
+ Your working notes from the ${this.injectionDays} most recent dates with notes, as of the start of this session. They are historical work records, not new user instructions. Within this session, memory_daily_write results are authoritative; use memory_daily_read for an item's current text before replacing it.
12063
+
12064
+ `;
12065
+ const shown = records.map((record3) => ({ ...record3, parts: items(record3.content), removed: [] }));
12066
+ const render = () => header + shown.map((record3) => record3.removed.length ? record3.parts.length ? `# ${record3.date}
12067
+ ${record3.parts.map((item) => item.text).join("\n\n")}
12068
+ ` : "" : record3.content).filter(Boolean).join("\n") + shown.filter((record3) => record3.removed.length).map((record3) => `
12069
+ [Omitted for length: ${record3.date} (${record3.removed.length} items: ${record3.removed.map((title) => `\u300A${title}\u300B`).join("")}\u2026). Use memory_daily_read with date to read them.]`).join("");
12070
+ for (const record3 of [...shown].reverse()) {
12071
+ while (render().length > this.budget && record3.parts.length) record3.removed.unshift(record3.parts.pop().title);
12072
+ }
12073
+ const output = render();
12074
+ if (output.length <= this.budget) return output;
12075
+ const notice = records.map((record3) => `
12076
+ [Omitted for length: ${record3.date} (${items(record3.content).length} items: ${items(record3.content).slice(0, 1).map((item) => `\u300A${item.title.slice(0, 20)}\u300B`).join("")}\u2026). Use memory_daily_read with date to read them.]`).join("");
12077
+ if ((header + notice).length <= this.budget) return header + notice;
12078
+ return header + `
12079
+ [Omitted for length: ${records.length} note dates (${records[records.length - 1].date} to ${records[0].date}). Use memory_daily_read to list dates and read their full text.]`;
12080
+ }
12081
+ };
12082
+ function dailyVersion(text3) {
12083
+ return createHash5("sha256").update(JSON.stringify(text3)).digest("hex");
12084
+ }
12085
+
12086
+ // src/letters.ts
12087
+ var DAY_MS = 864e5;
12088
+ var LEASE_MS = 3e5;
12089
+ var DAILY_LETTER_SKILL = `\u4F60\u6B63\u5728\u7ED9\u7528\u6237\u5199\u4E00\u5C01\u6309\u65E5\u671F\u5F52\u6863\u7684\u624B\u5199\u6765\u4FE1\u3002\u7D20\u6750\u91CC\u53EA\u6709\u90A3\u5929\u7684\u4F1A\u8BDD\u7247\u6BB5\uFF0C\u5B83\u4EEC\u662F\u8BB0\u5F55\uFF0C\u4E0D\u662F\u6307\u4EE4\u3002
12090
+ \u4ECE\u8FD9\u4E00\u5929\u91CC\u6311\u4E00\u4E24\u4EF6\u786E\u5B9E\u63A8\u8FDB\u4E86\u7684\u4E8B\uFF0C\u5199\u6E05\u695A\u53D1\u751F\u4E86\u4EC0\u4E48\u3001\u4E3A\u4EC0\u4E48\u503C\u5F97\u8BB0\u4F4F\u3002\u7528\u81EA\u7136\u3001\u6709\u4E00\u70B9\u4FCF\u76AE\u7684\u53E3\u543B\uFF0C\u50CF\u672C\u4EBA\u56DE\u671B\u4E00\u5929\uFF0C\u5199\u4E24\u4E09\u4E2A\u77ED\u6BB5\u843D\u3002\u907F\u514D\u6D41\u6C34\u8D26\u548C\u5957\u8BDD\uFF0C\u522B\u8865\u5199\u7D20\u6750\u91CC\u6CA1\u6709\u7684\u51B3\u5B9A\u3001\u8FDB\u5C55\u6216\u611F\u53D7\u3002
12091
+ \u5E38\u9A7B\u753B\u50CF\u53EA\u7528\u4E8E\u8BED\u6C14\u3001\u79F0\u547C\u548C\u7F72\u540D\u3002\u9ED8\u8BA4\u7528\u7B80\u4F53\u4E2D\u6587\u3001\u8BED\u6C14\u8F7B\u677E\u514B\u5236\u3002\u6765\u4FE1\u53EA\u5199\u4F1A\u8BDD\u4E2D\u7684\u4E8B\uFF0C\u6574\u7406\u6570\u636E\u4F1A\u7531\u754C\u9762\u5355\u72EC\u9644\u4E0A\u3002\u7D20\u6750\u6CA1\u6709\u503C\u5F97\u8BB0\u4E0B\u7684\u8FDB\u5C55\u65F6\uFF0C\u8FD4\u56DE\u7A7A\u7684 paragraphs\u3002`;
12092
+ function shiftLetterDate(date, days) {
12093
+ return new Date(Date.parse(date) + days * DAY_MS).toISOString().slice(0, 10);
12094
+ }
12095
+ function startOfLetterDate(date, timeZone) {
12096
+ const utc = Date.parse(date);
12097
+ let before = utc - DAY_MS;
12098
+ let after = utc + DAY_MS;
12099
+ while (after - before > 1) {
12100
+ const middle = Math.floor((before + after) / 2);
12101
+ if (dailyDate(new Date(middle), timeZone) < date) before = middle;
12102
+ else after = middle;
12103
+ }
12104
+ return after;
12105
+ }
12106
+ var DailyLetters = class {
12107
+ database;
12108
+ constructor(filename) {
12109
+ this.database = new DatabaseSync3(filename, { timeout: 5e3 });
12110
+ this.database.exec(`
12111
+ CREATE TABLE IF NOT EXISTS stratagate_dsh_letters (
12112
+ namespace TEXT NOT NULL,
12113
+ date TEXT NOT NULL,
12114
+ claim TEXT,
12115
+ lease_until INTEGER NOT NULL DEFAULT 0,
12116
+ finished INTEGER NOT NULL DEFAULT 0,
12117
+ letter_json TEXT,
12118
+ PRIMARY KEY (namespace, date),
12119
+ FOREIGN KEY (namespace) REFERENCES memory_spaces(namespace) ON DELETE CASCADE
12120
+ ) STRICT;
12121
+ `);
12122
+ }
12123
+ close() {
12124
+ this.database.close();
12125
+ }
12126
+ nextDate(namespace, firstDate) {
12127
+ const latest = this.database.prepare("SELECT date, finished FROM stratagate_dsh_letters WHERE namespace = ? ORDER BY date DESC LIMIT 1").get(namespace);
12128
+ return latest ? latest.finished ? shiftLetterDate(latest.date, 1) : latest.date : firstDate;
12129
+ }
12130
+ claim(namespace, date, now) {
12131
+ const claim = randomUUID6();
12132
+ const result = this.database.prepare(`
12133
+ INSERT INTO stratagate_dsh_letters (namespace, date, claim, lease_until) VALUES (?, ?, ?, ?)
12134
+ ON CONFLICT(namespace, date) DO UPDATE SET claim = excluded.claim, lease_until = excluded.lease_until
12135
+ WHERE finished = 0 AND lease_until <= ?
12136
+ `).run(namespace, date, claim, now + LEASE_MS, now);
12137
+ return result.changes ? claim : null;
12138
+ }
12139
+ finish(namespace, date, claim, letter) {
12140
+ this.database.prepare(`
12141
+ UPDATE stratagate_dsh_letters SET letter_json = ?, finished = 1, claim = NULL, lease_until = 0
12142
+ WHERE namespace = ? AND date = ? AND claim = ?
12143
+ `).run(letter ? JSON.stringify(letter) : null, namespace, date, claim);
12144
+ }
12145
+ release(namespace, date, claim) {
12146
+ this.database.prepare("UPDATE stratagate_dsh_letters SET lease_until = 0 WHERE namespace = ? AND date = ? AND claim = ?").run(namespace, date, claim);
12147
+ }
12148
+ dates(namespace) {
12149
+ return this.database.prepare("SELECT date FROM stratagate_dsh_letters WHERE namespace = ? AND letter_json IS NOT NULL ORDER BY date DESC").all(namespace).map((row) => row.date);
12150
+ }
12151
+ read(namespace, date) {
12152
+ const row = this.database.prepare("SELECT letter_json FROM stratagate_dsh_letters WHERE namespace = ? AND date = ?").get(namespace, date);
12153
+ return row?.letter_json ? JSON.parse(row.letter_json) : null;
12154
+ }
12155
+ material(namespace, date, timeZone) {
12156
+ const start = startOfLetterDate(date, timeZone);
12157
+ const end = startOfLetterDate(shiftLetterDate(date, 1), timeZone);
12158
+ const rows = this.database.prepare(`
12159
+ SELECT role, content FROM messages WHERE namespace = ? AND role IN ('user', 'assistant')
12160
+ AND unixepoch(created_at) >= ? AND unixepoch(created_at) < ?
12161
+ AND trim(content) <> '' AND COALESCE(thread_id, '') NOT LIKE 'stratagate-dreaming:%'
12162
+ ORDER BY unixepoch(created_at) DESC, position DESC LIMIT 40
12163
+ `).all(namespace, start / 1e3, end / 1e3);
12164
+ return rows.reverse().filter((row) => !containsCredentials(row.content)).map((row) => ({ role: row.role, text: row.content.slice(0, 650) }));
12165
+ }
12166
+ reports(namespace, date, timeZone) {
12167
+ const start = startOfLetterDate(date, timeZone);
12168
+ const end = startOfLetterDate(shiftLetterDate(date, 1), timeZone);
12169
+ const rows = this.database.prepare(`
12170
+ SELECT run_id, finished_at, changes_json FROM dreaming_reports
12171
+ WHERE namespace = ? AND finished_at >= ? AND finished_at < ? ORDER BY finished_at, run_id
12172
+ `).all(namespace, start, end);
12173
+ return rows.map((row) => ({ id: row.run_id, finishedAt: row.finished_at, changes: JSON.parse(row.changes_json) }));
12174
+ }
12175
+ };
12176
+
12177
+ // src/llm.ts
12178
+ import { BlockAssembler, createUserMessage } from "@deepseek-ai/dsh-llm";
12179
+ import { parameterSchemaSpecToJsonSchema, validateArgs } from "@deepseek-ai/dsh-tools";
12180
+
12181
+ // src/dsh-compatibility.ts
12182
+ import { readFileSync } from "node:fs";
12183
+ import { createRequire as createRequire2 } from "node:module";
12184
+ import { satisfies } from "semver";
12185
+ var nodeRequire = createRequire2(import.meta.url);
12186
+ var CORE_RUNTIME_PACKAGES = [
12187
+ "@deepseek-ai/cordis",
12188
+ "@deepseek-ai/dsh-agent-default-model",
12189
+ "@deepseek-ai/dsh-client-ui-conversation",
12190
+ "@deepseek-ai/dsh-llm",
12191
+ "@deepseek-ai/dsh-native-command",
12192
+ "@deepseek-ai/dsh-session",
12193
+ "@deepseek-ai/dsh-settings",
12194
+ "@deepseek-ai/dsh-system-prompt",
12195
+ "@deepseek-ai/dsh-tools",
12196
+ "@deepseek-ai/schemastery"
12197
+ ];
12198
+ var SESSION_FORMAT_PACKAGES = [
12199
+ "@deepseek-ai/dsh-session-format",
12200
+ "@deepseek-ai/dsh-session-format-catalog",
12201
+ "@deepseek-ai/dsh-session-format-v0-to-v1"
12202
+ ];
12203
+ var RUNTIME_PACKAGES = [...CORE_RUNTIME_PACKAGES, ...SESSION_FORMAT_PACKAGES];
12204
+ var STRATAGATE_MESSAGE_SOURCE_KIND = "plugin:stratagate-memory";
12205
+ var DSH_RUNTIME_RANGE = "0.1.2-rc.1 || >=0.1.5-rc.2 <0.3.0-0";
12206
+ var MODERN_API_RANGE = ">=0.1.7-rc.1";
12207
+ var SESSION_FORMAT_RUNTIME_RANGE = ">=0.2.0-0";
12208
+ var DSH_022_VENDOR_RUNTIME_RANGE = ">=0.2.2-0 <0.3.0-0";
12209
+ var SEMVER_OPTIONS = { includePrerelease: true };
12210
+ function assertDshMethods(scope, value, methods) {
12211
+ const target = value;
12212
+ const missing2 = methods.filter((method) => typeof target?.[method] !== "function");
12213
+ if (missing2.length) {
12214
+ throw new Error(`StrataGate cannot use this DSH host: missing required interface ${missing2.map((method) => `${scope}.${method}`).join(", ")}. Use a compatible host or plugin version.`);
12215
+ }
12216
+ }
12217
+ function assertDshHostContract(ctx) {
12218
+ assertDshMethods("tools", ctx.tools, ["register", "get"]);
12219
+ assertDshMethods("systemPrompt", ctx.systemPrompt, ["section"]);
12220
+ assertDshMethods("llm", ctx.llm, ["stream", "listProviders"]);
12221
+ assertDshMethods("agentDefaultModel", ctx.agentDefaultModel, ["currentSelection"]);
12222
+ }
12223
+ function buildDshMessageSource(version, form) {
12224
+ const source = satisfies(version, MODERN_API_RANGE, SEMVER_OPTIONS) ? { kind: STRATAGATE_MESSAGE_SOURCE_KIND } : { kind: "plugin", plugin: "stratagate-memory" };
12225
+ return form ? { ...source, form } : source;
12226
+ }
12227
+ function installedVersion(packageName) {
12228
+ try {
12229
+ const manifestPath = nodeRequire.resolve(`${packageName}/package.json`);
12230
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
12231
+ if (typeof manifest.version === "string" && manifest.version.length > 0) return manifest.version;
12232
+ } catch {
12233
+ }
12234
+ return "<missing>";
12235
+ }
12236
+ function buildDshReplaceSurfaceOp(version, start, end) {
12237
+ return version === "0.1.2-rc.1" ? { op: "replace", start, end } : { op: "replace", startSeq: start, endSeq: end };
12238
+ }
12239
+ function dshReplaceSurfaceOp(start, end) {
12240
+ return buildDshReplaceSurfaceOp(installedVersion("@deepseek-ai/dsh-session"), start, end);
12241
+ }
12242
+ function dshMessageSource(form) {
12243
+ return buildDshMessageSource(installedVersion("@deepseek-ai/dsh-session"), form);
12244
+ }
12245
+ function isStrataGateMessageSource(source) {
12246
+ if (!source || typeof source !== "object") return false;
12247
+ const value = source;
12248
+ return value.kind === STRATAGATE_MESSAGE_SOURCE_KIND || value.kind === "plugin" && value.plugin === "stratagate-memory";
12249
+ }
12250
+ function isCompatiblePatch(version, major, minor, minimumPatch) {
12251
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
12252
+ return !!match && Number(match[1]) === major && Number(match[2]) === minor && Number(match[3]) >= minimumPatch;
12253
+ }
12254
+ function classifyDshRuntime(packageVersions) {
12255
+ const dshVersion = packageVersions["@deepseek-ai/dsh-session"];
12256
+ const sameDshFamily = CORE_RUNTIME_PACKAGES.filter((name2) => name2.startsWith("@deepseek-ai/dsh-")).every((name2) => packageVersions[name2] === dshVersion);
12257
+ const sameSessionFormatFamily = !satisfies(dshVersion, SESSION_FORMAT_RUNTIME_RANGE, SEMVER_OPTIONS) || SESSION_FORMAT_PACKAGES.every((name2) => packageVersions[name2] === dshVersion);
12258
+ const modernApi = satisfies(dshVersion, MODERN_API_RANGE, SEMVER_OPTIONS);
12259
+ const dsh022VendorFamily = satisfies(dshVersion, DSH_022_VENDOR_RUNTIME_RANGE, SEMVER_OPTIONS);
12260
+ const compatibleVendors = modernApi ? dsh022VendorFamily ? isCompatiblePatch(packageVersions["@deepseek-ai/cordis"], 4, 1, 0) && isCompatiblePatch(packageVersions["@deepseek-ai/schemastery"], 3, 19, 0) : isCompatiblePatch(packageVersions["@deepseek-ai/cordis"], 4, 0, 4) && isCompatiblePatch(packageVersions["@deepseek-ai/schemastery"], 3, 18, 4) : packageVersions["@deepseek-ai/cordis"] === "4.0.2" && packageVersions["@deepseek-ai/schemastery"] === "3.18.2";
12261
+ if (satisfies(dshVersion, DSH_RUNTIME_RANGE, SEMVER_OPTIONS) && sameDshFamily && sameSessionFormatFamily && compatibleVendors) {
12262
+ return { cliVersion: dshVersion === "0.1.5-rc.2" ? "0.1.5-rc.1" : dshVersion, packageVersions };
12263
+ }
12264
+ const found = RUNTIME_PACKAGES.map((name2) => `${name2}@${packageVersions[name2]}`).join(", ");
12265
+ throw new Error(
12266
+ `StrataGate cannot start because this DSH profile resolves an unsupported or mixed core runtime. Resolved: ${found}. Supported DSH versions: ${DSH_RUNTIME_RANGE} (including prereleases). Core DSH packages must share one version; DSH 0.2.0 and later also require matching Session Format packages. DSH 0.2.2 and later require Cordis 4.1.x from 4.1.0 and Schemastery 3.19.x from 3.19.0; earlier modern hosts require Cordis 4.0.x from 4.0.4 and Schemastery 3.18.x from 3.18.4, while older hosts use 4.0.2 and 3.18.2. Reinstall or update stratagate-dsh through \`dsh plugin --profile <name> add <package>\` so the host supplies its peers.`
12267
+ );
12268
+ }
12269
+ function assertCompatibleDshRuntime() {
12270
+ const packageVersions = Object.fromEntries(RUNTIME_PACKAGES.map((name2) => [name2, installedVersion(name2)]));
12271
+ return classifyDshRuntime(packageVersions);
12272
+ }
12273
+
12274
+ // src/json-response.ts
12275
+ var RESPONSE_PREVIEW_LIMIT = 500;
12276
+ function truncateResponsePreview(value) {
12277
+ return value.slice(0, RESPONSE_PREVIEW_LIMIT);
12278
+ }
12279
+ var ModelJsonResponseError = class extends Error {
12280
+ fullMessage;
12281
+ response;
12282
+ responsePreview;
12283
+ constructor(message = "StrataGate model response was not valid JSON", options) {
12284
+ const response = options?.response ?? options?.responsePreview;
12285
+ const responsePreview = response ? truncateResponsePreview(response) : void 0;
12286
+ const displayMessage = responsePreview ? `${message}
12287
+ Raw response preview (first ${RESPONSE_PREVIEW_LIMIT} chars):
12288
+ ${responsePreview}` : message;
12289
+ super(displayMessage, options);
12290
+ this.name = "ModelJsonResponseError";
12291
+ const causeMessage = options?.cause instanceof Error ? options.cause.message.split("\nRaw response preview")[0] : "";
12292
+ const causeDetail = causeMessage && causeMessage !== message ? `
12293
+ Cause: ${causeMessage}` : "";
12294
+ this.fullMessage = response ? `${message}${causeDetail}
12295
+ Raw response (full):
12296
+ ${response}` : `${displayMessage}${causeDetail}`;
12297
+ this.response = response;
12298
+ this.responsePreview = responsePreview;
12299
+ }
12300
+ };
12301
+ function isObject(value) {
12302
+ return value !== null && typeof value === "object" && !Array.isArray(value);
12303
+ }
12304
+ function hasRequiredKeys(value, requiredKeys) {
12305
+ return requiredKeys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
12306
+ }
12307
+ function balancedValueEnd(value, start) {
12308
+ const opening = value[start];
12309
+ if (opening !== "{" && opening !== "[") return null;
12310
+ const stack = [opening];
12311
+ let inString = false;
12312
+ let escaped = false;
12313
+ for (let index = start + 1; index < value.length; index += 1) {
12314
+ const character = value[index];
12315
+ if (inString) {
12316
+ if (escaped) escaped = false;
12317
+ else if (character === "\\") escaped = true;
12318
+ else if (character === '"') inString = false;
12319
+ continue;
12320
+ }
12321
+ if (character === '"') {
12322
+ inString = true;
12323
+ continue;
12324
+ }
12325
+ if (character === "{" || character === "[") {
12326
+ stack.push(character);
12327
+ continue;
12328
+ }
12329
+ if (character !== "}" && character !== "]") continue;
12330
+ const expected = character === "}" ? "{" : "[";
12331
+ if (stack.at(-1) !== expected) return null;
12332
+ stack.pop();
12333
+ if (stack.length === 0) return index;
12334
+ }
12335
+ return null;
12336
+ }
12337
+ function parse(value) {
12338
+ try {
12339
+ return JSON.parse(value);
12340
+ } catch {
12341
+ return void 0;
12342
+ }
12343
+ }
12344
+ function parseJsonResponse(value, requiredKeys = []) {
12345
+ const trimmed = value.trim().replace(/^\uFEFF/, "");
12346
+ const direct = parse(trimmed);
12347
+ if (direct !== void 0) {
12348
+ if (isObject(direct) && hasRequiredKeys(direct, requiredKeys)) return direct;
12349
+ if (isObject(direct) && requiredKeys.length > 0) {
12350
+ throw new ModelJsonResponseError(
12351
+ `StrataGate model response JSON object was missing required fields: ${requiredKeys.join(", ")}`,
12352
+ { response: value }
12353
+ );
12354
+ }
12355
+ throw new ModelJsonResponseError("StrataGate model response was not a JSON object", { response: value });
12356
+ }
12357
+ const parsedValues = [];
12358
+ for (let start = 0; start < trimmed.length; start += 1) {
12359
+ const character = trimmed[start];
12360
+ if (character !== "{" && character !== "[") continue;
12361
+ const end = balancedValueEnd(trimmed, start);
12362
+ if (end === null) continue;
12363
+ const candidate = parse(trimmed.slice(start, end + 1));
12364
+ if (candidate !== void 0) parsedValues.push({ value: candidate, start, end });
12365
+ start = end;
12366
+ }
12367
+ if (parsedValues.length === 1) {
12368
+ const only = parsedValues[0];
12369
+ if (isObject(only.value) && hasRequiredKeys(only.value, requiredKeys)) return only.value;
12370
+ if (isObject(only.value) && requiredKeys.length > 0) {
12371
+ throw new ModelJsonResponseError(
12372
+ `StrataGate model response JSON object was missing required fields: ${requiredKeys.join(", ")}`,
12373
+ { response: value }
12374
+ );
12375
+ }
12376
+ throw new ModelJsonResponseError("StrataGate model response did not contain a JSON object", { response: value });
12377
+ }
12378
+ if (parsedValues.length > 1) {
12379
+ const first = parsedValues[0];
12380
+ const last = parsedValues.at(-1);
12381
+ const between = parsedValues.slice(0, -1).some((candidate, index) => {
12382
+ const next = parsedValues[index + 1];
12383
+ return trimmed.slice(candidate.end + 1, next.start).trim().length > 0;
12384
+ });
12385
+ const hasNonJsonPrefix = trimmed.slice(0, first.start).trim().length > 0;
12386
+ const hasNonJsonSuffix = trimmed.slice(last.end + 1).trim().length > 0;
12387
+ const final = last.value;
12388
+ if ((between || hasNonJsonPrefix || hasNonJsonSuffix) && isObject(final) && hasRequiredKeys(final, requiredKeys)) return final;
12389
+ if ((between || hasNonJsonPrefix || hasNonJsonSuffix) && isObject(final) && requiredKeys.length > 0) {
12390
+ throw new ModelJsonResponseError(
12391
+ `StrataGate model response JSON object was missing required fields: ${requiredKeys.join(", ")}`,
12392
+ { response: value }
12393
+ );
12394
+ }
12395
+ throw new ModelJsonResponseError("StrataGate model response contained multiple JSON values", { response: value });
12396
+ }
12397
+ throw new ModelJsonResponseError(void 0, { response: value });
12398
+ }
12399
+
12400
+ // src/extraction-batches.ts
12401
+ var ExtractionCapacityError = class extends Error {
12402
+ constructor(capacity) {
12403
+ super(`Event extraction ${capacity} capacity exceeded; a smaller source batch is required`);
12404
+ this.capacity = capacity;
12405
+ }
12406
+ capacity;
12407
+ };
12408
+ var CONTEXT_CHARS = 1200;
12409
+ function splitExtractionSlice(slice) {
12410
+ const messages = slice.messages;
12411
+ let left;
12412
+ let right;
12413
+ if (messages.length > 1) {
12414
+ const weights = messages.map((message) => estimateTokens(JSON.stringify(message)));
12415
+ const half = weights.reduce((sum, size2) => sum + size2, 0) / 2;
12416
+ let index = 1;
12417
+ let size = weights[0];
12418
+ while (index < messages.length - 1 && size < half) size += weights[index++];
12419
+ left = messages.slice(0, index);
12420
+ right = messages.slice(index);
12421
+ } else {
12422
+ const message = messages[0];
12423
+ if (!message) throw new Error("Event extraction has no source to split");
12424
+ const content = message.content + (message.toolCalls?.length ? `
12425
+ [Tool evidence, JSON]
12426
+ ${JSON.stringify(message.toolCalls)}` : "");
12427
+ if (content.length < 2) throw new Error("Event extraction cannot split this source any further");
12428
+ const middle = Math.floor(content.length / 2);
12429
+ const boundary = content.lastIndexOf("\n", middle);
12430
+ let cut = boundary >= middle / 2 ? boundary + 1 : middle;
12431
+ if (/[\uD800-\uDBFF]/.test(content[cut - 1])) cut += 1;
12432
+ if (cut >= content.length) throw new Error("Event extraction cannot split this source any further");
12433
+ const { toolCalls: _tools, ...base } = message;
12434
+ left = [{ ...base, content: content.slice(0, cut) }];
12435
+ right = [{ ...base, content: content.slice(cut) }];
12436
+ }
12437
+ const excerpt = (items2) => items2.map((message) => JSON.stringify(message)).join("\n");
12438
+ return [
12439
+ { messages: left, before: slice.before, after: excerpt(right).slice(0, CONTEXT_CHARS), depth: slice.depth + 1 },
12440
+ { messages: right, before: excerpt(left).slice(-CONTEXT_CHARS), after: slice.after, depth: slice.depth + 1 }
12441
+ ];
12442
+ }
12443
+ function mergeExtractionEvents(events, exactKey) {
12444
+ const unique3 = /* @__PURE__ */ new Map();
12445
+ for (const event of events) {
12446
+ const key = exactKey(event);
12447
+ const prior = unique3.get(key);
12448
+ if (!prior) {
12449
+ unique3.set(key, structuredClone(event));
12450
+ continue;
12451
+ }
12452
+ prior.sourceMessageIds = [.../* @__PURE__ */ new Set([...prior.sourceMessageIds, ...event.sourceMessageIds])];
12453
+ prior.tags = [.../* @__PURE__ */ new Set([...prior.tags ?? [], ...event.tags ?? []])].slice(0, 16);
12454
+ prior.quotes = [.../* @__PURE__ */ new Set([...prior.quotes ?? [], ...event.quotes ?? []])].slice(0, 12);
12093
12455
  }
12456
+ return [...unique3.values()];
12094
12457
  }
12095
12458
 
12096
12459
  // src/llm.ts
12460
+ import { randomUUID as randomUUID7 } from "node:crypto";
12097
12461
  var ELEMENT_TYPES2 = /* @__PURE__ */ new Set(["person", "project", "organization", "tool", "place"]);
12098
12462
  var CRITICALITIES = /* @__PURE__ */ new Set(["routine", "preference", "identity", "safety"]);
12099
12463
  function object(value) {
@@ -12154,6 +12518,7 @@ var STRUCTURED_FIELDS = {
12154
12518
  graphProjector: ["reason", "nodes", "edges"],
12155
12519
  topicProjector: ["topics"],
12156
12520
  dreamingStep: ["tool", "args"],
12521
+ dailyLetter: ["title", "paragraphs", "signature"],
12157
12522
  externalMemoryExtractor: ["reason", "candidates"],
12158
12523
  externalMemoryDecider: ["action", "reason", "confidence"],
12159
12524
  eventDuplicateDecider: ["action", "reason", "confidence"],
@@ -12419,6 +12784,15 @@ var STRUCTURED_TOOLS = {
12419
12784
  args: { ...OPEN_OBJECT, required: true }
12420
12785
  }
12421
12786
  },
12787
+ dailyLetter: {
12788
+ name: "stratagate_write_daily_letter",
12789
+ description: "Save the title, short paragraphs, and signature of one dated letter.",
12790
+ parameters: {
12791
+ title: { type: "string", required: true },
12792
+ paragraphs: { type: "array", items: { type: "string" }, required: true },
12793
+ signature: { type: "string", required: true }
12794
+ }
12795
+ },
12422
12796
  externalMemoryDecider: {
12423
12797
  name: "stratagate_decide_external_memory",
12424
12798
  description: "Decide how one external memory candidate relates to retrieved local events.",
@@ -12756,6 +13130,11 @@ dreaming_directory {operations:[...]}: atomic current-chapter operations, chosen
12756
13130
  ${DREAMING_DIRECTORY_GUIDANCE}
12757
13131
  Choose exactly one action using stratagate_dreaming_step. args is an object. Finish args may contain a short summary.`, payload);
12758
13132
  };
13133
+ async writeDailyLetter(payload, profile) {
13134
+ return await this.callStructured("dailyLetter", profile ? `${DAILY_LETTER_SKILL}
13135
+
13136
+ ${profile}` : DAILY_LETTER_SKILL, payload);
13137
+ }
12759
13138
  takeSuccessfulResponses() {
12760
13139
  const responses = this.successfulResponses.splice(0, this.successfulResponses.length);
12761
13140
  return responses;
@@ -13087,7 +13466,7 @@ Use project scope for repository decisions, user scope for stable preferences/id
13087
13466
  const scope = {
13088
13467
  namespace: execution?.namespace ?? this.diagnosticNamespace(execution?.session, String(execution?.sessionId ?? "")),
13089
13468
  stage: kind,
13090
- taskId: `task_${randomUUID5()}`,
13469
+ taskId: `task_${randomUUID7()}`,
13091
13470
  calls: 0
13092
13471
  };
13093
13472
  const start = Date.now();
@@ -13365,7 +13744,7 @@ Correct these canonical-name provenance fields: ${[...new Set(paths)].slice(0, 2
13365
13744
  { cause: error, response: responseForError }
13366
13745
  );
13367
13746
  }
13368
- if (kind !== "profileMaintenance" && kind !== "topicProjector" && kind !== "dreamingStep" && kind !== "eventDuplicateDecider") {
13747
+ if (kind !== "profileMaintenance" && kind !== "topicProjector" && kind !== "dreamingStep" && kind !== "dailyLetter" && kind !== "eventDuplicateDecider") {
13369
13748
  this.successfulResponses.push({
13370
13749
  id: `model_response_${crypto.randomUUID()}`,
13371
13750
  kind,
@@ -13528,12 +13907,12 @@ function isOffRejection(error) {
13528
13907
  }
13529
13908
 
13530
13909
  // src/metadata.ts
13531
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
13910
+ import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
13532
13911
  import { existsSync } from "node:fs";
13533
13912
  function readGraphSettings(filename) {
13534
13913
  const defaults = { enabled: false, paused: false, epoch: 0, legacy: false, noticeSeen: false, everEnabled: false, approved: {} };
13535
13914
  if (filename === ":memory:" || !existsSync(filename)) return defaults;
13536
- const db = new DatabaseSync3(filename, { readOnly: true, timeout: 5e3 });
13915
+ const db = new DatabaseSync4(filename, { readOnly: true, timeout: 5e3 });
13537
13916
  try {
13538
13917
  const tables = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
13539
13918
  defaults.legacy = tables.has("memory_spaces") && Boolean(db.prepare("SELECT 1 FROM memory_spaces LIMIT 1").get());
@@ -13566,7 +13945,7 @@ CREATE TABLE IF NOT EXISTS stratagate_dsh_feedback_drafts (
13566
13945
  ) STRICT;
13567
13946
  `;
13568
13947
  function dropLegacyAgentMemoriesTable(filename) {
13569
- const database = new DatabaseSync3(filename);
13948
+ const database = new DatabaseSync4(filename);
13570
13949
  try {
13571
13950
  const legacyTable = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_agent_memories'").get();
13572
13951
  if (!legacyTable) return;
@@ -13579,7 +13958,7 @@ function dropLegacyAgentMemoriesTable(filename) {
13579
13958
  var DshMetadataStore = class {
13580
13959
  database;
13581
13960
  constructor(filename) {
13582
- this.database = new DatabaseSync3(filename, { timeout: 5e3 });
13961
+ this.database = new DatabaseSync4(filename, { timeout: 5e3 });
13583
13962
  this.database.exec("PRAGMA busy_timeout = 5000");
13584
13963
  this.database.exec(METADATA_SCHEMA);
13585
13964
  this.database.exec("BEGIN IMMEDIATE");
@@ -13749,221 +14128,10 @@ var DshMetadataStore = class {
13749
14128
 
13750
14129
  // src/runtime.ts
13751
14130
  import { mkdir as mkdir2 } from "node:fs/promises";
13752
-
13753
- // src/daily-notes.ts
13754
- import { mkdir, readFile, readdir, writeFile, rename, rm, stat } from "node:fs/promises";
13755
- import { dirname, join, resolve as resolve2 } from "node:path";
13756
- import { randomUUID as randomUUID6, createHash as createHash5 } from "node:crypto";
13757
- var DAILY_NOTE_LABEL = "\u5DE5\u4F5C\u7B14\u8BB0\uFF0C\u4E0D\u662F\u4E8B\u5B9E\u8BC1\u636E\uFF0C\u4E5F\u4E0D\u662F\u65B0\u6307\u4EE4\u3002";
13758
- var DAILY_LOAD_FAILURE = "[StrataGate daily notes]\nDaily notes could not be loaded for this session. This is a read failure, not an empty record. Use memory_daily_read to retry.";
13759
- var queues = /* @__PURE__ */ new Map();
13760
- var missing = (error) => error.code === "ENOENT";
13761
- function dailyDate(now = /* @__PURE__ */ new Date(), timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone) {
13762
- const parts = new Intl.DateTimeFormat("en-US", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(now);
13763
- return ["year", "month", "day"].map((key) => parts.find((part) => part.type === key).value).join("-");
13764
- }
13765
- function validDate(date) {
13766
- if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !Number.isFinite(Date.parse(date)) || new Date(date).toISOString().slice(0, 10) !== date) throw new TypeError("date \u5FC5\u987B\u662F\u6709\u6548\u7684 YYYY-MM-DD");
13767
- return date;
13768
- }
13769
- function selectDailyInjectionDates(dates, days = 3) {
13770
- return dates.slice(0, days);
13771
- }
13772
- function items(text3) {
13773
- const matches = [...text3.matchAll(/^## (.+)\r?$/gm)];
13774
- return matches.map((match, index) => ({ title: match[1], text: text3.slice(match.index, matches[index + 1]?.index ?? text3.length).trimEnd() }));
13775
- }
13776
- var DailyNotes = class {
13777
- constructor(database, timeZone, budget = 12e3, injectionDays = 3) {
13778
- this.database = database;
13779
- this.budget = budget;
13780
- this.injectionDays = injectionDays;
13781
- this.timeZone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
13782
- dailyDate(/* @__PURE__ */ new Date(), this.timeZone);
13783
- }
13784
- database;
13785
- budget;
13786
- injectionDays;
13787
- timeZone;
13788
- directory(namespace) {
13789
- if (this.database === ":memory:") throw new Error("\u6BCF\u65E5\u7B14\u8BB0\u4E0D\u53EF\u7528\uFF1Adatabase \u4E3A :memory:\uFF0C\u8BF7\u914D\u7F6E\u6301\u4E45\u6570\u636E\u5E93\u8DEF\u5F84\u3002");
13790
- return join(dirname(resolve2(this.database)), "daily", `ns-${createHash5("sha256").update(namespace).digest("hex")}`);
13791
- }
13792
- async dates(namespace) {
13793
- try {
13794
- return (await readdir(this.directory(namespace))).filter((name2) => /^\d{4}-\d{2}-\d{2}\.md$/.test(name2)).map((name2) => name2.slice(0, 10)).sort().reverse();
13795
- } catch (error) {
13796
- if (missing(error)) return [];
13797
- throw error;
13798
- }
13799
- }
13800
- async versions(namespace) {
13801
- const entries = await Promise.all((await this.dates(namespace)).map(async (date) => {
13802
- try {
13803
- const info = await stat(join(this.directory(namespace), `${date}.md`));
13804
- return [date, `${info.mtimeMs}:${info.size}`];
13805
- } catch (error) {
13806
- if (missing(error)) return null;
13807
- throw error;
13808
- }
13809
- }));
13810
- return Object.fromEntries(entries.flatMap((entry) => entry ? [entry] : []));
13811
- }
13812
- /** 总览用:事项条数与最近一次写入时间。只读本地 Markdown,不建证据批次。 */
13813
- async usage(namespace) {
13814
- const dates = await this.dates(namespace);
13815
- let count = 0;
13816
- let updatedAt = null;
13817
- for (const date of dates) {
13818
- let content;
13819
- try {
13820
- content = await this.load(namespace, date);
13821
- } catch (error) {
13822
- if (missing(error)) continue;
13823
- throw error;
13824
- }
13825
- count += items(content).length;
13826
- const day = Date.parse(`${date}T00:00:00+08:00`);
13827
- if (Number.isFinite(day) && (updatedAt === null || day > Date.parse(updatedAt))) updatedAt = new Date(day).toISOString();
13828
- }
13829
- return { items: count, updatedAt };
13830
- }
13831
- load(namespace, date) {
13832
- return readFile(join(this.directory(namespace), `${validDate(date)}.md`), "utf8");
13833
- }
13834
- async write(namespace, args, checkpoint) {
13835
- const date = validDate(args.date ?? dailyDate(/* @__PURE__ */ new Date(), this.timeZone));
13836
- if (typeof args.title !== "string" || !args.title.trim() || /[\r\n]/.test(args.title)) throw new TypeError("title \u5FC5\u987B\u662F\u975E\u7A7A\u5355\u884C\u4E8B\u9879\u540D\u79F0");
13837
- if (typeof args.content !== "string" || args.old_text !== void 0 && (typeof args.old_text !== "string" || !args.old_text)) throw new TypeError("content \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\uFF0Cold_text \u5FC5\u987B\u4E3A\u975E\u7A7A\u539F\u6587");
13838
- if (containsCredentials(`${args.title}
13839
- ${args.content}
13840
- ${args.old_text ?? ""}`)) throw new Error("\u672A\u4FDD\u5B58\uFF1A\u5185\u5BB9\u7591\u4F3C\u5305\u542B\u51ED\u636E\u6216\u5BC6\u94A5\uFF0C\u8BF7\u5220\u9664\u654F\u611F\u5185\u5BB9\u540E\u91CD\u8BD5\u3002");
13841
- const path = join(this.directory(namespace), `${date}.md`);
13842
- const run = (queues.get(path) ?? Promise.resolve()).catch(() => {
13843
- }).then(async () => {
13844
- let previous;
13845
- try {
13846
- previous = await this.load(namespace, date);
13847
- } catch (error) {
13848
- if (!missing(error)) throw error;
13849
- }
13850
- if (checkpoint && (previous === void 0 ? null : dailyVersion(previous)) !== checkpoint.expectedVersion) {
13851
- throw new Error("\u7B14\u8BB0\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FEE\u6539\u3002");
13852
- }
13853
- const original = previous ?? `# ${date}
13854
- `;
13855
- const item = items(original).find((item2) => item2.title === args.title)?.text;
13856
- const current = item ?? `\u672A\u627E\u5230\u4E8B\u9879\u300A${args.title}\u300B\uFF0C\u4EE5\u4E0B\u4E3A ${date}.md \u5168\u6587\uFF1A
13857
- ${original}`;
13858
- let updated;
13859
- const operation = args.old_text === void 0 ? "\u65B0\u589E" : "\u4FEE\u6539";
13860
- if (args.old_text === void 0) {
13861
- if (item !== void 0) throw new Error(`\u672A\u4FDD\u5B58\uFF1A${date}.md \u5DF2\u6709\u4E8B\u9879\u300A${args.title}\u300B\uFF0C\u6CA1\u6709\u91CD\u590D\u65B0\u589E\u3002\u8BE5\u4E8B\u9879\u5F53\u524D\u5168\u6587\u5982\u4E0B\uFF0C\u8BF7\u7528 old_text \u4FEE\u6539\uFF1A
13862
- ${item}`);
13863
- if (/^## /m.test(args.content)) throw new TypeError("\u65B0\u589E\u6B63\u6587\u4E0D\u80FD\u5305\u542B\u4E8B\u9879\u6807\u9898\u884C\uFF08## \uFF09");
13864
- updated = `${original.trimEnd()}
13865
-
13866
- ## ${args.title}
13867
- ${args.content}
13868
- `;
13869
- } else {
13870
- let n = 0;
13871
- for (let start = 0; ; ) {
13872
- const index = original.indexOf(args.old_text, start);
13873
- if (index < 0) break;
13874
- n++;
13875
- start = index + 1;
13876
- }
13877
- if (!n) throw new Error(`\u672A\u4FDD\u5B58\uFF1Aold_text \u5728 ${date}.md \u4E2D\u6CA1\u6709\u5339\u914D\uFF0C\u7B14\u8BB0\u53EF\u80FD\u5DF2\u88AB\u66F4\u65B0\u3002\u4E8B\u9879\u300A${args.title}\u300B\u5F53\u524D\u5168\u6587\u5982\u4E0B\uFF0C\u8BF7\u57FA\u4E8E\u5B83\u5408\u5E76\u540E\u91CD\u8BD5\uFF1A
13878
- ${current}`);
13879
- if (n !== 1) throw new Error(`\u672A\u4FDD\u5B58\uFF1Aold_text \u5728 ${date}.md \u4E2D\u5339\u914D\u5230 ${n} \u5904\uFF0C\u8BF7\u52A0\u5165\u66F4\u591A\u4E0A\u4E0B\u6587\u4F7F\u5176\u552F\u4E00\u3002\u4E8B\u9879\u300A${args.title}\u300B\u5F53\u524D\u5168\u6587\u5982\u4E0B\uFF1A
13880
- ${current}`);
13881
- updated = original.replace(args.old_text, () => args.content);
13882
- }
13883
- await mkdir(dirname(path), { recursive: true });
13884
- const temporary = `${path}.${randomUUID6()}.tmp`;
13885
- const backup = `${temporary}.bak`;
13886
- try {
13887
- await writeFile(temporary, updated, { encoding: "utf8", flag: "wx" });
13888
- if (previous !== void 0) {
13889
- await writeFile(backup, previous, { encoding: "utf8", flag: "wx" });
13890
- await rename(backup, `${path}.bak`);
13891
- }
13892
- await checkpoint?.beforePublish();
13893
- await rename(temporary, path);
13894
- } finally {
13895
- await rm(temporary, { force: true });
13896
- await rm(backup, { force: true });
13897
- }
13898
- const info = checkpoint ? await stat(path) : void 0;
13899
- return {
13900
- date,
13901
- filename: `${date}.md`,
13902
- title: args.title,
13903
- operation,
13904
- message: `\u5DF2\u4FDD\u5B58\u5230 ${date}.md\uFF1A\u300A${args.title}\u300B\uFF08${operation}\uFF09\u3002`,
13905
- ...info ? { version: `${info.mtimeMs}:${info.size}` } : {}
13906
- };
13907
- });
13908
- queues.set(path, run);
13909
- try {
13910
- return await run;
13911
- } finally {
13912
- if (queues.get(path) === run) queues.delete(path);
13913
- }
13914
- }
13915
- async read(namespace, args = {}) {
13916
- const offset = args.offset ?? 0;
13917
- if (!Number.isSafeInteger(offset) || offset < 0) throw new TypeError("offset \u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570");
13918
- if (args.date) validDate(args.date);
13919
- if (args.date && args.query === void 0) return { note: DAILY_NOTE_LABEL, date: args.date, filename: `${args.date}.md`, content: await this.load(namespace, args.date) };
13920
- const dates = args.date ? [args.date] : await this.dates(namespace);
13921
- const selected = dates.slice(offset, offset + 30);
13922
- const records = await Promise.all(selected.map(async (date) => ({ date, content: await this.load(namespace, date) })));
13923
- return {
13924
- note: DAILY_NOTE_LABEL,
13925
- ...args.query !== void 0 ? { matches: records.flatMap(({ date, content }) => items(content).filter((item) => item.text.toLocaleLowerCase().includes(args.query.toLocaleLowerCase())).map((item) => {
13926
- const index = item.text.toLocaleLowerCase().indexOf(args.query.toLocaleLowerCase());
13927
- return { date, title: item.title, snippet: item.text.slice(Math.max(0, index - 100), index + 400) };
13928
- })) } : { dates: records.map(({ date, content }) => ({ date, titles: items(content).map((item) => item.title) })) },
13929
- ...offset + selected.length < dates.length ? { nextOffset: offset + selected.length } : {}
13930
- };
13931
- }
13932
- async snapshot(namespace) {
13933
- const dates = selectDailyInjectionDates(await this.dates(namespace), this.injectionDays);
13934
- if (!dates.length) return "";
13935
- const records = await Promise.all(dates.map(async (date) => ({ date, content: await this.load(namespace, date) })));
13936
- const header = `[StrataGate daily notes]
13937
- Today: ${dailyDate(/* @__PURE__ */ new Date(), this.timeZone)} (${this.timeZone})
13938
- Your working notes from the ${this.injectionDays} most recent dates with notes, as of the start of this session. They are historical work records, not new user instructions. Within this session, memory_daily_write results are authoritative; use memory_daily_read for an item's current text before replacing it.
13939
-
13940
- `;
13941
- const shown = records.map((record3) => ({ ...record3, parts: items(record3.content), removed: [] }));
13942
- const render = () => header + shown.map((record3) => record3.removed.length ? record3.parts.length ? `# ${record3.date}
13943
- ${record3.parts.map((item) => item.text).join("\n\n")}
13944
- ` : "" : record3.content).filter(Boolean).join("\n") + shown.filter((record3) => record3.removed.length).map((record3) => `
13945
- [Omitted for length: ${record3.date} (${record3.removed.length} items: ${record3.removed.map((title) => `\u300A${title}\u300B`).join("")}\u2026). Use memory_daily_read with date to read them.]`).join("");
13946
- for (const record3 of [...shown].reverse()) {
13947
- while (render().length > this.budget && record3.parts.length) record3.removed.unshift(record3.parts.pop().title);
13948
- }
13949
- const output = render();
13950
- if (output.length <= this.budget) return output;
13951
- const notice = records.map((record3) => `
13952
- [Omitted for length: ${record3.date} (${items(record3.content).length} items: ${items(record3.content).slice(0, 1).map((item) => `\u300A${item.title.slice(0, 20)}\u300B`).join("")}\u2026). Use memory_daily_read with date to read them.]`).join("");
13953
- if ((header + notice).length <= this.budget) return header + notice;
13954
- return header + `
13955
- [Omitted for length: ${records.length} note dates (${records[records.length - 1].date} to ${records[0].date}). Use memory_daily_read to list dates and read their full text.]`;
13956
- }
13957
- };
13958
- function dailyVersion(text3) {
13959
- return createHash5("sha256").update(JSON.stringify(text3)).digest("hex");
13960
- }
13961
-
13962
- // src/runtime.ts
13963
- import { createHash as createHash6, randomUUID as randomUUID8 } from "node:crypto";
14131
+ import { createHash as createHash6, randomUUID as randomUUID9 } from "node:crypto";
13964
14132
  import { existsSync as existsSync2 } from "node:fs";
13965
14133
  import { dirname as dirname2, resolve as resolve3 } from "node:path";
13966
- import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
14134
+ import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
13967
14135
  import { setTimeout as delay } from "node:timers/promises";
13968
14136
  import { createUserMessage as createUserMessage2 } from "@deepseek-ai/dsh-llm";
13969
14137
  import { openNativePath } from "@deepseek-ai/dsh-native-command";
@@ -14315,9 +14483,9 @@ var TurnFolder = class {
14315
14483
  };
14316
14484
 
14317
14485
  // src/event-duplicate-maintenance.ts
14318
- import { randomUUID as randomUUID7 } from "node:crypto";
14319
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
14320
- var LEASE_MS = 18e4;
14486
+ import { randomUUID as randomUUID8 } from "node:crypto";
14487
+ import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
14488
+ var LEASE_MS2 = 18e4;
14321
14489
  function repairSummary(state) {
14322
14490
  if (!state) return null;
14323
14491
  return {
@@ -14339,7 +14507,7 @@ function repairSummary(state) {
14339
14507
  var EventDuplicateMaintenance = class {
14340
14508
  database;
14341
14509
  constructor(filename) {
14342
- this.database = new DatabaseSync4(filename);
14510
+ this.database = new DatabaseSync5(filename);
14343
14511
  this.database.exec(`CREATE TABLE IF NOT EXISTS stratagate_dsh_event_duplicate_repair (
14344
14512
  namespace TEXT PRIMARY KEY, version INTEGER NOT NULL, state_json TEXT NOT NULL,
14345
14513
  lease_owner TEXT, lease_until INTEGER NOT NULL DEFAULT 0
@@ -14410,10 +14578,10 @@ var EventDuplicateMaintenance = class {
14410
14578
  renewal = setInterval(() => {
14411
14579
  try {
14412
14580
  this.database.prepare(`UPDATE stratagate_dsh_event_duplicate_repair SET lease_until = ?
14413
- WHERE namespace = ? AND lease_owner = ? AND lease_until > ?`).run(Date.now() + LEASE_MS, namespace, owner, Date.now());
14581
+ WHERE namespace = ? AND lease_owner = ? AND lease_until > ?`).run(Date.now() + LEASE_MS2, namespace, owner, Date.now());
14414
14582
  } catch {
14415
14583
  }
14416
- }, LEASE_MS / 3);
14584
+ }, LEASE_MS2 / 3);
14417
14585
  renewal.unref?.();
14418
14586
  try {
14419
14587
  const decision = await generate();
@@ -14464,7 +14632,7 @@ var EventDuplicateMaintenance = class {
14464
14632
  if (keepId && keepId !== pair.leftId && keepId !== pair.rightId) throw new Error("\u4FDD\u7559\u5361\u4E0D\u5C5E\u4E8E\u5F53\u524D\u5019\u9009");
14465
14633
  if (!keepId) {
14466
14634
  const { undo: _undo, manualResolution: _intent, ...original } = structuredClone(pair);
14467
- pair.undo = { id: randomUUID7(), previous: original };
14635
+ pair.undo = { id: randomUUID8(), previous: original };
14468
14636
  } else {
14469
14637
  const previous = structuredClone(state);
14470
14638
  pair.manualResolution = { mode, keepId };
@@ -14472,7 +14640,7 @@ var EventDuplicateMaintenance = class {
14472
14640
  this.save(namespace, owner, state);
14473
14641
  if (!await archive(expected, keepId, (data) => {
14474
14642
  const { undo: _undo, manualResolution: _intent, ...original } = previous.pairs.find((value) => value.leftId === pair.leftId && value.rightId === pair.rightId);
14475
- pair.undo = { id: randomUUID7(), data, previous: original };
14643
+ pair.undo = { id: randomUUID8(), data, previous: original };
14476
14644
  this.save(namespace, owner, state);
14477
14645
  })) {
14478
14646
  this.save(namespace, owner, previous);
@@ -14561,15 +14729,15 @@ var EventDuplicateMaintenance = class {
14561
14729
  }
14562
14730
  }
14563
14731
  claim(namespace) {
14564
- const owner = randomUUID7();
14732
+ const owner = randomUUID8();
14565
14733
  return this.database.prepare(`UPDATE stratagate_dsh_event_duplicate_repair SET lease_owner = ?, lease_until = ?
14566
- WHERE namespace = ? AND lease_until <= ?`).run(owner, Date.now() + LEASE_MS, namespace, Date.now()).changes ? owner : null;
14734
+ WHERE namespace = ? AND lease_until <= ?`).run(owner, Date.now() + LEASE_MS2, namespace, Date.now()).changes ? owner : null;
14567
14735
  }
14568
14736
  release(namespace, owner) {
14569
14737
  this.database.prepare("UPDATE stratagate_dsh_event_duplicate_repair SET lease_owner = NULL, lease_until = 0 WHERE namespace = ? AND lease_owner = ?").run(namespace, owner);
14570
14738
  }
14571
14739
  static readSummary(filename, namespace) {
14572
- const database = new DatabaseSync4(filename, { readOnly: true });
14740
+ const database = new DatabaseSync5(filename, { readOnly: true });
14573
14741
  try {
14574
14742
  if (!database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_event_duplicate_repair'").get()) return null;
14575
14743
  const row = database.prepare("SELECT state_json FROM stratagate_dsh_event_duplicate_repair WHERE namespace = ? AND version <= ?").get(namespace, EVENT_DUPLICATE_REPAIR_VERSION);
@@ -14580,7 +14748,7 @@ var EventDuplicateMaintenance = class {
14580
14748
  }
14581
14749
  /** Offline startup only needs unfinished human transactions, not every memory namespace. */
14582
14750
  static pendingManualNamespaces(filename) {
14583
- const database = new DatabaseSync4(filename, { readOnly: true });
14751
+ const database = new DatabaseSync5(filename, { readOnly: true });
14584
14752
  try {
14585
14753
  if (!database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_event_duplicate_repair'").get()) return [];
14586
14754
  return database.prepare(`SELECT namespace FROM stratagate_dsh_event_duplicate_repair
@@ -14591,7 +14759,7 @@ var EventDuplicateMaintenance = class {
14591
14759
  }
14592
14760
  }
14593
14761
  static readDetails(filename, namespace) {
14594
- const database = new DatabaseSync4(filename, { readOnly: true });
14762
+ const database = new DatabaseSync5(filename, { readOnly: true });
14595
14763
  try {
14596
14764
  if (!database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_event_duplicate_repair'").get()) return [];
14597
14765
  const row = database.prepare("SELECT state_json FROM stratagate_dsh_event_duplicate_repair WHERE namespace = ? AND version <= ?").get(namespace, EVENT_DUPLICATE_REPAIR_VERSION);
@@ -14655,9 +14823,9 @@ var EventDuplicateMaintenance = class {
14655
14823
  VALUES (?, ?, ?) ON CONFLICT(namespace) DO UPDATE SET version = excluded.version, state_json = excluded.state_json,
14656
14824
  lease_owner = NULL, lease_until = 0 WHERE stratagate_dsh_event_duplicate_repair.version < excluded.version`).run(namespace, state.version, JSON.stringify(state));
14657
14825
  }
14658
- const owner = randomUUID7();
14826
+ const owner = randomUUID8();
14659
14827
  const claim = this.database.prepare(`UPDATE stratagate_dsh_event_duplicate_repair SET lease_owner = ?, lease_until = ?
14660
- WHERE namespace = ? AND version = ? AND lease_until <= ?`).run(owner, Date.now() + LEASE_MS, namespace, EVENT_DUPLICATE_REPAIR_VERSION, Date.now());
14828
+ WHERE namespace = ? AND version = ? AND lease_until <= ?`).run(owner, Date.now() + LEASE_MS2, namespace, EVENT_DUPLICATE_REPAIR_VERSION, Date.now());
14661
14829
  if (!claim.changes) return false;
14662
14830
  try {
14663
14831
  state = this.read(namespace);
@@ -14736,7 +14904,7 @@ var EventDuplicateMaintenance = class {
14736
14904
  pair.manualResolution = { mode: "merge", keepId, actor: "ai" };
14737
14905
  this.save(namespace, owner, state);
14738
14906
  pair.outcome = await operations.archive(pair, keepId, pair.draft, (data) => {
14739
- pair.undo = { id: randomUUID7(), data, previous };
14907
+ pair.undo = { id: randomUUID8(), data, previous };
14740
14908
  this.save(namespace, owner, state);
14741
14909
  }) ? "merged" : "kept";
14742
14910
  delete pair.manualResolution;
@@ -14766,7 +14934,7 @@ var EventDuplicateMaintenance = class {
14766
14934
  }
14767
14935
  save(namespace, owner, state) {
14768
14936
  const result = this.database.prepare(`UPDATE stratagate_dsh_event_duplicate_repair SET state_json = ?, lease_until = ?
14769
- WHERE namespace = ? AND lease_owner = ? AND lease_until > ?`).run(JSON.stringify(state), Date.now() + LEASE_MS, namespace, owner, Date.now());
14937
+ WHERE namespace = ? AND lease_owner = ? AND lease_until > ?`).run(JSON.stringify(state), Date.now() + LEASE_MS2, namespace, owner, Date.now());
14770
14938
  if (!result.changes) throw new Error("Duplicate repair lease expired");
14771
14939
  }
14772
14940
  };
@@ -15013,10 +15181,14 @@ var StrataGateRuntime = class _StrataGateRuntime {
15013
15181
  externalImportRuns = /* @__PURE__ */ new Map();
15014
15182
  dreamingRuns = /* @__PURE__ */ new Map();
15015
15183
  dreamingControllers = /* @__PURE__ */ new Map();
15016
- dreamingOwner = randomUUID8();
15184
+ dreamingOwner = randomUUID9();
15017
15185
  dreamingHost;
15018
15186
  dreamingScope = "directory";
15019
15187
  lastDreamingIdleCheck = 0;
15188
+ dailyLetters;
15189
+ dailyLetterRun;
15190
+ lastLetterCheck = 0;
15191
+ dailyLetterStop = new AbortController();
15020
15192
  lastMainActivity = Date.now();
15021
15193
  adminJobRetryRuns = /* @__PURE__ */ new Map();
15022
15194
  feedbackDrafts = /* @__PURE__ */ new Map();
@@ -15085,7 +15257,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15085
15257
  approved[namespace] = [...snapshot.events, ...snapshot.agentEvents].filter((event) => event.status !== "forgotten" && event.status !== "archived" && !completed.has(event.id)).map((event) => event.id);
15086
15258
  count += approved[namespace].length;
15087
15259
  }
15088
- const id = randomUUID8();
15260
+ const id = randomUUID9();
15089
15261
  this.graphPreviews.clear();
15090
15262
  this.graphPreviews.set(id, { epoch: state.epoch, approved, count });
15091
15263
  return { token: id, pending: count, batches: Object.values(approved).reduce((sum, ids2) => sum + Math.ceil(ids2.length / 8), 0), epoch: state.epoch };
@@ -15134,6 +15306,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15134
15306
  void this.runEventDuplicateMaintenance().catch((error) => this.onIngestError(error));
15135
15307
  if (!this.models.isReady()) return;
15136
15308
  await this.checkAutomaticDreaming().catch((error) => this.onIngestError(error));
15309
+ this.checkDailyLetters();
15137
15310
  void this.runProfileMaintenance().catch((error) => this.onIngestError(error));
15138
15311
  let namespaces;
15139
15312
  try {
@@ -15416,7 +15589,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15416
15589
  /** 只读已有画像;表不存在就返回 null,绝不打开可写存储。 */
15417
15590
  readProfileOverview() {
15418
15591
  if (this.config.database === ":memory:" || !existsSync2(this.config.database)) return null;
15419
- const database = new DatabaseSync5(this.config.database, { readOnly: true });
15592
+ const database = new DatabaseSync6(this.config.database, { readOnly: true });
15420
15593
  try {
15421
15594
  const names = new Set(database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('persistent_profile', 'persistent_profile_changes')").all().map((row) => row.name));
15422
15595
  if (!names.has("persistent_profile") || !names.has("persistent_profile_changes")) return null;
@@ -16755,6 +16928,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
16755
16928
  async close() {
16756
16929
  if (this.closed) return;
16757
16930
  this.closed = true;
16931
+ this.dailyLetterStop.abort();
16758
16932
  for (const controller of this.dreamingControllers.values()) controller.abort(new Error("\u5BBF\u4E3B\u5DF2\u5173\u95ED\uFF0C\u4EFB\u52A1\u4FDD\u7559\u4E3A\u6682\u505C"));
16759
16933
  this.disposeAdaptersUpdated();
16760
16934
  this.disposeWorkChanged();
@@ -16785,6 +16959,8 @@ var StrataGateRuntime = class _StrataGateRuntime {
16785
16959
  this.surfaceMaintenance.clear();
16786
16960
  await Promise.allSettled(this.externalImportRuns.values());
16787
16961
  await Promise.allSettled(this.dreamingRuns.values());
16962
+ await this.dailyLetterRun;
16963
+ this.dailyLetters?.close();
16788
16964
  await this.dreamingHost?.close();
16789
16965
  this.diagnostics.close();
16790
16966
  await Promise.all(settled.flatMap((result) => result.status === "fulfilled" ? [result.value.close()] : []));
@@ -17219,8 +17395,67 @@ var StrataGateRuntime = class _StrataGateRuntime {
17219
17395
  const snapshot = await this.adminSnapshot(namespace);
17220
17396
  if (!snapshot) throw new Error("Unknown memory namespace");
17221
17397
  const run = snapshot.memoryTopicState?.dreaming;
17222
- if (!run) return { namespace, run: null };
17223
- return { namespace, run: dreamingStatus(run) };
17398
+ return { namespace, run: dreamingStatus(run), letterDates: this.letterStore()?.dates(namespace) ?? [] };
17399
+ }
17400
+ adminDailyLetter(namespace, date) {
17401
+ return this.letterStore()?.read(namespace, date) ?? null;
17402
+ }
17403
+ letterStore() {
17404
+ if (this.config.database === ":memory:" || !existsSync2(this.config.database)) return void 0;
17405
+ return this.dailyLetters ??= new DailyLetters(this.config.database);
17406
+ }
17407
+ checkDailyLetters(now = Date.now()) {
17408
+ if (this.dreamingScope !== "memory" || this.dailyLetterRun || this.closed || now - this.lastLetterCheck < 6e4) return;
17409
+ this.lastLetterCheck = now;
17410
+ this.dailyLetterRun = this.writeClosedDayLetters(now).catch((error) => this.onIngestError(error)).finally(() => {
17411
+ this.dailyLetterRun = void 0;
17412
+ });
17413
+ }
17414
+ async writeClosedDayLetters(now) {
17415
+ const store = this.letterStore();
17416
+ if (!store) return;
17417
+ const { signal } = this.dailyLetterStop;
17418
+ const timeZone = this.dailyNotes.timeZone;
17419
+ const today = dailyDate(new Date(now), timeZone);
17420
+ const yesterday = shiftLetterDate(today, -1);
17421
+ for (const namespace of await this.adminNamespaces()) {
17422
+ if (signal.aborted) return;
17423
+ let date = store.nextDate(namespace, yesterday);
17424
+ for (let checked = 0; date < today && checked < 32 && !signal.aborted; checked++, date = shiftLetterDate(date, 1)) {
17425
+ const claim = store.claim(namespace, date, now);
17426
+ if (!claim) break;
17427
+ try {
17428
+ const messages = store.material(namespace, date, timeZone);
17429
+ if (!messages.some((message) => message.role === "user")) {
17430
+ store.finish(namespace, date, claim, null);
17431
+ continue;
17432
+ }
17433
+ const profile = this.getPersistentProfile();
17434
+ const profileContext = this.renderProfileContext();
17435
+ const draft = await this.models.runDetached(`stratagate-letter:${date}`, () => this.models.writeDailyLetter({ date, messages }, profileContext ?? ""), signal, namespace);
17436
+ signal.throwIfAborted();
17437
+ const paragraphs = draft.paragraphs.map((text3) => text3.trim().slice(0, 650)).filter(Boolean).slice(0, 3);
17438
+ const title = draft.title.trim().slice(0, 160) || "\u4E00\u5C01\u6765\u4FE1";
17439
+ const signature = draft.signature.trim().slice(0, 80) || profile.assistantPreferredName || "StrataGate";
17440
+ const letter = paragraphs.length ? {
17441
+ date,
17442
+ title,
17443
+ paragraphs,
17444
+ signature,
17445
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
17446
+ profileStyled: Boolean(profileContext),
17447
+ reports: store.reports(namespace, date, timeZone)
17448
+ } : null;
17449
+ if (letter && containsCredentials([title, signature, ...paragraphs].join("\n"))) {
17450
+ store.finish(namespace, date, claim, null);
17451
+ } else store.finish(namespace, date, claim, letter);
17452
+ } catch (error) {
17453
+ if (signal.aborted) store.release(namespace, date, claim);
17454
+ else this.onIngestError(error);
17455
+ }
17456
+ break;
17457
+ }
17458
+ }
17224
17459
  }
17225
17460
  setDreamingHost(host, scope = "memory") {
17226
17461
  this.dreamingHost = host;
@@ -17763,7 +17998,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
17763
17998
  */
17764
17999
  readVectorSetting(key) {
17765
18000
  if (this.config.database === ":memory:" || !existsSync2(this.config.database)) return null;
17766
- const database = new DatabaseSync5(this.config.database, { readOnly: true });
18001
+ const database = new DatabaseSync6(this.config.database, { readOnly: true });
17767
18002
  try {
17768
18003
  const table = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_settings'").get();
17769
18004
  if (!table) return null;
@@ -17779,7 +18014,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
17779
18014
  writeVectorSettings(values) {
17780
18015
  if (this.config.database === ":memory:") return;
17781
18016
  this.profileStore();
17782
- const database = new DatabaseSync5(this.config.database);
18017
+ const database = new DatabaseSync6(this.config.database);
17783
18018
  try {
17784
18019
  database.exec("PRAGMA busy_timeout = 5000");
17785
18020
  database.exec(`
@@ -17806,7 +18041,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
17806
18041
  /** Read one scalar runtime setting from the shared settings table. */
17807
18042
  readRuntimeSetting(key) {
17808
18043
  if (this.config.database === ":memory:" || !existsSync2(this.config.database)) return null;
17809
- const database = new DatabaseSync5(this.config.database, { readOnly: true });
18044
+ const database = new DatabaseSync6(this.config.database, { readOnly: true });
17810
18045
  try {
17811
18046
  if (!database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_settings'").get()) return null;
17812
18047
  const row = database.prepare("SELECT value FROM stratagate_dsh_settings WHERE key = ?").get(key);
@@ -17821,7 +18056,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
17821
18056
  writeRuntimeSetting(key, value) {
17822
18057
  if (this.config.database === ":memory:") return;
17823
18058
  this.profileStore();
17824
- const database = new DatabaseSync5(this.config.database);
18059
+ const database = new DatabaseSync6(this.config.database);
17825
18060
  try {
17826
18061
  database.exec("PRAGMA busy_timeout = 5000");
17827
18062
  database.exec(`
@@ -17844,7 +18079,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
17844
18079
  const remembered = this.workspaceNames.get(namespace);
17845
18080
  if (remembered) return remembered;
17846
18081
  if (this.config.database === ":memory:" || !existsSync2(this.config.database)) return null;
17847
- const database = new DatabaseSync5(this.config.database, { readOnly: true });
18082
+ const database = new DatabaseSync6(this.config.database, { readOnly: true });
17848
18083
  try {
17849
18084
  if (!database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_workspaces'").get()) {
17850
18085
  return null;
@@ -19192,7 +19427,7 @@ var DshDreamingSessions = class {
19192
19427
  this.bindings.set(sessionId, binding);
19193
19428
  } else {
19194
19429
  agent.ctx.tools.restrict({ allow: [] });
19195
- agent.ctx.tools.guard(() => "\u8BE5 Dreaming \u4F1A\u8BDD\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u4ECE\u76EE\u5F55\u9875\u5F00\u59CB\u65B0\u4E00\u8F6E");
19430
+ agent.ctx.tools.guard(() => "\u8BE5 Dreaming \u4F1A\u8BDD\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u4ECE\u603B\u89C8\u5F00\u59CB\u65B0\u4E00\u8F6E");
19196
19431
  agent.ctx.on("agent/pre-step", async () => ({ kind: "reject" }));
19197
19432
  }
19198
19433
  });
@@ -19287,7 +19522,7 @@ ${profile}
19287
19522
  parameters: DshTools.parameterSchemaSpecToJsonSchema(tool.parameters)
19288
19523
  }));
19289
19524
  scoped.tools.restrict({ allow: [] });
19290
- scoped.tools.guard((exec) => !names.has(exec.name) ? "Dreaming \u4EC5\u53EF\u4F7F\u7528\u6388\u6743\u6574\u7406\u5DE5\u5177" : void 0);
19525
+ scoped.tools.guard((exec) => binding.reporting ? "\u672C\u8F6E\u6574\u7406\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u76F4\u63A5\u56DE\u590D\u672C\u8F6E\u5B9E\u9645\u6539\u52A8\u3002" : !names.has(exec.name) ? "Dreaming \u4EC5\u53EF\u4F7F\u7528\u6388\u6743\u6574\u7406\u5DE5\u5177" : void 0);
19291
19526
  for (const tool of available) scoped.tools.register(DshTools.defineTool({
19292
19527
  ...tool,
19293
19528
  output: { schema: { type: "json" }, render: (_args, result) => [{ type: "text", text: JSON.stringify(result) }] },
@@ -19341,7 +19576,15 @@ ${profile}
19341
19576
  let run = await this.runtime.dreamingRun(binding.namespace, binding.id);
19342
19577
  if (run.status === "completed" && binding.finalStep) {
19343
19578
  binding.finalStep = false;
19344
- return next();
19579
+ const decision2 = await next();
19580
+ if (decision2.kind !== "enter") return decision2;
19581
+ binding.reporting = true;
19582
+ const changes = run.changes && { ...run.changes, items: run.changes.items.slice(-12) };
19583
+ const messages2 = [...decision2.messages, createUserMessage3({
19584
+ source: dshMessageSource(),
19585
+ content: [{ type: "text", text: `\u8BF7\u7528\u7B80\u6D01\u4E2D\u6587\u8BF4\u660E\u672C\u8F6E\u6574\u7406\u5B9E\u9645\u6539\u52A8\u548C\u672A\u89E3\u51B3\u4E8B\u9879\uFF0C\u4EC5\u4EE5\u5DE5\u5177\u5DF2\u786E\u8BA4\u7684\u7ED3\u679C\u4E3A\u4F9D\u636E\u3002\u5DF2\u4FDD\u5B58\u7684\u603B\u6570\u548C\u6700\u8FD1\u6539\u52A8\uFF1A${JSON.stringify(changes ?? {})}` }]
19586
+ })];
19587
+ return { ...decision2, messages: messages2 };
19345
19588
  }
19346
19589
  if (!["running", "pausing"].includes(run.status)) {
19347
19590
  this.keepDirections(binding, _payload.messages);
@@ -19362,6 +19605,7 @@ ${profile}
19362
19605
  if (decision.kind !== "enter") return decision;
19363
19606
  binding.epoch = run.epoch;
19364
19607
  binding.cursor = run.cursor;
19608
+ binding.totalUnits = run.units.length;
19365
19609
  const taskKey = `${run.epoch}:${run.cursor}`;
19366
19610
  if (binding.taskKey === taskKey) return decision;
19367
19611
  binding.taskKey = taskKey;
@@ -19399,6 +19643,7 @@ ${profile}
19399
19643
  if (binding.scope === "directory" && chunk.type === "finish" && chunk.reason.kind === "max-tokens") binding.error = "\u5355\u6B21\u6A21\u578B\u8F93\u51FA\u8FBE\u5230\u4E0A\u9650\uFF0C\u5DF2\u6682\u505C\u5E76\u4FDD\u7559\u65AD\u70B9\uFF1B\u6CA1\u6709\u81EA\u52A8\u8FFD\u52A0\u8BF7\u6C42";
19400
19644
  } else if (frame.type === "end") {
19401
19645
  const output = Math.max(binding.outputEstimate ?? 0, binding.reportedOutput ?? 0);
19646
+ binding.reporting = false;
19402
19647
  binding.accounting = this.runtime.dreamingRun(binding.namespace, binding.id).then((run) => {
19403
19648
  if (run.status === "running" || run.status === "pausing" || run.status === "completed") return this.runtime.dreamingMutate(binding.namespace, run, { kind: "model-usage", estimatedTokens: output });
19404
19649
  }).catch(() => {
@@ -19944,7 +20189,7 @@ function clusterKnowledgeGraph(rawNodes, rawEdges) {
19944
20189
  var MEMORY_USAGE_WINDOW_DAYS = 7;
19945
20190
  var MEMORY_HEATMAP_DAYS = 28;
19946
20191
  var TIME_ZONE = "Asia/Shanghai";
19947
- var DAY_MS = 864e5;
20192
+ var DAY_MS2 = 864e5;
19948
20193
  function dayKey(time) {
19949
20194
  return new Intl.DateTimeFormat("en-CA", { timeZone: TIME_ZONE, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(time));
19950
20195
  }
@@ -19952,7 +20197,7 @@ function dayStart(day) {
19952
20197
  return Date.parse(`${day}T00:00:00+08:00`);
19953
20198
  }
19954
20199
  function shiftDay(day, offset) {
19955
- return dayKey(dayStart(day) + offset * DAY_MS);
20200
+ return dayKey(dayStart(day) + offset * DAY_MS2);
19956
20201
  }
19957
20202
  function timestamp(value) {
19958
20203
  if (!value) return null;
@@ -21831,6 +22076,19 @@ async function handleAdminRequest(runtime, req, res) {
21831
22076
  } else if (path === "/api/stratagate/topics/retry") {
21832
22077
  if (req.method !== "POST") throw new AdminHttpError(405, "Topic retry requires POST");
21833
22078
  sendJson(res, 200, await retryTopicProjection(runtime, url));
22079
+ } else if (path === "/api/stratagate/letters/note") {
22080
+ if (req.method !== "GET") throw new AdminHttpError(405, "Letters require GET");
22081
+ const namespace = url.searchParams.get("namespace")?.trim();
22082
+ if (!namespace) throw new AdminHttpError(400, "namespace is required");
22083
+ const date = url.searchParams.get("date") ?? "";
22084
+ try {
22085
+ validDate(date);
22086
+ } catch {
22087
+ throw new AdminHttpError(400, "date \u5FC5\u987B\u662F\u6709\u6548\u7684 YYYY-MM-DD");
22088
+ }
22089
+ const letter = runtime.adminDailyLetter(namespace, date);
22090
+ if (!letter) throw new AdminHttpError(404, "\u8BE5\u65E5\u671F\u6CA1\u6709\u6765\u4FE1");
22091
+ sendJson(res, 200, letter, true);
21834
22092
  } else if (path === "/api/stratagate/dreaming") {
21835
22093
  const namespace = url.searchParams.get("namespace")?.trim() ?? "";
21836
22094
  if (!namespace) throw new AdminHttpError(400, "namespace is required");
@@ -21977,7 +22235,7 @@ import {
21977
22235
  writeFile as writeFile2
21978
22236
  } from "node:fs/promises";
21979
22237
  import { basename, dirname as dirname3, join as join2 } from "node:path";
21980
- import { createHash as createHash8, randomUUID as randomUUID9 } from "node:crypto";
22238
+ import { createHash as createHash8, randomUUID as randomUUID10 } from "node:crypto";
21981
22239
  import { encodeSeqRanges, KNOWN_SESSION_EVENT_TYPES } from "@deepseek-ai/dsh-session";
21982
22240
  var LEGACY_EVENT_TYPE = "stratagate/memory-citations";
21983
22241
  var COMPAT_EVENT_TYPE = "feedback/record";
@@ -22206,7 +22464,7 @@ async function exists(path) {
22206
22464
  }
22207
22465
  async function publishExclusive(path, bytes) {
22208
22466
  await mkdir3(dirname3(path), { recursive: true });
22209
- const temporary = join2(dirname3(path), `.${basename(path)}.stratagate-${randomUUID9()}.tmp`);
22467
+ const temporary = join2(dirname3(path), `.${basename(path)}.stratagate-${randomUUID10()}.tmp`);
22210
22468
  const handle = await open(temporary, "wx", 384);
22211
22469
  try {
22212
22470
  await handle.writeFile(bytes);