@agentmemory/agentmemory 0.8.1 → 0.8.5

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.
@@ -1,11 +1,13 @@
1
+ import { a as jaccardSimilarity, i as generateId, n as STREAM, r as fingerprintId, t as KV } from "./cli.mjs";
2
+ import { a as getEnvVar, c as isGraphExtractionEnabled, d as loadEmbeddingConfig, f as loadFallbackConfig, i as getConsolidationDecayDays, l as loadClaudeBridgeConfig, m as loadTeamConfig, n as VERSION, p as loadSnapshotConfig, r as detectEmbeddingProvider, s as isConsolidationEnabled, t as getVisibleTools, u as loadConfig } from "./tools-registry-B9EXJvIf.mjs";
1
3
  import { execFile } from "node:child_process";
2
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { dirname, join, resolve } from "node:path";
5
+ import { dirname, join, resolve, sep } from "node:path";
4
6
  import { fileURLToPath } from "node:url";
5
- import { getContext, init } from "iii-sdk";
6
7
  import { homedir } from "node:os";
7
- import Anthropic from "@anthropic-ai/sdk";
8
8
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
9
+ import { getContext, init } from "iii-sdk";
10
+ import Anthropic from "@anthropic-ai/sdk";
9
11
  import { z } from "zod";
10
12
  import { promisify } from "node:util";
11
13
  import { lookup } from "node:dns/promises";
@@ -13,163 +15,6 @@ import { isIP } from "node:net";
13
15
  import { mkdir, writeFile } from "node:fs/promises";
14
16
  import { createServer } from "node:http";
15
17
 
16
- //#region src/config.ts
17
- function safeParseInt(value, fallback) {
18
- if (!value) return fallback;
19
- const parsed = parseInt(value, 10);
20
- return Number.isNaN(parsed) ? fallback : parsed;
21
- }
22
- const DATA_DIR = join(homedir(), ".agentmemory");
23
- const ENV_FILE = join(DATA_DIR, ".env");
24
- function loadEnvFile() {
25
- if (!existsSync(ENV_FILE)) return {};
26
- const content = readFileSync(ENV_FILE, "utf-8");
27
- const vars = {};
28
- for (const line of content.split("\n")) {
29
- const trimmed = line.trim();
30
- if (!trimmed || trimmed.startsWith("#")) continue;
31
- const eqIdx = trimmed.indexOf("=");
32
- if (eqIdx === -1) continue;
33
- const key = trimmed.slice(0, eqIdx).trim();
34
- let val = trimmed.slice(eqIdx + 1).trim();
35
- if (val.startsWith("\"") && val.endsWith("\"") || val.startsWith("'") && val.endsWith("'")) val = val.slice(1, -1);
36
- vars[key] = val;
37
- }
38
- return vars;
39
- }
40
- function detectProvider(env) {
41
- const maxTokens = parseInt(env["MAX_TOKENS"] || "4096", 10);
42
- if (env["MINIMAX_API_KEY"]) return {
43
- provider: "minimax",
44
- model: env["MINIMAX_MODEL"] || "MiniMax-M2.7",
45
- maxTokens
46
- };
47
- if (env["ANTHROPIC_API_KEY"]) return {
48
- provider: "anthropic",
49
- model: env["ANTHROPIC_MODEL"] || "claude-sonnet-4-20250514",
50
- maxTokens,
51
- baseURL: env["ANTHROPIC_BASE_URL"]
52
- };
53
- if (env["GEMINI_API_KEY"]) return {
54
- provider: "gemini",
55
- model: env["GEMINI_MODEL"] || "gemini-2.0-flash",
56
- maxTokens
57
- };
58
- if (env["OPENROUTER_API_KEY"]) return {
59
- provider: "openrouter",
60
- model: env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-4-20250514",
61
- maxTokens
62
- };
63
- return {
64
- provider: "agent-sdk",
65
- model: "claude-sonnet-4-20250514",
66
- maxTokens: 4096
67
- };
68
- }
69
- function loadConfig() {
70
- const env = getMergedEnv();
71
- const provider = detectProvider(env);
72
- return {
73
- engineUrl: env["III_ENGINE_URL"] || "ws://localhost:49134",
74
- restPort: parseInt(env["III_REST_PORT"] || "3111", 10) || 3111,
75
- streamsPort: parseInt(env["III_STREAMS_PORT"] || "3112", 10) || 3112,
76
- provider,
77
- tokenBudget: safeParseInt(env["TOKEN_BUDGET"], 2e3),
78
- maxObservationsPerSession: safeParseInt(env["MAX_OBS_PER_SESSION"], 500),
79
- compressionModel: provider.model,
80
- dataDir: DATA_DIR
81
- };
82
- }
83
- function getMergedEnv(overrides) {
84
- return {
85
- ...loadEnvFile(),
86
- ...process.env,
87
- ...overrides
88
- };
89
- }
90
- function getEnvVar(key) {
91
- return getMergedEnv()[key];
92
- }
93
- function loadEmbeddingConfig() {
94
- const env = getMergedEnv();
95
- let bm25Weight = parseFloat(env["BM25_WEIGHT"] || "0.4");
96
- let vectorWeight = parseFloat(env["VECTOR_WEIGHT"] || "0.6");
97
- bm25Weight = isNaN(bm25Weight) || bm25Weight < 0 ? .4 : Math.min(bm25Weight, 1);
98
- vectorWeight = isNaN(vectorWeight) || vectorWeight < 0 ? .6 : Math.min(vectorWeight, 1);
99
- return {
100
- provider: env["EMBEDDING_PROVIDER"] || void 0,
101
- bm25Weight,
102
- vectorWeight
103
- };
104
- }
105
- function detectEmbeddingProvider(env) {
106
- const source = env ?? getMergedEnv();
107
- const forced = source["EMBEDDING_PROVIDER"];
108
- if (forced) return forced;
109
- if (source["GEMINI_API_KEY"]) return "gemini";
110
- if (source["OPENAI_API_KEY"]) return "openai";
111
- if (source["VOYAGE_API_KEY"]) return "voyage";
112
- if (source["COHERE_API_KEY"]) return "cohere";
113
- if (source["OPENROUTER_API_KEY"]) return "openrouter";
114
- return null;
115
- }
116
- function loadClaudeBridgeConfig() {
117
- const env = getMergedEnv();
118
- const enabled = env["CLAUDE_MEMORY_BRIDGE"] === "true";
119
- const projectPath = env["CLAUDE_PROJECT_PATH"] || "";
120
- const lineBudget = safeParseInt(env["CLAUDE_MEMORY_LINE_BUDGET"], 200);
121
- let memoryFilePath = "";
122
- if (enabled && projectPath) {
123
- const safePath = projectPath.replace(/[/\\]/g, "-").replace(/^-/, "");
124
- memoryFilePath = join(homedir(), ".claude", "projects", safePath, "memory", "MEMORY.md");
125
- }
126
- return {
127
- enabled,
128
- projectPath,
129
- memoryFilePath,
130
- lineBudget
131
- };
132
- }
133
- function loadTeamConfig() {
134
- const env = getMergedEnv();
135
- const teamId = env["TEAM_ID"];
136
- const userId = env["USER_ID"];
137
- if (!teamId || !userId) return null;
138
- return {
139
- teamId,
140
- userId,
141
- mode: env["TEAM_MODE"] === "shared" ? "shared" : "private"
142
- };
143
- }
144
- function loadSnapshotConfig() {
145
- const env = getMergedEnv();
146
- return {
147
- enabled: env["SNAPSHOT_ENABLED"] === "true",
148
- interval: safeParseInt(env["SNAPSHOT_INTERVAL"], 3600),
149
- dir: env["SNAPSHOT_DIR"] || join(homedir(), ".agentmemory", "snapshots")
150
- };
151
- }
152
- function isGraphExtractionEnabled() {
153
- return getMergedEnv()["GRAPH_EXTRACTION_ENABLED"] === "true";
154
- }
155
- function isConsolidationEnabled() {
156
- return getMergedEnv()["CONSOLIDATION_ENABLED"] === "true";
157
- }
158
- function getConsolidationDecayDays() {
159
- return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30);
160
- }
161
- const VALID_PROVIDERS = new Set([
162
- "anthropic",
163
- "gemini",
164
- "openrouter",
165
- "agent-sdk",
166
- "minimax"
167
- ]);
168
- function loadFallbackConfig() {
169
- return { providers: (getMergedEnv()["FALLBACK_PROVIDERS"] || "").split(",").map((p) => p.trim()).filter((p) => Boolean(p) && VALID_PROVIDERS.has(p)) };
170
- }
171
-
172
- //#endregion
173
18
  //#region src/providers/agent-sdk.ts
174
19
  var AgentSDKProvider = class {
175
20
  name = "agent-sdk";
@@ -861,69 +706,6 @@ var VectorIndex = class VectorIndex {
861
706
  }
862
707
  };
863
708
 
864
- //#endregion
865
- //#region src/state/schema.ts
866
- const KV = {
867
- sessions: "mem:sessions",
868
- observations: (sessionId) => `mem:obs:${sessionId}`,
869
- memories: "mem:memories",
870
- summaries: "mem:summaries",
871
- config: "mem:config",
872
- metrics: "mem:metrics",
873
- health: "mem:health",
874
- embeddings: (obsId) => `mem:emb:${obsId}`,
875
- bm25Index: "mem:index:bm25",
876
- relations: "mem:relations",
877
- profiles: "mem:profiles",
878
- claudeBridge: "mem:claude-bridge",
879
- graphNodes: "mem:graph:nodes",
880
- graphEdges: "mem:graph:edges",
881
- semantic: "mem:semantic",
882
- procedural: "mem:procedural",
883
- teamShared: (teamId) => `mem:team:${teamId}:shared`,
884
- teamUsers: (teamId, userId) => `mem:team:${teamId}:users:${userId}`,
885
- teamProfile: (teamId) => `mem:team:${teamId}:profile`,
886
- audit: "mem:audit",
887
- actions: "mem:actions",
888
- actionEdges: "mem:action-edges",
889
- leases: "mem:leases",
890
- routines: "mem:routines",
891
- routineRuns: "mem:routine-runs",
892
- signals: "mem:signals",
893
- checkpoints: "mem:checkpoints",
894
- mesh: "mem:mesh",
895
- sketches: "mem:sketches",
896
- facets: "mem:facets",
897
- sentinels: "mem:sentinels",
898
- crystals: "mem:crystals",
899
- lessons: "mem:lessons",
900
- insights: "mem:insights",
901
- graphEdgeHistory: "mem:graph:edge-history",
902
- enrichedChunks: (sessionId) => `mem:enriched:${sessionId}`,
903
- latentEmbeddings: (obsId) => `mem:latent:${obsId}`,
904
- retentionScores: "mem:retention"
905
- };
906
- const STREAM = {
907
- name: "mem-live",
908
- group: (sessionId) => sessionId,
909
- viewerGroup: "viewer"
910
- };
911
- function generateId(prefix) {
912
- return `${prefix}_${Date.now().toString(36)}_${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
913
- }
914
- function fingerprintId(prefix, content) {
915
- return `${prefix}_${createHash("sha256").update(content).digest("hex").slice(0, 16)}`;
916
- }
917
- function jaccardSimilarity(a, b) {
918
- const setA = new Set(a.split(/\s+/).filter((t) => t.length > 2));
919
- const setB = new Set(b.split(/\s+/).filter((t) => t.length > 2));
920
- if (setA.size === 0 && setB.size === 0) return 1;
921
- if (setA.size === 0 || setB.size === 0) return 0;
922
- let intersection = 0;
923
- for (const word of setA) if (setB.has(word)) intersection++;
924
- return intersection / (setA.size + setB.size - intersection);
925
- }
926
-
927
709
  //#endregion
928
710
  //#region src/functions/graph-retrieval.ts
929
711
  function buildGraphContext(path) {
@@ -1950,9 +1732,11 @@ var IndexPersistence = class {
1950
1732
  const PRIVATE_TAG_RE = /<private>[\s\S]*?<\/private>/gi;
1951
1733
  const SECRET_PATTERN_SOURCES = [
1952
1734
  /(?:api[_-]?key|secret|token|password|credential|auth)[\s]*[=:]\s*["']?[A-Za-z0-9_\-/.+]{20,}["']?/gi,
1953
- /(?:sk|pk|rk|ak)-[A-Za-z0-9]{20,}/g,
1735
+ /Bearer\s+[A-Za-z0-9._\-+/=]{20,}/gi,
1736
+ /sk-proj-[A-Za-z0-9\-_]{20,}/g,
1737
+ /(?:sk|pk|rk|ak)-[A-Za-z0-9][A-Za-z0-9\-_]{19,}/g,
1954
1738
  /sk-ant-[A-Za-z0-9\-_]{20,}/g,
1955
- /ghp_[A-Za-z0-9]{36}/g,
1739
+ /gh[pus]_[A-Za-z0-9]{36,}/g,
1956
1740
  /github_pat_[A-Za-z0-9_]{22,}/g,
1957
1741
  /xoxb-[A-Za-z0-9\-]+/g,
1958
1742
  /AKIA[0-9A-Z]{16}/g,
@@ -2153,6 +1937,77 @@ function getXmlChildren(xml, parentTag, childTag) {
2153
1937
  return items;
2154
1938
  }
2155
1939
 
1940
+ //#endregion
1941
+ //#region src/functions/access-tracker.ts
1942
+ const RECENT_CAP = 20;
1943
+ function emptyAccessLog(memoryId) {
1944
+ return {
1945
+ memoryId,
1946
+ count: 0,
1947
+ lastAt: "",
1948
+ recent: []
1949
+ };
1950
+ }
1951
+ function normalizeAccessLog(raw) {
1952
+ const r = raw ?? {};
1953
+ const rawCount = typeof r.count === "number" && Number.isFinite(r.count) ? r.count : 0;
1954
+ const count = Math.max(0, Math.floor(rawCount));
1955
+ const rawRecent = Array.isArray(r.recent) ? r.recent.filter((x) => typeof x === "number" && Number.isFinite(x)) : [];
1956
+ const recent = rawRecent.length > RECENT_CAP ? rawRecent.slice(-RECENT_CAP) : rawRecent;
1957
+ return {
1958
+ memoryId: typeof r.memoryId === "string" ? r.memoryId : "",
1959
+ count: Math.max(count, recent.length),
1960
+ lastAt: typeof r.lastAt === "string" ? r.lastAt : "",
1961
+ recent
1962
+ };
1963
+ }
1964
+ async function getAccessLog(kv, memoryId) {
1965
+ try {
1966
+ const raw = await kv.get(KV.accessLog, memoryId);
1967
+ if (!raw) return emptyAccessLog(memoryId);
1968
+ const normalized = normalizeAccessLog(raw);
1969
+ if (!normalized.memoryId) normalized.memoryId = memoryId;
1970
+ return normalized;
1971
+ } catch {
1972
+ return emptyAccessLog(memoryId);
1973
+ }
1974
+ }
1975
+ async function recordAccess(kv, memoryId, timestampMs) {
1976
+ if (!memoryId) return;
1977
+ const ts = timestampMs ?? Date.now();
1978
+ try {
1979
+ await withKeyedLock(`mem:access:${memoryId}`, async () => {
1980
+ const existing = await getAccessLog(kv, memoryId);
1981
+ existing.count += 1;
1982
+ existing.lastAt = new Date(ts).toISOString();
1983
+ existing.recent.push(ts);
1984
+ if (existing.recent.length > RECENT_CAP) existing.recent = existing.recent.slice(-RECENT_CAP);
1985
+ await kv.set(KV.accessLog, memoryId, existing);
1986
+ });
1987
+ } catch (err) {
1988
+ try {
1989
+ getContext().logger.warn("recordAccess failed", {
1990
+ memoryId,
1991
+ error: err instanceof Error ? err.message : String(err)
1992
+ });
1993
+ } catch {}
1994
+ }
1995
+ }
1996
+ async function recordAccessBatch(kv, memoryIds, timestampMs) {
1997
+ if (!memoryIds || memoryIds.length === 0) return;
1998
+ const ts = timestampMs ?? Date.now();
1999
+ const unique = Array.from(new Set(memoryIds.filter(Boolean)));
2000
+ await Promise.allSettled(unique.map((id) => recordAccess(kv, id, ts)));
2001
+ }
2002
+ async function deleteAccessLog(kv, memoryId) {
2003
+ if (!memoryId) return;
2004
+ try {
2005
+ await withKeyedLock(`mem:access:${memoryId}`, async () => {
2006
+ await kv.delete(KV.accessLog, memoryId);
2007
+ });
2008
+ } catch {}
2009
+ }
2010
+
2156
2011
  //#endregion
2157
2012
  //#region src/functions/search.ts
2158
2013
  let index = null;
@@ -2239,6 +2094,7 @@ function registerSearchFunction(sdk, kv) {
2239
2094
  sessionId: candidates[i].sessionId
2240
2095
  });
2241
2096
  }
2097
+ recordAccessBatch(kv, enriched.map((r) => r.observation.id));
2242
2098
  ctx.logger.info("Search completed", {
2243
2099
  query,
2244
2100
  results: enriched.length,
@@ -2634,19 +2490,22 @@ function registerContextFunction(sdk, kv, tokenBudget) {
2634
2490
  const i = sessionsNeedingObs[j];
2635
2491
  const important = obsResults[j].filter((o) => o.title && o.importance >= 5);
2636
2492
  if (important.length > 0) {
2637
- const items = important.sort((a, b) => b.importance - a.importance).slice(0, 5).map((o) => `- [${o.type}] ${o.title}: ${o.narrative}`).join("\n");
2493
+ const top = important.sort((a, b) => b.importance - a.importance).slice(0, 5);
2494
+ const items = top.map((o) => `- [${o.type}] ${o.title}: ${o.narrative}`).join("\n");
2638
2495
  const content = `## Session ${sessions[i].id.slice(0, 8)} (${sessions[i].startedAt})\n${items}`;
2639
2496
  blocks.push({
2640
2497
  type: "observation",
2641
2498
  content,
2642
2499
  tokens: estimateTokens$1(content),
2643
- recency: new Date(sessions[i].startedAt).getTime()
2500
+ recency: new Date(sessions[i].startedAt).getTime(),
2501
+ sourceIds: top.map((o) => o.id)
2644
2502
  });
2645
2503
  }
2646
2504
  }
2647
2505
  blocks.sort((a, b) => b.recency - a.recency);
2648
2506
  let usedTokens = 0;
2649
2507
  const selected = [];
2508
+ const accessedIds = [];
2650
2509
  const header = `<agentmemory-context project="${escapeXmlAttr(data.project)}">`;
2651
2510
  const footer = `</agentmemory-context>`;
2652
2511
  usedTokens += estimateTokens$1(header) + estimateTokens$1(footer);
@@ -2654,7 +2513,9 @@ function registerContextFunction(sdk, kv, tokenBudget) {
2654
2513
  if (usedTokens + block.tokens > budget) break;
2655
2514
  selected.push(block.content);
2656
2515
  usedTokens += block.tokens;
2516
+ if (block.sourceIds && block.sourceIds.length > 0) accessedIds.push(...block.sourceIds);
2657
2517
  }
2518
+ if (accessedIds.length > 0) recordAccessBatch(kv, accessedIds);
2658
2519
  if (selected.length === 0) {
2659
2520
  ctx.logger.info("No context available", { project: data.project });
2660
2521
  return {
@@ -2987,6 +2848,9 @@ function registerFileIndexFunction(sdk, kv) {
2987
2848
  for (const obs of fh.observations) lines.push(`- [${obs.type}] ${obs.title}: ${obs.narrative}`);
2988
2849
  }
2989
2850
  lines.push("</agentmemory-file-context>");
2851
+ const accessedIds = [];
2852
+ for (const fh of results) for (const obs of fh.observations) accessedIds.push(obs.obsId);
2853
+ recordAccessBatch(kv, accessedIds);
2990
2854
  const context = lines.join("\n");
2991
2855
  ctx.logger.info("File context generated", {
2992
2856
  files: data.files.length,
@@ -3299,6 +3163,7 @@ function registerRememberFunction(sdk, kv) {
3299
3163
  let deleted = 0;
3300
3164
  if (data.memoryId) {
3301
3165
  await kv.delete(KV.memories, data.memoryId);
3166
+ await deleteAccessLog(kv, data.memoryId);
3302
3167
  deleted++;
3303
3168
  }
3304
3169
  if (data.sessionId && data.observationIds && data.observationIds.length > 0) for (const obsId of data.observationIds) {
@@ -3390,13 +3255,19 @@ function registerEvictFunction(sdk, kv) {
3390
3255
  if (now > new Date(mem.forgetAfter).getTime()) {
3391
3256
  stats.expiredMemories++;
3392
3257
  evictedMemIds.add(mem.id);
3393
- if (!dryRun) await kv.delete(KV.memories, mem.id).catch(() => {});
3258
+ if (!dryRun) {
3259
+ await kv.delete(KV.memories, mem.id).catch(() => {});
3260
+ await deleteAccessLog(kv, mem.id);
3261
+ }
3394
3262
  }
3395
3263
  }
3396
3264
  if (!evictedMemIds.has(mem.id) && mem.isLatest === false && mem.createdAt) {
3397
3265
  if (now - new Date(mem.createdAt).getTime() > cfg.lowImportanceMaxDays * MS_PER_DAY$1) {
3398
3266
  stats.nonLatestMemories++;
3399
- if (!dryRun) await kv.delete(KV.memories, mem.id).catch(() => {});
3267
+ if (!dryRun) {
3268
+ await kv.delete(KV.memories, mem.id).catch(() => {});
3269
+ await deleteAccessLog(kv, mem.id);
3270
+ }
3400
3271
  }
3401
3272
  }
3402
3273
  }
@@ -3561,6 +3432,7 @@ function registerRelationsFunction(sdk, kv) {
3561
3432
  });
3562
3433
  }
3563
3434
  result.sort((a, b) => b.confidence - a.confidence);
3435
+ recordAccessBatch(kv, result.map((r) => r.memory.id));
3564
3436
  ctx.logger.info("Related memories retrieved", {
3565
3437
  memoryId: data.memoryId,
3566
3438
  found: result.length
@@ -3632,6 +3504,7 @@ function registerTimelineFunction(sdk, kv) {
3632
3504
  relativePosition: i - anchorIdx
3633
3505
  });
3634
3506
  }
3507
+ recordAccessBatch(kv, entries.map((e) => e.observation.id));
3635
3508
  ctx.logger.info("Timeline retrieved", {
3636
3509
  anchor: data.anchor,
3637
3510
  entries: entries.length
@@ -3682,6 +3555,7 @@ function registerSmartSearchFunction(sdk, kv, searchFn) {
3682
3555
  observation: obs
3683
3556
  } : null)));
3684
3557
  for (const r of results) if (r) expanded.push(r);
3558
+ recordAccessBatch(kv, expanded.map((e) => e.observation.id));
3685
3559
  const truncated = data.expandIds.length > raw.length;
3686
3560
  ctx.logger.info("Smart search expanded", {
3687
3561
  requested: data.expandIds.length,
@@ -3709,6 +3583,7 @@ function registerSmartSearchFunction(sdk, kv, searchFn) {
3709
3583
  score: r.combinedScore,
3710
3584
  timestamp: r.observation.timestamp
3711
3585
  }));
3586
+ recordAccessBatch(kv, compact.map((r) => r.obsId));
3712
3587
  ctx.logger.info("Smart search compact", {
3713
3588
  query: data.query,
3714
3589
  results: compact.length
@@ -3840,7 +3715,10 @@ function registerAutoForgetFunction(sdk, kv) {
3840
3715
  if (now > new Date(mem.forgetAfter).getTime()) {
3841
3716
  result.ttlExpired.push(mem.id);
3842
3717
  deletedIds.add(mem.id);
3843
- if (!dryRun) await kv.delete(KV.memories, mem.id);
3718
+ if (!dryRun) {
3719
+ await kv.delete(KV.memories, mem.id);
3720
+ await deleteAccessLog(kv, mem.id);
3721
+ }
3844
3722
  }
3845
3723
  }
3846
3724
  const latestMemories = memories.filter((m) => m.isLatest !== false && !deletedIds.has(m.id)).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()).slice(0, 1e3);
@@ -3907,10 +3785,6 @@ function registerAutoForgetFunction(sdk, kv) {
3907
3785
  });
3908
3786
  }
3909
3787
 
3910
- //#endregion
3911
- //#region src/version.ts
3912
- const VERSION = "0.8.1";
3913
-
3914
3788
  //#endregion
3915
3789
  //#region src/functions/export-import.ts
3916
3790
  function registerExportImportFunction(sdk, kv) {
@@ -3937,7 +3811,7 @@ function registerExportImportFunction(sdk, kv) {
3937
3811
  const uniqueProjects = [...new Set(paginatedSessions.map((s) => s.project))];
3938
3812
  const profileResults = await Promise.all(uniqueProjects.map((project) => kv.get(KV.profiles, project).catch(() => null)));
3939
3813
  for (const profile of profileResults) if (profile) profiles.push(profile);
3940
- const [graphNodes, graphEdges, semanticMemories, proceduralMemories, actions, actionEdges, sentinels, sketches, crystals, facets, lessons, insights, routines, signals, checkpoints] = await Promise.all([
3814
+ const [graphNodes, graphEdges, semanticMemories, proceduralMemories, actions, actionEdges, sentinels, sketches, crystals, facets, lessons, insights, routines, signals, checkpoints, accessLogs] = await Promise.all([
3941
3815
  kv.list(KV.graphNodes).catch(() => []),
3942
3816
  kv.list(KV.graphEdges).catch(() => []),
3943
3817
  kv.list(KV.semantic).catch(() => []),
@@ -3952,7 +3826,8 @@ function registerExportImportFunction(sdk, kv) {
3952
3826
  kv.list(KV.insights).catch(() => []),
3953
3827
  kv.list(KV.routines).catch(() => []),
3954
3828
  kv.list(KV.signals).catch(() => []),
3955
- kv.list(KV.checkpoints).catch(() => [])
3829
+ kv.list(KV.checkpoints).catch(() => []),
3830
+ kv.list(KV.accessLog).catch(() => [])
3956
3831
  ]);
3957
3832
  const exportData = {
3958
3833
  version: VERSION,
@@ -3976,7 +3851,8 @@ function registerExportImportFunction(sdk, kv) {
3976
3851
  insights: insights.length > 0 ? insights : void 0,
3977
3852
  routines: routines.length > 0 ? routines : void 0,
3978
3853
  signals: signals.length > 0 ? signals : void 0,
3979
- checkpoints: checkpoints.length > 0 ? checkpoints : void 0
3854
+ checkpoints: checkpoints.length > 0 ? checkpoints : void 0,
3855
+ accessLogs: accessLogs.length > 0 ? accessLogs : void 0
3980
3856
  };
3981
3857
  if (maxSessions !== void 0) exportData.pagination = {
3982
3858
  offset,
@@ -4016,7 +3892,11 @@ function registerExportImportFunction(sdk, kv) {
4016
3892
  "0.7.7",
4017
3893
  "0.7.9",
4018
3894
  "0.8.0",
4019
- "0.8.1"
3895
+ "0.8.1",
3896
+ "0.8.2",
3897
+ "0.8.3",
3898
+ "0.8.4",
3899
+ "0.8.5"
4020
3900
  ]).has(importData.version)) return {
4021
3901
  success: false,
4022
3902
  error: `Unsupported export version: ${importData.version}`
@@ -4026,6 +3906,7 @@ function registerExportImportFunction(sdk, kv) {
4026
3906
  const MAX_SUMMARIES = 1e4;
4027
3907
  const MAX_OBS_PER_SESSION = 5e3;
4028
3908
  const MAX_TOTAL_OBSERVATIONS = 5e5;
3909
+ const MAX_ACCESS_LOGS = 5e4;
4029
3910
  if (!Array.isArray(importData.sessions)) return {
4030
3911
  success: false,
4031
3912
  error: "sessions must be an array"
@@ -4108,6 +3989,7 @@ function registerExportImportFunction(sdk, kv) {
4108
3989
  for (const e of await kv.list(KV.graphEdges).catch(() => [])) await kv.delete(KV.graphEdges, e.id);
4109
3990
  for (const s of await kv.list(KV.semantic).catch(() => [])) await kv.delete(KV.semantic, s.id);
4110
3991
  for (const p of await kv.list(KV.procedural).catch(() => [])) await kv.delete(KV.procedural, p.id);
3992
+ for (const a of await kv.list(KV.accessLog).catch(() => [])) await kv.delete(KV.accessLog, a.memoryId);
4111
3993
  }
4112
3994
  for (const session of importData.sessions) {
4113
3995
  if (strategy === "skip") {
@@ -4284,6 +4166,28 @@ function registerExportImportFunction(sdk, kv) {
4284
4166
  }
4285
4167
  await kv.set(KV.insights, insight.id, insight);
4286
4168
  }
4169
+ if (importData.accessLogs) {
4170
+ if (!Array.isArray(importData.accessLogs)) return {
4171
+ success: false,
4172
+ error: "accessLogs must be an array"
4173
+ };
4174
+ if (importData.accessLogs.length > MAX_ACCESS_LOGS) return {
4175
+ success: false,
4176
+ error: `Too many access logs (max ${MAX_ACCESS_LOGS})`
4177
+ };
4178
+ const memoryIds = new Set(importData.memories.map((m) => m.id));
4179
+ for (const raw of importData.accessLogs) {
4180
+ const log = normalizeAccessLog(raw);
4181
+ if (!log.memoryId || !memoryIds.has(log.memoryId)) continue;
4182
+ if (strategy === "skip") {
4183
+ if (await kv.get(KV.accessLog, log.memoryId).catch(() => null)) {
4184
+ stats.skipped++;
4185
+ continue;
4186
+ }
4187
+ }
4188
+ await kv.set(KV.accessLog, log.memoryId, log);
4189
+ }
4190
+ }
4287
4191
  ctx.logger.info("Import complete", {
4288
4192
  strategy,
4289
4193
  ...stats
@@ -5052,6 +4956,7 @@ function registerGovernanceFunction(sdk, kv) {
5052
4956
  let deleted = 0;
5053
4957
  for (const id of data.memoryIds) if (await kv.get(KV.memories, id)) {
5054
4958
  await kv.delete(KV.memories, id);
4959
+ await deleteAccessLog(kv, id);
5055
4960
  deleted++;
5056
4961
  }
5057
4962
  await recordAudit(kv, "delete", "mem::governance-delete", data.memoryIds, {
@@ -5099,7 +5004,10 @@ function registerGovernanceFunction(sdk, kv) {
5099
5004
  wouldDelete: candidates.length,
5100
5005
  ids: candidates.map((m) => m.id)
5101
5006
  };
5102
- for (const mem of candidates) await kv.delete(KV.memories, mem.id);
5007
+ for (const mem of candidates) {
5008
+ await kv.delete(KV.memories, mem.id);
5009
+ await deleteAccessLog(kv, mem.id);
5010
+ }
5103
5011
  await recordAudit(kv, "delete", "mem::governance-bulk", candidates.map((m) => m.id), {
5104
5012
  filter: data,
5105
5013
  deleted: candidates.length
@@ -5147,6 +5055,7 @@ function registerSnapshotFunction(sdk, kv, snapshotDir) {
5147
5055
  const sessions = await kv.list(KV.sessions);
5148
5056
  const memories = await kv.list(KV.memories);
5149
5057
  const graphNodes = await kv.list(KV.graphNodes);
5058
+ const accessLogs = await kv.list(KV.accessLog).catch(() => []);
5150
5059
  const observations = {};
5151
5060
  for (const session of sessions) {
5152
5061
  const obs = await kv.list(KV.observations(session.id)).catch(() => []);
@@ -5158,7 +5067,8 @@ function registerSnapshotFunction(sdk, kv, snapshotDir) {
5158
5067
  sessions,
5159
5068
  memories,
5160
5069
  graphNodes,
5161
- observations
5070
+ observations,
5071
+ accessLogs
5162
5072
  };
5163
5073
  writeFileSync(join(snapshotDir, "state.json"), JSON.stringify(state, null, 2), "utf-8");
5164
5074
  await gitExec(snapshotDir, ["add", "."]);
@@ -5250,6 +5160,7 @@ function registerSnapshotFunction(sdk, kv, snapshotDir) {
5250
5160
  if (state.memories) for (const memory of state.memories) await kv.set(KV.memories, memory.id, memory);
5251
5161
  if (state.graphNodes) for (const node of state.graphNodes) await kv.set(KV.graphNodes, node.id, node);
5252
5162
  if (state.observations) for (const [sessionId, obs] of Object.entries(state.observations)) for (const o of obs) await kv.set(KV.observations(sessionId), o.id, o);
5163
+ if (state.accessLogs) for (const log of state.accessLogs) await kv.set(KV.accessLog, log.memoryId, log);
5253
5164
  await gitExec(snapshotDir, [
5254
5165
  "checkout",
5255
5166
  "HEAD",
@@ -6417,7 +6328,7 @@ async function lwwMergeGraphNodes(kv, items) {
6417
6328
  }
6418
6329
  return count;
6419
6330
  }
6420
- function registerMeshFunction(sdk, kv) {
6331
+ function registerMeshFunction(sdk, kv, meshAuthToken) {
6421
6332
  sdk.registerFunction({ id: "mem::mesh-register" }, async (data) => {
6422
6333
  if (!data.url || !data.name) return {
6423
6334
  success: false,
@@ -6454,6 +6365,10 @@ function registerMeshFunction(sdk, kv) {
6454
6365
  };
6455
6366
  });
6456
6367
  sdk.registerFunction({ id: "mem::mesh-sync" }, async (data) => {
6368
+ if (!meshAuthToken) return {
6369
+ success: false,
6370
+ error: "mesh sync requires AGENTMEMORY_SECRET"
6371
+ };
6457
6372
  const direction = data.direction || "both";
6458
6373
  let peers;
6459
6374
  if (data.peerId) {
@@ -6489,7 +6404,10 @@ function registerMeshFunction(sdk, kv) {
6489
6404
  try {
6490
6405
  const response = await fetch(`${peer.url}/agentmemory/mesh/receive`, {
6491
6406
  method: "POST",
6492
- headers: { "Content-Type": "application/json" },
6407
+ headers: {
6408
+ "Content-Type": "application/json",
6409
+ Authorization: `Bearer ${meshAuthToken}`
6410
+ },
6493
6411
  body: JSON.stringify(pushData),
6494
6412
  signal: AbortSignal.timeout(3e4),
6495
6413
  redirect: "error"
@@ -6502,6 +6420,7 @@ function registerMeshFunction(sdk, kv) {
6502
6420
  }
6503
6421
  if (direction === "pull" || direction === "both") try {
6504
6422
  const response = await fetch(`${peer.url}/agentmemory/mesh/export?since=${peer.lastSyncAt || ""}`, {
6423
+ headers: { Authorization: `Bearer ${meshAuthToken}` },
6505
6424
  signal: AbortSignal.timeout(3e4),
6506
6425
  redirect: "error"
6507
6426
  });
@@ -8362,7 +8281,16 @@ function registerLessonsFunctions(sdk, kv) {
8362
8281
 
8363
8282
  //#endregion
8364
8283
  //#region src/functions/obsidian-export.ts
8365
- const DEFAULT_VAULT = join(homedir(), ".agentmemory", "vault");
8284
+ const DEFAULT_EXPORT_ROOT = join(homedir(), ".agentmemory");
8285
+ function getExportRoot() {
8286
+ return resolve(process.env["AGENTMEMORY_EXPORT_ROOT"] || DEFAULT_EXPORT_ROOT);
8287
+ }
8288
+ function resolveVaultDir(vaultDir) {
8289
+ const root = getExportRoot();
8290
+ const resolved = resolve(vaultDir || join(root, "vault"));
8291
+ if (resolved === root || resolved.startsWith(root + sep)) return resolved;
8292
+ return null;
8293
+ }
8366
8294
  function sanitize(name) {
8367
8295
  return name.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 100);
8368
8296
  }
@@ -8475,7 +8403,11 @@ function sessionToMd(s) {
8475
8403
  }
8476
8404
  function registerObsidianExportFunction(sdk, kv) {
8477
8405
  sdk.registerFunction({ id: "mem::obsidian-export" }, async (data) => {
8478
- const vaultDir = data.vaultDir || DEFAULT_VAULT;
8406
+ const vaultDir = resolveVaultDir(data.vaultDir);
8407
+ if (!vaultDir) return {
8408
+ success: false,
8409
+ error: `vaultDir must be inside ${getExportRoot()}`
8410
+ };
8479
8411
  const exportTypes = new Set(data.types || [
8480
8412
  "memories",
8481
8413
  "lessons",
@@ -9021,12 +8953,15 @@ function registerWorkingMemoryFunctions(sdk, kv, tokenBudget) {
9021
8953
  if (Math.abs(strengthDiff) > .2) return strengthDiff;
9022
8954
  return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
9023
8955
  });
8956
+ const archivalIds = [];
9024
8957
  for (const mem of active) {
9025
8958
  const tokens = estimateTokens(mem.content);
9026
8959
  if (usedTokens + tokens > budget) continue;
9027
8960
  archivalLines.push(`- [${mem.type}] ${mem.title}: ${mem.content}`);
8961
+ archivalIds.push(mem.id);
9028
8962
  usedTokens += tokens;
9029
8963
  }
8964
+ recordAccessBatch(kv, archivalIds);
9030
8965
  const pagedOut = active.length - archivalLines.length;
9031
8966
  const sections = [];
9032
8967
  if (coreLines.length > 0) sections.push(`## Core Memory\n${coreLines.join("\n")}`);
@@ -9780,17 +9715,15 @@ const DEFAULT_DECAY = {
9780
9715
  cold: .15
9781
9716
  }
9782
9717
  };
9783
- function computeRetention(salience, createdAt, accessTimestamps, config) {
9718
+ function computeReinforcementBoost(accessTimestamps, sigma) {
9784
9719
  const now = Date.now();
9785
- const deltaT = (now - new Date(createdAt).getTime()) / (1e3 * 60 * 60 * 24);
9786
- const temporalDecay = Math.exp(-config.lambda * deltaT);
9787
- let reinforcementBoost = 0;
9720
+ let boost = 0;
9788
9721
  for (const tAccess of accessTimestamps) {
9722
+ if (!Number.isFinite(tAccess)) continue;
9789
9723
  const daysSinceAccess = (now - tAccess) / (1e3 * 60 * 60 * 24);
9790
- if (daysSinceAccess > 0) reinforcementBoost += 1 / daysSinceAccess;
9724
+ if (daysSinceAccess > 0) boost += 1 / daysSinceAccess;
9791
9725
  }
9792
- reinforcementBoost *= config.sigma;
9793
- return Math.min(1, salience * temporalDecay + reinforcementBoost);
9726
+ return boost * sigma;
9794
9727
  }
9795
9728
  function computeSalience(memory, accessCount) {
9796
9729
  let baseSalience = .5;
@@ -9816,37 +9749,64 @@ function registerRetentionFunctions(sdk, kv) {
9816
9749
  ...DEFAULT_DECAY,
9817
9750
  ...data.config
9818
9751
  };
9819
- const memories = await kv.list(KV.memories);
9820
- const semanticMems = await kv.list(KV.semantic);
9752
+ const [memories, semanticMems, allLogs] = await Promise.all([
9753
+ kv.list(KV.memories),
9754
+ kv.list(KV.semantic),
9755
+ kv.list(KV.accessLog).catch(() => [])
9756
+ ]);
9757
+ const logsById = /* @__PURE__ */ new Map();
9758
+ for (const raw of allLogs) {
9759
+ const log = normalizeAccessLog(raw);
9760
+ if (log.memoryId) logsById.set(log.memoryId, log);
9761
+ }
9821
9762
  const scores = [];
9763
+ const computeDecay = (createdAt) => Math.exp(-config.lambda * ((Date.now() - new Date(createdAt).getTime()) / (1e3 * 60 * 60 * 24)));
9822
9764
  for (const mem of memories) {
9823
9765
  if (!mem.isLatest) continue;
9824
- const salience = computeSalience(mem, 0);
9825
- const score = computeRetention(salience, mem.createdAt, [], config);
9766
+ const log = logsById.get(mem.id) ?? emptyAccessLog(mem.id);
9767
+ const salience = computeSalience(mem, log.count);
9768
+ const temporalDecay = computeDecay(mem.createdAt);
9769
+ const reinforcementBoost = computeReinforcementBoost(log.recent, config.sigma);
9770
+ const score = Math.min(1, salience * temporalDecay + reinforcementBoost);
9826
9771
  const entry = {
9827
9772
  memoryId: mem.id,
9828
9773
  score,
9829
9774
  salience,
9830
- temporalDecay: Math.exp(-config.lambda * ((Date.now() - new Date(mem.createdAt).getTime()) / (1e3 * 60 * 60 * 24))),
9831
- reinforcementBoost: 0,
9832
- lastAccessed: mem.updatedAt,
9833
- accessCount: 0
9775
+ temporalDecay,
9776
+ reinforcementBoost,
9777
+ lastAccessed: log.lastAt || mem.updatedAt,
9778
+ accessCount: log.count
9834
9779
  };
9835
9780
  scores.push(entry);
9836
9781
  await kv.set(KV.retentionScores, mem.id, entry);
9837
9782
  }
9838
9783
  for (const sem of semanticMems) {
9839
- const accessTimestamps = sem.lastAccessedAt ? [new Date(sem.lastAccessedAt).getTime()] : [];
9840
- const salience = computeSalience(sem, sem.accessCount);
9841
- const score = computeRetention(salience, sem.createdAt, accessTimestamps, config);
9784
+ const log = logsById.get(sem.id) ?? emptyAccessLog(sem.id);
9785
+ let accessTimestamps;
9786
+ let effectiveCount;
9787
+ if (log.recent.length > 0 || log.count > 0) {
9788
+ accessTimestamps = log.recent;
9789
+ effectiveCount = log.count;
9790
+ } else if (sem.lastAccessedAt) {
9791
+ const legacyTs = Date.parse(sem.lastAccessedAt);
9792
+ accessTimestamps = Number.isFinite(legacyTs) ? [legacyTs] : [];
9793
+ effectiveCount = sem.accessCount;
9794
+ } else {
9795
+ accessTimestamps = [];
9796
+ effectiveCount = sem.accessCount;
9797
+ }
9798
+ const salience = computeSalience(sem, effectiveCount);
9799
+ const temporalDecay = computeDecay(sem.createdAt);
9800
+ const reinforcementBoost = computeReinforcementBoost(accessTimestamps, config.sigma);
9801
+ const score = Math.min(1, salience * temporalDecay + reinforcementBoost);
9842
9802
  const entry = {
9843
9803
  memoryId: sem.id,
9844
9804
  score,
9845
9805
  salience,
9846
- temporalDecay: Math.exp(-config.lambda * ((Date.now() - new Date(sem.createdAt).getTime()) / (1e3 * 60 * 60 * 24))),
9847
- reinforcementBoost: score - salience * Math.exp(-config.lambda * ((Date.now() - new Date(sem.createdAt).getTime()) / (1e3 * 60 * 60 * 24))),
9848
- lastAccessed: sem.lastAccessedAt,
9849
- accessCount: sem.accessCount
9806
+ temporalDecay,
9807
+ reinforcementBoost,
9808
+ lastAccessed: log.lastAt || sem.lastAccessedAt,
9809
+ accessCount: effectiveCount
9850
9810
  };
9851
9811
  scores.push(entry);
9852
9812
  await kv.set(KV.retentionScores, sem.id, entry);
@@ -9890,6 +9850,7 @@ function registerRetentionFunctions(sdk, kv) {
9890
9850
  for (const candidate of candidates) try {
9891
9851
  await kv.delete(KV.memories, candidate.memoryId);
9892
9852
  await kv.delete(KV.retentionScores, candidate.memoryId);
9853
+ await deleteAccessLog(kv, candidate.memoryId);
9893
9854
  evicted++;
9894
9855
  } catch {
9895
9856
  continue;
@@ -10045,14 +10006,57 @@ async function getLatestHealth(kv) {
10045
10006
  //#endregion
10046
10007
  //#region src/auth.ts
10047
10008
  const hmacKey = randomBytes(32);
10009
+ const VIEWER_NONCE_PLACEHOLDER = "__AGENTMEMORY_VIEWER_NONCE__";
10048
10010
  function timingSafeCompare(a, b) {
10049
10011
  return timingSafeEqual(createHmac("sha256", hmacKey).update(a).digest(), createHmac("sha256", hmacKey).update(b).digest());
10050
10012
  }
10051
- const VIEWER_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self' ws://localhost:* wss://localhost:*; img-src 'self'; font-src 'self'";
10013
+ function createViewerNonce() {
10014
+ return randomBytes(16).toString("base64url");
10015
+ }
10016
+ function buildViewerCsp(nonce) {
10017
+ return [
10018
+ "default-src 'none'",
10019
+ "base-uri 'none'",
10020
+ "frame-ancestors 'none'",
10021
+ "object-src 'none'",
10022
+ "form-action 'none'",
10023
+ `script-src 'nonce-${nonce}'`,
10024
+ "script-src-attr 'none'",
10025
+ "style-src 'unsafe-inline'",
10026
+ "connect-src 'self' http://localhost:* http://127.0.0.1:* ws://localhost:* ws://127.0.0.1:* wss://localhost:* wss://127.0.0.1:*",
10027
+ "img-src 'self'",
10028
+ "font-src 'self'"
10029
+ ].join("; ");
10030
+ }
10031
+
10032
+ //#endregion
10033
+ //#region src/viewer/document.ts
10034
+ function loadViewerTemplate() {
10035
+ const base = dirname(fileURLToPath(import.meta.url));
10036
+ const candidates = [
10037
+ join(base, "..", "src", "viewer", "index.html"),
10038
+ join(base, "..", "viewer", "index.html"),
10039
+ join(base, "viewer", "index.html")
10040
+ ];
10041
+ for (const path of candidates) try {
10042
+ return readFileSync(path, "utf-8");
10043
+ } catch {}
10044
+ return null;
10045
+ }
10046
+ function renderViewerDocument() {
10047
+ const template = loadViewerTemplate();
10048
+ if (!template) return { found: false };
10049
+ const nonce = createViewerNonce();
10050
+ return {
10051
+ found: true,
10052
+ html: template.replaceAll(VIEWER_NONCE_PLACEHOLDER, nonce),
10053
+ csp: buildViewerCsp(nonce)
10054
+ };
10055
+ }
10052
10056
 
10053
10057
  //#endregion
10054
10058
  //#region src/triggers/api.ts
10055
- function checkAuth$1(req, secret) {
10059
+ function checkAuth(req, secret) {
10056
10060
  if (!secret) return null;
10057
10061
  const auth = req.headers?.["authorization"] || req.headers?.["Authorization"];
10058
10062
  if (typeof auth !== "string" || !timingSafeCompare(auth, `Bearer ${secret}`)) return {
@@ -10061,6 +10065,13 @@ function checkAuth$1(req, secret) {
10061
10065
  };
10062
10066
  return null;
10063
10067
  }
10068
+ function requireConfiguredSecret(secret, feature) {
10069
+ if (secret) return null;
10070
+ return {
10071
+ status_code: 503,
10072
+ body: { error: `${feature} requires AGENTMEMORY_SECRET` }
10073
+ };
10074
+ }
10064
10075
  function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10065
10076
  sdk.registerFunction({ id: "api::liveness" }, async () => ({
10066
10077
  status_code: 200,
@@ -10078,7 +10089,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10078
10089
  }
10079
10090
  });
10080
10091
  sdk.registerFunction({ id: "api::health" }, async (req) => {
10081
- const authErr = checkAuth$1(req, secret);
10092
+ const authErr = checkAuth(req, secret);
10082
10093
  if (authErr) return authErr;
10083
10094
  const health = await getLatestHealth(kv);
10084
10095
  const functionMetrics = metricsStore ? await metricsStore.getAll() : [];
@@ -10105,7 +10116,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10105
10116
  }
10106
10117
  });
10107
10118
  sdk.registerFunction({ id: "api::observe" }, async (req) => {
10108
- const authErr = checkAuth$1(req, secret);
10119
+ const authErr = checkAuth(req, secret);
10109
10120
  if (authErr) return authErr;
10110
10121
  return {
10111
10122
  status_code: 201,
@@ -10121,7 +10132,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10121
10132
  }
10122
10133
  });
10123
10134
  sdk.registerFunction({ id: "api::context" }, async (req) => {
10124
- const authErr = checkAuth$1(req, secret);
10135
+ const authErr = checkAuth(req, secret);
10125
10136
  if (authErr) return authErr;
10126
10137
  return {
10127
10138
  status_code: 200,
@@ -10137,7 +10148,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10137
10148
  }
10138
10149
  });
10139
10150
  sdk.registerFunction({ id: "api::search" }, async (req) => {
10140
- const authErr = checkAuth$1(req, secret);
10151
+ const authErr = checkAuth(req, secret);
10141
10152
  if (authErr) return authErr;
10142
10153
  const body = req.body ?? {};
10143
10154
  if (typeof body.query !== "string" || !body.query.trim()) return {
@@ -10176,7 +10187,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10176
10187
  }
10177
10188
  });
10178
10189
  sdk.registerFunction({ id: "api::session::start" }, async (req) => {
10179
- const authErr = checkAuth$1(req, secret);
10190
+ const authErr = checkAuth(req, secret);
10180
10191
  if (authErr) return authErr;
10181
10192
  const { sessionId, project, cwd } = req.body;
10182
10193
  const session = {
@@ -10208,7 +10219,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10208
10219
  }
10209
10220
  });
10210
10221
  sdk.registerFunction({ id: "api::session::end" }, async (req) => {
10211
- const authErr = checkAuth$1(req, secret);
10222
+ const authErr = checkAuth(req, secret);
10212
10223
  if (authErr) return authErr;
10213
10224
  const session = await kv.get(KV.sessions, req.body.sessionId);
10214
10225
  if (session) await kv.set(KV.sessions, req.body.sessionId, {
@@ -10230,7 +10241,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10230
10241
  }
10231
10242
  });
10232
10243
  sdk.registerFunction({ id: "api::summarize" }, async (req) => {
10233
- const authErr = checkAuth$1(req, secret);
10244
+ const authErr = checkAuth(req, secret);
10234
10245
  if (authErr) return authErr;
10235
10246
  return {
10236
10247
  status_code: 200,
@@ -10246,7 +10257,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10246
10257
  }
10247
10258
  });
10248
10259
  sdk.registerFunction({ id: "api::sessions" }, async (req) => {
10249
- const authErr = checkAuth$1(req, secret);
10260
+ const authErr = checkAuth(req, secret);
10250
10261
  if (authErr) return authErr;
10251
10262
  return {
10252
10263
  status_code: 200,
@@ -10262,7 +10273,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10262
10273
  }
10263
10274
  });
10264
10275
  sdk.registerFunction({ id: "api::observations" }, async (req) => {
10265
- const authErr = checkAuth$1(req, secret);
10276
+ const authErr = checkAuth(req, secret);
10266
10277
  if (authErr) return authErr;
10267
10278
  const sessionId = req.query_params["sessionId"];
10268
10279
  if (!sessionId) return {
@@ -10283,7 +10294,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10283
10294
  }
10284
10295
  });
10285
10296
  sdk.registerFunction({ id: "api::file-context" }, async (req) => {
10286
- const authErr = checkAuth$1(req, secret);
10297
+ const authErr = checkAuth(req, secret);
10287
10298
  if (authErr) return authErr;
10288
10299
  return {
10289
10300
  status_code: 200,
@@ -10299,7 +10310,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10299
10310
  }
10300
10311
  });
10301
10312
  sdk.registerFunction({ id: "api::enrich" }, async (req) => {
10302
- const authErr = checkAuth$1(req, secret);
10313
+ const authErr = checkAuth(req, secret);
10303
10314
  if (authErr) return authErr;
10304
10315
  if (!req.body?.sessionId || typeof req.body.sessionId !== "string" || !Array.isArray(req.body?.files) || req.body.files.length === 0 || !req.body.files.every((f) => typeof f === "string")) return {
10305
10316
  status_code: 400,
@@ -10323,7 +10334,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10323
10334
  }
10324
10335
  });
10325
10336
  sdk.registerFunction({ id: "api::remember" }, async (req) => {
10326
- const authErr = checkAuth$1(req, secret);
10337
+ const authErr = checkAuth(req, secret);
10327
10338
  if (authErr) return authErr;
10328
10339
  if (!req.body?.content || typeof req.body.content !== "string" || !req.body.content.trim()) return {
10329
10340
  status_code: 400,
@@ -10343,7 +10354,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10343
10354
  }
10344
10355
  });
10345
10356
  sdk.registerFunction({ id: "api::forget" }, async (req) => {
10346
- const authErr = checkAuth$1(req, secret);
10357
+ const authErr = checkAuth(req, secret);
10347
10358
  if (authErr) return authErr;
10348
10359
  if (!req.body?.sessionId && !req.body?.memoryId) return {
10349
10360
  status_code: 400,
@@ -10363,7 +10374,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10363
10374
  }
10364
10375
  });
10365
10376
  sdk.registerFunction({ id: "api::consolidate" }, async (req) => {
10366
- const authErr = checkAuth$1(req, secret);
10377
+ const authErr = checkAuth(req, secret);
10367
10378
  if (authErr) return authErr;
10368
10379
  return {
10369
10380
  status_code: 200,
@@ -10379,7 +10390,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10379
10390
  }
10380
10391
  });
10381
10392
  sdk.registerFunction({ id: "api::patterns" }, async (req) => {
10382
- const authErr = checkAuth$1(req, secret);
10393
+ const authErr = checkAuth(req, secret);
10383
10394
  if (authErr) return authErr;
10384
10395
  return {
10385
10396
  status_code: 200,
@@ -10395,7 +10406,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10395
10406
  }
10396
10407
  });
10397
10408
  sdk.registerFunction({ id: "api::generate-rules" }, async (req) => {
10398
- const authErr = checkAuth$1(req, secret);
10409
+ const authErr = checkAuth(req, secret);
10399
10410
  if (authErr) return authErr;
10400
10411
  return {
10401
10412
  status_code: 200,
@@ -10411,7 +10422,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10411
10422
  }
10412
10423
  });
10413
10424
  sdk.registerFunction({ id: "api::migrate" }, async (req) => {
10414
- const authErr = checkAuth$1(req, secret);
10425
+ const authErr = checkAuth(req, secret);
10415
10426
  if (authErr) return authErr;
10416
10427
  if (!req.body?.dbPath || typeof req.body.dbPath !== "string") return {
10417
10428
  status_code: 400,
@@ -10431,7 +10442,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10431
10442
  }
10432
10443
  });
10433
10444
  sdk.registerFunction({ id: "api::evict" }, async (req) => {
10434
- const authErr = checkAuth$1(req, secret);
10445
+ const authErr = checkAuth(req, secret);
10435
10446
  if (authErr) return authErr;
10436
10447
  const dryRun = req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true;
10437
10448
  return {
@@ -10448,7 +10459,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10448
10459
  }
10449
10460
  });
10450
10461
  sdk.registerFunction({ id: "api::smart-search" }, async (req) => {
10451
- const authErr = checkAuth$1(req, secret);
10462
+ const authErr = checkAuth(req, secret);
10452
10463
  if (authErr) return authErr;
10453
10464
  if (!req.body?.query && (!req.body?.expandIds || req.body.expandIds.length === 0)) return {
10454
10465
  status_code: 400,
@@ -10468,7 +10479,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10468
10479
  }
10469
10480
  });
10470
10481
  sdk.registerFunction({ id: "api::timeline" }, async (req) => {
10471
- const authErr = checkAuth$1(req, secret);
10482
+ const authErr = checkAuth(req, secret);
10472
10483
  if (authErr) return authErr;
10473
10484
  if (!req.body?.anchor) return {
10474
10485
  status_code: 400,
@@ -10488,7 +10499,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10488
10499
  }
10489
10500
  });
10490
10501
  sdk.registerFunction({ id: "api::profile" }, async (req) => {
10491
- const authErr = checkAuth$1(req, secret);
10502
+ const authErr = checkAuth(req, secret);
10492
10503
  if (authErr) return authErr;
10493
10504
  const project = req.query_params["project"];
10494
10505
  if (!project) return {
@@ -10509,7 +10520,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10509
10520
  }
10510
10521
  });
10511
10522
  sdk.registerFunction({ id: "api::export" }, async (req) => {
10512
- const authErr = checkAuth$1(req, secret);
10523
+ const authErr = checkAuth(req, secret);
10513
10524
  if (authErr) return authErr;
10514
10525
  return {
10515
10526
  status_code: 200,
@@ -10525,7 +10536,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10525
10536
  }
10526
10537
  });
10527
10538
  sdk.registerFunction({ id: "api::import" }, async (req) => {
10528
- const authErr = checkAuth$1(req, secret);
10539
+ const authErr = checkAuth(req, secret);
10529
10540
  if (authErr) return authErr;
10530
10541
  if (!req.body?.exportData) return {
10531
10542
  status_code: 400,
@@ -10545,7 +10556,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10545
10556
  }
10546
10557
  });
10547
10558
  sdk.registerFunction({ id: "api::relations" }, async (req) => {
10548
- const authErr = checkAuth$1(req, secret);
10559
+ const authErr = checkAuth(req, secret);
10549
10560
  if (authErr) return authErr;
10550
10561
  if (!req.body?.sourceId || !req.body?.targetId || !req.body?.type) return {
10551
10562
  status_code: 400,
@@ -10565,7 +10576,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10565
10576
  }
10566
10577
  });
10567
10578
  sdk.registerFunction({ id: "api::evolve" }, async (req) => {
10568
- const authErr = checkAuth$1(req, secret);
10579
+ const authErr = checkAuth(req, secret);
10569
10580
  if (authErr) return authErr;
10570
10581
  if (!req.body?.memoryId || !req.body?.newContent) return {
10571
10582
  status_code: 400,
@@ -10585,7 +10596,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10585
10596
  }
10586
10597
  });
10587
10598
  sdk.registerFunction({ id: "api::auto-forget" }, async (req) => {
10588
- const authErr = checkAuth$1(req, secret);
10599
+ const authErr = checkAuth(req, secret);
10589
10600
  if (authErr) return authErr;
10590
10601
  const dryRun = req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true;
10591
10602
  return {
@@ -10602,7 +10613,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10602
10613
  }
10603
10614
  });
10604
10615
  sdk.registerFunction({ id: "api::claude-bridge-read" }, async (req) => {
10605
- const authErr = checkAuth$1(req, secret);
10616
+ const authErr = checkAuth(req, secret);
10606
10617
  if (authErr) return authErr;
10607
10618
  try {
10608
10619
  return {
@@ -10625,7 +10636,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10625
10636
  }
10626
10637
  });
10627
10638
  sdk.registerFunction({ id: "api::claude-bridge-sync" }, async (req) => {
10628
- const authErr = checkAuth$1(req, secret);
10639
+ const authErr = checkAuth(req, secret);
10629
10640
  if (authErr) return authErr;
10630
10641
  try {
10631
10642
  return {
@@ -10648,7 +10659,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10648
10659
  }
10649
10660
  });
10650
10661
  sdk.registerFunction({ id: "api::graph-query" }, async (req) => {
10651
- const authErr = checkAuth$1(req, secret);
10662
+ const authErr = checkAuth(req, secret);
10652
10663
  if (authErr) return authErr;
10653
10664
  try {
10654
10665
  return {
@@ -10671,7 +10682,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10671
10682
  }
10672
10683
  });
10673
10684
  sdk.registerFunction({ id: "api::graph-stats" }, async (req) => {
10674
- const authErr = checkAuth$1(req, secret);
10685
+ const authErr = checkAuth(req, secret);
10675
10686
  if (authErr) return authErr;
10676
10687
  try {
10677
10688
  return {
@@ -10694,7 +10705,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10694
10705
  }
10695
10706
  });
10696
10707
  sdk.registerFunction({ id: "api::graph-extract" }, async (req) => {
10697
- const authErr = checkAuth$1(req, secret);
10708
+ const authErr = checkAuth(req, secret);
10698
10709
  if (authErr) return authErr;
10699
10710
  if (!Array.isArray(req.body?.observations) || req.body.observations.length === 0) return {
10700
10711
  status_code: 400,
@@ -10721,7 +10732,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10721
10732
  }
10722
10733
  });
10723
10734
  sdk.registerFunction({ id: "api::consolidate-pipeline" }, async (req) => {
10724
- const authErr = checkAuth$1(req, secret);
10735
+ const authErr = checkAuth(req, secret);
10725
10736
  if (authErr) return authErr;
10726
10737
  try {
10727
10738
  return {
@@ -10744,7 +10755,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10744
10755
  }
10745
10756
  });
10746
10757
  sdk.registerFunction({ id: "api::team-share" }, async (req) => {
10747
- const authErr = checkAuth$1(req, secret);
10758
+ const authErr = checkAuth(req, secret);
10748
10759
  if (authErr) return authErr;
10749
10760
  if (!req.body?.itemId || !req.body?.itemType) return {
10750
10761
  status_code: 400,
@@ -10771,7 +10782,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10771
10782
  }
10772
10783
  });
10773
10784
  sdk.registerFunction({ id: "api::team-feed" }, async (req) => {
10774
- const authErr = checkAuth$1(req, secret);
10785
+ const authErr = checkAuth(req, secret);
10775
10786
  if (authErr) return authErr;
10776
10787
  try {
10777
10788
  const limit = parseInt(req.query_params?.["limit"]) || 20;
@@ -10795,7 +10806,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10795
10806
  }
10796
10807
  });
10797
10808
  sdk.registerFunction({ id: "api::team-profile" }, async (req) => {
10798
- const authErr = checkAuth$1(req, secret);
10809
+ const authErr = checkAuth(req, secret);
10799
10810
  if (authErr) return authErr;
10800
10811
  try {
10801
10812
  return {
@@ -10818,7 +10829,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10818
10829
  }
10819
10830
  });
10820
10831
  sdk.registerFunction({ id: "api::audit" }, async (req) => {
10821
- const authErr = checkAuth$1(req, secret);
10832
+ const authErr = checkAuth(req, secret);
10822
10833
  if (authErr) return authErr;
10823
10834
  return {
10824
10835
  status_code: 200,
@@ -10837,7 +10848,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10837
10848
  }
10838
10849
  });
10839
10850
  sdk.registerFunction({ id: "api::governance-delete" }, async (req) => {
10840
- const authErr = checkAuth$1(req, secret);
10851
+ const authErr = checkAuth(req, secret);
10841
10852
  if (authErr) return authErr;
10842
10853
  if (!req.body?.memoryIds || !Array.isArray(req.body.memoryIds)) return {
10843
10854
  status_code: 400,
@@ -10857,7 +10868,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10857
10868
  }
10858
10869
  });
10859
10870
  sdk.registerFunction({ id: "api::governance-bulk" }, async (req) => {
10860
- const authErr = checkAuth$1(req, secret);
10871
+ const authErr = checkAuth(req, secret);
10861
10872
  if (authErr) return authErr;
10862
10873
  return {
10863
10874
  status_code: 200,
@@ -10873,7 +10884,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10873
10884
  }
10874
10885
  });
10875
10886
  sdk.registerFunction({ id: "api::snapshots" }, async (req) => {
10876
- const authErr = checkAuth$1(req, secret);
10887
+ const authErr = checkAuth(req, secret);
10877
10888
  if (authErr) return authErr;
10878
10889
  try {
10879
10890
  return {
@@ -10896,7 +10907,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10896
10907
  }
10897
10908
  });
10898
10909
  sdk.registerFunction({ id: "api::snapshot-create" }, async (req) => {
10899
- const authErr = checkAuth$1(req, secret);
10910
+ const authErr = checkAuth(req, secret);
10900
10911
  if (authErr) return authErr;
10901
10912
  try {
10902
10913
  return {
@@ -10919,7 +10930,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10919
10930
  }
10920
10931
  });
10921
10932
  sdk.registerFunction({ id: "api::snapshot-restore" }, async (req) => {
10922
- const authErr = checkAuth$1(req, secret);
10933
+ const authErr = checkAuth(req, secret);
10923
10934
  if (authErr) return authErr;
10924
10935
  if (!req.body?.commitHash) return {
10925
10936
  status_code: 400,
@@ -10946,7 +10957,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10946
10957
  }
10947
10958
  });
10948
10959
  sdk.registerFunction({ id: "api::memories" }, async (req) => {
10949
- const authErr = checkAuth$1(req, secret);
10960
+ const authErr = checkAuth(req, secret);
10950
10961
  if (authErr) return authErr;
10951
10962
  const memories = await kv.list(KV.memories);
10952
10963
  return {
@@ -10963,7 +10974,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10963
10974
  }
10964
10975
  });
10965
10976
  sdk.registerFunction({ id: "api::action-create" }, async (req) => {
10966
- const authErr = checkAuth$1(req, secret);
10977
+ const authErr = checkAuth(req, secret);
10967
10978
  if (authErr) return authErr;
10968
10979
  if (!req.body?.title) return {
10969
10980
  status_code: 400,
@@ -10983,7 +10994,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
10983
10994
  }
10984
10995
  });
10985
10996
  sdk.registerFunction({ id: "api::action-update" }, async (req) => {
10986
- const authErr = checkAuth$1(req, secret);
10997
+ const authErr = checkAuth(req, secret);
10987
10998
  if (authErr) return authErr;
10988
10999
  if (!req.body?.actionId) return {
10989
11000
  status_code: 400,
@@ -11003,7 +11014,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11003
11014
  }
11004
11015
  });
11005
11016
  sdk.registerFunction({ id: "api::action-list" }, async (req) => {
11006
- const authErr = checkAuth$1(req, secret);
11017
+ const authErr = checkAuth(req, secret);
11007
11018
  if (authErr) return authErr;
11008
11019
  return {
11009
11020
  status_code: 200,
@@ -11023,7 +11034,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11023
11034
  }
11024
11035
  });
11025
11036
  sdk.registerFunction({ id: "api::action-get" }, async (req) => {
11026
- const authErr = checkAuth$1(req, secret);
11037
+ const authErr = checkAuth(req, secret);
11027
11038
  if (authErr) return authErr;
11028
11039
  const actionId = req.query_params?.["actionId"];
11029
11040
  if (!actionId) return {
@@ -11044,7 +11055,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11044
11055
  }
11045
11056
  });
11046
11057
  sdk.registerFunction({ id: "api::action-edge" }, async (req) => {
11047
- const authErr = checkAuth$1(req, secret);
11058
+ const authErr = checkAuth(req, secret);
11048
11059
  if (authErr) return authErr;
11049
11060
  if (!req.body?.sourceActionId || !req.body?.targetActionId || !req.body?.type) return {
11050
11061
  status_code: 400,
@@ -11064,7 +11075,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11064
11075
  }
11065
11076
  });
11066
11077
  sdk.registerFunction({ id: "api::frontier" }, async (req) => {
11067
- const authErr = checkAuth$1(req, secret);
11078
+ const authErr = checkAuth(req, secret);
11068
11079
  if (authErr) return authErr;
11069
11080
  return {
11070
11081
  status_code: 200,
@@ -11084,7 +11095,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11084
11095
  }
11085
11096
  });
11086
11097
  sdk.registerFunction({ id: "api::next" }, async (req) => {
11087
- const authErr = checkAuth$1(req, secret);
11098
+ const authErr = checkAuth(req, secret);
11088
11099
  if (authErr) return authErr;
11089
11100
  return {
11090
11101
  status_code: 200,
@@ -11103,7 +11114,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11103
11114
  }
11104
11115
  });
11105
11116
  sdk.registerFunction({ id: "api::lease-acquire" }, async (req) => {
11106
- const authErr = checkAuth$1(req, secret);
11117
+ const authErr = checkAuth(req, secret);
11107
11118
  if (authErr) return authErr;
11108
11119
  if (!req.body?.actionId || !req.body?.agentId) return {
11109
11120
  status_code: 400,
@@ -11123,7 +11134,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11123
11134
  }
11124
11135
  });
11125
11136
  sdk.registerFunction({ id: "api::lease-release" }, async (req) => {
11126
- const authErr = checkAuth$1(req, secret);
11137
+ const authErr = checkAuth(req, secret);
11127
11138
  if (authErr) return authErr;
11128
11139
  if (!req.body?.actionId || !req.body?.agentId) return {
11129
11140
  status_code: 400,
@@ -11143,7 +11154,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11143
11154
  }
11144
11155
  });
11145
11156
  sdk.registerFunction({ id: "api::lease-renew" }, async (req) => {
11146
- const authErr = checkAuth$1(req, secret);
11157
+ const authErr = checkAuth(req, secret);
11147
11158
  if (authErr) return authErr;
11148
11159
  if (!req.body?.actionId || !req.body?.agentId) return {
11149
11160
  status_code: 400,
@@ -11163,7 +11174,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11163
11174
  }
11164
11175
  });
11165
11176
  sdk.registerFunction({ id: "api::routine-create" }, async (req) => {
11166
- const authErr = checkAuth$1(req, secret);
11177
+ const authErr = checkAuth(req, secret);
11167
11178
  if (authErr) return authErr;
11168
11179
  if (!req.body?.name) return {
11169
11180
  status_code: 400,
@@ -11183,7 +11194,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11183
11194
  }
11184
11195
  });
11185
11196
  sdk.registerFunction({ id: "api::routine-list" }, async (req) => {
11186
- const authErr = checkAuth$1(req, secret);
11197
+ const authErr = checkAuth(req, secret);
11187
11198
  if (authErr) return authErr;
11188
11199
  return {
11189
11200
  status_code: 200,
@@ -11199,7 +11210,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11199
11210
  }
11200
11211
  });
11201
11212
  sdk.registerFunction({ id: "api::routine-run" }, async (req) => {
11202
- const authErr = checkAuth$1(req, secret);
11213
+ const authErr = checkAuth(req, secret);
11203
11214
  if (authErr) return authErr;
11204
11215
  if (!req.body?.routineId) return {
11205
11216
  status_code: 400,
@@ -11219,7 +11230,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11219
11230
  }
11220
11231
  });
11221
11232
  sdk.registerFunction({ id: "api::routine-status" }, async (req) => {
11222
- const authErr = checkAuth$1(req, secret);
11233
+ const authErr = checkAuth(req, secret);
11223
11234
  if (authErr) return authErr;
11224
11235
  const runId = req.query_params?.["runId"];
11225
11236
  if (!runId) return {
@@ -11240,7 +11251,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11240
11251
  }
11241
11252
  });
11242
11253
  sdk.registerFunction({ id: "api::signal-send" }, async (req) => {
11243
- const authErr = checkAuth$1(req, secret);
11254
+ const authErr = checkAuth(req, secret);
11244
11255
  if (authErr) return authErr;
11245
11256
  if (!req.body?.from || !req.body?.content) return {
11246
11257
  status_code: 400,
@@ -11260,7 +11271,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11260
11271
  }
11261
11272
  });
11262
11273
  sdk.registerFunction({ id: "api::signal-read" }, async (req) => {
11263
- const authErr = checkAuth$1(req, secret);
11274
+ const authErr = checkAuth(req, secret);
11264
11275
  if (authErr) return authErr;
11265
11276
  const agentId = req.query_params?.["agentId"];
11266
11277
  if (!agentId) return {
@@ -11286,7 +11297,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11286
11297
  }
11287
11298
  });
11288
11299
  sdk.registerFunction({ id: "api::checkpoint-create" }, async (req) => {
11289
- const authErr = checkAuth$1(req, secret);
11300
+ const authErr = checkAuth(req, secret);
11290
11301
  if (authErr) return authErr;
11291
11302
  if (!req.body?.name) return {
11292
11303
  status_code: 400,
@@ -11306,7 +11317,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11306
11317
  }
11307
11318
  });
11308
11319
  sdk.registerFunction({ id: "api::checkpoint-resolve" }, async (req) => {
11309
- const authErr = checkAuth$1(req, secret);
11320
+ const authErr = checkAuth(req, secret);
11310
11321
  if (authErr) return authErr;
11311
11322
  if (!req.body?.checkpointId || !req.body?.status) return {
11312
11323
  status_code: 400,
@@ -11326,7 +11337,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11326
11337
  }
11327
11338
  });
11328
11339
  sdk.registerFunction({ id: "api::checkpoint-list" }, async (req) => {
11329
- const authErr = checkAuth$1(req, secret);
11340
+ const authErr = checkAuth(req, secret);
11330
11341
  if (authErr) return authErr;
11331
11342
  return {
11332
11343
  status_code: 200,
@@ -11345,7 +11356,9 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11345
11356
  }
11346
11357
  });
11347
11358
  sdk.registerFunction({ id: "api::mesh-register" }, async (req) => {
11348
- const authErr = checkAuth$1(req, secret);
11359
+ const secretErr = requireConfiguredSecret(secret, "mesh");
11360
+ if (secretErr) return secretErr;
11361
+ const authErr = checkAuth(req, secret);
11349
11362
  if (authErr) return authErr;
11350
11363
  if (!req.body?.url || !req.body?.name) return {
11351
11364
  status_code: 400,
@@ -11365,7 +11378,9 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11365
11378
  }
11366
11379
  });
11367
11380
  sdk.registerFunction({ id: "api::mesh-list" }, async (req) => {
11368
- const authErr = checkAuth$1(req, secret);
11381
+ const secretErr = requireConfiguredSecret(secret, "mesh");
11382
+ if (secretErr) return secretErr;
11383
+ const authErr = checkAuth(req, secret);
11369
11384
  if (authErr) return authErr;
11370
11385
  return {
11371
11386
  status_code: 200,
@@ -11381,7 +11396,9 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11381
11396
  }
11382
11397
  });
11383
11398
  sdk.registerFunction({ id: "api::mesh-sync" }, async (req) => {
11384
- const authErr = checkAuth$1(req, secret);
11399
+ const secretErr = requireConfiguredSecret(secret, "mesh");
11400
+ if (secretErr) return secretErr;
11401
+ const authErr = checkAuth(req, secret);
11385
11402
  if (authErr) return authErr;
11386
11403
  return {
11387
11404
  status_code: 200,
@@ -11397,7 +11414,9 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11397
11414
  }
11398
11415
  });
11399
11416
  sdk.registerFunction({ id: "api::mesh-receive" }, async (req) => {
11400
- const authErr = checkAuth$1(req, secret);
11417
+ const secretErr = requireConfiguredSecret(secret, "mesh");
11418
+ if (secretErr) return secretErr;
11419
+ const authErr = checkAuth(req, secret);
11401
11420
  if (authErr) return authErr;
11402
11421
  return {
11403
11422
  status_code: 200,
@@ -11413,7 +11432,9 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11413
11432
  }
11414
11433
  });
11415
11434
  sdk.registerFunction({ id: "api::mesh-export" }, async (req) => {
11416
- const authErr = checkAuth$1(req, secret);
11435
+ const secretErr = requireConfiguredSecret(secret, "mesh");
11436
+ if (secretErr) return secretErr;
11437
+ const authErr = checkAuth(req, secret);
11417
11438
  if (authErr) return authErr;
11418
11439
  const since = req.query_params?.["since"];
11419
11440
  if (since) {
@@ -11459,7 +11480,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11459
11480
  }
11460
11481
  });
11461
11482
  sdk.registerFunction({ id: "api::flow-compress" }, async (req) => {
11462
- const authErr = checkAuth$1(req, secret);
11483
+ const authErr = checkAuth(req, secret);
11463
11484
  if (authErr) return authErr;
11464
11485
  try {
11465
11486
  return {
@@ -11482,7 +11503,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11482
11503
  }
11483
11504
  });
11484
11505
  sdk.registerFunction({ id: "api::branch-detect" }, async (req) => {
11485
- const authErr = checkAuth$1(req, secret);
11506
+ const authErr = checkAuth(req, secret);
11486
11507
  if (authErr) return authErr;
11487
11508
  const cwd = req.query_params?.["cwd"] || process.cwd();
11488
11509
  return {
@@ -11499,7 +11520,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11499
11520
  }
11500
11521
  });
11501
11522
  sdk.registerFunction({ id: "api::branch-worktrees" }, async (req) => {
11502
- const authErr = checkAuth$1(req, secret);
11523
+ const authErr = checkAuth(req, secret);
11503
11524
  if (authErr) return authErr;
11504
11525
  const cwd = req.query_params?.["cwd"] || process.cwd();
11505
11526
  return {
@@ -11516,7 +11537,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11516
11537
  }
11517
11538
  });
11518
11539
  sdk.registerFunction({ id: "api::branch-sessions" }, async (req) => {
11519
- const authErr = checkAuth$1(req, secret);
11540
+ const authErr = checkAuth(req, secret);
11520
11541
  if (authErr) return authErr;
11521
11542
  const cwd = req.query_params?.["cwd"] || process.cwd();
11522
11543
  return {
@@ -11532,27 +11553,21 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11532
11553
  http_method: "GET"
11533
11554
  }
11534
11555
  });
11535
- sdk.registerFunction({ id: "api::viewer" }, async () => {
11536
- const headers = {
11537
- "Content-Type": "text/html",
11538
- "Content-Security-Policy": VIEWER_CSP
11556
+ sdk.registerFunction({ id: "api::viewer" }, async (req) => {
11557
+ const denied = checkAuth(req, secret);
11558
+ if (denied) return denied;
11559
+ const rendered = renderViewerDocument();
11560
+ if (rendered.found) return {
11561
+ status_code: 200,
11562
+ headers: {
11563
+ "Content-Type": "text/html",
11564
+ "Content-Security-Policy": rendered.csp
11565
+ },
11566
+ body: rendered.html
11539
11567
  };
11540
- const base = dirname(fileURLToPath(import.meta.url));
11541
- const candidates = [
11542
- join(base, "..", "viewer", "index.html"),
11543
- join(base, "..", "src", "viewer", "index.html"),
11544
- join(base, "viewer", "index.html")
11545
- ];
11546
- for (const p of candidates) try {
11547
- return {
11548
- status_code: 200,
11549
- headers,
11550
- body: readFileSync(p, "utf-8")
11551
- };
11552
- } catch {}
11553
11568
  return {
11554
11569
  status_code: 404,
11555
- headers,
11570
+ headers: { "Content-Type": "text/html" },
11556
11571
  body: "<!DOCTYPE html><html><body><h1>agentmemory</h1><p>viewer not found</p></body></html>"
11557
11572
  };
11558
11573
  });
@@ -11565,7 +11580,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11565
11580
  }
11566
11581
  });
11567
11582
  sdk.registerFunction({ id: "api::sentinel-create" }, async (req) => {
11568
- const denied = checkAuth$1(req, secret);
11583
+ const denied = checkAuth(req, secret);
11569
11584
  if (denied) return denied;
11570
11585
  const body = req.body;
11571
11586
  if (!body?.name) return {
@@ -11586,7 +11601,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11586
11601
  }
11587
11602
  });
11588
11603
  sdk.registerFunction({ id: "api::sentinel-trigger" }, async (req) => {
11589
- const denied = checkAuth$1(req, secret);
11604
+ const denied = checkAuth(req, secret);
11590
11605
  if (denied) return denied;
11591
11606
  const body = req.body;
11592
11607
  if (!body?.sentinelId) return {
@@ -11607,7 +11622,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11607
11622
  }
11608
11623
  });
11609
11624
  sdk.registerFunction({ id: "api::sentinel-check" }, async (req) => {
11610
- const denied = checkAuth$1(req, secret);
11625
+ const denied = checkAuth(req, secret);
11611
11626
  if (denied) return denied;
11612
11627
  return {
11613
11628
  status_code: 200,
@@ -11623,7 +11638,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11623
11638
  }
11624
11639
  });
11625
11640
  sdk.registerFunction({ id: "api::sentinel-cancel" }, async (req) => {
11626
- const denied = checkAuth$1(req, secret);
11641
+ const denied = checkAuth(req, secret);
11627
11642
  if (denied) return denied;
11628
11643
  const body = req.body;
11629
11644
  if (!body?.sentinelId) return {
@@ -11644,7 +11659,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11644
11659
  }
11645
11660
  });
11646
11661
  sdk.registerFunction({ id: "api::sentinel-list" }, async (req) => {
11647
- const denied = checkAuth$1(req, secret);
11662
+ const denied = checkAuth(req, secret);
11648
11663
  if (denied) return denied;
11649
11664
  const params = req.query_params || {};
11650
11665
  return {
@@ -11664,7 +11679,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11664
11679
  }
11665
11680
  });
11666
11681
  sdk.registerFunction({ id: "api::sketch-create" }, async (req) => {
11667
- const denied = checkAuth$1(req, secret);
11682
+ const denied = checkAuth(req, secret);
11668
11683
  if (denied) return denied;
11669
11684
  const body = req.body;
11670
11685
  if (!body?.title) return {
@@ -11685,7 +11700,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11685
11700
  }
11686
11701
  });
11687
11702
  sdk.registerFunction({ id: "api::sketch-add" }, async (req) => {
11688
- const denied = checkAuth$1(req, secret);
11703
+ const denied = checkAuth(req, secret);
11689
11704
  if (denied) return denied;
11690
11705
  const body = req.body;
11691
11706
  if (!body?.sketchId || !body?.title) return {
@@ -11706,7 +11721,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11706
11721
  }
11707
11722
  });
11708
11723
  sdk.registerFunction({ id: "api::sketch-promote" }, async (req) => {
11709
- const denied = checkAuth$1(req, secret);
11724
+ const denied = checkAuth(req, secret);
11710
11725
  if (denied) return denied;
11711
11726
  const body = req.body;
11712
11727
  if (!body?.sketchId) return {
@@ -11727,7 +11742,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11727
11742
  }
11728
11743
  });
11729
11744
  sdk.registerFunction({ id: "api::sketch-discard" }, async (req) => {
11730
- const denied = checkAuth$1(req, secret);
11745
+ const denied = checkAuth(req, secret);
11731
11746
  if (denied) return denied;
11732
11747
  const body = req.body;
11733
11748
  if (!body?.sketchId) return {
@@ -11748,7 +11763,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11748
11763
  }
11749
11764
  });
11750
11765
  sdk.registerFunction({ id: "api::sketch-list" }, async (req) => {
11751
- const denied = checkAuth$1(req, secret);
11766
+ const denied = checkAuth(req, secret);
11752
11767
  if (denied) return denied;
11753
11768
  const params = req.query_params || {};
11754
11769
  return {
@@ -11768,7 +11783,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11768
11783
  }
11769
11784
  });
11770
11785
  sdk.registerFunction({ id: "api::sketch-gc" }, async (req) => {
11771
- const denied = checkAuth$1(req, secret);
11786
+ const denied = checkAuth(req, secret);
11772
11787
  if (denied) return denied;
11773
11788
  return {
11774
11789
  status_code: 200,
@@ -11784,7 +11799,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11784
11799
  }
11785
11800
  });
11786
11801
  sdk.registerFunction({ id: "api::crystallize" }, async (req) => {
11787
- const denied = checkAuth$1(req, secret);
11802
+ const denied = checkAuth(req, secret);
11788
11803
  if (denied) return denied;
11789
11804
  const body = req.body;
11790
11805
  if (!body?.actionIds) return {
@@ -11805,7 +11820,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11805
11820
  }
11806
11821
  });
11807
11822
  sdk.registerFunction({ id: "api::crystal-list" }, async (req) => {
11808
- const denied = checkAuth$1(req, secret);
11823
+ const denied = checkAuth(req, secret);
11809
11824
  if (denied) return denied;
11810
11825
  const params = req.query_params || {};
11811
11826
  return {
@@ -11826,7 +11841,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11826
11841
  }
11827
11842
  });
11828
11843
  sdk.registerFunction({ id: "api::auto-crystallize" }, async (req) => {
11829
- const denied = checkAuth$1(req, secret);
11844
+ const denied = checkAuth(req, secret);
11830
11845
  if (denied) return denied;
11831
11846
  const body = req.body;
11832
11847
  return {
@@ -11843,7 +11858,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11843
11858
  }
11844
11859
  });
11845
11860
  sdk.registerFunction({ id: "api::diagnose" }, async (req) => {
11846
- const denied = checkAuth$1(req, secret);
11861
+ const denied = checkAuth(req, secret);
11847
11862
  if (denied) return denied;
11848
11863
  const body = req.body;
11849
11864
  return {
@@ -11860,7 +11875,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11860
11875
  }
11861
11876
  });
11862
11877
  sdk.registerFunction({ id: "api::heal" }, async (req) => {
11863
- const denied = checkAuth$1(req, secret);
11878
+ const denied = checkAuth(req, secret);
11864
11879
  if (denied) return denied;
11865
11880
  const body = req.body;
11866
11881
  return {
@@ -11877,7 +11892,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11877
11892
  }
11878
11893
  });
11879
11894
  sdk.registerFunction({ id: "api::facet-tag" }, async (req) => {
11880
- const denied = checkAuth$1(req, secret);
11895
+ const denied = checkAuth(req, secret);
11881
11896
  if (denied) return denied;
11882
11897
  const body = req.body;
11883
11898
  if (!body?.targetId || !body?.dimension || !body?.value) return {
@@ -11898,7 +11913,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11898
11913
  }
11899
11914
  });
11900
11915
  sdk.registerFunction({ id: "api::facet-untag" }, async (req) => {
11901
- const denied = checkAuth$1(req, secret);
11916
+ const denied = checkAuth(req, secret);
11902
11917
  if (denied) return denied;
11903
11918
  const body = req.body;
11904
11919
  if (!body?.targetId || !body?.dimension) return {
@@ -11919,7 +11934,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11919
11934
  }
11920
11935
  });
11921
11936
  sdk.registerFunction({ id: "api::facet-query" }, async (req) => {
11922
- const denied = checkAuth$1(req, secret);
11937
+ const denied = checkAuth(req, secret);
11923
11938
  if (denied) return denied;
11924
11939
  const body = req.body;
11925
11940
  return {
@@ -11936,7 +11951,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11936
11951
  }
11937
11952
  });
11938
11953
  sdk.registerFunction({ id: "api::facet-get" }, async (req) => {
11939
- const denied = checkAuth$1(req, secret);
11954
+ const denied = checkAuth(req, secret);
11940
11955
  if (denied) return denied;
11941
11956
  const params = req.query_params || {};
11942
11957
  if (!params.targetId) return {
@@ -11957,7 +11972,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11957
11972
  }
11958
11973
  });
11959
11974
  sdk.registerFunction({ id: "api::facet-stats" }, async (req) => {
11960
- const denied = checkAuth$1(req, secret);
11975
+ const denied = checkAuth(req, secret);
11961
11976
  if (denied) return denied;
11962
11977
  const params = req.query_params || {};
11963
11978
  return {
@@ -11974,7 +11989,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11974
11989
  }
11975
11990
  });
11976
11991
  sdk.registerFunction({ id: "api::verify" }, async (req) => {
11977
- const denied = checkAuth$1(req, secret);
11992
+ const denied = checkAuth(req, secret);
11978
11993
  if (denied) return denied;
11979
11994
  const body = req.body;
11980
11995
  if (!body?.id || typeof body.id !== "string") return {
@@ -11995,7 +12010,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
11995
12010
  }
11996
12011
  });
11997
12012
  sdk.registerFunction({ id: "api::cascade-update" }, async (req) => {
11998
- const denied = checkAuth$1(req, secret);
12013
+ const denied = checkAuth(req, secret);
11999
12014
  if (denied) return denied;
12000
12015
  const body = req.body;
12001
12016
  if (!body?.supersededMemoryId || typeof body.supersededMemoryId !== "string") return {
@@ -12016,7 +12031,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
12016
12031
  }
12017
12032
  });
12018
12033
  sdk.registerFunction({ id: "api::lesson-save" }, async (req) => {
12019
- const denied = checkAuth$1(req, secret);
12034
+ const denied = checkAuth(req, secret);
12020
12035
  if (denied) return denied;
12021
12036
  const body = req.body;
12022
12037
  if (!body?.content || typeof body.content !== "string") return {
@@ -12046,7 +12061,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
12046
12061
  }
12047
12062
  });
12048
12063
  sdk.registerFunction({ id: "api::lesson-list" }, async (req) => {
12049
- const denied = checkAuth$1(req, secret);
12064
+ const denied = checkAuth(req, secret);
12050
12065
  if (denied) return denied;
12051
12066
  const params = req.query_params || {};
12052
12067
  return {
@@ -12068,7 +12083,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
12068
12083
  }
12069
12084
  });
12070
12085
  sdk.registerFunction({ id: "api::lesson-search" }, async (req) => {
12071
- const denied = checkAuth$1(req, secret);
12086
+ const denied = checkAuth(req, secret);
12072
12087
  if (denied) return denied;
12073
12088
  const body = req.body;
12074
12089
  if (!body?.query || typeof body.query !== "string") return {
@@ -12089,7 +12104,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
12089
12104
  }
12090
12105
  });
12091
12106
  sdk.registerFunction({ id: "api::lesson-strengthen" }, async (req) => {
12092
- const denied = checkAuth$1(req, secret);
12107
+ const denied = checkAuth(req, secret);
12093
12108
  if (denied) return denied;
12094
12109
  const body = req.body;
12095
12110
  if (!body?.lessonId || typeof body.lessonId !== "string") return {
@@ -12110,7 +12125,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
12110
12125
  }
12111
12126
  });
12112
12127
  sdk.registerFunction({ id: "api::obsidian-export" }, async (req) => {
12113
- const denied = checkAuth$1(req, secret);
12128
+ const denied = checkAuth(req, secret);
12114
12129
  if (denied) return denied;
12115
12130
  const body = req.body || {};
12116
12131
  const types = typeof body.types === "string" ? body.types.split(",").map((t) => t.trim()).filter(Boolean) : void 0;
@@ -12131,7 +12146,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
12131
12146
  }
12132
12147
  });
12133
12148
  sdk.registerFunction({ id: "api::reflect" }, async (req) => {
12134
- const denied = checkAuth$1(req, secret);
12149
+ const denied = checkAuth(req, secret);
12135
12150
  if (denied) return denied;
12136
12151
  const body = req.body || {};
12137
12152
  return {
@@ -12151,7 +12166,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
12151
12166
  }
12152
12167
  });
12153
12168
  sdk.registerFunction({ id: "api::insight-list" }, async (req) => {
12154
- const denied = checkAuth$1(req, secret);
12169
+ const denied = checkAuth(req, secret);
12155
12170
  if (denied) return denied;
12156
12171
  const params = req.query_params || {};
12157
12172
  return {
@@ -12172,7 +12187,7 @@ function registerApiTriggers(sdk, kv, secret, metricsStore, provider) {
12172
12187
  }
12173
12188
  });
12174
12189
  sdk.registerFunction({ id: "api::insight-search" }, async (req) => {
12175
- const denied = checkAuth$1(req, secret);
12190
+ const denied = checkAuth(req, secret);
12176
12191
  if (denied) return denied;
12177
12192
  const body = req.body;
12178
12193
  if (!body?.query || typeof body.query !== "string") return {
@@ -12253,925 +12268,6 @@ function registerEventTriggers(sdk, kv) {
12253
12268
  });
12254
12269
  }
12255
12270
 
12256
- //#endregion
12257
- //#region src/mcp/tools-registry.ts
12258
- const CORE_TOOLS = [
12259
- {
12260
- name: "memory_recall",
12261
- description: "Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.",
12262
- inputSchema: {
12263
- type: "object",
12264
- properties: {
12265
- query: {
12266
- type: "string",
12267
- description: "Search query (keywords, file names, concepts)"
12268
- },
12269
- limit: {
12270
- type: "number",
12271
- description: "Max results to return (default 10)"
12272
- }
12273
- },
12274
- required: ["query"]
12275
- }
12276
- },
12277
- {
12278
- name: "memory_save",
12279
- description: "Explicitly save an important insight, decision, or pattern to long-term memory.",
12280
- inputSchema: {
12281
- type: "object",
12282
- properties: {
12283
- content: {
12284
- type: "string",
12285
- description: "The insight or decision to remember"
12286
- },
12287
- type: {
12288
- type: "string",
12289
- description: "Memory type: pattern, preference, architecture, bug, workflow, or fact"
12290
- },
12291
- concepts: {
12292
- type: "string",
12293
- description: "Comma-separated key concepts"
12294
- },
12295
- files: {
12296
- type: "string",
12297
- description: "Comma-separated relevant file paths"
12298
- }
12299
- },
12300
- required: ["content"]
12301
- }
12302
- },
12303
- {
12304
- name: "memory_file_history",
12305
- description: "Get past observations about specific files.",
12306
- inputSchema: {
12307
- type: "object",
12308
- properties: {
12309
- files: {
12310
- type: "string",
12311
- description: "Comma-separated file paths"
12312
- },
12313
- sessionId: {
12314
- type: "string",
12315
- description: "Current session ID to exclude"
12316
- }
12317
- },
12318
- required: ["files"]
12319
- }
12320
- },
12321
- {
12322
- name: "memory_patterns",
12323
- description: "Detect recurring patterns across sessions.",
12324
- inputSchema: {
12325
- type: "object",
12326
- properties: { project: {
12327
- type: "string",
12328
- description: "Project path to analyze"
12329
- } }
12330
- }
12331
- },
12332
- {
12333
- name: "memory_sessions",
12334
- description: "List recent sessions with their status and observation counts.",
12335
- inputSchema: {
12336
- type: "object",
12337
- properties: {}
12338
- }
12339
- },
12340
- {
12341
- name: "memory_smart_search",
12342
- description: "Hybrid semantic+keyword search with progressive disclosure.",
12343
- inputSchema: {
12344
- type: "object",
12345
- properties: {
12346
- query: {
12347
- type: "string",
12348
- description: "Search query"
12349
- },
12350
- expandIds: {
12351
- type: "string",
12352
- description: "Comma-separated observation IDs to expand"
12353
- },
12354
- limit: {
12355
- type: "number",
12356
- description: "Max results (default 10)"
12357
- }
12358
- },
12359
- required: ["query"]
12360
- }
12361
- },
12362
- {
12363
- name: "memory_timeline",
12364
- description: "Chronological observations around an anchor point.",
12365
- inputSchema: {
12366
- type: "object",
12367
- properties: {
12368
- anchor: {
12369
- type: "string",
12370
- description: "Anchor point: ISO date or keyword"
12371
- },
12372
- project: {
12373
- type: "string",
12374
- description: "Filter by project path"
12375
- },
12376
- before: {
12377
- type: "number",
12378
- description: "Observations before anchor (default 5)"
12379
- },
12380
- after: {
12381
- type: "number",
12382
- description: "Observations after anchor (default 5)"
12383
- }
12384
- },
12385
- required: ["anchor"]
12386
- }
12387
- },
12388
- {
12389
- name: "memory_profile",
12390
- description: "User/project profile with top concepts and file patterns.",
12391
- inputSchema: {
12392
- type: "object",
12393
- properties: {
12394
- project: {
12395
- type: "string",
12396
- description: "Project path"
12397
- },
12398
- refresh: {
12399
- type: "string",
12400
- description: "Set to 'true' to force rebuild"
12401
- }
12402
- },
12403
- required: ["project"]
12404
- }
12405
- },
12406
- {
12407
- name: "memory_export",
12408
- description: "Export all memory data as JSON.",
12409
- inputSchema: {
12410
- type: "object",
12411
- properties: {}
12412
- }
12413
- },
12414
- {
12415
- name: "memory_relations",
12416
- description: "Query the memory relationship graph.",
12417
- inputSchema: {
12418
- type: "object",
12419
- properties: {
12420
- memoryId: {
12421
- type: "string",
12422
- description: "Memory ID to find relations for"
12423
- },
12424
- maxHops: {
12425
- type: "number",
12426
- description: "Max traversal depth (default 2)"
12427
- },
12428
- minConfidence: {
12429
- type: "number",
12430
- description: "Min confidence (0-1, default 0)"
12431
- }
12432
- },
12433
- required: ["memoryId"]
12434
- }
12435
- }
12436
- ];
12437
- const V040_TOOLS = [
12438
- {
12439
- name: "memory_claude_bridge_sync",
12440
- description: "Sync memory state to/from Claude Code's native MEMORY.md file.",
12441
- inputSchema: {
12442
- type: "object",
12443
- properties: { direction: {
12444
- type: "string",
12445
- description: "'read' to import from MEMORY.md, 'write' to export to MEMORY.md"
12446
- } },
12447
- required: ["direction"]
12448
- }
12449
- },
12450
- {
12451
- name: "memory_graph_query",
12452
- description: "Query the knowledge graph for entities and relationships.",
12453
- inputSchema: {
12454
- type: "object",
12455
- properties: {
12456
- startNodeId: {
12457
- type: "string",
12458
- description: "Starting node ID for traversal"
12459
- },
12460
- nodeType: {
12461
- type: "string",
12462
- description: "Filter by node type"
12463
- },
12464
- maxDepth: {
12465
- type: "number",
12466
- description: "Max BFS depth (default 3, max 5)"
12467
- },
12468
- query: {
12469
- type: "string",
12470
- description: "Search nodes by name"
12471
- }
12472
- }
12473
- }
12474
- },
12475
- {
12476
- name: "memory_consolidate",
12477
- description: "Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural).",
12478
- inputSchema: {
12479
- type: "object",
12480
- properties: { tier: {
12481
- type: "string",
12482
- description: "Target tier: episodic, semantic, or procedural"
12483
- } }
12484
- }
12485
- },
12486
- {
12487
- name: "memory_team_share",
12488
- description: "Share a memory or observation with team members.",
12489
- inputSchema: {
12490
- type: "object",
12491
- properties: {
12492
- itemId: {
12493
- type: "string",
12494
- description: "ID of memory or observation to share"
12495
- },
12496
- itemType: {
12497
- type: "string",
12498
- description: "Type: observation, memory, or pattern"
12499
- }
12500
- },
12501
- required: ["itemId", "itemType"]
12502
- }
12503
- },
12504
- {
12505
- name: "memory_team_feed",
12506
- description: "Get recent shared items from all team members.",
12507
- inputSchema: {
12508
- type: "object",
12509
- properties: { limit: {
12510
- type: "number",
12511
- description: "Max items (default 20)"
12512
- } }
12513
- }
12514
- },
12515
- {
12516
- name: "memory_audit",
12517
- description: "View the audit trail of memory operations.",
12518
- inputSchema: {
12519
- type: "object",
12520
- properties: {
12521
- operation: {
12522
- type: "string",
12523
- description: "Filter by operation type"
12524
- },
12525
- limit: {
12526
- type: "number",
12527
- description: "Max entries (default 50)"
12528
- }
12529
- }
12530
- }
12531
- },
12532
- {
12533
- name: "memory_governance_delete",
12534
- description: "Delete specific memories with audit trail.",
12535
- inputSchema: {
12536
- type: "object",
12537
- properties: {
12538
- memoryIds: {
12539
- type: "string",
12540
- description: "Comma-separated memory IDs to delete"
12541
- },
12542
- reason: {
12543
- type: "string",
12544
- description: "Reason for deletion"
12545
- }
12546
- },
12547
- required: ["memoryIds"]
12548
- }
12549
- },
12550
- {
12551
- name: "memory_snapshot_create",
12552
- description: "Create a git-versioned snapshot of current memory state.",
12553
- inputSchema: {
12554
- type: "object",
12555
- properties: { message: {
12556
- type: "string",
12557
- description: "Snapshot description"
12558
- } }
12559
- }
12560
- }
12561
- ];
12562
- const V050_TOOLS = [
12563
- {
12564
- name: "memory_action_create",
12565
- description: "Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other.",
12566
- inputSchema: {
12567
- type: "object",
12568
- properties: {
12569
- title: {
12570
- type: "string",
12571
- description: "Action title"
12572
- },
12573
- description: {
12574
- type: "string",
12575
- description: "Detailed description of the work"
12576
- },
12577
- priority: {
12578
- type: "number",
12579
- description: "Priority 1-10 (10 highest)"
12580
- },
12581
- project: {
12582
- type: "string",
12583
- description: "Project path"
12584
- },
12585
- tags: {
12586
- type: "string",
12587
- description: "Comma-separated tags"
12588
- },
12589
- parentId: {
12590
- type: "string",
12591
- description: "Parent action ID for hierarchical actions"
12592
- },
12593
- requires: {
12594
- type: "string",
12595
- description: "Comma-separated action IDs that must complete before this"
12596
- }
12597
- },
12598
- required: ["title"]
12599
- }
12600
- },
12601
- {
12602
- name: "memory_action_update",
12603
- description: "Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions.",
12604
- inputSchema: {
12605
- type: "object",
12606
- properties: {
12607
- actionId: {
12608
- type: "string",
12609
- description: "Action ID to update"
12610
- },
12611
- status: {
12612
- type: "string",
12613
- description: "New status: pending, active, done, blocked, cancelled"
12614
- },
12615
- result: {
12616
- type: "string",
12617
- description: "Outcome description (when completing)"
12618
- },
12619
- priority: {
12620
- type: "number",
12621
- description: "New priority 1-10"
12622
- }
12623
- },
12624
- required: ["actionId"]
12625
- }
12626
- },
12627
- {
12628
- name: "memory_frontier",
12629
- description: "Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies.",
12630
- inputSchema: {
12631
- type: "object",
12632
- properties: {
12633
- project: {
12634
- type: "string",
12635
- description: "Filter by project"
12636
- },
12637
- agentId: {
12638
- type: "string",
12639
- description: "Agent ID to check lease conflicts"
12640
- },
12641
- limit: {
12642
- type: "number",
12643
- description: "Max results (default 20)"
12644
- }
12645
- }
12646
- }
12647
- },
12648
- {
12649
- name: "memory_next",
12650
- description: "Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score.",
12651
- inputSchema: {
12652
- type: "object",
12653
- properties: {
12654
- project: {
12655
- type: "string",
12656
- description: "Filter by project"
12657
- },
12658
- agentId: {
12659
- type: "string",
12660
- description: "Current agent ID"
12661
- }
12662
- }
12663
- }
12664
- },
12665
- {
12666
- name: "memory_lease",
12667
- description: "Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing.",
12668
- inputSchema: {
12669
- type: "object",
12670
- properties: {
12671
- actionId: {
12672
- type: "string",
12673
- description: "Action ID"
12674
- },
12675
- agentId: {
12676
- type: "string",
12677
- description: "Agent claiming the action"
12678
- },
12679
- operation: {
12680
- type: "string",
12681
- description: "acquire, release, or renew"
12682
- },
12683
- result: {
12684
- type: "string",
12685
- description: "Result when releasing (marks action done)"
12686
- },
12687
- ttlMs: {
12688
- type: "number",
12689
- description: "Lease duration in ms (default 10min, max 1hr)"
12690
- }
12691
- },
12692
- required: [
12693
- "actionId",
12694
- "agentId",
12695
- "operation"
12696
- ]
12697
- }
12698
- },
12699
- {
12700
- name: "memory_routine_run",
12701
- description: "Instantiate a frozen workflow routine, creating actions for each step with proper dependencies.",
12702
- inputSchema: {
12703
- type: "object",
12704
- properties: {
12705
- routineId: {
12706
- type: "string",
12707
- description: "Routine template ID"
12708
- },
12709
- project: {
12710
- type: "string",
12711
- description: "Project context"
12712
- },
12713
- initiatedBy: {
12714
- type: "string",
12715
- description: "Agent starting the run"
12716
- }
12717
- },
12718
- required: ["routineId"]
12719
- }
12720
- },
12721
- {
12722
- name: "memory_signal_send",
12723
- description: "Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration.",
12724
- inputSchema: {
12725
- type: "object",
12726
- properties: {
12727
- from: {
12728
- type: "string",
12729
- description: "Sender agent ID"
12730
- },
12731
- to: {
12732
- type: "string",
12733
- description: "Recipient agent ID (omit for broadcast)"
12734
- },
12735
- content: {
12736
- type: "string",
12737
- description: "Message content"
12738
- },
12739
- type: {
12740
- type: "string",
12741
- description: "Message type: info, request, response, alert, handoff"
12742
- },
12743
- replyTo: {
12744
- type: "string",
12745
- description: "Signal ID to reply to (auto-threads)"
12746
- }
12747
- },
12748
- required: ["from", "content"]
12749
- }
12750
- },
12751
- {
12752
- name: "memory_signal_read",
12753
- description: "Read messages for an agent. Marks delivered messages as read.",
12754
- inputSchema: {
12755
- type: "object",
12756
- properties: {
12757
- agentId: {
12758
- type: "string",
12759
- description: "Agent to read messages for"
12760
- },
12761
- unreadOnly: {
12762
- type: "string",
12763
- description: "Set to 'true' for unread only"
12764
- },
12765
- threadId: {
12766
- type: "string",
12767
- description: "Filter by conversation thread"
12768
- },
12769
- limit: {
12770
- type: "number",
12771
- description: "Max messages (default 50)"
12772
- }
12773
- },
12774
- required: ["agentId"]
12775
- }
12776
- },
12777
- {
12778
- name: "memory_checkpoint",
12779
- description: "Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress.",
12780
- inputSchema: {
12781
- type: "object",
12782
- properties: {
12783
- operation: {
12784
- type: "string",
12785
- description: "create, resolve, or list"
12786
- },
12787
- name: {
12788
- type: "string",
12789
- description: "Checkpoint name (for create)"
12790
- },
12791
- checkpointId: {
12792
- type: "string",
12793
- description: "Checkpoint ID (for resolve)"
12794
- },
12795
- status: {
12796
- type: "string",
12797
- description: "passed or failed (for resolve)"
12798
- },
12799
- type: {
12800
- type: "string",
12801
- description: "Checkpoint type: ci, approval, deploy, external, timer"
12802
- },
12803
- linkedActionIds: {
12804
- type: "string",
12805
- description: "Comma-separated action IDs this checkpoint gates (for create)"
12806
- }
12807
- },
12808
- required: ["operation"]
12809
- }
12810
- },
12811
- {
12812
- name: "memory_mesh_sync",
12813
- description: "Sync memories and actions with peer agentmemory instances for multi-agent collaboration.",
12814
- inputSchema: {
12815
- type: "object",
12816
- properties: {
12817
- peerId: {
12818
- type: "string",
12819
- description: "Specific peer ID (omit for all)"
12820
- },
12821
- direction: {
12822
- type: "string",
12823
- description: "push, pull, or both (default both)"
12824
- }
12825
- }
12826
- }
12827
- }
12828
- ];
12829
- const V051_TOOLS = [
12830
- {
12831
- name: "memory_sentinel_create",
12832
- description: "Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered.",
12833
- inputSchema: {
12834
- type: "object",
12835
- properties: {
12836
- name: {
12837
- type: "string",
12838
- description: "Sentinel name"
12839
- },
12840
- type: {
12841
- type: "string",
12842
- description: "Type: webhook, timer, threshold, pattern, approval, custom"
12843
- },
12844
- config: {
12845
- type: "string",
12846
- description: "JSON config (timer: {durationMs}, threshold: {metric,operator,value}, pattern: {pattern}, webhook: {path})"
12847
- },
12848
- linkedActionIds: {
12849
- type: "string",
12850
- description: "Comma-separated action IDs to gate"
12851
- },
12852
- expiresInMs: {
12853
- type: "number",
12854
- description: "Auto-expire after ms"
12855
- }
12856
- },
12857
- required: ["name", "type"]
12858
- }
12859
- },
12860
- {
12861
- name: "memory_sentinel_trigger",
12862
- description: "Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions.",
12863
- inputSchema: {
12864
- type: "object",
12865
- properties: {
12866
- sentinelId: {
12867
- type: "string",
12868
- description: "Sentinel ID to trigger"
12869
- },
12870
- result: {
12871
- type: "string",
12872
- description: "JSON result payload"
12873
- }
12874
- },
12875
- required: ["sentinelId"]
12876
- }
12877
- },
12878
- {
12879
- name: "memory_sketch_create",
12880
- description: "Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded.",
12881
- inputSchema: {
12882
- type: "object",
12883
- properties: {
12884
- title: {
12885
- type: "string",
12886
- description: "Sketch title"
12887
- },
12888
- description: {
12889
- type: "string",
12890
- description: "What this sketch explores"
12891
- },
12892
- expiresInMs: {
12893
- type: "number",
12894
- description: "TTL in ms (default 1 hour)"
12895
- },
12896
- project: {
12897
- type: "string",
12898
- description: "Project context"
12899
- }
12900
- },
12901
- required: ["title"]
12902
- }
12903
- },
12904
- {
12905
- name: "memory_sketch_promote",
12906
- description: "Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official.",
12907
- inputSchema: {
12908
- type: "object",
12909
- properties: {
12910
- sketchId: {
12911
- type: "string",
12912
- description: "Sketch ID to promote"
12913
- },
12914
- project: {
12915
- type: "string",
12916
- description: "Override project for promoted actions"
12917
- }
12918
- },
12919
- required: ["sketchId"]
12920
- }
12921
- },
12922
- {
12923
- name: "memory_crystallize",
12924
- description: "Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons.",
12925
- inputSchema: {
12926
- type: "object",
12927
- properties: {
12928
- actionIds: {
12929
- type: "string",
12930
- description: "Comma-separated completed action IDs to crystallize"
12931
- },
12932
- project: {
12933
- type: "string",
12934
- description: "Project context"
12935
- },
12936
- sessionId: {
12937
- type: "string",
12938
- description: "Session context"
12939
- }
12940
- },
12941
- required: ["actionIds"]
12942
- }
12943
- },
12944
- {
12945
- name: "memory_diagnose",
12946
- description: "Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state.",
12947
- inputSchema: {
12948
- type: "object",
12949
- properties: { categories: {
12950
- type: "string",
12951
- description: "Comma-separated categories to check (default all)"
12952
- } }
12953
- }
12954
- },
12955
- {
12956
- name: "memory_heal",
12957
- description: "Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data.",
12958
- inputSchema: {
12959
- type: "object",
12960
- properties: {
12961
- categories: {
12962
- type: "string",
12963
- description: "Comma-separated categories to heal (default all)"
12964
- },
12965
- dryRun: {
12966
- type: "string",
12967
- description: "Set to 'true' for dry run (report but don't fix)"
12968
- }
12969
- }
12970
- }
12971
- },
12972
- {
12973
- name: "memory_facet_tag",
12974
- description: "Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.",
12975
- inputSchema: {
12976
- type: "object",
12977
- properties: {
12978
- targetId: {
12979
- type: "string",
12980
- description: "ID of the target to tag"
12981
- },
12982
- targetType: {
12983
- type: "string",
12984
- description: "Type: action, memory, or observation"
12985
- },
12986
- dimension: {
12987
- type: "string",
12988
- description: "Tag dimension (e.g., priority, team, status)"
12989
- },
12990
- value: {
12991
- type: "string",
12992
- description: "Tag value (e.g., urgent, backend, reviewed)"
12993
- }
12994
- },
12995
- required: [
12996
- "targetId",
12997
- "targetType",
12998
- "dimension",
12999
- "value"
13000
- ]
13001
- }
13002
- },
13003
- {
13004
- name: "memory_facet_query",
13005
- description: "Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.",
13006
- inputSchema: {
13007
- type: "object",
13008
- properties: {
13009
- matchAll: {
13010
- type: "string",
13011
- description: "Comma-separated dimension:value pairs (AND logic)"
13012
- },
13013
- matchAny: {
13014
- type: "string",
13015
- description: "Comma-separated dimension:value pairs (OR logic)"
13016
- },
13017
- targetType: {
13018
- type: "string",
13019
- description: "Filter by type: action, memory, or observation"
13020
- }
13021
- }
13022
- }
13023
- }
13024
- ];
13025
- const V061_TOOLS = [{
13026
- name: "memory_verify",
13027
- description: "Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores.",
13028
- inputSchema: {
13029
- type: "object",
13030
- properties: { id: {
13031
- type: "string",
13032
- description: "Memory ID or observation ID to verify"
13033
- } },
13034
- required: ["id"]
13035
- }
13036
- }];
13037
- const V070_TOOLS = [
13038
- {
13039
- name: "memory_lesson_save",
13040
- description: "Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson.",
13041
- inputSchema: {
13042
- type: "object",
13043
- properties: {
13044
- content: {
13045
- type: "string",
13046
- description: "The lesson learned (what worked, what to avoid, when to use X approach)"
13047
- },
13048
- context: {
13049
- type: "string",
13050
- description: "When/where this lesson applies"
13051
- },
13052
- confidence: {
13053
- type: "number",
13054
- description: "Initial confidence 0.0-1.0 (default 0.5)"
13055
- },
13056
- project: {
13057
- type: "string",
13058
- description: "Project this lesson is about"
13059
- },
13060
- tags: {
13061
- type: "string",
13062
- description: "Comma-separated tags"
13063
- }
13064
- },
13065
- required: ["content"]
13066
- }
13067
- },
13068
- {
13069
- name: "memory_lesson_recall",
13070
- description: "Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions.",
13071
- inputSchema: {
13072
- type: "object",
13073
- properties: {
13074
- query: {
13075
- type: "string",
13076
- description: "Search query"
13077
- },
13078
- project: {
13079
- type: "string",
13080
- description: "Filter by project"
13081
- },
13082
- minConfidence: {
13083
- type: "number",
13084
- description: "Minimum confidence threshold (default 0.1)"
13085
- },
13086
- limit: {
13087
- type: "number",
13088
- description: "Max results (default 10)"
13089
- }
13090
- },
13091
- required: ["query"]
13092
- }
13093
- },
13094
- {
13095
- name: "memory_obsidian_export",
13096
- description: "Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view.",
13097
- inputSchema: {
13098
- type: "object",
13099
- properties: {
13100
- vaultDir: {
13101
- type: "string",
13102
- description: "Output directory (default ~/.agentmemory/vault/)"
13103
- },
13104
- types: {
13105
- type: "string",
13106
- description: "Comma-separated types to export: memories,lessons,crystals,sessions (default all)"
13107
- }
13108
- }
13109
- }
13110
- }
13111
- ];
13112
- const V073_TOOLS = [{
13113
- name: "memory_reflect",
13114
- description: "Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights.",
13115
- inputSchema: {
13116
- type: "object",
13117
- properties: {
13118
- project: {
13119
- type: "string",
13120
- description: "Filter by project"
13121
- },
13122
- maxClusters: {
13123
- type: "number",
13124
- description: "Max concept clusters to process (default 10, max 20)"
13125
- }
13126
- }
13127
- }
13128
- }, {
13129
- name: "memory_insight_list",
13130
- description: "List synthesized insights — higher-order observations derived from patterns across memories, lessons, and crystals.",
13131
- inputSchema: {
13132
- type: "object",
13133
- properties: {
13134
- project: {
13135
- type: "string",
13136
- description: "Filter by project"
13137
- },
13138
- minConfidence: {
13139
- type: "number",
13140
- description: "Minimum confidence threshold (default 0)"
13141
- },
13142
- limit: {
13143
- type: "number",
13144
- description: "Max results (default 50)"
13145
- }
13146
- }
13147
- }
13148
- }];
13149
- const ESSENTIAL_TOOLS = new Set([
13150
- "memory_save",
13151
- "memory_recall",
13152
- "memory_consolidate",
13153
- "memory_smart_search",
13154
- "memory_sessions",
13155
- "memory_diagnose",
13156
- "memory_lesson_save",
13157
- "memory_reflect"
13158
- ]);
13159
- function getAllTools() {
13160
- return [
13161
- ...CORE_TOOLS,
13162
- ...V040_TOOLS,
13163
- ...V050_TOOLS,
13164
- ...V051_TOOLS,
13165
- ...V061_TOOLS,
13166
- ...V070_TOOLS,
13167
- ...V073_TOOLS
13168
- ];
13169
- }
13170
- function getVisibleTools() {
13171
- if ((process.env["AGENTMEMORY_TOOLS"] || "core") === "all") return getAllTools();
13172
- return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name));
13173
- }
13174
-
13175
12271
  //#endregion
13176
12272
  //#region src/mcp/server.ts
13177
12273
  function registerMcpEndpoints(sdk, kv, secret) {
@@ -14441,11 +13537,6 @@ function readBody(req) {
14441
13537
  req.on("error", reject);
14442
13538
  });
14443
13539
  }
14444
- function checkAuth(req, secret) {
14445
- if (!secret) return true;
14446
- const auth = req.headers["authorization"] || "";
14447
- return typeof auth === "string" && timingSafeCompare(auth, `Bearer ${secret}`);
14448
- }
14449
13540
  function startViewerServer(port, _kv, _sdk, secret, restPort) {
14450
13541
  const resolvedRestPort = restPort ?? port - 2;
14451
13542
  const server = createServer(async (req, res) => {
@@ -14463,32 +13554,20 @@ function startViewerServer(port, _kv, _sdk, secret, restPort) {
14463
13554
  return;
14464
13555
  }
14465
13556
  if (method === "GET" && (pathname === "/" || pathname === "/viewer" || pathname === "/agentmemory/viewer")) {
14466
- const base = dirname(fileURLToPath(import.meta.url));
14467
- const candidates = [
14468
- join(base, "index.html"),
14469
- join(base, "viewer", "index.html"),
14470
- join(base, "..", "viewer", "index.html"),
14471
- join(base, "..", "src", "viewer", "index.html"),
14472
- join(base, "..", "dist", "viewer", "index.html")
14473
- ];
14474
- for (const p of candidates) try {
14475
- const html = readFileSync(p, "utf-8");
13557
+ const rendered = renderViewerDocument();
13558
+ if (rendered.found) {
14476
13559
  res.writeHead(200, {
14477
13560
  "Content-Type": "text/html; charset=utf-8",
14478
- "Content-Security-Policy": VIEWER_CSP,
13561
+ "Content-Security-Policy": rendered.csp,
14479
13562
  "Cache-Control": "no-cache"
14480
13563
  });
14481
- res.end(html);
13564
+ res.end(rendered.html);
14482
13565
  return;
14483
- } catch {}
13566
+ }
14484
13567
  res.writeHead(404, { "Content-Type": "text/plain" });
14485
13568
  res.end("viewer not found");
14486
13569
  return;
14487
13570
  }
14488
- if (!checkAuth(req, secret)) {
14489
- json(res, 401, { error: "unauthorized" }, req);
14490
- return;
14491
- }
14492
13571
  try {
14493
13572
  await proxyToRestApi(resolvedRestPort, pathname, qs, method, req, res, secret);
14494
13573
  } catch (err) {
@@ -14746,7 +13825,7 @@ async function main() {
14746
13825
  registerRoutinesFunction(sdk, kv);
14747
13826
  registerSignalsFunction(sdk, kv);
14748
13827
  registerCheckpointsFunction(sdk, kv);
14749
- registerMeshFunction(sdk, kv);
13828
+ registerMeshFunction(sdk, kv, secret);
14750
13829
  registerBranchAwareFunction(sdk, kv);
14751
13830
  registerFlowCompressFunction(sdk, kv, provider);
14752
13831
  registerSentinelsFunction(sdk, kv);
@@ -14859,4 +13938,4 @@ main().catch((err) => {
14859
13938
 
14860
13939
  //#endregion
14861
13940
  export { };
14862
- //# sourceMappingURL=src-Df36IFVL.mjs.map
13941
+ //# sourceMappingURL=src-BuDB8dPq.mjs.map