@wipcomputer/memory-crystal 0.7.32 → 0.7.34-alpha.1

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 (155) hide show
  1. package/SKILL.md +1 -1
  2. package/cloud/wrangler.toml +30 -0
  3. package/dist/bridge.d.ts +7 -0
  4. package/dist/bridge.js +14 -0
  5. package/dist/bulk-copy.d.ts +17 -0
  6. package/dist/bulk-copy.js +90 -0
  7. package/dist/cc-hook.d.ts +8 -0
  8. package/dist/cc-hook.js +368 -0
  9. package/dist/cc-poller.d.ts +1 -0
  10. package/dist/cc-poller.js +550 -0
  11. package/dist/chunk-25LXQJ4Z.js +110 -0
  12. package/dist/chunk-2DRXIRQW.js +97 -0
  13. package/dist/chunk-2GBYLMEF.js +1385 -0
  14. package/dist/chunk-2ZNH5F6E.js +1281 -0
  15. package/dist/chunk-3G3SFYYI.js +288 -0
  16. package/dist/chunk-3RG5ZIWI.js +10 -0
  17. package/dist/chunk-3S6TI23B.js +97 -0
  18. package/dist/chunk-3VFIJYS4.js +818 -0
  19. package/dist/chunk-437F27T6.js +97 -0
  20. package/dist/chunk-52QE3YI3.js +1169 -0
  21. package/dist/chunk-57RP3DIN.js +1205 -0
  22. package/dist/chunk-5HSZ4W2P.js +62 -0
  23. package/dist/chunk-5I7GMRDN.js +146 -0
  24. package/dist/chunk-645IPXW3.js +290 -0
  25. package/dist/chunk-7A7ELD4C.js +1205 -0
  26. package/dist/chunk-7FYY4GZM.js +1205 -0
  27. package/dist/chunk-7IUE7ODU.js +254 -0
  28. package/dist/chunk-7RMLKZIS.js +108 -0
  29. package/dist/chunk-AA3OPP4Z.js +432 -0
  30. package/dist/chunk-AEWLSYPH.js +72 -0
  31. package/dist/chunk-ASSZDR6I.js +108 -0
  32. package/dist/chunk-AYRJVWUC.js +1205 -0
  33. package/dist/chunk-CCYI5O3D.js +148 -0
  34. package/dist/chunk-CGIDSAJB.js +288 -0
  35. package/dist/chunk-D3I3ZSE2.js +411 -0
  36. package/dist/chunk-D3MACYZ4.js +108 -0
  37. package/dist/chunk-DACSKLY6.js +219 -0
  38. package/dist/chunk-DFQ72B7M.js +248 -0
  39. package/dist/chunk-DW5B4BL7.js +108 -0
  40. package/dist/chunk-EKSACBTJ.js +1070 -0
  41. package/dist/chunk-EXEZZADG.js +248 -0
  42. package/dist/chunk-F3Y7EL7K.js +83 -0
  43. package/dist/chunk-FBQWSDPC.js +1328 -0
  44. package/dist/chunk-FHRZNOMW.js +1205 -0
  45. package/dist/chunk-IM7N24MT.js +129 -0
  46. package/dist/chunk-IPNYIXFK.js +1178 -0
  47. package/dist/chunk-J7MRSZIO.js +167 -0
  48. package/dist/chunk-JITKI2OI.js +106 -0
  49. package/dist/chunk-JWZXYVET.js +1068 -0
  50. package/dist/chunk-KCQUXVYT.js +108 -0
  51. package/dist/chunk-KOQ43OX6.js +1281 -0
  52. package/dist/chunk-KYVWO6ZM.js +1069 -0
  53. package/dist/chunk-L3VHARQH.js +413 -0
  54. package/dist/chunk-LBWDS6BE.js +288 -0
  55. package/dist/chunk-LOVAHSQV.js +411 -0
  56. package/dist/chunk-LQOYCAGG.js +446 -0
  57. package/dist/chunk-LWAIPJ2W.js +146 -0
  58. package/dist/chunk-M5DHKW7M.js +127 -0
  59. package/dist/chunk-MBKCIJHM.js +1328 -0
  60. package/dist/chunk-MK42FMEG.js +147 -0
  61. package/dist/chunk-MOBMYHKL.js +1205 -0
  62. package/dist/chunk-MPLTNMRG.js +67 -0
  63. package/dist/chunk-NIJCVN3O.js +147 -0
  64. package/dist/chunk-NX647OM3.js +310 -0
  65. package/dist/chunk-NZCFSZQ7.js +1205 -0
  66. package/dist/chunk-O2UITJGH.js +465 -0
  67. package/dist/chunk-OCRA44AZ.js +108 -0
  68. package/dist/chunk-P3KJR66H.js +117 -0
  69. package/dist/chunk-PEK6JH65.js +432 -0
  70. package/dist/chunk-PJ6FFKEX.js +77 -0
  71. package/dist/chunk-PLUBBZYR.js +800 -0
  72. package/dist/chunk-PNKVD2UK.js +26 -0
  73. package/dist/chunk-PSQZURHO.js +229 -0
  74. package/dist/chunk-SGL6ISBJ.js +1061 -0
  75. package/dist/chunk-SJABZZT5.js +97 -0
  76. package/dist/chunk-TD3P3K32.js +1199 -0
  77. package/dist/chunk-TMDZJJKV.js +288 -0
  78. package/dist/chunk-UNHVZB5G.js +411 -0
  79. package/dist/chunk-VAFTWSTE.js +1061 -0
  80. package/dist/chunk-VNFXFQBB.js +217 -0
  81. package/dist/chunk-X3GVFKSJ.js +1205 -0
  82. package/dist/chunk-XZ3S56RQ.js +1061 -0
  83. package/dist/chunk-Y72C7F6O.js +148 -0
  84. package/dist/chunk-YLICP577.js +1205 -0
  85. package/dist/chunk-YX6AXLVK.js +159 -0
  86. package/dist/chunk-ZCQYHTNU.js +146 -0
  87. package/dist/cli.d.ts +1 -0
  88. package/dist/cli.js +1160 -0
  89. package/dist/cloud-crystal.js +6 -0
  90. package/dist/core.d.ts +252 -0
  91. package/dist/core.js +12 -0
  92. package/dist/crypto.d.ts +20 -0
  93. package/dist/crypto.js +27 -0
  94. package/dist/crystal-capture.sh +29 -0
  95. package/dist/crystal-serve.d.ts +4 -0
  96. package/dist/crystal-serve.js +252 -0
  97. package/dist/dev-update-SZ2Z4WCQ.js +6 -0
  98. package/dist/discover.d.ts +30 -0
  99. package/dist/discover.js +177 -0
  100. package/dist/doctor.d.ts +9 -0
  101. package/dist/doctor.js +342 -0
  102. package/dist/dream-weaver.d.ts +8 -0
  103. package/dist/dream-weaver.js +56 -0
  104. package/dist/file-sync.d.ts +48 -0
  105. package/dist/file-sync.js +18 -0
  106. package/dist/installer.d.ts +61 -0
  107. package/dist/installer.js +772 -0
  108. package/dist/ldm-backup.sh +116 -0
  109. package/dist/ldm.d.ts +50 -0
  110. package/dist/ldm.js +32 -0
  111. package/dist/llm-XXLYPIOF.js +16 -0
  112. package/dist/mcp-server.d.ts +1 -0
  113. package/dist/mcp-server.js +277 -0
  114. package/dist/migrate.d.ts +1 -0
  115. package/dist/migrate.js +89 -0
  116. package/dist/mirror-sync.d.ts +1 -0
  117. package/dist/mirror-sync.js +159 -0
  118. package/dist/mlx-setup-XKU67WCT.js +289 -0
  119. package/dist/oc-backfill.d.ts +19 -0
  120. package/dist/oc-backfill.js +74 -0
  121. package/dist/openclaw.d.ts +5 -0
  122. package/dist/openclaw.js +434 -0
  123. package/dist/pair.d.ts +4 -0
  124. package/dist/pair.js +75 -0
  125. package/dist/poller.d.ts +1 -0
  126. package/dist/poller.js +634 -0
  127. package/dist/role.d.ts +24 -0
  128. package/dist/role.js +13 -0
  129. package/dist/search-pipeline-4K4OJSSS.js +255 -0
  130. package/dist/search-pipeline-4PRS6LI7.js +280 -0
  131. package/dist/search-pipeline-7UJMXPLO.js +280 -0
  132. package/dist/search-pipeline-CBV25NX7.js +99 -0
  133. package/dist/search-pipeline-DQTRLGBH.js +74 -0
  134. package/dist/search-pipeline-HNG37REH.js +282 -0
  135. package/dist/search-pipeline-IZFPLBUB.js +280 -0
  136. package/dist/search-pipeline-MID6F26Q.js +73 -0
  137. package/dist/search-pipeline-N52JZFNN.js +282 -0
  138. package/dist/search-pipeline-OPB2PRQQ.js +280 -0
  139. package/dist/search-pipeline-VXTE5HAD.js +262 -0
  140. package/dist/search-pipeline-XHFKADRG.js +73 -0
  141. package/dist/staging.d.ts +29 -0
  142. package/dist/staging.js +21 -0
  143. package/dist/summarize.d.ts +19 -0
  144. package/dist/summarize.js +10 -0
  145. package/dist/worker-demo.js +186 -0
  146. package/dist/worker-mcp.js +404 -0
  147. package/dist/worker.js +137 -0
  148. package/package.json +15 -1
  149. package/.env.example +0 -20
  150. package/.publish-skill.json +0 -1
  151. package/CHANGELOG.md +0 -1372
  152. package/README-ENTERPRISE.md +0 -226
  153. package/RELAY.md +0 -199
  154. package/wrangler-demo.toml +0 -8
  155. package/wrangler-mcp.toml +0 -24
@@ -0,0 +1,404 @@
1
+ import {
2
+ CloudCrystal
3
+ } from "./chunk-J7MRSZIO.js";
4
+
5
+ // src/worker-mcp.ts
6
+ function json(data, status = 200, headers = {}) {
7
+ return new Response(JSON.stringify(data), {
8
+ status,
9
+ headers: { "Content-Type": "application/json", ...headers }
10
+ });
11
+ }
12
+ function cors(response) {
13
+ const headers = new Headers(response.headers);
14
+ headers.set("Access-Control-Allow-Origin", "*");
15
+ headers.set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
16
+ headers.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
17
+ return new Response(response.body, { status: response.status, headers });
18
+ }
19
+ async function sha256(input) {
20
+ const encoded = new TextEncoder().encode(input);
21
+ const hash = await crypto.subtle.digest("SHA-256", encoded);
22
+ return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, "0")).join("");
23
+ }
24
+ async function sha256Base64url(input) {
25
+ const encoded = new TextEncoder().encode(input);
26
+ const hash = await crypto.subtle.digest("SHA-256", encoded);
27
+ const bytes = new Uint8Array(hash);
28
+ return btoa(String.fromCharCode.apply(null, Array.from(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
29
+ }
30
+ function generateToken() {
31
+ const bytes = new Uint8Array(32);
32
+ crypto.getRandomValues(bytes);
33
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
34
+ }
35
+ function handleProtectedResourceMetadata(url) {
36
+ return json({
37
+ resource: url.origin,
38
+ authorization_servers: [url.origin],
39
+ bearer_methods_supported: ["header"]
40
+ });
41
+ }
42
+ function handleAuthServerMetadata(url) {
43
+ return json({
44
+ issuer: url.origin,
45
+ authorization_endpoint: `${url.origin}/oauth/authorize`,
46
+ token_endpoint: `${url.origin}/oauth/token`,
47
+ registration_endpoint: `${url.origin}/oauth/register`,
48
+ response_types_supported: ["code"],
49
+ grant_types_supported: ["authorization_code"],
50
+ code_challenge_methods_supported: ["S256"],
51
+ token_endpoint_auth_methods_supported: ["none"],
52
+ scopes_supported: ["memory"]
53
+ });
54
+ }
55
+ async function handleRegister(request, env) {
56
+ const body = await request.json();
57
+ if (!body.redirect_uris?.length) {
58
+ return json({ error: "redirect_uris required" }, 400);
59
+ }
60
+ const clientId = crypto.randomUUID();
61
+ await env.DB.prepare(`
62
+ INSERT INTO oauth_clients (client_id, redirect_uris, client_name)
63
+ VALUES (?, ?, ?)
64
+ `).bind(clientId, JSON.stringify(body.redirect_uris), body.client_name || "").run();
65
+ return json({
66
+ client_id: clientId,
67
+ redirect_uris: body.redirect_uris,
68
+ client_name: body.client_name || "",
69
+ token_endpoint_auth_method: "none"
70
+ }, 201);
71
+ }
72
+ async function handleAuthorize(request, url, env) {
73
+ const clientId = url.searchParams.get("client_id");
74
+ const redirectUri = url.searchParams.get("redirect_uri");
75
+ const codeChallenge = url.searchParams.get("code_challenge");
76
+ const codeChallengeMethod = url.searchParams.get("code_challenge_method") || "S256";
77
+ const state = url.searchParams.get("state");
78
+ const scope = url.searchParams.get("scope") || "memory";
79
+ if (!clientId || !redirectUri || !codeChallenge) {
80
+ return json({ error: "Missing required parameters (client_id, redirect_uri, code_challenge)" }, 400);
81
+ }
82
+ if (codeChallengeMethod !== "S256") {
83
+ return json({ error: "Only S256 code_challenge_method supported" }, 400);
84
+ }
85
+ const client = await env.DB.prepare(
86
+ "SELECT * FROM oauth_clients WHERE client_id = ?"
87
+ ).bind(clientId).first();
88
+ if (!client) {
89
+ return json({ error: "Unknown client_id" }, 400);
90
+ }
91
+ const allowedUris = JSON.parse(client.redirect_uris);
92
+ if (!allowedUris.includes(redirectUri)) {
93
+ return json({ error: "redirect_uri not registered" }, 400);
94
+ }
95
+ if (request.method === "GET") {
96
+ return new Response(consentPage(clientId, redirectUri, codeChallenge, codeChallengeMethod, state, scope), {
97
+ headers: { "Content-Type": "text/html" }
98
+ });
99
+ }
100
+ const formData = await request.formData();
101
+ const email = formData.get("email");
102
+ if (!email) {
103
+ return json({ error: "Email required" }, 400);
104
+ }
105
+ const userId = await sha256(email.toLowerCase().trim());
106
+ await env.DB.prepare(`
107
+ INSERT INTO users (user_id, email) VALUES (?, ?)
108
+ ON CONFLICT (user_id) DO NOTHING
109
+ `).bind(userId, email.toLowerCase().trim()).run();
110
+ const code = generateToken();
111
+ const expiresAt = new Date(Date.now() + 10 * 60 * 1e3).toISOString();
112
+ await env.DB.prepare(`
113
+ INSERT INTO authorization_codes (code, client_id, user_id, code_challenge, code_challenge_method, redirect_uri, scope, expires_at)
114
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
115
+ `).bind(code, clientId, userId, codeChallenge, codeChallengeMethod, redirectUri, scope, expiresAt).run();
116
+ const redirect = new URL(redirectUri);
117
+ redirect.searchParams.set("code", code);
118
+ if (state) redirect.searchParams.set("state", state);
119
+ return Response.redirect(redirect.toString(), 302);
120
+ }
121
+ async function handleToken(request, env) {
122
+ const body = await request.formData();
123
+ const grantType = body.get("grant_type");
124
+ const code = body.get("code");
125
+ const redirectUri = body.get("redirect_uri");
126
+ const codeVerifier = body.get("code_verifier");
127
+ if (grantType !== "authorization_code") {
128
+ return json({ error: "unsupported_grant_type" }, 400);
129
+ }
130
+ if (!code || !codeVerifier) {
131
+ return json({ error: "Missing code or code_verifier" }, 400);
132
+ }
133
+ const authCode = await env.DB.prepare(
134
+ "SELECT * FROM authorization_codes WHERE code = ? AND used = 0"
135
+ ).bind(code).first();
136
+ if (!authCode) {
137
+ return json({ error: "invalid_grant", error_description: "Code not found or already used" }, 400);
138
+ }
139
+ if (new Date(authCode.expires_at) < /* @__PURE__ */ new Date()) {
140
+ return json({ error: "invalid_grant", error_description: "Code expired" }, 400);
141
+ }
142
+ if (redirectUri && authCode.redirect_uri !== redirectUri) {
143
+ return json({ error: "invalid_grant", error_description: "redirect_uri mismatch" }, 400);
144
+ }
145
+ const expectedChallenge = await sha256Base64url(codeVerifier);
146
+ if (expectedChallenge !== authCode.code_challenge) {
147
+ return json({ error: "invalid_grant", error_description: "PKCE verification failed" }, 400);
148
+ }
149
+ await env.DB.prepare("UPDATE authorization_codes SET used = 1 WHERE code = ?").bind(code).run();
150
+ const user = await env.DB.prepare("SELECT * FROM users WHERE user_id = ?").bind(authCode.user_id).first();
151
+ const tier = user?.tier || "sovereign";
152
+ const accessToken = generateToken();
153
+ const tokenHash = await sha256(accessToken);
154
+ const expiresAt = new Date(Date.now() + 90 * 24 * 60 * 60 * 1e3).toISOString();
155
+ await env.DB.prepare(`
156
+ INSERT INTO access_tokens (token_hash, client_id, user_id, scope, tier, expires_at)
157
+ VALUES (?, ?, ?, ?, ?, ?)
158
+ `).bind(tokenHash, authCode.client_id, authCode.user_id, authCode.scope, tier, expiresAt).run();
159
+ return json({
160
+ access_token: accessToken,
161
+ token_type: "Bearer",
162
+ expires_in: 90 * 24 * 60 * 60,
163
+ scope: authCode.scope
164
+ });
165
+ }
166
+ async function verifyToken(request, env) {
167
+ const auth = request.headers.get("Authorization");
168
+ if (!auth?.startsWith("Bearer ")) {
169
+ return json({ error: "Missing Authorization header" }, 401);
170
+ }
171
+ const token = auth.slice(7);
172
+ const tokenHash = await sha256(token);
173
+ const row = await env.DB.prepare(
174
+ "SELECT * FROM access_tokens WHERE token_hash = ?"
175
+ ).bind(tokenHash).first();
176
+ if (!row) {
177
+ return json({ error: "Invalid token" }, 401);
178
+ }
179
+ if (new Date(row.expires_at) < /* @__PURE__ */ new Date()) {
180
+ return json({ error: "Token expired" }, 401);
181
+ }
182
+ return {
183
+ user_id: row.user_id,
184
+ client_id: row.client_id,
185
+ scope: row.scope,
186
+ tier: row.tier
187
+ };
188
+ }
189
+ function consentPage(clientId, redirectUri, codeChallenge, codeChallengeMethod, state, scope) {
190
+ return `<!DOCTYPE html>
191
+ <html>
192
+ <head>
193
+ <meta charset="utf-8">
194
+ <meta name="viewport" content="width=device-width, initial-scale=1">
195
+ <title>Memory Crystal</title>
196
+ <style>
197
+ body { font-family: -apple-system, system-ui, sans-serif; max-width: 420px; margin: 60px auto; padding: 0 20px; color: #1a1a1a; }
198
+ h1 { font-size: 1.4em; }
199
+ p { color: #555; line-height: 1.5; }
200
+ form { margin-top: 24px; }
201
+ label { display: block; font-weight: 500; margin-bottom: 6px; }
202
+ input[type=email] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 16px; box-sizing: border-box; }
203
+ button { margin-top: 16px; width: 100%; padding: 12px; background: #1a1a1a; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; }
204
+ button:hover { background: #333; }
205
+ .note { font-size: 0.85em; color: #888; margin-top: 16px; }
206
+ </style>
207
+ </head>
208
+ <body>
209
+ <h1>Memory Crystal</h1>
210
+ <p>An app wants to access your memory. Enter your email to continue.</p>
211
+ <form method="POST">
212
+ <input type="hidden" name="client_id" value="${clientId}">
213
+ <input type="hidden" name="redirect_uri" value="${redirectUri}">
214
+ <input type="hidden" name="code_challenge" value="${codeChallenge}">
215
+ <input type="hidden" name="code_challenge_method" value="${codeChallengeMethod}">
216
+ ${state ? `<input type="hidden" name="state" value="${state}">` : ""}
217
+ <input type="hidden" name="scope" value="${scope}">
218
+ <label for="email">Email</label>
219
+ <input type="email" id="email" name="email" required placeholder="you@example.com" autocomplete="email">
220
+ <button type="submit">Connect Memory</button>
221
+ </form>
222
+ <p class="note">Your email identifies your memory account. No password needed... your AI client handles authentication.</p>
223
+ </body>
224
+ </html>`;
225
+ }
226
+ var TOOLS = [
227
+ {
228
+ name: "memory_search",
229
+ description: "Search your memories across all conversations and surfaces.",
230
+ inputSchema: {
231
+ type: "object",
232
+ properties: {
233
+ query: { type: "string", description: "What to search for" },
234
+ limit: { type: "number", description: "Max results (default 5, max 20)" }
235
+ },
236
+ required: ["query"]
237
+ },
238
+ annotations: { readOnlyHint: true, openWorldHint: false }
239
+ },
240
+ {
241
+ name: "memory_remember",
242
+ description: "Save a fact, preference, or observation to your memory.",
243
+ inputSchema: {
244
+ type: "object",
245
+ properties: {
246
+ text: { type: "string", description: "The fact or observation to remember" },
247
+ category: {
248
+ type: "string",
249
+ enum: ["fact", "preference", "event", "opinion", "skill"],
250
+ description: "Category of memory (default: fact)"
251
+ }
252
+ },
253
+ required: ["text"]
254
+ },
255
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
256
+ },
257
+ {
258
+ name: "memory_forget",
259
+ description: "Deprecate a memory by ID.",
260
+ inputSchema: {
261
+ type: "object",
262
+ properties: {
263
+ id: { type: "number", description: "Memory ID to deprecate" }
264
+ },
265
+ required: ["id"]
266
+ },
267
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }
268
+ },
269
+ {
270
+ name: "memory_status",
271
+ description: "Show your memory status: chunk count, memory count, connected agents.",
272
+ inputSchema: { type: "object", properties: {} },
273
+ annotations: { readOnlyHint: true, openWorldHint: false }
274
+ }
275
+ ];
276
+ async function handleMCP(request, env, tokenInfo) {
277
+ const body = await request.json();
278
+ const { method, id, params } = body;
279
+ const crystal = new CloudCrystal(env.DB, env.VECTORIZE, env.OPENAI_API_KEY);
280
+ let result;
281
+ switch (method) {
282
+ case "initialize":
283
+ result = {
284
+ protocolVersion: "2025-03-26",
285
+ serverInfo: { name: "memory-crystal", version: "0.2.0" },
286
+ capabilities: { tools: {} }
287
+ };
288
+ break;
289
+ case "tools/list":
290
+ result = { tools: TOOLS };
291
+ break;
292
+ case "tools/call": {
293
+ const toolName = params?.name;
294
+ const args = params?.arguments || {};
295
+ switch (toolName) {
296
+ case "memory_search": {
297
+ if (tokenInfo.tier === "sovereign") {
298
+ result = {
299
+ content: [{
300
+ type: "text",
301
+ text: "Search is available on your local devices only (Sovereign tier). Your memories from this session have been saved and will be searchable from any device with Memory Crystal installed locally."
302
+ }]
303
+ };
304
+ } else {
305
+ const limit = Math.min(args.limit || 5, 20);
306
+ const results = await crystal.search(tokenInfo.user_id, args.query, limit);
307
+ const formatted = results.map(
308
+ (r, i) => `[${i + 1}] (${r.score.toFixed(1)}% match, ${r.agent_id}, ${r.created_at})
309
+ ${r.text}`
310
+ ).join("\n\n");
311
+ result = {
312
+ content: [{
313
+ type: "text",
314
+ text: results.length > 0 ? formatted : `No results for "${args.query}".`
315
+ }]
316
+ };
317
+ }
318
+ break;
319
+ }
320
+ case "memory_remember": {
321
+ if (tokenInfo.tier === "sovereign") {
322
+ }
323
+ const memId = await crystal.remember(tokenInfo.user_id, args.text, args.category || "fact");
324
+ result = {
325
+ content: [{
326
+ type: "text",
327
+ text: `Remembered (id: ${memId}, category: ${args.category || "fact"}): ${args.text}`
328
+ }]
329
+ };
330
+ break;
331
+ }
332
+ case "memory_forget": {
333
+ const ok = await crystal.forget(tokenInfo.user_id, args.id);
334
+ result = {
335
+ content: [{
336
+ type: "text",
337
+ text: ok ? `Memory ${args.id} deprecated.` : `Memory ${args.id} not found or already deprecated.`
338
+ }]
339
+ };
340
+ break;
341
+ }
342
+ case "memory_status": {
343
+ const status = await crystal.status(tokenInfo.user_id);
344
+ result = {
345
+ content: [{
346
+ type: "text",
347
+ text: [
348
+ `Chunks: ${status.chunks}`,
349
+ `Memories: ${status.memories}`,
350
+ `Agents: ${status.agents.join(", ") || "none"}`,
351
+ `Tier: ${status.tier}`
352
+ ].join("\n")
353
+ }]
354
+ };
355
+ break;
356
+ }
357
+ default:
358
+ return json({ jsonrpc: "2.0", id, error: { code: -32601, message: `Unknown tool: ${toolName}` } });
359
+ }
360
+ break;
361
+ }
362
+ case "notifications/initialized":
363
+ return new Response(null, { status: 204 });
364
+ default:
365
+ return json({ jsonrpc: "2.0", id, error: { code: -32601, message: `Unknown method: ${method}` } });
366
+ }
367
+ return json({ jsonrpc: "2.0", id, result });
368
+ }
369
+ var worker_mcp_default = {
370
+ async fetch(request, env) {
371
+ const url = new URL(request.url);
372
+ const path = url.pathname;
373
+ if (request.method === "OPTIONS") {
374
+ return cors(new Response(null, { status: 204 }));
375
+ }
376
+ if (path === "/health" && request.method === "GET") {
377
+ return cors(json({ ok: true, service: "memory-crystal-cloud", version: "0.2.0" }));
378
+ }
379
+ if (path === "/.well-known/oauth-protected-resource") {
380
+ return cors(handleProtectedResourceMetadata(url));
381
+ }
382
+ if (path === "/.well-known/oauth-authorization-server") {
383
+ return cors(handleAuthServerMetadata(url));
384
+ }
385
+ if (path === "/oauth/register" && request.method === "POST") {
386
+ return cors(await handleRegister(request, env));
387
+ }
388
+ if (path === "/oauth/authorize") {
389
+ return await handleAuthorize(request, url, env);
390
+ }
391
+ if (path === "/oauth/token" && request.method === "POST") {
392
+ return cors(await handleToken(request, env));
393
+ }
394
+ if (path === "/mcp" && request.method === "POST") {
395
+ const tokenResult = await verifyToken(request, env);
396
+ if (tokenResult instanceof Response) return cors(tokenResult);
397
+ return cors(await handleMCP(request, env, tokenResult));
398
+ }
399
+ return cors(json({ error: "Not found" }, 404));
400
+ }
401
+ };
402
+ export {
403
+ worker_mcp_default as default
404
+ };
package/dist/worker.js ADDED
@@ -0,0 +1,137 @@
1
+ // src/worker.ts
2
+ function authenticate(request, env) {
3
+ const auth = request.headers.get("Authorization");
4
+ if (!auth?.startsWith("Bearer ")) {
5
+ return json({ error: "Missing Authorization header" }, 401);
6
+ }
7
+ const token = auth.slice(7);
8
+ const tokenMap = {};
9
+ if (env.AUTH_TOKEN_CC_AIR) tokenMap[env.AUTH_TOKEN_CC_AIR] = "cc-air";
10
+ if (env.AUTH_TOKEN_CC_MINI) tokenMap[env.AUTH_TOKEN_CC_MINI] = "cc-mini";
11
+ if (env.AUTH_TOKEN_LESA) tokenMap[env.AUTH_TOKEN_LESA] = "lesa-mini";
12
+ const agentId = tokenMap[token];
13
+ if (!agentId) {
14
+ return json({ error: "Invalid token" }, 403);
15
+ }
16
+ return { agentId };
17
+ }
18
+ var VALID_CHANNELS = ["conversations", "mirror", "commands", "files", "chatgpt", "chatgpt-attachments"];
19
+ function isValidChannel(channel) {
20
+ return VALID_CHANNELS.includes(channel);
21
+ }
22
+ async function handleDrop(request, env, agentId, channel) {
23
+ if (!isValidChannel(channel)) {
24
+ return json({ error: `Invalid channel: ${channel}. Valid: ${VALID_CHANNELS.join(", ")}` }, 400);
25
+ }
26
+ const body = await request.arrayBuffer();
27
+ if (body.byteLength === 0) {
28
+ return json({ error: "Empty payload" }, 400);
29
+ }
30
+ if (body.byteLength > 100 * 1024 * 1024) {
31
+ return json({ error: "Payload too large (max 100MB)" }, 413);
32
+ }
33
+ const id = crypto.randomUUID();
34
+ const key = `${channel}/${id}`;
35
+ const now = (/* @__PURE__ */ new Date()).toISOString();
36
+ await env.RELAY.put(key, body, {
37
+ customMetadata: {
38
+ agent_id: agentId,
39
+ dropped_at: now,
40
+ size: String(body.byteLength)
41
+ }
42
+ });
43
+ return json({ ok: true, id, channel, size: body.byteLength, dropped_at: now });
44
+ }
45
+ async function handlePickupList(env, channel) {
46
+ if (!isValidChannel(channel)) {
47
+ return json({ error: `Invalid channel: ${channel}` }, 400);
48
+ }
49
+ const listed = await env.RELAY.list({ prefix: `${channel}/` });
50
+ const blobs = listed.objects.map((obj) => ({
51
+ id: obj.key.split("/")[1],
52
+ size: obj.size,
53
+ dropped_at: obj.customMetadata?.dropped_at || obj.uploaded.toISOString(),
54
+ agent_id: obj.customMetadata?.agent_id || "unknown"
55
+ }));
56
+ return json({ channel, count: blobs.length, blobs });
57
+ }
58
+ async function handlePickup(env, channel, id) {
59
+ if (!isValidChannel(channel)) {
60
+ return json({ error: `Invalid channel: ${channel}` }, 400);
61
+ }
62
+ const key = `${channel}/${id}`;
63
+ const obj = await env.RELAY.get(key);
64
+ if (!obj) {
65
+ return json({ error: "Blob not found (already picked up or expired)" }, 404);
66
+ }
67
+ return new Response(obj.body, {
68
+ headers: {
69
+ "Content-Type": "application/octet-stream",
70
+ "X-Agent-Id": obj.customMetadata?.agent_id || "unknown",
71
+ "X-Dropped-At": obj.customMetadata?.dropped_at || ""
72
+ }
73
+ });
74
+ }
75
+ async function handleConfirm(env, channel, id) {
76
+ if (!isValidChannel(channel)) {
77
+ return json({ error: `Invalid channel: ${channel}` }, 400);
78
+ }
79
+ const key = `${channel}/${id}`;
80
+ const obj = await env.RELAY.head(key);
81
+ if (!obj) {
82
+ return json({ error: "Blob not found (already confirmed or expired)" }, 404);
83
+ }
84
+ await env.RELAY.delete(key);
85
+ return json({ ok: true, deleted: key });
86
+ }
87
+ function json(data, status = 200) {
88
+ return new Response(JSON.stringify(data), {
89
+ status,
90
+ headers: { "Content-Type": "application/json" }
91
+ });
92
+ }
93
+ var worker_default = {
94
+ async fetch(request, env) {
95
+ const url = new URL(request.url);
96
+ const parts = url.pathname.split("/").filter(Boolean);
97
+ if (parts[0] === "health" && request.method === "GET") {
98
+ return json({ ok: true, service: "memory-crystal-relay", mode: "ephemeral" });
99
+ }
100
+ const authResult = authenticate(request, env);
101
+ if (authResult instanceof Response) return authResult;
102
+ const { agentId } = authResult;
103
+ try {
104
+ if (parts[0] === "drop" && parts[1] && request.method === "POST") {
105
+ return handleDrop(request, env, agentId, parts[1]);
106
+ }
107
+ if (parts[0] === "pickup" && parts[1] && request.method === "GET") {
108
+ if (parts[2]) {
109
+ return handlePickup(env, parts[1], parts[2]);
110
+ }
111
+ return handlePickupList(env, parts[1]);
112
+ }
113
+ if (parts[0] === "confirm" && parts[1] && parts[2] && request.method === "DELETE") {
114
+ return handleConfirm(env, parts[1], parts[2]);
115
+ }
116
+ return json({ error: "Not found" }, 404);
117
+ } catch (err) {
118
+ return json({ error: err.message || "Internal error" }, 500);
119
+ }
120
+ },
121
+ // Scheduled cleanup: delete blobs older than 24h (TTL safety net)
122
+ async scheduled(event, env) {
123
+ const cutoff = Date.now() - 24 * 60 * 60 * 1e3;
124
+ for (const channel of VALID_CHANNELS) {
125
+ const listed = await env.RELAY.list({ prefix: `${channel}/` });
126
+ for (const obj of listed.objects) {
127
+ const droppedAt = obj.customMetadata?.dropped_at;
128
+ if (droppedAt && new Date(droppedAt).getTime() < cutoff) {
129
+ await env.RELAY.delete(obj.key);
130
+ }
131
+ }
132
+ }
133
+ }
134
+ };
135
+ export {
136
+ worker_default as default
137
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wipcomputer/memory-crystal",
3
- "version": "0.7.32",
3
+ "version": "0.7.34-alpha.1",
4
4
  "description": "Sovereign memory system — local-first with ephemeral encrypted relay. Your memory, your machine, your rules.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,7 +17,21 @@
17
17
  "crystal": "dist/cli.js",
18
18
  "crystal-mcp": "dist/mcp-server.js"
19
19
  },
20
+ "files": [
21
+ "dist/",
22
+ "scripts/",
23
+ "skills/",
24
+ "migrations/",
25
+ "cloud/",
26
+ "openclaw.plugin.json",
27
+ "SKILL.md",
28
+ "TECHNICAL.md",
29
+ "README.md",
30
+ "LICENSE",
31
+ "CLA.md"
32
+ ],
20
33
  "scripts": {
34
+ "prepublishOnly": "npm run build",
21
35
  "build": "tsup src/core.ts src/cli.ts src/mcp-server.ts src/openclaw.ts src/migrate.ts src/cc-hook.ts src/cc-poller.ts src/crypto.ts src/pair.ts src/poller.ts src/mirror-sync.ts src/file-sync.ts src/ldm.ts src/summarize.ts src/role.ts src/doctor.ts src/bridge.ts src/discover.ts src/bulk-copy.ts src/oc-backfill.ts src/dream-weaver.ts src/crystal-serve.ts src/staging.ts src/installer.ts --format esm --dts --outDir dist && tsup src/worker.ts --format esm --outDir dist --no-dts && cp scripts/crystal-capture.sh scripts/ldm-backup.sh dist/",
22
36
  "build:local": "tsup src/core.ts src/cli.ts src/mcp-server.ts src/openclaw.ts src/migrate.ts src/cc-hook.ts src/cc-poller.ts src/crypto.ts src/pair.ts src/poller.ts src/mirror-sync.ts src/file-sync.ts src/ldm.ts src/summarize.ts src/role.ts src/doctor.ts src/bridge.ts src/discover.ts src/bulk-copy.ts src/oc-backfill.ts src/dream-weaver.ts src/crystal-serve.ts src/staging.ts src/installer.ts --format esm --dts --outDir dist",
23
37
  "build:worker": "tsup src/worker.ts --format esm --outDir dist --no-dts",
package/.env.example DELETED
@@ -1,20 +0,0 @@
1
- # Memory Crystal — Environment Config
2
- # Copy to ~/.openclaw/memory-crystal/.env and fill in your keys.
3
- # Or skip this and use 1Password (keys auto-resolve from "Agent Secrets" vault).
4
-
5
- # Embedding provider: openai (default), ollama, or google
6
- # CRYSTAL_EMBEDDING_PROVIDER=openai
7
-
8
- # OpenAI (required if provider is openai)
9
- OPENAI_API_KEY=sk-...
10
-
11
- # Google (required if provider is google)
12
- # GOOGLE_API_KEY=AIza...
13
-
14
- # Ollama (only if provider is ollama — runs locally, no key needed)
15
- # CRYSTAL_OLLAMA_HOST=http://localhost:11434
16
- # CRYSTAL_OLLAMA_MODEL=nomic-embed-text
17
-
18
- # Cloud mirror (Phase 2)
19
- # CRYSTAL_REMOTE_URL=https://memory-crystal.your-worker.workers.dev
20
- # CRYSTAL_REMOTE_TOKEN=your-token
@@ -1 +0,0 @@
1
- { "name": "wip-memory-crystal" }