cladogram 0.6.0-beta.7 → 0.6.0-beta.9
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.
- package/docs/release.md +35 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +314 -913
- package/plugins/agent/settings.js +3329 -0
- package/plugins/agent/style.css +214 -0
- package/src/agent/pi-bridge.js +702 -60
- package/src/agent/pi-config.js +894 -44
- package/src/agent/pi-hooks-perms.js +621 -0
- package/src/html/plugin-assets.js +5 -1
- package/src/server/agent.js +259 -16
- package/src/server/assets/library.js +9 -1
- package/src/server/plugin-registry.js +664 -2
- package/src/server/workspace.js +120 -3
package/src/agent/pi-config.js
CHANGED
|
@@ -12,8 +12,9 @@
|
|
|
12
12
|
* - <workspace>/AGENTS.md — 项目记忆与工程规范
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
|
-
import {
|
|
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';
|
|
17
18
|
import { fileURLToPath } from 'node:url';
|
|
18
19
|
import {
|
|
19
20
|
DefaultPackageManager,
|
|
@@ -22,6 +23,12 @@ import {
|
|
|
22
23
|
ModelRuntime,
|
|
23
24
|
SettingsManager,
|
|
24
25
|
} from '@earendil-works/pi-coding-agent';
|
|
26
|
+
import {
|
|
27
|
+
hooksFilePath,
|
|
28
|
+
permissionsFilePath,
|
|
29
|
+
saveHooksRawJson,
|
|
30
|
+
savePermissionsRawJson,
|
|
31
|
+
} from './pi-hooks-perms.js';
|
|
25
32
|
|
|
26
33
|
const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
27
34
|
const PACKAGE_CONTEXT_DOC_PATH = join(PKG_ROOT, 'docs', 'agent-context.md');
|
|
@@ -184,6 +191,65 @@ export const PROVIDER_CATALOG = [
|
|
|
184
191
|
{ id: 'openai/gpt-6.2-sol', label: 'GPT-6.2 Sol (1.05M)', contextWindow: 1050000, maxTokens: 128000, reasoning: true },
|
|
185
192
|
],
|
|
186
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
|
+
},
|
|
187
253
|
{
|
|
188
254
|
id: 'ollama',
|
|
189
255
|
name: '本地模型 · Ollama',
|
|
@@ -200,6 +266,19 @@ export const PROVIDER_CATALOG = [
|
|
|
200
266
|
{ id: 'deepseek-r1:14b', label: 'DeepSeek-R1 14B (128K · 推理)', contextWindow: 128000, maxTokens: 16384, reasoning: true },
|
|
201
267
|
],
|
|
202
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
|
+
},
|
|
203
282
|
{
|
|
204
283
|
id: 'custom-openai',
|
|
205
284
|
name: '自定义代理(OpenAI 兼容)',
|
|
@@ -234,6 +313,9 @@ export function resolvePiAgentDir() {
|
|
|
234
313
|
const dir = process.env.CLADO_PI_AGENT_DIR
|
|
235
314
|
? resolve(process.env.CLADO_PI_AGENT_DIR)
|
|
236
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
|
+
}
|
|
237
319
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
238
320
|
return dir;
|
|
239
321
|
}
|
|
@@ -300,12 +382,15 @@ function inferReasoning(modelId) {
|
|
|
300
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 || ''));
|
|
301
383
|
}
|
|
302
384
|
|
|
303
|
-
export function saveProviderConfig({
|
|
385
|
+
export async function saveProviderConfig({
|
|
304
386
|
providerId,
|
|
387
|
+
name,
|
|
305
388
|
apiKey,
|
|
306
389
|
baseUrl,
|
|
307
390
|
api,
|
|
391
|
+
headers,
|
|
308
392
|
models,
|
|
393
|
+
replaceModels = false,
|
|
309
394
|
defaultModel,
|
|
310
395
|
contextWindow,
|
|
311
396
|
maxTokens,
|
|
@@ -326,15 +411,24 @@ export function saveProviderConfig({
|
|
|
326
411
|
writeJsonSafe(authPath, auth);
|
|
327
412
|
}
|
|
328
413
|
|
|
329
|
-
// Update models.json if baseUrl / custom models / limits / custom provider / recommended preset models
|
|
414
|
+
// Update models.json if baseUrl / custom models / limits / headers / custom provider / recommended preset models
|
|
330
415
|
const cleanBaseUrl = typeof baseUrl === 'string' ? baseUrl.trim().replace(/\/+$/, '') : '';
|
|
331
|
-
const
|
|
332
|
-
|
|
333
|
-
|
|
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);
|
|
334
425
|
const chosenModel = String(defaultModel || modelIds[0] || preset?.defaultModel || '').trim();
|
|
335
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;
|
|
336
430
|
|
|
337
|
-
if (cleanBaseUrl || modelIds.length || hasExplicitLimits || chosenModel || !preset || preset.keyless || cleanId.startsWith('custom-')) {
|
|
431
|
+
if (cleanBaseUrl || modelIds.length || replaceModels || hasExplicitLimits || chosenModel || cleanHeaders || !preset || preset.keyless || cleanId.startsWith('custom-')) {
|
|
338
432
|
const cfg = readPiModelsConfig(agentDir);
|
|
339
433
|
const prev = cfg.providers[cleanId] || {};
|
|
340
434
|
const prevById = new Map(
|
|
@@ -348,37 +442,55 @@ export function saveProviderConfig({
|
|
|
348
442
|
api: resolvedApi,
|
|
349
443
|
...(cleanBaseUrl ? { baseUrl: cleanBaseUrl } : prev.baseUrl ? { baseUrl: prev.baseUrl } : preset?.defaultBaseUrl ? { baseUrl: preset.defaultBaseUrl } : {}),
|
|
350
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
|
+
}
|
|
351
452
|
if (preset?.keyless && !nextEntry.apiKey) nextEntry.apiKey = 'ollama';
|
|
352
453
|
const recommendedIds = (preset?.recommendedModels || []).map(m => m.id);
|
|
353
|
-
const mergedIds =
|
|
354
|
-
...(chosenModel ? [chosenModel] : []),
|
|
355
|
-
...
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
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
|
+
])];
|
|
359
462
|
if (mergedIds.length) {
|
|
360
463
|
nextEntry.models = mergedIds.map(id => {
|
|
464
|
+
const inItem = inputById.get(id);
|
|
361
465
|
const prevItem = prevById.get(id);
|
|
362
466
|
const recSpec = lookupRecommendedSpec(preset, id);
|
|
363
467
|
const isTarget = id === chosenModel;
|
|
364
|
-
const resolvedCtx =
|
|
365
|
-
? clampInt(contextWindow, 4096, 4000000, preset?.defaultContextWindow || 128000)
|
|
366
|
-
: (
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
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))));
|
|
373
483
|
return {
|
|
374
484
|
id,
|
|
375
|
-
name: recSpec?.label || prevItem?.name || id,
|
|
485
|
+
name: inItem?.name || recSpec?.label || prevItem?.name || id,
|
|
376
486
|
reasoning: resolvedReasoning,
|
|
377
|
-
input: prevItem?.input || ['text'],
|
|
487
|
+
input: Array.isArray(inItem?.input) && inItem.input.length ? inItem.input : (prevItem?.input || ['text']),
|
|
378
488
|
contextWindow: resolvedCtx,
|
|
379
489
|
maxTokens: resolvedMaxOut,
|
|
380
490
|
};
|
|
381
491
|
});
|
|
492
|
+
} else if (replaceModels) {
|
|
493
|
+
nextEntry.models = [];
|
|
382
494
|
}
|
|
383
495
|
cfg.providers[cleanId] = nextEntry;
|
|
384
496
|
writeJsonSafe(modelsPath, cfg);
|
|
@@ -387,6 +499,7 @@ export function saveProviderConfig({
|
|
|
387
499
|
if (setAsDefault && chosenModel) {
|
|
388
500
|
const sm = SettingsManager.create(workspace, agentDir);
|
|
389
501
|
sm.setDefaultModelAndProvider(cleanId, chosenModel);
|
|
502
|
+
await sm.flush();
|
|
390
503
|
}
|
|
391
504
|
|
|
392
505
|
return { ok: true, providerId: cleanId, defaultModel: chosenModel };
|
|
@@ -443,7 +556,7 @@ export async function listProvidersAndModels(workspace = process.cwd(), agentDir
|
|
|
443
556
|
const authEntry = auth[id];
|
|
444
557
|
const customEntry = customCfg.providers?.[id];
|
|
445
558
|
const envHasKey = Boolean(preset?.envKey && process.env[preset.envKey]);
|
|
446
|
-
const hasAuth = Boolean(authEntry?.key || authEntry?.access || envHasKey || mr.hasConfiguredAuth(id) || (preset?.keyless && customEntry?.baseUrl));
|
|
559
|
+
const hasAuth = Boolean(authEntry?.key || authEntry?.access || customEntry?.apiKey || envHasKey || mr.hasConfiguredAuth(id) || (preset?.keyless && customEntry?.baseUrl));
|
|
447
560
|
const runtimeModels = mr.getModels(id) || [];
|
|
448
561
|
const customModelObjs = Array.isArray(customEntry?.models) ? customEntry.models : [];
|
|
449
562
|
const customById = new Map(customModelObjs.filter(m => m && typeof m === 'object' && m.id).map(m => [m.id, m]));
|
|
@@ -470,38 +583,42 @@ export async function listProvidersAndModels(workspace = process.cwd(), agentDir
|
|
|
470
583
|
const reas = typeof cObj?.reasoning === 'boolean'
|
|
471
584
|
? cObj.reasoning
|
|
472
585
|
: (typeof rObj?.reasoning === 'boolean' ? rObj.reasoning : (typeof rec?.reasoning === 'boolean' ? rec.reasoning : inferReasoning(mId)));
|
|
473
|
-
|
|
586
|
+
const inp = Array.isArray(cObj?.input) && cObj.input.length ? cObj.input : (Array.isArray(rObj?.input) ? rObj.input : ['text']);
|
|
587
|
+
return { contextWindow: ctx, maxTokens: maxOut, reasoning: reas, input: inp, label: cObj?.name || rec?.label || mId };
|
|
474
588
|
};
|
|
475
589
|
|
|
476
590
|
const activeSpecs = resolveSpecs(activeModelId);
|
|
477
591
|
|
|
478
592
|
providers.push({
|
|
479
593
|
id,
|
|
480
|
-
name: preset?.name || id,
|
|
594
|
+
name: preset?.name || customEntry?.displayName || id,
|
|
595
|
+
isCustom: !preset,
|
|
481
596
|
api: customEntry?.api || preset?.api || 'openai-completions',
|
|
482
597
|
baseUrl: customEntry?.baseUrl || preset?.defaultBaseUrl || '',
|
|
598
|
+
headers: customEntry?.headers && typeof customEntry.headers === 'object' ? customEntry.headers : {},
|
|
483
599
|
hint: preset?.hint || '',
|
|
484
600
|
keyless: Boolean(preset?.keyless),
|
|
485
601
|
configured: hasAuth,
|
|
486
|
-
authSource: authEntry?.key ? 'auth.json' : authEntry?.access ? 'oauth' : envHasKey ? 'env' : preset?.keyless && customEntry ? 'local' : '',
|
|
487
|
-
maskedKey: authEntry?.key ? maskSecret(authEntry.key) : '',
|
|
602
|
+
authSource: authEntry?.key ? 'auth.json' : authEntry?.access ? 'oauth' : customEntry?.apiKey ? 'models.json' : envHasKey ? 'env' : preset?.keyless && customEntry ? 'local' : '',
|
|
603
|
+
maskedKey: authEntry?.key ? maskSecret(authEntry.key) : (customEntry?.apiKey ? maskSecret(customEntry.apiKey) : ''),
|
|
488
604
|
defaultModel: activeModelId,
|
|
489
605
|
contextWindow: activeSpecs.contextWindow,
|
|
490
606
|
maxTokens: activeSpecs.maxTokens,
|
|
491
607
|
reasoning: activeSpecs.reasoning,
|
|
492
608
|
recommendedModels: preset?.recommendedModels || [],
|
|
493
609
|
models: modelList,
|
|
610
|
+
modelDetails: modelList.map(mId => ({ id: mId, ...resolveSpecs(mId) })),
|
|
494
611
|
});
|
|
495
612
|
|
|
496
613
|
if (hasAuth) {
|
|
497
|
-
for (const mId of modelList.slice(0,
|
|
614
|
+
for (const mId of modelList.slice(0, 20)) {
|
|
498
615
|
const specs = resolveSpecs(mId);
|
|
499
616
|
configuredModels.push({
|
|
500
617
|
id: `${id}/${mId}`,
|
|
501
618
|
provider: id,
|
|
502
619
|
model: mId,
|
|
503
620
|
label: `${mId}`,
|
|
504
|
-
providerName: preset?.name || id,
|
|
621
|
+
providerName: preset?.name || customEntry?.displayName || id,
|
|
505
622
|
contextWindow: specs.contextWindow,
|
|
506
623
|
maxTokens: specs.maxTokens,
|
|
507
624
|
reasoning: specs.reasoning,
|
|
@@ -631,7 +748,9 @@ export function listRoles(agentDir = resolvePiAgentDir()) {
|
|
|
631
748
|
const raw = readJsonSafe(customPath, []);
|
|
632
749
|
const custom = Array.isArray(raw) ? raw.filter(r => r && r.id && r.name) : [];
|
|
633
750
|
const merged = new Map();
|
|
634
|
-
for (const role of BUILTIN_ROLES)
|
|
751
|
+
for (const role of BUILTIN_ROLES) {
|
|
752
|
+
merged.set(role.id, { ...role, model: '', thinkingLevel: '', tools: [], disabledTools: [], customized: false });
|
|
753
|
+
}
|
|
635
754
|
for (const role of custom) {
|
|
636
755
|
const existing = merged.get(role.id);
|
|
637
756
|
merged.set(role.id, {
|
|
@@ -640,9 +759,13 @@ export function listRoles(agentDir = resolvePiAgentDir()) {
|
|
|
640
759
|
phase: String(role.phase || existing?.phase || '自定义').trim(),
|
|
641
760
|
tone: ['sky', 'emerald', 'violet', 'amber'].includes(role.tone) ? role.tone : (existing?.tone || 'sky'),
|
|
642
761
|
builtin: Boolean(existing?.builtin),
|
|
762
|
+
customized: Boolean(existing?.builtin),
|
|
643
763
|
description: String(role.description || existing?.description || '').trim(),
|
|
644
764
|
systemPrompt: String(role.systemPrompt || existing?.systemPrompt || '').trim(),
|
|
645
765
|
model: String(role.model || '').trim(),
|
|
766
|
+
thinkingLevel: THINKING_LEVELS.includes(role.thinkingLevel) ? role.thinkingLevel : '',
|
|
767
|
+
tools: Array.isArray(role.tools) ? role.tools.map(s => String(s || '').trim()).filter(Boolean) : [],
|
|
768
|
+
disabledTools: Array.isArray(role.disabledTools) ? role.disabledTools.map(s => String(s || '').trim()).filter(Boolean) : [],
|
|
646
769
|
});
|
|
647
770
|
}
|
|
648
771
|
return [...merged.values()];
|
|
@@ -669,6 +792,9 @@ export function saveRole(input, agentDir = resolvePiAgentDir()) {
|
|
|
669
792
|
description: String(input?.description || '').trim().slice(0, 200),
|
|
670
793
|
systemPrompt: String(input?.systemPrompt || '').trim().slice(0, 6000),
|
|
671
794
|
model: String(input?.model || '').trim().slice(0, 120),
|
|
795
|
+
thinkingLevel: THINKING_LEVELS.includes(input?.thinkingLevel) ? input.thinkingLevel : '',
|
|
796
|
+
tools: Array.isArray(input?.tools) ? [...new Set(input.tools.map(s => String(s || '').trim()).filter(Boolean))] : [],
|
|
797
|
+
disabledTools: Array.isArray(input?.disabledTools) ? [...new Set(input.disabledTools.map(s => String(s || '').trim()).filter(Boolean))] : [],
|
|
672
798
|
};
|
|
673
799
|
arr.push(entry);
|
|
674
800
|
writeJsonSafe(customPath, arr);
|
|
@@ -687,6 +813,8 @@ export function deleteRole(roleId, agentDir = resolvePiAgentDir()) {
|
|
|
687
813
|
// 3. Pi Native MCP (mcp.json), Skills, Prompt Templates (/Commands), Packages
|
|
688
814
|
// ============================================================================
|
|
689
815
|
|
|
816
|
+
const MCP_EXPOSURES = ['direct', 'codemode', 'deferred', 'hidden'];
|
|
817
|
+
|
|
690
818
|
function readMcpFile(filePath, scope) {
|
|
691
819
|
const raw = readJsonSafe(filePath, null);
|
|
692
820
|
const servers = raw?.mcpServers && typeof raw.mcpServers === 'object' ? raw.mcpServers : {};
|
|
@@ -696,10 +824,15 @@ function readMcpFile(filePath, scope) {
|
|
|
696
824
|
type: cfg?.url ? 'http' : 'stdio',
|
|
697
825
|
command: cfg?.command || '',
|
|
698
826
|
args: Array.isArray(cfg?.args) ? cfg.args : [],
|
|
827
|
+
cwd: cfg?.cwd || '',
|
|
699
828
|
url: cfg?.url || '',
|
|
700
|
-
env: cfg?.env
|
|
701
|
-
headers: cfg?.headers
|
|
702
|
-
|
|
829
|
+
env: cfg?.env && typeof cfg.env === 'object' ? cfg.env : {},
|
|
830
|
+
headers: cfg?.headers && typeof cfg.headers === 'object' ? cfg.headers : {},
|
|
831
|
+
timeout: typeof cfg?.timeout === 'number' ? cfg.timeout : undefined,
|
|
832
|
+
exposure: MCP_EXPOSURES.includes(cfg?.exposure) ? cfg.exposure : 'codemode',
|
|
833
|
+
toolExposure: cfg?.toolExposure && typeof cfg.toolExposure === 'object' && !Array.isArray(cfg.toolExposure) ? cfg.toolExposure : {},
|
|
834
|
+
description: typeof cfg?.description === 'string' ? cfg.description : '',
|
|
835
|
+
enabled: cfg?.enabled !== false && cfg?.disabled !== true,
|
|
703
836
|
}));
|
|
704
837
|
}
|
|
705
838
|
|
|
@@ -712,6 +845,35 @@ export function listPiMcpServers(workspace = process.cwd(), agentDir = resolvePi
|
|
|
712
845
|
return [...byName.values()];
|
|
713
846
|
}
|
|
714
847
|
|
|
848
|
+
export function readPiMcpRawJson(workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
|
|
849
|
+
const userPath = join(agentDir, 'mcp.json');
|
|
850
|
+
const projectPath = join(workspace, '.pi', 'mcp.json');
|
|
851
|
+
const readRaw = p => {
|
|
852
|
+
if (!existsSync(p)) return JSON.stringify({ mcpServers: {} }, null, 2) + '\n';
|
|
853
|
+
try { return readFileSync(p, 'utf8'); } catch { return JSON.stringify({ mcpServers: {} }, null, 2) + '\n'; }
|
|
854
|
+
};
|
|
855
|
+
return {
|
|
856
|
+
userPath,
|
|
857
|
+
projectPath,
|
|
858
|
+
user: readRaw(userPath),
|
|
859
|
+
project: readRaw(projectPath),
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
export function savePiMcpRawJson(scope = 'user', jsonText = '', workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
|
|
864
|
+
const parsed = typeof jsonText === 'string' ? JSON.parse(jsonText || '{"mcpServers":{}}') : jsonText;
|
|
865
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
866
|
+
throw new Error('mcp.json 顶层必须是 JSON 对象。');
|
|
867
|
+
}
|
|
868
|
+
const normalized = parsed.mcpServers && typeof parsed.mcpServers === 'object'
|
|
869
|
+
? parsed
|
|
870
|
+
: { mcpServers: parsed };
|
|
871
|
+
const targetScope = scope === 'project' ? 'project' : 'user';
|
|
872
|
+
const filePath = targetScope === 'project' ? join(workspace, '.pi', 'mcp.json') : join(agentDir, 'mcp.json');
|
|
873
|
+
writeJsonSafe(filePath, normalized);
|
|
874
|
+
return { ok: true, scope: targetScope, path: filePath, count: Object.keys(normalized.mcpServers || {}).length };
|
|
875
|
+
}
|
|
876
|
+
|
|
715
877
|
export function savePiMcpServer(input, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
|
|
716
878
|
const name = String(input?.name || '').trim().replace(/[^a-zA-Z0-9._-]/g, '-');
|
|
717
879
|
if (!name) throw new Error('MCP 服务器名称不能为空。');
|
|
@@ -719,33 +881,59 @@ export function savePiMcpServer(input, workspace = process.cwd(), agentDir = res
|
|
|
719
881
|
const filePath = scope === 'project' ? join(workspace, '.pi', 'mcp.json') : join(agentDir, 'mcp.json');
|
|
720
882
|
const doc = readJsonSafe(filePath, { mcpServers: {} });
|
|
721
883
|
if (!doc.mcpServers || typeof doc.mcpServers !== 'object') doc.mcpServers = {};
|
|
884
|
+
const prevName = String(input?.originalName || '').trim();
|
|
885
|
+
if (prevName && prevName !== name && prevName in doc.mcpServers) {
|
|
886
|
+
delete doc.mcpServers[prevName];
|
|
887
|
+
}
|
|
722
888
|
const entry = {};
|
|
723
|
-
if (input?.url && String(input.url).trim()) {
|
|
724
|
-
|
|
725
|
-
if (
|
|
889
|
+
if (input?.type === 'http' || (input?.url && String(input.url).trim() && input?.type !== 'stdio')) {
|
|
890
|
+
const urlStr = String(input?.url || '').trim();
|
|
891
|
+
if (!urlStr) throw new Error('请填写远程 MCP 端点 URL。');
|
|
892
|
+
entry.url = urlStr;
|
|
893
|
+
if (input.headers && typeof input.headers === 'object' && Object.keys(input.headers).length) {
|
|
894
|
+
entry.headers = input.headers;
|
|
895
|
+
}
|
|
726
896
|
} else {
|
|
727
897
|
const cmd = String(input?.command || '').trim();
|
|
728
898
|
if (!cmd) throw new Error('请填写 MCP 启动命令(command)或远程 URL。');
|
|
729
899
|
entry.command = cmd;
|
|
730
900
|
entry.args = Array.isArray(input?.args)
|
|
731
|
-
? input.args.map(String)
|
|
901
|
+
? input.args.map(String).filter(Boolean)
|
|
732
902
|
: typeof input?.args === 'string' && input.args.trim()
|
|
733
903
|
? input.args.trim().split(/\s+/)
|
|
734
904
|
: [];
|
|
905
|
+
if (input?.cwd && String(input.cwd).trim()) entry.cwd = String(input.cwd).trim();
|
|
735
906
|
if (input.env && typeof input.env === 'object' && Object.keys(input.env).length) entry.env = input.env;
|
|
736
907
|
}
|
|
737
|
-
if (input?.
|
|
908
|
+
if (typeof input?.timeout === 'number' && Number.isFinite(input.timeout) && input.timeout > 0) {
|
|
909
|
+
entry.timeout = Math.round(input.timeout);
|
|
910
|
+
}
|
|
911
|
+
if (input?.description && String(input.description).trim()) {
|
|
912
|
+
entry.description = String(input.description).trim().slice(0, 250);
|
|
913
|
+
}
|
|
914
|
+
const exposure = MCP_EXPOSURES.includes(input?.exposure) ? input.exposure : 'direct';
|
|
915
|
+
entry.exposure = exposure;
|
|
916
|
+
if (input?.toolExposure && typeof input.toolExposure === 'object' && !Array.isArray(input.toolExposure)) {
|
|
917
|
+
const cleanMap = {};
|
|
918
|
+
for (const [tk, tv] of Object.entries(input.toolExposure)) {
|
|
919
|
+
const k = String(tk || '').trim();
|
|
920
|
+
if (k && MCP_EXPOSURES.includes(tv)) cleanMap[k] = tv;
|
|
921
|
+
}
|
|
922
|
+
if (Object.keys(cleanMap).length) entry.toolExposure = cleanMap;
|
|
923
|
+
}
|
|
924
|
+
if (input?.enabled === false) entry.enabled = false;
|
|
738
925
|
doc.mcpServers[name] = entry;
|
|
739
926
|
writeJsonSafe(filePath, doc);
|
|
740
|
-
return { ok: true, name, scope };
|
|
927
|
+
return { ok: true, name, scope, exposure };
|
|
741
928
|
}
|
|
742
929
|
|
|
743
930
|
export function togglePiMcpServer(name, enabled, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
|
|
744
931
|
for (const filePath of [join(workspace, '.pi', 'mcp.json'), join(agentDir, 'mcp.json')]) {
|
|
745
932
|
const doc = readJsonSafe(filePath, null);
|
|
746
933
|
if (doc?.mcpServers && name in doc.mcpServers) {
|
|
747
|
-
|
|
748
|
-
|
|
934
|
+
delete doc.mcpServers[name].disabled;
|
|
935
|
+
if (enabled) delete doc.mcpServers[name].enabled;
|
|
936
|
+
else doc.mcpServers[name].enabled = false;
|
|
749
937
|
writeJsonSafe(filePath, doc);
|
|
750
938
|
return { ok: true, name, enabled: Boolean(enabled) };
|
|
751
939
|
}
|
|
@@ -783,6 +971,76 @@ export function importPiMcpJson(jsonText, scope = 'user', workspace = process.cw
|
|
|
783
971
|
return { ok: true, count };
|
|
784
972
|
}
|
|
785
973
|
|
|
974
|
+
// ============================================================================
|
|
975
|
+
// 3.5 Plugin / Extension Injected Parameters (.clado/plugin-params.json + user)
|
|
976
|
+
// ============================================================================
|
|
977
|
+
|
|
978
|
+
export function readPluginParams(workspace = process.cwd(), stateDir = '', agentDir = resolvePiAgentDir()) {
|
|
979
|
+
const userPath = join(agentDir, 'clado-plugin-params.json');
|
|
980
|
+
const wsPath = stateDir ? join(stateDir, 'plugin-params.json') : join(workspace, '.clado', 'plugin-params.json');
|
|
981
|
+
const userRaw = readJsonSafe(userPath, {});
|
|
982
|
+
const wsRaw = readJsonSafe(wsPath, {});
|
|
983
|
+
const merged = {};
|
|
984
|
+
for (const [id, val] of Object.entries(userRaw && typeof userRaw === 'object' ? userRaw : {})) {
|
|
985
|
+
if (val && typeof val === 'object') merged[id] = { scope: 'user', env: val.env || {}, params: val.params || {} };
|
|
986
|
+
}
|
|
987
|
+
for (const [id, val] of Object.entries(wsRaw && typeof wsRaw === 'object' ? wsRaw : {})) {
|
|
988
|
+
if (val && typeof val === 'object') {
|
|
989
|
+
const prev = merged[id] || { env: {}, params: {} };
|
|
990
|
+
merged[id] = {
|
|
991
|
+
scope: 'project',
|
|
992
|
+
env: { ...(prev.env || {}), ...(val.env || {}) },
|
|
993
|
+
params: { ...(prev.params || {}), ...(val.params || {}) },
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
return { userPath, projectPath: wsPath, items: merged };
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
export function savePluginParams({ pluginId, scope = 'project', env = {}, params = {} } = {}, workspace = process.cwd(), stateDir = '', agentDir = resolvePiAgentDir()) {
|
|
1001
|
+
const id = String(pluginId || '').trim();
|
|
1002
|
+
if (!id) throw new Error('插件或扩展标识不能为空。');
|
|
1003
|
+
const targetScope = scope === 'user' ? 'user' : 'project';
|
|
1004
|
+
const filePath = targetScope === 'user'
|
|
1005
|
+
? join(agentDir, 'clado-plugin-params.json')
|
|
1006
|
+
: (stateDir ? join(stateDir, 'plugin-params.json') : join(workspace, '.clado', 'plugin-params.json'));
|
|
1007
|
+
const doc = readJsonSafe(filePath, {});
|
|
1008
|
+
const cleanEnv = {};
|
|
1009
|
+
if (env && typeof env === 'object' && !Array.isArray(env)) {
|
|
1010
|
+
for (const [k, v] of Object.entries(env)) {
|
|
1011
|
+
const ck = String(k || '').trim();
|
|
1012
|
+
if (ck) cleanEnv[ck] = String(v ?? '');
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
const cleanParams = (params && typeof params === 'object' && !Array.isArray(params)) ? params : {};
|
|
1016
|
+
doc[id] = { env: cleanEnv, params: cleanParams, updatedAt: new Date().toISOString() };
|
|
1017
|
+
writeJsonSafe(filePath, doc);
|
|
1018
|
+
return { ok: true, pluginId: id, scope: targetScope, path: filePath };
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
export function deletePluginParams(pluginId, scope = 'all', workspace = process.cwd(), stateDir = '', agentDir = resolvePiAgentDir()) {
|
|
1022
|
+
const id = String(pluginId || '').trim();
|
|
1023
|
+
if (!id) return { ok: false };
|
|
1024
|
+
const paths = scope === 'user'
|
|
1025
|
+
? [join(agentDir, 'clado-plugin-params.json')]
|
|
1026
|
+
: scope === 'project'
|
|
1027
|
+
? [stateDir ? join(stateDir, 'plugin-params.json') : join(workspace, '.clado', 'plugin-params.json')]
|
|
1028
|
+
: [
|
|
1029
|
+
join(agentDir, 'clado-plugin-params.json'),
|
|
1030
|
+
stateDir ? join(stateDir, 'plugin-params.json') : join(workspace, '.clado', 'plugin-params.json'),
|
|
1031
|
+
];
|
|
1032
|
+
let removed = false;
|
|
1033
|
+
for (const p of paths) {
|
|
1034
|
+
const doc = readJsonSafe(p, null);
|
|
1035
|
+
if (doc && typeof doc === 'object' && id in doc) {
|
|
1036
|
+
delete doc[id];
|
|
1037
|
+
writeJsonSafe(p, doc);
|
|
1038
|
+
removed = true;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
return { ok: removed, pluginId: id };
|
|
1042
|
+
}
|
|
1043
|
+
|
|
786
1044
|
export function savePiSkill({ name, description, content, scope = 'user' }, workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
|
|
787
1045
|
const slug = String(name || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
788
1046
|
if (!slug) throw new Error('Skill 名称不能为空。');
|
|
@@ -1004,3 +1262,595 @@ export function resetCladoPlatformDocs(agentDir = resolvePiAgentDir()) {
|
|
|
1004
1262
|
if (defaultReference) writeFileSync(referencePath, defaultReference, 'utf8');
|
|
1005
1263
|
return { ok: true, ...ensureCladoPlatformDocs(agentDir) };
|
|
1006
1264
|
}
|
|
1265
|
+
|
|
1266
|
+
// ============================================================================
|
|
1267
|
+
// 7. Full Pi 1.x Settings Bridge (User ~/.pi/agent/settings.json + Project .pi/settings.json)
|
|
1268
|
+
// ============================================================================
|
|
1269
|
+
|
|
1270
|
+
export const BUILTIN_PI_TOOLS = [
|
|
1271
|
+
{ id: 'read', label: 'read', desc: '读取工作区文件与图片' },
|
|
1272
|
+
{ id: 'bash', label: 'bash', desc: '在工作区执行终端命令' },
|
|
1273
|
+
{ id: 'edit', label: 'edit', desc: '局部精确修改文件内容' },
|
|
1274
|
+
{ id: 'write', label: 'write', desc: '新建或整文件覆写' },
|
|
1275
|
+
{ id: 'grep', label: 'grep', desc: '正则全文检索代码' },
|
|
1276
|
+
{ id: 'find', label: 'find', desc: '按路径模式查找文件' },
|
|
1277
|
+
{ id: 'ls', label: 'ls', desc: '列出目录内容' },
|
|
1278
|
+
{ id: 'codemode', label: 'codemode', desc: 'Pi 1.x 代码编排工具模式' },
|
|
1279
|
+
{ id: 'tool_search', label: 'tool_search', desc: 'Pi 1.x 延迟工具发现检索' },
|
|
1280
|
+
];
|
|
1281
|
+
|
|
1282
|
+
export function readFullPiSettings(workspace = process.cwd(), agentDir = resolvePiAgentDir(), activeContextWindow = 128000) {
|
|
1283
|
+
const userPath = join(agentDir, 'settings.json');
|
|
1284
|
+
const projectPath = workspace ? join(workspace, '.pi', 'settings.json') : '';
|
|
1285
|
+
const userRaw = readJsonSafe(userPath, {});
|
|
1286
|
+
const projectRaw = projectPath ? readJsonSafe(projectPath, {}) : {};
|
|
1287
|
+
const merged = {
|
|
1288
|
+
...userRaw,
|
|
1289
|
+
...projectRaw,
|
|
1290
|
+
compaction: { ...(userRaw.compaction || {}), ...(projectRaw.compaction || {}) },
|
|
1291
|
+
retry: {
|
|
1292
|
+
...(userRaw.retry || {}),
|
|
1293
|
+
...(projectRaw.retry || {}),
|
|
1294
|
+
provider: { ...(userRaw.retry?.provider || {}), ...(projectRaw.retry?.provider || {}) },
|
|
1295
|
+
},
|
|
1296
|
+
branchSummary: { ...(userRaw.branchSummary || {}), ...(projectRaw.branchSummary || {}) },
|
|
1297
|
+
images: { ...(userRaw.images || {}), ...(projectRaw.images || {}) },
|
|
1298
|
+
markdown: { ...(userRaw.markdown || {}), ...(projectRaw.markdown || {}) },
|
|
1299
|
+
notices: { ...(userRaw.notices || {}), ...(projectRaw.notices || {}) },
|
|
1300
|
+
codemode: { ...(userRaw.codemode || {}), ...(projectRaw.codemode || {}) },
|
|
1301
|
+
thinkingBudgets: { ...(userRaw.thinkingBudgets || {}), ...(projectRaw.thinkingBudgets || {}) },
|
|
1302
|
+
modelThinkingLevels: { ...(userRaw.modelThinkingLevels || {}), ...(projectRaw.modelThinkingLevels || {}) },
|
|
1303
|
+
};
|
|
1304
|
+
const runtime = readRuntimeSettings(workspace, agentDir, activeContextWindow);
|
|
1305
|
+
return {
|
|
1306
|
+
userPath,
|
|
1307
|
+
projectPath,
|
|
1308
|
+
user: userRaw,
|
|
1309
|
+
project: projectRaw,
|
|
1310
|
+
effective: {
|
|
1311
|
+
// General
|
|
1312
|
+
steeringMode: merged.steeringMode || 'one-at-a-time',
|
|
1313
|
+
followUpMode: merged.followUpMode || 'one-at-a-time',
|
|
1314
|
+
shellPath: merged.shellPath || '',
|
|
1315
|
+
shellCommandPrefix: merged.shellCommandPrefix || '',
|
|
1316
|
+
httpProxy: merged.httpProxy || '',
|
|
1317
|
+
httpIdleTimeoutMs: merged.httpIdleTimeoutMs ?? '',
|
|
1318
|
+
websocketConnectTimeoutMs: merged.websocketConnectTimeoutMs ?? '',
|
|
1319
|
+
externalEditor: merged.externalEditor || '',
|
|
1320
|
+
npmCommand: Array.isArray(merged.npmCommand) ? merged.npmCommand : [],
|
|
1321
|
+
defaultProjectTrust: merged.defaultProjectTrust || 'ask',
|
|
1322
|
+
enableSkillCommands: merged.enableSkillCommands !== false,
|
|
1323
|
+
images: {
|
|
1324
|
+
autoResize: merged.images?.autoResize !== false,
|
|
1325
|
+
blockImages: Boolean(merged.images?.blockImages),
|
|
1326
|
+
},
|
|
1327
|
+
codemode: {
|
|
1328
|
+
mode: merged.codemode?.mode === 'only' ? 'only' : 'on',
|
|
1329
|
+
inlineBudget: Number(merged.codemode?.inlineBudget) || 0,
|
|
1330
|
+
},
|
|
1331
|
+
notices: {
|
|
1332
|
+
cacheMisses: merged.notices?.cacheMisses !== false,
|
|
1333
|
+
cacheWarming: merged.notices?.cacheWarming !== false,
|
|
1334
|
+
compactionCosts: merged.notices?.compactionCosts !== false,
|
|
1335
|
+
reasoningDrops: merged.notices?.reasoningDrops !== false,
|
|
1336
|
+
},
|
|
1337
|
+
// Appearance
|
|
1338
|
+
theme: merged.theme || '',
|
|
1339
|
+
hideThinkingBlock: runtime.hideThinkingBlock,
|
|
1340
|
+
markdown: {
|
|
1341
|
+
codeBlockIndent: merged.markdown?.codeBlockIndent ?? ' ',
|
|
1342
|
+
mermaid: ['off', 'final', 'streaming'].includes(merged.markdown?.mermaid) ? merged.markdown.mermaid : 'final',
|
|
1343
|
+
},
|
|
1344
|
+
// Models & Runtime
|
|
1345
|
+
defaultProvider: merged.defaultProvider || '',
|
|
1346
|
+
defaultModel: merged.defaultModel || '',
|
|
1347
|
+
enabledModels: Array.isArray(merged.enabledModels) ? merged.enabledModels : [],
|
|
1348
|
+
defaultThinkingLevel: runtime.thinkingLevel,
|
|
1349
|
+
modelThinkingLevels: merged.modelThinkingLevels || {},
|
|
1350
|
+
thinkingBudgets: {
|
|
1351
|
+
minimal: Number(merged.thinkingBudgets?.minimal) || 1024,
|
|
1352
|
+
low: Number(merged.thinkingBudgets?.low) || 4096,
|
|
1353
|
+
medium: Number(merged.thinkingBudgets?.medium) || 10000,
|
|
1354
|
+
high: Number(merged.thinkingBudgets?.high) || 24000,
|
|
1355
|
+
},
|
|
1356
|
+
transport: runtime.transport,
|
|
1357
|
+
cacheWarming: runtime.cacheWarming,
|
|
1358
|
+
compaction: {
|
|
1359
|
+
enabled: runtime.compactionEnabled,
|
|
1360
|
+
triggerPercent: runtime.compactionTriggerPercent,
|
|
1361
|
+
reserveTokens: runtime.reserveTokens,
|
|
1362
|
+
keepRecentTokens: runtime.keepRecentTokens,
|
|
1363
|
+
modelOverrides: merged.compaction?.modelOverrides && typeof merged.compaction.modelOverrides === 'object' ? merged.compaction.modelOverrides : {},
|
|
1364
|
+
},
|
|
1365
|
+
retry: {
|
|
1366
|
+
enabled: runtime.retryEnabled,
|
|
1367
|
+
maxRetries: runtime.maxRetries,
|
|
1368
|
+
baseDelayMs: Number(merged.retry?.baseDelayMs) || 2000,
|
|
1369
|
+
maxAgentDelayMs: Number(merged.retry?.maxAgentDelayMs) || 60000,
|
|
1370
|
+
provider: {
|
|
1371
|
+
timeoutMs: Number(merged.retry?.provider?.timeoutMs) || 0,
|
|
1372
|
+
maxRetries: Number(merged.retry?.provider?.maxRetries) || 0,
|
|
1373
|
+
maxRetryDelayMs: Number(merged.retry?.provider?.maxRetryDelayMs) || 0,
|
|
1374
|
+
},
|
|
1375
|
+
},
|
|
1376
|
+
branchSummary: {
|
|
1377
|
+
reserveTokens: Number(merged.branchSummary?.reserveTokens) || 16384,
|
|
1378
|
+
skipPrompt: Boolean(merged.branchSummary?.skipPrompt),
|
|
1379
|
+
},
|
|
1380
|
+
// Tools & Resource paths
|
|
1381
|
+
defaultTools: Array.isArray(merged.defaultTools) ? merged.defaultTools : [],
|
|
1382
|
+
skills: Array.isArray(merged.skills) ? merged.skills : (Array.isArray(merged.skills?.customDirectories) ? merged.skills.customDirectories : []),
|
|
1383
|
+
prompts: Array.isArray(merged.prompts) ? merged.prompts : [],
|
|
1384
|
+
extensions: Array.isArray(merged.extensions) ? merged.extensions : [],
|
|
1385
|
+
},
|
|
1386
|
+
builtinTools: BUILTIN_PI_TOOLS,
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
export async function saveFullPiSettings(patch = {}, scope = 'user', workspace = process.cwd(), agentDir = resolvePiAgentDir(), activeContextWindow = 128000) {
|
|
1391
|
+
const sc = scope === 'project' && workspace ? 'project' : 'user';
|
|
1392
|
+
const filePath = sc === 'project' ? join(workspace, '.pi', 'settings.json') : join(agentDir, 'settings.json');
|
|
1393
|
+
const raw = readJsonSafe(filePath, {});
|
|
1394
|
+
|
|
1395
|
+
const assignOrDelete = (obj, key, val) => {
|
|
1396
|
+
if (val === undefined) return;
|
|
1397
|
+
if (val === '' || val === null) delete obj[key];
|
|
1398
|
+
else obj[key] = val;
|
|
1399
|
+
};
|
|
1400
|
+
|
|
1401
|
+
// Top-level simple keys
|
|
1402
|
+
if (patch.steeringMode && ['one-at-a-time', 'all'].includes(patch.steeringMode)) raw.steeringMode = patch.steeringMode;
|
|
1403
|
+
if (patch.followUpMode && ['one-at-a-time', 'all'].includes(patch.followUpMode)) raw.followUpMode = patch.followUpMode;
|
|
1404
|
+
assignOrDelete(raw, 'shellPath', patch.shellPath !== undefined ? String(patch.shellPath || '').trim() : undefined);
|
|
1405
|
+
assignOrDelete(raw, 'shellCommandPrefix', patch.shellCommandPrefix !== undefined ? String(patch.shellCommandPrefix || '').trim() : undefined);
|
|
1406
|
+
assignOrDelete(raw, 'httpProxy', patch.httpProxy !== undefined ? String(patch.httpProxy || '').trim() : undefined);
|
|
1407
|
+
assignOrDelete(raw, 'externalEditor', patch.externalEditor !== undefined ? String(patch.externalEditor || '').trim() : undefined);
|
|
1408
|
+
assignOrDelete(raw, 'theme', patch.theme !== undefined ? String(patch.theme || '').trim() : undefined);
|
|
1409
|
+
|
|
1410
|
+
if (patch.httpIdleTimeoutMs !== undefined) {
|
|
1411
|
+
if (patch.httpIdleTimeoutMs === 'disabled') raw.httpIdleTimeoutMs = 'disabled';
|
|
1412
|
+
else if (patch.httpIdleTimeoutMs === '' || patch.httpIdleTimeoutMs === null || Number(patch.httpIdleTimeoutMs) <= 0) delete raw.httpIdleTimeoutMs;
|
|
1413
|
+
else raw.httpIdleTimeoutMs = Math.round(Number(patch.httpIdleTimeoutMs));
|
|
1414
|
+
}
|
|
1415
|
+
if (patch.websocketConnectTimeoutMs !== undefined) {
|
|
1416
|
+
if (patch.websocketConnectTimeoutMs === 'disabled') raw.websocketConnectTimeoutMs = 'disabled';
|
|
1417
|
+
else if (patch.websocketConnectTimeoutMs === '' || patch.websocketConnectTimeoutMs === null || Number(patch.websocketConnectTimeoutMs) <= 0) delete raw.websocketConnectTimeoutMs;
|
|
1418
|
+
else raw.websocketConnectTimeoutMs = Math.round(Number(patch.websocketConnectTimeoutMs));
|
|
1419
|
+
}
|
|
1420
|
+
if (patch.npmCommand !== undefined) {
|
|
1421
|
+
const arr = Array.isArray(patch.npmCommand)
|
|
1422
|
+
? patch.npmCommand.map(s => String(s || '').trim()).filter(Boolean)
|
|
1423
|
+
: String(patch.npmCommand || '').trim().split(/\s+/).filter(Boolean);
|
|
1424
|
+
if (arr.length) raw.npmCommand = arr;
|
|
1425
|
+
else delete raw.npmCommand;
|
|
1426
|
+
}
|
|
1427
|
+
if (patch.defaultProjectTrust && ['ask', 'always', 'never'].includes(patch.defaultProjectTrust)) {
|
|
1428
|
+
raw.defaultProjectTrust = patch.defaultProjectTrust;
|
|
1429
|
+
}
|
|
1430
|
+
if (typeof patch.enableSkillCommands === 'boolean') raw.enableSkillCommands = patch.enableSkillCommands;
|
|
1431
|
+
if (typeof patch.hideThinkingBlock === 'boolean') raw.hideThinkingBlock = patch.hideThinkingBlock;
|
|
1432
|
+
if (patch.defaultThinkingLevel && THINKING_LEVELS.includes(patch.defaultThinkingLevel)) raw.defaultThinkingLevel = patch.defaultThinkingLevel;
|
|
1433
|
+
if (patch.transport && TRANSPORT_MODES.includes(patch.transport)) raw.transport = patch.transport;
|
|
1434
|
+
if (patch.cacheWarming && CACHE_WARMING_MODES.includes(patch.cacheWarming)) raw.cacheWarming = patch.cacheWarming;
|
|
1435
|
+
|
|
1436
|
+
// Nested objects
|
|
1437
|
+
if (patch.images && typeof patch.images === 'object') {
|
|
1438
|
+
raw.images = { ...(raw.images || {}), ...patch.images };
|
|
1439
|
+
}
|
|
1440
|
+
if (patch.codemode && typeof patch.codemode === 'object') {
|
|
1441
|
+
const cm = { ...(raw.codemode || {}) };
|
|
1442
|
+
if (['on', 'only'].includes(patch.codemode.mode)) cm.mode = patch.codemode.mode;
|
|
1443
|
+
if (Number(patch.codemode.inlineBudget) > 0) cm.inlineBudget = Math.round(Number(patch.codemode.inlineBudget));
|
|
1444
|
+
else if (patch.codemode.inlineBudget === 0 || patch.codemode.inlineBudget === '') delete cm.inlineBudget;
|
|
1445
|
+
raw.codemode = cm;
|
|
1446
|
+
}
|
|
1447
|
+
if (patch.notices && typeof patch.notices === 'object') {
|
|
1448
|
+
raw.notices = { ...(raw.notices || {}), ...patch.notices };
|
|
1449
|
+
}
|
|
1450
|
+
if (patch.markdown && typeof patch.markdown === 'object') {
|
|
1451
|
+
const md = { ...(raw.markdown || {}) };
|
|
1452
|
+
if (typeof patch.markdown.codeBlockIndent === 'string') md.codeBlockIndent = patch.markdown.codeBlockIndent;
|
|
1453
|
+
if (['off', 'final', 'streaming'].includes(patch.markdown.mermaid)) md.mermaid = patch.markdown.mermaid;
|
|
1454
|
+
raw.markdown = md;
|
|
1455
|
+
}
|
|
1456
|
+
if (Array.isArray(patch.enabledModels)) {
|
|
1457
|
+
const clean = [...new Set(patch.enabledModels.map(s => String(s || '').trim()).filter(Boolean))];
|
|
1458
|
+
if (clean.length) raw.enabledModels = clean;
|
|
1459
|
+
else delete raw.enabledModels;
|
|
1460
|
+
}
|
|
1461
|
+
if (patch.modelThinkingLevels && typeof patch.modelThinkingLevels === 'object') {
|
|
1462
|
+
const clean = {};
|
|
1463
|
+
for (const [k, v] of Object.entries(patch.modelThinkingLevels)) {
|
|
1464
|
+
if (String(k).trim() && THINKING_LEVELS.includes(v)) clean[String(k).trim()] = v;
|
|
1465
|
+
}
|
|
1466
|
+
if (Object.keys(clean).length) raw.modelThinkingLevels = clean;
|
|
1467
|
+
else delete raw.modelThinkingLevels;
|
|
1468
|
+
}
|
|
1469
|
+
if (patch.thinkingBudgets && typeof patch.thinkingBudgets === 'object') {
|
|
1470
|
+
const tb = { ...(raw.thinkingBudgets || {}) };
|
|
1471
|
+
for (const lvl of ['minimal', 'low', 'medium', 'high']) {
|
|
1472
|
+
if (Number(patch.thinkingBudgets[lvl]) > 0) tb[lvl] = Math.round(Number(patch.thinkingBudgets[lvl]));
|
|
1473
|
+
}
|
|
1474
|
+
raw.thinkingBudgets = tb;
|
|
1475
|
+
}
|
|
1476
|
+
if (patch.compaction && typeof patch.compaction === 'object') {
|
|
1477
|
+
const comp = { ...(raw.compaction || {}) };
|
|
1478
|
+
if (typeof patch.compaction.enabled === 'boolean') comp.enabled = patch.compaction.enabled;
|
|
1479
|
+
if (Number(patch.compaction.keepRecentTokens) >= 2048) comp.keepRecentTokens = Math.round(Number(patch.compaction.keepRecentTokens));
|
|
1480
|
+
if (Number(patch.compaction.triggerPercent) >= 50 && Number(patch.compaction.triggerPercent) <= 95) {
|
|
1481
|
+
const pct = Math.round(Number(patch.compaction.triggerPercent));
|
|
1482
|
+
const ctxWin = clampInt(activeContextWindow, 8192, 4000000, 128000);
|
|
1483
|
+
comp.reserveTokens = Math.max(4096, Math.round(ctxWin * (1 - pct / 100)));
|
|
1484
|
+
const sidecarPath = join(agentDir, 'clado-runtime.json');
|
|
1485
|
+
const sidecar = readJsonSafe(sidecarPath, {});
|
|
1486
|
+
sidecar.compactionTriggerPercent = pct;
|
|
1487
|
+
writeJsonSafe(sidecarPath, sidecar);
|
|
1488
|
+
} else if (Number(patch.compaction.reserveTokens) >= 4096) {
|
|
1489
|
+
comp.reserveTokens = Math.round(Number(patch.compaction.reserveTokens));
|
|
1490
|
+
}
|
|
1491
|
+
if (patch.compaction.modelOverrides && typeof patch.compaction.modelOverrides === 'object') {
|
|
1492
|
+
const cleanOv = {};
|
|
1493
|
+
for (const [mk, mv] of Object.entries(patch.compaction.modelOverrides)) {
|
|
1494
|
+
if (!String(mk).trim() || !mv || typeof mv !== 'object') continue;
|
|
1495
|
+
const entry = {};
|
|
1496
|
+
if (Number(mv.reserveTokens) >= 1024) entry.reserveTokens = Math.round(Number(mv.reserveTokens));
|
|
1497
|
+
if (Number(mv.keepRecentTokens) >= 1024) entry.keepRecentTokens = Math.round(Number(mv.keepRecentTokens));
|
|
1498
|
+
if (Object.keys(entry).length) cleanOv[String(mk).trim()] = entry;
|
|
1499
|
+
}
|
|
1500
|
+
if (Object.keys(cleanOv).length) comp.modelOverrides = cleanOv;
|
|
1501
|
+
else delete comp.modelOverrides;
|
|
1502
|
+
}
|
|
1503
|
+
raw.compaction = comp;
|
|
1504
|
+
}
|
|
1505
|
+
if (patch.retry && typeof patch.retry === 'object') {
|
|
1506
|
+
const rt = { ...(raw.retry || {}) };
|
|
1507
|
+
if (typeof patch.retry.enabled === 'boolean') rt.enabled = patch.retry.enabled;
|
|
1508
|
+
if (patch.retry.maxRetries !== undefined) rt.maxRetries = clampInt(patch.retry.maxRetries, 0, 10, 3);
|
|
1509
|
+
if (Number(patch.retry.baseDelayMs) > 0) rt.baseDelayMs = Math.round(Number(patch.retry.baseDelayMs));
|
|
1510
|
+
if (Number(patch.retry.maxAgentDelayMs) > 0) rt.maxAgentDelayMs = Math.round(Number(patch.retry.maxAgentDelayMs));
|
|
1511
|
+
if (patch.retry.provider && typeof patch.retry.provider === 'object') {
|
|
1512
|
+
const pr = {};
|
|
1513
|
+
if (Number(patch.retry.provider.timeoutMs) > 0) pr.timeoutMs = Math.round(Number(patch.retry.provider.timeoutMs));
|
|
1514
|
+
if (Number(patch.retry.provider.maxRetries) > 0) pr.maxRetries = Math.round(Number(patch.retry.provider.maxRetries));
|
|
1515
|
+
if (Number(patch.retry.provider.maxRetryDelayMs) > 0) pr.maxRetryDelayMs = Math.round(Number(patch.retry.provider.maxRetryDelayMs));
|
|
1516
|
+
if (Object.keys(pr).length) rt.provider = pr;
|
|
1517
|
+
else delete rt.provider;
|
|
1518
|
+
}
|
|
1519
|
+
raw.retry = rt;
|
|
1520
|
+
}
|
|
1521
|
+
if (patch.branchSummary && typeof patch.branchSummary === 'object') {
|
|
1522
|
+
const bs = { ...(raw.branchSummary || {}) };
|
|
1523
|
+
if (Number(patch.branchSummary.reserveTokens) >= 1024) bs.reserveTokens = Math.round(Number(patch.branchSummary.reserveTokens));
|
|
1524
|
+
if (typeof patch.branchSummary.skipPrompt === 'boolean') bs.skipPrompt = patch.branchSummary.skipPrompt;
|
|
1525
|
+
raw.branchSummary = bs;
|
|
1526
|
+
}
|
|
1527
|
+
for (const listKey of ['defaultTools', 'skills', 'prompts', 'extensions']) {
|
|
1528
|
+
if (Array.isArray(patch[listKey])) {
|
|
1529
|
+
const clean = [...new Set(patch[listKey].map(s => String(s || '').trim()).filter(Boolean))];
|
|
1530
|
+
if (clean.length) raw[listKey] = clean;
|
|
1531
|
+
else delete raw[listKey];
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
writeJsonSafe(filePath, raw);
|
|
1536
|
+
return {
|
|
1537
|
+
ok: true,
|
|
1538
|
+
scope: sc,
|
|
1539
|
+
path: filePath,
|
|
1540
|
+
piSettings: readFullPiSettings(workspace, agentDir, activeContextWindow),
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
// ============================================================================
|
|
1545
|
+
// 8. Provider Connectivity Probe
|
|
1546
|
+
// ============================================================================
|
|
1547
|
+
|
|
1548
|
+
export async function testProviderConnection({ providerId, api, baseUrl, apiKey, headers } = {}, agentDir = resolvePiAgentDir()) {
|
|
1549
|
+
const cleanId = String(providerId || '').trim().toLowerCase();
|
|
1550
|
+
const preset = PROVIDER_CATALOG.find(p => p.id === cleanId);
|
|
1551
|
+
const auth = readPiAuth(agentDir);
|
|
1552
|
+
const modelsCfg = readPiModelsConfig(agentDir);
|
|
1553
|
+
const custom = modelsCfg.providers?.[cleanId] || {};
|
|
1554
|
+
|
|
1555
|
+
const resolvedApi = api || custom.api || preset?.api || 'openai-completions';
|
|
1556
|
+
const resolvedBase = String(baseUrl || custom.baseUrl || preset?.defaultBaseUrl || '').trim().replace(/\/+$/, '');
|
|
1557
|
+
const resolvedKey = (typeof apiKey === 'string' && apiKey.trim() && !apiKey.includes('••••'))
|
|
1558
|
+
? apiKey.trim()
|
|
1559
|
+
: (auth[cleanId]?.key || custom.apiKey || (preset?.envKey ? process.env[preset.envKey] : '') || '');
|
|
1560
|
+
if (!resolvedBase) return { ok: false, status: 0, latencyMs: 0, discoveredModels: [], message: '请先填写 Base URL' };
|
|
1561
|
+
|
|
1562
|
+
const reqHeaders = {
|
|
1563
|
+
accept: 'application/json',
|
|
1564
|
+
...(custom.headers || {}),
|
|
1565
|
+
...(headers && typeof headers === 'object' ? headers : {}),
|
|
1566
|
+
};
|
|
1567
|
+
let probeUrl = `${resolvedBase}/models`;
|
|
1568
|
+
if (resolvedApi === 'anthropic-messages') {
|
|
1569
|
+
probeUrl = resolvedBase.endsWith('/v1') ? `${resolvedBase}/models` : `${resolvedBase}/v1/models`;
|
|
1570
|
+
if (resolvedKey) reqHeaders['x-api-key'] = resolvedKey;
|
|
1571
|
+
reqHeaders['anthropic-version'] = reqHeaders['anthropic-version'] || '2023-06-01';
|
|
1572
|
+
} else if (resolvedApi === 'google-generative-ai') {
|
|
1573
|
+
probeUrl = `${resolvedBase}/models${resolvedKey ? `?key=${encodeURIComponent(resolvedKey)}` : ''}`;
|
|
1574
|
+
} else {
|
|
1575
|
+
if (resolvedKey) reqHeaders.authorization = `Bearer ${resolvedKey}`;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
const start = Date.now();
|
|
1579
|
+
const ctrl = new AbortController();
|
|
1580
|
+
const timer = setTimeout(() => ctrl.abort(), 8000);
|
|
1581
|
+
try {
|
|
1582
|
+
const res = await fetch(probeUrl, { method: 'GET', headers: reqHeaders, signal: ctrl.signal });
|
|
1583
|
+
const latencyMs = Date.now() - start;
|
|
1584
|
+
const text = await res.text();
|
|
1585
|
+
let parsed = null;
|
|
1586
|
+
try { parsed = JSON.parse(text); } catch {}
|
|
1587
|
+
const discoveredModels = Array.isArray(parsed?.data)
|
|
1588
|
+
? parsed.data.map(m => String(m?.id || '')).filter(Boolean).slice(0, 30)
|
|
1589
|
+
: Array.isArray(parsed?.models)
|
|
1590
|
+
? parsed.models.map(m => String(m?.name || m?.id || '').replace(/^models\//, '')).filter(Boolean).slice(0, 30)
|
|
1591
|
+
: [];
|
|
1592
|
+
if (res.ok) {
|
|
1593
|
+
return {
|
|
1594
|
+
ok: true,
|
|
1595
|
+
status: res.status,
|
|
1596
|
+
latencyMs,
|
|
1597
|
+
discoveredModels,
|
|
1598
|
+
message: discoveredModels.length
|
|
1599
|
+
? `连接成功 (${res.status} · ${latencyMs}ms),探测到 ${discoveredModels.length} 个模型`
|
|
1600
|
+
: `连接成功 (${res.status} · ${latencyMs}ms)`,
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
const errMsg = parsed?.error?.message || parsed?.message || text.slice(0, 180) || `HTTP ${res.status}`;
|
|
1604
|
+
return { ok: false, status: res.status, latencyMs, discoveredModels: [], message: `HTTP ${res.status}: ${errMsg}` };
|
|
1605
|
+
} catch (err) {
|
|
1606
|
+
return { ok: false, status: 0, latencyMs: Date.now() - start, discoveredModels: [], message: err?.name === 'AbortError' ? '连接超时 (>8s)' : (err?.message || '网络请求失败') };
|
|
1607
|
+
} finally {
|
|
1608
|
+
clearTimeout(timer);
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
// ============================================================================
|
|
1613
|
+
// 9. Workspace Preferences, Multi-Layer Memory & Scoped Rules (.clado/rules/)
|
|
1614
|
+
// ============================================================================
|
|
1615
|
+
|
|
1616
|
+
export function readWorkspacePrefs(workspace) {
|
|
1617
|
+
if (!workspace) return { defaultRoleId: 'architect' };
|
|
1618
|
+
const filePath = join(resolve(workspace), '.clado', 'workspace-prefs.json');
|
|
1619
|
+
const raw = readJsonSafe(filePath, {});
|
|
1620
|
+
return {
|
|
1621
|
+
path: filePath,
|
|
1622
|
+
defaultRoleId: String(raw?.defaultRoleId || 'architect'),
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
export function saveWorkspacePrefs(patch = {}, workspace) {
|
|
1627
|
+
if (!workspace) throw new Error('工作区路径不能为空。');
|
|
1628
|
+
const filePath = join(resolve(workspace), '.clado', 'workspace-prefs.json');
|
|
1629
|
+
const prev = readJsonSafe(filePath, {});
|
|
1630
|
+
const next = {
|
|
1631
|
+
...prev,
|
|
1632
|
+
...(patch.defaultRoleId !== undefined ? { defaultRoleId: String(patch.defaultRoleId || 'architect').trim() } : {}),
|
|
1633
|
+
};
|
|
1634
|
+
writeJsonSafe(filePath, next);
|
|
1635
|
+
return { ok: true, ...readWorkspacePrefs(workspace) };
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
export function readMemoryBundle(workspace, agentDir = resolvePiAgentDir()) {
|
|
1639
|
+
const globalPath = join(agentDir, 'AGENTS.md');
|
|
1640
|
+
const globalExists = existsSync(globalPath);
|
|
1641
|
+
const globalContent = globalExists ? readFileSync(globalPath, 'utf8') : '';
|
|
1642
|
+
const project = readAgentsMemory(workspace);
|
|
1643
|
+
const rulesDir = workspace ? join(resolve(workspace), '.clado', 'rules') : '';
|
|
1644
|
+
const rules = [];
|
|
1645
|
+
if (rulesDir && existsSync(rulesDir)) {
|
|
1646
|
+
try {
|
|
1647
|
+
for (const name of readdirSync(rulesDir).sort()) {
|
|
1648
|
+
if (!name.endsWith('.md')) continue;
|
|
1649
|
+
const full = join(rulesDir, name);
|
|
1650
|
+
try {
|
|
1651
|
+
if (!statSync(full).isFile()) continue;
|
|
1652
|
+
rules.push({
|
|
1653
|
+
name: name.replace(/\.md$/i, ''),
|
|
1654
|
+
fileName: name,
|
|
1655
|
+
path: full,
|
|
1656
|
+
content: readFileSync(full, 'utf8'),
|
|
1657
|
+
});
|
|
1658
|
+
} catch {}
|
|
1659
|
+
}
|
|
1660
|
+
} catch {}
|
|
1661
|
+
}
|
|
1662
|
+
return {
|
|
1663
|
+
global: { path: globalPath, exists: globalExists, content: globalContent },
|
|
1664
|
+
project,
|
|
1665
|
+
rulesDir,
|
|
1666
|
+
rules,
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
export function saveGlobalAgentsMemory(content, agentDir = resolvePiAgentDir()) {
|
|
1671
|
+
mkdirSync(agentDir, { recursive: true });
|
|
1672
|
+
const filePath = join(agentDir, 'AGENTS.md');
|
|
1673
|
+
writeFileSync(filePath, String(content || ''), 'utf8');
|
|
1674
|
+
return { ok: true, path: filePath, exists: true, content: String(content || '') };
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
export function saveProjectRule({ name, content } = {}, workspace) {
|
|
1678
|
+
if (!workspace) throw new Error('缺少工作区路径。');
|
|
1679
|
+
const slug = String(name || '').trim().replace(/\.md$/i, '').replace(/[^a-zA-Z0-9._\-\u4e00-\u9fa5]+/g, '-').replace(/^-+|-+$/g, '');
|
|
1680
|
+
if (!slug) throw new Error('规则文件名不能为空。');
|
|
1681
|
+
const dir = join(resolve(workspace), '.clado', 'rules');
|
|
1682
|
+
mkdirSync(dir, { recursive: true });
|
|
1683
|
+
const filePath = join(dir, slug + '.md');
|
|
1684
|
+
writeFileSync(filePath, String(content || ''), 'utf8');
|
|
1685
|
+
return { ok: true, name: slug, path: filePath };
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
export function deleteProjectRule(name, workspace) {
|
|
1689
|
+
if (!workspace) return { ok: false };
|
|
1690
|
+
const slug = String(name || '').trim().replace(/\.md$/i, '');
|
|
1691
|
+
if (!slug || slug.includes('..') || slug.includes('/') || slug.includes('\\')) return { ok: false };
|
|
1692
|
+
const filePath = join(resolve(workspace), '.clado', 'rules', slug + '.md');
|
|
1693
|
+
if (existsSync(filePath)) {
|
|
1694
|
+
rmSync(filePath, { force: true });
|
|
1695
|
+
return { ok: true, name: slug };
|
|
1696
|
+
}
|
|
1697
|
+
return { ok: false, name: slug };
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
export function readSkillOrPromptContent(filePath, workspace, agentDir = resolvePiAgentDir()) {
|
|
1701
|
+
const target = resolve(String(filePath || ''));
|
|
1702
|
+
const allowedRoots = [
|
|
1703
|
+
resolve(agentDir),
|
|
1704
|
+
workspace ? resolve(workspace, '.pi') : '',
|
|
1705
|
+
workspace ? resolve(workspace, '.clado') : '',
|
|
1706
|
+
].filter(Boolean);
|
|
1707
|
+
const inside = allowedRoots.some(root => {
|
|
1708
|
+
const rel = relative(root, target);
|
|
1709
|
+
return rel && !rel.startsWith('..') && !rel.startsWith('/');
|
|
1710
|
+
});
|
|
1711
|
+
if (!inside || !existsSync(target)) throw new Error('无法读取指定文件(路径越界或不存在)。');
|
|
1712
|
+
return { ok: true, path: target, content: readFileSync(target, 'utf8') };
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
// ============================================================================
|
|
1716
|
+
// 10. External MCP Auto-Discovery Importer (Claude Code / Cursor / Codex)
|
|
1717
|
+
// ============================================================================
|
|
1718
|
+
|
|
1719
|
+
function parseSimpleCodexMcpToml(text) {
|
|
1720
|
+
const servers = {};
|
|
1721
|
+
const lines = String(text || '').split(/\r?\n/);
|
|
1722
|
+
let current = null;
|
|
1723
|
+
for (const rawLine of lines) {
|
|
1724
|
+
const line = rawLine.trim();
|
|
1725
|
+
if (!line || line.startsWith('#')) continue;
|
|
1726
|
+
const sec = line.match(/^\[mcp_servers\.([a-zA-Z0-9._-]+)(?:\.(env|headers))?\]$/);
|
|
1727
|
+
if (sec) {
|
|
1728
|
+
const name = sec[1];
|
|
1729
|
+
const sub = sec[2] || '';
|
|
1730
|
+
if (!servers[name]) servers[name] = {};
|
|
1731
|
+
current = { name, sub };
|
|
1732
|
+
continue;
|
|
1733
|
+
}
|
|
1734
|
+
if (line.startsWith('[')) {
|
|
1735
|
+
current = null;
|
|
1736
|
+
continue;
|
|
1737
|
+
}
|
|
1738
|
+
if (!current) continue;
|
|
1739
|
+
const kv = line.match(/^([a-zA-Z0-9._-]+)\s*=\s*(.+)$/);
|
|
1740
|
+
if (!kv) continue;
|
|
1741
|
+
const key = kv[1].trim();
|
|
1742
|
+
const rawVal = kv[2].trim();
|
|
1743
|
+
let val = rawVal;
|
|
1744
|
+
try {
|
|
1745
|
+
val = JSON.parse(rawVal.replace(/'([^']*)'/g, '"$1"'));
|
|
1746
|
+
} catch {
|
|
1747
|
+
val = rawVal.replace(/^['"]|['"]$/g, '');
|
|
1748
|
+
}
|
|
1749
|
+
if (current.sub) {
|
|
1750
|
+
servers[current.name][current.sub] = servers[current.name][current.sub] || {};
|
|
1751
|
+
servers[current.name][current.sub][key] = String(val);
|
|
1752
|
+
} else {
|
|
1753
|
+
servers[current.name][key] = val;
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
return servers;
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
export function scanExternalMcpConfigs(workspace = process.cwd(), homeOverride = '') {
|
|
1760
|
+
const home = homeOverride || homedir();
|
|
1761
|
+
const candidates = [
|
|
1762
|
+
{ source: 'Claude Code (全局)', path: join(home, '.claude.json'), format: 'json' },
|
|
1763
|
+
{ source: 'Claude Code (项目 .mcp.json)', path: workspace ? join(workspace, '.mcp.json') : '', format: 'json' },
|
|
1764
|
+
{ source: 'Cursor (全局)', path: join(home, '.cursor', 'mcp.json'), format: 'json' },
|
|
1765
|
+
{ source: 'Cursor (项目)', path: workspace ? join(workspace, '.cursor', 'mcp.json') : '', format: 'json' },
|
|
1766
|
+
{ source: 'OpenAI Codex (config.toml)', path: join(home, '.codex', 'config.toml'), format: 'toml' },
|
|
1767
|
+
].filter(c => c.path);
|
|
1768
|
+
|
|
1769
|
+
const items = [];
|
|
1770
|
+
for (const cand of candidates) {
|
|
1771
|
+
if (!existsSync(cand.path)) continue;
|
|
1772
|
+
try {
|
|
1773
|
+
const text = readFileSync(cand.path, 'utf8');
|
|
1774
|
+
let map = {};
|
|
1775
|
+
if (cand.format === 'toml') {
|
|
1776
|
+
map = parseSimpleCodexMcpToml(text);
|
|
1777
|
+
} else {
|
|
1778
|
+
const parsed = JSON.parse(text);
|
|
1779
|
+
map = parsed?.mcpServers && typeof parsed.mcpServers === 'object' ? parsed.mcpServers : {};
|
|
1780
|
+
}
|
|
1781
|
+
for (const [name, cfg] of Object.entries(map)) {
|
|
1782
|
+
if (!cfg || typeof cfg !== 'object') continue;
|
|
1783
|
+
if (!cfg.command && !cfg.url) continue;
|
|
1784
|
+
items.push({
|
|
1785
|
+
name,
|
|
1786
|
+
source: cand.source,
|
|
1787
|
+
sourcePath: cand.path,
|
|
1788
|
+
type: cfg.url ? 'http' : 'stdio',
|
|
1789
|
+
command: cfg.command || '',
|
|
1790
|
+
args: Array.isArray(cfg.args) ? cfg.args.map(String) : [],
|
|
1791
|
+
url: cfg.url || '',
|
|
1792
|
+
env: cfg.env && typeof cfg.env === 'object' ? cfg.env : {},
|
|
1793
|
+
headers: cfg.headers && typeof cfg.headers === 'object' ? cfg.headers : {},
|
|
1794
|
+
cwd: cfg.cwd || '',
|
|
1795
|
+
});
|
|
1796
|
+
}
|
|
1797
|
+
} catch {}
|
|
1798
|
+
}
|
|
1799
|
+
return { ok: true, items };
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
// ============================================================================
|
|
1803
|
+
// 11. Unified Raw Config JSON Editor (settings / mcp / models / hooks / permissions)
|
|
1804
|
+
// ============================================================================
|
|
1805
|
+
|
|
1806
|
+
export function readRawConfigTarget(target = 'settings', scope = 'user', workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
|
|
1807
|
+
const sc = scope === 'project' && workspace ? 'project' : 'user';
|
|
1808
|
+
let filePath = '';
|
|
1809
|
+
let fallback = {};
|
|
1810
|
+
if (target === 'settings') {
|
|
1811
|
+
filePath = sc === 'project' ? join(workspace, '.pi', 'settings.json') : join(agentDir, 'settings.json');
|
|
1812
|
+
fallback = {};
|
|
1813
|
+
} else if (target === 'mcp') {
|
|
1814
|
+
filePath = sc === 'project' ? join(workspace, '.pi', 'mcp.json') : join(agentDir, 'mcp.json');
|
|
1815
|
+
fallback = { mcpServers: {} };
|
|
1816
|
+
} else if (target === 'models') {
|
|
1817
|
+
filePath = join(agentDir, 'models.json');
|
|
1818
|
+
fallback = { providers: {} };
|
|
1819
|
+
} else if (target === 'hooks') {
|
|
1820
|
+
filePath = hooksFilePath(sc, workspace, agentDir);
|
|
1821
|
+
fallback = { version: 1, hooks: [] };
|
|
1822
|
+
} else if (target === 'permissions') {
|
|
1823
|
+
filePath = permissionsFilePath(sc, workspace, agentDir);
|
|
1824
|
+
fallback = { version: 1, mode: sc === 'user' ? 'full-access' : undefined, allow: [], ask: [], deny: [], shellEnvExclude: [] };
|
|
1825
|
+
} else {
|
|
1826
|
+
throw new Error(`不支持的原始配置目标:${target}`);
|
|
1827
|
+
}
|
|
1828
|
+
const exists = existsSync(filePath);
|
|
1829
|
+
let content = JSON.stringify(fallback, null, 2) + '\n';
|
|
1830
|
+
if (exists) {
|
|
1831
|
+
try { content = readFileSync(filePath, 'utf8'); } catch {}
|
|
1832
|
+
}
|
|
1833
|
+
return { ok: true, target, scope: target === 'models' ? 'user' : sc, path: filePath, exists, content };
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
export function saveRawConfigTarget(target = 'settings', scope = 'user', jsonText = '', workspace = process.cwd(), agentDir = resolvePiAgentDir()) {
|
|
1837
|
+
if (target === 'mcp') return savePiMcpRawJson(scope, jsonText, workspace, agentDir);
|
|
1838
|
+
if (target === 'hooks') return saveHooksRawJson(scope, jsonText, workspace, agentDir);
|
|
1839
|
+
if (target === 'permissions') return savePermissionsRawJson(scope, jsonText, workspace, agentDir);
|
|
1840
|
+
|
|
1841
|
+
let parsed;
|
|
1842
|
+
try {
|
|
1843
|
+
parsed = JSON.parse(String(jsonText || '{}'));
|
|
1844
|
+
} catch (err) {
|
|
1845
|
+
throw new Error('JSON 语法错误:' + err.message);
|
|
1846
|
+
}
|
|
1847
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
1848
|
+
throw new Error('配置文件顶层必须是 JSON 对象。');
|
|
1849
|
+
}
|
|
1850
|
+
const sc = scope === 'project' && workspace ? 'project' : 'user';
|
|
1851
|
+
const filePath = target === 'models'
|
|
1852
|
+
? join(agentDir, 'models.json')
|
|
1853
|
+
: (sc === 'project' ? join(workspace, '.pi', 'settings.json') : join(agentDir, 'settings.json'));
|
|
1854
|
+
writeJsonSafe(filePath, parsed);
|
|
1855
|
+
return { ok: true, target, scope: target === 'models' ? 'user' : sc, path: filePath };
|
|
1856
|
+
}
|