codexmate 0.1.33 → 0.1.35

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 (91) hide show
  1. package/README.md +27 -2
  2. package/README.vi.md +27 -2
  3. package/README.zh.md +27 -2
  4. package/cli/analytics-export-args.js +7 -0
  5. package/cli/local-bridge.js +10 -6
  6. package/cli/openai-chat-routing.js +38 -0
  7. package/cli/routing-bridge.js +143 -0
  8. package/cli/session-usage.js +4 -1
  9. package/cli/system-prompt-files.js +75 -53
  10. package/cli.js +191 -9
  11. package/lib/data/model-prices.json +1868 -0
  12. package/lib/file-sharing-lan.js +111 -0
  13. package/lib/file-sharing.js +196 -0
  14. package/lib/model-test-client.js +61 -0
  15. package/lib/model-test.js +126 -0
  16. package/lib/routing-groups.js +161 -0
  17. package/lib/session-context-health.js +5 -1
  18. package/lib/session-evidence-collections.js +85 -0
  19. package/lib/session-features.js +15 -0
  20. package/lib/session-project-git.js +65 -0
  21. package/lib/session-projects.js +12 -1
  22. package/lib/session-stories.js +67 -0
  23. package/lib/session-usage-ledger.js +77 -0
  24. package/lib/session-usage-pricing.js +42 -0
  25. package/lib/session-usage-report.js +101 -0
  26. package/package.json +4 -1
  27. package/plugins/file-sharing/manifest.mjs +10 -0
  28. package/plugins/file-sharing/methods.mjs +101 -0
  29. package/plugins/file-sharing/overview.mjs +3 -0
  30. package/plugins/file-sharing/ownership.mjs +5 -0
  31. package/plugins/prompt-templates/computed.mjs +9 -0
  32. package/plugins/registry.mjs +3 -0
  33. package/web-ui/app.js +25 -2
  34. package/web-ui/index.html +3 -2
  35. package/web-ui/logic.session-artifacts.mjs +39 -0
  36. package/web-ui/modules/app.computed.main-tabs.mjs +3 -0
  37. package/web-ui/modules/app.methods.agents.mjs +14 -1
  38. package/web-ui/modules/app.methods.install.mjs +23 -3
  39. package/web-ui/modules/app.methods.navigation.mjs +2 -0
  40. package/web-ui/modules/app.methods.prompts-editor.mjs +7 -4
  41. package/web-ui/modules/app.methods.session-actions.mjs +2 -2
  42. package/web-ui/modules/app.methods.session-browser.mjs +35 -0
  43. package/web-ui/modules/app.methods.system-prompt.mjs +99 -19
  44. package/web-ui/modules/app.methods.theme.mjs +4 -3
  45. package/web-ui/modules/app.methods.web-ui-preferences.mjs +12 -0
  46. package/web-ui/modules/i18n/locales/en.mjs +239 -5
  47. package/web-ui/modules/i18n/locales/ja.mjs +239 -5
  48. package/web-ui/modules/i18n/locales/vi.mjs +239 -5
  49. package/web-ui/modules/i18n/locales/zh-tw.mjs +239 -5
  50. package/web-ui/modules/i18n/locales/zh.mjs +239 -5
  51. package/web-ui/modules/model-test.mjs +82 -0
  52. package/web-ui/modules/plugins.methods.mjs +3 -1
  53. package/web-ui/modules/prompt-ecosystem.methods.mjs +4 -3
  54. package/web-ui/modules/routing.mjs +206 -0
  55. package/web-ui/modules/session-collections.mjs +65 -0
  56. package/web-ui/modules/session-evidence.mjs +81 -0
  57. package/web-ui/modules/session-features.mjs +15 -1
  58. package/web-ui/modules/session-git.mjs +39 -0
  59. package/web-ui/modules/session-stories.mjs +64 -0
  60. package/web-ui/modules/usage-pricing.mjs +30 -0
  61. package/web-ui/partials/index/layout-footer.html +1 -1
  62. package/web-ui/partials/index/layout-header.html +33 -12
  63. package/web-ui/partials/index/modals-basic.html +15 -0
  64. package/web-ui/partials/index/panel-plugins.html +3 -9
  65. package/web-ui/partials/index/panel-prompts.html +13 -7
  66. package/web-ui/partials/index/panel-routing.html +3 -0
  67. package/web-ui/partials/index/panel-sessions.html +20 -20
  68. package/web-ui/partials/index/panel-settings.html +11 -1
  69. package/web-ui/partials/index/panel-usage.html +2 -0
  70. package/web-ui/partials/index/plugin-file-sharing.html +47 -0
  71. package/web-ui/partials/index/routing-model-test.html +53 -0
  72. package/web-ui/partials/index/session-diagnostics.html +7 -4
  73. package/web-ui/partials/index/session-features.html +82 -2
  74. package/web-ui/partials/index/thread-handoff.html +73 -62
  75. package/web-ui/partials/index/usage-records.html +41 -0
  76. package/web-ui/res/web-ui-render.precompiled.js +1378 -230
  77. package/web-ui/styles/base-theme.css +1 -1
  78. package/web-ui/styles/modals-core.css +6 -5
  79. package/web-ui/styles/navigation-panels.css +4 -0
  80. package/web-ui/styles/plugins-panel.css +40 -1
  81. package/web-ui/styles/responsive.css +10 -5
  82. package/web-ui/styles/routing.css +78 -0
  83. package/web-ui/styles/session-features.css +180 -7
  84. package/web-ui/styles/sessions-list.css +74 -0
  85. package/web-ui/styles/sessions-preview.css +106 -68
  86. package/web-ui/styles/sessions-usage.css +8 -0
  87. package/web-ui/styles/settings-panel.css +30 -0
  88. package/web-ui/styles/system-prompt.css +8 -7
  89. package/web-ui/styles/theme-violet-tokens.css +52 -0
  90. package/web-ui/styles/theme-violet.css +1742 -0
  91. package/web-ui/styles.css +2 -0
package/README.md CHANGED
@@ -30,10 +30,35 @@ Codex Mate is a locally running CLI + Web tool for browsing, filtering, and expo
30
30
 
31
31
  </div>
32
32
 
33
+ ### Usage record breakdown
34
+
35
+ Expand UTC usage records on demand to separate recorded tokens, cache categories and full saved-text estimates. Record adapters cover Codex, Claude, Pi and Gemini JSON sessions; existing charts and default exports keep their original semantics. No cost calculation. Use `codexmate analytics export --attribution records`. See the [usage guide](https://sakurabytecore.github.io/codexmate/guide/sessions#%E7%94%A8%E9%87%8F%E8%AE%B0%E5%BD%95%E6%98%8E%E7%BB%86).
36
+
37
+ ### File sharing
38
+
39
+ Select files or a folder, then upload explicitly. Download copies or copy LAN links valid for 60 minutes. Downloads use a separate port without management API access. Removing a batch or stopping the service invalidates its links and preserves the originals. See the [file-sharing guide](https://sakurabytecore.github.io/codexmate/guide/web-ui#%E6%96%87%E4%BB%B6%E5%85%B1%E4%BA%AB).
40
+
41
+ ### Appearance themes
42
+
43
+ Choose Light, Dark, Ocean or Violet in Settings. Violet adapts [Catppuccin Latte](https://github.com/catppuccin/palette) with light surfaces and a purple accent. Your theme is saved automatically and restored after reload.
44
+
45
+ <a id="routing-groups"></a>
46
+ ### Model test
47
+
48
+ The selected Codex/Pi subtab is saved and restored after reload. Choose a provider and model from existing configuration, enter a message and send it. View the Markdown reply, returned model ID and response time in seconds. Tests consume API credits without starting CLIs, changing configuration or saving test history. Each test sends one request without retries, sets no local response deadline and limits output to 2048 tokens. Supports configured Responses, Chat Completions, Completions and Anthropic Messages; native login and command-based credentials are not integrated. Group settings are no longer shown in the Web UI; existing backend routing and OpenAI Chat API behavior is unchanged. See the [Web UI guide](https://sakurabytecore.github.io/codexmate/guide/web-ui).
49
+
50
+ Tests use Codex UA/Originator or Pi SDK headers, with configured UA overrides taking priority. They read Codex reasoning/output settings and Pi model token limits and compatibility flags. If the installed client version cannot be resolved, requests identify as versioned CodexMate tests rather than inventing a client version.
51
+
33
52
  ### Session workbench
34
53
 
35
54
  The session page adds message bookmarks with notes and tags, an incremental local full-text index, evidence-linked handoff drafts, a read-only project workspace, and model-window references. Bookmarks do not modify source sessions. The index covers discovered candidates only; refresh it for new messages. Historical text ratios are not actual request utilization. Settings offers local diagnostics and redacted JSON/Markdown exports. Only selected checks probe the current Codex route or start selected MCP servers; no write tools are called. See the [session guide](https://sakurabytecore.github.io/codexmate/guide/sessions).
36
55
 
56
+ Build cross-session evidence packs from indexed selections, verify source hashes, and download Markdown; reload clears only the new in-memory basket. Usage offers a separate cost reference using a bundled versioned snapshot from [Wei-Shaw/model-price-repo](https://github.com/Wei-Shaw/model-price-repo), with unknown rows separate from known subtotals, not a bill and no automatic network updates. The project workspace adds read-only Git state and commit file statistics; associations within 24 hours are time-based candidates, not causation. These features do not call models or send sessions automatically. Pricing excludes tiers, service levels, cache durations, tool and multimodal extras.
57
+
58
+ Evidence collections explicitly save named source references. Reopen them after reload to recheck originals; the temporary basket still clears, and full sessions are not backed up. Commit details add development stories: manually link sessions and reasons for changes, with project isolation. Only local metadata is written; Git is unchanged, and links do not prove authorship or passing tests. See the [session guide](https://sakurabytecore.github.io/codexmate/guide/sessions).
59
+
60
+ The material basket also generates development receipts and multi-agent relay packs. Choose a format, supply a goal and optional notes, then verify sources and download Markdown. Historical material only: no model calls, command execution or automatic delivery; the current version still needs acceptance. Notes are not saved in collections and clear when a collection opens.
61
+
37
62
  ---
38
63
 
39
64
  > [!TIP]
@@ -186,9 +211,9 @@ After finding your conversations, manage the configuration, skills, and tasks us
186
211
  | **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` |
187
212
  | **Provider Health Check** | ✅ | Probe local Codex/Claude provider routes, highlight failed configs, and bulk-remove selected broken providers safely |
188
213
  | **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. |
189
- | **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. |
214
+ | **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. Editor tabs and target selections persist across refreshes. Pi restores the selected file when listed; a missing selection falls back to the first item only when no draft is pending. Pi lists direct `.md` files in `~/.pi/agent/` or `<cwd>/.pi/`, refreshing on tab entry or file-picker opening. Listing does not auto-load prompts. Initial config loading does not add a page spacer to the prompt editor or make scrolling jump when loading finishes. |
190
215
  | **MCP Integration** | ✅ | Expose local tools and resources via MCP stdio |
191
- | **Auto Update** | ✅ | Quick update CLI via `codexmate update` |
216
+ | **Auto Update** | ✅ | Click the Web UI update notice to view versions and copy `codexmate update`. Run it on the service host, then restart the service after a successful update. Clicking or copying does not run updates |
192
217
 
193
218
  ---
194
219
 
package/README.vi.md CHANGED
@@ -30,10 +30,35 @@ Codex Mate là công cụ CLI + Web chạy cục bộ, giúp xem, lọc và xu
30
30
 
31
31
  </div>
32
32
 
33
+ ### Chi tiết bản ghi sử dụng
34
+
35
+ Mở bản ghi UTC khi cần để tách token ghi nhận, các loại bộ nhớ đệm và ước tính toàn bộ văn bản đã lưu. Hỗ trợ bản ghi Codex, Claude, Pi và phiên Gemini JSON; biểu đồ và xuất mặc định giữ nguyên cách thống kê. Không tính chi phí. Dùng `codexmate analytics export --attribution records`. Xem [hướng dẫn sử dụng](https://sakurabytecore.github.io/codexmate/guide/sessions#%E7%94%A8%E9%87%8F%E8%AE%B0%E5%BD%95%E6%98%8E%E7%BB%86).
36
+
37
+ ### Chia sẻ tệp
38
+
39
+ Chọn tệp hoặc thư mục rồi tải lên thủ công. Tải bản sao hoặc sao chép liên kết LAN có hiệu lực 60 phút. Tải xuống dùng cổng riêng, không cấp quyền API quản trị. Xóa lô hoặc dừng dịch vụ sẽ vô hiệu hóa liên kết và giữ nguyên tệp gốc. Xem [hướng dẫn chia sẻ tệp](https://sakurabytecore.github.io/codexmate/guide/web-ui#%E6%96%87%E4%BB%B6%E5%85%B1%E4%BA%AB).
40
+
41
+ ### Chủ đề giao diện
42
+
43
+ Chọn Sáng, Tối, Đại dương hoặc Tím dịu trong phần cài đặt. Tím dịu tham khảo [Catppuccin Latte](https://github.com/catppuccin/palette), dùng nền sáng và điểm nhấn tím. Chủ đề được lưu tự động và khôi phục sau khi tải lại.
44
+
45
+ <a id="nhóm-định-tuyến"></a>
46
+ ### Kiểm thử mô hình
47
+
48
+ Lựa chọn tab Codex/Pi được lưu và khôi phục sau khi tải lại. Chọn nhà cung cấp và mô hình trong cấu hình hiện có, nhập nội dung rồi gửi. Xem câu trả lời Markdown, ID mô hình trả về và thời gian tính bằng giây. Kiểm thử tiêu thụ hạn mức API; không mở CLI, đổi cấu hình hoặc lưu lịch sử. Mỗi lần chỉ gửi một yêu cầu, không tự thử lại, không đặt thời hạn phản hồi cục bộ và giới hạn đầu ra 2048 token. Hỗ trợ Responses, Chat Completions, Completions và Anthropic Messages đã cấu hình; chưa tích hợp đăng nhập gốc hoặc khóa lấy bằng lệnh. Web không còn hiển thị cài đặt nhóm; chức năng phân phối phía máy chủ và OpenAI Chat API giữ nguyên. Xem [hướng dẫn Web UI](https://sakurabytecore.github.io/codexmate/guide/web-ui).
49
+
50
+ Yêu cầu kiểm thử dùng UA/Originator của Codex hoặc header SDK của Pi; UA đã cấu hình được ưu tiên. Đọc thiết lập suy luận/đầu ra Codex và giới hạn token, tham số tương thích của mô hình Pi. Nếu không đọc được phiên bản khách đã cài, yêu cầu dùng định danh kiểm thử CodexMate có phiên bản, không giả tạo phiên bản khách.
51
+
33
52
  ### Không gian làm việc phiên
34
53
 
35
54
  Trang phiên bổ sung dấu trang tin nhắn với ghi chú và nhãn, chỉ mục toàn văn cục bộ cập nhật tăng dần, bản nháp bàn giao có bằng chứng, không gian dự án chỉ đọc và tham chiếu cửa sổ mô hình. Dấu trang không sửa phiên gốc. Chỉ mục chỉ bao gồm phiên đã phát hiện; cần cập nhật để tìm tin nhắn mới. Tỷ lệ văn bản lịch sử không phải mức sử dụng thực tế của yêu cầu. Cài đặt cung cấp chẩn đoán cục bộ và xuất JSON/Markdown đã ẩn bí mật. Chỉ mục kiểm tra được chọn mới truy cập tuyến Codex hiện tại hoặc khởi động MCP; không gọi công cụ ghi. Xem [hướng dẫn phiên](https://sakurabytecore.github.io/codexmate/guide/sessions).
36
55
 
56
+ Tạo gói bằng chứng liên phiên từ kết quả chỉ mục, kiểm tra hash nguồn và tải Markdown; tải lại chỉ xóa giỏ tài liệu trong bộ nhớ. Usage có tham khảo chi phí riêng từ bản giá tích hợp có phiên bản của [Wei-Shaw/model-price-repo](https://github.com/Wei-Shaw/model-price-repo), tách dòng chưa rõ khỏi tổng đã biết, không phải hóa đơn và không tự cập nhật qua mạng. Không gian dự án bổ sung trạng thái Git chỉ đọc và thống kê tệp của commit; liên kết trong 24 giờ chỉ là ứng viên theo thời gian, không chứng minh nguyên nhân. Các tính năng không gọi mô hình hay tự gửi phiên. Giá không gồm bậc giá, tầng dịch vụ, thời hạn bộ nhớ đệm, công cụ hoặc đa phương thức.
57
+
58
+ Bộ sưu tập bằng chứng lưu tham chiếu nguồn có tên khi người dùng chọn lưu. Sau khi tải lại, mở thủ công để kiểm tra nguồn; giỏ tạm vẫn bị xóa và không sao lưu toàn bộ phiên. Chi tiết commit có câu chuyện phát triển để liên kết phiên và lý do thay đổi, tách biệt từng dự án. Chỉ ghi siêu dữ liệu cục bộ; không đổi Git, không chứng minh nguồn tạo mã hay kiểm thử đạt. Xem [hướng dẫn phiên](https://sakurabytecore.github.io/codexmate/guide/sessions).
59
+
60
+ Giỏ tài liệu cũng tạo phiếu phát triển và gói tiếp sức đa Agent. Chọn định dạng, nhập mục tiêu và ghi chú tùy chọn, kiểm tra nguồn rồi tải Markdown. Chỉ tổng hợp tài liệu lịch sử: không gọi mô hình, chạy lệnh hay tự gửi; phiên bản hiện tại vẫn cần nghiệm thu. Ghi chú không lưu vào bộ sưu tập và bị xóa khi mở bộ sưu tập.
61
+
37
62
  ---
38
63
 
39
64
  > [!TIP]
@@ -178,9 +203,9 @@ Sau khi tìm lại cuộc trò chuyện, bạn có thể quản lý cấu hình,
178
203
  | **Bridge OpenAI** | ✅ | Chuyển đổi Codex Responses API sang định dạng OpenAI chuẩn |
179
204
  | **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 |
180
205
  | **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. |
181
- | **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. |
206
+ | **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. Tab và lựa chọn tệp đích được lưu và khôi phục sau khi tải lại. Pi giữ tệp đã chọn nếu còn trong danh sách; chỉ chuyển về mục đầu khi tệp không còn và không có bản nháp chưa lưu. Tab Pi liệt kê tệp `.md` trực tiếp trong `~/.pi/agent/` hoặc `<cwd>/.pi/`, cập nhật khi mở tab hoặc danh sách tệp; không tự động nạp prompt. Trang sửa prompt không thêm khoảng trống tải cấu hình, tránh nhảy vị trí cuộn khi quá trình tải hoàn tất. |
182
207
  | **Tích hợp MCP** | ✅ | Expose tool và resource cục bộ qua MCP stdio |
183
- | **Tự động cập nhật** | ✅ | Cập nhật nhanh qua `codexmate update` |
208
+ | **Tự động cập nhật** | ✅ | Nhấp thông báo phiên bản mới trong Web UI để xem phiên bản và sao chép `codexmate update`. Chạy trên máy chủ dịch vụ rồi khởi động lại dịch vụ sau khi cập nhật thành công. Nhấp hoặc sao chép không thực thi cập nhật |
184
209
 
185
210
  ---
186
211
 
package/README.zh.md CHANGED
@@ -30,10 +30,35 @@ Codex Mate 是本地运行的 CLI + Web 管理工具,在一个界面查看、
30
30
 
31
31
  </div>
32
32
 
33
+ ### 用量记录明细
34
+
35
+ 在 Usage 页按需展开 UTC 记录明细,区分记录 Token、缓存分项与完整文本估算。当前适配 Codex、Claude、Pi 与 Gemini JSON 会话;旧图表和默认导出保持原口径,不计算费用。CLI 使用 `codexmate analytics export --attribution records`。详见[用量指南](https://sakurabytecore.github.io/codexmate/guide/sessions#用量记录明细)。
36
+
37
+ ### 文件共享
38
+
39
+ 选择文件或文件夹后手动上传,下载副本或复制 60 分钟有效的局域网文件链接。下载使用独立端口,不授权管理 API;移除批次或停止服务后链接失效,原文件保留。详见[文件共享指南](https://sakurabytecore.github.io/codexmate/guide/web-ui#文件共享)。
40
+
41
+ ### 外观主题
42
+
43
+ 在设置中选择浅色、深色、海洋蓝或柔紫。柔紫参考 [Catppuccin Latte](https://github.com/catppuccin/palette),使用浅底与紫色强调。主题自动保存,刷新后恢复。
44
+
45
+ <a id="路由组"></a>
46
+ ### 模型测试
47
+
48
+ Codex/Pi 子页签选择会保存,刷新后恢复。选择已有配置中的供应商与模型,手动输入问题后发送。查看 Markdown 回复、返回模型 ID 与耗时秒数。测试消耗 API 额度;不启动 CLI、不改配置、不保存测试记录。单次只发一个请求,不自动重试,不设本地响应超时,输出上限 2048 Token。支持配置中的 Responses、Chat Completions、Completions 与 Anthropic Messages;原生登录与命令式凭据暂不接入。Web 已移除模型组设置入口,已有后端分配与 OpenAI Chat API 保持原行为。详见 [Web UI 指南](https://sakurabytecore.github.io/codexmate/guide/web-ui)。
49
+
50
+ 测试请求使用 Codex UA/Originator 或 Pi 的 SDK 请求头,已有自定义 UA 优先。读取 Codex 的推理/输出配置及 Pi 模型的 Token 上限与兼容参数。无法读取客户端版本时使用带版本的 CodexMate 测试标识,不伪造客户端版本。
51
+
33
52
  ### 会话工作台
34
53
 
35
54
  会话页新增消息收藏、备注与标签、本地增量全文索引、带来源证据的交接草稿、只读项目聚合与模型窗口参考。收藏保存在本机,不改原会话;索引仅覆盖已发现候选,新增消息需更新索引;历史文本占比不是实际请求窗口占用。设置页提供本地诊断与脱敏 JSON/Markdown 导出,勾选后才探测当前 Codex 路由或启动选定 MCP,不调用写工具。详见[会话指南](https://sakurabytecore.github.io/codexmate/guide/sessions)。
36
55
 
56
+ 跨会话证据包支持从索引结果累计材料,生成前核对原文哈希,下载 Markdown;刷新只清空新材料篮。Usage 可单独展开费用参考,使用 [Wei-Shaw/model-price-repo](https://github.com/Wei-Shaw/model-price-repo) 的内置版本快照,未知与已知小计分开,不是账单,不自动联网更新。项目工作台新增只读 Git 状态与提交文件统计;前后 24 小时关联仅为时间候选,不证明因果。三项功能不调用模型、不自动发送会话;价格不包含阶梯、服务层、缓存时长或工具及多模态附加费。
57
+
58
+ 证据专题夹可显式保存命名材料引用,刷新后手动打开并复核原文;临时材料篮仍清空,不备份会话全文。Git 提交详情新增开发故事线,手工关联会话与改动原因,保留跨项目隔离;仅写本机元数据,不改 Git,不证明因果或测试通过。详见[会话指南](https://sakurabytecore.github.io/codexmate/guide/sessions)。
59
+
60
+ 材料篮新增开发小票与多 Agent 接力包:选择输出格式,填写目标与可选说明,复核原文后下载 Markdown。只整理历史材料;不调用模型、不执行命令、不自动发送,当前版本仍待验收。说明不保存到专题,打开专题会清空。
61
+
37
62
  ---
38
63
 
39
64
  > [!TIP]
@@ -184,9 +209,9 @@ node cli.js thread ack <thread-id> --handoff <id> --agent <target> --evidence <s
184
209
  | **Pi Provider 配置** | ✅ | 在 Web UI 中管理 Pi 供应商,写入 `~/.pi/agent/models.json`(未知字段无损保留),并切换 `~/.pi/agent/settings.json` 中的默认供应商/模型 |
185
210
  | **Provider 健康检查** | ✅ | 探测本地 Codex/Claude provider 路由,标记失败配置,并安全批量移除已选坏配置 |
186
211
  | **提示词模板** | ✅ | 调用时弹窗填写变量,支持单模板 JSON 分享、插件模板配置历史 Diff 与回滚。`git_diff` 需粘贴差异文本,不执行命令。 |
187
- | **提示词文件编辑器** | ✅ | 编辑全局及项目级 CLAUDE.md / AGENTS.md,支持通用预设池。应用预设先填写变量,只更新编辑器,需手动保存。历史支持版本 Diff;确认回滚后写入所选版本,保留原子备份,校验外部修改。 |
212
+ | **提示词文件编辑器** | ✅ | 编辑全局及项目级 CLAUDE.md / AGENTS.md,支持通用预设池。应用预设先填写变量,只更新编辑器,需手动保存。历史支持版本 Diff;确认回滚后写入所选版本,保留原子备份,校验外部修改。页签和编辑目标选择会保存,刷新后恢复。Pi 文件仍在列表时保留选择;选项失效且无未保存草稿时才回到首项。Pi 页签动态列出 `~/.pi/agent/` 或 `<cwd>/.pi/` 直属 `.md`,进入页签或展开文件列表时更新;不自动加载提示词。 提示词页不显示配置加载占位,避免加载完成后页面缩短导致滚动回跳。 |
188
213
  | **MCP 集成** | ✅ | 通过 MCP stdio 暴露本地工具与资源 |
189
- | **自动更新** | ✅ | 通过 `codexmate update` 快速更新 CLI |
214
+ | **自动更新** | ✅ | 点击 Web UI 的新版本提示,弹窗查看版本与复制 `codexmate update`;在服务主机终端执行,更新成功后重启服务。点击与复制不执行更新 |
190
215
 
191
216
  ---
192
217
 
@@ -19,6 +19,10 @@ function parseAnalyticsExportArgs(args = []) {
19
19
  options.format = String(readValue('--format') || '').trim().toLowerCase();
20
20
  continue;
21
21
  }
22
+ if (token === '--attribution' || token.startsWith('--attribution=')) {
23
+ options.attribution = String(readValue('--attribution') || '').trim().toLowerCase();
24
+ continue;
25
+ }
22
26
  if (token === '--from' || token.startsWith('--from=')) {
23
27
  options.from = String(readValue('--from') || '').trim();
24
28
  continue;
@@ -54,6 +58,9 @@ function parseAnalyticsExportArgs(args = []) {
54
58
  if (options.format !== 'csv' && options.format !== 'json') {
55
59
  errors.push('--format 必须是 csv 或 json');
56
60
  }
61
+ if (options.attribution !== undefined && !['session', 'records'].includes(options.attribution)) {
62
+ errors.push('--attribution 必须是 session 或 records');
63
+ }
57
64
  if (options.source && !['codex', 'claude', 'gemini', 'codebuddy', 'pi', 'all'].includes(options.source)) {
58
65
  errors.push('--source 必须是 codex、claude、gemini、codebuddy、pi 或 all');
59
66
  }
@@ -14,7 +14,7 @@ const {
14
14
  parseJsonOrError,
15
15
  extractChatCompletionResult,
16
16
  buildResponsesPayloadFromChatResult,
17
- retryTransientRequest,
17
+ retryTransientRequest: retryBridgeRequest,
18
18
  shouldFallbackFromUpstreamResponses,
19
19
  isTransientNetworkError,
20
20
  isLoopbackAddress
@@ -109,11 +109,14 @@ function buildUpstreamPool(readConfigFn, openaiBridgeFile, excludedProviders) {
109
109
  return { pool };
110
110
  }
111
111
 
112
- function buildClaudeUpstreamPool(claudeProvidersFile, excludedProviders) {
112
+ function buildClaudeUpstreamPool(claudeProvidersFile, excludedProviders, readProviders) {
113
113
  let raw;
114
114
  try {
115
- if (!fs.existsSync(claudeProvidersFile)) return { error: '暂无可用上游 provider,请先添加 Claude 提供商' };
116
- raw = JSON.parse(fs.readFileSync(claudeProvidersFile, 'utf-8'));
115
+ if (readProviders) raw = readProviders();
116
+ else {
117
+ if (!fs.existsSync(claudeProvidersFile)) return { error: '暂无可用上游 provider,请先添加 Claude 提供商' };
118
+ raw = JSON.parse(fs.readFileSync(claudeProvidersFile, 'utf-8'));
119
+ }
117
120
  } catch (e) { return { error: '读取 Claude 提供商配置失败' }; }
118
121
  const providers = (raw && typeof raw.providers === 'object' && !Array.isArray(raw.providers))
119
122
  ? raw.providers : {};
@@ -157,6 +160,7 @@ function resolveUpstreamAuth(entry, openaiBridgeFile, reqAuthToken) {
157
160
 
158
161
  function createLocalBridgeHttpHandler(options = {}) {
159
162
  const readConfigFn = options.readConfigFn;
163
+ const retryTransientRequest = executor => retryBridgeRequest(executor, { maxRetries: options.requestMaxRetries });
160
164
  const openaiBridgeFile = options.openaiBridgeFile;
161
165
  const claudeProvidersFile = options.claudeProvidersFile || '';
162
166
  const expectedToken = typeof options.expectedToken === 'string' ? options.expectedToken.trim() : '';
@@ -314,7 +318,7 @@ function createLocalBridgeHttpHandler(options = {}) {
314
318
  return;
315
319
  }
316
320
 
317
- const poolResult = buildClaudeUpstreamPool(claudeProvidersFile, readClaudeExcludedProviders());
321
+ const poolResult = buildClaudeUpstreamPool(claudeProvidersFile, readClaudeExcludedProviders(), options.readClaudeProviders);
318
322
  if (poolResult.error) {
319
323
  res.writeHead(503, { 'Content-Type': 'application/json; charset=utf-8' });
320
324
  res.end(JSON.stringify({ error: poolResult.error }));
@@ -752,4 +756,4 @@ function createLocalBridgeHttpHandler(options = {}) {
752
756
  return handler;
753
757
  }
754
758
 
755
- module.exports = { createLocalBridgeHttpHandler };
759
+ module.exports = { createLocalBridgeHttpHandler, buildUpstreamPool, buildClaudeUpstreamPool };
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+ const http = require('http');
3
+ const https = require('https');
4
+ const { pipeline } = require('stream');
5
+ const { joinApiUrl } = require('../lib/cli-utils');
6
+ const UPSTREAM_IDLE_TIMEOUT_MS = 300000;
7
+
8
+ function createOpenaiChatRoutingHandler({ member, authorization, upstreamHeaders, httpAgent, httpsAgent }) {
9
+ return (req, res) => {
10
+ const url = new URL(joinApiUrl(member.baseUrl, 'chat/completions'));
11
+ const transport = url.protocol === 'https:' ? https : http;
12
+ const headers = { ...upstreamHeaders, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', 'X-Codexmate-Routing-Hop': '1' };
13
+ if (authorization) headers.Authorization = authorization;
14
+ const upstream = transport.request(url, {
15
+ method: 'POST', headers, agent: url.protocol === 'https:' ? httpsAgent : httpAgent
16
+ }, response => {
17
+ res.writeHead(response.statusCode, {
18
+ 'Content-Type': response.headers['content-type'] || 'application/json',
19
+ 'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'
20
+ });
21
+ if (response.statusCode < 400 && typeof res.flushHeaders === 'function') res.flushHeaders();
22
+ pipeline(response, res, error => { if (error) res.destroy(error); });
23
+ });
24
+ const abort = () => upstream.destroy();
25
+ res.once('close', abort);
26
+ res.once('finish', () => res.removeListener('close', abort));
27
+ upstream.setTimeout(UPSTREAM_IDLE_TIMEOUT_MS, () => upstream.destroy(new Error('Upstream timeout')));
28
+ upstream.once('error', () => {
29
+ if (res.destroyed) return;
30
+ if (res.headersSent) { res.destroy(); return; }
31
+ res.writeHead(502, { 'Content-Type': 'application/json' });
32
+ res.end(JSON.stringify({ error: { message: 'OpenAI Chat upstream request failed', type: 'api_error', code: null, param: null } }));
33
+ });
34
+ req.pipe(upstream);
35
+ return true;
36
+ };
37
+ }
38
+ module.exports = { createOpenaiChatRoutingHandler };
@@ -0,0 +1,143 @@
1
+ 'use strict';
2
+ const { PassThrough, Writable } = require('stream');
3
+ const { readRequestBody, extractAuthorizationToken, isLoopbackAddress } = require('./openai-bridge');
4
+ const { createRoutingScheduler, OPENAI_CHAT_TARGET } = require('../lib/routing-groups');
5
+ const OPENAI_CHAT_BASE_PATH = '/bridge/openai-chat/v1';
6
+ const OPENAI_CHAT_MODEL = 'routing';
7
+
8
+ const JSON_HEADERS = { 'Content-Type': 'application/json; charset=utf-8' };
9
+ const MAX_ERROR_BYTES = 1024 * 1024;
10
+ function isRetryStatus(status) {
11
+ return status === 408 || status === 429 || (status >= 500 && status <= 599);
12
+ }
13
+ function sendError(res, status, message) {
14
+ res.writeHead(status, JSON_HEADERS);
15
+ res.end(JSON.stringify({ error: message }));
16
+ }
17
+ function sendChatError(res, status, message) {
18
+ res.writeHead(status, { ...JSON_HEADERS, ...(status === 401 ? { 'WWW-Authenticate': 'Bearer' } : {}) });
19
+ res.end(JSON.stringify({ error: { message, type: status < 500 ? 'invalid_request_error' : 'api_error', code: null, param: null } }));
20
+ }
21
+ function forwardAttempt({ handler, req, res, body }) {
22
+ return new Promise((resolve, reject) => {
23
+ let status = 200;
24
+ let headers = {};
25
+ let bytes = 0;
26
+ const chunks = [];
27
+ const replay = new PassThrough();
28
+ Object.assign(replay, { method: req.method, url: req.url, headers: req.headers, socket: req.socket });
29
+ const commit = () => { if (!res.headersSent) res.writeHead(status, headers); };
30
+ const sink = new Writable({
31
+ write(chunk, encoding, callback) {
32
+ if (!res.headersSent && isRetryStatus(status)) {
33
+ bytes += chunk.length;
34
+ if (bytes <= MAX_ERROR_BYTES) chunks.push(Buffer.from(chunk));
35
+ callback();
36
+ return;
37
+ }
38
+ commit();
39
+ res.write(chunk, encoding, callback);
40
+ },
41
+ final(callback) {
42
+ if (res.headersSent || !isRetryStatus(status)) {
43
+ commit();
44
+ res.end();
45
+ }
46
+ callback();
47
+ }
48
+ });
49
+ Object.defineProperty(sink, 'headersSent', { get: () => res.headersSent });
50
+ sink.writeHead = (code, responseHeaders = {}) => { status = code; headers = responseHeaders; return sink; };
51
+ sink.flushHeaders = () => { if (!isRetryStatus(status)) { commit(); if (res.flushHeaders) res.flushHeaders(); } };
52
+ const cancel = () => { replay.destroy(); sink.destroy(); };
53
+ res.once('close', cancel);
54
+ sink.once('error', reject);
55
+ sink.once('finish', () => {
56
+ res.removeListener('close', cancel);
57
+ resolve({ status, headers, body: Buffer.concat(chunks) });
58
+ });
59
+ sink.once('close', () => {
60
+ res.removeListener('close', cancel);
61
+ if (res.destroyed) resolve({ status, headers, body: Buffer.alloc(0) });
62
+ });
63
+ if (!handler(replay, sink)) { reject(new Error('Routing bridge path was not handled')); return; }
64
+ replay.end(body);
65
+ });
66
+ }
67
+
68
+ function createRoutingBridgeHttpHandler({ groups, createHandler, maxBodySize, expectedToken = '' }) {
69
+ const schedule = createRoutingScheduler();
70
+ async function serve(req, res, group) {
71
+ const send = group.target === OPENAI_CHAT_TARGET ? sendChatError : sendError;
72
+ const bodyResult = await readRequestBody(req, maxBodySize);
73
+ if (bodyResult.error) { send(res, 413, bodyResult.error); return; }
74
+ let payload;
75
+ if (bodyResult.body && bodyResult.body.trim()) {
76
+ try { payload = JSON.parse(bodyResult.body); }
77
+ catch (_) { send(res, 400, 'Invalid JSON request'); return; }
78
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
79
+ send(res, 400, 'Invalid request payload'); return;
80
+ }
81
+ }
82
+ if (group.target === OPENAI_CHAT_TARGET && (!payload || payload.model !== OPENAI_CHAT_MODEL || !Array.isArray(payload.messages) || !payload.messages.length)) {
83
+ send(res, 400, "Use model 'routing' and a non-empty messages array");
84
+ return;
85
+ }
86
+ const members = schedule(group);
87
+ for (const member of members) {
88
+ if (res.destroyed || req.aborted) return;
89
+ const body = payload ? JSON.stringify({ ...payload, model: member.model }) : bodyResult.body;
90
+ const outcome = await forwardAttempt({ handler: createHandler(group.target, member), req, res, body });
91
+ if (res.headersSent || res.destroyed) return;
92
+ if (!isRetryStatus(outcome.status) || member === members[members.length - 1]) {
93
+ res.writeHead(outcome.status, { ...outcome.headers, 'Content-Length': outcome.body.length });
94
+ res.end(outcome.body);
95
+ return;
96
+ }
97
+ }
98
+ }
99
+ return (req, res) => {
100
+ const pathname = (req.url || '').split('?')[0];
101
+ const isChat = pathname === OPENAI_CHAT_BASE_PATH || pathname.startsWith(OPENAI_CHAT_BASE_PATH + '/');
102
+ const target = isChat ? OPENAI_CHAT_TARGET : pathname.startsWith('/bridge/claude-local/') ? 'claude'
103
+ : pathname.startsWith('/bridge/local/v1') ? 'codex' : '';
104
+ if (!target) return false;
105
+ const fail = (status, message) => (isChat ? sendChatError : sendError)(res, status, message);
106
+ const isLoopback = isLoopbackAddress(req.socket && req.socket.remoteAddress);
107
+ const authorize = () => {
108
+ if (!isLoopback && !expectedToken) { fail(403, 'Remote access is disabled'); return false; }
109
+ const requiresToken = !isLoopback || isChat && !!expectedToken;
110
+ if (requiresToken && extractAuthorizationToken(req) !== expectedToken) { fail(401, 'Unauthorized'); return false; }
111
+ return true;
112
+ };
113
+ if (isChat && !authorize()) return true;
114
+ if (isChat && req.headers['x-codexmate-routing-hop']) { fail(508, 'Nested OpenAI routing is not supported'); return true; }
115
+ if (isChat) {
116
+ const method = req.method || 'GET';
117
+ if (pathname !== OPENAI_CHAT_BASE_PATH + '/models' && pathname !== OPENAI_CHAT_BASE_PATH + '/chat/completions') {
118
+ fail(404, 'Unsupported OpenAI Chat path'); return true;
119
+ }
120
+ const allowedMethod = pathname.endsWith('/models') ? 'GET' : 'POST';
121
+ if (method !== allowedMethod) { res.setHeader('Allow', allowedMethod); fail(405, 'Method Not Allowed'); return true; }
122
+ }
123
+ let group;
124
+ try { group = groups.resolve(target); }
125
+ catch (_) { fail(503, 'Routing group unavailable; check its providers and configuration'); return true; }
126
+ if (!group) {
127
+ if (isChat) { fail(503, 'Enable an OpenAI Chat group first'); return true; }
128
+ return false;
129
+ }
130
+ if (!isChat && !authorize()) return true;
131
+ if (isChat && pathname.endsWith('/models')) {
132
+ res.writeHead(200, JSON_HEADERS);
133
+ res.end(JSON.stringify({ object: 'list', data: [{ id: OPENAI_CHAT_MODEL, object: 'model', created: 0, owned_by: 'codexmate' }] }));
134
+ return true;
135
+ }
136
+ void serve(req, res, group).catch(() => {
137
+ if (res.headersSent) res.destroy();
138
+ else if (!res.destroyed) fail(502, 'Routing upstream request failed');
139
+ });
140
+ return true;
141
+ };
142
+ }
143
+ module.exports = { createRoutingBridgeHttpHandler, OPENAI_CHAT_BASE_PATH, OPENAI_CHAT_MODEL };
@@ -309,5 +309,8 @@ module.exports = {
309
309
  listSessionUsageCore,
310
310
  buildUsageExportRows,
311
311
  exportSessionUsageCore,
312
- serializeUsageExportRowsToCsv
312
+ serializeUsageExportRowsToCsv,
313
+ parseUsageExportDate,
314
+ normalizeUsageExportModelFilters,
315
+ sessionMatchesUsageExportModelFilters
313
316
  };
@@ -29,6 +29,8 @@ function createSystemPromptFileController(deps = {}) {
29
29
  };
30
30
 
31
31
  const SCOPES = ['global', 'project'];
32
+ const MAX_PROMPT_BYTES = 2 * 1024 * 1024;
33
+ const READ_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0);
32
34
 
33
35
  function normalizeMode(mode) {
34
36
  const key = typeof mode === 'string' ? mode.trim() : '';
@@ -56,45 +58,60 @@ function createSystemPromptFileController(deps = {}) {
56
58
  return crypto.createHash('sha256').update(String(content || '')).digest('hex');
57
59
  }
58
60
 
59
- function resolveSystemPromptFilePath(params = {}) {
61
+ function isValidFileName(filename) {
62
+ return typeof filename === 'string' && filename.length > 3
63
+ && filename === filename.trim() && filename.endsWith('.md')
64
+ && !/[\\/\0]/.test(filename) && path.basename(filename) === filename;
65
+ }
66
+
67
+ function resolveSystemPromptDirectory(params) {
60
68
  const scope = normalizeScope(params.scope);
61
- const mode = normalizeMode(params.mode);
62
- const filename = MODES[mode];
63
- let base;
64
- if (scope === 'global') {
65
- base = PI_AGENT_DIR;
66
- } else {
67
- const cwd = typeof params.cwd === 'string' && params.cwd.trim()
68
- ? params.cwd.trim()
69
- : process.cwd();
70
- base = path.join(path.resolve(cwd), '.pi');
69
+ const cwd = typeof params.cwd === 'string' && params.cwd.trim() ? params.cwd.trim() : process.cwd();
70
+ return { scope, directory: scope === 'global' ? path.resolve(PI_AGENT_DIR) : path.join(path.resolve(cwd), '.pi') };
71
+ }
72
+
73
+ function resolveSystemPromptFilePath(params = {}) {
74
+ const { scope, directory } = resolveSystemPromptDirectory(params);
75
+ const hasFileName = Object.prototype.hasOwnProperty.call(params, 'fileName');
76
+ if (hasFileName && !isValidFileName(params.fileName)) {
77
+ throw new Error('Invalid system prompt filename: expected a direct .md file');
71
78
  }
72
- return {
73
- scope,
74
- mode,
75
- filename,
76
- path: path.join(base, filename),
77
- replaceDefault: mode === 'system'
78
- };
79
+ const requestedMode = normalizeMode(hasFileName ? (params.mode || 'system') : params.mode);
80
+ const filename = hasFileName ? params.fileName : MODES[requestedMode];
81
+ const mode = filename === MODES.append ? 'append' : (filename === MODES.system ? 'system' : requestedMode);
82
+ return { scope, mode, filename, path: path.join(directory, filename), replaceDefault: filename === MODES.system };
79
83
  }
80
84
 
81
- function readSystemPromptFile(params = {}) {
82
- const target = resolveSystemPromptFilePath(params);
83
- const exists = fs.existsSync(target.path);
84
- let content = '';
85
- if (exists) {
86
- try {
87
- content = fs.readFileSync(target.path, 'utf8');
88
- } catch (e) {
89
- return { ...target, exists: false, content: '', hash: hashContent(''), error: '读取 system prompt 失败: ' + e.message };
85
+ function systemHistoryBucket(target) {
86
+ if (!Object.values(MODES).includes(target.filename)) return 'system_file_' + hashContent(target.path);
87
+ return 'system_' + target.scope + '_' + (target.scope === 'project'
88
+ ? sanitizeSystemHistoryId(path.dirname(target.path)) : 'global');
89
+ }
90
+
91
+ function listSystemPromptFiles(params = {}) {
92
+ const { scope, directory } = resolveSystemPromptDirectory(params);
93
+ try {
94
+ let entries;
95
+ try { entries = fs.readdirSync(directory, { withFileTypes: true }); }
96
+ catch (error) { if (error.code !== 'ENOENT') throw error; entries = []; }
97
+ const files = entries.filter(entry => entry.isFile() && isValidFileName(entry.name))
98
+ .map(entry => ({ filename: entry.name, path: path.join(directory, entry.name), exists: true }));
99
+ for (const filename of Object.values(MODES)) {
100
+ if (!entries.some(entry => entry.name === filename)) {
101
+ files.push({ filename, path: path.join(directory, filename), exists: false });
102
+ }
90
103
  }
91
- }
92
- return {
93
- ...target,
94
- exists,
95
- content,
96
- hash: hashContent(content)
97
- };
104
+ const order = Object.values(MODES);
105
+ files.sort((left, right) => {
106
+ const rank = name => order.includes(name) ? order.indexOf(name) : order.length;
107
+ return rank(left.filename) - rank(right.filename) || left.filename.localeCompare(right.filename);
108
+ });
109
+ return { scope, directory, files };
110
+ } catch (error) { return { scope, directory, files: [], error: '读取 Pi 文件列表失败: ' + error.message }; }
111
+ }
112
+
113
+ function readSystemPromptFile(params = {}) {
114
+ return readSystemPromptFilePath(resolveSystemPromptFilePath(params));
98
115
  }
99
116
 
100
117
  function saveSystemPromptFile(params = {}) {
@@ -102,14 +119,20 @@ function createSystemPromptFileController(deps = {}) {
102
119
  if (!content.trim()) {
103
120
  return { error: 'System prompt 不能为空' };
104
121
  }
105
- if (content.length > 2 * 1024 * 1024) {
122
+ if (content.length > MAX_PROMPT_BYTES) {
106
123
  return { error: '内容过大(最大 2MB)' };
107
124
  }
108
125
  const target = resolveSystemPromptFilePath(params);
126
+ if (!Object.values(MODES).includes(target.filename) && Buffer.byteLength(content, 'utf8') > MAX_PROMPT_BYTES) {
127
+ return { error: '内容过大(最大 2MB)' };
128
+ }
109
129
  const current = readSystemPromptFilePath(target);
110
130
  if (current.error) {
111
131
  return { error: current.error };
112
132
  }
133
+ if (!Object.values(MODES).includes(target.filename) && !current.exists) {
134
+ return { error: '文件不存在,请刷新文件列表' };
135
+ }
113
136
  const baseHash = typeof params.baseHash === 'string' ? params.baseHash.trim() : '';
114
137
  if (baseHash && baseHash !== current.hash) {
115
138
  return { error: '文件已被外部修改,请重新加载后再保存' };
@@ -119,9 +142,7 @@ function createSystemPromptFileController(deps = {}) {
119
142
  const dir = path.dirname(target.path);
120
143
  fs.mkdirSync(dir, { recursive: true });
121
144
  if (typeof backupPromptBeforeWrite === 'function') {
122
- const bucket = 'system_' + target.scope + '_' + (target.scope === 'project'
123
- ? sanitizeSystemHistoryId(path.dirname(target.path))
124
- : 'global');
145
+ const bucket = systemHistoryBucket(target);
125
146
  const backup = backupPromptBeforeWrite(bucket, target.path);
126
147
  if (backup && backup.error) return { error: backup.error };
127
148
  sysHistoryBucket = bucket;
@@ -138,23 +159,22 @@ function createSystemPromptFileController(deps = {}) {
138
159
  }
139
160
 
140
161
  function readSystemPromptFilePath(resolved) {
141
- const exists = fs.existsSync(resolved.path);
162
+ let exists = false;
142
163
  let content = '';
143
- if (exists) {
144
- try {
145
- content = fs.readFileSync(resolved.path, 'utf8');
146
- } catch (e) {
147
- return { ...resolved, exists: false, content: '', hash: hashContent(''), error: '读取 system prompt 失败: ' + e.message };
164
+ try {
165
+ const stat = fs.lstatSync(resolved.path);
166
+ if (!stat.isFile()) throw new Error('目标必须是普通 .md 文件,不能使用符号链接');
167
+ if (!Object.values(MODES).includes(resolved.filename) && stat.size > MAX_PROMPT_BYTES) {
168
+ throw new Error('内容过大(最大 2MB)');
169
+ }
170
+ content = fs.readFileSync(resolved.path, { encoding: 'utf8', flag: READ_FLAGS });
171
+ exists = true;
172
+ } catch (error) {
173
+ if (error.code !== 'ENOENT') {
174
+ return { ...resolved, exists: false, content: '', hash: hashContent(''), error: '读取 system prompt 失败: ' + error.message };
148
175
  }
149
176
  }
150
- return {
151
- ...resolved,
152
- historyBucket: 'system_' + resolved.scope + '_' + (resolved.scope === 'project'
153
- ? sanitizeSystemHistoryId(path.dirname(resolved.path)) : 'global'),
154
- exists,
155
- content,
156
- hash: hashContent(content)
157
- };
177
+ return { ...resolved, historyBucket: systemHistoryBucket(resolved), exists, content, hash: hashContent(content) };
158
178
  }
159
179
 
160
180
  function buildSystemPromptDiff(params = {}) {
@@ -182,11 +202,13 @@ function createSystemPromptFileController(deps = {}) {
182
202
  path: target.path,
183
203
  exists: current.exists,
184
204
  scope: target.scope,
185
- mode: target.mode
205
+ mode: target.mode,
206
+ filename: target.filename
186
207
  };
187
208
  }
188
209
 
189
210
  return {
211
+ listSystemPromptFiles,
190
212
  readSystemPromptFile,
191
213
  saveSystemPromptFile,
192
214
  buildSystemPromptDiff,