@wipcomputer/memory-crystal 0.7.34-alpha.2 → 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 (120) hide show
  1. package/LICENSE +1 -1
  2. package/dist/bridge.js +64 -7
  3. package/dist/bulk-copy.js +67 -16
  4. package/dist/cc-hook.js +2163 -62
  5. package/dist/cc-poller.js +1967 -70
  6. package/dist/cli.js +4538 -139
  7. package/dist/core.js +1789 -6
  8. package/dist/crypto.js +153 -14
  9. package/dist/crystal-serve.js +64 -12
  10. package/dist/doctor.js +517 -52
  11. package/dist/dream-weaver.js +1755 -7
  12. package/dist/file-sync.js +407 -9
  13. package/dist/installer.js +840 -145
  14. package/dist/ldm.js +231 -16
  15. package/dist/mcp-server.js +1882 -17
  16. package/dist/migrate.js +1707 -11
  17. package/dist/mirror-sync.js +2052 -34
  18. package/dist/openclaw.js +1895 -84
  19. package/dist/pair.js +112 -16
  20. package/dist/poller.js +2275 -80
  21. package/dist/role.js +159 -7
  22. package/dist/staging.js +235 -10
  23. package/dist/summarize.js +142 -5
  24. package/package.json +7 -4
  25. package/dist/chunk-25LXQJ4Z.js +0 -110
  26. package/dist/chunk-2DRXIRQW.js +0 -97
  27. package/dist/chunk-2GBYLMEF.js +0 -1385
  28. package/dist/chunk-2ZNH5F6E.js +0 -1281
  29. package/dist/chunk-3G3SFYYI.js +0 -288
  30. package/dist/chunk-3RG5ZIWI.js +0 -10
  31. package/dist/chunk-3S6TI23B.js +0 -97
  32. package/dist/chunk-3VFIJYS4.js +0 -818
  33. package/dist/chunk-437F27T6.js +0 -97
  34. package/dist/chunk-52QE3YI3.js +0 -1169
  35. package/dist/chunk-57RP3DIN.js +0 -1205
  36. package/dist/chunk-5HSZ4W2P.js +0 -62
  37. package/dist/chunk-5I7GMRDN.js +0 -146
  38. package/dist/chunk-645IPXW3.js +0 -290
  39. package/dist/chunk-7A7ELD4C.js +0 -1205
  40. package/dist/chunk-7FYY4GZM.js +0 -1205
  41. package/dist/chunk-7IUE7ODU.js +0 -254
  42. package/dist/chunk-7RMLKZIS.js +0 -108
  43. package/dist/chunk-AA3OPP4Z.js +0 -432
  44. package/dist/chunk-AEWLSYPH.js +0 -72
  45. package/dist/chunk-ASSZDR6I.js +0 -108
  46. package/dist/chunk-AYRJVWUC.js +0 -1205
  47. package/dist/chunk-CCYI5O3D.js +0 -148
  48. package/dist/chunk-CGIDSAJB.js +0 -288
  49. package/dist/chunk-D3I3ZSE2.js +0 -411
  50. package/dist/chunk-D3MACYZ4.js +0 -108
  51. package/dist/chunk-DACSKLY6.js +0 -219
  52. package/dist/chunk-DFQ72B7M.js +0 -248
  53. package/dist/chunk-DW5B4BL7.js +0 -108
  54. package/dist/chunk-EKSACBTJ.js +0 -1070
  55. package/dist/chunk-EXEZZADG.js +0 -248
  56. package/dist/chunk-F3Y7EL7K.js +0 -83
  57. package/dist/chunk-FBQWSDPC.js +0 -1328
  58. package/dist/chunk-FHRZNOMW.js +0 -1205
  59. package/dist/chunk-IM7N24MT.js +0 -129
  60. package/dist/chunk-IPNYIXFK.js +0 -1178
  61. package/dist/chunk-J7MRSZIO.js +0 -167
  62. package/dist/chunk-JITKI2OI.js +0 -106
  63. package/dist/chunk-JWZXYVET.js +0 -1068
  64. package/dist/chunk-KCQUXVYT.js +0 -108
  65. package/dist/chunk-KOQ43OX6.js +0 -1281
  66. package/dist/chunk-KYVWO6ZM.js +0 -1069
  67. package/dist/chunk-L3VHARQH.js +0 -413
  68. package/dist/chunk-LBWDS6BE.js +0 -288
  69. package/dist/chunk-LOVAHSQV.js +0 -411
  70. package/dist/chunk-LQOYCAGG.js +0 -446
  71. package/dist/chunk-LWAIPJ2W.js +0 -146
  72. package/dist/chunk-M5DHKW7M.js +0 -127
  73. package/dist/chunk-MBKCIJHM.js +0 -1328
  74. package/dist/chunk-MK42FMEG.js +0 -147
  75. package/dist/chunk-MOBMYHKL.js +0 -1205
  76. package/dist/chunk-MPLTNMRG.js +0 -67
  77. package/dist/chunk-NIJCVN3O.js +0 -147
  78. package/dist/chunk-NX647OM3.js +0 -310
  79. package/dist/chunk-NZCFSZQ7.js +0 -1205
  80. package/dist/chunk-O2UITJGH.js +0 -465
  81. package/dist/chunk-OCRA44AZ.js +0 -108
  82. package/dist/chunk-P3KJR66H.js +0 -117
  83. package/dist/chunk-PEK6JH65.js +0 -432
  84. package/dist/chunk-PJ6FFKEX.js +0 -77
  85. package/dist/chunk-PLUBBZYR.js +0 -800
  86. package/dist/chunk-PNKVD2UK.js +0 -26
  87. package/dist/chunk-PSQZURHO.js +0 -229
  88. package/dist/chunk-SGL6ISBJ.js +0 -1061
  89. package/dist/chunk-SJABZZT5.js +0 -97
  90. package/dist/chunk-TD3P3K32.js +0 -1199
  91. package/dist/chunk-TMDZJJKV.js +0 -288
  92. package/dist/chunk-UNHVZB5G.js +0 -411
  93. package/dist/chunk-VAFTWSTE.js +0 -1061
  94. package/dist/chunk-VNFXFQBB.js +0 -217
  95. package/dist/chunk-X3GVFKSJ.js +0 -1205
  96. package/dist/chunk-XZ3S56RQ.js +0 -1061
  97. package/dist/chunk-Y72C7F6O.js +0 -148
  98. package/dist/chunk-YLICP577.js +0 -1205
  99. package/dist/chunk-YX6AXLVK.js +0 -159
  100. package/dist/chunk-ZCQYHTNU.js +0 -146
  101. package/dist/cloud-crystal.js +0 -6
  102. package/dist/dev-update-SZ2Z4WCQ.js +0 -6
  103. package/dist/llm-XXLYPIOF.js +0 -16
  104. package/dist/mlx-setup-XKU67WCT.js +0 -289
  105. package/dist/search-pipeline-4K4OJSSS.js +0 -255
  106. package/dist/search-pipeline-4PRS6LI7.js +0 -280
  107. package/dist/search-pipeline-7UJMXPLO.js +0 -280
  108. package/dist/search-pipeline-CBV25NX7.js +0 -99
  109. package/dist/search-pipeline-DQTRLGBH.js +0 -74
  110. package/dist/search-pipeline-HNG37REH.js +0 -282
  111. package/dist/search-pipeline-IZFPLBUB.js +0 -280
  112. package/dist/search-pipeline-MID6F26Q.js +0 -73
  113. package/dist/search-pipeline-N52JZFNN.js +0 -282
  114. package/dist/search-pipeline-OPB2PRQQ.js +0 -280
  115. package/dist/search-pipeline-VXTE5HAD.js +0 -262
  116. package/dist/search-pipeline-XHFKADRG.js +0 -73
  117. package/dist/worker-demo.js +0 -186
  118. package/dist/worker-mcp.js +0 -404
  119. package/scripts/crystal-capture 2.sh +0 -29
  120. package/scripts/deploy-cloud 2.sh +0 -153
@@ -1,159 +0,0 @@
1
- // src/ldm.ts
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync, chmodSync } from "fs";
3
- import { join, dirname } from "path";
4
- import { execSync } from "child_process";
5
- import { fileURLToPath } from "url";
6
- var HOME = process.env.HOME || "";
7
- var LDM_ROOT = join(HOME, ".ldm");
8
- function getAgentId() {
9
- return process.env.CRYSTAL_AGENT_ID || "cc-mini";
10
- }
11
- function ldmPaths(agentId) {
12
- const id = agentId || getAgentId();
13
- const agentRoot = join(LDM_ROOT, "agents", id);
14
- return {
15
- root: LDM_ROOT,
16
- bin: join(LDM_ROOT, "bin"),
17
- secrets: join(LDM_ROOT, "secrets"),
18
- state: join(LDM_ROOT, "state"),
19
- config: join(LDM_ROOT, "config.json"),
20
- crystalDb: join(LDM_ROOT, "memory", "crystal.db"),
21
- crystalLance: join(LDM_ROOT, "memory", "lance"),
22
- agentRoot,
23
- transcripts: join(agentRoot, "memory", "transcripts"),
24
- sessions: join(agentRoot, "memory", "sessions"),
25
- daily: join(agentRoot, "memory", "daily"),
26
- journals: join(agentRoot, "memory", "journals")
27
- };
28
- }
29
- function loadConfig() {
30
- const configPath = join(LDM_ROOT, "config.json");
31
- try {
32
- if (existsSync(configPath)) {
33
- return JSON.parse(readFileSync(configPath, "utf-8"));
34
- }
35
- } catch {
36
- }
37
- return null;
38
- }
39
- function saveConfig(config) {
40
- const configPath = join(LDM_ROOT, "config.json");
41
- writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
42
- }
43
- function scaffoldLdm(agentId) {
44
- const paths = ldmPaths(agentId);
45
- mkdirSync(join(paths.root, "memory"), { recursive: true });
46
- mkdirSync(paths.crystalLance, { recursive: true });
47
- mkdirSync(paths.bin, { recursive: true });
48
- mkdirSync(paths.secrets, { recursive: true, mode: 448 });
49
- mkdirSync(paths.state, { recursive: true });
50
- mkdirSync(paths.transcripts, { recursive: true });
51
- mkdirSync(paths.sessions, { recursive: true });
52
- mkdirSync(paths.daily, { recursive: true });
53
- mkdirSync(paths.journals, { recursive: true });
54
- const id = agentId || getAgentId();
55
- let config = loadConfig();
56
- if (!config) {
57
- config = {
58
- version: "1.0.0",
59
- agents: [id],
60
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
61
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
62
- };
63
- } else {
64
- if (!config.agents.includes(id)) {
65
- config.agents.push(id);
66
- }
67
- config.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
68
- }
69
- saveConfig(config);
70
- return paths;
71
- }
72
- function deployCaptureScript() {
73
- const paths = ldmPaths();
74
- mkdirSync(paths.bin, { recursive: true });
75
- const thisDir = dirname(fileURLToPath(import.meta.url));
76
- let scriptSrc = join(thisDir, "crystal-capture.sh");
77
- if (!existsSync(scriptSrc)) {
78
- scriptSrc = join(thisDir, "..", "scripts", "crystal-capture.sh");
79
- }
80
- const scriptDest = join(paths.bin, "crystal-capture.sh");
81
- if (!existsSync(scriptSrc)) {
82
- throw new Error(`crystal-capture.sh not found at ${scriptSrc}`);
83
- }
84
- copyFileSync(scriptSrc, scriptDest);
85
- chmodSync(scriptDest, 493);
86
- return scriptDest;
87
- }
88
- var CRON_TAG = "# crystal-capture";
89
- var CRON_ENTRY = "* * * * * ~/.ldm/bin/crystal-capture.sh >> /tmp/ldm-dev-tools/crystal-capture.log 2>&1";
90
- function isCrystalCaptureLine(line) {
91
- return line === CRON_TAG || line.includes("crystal-capture.sh") && line.startsWith("*");
92
- }
93
- function installCron() {
94
- mkdirSync("/tmp/ldm-dev-tools", { recursive: true });
95
- let existing = "";
96
- try {
97
- existing = execSync("crontab -l 2>/dev/null", { encoding: "utf8" });
98
- } catch {
99
- }
100
- const lines = existing.split("\n").filter((line) => !isCrystalCaptureLine(line));
101
- lines.push(CRON_TAG);
102
- lines.push(CRON_ENTRY);
103
- const newCrontab = lines.filter((l, i, arr) => !(l === "" && i === arr.length - 1)).join("\n") + "\n";
104
- execSync("crontab -", { input: newCrontab, encoding: "utf8" });
105
- }
106
- function removeCron() {
107
- let existing = "";
108
- try {
109
- existing = execSync("crontab -l 2>/dev/null", { encoding: "utf8" });
110
- } catch {
111
- return;
112
- }
113
- const lines = existing.split("\n").filter((line) => !isCrystalCaptureLine(line));
114
- const newCrontab = lines.join("\n");
115
- execSync("crontab -", { input: newCrontab, encoding: "utf8" });
116
- }
117
- var LEGACY_OC_DIR = join(HOME, ".openclaw");
118
- function resolveStatePath(filename) {
119
- const paths = ldmPaths();
120
- const ldmPath = join(paths.state, filename);
121
- if (existsSync(ldmPath)) return ldmPath;
122
- const legacyPath = join(LEGACY_OC_DIR, "memory", filename);
123
- if (existsSync(legacyPath)) return legacyPath;
124
- return ldmPath;
125
- }
126
- function stateWritePath(filename) {
127
- const paths = ldmPaths();
128
- const dir = paths.state;
129
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
130
- return join(dir, filename);
131
- }
132
- function resolveSecretPath(filename) {
133
- const paths = ldmPaths();
134
- const ldmPath = join(paths.secrets, filename);
135
- if (existsSync(ldmPath)) return ldmPath;
136
- const legacyPath = join(LEGACY_OC_DIR, "secrets", filename);
137
- if (existsSync(legacyPath)) return legacyPath;
138
- return ldmPath;
139
- }
140
- function ensureLdm(agentId) {
141
- const paths = ldmPaths(agentId);
142
- if (existsSync(paths.transcripts) && existsSync(paths.config)) {
143
- return paths;
144
- }
145
- return scaffoldLdm(agentId);
146
- }
147
-
148
- export {
149
- getAgentId,
150
- ldmPaths,
151
- scaffoldLdm,
152
- deployCaptureScript,
153
- installCron,
154
- removeCron,
155
- resolveStatePath,
156
- stateWritePath,
157
- resolveSecretPath,
158
- ensureLdm
159
- };
@@ -1,146 +0,0 @@
1
- import {
2
- ensureLdm,
3
- ldmPaths
4
- } from "./chunk-EXEZZADG.js";
5
-
6
- // src/staging.ts
7
- import {
8
- existsSync,
9
- mkdirSync,
10
- readdirSync,
11
- renameSync,
12
- unlinkSync,
13
- writeFileSync
14
- } from "fs";
15
- import { join } from "path";
16
- import { execSync } from "child_process";
17
- var HOME = process.env.HOME || "";
18
- var STAGING_ROOT = join(HOME, ".ldm", "staging");
19
- function stagingPaths(agentId) {
20
- const root = join(STAGING_ROOT, agentId);
21
- return {
22
- root,
23
- transcripts: join(root, "transcripts"),
24
- readyFile: join(root, "READY")
25
- };
26
- }
27
- function ensureStaging(agentId) {
28
- const paths = stagingPaths(agentId);
29
- mkdirSync(paths.transcripts, { recursive: true });
30
- return paths;
31
- }
32
- function markReady(agentId) {
33
- const paths = stagingPaths(agentId);
34
- writeFileSync(paths.readyFile, JSON.stringify({
35
- markedAt: (/* @__PURE__ */ new Date()).toISOString(),
36
- agentId
37
- }));
38
- }
39
- function isNewAgent(agentId) {
40
- const paths = ldmPaths(agentId);
41
- return !existsSync(paths.agentRoot);
42
- }
43
- function hasStagedData(agentId) {
44
- const paths = stagingPaths(agentId);
45
- return existsSync(paths.readyFile);
46
- }
47
- function listStagedAgents() {
48
- if (!existsSync(STAGING_ROOT)) return [];
49
- const agents = [];
50
- for (const entry of readdirSync(STAGING_ROOT, { withFileTypes: true })) {
51
- if (!entry.isDirectory()) continue;
52
- if (existsSync(join(STAGING_ROOT, entry.name, "READY"))) {
53
- agents.push(entry.name);
54
- }
55
- }
56
- return agents;
57
- }
58
- async function processStagedAgent(agentId) {
59
- const startTime = Date.now();
60
- const staging = stagingPaths(agentId);
61
- if (!existsSync(staging.readyFile)) {
62
- throw new Error(`No READY file for agent ${agentId}`);
63
- }
64
- const agentPaths = ensureLdm(agentId);
65
- const stagedFiles = existsSync(staging.transcripts) ? readdirSync(staging.transcripts).filter((f) => f.endsWith(".jsonl")) : [];
66
- if (stagedFiles.length === 0) {
67
- unlinkSync(staging.readyFile);
68
- return {
69
- agentId,
70
- transcriptsProcessed: 0,
71
- backfillChunks: 0,
72
- dreamWeaverRan: false,
73
- durationMs: Date.now() - startTime
74
- };
75
- }
76
- for (const file of stagedFiles) {
77
- const src = join(staging.transcripts, file);
78
- const dest = join(agentPaths.transcripts, file);
79
- try {
80
- renameSync(src, dest);
81
- } catch {
82
- const { copyFileSync } = await import("fs");
83
- copyFileSync(src, dest);
84
- unlinkSync(src);
85
- }
86
- }
87
- let backfillChunks = 0;
88
- let dreamWeaverRan = false;
89
- try {
90
- const output = execSync(
91
- `crystal backfill --agent ${agentId}`,
92
- { encoding: "utf-8", timeout: 6e5 }
93
- );
94
- const match = output.match(/(\d+) chunks embedded/);
95
- if (match) backfillChunks = parseInt(match[1], 10);
96
- } catch (err) {
97
- process.stderr.write(`[staging] backfill failed for ${agentId}: ${err.message}
98
- `);
99
- }
100
- try {
101
- execSync(
102
- `crystal dream-weave --agent ${agentId} --mode full`,
103
- { encoding: "utf-8", timeout: 6e5 }
104
- );
105
- dreamWeaverRan = true;
106
- } catch (err) {
107
- process.stderr.write(`[staging] dream-weave failed for ${agentId}: ${err.message}
108
- `);
109
- }
110
- try {
111
- unlinkSync(staging.readyFile);
112
- } catch {
113
- }
114
- return {
115
- agentId,
116
- transcriptsProcessed: stagedFiles.length,
117
- backfillChunks,
118
- dreamWeaverRan,
119
- durationMs: Date.now() - startTime
120
- };
121
- }
122
- async function processAllStaged() {
123
- const agents = listStagedAgents();
124
- const results = [];
125
- for (const agentId of agents) {
126
- try {
127
- const result = await processStagedAgent(agentId);
128
- results.push(result);
129
- } catch (err) {
130
- process.stderr.write(`[staging] failed to process ${agentId}: ${err.message}
131
- `);
132
- }
133
- }
134
- return results;
135
- }
136
-
137
- export {
138
- stagingPaths,
139
- ensureStaging,
140
- markReady,
141
- isNewAgent,
142
- hasStagedData,
143
- listStagedAgents,
144
- processStagedAgent,
145
- processAllStaged
146
- };
@@ -1,6 +0,0 @@
1
- import {
2
- CloudCrystal
3
- } from "./chunk-J7MRSZIO.js";
4
- export {
5
- CloudCrystal
6
- };
@@ -1,6 +0,0 @@
1
- import {
2
- runDevUpdate
3
- } from "./chunk-MK42FMEG.js";
4
- export {
5
- runDevUpdate
6
- };
@@ -1,16 +0,0 @@
1
- import {
2
- detectProvider,
3
- expandQuery,
4
- hasSampling,
5
- rerankResults,
6
- setLLMCacheDb,
7
- setSamplingServer
8
- } from "./chunk-NX647OM3.js";
9
- export {
10
- detectProvider,
11
- expandQuery,
12
- hasSampling,
13
- rerankResults,
14
- setLLMCacheDb,
15
- setSamplingServer
16
- };
@@ -1,289 +0,0 @@
1
- // src/mlx-setup.ts
2
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
3
- import { execSync } from "child_process";
4
- import { join } from "path";
5
- import { homedir } from "os";
6
- var HOME = homedir();
7
- var MLX_PORT = 18791;
8
- var MLX_MODEL = "mlx-community/Qwen2.5-3B-Instruct-4bit";
9
- var MLX_STATE_FILE = join(HOME, ".ldm", "state", "mlx-server.json");
10
- var MLX_PLIST_LABEL = "ai.ldm.mlx-server";
11
- var MLX_PLIST_PATH = join(HOME, "Library", "LaunchAgents", `${MLX_PLIST_LABEL}.plist`);
12
- var MLX_LOG_PATH = "/tmp/mlx-server.log";
13
- function detectPlatform() {
14
- const platform = process.platform;
15
- const arch = process.arch;
16
- if (platform === "darwin") {
17
- return arch === "arm64" ? "apple-silicon" : "intel-mac";
18
- }
19
- if (platform === "linux") return "linux";
20
- return "other";
21
- }
22
- function canRunMlx() {
23
- return detectPlatform() === "apple-silicon";
24
- }
25
- function findPython() {
26
- const candidates = ["python3", "/opt/homebrew/bin/python3", "/usr/local/bin/python3"];
27
- for (const cmd of candidates) {
28
- try {
29
- const version = execSync(`${cmd} --version 2>&1`, { encoding: "utf-8", timeout: 5e3 }).trim();
30
- const match = version.match(/Python (\d+)\.(\d+)/);
31
- if (match && parseInt(match[1]) >= 3 && parseInt(match[2]) >= 10) {
32
- const realPath = execSync(`which ${cmd} 2>/dev/null`, { encoding: "utf-8", timeout: 3e3 }).trim();
33
- return realPath || cmd;
34
- }
35
- } catch {
36
- }
37
- }
38
- return null;
39
- }
40
- function findInstaller() {
41
- try {
42
- execSync("uv --version 2>/dev/null", { encoding: "utf-8", timeout: 3e3 });
43
- return "uv";
44
- } catch {
45
- }
46
- try {
47
- execSync("pip3 --version 2>/dev/null", { encoding: "utf-8", timeout: 3e3 });
48
- return "pip3";
49
- } catch {
50
- }
51
- return null;
52
- }
53
- function isMlxLmInstalled() {
54
- try {
55
- execSync('python3 -c "import mlx_lm" 2>/dev/null', { timeout: 5e3 });
56
- return true;
57
- } catch {
58
- return false;
59
- }
60
- }
61
- function installMlxLm(steps) {
62
- const installer = findInstaller();
63
- if (!installer) {
64
- steps.push("No pip3 or uv found. Cannot install mlx-lm.");
65
- return false;
66
- }
67
- const cmd = installer === "uv" ? "uv pip install mlx-lm" : "pip3 install mlx-lm";
68
- steps.push(`Installing mlx-lm via ${installer}...`);
69
- try {
70
- execSync(cmd, { encoding: "utf-8", timeout: 12e4, stdio: "pipe" });
71
- steps.push("mlx-lm installed successfully.");
72
- return true;
73
- } catch (err) {
74
- if (installer === "pip3") {
75
- try {
76
- execSync("pip3 install --user mlx-lm", { encoding: "utf-8", timeout: 12e4, stdio: "pipe" });
77
- steps.push("mlx-lm installed (--user) successfully.");
78
- return true;
79
- } catch {
80
- }
81
- }
82
- steps.push(`mlx-lm install failed: ${err.message.slice(0, 200)}`);
83
- return false;
84
- }
85
- }
86
- function isServerRunning() {
87
- try {
88
- const state = loadState();
89
- const port = state?.port || MLX_PORT;
90
- execSync(`curl -s -o /dev/null -w "%{http_code}" http://localhost:${port}/v1/models`, {
91
- encoding: "utf-8",
92
- timeout: 3e3
93
- });
94
- return true;
95
- } catch {
96
- return false;
97
- }
98
- }
99
- function createLaunchAgent(pythonPath, steps) {
100
- const plist = `<?xml version="1.0" encoding="UTF-8"?>
101
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
102
- <plist version="1.0">
103
- <dict>
104
- <key>Label</key>
105
- <string>${MLX_PLIST_LABEL}</string>
106
- <key>ProgramArguments</key>
107
- <array>
108
- <string>${pythonPath}</string>
109
- <string>-m</string>
110
- <string>mlx_lm.server</string>
111
- <string>--model</string>
112
- <string>${MLX_MODEL}</string>
113
- <string>--port</string>
114
- <string>${MLX_PORT}</string>
115
- </array>
116
- <key>RunAtLoad</key>
117
- <true/>
118
- <key>KeepAlive</key>
119
- <true/>
120
- <key>StandardOutPath</key>
121
- <string>${MLX_LOG_PATH}</string>
122
- <key>StandardErrorPath</key>
123
- <string>${MLX_LOG_PATH}</string>
124
- </dict>
125
- </plist>`;
126
- try {
127
- writeFileSync(MLX_PLIST_PATH, plist);
128
- execSync(`launchctl load "${MLX_PLIST_PATH}" 2>/dev/null`, { timeout: 5e3 });
129
- steps.push(`LaunchAgent installed at ${MLX_PLIST_PATH}`);
130
- steps.push(`MLX server will start on port ${MLX_PORT}`);
131
- return true;
132
- } catch (err) {
133
- steps.push(`LaunchAgent install failed: ${err.message}`);
134
- return false;
135
- }
136
- }
137
- function startServer(steps) {
138
- try {
139
- execSync(`launchctl kickstart -kp gui/$(id -u)/${MLX_PLIST_LABEL} 2>/dev/null`, { timeout: 1e4 });
140
- steps.push("MLX server started.");
141
- return true;
142
- } catch {
143
- steps.push("MLX server start failed. Check /tmp/mlx-server.log");
144
- return false;
145
- }
146
- }
147
- function stopServer() {
148
- try {
149
- execSync(`launchctl unload "${MLX_PLIST_PATH}" 2>/dev/null`, { timeout: 5e3 });
150
- return true;
151
- } catch {
152
- return false;
153
- }
154
- }
155
- function loadState() {
156
- try {
157
- if (existsSync(MLX_STATE_FILE)) {
158
- return JSON.parse(readFileSync(MLX_STATE_FILE, "utf-8"));
159
- }
160
- } catch {
161
- }
162
- return null;
163
- }
164
- function saveState(state) {
165
- const dir = join(HOME, ".ldm", "state");
166
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
167
- writeFileSync(MLX_STATE_FILE, JSON.stringify(state, null, 2) + "\n");
168
- }
169
- async function verifyServer(steps) {
170
- const state = loadState();
171
- const port = state?.port || MLX_PORT;
172
- for (let i = 0; i < 15; i++) {
173
- try {
174
- const resp = await fetch(`http://localhost:${port}/v1/models`, {
175
- signal: AbortSignal.timeout(2e3)
176
- });
177
- if (resp.ok) {
178
- const data = await resp.json();
179
- const model = data?.data?.[0]?.id || "unknown";
180
- steps.push(`MLX server verified: ${model} on port ${port}`);
181
- return true;
182
- }
183
- } catch {
184
- }
185
- await new Promise((r) => setTimeout(r, 2e3));
186
- }
187
- steps.push("MLX server did not respond within 30 seconds. Check /tmp/mlx-server.log");
188
- return false;
189
- }
190
- async function setupMlx(options) {
191
- const steps = [];
192
- const platform = detectPlatform();
193
- if (platform !== "apple-silicon") {
194
- steps.push(`Platform: ${platform}. MLX requires Apple Silicon. Skipping.`);
195
- return { ok: false, steps };
196
- }
197
- steps.push("Platform: Apple Silicon detected.");
198
- const pythonPath = findPython();
199
- if (!pythonPath) {
200
- steps.push("Python 3.10+ not found. Install via: brew install python3");
201
- return { ok: false, steps };
202
- }
203
- steps.push(`Python: ${pythonPath}`);
204
- if (!isMlxLmInstalled()) {
205
- if (!options?.yes) {
206
- steps.push("mlx-lm not installed. Run with --yes to auto-install, or: pip3 install mlx-lm");
207
- return { ok: false, steps };
208
- }
209
- const installed = installMlxLm(steps);
210
- if (!installed) return { ok: false, steps };
211
- } else {
212
- steps.push("mlx-lm: already installed.");
213
- }
214
- if (!existsSync(MLX_PLIST_PATH)) {
215
- const created = createLaunchAgent(pythonPath, steps);
216
- if (!created) return { ok: false, steps };
217
- } else {
218
- steps.push("LaunchAgent: already installed.");
219
- }
220
- saveState({
221
- installed: true,
222
- port: MLX_PORT,
223
- model: MLX_MODEL,
224
- pythonPath,
225
- installedAt: (/* @__PURE__ */ new Date()).toISOString()
226
- });
227
- if (!isServerRunning()) {
228
- startServer(steps);
229
- steps.push(`Waiting for model to load (~1.5 GB on first run)...`);
230
- const verified = await verifyServer(steps);
231
- if (!verified) {
232
- steps.push("Server started but not yet responding. It may still be downloading the model.");
233
- steps.push(`Check: tail -f ${MLX_LOG_PATH}`);
234
- }
235
- } else {
236
- steps.push(`MLX server: already running on port ${MLX_PORT}`);
237
- }
238
- return { ok: true, steps };
239
- }
240
- function doctorCheck() {
241
- const platform = detectPlatform();
242
- if (platform !== "apple-silicon") {
243
- return { status: "skip", detail: `${platform} (MLX requires Apple Silicon)` };
244
- }
245
- const state = loadState();
246
- if (!state || !state.installed) {
247
- return {
248
- status: "warn",
249
- detail: "not installed",
250
- fix: "crystal init (will offer MLX setup)"
251
- };
252
- }
253
- if (isServerRunning()) {
254
- return { status: "ok", detail: `running on port ${state.port} (${state.model})` };
255
- }
256
- if (existsSync(MLX_PLIST_PATH)) {
257
- return {
258
- status: "warn",
259
- detail: "installed but not running",
260
- fix: `launchctl kickstart -kp gui/$(id -u)/${MLX_PLIST_LABEL}`
261
- };
262
- }
263
- return {
264
- status: "warn",
265
- detail: "installed but LaunchAgent missing",
266
- fix: "crystal init (will recreate LaunchAgent)"
267
- };
268
- }
269
- var MLX_CONFIG = {
270
- port: MLX_PORT,
271
- model: MLX_MODEL,
272
- plistPath: MLX_PLIST_PATH,
273
- logPath: MLX_LOG_PATH,
274
- stateFile: MLX_STATE_FILE
275
- };
276
- export {
277
- MLX_CONFIG,
278
- canRunMlx,
279
- createLaunchAgent,
280
- detectPlatform,
281
- doctorCheck,
282
- installMlxLm,
283
- isMlxLmInstalled,
284
- isServerRunning,
285
- setupMlx,
286
- startServer,
287
- stopServer,
288
- verifyServer
289
- };