@etilic/rutter_ai 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.
Files changed (66) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +80 -2
  3. package/THIRD_PARTY_LICENSES.txt +111 -0
  4. package/bin/cli.cjs +94 -0
  5. package/bin/npm-runtime.cjs +125 -0
  6. package/client/darwin-arm64/bootstrap.cjs +159 -0
  7. package/client/darwin-arm64/compat.cjs +61 -0
  8. package/client/darwin-arm64/hook.cjs +597 -0
  9. package/client/darwin-arm64/install.cjs +555 -0
  10. package/client/darwin-arm64/manifest.json +1 -0
  11. package/client/darwin-arm64/mcp.cjs +5666 -0
  12. package/client/darwin-arm64/migration.cjs +53 -0
  13. package/client/darwin-arm64/node_sqlite3.node +0 -0
  14. package/client/darwin-arm64/ordered-upload.cjs +236 -0
  15. package/client/darwin-arm64/outbox.cjs +218 -0
  16. package/client/darwin-arm64/recovery.cjs +61 -0
  17. package/client/darwin-arm64/sqlite3.cjs +217 -0
  18. package/client/darwin-arm64/transcript.cjs +138 -0
  19. package/client/darwin-arm64/upload.cjs +446 -0
  20. package/client/darwin-arm64/worker.cjs +76 -0
  21. package/client/darwin-x64/bootstrap.cjs +159 -0
  22. package/client/darwin-x64/compat.cjs +61 -0
  23. package/client/darwin-x64/hook.cjs +597 -0
  24. package/client/darwin-x64/install.cjs +555 -0
  25. package/client/darwin-x64/manifest.json +1 -0
  26. package/client/darwin-x64/mcp.cjs +5666 -0
  27. package/client/darwin-x64/migration.cjs +53 -0
  28. package/client/darwin-x64/node_sqlite3.node +0 -0
  29. package/client/darwin-x64/ordered-upload.cjs +236 -0
  30. package/client/darwin-x64/outbox.cjs +218 -0
  31. package/client/darwin-x64/recovery.cjs +61 -0
  32. package/client/darwin-x64/sqlite3.cjs +217 -0
  33. package/client/darwin-x64/transcript.cjs +138 -0
  34. package/client/darwin-x64/upload.cjs +446 -0
  35. package/client/darwin-x64/worker.cjs +76 -0
  36. package/client/linux-x64-glibc/bootstrap.cjs +159 -0
  37. package/client/linux-x64-glibc/compat.cjs +61 -0
  38. package/client/linux-x64-glibc/hook.cjs +597 -0
  39. package/client/linux-x64-glibc/install.cjs +555 -0
  40. package/client/linux-x64-glibc/manifest.json +1 -0
  41. package/client/linux-x64-glibc/mcp.cjs +5666 -0
  42. package/client/linux-x64-glibc/migration.cjs +53 -0
  43. package/client/linux-x64-glibc/node_sqlite3.node +0 -0
  44. package/client/linux-x64-glibc/ordered-upload.cjs +236 -0
  45. package/client/linux-x64-glibc/outbox.cjs +218 -0
  46. package/client/linux-x64-glibc/recovery.cjs +61 -0
  47. package/client/linux-x64-glibc/sqlite3.cjs +217 -0
  48. package/client/linux-x64-glibc/transcript.cjs +138 -0
  49. package/client/linux-x64-glibc/upload.cjs +446 -0
  50. package/client/linux-x64-glibc/worker.cjs +76 -0
  51. package/client/win32-x64/bootstrap.cjs +159 -0
  52. package/client/win32-x64/compat.cjs +61 -0
  53. package/client/win32-x64/hook.cjs +597 -0
  54. package/client/win32-x64/install.cjs +555 -0
  55. package/client/win32-x64/manifest.json +1 -0
  56. package/client/win32-x64/mcp.cjs +5666 -0
  57. package/client/win32-x64/migration.cjs +53 -0
  58. package/client/win32-x64/node_sqlite3.node +0 -0
  59. package/client/win32-x64/ordered-upload.cjs +236 -0
  60. package/client/win32-x64/outbox.cjs +218 -0
  61. package/client/win32-x64/recovery.cjs +61 -0
  62. package/client/win32-x64/sqlite3.cjs +217 -0
  63. package/client/win32-x64/transcript.cjs +138 -0
  64. package/client/win32-x64/upload.cjs +446 -0
  65. package/client/win32-x64/worker.cjs +76 -0
  66. package/package.json +34 -4
@@ -0,0 +1,555 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { request: fetch, performance } = require('./compat.cjs');
5
+
6
+ const fs = require('node:fs');
7
+ const os = require('node:os');
8
+ const path = require('node:path');
9
+ const readline = require('node:readline');
10
+ const { readConfig, configPath, configFingerprint, stateDirectory, writeSession, defaultsFile, readDirectoryDefaults, directoryDefault, requestMemory, normalizeCatalog, validateSelection } = require('./hook.cjs');
11
+
12
+ const CODEX_MARKER_START = '# >>> rutter-direct-memory-access (managed)';
13
+ const CODEX_MARKER_END = '# <<< rutter-direct-memory-access (managed)';
14
+ const HOOK_TIMEOUT_SECONDS = 330;
15
+
16
+ function installLog(home = process.env.HOME || os.homedir()) {
17
+ const file = path.join(home, '.config', 'rutter-direct-memory', 'install.log');
18
+ return {
19
+ file,
20
+ write(message) {
21
+ try {
22
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
23
+ fs.appendFileSync(file, `${new Date().toISOString()} ${message}\n`, { mode: 0o600 });
24
+ } catch { /* Logging must not prevent installation. */ }
25
+ },
26
+ };
27
+ }
28
+
29
+ function paths(home = process.env.HOME || os.homedir(), codexHome = process.env.CODEX_HOME || path.join(home, '.codex')) {
30
+ return {
31
+ home,
32
+ config: path.join(home, '.config', 'rutter-direct-memory', 'config.json'),
33
+ claudeSettings: path.join(home, '.claude', 'settings.json'),
34
+ claudeConfig: path.join(home, '.claude.json'),
35
+ codexConfig: path.join(codexHome, 'config.toml'),
36
+ };
37
+ }
38
+
39
+ function atomicWrite(file, contents, mode = 0o600) {
40
+ const directory = path.dirname(file);
41
+ const existed = fs.existsSync(directory);
42
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
43
+ if (!existed) try { fs.chmodSync(directory, 0o700); } catch {}
44
+ const temp = `${file}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
45
+ fs.writeFileSync(temp, contents, { encoding: 'utf8', mode, flag: 'wx' });
46
+ fs.renameSync(temp, file);
47
+ fs.chmodSync(file, mode);
48
+ }
49
+
50
+ function backup(file) {
51
+ if (!fs.existsSync(file)) return null;
52
+ const stamp = new Date().toISOString().replace(/[-:TZ.]/g, '').slice(0, 14);
53
+ const backupPath = `${file}.backup-${stamp}-${process.pid}-${Math.random().toString(16).slice(2, 8)}`;
54
+ fs.copyFileSync(file, backupPath, fs.constants.COPYFILE_EXCL);
55
+ try { fs.chmodSync(backupPath, fs.statSync(file).mode & 0o777); } catch {}
56
+ return backupPath;
57
+ }
58
+
59
+ function shellQuote(value) {
60
+ if (/[\r\n]/.test(value)) throw new Error('Hook 路径不能包含换行符。');
61
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\$/g, '\\$').replace(/`/g, '\\`')}"`;
62
+ }
63
+
64
+ function quoteCommandPath(hookPath) {
65
+ if (process.platform === 'win32') {
66
+ if (/[\r\n]/.test(hookPath)) throw new Error('Hook 路径不能包含换行符。');
67
+ return `"${hookPath.replace(/"/g, '\\"')}"`;
68
+ }
69
+ return shellQuote(hookPath);
70
+ }
71
+
72
+ function claudeCommand(hookPath) { return `node ${quoteCommandPath(hookPath)} --client claude`; }
73
+ function codexCommand(hookPath) { return `node ${shellQuote(hookPath)} --client codex`; }
74
+ function codexWindowsCommand(hookPath) {
75
+ if (/[\r\n]/.test(hookPath)) throw new Error('Hook 路径不能包含换行符。');
76
+ return `node "${hookPath.replace(/"/g, '\\"')}" --client codex`;
77
+ }
78
+
79
+ function prepareClaude(settingsFile, hookPath, previousHookPath) {
80
+ let settings = {};
81
+ let exists = fs.existsSync(settingsFile);
82
+ if (exists) {
83
+ try { settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8')); }
84
+ catch { throw new Error(`Claude Code 设置文件不是有效 JSON,未修改:${settingsFile}`); }
85
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw new Error(`Claude Code 设置根节点格式无效,未修改:${settingsFile}`);
86
+ }
87
+ const next = JSON.parse(JSON.stringify(settings));
88
+ next.hooks ??= {};
89
+ if (!next.hooks || typeof next.hooks !== 'object' || Array.isArray(next.hooks)) throw new Error('Claude Code hooks 设置格式无效,未修改。');
90
+ const command = claudeCommand(hookPath);
91
+ let changed = !exists;
92
+ for (const event of ['UserPromptSubmit', 'Stop']) {
93
+ next.hooks[event] ??= [];
94
+ if (!Array.isArray(next.hooks[event])) throw new Error(`Claude Code ${event} 必须是数组,未修改。`);
95
+ if (previousHookPath && previousHookPath !== hookPath) {
96
+ const oldCommand = claudeCommand(previousHookPath);
97
+ for (const group of next.hooks[event]) {
98
+ if (!Array.isArray(group?.hooks)) continue;
99
+ for (const item of group.hooks) {
100
+ if (item?.type === 'command' && item.command === oldCommand) { item.command = command; changed = true; }
101
+ }
102
+ }
103
+ }
104
+ const installed = next.hooks[event].some(group => Array.isArray(group?.hooks) && group.hooks.some(item => item?.type === 'command' && item.command === command));
105
+ if (!installed) { next.hooks[event].push({ hooks: [{ type: 'command', command, timeout: HOOK_TIMEOUT_SECONDS }] }); changed = true; }
106
+ }
107
+ return { changed, next, exists };
108
+ }
109
+
110
+ function removeClaude(settingsFile, hookPath) {
111
+ if (!fs.existsSync(settingsFile)) return { changed: false };
112
+ let settings;
113
+ try { settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8')); }
114
+ catch { throw new Error(`Claude Code 设置文件不是有效 JSON,未修改:${settingsFile}`); }
115
+ const command = claudeCommand(hookPath);
116
+ let changed = false;
117
+ for (const event of ['UserPromptSubmit', 'Stop']) {
118
+ const list = settings?.hooks?.[event];
119
+ if (!Array.isArray(list)) continue;
120
+ const nextList = list.map(group => ({ ...group, hooks: Array.isArray(group?.hooks) ? group.hooks.filter(item => !(item?.type === 'command' && item.command === command)) : group?.hooks }))
121
+ .filter(group => !Array.isArray(group?.hooks) || group.hooks.length > 0);
122
+ if (JSON.stringify(list) === JSON.stringify(nextList)) continue;
123
+ changed = true;
124
+ if (nextList.length) settings.hooks[event] = nextList; else delete settings.hooks[event];
125
+ }
126
+ return { changed, next: settings, exists: true };
127
+ }
128
+
129
+ function inspectCodexConfig(source) {
130
+ if (/^\s*hooks\s*=/m.test(source)) throw new Error('Codex config.toml 使用了 inline hooks 表,安装器无法安全合并;未修改。请手动把 UserPromptSubmit Hook 合并进现有 hooks 设置。');
131
+ const lines = source.split(/\r?\n/);
132
+ let section = '';
133
+ for (const line of lines) {
134
+ const table = line.match(/^\s*\[\[?([^\]]+)\]\]?\s*(?:#.*)?$/);
135
+ if (table) {
136
+ section = table[1].trim();
137
+ if (['hooks.UserPromptSubmit', 'hooks.UserPromptSubmit.hooks', 'hooks.Stop', 'hooks.Stop.hooks'].includes(section)) {
138
+ throw new Error('Codex config.toml 已有 UserPromptSubmit Hook,安装器不会重复或猜测合并;未修改。请先手动合并 Hook。');
139
+ }
140
+ }
141
+ if (/^\s*hooks\.(UserPromptSubmit|Stop)\s*=/.test(line) || (section === 'hooks' && /^\s*(UserPromptSubmit|Stop)\s*=/.test(line))) {
142
+ throw new Error('Codex config.toml 已定义 UserPromptSubmit 的 inline 配置,安装器不会覆盖或猜测合并;未修改。请先手动合并 Hook。');
143
+ }
144
+ }
145
+ }
146
+
147
+ function prepareCodex(configFile, hookPath) {
148
+ const exists = fs.existsSync(configFile);
149
+ const source = exists ? fs.readFileSync(configFile, 'utf8') : '';
150
+ const block = source.match(new RegExp(`${escapeRegex(CODEX_MARKER_START)}[\\s\\S]*?${escapeRegex(CODEX_MARKER_END)}`))?.[0];
151
+ const base = block ? source.replace(block, '') : source;
152
+ inspectCodexConfig(base);
153
+ const command = codexCommand(hookPath);
154
+ const windowsCommand = process.platform === 'win32' ? `commandWindows = ${JSON.stringify(codexWindowsCommand(hookPath))}\n` : '';
155
+ if (/^\s*\[mcp_servers\.rutter_direct_memory\]/m.test(base)) throw new Error('Codex 已存在 rutter_direct_memory MCP 配置,未修改。');
156
+ const mcpPath = path.join(path.dirname(hookPath), 'mcp.cjs');
157
+ const addition = `${CODEX_MARKER_START}\n[mcp_servers.rutter_direct_memory]\ncommand = "node"\nargs = [${JSON.stringify(mcpPath)}, "codex"]\n\n[[hooks.UserPromptSubmit]]\nstatusMessage = "Loading authorized Memory context"\n\n[[hooks.UserPromptSubmit.hooks]]\ntype = "command"\ncommand = ${JSON.stringify(command)}\n${windowsCommand}timeout = ${HOOK_TIMEOUT_SECONDS}\n\n[[hooks.Stop]]\n[[hooks.Stop.hooks]]\ntype = "command"\ncommand = ${JSON.stringify(command)}\n${windowsCommand}timeout = ${HOOK_TIMEOUT_SECONDS}\n${CODEX_MARKER_END}`;
158
+ const next = block ? source.replace(block, addition) : `${source.trimEnd()}${source.trim() ? '\n\n' : ''}${addition}\n`;
159
+ return { changed: next !== source, next, exists };
160
+ }
161
+
162
+ function escapeRegex(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
163
+
164
+ function prepareClaudeMcp(file, hookPath, remove = false) {
165
+ const exists = fs.existsSync(file);
166
+ let config = {};
167
+ if (exists) { try { config = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { throw new Error('Claude 配置不是有效 JSON,未修改。'); } }
168
+ if (!config || typeof config !== 'object' || Array.isArray(config) || (config.mcpServers && (typeof config.mcpServers !== 'object' || Array.isArray(config.mcpServers)))) throw new Error('Claude MCP 配置格式无效,未修改。');
169
+ const name = 'rutter_direct_memory';
170
+ const entry = { type: 'stdio', command: 'node', args: [path.join(path.dirname(hookPath), 'mcp.cjs'), 'claude'] };
171
+ const current = config.mcpServers?.[name];
172
+ let previousHookPath;
173
+ if (current && JSON.stringify(current) !== JSON.stringify(entry)) {
174
+ const previous = current.type === 'stdio' && current.command === 'node' && Array.isArray(current.args) && current.args.length === 2 && current.args[1] === 'claude' && typeof current.args[0] === 'string' && path.basename(current.args[0]) === 'mcp.cjs' ? current.args[0] : '';
175
+ const previousDir = previous && path.dirname(previous);
176
+ const recognized = previousDir && (path.basename(previousDir) === 'direct-memory-access' || path.basename(path.dirname(previousDir)) === 'releases');
177
+ if (!recognized) throw new Error('Claude 已存在不同的 rutter_direct_memory MCP 配置,未修改。');
178
+ previousHookPath = path.join(previousDir, 'hook.cjs');
179
+ }
180
+ if (remove) { if (!current) return { changed: false }; delete config.mcpServers[name]; if (!Object.keys(config.mcpServers).length) delete config.mcpServers; }
181
+ else { config.mcpServers ??= {}; config.mcpServers[name] = entry; }
182
+ return { changed: remove || !current || Boolean(previousHookPath), next: config, exists, previousHookPath };
183
+ }
184
+
185
+ function removeCodex(configFile) {
186
+ if (!fs.existsSync(configFile)) return { changed: false };
187
+ const source = fs.readFileSync(configFile, 'utf8');
188
+ const expression = new RegExp(`(?:\\r?\\n)?${escapeRegex(CODEX_MARKER_START)}[\\s\\S]*?${escapeRegex(CODEX_MARKER_END)}\\s*`);
189
+ const next = source.replace(expression, '\n').replace(/\n{3,}/g, '\n\n');
190
+ return { changed: next !== source, next, exists: true };
191
+ }
192
+
193
+ function validateNewConfig(config) {
194
+ const url = new URL(config.service_url);
195
+ const localHttp = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
196
+ if (!['https:', ...(localHttp ? ['http:'] : [])].includes(url.protocol) || url.search || url.hash || !url.pathname.replace(/\/$/, '').endsWith('/v3')) {
197
+ throw new Error('服务地址必须是 HTTPS 的 /v3 API 地址;仅 localhost 可使用 HTTP。');
198
+ }
199
+ if (!/^[A-Za-z0-9_-]{1,200}$/.test(config.service_id)) throw new Error('Service ID 只能包含字母、数字、下划线和连字符。');
200
+ if (!/^sk-mem-[A-Za-z0-9_-]{32}$/.test(config.memory_user_key || '')) throw new Error('Memory 用户凭证必须是目标实例的完整 User_Key(sk-mem- 开头);不能填写 default、Service ID 或密码。');
201
+ }
202
+
203
+ function promptLine(label, { hidden = false } = {}) {
204
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return Promise.reject(new Error('首次配置需要交互式终端;请在 TTY 中重新运行安装器。'));
205
+ return new Promise((resolve, reject) => {
206
+ if (!hidden) {
207
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
208
+ rl.question(label, answer => { rl.close(); resolve(answer.trim()); });
209
+ return;
210
+ }
211
+ const stdin = process.stdin;
212
+ const wasRaw = stdin.isRaw;
213
+ let value = '';
214
+ stdin.setRawMode(true);
215
+ stdin.resume();
216
+ const finish = (error, answer) => {
217
+ stdin.off('data', onData);
218
+ stdin.setRawMode(Boolean(wasRaw));
219
+ stdin.pause();
220
+ process.stdout.write('\n');
221
+ error ? reject(error) : resolve(answer);
222
+ };
223
+ const onData = chunk => {
224
+ for (const char of chunk.toString('utf8')) {
225
+ if (char === '\u0003') return finish(new Error('配置已取消。'));
226
+ if (char === '\r' || char === '\n') return finish(null, value);
227
+ if (char === '\u007f' || char === '\b') value = value.slice(0, -1);
228
+ else if (char >= ' ') value += char;
229
+ }
230
+ };
231
+ stdin.on('data', onData);
232
+ process.stdout.write(label);
233
+ });
234
+ }
235
+
236
+ async function verifyConnection(config, fetcher = fetch) {
237
+ let response;
238
+ try {
239
+ response = await fetcher(`${config.service_url}/hierarchy/direct-memory/catalog`, {
240
+ method: 'POST', redirect: 'error', timeoutMs: 15000,
241
+ headers: { 'content-type': 'application/json', 'x-tdai-service-id': config.service_id, 'x-tdai-user-key': config.memory_user_key },
242
+ body: '{}',
243
+ });
244
+ } catch {
245
+ const error = new Error('无法连接 Memory 服务,配置未保存。请检查 API 地址、网络和 HTTPS 服务状态后重新安装。');
246
+ error.code = 'CONNECTION_FAILED';
247
+ throw error;
248
+ }
249
+ let envelope;
250
+ try { envelope = await response.json(); } catch {
251
+ const error = new Error('Memory 服务返回了无法识别的响应,配置未保存。请确认使用的是 /v3 API 地址。');
252
+ error.code = 'INVALID_RESPONSE';
253
+ throw error;
254
+ }
255
+ if ([401, 403].includes(response.status) || [401, 403].includes(envelope?.code)) {
256
+ const error = new Error('Memory 用户凭证无效、已过期或无访问权限,请检查 Service ID 并使用目标实例的 User_Key 重新配置。');
257
+ error.code = 'ACCESS_DENIED';
258
+ error.reconfigure = true;
259
+ throw error;
260
+ }
261
+ if (!response.ok || envelope?.code !== 0 || !Array.isArray(envelope?.data?.teams)) {
262
+ const error = new Error('Memory 服务验证失败,配置未保存。请检查服务状态及 /v3 API 地址后重新安装。');
263
+ error.code = 'VERIFICATION_FAILED';
264
+ throw error;
265
+ }
266
+ }
267
+
268
+ async function configureConnection(configFile, { reconfigure = false, prompt = promptLine, fetcher = fetch, output = process.stdout, env = process.env } = {}) {
269
+ const defaultUrl = env.RUTTER_DIRECT_MEMORY_SERVER ? `${env.RUTTER_DIRECT_MEMORY_SERVER}/v3` : '';
270
+ const quickSetup = env.RUTTER_DIRECT_MEMORY_QUICK_SETUP === '1' && Boolean(defaultUrl);
271
+ if (quickSetup) output.write(`直接连接 ${defaultUrl}(Service ID:default),无需 SSH。\n`);
272
+ if (!reconfigure && fs.existsSync(configFile)) {
273
+ let config;
274
+ try { config = readConfig(configFile); validateNewConfig(config); }
275
+ catch { config = undefined; output.write('已有 Memory 配置格式无效,请重新填写;验证成功前保留原配置。\n'); }
276
+ if (config && quickSetup && (config.service_url !== defaultUrl || config.service_id !== 'default')) {
277
+ output.write('检测到其他地址或实例的旧配置。本次将接入上述 HTTPS 服务,请填写该服务的 User_Key;验证成功前保留旧配置。\n');
278
+ config = undefined;
279
+ }
280
+ if (config) {
281
+ try {
282
+ await verifyConnection(config, fetcher);
283
+ return { config, changed: false };
284
+ } catch (error) {
285
+ if (!error.reconfigure) throw error;
286
+ output.write(`${error.message}\n`);
287
+ }
288
+ }
289
+ }
290
+ output.write('配置 Memory:用户凭证仅保存在本机,不会发送给模型。\n');
291
+ for (;;) {
292
+ const serviceUrl = quickSetup ? defaultUrl : await prompt(defaultUrl ? `Memory API 地址(回车使用 ${defaultUrl}):` : 'Memory API 地址(HTTPS,包含 /v3):') || defaultUrl;
293
+ const serviceId = quickSetup ? 'default' : await prompt('Service ID(回车使用 default):') || 'default';
294
+ const userKey = await prompt('Memory 用户凭证(User_Key,输入时不显示):', { hidden: true });
295
+ const config = { service_url: serviceUrl.replace(/\/$/, ''), service_id: serviceId, memory_user_key: userKey };
296
+ try { validateNewConfig(config); }
297
+ catch (error) { output.write(`${error.message}\n请重新填写。\n`); continue; }
298
+ try {
299
+ await verifyConnection(config, fetcher);
300
+ return { config, changed: true };
301
+ } catch (error) {
302
+ if (!error.reconfigure) throw error;
303
+ output.write(`${error.message}\n`);
304
+ }
305
+ }
306
+ }
307
+
308
+ // Configuration commands share the upload lock, so a credential change cannot
309
+ // race capture/retry. Interactive choices and network validation happen first.
310
+ async function configCommand(argv, { env = process.env, prompt = promptLine, fetcher = fetch, output = process.stdout, cwd = process.cwd() } = {}) {
311
+ const usage = '用法:config key | config project set|show|clear(当前目录及子目录)';
312
+ if (!argv.length || (argv.length === 1 && ['--help', '-h'].includes(argv[0]))) { output.write(`${usage}\n`); return; }
313
+ const keyAction = argv.length === 1 && argv[0] === 'key';
314
+ const projectAction = argv.length === 2 && argv[0] === 'project' && ['set', 'show', 'clear'].includes(argv[1]);
315
+ if (!keyAction && !projectAction) throw new Error(usage);
316
+ const upload = require('./upload.cjs');
317
+ const file = configPath(env);
318
+ const safe = value => String(value).replace(/\bsk[-_][A-Za-z0-9_-]{4,}/gi, '[已隐藏]').replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ');
319
+ let canonical;
320
+ try { canonical = fs.realpathSync.native(cwd); if (!fs.statSync(canonical).isDirectory()) throw new Error(); }
321
+ catch { throw new Error('当前目录无法访问,未修改配置。'); }
322
+ if (projectAction && argv[1] === 'show') {
323
+ const entry = directoryDefault(canonical, env);
324
+ if (!entry) { output.write('当前目录没有默认项目,新会话使用原选择流程。\n'); return null; }
325
+ const selection = entry.selection;
326
+ output.write(`默认配置来源:${safe(entry.directory)}\n团队:${safe(selection.team_id)};项目:${safe(selection.project_id)};Agent:${safe(selection.agent_id)};Task:${safe(selection.task_id) || '无'};自动上传同意:${selection.upload_enabled ? '是(仍受总开关限制)' : '否'}。\n`);
327
+ const current = readConfig(file);
328
+ output.write(entry.fingerprint === configFingerprint(current) ? '身份匹配;实际资产权限将在加载时验证。\n' : '身份已改变;请运行 config project set 重新配置或用 config key 恢复原 Key。\n');
329
+ return entry;
330
+ }
331
+ if (projectAction && argv[1] === 'clear') {
332
+ return upload.withLock(env, async () => {
333
+ const data = readDirectoryDefaults(env);
334
+ const entries = data.entries.filter(entry => entry.directory !== canonical);
335
+ atomicWrite(defaultsFile(env), `${JSON.stringify({ version: 1, entries })}\n`);
336
+ output.write(entries.length === data.entries.length ? '当前目录没有独立默认配置;父目录配置仍会继承。\n' : '已清除当前目录的默认配置;已有会话不变。\n');
337
+ if (directoryDefault(canonical, env)) output.write('当前仍继承父目录默认配置;可用 config project show 查看来源。\n');
338
+ });
339
+ }
340
+ const original = fs.readFileSync(file, 'utf8');
341
+ const config = readConfig(file);
342
+ const fingerprint = configFingerprint(config);
343
+ const unchanged = () => {
344
+ if (fs.readFileSync(file, 'utf8') !== original) throw new Error('Memory 配置在操作期间改变,未保存,请重试。');
345
+ };
346
+ if (keyAction) {
347
+ const value = await prompt('新的 Memory User_Key(输入时不显示,回车取消):', { hidden: true });
348
+ if (typeof value !== 'string' || !value.trim()) { output.write('已取消,原配置未更改。\n'); return { cancelled: true }; }
349
+ const next = { ...config, memory_user_key: value.trim() };
350
+ validateNewConfig(next);
351
+ await verifyConnection(next, fetcher);
352
+ return upload.withLock(env, async () => {
353
+ unchanged();
354
+ const active = upload.readState(env);
355
+ if ((active.fingerprint && !/^[a-f0-9]{64}$/.test(active.fingerprint)) || (!active.fingerprint && active.queue.length)) throw new Error('旧队列身份无法确认,未更换 Key。');
356
+ if (next.memory_user_key === config.memory_user_key && (!active.fingerprint || active.fingerprint === fingerprint)) { output.write('User_Key 验证成功,与原配置相同。\n'); return; }
357
+ // Stamp legacy bindings before changing identity. Never change their IDs,
358
+ // consent, signatures, or content. Restoring the old Key can reuse them.
359
+ let files = [];
360
+ try { files = fs.readdirSync(stateDirectory(env)); } catch (error) { if (error.code !== 'ENOENT') throw new Error('旧会话状态无法检查,未更换 Key。'); }
361
+ for (const name of files.filter(name => /^[a-f0-9]{64}\.json$/.test(name))) {
362
+ let state;
363
+ try { state = JSON.parse(fs.readFileSync(path.join(stateDirectory(env), name), 'utf8')); }
364
+ catch { throw new Error('旧会话状态无法读取,未更换 Key。'); }
365
+ if (state.mode === 'off' || state.config_fingerprint) continue;
366
+ if (!['codex', 'claude'].includes(state.client) || typeof state.session_id !== 'string' || !state.session_id || typeof state.cwd !== 'string' || !state.cwd) throw new Error('旧会话格式无效,未更换 Key。');
367
+ writeSession(state.client, state.session_id, state.cwd, { ...state, config_fingerprint: fingerprint }, env);
368
+ }
369
+ const state = upload.readState(env);
370
+ state.preserve_identity = true;
371
+ // Persist the active state first: a crash during the following switch
372
+ // leaves a mismatching fingerprint that stops sending without deleting.
373
+ upload.writeState(env, state);
374
+ if (state.fingerprint) upload.writeState(env, state, `${upload.statePath(env)}.${state.fingerprint}.json`);
375
+ const nextFingerprint = configFingerprint(next);
376
+ const nextState = upload.readState(env, `${upload.statePath(env)}.${nextFingerprint}.json`);
377
+ if ((nextState.fingerprint && nextState.fingerprint !== nextFingerprint) || (!nextState.fingerprint && nextState.queue.length)) throw new Error('目标身份队列指纹无效,未更换 Key。');
378
+ if (!nextState.fingerprint) {
379
+ nextState.fingerprint = nextFingerprint;
380
+ // Each session owns its consent boundary. A Key change cannot expire
381
+ // other windows before stable-user verification has run.
382
+ nextState.since = state.since || Date.now();
383
+ nextState.enabled = state.enabled;
384
+ }
385
+ // Explicit global disable remains authoritative across identity switches.
386
+ if (state.manually_disabled) { nextState.enabled = false; nextState.manually_disabled = true; }
387
+ nextState.preserve_identity = true;
388
+ // Preserve unrelated configuration fields; the command only changes Key.
389
+ const nextRaw = { ...JSON.parse(original), memory_user_key: next.memory_user_key };
390
+ const saved = backup(file);
391
+ if (saved) fs.chmodSync(saved, 0o600);
392
+ atomicWrite(file, `${JSON.stringify(nextRaw, null, 2)}\n`, 0o600);
393
+ upload.writeState(env, nextState);
394
+ fs.rmSync(`${upload.statePath(env)}.${nextFingerprint}.json`, { force: true });
395
+ output.write('User_Key 验证成功,已备份并保存。旧身份会话、目录默认配置及待传内容均保留;不会自动迁移。\n');
396
+ return { changed: true };
397
+ });
398
+ }
399
+ const catalog = normalizeCatalog(await requestMemory(config, 'catalog', {}, fetcher));
400
+ const clean = value => safe(value).split(config.memory_user_key).join('[已隐藏]');
401
+ async function choose(items, label, optional = false) {
402
+ if (!items.length && !optional) throw new Error('当前身份没有可选资产,未保存默认项目。');
403
+ items.forEach((item, index) => output.write(`${index + 1}. ${clean(label(item))}\n`));
404
+ for (;;) {
405
+ const answer = String(await prompt(optional ? 'Task:输入序号,0 不关联,回车取消:' : '输入序号,回车取消:')).trim();
406
+ if (!answer) return null;
407
+ if (optional && answer === '0') return {};
408
+ if (/^[1-9]\d*$/.test(answer) && items[Number(answer) - 1]) return items[Number(answer) - 1];
409
+ output.write('请选择列表中的序号。\n');
410
+ }
411
+ }
412
+ const cancelled = () => { output.write('已取消,默认项目未更改。\n'); return { cancelled: true }; };
413
+ output.write('选择默认团队:\n');
414
+ const team = await choose(catalog, item => item.name); if (!team) return cancelled();
415
+ output.write('选择默认项目:\n');
416
+ const project = await choose(team.projects, item => item.name); if (!project) return cancelled();
417
+ output.write('选择默认 Agent:\n');
418
+ const agent = await choose(team.agents, item => item.name); if (!agent) return cancelled();
419
+ output.write('选择可选 Task:\n');
420
+ const task = await choose(team.tasks, item => item.title, true); if (!task) return cancelled();
421
+ const consent = String(await prompt('此目录未来新会话是否自动上传主会话用户文本和最终助手回复到项目 L0?输入 YES 同意、NO 不上传,回车取消:')).trim();
422
+ if (!['YES', 'NO'].includes(consent)) return cancelled();
423
+ const selection = validateSelection(catalog, { team_id: team.team_id, company_id: project.company_id, project_id: project.project_id, agent_id: agent.agent_id, task_id: task.task_id || '', upload_enabled: consent === 'YES' });
424
+ const context = await requestMemory(config, 'context', { ...selection, session_id: `directory-check-${require('node:crypto').randomBytes(16).toString('hex')}`, query: 'Validate directory default assets' }, fetcher);
425
+ if (typeof context.session_binding !== 'string' || !/^[a-f0-9]{64}$/.test(context.session_binding)) throw new Error('服务端未确认资产绑定,未保存默认项目。');
426
+ return upload.withLock(env, async () => {
427
+ unchanged();
428
+ const data = readDirectoryDefaults(env);
429
+ const entry = { directory: canonical, fingerprint, selection };
430
+ const entries = [...data.entries.filter(entry => entry.directory !== canonical), entry];
431
+ atomicWrite(defaultsFile(env), `${JSON.stringify({ version: 1, entries })}\n`, 0o600);
432
+ output.write('已保存当前目录及子目录的默认配置。后续新会话直接加载,不打开选择页;已有会话和队列不变。\n');
433
+ return entry;
434
+ });
435
+ }
436
+
437
+ function writePrepared(file, prepared) {
438
+ if (!prepared.changed) return null;
439
+ const backupPath = backup(file);
440
+ const mode = prepared.exists ? fs.statSync(file).mode & 0o777 : 0o600;
441
+ atomicWrite(file, typeof prepared.next === 'string' ? prepared.next : `${JSON.stringify(prepared.next, null, 2)}\n`, mode);
442
+ return backupPath;
443
+ }
444
+
445
+ function install({ client = 'both', hookPath = path.join(__dirname, 'hook.cjs'), home, codexHome } = {}) {
446
+ const filePaths = paths(home, codexHome);
447
+ if (!['both', 'codex', 'claude'].includes(client)) throw new Error('client 必须为 both、codex 或 claude。');
448
+ const plans = [];
449
+ if (client === 'both' || client === 'claude') {
450
+ const mcp = prepareClaudeMcp(filePaths.claudeConfig, hookPath);
451
+ plans.push([filePaths.claudeSettings, prepareClaude(filePaths.claudeSettings, hookPath, mcp.previousHookPath)]);
452
+ plans.push([filePaths.claudeConfig, mcp]);
453
+ }
454
+ if (client === 'both' || client === 'codex') plans.push([filePaths.codexConfig, prepareCodex(filePaths.codexConfig, hookPath)]);
455
+ const backups = [];
456
+ for (const [file, prepared] of plans) {
457
+ const saved = writePrepared(file, prepared);
458
+ if (saved) backups.push(saved);
459
+ }
460
+ return { config: filePaths.config, changed: plans.filter(([, plan]) => plan.changed).map(([file]) => file), backups };
461
+ }
462
+
463
+ function uninstall({ client = 'both', hookPath = path.join(__dirname, 'hook.cjs'), home, codexHome } = {}) {
464
+ const filePaths = paths(home, codexHome);
465
+ if (!['both', 'codex', 'claude'].includes(client)) throw new Error('client 必须为 both、codex 或 claude。');
466
+ const plans = [];
467
+ if (client === 'both' || client === 'claude') {
468
+ const mcp = prepareClaudeMcp(filePaths.claudeConfig, hookPath, true);
469
+ plans.push([filePaths.claudeSettings, removeClaude(filePaths.claudeSettings, mcp.previousHookPath || hookPath)]);
470
+ plans.push([filePaths.claudeConfig, mcp]);
471
+ }
472
+ if (client === 'both' || client === 'codex') plans.push([filePaths.codexConfig, removeCodex(filePaths.codexConfig)]);
473
+ const backups = [];
474
+ for (const [file, prepared] of plans) {
475
+ const saved = writePrepared(file, prepared);
476
+ if (saved) backups.push(saved);
477
+ }
478
+ return { changed: plans.filter(([, plan]) => plan.changed).map(([file]) => file), backups };
479
+ }
480
+
481
+ function parseArgs(args) {
482
+ const parsed = { client: 'both', uninstall: false, reconfigure: false };
483
+ for (let i = 0; i < args.length; i += 1) {
484
+ if (args[i] === '--client') parsed.client = args[++i];
485
+ else if (args[i].startsWith('--client=')) parsed.client = args[i].slice(9);
486
+ else if (args[i] === '--uninstall') parsed.uninstall = true;
487
+ else if (args[i] === '--reconfigure') parsed.reconfigure = true;
488
+ else if (args[i] === '--help' || args[i] === '-h') parsed.help = true;
489
+ else throw new Error(`未知参数:${args[i]}`);
490
+ }
491
+ return parsed;
492
+ }
493
+
494
+ async function main(argv = process.argv.slice(2), { home, codexHome, env = process.env, prompt, fetcher, output = process.stdout } = {}) {
495
+ if (argv[0] === 'config') return configCommand(argv.slice(1), { env, prompt, fetcher, output });
496
+ const args = parseArgs(argv);
497
+ if (args.help) {
498
+ process.stdout.write('用法:node install.cjs [--client both|codex|claude] [--reconfigure] [--uninstall]\n首次安装会交互式收集 Memory API 地址、Service ID 和 Memory 用户凭证;凭证不回显并以 0600 权限保存。\n');
499
+ return;
500
+ }
501
+ const filePaths = paths(home, codexHome);
502
+ const log = installLog(filePaths.home);
503
+ let stage = 'start';
504
+ log.write(`start operation=${args.uninstall ? 'uninstall' : 'install'} client=${['both', 'codex', 'claude'].includes(args.client) ? args.client : 'invalid'}`);
505
+ output.write(`安装日志:${log.file}\n`);
506
+ try {
507
+ if (args.uninstall) {
508
+ stage = 'remove client configuration';
509
+ await require('./upload.cjs').setConsent(false, { ...env, HOME: filePaths.home });
510
+ if (env.RUTTER_DIRECT_MEMORY_RECOVERY !== 'manual') require('./recovery.cjs').configure({ remove: true, env: { ...env, HOME: filePaths.home } });
511
+ const result = uninstall({ client: args.client, home, codexHome, hookPath: env.RUTTER_DIRECT_MEMORY_HOOK_PATH || path.join(__dirname, 'hook.cjs') });
512
+ log.write(`success stage=uninstall changed=${result.changed.length}`);
513
+ process.stdout.write(`已移除 Hook:${result.changed.length ? result.changed.join(', ') : '没有需要移除的配置'}\n`);
514
+ return;
515
+ }
516
+ stage = 'verify connection';
517
+ log.write(`stage=${stage}`);
518
+ const prepared = await configureConnection(filePaths.config, { reconfigure: args.reconfigure, prompt, fetcher, output, env });
519
+ stage = 'verify SQLite runtime';
520
+ const probe = await require('./outbox.cjs').Outbox.open(path.join(filePaths.home, '.config/rutter-direct-memory/outbox.sqlite'));
521
+ await probe.close();
522
+ stage = 'write client configuration';
523
+ log.write(`stage=${stage}`);
524
+ const result = install({ client: args.client, home, codexHome, hookPath: env.RUTTER_DIRECT_MEMORY_HOOK_PATH || path.join(__dirname, 'hook.cjs') });
525
+ stage = 'save memory configuration';
526
+ log.write(`stage=${stage}`);
527
+ if (prepared.changed) {
528
+ const saved = backup(filePaths.config);
529
+ if (saved) { fs.chmodSync(saved, 0o600); result.backups.push(saved); }
530
+ atomicWrite(filePaths.config, `${JSON.stringify(prepared.config, null, 2)}\n`, 0o600);
531
+ }
532
+ fs.chmodSync(filePaths.config, 0o600);
533
+ stage = 'enable upload';
534
+ log.write(`stage=${stage}`);
535
+ await require('./upload.cjs').enableAfterInstall({ ...env, HOME: filePaths.home, RUTTER_DIRECT_MEMORY_CONFIG: filePaths.config });
536
+ stage = 'register recovery';
537
+ if (env.RUTTER_DIRECT_MEMORY_RECOVERY === 'manual') output.write('后台恢复未注册(manual 模式);需要自行运行 ordered-upload.cjs --recover。\n');
538
+ else require('./recovery.cjs').configure({ env: { ...env, HOME: filePaths.home, RUTTER_DIRECT_MEMORY_CONFIG: filePaths.config } });
539
+ log.write(`success stage=install changed=${result.changed.length} backups=${result.backups.length}`);
540
+ output.write(`Memory 连接及用户凭证验证成功,已安装 ${args.client} Hook 和 MCP。Memory 凭证保存在 ${filePaths.config}(仅当前用户可读)。\n`);
541
+ output.write('上传总开关已开启(包括重新安装或升级);新会话默认勾选上传用户文本和最终助手回复到项目 L0,可在选择页取消勾选或选择本次不使用 Memory。\n');
542
+ if (result.backups.length) output.write(`原设置已备份:${result.backups.join(', ')}\n`);
543
+ output.write('下次运行 Codex 时,若出现 Hook 信任确认,请检查命令路径后在客户端确认;安装器不会绕过该确认。\n');
544
+ return result;
545
+ } catch (error) {
546
+ const code = typeof error?.code === 'string' && /^[A-Z0-9_]{1,32}$/.test(error.code) ? error.code : 'UNKNOWN';
547
+ log.write(`failure stage=${stage} code=${code}`);
548
+ throw error;
549
+ }
550
+ }
551
+
552
+ if (require.main === module) main().catch(error => { process.stderr.write(`${error.message}\n`); process.exitCode = 1; });
553
+
554
+ module.exports = { installLog, paths, atomicWrite, backup, shellQuote, quoteCommandPath, claudeCommand, codexCommand, codexWindowsCommand, prepareClaude, removeClaude,
555
+ inspectCodexConfig, prepareCodex, removeCodex, validateNewConfig, verifyConnection, configureConnection, configCommand, install, uninstall, parseArgs, main };
@@ -0,0 +1 @@
1
+ {"version":"7d4f8c5c23473db20298","runtime":{"platform":"linux","arch":"x64","napi":6,"sqlite_version":"3.51.3","sqlite_source_id":"2026-03-13 10:38:09 737ae4a34738ffa0c3ff7f9bb18df914dd1cad163f28fd6b6e114a344fe6d618","libc":"glibc"},"files":{"hook.cjs":"87ed807aadec959cd328e8780f207d8cbb951ceb1545e295b642e8dc43f13395","install.cjs":"38450e5904f0825e0ec30056843ddfdcb3ed4e847666402b203600559a188333","mcp.cjs":"cab9765876232d6e868dadbbe85292060cb6c285eff99ebff7fb3976407dc621","transcript.cjs":"66c5a4e88578742964376410d72f4bc5006fad9e44a1e63c78edc21c4e2b1f29","upload.cjs":"20e68bc8bf02efd8b079899ff48772a8bda8e898dea49d94744f10a4beef58e5","compat.cjs":"36cd86982401bc6274fbea33772aa837498442215f9e2dbaa92e808960193fa3","outbox.cjs":"0befb8a890e2806422453f20545a4677045bd917e1c55dae252460673762c8f0","worker.cjs":"5bba7f2682c107d5b2f30d0dbe018ae878f7d341d643755f3639f15fb24dd80f","ordered-upload.cjs":"7327d2cf7811611e3c094363f279e1e1485a9e134e33fcee01f9a852bbf84b52","recovery.cjs":"d71bde0478699eef0df0e54f4eaeb81fba38627bcc7b013e3a39794bee36a926","migration.cjs":"1cd26b2ef709cae16e1ae00cd475a090378fd1d8ea5924da46f7cb4eaff13a32","sqlite3.cjs":"2834e6944034d788eb252f8b19d737fd994b9e87b30abb02a54bc687c819d7ae","node_sqlite3.node":"05df22ecef5dee67c66866f1b73ffb3e55fc433789d93b733f1b55671887d27b"}}