neuralbrain 0.0.0-stage → 0.0.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 (293) hide show
  1. package/.dockerignore +11 -0
  2. package/.env.example +245 -0
  3. package/Dockerfile +65 -0
  4. package/LICENSE +44 -0
  5. package/README.md +312 -2
  6. package/dist/ai/chat.d.ts +45 -0
  7. package/dist/ai/chat.d.ts.map +1 -0
  8. package/dist/ai/chat.js +153 -0
  9. package/dist/ai/chat.js.map +1 -0
  10. package/dist/ai/circuitBreaker.d.ts +35 -0
  11. package/dist/ai/circuitBreaker.d.ts.map +1 -0
  12. package/dist/ai/circuitBreaker.js +95 -0
  13. package/dist/ai/circuitBreaker.js.map +1 -0
  14. package/dist/ai/config.d.ts +88 -0
  15. package/dist/ai/config.d.ts.map +1 -0
  16. package/dist/ai/config.js +255 -0
  17. package/dist/ai/config.js.map +1 -0
  18. package/dist/ai/vendors.d.ts +58 -0
  19. package/dist/ai/vendors.d.ts.map +1 -0
  20. package/dist/ai/vendors.js +223 -0
  21. package/dist/ai/vendors.js.map +1 -0
  22. package/dist/app.d.ts +4 -0
  23. package/dist/app.d.ts.map +1 -0
  24. package/dist/app.js +1013 -0
  25. package/dist/app.js.map +1 -0
  26. package/dist/cli.d.ts +133 -0
  27. package/dist/cli.d.ts.map +1 -0
  28. package/dist/cli.js +912 -0
  29. package/dist/cli.js.map +1 -0
  30. package/dist/consolidation/candidates.d.ts +34 -0
  31. package/dist/consolidation/candidates.d.ts.map +1 -0
  32. package/dist/consolidation/candidates.js +150 -0
  33. package/dist/consolidation/candidates.js.map +1 -0
  34. package/dist/consolidation/fixtures.d.ts +25 -0
  35. package/dist/consolidation/fixtures.d.ts.map +1 -0
  36. package/dist/consolidation/fixtures.js +400 -0
  37. package/dist/consolidation/fixtures.js.map +1 -0
  38. package/dist/consolidation/gate.d.ts +39 -0
  39. package/dist/consolidation/gate.d.ts.map +1 -0
  40. package/dist/consolidation/gate.js +286 -0
  41. package/dist/consolidation/gate.js.map +1 -0
  42. package/dist/consolidation/runner.d.ts +63 -0
  43. package/dist/consolidation/runner.d.ts.map +1 -0
  44. package/dist/consolidation/runner.js +171 -0
  45. package/dist/consolidation/runner.js.map +1 -0
  46. package/dist/dashboard/clientScript.d.ts +2 -0
  47. package/dist/dashboard/clientScript.d.ts.map +1 -0
  48. package/dist/dashboard/clientScript.js +4212 -0
  49. package/dist/dashboard/clientScript.js.map +1 -0
  50. package/dist/dashboard/html.d.ts +2 -0
  51. package/dist/dashboard/html.d.ts.map +1 -0
  52. package/dist/dashboard/html.js +554 -0
  53. package/dist/dashboard/html.js.map +1 -0
  54. package/dist/dashboard/styles.d.ts +2 -0
  55. package/dist/dashboard/styles.d.ts.map +1 -0
  56. package/dist/dashboard/styles.js +1283 -0
  57. package/dist/dashboard/styles.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +124 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/learning/embedWorker.d.ts +58 -0
  63. package/dist/learning/embedWorker.d.ts.map +1 -0
  64. package/dist/learning/embedWorker.js +552 -0
  65. package/dist/learning/embedWorker.js.map +1 -0
  66. package/dist/learning/embedding.d.ts +52 -0
  67. package/dist/learning/embedding.d.ts.map +1 -0
  68. package/dist/learning/embedding.js +511 -0
  69. package/dist/learning/embedding.js.map +1 -0
  70. package/dist/learning/engine.d.ts +20 -0
  71. package/dist/learning/engine.d.ts.map +1 -0
  72. package/dist/learning/engine.js +69 -0
  73. package/dist/learning/engine.js.map +1 -0
  74. package/dist/learning/search.d.ts +4 -0
  75. package/dist/learning/search.d.ts.map +1 -0
  76. package/dist/learning/search.js +509 -0
  77. package/dist/learning/search.js.map +1 -0
  78. package/dist/learning/storeMeta.d.ts +11 -0
  79. package/dist/learning/storeMeta.d.ts.map +1 -0
  80. package/dist/learning/storeMeta.js +100 -0
  81. package/dist/learning/storeMeta.js.map +1 -0
  82. package/dist/learning/types.d.ts +101 -0
  83. package/dist/learning/types.d.ts.map +1 -0
  84. package/dist/learning/types.js +3 -0
  85. package/dist/learning/types.js.map +1 -0
  86. package/dist/lib/brainHome.d.ts +28 -0
  87. package/dist/lib/brainHome.d.ts.map +1 -0
  88. package/dist/lib/brainHome.js +104 -0
  89. package/dist/lib/brainHome.js.map +1 -0
  90. package/dist/lib/db.d.ts +10 -0
  91. package/dist/lib/db.d.ts.map +1 -0
  92. package/dist/lib/db.js +589 -0
  93. package/dist/lib/db.js.map +1 -0
  94. package/dist/lib/logger.d.ts +3 -0
  95. package/dist/lib/logger.d.ts.map +1 -0
  96. package/dist/lib/logger.js +11 -0
  97. package/dist/lib/logger.js.map +1 -0
  98. package/dist/lib/projectSlug.d.ts +61 -0
  99. package/dist/lib/projectSlug.d.ts.map +1 -0
  100. package/dist/lib/projectSlug.js +273 -0
  101. package/dist/lib/projectSlug.js.map +1 -0
  102. package/dist/lib/redactSecrets.d.ts +7 -0
  103. package/dist/lib/redactSecrets.d.ts.map +1 -0
  104. package/dist/lib/redactSecrets.js +90 -0
  105. package/dist/lib/redactSecrets.js.map +1 -0
  106. package/dist/lib/scope.d.ts +54 -0
  107. package/dist/lib/scope.d.ts.map +1 -0
  108. package/dist/lib/scope.js +103 -0
  109. package/dist/lib/scope.js.map +1 -0
  110. package/dist/lib/spool.d.ts +23 -0
  111. package/dist/lib/spool.d.ts.map +1 -0
  112. package/dist/lib/spool.js +317 -0
  113. package/dist/lib/spool.js.map +1 -0
  114. package/dist/lib/sqlite.d.ts +50 -0
  115. package/dist/lib/sqlite.d.ts.map +1 -0
  116. package/dist/lib/sqlite.js +130 -0
  117. package/dist/lib/sqlite.js.map +1 -0
  118. package/dist/lib/tls.d.ts +34 -0
  119. package/dist/lib/tls.d.ts.map +1 -0
  120. package/dist/lib/tls.js +212 -0
  121. package/dist/lib/tls.js.map +1 -0
  122. package/dist/mcp/server.d.ts +231 -0
  123. package/dist/mcp/server.d.ts.map +1 -0
  124. package/dist/mcp/server.js +615 -0
  125. package/dist/mcp/server.js.map +1 -0
  126. package/dist/memory/actionStore.d.ts +75 -0
  127. package/dist/memory/actionStore.d.ts.map +1 -0
  128. package/dist/memory/actionStore.js +239 -0
  129. package/dist/memory/actionStore.js.map +1 -0
  130. package/dist/memory/deadLetterStore.d.ts +30 -0
  131. package/dist/memory/deadLetterStore.d.ts.map +1 -0
  132. package/dist/memory/deadLetterStore.js +91 -0
  133. package/dist/memory/deadLetterStore.js.map +1 -0
  134. package/dist/memory/embedQueueStore.d.ts +32 -0
  135. package/dist/memory/embedQueueStore.d.ts.map +1 -0
  136. package/dist/memory/embedQueueStore.js +143 -0
  137. package/dist/memory/embedQueueStore.js.map +1 -0
  138. package/dist/memory/failurePatternStore.d.ts +37 -0
  139. package/dist/memory/failurePatternStore.d.ts.map +1 -0
  140. package/dist/memory/failurePatternStore.js +179 -0
  141. package/dist/memory/failurePatternStore.js.map +1 -0
  142. package/dist/memory/graphStore.d.ts +38 -0
  143. package/dist/memory/graphStore.d.ts.map +1 -0
  144. package/dist/memory/graphStore.js +229 -0
  145. package/dist/memory/graphStore.js.map +1 -0
  146. package/dist/memory/noteStore.d.ts +58 -0
  147. package/dist/memory/noteStore.d.ts.map +1 -0
  148. package/dist/memory/noteStore.js +280 -0
  149. package/dist/memory/noteStore.js.map +1 -0
  150. package/dist/memory/observationStore.d.ts +40 -0
  151. package/dist/memory/observationStore.d.ts.map +1 -0
  152. package/dist/memory/observationStore.js +213 -0
  153. package/dist/memory/observationStore.js.map +1 -0
  154. package/dist/memory/projectRename.d.ts +14 -0
  155. package/dist/memory/projectRename.d.ts.map +1 -0
  156. package/dist/memory/projectRename.js +105 -0
  157. package/dist/memory/projectRename.js.map +1 -0
  158. package/dist/memory/rollupSweeper.d.ts +36 -0
  159. package/dist/memory/rollupSweeper.d.ts.map +1 -0
  160. package/dist/memory/rollupSweeper.js +235 -0
  161. package/dist/memory/rollupSweeper.js.map +1 -0
  162. package/dist/memory/sessionStore.d.ts +81 -0
  163. package/dist/memory/sessionStore.d.ts.map +1 -0
  164. package/dist/memory/sessionStore.js +285 -0
  165. package/dist/memory/sessionStore.js.map +1 -0
  166. package/dist/memory/trajectoryStore.d.ts +86 -0
  167. package/dist/memory/trajectoryStore.d.ts.map +1 -0
  168. package/dist/memory/trajectoryStore.js +528 -0
  169. package/dist/memory/trajectoryStore.js.map +1 -0
  170. package/dist/middleware/auth.d.ts +30 -0
  171. package/dist/middleware/auth.d.ts.map +1 -0
  172. package/dist/middleware/auth.js +387 -0
  173. package/dist/middleware/auth.js.map +1 -0
  174. package/dist/middleware/rateLimiter.d.ts +13 -0
  175. package/dist/middleware/rateLimiter.d.ts.map +1 -0
  176. package/dist/middleware/rateLimiter.js +153 -0
  177. package/dist/middleware/rateLimiter.js.map +1 -0
  178. package/dist/middleware/tracing.d.ts +15 -0
  179. package/dist/middleware/tracing.d.ts.map +1 -0
  180. package/dist/middleware/tracing.js +53 -0
  181. package/dist/middleware/tracing.js.map +1 -0
  182. package/dist/routes/dashboard.d.ts +2 -0
  183. package/dist/routes/dashboard.d.ts.map +1 -0
  184. package/dist/routes/dashboard.js +443 -0
  185. package/dist/routes/dashboard.js.map +1 -0
  186. package/dist/routes/learning.d.ts +2 -0
  187. package/dist/routes/learning.d.ts.map +1 -0
  188. package/dist/routes/learning.js +46 -0
  189. package/dist/routes/learning.js.map +1 -0
  190. package/dist/routes/mcp.d.ts +8 -0
  191. package/dist/routes/mcp.d.ts.map +1 -0
  192. package/dist/routes/mcp.js +316 -0
  193. package/dist/routes/mcp.js.map +1 -0
  194. package/dist/routes/memories.d.ts +2 -0
  195. package/dist/routes/memories.d.ts.map +1 -0
  196. package/dist/routes/memories.js +33 -0
  197. package/dist/routes/memories.js.map +1 -0
  198. package/dist/scripts/createApiKey.d.ts +2 -0
  199. package/dist/scripts/createApiKey.d.ts.map +1 -0
  200. package/dist/scripts/createApiKey.js +78 -0
  201. package/dist/scripts/createApiKey.js.map +1 -0
  202. package/dist/scripts/doctor.d.ts +24 -0
  203. package/dist/scripts/doctor.d.ts.map +1 -0
  204. package/dist/scripts/doctor.js +332 -0
  205. package/dist/scripts/doctor.js.map +1 -0
  206. package/dist/scripts/installAgent.d.ts +80 -0
  207. package/dist/scripts/installAgent.d.ts.map +1 -0
  208. package/dist/scripts/installAgent.js +1046 -0
  209. package/dist/scripts/installAgent.js.map +1 -0
  210. package/dist/scripts/migrateAgentMemory.d.ts +16 -0
  211. package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
  212. package/dist/scripts/migrateAgentMemory.js +209 -0
  213. package/dist/scripts/migrateAgentMemory.js.map +1 -0
  214. package/dist/scripts/smokeTest.d.ts +16 -0
  215. package/dist/scripts/smokeTest.d.ts.map +1 -0
  216. package/dist/scripts/smokeTest.js +150 -0
  217. package/dist/scripts/smokeTest.js.map +1 -0
  218. package/docker-compose.qdrant-port.yml +7 -0
  219. package/docker-compose.yml +107 -0
  220. package/npm-shrinkwrap.json +7635 -0
  221. package/package.json +106 -4
  222. package/plugin/hooks/postToolUse.js +513 -0
  223. package/plugin/hooks/sessionStart.js +416 -0
  224. package/plugin/hooks/sessionStop.js +346 -0
  225. package/plugin/hooks.json +30 -0
  226. package/plugin/mcp_config.json +13 -0
  227. package/plugin/plugin.json +15 -0
  228. package/plugin/rules/AGENTS.md +66 -0
  229. package/plugin/skills/brain-memory/REFERENCE.md +64 -0
  230. package/plugin/skills/brain-memory/SKILL.md +68 -0
  231. package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
  232. package/plugin/skills/digest/SKILL.md +54 -0
  233. package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
  234. package/plugin/skills/handoff/SKILL.md +59 -0
  235. package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
  236. package/plugin/skills/save/SKILL.md +76 -0
  237. package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
  238. package/plugin/skills/search/SKILL.md +60 -0
  239. package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
  240. package/src/ai/chat.ts +214 -0
  241. package/src/ai/circuitBreaker.ts +120 -0
  242. package/src/ai/config.ts +311 -0
  243. package/src/ai/vendors.ts +292 -0
  244. package/src/app.ts +1150 -0
  245. package/src/cli.ts +1080 -0
  246. package/src/consolidation/candidates.ts +219 -0
  247. package/src/consolidation/fixtures.ts +461 -0
  248. package/src/consolidation/gate.ts +408 -0
  249. package/src/consolidation/runner.ts +220 -0
  250. package/src/dashboard/clientScript.ts +4208 -0
  251. package/src/dashboard/html.ts +550 -0
  252. package/src/dashboard/styles.ts +1279 -0
  253. package/src/index.ts +139 -0
  254. package/src/learning/embedWorker.ts +651 -0
  255. package/src/learning/embedding.ts +522 -0
  256. package/src/learning/engine.ts +86 -0
  257. package/src/learning/search.ts +568 -0
  258. package/src/learning/storeMeta.ts +147 -0
  259. package/src/learning/types.ts +111 -0
  260. package/src/lib/brainHome.ts +101 -0
  261. package/src/lib/db.ts +627 -0
  262. package/src/lib/logger.ts +7 -0
  263. package/src/lib/projectSlug.ts +286 -0
  264. package/src/lib/redactSecrets.ts +87 -0
  265. package/src/lib/scope.ts +121 -0
  266. package/src/lib/spool.ts +372 -0
  267. package/src/lib/sqlite.ts +158 -0
  268. package/src/lib/tls.ts +252 -0
  269. package/src/mcp/server.ts +793 -0
  270. package/src/memory/actionStore.ts +378 -0
  271. package/src/memory/deadLetterStore.ts +141 -0
  272. package/src/memory/embedQueueStore.ts +176 -0
  273. package/src/memory/failurePatternStore.ts +221 -0
  274. package/src/memory/graphStore.ts +352 -0
  275. package/src/memory/noteStore.ts +403 -0
  276. package/src/memory/observationStore.ts +303 -0
  277. package/src/memory/projectRename.ts +147 -0
  278. package/src/memory/rollupSweeper.ts +309 -0
  279. package/src/memory/sessionStore.ts +410 -0
  280. package/src/memory/trajectoryStore.ts +775 -0
  281. package/src/middleware/auth.ts +450 -0
  282. package/src/middleware/rateLimiter.ts +186 -0
  283. package/src/middleware/tracing.ts +70 -0
  284. package/src/routes/dashboard.ts +496 -0
  285. package/src/routes/learning.ts +51 -0
  286. package/src/routes/mcp.ts +349 -0
  287. package/src/routes/memories.ts +33 -0
  288. package/src/scripts/createApiKey.ts +109 -0
  289. package/src/scripts/doctor.ts +359 -0
  290. package/src/scripts/installAgent.ts +1278 -0
  291. package/src/scripts/migrateAgentMemory.ts +263 -0
  292. package/src/scripts/smokeTest.ts +189 -0
  293. package/tsconfig.json +21 -0
package/dist/cli.js ADDED
@@ -0,0 +1,912 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.readRuntimeMode = readRuntimeMode;
8
+ exports.upsertEnvContent = upsertEnvContent;
9
+ exports.initializeBrainHome = initializeBrainHome;
10
+ exports.parseInstallArgs = parseInstallArgs;
11
+ exports.hostNeedsLocalEmbedder = hostNeedsLocalEmbedder;
12
+ exports.ensureLocalEmbedder = ensureLocalEmbedder;
13
+ exports.isNpxCacheCopy = isNpxCacheCopy;
14
+ exports.isInstalledCopy = isInstalledCopy;
15
+ exports.installGlobalPackage = installGlobalPackage;
16
+ exports.modeUsesCompose = modeUsesCompose;
17
+ exports.runInit = runInit;
18
+ const crypto_1 = __importDefault(require("crypto"));
19
+ const fs_1 = __importDefault(require("fs"));
20
+ const https_1 = __importDefault(require("https"));
21
+ const os_1 = __importDefault(require("os"));
22
+ const path_1 = __importDefault(require("path"));
23
+ const promises_1 = __importDefault(require("readline/promises"));
24
+ const child_process_1 = require("child_process");
25
+ const dotenv_1 = __importDefault(require("dotenv"));
26
+ const brainHome_1 = require("./lib/brainHome");
27
+ const tls_1 = require("./lib/tls");
28
+ const projectSlug_1 = require("./lib/projectSlug");
29
+ const scope_1 = require("./lib/scope");
30
+ const installAgent_1 = require("./scripts/installAgent");
31
+ const COMPOSE_PROJECT_NAME = 'neuralbrain';
32
+ function getPackageRoot() {
33
+ return path_1.default.resolve(__dirname, '..');
34
+ }
35
+ function getModeFilePath(homeDir) {
36
+ return path_1.default.join((0, brainHome_1.getBrainHomeDir)(homeDir), 'mode');
37
+ }
38
+ function getPidFilePath(homeDir) {
39
+ return path_1.default.join((0, brainHome_1.getBrainHomeDir)(homeDir), 'brain.pid');
40
+ }
41
+ function getLogFilePath(homeDir) {
42
+ return path_1.default.join((0, brainHome_1.getBrainHomeDir)(homeDir), 'brain.log');
43
+ }
44
+ function readRuntimeMode(homeDir) {
45
+ const modePath = getModeFilePath(homeDir);
46
+ if (!fs_1.default.existsSync(modePath))
47
+ return null;
48
+ const raw = fs_1.default.readFileSync(modePath, 'utf8').trim();
49
+ if (raw === 'docker' || raw === 'qdrant-docker' || raw === 'local-only') {
50
+ return raw;
51
+ }
52
+ return null;
53
+ }
54
+ /**
55
+ * Updates or appends key=value pairs in an existing .env string while preserving
56
+ * unrelated lines and comments.
57
+ */
58
+ function upsertEnvContent(existing, updates) {
59
+ const lines = existing ? existing.split(/\r?\n/) : [];
60
+ const remaining = new Map(Object.entries(updates));
61
+ const out = [];
62
+ for (const line of lines) {
63
+ const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/);
64
+ if (match && remaining.has(match[1])) {
65
+ const key = match[1];
66
+ out.push(`${key}=${remaining.get(key)}`);
67
+ remaining.delete(key);
68
+ }
69
+ else {
70
+ out.push(line);
71
+ }
72
+ }
73
+ // Trim trailing empty lines before appending new keys
74
+ while (out.length > 0 && out[out.length - 1] === '') {
75
+ out.pop();
76
+ }
77
+ for (const [key, value] of remaining.entries()) {
78
+ out.push(`${key}=${value}`);
79
+ }
80
+ return out.join('\n') + '\n';
81
+ }
82
+ /**
83
+ * Initializes ~/.neuralbrain/ directories, mode file, and ~/.neuralbrain/.env.
84
+ */
85
+ function initializeBrainHome(options) {
86
+ const brainHome = (0, brainHome_1.getBrainHomeDir)(options.homeDir);
87
+ const dataDir = (0, brainHome_1.getBrainDataDir)(options.homeDir);
88
+ const modelsDir = (0, brainHome_1.getDefaultModelCacheDir)(options.homeDir);
89
+ const qdrantDir = (0, brainHome_1.getDefaultQdrantDir)(options.homeDir);
90
+ const spoolDir = (0, brainHome_1.getDefaultSpoolDir)(options.homeDir);
91
+ const envPath = (0, brainHome_1.getBrainEnvPath)(options.homeDir);
92
+ const modePath = getModeFilePath(options.homeDir);
93
+ for (const dir of [brainHome, dataDir, modelsDir, qdrantDir, spoolDir]) {
94
+ fs_1.default.mkdirSync(dir, { recursive: true });
95
+ }
96
+ fs_1.default.writeFileSync(modePath, `${options.mode}\n`, 'utf8');
97
+ const existingRaw = fs_1.default.existsSync(envPath) ? fs_1.default.readFileSync(envPath, 'utf8') : '';
98
+ const parsed = existingRaw ? dotenv_1.default.parse(existingRaw) : {};
99
+ const createdEnv = !fs_1.default.existsSync(envPath);
100
+ const port = options.port || (parsed.PORT ? parseInt(parsed.PORT, 10) : 3737) || 3737;
101
+ const apiKey = parsed.BRAIN_API_KEY?.trim() || crypto_1.default.randomBytes(32).toString('hex');
102
+ const useHttps = options.https ?? (parsed.BRAIN_HTTPS?.trim() === '1' || parsed.BRAIN_HTTPS?.trim() === 'true');
103
+ const updates = {
104
+ PORT: String(port),
105
+ HOST: parsed.HOST?.trim() || '127.0.0.1',
106
+ BRAIN_HOME: brainHome,
107
+ BRAIN_DATA_DIR: dataDir,
108
+ BRAIN_QDRANT_DIR: qdrantDir,
109
+ BRAIN_REQUIRE_API_KEY: parsed.BRAIN_REQUIRE_API_KEY?.trim() || '1',
110
+ BRAIN_API_KEY: apiKey,
111
+ BRAIN_AI: parsed.BRAIN_AI?.trim() || 'agent',
112
+ };
113
+ if (useHttps) {
114
+ updates.BRAIN_HTTPS = '1';
115
+ updates.BRAIN_API_URL = `https://127.0.0.1:${port}`;
116
+ (0, tls_1.ensureLocalTlsCerts)({ homeDir: options.homeDir });
117
+ }
118
+ if (options.gpu && options.mode === 'local-only') {
119
+ throw new Error('--gpu requires --mode docker or --mode qdrant-docker (spawns the Docker Compose gpu profile).');
120
+ }
121
+ if (options.mode === 'local-only') {
122
+ updates.BRAIN_EMBED = 'none';
123
+ }
124
+ else {
125
+ updates.BRAIN_EMBED = options.gpu ? 'local-gpu' : 'local';
126
+ updates.BRAIN_EMBED_MODEL = parsed.BRAIN_EMBED_MODEL?.trim() || 'nomic';
127
+ updates.BRAIN_EMBED_DIM = parsed.BRAIN_EMBED_DIM?.trim() || '512';
128
+ if (options.mode === 'qdrant-docker') {
129
+ updates.QDRANT_URL = parsed.QDRANT_URL?.trim() || 'http://127.0.0.1:6333';
130
+ }
131
+ }
132
+ const nextContent = createdEnv
133
+ ? [
134
+ '# neuralbrain user configuration (~/.neuralbrain/.env)',
135
+ upsertEnvContent('', updates).trimEnd(),
136
+ '',
137
+ ].join('\n')
138
+ : upsertEnvContent(existingRaw, updates);
139
+ fs_1.default.writeFileSync(envPath, nextContent, { mode: 0o600, encoding: 'utf8' });
140
+ return {
141
+ brainHome,
142
+ dataDir,
143
+ qdrantDir,
144
+ envPath,
145
+ modePath,
146
+ apiKey,
147
+ port,
148
+ https: useHttps,
149
+ createdEnv,
150
+ };
151
+ }
152
+ function parseInstallArgs(argv) {
153
+ const opts = { yes: false };
154
+ for (let i = 0; i < argv.length; i++) {
155
+ const arg = argv[i];
156
+ if (arg === '--yes' || arg === '-y') {
157
+ opts.yes = true;
158
+ }
159
+ else if (arg === '--mode') {
160
+ const val = argv[++i];
161
+ if (val === 'docker' || val === 'qdrant-docker' || val === 'local-only') {
162
+ opts.mode = val;
163
+ }
164
+ else {
165
+ throw new Error(`Invalid --mode '${val}'. Expected: docker | qdrant-docker | local-only`);
166
+ }
167
+ }
168
+ else if (arg === '--no-global') {
169
+ opts.global = false;
170
+ }
171
+ else if (arg === '--global') {
172
+ opts.global = true;
173
+ }
174
+ else if (arg === '--no-agents') {
175
+ opts.agents = false;
176
+ }
177
+ else if (arg === '--agents') {
178
+ opts.agents = true;
179
+ }
180
+ else if (arg === '--port') {
181
+ const p = parseInt(argv[++i], 10);
182
+ if (Number.isNaN(p) || p <= 0) {
183
+ throw new Error(`Invalid --port value`);
184
+ }
185
+ opts.port = p;
186
+ }
187
+ else if (arg === '--https') {
188
+ opts.https = true;
189
+ }
190
+ else if (arg === '--gpu') {
191
+ opts.gpu = true;
192
+ }
193
+ else {
194
+ throw new Error(`Unknown option: ${arg}`);
195
+ }
196
+ }
197
+ return opts;
198
+ }
199
+ function hasDockerCompose() {
200
+ const res = (0, child_process_1.spawnSync)('docker', ['compose', 'version'], { stdio: 'ignore' });
201
+ return res.status === 0;
202
+ }
203
+ function runCompose(args, envPath, packageRoot, extraComposeFiles = []) {
204
+ const composeFile = path_1.default.join(packageRoot, 'docker-compose.yml');
205
+ const fileFlags = [composeFile, ...extraComposeFiles].flatMap((file) => ['-f', file]);
206
+ const res = (0, child_process_1.spawnSync)('docker', ['compose', '-p', COMPOSE_PROJECT_NAME, ...fileFlags, '--env-file', envPath, ...args], {
207
+ cwd: packageRoot,
208
+ stdio: 'inherit',
209
+ env: { ...process.env, HOME: os_1.default.homedir() },
210
+ });
211
+ return res.status ?? 1;
212
+ }
213
+ function isPidAlive(pid) {
214
+ try {
215
+ process.kill(pid, 0);
216
+ return true;
217
+ }
218
+ catch {
219
+ return false;
220
+ }
221
+ }
222
+ function startHostDaemon(packageRoot, envPath) {
223
+ const pidFile = getPidFilePath();
224
+ if (fs_1.default.existsSync(pidFile)) {
225
+ const existingPid = parseInt(fs_1.default.readFileSync(pidFile, 'utf8').trim(), 10);
226
+ if (!Number.isNaN(existingPid) && isPidAlive(existingPid)) {
227
+ console.log(` Brain daemon already running (pid ${existingPid})`);
228
+ return existingPid;
229
+ }
230
+ }
231
+ const logPath = getLogFilePath();
232
+ const out = fs_1.default.openSync(logPath, 'a');
233
+ const entryJs = path_1.default.join(packageRoot, 'dist', 'index.js');
234
+ const parsedEnv = dotenv_1.default.parse(fs_1.default.readFileSync(envPath, 'utf8'));
235
+ const child = (0, child_process_1.spawn)(process.execPath, [entryJs], {
236
+ cwd: (0, brainHome_1.getBrainHomeDir)(),
237
+ detached: true,
238
+ stdio: ['ignore', out, out],
239
+ env: {
240
+ ...process.env,
241
+ ...parsedEnv,
242
+ NODE_ENV: process.env.NODE_ENV || 'production',
243
+ },
244
+ });
245
+ child.unref();
246
+ if (child.pid) {
247
+ fs_1.default.writeFileSync(pidFile, `${child.pid}\n`, 'utf8');
248
+ }
249
+ return child.pid ?? 0;
250
+ }
251
+ function stopHostDaemon() {
252
+ const pidFile = getPidFilePath();
253
+ if (!fs_1.default.existsSync(pidFile))
254
+ return false;
255
+ const pid = parseInt(fs_1.default.readFileSync(pidFile, 'utf8').trim(), 10);
256
+ fs_1.default.rmSync(pidFile, { force: true });
257
+ if (!Number.isNaN(pid) && isPidAlive(pid)) {
258
+ try {
259
+ process.kill(pid, 'SIGTERM');
260
+ return true;
261
+ }
262
+ catch {
263
+ return false;
264
+ }
265
+ }
266
+ return false;
267
+ }
268
+ function isHttpsEnabled() {
269
+ return (process.env.BRAIN_HTTPS === '1' ||
270
+ process.env.BRAIN_HTTPS === 'true' ||
271
+ Boolean(process.env.BRAIN_TLS_CERT && process.env.BRAIN_TLS_KEY));
272
+ }
273
+ async function checkHealth(port, useHttps) {
274
+ if (!useHttps) {
275
+ try {
276
+ const res = await fetch(`http://127.0.0.1:${port}/health`);
277
+ return { ok: res.ok, status: res.status };
278
+ }
279
+ catch {
280
+ return null;
281
+ }
282
+ }
283
+ const certPath = process.env.BRAIN_TLS_CERT?.trim() || path_1.default.join((0, tls_1.getDefaultCertsDir)(), 'server.crt');
284
+ const ca = fs_1.default.existsSync(certPath) ? fs_1.default.readFileSync(certPath) : undefined;
285
+ return new Promise((resolve) => {
286
+ const req = https_1.default.request({
287
+ hostname: '127.0.0.1',
288
+ port,
289
+ path: '/health',
290
+ method: 'GET',
291
+ ca,
292
+ timeout: 3000,
293
+ }, (res) => {
294
+ res.resume();
295
+ const status = res.statusCode ?? 0;
296
+ resolve({ ok: status >= 200 && status < 300, status });
297
+ });
298
+ req.on('timeout', () => {
299
+ req.destroy();
300
+ resolve(null);
301
+ });
302
+ req.on('error', () => {
303
+ resolve(null);
304
+ });
305
+ req.end();
306
+ });
307
+ }
308
+ async function waitForHealth(port, timeoutMs = 45000, useHttps = isHttpsEnabled()) {
309
+ const deadline = Date.now() + timeoutMs;
310
+ while (Date.now() < deadline) {
311
+ const res = await checkHealth(port, useHttps);
312
+ if (res?.ok)
313
+ return true;
314
+ await new Promise((r) => setTimeout(r, 1000));
315
+ }
316
+ return false;
317
+ }
318
+ async function promptMode(rl) {
319
+ console.log('\nChoose how to run neuralbrain:');
320
+ console.log(' 1) Full Docker stack (Brain + Qdrant in Docker)');
321
+ console.log(' 2) Qdrant in Docker + Brain on host (Node.js)');
322
+ console.log(' 3) Brain only on host, no Qdrant (SQLite + BM25, 0 MB vector RAM)');
323
+ while (true) {
324
+ const answer = (await rl.question('\nSelect mode [1/2/3] (default: 1): ')).trim();
325
+ if (!answer || answer === '1')
326
+ return 'docker';
327
+ if (answer === '2')
328
+ return 'qdrant-docker';
329
+ if (answer === '3')
330
+ return 'local-only';
331
+ console.log('Please enter 1, 2, or 3.');
332
+ }
333
+ }
334
+ async function promptYesNo(rl, question, defaultYes = true) {
335
+ const suffix = defaultYes ? '[Y/n]' : '[y/N]';
336
+ const answer = (await rl.question(`${question} ${suffix}: `)).trim().toLowerCase();
337
+ if (!answer)
338
+ return defaultYes;
339
+ return answer === 'y' || answer === 'yes';
340
+ }
341
+ function isLocalGpuEmbed(parsedEnv) {
342
+ return (parsedEnv.BRAIN_EMBED || '').toLowerCase().trim() === 'local-gpu';
343
+ }
344
+ /**
345
+ * True when the brain runs on this host (not inside the docker image) with the
346
+ * in-process `local` embedder, the only setup that needs the optional
347
+ * @huggingface/transformers dependency on the host. BRAIN_EMBED defaults to
348
+ * `local` when unset.
349
+ */
350
+ function hostNeedsLocalEmbedder(mode, parsedEnv) {
351
+ if (mode === 'docker')
352
+ return false;
353
+ const tier = (parsedEnv.BRAIN_EMBED || 'local').toLowerCase().trim();
354
+ return tier === 'local';
355
+ }
356
+ /**
357
+ * Checked in a child process: Node caches module lookups for the life of a
358
+ * process, so an in-process require.resolve() keeps failing after the package
359
+ * has just been installed.
360
+ */
361
+ function canResolve(id, packageRoot) {
362
+ const res = (0, child_process_1.spawnSync)(process.execPath, ['-e', `require.resolve(${JSON.stringify(id)}, { paths: [${JSON.stringify(packageRoot)}] })`], { stdio: 'ignore' });
363
+ return res.status === 0;
364
+ }
365
+ /**
366
+ * Makes sure the optional local embedder is installed in packageRoot,
367
+ * installing it if npm dropped it.
368
+ *
369
+ * npm drops it during `npm install -g neuralbrain` on Linux x64, where
370
+ * onnxruntime-node@1.20.1's install script tries to download a CUDA 11 build
371
+ * that no longer exists. Here we control the environment, so that download is
372
+ * skipped (onnxruntime-node ships its CPU binaries in the package).
373
+ */
374
+ function ensureLocalEmbedder(packageRoot, run = child_process_1.spawnSync, resolves = canResolve) {
375
+ const id = '@huggingface/transformers';
376
+ if (resolves(id, packageRoot))
377
+ return { ok: true, installed: false };
378
+ let spec = id;
379
+ try {
380
+ const pkg = JSON.parse(fs_1.default.readFileSync(path_1.default.join(packageRoot, 'package.json'), 'utf8'));
381
+ const version = pkg?.optionalDependencies?.[id] || pkg?.dependencies?.[id];
382
+ if (typeof version === 'string' && version)
383
+ spec = `${id}@${version}`;
384
+ }
385
+ catch {
386
+ // fall back to the unversioned spec
387
+ }
388
+ const res = run('npm', ['install', spec, '--no-save', '--no-audit', '--no-fund'], {
389
+ cwd: packageRoot,
390
+ stdio: 'inherit',
391
+ env: { ...process.env, ONNXRUNTIME_NODE_INSTALL_CUDA: 'skip' },
392
+ });
393
+ if (res.status !== 0) {
394
+ return { ok: false, installed: false, error: `\`npm install ${spec}\` failed in ${packageRoot}` };
395
+ }
396
+ if (!resolves(id, packageRoot)) {
397
+ return { ok: false, installed: false, error: `${id} is still not resolvable from ${packageRoot}` };
398
+ }
399
+ return { ok: true, installed: true };
400
+ }
401
+ function startForMode(mode, envPath, packageRoot) {
402
+ const parsedEnv = fs_1.default.existsSync(envPath) ? dotenv_1.default.parse(fs_1.default.readFileSync(envPath, 'utf8')) : {};
403
+ if (hostNeedsLocalEmbedder(mode, parsedEnv)) {
404
+ const embedder = ensureLocalEmbedder(packageRoot);
405
+ if (embedder.installed) {
406
+ console.log(' Installed the local embedder (@huggingface/transformers).');
407
+ }
408
+ else if (!embedder.ok) {
409
+ console.warn(` Warning: the local embedder is not installed (${embedder.error}). ` +
410
+ 'The brain will start, but embedding stays queued until it is installed ' +
411
+ '(re-run `neuralbrain start`) or BRAIN_EMBED is changed to none, remote, vendor or local-gpu.');
412
+ }
413
+ }
414
+ const useGpuProfile = isLocalGpuEmbed(parsedEnv);
415
+ if (parsedEnv.BRAIN_HTTPS === '1' || parsedEnv.BRAIN_HTTPS === 'true') {
416
+ (0, tls_1.ensureLocalTlsCerts)({
417
+ certPath: parsedEnv.BRAIN_TLS_CERT,
418
+ keyPath: parsedEnv.BRAIN_TLS_KEY,
419
+ });
420
+ }
421
+ if (mode === 'docker') {
422
+ if (!hasDockerCompose()) {
423
+ throw new Error('Docker Compose is required for mode "docker" but was not found.');
424
+ }
425
+ const composeArgs = useGpuProfile ? ['--profile', 'gpu', 'up', '-d', '--build'] : ['up', '-d', '--build'];
426
+ const code = runCompose(composeArgs, envPath, packageRoot);
427
+ if (code !== 0) {
428
+ throw new Error(`docker compose up failed with exit code ${code}`);
429
+ }
430
+ }
431
+ else if (mode === 'qdrant-docker') {
432
+ if (!hasDockerCompose()) {
433
+ throw new Error('Docker Compose is required for mode "qdrant-docker" but was not found.');
434
+ }
435
+ const qdrantPortFile = path_1.default.join(packageRoot, 'docker-compose.qdrant-port.yml');
436
+ const composeArgs = useGpuProfile
437
+ ? ['--profile', 'gpu', 'up', '-d', 'qdrant', 'embedder-gpu']
438
+ : ['up', '-d', 'qdrant'];
439
+ const code = runCompose(composeArgs, envPath, packageRoot, [qdrantPortFile]);
440
+ if (code !== 0) {
441
+ throw new Error(`docker compose up ${useGpuProfile ? 'qdrant embedder-gpu' : 'qdrant'} failed with exit code ${code}`);
442
+ }
443
+ const pid = startHostDaemon(packageRoot, envPath);
444
+ console.log(` Brain daemon started (pid ${pid})`);
445
+ }
446
+ else {
447
+ if (useGpuProfile && !parsedEnv.BRAIN_GPU_ENDPOINT?.trim()) {
448
+ console.warn(' Warning: BRAIN_EMBED=local-gpu in local-only mode does not start Docker. Set BRAIN_GPU_ENDPOINT or use --mode docker | qdrant-docker.');
449
+ }
450
+ const pid = startHostDaemon(packageRoot, envPath);
451
+ console.log(` Brain daemon started (pid ${pid})`);
452
+ }
453
+ }
454
+ /**
455
+ * Installs neuralbrain globally as a real copy, not a link.
456
+ *
457
+ * `npm install -g .` on a folder creates a symlink back to that folder (the same
458
+ * as `npm link`), so the CLI, the host daemon and the docker build would keep
459
+ * running out of the checkout, and moving or deleting it would break the install.
460
+ * Packing first and installing the tarball copies the package into npm's global
461
+ * root, exactly as a registry install would.
462
+ */
463
+ /**
464
+ * True when packageRoot is inside npm's npx cache (`~/.npm/_npx/<hash>/...`).
465
+ * npm may delete that cache at any time, so it is never a lasting install.
466
+ */
467
+ function isNpxCacheCopy(packageRoot) {
468
+ let real;
469
+ try {
470
+ real = fs_1.default.realpathSync(packageRoot);
471
+ }
472
+ catch {
473
+ real = path_1.default.resolve(packageRoot);
474
+ }
475
+ return real.split(path_1.default.sep).includes('_npx');
476
+ }
477
+ /**
478
+ * True when packageRoot is a real installed copy (it sits directly inside a
479
+ * node_modules folder once symlinks are resolved). A linked checkout resolves
480
+ * back to the checkout, so it is not an installed copy. A copy in the npx cache
481
+ * is not one either: the daemon and the docker build must not run from a cache
482
+ * that npm may clear.
483
+ */
484
+ function isInstalledCopy(packageRoot) {
485
+ let real;
486
+ try {
487
+ real = fs_1.default.realpathSync(packageRoot);
488
+ }
489
+ catch {
490
+ return false;
491
+ }
492
+ if (isNpxCacheCopy(real))
493
+ return false;
494
+ return path_1.default.basename(path_1.default.dirname(real)) === 'node_modules';
495
+ }
496
+ function readPackageVersion(packageRoot) {
497
+ try {
498
+ const pkg = JSON.parse(fs_1.default.readFileSync(path_1.default.join(packageRoot, 'package.json'), 'utf8'));
499
+ return typeof pkg?.version === 'string' && pkg.version ? pkg.version : null;
500
+ }
501
+ catch {
502
+ return null;
503
+ }
504
+ }
505
+ function installGlobalPackage(packageRoot, run = child_process_1.spawnSync) {
506
+ if (isInstalledCopy(packageRoot)) {
507
+ return { ok: true, installedRoot: packageRoot, alreadyInstalled: true };
508
+ }
509
+ const rootRes = run('npm', ['root', '-g'], { encoding: 'utf8', stdio: 'pipe' });
510
+ const globalRoot = rootRes.status === 0 ? String(rootRes.stdout || '').trim() : '';
511
+ if (!globalRoot) {
512
+ return { ok: false, installedRoot: null, alreadyInstalled: false, error: '`npm root -g` failed' };
513
+ }
514
+ const installedRoot = path_1.default.join(globalRoot, 'neuralbrain');
515
+ // onnxruntime-node's script only fetches the CUDA add-on, which the host never
516
+ // uses; with CUDA present it can 404 and fail the whole install. Skip it in
517
+ // case npm runs the script anyway (npm 10 and older run every script).
518
+ const installOptions = { stdio: 'inherit', env: { ...process.env, ONNXRUNTIME_NODE_INSTALL_CUDA: 'skip' } };
519
+ // From `npx neuralbrain`: the npx cache copy has no dev dependencies, so
520
+ // `npm pack` (whose prepack runs tsc) would fail there. Install the same
521
+ // version from the registry instead.
522
+ if (isNpxCacheCopy(packageRoot)) {
523
+ const version = readPackageVersion(packageRoot);
524
+ if (!version) {
525
+ return { ok: false, installedRoot: null, alreadyInstalled: false, error: 'could not read package version' };
526
+ }
527
+ const installRes = run('npm', ['install', '-g', `neuralbrain@${version}`, '--no-audit', '--no-fund'], installOptions);
528
+ if (installRes.status !== 0) {
529
+ return { ok: false, installedRoot: null, alreadyInstalled: false, error: '`npm install -g` failed' };
530
+ }
531
+ return { ok: true, installedRoot, alreadyInstalled: false };
532
+ }
533
+ const packDir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'neuralbrain-pack-'));
534
+ try {
535
+ const packRes = run('npm', ['pack', '--json', '--pack-destination', packDir], {
536
+ cwd: packageRoot,
537
+ encoding: 'utf8',
538
+ stdio: 'pipe',
539
+ });
540
+ if (packRes.status !== 0) {
541
+ return { ok: false, installedRoot: null, alreadyInstalled: false, error: '`npm pack` failed' };
542
+ }
543
+ let filename;
544
+ try {
545
+ // `npm pack --json` prints lifecycle output (e.g. the prepack build) before the JSON array.
546
+ const out = String(packRes.stdout || '');
547
+ const parsed = JSON.parse(out.slice(out.indexOf('[')));
548
+ filename = parsed?.[0]?.filename;
549
+ }
550
+ catch {
551
+ filename = undefined;
552
+ }
553
+ if (!filename) {
554
+ return { ok: false, installedRoot: null, alreadyInstalled: false, error: 'could not read `npm pack` output' };
555
+ }
556
+ const tarball = path_1.default.join(packDir, path_1.default.basename(filename));
557
+ // No dependency needs its install script: SQLite is built into Node, and sharp
558
+ // and onnxruntime-node ship prebuilt binaries. npm 11+ skips those scripts by
559
+ // default and says so; that is expected.
560
+ const installRes = run('npm', ['install', '-g', tarball, '--no-audit', '--no-fund'], installOptions);
561
+ if (installRes.status !== 0) {
562
+ return { ok: false, installedRoot: null, alreadyInstalled: false, error: '`npm install -g` failed' };
563
+ }
564
+ return { ok: true, installedRoot, alreadyInstalled: false };
565
+ }
566
+ finally {
567
+ fs_1.default.rmSync(packDir, { recursive: true, force: true });
568
+ }
569
+ }
570
+ async function cmdInstall(argv) {
571
+ const opts = parseInstallArgs(argv);
572
+ const packageRoot = getPackageRoot();
573
+ const isInteractive = !opts.yes && process.stdin.isTTY;
574
+ let mode = opts.mode || 'docker';
575
+ let installGlobal = opts.global ?? true;
576
+ let installAgents = opts.agents ?? true;
577
+ if (isInteractive) {
578
+ const rl = promises_1.default.createInterface({ input: process.stdin, output: process.stdout });
579
+ try {
580
+ if (!opts.mode) {
581
+ mode = await promptMode(rl);
582
+ }
583
+ if (opts.global === undefined) {
584
+ installGlobal = await promptYesNo(rl, '\nInstall `neuralbrain` globally so it works in any shell?', true);
585
+ }
586
+ if (opts.agents === undefined) {
587
+ installAgents = await promptYesNo(rl, 'Configure coding agents (Antigravity, Claude Code, Cursor)?', true);
588
+ }
589
+ }
590
+ finally {
591
+ rl.close();
592
+ }
593
+ }
594
+ console.log(`\nInitializing ${(0, brainHome_1.getBrainHomeDir)()} (mode: ${mode})...`);
595
+ const init = initializeBrainHome({ mode, port: opts.port, https: opts.https, gpu: opts.gpu });
596
+ const protocol = init.https ? 'https' : 'http';
597
+ console.log(` Config: ${init.envPath}${init.createdEnv ? ' (created)' : ' (updated)'}`);
598
+ // Install the global copy first, so the daemon and the docker build run from
599
+ // it rather than from this checkout.
600
+ let runtimeRoot = packageRoot;
601
+ if (installGlobal) {
602
+ console.log('\nInstalling `neuralbrain` globally...');
603
+ const res = installGlobalPackage(packageRoot);
604
+ if (res.ok && res.installedRoot) {
605
+ runtimeRoot = res.installedRoot;
606
+ console.log(res.alreadyInstalled
607
+ ? ` Already running from the installed copy at ${res.installedRoot}`
608
+ : ` Installed to ${res.installedRoot}`);
609
+ if (!res.alreadyInstalled) {
610
+ console.log(' (If npm listed skipped install scripts for onnxruntime-node, sharp or protobufjs above, that is expected: they are not needed.)');
611
+ }
612
+ }
613
+ else {
614
+ console.warn(` Warning: global install failed (${res.error}). You may need to fix npm permissions. Running from ${packageRoot} for now.`);
615
+ }
616
+ }
617
+ console.log('\nStarting neuralbrain...');
618
+ startForMode(mode, init.envPath, runtimeRoot);
619
+ process.stdout.write(` Waiting for ${protocol}://127.0.0.1:${init.port}/health...`);
620
+ const healthy = await waitForHealth(init.port, mode === 'docker' ? 90000 : 30000, init.https);
621
+ console.log(healthy ? ' ready!' : ' timed out (check `neuralbrain logs` or `neuralbrain status`).');
622
+ if (installAgents) {
623
+ console.log('\nConfiguring coding agents...');
624
+ const report = (0, installAgent_1.installAgentIntegration)({
625
+ homeDir: os_1.default.homedir(),
626
+ brainRepoDir: runtimeRoot,
627
+ });
628
+ console.log(` Configured targets: ${report.configuredTargets.join(', ') || 'none'}`);
629
+ }
630
+ console.log('\n┌──────────────────────────────────────────────────────────────┐');
631
+ console.log('│ neuralbrain ready │');
632
+ console.log(`│ Home ${init.brainHome.padEnd(48)} │`);
633
+ console.log(`│ Mode ${mode.padEnd(48)} │`);
634
+ console.log(`│ REST API ${`${protocol}://127.0.0.1:${init.port}`.padEnd(48)} │`);
635
+ console.log(`│ Dashboard ${`${protocol}://127.0.0.1:${init.port}/dashboard`.padEnd(48)} │`);
636
+ console.log('├──────────────────────────────────────────────────────────────┤');
637
+ console.log('│ Commands: neuralbrain status | stop | start | logs | doctor │');
638
+ console.log('└──────────────────────────────────────────────────────────────┘\n');
639
+ }
640
+ async function cmdStart() {
641
+ (0, brainHome_1.loadBrainEnv)();
642
+ const packageRoot = getPackageRoot();
643
+ const mode = readRuntimeMode() || 'local-only';
644
+ const envPath = (0, brainHome_1.getBrainEnvPath)();
645
+ if (!fs_1.default.existsSync(envPath)) {
646
+ throw new Error(`Not initialized. Run \`neuralbrain install\` first (missing ${envPath}).`);
647
+ }
648
+ const port = parseInt(process.env.PORT || '3737', 10);
649
+ const useHttps = isHttpsEnabled();
650
+ const protocol = useHttps ? 'https' : 'http';
651
+ console.log(`Starting neuralbrain (mode: ${mode})...`);
652
+ startForMode(mode, envPath, packageRoot);
653
+ const healthy = await waitForHealth(port, 30000, useHttps);
654
+ console.log(healthy ? `Ready at ${protocol}://127.0.0.1:${port}` : 'Started, waiting for health check...');
655
+ }
656
+ /**
657
+ * Whether this BRAIN_HOME's mode runs Docker Compose, and so whether `stop`
658
+ * may touch it. The compose project name is fixed ("neuralbrain"), so stopping
659
+ * compose from a `local-only` home would stop some other install's containers.
660
+ * Only modes that start compose stop it; an unknown mode stops nothing in Docker.
661
+ */
662
+ function modeUsesCompose(mode) {
663
+ return mode === 'docker' || mode === 'qdrant-docker';
664
+ }
665
+ function cmdStop() {
666
+ const packageRoot = getPackageRoot();
667
+ const envPath = (0, brainHome_1.getBrainEnvPath)();
668
+ const stoppedHost = stopHostDaemon();
669
+ if (stoppedHost) {
670
+ console.log('Stopped host Brain daemon.');
671
+ }
672
+ const mode = readRuntimeMode();
673
+ if (fs_1.default.existsSync(envPath) && modeUsesCompose(mode) && hasDockerCompose()) {
674
+ const extraFiles = mode === 'qdrant-docker' ? [path_1.default.join(packageRoot, 'docker-compose.qdrant-port.yml')] : [];
675
+ runCompose(['--profile', 'gpu', 'stop'], envPath, packageRoot, extraFiles);
676
+ }
677
+ if (!stoppedHost && !fs_1.default.existsSync(envPath)) {
678
+ console.log('Nothing running.');
679
+ }
680
+ }
681
+ async function cmdStatus() {
682
+ (0, brainHome_1.loadBrainEnv)();
683
+ const brainHome = (0, brainHome_1.getBrainHomeDir)();
684
+ const mode = readRuntimeMode() || 'unconfigured';
685
+ const port = parseInt(process.env.PORT || '3737', 10);
686
+ const pidFile = getPidFilePath();
687
+ let pidStatus = 'not running';
688
+ if (fs_1.default.existsSync(pidFile)) {
689
+ const pid = parseInt(fs_1.default.readFileSync(pidFile, 'utf8').trim(), 10);
690
+ pidStatus = !Number.isNaN(pid) && isPidAlive(pid) ? `running (pid ${pid})` : 'stale pid';
691
+ }
692
+ const useHttps = isHttpsEnabled();
693
+ const protocol = useHttps ? 'https' : 'http';
694
+ const health = await checkHealth(port, useHttps);
695
+ const healthStatus = health
696
+ ? health.ok
697
+ ? `healthy (${health.status})`
698
+ : `unhealthy (${health.status})`
699
+ : 'unreachable';
700
+ console.log(`Home: ${brainHome}`);
701
+ console.log(`Mode: ${mode}`);
702
+ console.log(`Daemon: ${pidStatus}`);
703
+ console.log(`API: ${protocol}://127.0.0.1:${port} (${healthStatus})`);
704
+ }
705
+ function cmdLogs() {
706
+ const mode = readRuntimeMode();
707
+ const envPath = (0, brainHome_1.getBrainEnvPath)();
708
+ const packageRoot = getPackageRoot();
709
+ if (mode === 'docker' && fs_1.default.existsSync(envPath) && hasDockerCompose()) {
710
+ const parsedEnv = dotenv_1.default.parse(fs_1.default.readFileSync(envPath, 'utf8'));
711
+ const logArgs = isLocalGpuEmbed(parsedEnv)
712
+ ? ['--profile', 'gpu', 'logs', '-f', '--tail=100']
713
+ : ['logs', '-f', '--tail=100'];
714
+ runCompose(logArgs, envPath, packageRoot);
715
+ return;
716
+ }
717
+ const logPath = getLogFilePath();
718
+ if (!fs_1.default.existsSync(logPath)) {
719
+ console.log(`No log file found at ${logPath}`);
720
+ return;
721
+ }
722
+ (0, child_process_1.spawnSync)('tail', ['-n', '100', '-f', logPath], { stdio: 'inherit' });
723
+ }
724
+ /**
725
+ * `neuralbrain init [project-id] [--force]`: writes .brainrc in `cwd` so every
726
+ * agent working anywhere below it records the same project_id.
727
+ *
728
+ * Defaults to the folder's own name. An existing .brainrc is kept unless
729
+ * `force` is set. An explicit id that is not a valid project_id is an error,
730
+ * never silently replaced.
731
+ */
732
+ function runInit(options) {
733
+ const cwd = path_1.default.resolve(options.cwd);
734
+ const filePath = path_1.default.join(cwd, '.brainrc');
735
+ let explicit;
736
+ if (options.projectId !== undefined) {
737
+ const sanitized = options.projectId
738
+ .trim()
739
+ .toLowerCase()
740
+ .replace(/[^a-z0-9._-]+/g, '-')
741
+ .replace(/^-+|-+$/g, '');
742
+ const norm = (0, scope_1.normalizeProjectId)(sanitized);
743
+ if (!norm.ok) {
744
+ throw new Error(`'${options.projectId}' is not a valid project id: ${norm.error}`);
745
+ }
746
+ explicit = norm.projectId;
747
+ }
748
+ // What this folder resolves to today, from a parent .brainrc or the git root.
749
+ const parentDir = path_1.default.dirname(cwd);
750
+ const enclosing = parentDir !== cwd ? (0, projectSlug_1.resolveCanonicalProjectId)({ cwd: parentDir, fallbackToDirname: false }) : null;
751
+ const gitOrParent = enclosing ?? (0, projectSlug_1.resolveCanonicalProjectId)({ cwd, fallbackToDirname: true });
752
+ if (fs_1.default.existsSync(filePath) && !options.force) {
753
+ const existing = (0, projectSlug_1.resolveCanonicalProjectId)({ cwd, fallbackToDirname: false });
754
+ return { filePath, projectId: existing ?? '', written: false, enclosingProjectId: null };
755
+ }
756
+ const written = (0, projectSlug_1.writeBrainRc)(cwd, explicit);
757
+ const enclosingProjectId = gitOrParent && gitOrParent !== written.projectId ? gitOrParent : null;
758
+ return { filePath: written.filePath, projectId: written.projectId, written: true, enclosingProjectId };
759
+ }
760
+ function cmdInit(argv) {
761
+ const force = argv.includes('--force') || argv.includes('-f');
762
+ const positional = argv.filter((a) => !a.startsWith('-'));
763
+ if (positional.length > 1) {
764
+ console.error('Usage: neuralbrain init [project-id] [--force]');
765
+ process.exit(1);
766
+ }
767
+ let result;
768
+ try {
769
+ result = runInit({ cwd: process.cwd(), projectId: positional[0], force });
770
+ }
771
+ catch (err) {
772
+ console.error(err instanceof Error ? err.message : String(err));
773
+ process.exit(1);
774
+ }
775
+ if (!result.written) {
776
+ console.log(`${result.filePath} already exists (project_id: ${result.projectId || 'unreadable'}).`);
777
+ console.log('Run `neuralbrain init [project-id] --force` to replace it.');
778
+ return;
779
+ }
780
+ console.log(`Wrote ${result.filePath}`);
781
+ console.log(`project_id: ${result.projectId}`);
782
+ if (result.enclosingProjectId) {
783
+ console.log(`Note: this folder was part of project "${result.enclosingProjectId}". ` +
784
+ `Work here will now be recorded as "${result.projectId}". ` +
785
+ 'If that was not intended, delete the file or run init in the project root.');
786
+ }
787
+ }
788
+ function printHelp() {
789
+ console.log(`
790
+ Usage: neuralbrain <command> [options]
791
+
792
+ Commands:
793
+ install Interactive setup in ~/.neuralbrain/ (default)
794
+ --mode <m> docker | qdrant-docker | local-only
795
+ --port <n> API port (default: 3737)
796
+ --https Enable local HTTPS with self-signed cert
797
+ --gpu Use BRAIN_EMBED=local-gpu (spawns Docker Compose gpu profile)
798
+ --yes, -y Non-interactive defaults
799
+ --no-global Skip global npm install
800
+ --no-agents Skip configuring coding agents
801
+ start Start the configured Brain service
802
+ stop Stop running Brain / Docker containers
803
+ status Show service and health status
804
+ logs Tail Brain service logs
805
+ doctor Run health and AI conformance diagnostics
806
+ install-agent Configure Antigravity, Claude Code, Cursor, or project rules
807
+ init Write .brainrc here so agents use one project_id for this folder
808
+ [project-id] Defaults to this folder's name
809
+ --force, -f Replace an existing .brainrc
810
+ rename-project Rename a project_id across SQLite and Qdrant (<from> <to>)
811
+ mcp Start the stdio MCP server
812
+ `);
813
+ }
814
+ async function main() {
815
+ const args = process.argv.slice(2);
816
+ const sub = args[0];
817
+ if (sub === '-h' || sub === '--help' || sub === 'help') {
818
+ printHelp();
819
+ return;
820
+ }
821
+ if (!sub || sub === 'install') {
822
+ await cmdInstall(sub === 'install' ? args.slice(1) : args);
823
+ return;
824
+ }
825
+ if (sub === 'start') {
826
+ await cmdStart();
827
+ return;
828
+ }
829
+ if (sub === 'stop') {
830
+ cmdStop();
831
+ return;
832
+ }
833
+ if (sub === 'status') {
834
+ await cmdStatus();
835
+ return;
836
+ }
837
+ if (sub === 'logs') {
838
+ cmdLogs();
839
+ return;
840
+ }
841
+ if (sub === 'doctor') {
842
+ (0, brainHome_1.loadBrainEnv)();
843
+ const doctorPath = path_1.default.join(getPackageRoot(), 'dist', 'scripts', 'doctor.js');
844
+ const res = (0, child_process_1.spawnSync)(process.execPath, [doctorPath, ...args.slice(1)], { stdio: 'inherit' });
845
+ process.exit(res.status ?? 0);
846
+ }
847
+ if (sub === 'install-agent') {
848
+ (0, brainHome_1.loadBrainEnv)();
849
+ const parsed = (0, installAgent_1.parseCliArgs)(args.slice(1));
850
+ const report = (0, installAgent_1.installAgentIntegration)({
851
+ ...parsed,
852
+ brainRepoDir: getPackageRoot(),
853
+ });
854
+ (0, installAgent_1.printInstallAgentReport)(report);
855
+ return;
856
+ }
857
+ if (sub === 'init') {
858
+ cmdInit(args.slice(1));
859
+ return;
860
+ }
861
+ if (sub === 'rename-project') {
862
+ (0, brainHome_1.loadBrainEnv)();
863
+ const [fromId, toId] = args.slice(1);
864
+ if (!fromId || !toId) {
865
+ console.error('Usage: neuralbrain rename-project <from_project_id> <to_project_id>');
866
+ process.exit(1);
867
+ }
868
+ const apiUrl = (0, installAgent_1.resolveApiUrl)({}, getPackageRoot(), process.cwd(), os_1.default.homedir()).replace(/\/+$/, '');
869
+ const apiKey = (0, installAgent_1.resolveApiKey)({}, getPackageRoot(), process.cwd(), os_1.default.homedir());
870
+ const headers = { 'Content-Type': 'application/json' };
871
+ if (apiKey)
872
+ headers.Authorization = `Bearer ${apiKey}`;
873
+ const res = await fetch(`${apiUrl}/maintenance/rename-project`, {
874
+ method: 'POST',
875
+ headers,
876
+ body: JSON.stringify({ from_project_id: fromId, to_project_id: toId }),
877
+ });
878
+ const data = (await res.json());
879
+ if (!res.ok) {
880
+ console.error(`Rename failed (${res.status}): ${data?.error?.message || JSON.stringify(data)}`);
881
+ process.exit(1);
882
+ }
883
+ console.log(`Renamed project "${data.from_project_id}" -> "${data.to_project_id}" (${data.total_updated} SQLite rows, qdrant_updated=${data.qdrant_updated})`);
884
+ if (data.updated_counts) {
885
+ for (const [table, count] of Object.entries(data.updated_counts)) {
886
+ if (Number(count) > 0) {
887
+ console.log(` - ${table}: ${count}`);
888
+ }
889
+ }
890
+ }
891
+ if (data.qdrant_error) {
892
+ console.warn(`Warning: Qdrant payload update failed: ${data.qdrant_error}`);
893
+ }
894
+ return;
895
+ }
896
+ if (sub === 'mcp') {
897
+ (0, brainHome_1.loadBrainEnv)();
898
+ const mcpPath = path_1.default.join(getPackageRoot(), 'dist', 'mcp', 'server.js');
899
+ const res = (0, child_process_1.spawnSync)(process.execPath, [mcpPath, ...args.slice(1)], { stdio: 'inherit' });
900
+ process.exit(res.status ?? 0);
901
+ }
902
+ console.error(`Unknown command: ${sub}`);
903
+ printHelp();
904
+ process.exit(1);
905
+ }
906
+ if (require.main === module) {
907
+ main().catch((err) => {
908
+ console.error('[ERROR]', err?.message || err);
909
+ process.exit(1);
910
+ });
911
+ }
912
+ //# sourceMappingURL=cli.js.map