nexorum 0.0.0-stage → 0.2.0
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/LICENSE +9 -0
- package/README.md +144 -2
- package/bin/nexorum.js +12 -0
- package/package.json +46 -4
- package/src/agent-dream.js +277 -0
- package/src/agents-md.js +80 -0
- package/src/args.js +71 -0
- package/src/cli.js +278 -0
- package/src/core/basics.js +88 -0
- package/src/core/diff.js +63 -0
- package/src/core/dream/agent.js +109 -0
- package/src/core/dream/engine.js +223 -0
- package/src/core/dream/prompts.js +112 -0
- package/src/core/dream/tools.js +348 -0
- package/src/core/estimate.js +57 -0
- package/src/core/index.js +13 -0
- package/src/core/providers/http.js +143 -0
- package/src/core/providers/index.js +179 -0
- package/src/core/scrub.js +82 -0
- package/src/core/search.js +107 -0
- package/src/core/sessions.js +171 -0
- package/src/core/text.js +72 -0
- package/src/core/wiki.js +102 -0
- package/src/doctor.js +177 -0
- package/src/dream.js +309 -0
- package/src/hook.js +101 -0
- package/src/import.js +137 -0
- package/src/init.js +266 -0
- package/src/mcp.js +376 -0
- package/src/memory.js +188 -0
- package/src/proposals.js +204 -0
- package/src/store.js +445 -0
- package/src/transcript.js +40 -0
- package/src/version.js +4 -0
package/src/hook.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// `nexorum hook session-start|user-prompt|stop`: Claude Code hooks (hook JSON on stdin). They never fail a session:
|
|
2
|
+
// always exit 0, and errors go to stderr only with NEXORUM_DEBUG=1.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { claudeCodeJsonlToEvents, scrubSecrets, sha256Hex } from "./core/index.js";
|
|
6
|
+
import { Store, atomicWrite, isSafeId, nexorumRoot, sanitizeSpace } from "./store.js";
|
|
7
|
+
import { contextFor, formatPromptRecall, promptRecall } from "./memory.js";
|
|
8
|
+
|
|
9
|
+
export const MAX_CONTEXT_CHARS = 10_000;
|
|
10
|
+
const MAX_READ_BYTES = 32 * 1024 * 1024;
|
|
11
|
+
const SEEN_FILE = "hook-seen.json";
|
|
12
|
+
const SEEN_SESSIONS = 20;
|
|
13
|
+
const SEEN_IDS = 200;
|
|
14
|
+
|
|
15
|
+
async function readStdin(input) {
|
|
16
|
+
if (input.isTTY) return "";
|
|
17
|
+
const chunks = [];
|
|
18
|
+
for await (const c of input) chunks.push(typeof c === "string" ? Buffer.from(c) : c);
|
|
19
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The space is --space, else NEXORUM_SPACE, else the name of the hook's cwd. */
|
|
23
|
+
function hookStore(input, flags, env) {
|
|
24
|
+
const space = flags.space ?? (env.NEXORUM_SPACE || undefined);
|
|
25
|
+
const cwd = typeof input.cwd === "string" && input.cwd ? input.cwd : process.cwd();
|
|
26
|
+
return new Store(nexorumRoot(env), sanitizeSpace(space ?? path.basename(path.resolve(cwd))));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const hookJson = (event, text) => JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text.slice(0, MAX_CONTEXT_CHARS) } });
|
|
30
|
+
|
|
31
|
+
/** SessionStart: the digest as additionalContext, or "" when memory is empty. */
|
|
32
|
+
export function sessionStartOutput(store) {
|
|
33
|
+
const { content } = contextFor(store, 4096);
|
|
34
|
+
return content ? hookJson("SessionStart", `Nexorum memory (space "${store.space}"):\n${content}`) : "";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function readSeen(store) {
|
|
38
|
+
try {
|
|
39
|
+
const v = JSON.parse(fs.readFileSync(path.join(store.dir, SEEN_FILE), "utf8"));
|
|
40
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
41
|
+
} catch {
|
|
42
|
+
return {};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** UserPromptSubmit: matching memory not yet shown in this session, or "" (also when NEXORUM_PROMPT_RECALL=0). */
|
|
47
|
+
export function userPromptOutput(store, input, env = process.env) {
|
|
48
|
+
if (env.NEXORUM_PROMPT_RECALL === "0") return "";
|
|
49
|
+
const session = String(input.session_id ?? "");
|
|
50
|
+
const seen = readSeen(store);
|
|
51
|
+
const shown = new Set(Array.isArray(seen[session]) ? seen[session] : []);
|
|
52
|
+
const items = promptRecall(store, input.prompt, shown);
|
|
53
|
+
const text = formatPromptRecall(store.space, items);
|
|
54
|
+
if (!text) return "";
|
|
55
|
+
if (session) {
|
|
56
|
+
delete seen[session]; // re-inserted last, so the most recent sessions are the ones kept
|
|
57
|
+
seen[session] = [...shown, ...items.map((i) => i.id)].slice(-SEEN_IDS);
|
|
58
|
+
const keep = Object.keys(seen).slice(-SEEN_SESSIONS);
|
|
59
|
+
try {
|
|
60
|
+
fs.mkdirSync(store.dir, { recursive: true });
|
|
61
|
+
atomicWrite(path.join(store.dir, SEEN_FILE), `${JSON.stringify(Object.fromEntries(keep.map((k) => [k, seen[k]])))}\n`);
|
|
62
|
+
} catch {}
|
|
63
|
+
}
|
|
64
|
+
return hookJson("UserPromptSubmit", text);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Stop: stores the session JSONL at transcript_path as a pending transcript (id = session id). */
|
|
68
|
+
export function recordStop(store, input) {
|
|
69
|
+
const sessionId = String(input.session_id ?? "");
|
|
70
|
+
const file = input.transcript_path;
|
|
71
|
+
if (!sessionId || typeof file !== "string" || !file) return false;
|
|
72
|
+
if (fs.statSync(file).size > MAX_READ_BYTES) throw new Error(`transcript is larger than ${MAX_READ_BYTES} bytes`);
|
|
73
|
+
const { events } = claudeCodeJsonlToEvents(fs.readFileSync(file, "utf8"));
|
|
74
|
+
if (!events.length) return false;
|
|
75
|
+
const clean = events.map((e) => ({ ...e, content: scrubSecrets(String(e.content ?? "")).text }));
|
|
76
|
+
const id = isSafeId(sessionId) ? sessionId : `cc_${sha256Hex(sessionId).slice(0, 32)}`;
|
|
77
|
+
store.upsertTranscript({ id, source: "claude-code", externalId: sessionId, events: clean });
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function hookCommand(sub, flags, env, { input = process.stdin, output = process.stdout } = {}) {
|
|
82
|
+
try {
|
|
83
|
+
let data = {};
|
|
84
|
+
const raw = (await readStdin(input)).trim();
|
|
85
|
+
if (raw) {
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(raw);
|
|
88
|
+
if (parsed && typeof parsed === "object") data = parsed;
|
|
89
|
+
} catch {}
|
|
90
|
+
}
|
|
91
|
+
const store = hookStore(data, flags, env);
|
|
92
|
+
let text = "";
|
|
93
|
+
if (sub === "session-start") text = sessionStartOutput(store);
|
|
94
|
+
else if (sub === "user-prompt") text = userPromptOutput(store, data, env);
|
|
95
|
+
else if (sub === "stop") recordStop(store, data);
|
|
96
|
+
if (text) output.write(`${text}\n`);
|
|
97
|
+
} catch (e) {
|
|
98
|
+
if (env.NEXORUM_DEBUG === "1") process.stderr.write(`nexorum hook ${sub}: ${e?.stack ?? e}\n`);
|
|
99
|
+
}
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
package/src/import.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// `nexorum import omp`: omp (oh-my-pi) session files become transcripts, idempotently (the omp session id is the
|
|
2
|
+
// transcript id, so a grown session updates the same transcript and makes it pending again).
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { ompJsonlToEvents, scrubSecrets, sha256Hex } from "./core/index.js";
|
|
7
|
+
import { UsageError } from "./args.js";
|
|
8
|
+
import { Store, isSafeId, nexorumRoot, sanitizeSpace } from "./store.js";
|
|
9
|
+
|
|
10
|
+
const out = (s = "") => process.stdout.write(`${s}\n`);
|
|
11
|
+
const MAX_SESSION_BYTES = 128 * 1024 * 1024;
|
|
12
|
+
const HEADER_BYTES = 64 * 1024;
|
|
13
|
+
|
|
14
|
+
/** --dir, else $OMP_SESSIONS_DIR, else ~/.omp/agent/sessions. */
|
|
15
|
+
export function ompSessionsDir(flags, env) {
|
|
16
|
+
if (flags.dir) return path.resolve(flags.dir);
|
|
17
|
+
if (env.OMP_SESSIONS_DIR) return path.resolve(env.OMP_SESSIONS_DIR);
|
|
18
|
+
return path.join(env.USERPROFILE || env.HOME || os.homedir(), ".omp", "agent", "sessions");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function sameDir(a, b) {
|
|
22
|
+
const norm = (p) => {
|
|
23
|
+
let r = path.resolve(String(p));
|
|
24
|
+
try {
|
|
25
|
+
r = fs.realpathSync.native(r);
|
|
26
|
+
} catch {}
|
|
27
|
+
return r.replace(/[\\/]+$/, "");
|
|
28
|
+
};
|
|
29
|
+
const [x, y] = [norm(a), norm(b)];
|
|
30
|
+
return process.platform === "win32" || process.platform === "darwin" ? x.toLowerCase() === y.toLowerCase() : x === y;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The `session` header line, read from the first 64 KiB only. */
|
|
34
|
+
function readHeader(file) {
|
|
35
|
+
const fd = fs.openSync(file, "r");
|
|
36
|
+
try {
|
|
37
|
+
const buf = Buffer.alloc(HEADER_BYTES);
|
|
38
|
+
const n = fs.readSync(fd, buf, 0, HEADER_BYTES, 0);
|
|
39
|
+
for (const line of buf.toString("utf8", 0, n).split("\n")) {
|
|
40
|
+
if (!line.includes('"type":"session"')) continue;
|
|
41
|
+
try {
|
|
42
|
+
const o = JSON.parse(line);
|
|
43
|
+
if (o?.type === "session" && typeof o.id === "string") {
|
|
44
|
+
return { id: o.id, cwd: typeof o.cwd === "string" ? o.cwd : null, timestamp: typeof o.timestamp === "string" ? o.timestamp : null };
|
|
45
|
+
}
|
|
46
|
+
} catch {}
|
|
47
|
+
}
|
|
48
|
+
} finally {
|
|
49
|
+
fs.closeSync(fd);
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** *.jsonl in the folder and in its direct subfolders. */
|
|
55
|
+
function sessionFiles(root) {
|
|
56
|
+
let entries;
|
|
57
|
+
try {
|
|
58
|
+
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
59
|
+
} catch (e) {
|
|
60
|
+
throw new UsageError(`Cannot read the omp sessions folder ${root}: ${e.code ?? e.message}. Use --dir to point at it.`);
|
|
61
|
+
}
|
|
62
|
+
const files = [];
|
|
63
|
+
const take = (dir) => {
|
|
64
|
+
for (const f of fs.readdirSync(dir, { withFileTypes: true })) if (f.isFile() && f.name.endsWith(".jsonl")) files.push(path.join(dir, f.name));
|
|
65
|
+
};
|
|
66
|
+
take(root);
|
|
67
|
+
for (const d of entries) if (d.isDirectory()) take(path.join(root, d.name));
|
|
68
|
+
return files;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* nexorum import omp [--dir D] [--session FILE] [--all] [--since ISO] [--space S]
|
|
73
|
+
* Default: the sessions whose working directory is the current one. --all: every session, each into the space
|
|
74
|
+
* named after its own working directory. --session: one file.
|
|
75
|
+
*/
|
|
76
|
+
export async function importCommand(positionals, flags, env) {
|
|
77
|
+
const [kind, ...extra] = positionals;
|
|
78
|
+
if (kind !== "omp" || extra.length) throw new UsageError("Usage: nexorum import omp [--dir D] [--session FILE] [--all] [--since ISO] [--space S]");
|
|
79
|
+
let since = null;
|
|
80
|
+
if (flags.since !== undefined) {
|
|
81
|
+
since = Date.parse(flags.since);
|
|
82
|
+
if (Number.isNaN(since)) throw new UsageError("--since must be an ISO date, for example 2026-11-01.");
|
|
83
|
+
}
|
|
84
|
+
let candidates;
|
|
85
|
+
if (flags.session) {
|
|
86
|
+
const file = path.resolve(flags.session);
|
|
87
|
+
if (!fs.existsSync(file)) throw new UsageError(`No such file: ${file}`);
|
|
88
|
+
candidates = [file];
|
|
89
|
+
} else {
|
|
90
|
+
candidates = sessionFiles(ompSessionsDir(flags, env));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const cwd = process.cwd();
|
|
94
|
+
const root = nexorumRoot(env);
|
|
95
|
+
let imported = 0;
|
|
96
|
+
let unchanged = 0;
|
|
97
|
+
let skipped = 0;
|
|
98
|
+
const spaces = new Set();
|
|
99
|
+
for (const file of candidates.sort()) {
|
|
100
|
+
let header = null;
|
|
101
|
+
try {
|
|
102
|
+
header = readHeader(file);
|
|
103
|
+
} catch {}
|
|
104
|
+
if (!header) {
|
|
105
|
+
skipped++;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (!flags.session && !flags.all && !(header.cwd && sameDir(header.cwd, cwd))) continue;
|
|
109
|
+
if (since !== null && header.timestamp && Date.parse(header.timestamp) < since) continue;
|
|
110
|
+
if (fs.statSync(file).size > MAX_SESSION_BYTES) {
|
|
111
|
+
out(`skipped ${path.basename(file)}: larger than ${MAX_SESSION_BYTES} bytes`);
|
|
112
|
+
skipped++;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const { events, meta } = ompJsonlToEvents(fs.readFileSync(file, "utf8"));
|
|
116
|
+
if (!events.length) {
|
|
117
|
+
skipped++;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
const clean = events.map((e) => ({ ...e, content: scrubSecrets(String(e.content ?? "")).text }));
|
|
121
|
+
const sessionId = meta.id ?? header.id;
|
|
122
|
+
const id = isSafeId(`omp_${sessionId}`) ? `omp_${sessionId}` : `omp_${sha256Hex(sessionId).slice(0, 32)}`;
|
|
123
|
+
const space = sanitizeSpace(flags.space ?? env.NEXORUM_SPACE ?? path.basename(path.resolve(header.cwd ?? cwd)));
|
|
124
|
+
const { transcript, changed } = new Store(root, space).upsertTranscript({ id, source: "omp", externalId: sessionId, events: clean });
|
|
125
|
+
spaces.add(space);
|
|
126
|
+
if (changed) {
|
|
127
|
+
imported++;
|
|
128
|
+
out(`imported ${transcript.id} (${clean.length} events) into space "${space}"${meta.title ? `: ${meta.title}` : ""}`);
|
|
129
|
+
} else unchanged++;
|
|
130
|
+
}
|
|
131
|
+
out(`Done: ${imported} imported, ${unchanged} unchanged, ${skipped} skipped${spaces.size ? `. Spaces: ${[...spaces].join(", ")}` : ""}.`);
|
|
132
|
+
if (!imported && !unchanged && !skipped) {
|
|
133
|
+
out("No omp sessions matched. Sessions are matched by working directory; use --all to import every session, or --dir to point at another sessions folder.");
|
|
134
|
+
}
|
|
135
|
+
if (imported) out('Next: nexorum dream (reads pending transcripts; needs your LLM settings, see "nexorum --help")');
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
package/src/init.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// `nexorum init`: wires Nexorum into the clients it finds (or the ones named by flags).
|
|
2
|
+
// Claude Code hooks merged into ~/.claude/settings.json (backup first) + `claude mcp add`
|
|
3
|
+
// Codex `codex mcp add` + a marked block in the project's AGENTS.md
|
|
4
|
+
// Hermes mcp_servers entry in $HERMES_HOME/config.yaml (backup first; `hermes mcp add` is interactive)
|
|
5
|
+
// Cursor mcpServers entry in ~/.cursor/mcp.json (backup first)
|
|
6
|
+
// Claude Desktop mcpServers entry in claude_desktop_config.json (backup first)
|
|
7
|
+
// Every path is derived from --home, so nothing outside it is touched (except AGENTS.md in --dir).
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { spawnSync } from "node:child_process";
|
|
11
|
+
import { CliError } from "./args.js";
|
|
12
|
+
import { atomicWrite } from "./store.js";
|
|
13
|
+
import { setupAgentsMd } from "./agents-md.js";
|
|
14
|
+
|
|
15
|
+
const MARK = (sub) => new RegExp(`nexorum hook ${sub}`);
|
|
16
|
+
const HOOKS = [
|
|
17
|
+
["SessionStart", "npx -y nexorum hook session-start", MARK("session-start")],
|
|
18
|
+
["Stop", "npx -y nexorum hook stop", MARK("stop")],
|
|
19
|
+
];
|
|
20
|
+
// Runs before EVERY prompt, so it must not go through npx (seconds per call, against a fraction of a second for the
|
|
21
|
+
// installed command) and must be the version that ran init. It needs `nexorum` on PATH.
|
|
22
|
+
const PROMPT_HOOK = ["UserPromptSubmit", "nexorum hook user-prompt", MARK("user-prompt")];
|
|
23
|
+
const MCP_ARGS = ["mcp", "add", "nexorum", "--", "npx", "-y", "nexorum", "mcp"];
|
|
24
|
+
const MCP_ENTRY = { command: "npx", args: ["-y", "nexorum", "mcp"] };
|
|
25
|
+
const CODEX_TOML = `[mcp_servers.nexorum]\ncommand = "npx"\nargs = ["-y", "nexorum", "mcp"]`;
|
|
26
|
+
const HERMES_ENTRY = ["nexorum:", ' command: "npx"', ' args: ["-y", "nexorum", "mcp"]', " enabled: true"];
|
|
27
|
+
const HERMES_CMD = "hermes mcp add nexorum --command npx --args -y nexorum mcp";
|
|
28
|
+
const BACKUP = ".nexorum-bak";
|
|
29
|
+
|
|
30
|
+
const out = (s = "") => process.stdout.write(`${s}\n`);
|
|
31
|
+
const mcpCommand = (bin) => `${bin} ${MCP_ARGS.join(" ")}`;
|
|
32
|
+
|
|
33
|
+
/** An executable on PATH (PATHEXT on Windows), or null. */
|
|
34
|
+
export function findBinary(name, env = process.env) {
|
|
35
|
+
const dirs = (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean);
|
|
36
|
+
const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
|
|
37
|
+
for (const dir of dirs) {
|
|
38
|
+
for (const ext of exts) {
|
|
39
|
+
const file = path.join(dir, name + ext);
|
|
40
|
+
try {
|
|
41
|
+
if (fs.statSync(file).isFile()) return file;
|
|
42
|
+
} catch {}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function claudeDesktopConfigPath(home, platform = process.platform) {
|
|
49
|
+
if (platform === "darwin") return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
50
|
+
if (platform === "win32") return path.join(home, "AppData", "Roaming", "Claude", "claude_desktop_config.json");
|
|
51
|
+
return path.join(home, ".config", "Claude", "claude_desktop_config.json");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function hasHook(list, marker) {
|
|
55
|
+
return Array.isArray(list) && list.some((e) => Array.isArray(e?.hooks) && e.hooks.some((h) => typeof h?.command === "string" && marker.test(h.command)));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Adds the Nexorum hooks to a parsed settings object, keeping every existing hook. Returns the events added. */
|
|
59
|
+
export function mergeClaudeSettings(settings, { promptRecall = false } = {}) {
|
|
60
|
+
if (settings.hooks === undefined) settings.hooks = {};
|
|
61
|
+
if (!settings.hooks || typeof settings.hooks !== "object" || Array.isArray(settings.hooks)) {
|
|
62
|
+
throw new CliError('settings.json has a "hooks" value that is not an object; fix it by hand and run init again.');
|
|
63
|
+
}
|
|
64
|
+
const added = [];
|
|
65
|
+
for (const [event, command, marker] of promptRecall ? [...HOOKS, PROMPT_HOOK] : HOOKS) {
|
|
66
|
+
if (settings.hooks[event] === undefined) settings.hooks[event] = [];
|
|
67
|
+
if (!Array.isArray(settings.hooks[event])) throw new CliError(`settings.json hooks.${event} is not an array; fix it by hand and run init again.`);
|
|
68
|
+
if (hasHook(settings.hooks[event], marker)) continue;
|
|
69
|
+
settings.hooks[event].push({ hooks: [{ type: "command", command }] });
|
|
70
|
+
added.push(event);
|
|
71
|
+
}
|
|
72
|
+
return added;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Adds the mcpServers.nexorum entry unless one exists. Returns true when it was added. */
|
|
76
|
+
export function mergeMcpServers(config) {
|
|
77
|
+
if (config.mcpServers === undefined) config.mcpServers = {};
|
|
78
|
+
if (!config.mcpServers || typeof config.mcpServers !== "object" || Array.isArray(config.mcpServers)) {
|
|
79
|
+
throw new CliError('The config has an "mcpServers" value that is not an object; fix it by hand and run init again.');
|
|
80
|
+
}
|
|
81
|
+
if (config.mcpServers.nexorum) return false;
|
|
82
|
+
config.mcpServers.nexorum = { ...MCP_ENTRY, args: [...MCP_ENTRY.args] };
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Reads a JSON object file; refuses (CliError) to touch invalid JSON. Returns {raw, data}; raw null when missing. */
|
|
87
|
+
function readJsonObject(file) {
|
|
88
|
+
let raw = null;
|
|
89
|
+
try {
|
|
90
|
+
raw = fs.readFileSync(file, "utf8");
|
|
91
|
+
} catch (e) {
|
|
92
|
+
if (e.code !== "ENOENT") throw e;
|
|
93
|
+
}
|
|
94
|
+
if (raw === null || raw.trim() === "") return { raw, data: {} };
|
|
95
|
+
let data;
|
|
96
|
+
try {
|
|
97
|
+
data = JSON.parse(raw);
|
|
98
|
+
} catch {
|
|
99
|
+
throw new CliError(`${file} is not valid JSON; refusing to touch it. Fix it and run init again.`);
|
|
100
|
+
}
|
|
101
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) throw new CliError(`${file} is not a JSON object; refusing to touch it.`);
|
|
102
|
+
return { raw, data };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Backs the file up once (never overwriting an older backup), then writes it atomically. */
|
|
106
|
+
function writeWithBackup(file, raw, data) {
|
|
107
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
108
|
+
const backup = `${file}${BACKUP}`;
|
|
109
|
+
if (raw !== null && !fs.existsSync(backup)) {
|
|
110
|
+
fs.writeFileSync(backup, raw);
|
|
111
|
+
out(` backed up ${file} -> ${backup}`);
|
|
112
|
+
}
|
|
113
|
+
atomicWrite(file, `${JSON.stringify(data, null, 2)}\n`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function setupMcp(client, bin, { dryRun, env }) {
|
|
117
|
+
if (!findBinary(bin, env)) {
|
|
118
|
+
out(` \`${bin}\` was not found on PATH. Register the MCP server yourself:`);
|
|
119
|
+
out(` ${mcpCommand(bin)}`);
|
|
120
|
+
if (client === "Codex") {
|
|
121
|
+
out(" or add this to ~/.codex/config.toml:");
|
|
122
|
+
for (const l of CODEX_TOML.split("\n")) out(` ${l}`);
|
|
123
|
+
}
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (dryRun) return out(` would run: ${mcpCommand(bin)}`);
|
|
127
|
+
// Windows needs a shell for .cmd shims; MCP_ARGS are fixed constants, so pass one command string.
|
|
128
|
+
const win = process.platform === "win32";
|
|
129
|
+
const r = win ? spawnSync([bin, ...MCP_ARGS].join(" "), { encoding: "utf8", env, shell: true, timeout: 60_000 }) : spawnSync(bin, MCP_ARGS, { encoding: "utf8", env, timeout: 60_000 });
|
|
130
|
+
if (r.status === 0 && !r.error) return out(` ran: ${mcpCommand(bin)}`);
|
|
131
|
+
const why = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n")[0];
|
|
132
|
+
out(` \`${mcpCommand(bin)}\` did not succeed${why ? ` (${why})` : ""}. If nexorum is already registered this is fine; otherwise run it yourself.`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function setupClaudeCode(home, { dryRun, env, promptRecall }) {
|
|
136
|
+
out("Claude Code:");
|
|
137
|
+
if (promptRecall && !findBinary("nexorum", env)) {
|
|
138
|
+
out(" --prompt-recall skipped: `nexorum` is not on your PATH, and this hook runs before every prompt, so it cannot go through npx");
|
|
139
|
+
out(" (npx takes seconds per call, the installed command a fraction of a second). Run:");
|
|
140
|
+
out(" npm install -g nexorum");
|
|
141
|
+
out(" then run `nexorum init --claude-code --prompt-recall` again. The other hooks are installed below as usual.");
|
|
142
|
+
promptRecall = false;
|
|
143
|
+
}
|
|
144
|
+
const file = path.join(home, ".claude", "settings.json");
|
|
145
|
+
const { raw, data } = readJsonObject(file);
|
|
146
|
+
const added = mergeClaudeSettings(data, { promptRecall });
|
|
147
|
+
if (!added.length) out(` hooks already present in ${file}`);
|
|
148
|
+
else if (dryRun) out(` would add ${added.join(" and ")} hook(s) to ${file}${raw !== null ? ` (backup: ${file}${BACKUP})` : " (new file)"}`);
|
|
149
|
+
else {
|
|
150
|
+
writeWithBackup(file, raw, data);
|
|
151
|
+
out(` added ${added.join(" and ")} hook(s) to ${file}`);
|
|
152
|
+
}
|
|
153
|
+
setupMcp("Claude Code", "claude", { dryRun, env });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function setupCodex({ dryRun, env, dir, home, agentsMd }) {
|
|
157
|
+
out("Codex:");
|
|
158
|
+
setupMcp("Codex", "codex", { dryRun, env });
|
|
159
|
+
if (!agentsMd) out(" AGENTS.md left alone (--no-agents-md). Without instructions Codex may never call Nexorum on its own.");
|
|
160
|
+
else {
|
|
161
|
+
const r = setupAgentsMd(dir, { dryRun, home });
|
|
162
|
+
if (r.skipped) out(` AGENTS.md not written: ${r.skipped}.`);
|
|
163
|
+
else if (r.action === "unchanged") out(` ${r.file} already has the Nexorum block.`);
|
|
164
|
+
else if (dryRun) out(` would ${{ created: "create", added: "add the Nexorum block to", updated: "update the Nexorum block in" }[r.action]} ${r.file}`);
|
|
165
|
+
else out(` ${{ created: "created", added: "added the Nexorum block to", updated: "updated the Nexorum block in" }[r.action]} ${r.file}${r.backup ? ` (backup: ${r.backup})` : ""}`);
|
|
166
|
+
if (!dryRun && r.action !== "skipped") out(" Why: Codex has no session hooks, and it uses a memory server reliably only once its project instructions tell it to.");
|
|
167
|
+
}
|
|
168
|
+
out(" Codex has no session hooks: store a session with the `save_transcript` tool or `nexorum log` if you want it dreamed.");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Hermes keeps its config in $HERMES_HOME (default ~/.hermes, or %LOCALAPPDATA%\hermes on Windows). */
|
|
172
|
+
export function hermesHome(home, env = process.env, { useEnv = true, platform = process.platform } = {}) {
|
|
173
|
+
if (useEnv && env.HERMES_HOME) return env.HERMES_HOME;
|
|
174
|
+
const posix = path.join(home, ".hermes");
|
|
175
|
+
if (platform !== "win32" || fs.existsSync(posix)) return posix;
|
|
176
|
+
return path.join(home, "AppData", "Local", "hermes");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Adds the nexorum entry under mcp_servers in a Hermes config.yaml, keeping every other line as it was.
|
|
181
|
+
* Returns the new text, or null when nexorum is already there. Handles no file, no mcp_servers key, an empty
|
|
182
|
+
* `mcp_servers: {}`, and an existing block (the entry takes the indentation of its siblings).
|
|
183
|
+
*/
|
|
184
|
+
export function mergeHermesYaml(text) {
|
|
185
|
+
const src = text ?? "";
|
|
186
|
+
const nl = src.includes("\r\n") ? "\r\n" : "\n";
|
|
187
|
+
const lines = src.split(/\r?\n/);
|
|
188
|
+
const top = lines.findIndex((l) => /^mcp_servers:\s*(\{\s*\})?\s*(#.*)?$/.test(l));
|
|
189
|
+
const entry = (indent) => HERMES_ENTRY.map((l) => indent + l);
|
|
190
|
+
if (top === -1) {
|
|
191
|
+
const head = src === "" || src.endsWith("\n") ? src : src + nl;
|
|
192
|
+
return `${head}${src.trim() ? nl : ""}mcp_servers:${nl}${entry(" ").join(nl)}${nl}`;
|
|
193
|
+
}
|
|
194
|
+
let end = top + 1;
|
|
195
|
+
while (end < lines.length && (lines[end].trim() === "" || /^\s/.test(lines[end]))) end++;
|
|
196
|
+
const block = lines.slice(top + 1, end);
|
|
197
|
+
if (block.some((l) => /^\s+(nexorum|"nexorum"|'nexorum'):\s*(#.*)?$/.test(l))) return null;
|
|
198
|
+
const sibling = block.find((l) => /^\s+\S/.test(l));
|
|
199
|
+
const indent = sibling ? /^(\s+)/.exec(sibling)[1] : " ";
|
|
200
|
+
lines[top] = "mcp_servers:";
|
|
201
|
+
let at = end;
|
|
202
|
+
while (at > top + 1 && lines[at - 1].trim() === "") at--;
|
|
203
|
+
lines.splice(at, 0, ...entry(indent));
|
|
204
|
+
return lines.join(nl);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function setupHermes(home, { dryRun, env, useEnv }) {
|
|
208
|
+
out("Hermes:");
|
|
209
|
+
const file = path.join(hermesHome(home, env, { useEnv }), "config.yaml");
|
|
210
|
+
const raw = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null;
|
|
211
|
+
const next = mergeHermesYaml(raw);
|
|
212
|
+
if (next === null) return out(` nexorum is already in ${file}`);
|
|
213
|
+
if (dryRun) return out(` would add the nexorum MCP server to ${file}${raw !== null ? ` (backup: ${file}${BACKUP})` : " (new file)"}`);
|
|
214
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
215
|
+
const backup = `${file}${BACKUP}`;
|
|
216
|
+
if (raw !== null && !fs.existsSync(backup)) {
|
|
217
|
+
fs.writeFileSync(backup, raw);
|
|
218
|
+
out(` backed up ${file} -> ${backup}`);
|
|
219
|
+
}
|
|
220
|
+
atomicWrite(file, next);
|
|
221
|
+
out(` added the nexorum MCP server to ${file}`);
|
|
222
|
+
out(` Check it with: hermes mcp test nexorum (by hand instead: ${HERMES_CMD})`);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function setupJsonClient(label, file, { dryRun }) {
|
|
226
|
+
out(`${label}:`);
|
|
227
|
+
const { raw, data } = readJsonObject(file);
|
|
228
|
+
if (!mergeMcpServers(data)) return out(` nexorum is already in ${file}`);
|
|
229
|
+
if (dryRun) return out(` would add the nexorum MCP server to ${file}${raw !== null ? ` (backup: ${file}${BACKUP})` : " (new file)"}`);
|
|
230
|
+
writeWithBackup(file, raw, data);
|
|
231
|
+
out(` added the nexorum MCP server to ${file}`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function initCommand(flags, env, home) {
|
|
235
|
+
const all = Boolean(flags.all);
|
|
236
|
+
const named = ["claude-code", "codex", "hermes", "cursor", "claude-desktop"].some((k) => flags[k]);
|
|
237
|
+
const desktopFile = claudeDesktopConfigPath(home);
|
|
238
|
+
const want = {
|
|
239
|
+
claude: all || flags["claude-code"],
|
|
240
|
+
codex: all || flags.codex,
|
|
241
|
+
hermes: all || flags.hermes,
|
|
242
|
+
cursor: all || flags.cursor,
|
|
243
|
+
desktop: all || flags["claude-desktop"],
|
|
244
|
+
};
|
|
245
|
+
if (!all && !named) {
|
|
246
|
+
want.claude = fs.existsSync(path.join(home, ".claude"));
|
|
247
|
+
want.codex = fs.existsSync(path.join(home, ".codex")) || findBinary("codex", env) !== null;
|
|
248
|
+
want.hermes = fs.existsSync(hermesHome(home, env, { useEnv: !flags.home })) || findBinary("hermes", env) !== null;
|
|
249
|
+
want.cursor = fs.existsSync(path.join(home, ".cursor"));
|
|
250
|
+
want.desktop = fs.existsSync(path.dirname(desktopFile));
|
|
251
|
+
if (!Object.values(want).some(Boolean)) {
|
|
252
|
+
out("No supported client detected (looked for ~/.claude, ~/.codex, the Hermes home, ~/.cursor, the Claude Desktop config folder, and `codex` / `hermes` on PATH).");
|
|
253
|
+
out("Run with --claude-code, --codex, --hermes, --cursor, --claude-desktop or --all to set one up anyway.");
|
|
254
|
+
return 0;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const dryRun = Boolean(flags["dry-run"]);
|
|
258
|
+
if (dryRun) out("Dry run: nothing will be changed.");
|
|
259
|
+
if (want.claude) setupClaudeCode(home, { dryRun, env, promptRecall: Boolean(flags["prompt-recall"]) });
|
|
260
|
+
if (want.codex) setupCodex({ dryRun, env, dir: path.resolve(flags.dir ?? process.cwd()), home, agentsMd: !flags["no-agents-md"] });
|
|
261
|
+
if (want.hermes) setupHermes(home, { dryRun, env, useEnv: !flags.home });
|
|
262
|
+
if (want.cursor) setupJsonClient("Cursor", path.join(home, ".cursor", "mcp.json"), { dryRun });
|
|
263
|
+
if (want.desktop) setupJsonClient("Claude Desktop", desktopFile, { dryRun });
|
|
264
|
+
if (!dryRun) out("Done. Memory lives in ~/.nexorum (or $NEXORUM_HOME). Next: `nexorum status`.");
|
|
265
|
+
return 0;
|
|
266
|
+
}
|