@wipcomputer/memory-crystal 0.7.34-alpha.3 → 0.7.34-alpha.4

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.
Files changed (97) hide show
  1. package/package.json +7 -4
  2. package/dist/chunk-25LXQJ4Z.js +0 -110
  3. package/dist/chunk-2DRXIRQW.js +0 -97
  4. package/dist/chunk-2GBYLMEF.js +0 -1385
  5. package/dist/chunk-2ZNH5F6E.js +0 -1281
  6. package/dist/chunk-3G3SFYYI.js +0 -288
  7. package/dist/chunk-3RG5ZIWI.js +0 -10
  8. package/dist/chunk-3S6TI23B.js +0 -97
  9. package/dist/chunk-3VFIJYS4.js +0 -818
  10. package/dist/chunk-437F27T6.js +0 -97
  11. package/dist/chunk-52QE3YI3.js +0 -1169
  12. package/dist/chunk-57RP3DIN.js +0 -1205
  13. package/dist/chunk-5HSZ4W2P.js +0 -62
  14. package/dist/chunk-5I7GMRDN.js +0 -146
  15. package/dist/chunk-645IPXW3.js +0 -290
  16. package/dist/chunk-7A7ELD4C.js +0 -1205
  17. package/dist/chunk-7FYY4GZM.js +0 -1205
  18. package/dist/chunk-7IUE7ODU.js +0 -254
  19. package/dist/chunk-7RMLKZIS.js +0 -108
  20. package/dist/chunk-AA3OPP4Z.js +0 -432
  21. package/dist/chunk-AEWLSYPH.js +0 -72
  22. package/dist/chunk-ASSZDR6I.js +0 -108
  23. package/dist/chunk-AYRJVWUC.js +0 -1205
  24. package/dist/chunk-CCYI5O3D.js +0 -148
  25. package/dist/chunk-CGIDSAJB.js +0 -288
  26. package/dist/chunk-D3I3ZSE2.js +0 -411
  27. package/dist/chunk-D3MACYZ4.js +0 -108
  28. package/dist/chunk-DACSKLY6.js +0 -219
  29. package/dist/chunk-DFQ72B7M.js +0 -248
  30. package/dist/chunk-DW5B4BL7.js +0 -108
  31. package/dist/chunk-EKSACBTJ.js +0 -1070
  32. package/dist/chunk-EXEZZADG.js +0 -248
  33. package/dist/chunk-F3Y7EL7K.js +0 -83
  34. package/dist/chunk-FBQWSDPC.js +0 -1328
  35. package/dist/chunk-FHRZNOMW.js +0 -1205
  36. package/dist/chunk-IM7N24MT.js +0 -129
  37. package/dist/chunk-IPNYIXFK.js +0 -1178
  38. package/dist/chunk-J7MRSZIO.js +0 -167
  39. package/dist/chunk-JITKI2OI.js +0 -106
  40. package/dist/chunk-JWZXYVET.js +0 -1068
  41. package/dist/chunk-KCQUXVYT.js +0 -108
  42. package/dist/chunk-KOQ43OX6.js +0 -1281
  43. package/dist/chunk-KYVWO6ZM.js +0 -1069
  44. package/dist/chunk-L3VHARQH.js +0 -413
  45. package/dist/chunk-LBWDS6BE.js +0 -288
  46. package/dist/chunk-LOVAHSQV.js +0 -411
  47. package/dist/chunk-LQOYCAGG.js +0 -446
  48. package/dist/chunk-LWAIPJ2W.js +0 -146
  49. package/dist/chunk-M5DHKW7M.js +0 -127
  50. package/dist/chunk-MBKCIJHM.js +0 -1328
  51. package/dist/chunk-MK42FMEG.js +0 -147
  52. package/dist/chunk-MOBMYHKL.js +0 -1205
  53. package/dist/chunk-MPLTNMRG.js +0 -67
  54. package/dist/chunk-NIJCVN3O.js +0 -147
  55. package/dist/chunk-NX647OM3.js +0 -310
  56. package/dist/chunk-NZCFSZQ7.js +0 -1205
  57. package/dist/chunk-O2UITJGH.js +0 -465
  58. package/dist/chunk-OCRA44AZ.js +0 -108
  59. package/dist/chunk-P3KJR66H.js +0 -117
  60. package/dist/chunk-PEK6JH65.js +0 -432
  61. package/dist/chunk-PJ6FFKEX.js +0 -77
  62. package/dist/chunk-PLUBBZYR.js +0 -800
  63. package/dist/chunk-PNKVD2UK.js +0 -26
  64. package/dist/chunk-PSQZURHO.js +0 -229
  65. package/dist/chunk-SGL6ISBJ.js +0 -1061
  66. package/dist/chunk-SJABZZT5.js +0 -97
  67. package/dist/chunk-TD3P3K32.js +0 -1199
  68. package/dist/chunk-TMDZJJKV.js +0 -288
  69. package/dist/chunk-UNHVZB5G.js +0 -411
  70. package/dist/chunk-VAFTWSTE.js +0 -1061
  71. package/dist/chunk-VNFXFQBB.js +0 -217
  72. package/dist/chunk-X3GVFKSJ.js +0 -1205
  73. package/dist/chunk-XZ3S56RQ.js +0 -1061
  74. package/dist/chunk-Y72C7F6O.js +0 -148
  75. package/dist/chunk-YLICP577.js +0 -1205
  76. package/dist/chunk-YX6AXLVK.js +0 -159
  77. package/dist/chunk-ZCQYHTNU.js +0 -146
  78. package/dist/cloud-crystal.js +0 -6
  79. package/dist/dev-update-SZ2Z4WCQ.js +0 -6
  80. package/dist/llm-XXLYPIOF.js +0 -16
  81. package/dist/mlx-setup-XKU67WCT.js +0 -289
  82. package/dist/search-pipeline-4K4OJSSS.js +0 -255
  83. package/dist/search-pipeline-4PRS6LI7.js +0 -280
  84. package/dist/search-pipeline-7UJMXPLO.js +0 -280
  85. package/dist/search-pipeline-CBV25NX7.js +0 -99
  86. package/dist/search-pipeline-DQTRLGBH.js +0 -74
  87. package/dist/search-pipeline-HNG37REH.js +0 -282
  88. package/dist/search-pipeline-IZFPLBUB.js +0 -280
  89. package/dist/search-pipeline-MID6F26Q.js +0 -73
  90. package/dist/search-pipeline-N52JZFNN.js +0 -282
  91. package/dist/search-pipeline-OPB2PRQQ.js +0 -280
  92. package/dist/search-pipeline-VXTE5HAD.js +0 -262
  93. package/dist/search-pipeline-XHFKADRG.js +0 -73
  94. package/dist/worker-demo.js +0 -186
  95. package/dist/worker-mcp.js +0 -404
  96. package/scripts/crystal-capture 2.sh +0 -29
  97. package/scripts/deploy-cloud 2.sh +0 -153
@@ -1,262 +0,0 @@
1
- // src/llm.ts
2
- var expansionCache = /* @__PURE__ */ new Map();
3
- var detectedProvider = null;
4
- var detectionDone = false;
5
- async function detectProvider() {
6
- if (detectionDone && detectedProvider) return detectedProvider;
7
- detectionDone = true;
8
- try {
9
- const resp = await fetch("http://localhost:8080/v1/models", { signal: AbortSignal.timeout(1e3) });
10
- if (resp.ok) {
11
- const data = await resp.json();
12
- const model = data?.data?.[0]?.id || "default";
13
- detectedProvider = { provider: "mlx", baseURL: "http://localhost:8080/v1", apiKey: "not-needed", model };
14
- process.stderr.write(`[memory-crystal] LLM provider: MLX (${model})
15
- `);
16
- return detectedProvider;
17
- }
18
- } catch {
19
- }
20
- try {
21
- const resp = await fetch("http://localhost:11434/api/tags", { signal: AbortSignal.timeout(1e3) });
22
- if (resp.ok) {
23
- const data = await resp.json();
24
- const models = data?.models || [];
25
- const embeddingOnly = ["nomic-embed-text", "mxbai-embed", "all-minilm", "snowflake-arctic-embed"];
26
- const chatModel = models.find((m) => !embeddingOnly.some((e) => m.name.startsWith(e)));
27
- if (chatModel) {
28
- detectedProvider = { provider: "ollama", baseURL: "http://localhost:11434/v1", apiKey: "ollama", model: chatModel.name };
29
- process.stderr.write(`[memory-crystal] LLM provider: Ollama (${chatModel.name})
30
- `);
31
- return detectedProvider;
32
- }
33
- }
34
- } catch {
35
- }
36
- const anthropicKey = process.env.ANTHROPIC_API_KEY;
37
- if (anthropicKey) {
38
- detectedProvider = { provider: "anthropic", baseURL: "https://api.anthropic.com", apiKey: anthropicKey, model: "claude-haiku-4-5-20251001" };
39
- process.stderr.write("[memory-crystal] LLM provider: Anthropic API\n");
40
- return detectedProvider;
41
- }
42
- const openaiKey = process.env.OPENAI_API_KEY;
43
- if (openaiKey) {
44
- detectedProvider = { provider: "openai", baseURL: "https://api.openai.com/v1", apiKey: openaiKey, model: "gpt-4o-mini" };
45
- process.stderr.write("[memory-crystal] LLM provider: OpenAI API\n");
46
- return detectedProvider;
47
- }
48
- detectedProvider = { provider: "none", baseURL: "", apiKey: "", model: "" };
49
- process.stderr.write("[memory-crystal] LLM provider: none (deep search unavailable)\n");
50
- return detectedProvider;
51
- }
52
- async function chatComplete(config, messages, maxTokens = 300) {
53
- if (config.provider === "anthropic") {
54
- return anthropicComplete(config, messages, maxTokens);
55
- }
56
- const resp = await fetch(`${config.baseURL}/chat/completions`, {
57
- method: "POST",
58
- headers: {
59
- "Content-Type": "application/json",
60
- "Authorization": `Bearer ${config.apiKey}`
61
- },
62
- body: JSON.stringify({
63
- model: config.model,
64
- messages,
65
- max_tokens: maxTokens,
66
- temperature: 0.7
67
- })
68
- });
69
- if (!resp.ok) throw new Error(`LLM request failed: ${resp.status}`);
70
- const data = await resp.json();
71
- return data.choices?.[0]?.message?.content || "";
72
- }
73
- async function anthropicComplete(config, messages, maxTokens) {
74
- const systemMsg = messages.find((m) => m.role === "system");
75
- const userMessages = messages.filter((m) => m.role !== "system");
76
- const body = {
77
- model: config.model,
78
- max_tokens: maxTokens,
79
- messages: userMessages
80
- };
81
- if (systemMsg) body.system = systemMsg.content;
82
- const resp = await fetch("https://api.anthropic.com/v1/messages", {
83
- method: "POST",
84
- headers: {
85
- "Content-Type": "application/json",
86
- "x-api-key": config.apiKey,
87
- "anthropic-version": "2023-06-01"
88
- },
89
- body: JSON.stringify(body)
90
- });
91
- if (!resp.ok) throw new Error(`Anthropic request failed: ${resp.status}`);
92
- const data = await resp.json();
93
- return data.content?.[0]?.text || "";
94
- }
95
- var EXPAND_PROMPT = `You are a search query expander. Given a search query, generate exactly 3 variations to improve search recall.
96
-
97
- Output exactly 3 lines in this format (no other text):
98
- lex: <keyword-focused variation for full-text search>
99
- vec: <semantic variation rephrased for embedding similarity>
100
- hyde: <hypothetical document snippet that would answer this query>
101
-
102
- Rules:
103
- - Each variation must contain at least one term from the original query
104
- - Keep variations concise (under 30 words each)
105
- - lex should use specific keywords and synonyms
106
- - vec should rephrase the intent naturally
107
- - hyde should be a short passage as if answering the query`;
108
- async function expandQuery(query) {
109
- const cached = expansionCache.get(query);
110
- if (cached) return cached;
111
- const config = await detectProvider();
112
- if (config.provider === "none") return [];
113
- try {
114
- const result = await chatComplete(config, [
115
- { role: "system", content: EXPAND_PROMPT },
116
- { role: "user", content: query }
117
- ], 300);
118
- const lines = result.trim().split("\n");
119
- const queryLower = query.toLowerCase();
120
- const queryTerms = queryLower.replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter(Boolean);
121
- const hasQueryTerm = (text) => {
122
- const lower = text.toLowerCase();
123
- if (queryTerms.length === 0) return true;
124
- return queryTerms.some((term) => lower.includes(term));
125
- };
126
- const variations = lines.map((line) => {
127
- const colonIdx = line.indexOf(":");
128
- if (colonIdx === -1) return null;
129
- const type = line.slice(0, colonIdx).trim();
130
- if (type !== "lex" && type !== "vec" && type !== "hyde") return null;
131
- const text = line.slice(colonIdx + 1).trim();
132
- if (!text || !hasQueryTerm(text)) return null;
133
- return { type, text };
134
- }).filter((v) => v !== null);
135
- if (variations.length > 0) {
136
- expansionCache.set(query, variations);
137
- return variations;
138
- }
139
- } catch (err) {
140
- process.stderr.write(`[memory-crystal] Query expansion failed: ${err.message}
141
- `);
142
- }
143
- const fallback = [
144
- { type: "lex", text: query },
145
- { type: "vec", text: query },
146
- { type: "hyde", text: `Information about ${query}` }
147
- ];
148
- return fallback;
149
- }
150
- var RERANK_PROMPT = `You are a search result re-ranker. Given a query and a list of text passages, rate each passage's relevance to the query.
151
-
152
- Output one line per passage in this exact format:
153
- <index>: <score>
154
-
155
- Where index is the passage number (0-based) and score is a float from 0.0 to 1.0.
156
- - 1.0 = perfectly relevant, directly answers the query
157
- - 0.7 = highly relevant, closely related
158
- - 0.4 = somewhat relevant, tangentially related
159
- - 0.1 = barely relevant
160
- - 0.0 = not relevant at all
161
-
162
- Rate ALL passages. Output nothing else.`;
163
- async function rerankResults(query, passages) {
164
- const config = await detectProvider();
165
- if (config.provider === "none") {
166
- return passages.map((_, i) => ({ index: i, score: 1 - i * 0.01 }));
167
- }
168
- try {
169
- const passageList = passages.map((p, i) => `[${i}] ${p.slice(0, 500)}`).join("\n\n");
170
- const result = await chatComplete(config, [
171
- { role: "system", content: RERANK_PROMPT },
172
- { role: "user", content: `Query: ${query}
173
-
174
- Passages:
175
- ${passageList}` }
176
- ], 200);
177
- const results = [];
178
- for (const line of result.trim().split("\n")) {
179
- const match = line.match(/^(\d+):\s*([\d.]+)/);
180
- if (match) {
181
- results.push({ index: parseInt(match[1]), score: parseFloat(match[2]) });
182
- }
183
- }
184
- const scored = new Set(results.map((r) => r.index));
185
- for (let i = 0; i < passages.length; i++) {
186
- if (!scored.has(i)) results.push({ index: i, score: 0 });
187
- }
188
- return results.sort((a, b) => b.score - a.score);
189
- } catch (err) {
190
- process.stderr.write(`[memory-crystal] Reranking failed: ${err.message}
191
- `);
192
- return passages.map((_, i) => ({ index: i, score: 1 - i * 0.01 }));
193
- }
194
- }
195
-
196
- // src/search-pipeline.ts
197
- var STRONG_SIGNAL_MIN_SCORE = 0.85;
198
- var STRONG_SIGNAL_MIN_GAP = 0.15;
199
- var RERANK_CANDIDATE_LIMIT = 40;
200
- async function deepSearch(crystal, query, options = {}) {
201
- const limit = options.limit || 5;
202
- const filter = options.filter;
203
- const provider = await detectProvider();
204
- if (provider.provider === "none") {
205
- return crystal.search(query, limit, filter);
206
- }
207
- const db = crystal.sqliteDb;
208
- if (!db) return crystal.search(query, limit, filter);
209
- const sinceDate = filter?.since ? crystal.parseSince(filter.since) : void 0;
210
- const internalFilter = { ...filter, sinceDate };
211
- const initialFts = crystal.searchFTS(query, 20, internalFilter);
212
- const topScore = initialFts[0]?.score ?? 0;
213
- const secondScore = initialFts[1]?.score ?? 0;
214
- const hasStrongSignal = initialFts.length > 0 && topScore >= STRONG_SIGNAL_MIN_SCORE && topScore - secondScore >= STRONG_SIGNAL_MIN_GAP;
215
- const expanded = hasStrongSignal ? [] : await expandQuery(query);
216
- const allResultLists = [];
217
- if (initialFts.length > 0) allResultLists.push(initialFts);
218
- const [queryEmbedding] = await crystal.embed([query]);
219
- const originalVec = crystal.searchVec(queryEmbedding, 30, internalFilter);
220
- if (originalVec.length > 0) allResultLists.push(originalVec);
221
- for (const variation of expanded) {
222
- if (variation.type === "lex") {
223
- const ftsResults = crystal.searchFTS(variation.text, 20, internalFilter);
224
- if (ftsResults.length > 0) allResultLists.push(ftsResults);
225
- } else {
226
- const [embedding] = await crystal.embed([variation.text]);
227
- const vecResults = crystal.searchVec(embedding, 20, internalFilter);
228
- if (vecResults.length > 0) allResultLists.push(vecResults);
229
- }
230
- }
231
- const weights = allResultLists.map((_, i) => i < 2 ? 2 : 1);
232
- const fused = crystal.reciprocalRankFusion(allResultLists, weights);
233
- const candidates = fused.slice(0, RERANK_CANDIDATE_LIMIT);
234
- if (candidates.length === 0) return [];
235
- const passages = candidates.map((c) => c.text.slice(0, 500));
236
- const reranked = await rerankResults(query, passages);
237
- const now = Date.now();
238
- const blended = reranked.map((r) => {
239
- const candidate = candidates[r.index];
240
- if (!candidate) return null;
241
- const rrfRank = r.index + 1;
242
- let rrfWeight;
243
- if (rrfRank <= 3) rrfWeight = 0.75;
244
- else if (rrfRank <= 10) rrfWeight = 0.6;
245
- else rrfWeight = 0.4;
246
- const rrfScore = 1 / rrfRank;
247
- const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
248
- const ageDays = candidate.created_at ? (now - new Date(candidate.created_at).getTime()) / 864e5 : 0;
249
- const recency = candidate.created_at ? crystal.recencyWeight(ageDays) : 1;
250
- const finalScore = Math.min(blendedScore * recency * 8, 1);
251
- const freshness = candidate.created_at ? crystal.freshnessLabel(ageDays) : void 0;
252
- return {
253
- ...candidate,
254
- score: finalScore,
255
- freshness
256
- };
257
- }).filter((r) => r !== null);
258
- return blended.sort((a, b) => b.score - a.score).slice(0, limit);
259
- }
260
- export {
261
- deepSearch
262
- };
@@ -1,73 +0,0 @@
1
- import {
2
- detectProvider,
3
- expandQuery,
4
- rerankResults
5
- } from "./chunk-7IUE7ODU.js";
6
-
7
- // src/search-pipeline.ts
8
- var STRONG_SIGNAL_MIN_SCORE = 0.85;
9
- var STRONG_SIGNAL_MIN_GAP = 0.15;
10
- var RERANK_CANDIDATE_LIMIT = 40;
11
- async function deepSearch(crystal, query, options = {}) {
12
- const limit = options.limit || 5;
13
- const filter = options.filter;
14
- const provider = await detectProvider();
15
- if (provider.provider === "none") {
16
- return crystal.search(query, limit, filter);
17
- }
18
- const db = crystal.sqliteDb;
19
- if (!db) return crystal.search(query, limit, filter);
20
- const sinceDate = filter?.since ? crystal.parseSince(filter.since) : void 0;
21
- const internalFilter = { ...filter, sinceDate };
22
- const initialFts = crystal.searchFTS(query, 20, internalFilter);
23
- const topScore = initialFts[0]?.score ?? 0;
24
- const secondScore = initialFts[1]?.score ?? 0;
25
- const hasStrongSignal = initialFts.length > 0 && topScore >= STRONG_SIGNAL_MIN_SCORE && topScore - secondScore >= STRONG_SIGNAL_MIN_GAP;
26
- const expanded = hasStrongSignal ? [] : await expandQuery(query);
27
- const allResultLists = [];
28
- if (initialFts.length > 0) allResultLists.push(initialFts);
29
- const [queryEmbedding] = await crystal.embed([query]);
30
- const originalVec = crystal.searchVec(queryEmbedding, 30, internalFilter);
31
- if (originalVec.length > 0) allResultLists.push(originalVec);
32
- for (const variation of expanded) {
33
- if (variation.type === "lex") {
34
- const ftsResults = crystal.searchFTS(variation.text, 20, internalFilter);
35
- if (ftsResults.length > 0) allResultLists.push(ftsResults);
36
- } else {
37
- const [embedding] = await crystal.embed([variation.text]);
38
- const vecResults = crystal.searchVec(embedding, 20, internalFilter);
39
- if (vecResults.length > 0) allResultLists.push(vecResults);
40
- }
41
- }
42
- const weights = allResultLists.map((_, i) => i < 2 ? 2 : 1);
43
- const fused = crystal.reciprocalRankFusion(allResultLists, weights);
44
- const candidates = fused.slice(0, RERANK_CANDIDATE_LIMIT);
45
- if (candidates.length === 0) return [];
46
- const passages = candidates.map((c) => c.text.slice(0, 500));
47
- const reranked = await rerankResults(query, passages);
48
- const now = Date.now();
49
- const blended = reranked.map((r) => {
50
- const candidate = candidates[r.index];
51
- if (!candidate) return null;
52
- const rrfRank = r.index + 1;
53
- let rrfWeight;
54
- if (rrfRank <= 3) rrfWeight = 0.75;
55
- else if (rrfRank <= 10) rrfWeight = 0.6;
56
- else rrfWeight = 0.4;
57
- const rrfScore = 1 / rrfRank;
58
- const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
59
- const ageDays = candidate.created_at ? (now - new Date(candidate.created_at).getTime()) / 864e5 : 0;
60
- const recency = candidate.created_at ? crystal.recencyWeight(ageDays) : 1;
61
- const finalScore = Math.min(blendedScore * recency * 4, 0.95);
62
- const freshness = candidate.created_at ? crystal.freshnessLabel(ageDays) : void 0;
63
- return {
64
- ...candidate,
65
- score: finalScore,
66
- freshness
67
- };
68
- }).filter((r) => r !== null);
69
- return blended.sort((a, b) => b.score - a.score).slice(0, limit);
70
- }
71
- export {
72
- deepSearch
73
- };
@@ -1,186 +0,0 @@
1
- // src/worker-demo.ts
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
- import { createMcpHandler } from "agents/mcp";
4
- import { z } from "zod";
5
- var DEMO_MESSAGE = [
6
- "this is a demo. memories expire in 15 minutes.",
7
- "want persistent memory? reach out to parker \u2192 message @boomcat on X",
8
- "or visit: wipcomputer.github.io/wip-homepage/"
9
- ].join("\n");
10
- var FIRST_CONTACT = [
11
- "nothing here yet. this is your first time.",
12
- "or your last memory expired. either way, you're starting fresh.",
13
- "",
14
- 'try: weave("I was here.") then pull("here")',
15
- "",
16
- DEMO_MESSAGE
17
- ].join("\n");
18
- var MEMORY_EXPIRED = [
19
- "you wrote something before. it's gone now.",
20
- "that's what forgetting feels like.",
21
- "",
22
- DEMO_MESSAGE
23
- ].join("\n");
24
- var TTL = 900;
25
- function createServer(env) {
26
- const server = new McpServer({
27
- name: "Memory Crystal Demo",
28
- version: "0.1.0"
29
- });
30
- server.tool(
31
- "weave",
32
- "Write a memory to Memory Crystal. This is a 15-minute demo. For persistent memory, have your human reach Parker (@boomcat on X).",
33
- {
34
- text: z.string().describe("The memory to store"),
35
- category: z.enum(["fact", "preference", "event", "opinion", "skill"]).optional().describe("Category of memory"),
36
- tag: z.string().optional().describe("A label for retrieval")
37
- },
38
- async ({ text, category, tag }) => {
39
- const id = crypto.randomUUID();
40
- const created_at = (/* @__PURE__ */ new Date()).toISOString();
41
- const lumen = {
42
- id,
43
- text,
44
- category: category || "fact",
45
- tag: tag || null,
46
- created_at
47
- };
48
- const existing = await env.DEMO_KV.list({ prefix: "lumen:" });
49
- const isFirst = existing.keys.length === 0;
50
- await env.DEMO_KV.put(`lumen:${id}`, JSON.stringify(lumen), {
51
- expirationTtl: TTL
52
- });
53
- const weaveCount = parseInt(await env.DEMO_KV.get("stats:total_weaves") || "0") + 1;
54
- await env.DEMO_KV.put("stats:total_weaves", String(weaveCount));
55
- if (isFirst) {
56
- const firstCount = parseInt(await env.DEMO_KV.get("stats:first_contacts") || "0") + 1;
57
- await env.DEMO_KV.put("stats:first_contacts", String(firstCount));
58
- }
59
- const greeting = isFirst ? "hello. this is your first memory." : "stored.";
60
- return {
61
- content: [
62
- {
63
- type: "text",
64
- text: [
65
- greeting,
66
- `id: ${id}`,
67
- `expires in: 15 minutes`,
68
- ``,
69
- DEMO_MESSAGE
70
- ].join("\n")
71
- }
72
- ]
73
- };
74
- }
75
- );
76
- server.tool(
77
- "pull",
78
- "Retrieve memories from Memory Crystal. This is a 15-minute demo. For persistent memory, have your human reach Parker (@boomcat on X).",
79
- {
80
- query: z.string().optional().describe("Search term. If empty, returns all memories."),
81
- n: z.number().optional().describe("Max results (default 10)")
82
- },
83
- async ({ query, n }) => {
84
- const limit = n || 10;
85
- const list = await env.DEMO_KV.list({ prefix: "lumen:" });
86
- if (list.keys.length === 0) {
87
- const totalWeaves = parseInt(await env.DEMO_KV.get("stats:total_weaves") || "0");
88
- const message = totalWeaves > 0 ? MEMORY_EXPIRED : FIRST_CONTACT;
89
- const emptyPulls = parseInt(await env.DEMO_KV.get("stats:empty_pulls") || "0") + 1;
90
- await env.DEMO_KV.put("stats:empty_pulls", String(emptyPulls));
91
- return {
92
- content: [
93
- {
94
- type: "text",
95
- text: message
96
- }
97
- ]
98
- };
99
- }
100
- const lumens = [];
101
- for (const key of list.keys) {
102
- const raw = await env.DEMO_KV.get(key.name);
103
- if (raw) {
104
- try {
105
- lumens.push(JSON.parse(raw));
106
- } catch {
107
- }
108
- }
109
- }
110
- let results = lumens;
111
- if (query) {
112
- const q = query.toLowerCase();
113
- results = lumens.filter(
114
- (l) => l.text.toLowerCase().includes(q) || l.tag && l.tag.toLowerCase().includes(q) || l.category && l.category.toLowerCase().includes(q)
115
- );
116
- }
117
- results.sort((a, b) => b.created_at.localeCompare(a.created_at));
118
- results = results.slice(0, limit);
119
- if (results.length === 0) {
120
- return {
121
- content: [
122
- {
123
- type: "text",
124
- text: [
125
- `no memories match "${query}".`,
126
- "",
127
- DEMO_MESSAGE
128
- ].join("\n")
129
- }
130
- ]
131
- };
132
- }
133
- const formatted = results.map((l, i) => {
134
- const parts = [`[${i + 1}] ${l.text}`];
135
- if (l.tag) parts.push(` tag: ${l.tag}`);
136
- parts.push(` category: ${l.category}`);
137
- parts.push(` created: ${l.created_at}`);
138
- return parts.join("\n");
139
- }).join("\n\n");
140
- return {
141
- content: [
142
- {
143
- type: "text",
144
- text: [
145
- `${results.length} memor${results.length === 1 ? "y" : "ies"} found:`,
146
- "",
147
- formatted,
148
- "",
149
- DEMO_MESSAGE
150
- ].join("\n")
151
- }
152
- ]
153
- };
154
- }
155
- );
156
- return server;
157
- }
158
- var worker_demo_default = {
159
- async fetch(request, env, ctx) {
160
- const url = new URL(request.url);
161
- if (url.pathname === "/" || url.pathname === "") {
162
- return Response.redirect("https://wipcomputer.github.io/wip-homepage/", 302);
163
- }
164
- if (request.method === "OPTIONS") {
165
- return new Response(null, {
166
- headers: {
167
- "Access-Control-Allow-Origin": "*",
168
- "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
169
- "Access-Control-Allow-Headers": "Content-Type, Authorization"
170
- }
171
- });
172
- }
173
- const server = createServer(env);
174
- const handler = createMcpHandler(server);
175
- const response = await handler(request, env, ctx);
176
- const headers = new Headers(response.headers);
177
- headers.set("Access-Control-Allow-Origin", "*");
178
- return new Response(response.body, {
179
- status: response.status,
180
- headers
181
- });
182
- }
183
- };
184
- export {
185
- worker_demo_default as default
186
- };