codexmate 0.1.31 → 0.1.33

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 (92) hide show
  1. package/README.md +8 -3
  2. package/README.vi.md +8 -3
  3. package/README.zh.md +8 -3
  4. package/cli/agents-files.js +18 -4
  5. package/cli/claude-proxy.js +2 -2
  6. package/cli/plugin-config.js +64 -0
  7. package/cli/prompt-history.js +19 -4
  8. package/cli/system-prompt-files.js +7 -2
  9. package/cli.js +200 -214
  10. package/lib/cli-config-engine.js +15 -4
  11. package/lib/cli-file-utils.js +6 -1
  12. package/lib/config-change-fs.js +132 -0
  13. package/lib/config-changes.js +293 -0
  14. package/lib/handoff-mcp.js +18 -2
  15. package/lib/local-feature-store.js +39 -0
  16. package/lib/session-bookmarks.js +72 -0
  17. package/lib/session-context-health.js +102 -0
  18. package/lib/session-context-records.js +153 -0
  19. package/lib/session-diagnostics.js +75 -0
  20. package/lib/session-feature-settings.js +21 -0
  21. package/lib/session-features.js +63 -0
  22. package/lib/session-handoff-draft.js +43 -0
  23. package/lib/session-projects.js +76 -0
  24. package/lib/session-search-index.js +188 -0
  25. package/lib/thread-handoff.js +8 -0
  26. package/lib/web-server.js +216 -0
  27. package/lib/web-startup-auth.js +5 -1
  28. package/package.json +1 -1
  29. package/plugins/prompt-templates/computed.mjs +3 -3
  30. package/plugins/prompt-templates/invocation.mjs +73 -0
  31. package/plugins/prompt-templates/methods.mjs +48 -3
  32. package/plugins/prompt-templates/overview.mjs +2 -0
  33. package/web-ui/app.js +32 -1
  34. package/web-ui/index.html +2 -0
  35. package/web-ui/logic.context-health.mjs +144 -0
  36. package/web-ui/logic.context-window.mjs +15 -0
  37. package/web-ui/modules/api.mjs +72 -39
  38. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  39. package/web-ui/modules/app.methods.agents.mjs +25 -3
  40. package/web-ui/modules/app.methods.claude-config.mjs +2 -0
  41. package/web-ui/modules/app.methods.codex-config.mjs +9 -0
  42. package/web-ui/modules/app.methods.config-changes.mjs +124 -0
  43. package/web-ui/modules/app.methods.index.mjs +4 -0
  44. package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
  45. package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
  46. package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
  47. package/web-ui/modules/app.methods.pi-config.mjs +12 -3
  48. package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
  49. package/web-ui/modules/app.methods.providers.mjs +6 -0
  50. package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
  51. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  52. package/web-ui/modules/config-change-actions.mjs +9 -0
  53. package/web-ui/modules/context-health.methods.mjs +70 -0
  54. package/web-ui/modules/i18n/locales/en.mjs +164 -4
  55. package/web-ui/modules/i18n/locales/ja.mjs +164 -4
  56. package/web-ui/modules/i18n/locales/vi.mjs +164 -4
  57. package/web-ui/modules/i18n/locales/zh-tw.mjs +164 -4
  58. package/web-ui/modules/i18n/locales/zh.mjs +164 -4
  59. package/web-ui/modules/plugins.methods.mjs +2 -0
  60. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  61. package/web-ui/modules/request-deadline.mjs +33 -0
  62. package/web-ui/modules/session-features.mjs +279 -0
  63. package/web-ui/modules/thread-handoff.mjs +1 -1
  64. package/web-ui/partials/index/config-changes.html +25 -0
  65. package/web-ui/partials/index/context-health.html +45 -0
  66. package/web-ui/partials/index/context-window-reference.html +17 -0
  67. package/web-ui/partials/index/layout-header.html +7 -30
  68. package/web-ui/partials/index/modal-openclaw-config.html +0 -2
  69. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  70. package/web-ui/partials/index/modal-skills.html +0 -1
  71. package/web-ui/partials/index/modals-basic.html +0 -8
  72. package/web-ui/partials/index/modals-pi-provider.html +0 -1
  73. package/web-ui/partials/index/panel-config-codex.html +0 -3
  74. package/web-ui/partials/index/panel-config-openclaw.html +16 -13
  75. package/web-ui/partials/index/panel-dashboard.html +0 -2
  76. package/web-ui/partials/index/panel-plugins.html +37 -10
  77. package/web-ui/partials/index/panel-prompts.html +18 -3
  78. package/web-ui/partials/index/panel-sessions.html +23 -11
  79. package/web-ui/partials/index/panel-settings.html +1 -12
  80. package/web-ui/partials/index/panel-trash.html +0 -1
  81. package/web-ui/partials/index/session-diagnostics.html +29 -0
  82. package/web-ui/partials/index/session-features.html +107 -0
  83. package/web-ui/partials/index/thread-handoff.html +6 -3
  84. package/web-ui/res/web-ui-render.precompiled.js +1863 -271
  85. package/web-ui/styles/config-changes.css +30 -0
  86. package/web-ui/styles/context-health.css +107 -0
  87. package/web-ui/styles/openclaw-structured.css +205 -189
  88. package/web-ui/styles/prompts-editor.css +23 -0
  89. package/web-ui/styles/session-features.css +148 -0
  90. package/web-ui/styles/sessions-preview.css +21 -0
  91. package/web-ui/styles/sub-tabs.css +181 -0
  92. package/web-ui/styles.css +5 -1
@@ -0,0 +1,102 @@
1
+ 'use strict';
2
+
3
+ const readline = require('readline');
4
+ const { createContextRecordReader } = require('./session-context-records');
5
+ const RULE_FIELDS = ['system_prompt', 'systemInstruction', 'instructions', 'project_rules', 'skills_instructions'];
6
+
7
+ function createSessionContextHealthController(deps) {
8
+ const { fs, normalizeSessionSourceName, resolveSessionFilePath, queryOpencodeSessionMessages, queryZedSessionMessages } = deps;
9
+ async function* records(source, filePath, sessionId) {
10
+ if (source === 'opencode' || source === 'zed') {
11
+ const query = source === 'zed' ? queryZedSessionMessages : queryOpencodeSessionMessages;
12
+ const data = query(sessionId, { maxMessages: Infinity, contextHealth: true });
13
+ if (!data) throw new Error('会话数据库读取失败');
14
+ if (data.cwd) yield { type: 'session_meta', payload: { cwd: data.cwd } };
15
+ if (data.instructions) yield { type: 'system_context', instructions: data.instructions };
16
+ for (const message of data.messages || []) yield message;
17
+ return;
18
+ }
19
+ if (source === 'gemini' || filePath.toLowerCase().endsWith('.json')) {
20
+ const data = JSON.parse(await fs.promises.readFile(filePath, 'utf8'));
21
+ const cwd = data.projectRoot || data.cwd;
22
+ if (cwd) yield { type: 'session_meta', payload: { cwd } };
23
+ for (const field of RULE_FIELDS) {
24
+ if (data[field]) yield { type: 'system_context', instructions: data[field] };
25
+ }
26
+ const messages = Array.isArray(data) ? data : (data.messages || data.children || []);
27
+ for (const message of messages) yield message;
28
+ return;
29
+ }
30
+ const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
31
+ const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
32
+ let readError;
33
+ stream.on('error', (error) => { readError = error; lines.close(); });
34
+ try {
35
+ for await (const line of lines) {
36
+ if (!line.trim()) { yield null; continue; }
37
+ try { yield JSON.parse(line.charCodeAt(0) === 0xFEFF ? line.slice(1) : line); }
38
+ catch (_) { throw new Error('会话含无法解析的消息记录'); }
39
+ }
40
+ if (readError) throw readError;
41
+ } finally { lines.close(); stream.destroy(); }
42
+ }
43
+ function resolve(params) {
44
+ const source = normalizeSessionSourceName(params.source, '');
45
+ if (!source) throw new Error('Invalid source');
46
+ const filePath = resolveSessionFilePath(source, params.filePath || params.file, params.sessionId);
47
+ if (!filePath) throw new Error('Session file not found');
48
+ return { source, filePath, sessionId: params.sessionId };
49
+ }
50
+ async function scan(params, focus) {
51
+ const target = resolve(params);
52
+ const { createContextAnalyzer } = await import('../web-ui/logic.context-health.mjs');
53
+ const analyzer = createContextAnalyzer();
54
+ const reader = createContextRecordReader(target.source, params.cwd || '');
55
+ let index = 0;
56
+ const models = new Set();
57
+ const modelWindows = {};
58
+ for await (const record of records(target.source, target.filePath, target.sessionId)) {
59
+ const metadata = record?.payload || record?.message || record || {};
60
+ const model = metadata.model || metadata.modelID || metadata.info?.modelID;
61
+ const window = metadata.model_context_window ?? metadata.context_window ?? metadata.contextWindow;
62
+ if (typeof model === 'string' && model) {
63
+ models.add(model);
64
+ if (Number.isSafeInteger(window) && window > 0) modelWindows[model] = window;
65
+ }
66
+ for (const node of reader(record, index)) {
67
+ if (!focus) analyzer.add(node);
68
+ if (node.id === focus) {
69
+ return { source: target.source, node: { id: node.id, role: node.role,
70
+ recordLineIndex: node.recordLineIndex, messageIndex: node.messageIndex,
71
+ text: node.parts.map((part) => part.text).join('\n'), readPaths: node.readPaths || [] } };
72
+ }
73
+ }
74
+ index++;
75
+ }
76
+ if (focus) throw new Error('消息节点不存在,请刷新体检结果');
77
+ return { source: target.source, sessionId: target.sessionId, complete: true, scannedRecords: index, models: [...models], modelWindows, ...analyzer.finish() };
78
+ }
79
+ async function readSessionContextHealth(params = {}) {
80
+ try { return await scan(params); } catch (error) { return { error: error.message }; }
81
+ }
82
+ async function readSessionContextNode(params = {}) {
83
+ if (typeof params.nodeId !== 'string' || !/^record-\d+(?:\.(?:body-)?(?:children|messages|branches)-\d+)*$/.test(params.nodeId)) {
84
+ return { error: '消息节点 ID 无效' };
85
+ }
86
+ try { return await scan(params, params.nodeId); } catch (error) { return { error: error.message }; }
87
+ }
88
+ async function* iterateSessionContextNodes(params = {}) {
89
+ const target = resolve(params);
90
+ const reader = createContextRecordReader(target.source, params.cwd || '');
91
+ let index = 0;
92
+ for await (const record of records(target.source, target.filePath, target.sessionId)) {
93
+ for (const node of reader(record, index)) yield { ...node,
94
+ text: node.parts.map((part) => part.text).join('\n'),
95
+ timestamp: record?.timestamp || record?.message?.timestamp || '' };
96
+ index++;
97
+ }
98
+ }
99
+ return { readSessionContextHealth, readSessionContextNode, iterateSessionContextNodes };
100
+ }
101
+
102
+ module.exports = { createSessionContextHealthController };
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+
3
+ const ROLE_CATEGORIES = { system: 'system', developer: 'system', skill: 'system', rules: 'system', user: 'user', human: 'user',
4
+ assistant: 'assistant', agent: 'assistant', model: 'assistant', gemini: 'assistant',
5
+ tool: 'tools', toolresult: 'tools', tool_result: 'tools', function_call_output: 'tools' };
6
+ const RULE_FIELDS = ['base_instructions', 'developer_instructions', 'system_prompt', 'systemInstruction', 'instructions', 'project_rules', 'skills_instructions'];
7
+
8
+ function categoryForRole(role) {
9
+ const key = String(role || '').toLowerCase();
10
+ return Object.prototype.hasOwnProperty.call(ROLE_CATEGORIES, key) ? ROLE_CATEGORIES[key] : '';
11
+ }
12
+
13
+ function contentParts(content, category) {
14
+ const parts = [];
15
+ const queue = [{ value: content, category }];
16
+ while (queue.length) {
17
+ const item = queue.pop();
18
+ const value = item.value;
19
+ if (typeof value === 'string') {
20
+ if (value) parts.push({ text: value, category: item.category });
21
+ continue;
22
+ }
23
+ if (!value || typeof value !== 'object') continue;
24
+ if (Array.isArray(value)) {
25
+ for (let index = value.length - 1; index >= 0; index--) queue.push({ value: value[index], category: item.category });
26
+ continue;
27
+ }
28
+ const type = String(value.type || '').toLowerCase();
29
+ const nextCategory = /^(code|diff)$/.test(type) || value.Code ? 'code'
30
+ : (/^(tool|tool_result|toolresult|function_call_output)$/.test(type) || value.ToolResult ? 'tools' : item.category);
31
+ const text = value.Text ?? value.text ?? value.thinking ?? value.Thinking ?? value.Code
32
+ ?? value.ToolResult ?? value.content ?? value.output ?? value.code ?? value.diff ?? value.value ?? value.summary ?? value.parts;
33
+ if (value.state && (value.state.output !== undefined || value.state.error !== undefined)) {
34
+ const output = value.state.output ?? value.state.error;
35
+ queue.push({ value: typeof output === 'object' ? JSON.stringify(output) : output, category: 'tools' });
36
+ } else if (/^(toolcall|tool_use)$/.test(type)) {
37
+ queue.push({ value: `${value.name || ''}\n${JSON.stringify(value.arguments || value.input || {})}`, category: 'assistant' });
38
+ } else if (text !== undefined) queue.push({ value: text, category: nextCategory });
39
+ }
40
+ return parts;
41
+ }
42
+
43
+ function normalizeReadPath(value, cwd) {
44
+ if (typeof value !== 'string' || !value.trim() || /^https?:\/\//i.test(value)) return '';
45
+ const raw = value.trim().replace(/\\/g, '/');
46
+ const full = raw.startsWith('/') || /^[A-Za-z]:\//.test(raw) ? raw : `${cwd || ''}/${raw}`;
47
+ const parts = [];
48
+ for (const part of full.split('/')) {
49
+ if (!part || part === '.') continue;
50
+ if (part === '..') parts.pop(); else parts.push(part);
51
+ }
52
+ return `${full.startsWith('/') ? '/' : ''}${parts.join('/')}`;
53
+ }
54
+
55
+ function readPaths(name, input, cwd) {
56
+ let args = input;
57
+ if (typeof input === 'string') { try { args = JSON.parse(input); } catch (_) { args = {}; } }
58
+ if (!args || typeof args !== 'object') return [];
59
+ const command = args.cmd || args.command || '';
60
+ const isRead = /read|cat|grep|get.content|open.file/i.test(name || '') || /(?:^|[\s;&|])(cat|sed|head|tail|rg|grep|Get-Content)\s/.test(command);
61
+ if (!isRead) return [];
62
+ const paths = [args.path, args.file_path, args.filePath, args.file, args.filename].filter((value) => typeof value === 'string');
63
+ if (!paths.length && command) {
64
+ const match = command.match(/(?:^|[;&|]\s*)(?:cat|sed|head|tail|rg|grep|Get-Content)\s+([^;&|]+)/);
65
+ const tokens = match ? match[1].match(/"[^"]+"|'[^']+'|\S+/g) || [] : [];
66
+ for (const token of tokens) {
67
+ const value = token.replace(/^['"]|['"]$/g, '');
68
+ if (!value.startsWith('-') && !/^\d+(?:,\d+)?[a-z]$/i.test(value)
69
+ && (value.includes('/') || /\.[A-Za-z0-9]+$/.test(value))) paths.push(value);
70
+ }
71
+ }
72
+ return paths.map((value) => normalizeReadPath(value, cwd)).filter(Boolean);
73
+ }
74
+
75
+ function createContextRecordReader(source, cwd = '') {
76
+ const calls = new Map();
77
+ return function readRecord(record, recordIndex) {
78
+ const metadataCwd = record?.type === 'session_meta' ? record.payload?.cwd : (record?.type === 'session' ? record.cwd : '');
79
+ if (typeof metadataCwd === 'string' && metadataCwd) cwd = metadataCwd;
80
+ const nodes = [];
81
+ const stack = [{ record, suffix: '' }];
82
+ while (stack.length) {
83
+ const current = stack.pop();
84
+ const raw = current.record;
85
+ if (!raw || typeof raw !== 'object') continue;
86
+ let body = raw.message && typeof raw.message === 'object' ? raw.message : raw;
87
+ if (source === 'codex' && raw.type === 'response_item') body = raw.payload || {};
88
+ if (raw.User) body = { ...raw.User, role: 'user' };
89
+ if (raw.Agent) body = { ...raw.Agent, role: 'assistant' };
90
+ if (raw.Tool || raw.ToolResult) body = { content: raw.Tool || raw.ToolResult, role: 'tool' };
91
+ if (raw.System) body = { content: raw.System.content ?? raw.System, role: 'system' };
92
+ const type = String(body.type || '').toLowerCase();
93
+ let role = body.role || raw.role || raw.type;
94
+ if (type === 'reasoning' || type === 'function_call' || type === 'tool_call') role = 'assistant';
95
+ if (type === 'function_call_output' || type === 'tool_result') role = 'tool';
96
+ const category = categoryForRole(role);
97
+ let parts = [];
98
+ const paths = [];
99
+ if (category) {
100
+ const content = body.content ?? body.text ?? body.message ?? body.output ?? body.summary ?? body.thinking ?? body.reasoning_content;
101
+ parts = contentParts(content, category);
102
+ const toolResults = body.tool_results;
103
+ if (toolResults) {
104
+ for (const result of Array.isArray(toolResults) ? toolResults : Object.values(toolResults)) {
105
+ parts.push(...contentParts(result, 'tools'));
106
+ }
107
+ }
108
+ for (const key of ['thoughts', 'reasoning_content', 'reasoning_details']) {
109
+ if (body[key] !== undefined && body[key] !== content) parts.push(...contentParts(body[key], 'assistant'));
110
+ }
111
+ if (type === 'function_call' || type === 'tool_call') {
112
+ parts = [{ category: 'assistant', text: `${body.name || body.tool || ''}\n${typeof body.arguments === 'string' ? body.arguments : JSON.stringify(body.arguments || body.input || {})}` }];
113
+ calls.set(body.call_id || body.id, readPaths(body.name || body.tool, body.arguments || body.input, cwd));
114
+ }
115
+ if (type === 'function_call_output' || String(role).toLowerCase() === 'toolresult') {
116
+ paths.push(...(calls.get(body.call_id || body.toolCallId || body.tool_use_id) || []));
117
+ }
118
+ for (const part of Array.isArray(body.content) ? body.content : []) {
119
+ if (!part) continue;
120
+ if (/^(toolcall|tool_use)$/i.test(part.type || '')) {
121
+ calls.set(part.id, readPaths(part.name, part.arguments || part.input, cwd));
122
+ }
123
+ if (part.type === 'tool_result') paths.push(...(calls.get(part.tool_use_id) || []));
124
+ if (/tool/i.test(part.type || '') && (part.state?.output !== undefined || part.state?.error !== undefined || part.type === 'tool_result')) {
125
+ paths.push(...readPaths(part.tool || part.name, part.state?.input || part.input, cwd));
126
+ }
127
+ }
128
+ if (category === 'tools') paths.push(...readPaths(body.name || body.tool, body.input || body.arguments, cwd));
129
+ }
130
+ if (raw.type === 'session_meta' || raw.type === 'system_context') {
131
+ const metadata = raw.payload || raw;
132
+ parts = RULE_FIELDS.flatMap((key) => contentParts(metadata[key], 'system'));
133
+ role = 'system';
134
+ }
135
+ if (parts.length) nodes.push({ id: `record-${recordIndex}${current.suffix}`, role,
136
+ recordLineIndex: recordIndex, messageIndex: recordIndex, parts, readPaths: paths });
137
+ const containers = body === raw ? [{ value: raw, prefix: '' }]
138
+ : [{ value: body, prefix: 'body-' }, { value: raw, prefix: '' }];
139
+ const groups = containers.flatMap((container) => ['children', 'messages', 'branches'].map((field) => ({
140
+ children: container.value[field], field: `${container.prefix}${field}`
141
+ })));
142
+ for (const group of groups) {
143
+ if (!Array.isArray(group.children)) continue;
144
+ for (let index = group.children.length - 1; index >= 0; index--) {
145
+ stack.push({ record: group.children[index], suffix: `${current.suffix}.${group.field}-${index}` });
146
+ }
147
+ }
148
+ }
149
+ return nodes;
150
+ };
151
+ }
152
+
153
+ module.exports = { createContextRecordReader, contentParts };
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+ const ITEM_TIMEOUT_MS = 15000;
3
+ const TOTAL_TIMEOUT_MS = 60000;
4
+ function redactDiagnostic(value, options = {}) {
5
+ const secrets = options.secrets || [];
6
+ function text(input) {
7
+ let output = String(input);
8
+ for (const secret of secrets.filter((item) => typeof item === 'string' && item)) output = output.split(secret).join('[redacted]');
9
+ if (options.home) output = output.split(options.home).join('~');
10
+ if (options.project) output = output.split(options.project).join('[project]');
11
+ return output.replace(/Bearer\s+[^\s"',;]+/gi, 'Bearer [redacted]')
12
+ .replace(/((?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*)[^\s,;]+/gi, '$1[redacted]')
13
+ .replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, '$1[redacted]@')
14
+ .replace(/([?&](?:api[_-]?key|token|password|secret)=)[^&\s]+/gi, '$1[redacted]');
15
+ }
16
+ function clean(input) {
17
+ if (typeof input === 'string') return text(input);
18
+ if (Array.isArray(input)) return input.map(clean);
19
+ if (!input || typeof input !== 'object') return input;
20
+ return Object.fromEntries(Object.entries(input).map(([key, item]) => [key,
21
+ /api[_-]?key|token|password|secret|authorization|headers|(?:^|_)env$/i.test(key) ? '[redacted]' : clean(item)]));
22
+ }
23
+ return clean(value);
24
+ }
25
+ function createSessionDiagnostics({ local, provider, mcp, mcpTargets, home, secrets }) {
26
+ let job = { status: 'idle', items: [], cancelled: false };
27
+ let running;
28
+ const status = () => {
29
+ const report = redactDiagnostic(job, { home, project: job.project, secrets: secrets ? secrets() : [] });
30
+ const markdown = ['# Codex Mate diagnostics', `Status: ${report.status}`, ...report.items.map((item) =>
31
+ `\n## ${item.id}\nStatus: ${item.status}\nChecked: ${item.checkedAt || ''}\n${JSON.stringify(item.evidence || {}, null, 2)}`)].join('\n');
32
+ return { report, markdown };
33
+ };
34
+ async function check(item, execute, deadline) {
35
+ if (job.cancelled) { item.status = 'cancelled'; return; }
36
+ const activeJob = job;
37
+ if (Date.now() >= deadline) { item.status = 'timeout'; return; }
38
+ const started = Date.now();
39
+ const timeout = Math.max(1, Math.min(ITEM_TIMEOUT_MS, deadline - started));
40
+ item.status = 'running'; item.checkedAt = new Date().toISOString();
41
+ let timer;
42
+ try {
43
+ const result = await Promise.race([execute({ timeoutMs: timeout, isCancelled: () => activeJob.cancelled }),
44
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('diagnostic-timeout')), timeout); })]);
45
+ item.status = activeJob.cancelled ? 'cancelled' : result.ok === false ? 'failed' : 'passed';
46
+ item.evidence = result;
47
+ } catch (error) {
48
+ item.status = activeJob.cancelled ? 'cancelled' : error.message === 'diagnostic-timeout' ? 'timeout' : 'failed';
49
+ item.errorCode = error.message === 'diagnostic-timeout' ? 'diagnostic-timeout' : 'diagnostic-check-failed';
50
+ } finally { clearTimeout(timer); item.durationMs = Date.now() - started; }
51
+ }
52
+ function start(params = {}) {
53
+ if (job.status === 'running') throw new Error('diagnostic-busy');
54
+ if (params.remote !== undefined && typeof params.remote !== 'boolean') throw new Error('diagnostic-input-invalid');
55
+ const names = params.mcpNames || [];
56
+ if (!Array.isArray(names) || names.some((name) => typeof name !== 'string' || !mcpTargets(params.cwd).includes(name))) throw new Error('diagnostic-input-invalid');
57
+ job = { status: 'running', cancelled: false, startedAt: new Date().toISOString(), project: params.cwd || '',
58
+ items: [{ id: 'local', status: 'pending' }, { id: 'provider', status: params.remote ? 'pending' : 'not_checked' },
59
+ ...names.map((name) => ({ id: `mcp:${name}`, status: 'pending' }))] };
60
+ running = (async () => {
61
+ const deadline = Date.now() + TOTAL_TIMEOUT_MS;
62
+ await check(job.items[0], local, deadline);
63
+ if (params.remote) await check(job.items[1], provider, deadline);
64
+ for (let index = 0; index < names.length; index++) {
65
+ if (Date.now() >= deadline) { job.items[index + 2].status = 'timeout'; continue; }
66
+ await check(job.items[index + 2], (options) => mcp(names[index], { ...options, cwd: params.cwd }), deadline);
67
+ }
68
+ job.status = job.cancelled ? 'cancelled' : job.items.some((item) => ['failed', 'timeout'].includes(item.status)) ? 'partial' : 'success';
69
+ job.finishedAt = new Date().toISOString();
70
+ })().catch(() => { job.status = 'failed'; });
71
+ return status();
72
+ }
73
+ return { start, status, cancel() { job.cancelled = true; return status(); }, targets: (cwd) => ({ names: mcpTargets(cwd) }), wait: () => running };
74
+ }
75
+ module.exports = { createSessionDiagnostics, redactDiagnostic };
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+ const path = require('path');
3
+ const { createLocalFeatureStore } = require('./local-feature-store');
4
+ function createSessionFeatureSettings(root) {
5
+ const store = createLocalFeatureStore(path.join(root, 'preferences.json'), { version: 1, windows: {}, dismissed: {} });
6
+ function get() { const snapshot = store.read(); return { settings: snapshot.value, revision: snapshot.revision }; }
7
+ function save(params) {
8
+ const snapshot = store.read();
9
+ if (snapshot.revision !== params.revision) throw new Error('feature-store-conflict');
10
+ if (typeof params.key !== 'string' || !params.key || params.key.length > 1000
11
+ || (params.window !== '' && (!Number.isSafeInteger(params.window) || params.window <= 0))
12
+ || typeof params.dismissed !== 'boolean') throw new Error('context-window-invalid');
13
+ if (params.window === '') delete snapshot.value.windows[params.key];
14
+ else snapshot.value.windows[params.key] = params.window;
15
+ snapshot.value.dismissed[params.key] = params.dismissed;
16
+ store.write(snapshot.value, snapshot.revision);
17
+ return get();
18
+ }
19
+ return { get, save };
20
+ }
21
+ module.exports = { createSessionFeatureSettings };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ const { createSessionBookmarks } = require('./session-bookmarks');
3
+ const { digest } = require('./local-feature-store');
4
+ const { createSessionSearchIndex } = require('./session-search-index');
5
+ const { generateHandoffDraft } = require('./session-handoff-draft');
6
+ const { createSessionProjects } = require('./session-projects');
7
+ const { createSessionFeatureSettings } = require('./session-feature-settings');
8
+ const { createSessionDiagnostics } = require('./session-diagnostics');
9
+
10
+ function createSessionFeatures(deps) {
11
+ async function readNode(params) {
12
+ if (params.nodeId) return deps.readNode(params);
13
+ let match;
14
+ for await (const node of deps.nodes(params)) {
15
+ if (node.text !== params.messageText) continue;
16
+ if (match) return { error: 'bookmark-source-unavailable' };
17
+ match = node;
18
+ }
19
+ return match ? { source: params.source, node: match } : { error: 'bookmark-source-unavailable' };
20
+ }
21
+ const bookmarks = createSessionBookmarks({ root: deps.root, readNode });
22
+ const index = createSessionSearchIndex(deps);
23
+ const projects = createSessionProjects({ ...deps, bookmarks });
24
+ const settings = createSessionFeatureSettings(deps.root);
25
+ const diagnostics = deps.diagnostics ? createSessionDiagnostics(deps.diagnostics) : null;
26
+ const actions = {
27
+ 'session-diagnostics-targets': (params) => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.targets(params.cwd); },
28
+ 'session-diagnostics-start': (params) => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.start(params); },
29
+ 'session-diagnostics-status': () => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.status(); },
30
+ 'session-diagnostics-cancel': () => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.cancel(); },
31
+ 'session-feature-settings-get': () => settings.get(),
32
+ 'session-feature-settings-save': (params) => settings.save(params),
33
+ 'session-projects': (params) => projects.list(params),
34
+ 'session-project-map': (params) => projects.map(params),
35
+ 'session-project-prompt': (params) => projects.prompt(params),
36
+ 'session-handoff-draft': (params) => generateHandoffDraft(params, readNode),
37
+ 'session-index-status': () => index.status(),
38
+ 'session-index-refresh': (params) => index.start(params),
39
+ 'session-index-cancel': () => index.cancel(),
40
+ 'session-index-search': (params) => index.search(params),
41
+ 'session-index-node': async (params) => {
42
+ const result = await readNode(params);
43
+ if (result.error || digest(result.node.text) !== params.textHash) throw new Error('bookmark-source-unavailable');
44
+ return result;
45
+ },
46
+ 'session-bookmarks-list': (params) => bookmarks.list(params),
47
+ 'session-bookmark-save': (params) => bookmarks.save(params),
48
+ 'session-bookmark-remove': (params) => bookmarks.remove(params),
49
+ 'session-bookmark-locate': (params) => bookmarks.locate(params)
50
+ };
51
+ async function handle(action, params = {}) {
52
+ try {
53
+ if (!actions[action]) throw new Error('feature-action-invalid');
54
+ return await actions[action](params);
55
+ } catch (error) {
56
+ // Keep filesystem paths and raw upstream errors out of the public contract.
57
+ const code = /^[a-z]+(?:-[a-z]+)+$/.test(error.message) ? error.message : 'feature-read-failed';
58
+ return { error: code, errorCode: code };
59
+ }
60
+ }
61
+ return { handle, bookmarks, readNode, index };
62
+ }
63
+ module.exports = { createSessionFeatures };
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+ const { digest } = require('./local-feature-store');
3
+ const MAX_SELECTIONS = 100;
4
+ const EXCERPT_LENGTH = 800;
5
+ const GOAL_LENGTH = 500;
6
+
7
+ function classifyEvidence(node) {
8
+ const text = node.text;
9
+ const isTool = /tool|function_call_output/i.test(node.role);
10
+ if (!isTool) return 'unverified';
11
+ const failed = /(?:\b(?:fail(?:ed|ures?)?|errors?)\s*[:=]?\s*[1-9]\d*\b|\bexit(?:ed)?(?: with)?(?: code)?\s*[:=]?\s*[1-9]\d*\b|测试失败|验证失败|未通过)/i.test(text);
12
+ if (failed) return 'failed';
13
+ const passed = /(?:^|\n)\s*(?:All \d+ tests passed[.!]?|(?:ℹ|#)?\s*pass\s+[1-9]\d*|exit(?:ed)?(?: with)?(?: code)?\s*[:=]?\s*0)\s*(?:\n|$)/i.test(text);
14
+ const ambiguous = /未(?:执行|运行|验证)|尚未|not (?:run|executed|passed)|待确认/i.test(text);
15
+ return passed && !ambiguous ? 'passed' : 'unverified';
16
+ }
17
+ async function generateHandoffDraft(params, readNode) {
18
+ if (!Array.isArray(params.selections) || !params.selections.length || params.selections.length > MAX_SELECTIONS
19
+ || params.selections.some((value) => typeof value !== 'string')) throw new Error('handoff-selection-invalid');
20
+ const card = { goal: String(params.goal || '').trim().slice(0, GOAL_LENGTH), completed: [], blockers: [], nextSteps: [], files: [] };
21
+ const evidence = [];
22
+ const unverified = [];
23
+ for (const selection of [...new Set(params.selections)]) {
24
+ const result = await readNode({ source: params.source, sessionId: params.sessionId, filePath: params.filePath,
25
+ cwd: params.cwd, ...(selection.startsWith('text:') ? { messageText: selection.slice(5) } : { nodeId: selection }) });
26
+ if (result.error) throw new Error('bookmark-source-unavailable');
27
+ const node = result.node;
28
+ const status = classifyEvidence(node);
29
+ const excerpt = node.text.slice(0, EXCERPT_LENGTH);
30
+ for (const file of node.readPaths || []) if (!card.files.includes(file)) card.files.push(file);
31
+ for (const line of node.text.split('\n')) {
32
+ if (/^(?:下一步|后续步骤|next steps?)\s*[::]/i.test(line.trim())) card.nextSteps.push(line.trim());
33
+ }
34
+ if (!card.goal && node.role === 'user') card.goal = node.text.slice(0, GOAL_LENGTH);
35
+ if (status === 'passed') card.completed.push(excerpt);
36
+ else if (status === 'failed') card.blockers.push(excerpt);
37
+ else unverified.push(excerpt);
38
+ evidence.push({ source: result.source, sessionId: params.sessionId || '', filePath: params.filePath || '',
39
+ cwd: params.cwd || '', nodeId: node.id, textHash: digest(node.text), excerpt, status });
40
+ }
41
+ return { card, evidence, unverified, requiresReview: true, sent: false };
42
+ }
43
+ module.exports = { generateHandoffDraft, classifyEvidence };
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { createLocalFeatureStore } = require('./local-feature-store');
5
+ const { projectKey } = require('./session-bookmarks');
6
+ const { SOURCES } = require('./session-search-index');
7
+ const PROJECT_DISCOVERY_LIMIT = 3000;
8
+ const PROJECT_SESSION_LIMIT = 100;
9
+
10
+ function createSessionProjects({ root, inventory, bookmarks, handoffs }) {
11
+ const store = createLocalFeatureStore(path.join(root, 'projects.json'), { version: 1, mappings: {} });
12
+ function resolveProject(cwd, mappings) {
13
+ let key = projectKey(cwd);
14
+ const visited = new Set();
15
+ while (mappings[key]) {
16
+ if (visited.has(key)) throw new Error('project-mapping-invalid');
17
+ visited.add(key); key = mappings[key];
18
+ }
19
+ return key;
20
+ }
21
+ function map(params) {
22
+ if (typeof params.from !== 'string' || typeof params.to !== 'string' || !path.isAbsolute(params.from)
23
+ || (params.to && !path.isAbsolute(params.to))) throw new Error('project-mapping-invalid');
24
+ const snapshot = store.read();
25
+ if (snapshot.revision !== params.revision) throw new Error('feature-store-conflict');
26
+ const from = projectKey(params.from);
27
+ if (params.to) snapshot.value.mappings[from] = projectKey(params.to);
28
+ else delete snapshot.value.mappings[from];
29
+ resolveProject(from, snapshot.value.mappings);
30
+ return store.write(snapshot.value, snapshot.revision);
31
+ }
32
+ async function list(params = {}) {
33
+ const snapshot = store.read();
34
+ const groups = new Map();
35
+ const failures = [];
36
+ for (const source of SOURCES) {
37
+ let sessions;
38
+ try { sessions = await inventory(source, PROJECT_DISCOVERY_LIMIT); }
39
+ catch (_) { failures.push({ source, code: 'index-source-unavailable' }); continue; }
40
+ for (const session of sessions) {
41
+ const key = resolveProject(session.cwd || '', snapshot.value.mappings);
42
+ if (!groups.has(key)) groups.set(key, { key, cwd: key, sessions: [], sources: [], updatedAt: '' });
43
+ const group = groups.get(key);
44
+ const timestamp = session.updatedAt || session.timestamp || '';
45
+ group.sessions.push({ source, sessionId: session.sessionId || '', filePath: session.filePath || '',
46
+ cwd: session.cwd || '', title: session.title || '', timestamp, updatedAt: timestamp });
47
+ if (!group.sources.includes(source)) group.sources.push(source);
48
+ if (timestamp > group.updatedAt) group.updatedAt = timestamp;
49
+ }
50
+ }
51
+ const projects = [...groups.values()].map((group) => ({ key: group.key, cwd: group.cwd,
52
+ sources: group.sources, sessionCount: group.sessions.length, updatedAt: group.updatedAt }));
53
+ const key = params.project === undefined ? null : resolveProject(params.project, snapshot.value.mappings);
54
+ const group = key === null ? null : groups.get(key);
55
+ let detail = null;
56
+ if (group) {
57
+ const sessions = group.sessions.sort((left, right) => String(right.timestamp).localeCompare(String(left.timestamp))).slice(0, PROJECT_SESSION_LIMIT);
58
+ const prompts = group.cwd ? ['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md'].map((name) => path.join(group.cwd, name))
59
+ .filter((file) => { try { return fs.lstatSync(file).isFile(); } catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return false; throw error; } }) : [];
60
+ detail = { ...group, sessions, truncated: group.sessions.length > PROJECT_SESSION_LIMIT, prompts,
61
+ bookmarks: bookmarks.list().items.filter((item) => resolveProject(item.cwd, snapshot.value.mappings) === key),
62
+ handoffs: sessions.flatMap((session) => session.sessionId ? handoffs(session.sessionId).map((record) => ({ ...record, source: session.source })) : []) };
63
+ }
64
+ return { projects, detail, failures, mappings: snapshot.value.mappings, revision: snapshot.revision,
65
+ readAt: new Date().toISOString(), scope: 'discovered-candidates', discoveryLimit: PROJECT_DISCOVERY_LIMIT };
66
+ }
67
+ function prompt(params) {
68
+ if (!['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md'].includes(params.name) || !params.project) throw new Error('project-mapping-invalid');
69
+ const file = path.join(projectKey(params.project), params.name);
70
+ const stat = fs.lstatSync(file);
71
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) throw new Error('feature-read-failed');
72
+ return { filePath: file, content: fs.readFileSync(file, 'utf8'), readOnly: true };
73
+ }
74
+ return { list, map, prompt };
75
+ }
76
+ module.exports = { createSessionProjects };