@agy-daddy/plugin-chat-nav 0.0.0-stage → 1.1.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.
@@ -0,0 +1,174 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const crypto = require('crypto');
7
+
8
+ const MAX_INLINE_FILE_BYTES = 2 * 1024 * 1024;
9
+ const MAX_BINARY_EXPORT_BYTES = 16 * 1024 * 1024;
10
+
11
+ function expandHomePath(rawPath) {
12
+ const s = String(rawPath || '').trim();
13
+ if (!s) return '';
14
+ if (s === '~') return os.homedir();
15
+ if (s.startsWith('~/') || s.startsWith('~\\')) {
16
+ return path.join(os.homedir(), s.slice(2));
17
+ }
18
+ return s;
19
+ }
20
+
21
+ const BLOCKED_PATH_PREFIXES = Object.freeze([
22
+ '/System',
23
+ '/usr',
24
+ '/bin',
25
+ '/sbin',
26
+ '/etc',
27
+ '/var',
28
+ '/private/etc',
29
+ '/Applications/Antigravity.app'
30
+ ]);
31
+
32
+ const SENSITIVE_PATH_REGEX = /[\\/](?:\.ssh|\.gnupg|\.aws|1Password)[\\/]/i;
33
+
34
+ function normalizeFilePathInput(rawPathOrUri) {
35
+ const s = String(rawPathOrUri || '').trim();
36
+ if (!s || s.includes('\0')) return null;
37
+
38
+ let decoded = s;
39
+ if (/^file:\/\//i.test(s)) {
40
+ if (/^file:\/\/\/?[A-Za-z]:[\\/]/i.test(s)) {
41
+ const stripped = s.replace(/^file:\/\/\/?/i, '');
42
+ try {
43
+ decoded = decodeURIComponent(stripped);
44
+ } catch {
45
+ decoded = stripped;
46
+ }
47
+ } else {
48
+ try {
49
+ decoded = decodeURIComponent(new URL(s).pathname);
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ }
55
+ if (!path.isAbsolute(decoded)) return null;
56
+ return path.resolve(decoded);
57
+ }
58
+
59
+ const ALLOWED_VAR_TEMP_PREFIXES = ['/var/folders/', '/private/var/folders/'];
60
+
61
+ function resolveSafeEditablePath(rawPathOrUri) {
62
+ const resolved = normalizeFilePathInput(rawPathOrUri);
63
+ if (!resolved) return null;
64
+ const slashed = resolved.replace(/\\/g, '/');
65
+ if (/^c:\/windows(?:\/|$)/i.test(slashed)) {
66
+ return null;
67
+ }
68
+ const posixPart = slashed.replace(/^[A-Za-z]:/, '');
69
+ const isMacUserTemp = ALLOWED_VAR_TEMP_PREFIXES.some((p) => slashed.startsWith(p));
70
+ for (const prefix of BLOCKED_PATH_PREFIXES) {
71
+ if (isMacUserTemp && prefix === '/var') continue;
72
+ for (const candidate of [slashed, posixPart]) {
73
+ if (candidate === prefix || candidate.startsWith(prefix + '/')) {
74
+ return null;
75
+ }
76
+ }
77
+ }
78
+ if (SENSITIVE_PATH_REGEX.test(resolved)) {
79
+ return null;
80
+ }
81
+ return resolved;
82
+ }
83
+
84
+ function readFileSafe(rawPathOrUri, options = {}) {
85
+ const maxBytes = Number(options.maxBytes) > 0 ? Number(options.maxBytes) : MAX_INLINE_FILE_BYTES;
86
+ const normalized = normalizeFilePathInput(rawPathOrUri);
87
+ if (!normalized) {
88
+ return { ok: false, error: '无效的文件路径(必须为绝对路径或 file:// URI)' };
89
+ }
90
+ const resolved = resolveSafeEditablePath(normalized);
91
+ if (!resolved) {
92
+ return { ok: false, error: '禁止访问受保护的系统或敏感凭据目录', path: normalized };
93
+ }
94
+ if (!fs.existsSync(resolved)) {
95
+ return { ok: false, error: '文件不存在', path: resolved };
96
+ }
97
+ const st = fs.statSync(resolved);
98
+ if (!st.isFile()) {
99
+ return { ok: false, error: '目标不是普通文件', path: resolved };
100
+ }
101
+ if (st.size > maxBytes) {
102
+ return { ok: false, error: `文件过大 (${st.size} bytes > ${maxBytes})`, path: resolved };
103
+ }
104
+ const content = fs.readFileSync(resolved, 'utf8');
105
+ return { ok: true, path: resolved, size: st.size, content };
106
+ }
107
+
108
+ function writeFileSafe(rawPathOrUri, content, options = {}) {
109
+ const maxBytes = Number(options.maxBytes) > 0 ? Number(options.maxBytes) : MAX_INLINE_FILE_BYTES;
110
+ const normalized = normalizeFilePathInput(rawPathOrUri);
111
+ if (!normalized) {
112
+ return { ok: false, error: '无效的文件路径(必须为绝对路径或 file:// URI)' };
113
+ }
114
+ const resolved = resolveSafeEditablePath(normalized);
115
+ if (!resolved) {
116
+ return { ok: false, error: '禁止写入受保护的系统或敏感凭据目录', path: normalized };
117
+ }
118
+ const text = String(content ?? '');
119
+ const bytes = Buffer.byteLength(text, 'utf8');
120
+ if (bytes > maxBytes) {
121
+ return { ok: false, error: `写入内容超限 (${bytes} bytes > ${maxBytes})`, path: resolved };
122
+ }
123
+
124
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
125
+ const tmpPath = path.join(path.dirname(resolved), `.${path.basename(resolved)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);
126
+ try {
127
+ fs.writeFileSync(tmpPath, text, 'utf8');
128
+ fs.renameSync(tmpPath, resolved);
129
+ return { ok: true, path: resolved, bytesWritten: bytes };
130
+ } catch (err) {
131
+ try { if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath); } catch {}
132
+ return { ok: false, error: err?.message || '写入失败', path: resolved };
133
+ }
134
+ }
135
+
136
+ function writeBinaryFileSafe(rawPathOrUri, buffer, options = {}) {
137
+ const maxBytes = Number(options.maxBytes) > 0 ? Number(options.maxBytes) : MAX_BINARY_EXPORT_BYTES;
138
+ const normalized = normalizeFilePathInput(expandHomePath(rawPathOrUri));
139
+ if (!normalized) {
140
+ return { ok: false, error: '无效的文件路径(必须为绝对路径或 file:// URI)' };
141
+ }
142
+ const resolved = resolveSafeEditablePath(normalized);
143
+ if (!resolved) {
144
+ return { ok: false, error: '禁止写入受保护的系统或敏感凭据目录', path: normalized };
145
+ }
146
+ const buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer || '');
147
+ if (buf.length > maxBytes) {
148
+ return { ok: false, error: `写入内容超限 (${buf.length} bytes > ${maxBytes})`, path: resolved };
149
+ }
150
+
151
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
152
+ const tmpPath = path.join(path.dirname(resolved), `.${path.basename(resolved)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);
153
+ try {
154
+ fs.writeFileSync(tmpPath, buf);
155
+ fs.renameSync(tmpPath, resolved);
156
+ return { ok: true, path: resolved, bytesWritten: buf.length };
157
+ } catch (err) {
158
+ try { if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath); } catch {}
159
+ return { ok: false, error: err?.message || '写入失败', path: resolved };
160
+ }
161
+ }
162
+
163
+ module.exports = {
164
+ MAX_INLINE_FILE_BYTES,
165
+ MAX_BINARY_EXPORT_BYTES,
166
+ BLOCKED_PATH_PREFIXES,
167
+ SENSITIVE_PATH_REGEX,
168
+ expandHomePath,
169
+ normalizeFilePathInput,
170
+ resolveSafeEditablePath,
171
+ readFileSafe,
172
+ writeFileSafe,
173
+ writeBinaryFileSafe
174
+ };
package/src/node.js ADDED
@@ -0,0 +1,465 @@
1
+ 'use strict';
2
+
3
+ const os = require('os');
4
+ const path = require('path');
5
+ const { readFileSafe, writeFileSafe, writeBinaryFileSafe, expandHomePath } = require('./file-service');
6
+ const {
7
+ normalizeExportFormat,
8
+ normalizeExportFormats,
9
+ getDefaultBrainDir,
10
+ listBrainSessions,
11
+ pickLatestCascadeId,
12
+ buildExportFilename,
13
+ normalizeDomMessagesToSteps,
14
+ exportConversationMarkdown,
15
+ exportConversationHtml,
16
+ renderHtmlToPdfBuffer,
17
+ openSaveFileDialog,
18
+ openDirectoryDialog
19
+ } = require('./conversation-export');
20
+
21
+ const DEFAULT_SETTINGS = Object.freeze({
22
+ showFloatDock: true,
23
+ keepThinkingExpanded: false,
24
+ enableInlineFileEditor: true,
25
+ enableCmdClickLinks: true,
26
+ searchRegexMode: false,
27
+ searchCaseSensitive: false,
28
+ exportSaveBehavior: 'dialog',
29
+ exportSaveDir: '',
30
+ exportFormats: ['md']
31
+ });
32
+
33
+ let disposers = [];
34
+
35
+ function matchMessages(messages = [], query = '', options = {}) {
36
+ const q = String(query || '').trim();
37
+ if (!q) return { ok: true, matches: [], total: 0 };
38
+ let matcher = null;
39
+ if (options.regexMode) {
40
+ try {
41
+ matcher = new RegExp(q, options.caseSensitive ? '' : 'i');
42
+ } catch (err) {
43
+ return { ok: false, error: `INVALID_REGEX: ${err.message}`, matches: [], total: 0 };
44
+ }
45
+ }
46
+ const needle = options.caseSensitive ? q : q.toLowerCase();
47
+ const matches = [];
48
+ for (let i = 0; i < (Array.isArray(messages) ? messages.length : 0); i++) {
49
+ const text = String(messages[i] ?? '');
50
+ const hit = matcher ? matcher.test(text) : (options.caseSensitive ? text.includes(needle) : text.toLowerCase().includes(needle));
51
+ if (hit) matches.push({ index: i, preview: text.slice(0, 120) });
52
+ }
53
+ return { ok: true, matches, total: matches.length };
54
+ }
55
+
56
+ async function activate(host) {
57
+ function readSettings() {
58
+ const merged = {
59
+ ...DEFAULT_SETTINGS,
60
+ ...(host.settings?.get?.() || {})
61
+ };
62
+ merged.exportSaveBehavior = merged.exportSaveBehavior === 'direct' ? 'direct' : 'dialog';
63
+ merged.exportSaveDir = typeof merged.exportSaveDir === 'string' ? merged.exportSaveDir.trim() : '';
64
+ merged.exportFormats = normalizeExportFormats(merged.exportFormats);
65
+ return merged;
66
+ }
67
+
68
+ function resolveDefaultExportDir(overrideDir, currentSettings) {
69
+ const raw = String(overrideDir || currentSettings?.exportSaveDir || process.env.AGY_DADDY_EXPORT_DIR || '').trim();
70
+ const expanded = raw ? expandHomePath(raw) : '';
71
+ return expanded ? path.resolve(expanded) : path.join(os.homedir(), 'Downloads');
72
+ }
73
+
74
+ let settings = readSettings();
75
+
76
+ const stopSettings = host.settings?.onChange?.((nextValues) => {
77
+ settings = {
78
+ ...DEFAULT_SETTINGS,
79
+ ...(nextValues || {}),
80
+ exportSaveBehavior: nextValues?.exportSaveBehavior === 'direct' ? 'direct' : 'dialog',
81
+ exportSaveDir: typeof nextValues?.exportSaveDir === 'string' ? nextValues.exportSaveDir.trim() : '',
82
+ exportFormats: normalizeExportFormats(nextValues?.exportFormats)
83
+ };
84
+ });
85
+
86
+ const stopReadRoute = await host.bridge.registerRoute('/file/read', async (body) => {
87
+ return readFileSafe(body?.path || body?.uri);
88
+ });
89
+ const stopWriteRoute = await host.bridge.registerRoute('/file/write', async (body) => {
90
+ return writeFileSafe(body?.path || body?.uri, body?.content);
91
+ });
92
+
93
+ async function resolveConversationData(opts = {}) {
94
+ let cascadeId = typeof opts.cascadeId === 'string' ? opts.cascadeId.trim() : '';
95
+ let steps = Array.isArray(opts.steps) ? opts.steps : null;
96
+ if (!cascadeId && !steps) {
97
+ const resolved = await serviceMethods.getActiveSessionId(opts);
98
+ if (resolved?.ok && resolved.cascadeId) {
99
+ cascadeId = resolved.cascadeId;
100
+ }
101
+ }
102
+ if (!steps && cascadeId) {
103
+ try {
104
+ const resp = await host.rpc.call('GetCascadeTrajectory', { cascadeId });
105
+ steps = resp?.steps || resp?.trajectory?.steps || [];
106
+ } catch {
107
+ steps = [];
108
+ }
109
+ }
110
+ if ((!Array.isArray(steps) || steps.length === 0) && Array.isArray(opts.domMessages) && opts.domMessages.length > 0) {
111
+ steps = normalizeDomMessagesToSteps(opts.domMessages);
112
+ }
113
+ return { cascadeId, steps: steps || [] };
114
+ }
115
+
116
+ function resolveSaveBehavior(opts = {}) {
117
+ if (opts.saveBehavior === 'dialog' || opts.saveBehavior === 'direct' || opts.saveBehavior === 'none') {
118
+ return opts.saveBehavior;
119
+ }
120
+ if (opts.saveToDisk === true || Boolean(opts.outputDir)) {
121
+ return 'direct';
122
+ }
123
+ return 'none';
124
+ }
125
+
126
+ async function writeFormattedExport({ format, targetPath, markdown, html, meta, opts = {} }) {
127
+ if (format === 'pdf') {
128
+ const pdfBuf = await renderHtmlToPdfBuffer(html, {
129
+ plainText: markdown,
130
+ meta,
131
+ pdfRenderer: opts.pdfRenderer,
132
+ chromeBin: opts.chromeBin
133
+ });
134
+ return writeBinaryFileSafe(targetPath, pdfBuf, { maxBytes: 16 * 1024 * 1024 });
135
+ }
136
+ const payload = format === 'html' ? html : markdown;
137
+ return writeFileSafe(targetPath, payload, { maxBytes: 16 * 1024 * 1024 });
138
+ }
139
+
140
+ const serviceMethods = {
141
+ async getActiveSessionId(opts = {}) {
142
+ const explicit = typeof opts.cascadeId === 'string' ? opts.cascadeId.trim() : '';
143
+ if (explicit) {
144
+ return { ok: true, cascadeId: explicit, source: 'explicit' };
145
+ }
146
+ let summary = null;
147
+ try {
148
+ const allResp = await host.rpc.call('GetAllCascadeTrajectories', {
149
+ metadata: { ideName: 'antigravity', extensionName: 'antigravity' }
150
+ });
151
+ const summaries = allResp?.trajectorySummaries || {};
152
+ const picked = pickLatestCascadeId(summaries);
153
+ if (picked) {
154
+ summary = summaries[picked] || null;
155
+ return { ok: true, cascadeId: picked, source: 'rpc', summary };
156
+ }
157
+ } catch {}
158
+
159
+ try {
160
+ const sessions = listBrainSessions(opts);
161
+ if (sessions.length > 0 && sessions[0].id) {
162
+ return { ok: true, cascadeId: sessions[0].id, source: 'brain' };
163
+ }
164
+ } catch {}
165
+
166
+ return { ok: false, cascadeId: null, error: 'NO_SESSION_ID' };
167
+ },
168
+ listBrainSessions(opts = {}) {
169
+ return listBrainSessions(opts);
170
+ },
171
+ async exportConversation(opts = {}) {
172
+ const current = readSettings();
173
+ const format = normalizeExportFormat(opts.format || 'md');
174
+ const { cascadeId, steps } = await resolveConversationData(opts);
175
+ const saveBehavior = resolveSaveBehavior(opts);
176
+
177
+ const defaultDir = resolveDefaultExportDir(opts.outputDir, current);
178
+ const defaultName = buildExportFilename({ title: opts.title, cascadeId, format });
179
+ let targetPath = '';
180
+
181
+ if (saveBehavior === 'dialog') {
182
+ const dlg = await openSaveFileDialog({
183
+ defaultDir,
184
+ defaultName,
185
+ format,
186
+ title: opts.dialogTitle,
187
+ saveDialogFn: opts.saveDialogFn
188
+ });
189
+ if (dlg && dlg.ok === false) {
190
+ return {
191
+ ok: false,
192
+ cancelled: false,
193
+ format,
194
+ saveBehavior,
195
+ cascadeId: cascadeId || null,
196
+ filePath: null,
197
+ error: dlg.error || '无法打开保存对话框'
198
+ };
199
+ }
200
+ if (!dlg || dlg.cancelled || !dlg.path) {
201
+ return {
202
+ ok: true,
203
+ cancelled: true,
204
+ format,
205
+ saveBehavior,
206
+ cascadeId: cascadeId || null,
207
+ filePath: null
208
+ };
209
+ }
210
+ targetPath = dlg.path;
211
+ } else if (saveBehavior === 'direct') {
212
+ targetPath = path.join(defaultDir, defaultName);
213
+ }
214
+
215
+ const meta = { ...opts, cascadeId };
216
+ const markdown = exportConversationMarkdown(steps, meta);
217
+ const result = {
218
+ ok: true,
219
+ cancelled: false,
220
+ format,
221
+ saveBehavior,
222
+ cascadeId: cascadeId || null,
223
+ markdown
224
+ };
225
+
226
+ if (format === 'html' || format === 'pdf') {
227
+ result.html = exportConversationHtml(steps, format === 'pdf' ? { ...meta, expandThinking: true } : meta);
228
+ }
229
+
230
+ if (targetPath) {
231
+ const writeRes = await writeFormattedExport({
232
+ format,
233
+ targetPath,
234
+ markdown,
235
+ html: result.html,
236
+ meta,
237
+ opts
238
+ });
239
+ result.filePath = writeRes.ok ? writeRes.path : null;
240
+ result.bytesWritten = writeRes.ok ? writeRes.bytesWritten : 0;
241
+ if (!writeRes.ok) {
242
+ result.saveError = writeRes.error;
243
+ if (format === 'pdf') {
244
+ result.ok = false;
245
+ result.error = writeRes.error;
246
+ }
247
+ }
248
+ }
249
+
250
+ return result;
251
+ },
252
+ async exportConversationBatch(opts = {}) {
253
+ const current = readSettings();
254
+ const formats = normalizeExportFormats(opts.formats || current.exportFormats);
255
+ const { cascadeId, steps } = await resolveConversationData(opts);
256
+ const saveBehavior = resolveSaveBehavior(opts);
257
+ const defaultDir = resolveDefaultExportDir(opts.outputDir, current);
258
+ const exportDate = opts.date instanceof Date ? opts.date : new Date();
259
+
260
+ let targetDir = '';
261
+ if (saveBehavior === 'dialog') {
262
+ const dlg = await openDirectoryDialog({
263
+ defaultDir,
264
+ title: opts.dialogTitle || '选择全部导出的保存文件夹',
265
+ dirPickerFn: opts.dirPickerFn
266
+ });
267
+ if (dlg && dlg.ok === false) {
268
+ return {
269
+ ok: false,
270
+ cancelled: false,
271
+ formats,
272
+ saveBehavior,
273
+ cascadeId: cascadeId || null,
274
+ targetDir: null,
275
+ results: [],
276
+ succeeded: [],
277
+ failed: [],
278
+ error: dlg.error || '无法打开文件夹选择对话框'
279
+ };
280
+ }
281
+ if (!dlg || dlg.cancelled || !dlg.path) {
282
+ return {
283
+ ok: true,
284
+ cancelled: true,
285
+ formats,
286
+ saveBehavior,
287
+ cascadeId: cascadeId || null,
288
+ targetDir: null,
289
+ results: [],
290
+ succeeded: [],
291
+ failed: []
292
+ };
293
+ }
294
+ targetDir = dlg.path;
295
+ } else if (saveBehavior === 'direct') {
296
+ targetDir = defaultDir;
297
+ }
298
+
299
+ const meta = { ...opts, cascadeId, date: exportDate };
300
+ const markdown = exportConversationMarkdown(steps, meta);
301
+ const html = formats.includes('html') ? exportConversationHtml(steps, meta) : undefined;
302
+ const pdfHtml = formats.includes('pdf') ? exportConversationHtml(steps, { ...meta, expandThinking: true }) : undefined;
303
+
304
+ const results = [];
305
+ const succeeded = [];
306
+ const failed = [];
307
+
308
+ if (targetDir) {
309
+ for (const fmt of formats) {
310
+ const fileName = buildExportFilename({ title: opts.title, cascadeId, format: fmt, date: exportDate });
311
+ const targetPath = path.join(targetDir, fileName);
312
+ try {
313
+ const writeRes = await writeFormattedExport({
314
+ format: fmt,
315
+ targetPath,
316
+ markdown,
317
+ html: fmt === 'pdf' ? pdfHtml : html,
318
+ meta,
319
+ opts
320
+ });
321
+ if (writeRes.ok) {
322
+ const item = { format: fmt, ok: true, filePath: writeRes.path, bytesWritten: writeRes.bytesWritten };
323
+ results.push(item);
324
+ succeeded.push(item);
325
+ } else {
326
+ const item = { format: fmt, ok: false, filePath: null, bytesWritten: 0, error: writeRes.error || '写入失败' };
327
+ results.push(item);
328
+ failed.push(item);
329
+ }
330
+ } catch (err) {
331
+ const item = { format: fmt, ok: false, filePath: null, bytesWritten: 0, error: err?.message || '导出失败' };
332
+ results.push(item);
333
+ failed.push(item);
334
+ }
335
+ }
336
+ }
337
+
338
+ const partial = succeeded.length > 0 && failed.length > 0;
339
+ const ok = saveBehavior === 'none' ? true : succeeded.length > 0;
340
+ const error = failed.length > 0
341
+ ? failed.map((f) => `${f.format.toUpperCase()}: ${f.error}`).join(';')
342
+ : undefined;
343
+
344
+ return {
345
+ ok,
346
+ partial,
347
+ cancelled: false,
348
+ formats,
349
+ saveBehavior,
350
+ cascadeId: cascadeId || null,
351
+ targetDir: targetDir || null,
352
+ results,
353
+ succeeded,
354
+ failed,
355
+ markdown,
356
+ ...(html !== undefined ? { html } : {}),
357
+ ...(error ? { error } : {})
358
+ };
359
+ },
360
+ async exportMarkdown(opts = {}) {
361
+ return serviceMethods.exportConversation({ ...opts, format: opts.format || 'md' });
362
+ },
363
+ async browseExportDir(opts = {}) {
364
+ const current = readSettings();
365
+ const valDir = typeof opts?.values?.exportSaveDir === 'string' ? opts.values.exportSaveDir.trim() : '';
366
+ const defaultDir = resolveDefaultExportDir(opts.defaultDir || valDir, current);
367
+ return openDirectoryDialog({
368
+ defaultDir,
369
+ title: opts.title || '选择默认导出保存文件夹',
370
+ dirPickerFn: opts.dirPickerFn
371
+ });
372
+ }
373
+ };
374
+
375
+ const stopSvc = await host.services.provide('chat-nav-node', serviceMethods, { realm: 'node', version: '1.0.0' });
376
+ const stopSessionRoute = await host.bridge.registerRoute('/session-id', async (body) => serviceMethods.getActiveSessionId(body || {}));
377
+ const stopBrainRoute = await host.bridge.registerRoute('/brain-sessions', async (body) => serviceMethods.listBrainSessions(body || {}));
378
+ const stopExportMdRoute = await host.bridge.registerRoute('/export-md', async (body) => serviceMethods.exportConversation(body || {}), { timeoutMs: 120000 });
379
+ const stopExportRoute = await host.bridge.registerRoute('/export', async (body) => serviceMethods.exportConversation(body || {}), { timeoutMs: 120000 });
380
+ const stopExportAllRoute = await host.bridge.registerRoute('/export-all', async (body) => serviceMethods.exportConversationBatch(body || {}), { timeoutMs: 120000 });
381
+
382
+ const stopCmdTop = await host.commands.register('chat-nav.scroll-top', () => {
383
+ host.events.emit('chat-nav:command@1', { command: 'scroll-top' });
384
+ return { ok: true, command: 'chat-nav.scroll-top', action: 'scrollTop', settings: { ...settings } };
385
+ });
386
+ const stopCmdBottom = await host.commands.register('chat-nav.scroll-bottom', () => {
387
+ host.events.emit('chat-nav:command@1', { command: 'scroll-bottom' });
388
+ return { ok: true, command: 'chat-nav.scroll-bottom', action: 'scrollBottom', settings: { ...settings } };
389
+ });
390
+ const stopCmdExpand = await host.commands.register('chat-nav.expand-thinking', () => {
391
+ host.events.emit('chat-nav:command@1', { command: 'expand-thinking' });
392
+ return { ok: true, command: 'chat-nav.expand-thinking', action: 'expandThinking', settings: { ...settings } };
393
+ });
394
+ const stopCmdSearch = await host.commands.register('chat-nav.search', (query = '', messages = [], opts = {}) => {
395
+ const current = readSettings();
396
+ const merged = {
397
+ regexMode: current.searchRegexMode,
398
+ caseSensitive: current.searchCaseSensitive,
399
+ ...opts
400
+ };
401
+ const res = matchMessages(messages, query, merged);
402
+ host.state?.set?.('state:chat-nav.search@1', {
403
+ query: String(query || ''),
404
+ total: res.total,
405
+ regexMode: Boolean(merged.regexMode)
406
+ });
407
+ return res;
408
+ });
409
+ const stopCmdCopyId = await host.commands.register('chat-nav.copy-id', async (opts = {}) => {
410
+ const res = await serviceMethods.getActiveSessionId(opts || {});
411
+ const cascadeId = res?.cascadeId || null;
412
+ host.events.emit('chat-nav:command@1', { command: 'copy-id', cascadeId });
413
+ return { ok: Boolean(cascadeId), command: 'chat-nav.copy-id', cascadeId };
414
+ });
415
+ const stopCmdExportMd = await host.commands.register('chat-nav.export-md', async (opts = {}) => {
416
+ return serviceMethods.exportMarkdown(opts || {});
417
+ });
418
+ const stopCmdExport = await host.commands.register('chat-nav.export', async (opts = {}) => {
419
+ return serviceMethods.exportConversation(opts || {});
420
+ });
421
+ const stopCmdExportAll = await host.commands.register('chat-nav.export-all', async (opts = {}) => {
422
+ return serviceMethods.exportConversationBatch(opts || {});
423
+ });
424
+ const stopCmdBrowseDir = await host.commands.register('chat-nav.browseExportDir', async (opts = {}) => {
425
+ return serviceMethods.browseExportDir(opts || {});
426
+ });
427
+
428
+ disposers.push(
429
+ stopSettings,
430
+ stopReadRoute,
431
+ stopWriteRoute,
432
+ stopSvc,
433
+ stopSessionRoute,
434
+ stopBrainRoute,
435
+ stopExportMdRoute,
436
+ stopExportRoute,
437
+ stopExportAllRoute,
438
+ stopCmdTop,
439
+ stopCmdBottom,
440
+ stopCmdExpand,
441
+ stopCmdSearch,
442
+ stopCmdCopyId,
443
+ stopCmdExportMd,
444
+ stopCmdExport,
445
+ stopCmdExportAll,
446
+ stopCmdBrowseDir
447
+ );
448
+ }
449
+
450
+ async function deactivate() {
451
+ for (const fn of disposers) {
452
+ try { if (typeof fn === 'function') fn(); } catch {}
453
+ }
454
+ disposers = [];
455
+ }
456
+
457
+ module.exports = {
458
+ matchMessages,
459
+ getDefaultBrainDir,
460
+ listBrainSessions,
461
+ exportConversationMarkdown,
462
+ exportConversationHtml,
463
+ activate,
464
+ deactivate
465
+ };