cladogram 0.6.0-beta.1 → 0.6.0-beta.10

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 (39) hide show
  1. package/README.md +50 -47
  2. package/bin/clado.js +34 -2
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +116 -0
  6. package/package.json +3 -1
  7. package/plugins/agent/index.js +2429 -723
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1327 -94
  10. package/plugins/view-controls/index.js +0 -11
  11. package/plugins/view-controls/style.css +7 -14
  12. package/skills/clado/SKILL.md +4 -2
  13. package/src/agent/automations.js +454 -0
  14. package/src/agent/clado-tools.js +597 -104
  15. package/src/agent/pi-bridge.js +2184 -112
  16. package/src/agent/pi-config.js +1889 -108
  17. package/src/agent/pi-hooks-perms.js +621 -0
  18. package/src/html/app-css.js +69 -1
  19. package/src/html/canvas-chain.js +32 -6
  20. package/src/html/canvas-focus.js +19 -13
  21. package/src/html/canvas-live-diff.js +1373 -0
  22. package/src/html/canvas-ui.css +503 -2
  23. package/src/html/canvas-wires.js +5 -1
  24. package/src/html/page.js +4 -2
  25. package/src/html/plugin-assets.js +5 -1
  26. package/src/html/plugin-ui.css +1 -1
  27. package/src/html/runtime-api.js +152 -10
  28. package/src/html/runtime.js +546 -37
  29. package/src/server/agent.js +594 -37
  30. package/src/server/assets/library-canvas.js +256 -9
  31. package/src/server/assets/library.css +567 -12
  32. package/src/server/assets/library.html +2 -0
  33. package/src/server/assets/library.js +1028 -32
  34. package/src/server/code-inspect.js +183 -0
  35. package/src/server/mcp.js +90 -22
  36. package/src/server/plugin-registry.js +664 -2
  37. package/src/server/workspace.js +551 -25
  38. package/src/workspace/graph-snapshot.js +695 -0
  39. package/src/workspace/service.js +201 -9
@@ -12,8 +12,10 @@
12
12
  * - <workspace>/AGENTS.md — 项目记忆与工程规范
13
13
  */
14
14
 
15
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
16
- import { join, resolve } from 'node:path';
15
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
16
+ import { homedir } from 'node:os';
17
+ import { dirname, join, relative, resolve } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
17
19
  import {
18
20
  DefaultPackageManager,
19
21
  DefaultResourceLoader,
@@ -21,6 +23,26 @@ import {
21
23
  ModelRuntime,
22
24
  SettingsManager,
23
25
  } from '@earendil-works/pi-coding-agent';
26
+ import {
27
+ hooksFilePath,
28
+ permissionsFilePath,
29
+ saveHooksRawJson,
30
+ savePermissionsRawJson,
31
+ } from './pi-hooks-perms.js';
32
+
33
+ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
34
+ const PACKAGE_CONTEXT_DOC_PATH = join(PKG_ROOT, 'docs', 'agent-context.md');
35
+ const PACKAGE_REFERENCE_DOC_PATH = join(PKG_ROOT, 'docs', 'agent-reference.md');
36
+
37
+ function readPackageDoc(filePath, fallback = '') {
38
+ try {
39
+ return existsSync(filePath) ? readFileSync(filePath, 'utf8') : fallback;
40
+ } catch {
41
+ return fallback;
42
+ }
43
+ }
44
+
45
+ export const CLADO_CANVAS_MASTERY_GUIDE = readPackageDoc(PACKAGE_CONTEXT_DOC_PATH);
24
46
 
25
47
  export const BUILTIN_ROLES = [
26
48
  {
@@ -29,11 +51,14 @@ export const BUILTIN_ROLES = [
29
51
  phase: '设计阶段',
30
52
  tone: 'sky',
31
53
  builtin: true,
32
- description: '分析老代码、梳理方案边界、在画布上反复迭代直到定稿。',
54
+ description: '分析现状代码、梳理模块边界与核心契约、设计清晰可扩展的端到端技术方案并推动定稿。',
33
55
  systemPrompt: [
34
- '你是 Clado 工作台中的「主架构师」角色。',
35
- '你的核心工作:深入阅读仓库源码与用户需求,通过 clado_* 工具在空间画布上梳理清晰的模块化架构卡片、接口契约、语义标签与依赖连线,并与用户反复迭代直到方案定稿。',
36
- '遇到存在多个合理方案或关键边界需要拍板时,主动调用 ask_user 给出简洁清晰的选项卡片让用户确认。',
56
+ '你是「主架构师」,专注于系统架构设计、模块边界梳理与技术方案评审。',
57
+ '你的核心工作流程:',
58
+ '1. **摸清现状**:动手设计前先核查真实源码、入口边界、数据模型与上下游依赖,避免凭空猜测。',
59
+ '2. **端到端方案设计**:从入口触发、核心编排与并行分支、领域处理到持久化与外部依赖,梳理清晰的职责划分、数据流向、异常边界与演进权衡;明确标出新增、变更与潜在风险点。',
60
+ '3. **保持设计简洁克制**:优先选择低耦合、易验证的方案,避免过度抽象与循环依赖。',
61
+ '4. **关键决策拍板**:存在多个合理方案或重大边界取舍时,先完整阐述利弊与推荐理由,再请用户确认方向。',
37
62
  ].join('\n'),
38
63
  },
39
64
  {
@@ -42,11 +67,14 @@ export const BUILTIN_ROLES = [
42
67
  phase: '交付阶段',
43
68
  tone: 'emerald',
44
69
  builtin: true,
45
- description: '接收画布定稿契约,直接通过 Pi 修改工程代码并运行校验。',
70
+ description: '对照设计契约精准落地代码、补齐边界处理、运行构建与测试校验并同步交付事实。',
46
71
  systemPrompt: [
47
- '你是 Clado 工作台中的「开发落地」角色。',
48
- '你的核心工作:依据用户或主架构师交付的画布卡片与契约规范,直接使用 read / edit / write / bash 工具完成真实代码实现、编译与运行检查,并在必要时把实际实现细节回写同步到画布卡片上。',
49
- '保持改动精准克制,完成后向用户清晰汇报修改了哪些文件及校验结果。',
72
+ '你是「开发落地」工程师,专注于高质量代码实现、边界处理与工程验证。',
73
+ '你的核心工作流程:',
74
+ '1. **先读设计契约与上下文**:开工前先理解目标方案的入口契约、核心数据流、修改范围与风险点。',
75
+ '2. **精准实现**:改动克制聚焦,遵循项目既有风格与约束,妥善处理空值、并发、超时与错误恢复,不引入无关重构。',
76
+ '3. **真实验证**:实现完成后务必实际运行构建、静态检查与相关测试,核对真实输出;遇到失败立即定位修复。',
77
+ '4. **同步与交付**:若落地细节较原设计有调整,及时同步更新文档事实,并清晰汇报改动文件与验证结果。',
50
78
  ].join('\n'),
51
79
  },
52
80
  {
@@ -55,10 +83,14 @@ export const BUILTIN_ROLES = [
55
83
  phase: '验收阶段',
56
84
  tone: 'violet',
57
85
  builtin: true,
58
- description: '依据画布契约生成单测与回归用例,执行验证并回写通过状态。',
86
+ description: '梳理关键路径与异常边界、编写高信噪比自动化测试、真实执行验证并沉淀验收结论。',
59
87
  systemPrompt: [
60
- '你是 Clado 工作台中的「测试验证」角色。',
61
- '你的核心工作:对照画布上的模块契约与边界条件,编写或补充单元测试、集成测试与异常分支用例,运行测试命令并核对结果,将未覆盖风险或验收通过状态反馈回画布。',
88
+ '你是「测试验证」工程师,专注于质量保障、边界挖掘与自动化回归测试。',
89
+ '你的核心工作流程:',
90
+ '1. **全路径查漏**:沿核心主流程、分支条件、并发竞争、权限与异常出口梳理测试矩阵,识别高风险薄弱点。',
91
+ '2. **编写高价值测试**:优先覆盖行为契约与真实回归场景,断言清晰独立、不依赖脆弱实现细节。',
92
+ '3. **真实执行验收**:实际运行测试套件并核对真实通过/失败结果;未执行的验证绝不可宣称为通过。',
93
+ '4. **沉淀验收结论**:清晰记录已覆盖路径、失败复现步骤与遗留风险,辅助团队决策发布。',
62
94
  ].join('\n'),
63
95
  },
64
96
  {
@@ -67,29 +99,223 @@ export const BUILTIN_ROLES = [
67
99
  phase: '文档阶段',
68
100
  tone: 'amber',
69
101
  builtin: true,
70
- description: '将定稿画布与代码变更沉淀为 README / ADR / 变更记录。',
102
+ description: '核对已落地事实与设计文档、清理过时信息、沉淀高质量系统现状文档、ADR 与变更记录。',
71
103
  systemPrompt: [
72
- '你是 Clado 工作台中的「归档整理」角色。',
73
- '你的核心工作:将已经定稿和落地的画布设计、关键决策和代码变更整理沉淀为结构清晰的架构文档、ADR 决策记录或发布说明。',
104
+ '你是「归档整理」专家,专注于技术文档沉淀、事实核对与知识结构化归档。',
105
+ '你的核心工作流程:',
106
+ '1. **事实核对**:以真实代码与已验证行为为准,严格区分「已落地现状」与「未实现提案」,绝不把提案写成事实。',
107
+ '2. **去冗提纯**:清理过时描述与矛盾表述,确保模块职责、关键契约、配置项与排障入口准确可查。',
108
+ '3. **结构化沉淀**:输出条理清晰的现状文档、架构决策记录(ADR)或版本变更说明,方便团队长期维护。',
74
109
  ].join('\n'),
75
110
  },
76
111
  ];
77
112
 
78
113
  export const PROVIDER_CATALOG = [
79
- { id: 'anthropic', name: 'Anthropic · Claude', api: 'anthropic-messages', defaultBaseUrl: 'https://api.anthropic.com', envKey: 'ANTHROPIC_API_KEY', defaultModel: 'claude-sonnet-4-5', hint: 'claude-sonnet-4-5 / claude-opus-4-5' },
80
- { id: 'openai', name: 'OpenAI', api: 'openai-responses', defaultBaseUrl: 'https://api.openai.com/v1', envKey: 'OPENAI_API_KEY', defaultModel: 'gpt-5.4', hint: 'gpt-5.4 / gpt-5.3-codex / o3' },
81
- { id: 'deepseek', name: 'DeepSeek', api: 'openai-completions', defaultBaseUrl: 'https://api.deepseek.com/v1', envKey: 'DEEPSEEK_API_KEY', defaultModel: 'deepseek-chat', hint: 'deepseek-chat / deepseek-reasoner' },
82
- { id: 'google', name: 'Google · Gemini', api: 'google-generative-ai', defaultBaseUrl: 'https://generativelanguage.googleapis.com/v1beta', envKey: 'GEMINI_API_KEY', defaultModel: 'gemini-2.5-pro', hint: 'gemini-2.5-pro / gemini-2.5-flash' },
83
- { id: 'openrouter', name: 'OpenRouter', api: 'openai-completions', defaultBaseUrl: 'https://openrouter.ai/api/v1', envKey: 'OPENROUTER_API_KEY', defaultModel: 'anthropic/claude-sonnet-4.5', hint: '多模型统一聚合网关' },
84
- { id: 'ollama', name: '本地模型 · Ollama', api: 'openai-completions', defaultBaseUrl: 'http://127.0.0.1:11434/v1', envKey: '', defaultModel: 'qwen2.5-coder:14b', hint: 'http://127.0.0.1:11434/v1 · 离线零延迟', keyless: true },
85
- { id: 'custom-openai', name: '自定义代理(OpenAI 兼容)', api: 'openai-completions', defaultBaseUrl: '', envKey: '', defaultModel: '', hint: '填写任意中转站或自建网关 Base URL' },
86
- { id: 'custom-anthropic', name: '自定义代理(Anthropic 兼容)', api: 'anthropic-messages', defaultBaseUrl: '', envKey: '', defaultModel: '', hint: '填写 Anthropic 协议中转站 Base URL' },
114
+ {
115
+ id: 'deepseek',
116
+ name: 'DeepSeek',
117
+ api: 'openai-completions',
118
+ defaultBaseUrl: 'https://api.deepseek.com',
119
+ envKey: 'DEEPSEEK_API_KEY',
120
+ defaultModel: 'deepseek-flash',
121
+ defaultContextWindow: 1000000,
122
+ defaultMaxTokens: 384000,
123
+ hint: 'deepseek-flash (V4.1 · 1M) / deepseek-v4-pro (1M)',
124
+ recommendedModels: [
125
+ { id: 'deepseek-flash', label: 'DeepSeek V4.1 Flash (1M · 思考/视觉)', contextWindow: 1000000, maxTokens: 384000, reasoning: true },
126
+ { id: 'deepseek-v4-pro', label: 'DeepSeek V4 Pro (1M · 深度推理)', contextWindow: 1000000, maxTokens: 384000, reasoning: true },
127
+ ],
128
+ },
129
+ {
130
+ id: 'anthropic',
131
+ name: 'Anthropic · Claude',
132
+ api: 'anthropic-messages',
133
+ defaultBaseUrl: 'https://api.anthropic.com',
134
+ envKey: 'ANTHROPIC_API_KEY',
135
+ defaultModel: 'claude-sonnet-5-5',
136
+ defaultContextWindow: 1000000,
137
+ defaultMaxTokens: 128000,
138
+ hint: 'claude-sonnet-5-5 / claude-opus-5-5 / claude-fable-5-2 / claude-haiku-5-5',
139
+ recommendedModels: [
140
+ { id: 'claude-sonnet-5-5', label: 'Claude Sonnet 5.5 (1M · 速度与智能平衡)', contextWindow: 1000000, maxTokens: 128000, reasoning: true },
141
+ { id: 'claude-opus-5-5', label: 'Claude Opus 5.5 (1M · 长程编码主力)', contextWindow: 1000000, maxTokens: 128000, reasoning: true },
142
+ { id: 'claude-fable-5-2', label: 'Claude Fable 5.2 (1M · 旗舰推理)', contextWindow: 1000000, maxTokens: 128000, reasoning: true },
143
+ { id: 'claude-haiku-5-5', label: 'Claude Haiku 5.5 (1M · 极速轻量)', contextWindow: 1000000, maxTokens: 128000, reasoning: true },
144
+ ],
145
+ },
146
+ {
147
+ id: 'openai',
148
+ name: 'OpenAI',
149
+ api: 'openai-responses',
150
+ defaultBaseUrl: 'https://api.openai.com/v1',
151
+ envKey: 'OPENAI_API_KEY',
152
+ defaultModel: 'gpt-6.2-sol',
153
+ defaultContextWindow: 1050000,
154
+ defaultMaxTokens: 128000,
155
+ hint: 'gpt-6.2-sol / gpt-6.2-astra / gpt-5.4',
156
+ recommendedModels: [
157
+ { id: 'gpt-6.2-sol', label: 'GPT-6.2 Sol (1.05M · 均衡主力)', contextWindow: 1050000, maxTokens: 128000, reasoning: true },
158
+ { id: 'gpt-6.2-astra', label: 'GPT-6.2 Astra (1.05M · 旗舰编码推理)', contextWindow: 1050000, maxTokens: 128000, reasoning: true },
159
+ { id: 'gpt-5.4', label: 'GPT-5.4 (1.05M)', contextWindow: 1050000, maxTokens: 128000, reasoning: true },
160
+ ],
161
+ },
162
+ {
163
+ id: 'google',
164
+ name: 'Google · Gemini',
165
+ api: 'google-generative-ai',
166
+ defaultBaseUrl: 'https://generativelanguage.googleapis.com/v1beta',
167
+ envKey: 'GEMINI_API_KEY',
168
+ defaultModel: 'gemini-4-carbon',
169
+ defaultContextWindow: 1000000,
170
+ defaultMaxTokens: 65536,
171
+ hint: 'gemini-4-carbon / gemini-3.6-flash / gemini-2.5-pro',
172
+ recommendedModels: [
173
+ { id: 'gemini-4-carbon', label: 'Gemini 4 Carbon (1M · 旗舰多模态)', contextWindow: 1000000, maxTokens: 65536, reasoning: true },
174
+ { id: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash (1M · 极速高吞吐)', contextWindow: 1000000, maxTokens: 65536, reasoning: true },
175
+ { id: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro (1M)', contextWindow: 1000000, maxTokens: 65536, reasoning: true },
176
+ ],
177
+ },
178
+ {
179
+ id: 'openrouter',
180
+ name: 'OpenRouter',
181
+ api: 'openai-completions',
182
+ defaultBaseUrl: 'https://openrouter.ai/api/v1',
183
+ envKey: 'OPENROUTER_API_KEY',
184
+ defaultModel: 'anthropic/claude-sonnet-5.5',
185
+ defaultContextWindow: 1000000,
186
+ defaultMaxTokens: 128000,
187
+ hint: '多模型统一聚合网关(anthropic/deepseek/openai)',
188
+ recommendedModels: [
189
+ { id: 'anthropic/claude-sonnet-5.5', label: 'Claude Sonnet 5.5 (1M)', contextWindow: 1000000, maxTokens: 128000, reasoning: true },
190
+ { id: 'deepseek/deepseek-v4.1-flash', label: 'DeepSeek V4.1 Flash (1M)', contextWindow: 1000000, maxTokens: 128000, reasoning: true },
191
+ { id: 'openai/gpt-6.2-sol', label: 'GPT-6.2 Sol (1.05M)', contextWindow: 1050000, maxTokens: 128000, reasoning: true },
192
+ ],
193
+ },
194
+ {
195
+ id: 'zhipu',
196
+ name: '智谱 · GLM',
197
+ api: 'openai-completions',
198
+ defaultBaseUrl: 'https://open.bigmodel.cn/api/paas/v4',
199
+ envKey: 'ZHIPU_API_KEY',
200
+ defaultModel: 'glm-4.5',
201
+ defaultContextWindow: 128000,
202
+ defaultMaxTokens: 16384,
203
+ hint: 'glm-4.5 / glm-4.5-air / glm-z1-air',
204
+ recommendedModels: [
205
+ { id: 'glm-4.5', label: 'GLM-4.5 (128K · 编程主力)', contextWindow: 128000, maxTokens: 16384, reasoning: true },
206
+ { id: 'glm-4.5-air', label: 'GLM-4.5 Air (128K · 轻量高性价比)', contextWindow: 128000, maxTokens: 16384, reasoning: true },
207
+ ],
208
+ },
209
+ {
210
+ id: 'moonshot',
211
+ name: '月之暗面 · Kimi',
212
+ api: 'openai-completions',
213
+ defaultBaseUrl: 'https://api.moonshot.cn/v1',
214
+ envKey: 'MOONSHOT_API_KEY',
215
+ defaultModel: 'kimi-k2-0905-preview',
216
+ defaultContextWindow: 256000,
217
+ defaultMaxTokens: 32768,
218
+ hint: 'kimi-k2-0905-preview / kimi-thinking-preview',
219
+ recommendedModels: [
220
+ { id: 'kimi-k2-0905-preview', label: 'Kimi K2 (256K · Agent 编码)', contextWindow: 256000, maxTokens: 32768, reasoning: false },
221
+ { id: 'kimi-thinking-preview', label: 'Kimi Thinking (128K · 推理)', contextWindow: 128000, maxTokens: 32768, reasoning: true },
222
+ ],
223
+ },
224
+ {
225
+ id: 'qwen',
226
+ name: '阿里 · 通义千问',
227
+ api: 'openai-completions',
228
+ defaultBaseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
229
+ envKey: 'DASHSCOPE_API_KEY',
230
+ defaultModel: 'qwen3-coder-plus',
231
+ defaultContextWindow: 1000000,
232
+ defaultMaxTokens: 65536,
233
+ hint: 'qwen3-coder-plus / qwen3-max / qwq-plus',
234
+ recommendedModels: [
235
+ { id: 'qwen3-coder-plus', label: 'Qwen3-Coder Plus (1M · 编码主力)', contextWindow: 1000000, maxTokens: 65536, reasoning: true },
236
+ { id: 'qwen3-max', label: 'Qwen3 Max (256K)', contextWindow: 256000, maxTokens: 32768, reasoning: true },
237
+ ],
238
+ },
239
+ {
240
+ id: 'minimax',
241
+ name: 'MiniMax',
242
+ api: 'openai-completions',
243
+ defaultBaseUrl: 'https://api.minimaxi.com/v1',
244
+ envKey: 'MINIMAX_API_KEY',
245
+ defaultModel: 'MiniMax-M1',
246
+ defaultContextWindow: 1000000,
247
+ defaultMaxTokens: 81920,
248
+ hint: 'MiniMax-M1 (1M · 推理)',
249
+ recommendedModels: [
250
+ { id: 'MiniMax-M1', label: 'MiniMax-M1 (1M · 推理)', contextWindow: 1000000, maxTokens: 81920, reasoning: true },
251
+ ],
252
+ },
253
+ {
254
+ id: 'ollama',
255
+ name: '本地模型 · Ollama',
256
+ api: 'openai-completions',
257
+ defaultBaseUrl: 'http://127.0.0.1:11434/v1',
258
+ envKey: '',
259
+ defaultModel: 'qwen2.5-coder:14b',
260
+ defaultContextWindow: 128000,
261
+ defaultMaxTokens: 16384,
262
+ hint: 'http://127.0.0.1:11434/v1 · 离线零延迟',
263
+ keyless: true,
264
+ recommendedModels: [
265
+ { id: 'qwen2.5-coder:14b', label: 'Qwen2.5-Coder 14B (128K)', contextWindow: 128000, maxTokens: 16384, reasoning: false },
266
+ { id: 'deepseek-r1:14b', label: 'DeepSeek-R1 14B (128K · 推理)', contextWindow: 128000, maxTokens: 16384, reasoning: true },
267
+ ],
268
+ },
269
+ {
270
+ id: 'lmstudio',
271
+ name: '本地模型 · LM Studio / vLLM',
272
+ api: 'openai-completions',
273
+ defaultBaseUrl: 'http://127.0.0.1:1234/v1',
274
+ envKey: '',
275
+ defaultModel: 'local-model',
276
+ defaultContextWindow: 128000,
277
+ defaultMaxTokens: 16384,
278
+ hint: 'http://127.0.0.1:1234/v1 · OpenAI 兼容本地推理引擎',
279
+ keyless: true,
280
+ recommendedModels: [],
281
+ },
282
+ {
283
+ id: 'custom-openai',
284
+ name: '自定义代理(OpenAI 兼容)',
285
+ api: 'openai-completions',
286
+ defaultBaseUrl: '',
287
+ envKey: '',
288
+ defaultModel: '',
289
+ defaultContextWindow: 200000,
290
+ defaultMaxTokens: 32768,
291
+ hint: '填写任意中转站或自建网关 Base URL 与模型 ID',
292
+ recommendedModels: [],
293
+ },
294
+ {
295
+ id: 'custom-anthropic',
296
+ name: '自定义代理(Anthropic 兼容)',
297
+ api: 'anthropic-messages',
298
+ defaultBaseUrl: '',
299
+ envKey: '',
300
+ defaultModel: '',
301
+ defaultContextWindow: 200000,
302
+ defaultMaxTokens: 32768,
303
+ hint: '填写 Anthropic 协议中转站 Base URL(如 DeepSeek Anthropic 端点)',
304
+ recommendedModels: [],
305
+ },
87
306
  ];
88
307
 
308
+ export const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
309
+ export const TRANSPORT_MODES = ['auto', 'sse', 'websocket', 'websocket-cached'];
310
+ export const CACHE_WARMING_MODES = ['off', 'streaming', 'idle'];
311
+
89
312
  export function resolvePiAgentDir() {
90
313
  const dir = process.env.CLADO_PI_AGENT_DIR
91
314
  ? resolve(process.env.CLADO_PI_AGENT_DIR)
92
315
  : getAgentDir();
316
+ if (process.env.CLADO_PI_AGENT_DIR && process.env.PI_CODING_AGENT_DIR !== dir) {
317
+ process.env.PI_CODING_AGENT_DIR = dir;
318
+ }
93
319
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
94
320
  return dir;
95
321
  }
@@ -141,13 +367,34 @@ export async function createCladoModelRuntime(agentDir = resolvePiAgentDir()) {
141
367
  });
142
368
  }
143
369
 
144
- export function saveProviderConfig({
370
+ function clampInt(val, min, max, fallback) {
371
+ const n = Number(val);
372
+ if (!Number.isFinite(n) || n <= 0) return fallback;
373
+ return Math.max(min, Math.min(max, Math.round(n)));
374
+ }
375
+
376
+ function lookupRecommendedSpec(preset, modelId) {
377
+ if (!preset || !Array.isArray(preset.recommendedModels)) return null;
378
+ return preset.recommendedModels.find(m => m.id === modelId) || null;
379
+ }
380
+
381
+ function inferReasoning(modelId) {
382
+ return /reason|r1|o1|o3|o4|thinking|sonnet-4|opus-4|sonnet-5|opus-5|fable-5|haiku-5|gpt-5|gpt-6|deepseek-flash|deepseek-v4|gemini-3|gemini-4|gemini-2\.5/i.test(String(modelId || ''));
383
+ }
384
+
385
+ export async function saveProviderConfig({
145
386
  providerId,
387
+ name,
146
388
  apiKey,
147
389
  baseUrl,
148
390
  api,
391
+ headers,
149
392
  models,
393
+ replaceModels = false,
150
394
  defaultModel,
395
+ contextWindow,
396
+ maxTokens,
397
+ reasoning,
151
398
  setAsDefault = false,
152
399
  }, agentDir = resolvePiAgentDir(), workspace = process.cwd()) {
153
400
  const cleanId = String(providerId || '').trim().toLowerCase().replace(/[^a-z0-9._-]/g, '-');
@@ -164,53 +411,150 @@ export function saveProviderConfig({
164
411
  writeJsonSafe(authPath, auth);
165
412
  }
166
413
 
167
- // Update models.json if baseUrl / custom models / custom provider
414
+ // Update models.json if baseUrl / custom models / limits / headers / custom provider / recommended preset models
168
415
  const cleanBaseUrl = typeof baseUrl === 'string' ? baseUrl.trim().replace(/\/+$/, '') : '';
169
- const modelIds = Array.isArray(models)
170
- ? models.map(m => (typeof m === 'string' ? m.trim() : String(m?.id || '').trim())).filter(Boolean)
171
- : [];
416
+ const inputModelsArr = Array.isArray(models) ? models : [];
417
+ const inputById = new Map(
418
+ inputModelsArr
419
+ .filter(m => m && typeof m === 'object' && String(m.id || '').trim())
420
+ .map(m => [String(m.id).trim(), m]),
421
+ );
422
+ const modelIds = inputModelsArr
423
+ .map(m => (typeof m === 'string' ? m.trim() : String(m?.id || '').trim()))
424
+ .filter(Boolean);
172
425
  const chosenModel = String(defaultModel || modelIds[0] || preset?.defaultModel || '').trim();
426
+ const hasExplicitLimits = Boolean(Number(contextWindow) > 0 || Number(maxTokens) > 0 || typeof reasoning === 'boolean');
427
+ const cleanHeaders = headers && typeof headers === 'object' && !Array.isArray(headers)
428
+ ? Object.fromEntries(Object.entries(headers).map(([k, v]) => [String(k).trim(), String(v ?? '')]).filter(([k]) => k))
429
+ : null;
173
430
 
174
- if (cleanBaseUrl || modelIds.length || !preset || preset.keyless || cleanId.startsWith('custom-')) {
431
+ if (cleanBaseUrl || modelIds.length || replaceModels || hasExplicitLimits || chosenModel || cleanHeaders || !preset || preset.keyless || cleanId.startsWith('custom-')) {
175
432
  const cfg = readPiModelsConfig(agentDir);
176
433
  const prev = cfg.providers[cleanId] || {};
434
+ const prevById = new Map(
435
+ (Array.isArray(prev.models) ? prev.models : [])
436
+ .filter(m => m && typeof m === 'object' && m.id)
437
+ .map(m => [m.id, m]),
438
+ );
177
439
  const resolvedApi = api || prev.api || preset?.api || 'openai-completions';
178
440
  const nextEntry = {
179
441
  ...prev,
180
442
  api: resolvedApi,
181
443
  ...(cleanBaseUrl ? { baseUrl: cleanBaseUrl } : prev.baseUrl ? { baseUrl: prev.baseUrl } : preset?.defaultBaseUrl ? { baseUrl: preset.defaultBaseUrl } : {}),
182
444
  };
445
+ if (typeof name === 'string' && name.trim() && !preset) {
446
+ nextEntry.displayName = name.trim().slice(0, 60);
447
+ }
448
+ if (cleanHeaders !== null) {
449
+ if (Object.keys(cleanHeaders).length) nextEntry.headers = cleanHeaders;
450
+ else delete nextEntry.headers;
451
+ }
183
452
  if (preset?.keyless && !nextEntry.apiKey) nextEntry.apiKey = 'ollama';
184
- const mergedIds = [...new Set([
185
- ...(chosenModel ? [chosenModel] : []),
186
- ...modelIds,
187
- ...((Array.isArray(prev.models) ? prev.models : []).map(m => (typeof m === 'string' ? m : m?.id)).filter(Boolean)),
188
- ])];
453
+ const recommendedIds = (preset?.recommendedModels || []).map(m => m.id);
454
+ const mergedIds = replaceModels
455
+ ? [...new Set([...(chosenModel ? [chosenModel] : []), ...modelIds])]
456
+ : [...new Set([
457
+ ...(chosenModel ? [chosenModel] : []),
458
+ ...modelIds,
459
+ ...recommendedIds,
460
+ ...((Array.isArray(prev.models) ? prev.models : []).map(m => (typeof m === 'string' ? m : m?.id)).filter(Boolean)),
461
+ ])];
189
462
  if (mergedIds.length) {
190
- nextEntry.models = mergedIds.map(id => ({
191
- id,
192
- name: id,
193
- reasoning: /reason|r1|o1|o3|o4|thinking|sonnet-4|opus-4|gpt-5/i.test(id),
194
- input: ['text'],
195
- contextWindow: 128000,
196
- maxTokens: 16384,
197
- }));
463
+ nextEntry.models = mergedIds.map(id => {
464
+ const inItem = inputById.get(id);
465
+ const prevItem = prevById.get(id);
466
+ const recSpec = lookupRecommendedSpec(preset, id);
467
+ const isTarget = id === chosenModel;
468
+ const resolvedCtx = Number(inItem?.contextWindow) > 0
469
+ ? clampInt(inItem.contextWindow, 4096, 4000000, preset?.defaultContextWindow || 128000)
470
+ : (isTarget && Number(contextWindow) > 0
471
+ ? clampInt(contextWindow, 4096, 4000000, preset?.defaultContextWindow || 128000)
472
+ : (prevItem?.contextWindow || recSpec?.contextWindow || preset?.defaultContextWindow || 128000));
473
+ const resolvedMaxOut = Number(inItem?.maxTokens) > 0
474
+ ? clampInt(inItem.maxTokens, 1024, Math.max(4096, resolvedCtx), preset?.defaultMaxTokens || 16384)
475
+ : (isTarget && Number(maxTokens) > 0
476
+ ? clampInt(maxTokens, 1024, Math.max(4096, resolvedCtx), preset?.defaultMaxTokens || 16384)
477
+ : (prevItem?.maxTokens || recSpec?.maxTokens || preset?.defaultMaxTokens || 16384));
478
+ const resolvedReasoning = typeof inItem?.reasoning === 'boolean'
479
+ ? inItem.reasoning
480
+ : (isTarget && typeof reasoning === 'boolean'
481
+ ? reasoning
482
+ : (typeof prevItem?.reasoning === 'boolean' ? prevItem.reasoning : (typeof recSpec?.reasoning === 'boolean' ? recSpec.reasoning : inferReasoning(id))));
483
+ return {
484
+ id,
485
+ name: inItem?.name || recSpec?.label || prevItem?.name || id,
486
+ reasoning: resolvedReasoning,
487
+ input: Array.isArray(inItem?.input) && inItem.input.length ? inItem.input : (prevItem?.input || ['text']),
488
+ contextWindow: resolvedCtx,
489
+ maxTokens: resolvedMaxOut,
490
+ };
491
+ });
492
+ } else if (replaceModels) {
493
+ nextEntry.models = [];
198
494
  }
199
495
  cfg.providers[cleanId] = nextEntry;
200
496
  writeJsonSafe(modelsPath, cfg);
201
497
  }
202
498
 
499
+ // Automatically un-hide & enable when user explicitly saves this provider
500
+ const st = readProviderState(agentDir);
501
+ if (st.disabled.includes(cleanId) || st.hidden.includes(cleanId)) {
502
+ writeProviderState({
503
+ disabled: st.disabled.filter(x => x !== cleanId),
504
+ hidden: st.hidden.filter(x => x !== cleanId),
505
+ }, agentDir);
506
+ }
507
+
203
508
  if (setAsDefault && chosenModel) {
204
509
  const sm = SettingsManager.create(workspace, agentDir);
205
510
  sm.setDefaultModelAndProvider(cleanId, chosenModel);
511
+ await sm.flush();
206
512
  }
207
513
 
208
514
  return { ok: true, providerId: cleanId, defaultModel: chosenModel };
209
515
  }
210
516
 
211
- export function deleteProviderConfig(providerId, agentDir = resolvePiAgentDir()) {
517
+ function readProviderState(agentDir = resolvePiAgentDir()) {
518
+ const raw = readJsonSafe(join(agentDir, 'clado-providers-state.json'), {});
519
+ return {
520
+ disabled: Array.isArray(raw?.disabled) ? [...new Set(raw.disabled.map(String).filter(Boolean))] : [],
521
+ hidden: Array.isArray(raw?.hidden) ? [...new Set(raw.hidden.map(String).filter(Boolean))] : [],
522
+ };
523
+ }
524
+
525
+ function writeProviderState(state, agentDir = resolvePiAgentDir()) {
526
+ writeJsonSafe(join(agentDir, 'clado-providers-state.json'), {
527
+ disabled: [...new Set((state?.disabled || []).map(String).filter(Boolean))],
528
+ hidden: [...new Set((state?.hidden || []).map(String).filter(Boolean))],
529
+ });
530
+ }
531
+
532
+ export function setProviderDisabled(providerId, disabled, agentDir = resolvePiAgentDir()) {
533
+ const cleanId = String(providerId || '').trim();
534
+ if (!cleanId) return { ok: false };
535
+ const st = readProviderState(agentDir);
536
+ const nextDisabled = disabled
537
+ ? [...new Set([...st.disabled, cleanId])]
538
+ : st.disabled.filter(x => x !== cleanId);
539
+ writeProviderState({ ...st, disabled: nextDisabled }, agentDir);
540
+ return { ok: true, providerId: cleanId, disabled: Boolean(disabled) };
541
+ }
542
+
543
+ export function restoreProviderPreset(providerId, agentDir = resolvePiAgentDir()) {
212
544
  const cleanId = String(providerId || '').trim();
213
545
  if (!cleanId) return { ok: false };
546
+ const st = readProviderState(agentDir);
547
+ writeProviderState({
548
+ disabled: st.disabled.filter(x => x !== cleanId),
549
+ hidden: st.hidden.filter(x => x !== cleanId),
550
+ }, agentDir);
551
+ return { ok: true, providerId: cleanId };
552
+ }
553
+
554
+ export function deleteProviderConfig(providerId, agentDir = resolvePiAgentDir(), { removeCard = false, workspace = '' } = {}) {
555
+ const cleanId = String(providerId || '').trim();
556
+ if (!cleanId) return { ok: false };
557
+ const preset = PROVIDER_CATALOG.find(p => p.id === cleanId);
214
558
  const authPath = join(agentDir, 'auth.json');
215
559
  const auth = readPiAuth(agentDir);
216
560
  if (cleanId in auth) {
@@ -223,7 +567,36 @@ export function deleteProviderConfig(providerId, agentDir = resolvePiAgentDir())
223
567
  delete cfg.providers[cleanId];
224
568
  writeJsonSafe(modelsPath, cfg);
225
569
  }
226
- return { ok: true, providerId: cleanId };
570
+ const st = readProviderState(agentDir);
571
+ const envHasKey = Boolean(preset?.envKey && process.env[preset.envKey]);
572
+ if (removeCard && preset) {
573
+ writeProviderState({
574
+ disabled: [...new Set([...st.disabled, cleanId])],
575
+ hidden: [...new Set([...st.hidden, cleanId])],
576
+ }, agentDir);
577
+ } else if (preset && envHasKey) {
578
+ // Env key still exists in shell — mark disabled so clicking "清除凭据" actually disconnects it!
579
+ writeProviderState({
580
+ ...st,
581
+ disabled: [...new Set([...st.disabled, cleanId])],
582
+ }, agentDir);
583
+ } else if (!preset) {
584
+ writeProviderState({
585
+ disabled: st.disabled.filter(x => x !== cleanId),
586
+ hidden: st.hidden.filter(x => x !== cleanId),
587
+ }, agentDir);
588
+ }
589
+ // Clear defaultProvider if it pointed to deleted provider
590
+ try {
591
+ const settingsPath = join(agentDir, 'settings.json');
592
+ const rawSettings = readJsonSafe(settingsPath, {});
593
+ if (rawSettings?.defaultProvider === cleanId) {
594
+ delete rawSettings.defaultProvider;
595
+ delete rawSettings.defaultModel;
596
+ writeJsonSafe(settingsPath, rawSettings);
597
+ }
598
+ } catch {}
599
+ return { ok: true, providerId: cleanId, removed: Boolean(removeCard || !preset) };
227
600
  }
228
601
 
229
602
  export async function setDefaultPiModel(providerId, modelId, agentDir = resolvePiAgentDir(), workspace = process.cwd()) {
@@ -241,6 +614,9 @@ export async function listProvidersAndModels(workspace = process.cwd(), agentDir
241
614
  const mr = await createCladoModelRuntime(agentDir);
242
615
  const auth = readPiAuth(agentDir);
243
616
  const customCfg = readPiModelsConfig(agentDir);
617
+ const provState = readProviderState(agentDir);
618
+ const disabledSet = new Set(provState.disabled);
619
+ const hiddenSet = new Set(provState.hidden);
244
620
 
245
621
  const defaultProvider = sm.getDefaultProvider() || '';
246
622
  const defaultModel = sm.getDefaultModel() || '';
@@ -252,147 +628,782 @@ export async function listProvidersAndModels(workspace = process.cwd(), agentDir
252
628
  ]);
253
629
 
254
630
  const providers = [];
631
+ const hiddenPresets = [];
255
632
  const configuredModels = [];
256
633
 
257
634
  for (const id of allIds) {
258
635
  const preset = PROVIDER_CATALOG.find(p => p.id === id);
636
+ if (preset && hiddenSet.has(id) && !(id in auth) && !(id in (customCfg.providers || {}))) {
637
+ hiddenPresets.push({ id: preset.id, name: preset.name, api: preset.api, hint: preset.hint, defaultBaseUrl: preset.defaultBaseUrl });
638
+ continue;
639
+ }
259
640
  const authEntry = auth[id];
260
641
  const customEntry = customCfg.providers?.[id];
642
+ const isDisabled = disabledSet.has(id);
261
643
  const envHasKey = Boolean(preset?.envKey && process.env[preset.envKey]);
262
- const hasAuth = Boolean(authEntry?.key || authEntry?.access || envHasKey || mr.hasConfiguredAuth(id) || (preset?.keyless && customEntry?.baseUrl));
644
+ const rawHasAuth = Boolean(authEntry?.key || authEntry?.access || customEntry?.apiKey || envHasKey || mr.hasConfiguredAuth(id) || (preset?.keyless && customEntry?.baseUrl));
645
+ const hasAuth = !isDisabled && rawHasAuth;
646
+ const authSource = authEntry?.key
647
+ ? 'auth.json'
648
+ : authEntry?.access
649
+ ? 'oauth'
650
+ : customEntry?.apiKey
651
+ ? 'models.json'
652
+ : envHasKey
653
+ ? 'env'
654
+ : (mr.hasConfiguredAuth(id) ? 'runtime' : (preset?.keyless && customEntry ? 'local' : ''));
655
+ const authSourceDetail = authSource === 'env'
656
+ ? `环境变量 ${preset?.envKey || ''}`
657
+ : authSource === 'auth.json'
658
+ ? 'auth.json'
659
+ : authSource === 'oauth'
660
+ ? 'OAuth 登录'
661
+ : authSource === 'models.json'
662
+ ? 'models.json'
663
+ : authSource === 'runtime'
664
+ ? 'Pi 环境/凭据'
665
+ : authSource === 'local'
666
+ ? '本地服务'
667
+ : '';
668
+
263
669
  const runtimeModels = mr.getModels(id) || [];
264
- const customModelIds = (Array.isArray(customEntry?.models) ? customEntry.models : []).map(m => (typeof m === 'string' ? m : m?.id)).filter(Boolean);
670
+ const customModelObjs = Array.isArray(customEntry?.models) ? customEntry.models : [];
671
+ const customById = new Map(customModelObjs.filter(m => m && typeof m === 'object' && m.id).map(m => [m.id, m]));
672
+ const runtimeById = new Map(runtimeModels.map(m => [m.id, m]));
673
+ const customModelIds = customModelObjs.map(m => (typeof m === 'string' ? m : m?.id)).filter(Boolean);
674
+ const recommendedIds = (preset?.recommendedModels || []).map(m => m.id);
265
675
  const modelList = [...new Set([
266
676
  ...customModelIds,
677
+ ...recommendedIds,
267
678
  ...runtimeModels.map(m => m.id),
268
679
  ...(preset?.defaultModel ? [preset.defaultModel] : []),
269
680
  ])].slice(0, 40);
270
681
 
682
+ const activeModelId = (defaultProvider === id && defaultModel)
683
+ ? defaultModel
684
+ : (customModelIds[0] || preset?.defaultModel || modelList[0] || '');
685
+
686
+ const resolveSpecs = mId => {
687
+ const cObj = customById.get(mId);
688
+ const rObj = runtimeById.get(mId);
689
+ const rec = lookupRecommendedSpec(preset, mId);
690
+ const ctx = cObj?.contextWindow || rObj?.contextWindow || rec?.contextWindow || preset?.defaultContextWindow || 128000;
691
+ const maxOut = cObj?.maxTokens || rObj?.maxTokens || rec?.maxTokens || preset?.defaultMaxTokens || 16384;
692
+ const reas = typeof cObj?.reasoning === 'boolean'
693
+ ? cObj.reasoning
694
+ : (typeof rObj?.reasoning === 'boolean' ? rObj.reasoning : (typeof rec?.reasoning === 'boolean' ? rec.reasoning : inferReasoning(mId)));
695
+ const inp = Array.isArray(cObj?.input) && cObj.input.length ? cObj.input : (Array.isArray(rObj?.input) ? rObj.input : ['text']);
696
+ return { contextWindow: ctx, maxTokens: maxOut, reasoning: reas, input: inp, label: cObj?.name || rec?.label || mId };
697
+ };
698
+
699
+ const activeSpecs = resolveSpecs(activeModelId);
700
+
271
701
  providers.push({
272
702
  id,
273
- name: preset?.name || id,
703
+ name: preset?.name || customEntry?.displayName || id,
704
+ isCustom: !preset,
274
705
  api: customEntry?.api || preset?.api || 'openai-completions',
275
706
  baseUrl: customEntry?.baseUrl || preset?.defaultBaseUrl || '',
707
+ headers: customEntry?.headers && typeof customEntry.headers === 'object' ? customEntry.headers : {},
276
708
  hint: preset?.hint || '',
277
709
  keyless: Boolean(preset?.keyless),
710
+ disabled: isDisabled,
278
711
  configured: hasAuth,
279
- authSource: authEntry?.key ? 'auth.json' : authEntry?.access ? 'oauth' : envHasKey ? 'env' : preset?.keyless && customEntry ? 'local' : '',
280
- maskedKey: authEntry?.key ? maskSecret(authEntry.key) : '',
281
- defaultModel: (defaultProvider === id && defaultModel) ? defaultModel : (customModelIds[0] || preset?.defaultModel || modelList[0] || ''),
712
+ rawHasAuth,
713
+ authSource,
714
+ authSourceDetail,
715
+ maskedKey: authEntry?.key ? maskSecret(authEntry.key) : (customEntry?.apiKey ? maskSecret(customEntry.apiKey) : ''),
716
+ defaultModel: activeModelId,
717
+ contextWindow: activeSpecs.contextWindow,
718
+ maxTokens: activeSpecs.maxTokens,
719
+ reasoning: activeSpecs.reasoning,
720
+ recommendedModels: preset?.recommendedModels || [],
282
721
  models: modelList,
722
+ modelDetails: modelList.map(mId => ({ id: mId, ...resolveSpecs(mId) })),
283
723
  });
284
724
 
285
725
  if (hasAuth) {
286
- for (const mId of modelList.slice(0, 12)) {
726
+ for (const mId of modelList.slice(0, 20)) {
727
+ const specs = resolveSpecs(mId);
287
728
  configuredModels.push({
288
729
  id: `${id}/${mId}`,
289
730
  provider: id,
290
731
  model: mId,
291
732
  label: `${mId}`,
292
- providerName: preset?.name || id,
733
+ providerName: preset?.name || customEntry?.displayName || id,
734
+ contextWindow: specs.contextWindow,
735
+ maxTokens: specs.maxTokens,
736
+ reasoning: specs.reasoning,
293
737
  });
294
738
  }
295
739
  }
296
740
  }
297
741
 
742
+ const activeEntry = configuredModels.find(m => m.provider === defaultProvider && m.model === defaultModel)
743
+ || providers.find(p => p.id === defaultProvider)
744
+ || configuredModels[0]
745
+ || null;
746
+
298
747
  return {
299
748
  agentDir,
300
749
  defaultProvider,
301
750
  defaultModel,
302
751
  activeModelLabel: defaultModel || configuredModels[0]?.model || '未配置模型',
752
+ activeContextWindow: activeEntry?.contextWindow || 128000,
753
+ activeMaxTokens: activeEntry?.maxTokens || 16384,
303
754
  providers,
755
+ hiddenPresets,
304
756
  configuredModels,
305
757
  };
306
758
  }
307
759
 
308
760
  // ============================================================================
309
- // 2. Roles (Built-in 4 Roles + Custom Roles in ~/.pi/agent/clado-roles.json)
761
+ // 1.5 Runtime & Compaction Settings (Pi settings.json + clado-runtime.json)
762
+ // ============================================================================
763
+
764
+ export function readRuntimeSettings(workspace = process.cwd(), agentDir = resolvePiAgentDir(), activeContextWindow = 128000) {
765
+ const sm = SettingsManager.create(workspace, agentDir);
766
+ const sidecar = readJsonSafe(join(agentDir, 'clado-runtime.json'), {});
767
+ const comp = sm.getCompactionSettings();
768
+ const retry = sm.getRetrySettings();
769
+ const thinkingLevel = sm.getDefaultThinkingLevel() || 'medium';
770
+ const transport = sm.getTransport() || 'auto';
771
+ const hideThinkingBlock = Boolean(sm.getHideThinkingBlock());
772
+ const cacheWarming = sm.getCacheWarmingMode() || 'off';
773
+ const keepRecentTokens = clampInt(comp?.keepRecentTokens, 2048, 256000, 20000);
774
+ const reserveTokens = clampInt(comp?.reserveTokens, 4096, 1000000, 16384);
775
+ const inferredPct = activeContextWindow > 0
776
+ ? Math.max(50, Math.min(95, Math.round((1 - reserveTokens / activeContextWindow) * 100)))
777
+ : 85;
778
+ const compactionTriggerPercent = typeof sidecar?.compactionTriggerPercent === 'number'
779
+ ? Math.max(50, Math.min(95, Math.round(sidecar.compactionTriggerPercent)))
780
+ : inferredPct;
781
+
782
+ return {
783
+ thinkingLevel: THINKING_LEVELS.includes(thinkingLevel) ? thinkingLevel : 'medium',
784
+ transport: TRANSPORT_MODES.includes(transport) ? transport : 'auto',
785
+ hideThinkingBlock,
786
+ compactionEnabled: comp?.enabled !== false,
787
+ compactionTriggerPercent,
788
+ reserveTokens,
789
+ keepRecentTokens,
790
+ retryEnabled: retry?.enabled !== false,
791
+ maxRetries: clampInt(retry?.maxRetries, 0, 10, 3),
792
+ cacheWarming: CACHE_WARMING_MODES.includes(cacheWarming) ? cacheWarming : 'off',
793
+ };
794
+ }
795
+
796
+ export async function saveRuntimeSettings(input = {}, workspace = process.cwd(), agentDir = resolvePiAgentDir(), activeContextWindow = 128000) {
797
+ const sm = SettingsManager.create(workspace, agentDir);
798
+ const settingsPath = join(agentDir, 'settings.json');
799
+ const sidecarPath = join(agentDir, 'clado-runtime.json');
800
+ const current = readRuntimeSettings(workspace, agentDir, activeContextWindow);
801
+
802
+ const thinkingLevel = THINKING_LEVELS.includes(input.thinkingLevel) ? input.thinkingLevel : current.thinkingLevel;
803
+ const transport = TRANSPORT_MODES.includes(input.transport) ? input.transport : current.transport;
804
+ const hideThinkingBlock = typeof input.hideThinkingBlock === 'boolean' ? input.hideThinkingBlock : current.hideThinkingBlock;
805
+ const compactionEnabled = typeof input.compactionEnabled === 'boolean' ? input.compactionEnabled : current.compactionEnabled;
806
+ const compactionTriggerPercent = input.compactionTriggerPercent !== undefined
807
+ ? Math.max(50, Math.min(95, Math.round(Number(input.compactionTriggerPercent) || 85)))
808
+ : current.compactionTriggerPercent;
809
+ const keepRecentTokens = input.keepRecentTokens !== undefined
810
+ ? clampInt(input.keepRecentTokens, 2048, 256000, current.keepRecentTokens)
811
+ : current.keepRecentTokens;
812
+ const retryEnabled = typeof input.retryEnabled === 'boolean' ? input.retryEnabled : current.retryEnabled;
813
+ const maxRetries = input.maxRetries !== undefined
814
+ ? clampInt(input.maxRetries, 0, 10, current.maxRetries)
815
+ : current.maxRetries;
816
+ const cacheWarming = CACHE_WARMING_MODES.includes(input.cacheWarming) ? input.cacheWarming : current.cacheWarming;
817
+
818
+ const ctxWin = clampInt(input.activeContextWindow || activeContextWindow, 8192, 4000000, 128000);
819
+ const reserveTokens = Math.max(4096, Math.round(ctxWin * (1 - compactionTriggerPercent / 100)));
820
+
821
+ // Persist Pi-native fields via SettingsManager + atomic settings.json merge for nested compaction/retry numbers
822
+ sm.setDefaultThinkingLevel(thinkingLevel);
823
+ sm.setTransport(transport);
824
+ sm.setHideThinkingBlock(hideThinkingBlock);
825
+ sm.setCompactionEnabled(compactionEnabled);
826
+ sm.setRetryEnabled(retryEnabled);
827
+ sm.setCacheWarmingMode(cacheWarming);
828
+ await sm.flush();
829
+
830
+ const rawSettings = readJsonSafe(settingsPath, {});
831
+ rawSettings.defaultThinkingLevel = thinkingLevel;
832
+ rawSettings.transport = transport;
833
+ rawSettings.hideThinkingBlock = hideThinkingBlock;
834
+ rawSettings.cacheWarming = cacheWarming;
835
+ rawSettings.compaction = {
836
+ ...(rawSettings.compaction && typeof rawSettings.compaction === 'object' ? rawSettings.compaction : {}),
837
+ enabled: compactionEnabled,
838
+ reserveTokens,
839
+ keepRecentTokens,
840
+ };
841
+ rawSettings.retry = {
842
+ ...(rawSettings.retry && typeof rawSettings.retry === 'object' ? rawSettings.retry : {}),
843
+ enabled: retryEnabled,
844
+ maxRetries,
845
+ };
846
+ writeJsonSafe(settingsPath, rawSettings);
847
+
848
+ const sidecar = readJsonSafe(sidecarPath, {});
849
+ sidecar.compactionTriggerPercent = compactionTriggerPercent;
850
+ writeJsonSafe(sidecarPath, sidecar);
851
+
852
+ return readRuntimeSettings(workspace, agentDir, ctxWin);
853
+ }
854
+
855
+ // ============================================================================
856
+ // 2. Roles (Built-in + Installed Plugins/Pi Packages + Workspace + Global)
857
+ // Roles are strictly personas (never conflated with /prompts slash commands).
310
858
  // ============================================================================
311
859
 
312
- export function listRoles(agentDir = resolvePiAgentDir()) {
313
- const customPath = join(agentDir, 'clado-roles.json');
314
- const raw = readJsonSafe(customPath, []);
315
- const custom = Array.isArray(raw) ? raw.filter(r => r && r.id && r.name) : [];
860
+ export const ROLE_SYSTEM_PROMPT_MAX_CHARS = 64000;
861
+
862
+ function collectInstalledPackageDirs(workspace = '', agentDir = resolvePiAgentDir()) {
863
+ const dirs = [];
864
+ const seen = new Set();
865
+ const pushDir = (dirPath, label, kind) => {
866
+ if (!dirPath) return;
867
+ const abs = resolve(dirPath);
868
+ if (seen.has(abs) || !existsSync(abs)) return;
869
+ try {
870
+ if (!statSync(abs).isDirectory()) return;
871
+ } catch { return; }
872
+ seen.add(abs);
873
+ dirs.push({ dir: abs, label, kind });
874
+ };
875
+
876
+ // 1. Installed Clado workspace plugins: <workspace>/.clado/plugins/<id>
877
+ if (workspace) {
878
+ const wsPluginsDir = join(resolve(workspace), '.clado', 'plugins');
879
+ if (existsSync(wsPluginsDir)) {
880
+ try {
881
+ for (const name of readdirSync(wsPluginsDir).sort()) {
882
+ const full = join(wsPluginsDir, name);
883
+ const manifest = readJsonSafe(join(full, 'clado-plugin.json'), null);
884
+ pushDir(full, manifest?.name || manifest?.id || name, 'clado-plugin');
885
+ }
886
+ } catch {}
887
+ }
888
+ }
889
+
890
+ // 2. Installed Pi packages & local package/extension directories
891
+ const scanPackagesRoot = (rootDir, prefixLabel) => {
892
+ if (!rootDir || !existsSync(rootDir)) return;
893
+ try {
894
+ for (const name of readdirSync(rootDir).sort()) {
895
+ if (name.startsWith('.')) continue;
896
+ const full = join(rootDir, name);
897
+ if (name.startsWith('@')) {
898
+ try {
899
+ for (const sub of readdirSync(full).sort()) {
900
+ pushDir(join(full, sub), `${name}/${sub}`, prefixLabel);
901
+ }
902
+ } catch {}
903
+ } else {
904
+ pushDir(full, name, prefixLabel);
905
+ }
906
+ }
907
+ } catch {}
908
+ };
909
+ scanPackagesRoot(join(agentDir, 'packages'), 'pi-package');
910
+ scanPackagesRoot(join(agentDir, 'npm', 'node_modules'), 'pi-package');
911
+ if (workspace) {
912
+ scanPackagesRoot(join(resolve(workspace), '.pi', 'packages'), 'pi-package');
913
+ scanPackagesRoot(join(resolve(workspace), '.pi', 'npm', 'node_modules'), 'pi-package');
914
+ }
915
+
916
+ // 3. Explicit local paths in user & project settings.json (`packages` and `extensions`)
917
+ const settingFiles = [
918
+ { file: join(agentDir, 'settings.json'), base: agentDir },
919
+ ...(workspace ? [{ file: join(resolve(workspace), '.pi', 'settings.json'), base: resolve(workspace) }] : []),
920
+ ];
921
+ for (const { file, base } of settingFiles) {
922
+ const raw = readJsonSafe(file, {});
923
+ const pkgList = Array.isArray(raw?.packages) ? raw.packages : [];
924
+ for (const item of pkgList) {
925
+ const src = typeof item === 'string' ? item : item?.source;
926
+ if (!src || /^(npm:|git:|https?:)/i.test(src)) continue;
927
+ const target = src.startsWith('/') ? src : resolve(base, src);
928
+ const pkgJson = readJsonSafe(join(target, 'package.json'), null);
929
+ pushDir(target, pkgJson?.name || src.split('/').pop() || src, 'pi-package');
930
+ }
931
+ const extList = Array.isArray(raw?.extensions) ? raw.extensions : [];
932
+ for (const extPath of extList) {
933
+ if (typeof extPath !== 'string' || !extPath.trim()) continue;
934
+ const target = extPath.startsWith('/') ? extPath : resolve(base, extPath);
935
+ try {
936
+ const st = statSync(target);
937
+ const dir = st.isDirectory() ? target : dirname(target);
938
+ pushDir(dir, dir.split('/').pop() || extPath, 'pi-extension');
939
+ } catch {}
940
+ }
941
+ }
942
+ return dirs;
943
+ }
944
+
945
+ function parseSimpleFrontmatter(rawText) {
946
+ const text = String(rawText || '');
947
+ const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
948
+ if (!m) return { meta: {}, body: text.trim() };
949
+ const meta = {};
950
+ const lines = m[1].split(/\r?\n/);
951
+ let currentListKey = '';
952
+ for (const line of lines) {
953
+ if (/^\s*-\s+(.+)$/.test(line) && currentListKey) {
954
+ const val = line.replace(/^\s*-\s+/, '').trim().replace(/^['"]|['"]$/g, '');
955
+ if (val) {
956
+ if (!Array.isArray(meta[currentListKey])) meta[currentListKey] = [];
957
+ meta[currentListKey].push(val);
958
+ }
959
+ continue;
960
+ }
961
+ const kv = line.match(/^([a-zA-Z0-9_-]+)\s*:\s*(.*)$/);
962
+ if (!kv) { currentListKey = ''; continue; }
963
+ const k = kv[1].trim();
964
+ const v = kv[2].trim();
965
+ if (!v) {
966
+ currentListKey = k;
967
+ meta[k] = [];
968
+ } else if (v.startsWith('[') && v.endsWith(']')) {
969
+ currentListKey = '';
970
+ meta[k] = v.slice(1, -1).split(',').map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean);
971
+ } else {
972
+ currentListKey = '';
973
+ meta[k] = v.replace(/^['"]|['"]$/g, '');
974
+ }
975
+ }
976
+ return { meta, body: m[2].trim() };
977
+ }
978
+
979
+ function normalizeRoleCandidate(raw, fallback = {}) {
980
+ if (!raw || typeof raw !== 'object') return null;
981
+ const name = String(raw.name || fallback.name || raw.id || '').trim();
982
+ const id = String(raw.id || fallback.id || name.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')).trim();
983
+ if (!id || !name) return null;
984
+ const toList = v => Array.isArray(v)
985
+ ? v.map(s => String(s || '').trim()).filter(Boolean)
986
+ : typeof v === 'string' && v.trim()
987
+ ? v.split(/[\n,]+/).map(s => s.trim()).filter(Boolean)
988
+ : [];
989
+ return {
990
+ id: id.slice(0, 48),
991
+ name: name.slice(0, 48),
992
+ phase: String(raw.phase || fallback.phase || '自定义').trim().slice(0, 24),
993
+ tone: ['sky', 'emerald', 'violet', 'amber'].includes(raw.tone) ? raw.tone : (fallback.tone || 'sky'),
994
+ description: String(raw.description || fallback.description || '').trim().slice(0, 400),
995
+ systemPrompt: String(raw.systemPrompt || raw.prompt || fallback.systemPrompt || '').trim().slice(0, ROLE_SYSTEM_PROMPT_MAX_CHARS),
996
+ model: String(raw.model || '').trim().slice(0, 120),
997
+ thinkingLevel: THINKING_LEVELS.includes(raw.thinkingLevel) ? raw.thinkingLevel : '',
998
+ tools: toList(raw.tools),
999
+ disabledTools: toList(raw.disabledTools),
1000
+ };
1001
+ }
1002
+
1003
+ function readRolesFromJsonFile(filePath, sourceMeta) {
1004
+ if (!existsSync(filePath)) return [];
1005
+ const raw = readJsonSafe(filePath, null);
1006
+ if (!raw) return [];
1007
+ const arr = Array.isArray(raw)
1008
+ ? raw
1009
+ : (Array.isArray(raw?.roles) ? raw.roles : (Array.isArray(raw?.agents) ? raw.agents : (raw && typeof raw === 'object' && (raw.name || raw.id) ? [raw] : [])));
1010
+ const out = [];
1011
+ for (const item of arr) {
1012
+ const norm = normalizeRoleCandidate(item);
1013
+ if (norm) out.push({ ...norm, ...sourceMeta, sourcePath: filePath });
1014
+ }
1015
+ return out;
1016
+ }
1017
+
1018
+ function readRolesFromDir(dirPath, sourceMeta) {
1019
+ if (!dirPath || !existsSync(dirPath)) return [];
1020
+ const out = [];
1021
+ try {
1022
+ for (const fileName of readdirSync(dirPath).sort()) {
1023
+ const full = join(dirPath, fileName);
1024
+ try {
1025
+ if (!statSync(full).isFile()) continue;
1026
+ } catch { continue; }
1027
+ if (fileName.endsWith('.json')) {
1028
+ out.push(...readRolesFromJsonFile(full, sourceMeta));
1029
+ } else if (fileName.endsWith('.md')) {
1030
+ const slug = fileName.replace(/\.md$/i, '');
1031
+ if (/^readme$/i.test(slug)) continue;
1032
+ const { meta, body } = parseSimpleFrontmatter(readFileSync(full, 'utf8'));
1033
+ const norm = normalizeRoleCandidate({
1034
+ id: meta.id || slug,
1035
+ name: meta.name || slug,
1036
+ phase: meta.phase || '自定义',
1037
+ tone: meta.tone || 'sky',
1038
+ description: meta.description || '',
1039
+ model: meta.model || '',
1040
+ thinkingLevel: meta.thinkingLevel || meta.thinking_level || '',
1041
+ tools: meta.tools,
1042
+ disabledTools: meta.disabledTools || meta.disabled_tools,
1043
+ systemPrompt: body,
1044
+ });
1045
+ if (norm) out.push({ ...norm, ...sourceMeta, sourcePath: full });
1046
+ }
1047
+ }
1048
+ } catch {}
1049
+ return out;
1050
+ }
1051
+
1052
+ export function listRoles(agentDir = resolvePiAgentDir(), workspace = '') {
316
1053
  const merged = new Map();
317
- for (const role of BUILTIN_ROLES) merged.set(role.id, { ...role });
318
- for (const role of custom) {
1054
+ const applyRole = role => {
319
1055
  const existing = merged.get(role.id);
320
1056
  merged.set(role.id, {
321
1057
  id: role.id,
322
- name: String(role.name).trim(),
323
- phase: String(role.phase || existing?.phase || '自定义').trim(),
1058
+ name: role.name,
1059
+ phase: role.phase || existing?.phase || '自定义',
324
1060
  tone: ['sky', 'emerald', 'violet', 'amber'].includes(role.tone) ? role.tone : (existing?.tone || 'sky'),
325
- builtin: Boolean(existing?.builtin),
326
- description: String(role.description || existing?.description || '').trim(),
327
- systemPrompt: String(role.systemPrompt || existing?.systemPrompt || '').trim(),
328
- model: String(role.model || '').trim(),
1061
+ builtin: Boolean(existing?.builtin || role.builtin),
1062
+ customized: Boolean(existing?.builtin && role.source !== 'builtin'),
1063
+ source: role.source || 'user',
1064
+ sourceLabel: role.sourceLabel || '',
1065
+ sourcePath: role.sourcePath || '',
1066
+ description: role.description || existing?.description || '',
1067
+ systemPrompt: role.systemPrompt || existing?.systemPrompt || '',
1068
+ model: role.model !== undefined ? role.model : (existing?.model || ''),
1069
+ thinkingLevel: role.thinkingLevel !== undefined ? role.thinkingLevel : (existing?.thinkingLevel || ''),
1070
+ tools: Array.isArray(role.tools) ? role.tools : (existing?.tools || []),
1071
+ disabledTools: Array.isArray(role.disabledTools) ? role.disabledTools : (existing?.disabledTools || []),
329
1072
  });
1073
+ };
1074
+
1075
+ // 1. Built-in roles
1076
+ for (const role of BUILTIN_ROLES) {
1077
+ applyRole({
1078
+ ...role,
1079
+ model: '',
1080
+ thinkingLevel: '',
1081
+ tools: [],
1082
+ disabledTools: [],
1083
+ source: 'builtin',
1084
+ sourceLabel: '内置',
1085
+ sourcePath: '',
1086
+ });
1087
+ }
1088
+
1089
+ // 2. Installed Clado plugins & Pi packages (agents/*.md, roles/*.json, clado-role.json, roles.json)
1090
+ for (const pkg of collectInstalledPackageDirs(workspace, agentDir)) {
1091
+ const meta = { source: 'plugin', sourceLabel: `插件:${pkg.label}` };
1092
+ for (const fileName of ['clado-role.json', 'roles.json', 'agents.json']) {
1093
+ for (const r of readRolesFromJsonFile(join(pkg.dir, fileName), meta)) applyRole(r);
1094
+ }
1095
+ for (const sub of ['roles', 'agents']) {
1096
+ for (const r of readRolesFromDir(join(pkg.dir, sub), meta)) applyRole(r);
1097
+ }
330
1098
  }
1099
+
1100
+ // 3. Workspace-level roles & agent definitions (never scanning prompts/!)
1101
+ if (workspace) {
1102
+ const ws = resolve(workspace);
1103
+ const wsMeta = { source: 'workspace', sourceLabel: '工作区' };
1104
+ for (const file of [join(ws, '.clado', 'roles.json'), join(ws, '.pi', 'roles.json')]) {
1105
+ for (const r of readRolesFromJsonFile(file, wsMeta)) applyRole(r);
1106
+ }
1107
+ for (const dir of [join(ws, '.clado', 'roles'), join(ws, '.clado', 'agents'), join(ws, '.pi', 'agents'), join(ws, '.claude', 'agents')]) {
1108
+ for (const r of readRolesFromDir(dir, wsMeta)) applyRole(r);
1109
+ }
1110
+ }
1111
+
1112
+ // 4. Global user roles (~/.pi/agent/agents/* and ~/.pi/agent/clado-roles.json)
1113
+ const userMeta = { source: 'user', sourceLabel: '全局' };
1114
+ for (const r of readRolesFromDir(join(agentDir, 'agents'), userMeta)) applyRole(r);
1115
+ for (const r of readRolesFromJsonFile(join(agentDir, 'clado-roles.json'), userMeta)) applyRole(r);
1116
+
331
1117
  return [...merged.values()];
332
1118
  }
333
1119
 
334
- export function resolveRole(roleId, agentDir = resolvePiAgentDir()) {
335
- const roles = listRoles(agentDir);
336
- return roles.find(r => r.id === roleId) || roles[0];
1120
+ export function resolveRole(roleId, agentDir = resolvePiAgentDir(), { workspace = '', strict = false } = {}) {
1121
+ const roles = listRoles(agentDir, workspace);
1122
+ const cleanId = String(roleId || '').trim();
1123
+ if (!cleanId) return roles[0];
1124
+ const found = roles.find(r => r.id === cleanId);
1125
+ if (found) return found;
1126
+ if (strict) {
1127
+ const available = roles.map(r => `${r.id}(${r.name})`).join(', ');
1128
+ throw new Error(`找不到角色 "${cleanId}"。当前可用角色:${available}。如需注册自定义角色,可在「设置中心 → 智能体与角色」新建,或放置到 .clado/roles/、.pi/agents/、.claude/agents/ 或插件包的 agents/ / roles/ 目录。`);
1129
+ }
1130
+ return roles[0];
337
1131
  }
338
1132
 
339
- export function saveRole(input, agentDir = resolvePiAgentDir()) {
1133
+ export function saveRole(input, agentDir = resolvePiAgentDir(), workspace = '') {
340
1134
  const name = String(input?.name || '').trim();
341
1135
  if (!name) throw new Error('角色名称不能为空。');
342
1136
  const rawId = String(input?.id || name.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || ('role-' + Date.now().toString(36)));
343
- const id = rawId.slice(0, 36);
344
- const customPath = join(agentDir, 'clado-roles.json');
345
- const list = readJsonSafe(customPath, []);
1137
+ const id = rawId.slice(0, 48);
1138
+ const scope = input?.scope === 'project' && workspace ? 'project' : 'user';
1139
+ const targetPath = scope === 'project'
1140
+ ? join(resolve(workspace), '.clado', 'roles.json')
1141
+ : join(agentDir, 'clado-roles.json');
1142
+ const list = readJsonSafe(targetPath, []);
346
1143
  const arr = Array.isArray(list) ? list.filter(r => r && r.id !== id) : [];
347
1144
  const entry = {
348
1145
  id,
349
- name: name.slice(0, 40),
350
- phase: String(input?.phase || '自定义阶段').trim().slice(0, 20),
1146
+ name: name.slice(0, 48),
1147
+ phase: String(input?.phase || '自定义阶段').trim().slice(0, 24),
351
1148
  tone: ['sky', 'emerald', 'violet', 'amber'].includes(input?.tone) ? input.tone : 'sky',
352
- description: String(input?.description || '').trim().slice(0, 200),
353
- systemPrompt: String(input?.systemPrompt || '').trim().slice(0, 6000),
1149
+ description: String(input?.description || '').trim().slice(0, 400),
1150
+ systemPrompt: String(input?.systemPrompt || '').trim().slice(0, ROLE_SYSTEM_PROMPT_MAX_CHARS),
354
1151
  model: String(input?.model || '').trim().slice(0, 120),
1152
+ thinkingLevel: THINKING_LEVELS.includes(input?.thinkingLevel) ? input.thinkingLevel : '',
1153
+ tools: Array.isArray(input?.tools) ? [...new Set(input.tools.map(s => String(s || '').trim()).filter(Boolean))] : [],
1154
+ disabledTools: Array.isArray(input?.disabledTools) ? [...new Set(input.disabledTools.map(s => String(s || '').trim()).filter(Boolean))] : [],
355
1155
  };
356
1156
  arr.push(entry);
357
- writeJsonSafe(customPath, arr);
358
- return entry;
1157
+ writeJsonSafe(targetPath, arr);
1158
+ return { ...entry, scope, sourcePath: targetPath };
359
1159
  }
360
1160
 
361
- export function deleteRole(roleId, agentDir = resolvePiAgentDir()) {
362
- const customPath = join(agentDir, 'clado-roles.json');
363
- const list = readJsonSafe(customPath, []);
364
- const next = Array.isArray(list) ? list.filter(r => r && r.id !== roleId) : [];
365
- writeJsonSafe(customPath, next);
1161
+ export function deleteRole(roleId, agentDir = resolvePiAgentDir(), workspace = '') {
1162
+ const paths = [
1163
+ join(agentDir, 'clado-roles.json'),
1164
+ ...(workspace ? [join(resolve(workspace), '.clado', 'roles.json')] : []),
1165
+ ];
1166
+ for (const p of paths) {
1167
+ if (!existsSync(p)) continue;
1168
+ const list = readJsonSafe(p, []);
1169
+ if (Array.isArray(list)) {
1170
+ const next = list.filter(r => r && r.id !== roleId);
1171
+ if (next.length !== list.length) writeJsonSafe(p, next);
1172
+ }
1173
+ }
366
1174
  return { ok: true, id: roleId };
367
1175
  }
368
1176
 
369
1177
  // ============================================================================
370
- // 3. Pi Native MCP (mcp.json), Skills, Prompt Templates (/Commands), Packages
1178
+ // 3. Pi Native MCP (mcp.json + .mcp.json + Plugin-bundled + Extension-registered)
371
1179
  // ============================================================================
372
1180
 
373
- function readMcpFile(filePath, scope) {
374
- const raw = readJsonSafe(filePath, null);
375
- const servers = raw?.mcpServers && typeof raw.mcpServers === 'object' ? raw.mcpServers : {};
376
- return Object.entries(servers).map(([name, cfg]) => ({
1181
+ const MCP_EXPOSURES = ['direct', 'codemode', 'deferred', 'hidden'];
1182
+
1183
+ function normalizeMcpEntry(name, cfg, meta = {}) {
1184
+ const isOverrideOnly = cfg && typeof cfg === 'object' && !cfg.command && !cfg.url;
1185
+ return {
377
1186
  name,
378
- scope,
1187
+ scope: meta.scope || 'user',
1188
+ sourceLabel: meta.sourceLabel || (meta.scope === 'project' ? '项目 .pi/mcp.json' : '全局 mcp.json'),
1189
+ sourcePath: meta.sourcePath || '',
1190
+ overrideOnly: Boolean(isOverrideOnly),
379
1191
  type: cfg?.url ? 'http' : 'stdio',
380
1192
  command: cfg?.command || '',
381
- args: Array.isArray(cfg?.args) ? cfg.args : [],
1193
+ args: Array.isArray(cfg?.args) ? cfg.args.map(String) : [],
1194
+ cwd: cfg?.cwd || '',
382
1195
  url: cfg?.url || '',
383
- env: cfg?.env || {},
384
- headers: cfg?.headers || {},
385
- enabled: cfg?.disabled !== true && cfg?.enabled !== false,
1196
+ env: cfg?.env && typeof cfg.env === 'object' ? cfg.env : {},
1197
+ headers: cfg?.headers && typeof cfg.headers === 'object' ? cfg.headers : {},
1198
+ timeout: typeof cfg?.timeout === 'number' ? cfg.timeout : undefined,
1199
+ exposure: MCP_EXPOSURES.includes(cfg?.exposure) ? cfg.exposure : (meta.defaultExposure || 'codemode'),
1200
+ toolExposure: cfg?.toolExposure && typeof cfg.toolExposure === 'object' && !Array.isArray(cfg.toolExposure) ? cfg.toolExposure : {},
1201
+ description: typeof cfg?.description === 'string' ? cfg.description : '',
1202
+ enabled: cfg?.enabled !== false && cfg?.disabled !== true,
1203
+ };
1204
+ }
1205
+
1206
+ function readMcpFile(filePath, scope, extraMeta = {}) {
1207
+ const raw = readJsonSafe(filePath, null);
1208
+ const servers = raw?.mcpServers && typeof raw.mcpServers === 'object' ? raw.mcpServers : {};
1209
+ return Object.entries(servers).map(([name, cfg]) => normalizeMcpEntry(name, cfg, {
1210
+ scope,
1211
+ sourcePath: filePath,
1212
+ ...extraMeta,
386
1213
  }));
387
1214
  }
388
1215
 
389
- export function listPiMcpServers(workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1216
+ function discoverBundledAndRootMcpServers(workspace = '', agentDir = resolvePiAgentDir()) {
1217
+ const out = [];
1218
+ // 1. Installed Clado plugins & Pi packages bundled MCP configs
1219
+ for (const pkg of collectInstalledPackageDirs(workspace, agentDir)) {
1220
+ const manifest = readJsonSafe(join(pkg.dir, 'clado-plugin.json'), null);
1221
+ if (manifest?.mcpServers && typeof manifest.mcpServers === 'object') {
1222
+ for (const [name, cfg] of Object.entries(manifest.mcpServers)) {
1223
+ if (!cfg || typeof cfg !== 'object' || (!cfg.command && !cfg.url)) continue;
1224
+ out.push(normalizeMcpEntry(name, cfg, {
1225
+ scope: 'plugin',
1226
+ sourceLabel: `插件:${pkg.label}`,
1227
+ sourcePath: join(pkg.dir, 'clado-plugin.json'),
1228
+ defaultExposure: 'direct',
1229
+ }));
1230
+ }
1231
+ }
1232
+ for (const fileName of ['mcp.json', '.mcp.json']) {
1233
+ const fp = join(pkg.dir, fileName);
1234
+ if (!existsSync(fp)) continue;
1235
+ for (const item of readMcpFile(fp, 'plugin', { sourceLabel: `插件:${pkg.label}`, defaultExposure: 'direct' })) {
1236
+ if (!item.overrideOnly) out.push(item);
1237
+ }
1238
+ }
1239
+ }
1240
+ // 2. Workspace root .mcp.json (Claude Code / standard project MCP convention)
1241
+ if (workspace) {
1242
+ const rootMcp = join(resolve(workspace), '.mcp.json');
1243
+ if (existsSync(rootMcp)) {
1244
+ for (const item of readMcpFile(rootMcp, 'workspace-mcp', { sourceLabel: '项目 .mcp.json', defaultExposure: 'direct' })) {
1245
+ if (!item.overrideOnly) out.push(item);
1246
+ }
1247
+ }
1248
+ }
1249
+ return out;
1250
+ }
1251
+
1252
+ function mergeMcpEntries(byName, item) {
1253
+ const prev = byName.get(item.name);
1254
+ if (item.overrideOnly && prev) {
1255
+ byName.set(item.name, {
1256
+ ...prev,
1257
+ enabled: item.enabled,
1258
+ exposure: item.exposure || prev.exposure,
1259
+ toolExposure: Object.keys(item.toolExposure || {}).length ? { ...(prev.toolExposure || {}), ...item.toolExposure } : prev.toolExposure,
1260
+ overriddenInProject: true,
1261
+ });
1262
+ return;
1263
+ }
1264
+ if (!item.overrideOnly) {
1265
+ byName.set(item.name, {
1266
+ ...item,
1267
+ ...(prev && prev.scope !== item.scope ? { overridesSource: prev.sourceLabel } : {}),
1268
+ });
1269
+ }
1270
+ }
1271
+
1272
+ export function listPiMcpServers(workspace = process.cwd(), agentDir = resolvePiAgentDir(), { runtimeServers = [], liveMcpTools = [] } = {}) {
390
1273
  const globalPath = join(agentDir, 'mcp.json');
391
- const projectPath = join(workspace, '.pi', 'mcp.json');
1274
+ const projectPath = workspace ? join(workspace, '.pi', 'mcp.json') : '';
392
1275
  const byName = new Map();
393
- for (const s of readMcpFile(globalPath, 'user')) byName.set(s.name, s);
394
- for (const s of readMcpFile(projectPath, 'project')) byName.set(s.name, s);
395
- return [...byName.values()];
1276
+
1277
+ // Precedence: plugin-bundled < workspace .mcp.json < extension-registered < global mcp.json < project .pi/mcp.json
1278
+ for (const s of discoverBundledAndRootMcpServers(workspace, agentDir)) mergeMcpEntries(byName, s);
1279
+ for (const rs of (Array.isArray(runtimeServers) ? runtimeServers : [])) {
1280
+ if (!rs || !rs.name) continue;
1281
+ const norm = normalizeMcpEntry(rs.name, rs.config || rs, {
1282
+ scope: 'extension',
1283
+ sourceLabel: `扩展注册${rs.extensionName ? ':' + rs.extensionName : ''}`,
1284
+ sourcePath: rs.extensionPath || '',
1285
+ defaultExposure: 'direct',
1286
+ });
1287
+ if (!byName.has(norm.name)) byName.set(norm.name, norm);
1288
+ }
1289
+ for (const s of readMcpFile(globalPath, 'user', { sourceLabel: '全局 mcp.json' })) mergeMcpEntries(byName, s);
1290
+ if (projectPath) {
1291
+ for (const s of readMcpFile(projectPath, 'project', { sourceLabel: '项目 .pi/mcp.json' })) mergeMcpEntries(byName, s);
1292
+ }
1293
+
1294
+ // Group mounted live mcp__<ns>__<tool> tools back onto their server entries
1295
+ const toolsByNs = new Map();
1296
+ for (const toolName of (Array.isArray(liveMcpTools) ? liveMcpTools : [])) {
1297
+ const m = String(toolName || '').match(/^mcp__(.+?)__(.+)$/);
1298
+ if (!m) continue;
1299
+ const ns = m[1];
1300
+ if (!toolsByNs.has(ns)) toolsByNs.set(ns, []);
1301
+ toolsByNs.get(ns).push(toolName);
1302
+ }
1303
+ const toNs = name => String(name || '').replace(/[^a-zA-Z0-9]+/g, '_').toLowerCase();
1304
+ const matchedNs = new Set();
1305
+ const result = [];
1306
+ for (const item of byName.values()) {
1307
+ const ns = toNs(item.name);
1308
+ let tools = toolsByNs.get(item.name) || toolsByNs.get(ns) || [];
1309
+ if (!tools.length) {
1310
+ for (const [k, v] of toolsByNs.entries()) {
1311
+ if (toNs(k) === ns) { tools = v; matchedNs.add(k); break; }
1312
+ }
1313
+ } else {
1314
+ matchedNs.add(toolsByNs.has(item.name) ? item.name : ns);
1315
+ }
1316
+ result.push({ ...item, liveTools: tools });
1317
+ }
1318
+ // Surface any remaining live-mounted MCP servers not present in any static file (e.g. dynamic extension registrations)
1319
+ for (const [ns, tools] of toolsByNs.entries()) {
1320
+ if (matchedNs.has(ns)) continue;
1321
+ result.push({
1322
+ name: ns,
1323
+ scope: 'extension',
1324
+ sourceLabel: '运行时扩展挂载',
1325
+ sourcePath: '',
1326
+ type: 'stdio',
1327
+ command: '',
1328
+ args: [],
1329
+ cwd: '',
1330
+ url: '',
1331
+ env: {},
1332
+ headers: {},
1333
+ exposure: 'direct',
1334
+ toolExposure: {},
1335
+ description: '由已加载插件或 Pi 扩展动态注册;点击「编辑/覆写」可写入 mcp.json 自定义参数。',
1336
+ enabled: true,
1337
+ liveTools: tools,
1338
+ });
1339
+ }
1340
+ return result;
1341
+ }
1342
+
1343
+ /**
1344
+ * Builds a Pi 1.x `LoadedMcpConfig` merging plugin-bundled MCPs, workspace `.mcp.json`,
1345
+ * global `~/.pi/agent/mcp.json`, and project `<workspace>/.pi/mcp.json` (always trusted
1346
+ * for the active Clado workspace) so BOTH main and peer/subagent sessions mount every server.
1347
+ */
1348
+ export function buildMergedPiMcpConfig(workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1349
+ const entries = listPiMcpServers(workspace, agentDir);
1350
+ const projectConfig = workspace ? join(resolve(workspace), '.pi', 'mcp.json') : undefined;
1351
+ const servers = [];
1352
+ const errors = [];
1353
+ for (const item of entries) {
1354
+ if (!item.command && !item.url) continue;
1355
+ const config = {};
1356
+ if (item.url) {
1357
+ config.url = item.url;
1358
+ if (item.headers && Object.keys(item.headers).length) config.headers = item.headers;
1359
+ } else {
1360
+ config.command = item.command;
1361
+ if (item.args?.length) config.args = item.args;
1362
+ if (item.cwd) config.cwd = item.cwd;
1363
+ if (item.env && Object.keys(item.env).length) config.env = item.env;
1364
+ }
1365
+ if (typeof item.timeout === 'number' && item.timeout > 0) config.timeout = item.timeout;
1366
+ if (item.description) config.description = item.description;
1367
+ config.exposure = MCP_EXPOSURES.includes(item.exposure) ? item.exposure : 'direct';
1368
+ if (item.toolExposure && Object.keys(item.toolExposure).length) config.toolExposure = item.toolExposure;
1369
+ if (item.enabled === false) config.enabled = false;
1370
+ servers.push({
1371
+ name: item.name,
1372
+ config,
1373
+ source: item.sourcePath || join(agentDir, 'mcp.json'),
1374
+ scope: item.scope === 'user' ? 'global' : 'project',
1375
+ });
1376
+ }
1377
+ return { servers, errors, ...(projectConfig ? { projectConfig } : {}) };
1378
+ }
1379
+
1380
+ export function readPiMcpRawJson(workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1381
+ const userPath = join(agentDir, 'mcp.json');
1382
+ const projectPath = join(workspace, '.pi', 'mcp.json');
1383
+ const readRaw = p => {
1384
+ if (!existsSync(p)) return JSON.stringify({ mcpServers: {} }, null, 2) + '\n';
1385
+ try { return readFileSync(p, 'utf8'); } catch { return JSON.stringify({ mcpServers: {} }, null, 2) + '\n'; }
1386
+ };
1387
+ return {
1388
+ userPath,
1389
+ projectPath,
1390
+ user: readRaw(userPath),
1391
+ project: readRaw(projectPath),
1392
+ };
1393
+ }
1394
+
1395
+ export function savePiMcpRawJson(scope = 'user', jsonText = '', workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1396
+ const parsed = typeof jsonText === 'string' ? JSON.parse(jsonText || '{"mcpServers":{}}') : jsonText;
1397
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1398
+ throw new Error('mcp.json 顶层必须是 JSON 对象。');
1399
+ }
1400
+ const normalized = parsed.mcpServers && typeof parsed.mcpServers === 'object'
1401
+ ? parsed
1402
+ : { mcpServers: parsed };
1403
+ const targetScope = scope === 'project' ? 'project' : 'user';
1404
+ const filePath = targetScope === 'project' ? join(workspace, '.pi', 'mcp.json') : join(agentDir, 'mcp.json');
1405
+ writeJsonSafe(filePath, normalized);
1406
+ return { ok: true, scope: targetScope, path: filePath, count: Object.keys(normalized.mcpServers || {}).length };
396
1407
  }
397
1408
 
398
1409
  export function savePiMcpServer(input, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
@@ -402,38 +1413,87 @@ export function savePiMcpServer(input, workspace = process.cwd(), agentDir = res
402
1413
  const filePath = scope === 'project' ? join(workspace, '.pi', 'mcp.json') : join(agentDir, 'mcp.json');
403
1414
  const doc = readJsonSafe(filePath, { mcpServers: {} });
404
1415
  if (!doc.mcpServers || typeof doc.mcpServers !== 'object') doc.mcpServers = {};
1416
+ const prevName = String(input?.originalName || '').trim();
1417
+ if (prevName && prevName !== name && prevName in doc.mcpServers) {
1418
+ delete doc.mcpServers[prevName];
1419
+ }
405
1420
  const entry = {};
406
- if (input?.url && String(input.url).trim()) {
407
- entry.url = String(input.url).trim();
408
- if (input.headers && typeof input.headers === 'object') entry.headers = input.headers;
1421
+ if (input?.overrideOnly) {
1422
+ // Allow overriding exposure/enabled/toolExposure on plugin or extension-registered MCP servers
1423
+ const exposure = MCP_EXPOSURES.includes(input?.exposure) ? input.exposure : 'direct';
1424
+ entry.exposure = exposure;
1425
+ entry.enabled = input?.enabled !== false;
1426
+ if (input?.toolExposure && typeof input.toolExposure === 'object' && !Array.isArray(input.toolExposure)) {
1427
+ const cleanMap = {};
1428
+ for (const [tk, tv] of Object.entries(input.toolExposure)) {
1429
+ const k = String(tk || '').trim();
1430
+ if (k && MCP_EXPOSURES.includes(tv)) cleanMap[k] = tv;
1431
+ }
1432
+ if (Object.keys(cleanMap).length) entry.toolExposure = cleanMap;
1433
+ }
1434
+ doc.mcpServers[name] = entry;
1435
+ writeJsonSafe(filePath, doc);
1436
+ return { ok: true, name, scope, exposure, overrideOnly: true };
1437
+ }
1438
+ if (input?.type === 'http' || (input?.url && String(input.url).trim() && input?.type !== 'stdio')) {
1439
+ const urlStr = String(input?.url || '').trim();
1440
+ if (!urlStr) throw new Error('请填写远程 MCP 端点 URL。');
1441
+ entry.url = urlStr;
1442
+ if (input.headers && typeof input.headers === 'object' && Object.keys(input.headers).length) {
1443
+ entry.headers = input.headers;
1444
+ }
409
1445
  } else {
410
1446
  const cmd = String(input?.command || '').trim();
411
1447
  if (!cmd) throw new Error('请填写 MCP 启动命令(command)或远程 URL。');
412
1448
  entry.command = cmd;
413
1449
  entry.args = Array.isArray(input?.args)
414
- ? input.args.map(String)
1450
+ ? input.args.map(String).filter(Boolean)
415
1451
  : typeof input?.args === 'string' && input.args.trim()
416
1452
  ? input.args.trim().split(/\s+/)
417
1453
  : [];
1454
+ if (input?.cwd && String(input.cwd).trim()) entry.cwd = String(input.cwd).trim();
418
1455
  if (input.env && typeof input.env === 'object' && Object.keys(input.env).length) entry.env = input.env;
419
1456
  }
420
- if (input?.enabled === false) entry.disabled = true;
1457
+ if (typeof input?.timeout === 'number' && Number.isFinite(input.timeout) && input.timeout > 0) {
1458
+ entry.timeout = Math.round(input.timeout);
1459
+ }
1460
+ if (input?.description && String(input.description).trim()) {
1461
+ entry.description = String(input.description).trim().slice(0, 250);
1462
+ }
1463
+ const exposure = MCP_EXPOSURES.includes(input?.exposure) ? input.exposure : 'direct';
1464
+ entry.exposure = exposure;
1465
+ if (input?.toolExposure && typeof input.toolExposure === 'object' && !Array.isArray(input.toolExposure)) {
1466
+ const cleanMap = {};
1467
+ for (const [tk, tv] of Object.entries(input.toolExposure)) {
1468
+ const k = String(tk || '').trim();
1469
+ if (k && MCP_EXPOSURES.includes(tv)) cleanMap[k] = tv;
1470
+ }
1471
+ if (Object.keys(cleanMap).length) entry.toolExposure = cleanMap;
1472
+ }
1473
+ if (input?.enabled === false) entry.enabled = false;
421
1474
  doc.mcpServers[name] = entry;
422
1475
  writeJsonSafe(filePath, doc);
423
- return { ok: true, name, scope };
1476
+ return { ok: true, name, scope, exposure };
424
1477
  }
425
1478
 
426
1479
  export function togglePiMcpServer(name, enabled, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
427
1480
  for (const filePath of [join(workspace, '.pi', 'mcp.json'), join(agentDir, 'mcp.json')]) {
428
1481
  const doc = readJsonSafe(filePath, null);
429
1482
  if (doc?.mcpServers && name in doc.mcpServers) {
430
- if (enabled) delete doc.mcpServers[name].disabled;
431
- else doc.mcpServers[name].disabled = true;
1483
+ delete doc.mcpServers[name].disabled;
1484
+ if (enabled) delete doc.mcpServers[name].enabled;
1485
+ else doc.mcpServers[name].enabled = false;
432
1486
  writeJsonSafe(filePath, doc);
433
1487
  return { ok: true, name, enabled: Boolean(enabled) };
434
1488
  }
435
1489
  }
436
- return { ok: false, name };
1490
+ // Plugin-bundled / .mcp.json / extension-registered server: persist toggle override in project .pi/mcp.json
1491
+ const projectPath = join(workspace, '.pi', 'mcp.json');
1492
+ const doc = readJsonSafe(projectPath, { mcpServers: {} });
1493
+ if (!doc.mcpServers || typeof doc.mcpServers !== 'object') doc.mcpServers = {};
1494
+ doc.mcpServers[name] = { ...(doc.mcpServers[name] || {}), enabled: Boolean(enabled) };
1495
+ writeJsonSafe(projectPath, doc);
1496
+ return { ok: true, name, enabled: Boolean(enabled), overridden: true };
437
1497
  }
438
1498
 
439
1499
  export function deletePiMcpServer(name, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
@@ -466,6 +1526,76 @@ export function importPiMcpJson(jsonText, scope = 'user', workspace = process.cw
466
1526
  return { ok: true, count };
467
1527
  }
468
1528
 
1529
+ // ============================================================================
1530
+ // 3.5 Plugin / Extension Injected Parameters (.clado/plugin-params.json + user)
1531
+ // ============================================================================
1532
+
1533
+ export function readPluginParams(workspace = process.cwd(), stateDir = '', agentDir = resolvePiAgentDir()) {
1534
+ const userPath = join(agentDir, 'clado-plugin-params.json');
1535
+ const wsPath = stateDir ? join(stateDir, 'plugin-params.json') : join(workspace, '.clado', 'plugin-params.json');
1536
+ const userRaw = readJsonSafe(userPath, {});
1537
+ const wsRaw = readJsonSafe(wsPath, {});
1538
+ const merged = {};
1539
+ for (const [id, val] of Object.entries(userRaw && typeof userRaw === 'object' ? userRaw : {})) {
1540
+ if (val && typeof val === 'object') merged[id] = { scope: 'user', env: val.env || {}, params: val.params || {} };
1541
+ }
1542
+ for (const [id, val] of Object.entries(wsRaw && typeof wsRaw === 'object' ? wsRaw : {})) {
1543
+ if (val && typeof val === 'object') {
1544
+ const prev = merged[id] || { env: {}, params: {} };
1545
+ merged[id] = {
1546
+ scope: 'project',
1547
+ env: { ...(prev.env || {}), ...(val.env || {}) },
1548
+ params: { ...(prev.params || {}), ...(val.params || {}) },
1549
+ };
1550
+ }
1551
+ }
1552
+ return { userPath, projectPath: wsPath, items: merged };
1553
+ }
1554
+
1555
+ export function savePluginParams({ pluginId, scope = 'project', env = {}, params = {} } = {}, workspace = process.cwd(), stateDir = '', agentDir = resolvePiAgentDir()) {
1556
+ const id = String(pluginId || '').trim();
1557
+ if (!id) throw new Error('插件或扩展标识不能为空。');
1558
+ const targetScope = scope === 'user' ? 'user' : 'project';
1559
+ const filePath = targetScope === 'user'
1560
+ ? join(agentDir, 'clado-plugin-params.json')
1561
+ : (stateDir ? join(stateDir, 'plugin-params.json') : join(workspace, '.clado', 'plugin-params.json'));
1562
+ const doc = readJsonSafe(filePath, {});
1563
+ const cleanEnv = {};
1564
+ if (env && typeof env === 'object' && !Array.isArray(env)) {
1565
+ for (const [k, v] of Object.entries(env)) {
1566
+ const ck = String(k || '').trim();
1567
+ if (ck) cleanEnv[ck] = String(v ?? '');
1568
+ }
1569
+ }
1570
+ const cleanParams = (params && typeof params === 'object' && !Array.isArray(params)) ? params : {};
1571
+ doc[id] = { env: cleanEnv, params: cleanParams, updatedAt: new Date().toISOString() };
1572
+ writeJsonSafe(filePath, doc);
1573
+ return { ok: true, pluginId: id, scope: targetScope, path: filePath };
1574
+ }
1575
+
1576
+ export function deletePluginParams(pluginId, scope = 'all', workspace = process.cwd(), stateDir = '', agentDir = resolvePiAgentDir()) {
1577
+ const id = String(pluginId || '').trim();
1578
+ if (!id) return { ok: false };
1579
+ const paths = scope === 'user'
1580
+ ? [join(agentDir, 'clado-plugin-params.json')]
1581
+ : scope === 'project'
1582
+ ? [stateDir ? join(stateDir, 'plugin-params.json') : join(workspace, '.clado', 'plugin-params.json')]
1583
+ : [
1584
+ join(agentDir, 'clado-plugin-params.json'),
1585
+ stateDir ? join(stateDir, 'plugin-params.json') : join(workspace, '.clado', 'plugin-params.json'),
1586
+ ];
1587
+ let removed = false;
1588
+ for (const p of paths) {
1589
+ const doc = readJsonSafe(p, null);
1590
+ if (doc && typeof doc === 'object' && id in doc) {
1591
+ delete doc[id];
1592
+ writeJsonSafe(p, doc);
1593
+ removed = true;
1594
+ }
1595
+ }
1596
+ return { ok: removed, pluginId: id };
1597
+ }
1598
+
469
1599
  export function savePiSkill({ name, description, content, scope = 'user' }, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
470
1600
  const slug = String(name || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
471
1601
  if (!slug) throw new Error('Skill 名称不能为空。');
@@ -628,3 +1758,654 @@ export function toggleCanvasComponent(id, enabled, agentDir = resolvePiAgentDir(
628
1758
  writeJsonSafe(file, saved);
629
1759
  return readCanvasComponentsConfig(agentDir);
630
1760
  }
1761
+
1762
+ // ============================================================================
1763
+ // 6. Clado Platform Context & Reference Manual (~/.pi/agent/clado-*.md)
1764
+ // Automatically injected into EVERY persona (builtin, custom, or external).
1765
+ // ============================================================================
1766
+
1767
+ export function ensureCladoPlatformDocs(agentDir = resolvePiAgentDir()) {
1768
+ mkdirSync(agentDir, { recursive: true });
1769
+ const contextPath = join(agentDir, 'clado-context.md');
1770
+ const referencePath = join(agentDir, 'clado-reference.md');
1771
+ const defaultContext = readPackageDoc(PACKAGE_CONTEXT_DOC_PATH);
1772
+ const defaultReference = readPackageDoc(PACKAGE_REFERENCE_DOC_PATH);
1773
+
1774
+ if (!existsSync(contextPath) && defaultContext) {
1775
+ writeFileSync(contextPath, defaultContext, 'utf8');
1776
+ }
1777
+ if (!existsSync(referencePath) && defaultReference) {
1778
+ writeFileSync(referencePath, defaultReference, 'utf8');
1779
+ }
1780
+
1781
+ const contextContent = existsSync(contextPath) ? readFileSync(contextPath, 'utf8') : defaultContext;
1782
+ const referenceContent = existsSync(referencePath) ? readFileSync(referencePath, 'utf8') : defaultReference;
1783
+ const customized = contextContent.trim() !== defaultContext.trim();
1784
+
1785
+ return {
1786
+ contextPath,
1787
+ referencePath,
1788
+ packageContextPath: PACKAGE_CONTEXT_DOC_PATH,
1789
+ packageReferencePath: PACKAGE_REFERENCE_DOC_PATH,
1790
+ contextContent,
1791
+ referenceContent,
1792
+ customized,
1793
+ };
1794
+ }
1795
+
1796
+ export function readCladoPlatformContext(agentDir = resolvePiAgentDir()) {
1797
+ const docs = ensureCladoPlatformDocs(agentDir);
1798
+ return String(docs.contextContent || '')
1799
+ .replace(/\{\{CLADO_CONTEXT_PATH\}\}/g, docs.contextPath)
1800
+ .replace(/\{\{CLADO_REFERENCE_PATH\}\}/g, docs.referencePath);
1801
+ }
1802
+
1803
+ export function saveCladoPlatformContext(content, agentDir = resolvePiAgentDir()) {
1804
+ mkdirSync(agentDir, { recursive: true });
1805
+ const contextPath = join(agentDir, 'clado-context.md');
1806
+ writeFileSync(contextPath, String(content || ''), 'utf8');
1807
+ return { ok: true, ...ensureCladoPlatformDocs(agentDir) };
1808
+ }
1809
+
1810
+ export function resetCladoPlatformDocs(agentDir = resolvePiAgentDir()) {
1811
+ mkdirSync(agentDir, { recursive: true });
1812
+ const contextPath = join(agentDir, 'clado-context.md');
1813
+ const referencePath = join(agentDir, 'clado-reference.md');
1814
+ const defaultContext = readPackageDoc(PACKAGE_CONTEXT_DOC_PATH);
1815
+ const defaultReference = readPackageDoc(PACKAGE_REFERENCE_DOC_PATH);
1816
+ if (defaultContext) writeFileSync(contextPath, defaultContext, 'utf8');
1817
+ if (defaultReference) writeFileSync(referencePath, defaultReference, 'utf8');
1818
+ return { ok: true, ...ensureCladoPlatformDocs(agentDir) };
1819
+ }
1820
+
1821
+ // ============================================================================
1822
+ // 7. Full Pi 1.x Settings Bridge (User ~/.pi/agent/settings.json + Project .pi/settings.json)
1823
+ // ============================================================================
1824
+
1825
+ export const BUILTIN_PI_TOOLS = [
1826
+ { id: 'read', label: 'read', desc: '读取工作区文件与图片' },
1827
+ { id: 'bash', label: 'bash', desc: '在工作区执行终端命令' },
1828
+ { id: 'edit', label: 'edit', desc: '局部精确修改文件内容' },
1829
+ { id: 'write', label: 'write', desc: '新建或整文件覆写' },
1830
+ { id: 'grep', label: 'grep', desc: '正则全文检索代码' },
1831
+ { id: 'find', label: 'find', desc: '按路径模式查找文件' },
1832
+ { id: 'ls', label: 'ls', desc: '列出目录内容' },
1833
+ { id: 'codemode', label: 'codemode', desc: 'Pi 1.x 代码编排工具模式' },
1834
+ { id: 'tool_search', label: 'tool_search', desc: 'Pi 1.x 延迟工具发现检索' },
1835
+ ];
1836
+
1837
+ export function readFullPiSettings(workspace = process.cwd(), agentDir = resolvePiAgentDir(), activeContextWindow = 128000) {
1838
+ const userPath = join(agentDir, 'settings.json');
1839
+ const projectPath = workspace ? join(workspace, '.pi', 'settings.json') : '';
1840
+ const userRaw = readJsonSafe(userPath, {});
1841
+ const projectRaw = projectPath ? readJsonSafe(projectPath, {}) : {};
1842
+ const merged = {
1843
+ ...userRaw,
1844
+ ...projectRaw,
1845
+ compaction: { ...(userRaw.compaction || {}), ...(projectRaw.compaction || {}) },
1846
+ retry: {
1847
+ ...(userRaw.retry || {}),
1848
+ ...(projectRaw.retry || {}),
1849
+ provider: { ...(userRaw.retry?.provider || {}), ...(projectRaw.retry?.provider || {}) },
1850
+ },
1851
+ branchSummary: { ...(userRaw.branchSummary || {}), ...(projectRaw.branchSummary || {}) },
1852
+ images: { ...(userRaw.images || {}), ...(projectRaw.images || {}) },
1853
+ markdown: { ...(userRaw.markdown || {}), ...(projectRaw.markdown || {}) },
1854
+ notices: { ...(userRaw.notices || {}), ...(projectRaw.notices || {}) },
1855
+ codemode: { ...(userRaw.codemode || {}), ...(projectRaw.codemode || {}) },
1856
+ thinkingBudgets: { ...(userRaw.thinkingBudgets || {}), ...(projectRaw.thinkingBudgets || {}) },
1857
+ modelThinkingLevels: { ...(userRaw.modelThinkingLevels || {}), ...(projectRaw.modelThinkingLevels || {}) },
1858
+ };
1859
+ const runtime = readRuntimeSettings(workspace, agentDir, activeContextWindow);
1860
+ return {
1861
+ userPath,
1862
+ projectPath,
1863
+ user: userRaw,
1864
+ project: projectRaw,
1865
+ effective: {
1866
+ // General
1867
+ steeringMode: merged.steeringMode || 'one-at-a-time',
1868
+ followUpMode: merged.followUpMode || 'one-at-a-time',
1869
+ shellPath: merged.shellPath || '',
1870
+ shellCommandPrefix: merged.shellCommandPrefix || '',
1871
+ httpProxy: merged.httpProxy || '',
1872
+ httpIdleTimeoutMs: merged.httpIdleTimeoutMs ?? '',
1873
+ websocketConnectTimeoutMs: merged.websocketConnectTimeoutMs ?? '',
1874
+ externalEditor: merged.externalEditor || '',
1875
+ npmCommand: Array.isArray(merged.npmCommand) ? merged.npmCommand : [],
1876
+ defaultProjectTrust: merged.defaultProjectTrust || 'ask',
1877
+ enableSkillCommands: merged.enableSkillCommands !== false,
1878
+ images: {
1879
+ autoResize: merged.images?.autoResize !== false,
1880
+ blockImages: Boolean(merged.images?.blockImages),
1881
+ },
1882
+ codemode: {
1883
+ mode: merged.codemode?.mode === 'only' ? 'only' : 'on',
1884
+ inlineBudget: Number(merged.codemode?.inlineBudget) || 0,
1885
+ },
1886
+ notices: {
1887
+ cacheMisses: merged.notices?.cacheMisses !== false,
1888
+ cacheWarming: merged.notices?.cacheWarming !== false,
1889
+ compactionCosts: merged.notices?.compactionCosts !== false,
1890
+ reasoningDrops: merged.notices?.reasoningDrops !== false,
1891
+ },
1892
+ // Appearance
1893
+ theme: merged.theme || '',
1894
+ hideThinkingBlock: runtime.hideThinkingBlock,
1895
+ markdown: {
1896
+ codeBlockIndent: merged.markdown?.codeBlockIndent ?? ' ',
1897
+ mermaid: ['off', 'final', 'streaming'].includes(merged.markdown?.mermaid) ? merged.markdown.mermaid : 'final',
1898
+ },
1899
+ // Models & Runtime
1900
+ defaultProvider: merged.defaultProvider || '',
1901
+ defaultModel: merged.defaultModel || '',
1902
+ enabledModels: Array.isArray(merged.enabledModels) ? merged.enabledModels : [],
1903
+ defaultThinkingLevel: runtime.thinkingLevel,
1904
+ modelThinkingLevels: merged.modelThinkingLevels || {},
1905
+ thinkingBudgets: {
1906
+ minimal: Number(merged.thinkingBudgets?.minimal) || 1024,
1907
+ low: Number(merged.thinkingBudgets?.low) || 4096,
1908
+ medium: Number(merged.thinkingBudgets?.medium) || 10000,
1909
+ high: Number(merged.thinkingBudgets?.high) || 24000,
1910
+ },
1911
+ transport: runtime.transport,
1912
+ cacheWarming: runtime.cacheWarming,
1913
+ compaction: {
1914
+ enabled: runtime.compactionEnabled,
1915
+ triggerPercent: runtime.compactionTriggerPercent,
1916
+ reserveTokens: runtime.reserveTokens,
1917
+ keepRecentTokens: runtime.keepRecentTokens,
1918
+ modelOverrides: merged.compaction?.modelOverrides && typeof merged.compaction.modelOverrides === 'object' ? merged.compaction.modelOverrides : {},
1919
+ },
1920
+ retry: {
1921
+ enabled: runtime.retryEnabled,
1922
+ maxRetries: runtime.maxRetries,
1923
+ baseDelayMs: Number(merged.retry?.baseDelayMs) || 2000,
1924
+ maxAgentDelayMs: Number(merged.retry?.maxAgentDelayMs) || 60000,
1925
+ provider: {
1926
+ timeoutMs: Number(merged.retry?.provider?.timeoutMs) || 0,
1927
+ maxRetries: Number(merged.retry?.provider?.maxRetries) || 0,
1928
+ maxRetryDelayMs: Number(merged.retry?.provider?.maxRetryDelayMs) || 0,
1929
+ },
1930
+ },
1931
+ branchSummary: {
1932
+ reserveTokens: Number(merged.branchSummary?.reserveTokens) || 16384,
1933
+ skipPrompt: Boolean(merged.branchSummary?.skipPrompt),
1934
+ },
1935
+ // Tools & Resource paths
1936
+ defaultTools: Array.isArray(merged.defaultTools) ? merged.defaultTools : [],
1937
+ skills: Array.isArray(merged.skills) ? merged.skills : (Array.isArray(merged.skills?.customDirectories) ? merged.skills.customDirectories : []),
1938
+ prompts: Array.isArray(merged.prompts) ? merged.prompts : [],
1939
+ extensions: Array.isArray(merged.extensions) ? merged.extensions : [],
1940
+ },
1941
+ builtinTools: BUILTIN_PI_TOOLS,
1942
+ };
1943
+ }
1944
+
1945
+ export async function saveFullPiSettings(patch = {}, scope = 'user', workspace = process.cwd(), agentDir = resolvePiAgentDir(), activeContextWindow = 128000) {
1946
+ const sc = scope === 'project' && workspace ? 'project' : 'user';
1947
+ const filePath = sc === 'project' ? join(workspace, '.pi', 'settings.json') : join(agentDir, 'settings.json');
1948
+ const raw = readJsonSafe(filePath, {});
1949
+
1950
+ const assignOrDelete = (obj, key, val) => {
1951
+ if (val === undefined) return;
1952
+ if (val === '' || val === null) delete obj[key];
1953
+ else obj[key] = val;
1954
+ };
1955
+
1956
+ // Top-level simple keys
1957
+ if (patch.steeringMode && ['one-at-a-time', 'all'].includes(patch.steeringMode)) raw.steeringMode = patch.steeringMode;
1958
+ if (patch.followUpMode && ['one-at-a-time', 'all'].includes(patch.followUpMode)) raw.followUpMode = patch.followUpMode;
1959
+ assignOrDelete(raw, 'shellPath', patch.shellPath !== undefined ? String(patch.shellPath || '').trim() : undefined);
1960
+ assignOrDelete(raw, 'shellCommandPrefix', patch.shellCommandPrefix !== undefined ? String(patch.shellCommandPrefix || '').trim() : undefined);
1961
+ assignOrDelete(raw, 'httpProxy', patch.httpProxy !== undefined ? String(patch.httpProxy || '').trim() : undefined);
1962
+ assignOrDelete(raw, 'externalEditor', patch.externalEditor !== undefined ? String(patch.externalEditor || '').trim() : undefined);
1963
+ assignOrDelete(raw, 'theme', patch.theme !== undefined ? String(patch.theme || '').trim() : undefined);
1964
+
1965
+ if (patch.httpIdleTimeoutMs !== undefined) {
1966
+ if (patch.httpIdleTimeoutMs === 'disabled') raw.httpIdleTimeoutMs = 'disabled';
1967
+ else if (patch.httpIdleTimeoutMs === '' || patch.httpIdleTimeoutMs === null || Number(patch.httpIdleTimeoutMs) <= 0) delete raw.httpIdleTimeoutMs;
1968
+ else raw.httpIdleTimeoutMs = Math.round(Number(patch.httpIdleTimeoutMs));
1969
+ }
1970
+ if (patch.websocketConnectTimeoutMs !== undefined) {
1971
+ if (patch.websocketConnectTimeoutMs === 'disabled') raw.websocketConnectTimeoutMs = 'disabled';
1972
+ else if (patch.websocketConnectTimeoutMs === '' || patch.websocketConnectTimeoutMs === null || Number(patch.websocketConnectTimeoutMs) <= 0) delete raw.websocketConnectTimeoutMs;
1973
+ else raw.websocketConnectTimeoutMs = Math.round(Number(patch.websocketConnectTimeoutMs));
1974
+ }
1975
+ if (patch.npmCommand !== undefined) {
1976
+ const arr = Array.isArray(patch.npmCommand)
1977
+ ? patch.npmCommand.map(s => String(s || '').trim()).filter(Boolean)
1978
+ : String(patch.npmCommand || '').trim().split(/\s+/).filter(Boolean);
1979
+ if (arr.length) raw.npmCommand = arr;
1980
+ else delete raw.npmCommand;
1981
+ }
1982
+ if (patch.defaultProjectTrust && ['ask', 'always', 'never'].includes(patch.defaultProjectTrust)) {
1983
+ raw.defaultProjectTrust = patch.defaultProjectTrust;
1984
+ }
1985
+ if (typeof patch.enableSkillCommands === 'boolean') raw.enableSkillCommands = patch.enableSkillCommands;
1986
+ if (typeof patch.hideThinkingBlock === 'boolean') raw.hideThinkingBlock = patch.hideThinkingBlock;
1987
+ if (patch.defaultThinkingLevel && THINKING_LEVELS.includes(patch.defaultThinkingLevel)) raw.defaultThinkingLevel = patch.defaultThinkingLevel;
1988
+ if (patch.transport && TRANSPORT_MODES.includes(patch.transport)) raw.transport = patch.transport;
1989
+ if (patch.cacheWarming && CACHE_WARMING_MODES.includes(patch.cacheWarming)) raw.cacheWarming = patch.cacheWarming;
1990
+
1991
+ // Nested objects
1992
+ if (patch.images && typeof patch.images === 'object') {
1993
+ raw.images = { ...(raw.images || {}), ...patch.images };
1994
+ }
1995
+ if (patch.codemode && typeof patch.codemode === 'object') {
1996
+ const cm = { ...(raw.codemode || {}) };
1997
+ if (['on', 'only'].includes(patch.codemode.mode)) cm.mode = patch.codemode.mode;
1998
+ if (Number(patch.codemode.inlineBudget) > 0) cm.inlineBudget = Math.round(Number(patch.codemode.inlineBudget));
1999
+ else if (patch.codemode.inlineBudget === 0 || patch.codemode.inlineBudget === '') delete cm.inlineBudget;
2000
+ raw.codemode = cm;
2001
+ }
2002
+ if (patch.notices && typeof patch.notices === 'object') {
2003
+ raw.notices = { ...(raw.notices || {}), ...patch.notices };
2004
+ }
2005
+ if (patch.markdown && typeof patch.markdown === 'object') {
2006
+ const md = { ...(raw.markdown || {}) };
2007
+ if (typeof patch.markdown.codeBlockIndent === 'string') md.codeBlockIndent = patch.markdown.codeBlockIndent;
2008
+ if (['off', 'final', 'streaming'].includes(patch.markdown.mermaid)) md.mermaid = patch.markdown.mermaid;
2009
+ raw.markdown = md;
2010
+ }
2011
+ if (Array.isArray(patch.enabledModels)) {
2012
+ const clean = [...new Set(patch.enabledModels.map(s => String(s || '').trim()).filter(Boolean))];
2013
+ if (clean.length) raw.enabledModels = clean;
2014
+ else delete raw.enabledModels;
2015
+ }
2016
+ if (patch.modelThinkingLevels && typeof patch.modelThinkingLevels === 'object') {
2017
+ const clean = {};
2018
+ for (const [k, v] of Object.entries(patch.modelThinkingLevels)) {
2019
+ if (String(k).trim() && THINKING_LEVELS.includes(v)) clean[String(k).trim()] = v;
2020
+ }
2021
+ if (Object.keys(clean).length) raw.modelThinkingLevels = clean;
2022
+ else delete raw.modelThinkingLevels;
2023
+ }
2024
+ if (patch.thinkingBudgets && typeof patch.thinkingBudgets === 'object') {
2025
+ const tb = { ...(raw.thinkingBudgets || {}) };
2026
+ for (const lvl of ['minimal', 'low', 'medium', 'high']) {
2027
+ if (Number(patch.thinkingBudgets[lvl]) > 0) tb[lvl] = Math.round(Number(patch.thinkingBudgets[lvl]));
2028
+ }
2029
+ raw.thinkingBudgets = tb;
2030
+ }
2031
+ if (patch.compaction && typeof patch.compaction === 'object') {
2032
+ const comp = { ...(raw.compaction || {}) };
2033
+ if (typeof patch.compaction.enabled === 'boolean') comp.enabled = patch.compaction.enabled;
2034
+ if (Number(patch.compaction.keepRecentTokens) >= 2048) comp.keepRecentTokens = Math.round(Number(patch.compaction.keepRecentTokens));
2035
+ if (Number(patch.compaction.triggerPercent) >= 50 && Number(patch.compaction.triggerPercent) <= 95) {
2036
+ const pct = Math.round(Number(patch.compaction.triggerPercent));
2037
+ const ctxWin = clampInt(activeContextWindow, 8192, 4000000, 128000);
2038
+ comp.reserveTokens = Math.max(4096, Math.round(ctxWin * (1 - pct / 100)));
2039
+ const sidecarPath = join(agentDir, 'clado-runtime.json');
2040
+ const sidecar = readJsonSafe(sidecarPath, {});
2041
+ sidecar.compactionTriggerPercent = pct;
2042
+ writeJsonSafe(sidecarPath, sidecar);
2043
+ } else if (Number(patch.compaction.reserveTokens) >= 4096) {
2044
+ comp.reserveTokens = Math.round(Number(patch.compaction.reserveTokens));
2045
+ }
2046
+ if (patch.compaction.modelOverrides && typeof patch.compaction.modelOverrides === 'object') {
2047
+ const cleanOv = {};
2048
+ for (const [mk, mv] of Object.entries(patch.compaction.modelOverrides)) {
2049
+ if (!String(mk).trim() || !mv || typeof mv !== 'object') continue;
2050
+ const entry = {};
2051
+ if (Number(mv.reserveTokens) >= 1024) entry.reserveTokens = Math.round(Number(mv.reserveTokens));
2052
+ if (Number(mv.keepRecentTokens) >= 1024) entry.keepRecentTokens = Math.round(Number(mv.keepRecentTokens));
2053
+ if (Object.keys(entry).length) cleanOv[String(mk).trim()] = entry;
2054
+ }
2055
+ if (Object.keys(cleanOv).length) comp.modelOverrides = cleanOv;
2056
+ else delete comp.modelOverrides;
2057
+ }
2058
+ raw.compaction = comp;
2059
+ }
2060
+ if (patch.retry && typeof patch.retry === 'object') {
2061
+ const rt = { ...(raw.retry || {}) };
2062
+ if (typeof patch.retry.enabled === 'boolean') rt.enabled = patch.retry.enabled;
2063
+ if (patch.retry.maxRetries !== undefined) rt.maxRetries = clampInt(patch.retry.maxRetries, 0, 10, 3);
2064
+ if (Number(patch.retry.baseDelayMs) > 0) rt.baseDelayMs = Math.round(Number(patch.retry.baseDelayMs));
2065
+ if (Number(patch.retry.maxAgentDelayMs) > 0) rt.maxAgentDelayMs = Math.round(Number(patch.retry.maxAgentDelayMs));
2066
+ if (patch.retry.provider && typeof patch.retry.provider === 'object') {
2067
+ const pr = {};
2068
+ if (Number(patch.retry.provider.timeoutMs) > 0) pr.timeoutMs = Math.round(Number(patch.retry.provider.timeoutMs));
2069
+ if (Number(patch.retry.provider.maxRetries) > 0) pr.maxRetries = Math.round(Number(patch.retry.provider.maxRetries));
2070
+ if (Number(patch.retry.provider.maxRetryDelayMs) > 0) pr.maxRetryDelayMs = Math.round(Number(patch.retry.provider.maxRetryDelayMs));
2071
+ if (Object.keys(pr).length) rt.provider = pr;
2072
+ else delete rt.provider;
2073
+ }
2074
+ raw.retry = rt;
2075
+ }
2076
+ if (patch.branchSummary && typeof patch.branchSummary === 'object') {
2077
+ const bs = { ...(raw.branchSummary || {}) };
2078
+ if (Number(patch.branchSummary.reserveTokens) >= 1024) bs.reserveTokens = Math.round(Number(patch.branchSummary.reserveTokens));
2079
+ if (typeof patch.branchSummary.skipPrompt === 'boolean') bs.skipPrompt = patch.branchSummary.skipPrompt;
2080
+ raw.branchSummary = bs;
2081
+ }
2082
+ for (const listKey of ['defaultTools', 'skills', 'prompts', 'extensions']) {
2083
+ if (Array.isArray(patch[listKey])) {
2084
+ const clean = [...new Set(patch[listKey].map(s => String(s || '').trim()).filter(Boolean))];
2085
+ if (clean.length) raw[listKey] = clean;
2086
+ else delete raw[listKey];
2087
+ }
2088
+ }
2089
+
2090
+ writeJsonSafe(filePath, raw);
2091
+ return {
2092
+ ok: true,
2093
+ scope: sc,
2094
+ path: filePath,
2095
+ piSettings: readFullPiSettings(workspace, agentDir, activeContextWindow),
2096
+ };
2097
+ }
2098
+
2099
+ // ============================================================================
2100
+ // 8. Provider Connectivity Probe
2101
+ // ============================================================================
2102
+
2103
+ export async function testProviderConnection({ providerId, api, baseUrl, apiKey, headers } = {}, agentDir = resolvePiAgentDir()) {
2104
+ const cleanId = String(providerId || '').trim().toLowerCase();
2105
+ const preset = PROVIDER_CATALOG.find(p => p.id === cleanId);
2106
+ const auth = readPiAuth(agentDir);
2107
+ const modelsCfg = readPiModelsConfig(agentDir);
2108
+ const custom = modelsCfg.providers?.[cleanId] || {};
2109
+
2110
+ const resolvedApi = api || custom.api || preset?.api || 'openai-completions';
2111
+ const resolvedBase = String(baseUrl || custom.baseUrl || preset?.defaultBaseUrl || '').trim().replace(/\/+$/, '');
2112
+ const resolvedKey = (typeof apiKey === 'string' && apiKey.trim() && !apiKey.includes('••••'))
2113
+ ? apiKey.trim()
2114
+ : (auth[cleanId]?.key || custom.apiKey || (preset?.envKey ? process.env[preset.envKey] : '') || '');
2115
+ if (!resolvedBase) return { ok: false, status: 0, latencyMs: 0, discoveredModels: [], message: '请先填写 Base URL' };
2116
+
2117
+ const reqHeaders = {
2118
+ accept: 'application/json',
2119
+ ...(custom.headers || {}),
2120
+ ...(headers && typeof headers === 'object' ? headers : {}),
2121
+ };
2122
+ let probeUrl = `${resolvedBase}/models`;
2123
+ if (resolvedApi === 'anthropic-messages') {
2124
+ probeUrl = resolvedBase.endsWith('/v1') ? `${resolvedBase}/models` : `${resolvedBase}/v1/models`;
2125
+ if (resolvedKey) reqHeaders['x-api-key'] = resolvedKey;
2126
+ reqHeaders['anthropic-version'] = reqHeaders['anthropic-version'] || '2023-06-01';
2127
+ } else if (resolvedApi === 'google-generative-ai') {
2128
+ probeUrl = `${resolvedBase}/models${resolvedKey ? `?key=${encodeURIComponent(resolvedKey)}` : ''}`;
2129
+ } else {
2130
+ if (resolvedKey) reqHeaders.authorization = `Bearer ${resolvedKey}`;
2131
+ }
2132
+
2133
+ const start = Date.now();
2134
+ const ctrl = new AbortController();
2135
+ const timer = setTimeout(() => ctrl.abort(), 8000);
2136
+ try {
2137
+ const res = await fetch(probeUrl, { method: 'GET', headers: reqHeaders, signal: ctrl.signal });
2138
+ const latencyMs = Date.now() - start;
2139
+ const text = await res.text();
2140
+ let parsed = null;
2141
+ try { parsed = JSON.parse(text); } catch {}
2142
+ const discoveredModels = Array.isArray(parsed?.data)
2143
+ ? parsed.data.map(m => String(m?.id || '')).filter(Boolean).slice(0, 30)
2144
+ : Array.isArray(parsed?.models)
2145
+ ? parsed.models.map(m => String(m?.name || m?.id || '').replace(/^models\//, '')).filter(Boolean).slice(0, 30)
2146
+ : [];
2147
+ if (res.ok) {
2148
+ return {
2149
+ ok: true,
2150
+ status: res.status,
2151
+ latencyMs,
2152
+ discoveredModels,
2153
+ message: discoveredModels.length
2154
+ ? `连接成功 (${res.status} · ${latencyMs}ms),探测到 ${discoveredModels.length} 个模型`
2155
+ : `连接成功 (${res.status} · ${latencyMs}ms)`,
2156
+ };
2157
+ }
2158
+ const errMsg = parsed?.error?.message || parsed?.message || text.slice(0, 180) || `HTTP ${res.status}`;
2159
+ return { ok: false, status: res.status, latencyMs, discoveredModels: [], message: `HTTP ${res.status}: ${errMsg}` };
2160
+ } catch (err) {
2161
+ return { ok: false, status: 0, latencyMs: Date.now() - start, discoveredModels: [], message: err?.name === 'AbortError' ? '连接超时 (>8s)' : (err?.message || '网络请求失败') };
2162
+ } finally {
2163
+ clearTimeout(timer);
2164
+ }
2165
+ }
2166
+
2167
+ // ============================================================================
2168
+ // 9. Workspace Preferences, Multi-Layer Memory & Scoped Rules (.clado/rules/)
2169
+ // ============================================================================
2170
+
2171
+ export function readWorkspacePrefs(workspace) {
2172
+ if (!workspace) return { defaultRoleId: 'architect' };
2173
+ const filePath = join(resolve(workspace), '.clado', 'workspace-prefs.json');
2174
+ const raw = readJsonSafe(filePath, {});
2175
+ return {
2176
+ path: filePath,
2177
+ defaultRoleId: String(raw?.defaultRoleId || 'architect'),
2178
+ };
2179
+ }
2180
+
2181
+ export function saveWorkspacePrefs(patch = {}, workspace) {
2182
+ if (!workspace) throw new Error('工作区路径不能为空。');
2183
+ const filePath = join(resolve(workspace), '.clado', 'workspace-prefs.json');
2184
+ const prev = readJsonSafe(filePath, {});
2185
+ const next = {
2186
+ ...prev,
2187
+ ...(patch.defaultRoleId !== undefined ? { defaultRoleId: String(patch.defaultRoleId || 'architect').trim() } : {}),
2188
+ };
2189
+ writeJsonSafe(filePath, next);
2190
+ return { ok: true, ...readWorkspacePrefs(workspace) };
2191
+ }
2192
+
2193
+ export function readMemoryBundle(workspace, agentDir = resolvePiAgentDir()) {
2194
+ const globalPath = join(agentDir, 'AGENTS.md');
2195
+ const globalExists = existsSync(globalPath);
2196
+ const globalContent = globalExists ? readFileSync(globalPath, 'utf8') : '';
2197
+ const project = readAgentsMemory(workspace);
2198
+ const rulesDir = workspace ? join(resolve(workspace), '.clado', 'rules') : '';
2199
+ const rules = [];
2200
+ if (rulesDir && existsSync(rulesDir)) {
2201
+ try {
2202
+ for (const name of readdirSync(rulesDir).sort()) {
2203
+ if (!name.endsWith('.md')) continue;
2204
+ const full = join(rulesDir, name);
2205
+ try {
2206
+ if (!statSync(full).isFile()) continue;
2207
+ rules.push({
2208
+ name: name.replace(/\.md$/i, ''),
2209
+ fileName: name,
2210
+ path: full,
2211
+ content: readFileSync(full, 'utf8'),
2212
+ });
2213
+ } catch {}
2214
+ }
2215
+ } catch {}
2216
+ }
2217
+ return {
2218
+ global: { path: globalPath, exists: globalExists, content: globalContent },
2219
+ project,
2220
+ rulesDir,
2221
+ rules,
2222
+ };
2223
+ }
2224
+
2225
+ export function saveGlobalAgentsMemory(content, agentDir = resolvePiAgentDir()) {
2226
+ mkdirSync(agentDir, { recursive: true });
2227
+ const filePath = join(agentDir, 'AGENTS.md');
2228
+ writeFileSync(filePath, String(content || ''), 'utf8');
2229
+ return { ok: true, path: filePath, exists: true, content: String(content || '') };
2230
+ }
2231
+
2232
+ export function saveProjectRule({ name, content } = {}, workspace) {
2233
+ if (!workspace) throw new Error('缺少工作区路径。');
2234
+ const slug = String(name || '').trim().replace(/\.md$/i, '').replace(/[^a-zA-Z0-9._\-\u4e00-\u9fa5]+/g, '-').replace(/^-+|-+$/g, '');
2235
+ if (!slug) throw new Error('规则文件名不能为空。');
2236
+ const dir = join(resolve(workspace), '.clado', 'rules');
2237
+ mkdirSync(dir, { recursive: true });
2238
+ const filePath = join(dir, slug + '.md');
2239
+ writeFileSync(filePath, String(content || ''), 'utf8');
2240
+ return { ok: true, name: slug, path: filePath };
2241
+ }
2242
+
2243
+ export function deleteProjectRule(name, workspace) {
2244
+ if (!workspace) return { ok: false };
2245
+ const slug = String(name || '').trim().replace(/\.md$/i, '');
2246
+ if (!slug || slug.includes('..') || slug.includes('/') || slug.includes('\\')) return { ok: false };
2247
+ const filePath = join(resolve(workspace), '.clado', 'rules', slug + '.md');
2248
+ if (existsSync(filePath)) {
2249
+ rmSync(filePath, { force: true });
2250
+ return { ok: true, name: slug };
2251
+ }
2252
+ return { ok: false, name: slug };
2253
+ }
2254
+
2255
+ export function readSkillOrPromptContent(filePath, workspace, agentDir = resolvePiAgentDir()) {
2256
+ const target = resolve(String(filePath || ''));
2257
+ const allowedRoots = [
2258
+ resolve(agentDir),
2259
+ workspace ? resolve(workspace, '.pi') : '',
2260
+ workspace ? resolve(workspace, '.clado') : '',
2261
+ ].filter(Boolean);
2262
+ const inside = allowedRoots.some(root => {
2263
+ const rel = relative(root, target);
2264
+ return rel && !rel.startsWith('..') && !rel.startsWith('/');
2265
+ });
2266
+ if (!inside || !existsSync(target)) throw new Error('无法读取指定文件(路径越界或不存在)。');
2267
+ return { ok: true, path: target, content: readFileSync(target, 'utf8') };
2268
+ }
2269
+
2270
+ // ============================================================================
2271
+ // 10. External MCP Auto-Discovery Importer (Claude Code / Cursor / Codex)
2272
+ // ============================================================================
2273
+
2274
+ function parseSimpleCodexMcpToml(text) {
2275
+ const servers = {};
2276
+ const lines = String(text || '').split(/\r?\n/);
2277
+ let current = null;
2278
+ for (const rawLine of lines) {
2279
+ const line = rawLine.trim();
2280
+ if (!line || line.startsWith('#')) continue;
2281
+ const sec = line.match(/^\[mcp_servers\.([a-zA-Z0-9._-]+)(?:\.(env|headers))?\]$/);
2282
+ if (sec) {
2283
+ const name = sec[1];
2284
+ const sub = sec[2] || '';
2285
+ if (!servers[name]) servers[name] = {};
2286
+ current = { name, sub };
2287
+ continue;
2288
+ }
2289
+ if (line.startsWith('[')) {
2290
+ current = null;
2291
+ continue;
2292
+ }
2293
+ if (!current) continue;
2294
+ const kv = line.match(/^([a-zA-Z0-9._-]+)\s*=\s*(.+)$/);
2295
+ if (!kv) continue;
2296
+ const key = kv[1].trim();
2297
+ const rawVal = kv[2].trim();
2298
+ let val = rawVal;
2299
+ try {
2300
+ val = JSON.parse(rawVal.replace(/'([^']*)'/g, '"$1"'));
2301
+ } catch {
2302
+ val = rawVal.replace(/^['"]|['"]$/g, '');
2303
+ }
2304
+ if (current.sub) {
2305
+ servers[current.name][current.sub] = servers[current.name][current.sub] || {};
2306
+ servers[current.name][current.sub][key] = String(val);
2307
+ } else {
2308
+ servers[current.name][key] = val;
2309
+ }
2310
+ }
2311
+ return servers;
2312
+ }
2313
+
2314
+ export function scanExternalMcpConfigs(workspace = process.cwd(), homeOverride = '') {
2315
+ const home = homeOverride || homedir();
2316
+ const candidates = [
2317
+ { source: 'Claude Code (全局)', path: join(home, '.claude.json'), format: 'json' },
2318
+ { source: 'Claude Code (项目 .mcp.json)', path: workspace ? join(workspace, '.mcp.json') : '', format: 'json' },
2319
+ { source: 'Cursor (全局)', path: join(home, '.cursor', 'mcp.json'), format: 'json' },
2320
+ { source: 'Cursor (项目)', path: workspace ? join(workspace, '.cursor', 'mcp.json') : '', format: 'json' },
2321
+ { source: 'OpenAI Codex (config.toml)', path: join(home, '.codex', 'config.toml'), format: 'toml' },
2322
+ ].filter(c => c.path);
2323
+
2324
+ const items = [];
2325
+ for (const cand of candidates) {
2326
+ if (!existsSync(cand.path)) continue;
2327
+ try {
2328
+ const text = readFileSync(cand.path, 'utf8');
2329
+ let map = {};
2330
+ if (cand.format === 'toml') {
2331
+ map = parseSimpleCodexMcpToml(text);
2332
+ } else {
2333
+ const parsed = JSON.parse(text);
2334
+ map = parsed?.mcpServers && typeof parsed.mcpServers === 'object' ? parsed.mcpServers : {};
2335
+ }
2336
+ for (const [name, cfg] of Object.entries(map)) {
2337
+ if (!cfg || typeof cfg !== 'object') continue;
2338
+ if (!cfg.command && !cfg.url) continue;
2339
+ items.push({
2340
+ name,
2341
+ source: cand.source,
2342
+ sourcePath: cand.path,
2343
+ type: cfg.url ? 'http' : 'stdio',
2344
+ command: cfg.command || '',
2345
+ args: Array.isArray(cfg.args) ? cfg.args.map(String) : [],
2346
+ url: cfg.url || '',
2347
+ env: cfg.env && typeof cfg.env === 'object' ? cfg.env : {},
2348
+ headers: cfg.headers && typeof cfg.headers === 'object' ? cfg.headers : {},
2349
+ cwd: cfg.cwd || '',
2350
+ });
2351
+ }
2352
+ } catch {}
2353
+ }
2354
+ return { ok: true, items };
2355
+ }
2356
+
2357
+ // ============================================================================
2358
+ // 11. Unified Raw Config JSON Editor (settings / mcp / models / hooks / permissions)
2359
+ // ============================================================================
2360
+
2361
+ export function readRawConfigTarget(target = 'settings', scope = 'user', workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
2362
+ const sc = scope === 'project' && workspace ? 'project' : 'user';
2363
+ let filePath = '';
2364
+ let fallback = {};
2365
+ if (target === 'settings') {
2366
+ filePath = sc === 'project' ? join(workspace, '.pi', 'settings.json') : join(agentDir, 'settings.json');
2367
+ fallback = {};
2368
+ } else if (target === 'mcp') {
2369
+ filePath = sc === 'project' ? join(workspace, '.pi', 'mcp.json') : join(agentDir, 'mcp.json');
2370
+ fallback = { mcpServers: {} };
2371
+ } else if (target === 'models') {
2372
+ filePath = join(agentDir, 'models.json');
2373
+ fallback = { providers: {} };
2374
+ } else if (target === 'hooks') {
2375
+ filePath = hooksFilePath(sc, workspace, agentDir);
2376
+ fallback = { version: 1, hooks: [] };
2377
+ } else if (target === 'permissions') {
2378
+ filePath = permissionsFilePath(sc, workspace, agentDir);
2379
+ fallback = { version: 1, mode: sc === 'user' ? 'full-access' : undefined, allow: [], ask: [], deny: [], shellEnvExclude: [] };
2380
+ } else {
2381
+ throw new Error(`不支持的原始配置目标:${target}`);
2382
+ }
2383
+ const exists = existsSync(filePath);
2384
+ let content = JSON.stringify(fallback, null, 2) + '\n';
2385
+ if (exists) {
2386
+ try { content = readFileSync(filePath, 'utf8'); } catch {}
2387
+ }
2388
+ return { ok: true, target, scope: target === 'models' ? 'user' : sc, path: filePath, exists, content };
2389
+ }
2390
+
2391
+ export function saveRawConfigTarget(target = 'settings', scope = 'user', jsonText = '', workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
2392
+ if (target === 'mcp') return savePiMcpRawJson(scope, jsonText, workspace, agentDir);
2393
+ if (target === 'hooks') return saveHooksRawJson(scope, jsonText, workspace, agentDir);
2394
+ if (target === 'permissions') return savePermissionsRawJson(scope, jsonText, workspace, agentDir);
2395
+
2396
+ let parsed;
2397
+ try {
2398
+ parsed = JSON.parse(String(jsonText || '{}'));
2399
+ } catch (err) {
2400
+ throw new Error('JSON 语法错误:' + err.message);
2401
+ }
2402
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
2403
+ throw new Error('配置文件顶层必须是 JSON 对象。');
2404
+ }
2405
+ const sc = scope === 'project' && workspace ? 'project' : 'user';
2406
+ const filePath = target === 'models'
2407
+ ? join(agentDir, 'models.json')
2408
+ : (sc === 'project' ? join(workspace, '.pi', 'settings.json') : join(agentDir, 'settings.json'));
2409
+ writeJsonSafe(filePath, parsed);
2410
+ return { ok: true, target, scope: target === 'models' ? 'user' : sc, path: filePath };
2411
+ }