@wipcomputer/memory-crystal 0.7.29 → 0.7.32

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 (146) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/SKILL.md +1 -1
  3. package/package.json +1 -1
  4. package/scripts/migrate-lance-to-sqlite.mjs +2 -1
  5. package/_trash/RELEASE-NOTES-v0-7-23.md +0 -48
  6. package/_trash/RELEASE-NOTES-v0-7-25.md +0 -24
  7. package/_trash/RELEASE-NOTES-v0-7-26.md +0 -7
  8. package/_trash/RELEASE-NOTES-v0-7-28.md +0 -31
  9. package/_trash/RELEASE-NOTES-v0-7-29.md +0 -28
  10. package/_trash/RELEASE-NOTES-v0-7-4.md +0 -64
  11. package/_trash/RELEASE-NOTES-v0-7-5.md +0 -19
  12. package/dist/bridge.d.ts +0 -7
  13. package/dist/bridge.js +0 -14
  14. package/dist/bulk-copy.d.ts +0 -17
  15. package/dist/bulk-copy.js +0 -90
  16. package/dist/cc-hook.d.ts +0 -8
  17. package/dist/cc-hook.js +0 -368
  18. package/dist/cc-poller.d.ts +0 -1
  19. package/dist/cc-poller.js +0 -550
  20. package/dist/chunk-25LXQJ4Z.js +0 -110
  21. package/dist/chunk-2DRXIRQW.js +0 -97
  22. package/dist/chunk-2ZNH5F6E.js +0 -1281
  23. package/dist/chunk-3G3SFYYI.js +0 -288
  24. package/dist/chunk-3RG5ZIWI.js +0 -10
  25. package/dist/chunk-3S6TI23B.js +0 -97
  26. package/dist/chunk-3VFIJYS4.js +0 -818
  27. package/dist/chunk-52QE3YI3.js +0 -1169
  28. package/dist/chunk-57RP3DIN.js +0 -1205
  29. package/dist/chunk-5HSZ4W2P.js +0 -62
  30. package/dist/chunk-645IPXW3.js +0 -290
  31. package/dist/chunk-7A7ELD4C.js +0 -1205
  32. package/dist/chunk-7FYY4GZM.js +0 -1205
  33. package/dist/chunk-7IUE7ODU.js +0 -254
  34. package/dist/chunk-7RMLKZIS.js +0 -108
  35. package/dist/chunk-AA3OPP4Z.js +0 -432
  36. package/dist/chunk-AEWLSYPH.js +0 -72
  37. package/dist/chunk-ASSZDR6I.js +0 -108
  38. package/dist/chunk-AYRJVWUC.js +0 -1205
  39. package/dist/chunk-CCYI5O3D.js +0 -148
  40. package/dist/chunk-D3I3ZSE2.js +0 -411
  41. package/dist/chunk-DACSKLY6.js +0 -219
  42. package/dist/chunk-DW5B4BL7.js +0 -108
  43. package/dist/chunk-EKSACBTJ.js +0 -1070
  44. package/dist/chunk-EXEZZADG.js +0 -248
  45. package/dist/chunk-F3Y7EL7K.js +0 -83
  46. package/dist/chunk-FBQWSDPC.js +0 -1328
  47. package/dist/chunk-FHRZNOMW.js +0 -1205
  48. package/dist/chunk-IM7N24MT.js +0 -129
  49. package/dist/chunk-IPNYIXFK.js +0 -1178
  50. package/dist/chunk-J7MRSZIO.js +0 -167
  51. package/dist/chunk-JITKI2OI.js +0 -106
  52. package/dist/chunk-JWZXYVET.js +0 -1068
  53. package/dist/chunk-KCQUXVYT.js +0 -108
  54. package/dist/chunk-KOQ43OX6.js +0 -1281
  55. package/dist/chunk-KYVWO6ZM.js +0 -1069
  56. package/dist/chunk-L3VHARQH.js +0 -413
  57. package/dist/chunk-LBWDS6BE.js +0 -288
  58. package/dist/chunk-LOVAHSQV.js +0 -411
  59. package/dist/chunk-LQOYCAGG.js +0 -446
  60. package/dist/chunk-LWAIPJ2W.js +0 -146
  61. package/dist/chunk-M5DHKW7M.js +0 -127
  62. package/dist/chunk-MBKCIJHM.js +0 -1328
  63. package/dist/chunk-MK42FMEG.js +0 -147
  64. package/dist/chunk-MOBMYHKL.js +0 -1205
  65. package/dist/chunk-MPLTNMRG.js +0 -67
  66. package/dist/chunk-NIJCVN3O.js +0 -147
  67. package/dist/chunk-NZCFSZQ7.js +0 -1205
  68. package/dist/chunk-O2UITJGH.js +0 -465
  69. package/dist/chunk-OCRA44AZ.js +0 -108
  70. package/dist/chunk-P3KJR66H.js +0 -117
  71. package/dist/chunk-PEK6JH65.js +0 -432
  72. package/dist/chunk-PJ6FFKEX.js +0 -77
  73. package/dist/chunk-PLUBBZYR.js +0 -800
  74. package/dist/chunk-PNKVD2UK.js +0 -26
  75. package/dist/chunk-PSQZURHO.js +0 -229
  76. package/dist/chunk-SGL6ISBJ.js +0 -1061
  77. package/dist/chunk-SJABZZT5.js +0 -97
  78. package/dist/chunk-TD3P3K32.js +0 -1199
  79. package/dist/chunk-TMDZJJKV.js +0 -288
  80. package/dist/chunk-UNHVZB5G.js +0 -411
  81. package/dist/chunk-VAFTWSTE.js +0 -1061
  82. package/dist/chunk-VNFXFQBB.js +0 -217
  83. package/dist/chunk-X3GVFKSJ.js +0 -1205
  84. package/dist/chunk-XZ3S56RQ.js +0 -1061
  85. package/dist/chunk-Y72C7F6O.js +0 -148
  86. package/dist/chunk-YLICP577.js +0 -1205
  87. package/dist/chunk-YX6AXLVK.js +0 -159
  88. package/dist/chunk-ZCQYHTNU.js +0 -146
  89. package/dist/cli.d.ts +0 -1
  90. package/dist/cli.js +0 -1105
  91. package/dist/cloud-crystal.js +0 -6
  92. package/dist/core.d.ts +0 -232
  93. package/dist/core.js +0 -12
  94. package/dist/crypto.d.ts +0 -20
  95. package/dist/crypto.js +0 -27
  96. package/dist/crystal-capture.sh +0 -29
  97. package/dist/crystal-serve.d.ts +0 -4
  98. package/dist/crystal-serve.js +0 -252
  99. package/dist/dev-update-SZ2Z4WCQ.js +0 -6
  100. package/dist/discover.d.ts +0 -30
  101. package/dist/discover.js +0 -177
  102. package/dist/doctor.d.ts +0 -9
  103. package/dist/doctor.js +0 -334
  104. package/dist/dream-weaver.d.ts +0 -8
  105. package/dist/dream-weaver.js +0 -56
  106. package/dist/file-sync.d.ts +0 -48
  107. package/dist/file-sync.js +0 -18
  108. package/dist/installer.d.ts +0 -61
  109. package/dist/installer.js +0 -676
  110. package/dist/ldm-backup.sh +0 -116
  111. package/dist/ldm.d.ts +0 -50
  112. package/dist/ldm.js +0 -32
  113. package/dist/mcp-server.d.ts +0 -1
  114. package/dist/mcp-server.js +0 -265
  115. package/dist/migrate.d.ts +0 -1
  116. package/dist/migrate.js +0 -89
  117. package/dist/mirror-sync.d.ts +0 -1
  118. package/dist/mirror-sync.js +0 -159
  119. package/dist/oc-backfill.d.ts +0 -19
  120. package/dist/oc-backfill.js +0 -74
  121. package/dist/openclaw.d.ts +0 -5
  122. package/dist/openclaw.js +0 -423
  123. package/dist/pair.d.ts +0 -4
  124. package/dist/pair.js +0 -75
  125. package/dist/poller.d.ts +0 -1
  126. package/dist/poller.js +0 -634
  127. package/dist/role.d.ts +0 -24
  128. package/dist/role.js +0 -13
  129. package/dist/search-pipeline-4K4OJSSS.js +0 -255
  130. package/dist/search-pipeline-4PRS6LI7.js +0 -280
  131. package/dist/search-pipeline-7UJMXPLO.js +0 -280
  132. package/dist/search-pipeline-DQTRLGBH.js +0 -74
  133. package/dist/search-pipeline-HNG37REH.js +0 -282
  134. package/dist/search-pipeline-IZFPLBUB.js +0 -280
  135. package/dist/search-pipeline-MID6F26Q.js +0 -73
  136. package/dist/search-pipeline-N52JZFNN.js +0 -282
  137. package/dist/search-pipeline-OPB2PRQQ.js +0 -280
  138. package/dist/search-pipeline-VXTE5HAD.js +0 -262
  139. package/dist/search-pipeline-XHFKADRG.js +0 -73
  140. package/dist/staging.d.ts +0 -29
  141. package/dist/staging.js +0 -21
  142. package/dist/summarize.d.ts +0 -19
  143. package/dist/summarize.js +0 -10
  144. package/dist/worker-demo.js +0 -186
  145. package/dist/worker-mcp.js +0 -404
  146. package/dist/worker.js +0 -137
@@ -1,6 +0,0 @@
1
- import {
2
- CloudCrystal
3
- } from "./chunk-J7MRSZIO.js";
4
- export {
5
- CloudCrystal
6
- };
package/dist/core.d.ts DELETED
@@ -1,232 +0,0 @@
1
- interface CrystalConfig {
2
- /** Root directory for all crystal data */
3
- dataDir: string;
4
- /** Embedding provider: 'openai' | 'ollama' | 'google' */
5
- embeddingProvider: 'openai' | 'ollama' | 'google';
6
- /** OpenAI API key (required if provider is 'openai') */
7
- openaiApiKey?: string;
8
- /** OpenAI embedding model (default: text-embedding-3-small) */
9
- openaiModel?: string;
10
- /** Ollama host (default: http://localhost:11434) */
11
- ollamaHost?: string;
12
- /** Ollama model (default: nomic-embed-text) */
13
- ollamaModel?: string;
14
- /** Google API key (required if provider is 'google') */
15
- googleApiKey?: string;
16
- /** Google embedding model (default: text-embedding-004) */
17
- googleModel?: string;
18
- /** Remote Worker URL for cloud mirror mode */
19
- remoteUrl?: string;
20
- /** Remote auth token */
21
- remoteToken?: string;
22
- }
23
- interface Chunk {
24
- id?: number;
25
- text: string;
26
- embedding?: number[];
27
- role: 'user' | 'assistant' | 'system';
28
- source_type: string;
29
- source_id: string;
30
- agent_id: string;
31
- token_count: number;
32
- created_at: string;
33
- }
34
- /** Pre-embedded chunk for delta sync. Includes embedding vector so Nodes don't re-embed. */
35
- interface ExportedChunk {
36
- id: number;
37
- text: string;
38
- text_hash: string;
39
- role: string;
40
- source_type: string;
41
- source_id: string;
42
- agent_id: string;
43
- token_count: number;
44
- created_at: string;
45
- embedding: number[] | null;
46
- }
47
- interface Memory {
48
- id?: number;
49
- text: string;
50
- embedding?: number[];
51
- category: 'fact' | 'preference' | 'event' | 'opinion' | 'skill';
52
- confidence: number;
53
- source_ids: string;
54
- status: 'active' | 'deprecated' | 'deleted';
55
- created_at: string;
56
- updated_at: string;
57
- }
58
- interface SearchResult {
59
- text: string;
60
- role: string;
61
- score: number;
62
- source_type: string;
63
- source_id: string;
64
- agent_id: string;
65
- created_at: string;
66
- freshness?: "fresh" | "recent" | "aging" | "stale";
67
- }
68
- interface CrystalStatus {
69
- chunks: number;
70
- memories: number;
71
- sources: number;
72
- agents: string[];
73
- oldestChunk: string | null;
74
- newestChunk: string | null;
75
- embeddingProvider: string;
76
- dataDir: string;
77
- capturedSessions: number;
78
- latestCapture: string | null;
79
- }
80
- interface SourceCollection {
81
- id?: number;
82
- name: string;
83
- root_path: string;
84
- glob_patterns: string;
85
- ignore_patterns: string;
86
- file_count: number;
87
- chunk_count: number;
88
- last_sync_at: string | null;
89
- created_at: string;
90
- }
91
- interface SourceFile {
92
- id?: number;
93
- collection_id: number;
94
- file_path: string;
95
- file_hash: string;
96
- file_size: number;
97
- chunk_count: number;
98
- last_indexed_at: string;
99
- }
100
- interface SourcesStatus {
101
- collections: Array<{
102
- name: string;
103
- root_path: string;
104
- file_count: number;
105
- chunk_count: number;
106
- last_sync_at: string | null;
107
- }>;
108
- total_files: number;
109
- total_chunks: number;
110
- }
111
- interface SyncResult {
112
- collection: string;
113
- added: number;
114
- updated: number;
115
- removed: number;
116
- chunks_added: number;
117
- duration_ms: number;
118
- }
119
- declare class Crystal {
120
- private config;
121
- private lanceDb;
122
- private sqliteDb;
123
- private chunksTable;
124
- private vecDimensions;
125
- constructor(config: CrystalConfig);
126
- init(): Promise<void>;
127
- private initSqliteTables;
128
- private initChunksTables;
129
- private ensureVecTable;
130
- private initLanceTables;
131
- embed(texts: string[]): Promise<number[][]>;
132
- chunkText(text: string, targetTokens?: number, overlapTokens?: number): string[];
133
- ingest(chunks: Chunk[]): Promise<number>;
134
- /** Export interface for delta sync payloads. */
135
- static readonly DELTA_VERSION = 1;
136
- /** Export chunks with IDs greater than sinceId. Returns pre-embedded chunks for delta sync.
137
- * Core calls this to build delta payloads for Nodes. */
138
- exportChunksSince(sinceId: number): ExportedChunk[];
139
- /** Get the highest chunk ID in the database. Used for watermark tracking. */
140
- getMaxChunkId(): number;
141
- /** Import pre-embedded chunks from Core. Node calls this to apply delta payloads.
142
- * Skips chunks that already exist (by text_hash). Does NOT re-embed. */
143
- importChunks(exported: ExportedChunk[]): number;
144
- private recencyWeight;
145
- /** Parse relative time strings ("24h", "7d", "30d") or ISO dates into ISO date strings. */
146
- private parseSince;
147
- private freshnessLabel;
148
- search(query: string, limit?: number, filter?: {
149
- agent_id?: string;
150
- source_type?: string;
151
- since?: string;
152
- }): Promise<SearchResult[]>;
153
- /** Deep search: query expansion + LLM re-ranking + position-aware blending.
154
- * Falls back to standard search if no LLM provider is available. */
155
- deepSearch(query: string, limit?: number, filter?: {
156
- agent_id?: string;
157
- source_type?: string;
158
- since?: string;
159
- }): Promise<SearchResult[]>;
160
- /** Vector search via sqlite-vec. Two-step pattern: MATCH first, then JOIN. */
161
- private searchVec;
162
- /** Full-text search via FTS5 with BM25 scoring. */
163
- private searchFTS;
164
- /** Build a safe FTS5 query from user input. */
165
- private buildFTS5Query;
166
- /**
167
- * Reciprocal Rank Fusion. Ported from QMD (MIT License, Tobi Lutke, 2024-2026).
168
- * Fuses multiple ranked result lists into one using RRF scoring.
169
- * Uses text content as dedup key (instead of QMD's file path).
170
- */
171
- private reciprocalRankFusion;
172
- /** LanceDB fallback for search (used when sqlite-vec tables are empty, pre-migration). */
173
- private searchLanceFallback;
174
- remember(text: string, category?: Memory['category']): Promise<number>;
175
- forget(memoryId: number): boolean;
176
- status(): Promise<CrystalStatus>;
177
- getCaptureState(agentId: string, sourceId: string): {
178
- lastMessageCount: number;
179
- captureCount: number;
180
- };
181
- setCaptureState(agentId: string, sourceId: string, messageCount: number, captureCount: number): void;
182
- private static readonly DEFAULT_INCLUDE;
183
- private static readonly DEFAULT_IGNORE;
184
- /** Add a directory as a source collection for indexing. */
185
- sourcesAdd(rootPath: string, name: string, options?: {
186
- include?: string[];
187
- ignore?: string[];
188
- }): Promise<SourceCollection>;
189
- /** Remove a source collection and its file records. Chunks remain in LanceDB. */
190
- sourcesRemove(name: string): boolean;
191
- /** Sync a collection: scan files, detect changes, re-index what changed. */
192
- sourcesSync(name: string, options?: {
193
- dryRun?: boolean;
194
- batchSize?: number;
195
- }): Promise<SyncResult>;
196
- /** Get status of all source collections. */
197
- sourcesStatus(): SourcesStatus;
198
- /** Scan a directory recursively, matching include/ignore patterns. */
199
- private scanDirectory;
200
- /** Clean orphaned entries in chunks_vec and chunks_fts that no longer have
201
- * corresponding rows in the chunks table. Returns counts of what was found/cleaned. */
202
- cleanOrphans(options?: {
203
- dryRun?: boolean;
204
- }): {
205
- orphanedVec: number;
206
- orphanedFts: number;
207
- cleanedVec: number;
208
- cleanedFts: number;
209
- dryRun: boolean;
210
- };
211
- close(): void;
212
- }
213
- declare function resolveConfig(overrides?: Partial<CrystalConfig>): CrystalConfig;
214
- declare class RemoteCrystal {
215
- private url;
216
- private token;
217
- constructor(url: string, token: string);
218
- init(): Promise<void>;
219
- private request;
220
- search(query: string, limit?: number, filter?: {
221
- agent_id?: string;
222
- }): Promise<SearchResult[]>;
223
- ingest(chunks: Chunk[]): Promise<number>;
224
- remember(text: string, category?: Memory['category']): Promise<number>;
225
- forget(memoryId: number): Promise<boolean>;
226
- status(): Promise<CrystalStatus>;
227
- chunkText(text: string): string[];
228
- }
229
- /** Create the appropriate Crystal instance based on config. */
230
- declare function createCrystal(config: CrystalConfig): Crystal | RemoteCrystal;
231
-
232
- export { type Chunk, Crystal, type CrystalConfig, type CrystalStatus, type ExportedChunk, type Memory, RemoteCrystal, type SearchResult, type SourceCollection, type SourceFile, type SourcesStatus, type SyncResult, createCrystal, resolveConfig };
package/dist/core.js DELETED
@@ -1,12 +0,0 @@
1
- import {
2
- Crystal,
3
- RemoteCrystal,
4
- createCrystal,
5
- resolveConfig
6
- } from "./chunk-FBQWSDPC.js";
7
- export {
8
- Crystal,
9
- RemoteCrystal,
10
- createCrystal,
11
- resolveConfig
12
- };
package/dist/crypto.d.ts DELETED
@@ -1,20 +0,0 @@
1
- declare function loadRelayKey(): Buffer;
2
- interface EncryptedPayload {
3
- v: 1;
4
- nonce: string;
5
- ciphertext: string;
6
- tag: string;
7
- hmac: string;
8
- }
9
- declare function encrypt(plaintext: Buffer, masterKey: Buffer): EncryptedPayload;
10
- declare function decrypt(payload: EncryptedPayload, masterKey: Buffer): Buffer;
11
- declare function encryptJSON(data: unknown, masterKey: Buffer): EncryptedPayload;
12
- declare function decryptJSON<T = unknown>(payload: EncryptedPayload, masterKey: Buffer): T;
13
- declare function encryptFile(filePath: string, masterKey: Buffer): EncryptedPayload;
14
- declare const RELAY_KEY_PATH: string;
15
- declare function generateRelayKey(): Buffer;
16
- declare function encodePairingString(key: Buffer): string;
17
- declare function decodePairingString(str: string): Buffer;
18
- declare function hashBuffer(data: Buffer): string;
19
-
20
- export { type EncryptedPayload, RELAY_KEY_PATH, decodePairingString, decrypt, decryptJSON, encodePairingString, encrypt, encryptFile, encryptJSON, generateRelayKey, hashBuffer, loadRelayKey };
package/dist/crypto.js DELETED
@@ -1,27 +0,0 @@
1
- import {
2
- RELAY_KEY_PATH,
3
- decodePairingString,
4
- decrypt,
5
- decryptJSON,
6
- encodePairingString,
7
- encrypt,
8
- encryptFile,
9
- encryptJSON,
10
- generateRelayKey,
11
- hashBuffer,
12
- loadRelayKey
13
- } from "./chunk-KCQUXVYT.js";
14
- import "./chunk-EXEZZADG.js";
15
- export {
16
- RELAY_KEY_PATH,
17
- decodePairingString,
18
- decrypt,
19
- decryptJSON,
20
- encodePairingString,
21
- encrypt,
22
- encryptFile,
23
- encryptJSON,
24
- generateRelayKey,
25
- hashBuffer,
26
- loadRelayKey
27
- };
@@ -1,29 +0,0 @@
1
- #!/bin/bash
2
- # Job: crystal-capture
3
- # Continuous capture for Claude Code sessions.
4
- # Reads JSONL files on disk, ingests into Crystal, exports MD sessions, writes daily logs.
5
- # Primary capture path. Runs every minute via cron.
6
- # The Stop hook (cc-hook.ts) is a redundancy check only.
7
- #
8
- # Source of truth: memory-crystal-private/scripts/crystal-capture.sh
9
- # Deployed to: ~/.ldm/bin/crystal-capture.sh (via crystal init)
10
- # Cron entry: * * * * * ~/.ldm/bin/crystal-capture.sh >> /tmp/ldm-dev-tools/crystal-capture.log 2>&1
11
- #
12
- # The Node poller fetches the OpenAI API key internally via opRead() in core.ts.
13
- # opRead uses: op read "op://Agent Secrets/OpenAI API/api key" with the SA token from
14
- # ~/.openclaw/secrets/op-sa-token. Do NOT call op from this shell script... it triggers
15
- # macOS TCC popups when run from cron.
16
-
17
- # Cron provides minimal PATH. Ensure Homebrew binaries (node, op) are findable.
18
- export PATH="/opt/homebrew/bin:$PATH"
19
-
20
- POLLER="$HOME/.ldm/extensions/memory-crystal/dist/cc-poller.js"
21
- NODE="/opt/homebrew/bin/node"
22
-
23
- if [ ! -f "$POLLER" ]; then
24
- echo "ERROR: cc-poller not found at $POLLER"
25
- exit 1
26
- fi
27
-
28
- # Single run: scan all sessions, ingest new turns, export MD, exit.
29
- $NODE "$POLLER" 2>&1
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- declare function startServer(port?: number): void;
3
-
4
- export { startServer };
@@ -1,252 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- ldmPaths
4
- } from "./chunk-EXEZZADG.js";
5
-
6
- // src/crystal-serve.ts
7
- import { createServer } from "http";
8
- import { spawn } from "child_process";
9
- import { existsSync, readFileSync } from "fs";
10
- import { join } from "path";
11
- var DEFAULT_PORT = 18790;
12
- var AUTH_TOKEN = process.env.CRYSTAL_SERVE_TOKEN || "";
13
- function checkAuth(req) {
14
- if (!AUTH_TOKEN) return true;
15
- const authHeader = req.headers.authorization;
16
- if (!authHeader) return false;
17
- return authHeader === `Bearer ${AUTH_TOKEN}`;
18
- }
19
- function sendJson(res, status, body) {
20
- res.writeHead(status, { "Content-Type": "application/json" });
21
- res.end(JSON.stringify(body));
22
- }
23
- function send401(res) {
24
- sendJson(res, 401, { error: "Unauthorized" });
25
- }
26
- function readBody(req) {
27
- return new Promise((resolve, reject) => {
28
- let body = "";
29
- req.on("data", (chunk) => {
30
- body += chunk;
31
- });
32
- req.on("end", () => resolve(body));
33
- req.on("error", reject);
34
- req.on("data", () => {
35
- if (body.length > 1e6) {
36
- req.destroy();
37
- reject(new Error("Request body too large"));
38
- }
39
- });
40
- });
41
- }
42
- async function handleChatCompletions(req, res) {
43
- const raw = await readBody(req);
44
- let parsed;
45
- try {
46
- parsed = JSON.parse(raw);
47
- } catch {
48
- sendJson(res, 400, { error: "Invalid JSON" });
49
- return;
50
- }
51
- const messages = parsed.messages;
52
- if (!messages || !Array.isArray(messages) || messages.length === 0) {
53
- sendJson(res, 400, { error: "messages array required" });
54
- return;
55
- }
56
- const lastUser = [...messages].reverse().find((m) => m.role === "user");
57
- if (!lastUser) {
58
- sendJson(res, 400, { error: "No user message found" });
59
- return;
60
- }
61
- const prompt = typeof lastUser.content === "string" ? lastUser.content : Array.isArray(lastUser.content) ? lastUser.content.filter((b) => b.type === "text").map((b) => b.text).join("\n") : "";
62
- if (!prompt) {
63
- sendJson(res, 400, { error: "Empty prompt" });
64
- return;
65
- }
66
- const systemMsg = messages.find((m) => m.role === "system");
67
- const systemPrompt = systemMsg ? typeof systemMsg.content === "string" ? systemMsg.content : "" : void 0;
68
- try {
69
- const args2 = ["-p", prompt];
70
- if (systemPrompt) args2.push("--system", systemPrompt);
71
- args2.push("--output-format", "text");
72
- const result = await new Promise((resolve, reject) => {
73
- const proc = spawn("claude", args2, {
74
- stdio: ["ignore", "pipe", "pipe"],
75
- env: { ...process.env },
76
- timeout: 3e5
77
- });
78
- let stdout = "";
79
- let stderr = "";
80
- proc.stdout.on("data", (data) => {
81
- stdout += data.toString();
82
- });
83
- proc.stderr.on("data", (data) => {
84
- stderr += data.toString();
85
- });
86
- proc.on("close", (code) => {
87
- if (code === 0) resolve(stdout.trim());
88
- else reject(new Error(`claude exited ${code}: ${stderr.slice(0, 300)}`));
89
- });
90
- proc.on("error", reject);
91
- });
92
- sendJson(res, 200, {
93
- id: `crystal-${Date.now()}`,
94
- object: "chat.completion",
95
- created: Math.floor(Date.now() / 1e3),
96
- model: "claude-opus-4-6",
97
- choices: [{
98
- index: 0,
99
- message: { role: "assistant", content: result },
100
- finish_reason: "stop"
101
- }]
102
- });
103
- } catch (err) {
104
- sendJson(res, 500, { error: err.message });
105
- }
106
- }
107
- async function handleProcess(req, res) {
108
- const raw = await readBody(req);
109
- let parsed;
110
- try {
111
- parsed = JSON.parse(raw);
112
- } catch {
113
- sendJson(res, 400, { error: "Invalid JSON" });
114
- return;
115
- }
116
- const agentId = parsed.agent_id || parsed.agentId;
117
- const action = parsed.action || "dream-weave";
118
- if (!agentId) {
119
- sendJson(res, 400, { error: "agent_id required" });
120
- return;
121
- }
122
- const args2 = [];
123
- if (action === "backfill") {
124
- args2.push("backfill", "--agent", agentId);
125
- } else if (action === "dream-weave") {
126
- args2.push("dream-weave", "--agent", agentId, "--mode", parsed.mode || "incremental");
127
- } else {
128
- sendJson(res, 400, { error: `Unknown action: ${action}` });
129
- return;
130
- }
131
- try {
132
- const proc = spawn("crystal", args2, {
133
- stdio: "ignore",
134
- detached: true,
135
- env: { ...process.env }
136
- });
137
- proc.unref();
138
- sendJson(res, 202, {
139
- status: "accepted",
140
- action,
141
- agent_id: agentId,
142
- message: `${action} started for ${agentId}`
143
- });
144
- } catch (err) {
145
- sendJson(res, 500, { error: err.message });
146
- }
147
- }
148
- function handleStatus(_req, res) {
149
- const paths = ldmPaths();
150
- const hasDb = existsSync(paths.crystalDb);
151
- let lastDreamWeaver = null;
152
- const agentId = process.env.CRYSTAL_AGENT_ID || "cc-mini";
153
- const wmPath = join(paths.state, `dream-weaver-${agentId}.json`);
154
- if (existsSync(wmPath)) {
155
- try {
156
- const wm = JSON.parse(readFileSync(wmPath, "utf-8"));
157
- lastDreamWeaver = wm.lastRunAt || null;
158
- } catch {
159
- }
160
- }
161
- let role = "standalone";
162
- const rolePath = join(paths.state, "role.json");
163
- if (existsSync(rolePath)) {
164
- try {
165
- const r = JSON.parse(readFileSync(rolePath, "utf-8"));
166
- role = r.role || "standalone";
167
- } catch {
168
- }
169
- }
170
- sendJson(res, 200, {
171
- status: "ok",
172
- role,
173
- agentId,
174
- hasDatabase: hasDb,
175
- lastDreamWeaver,
176
- uptime: process.uptime(),
177
- version: "0.6.0"
178
- });
179
- }
180
- function startServer(port2 = DEFAULT_PORT) {
181
- const server = createServer(async (req, res) => {
182
- const url = req.url || "";
183
- const method = req.method || "GET";
184
- res.setHeader("Access-Control-Allow-Origin", "http://localhost:*");
185
- res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
186
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
187
- if (method === "OPTIONS") {
188
- res.writeHead(204);
189
- res.end();
190
- return;
191
- }
192
- if (url !== "/status" && !checkAuth(req)) {
193
- send401(res);
194
- return;
195
- }
196
- try {
197
- if (method === "POST" && url === "/v1/chat/completions") {
198
- await handleChatCompletions(req, res);
199
- } else if (method === "POST" && url === "/process") {
200
- await handleProcess(req, res);
201
- } else if (method === "GET" && url === "/status") {
202
- handleStatus(req, res);
203
- } else {
204
- sendJson(res, 404, { error: "Not found" });
205
- }
206
- } catch (err) {
207
- sendJson(res, 500, { error: err.message });
208
- }
209
- });
210
- server.listen(port2, "127.0.0.1", () => {
211
- console.log(`Crystal Core gateway listening on http://127.0.0.1:${port2}`);
212
- console.log(` POST /v1/chat/completions (OpenAI-compatible)`);
213
- console.log(` POST /process (trigger backfill/dream-weaver)`);
214
- console.log(` GET /status (health check)`);
215
- if (AUTH_TOKEN) {
216
- console.log(` Auth: bearer token required`);
217
- } else {
218
- console.log(` Auth: none (set CRYSTAL_SERVE_TOKEN to enable)`);
219
- }
220
- });
221
- process.on("SIGTERM", () => {
222
- console.log("Crystal Core gateway shutting down...");
223
- server.close();
224
- process.exit(0);
225
- });
226
- process.on("SIGINT", () => {
227
- console.log("Crystal Core gateway shutting down...");
228
- server.close();
229
- process.exit(0);
230
- });
231
- }
232
- var args = process.argv.slice(2);
233
- if (args.includes("--help") || args.includes("-h")) {
234
- console.log(`crystal serve [--port <port>]
235
-
236
- Crystal Core gateway. Localhost-only HTTP server.
237
-
238
- Options:
239
- --port <port> Port to listen on (default: ${DEFAULT_PORT})
240
-
241
- Environment:
242
- CRYSTAL_SERVE_TOKEN Bearer token for auth (optional)
243
- CRYSTAL_AGENT_ID Agent identifier (default: cc-mini)
244
- `);
245
- process.exit(0);
246
- }
247
- var portFlag = args.indexOf("--port");
248
- var port = portFlag >= 0 ? parseInt(args[portFlag + 1], 10) : DEFAULT_PORT;
249
- startServer(port);
250
- export {
251
- startServer
252
- };
@@ -1,6 +0,0 @@
1
- import {
2
- runDevUpdate
3
- } from "./chunk-MK42FMEG.js";
4
- export {
5
- runDevUpdate
6
- };
@@ -1,30 +0,0 @@
1
- interface HarnessInfo {
2
- platform: 'claude-code' | 'openclaw';
3
- sessionDir: string;
4
- workspaceDir?: string;
5
- filePattern: string;
6
- agentIdDefault: string;
7
- }
8
- interface DiscoveryBreakdown {
9
- platform: string;
10
- files: number;
11
- sizeBytes: number;
12
- sessionPaths: string[];
13
- }
14
- interface DiscoveryResult {
15
- harnesses: HarnessInfo[];
16
- totalFiles: number;
17
- totalSizeBytes: number;
18
- breakdown: DiscoveryBreakdown[];
19
- }
20
- /** Detect which agent platforms are installed on this machine. */
21
- declare function discoverHarnesses(): HarnessInfo[];
22
- /** Discover all session JSONL files for a given harness. */
23
- declare function discoverSessionFiles(harness: HarnessInfo): string[];
24
- /** Discover workspace .md files for OpenClaw harness. */
25
- declare function discoverWorkspaceFiles(harness: HarnessInfo): string[];
26
- /** Run full discovery: detect harnesses, find all files, compute sizes. */
27
- declare function discoverAll(): DiscoveryResult;
28
- declare function formatBytes(bytes: number): string;
29
-
30
- export { type DiscoveryBreakdown, type DiscoveryResult, type HarnessInfo, discoverAll, discoverHarnesses, discoverSessionFiles, discoverWorkspaceFiles, formatBytes };