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