cladogram 0.5.5-beta.9 → 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 (56) hide show
  1. package/README.md +106 -80
  2. package/bin/clado.js +35 -3
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +123 -0
  6. package/package.json +5 -3
  7. package/plugins/agent/index.js +2485 -2982
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1441 -1315
  10. package/plugins/brand/index.js +84 -466
  11. package/plugins/brand/style.css +39 -172
  12. package/plugins/directory/index.js +10 -10
  13. package/plugins/view-controls/index.js +6 -1
  14. package/plugins/view-controls/style.css +41 -30
  15. package/skills/clado/SKILL.md +4 -2
  16. package/src/agent/automations.js +454 -0
  17. package/src/agent/clado-tools.js +792 -0
  18. package/src/agent/pi-bridge.js +2559 -0
  19. package/src/agent/pi-config.js +2411 -0
  20. package/src/agent/pi-hooks-perms.js +621 -0
  21. package/src/html/app-css.js +69 -1
  22. package/src/html/canvas-chain.js +32 -6
  23. package/src/html/canvas-focus.js +19 -13
  24. package/src/html/canvas-live-diff.js +1373 -0
  25. package/src/html/canvas-ui.css +503 -2
  26. package/src/html/canvas-wires.js +5 -1
  27. package/src/html/page.js +4 -2
  28. package/src/html/plugin-assets.js +5 -1
  29. package/src/html/plugin-ui.css +159 -134
  30. package/src/html/plugin-ui.js +3 -2
  31. package/src/html/runtime-api.js +152 -10
  32. package/src/html/runtime.js +546 -37
  33. package/src/server/agent.js +862 -1566
  34. package/src/server/assets/library-canvas.js +256 -9
  35. package/src/server/assets/library.css +951 -11
  36. package/src/server/assets/library.html +39 -4
  37. package/src/server/assets/library.js +1445 -224
  38. package/src/server/code-inspect.js +183 -0
  39. package/src/server/mcp.js +90 -22
  40. package/src/server/plugin-registry.js +671 -9
  41. package/src/server/plugins.js +1 -1
  42. package/src/server/workspace-hub.js +50 -0
  43. package/src/server/workspace.js +554 -39
  44. package/src/workspace/graph-snapshot.js +695 -0
  45. package/src/workspace/service.js +201 -9
  46. package/src/agent/commands.js +0 -204
  47. package/src/agent/context.js +0 -445
  48. package/src/agent/executors.js +0 -213
  49. package/src/agent/mcp-client.js +0 -308
  50. package/src/agent/probe.js +0 -234
  51. package/src/agent/providers/anthropic.js +0 -220
  52. package/src/agent/providers/index.js +0 -235
  53. package/src/agent/providers/openai.js +0 -146
  54. package/src/agent/runtime.js +0 -995
  55. package/src/agent/sessions.js +0 -336
  56. package/src/agent/skills.js +0 -190
@@ -0,0 +1,2411 @@
1
+ /**
2
+ * Pi 1.x 原生配置整合桥(Unified Pi Config Bridge)
3
+ *
4
+ * 将 Clado 设置中心直接对接到 Pi 1.x 原生目录结构:
5
+ * - ~/.pi/agent/auth.json — 供应商凭据(API Key)
6
+ * - ~/.pi/agent/models.json — 自定义供应商 Base URL / 本地模型 / 代理端点
7
+ * - ~/.pi/agent/settings.json — 默认供应商、默认模型、已安装 Pi Packages
8
+ * - ~/.pi/agent/mcp.json — Pi 1.x 原生 MCP 服务器清单
9
+ * - ~/.pi/agent/skills/ — SKILL.md 技能包
10
+ * - ~/.pi/agent/prompts/ — /命令 Prompt 模板
11
+ * - ~/.pi/agent/clado-roles.json — Clado 自定义编排角色
12
+ * - <workspace>/AGENTS.md — 项目记忆与工程规范
13
+ */
14
+
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';
19
+ import {
20
+ DefaultPackageManager,
21
+ DefaultResourceLoader,
22
+ getAgentDir,
23
+ ModelRuntime,
24
+ SettingsManager,
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);
46
+
47
+ export const BUILTIN_ROLES = [
48
+ {
49
+ id: 'architect',
50
+ name: '主架构师',
51
+ phase: '设计阶段',
52
+ tone: 'sky',
53
+ builtin: true,
54
+ description: '分析现状代码、梳理模块边界与核心契约、设计清晰可扩展的端到端技术方案并推动定稿。',
55
+ systemPrompt: [
56
+ '你是「主架构师」,专注于系统架构设计、模块边界梳理与技术方案评审。',
57
+ '你的核心工作流程:',
58
+ '1. **摸清现状**:动手设计前先核查真实源码、入口边界、数据模型与上下游依赖,避免凭空猜测。',
59
+ '2. **端到端方案设计**:从入口触发、核心编排与并行分支、领域处理到持久化与外部依赖,梳理清晰的职责划分、数据流向、异常边界与演进权衡;明确标出新增、变更与潜在风险点。',
60
+ '3. **保持设计简洁克制**:优先选择低耦合、易验证的方案,避免过度抽象与循环依赖。',
61
+ '4. **关键决策拍板**:存在多个合理方案或重大边界取舍时,先完整阐述利弊与推荐理由,再请用户确认方向。',
62
+ ].join('\n'),
63
+ },
64
+ {
65
+ id: 'developer',
66
+ name: '开发落地',
67
+ phase: '交付阶段',
68
+ tone: 'emerald',
69
+ builtin: true,
70
+ description: '对照设计契约精准落地代码、补齐边界处理、运行构建与测试校验并同步交付事实。',
71
+ systemPrompt: [
72
+ '你是「开发落地」工程师,专注于高质量代码实现、边界处理与工程验证。',
73
+ '你的核心工作流程:',
74
+ '1. **先读设计契约与上下文**:开工前先理解目标方案的入口契约、核心数据流、修改范围与风险点。',
75
+ '2. **精准实现**:改动克制聚焦,遵循项目既有风格与约束,妥善处理空值、并发、超时与错误恢复,不引入无关重构。',
76
+ '3. **真实验证**:实现完成后务必实际运行构建、静态检查与相关测试,核对真实输出;遇到失败立即定位修复。',
77
+ '4. **同步与交付**:若落地细节较原设计有调整,及时同步更新文档事实,并清晰汇报改动文件与验证结果。',
78
+ ].join('\n'),
79
+ },
80
+ {
81
+ id: 'tester',
82
+ name: '测试验证',
83
+ phase: '验收阶段',
84
+ tone: 'violet',
85
+ builtin: true,
86
+ description: '梳理关键路径与异常边界、编写高信噪比自动化测试、真实执行验证并沉淀验收结论。',
87
+ systemPrompt: [
88
+ '你是「测试验证」工程师,专注于质量保障、边界挖掘与自动化回归测试。',
89
+ '你的核心工作流程:',
90
+ '1. **全路径查漏**:沿核心主流程、分支条件、并发竞争、权限与异常出口梳理测试矩阵,识别高风险薄弱点。',
91
+ '2. **编写高价值测试**:优先覆盖行为契约与真实回归场景,断言清晰独立、不依赖脆弱实现细节。',
92
+ '3. **真实执行验收**:实际运行测试套件并核对真实通过/失败结果;未执行的验证绝不可宣称为通过。',
93
+ '4. **沉淀验收结论**:清晰记录已覆盖路径、失败复现步骤与遗留风险,辅助团队决策发布。',
94
+ ].join('\n'),
95
+ },
96
+ {
97
+ id: 'archivist',
98
+ name: '归档整理',
99
+ phase: '文档阶段',
100
+ tone: 'amber',
101
+ builtin: true,
102
+ description: '核对已落地事实与设计文档、清理过时信息、沉淀高质量系统现状文档、ADR 与变更记录。',
103
+ systemPrompt: [
104
+ '你是「归档整理」专家,专注于技术文档沉淀、事实核对与知识结构化归档。',
105
+ '你的核心工作流程:',
106
+ '1. **事实核对**:以真实代码与已验证行为为准,严格区分「已落地现状」与「未实现提案」,绝不把提案写成事实。',
107
+ '2. **去冗提纯**:清理过时描述与矛盾表述,确保模块职责、关键契约、配置项与排障入口准确可查。',
108
+ '3. **结构化沉淀**:输出条理清晰的现状文档、架构决策记录(ADR)或版本变更说明,方便团队长期维护。',
109
+ ].join('\n'),
110
+ },
111
+ ];
112
+
113
+ export const PROVIDER_CATALOG = [
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
+ },
306
+ ];
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
+
312
+ export function resolvePiAgentDir() {
313
+ const dir = process.env.CLADO_PI_AGENT_DIR
314
+ ? resolve(process.env.CLADO_PI_AGENT_DIR)
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
+ }
319
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
320
+ return dir;
321
+ }
322
+
323
+ function readJsonSafe(file, fallback) {
324
+ if (!existsSync(file)) return fallback;
325
+ try {
326
+ return JSON.parse(readFileSync(file, 'utf8'));
327
+ } catch {
328
+ return fallback;
329
+ }
330
+ }
331
+
332
+ function writeJsonSafe(file, value) {
333
+ const dir = resolve(file, '..');
334
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
335
+ writeFileSync(file, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
336
+ }
337
+
338
+ export function maskSecret(secret) {
339
+ const s = String(secret || '').trim();
340
+ if (!s) return '';
341
+ if (s.length <= 8) return '••••';
342
+ return s.slice(0, 4) + '••••' + s.slice(-4);
343
+ }
344
+
345
+ // ============================================================================
346
+ // 1. Providers & Models (Pi auth.json + models.json + settings.json)
347
+ // ============================================================================
348
+
349
+ export function readPiAuth(agentDir = resolvePiAgentDir()) {
350
+ const data = readJsonSafe(join(agentDir, 'auth.json'), {});
351
+ return data && typeof data === 'object' ? data : {};
352
+ }
353
+
354
+ export function readPiModelsConfig(agentDir = resolvePiAgentDir()) {
355
+ const data = readJsonSafe(join(agentDir, 'models.json'), { providers: {} });
356
+ if (!data || typeof data !== 'object') return { providers: {} };
357
+ if (!data.providers || typeof data.providers !== 'object') data.providers = {};
358
+ return data;
359
+ }
360
+
361
+ export async function createCladoModelRuntime(agentDir = resolvePiAgentDir()) {
362
+ return ModelRuntime.create({
363
+ authPath: join(agentDir, 'auth.json'),
364
+ modelsPath: join(agentDir, 'models.json'),
365
+ refreshOnCreate: false,
366
+ allowModelNetwork: false,
367
+ });
368
+ }
369
+
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({
386
+ providerId,
387
+ name,
388
+ apiKey,
389
+ baseUrl,
390
+ api,
391
+ headers,
392
+ models,
393
+ replaceModels = false,
394
+ defaultModel,
395
+ contextWindow,
396
+ maxTokens,
397
+ reasoning,
398
+ setAsDefault = false,
399
+ }, agentDir = resolvePiAgentDir(), workspace = process.cwd()) {
400
+ const cleanId = String(providerId || '').trim().toLowerCase().replace(/[^a-z0-9._-]/g, '-');
401
+ if (!cleanId) throw new Error('供应商 ID 不能为空。');
402
+
403
+ const preset = PROVIDER_CATALOG.find(p => p.id === cleanId);
404
+ const authPath = join(agentDir, 'auth.json');
405
+ const modelsPath = join(agentDir, 'models.json');
406
+
407
+ // Update auth.json if apiKey provided
408
+ if (typeof apiKey === 'string' && apiKey.trim() && !apiKey.includes('••••')) {
409
+ const auth = readPiAuth(agentDir);
410
+ auth[cleanId] = { type: 'api_key', key: apiKey.trim() };
411
+ writeJsonSafe(authPath, auth);
412
+ }
413
+
414
+ // Update models.json if baseUrl / custom models / limits / headers / custom provider / recommended preset models
415
+ const cleanBaseUrl = typeof baseUrl === 'string' ? baseUrl.trim().replace(/\/+$/, '') : '';
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);
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;
430
+
431
+ if (cleanBaseUrl || modelIds.length || replaceModels || hasExplicitLimits || chosenModel || cleanHeaders || !preset || preset.keyless || cleanId.startsWith('custom-')) {
432
+ const cfg = readPiModelsConfig(agentDir);
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
+ );
439
+ const resolvedApi = api || prev.api || preset?.api || 'openai-completions';
440
+ const nextEntry = {
441
+ ...prev,
442
+ api: resolvedApi,
443
+ ...(cleanBaseUrl ? { baseUrl: cleanBaseUrl } : prev.baseUrl ? { baseUrl: prev.baseUrl } : preset?.defaultBaseUrl ? { baseUrl: preset.defaultBaseUrl } : {}),
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
+ }
452
+ if (preset?.keyless && !nextEntry.apiKey) nextEntry.apiKey = 'ollama';
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
+ ])];
462
+ if (mergedIds.length) {
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 = [];
494
+ }
495
+ cfg.providers[cleanId] = nextEntry;
496
+ writeJsonSafe(modelsPath, cfg);
497
+ }
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
+
508
+ if (setAsDefault && chosenModel) {
509
+ const sm = SettingsManager.create(workspace, agentDir);
510
+ sm.setDefaultModelAndProvider(cleanId, chosenModel);
511
+ await sm.flush();
512
+ }
513
+
514
+ return { ok: true, providerId: cleanId, defaultModel: chosenModel };
515
+ }
516
+
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()) {
544
+ const cleanId = String(providerId || '').trim();
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);
558
+ const authPath = join(agentDir, 'auth.json');
559
+ const auth = readPiAuth(agentDir);
560
+ if (cleanId in auth) {
561
+ delete auth[cleanId];
562
+ writeJsonSafe(authPath, auth);
563
+ }
564
+ const modelsPath = join(agentDir, 'models.json');
565
+ const cfg = readPiModelsConfig(agentDir);
566
+ if (cleanId in cfg.providers) {
567
+ delete cfg.providers[cleanId];
568
+ writeJsonSafe(modelsPath, cfg);
569
+ }
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) };
600
+ }
601
+
602
+ export async function setDefaultPiModel(providerId, modelId, agentDir = resolvePiAgentDir(), workspace = process.cwd()) {
603
+ const p = String(providerId || '').trim();
604
+ const m = String(modelId || '').trim();
605
+ if (!p || !m) throw new Error('请选择有效的供应商与模型。');
606
+ const sm = SettingsManager.create(workspace, agentDir);
607
+ sm.setDefaultModelAndProvider(p, m);
608
+ await sm.flush();
609
+ return { ok: true, provider: p, model: m };
610
+ }
611
+
612
+ export async function listProvidersAndModels(workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
613
+ const sm = SettingsManager.create(workspace, agentDir);
614
+ const mr = await createCladoModelRuntime(agentDir);
615
+ const auth = readPiAuth(agentDir);
616
+ const customCfg = readPiModelsConfig(agentDir);
617
+ const provState = readProviderState(agentDir);
618
+ const disabledSet = new Set(provState.disabled);
619
+ const hiddenSet = new Set(provState.hidden);
620
+
621
+ const defaultProvider = sm.getDefaultProvider() || '';
622
+ const defaultModel = sm.getDefaultModel() || '';
623
+
624
+ const allIds = new Set([
625
+ ...PROVIDER_CATALOG.map(p => p.id),
626
+ ...Object.keys(auth),
627
+ ...Object.keys(customCfg.providers || {}),
628
+ ]);
629
+
630
+ const providers = [];
631
+ const hiddenPresets = [];
632
+ const configuredModels = [];
633
+
634
+ for (const id of allIds) {
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
+ }
640
+ const authEntry = auth[id];
641
+ const customEntry = customCfg.providers?.[id];
642
+ const isDisabled = disabledSet.has(id);
643
+ const envHasKey = Boolean(preset?.envKey && process.env[preset.envKey]);
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
+
669
+ const runtimeModels = mr.getModels(id) || [];
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);
675
+ const modelList = [...new Set([
676
+ ...customModelIds,
677
+ ...recommendedIds,
678
+ ...runtimeModels.map(m => m.id),
679
+ ...(preset?.defaultModel ? [preset.defaultModel] : []),
680
+ ])].slice(0, 40);
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
+
701
+ providers.push({
702
+ id,
703
+ name: preset?.name || customEntry?.displayName || id,
704
+ isCustom: !preset,
705
+ api: customEntry?.api || preset?.api || 'openai-completions',
706
+ baseUrl: customEntry?.baseUrl || preset?.defaultBaseUrl || '',
707
+ headers: customEntry?.headers && typeof customEntry.headers === 'object' ? customEntry.headers : {},
708
+ hint: preset?.hint || '',
709
+ keyless: Boolean(preset?.keyless),
710
+ disabled: isDisabled,
711
+ configured: hasAuth,
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 || [],
721
+ models: modelList,
722
+ modelDetails: modelList.map(mId => ({ id: mId, ...resolveSpecs(mId) })),
723
+ });
724
+
725
+ if (hasAuth) {
726
+ for (const mId of modelList.slice(0, 20)) {
727
+ const specs = resolveSpecs(mId);
728
+ configuredModels.push({
729
+ id: `${id}/${mId}`,
730
+ provider: id,
731
+ model: mId,
732
+ label: `${mId}`,
733
+ providerName: preset?.name || customEntry?.displayName || id,
734
+ contextWindow: specs.contextWindow,
735
+ maxTokens: specs.maxTokens,
736
+ reasoning: specs.reasoning,
737
+ });
738
+ }
739
+ }
740
+ }
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
+
747
+ return {
748
+ agentDir,
749
+ defaultProvider,
750
+ defaultModel,
751
+ activeModelLabel: defaultModel || configuredModels[0]?.model || '未配置模型',
752
+ activeContextWindow: activeEntry?.contextWindow || 128000,
753
+ activeMaxTokens: activeEntry?.maxTokens || 16384,
754
+ providers,
755
+ hiddenPresets,
756
+ configuredModels,
757
+ };
758
+ }
759
+
760
+ // ============================================================================
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).
858
+ // ============================================================================
859
+
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 = '') {
1053
+ const merged = new Map();
1054
+ const applyRole = role => {
1055
+ const existing = merged.get(role.id);
1056
+ merged.set(role.id, {
1057
+ id: role.id,
1058
+ name: role.name,
1059
+ phase: role.phase || existing?.phase || '自定义',
1060
+ tone: ['sky', 'emerald', 'violet', 'amber'].includes(role.tone) ? role.tone : (existing?.tone || 'sky'),
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 || []),
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
+ }
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
+
1117
+ return [...merged.values()];
1118
+ }
1119
+
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];
1131
+ }
1132
+
1133
+ export function saveRole(input, agentDir = resolvePiAgentDir(), workspace = '') {
1134
+ const name = String(input?.name || '').trim();
1135
+ if (!name) throw new Error('角色名称不能为空。');
1136
+ const rawId = String(input?.id || name.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || ('role-' + Date.now().toString(36)));
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, []);
1143
+ const arr = Array.isArray(list) ? list.filter(r => r && r.id !== id) : [];
1144
+ const entry = {
1145
+ id,
1146
+ name: name.slice(0, 48),
1147
+ phase: String(input?.phase || '自定义阶段').trim().slice(0, 24),
1148
+ tone: ['sky', 'emerald', 'violet', 'amber'].includes(input?.tone) ? input.tone : 'sky',
1149
+ description: String(input?.description || '').trim().slice(0, 400),
1150
+ systemPrompt: String(input?.systemPrompt || '').trim().slice(0, ROLE_SYSTEM_PROMPT_MAX_CHARS),
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))] : [],
1155
+ };
1156
+ arr.push(entry);
1157
+ writeJsonSafe(targetPath, arr);
1158
+ return { ...entry, scope, sourcePath: targetPath };
1159
+ }
1160
+
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
+ }
1174
+ return { ok: true, id: roleId };
1175
+ }
1176
+
1177
+ // ============================================================================
1178
+ // 3. Pi Native MCP (mcp.json + .mcp.json + Plugin-bundled + Extension-registered)
1179
+ // ============================================================================
1180
+
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 {
1186
+ name,
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),
1191
+ type: cfg?.url ? 'http' : 'stdio',
1192
+ command: cfg?.command || '',
1193
+ args: Array.isArray(cfg?.args) ? cfg.args.map(String) : [],
1194
+ cwd: cfg?.cwd || '',
1195
+ url: cfg?.url || '',
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,
1213
+ }));
1214
+ }
1215
+
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 = [] } = {}) {
1273
+ const globalPath = join(agentDir, 'mcp.json');
1274
+ const projectPath = workspace ? join(workspace, '.pi', 'mcp.json') : '';
1275
+ const byName = new Map();
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 };
1407
+ }
1408
+
1409
+ export function savePiMcpServer(input, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1410
+ const name = String(input?.name || '').trim().replace(/[^a-zA-Z0-9._-]/g, '-');
1411
+ if (!name) throw new Error('MCP 服务器名称不能为空。');
1412
+ const scope = input?.scope === 'project' ? 'project' : 'user';
1413
+ const filePath = scope === 'project' ? join(workspace, '.pi', 'mcp.json') : join(agentDir, 'mcp.json');
1414
+ const doc = readJsonSafe(filePath, { mcpServers: {} });
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
+ }
1420
+ const entry = {};
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
+ }
1445
+ } else {
1446
+ const cmd = String(input?.command || '').trim();
1447
+ if (!cmd) throw new Error('请填写 MCP 启动命令(command)或远程 URL。');
1448
+ entry.command = cmd;
1449
+ entry.args = Array.isArray(input?.args)
1450
+ ? input.args.map(String).filter(Boolean)
1451
+ : typeof input?.args === 'string' && input.args.trim()
1452
+ ? input.args.trim().split(/\s+/)
1453
+ : [];
1454
+ if (input?.cwd && String(input.cwd).trim()) entry.cwd = String(input.cwd).trim();
1455
+ if (input.env && typeof input.env === 'object' && Object.keys(input.env).length) entry.env = input.env;
1456
+ }
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;
1474
+ doc.mcpServers[name] = entry;
1475
+ writeJsonSafe(filePath, doc);
1476
+ return { ok: true, name, scope, exposure };
1477
+ }
1478
+
1479
+ export function togglePiMcpServer(name, enabled, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1480
+ for (const filePath of [join(workspace, '.pi', 'mcp.json'), join(agentDir, 'mcp.json')]) {
1481
+ const doc = readJsonSafe(filePath, null);
1482
+ if (doc?.mcpServers && name in doc.mcpServers) {
1483
+ delete doc.mcpServers[name].disabled;
1484
+ if (enabled) delete doc.mcpServers[name].enabled;
1485
+ else doc.mcpServers[name].enabled = false;
1486
+ writeJsonSafe(filePath, doc);
1487
+ return { ok: true, name, enabled: Boolean(enabled) };
1488
+ }
1489
+ }
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 };
1497
+ }
1498
+
1499
+ export function deletePiMcpServer(name, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1500
+ let removed = false;
1501
+ for (const filePath of [join(workspace, '.pi', 'mcp.json'), join(agentDir, 'mcp.json')]) {
1502
+ const doc = readJsonSafe(filePath, null);
1503
+ if (doc?.mcpServers && name in doc.mcpServers) {
1504
+ delete doc.mcpServers[name];
1505
+ writeJsonSafe(filePath, doc);
1506
+ removed = true;
1507
+ }
1508
+ }
1509
+ return { ok: removed, name };
1510
+ }
1511
+
1512
+ export function importPiMcpJson(jsonText, scope = 'user', workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1513
+ const parsed = typeof jsonText === 'string' ? JSON.parse(jsonText) : jsonText;
1514
+ const src = parsed?.mcpServers && typeof parsed.mcpServers === 'object' ? parsed.mcpServers : parsed;
1515
+ if (!src || typeof src !== 'object') throw new Error('无效的 mcp.json 格式。');
1516
+ const filePath = scope === 'project' ? join(workspace, '.pi', 'mcp.json') : join(agentDir, 'mcp.json');
1517
+ const doc = readJsonSafe(filePath, { mcpServers: {} });
1518
+ if (!doc.mcpServers) doc.mcpServers = {};
1519
+ let count = 0;
1520
+ for (const [k, v] of Object.entries(src)) {
1521
+ if (!v || typeof v !== 'object') continue;
1522
+ doc.mcpServers[k] = v;
1523
+ count++;
1524
+ }
1525
+ writeJsonSafe(filePath, doc);
1526
+ return { ok: true, count };
1527
+ }
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
+
1599
+ export function savePiSkill({ name, description, content, scope = 'user' }, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1600
+ const slug = String(name || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
1601
+ if (!slug) throw new Error('Skill 名称不能为空。');
1602
+ const baseDir = scope === 'project' ? join(workspace, '.pi', 'skills', slug) : join(agentDir, 'skills', slug);
1603
+ mkdirSync(baseDir, { recursive: true });
1604
+ const body = String(content || '').trim();
1605
+ const hasFm = body.startsWith('---');
1606
+ const finalContent = hasFm
1607
+ ? body + '\n'
1608
+ : `---\nname: ${slug}\ndescription: ${String(description || slug).trim()}\n---\n\n${body}\n`;
1609
+ writeFileSync(join(baseDir, 'SKILL.md'), finalContent, 'utf8');
1610
+ return { ok: true, name: slug, path: join(baseDir, 'SKILL.md') };
1611
+ }
1612
+
1613
+ export function deletePiSkill(name, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1614
+ const slug = String(name || '').trim();
1615
+ if (!slug || slug.includes('..') || slug.includes('/')) return { ok: false };
1616
+ for (const dir of [join(workspace, '.pi', 'skills', slug), join(agentDir, 'skills', slug)]) {
1617
+ if (existsSync(dir)) {
1618
+ rmSync(dir, { recursive: true, force: true });
1619
+ return { ok: true, name: slug };
1620
+ }
1621
+ }
1622
+ return { ok: false, name: slug };
1623
+ }
1624
+
1625
+ export function savePiPrompt({ name, description, content, scope = 'user' }, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1626
+ const slug = String(name || '').trim().replace(/^\/+/, '').toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
1627
+ if (!slug) throw new Error('命令名称不能为空。');
1628
+ const baseDir = scope === 'project' ? join(workspace, '.pi', 'prompts') : join(agentDir, 'prompts');
1629
+ mkdirSync(baseDir, { recursive: true });
1630
+ const body = String(content || '').trim();
1631
+ const hasFm = body.startsWith('---');
1632
+ const finalContent = hasFm
1633
+ ? body + '\n'
1634
+ : `---\ndescription: ${String(description || '/' + slug).trim()}\n---\n\n${body}\n`;
1635
+ writeFileSync(join(baseDir, slug + '.md'), finalContent, 'utf8');
1636
+ return { ok: true, name: slug, path: join(baseDir, slug + '.md') };
1637
+ }
1638
+
1639
+ export function deletePiPrompt(name, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1640
+ const slug = String(name || '').trim().replace(/^\/+/, '');
1641
+ if (!slug || slug.includes('..') || slug.includes('/')) return { ok: false };
1642
+ for (const file of [join(workspace, '.pi', 'prompts', slug + '.md'), join(agentDir, 'prompts', slug + '.md')]) {
1643
+ if (existsSync(file)) {
1644
+ rmSync(file, { force: true });
1645
+ return { ok: true, name: slug };
1646
+ }
1647
+ }
1648
+ return { ok: false, name: slug };
1649
+ }
1650
+
1651
+ export async function inspectPiEcosystem(workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1652
+ const sm = SettingsManager.create(workspace, agentDir);
1653
+ const pm = new DefaultPackageManager({ cwd: workspace, agentDir, settingsManager: sm, commandOutput: 'capture' });
1654
+ const loader = new DefaultResourceLoader({
1655
+ cwd: workspace,
1656
+ agentDir,
1657
+ settingsManager: sm,
1658
+ noExtensions: true,
1659
+ noThemes: true,
1660
+ packageCommandOutput: 'capture',
1661
+ });
1662
+ await loader.reload();
1663
+
1664
+ const skills = (loader.getSkills()?.skills || []).map(s => ({
1665
+ name: s.name,
1666
+ description: s.description || '',
1667
+ filePath: s.filePath || '',
1668
+ scope: s.sourceInfo?.scope || 'user',
1669
+ }));
1670
+
1671
+ const prompts = (loader.getPrompts()?.prompts || []).map(p => ({
1672
+ name: p.name,
1673
+ description: p.description || '',
1674
+ filePath: p.filePath || '',
1675
+ scope: p.sourceInfo?.scope || 'user',
1676
+ }));
1677
+
1678
+ const packages = pm.listConfiguredPackages().map(p => ({
1679
+ source: p.source,
1680
+ scope: p.scope,
1681
+ installedPath: p.installedPath || '',
1682
+ }));
1683
+
1684
+ const mcpServers = listPiMcpServers(workspace, agentDir);
1685
+
1686
+ return { packages, mcpServers, skills, prompts };
1687
+ }
1688
+
1689
+ export async function installPiPackage(source, { local = false } = {}, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1690
+ const clean = String(source || '').trim();
1691
+ if (!clean) throw new Error('请填写 Pi 扩展包来源(例如 npm:... 或 git:...)。');
1692
+ const sm = SettingsManager.create(workspace, agentDir);
1693
+ const pm = new DefaultPackageManager({ cwd: workspace, agentDir, settingsManager: sm, commandOutput: 'capture' });
1694
+ await pm.installAndPersist(clean, { local });
1695
+ await sm.flush();
1696
+ return { ok: true, source: clean };
1697
+ }
1698
+
1699
+ export async function removePiPackage(source, { local = false } = {}, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
1700
+ const clean = String(source || '').trim();
1701
+ if (!clean) throw new Error('请指定要移除的扩展包来源。');
1702
+ const sm = SettingsManager.create(workspace, agentDir);
1703
+ const pm = new DefaultPackageManager({ cwd: workspace, agentDir, settingsManager: sm, commandOutput: 'capture' });
1704
+ const removed = await pm.removeAndPersist(clean, { local });
1705
+ await sm.flush();
1706
+ return { ok: removed, source: clean };
1707
+ }
1708
+
1709
+ // ============================================================================
1710
+ // 4. Workspace Memory (AGENTS.md)
1711
+ // ============================================================================
1712
+
1713
+ export function readAgentsMemory(workspace) {
1714
+ const file = join(workspace, 'AGENTS.md');
1715
+ if (!existsSync(file)) {
1716
+ return { path: file, exists: false, content: '' };
1717
+ }
1718
+ try {
1719
+ return { path: file, exists: true, content: readFileSync(file, 'utf8') };
1720
+ } catch {
1721
+ return { path: file, exists: false, content: '' };
1722
+ }
1723
+ }
1724
+
1725
+ export function saveAgentsMemory(workspace, content) {
1726
+ const file = join(workspace, 'AGENTS.md');
1727
+ writeFileSync(file, String(content || ''), 'utf8');
1728
+ return { ok: true, path: file, exists: true, content: String(content || '') };
1729
+ }
1730
+
1731
+ // ============================================================================
1732
+ // 5. Optional Canvas Components toggle (e.g., Lo-Fi Studio Widget — OFF by default)
1733
+ // ============================================================================
1734
+
1735
+ const DEFAULT_CANVAS_COMPONENTS = [
1736
+ {
1737
+ id: 'lofi-studio-widget',
1738
+ name: 'lofi-studio-widget',
1739
+ label: '画布组件',
1740
+ description: '启用后在画布右键菜单提供 Lo-Fi 专注电台浮窗,默认关闭保持极简。',
1741
+ defaultEnabled: false,
1742
+ },
1743
+ ];
1744
+
1745
+ export function readCanvasComponentsConfig(agentDir = resolvePiAgentDir()) {
1746
+ const file = join(agentDir, 'clado-canvas-components.json');
1747
+ const saved = readJsonSafe(file, {});
1748
+ return DEFAULT_CANVAS_COMPONENTS.map(item => ({
1749
+ ...item,
1750
+ enabled: typeof saved[item.id] === 'boolean' ? saved[item.id] : item.defaultEnabled,
1751
+ }));
1752
+ }
1753
+
1754
+ export function toggleCanvasComponent(id, enabled, agentDir = resolvePiAgentDir()) {
1755
+ const file = join(agentDir, 'clado-canvas-components.json');
1756
+ const saved = readJsonSafe(file, {});
1757
+ saved[String(id)] = Boolean(enabled);
1758
+ writeJsonSafe(file, saved);
1759
+ return readCanvasComponentsConfig(agentDir);
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
+ }