codexmate 0.1.31 → 0.1.32

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 (43) hide show
  1. package/README.md +3 -3
  2. package/README.vi.md +3 -3
  3. package/README.zh.md +3 -3
  4. package/cli/agents-files.js +18 -4
  5. package/cli/plugin-config.js +64 -0
  6. package/cli/prompt-history.js +17 -4
  7. package/cli/system-prompt-files.js +7 -2
  8. package/cli.js +36 -2
  9. package/lib/cli-config-engine.js +9 -3
  10. package/lib/session-context-health.js +82 -0
  11. package/lib/session-context-records.js +153 -0
  12. package/lib/web-startup-auth.js +5 -1
  13. package/package.json +1 -1
  14. package/plugins/prompt-templates/computed.mjs +3 -3
  15. package/plugins/prompt-templates/invocation.mjs +73 -0
  16. package/plugins/prompt-templates/methods.mjs +48 -3
  17. package/plugins/prompt-templates/overview.mjs +2 -0
  18. package/web-ui/app.js +25 -0
  19. package/web-ui/index.html +1 -0
  20. package/web-ui/logic.context-health.mjs +144 -0
  21. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  22. package/web-ui/modules/app.methods.agents.mjs +20 -3
  23. package/web-ui/modules/app.methods.index.mjs +4 -0
  24. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  25. package/web-ui/modules/context-health.methods.mjs +70 -0
  26. package/web-ui/modules/i18n/locales/en.mjs +33 -0
  27. package/web-ui/modules/i18n/locales/ja.mjs +33 -0
  28. package/web-ui/modules/i18n/locales/vi.mjs +33 -0
  29. package/web-ui/modules/i18n/locales/zh-tw.mjs +33 -0
  30. package/web-ui/modules/i18n/locales/zh.mjs +33 -0
  31. package/web-ui/modules/plugins.methods.mjs +2 -0
  32. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  33. package/web-ui/partials/index/context-health.html +45 -0
  34. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  35. package/web-ui/partials/index/panel-plugins.html +37 -9
  36. package/web-ui/partials/index/panel-prompts.html +18 -2
  37. package/web-ui/partials/index/panel-sessions.html +14 -11
  38. package/web-ui/res/web-ui-render.precompiled.js +682 -32
  39. package/web-ui/styles/context-health.css +107 -0
  40. package/web-ui/styles/prompts-editor.css +23 -0
  41. package/web-ui/styles/sessions-preview.css +21 -0
  42. package/web-ui/styles/sub-tabs.css +181 -0
  43. package/web-ui/styles.css +2 -0
package/README.md CHANGED
@@ -151,7 +151,7 @@ Use the handoff's returned ID for `<id>`, the same target agent for `<target>`,
151
151
  ## What's So Special?
152
152
 
153
153
  After finding your conversations, manage the configuration, skills, and tasks used in your daily work:
154
- - **Unified Session Browser**: Browse local sessions from Codex, Claude Code, Gemini CLI, CodeBuddy Code, WorkBuddy, Pi, OpenCode, and Zed in one place. Search, export, and deletion availability varies by source; see the [session guide (Chinese)](https://sakurabytecore.github.io/codexmate/guide/sessions).
154
+ - **Unified Session Browser**: Browse local sessions from Codex, Claude Code, Gemini CLI, CodeBuddy Code, WorkBuddy, Pi, OpenCode, and Zed in one place. Search, export, and deletion availability varies by source; see the [session guide (Chinese)](https://sakurabytecore.github.io/codexmate/guide/sessions). Session details show an always-visible five-category token breakdown, a composition bar, and a health rating.
155
155
  - **OpenAI-Compatible Bridge**: Use Codex with any OpenAI-compatible UI by normalizing the Responses API; the built-in Codex conversion also fills and normalizes Codex fingerprint headers such as `User-Agent`, `Version`, `OpenAI-Beta`, and `Originator` so upstream providers see an official Codex CLI-shaped request.
156
156
  - **Claude Provider Bridge**: Connect Claude Code to OpenAI Chat Completions-compatible providers and Ollama through the built-in local Claude-compatible proxy.
157
157
  - **OpenCode Provider Control**: Manage OpenCode provider/model selection with a CodexMate-owned provider store under `~/.codexmate`, projecting only the active provider into native OpenCode config to avoid polluting or deleting user-owned settings.
@@ -180,8 +180,8 @@ After finding your conversations, manage the configuration, skills, and tasks us
180
180
  | **KiloCode Config Bridge** | ✅ | Configure KiloCode through `codexmate kilo config` or the Web UI, writing provider URL/model/API key data to `~/.config/kilo/kilo.jsonc` |
181
181
  | **Pi Provider Config** | ✅ | Manage Pi providers in the Web UI writing to `~/.pi/agent/models.json` (unknown fields preserved) and switch the default provider/model in `~/.pi/agent/settings.json` |
182
182
  | **Provider Health Check** | ✅ | Probe local Codex/Claude provider routes, highlight failed configs, and bulk-remove selected broken providers safely |
183
- | **Prompt Templates** | ✅ | Reusable prompt plugins with variables |
184
- | **Prompt File Editor** | ✅ | Edit global and project-level CLAUDE.md / AGENTS.md with auto-detect, path switching, and a shared preset pool. Applying a preset only updates the editor; save manually to write the file. |
183
+ | **Prompt Templates** | ✅ | Variable-fill dialog on invocation, one-template JSON sharing, and versioned plugin template configuration with history Diff and rollback. `git_diff` is pasted text, not an executed command. |
184
+ | **Prompt File Editor** | ✅ | Edit global and project-level CLAUDE.md / AGENTS.md with a shared preset pool. Presets fill variables before updating the editor; save manually to write files. History shows version Diff; confirmed rollback writes the selected version with an atomic backup and concurrent-change checks. |
185
185
  | **MCP Integration** | ✅ | Expose local tools and resources via MCP stdio |
186
186
  | **Auto Update** | ✅ | Quick update CLI via `codexmate update` |
187
187
 
package/README.vi.md CHANGED
@@ -151,7 +151,7 @@ Dùng mã bàn giao được trả về cho `<id>`, cùng tác nhân đích cho
151
151
  ## Điểm nổi bật
152
152
 
153
153
  Sau khi tìm lại cuộc trò chuyện, bạn có thể quản lý cấu hình, skill và tác vụ phục vụ công việc hằng ngày:
154
- - **Trình duyệt phiên thống nhất**: Xem phiên cục bộ từ Codex, Claude Code, Gemini CLI, CodeBuddy Code, WorkBuddy, Pi, OpenCode và Zed tại một nơi. Khả năng tìm kiếm, xuất và xóa tùy thuộc nguồn; xem [hướng dẫn phiên (tiếng Trung)](https://sakurabytecore.github.io/codexmate/guide/sessions).
154
+ - **Trình duyệt phiên thống nhất**: Xem phiên cục bộ từ Codex, Claude Code, Gemini CLI, CodeBuddy Code, WorkBuddy, Pi, OpenCode và Zed tại một nơi. Khả năng tìm kiếm, xuất và xóa tùy thuộc nguồn; xem [hướng dẫn phiên (tiếng Trung)](https://sakurabytecore.github.io/codexmate/guide/sessions). Chi tiết phiên luôn hiển thị ước tính token theo năm nhóm, thanh tỷ lệ và mức sức khỏe ngữ cảnh.
155
155
  - **Bridge tương thích OpenAI**: Dùng Codex với bất kỳ UI nào hỗ trợ OpenAI bằng cách chuẩn hóa Responses API.
156
156
  - **Dọn dẹp provider lỗi**: Kiểm tra route provider cục bộ của Codex/Claude, hiển thị cấu hình lỗi trong một modal và xóa hàng loạt các provider hỏng đã chọn mà không chạm vào mục khỏe mạnh hoặc được bảo vệ.
157
157
  - **Chợ skill cục bộ**: Chia sẻ và nhập skill giữa các app agent khác nhau.
@@ -172,8 +172,8 @@ Sau khi tìm lại cuộc trò chuyện, bạn có thể quản lý cấu hình,
172
172
  | **Hàng đợi tác vụ** | ✅ | Quy trình tự động có phụ thuộc, lưu tiến độ, khôi phục an toàn và tổng kết kết quả |
173
173
  | **Bridge OpenAI** | ✅ | Chuyển đổi Codex Responses API sang định dạng OpenAI chuẩn |
174
174
  | **Kiểm tra sức khỏe Provider** | ✅ | Kiểm tra route provider Codex/Claude, đánh dấu cấu hình lỗi và xóa hàng loạt các provider hỏng đã chọn một cách an toàn |
175
- | **Mẫu Prompt** | ✅ | Plugin prompt tái sử dụng được với hỗ trợ biến |
176
- | **Trình sửa tệp prompt** | ✅ | Chỉnh sửa CLAUDE.md / AGENTS.md (bao gồm `~/.config/opencode/AGENTS.md` của OpenCode) và dùng kho preset chung. Áp dụng preset chỉ cập nhật editor; cần lưu thủ công để ghi vào tệp. |
175
+ | **Mẫu Prompt** | ✅ | Hộp thoại điền biến khi gọi, chia sẻ một mẫu bằng JSON, lịch sử Diff và khôi phục cấu hình mẫu plugin. `git_diff` là văn bản được dán, không thực thi lệnh. |
176
+ | **Trình sửa tệp prompt** | ✅ | Chỉnh sửa CLAUDE.md / AGENTS.md toàn cục và theo dự án với kho preset chung. Điền biến trước khi áp dụng preset; cần lưu thủ công để ghi tệp. Lịch sử hiển thị Diff; xác nhận khôi phục sẽ ghi phiên bản đã chọn với bản sao lưu nguyên tử và kiểm tra thay đổi bên ngoài. |
177
177
  | **Tích hợp MCP** | ✅ | Expose tool và resource cục bộ qua MCP stdio |
178
178
  | **Tự động cập nhật** | ✅ | Cập nhật nhanh qua `codexmate update` |
179
179
 
package/README.zh.md CHANGED
@@ -151,7 +151,7 @@ node cli.js thread ack <thread-id> --handoff <id> --agent <target> --evidence <s
151
151
  ## 有什么独特之处?
152
152
 
153
153
  找回对话之后,还可以继续管理日常工作所需的配置、Skills 与任务:
154
- - **统一会话浏览器**:集中浏览 Codex、Claude Code、Gemini CLI、CodeBuddy Code、WorkBuddy、Pi、OpenCode 与 Zed 的本地会话;检索、导出和删除的来源限制见[会话指南](https://sakurabytecore.github.io/codexmate/guide/sessions)。
154
+ - **统一会话浏览器**:集中浏览 Codex、Claude Code、Gemini CLI、CodeBuddy Code、WorkBuddy、Pi、OpenCode 与 Zed 的本地会话;检索、导出和删除的来源限制见[会话指南](https://sakurabytecore.github.io/codexmate/guide/sessions)。会话详情默认显示五类预估 Token、构成条与健康评级,无需展开。
155
155
  - **OpenAI 兼容桥接**:通过归一化 Responses API,让 Codex 能够与任何支持 OpenAI 格式的 UI 配合使用;内建 Codex 转换会补齐并规范化 `User-Agent`、`Version`、`OpenAI-Beta`、`Originator` 等 Codex 指纹,对上游伪装为官方 Codex CLI 请求。
156
156
  - **Claude Provider 桥接**:通过内建本地 Claude 兼容代理,让 Claude Code 接入 OpenAI Chat Completions 兼容 provider 与 Ollama。
157
157
  - **OpenCode Provider 控制**:在 `~/.codexmate` 下维护 CodexMate 自有的 OpenCode 多 provider 存储,只将当前选中的 provider 投影到 OpenCode 原生配置,避免污染或误删用户已有配置。
@@ -178,8 +178,8 @@ node cli.js thread ack <thread-id> --handoff <id> --agent <target> --evidence <s
178
178
  | **OpenCode Provider 存储** | ✅ | 在 `~/.codexmate` 中保留多个 OpenCode provider,只将当前选中的 provider 投影到 OpenCode 原生配置 |
179
179
  | **Pi Provider 配置** | ✅ | 在 Web UI 中管理 Pi 供应商,写入 `~/.pi/agent/models.json`(未知字段无损保留),并切换 `~/.pi/agent/settings.json` 中的默认供应商/模型 |
180
180
  | **Provider 健康检查** | ✅ | 探测本地 Codex/Claude provider 路由,标记失败配置,并安全批量移除已选坏配置 |
181
- | **提示词模板** | ✅ | 支持变量的可复用提示词插件 |
182
- | **提示词文件编辑器** | ✅ | 编辑全局和项目级 CLAUDE.md / AGENTS.md,支持自动检测、路径切换与通用预设池。应用预设只更新编辑器,需手动保存才会写入文件。 |
181
+ | **提示词模板** | ✅ | 调用时弹窗填写变量,支持单模板 JSON 分享、插件模板配置历史 Diff 与回滚。`git_diff` 需粘贴差异文本,不执行命令。 |
182
+ | **提示词文件编辑器** | ✅ | 编辑全局及项目级 CLAUDE.md / AGENTS.md,支持通用预设池。应用预设先填写变量,只更新编辑器,需手动保存。历史支持版本 Diff;确认回滚后写入所选版本,保留原子备份,校验外部修改。 |
183
183
  | **MCP 集成** | ✅ | 通过 MCP stdio 暴露本地工具与资源 |
184
184
  | **自动更新** | ✅ | 通过 `codexmate update` 快速更新 CLI |
185
185
 
@@ -1,3 +1,5 @@
1
+ const { writeTextAtomicWithBackup } = require('../lib/cli-config-engine');
2
+
1
3
  function createAgentsFileController(deps = {}) {
2
4
  const {
3
5
  fs,
@@ -162,11 +164,17 @@ function createAgentsFileController(deps = {}) {
162
164
  if (content.length > 2 * 1024 * 1024) {
163
165
  return { error: 'content too large (max 2MB)' };
164
166
  }
167
+ if (typeof params.baseContent === 'string') {
168
+ const current = readClaudeMdFile(params);
169
+ if (current.error) return current;
170
+ if (current.content !== params.baseContent) return { error: '文件已被修改,请重新加载后再回滚' };
171
+ }
165
172
  if (typeof backupPromptBeforeWrite === 'function') {
166
173
  var bucket = resolved.isProject
167
174
  ? 'claude-project_' + sanitizeHistoryId(resolved.projectPath)
168
175
  : 'claude-global';
169
- backupPromptBeforeWrite(bucket, filePath);
176
+ const backup = backupPromptBeforeWrite(bucket, filePath);
177
+ if (backup && backup.error) return { error: backup.error };
170
178
  resolved.historyBucket = bucket;
171
179
  }
172
180
  var lineEnding = params.lineEnding === '\r\n' ? '\r\n' : '\n';
@@ -174,7 +182,7 @@ function createAgentsFileController(deps = {}) {
174
182
  var finalContent = ensureUtf8Bom(normalized);
175
183
  try {
176
184
  ensureDir(path.dirname(filePath));
177
- fs.writeFileSync(filePath, finalContent, 'utf-8');
185
+ writeTextAtomicWithBackup(filePath, finalContent, { fs });
178
186
  var result = { success: true, path: filePath };
179
187
  if (resolved.historyBucket) result.historyBucket = resolved.historyBucket;
180
188
  if (resolved.isProject) {
@@ -236,12 +244,18 @@ function createAgentsFileController(deps = {}) {
236
244
  if (content.length > 2 * 1024 * 1024) {
237
245
  return { error: '内容过大(最大 2MB)' };
238
246
  }
247
+ if (typeof params.baseContent === 'string') {
248
+ const current = readAgentsFile(params);
249
+ if (current.error) return current;
250
+ if (current.content !== params.baseContent) return { error: '文件已被修改,请重新加载后再回滚' };
251
+ }
239
252
  let agentsHistoryBucket = '';
240
253
  if (typeof backupPromptBeforeWrite === 'function') {
241
254
  const explicitBucket = typeof params.historyBucket === 'string' ? params.historyBucket.trim() : '';
242
255
  const bucket = explicitBucket
243
256
  || ('codex_' + sanitizeHistoryId(String(params.baseDir || '').trim() || 'global'));
244
- backupPromptBeforeWrite(bucket, filePath);
257
+ const backup = backupPromptBeforeWrite(bucket, filePath);
258
+ if (backup && backup.error) return { error: backup.error };
245
259
  agentsHistoryBucket = bucket;
246
260
  }
247
261
  const lineEnding = params.lineEnding === '\r\n' ? '\r\n' : '\n';
@@ -249,7 +263,7 @@ function createAgentsFileController(deps = {}) {
249
263
  const finalContent = ensureUtf8Bom(normalized);
250
264
 
251
265
  try {
252
- fs.writeFileSync(filePath, finalContent, 'utf-8');
266
+ writeTextAtomicWithBackup(filePath, finalContent, { fs });
253
267
  const agentsResult = { success: true, path: filePath };
254
268
  if (agentsHistoryBucket) agentsResult.historyBucket = agentsHistoryBucket;
255
269
  return agentsResult;
@@ -0,0 +1,64 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { writeTextAtomicWithBackup } = require('../lib/cli-config-engine');
5
+ const CONFIG_VERSION = 1;
6
+ const MAX_CONFIG_BYTES = 2 * 1024 * 1024;
7
+ const HISTORY_BUCKET = 'plugin_prompt_templates';
8
+ const TEMPLATE_FIELDS = ['id', 'name', 'description', 'template', 'createdAt', 'updatedAt', 'createdBy'];
9
+
10
+ function normalizeTemplates(input) {
11
+ if (!Array.isArray(input)) throw new Error('模板配置必须是数组');
12
+ const ids = new Set();
13
+ return input.filter((item) => item && item.isBuiltin !== true).map((item) => {
14
+ if (typeof item.id !== 'string' || !item.id || typeof item.name !== 'string' || !item.name.trim()
15
+ || typeof item.template !== 'string' || ids.has(item.id)) throw new Error('模板配置条目无效');
16
+ ids.add(item.id);
17
+ const entry = Object.fromEntries(TEMPLATE_FIELDS.map((field) => [field, typeof item[field] === 'string' ? item[field] : '']));
18
+ entry.isBuiltin = false;
19
+ entry.maintainers = Array.isArray(item.maintainers) ? item.maintainers.filter((name) => typeof name === 'string') : [];
20
+ return entry;
21
+ });
22
+ }
23
+
24
+ function serializeTemplates(templates) {
25
+ const content = JSON.stringify({ version: CONFIG_VERSION, templates: normalizeTemplates(templates) }, null, 2) + '\n';
26
+ if (Buffer.byteLength(content, 'utf8') > MAX_CONFIG_BYTES) throw new Error('模板配置超过 2MB');
27
+ return content;
28
+ }
29
+
30
+ function createPluginConfigController({ fs, path, CONFIG_DIR, backupPromptBeforeWrite }) {
31
+ const filePath = path.join(CONFIG_DIR, 'codexmate-plugin-config.json');
32
+ function getPluginConfig() {
33
+ try {
34
+ const exists = fs.existsSync(filePath);
35
+ const raw = exists ? fs.readFileSync(filePath, 'utf8') : '';
36
+ const parsed = exists ? JSON.parse(raw) : { version: CONFIG_VERSION, templates: [] };
37
+ if (parsed.version !== CONFIG_VERSION) throw new Error('模板配置版本无效');
38
+ return {
39
+ exists, templates: normalizeTemplates(parsed.templates), historyBucket: HISTORY_BUCKET,
40
+ hash: crypto.createHash('sha256').update(raw).digest('hex')
41
+ };
42
+ } catch (error) { return { error: error.message }; }
43
+ }
44
+ function applyPluginConfig(params = {}) {
45
+ try {
46
+ const content = serializeTemplates(params.templates);
47
+ const current = getPluginConfig();
48
+ if (current.error) return current;
49
+ if (typeof params.baseHash !== 'string' || params.baseHash !== current.hash) {
50
+ return { error: '模板配置已被修改,请重新加载后再保存' };
51
+ }
52
+ if (!current.exists && Array.isArray(params.legacyTemplates) && params.legacyTemplates.length) {
53
+ writeTextAtomicWithBackup(filePath, serializeTemplates(params.legacyTemplates), { fs });
54
+ }
55
+ const backup = backupPromptBeforeWrite(HISTORY_BUCKET, filePath);
56
+ if (backup && backup.error) return { error: backup.error };
57
+ writeTextAtomicWithBackup(filePath, content, { fs });
58
+ return getPluginConfig();
59
+ } catch (error) { return { error: error.message }; }
60
+ }
61
+ return { getPluginConfig, applyPluginConfig };
62
+ }
63
+
64
+ module.exports = { createPluginConfigController };
@@ -1,11 +1,15 @@
1
1
  'use strict';
2
2
 
3
+ const crypto = require('crypto');
4
+ const { writeTextAtomicWithBackup } = require('../lib/cli-config-engine');
5
+
3
6
  function createPromptHistoryController(deps = {}) {
4
7
  const {
5
8
  fs,
6
9
  path,
7
10
  CONFIG_DIR,
8
- MAX_HISTORY = 20
11
+ MAX_HISTORY = 20,
12
+ now = Date.now
9
13
  } = deps;
10
14
 
11
15
  if (!fs) throw new Error('createPromptHistoryController 缺少 fs');
@@ -61,10 +65,19 @@ function createPromptHistoryController(deps = {}) {
61
65
  return { backedUp: false, error: '读取当前文件失败: ' + e.message };
62
66
  }
63
67
  ensureDirSync(dir);
64
- const stamp = buildTimestamp();
65
- const dest = path.join(dir, stamp + '.bak');
68
+ let time = now();
69
+ let stamp = buildTimestamp(new Date(time));
70
+ let dest = path.join(dir, stamp + '.bak');
71
+ while (fs.existsSync(dest)) {
72
+ time += 1;
73
+ stamp = buildTimestamp(new Date(time));
74
+ dest = path.join(dir, stamp + '.bak');
75
+ }
66
76
  try {
67
- fs.writeFileSync(dest, raw, 'utf-8');
77
+ writeTextAtomicWithBackup(dest, raw, { fs });
78
+ const sourceHash = crypto.createHash('sha256').update(Buffer.from(raw, 'utf8')).digest('hex');
79
+ const backupHash = crypto.createHash('sha256').update(fs.readFileSync(dest)).digest('hex');
80
+ if (sourceHash !== backupHash) throw new Error('历史备份校验失败');
68
81
  } catch (e) {
69
82
  return { backedUp: false, error: '写入备份失败: ' + e.message };
70
83
  }
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { writeTextAtomicWithBackup } = require('../lib/cli-config-engine');
4
+
3
5
  function createSystemPromptFileController(deps = {}) {
4
6
  const {
5
7
  fs,
@@ -120,11 +122,12 @@ function createSystemPromptFileController(deps = {}) {
120
122
  const bucket = 'system_' + target.scope + '_' + (target.scope === 'project'
121
123
  ? sanitizeSystemHistoryId(path.dirname(target.path))
122
124
  : 'global');
123
- backupPromptBeforeWrite(bucket, target.path);
125
+ const backup = backupPromptBeforeWrite(bucket, target.path);
126
+ if (backup && backup.error) return { error: backup.error };
124
127
  sysHistoryBucket = bucket;
125
128
  }
126
129
  const finalContent = content.endsWith('\n') ? content : content + '\n';
127
- fs.writeFileSync(target.path, finalContent, { encoding: 'utf8', mode: 0o600 });
130
+ writeTextAtomicWithBackup(target.path, finalContent, { fs });
128
131
  try { fs.chmodSync(target.path, 0o600); } catch (_) {}
129
132
  } catch (e) {
130
133
  return { error: '写入 system prompt 失败: ' + e.message };
@@ -146,6 +149,8 @@ function createSystemPromptFileController(deps = {}) {
146
149
  }
147
150
  return {
148
151
  ...resolved,
152
+ historyBucket: 'system_' + resolved.scope + '_' + (resolved.scope === 'project'
153
+ ? sanitizeSystemHistoryId(path.dirname(resolved.path)) : 'global'),
149
154
  exists,
150
155
  content,
151
156
  hash: hashContent(content)
package/cli.js CHANGED
@@ -138,6 +138,8 @@ const {
138
138
  const {
139
139
  createPromptHistoryController
140
140
  } = require('./cli/prompt-history');
141
+ const { createPluginConfigController } = require('./cli/plugin-config');
142
+ const { createSessionContextHealthController } = require('./lib/session-context-health');
141
143
  const {
142
144
  createArchiveHelperController
143
145
  } = require('./cli/archive-helpers');
@@ -2332,7 +2334,8 @@ function queryOpencodeSessionMessages(sessionId, options = {}) {
2332
2334
  const id = typeof sessionId === 'string' ? sessionId.trim() : '';
2333
2335
  if (!id) return null;
2334
2336
  const maxMessages = resolveMaxMessagesValue(options.maxMessages, DEFAULT_SESSION_DETAIL_MESSAGES);
2335
- const limit = maxMessages === Infinity ? OPENCODE_DB_READ_LIMIT : Math.min(OPENCODE_DB_READ_LIMIT, Math.max(1, Math.floor(maxMessages)));
2337
+ const limit = options.contextHealth === true ? -1
2338
+ : (maxMessages === Infinity ? OPENCODE_DB_READ_LIMIT : Math.min(OPENCODE_DB_READ_LIMIT, Math.max(1, Math.floor(maxMessages))));
2336
2339
  return withOpencodeDb((db) => {
2337
2340
  const totalRow = db.prepare('select count(*) as count from message where session_id = ?').get(id) || {};
2338
2341
  const totalMessages = Math.max(0, Math.floor(Number(totalRow.count) || 0));
@@ -2346,8 +2349,12 @@ function queryOpencodeSessionMessages(sessionId, options = {}) {
2346
2349
  group by m.id
2347
2350
  order by m.time_created asc
2348
2351
  `).all(id, limit);
2349
- const messages = rows.map(normalizeOpencodeMessageRow).filter(Boolean);
2352
+ const messages = options.contextHealth === true ? rows.map((row) => ({
2353
+ role: parseJsonObjectSafe(row.message_data || '')?.role || 'assistant',
2354
+ content: String(row.parts || '').split('\n').map(parseJsonObjectSafe).filter(Boolean)
2355
+ })) : rows.map(normalizeOpencodeMessageRow).filter(Boolean);
2350
2356
  const sessionRow = db.prepare('select id, directory, path, time_updated from session where id = ?').get(id) || null;
2357
+ if (options.contextHealth === true && !sessionRow) return null;
2351
2358
  return {
2352
2359
  sessionId: id,
2353
2360
  cwd: sessionRow && (sessionRow.path || sessionRow.directory) ? (sessionRow.path || sessionRow.directory) : '',
@@ -2601,7 +2608,14 @@ function queryZedSessionMessages(sessionId, options = {}) {
2601
2608
  return withZedThreadsDb((db) => {
2602
2609
  const row = db.prepare('select data, data_type, folder_paths, updated_at from threads where id = ?').get(id) || null;
2603
2610
  const doc = parseZedThreadDocument(row);
2611
+ if (options.contextHealth === true && !doc) return null;
2604
2612
  const modelInfo = readZedThreadModelInfo(doc);
2613
+ if (options.contextHealth === true) return {
2614
+ sessionId: id, messages: Array.isArray(doc?.messages) ? doc.messages : [],
2615
+ cwd: doc ? readZedThreadCwd(row, doc) : '',
2616
+ instructions: doc?.system_prompt || doc?.instructions || '',
2617
+ totalMessages: Array.isArray(doc?.messages) ? doc.messages.length : 0, clipped: false
2618
+ };
2605
2619
  const all = (doc && Array.isArray(doc.messages) ? doc.messages : [])
2606
2620
  .map(entry => normalizeZedThreadMessage(entry, modelInfo))
2607
2621
  .filter(Boolean);
@@ -2956,6 +2970,10 @@ const {
2956
2970
  CONFIG_DIR
2957
2971
  });
2958
2972
 
2973
+ const { getPluginConfig, applyPluginConfig } = createPluginConfigController({
2974
+ fs, path, CONFIG_DIR, backupPromptBeforeWrite: historyBackup
2975
+ });
2976
+
2959
2977
  const {
2960
2978
  resolveAgentsFilePath,
2961
2979
  validateAgentsBaseDir,
@@ -9808,6 +9826,10 @@ async function extractMessagesFromFile(filePath, source, options = {}) {
9808
9826
  return state;
9809
9827
  }
9810
9828
 
9829
+ const { readSessionContextHealth, readSessionContextNode } = createSessionContextHealthController({
9830
+ fs, normalizeSessionSourceName, resolveSessionFilePath, queryOpencodeSessionMessages, queryZedSessionMessages
9831
+ });
9832
+
9811
9833
  async function readSessionDetail(params = {}) {
9812
9834
  const source = normalizeSessionSourceName(params.source, '');
9813
9835
  if (!source) {
@@ -14771,6 +14793,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14771
14793
  case 'preview-system-prompt-diff':
14772
14794
  result = buildSystemPromptDiff(params || {});
14773
14795
  break;
14796
+ case 'get-plugin-config':
14797
+ result = getPluginConfig();
14798
+ break;
14799
+ case 'apply-plugin-config':
14800
+ result = applyPluginConfig(params || {});
14801
+ break;
14774
14802
  case 'list-prompt-history':
14775
14803
  result = listPromptHistory((params && params.bucket) || '');
14776
14804
  break;
@@ -15021,6 +15049,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15021
15049
  case 'thread-handoff-ack':
15022
15050
  result = await handleThreadAction(action, params || {});
15023
15051
  break;
15052
+ case 'session-context-health':
15053
+ result = await readSessionContextHealth(params || {});
15054
+ break;
15055
+ case 'session-context-node':
15056
+ result = await readSessionContextNode(params || {});
15057
+ break;
15024
15058
  case 'session-detail':
15025
15059
  result = await readSessionDetail(params);
15026
15060
  break;
@@ -155,9 +155,7 @@ function writeBufferAtomically(filePath, buffer, mode, fsImpl) {
155
155
  }
156
156
 
157
157
  function writeConfigAtomicWithBackup(filePath, content, options = {}) {
158
- const fsImpl = options.fs || fs;
159
158
  const tomlImpl = options.toml || toml;
160
- const now = options.now instanceof Date ? options.now : new Date();
161
159
  const text = typeof content === 'string' ? content : String(content || '');
162
160
 
163
161
  try {
@@ -172,6 +170,13 @@ function writeConfigAtomicWithBackup(filePath, content, options = {}) {
172
170
  });
173
171
  }
174
172
 
173
+ return writeTextAtomicWithBackup(filePath, text, options);
174
+ }
175
+
176
+ function writeTextAtomicWithBackup(filePath, content, options = {}) {
177
+ const fsImpl = options.fs || fs;
178
+ const now = options.now instanceof Date ? options.now : new Date();
179
+ const text = typeof content === 'string' ? content : String(content || '');
175
180
  fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
176
181
  const targetExists = fsImpl.existsSync(filePath);
177
182
  const originalBuffer = targetExists ? fsImpl.readFileSync(filePath) : null;
@@ -256,5 +261,6 @@ module.exports = {
256
261
  isValidProviderName,
257
262
  createConfigError,
258
263
  formatConfigError,
259
- writeConfigAtomicWithBackup
264
+ writeConfigAtomicWithBackup,
265
+ writeTextAtomicWithBackup
260
266
  };
@@ -0,0 +1,82 @@
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
+ for await (const record of records(target.source, target.filePath, target.sessionId)) {
57
+ for (const node of reader(record, index)) {
58
+ if (!focus) analyzer.add(node);
59
+ if (node.id === focus) {
60
+ return { source: target.source, node: { id: node.id, role: node.role,
61
+ recordLineIndex: node.recordLineIndex, messageIndex: node.messageIndex,
62
+ text: node.parts.map((part) => part.text).join('\n') } };
63
+ }
64
+ }
65
+ index++;
66
+ }
67
+ if (focus) throw new Error('消息节点不存在,请刷新体检结果');
68
+ return { source: target.source, sessionId: target.sessionId, complete: true, scannedRecords: index, ...analyzer.finish() };
69
+ }
70
+ async function readSessionContextHealth(params = {}) {
71
+ try { return await scan(params); } catch (error) { return { error: error.message }; }
72
+ }
73
+ async function readSessionContextNode(params = {}) {
74
+ if (typeof params.nodeId !== 'string' || !/^record-\d+(?:\.(?:body-)?(?:children|messages|branches)-\d+)*$/.test(params.nodeId)) {
75
+ return { error: '消息节点 ID 无效' };
76
+ }
77
+ try { return await scan(params, params.nodeId); } catch (error) { return { error: error.message }; }
78
+ }
79
+ return { readSessionContextHealth, readSessionContextNode };
80
+ }
81
+
82
+ 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 };