cladogram 0.6.0-beta.8 → 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 +21 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +46 -1850
- package/plugins/agent/settings.js +3329 -0
- package/plugins/agent/style.css +164 -0
- package/src/agent/pi-bridge.js +84 -5
- package/src/agent/pi-config.js +757 -33
- package/src/agent/pi-hooks-perms.js +621 -0
- package/src/html/plugin-assets.js +5 -1
- package/src/server/agent.js +165 -1
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 兼容)',
|
|
@@ -303,12 +382,15 @@ function inferReasoning(modelId) {
|
|
|
303
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 || ''));
|
|
304
383
|
}
|
|
305
384
|
|
|
306
|
-
export function saveProviderConfig({
|
|
385
|
+
export async function saveProviderConfig({
|
|
307
386
|
providerId,
|
|
387
|
+
name,
|
|
308
388
|
apiKey,
|
|
309
389
|
baseUrl,
|
|
310
390
|
api,
|
|
391
|
+
headers,
|
|
311
392
|
models,
|
|
393
|
+
replaceModels = false,
|
|
312
394
|
defaultModel,
|
|
313
395
|
contextWindow,
|
|
314
396
|
maxTokens,
|
|
@@ -329,15 +411,24 @@ export function saveProviderConfig({
|
|
|
329
411
|
writeJsonSafe(authPath, auth);
|
|
330
412
|
}
|
|
331
413
|
|
|
332
|
-
// 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
|
|
333
415
|
const cleanBaseUrl = typeof baseUrl === 'string' ? baseUrl.trim().replace(/\/+$/, '') : '';
|
|
334
|
-
const
|
|
335
|
-
|
|
336
|
-
|
|
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);
|
|
337
425
|
const chosenModel = String(defaultModel || modelIds[0] || preset?.defaultModel || '').trim();
|
|
338
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;
|
|
339
430
|
|
|
340
|
-
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-')) {
|
|
341
432
|
const cfg = readPiModelsConfig(agentDir);
|
|
342
433
|
const prev = cfg.providers[cleanId] || {};
|
|
343
434
|
const prevById = new Map(
|
|
@@ -351,37 +442,55 @@ export function saveProviderConfig({
|
|
|
351
442
|
api: resolvedApi,
|
|
352
443
|
...(cleanBaseUrl ? { baseUrl: cleanBaseUrl } : prev.baseUrl ? { baseUrl: prev.baseUrl } : preset?.defaultBaseUrl ? { baseUrl: preset.defaultBaseUrl } : {}),
|
|
353
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
|
+
}
|
|
354
452
|
if (preset?.keyless && !nextEntry.apiKey) nextEntry.apiKey = 'ollama';
|
|
355
453
|
const recommendedIds = (preset?.recommendedModels || []).map(m => m.id);
|
|
356
|
-
const mergedIds =
|
|
357
|
-
...(chosenModel ? [chosenModel] : []),
|
|
358
|
-
...
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
+
])];
|
|
362
462
|
if (mergedIds.length) {
|
|
363
463
|
nextEntry.models = mergedIds.map(id => {
|
|
464
|
+
const inItem = inputById.get(id);
|
|
364
465
|
const prevItem = prevById.get(id);
|
|
365
466
|
const recSpec = lookupRecommendedSpec(preset, id);
|
|
366
467
|
const isTarget = id === chosenModel;
|
|
367
|
-
const resolvedCtx =
|
|
368
|
-
? clampInt(contextWindow, 4096, 4000000, preset?.defaultContextWindow || 128000)
|
|
369
|
-
: (
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
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))));
|
|
376
483
|
return {
|
|
377
484
|
id,
|
|
378
|
-
name: recSpec?.label || prevItem?.name || id,
|
|
485
|
+
name: inItem?.name || recSpec?.label || prevItem?.name || id,
|
|
379
486
|
reasoning: resolvedReasoning,
|
|
380
|
-
input: prevItem?.input || ['text'],
|
|
487
|
+
input: Array.isArray(inItem?.input) && inItem.input.length ? inItem.input : (prevItem?.input || ['text']),
|
|
381
488
|
contextWindow: resolvedCtx,
|
|
382
489
|
maxTokens: resolvedMaxOut,
|
|
383
490
|
};
|
|
384
491
|
});
|
|
492
|
+
} else if (replaceModels) {
|
|
493
|
+
nextEntry.models = [];
|
|
385
494
|
}
|
|
386
495
|
cfg.providers[cleanId] = nextEntry;
|
|
387
496
|
writeJsonSafe(modelsPath, cfg);
|
|
@@ -390,6 +499,7 @@ export function saveProviderConfig({
|
|
|
390
499
|
if (setAsDefault && chosenModel) {
|
|
391
500
|
const sm = SettingsManager.create(workspace, agentDir);
|
|
392
501
|
sm.setDefaultModelAndProvider(cleanId, chosenModel);
|
|
502
|
+
await sm.flush();
|
|
393
503
|
}
|
|
394
504
|
|
|
395
505
|
return { ok: true, providerId: cleanId, defaultModel: chosenModel };
|
|
@@ -446,7 +556,7 @@ export async function listProvidersAndModels(workspace = process.cwd(), agentDir
|
|
|
446
556
|
const authEntry = auth[id];
|
|
447
557
|
const customEntry = customCfg.providers?.[id];
|
|
448
558
|
const envHasKey = Boolean(preset?.envKey && process.env[preset.envKey]);
|
|
449
|
-
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));
|
|
450
560
|
const runtimeModels = mr.getModels(id) || [];
|
|
451
561
|
const customModelObjs = Array.isArray(customEntry?.models) ? customEntry.models : [];
|
|
452
562
|
const customById = new Map(customModelObjs.filter(m => m && typeof m === 'object' && m.id).map(m => [m.id, m]));
|
|
@@ -473,38 +583,42 @@ export async function listProvidersAndModels(workspace = process.cwd(), agentDir
|
|
|
473
583
|
const reas = typeof cObj?.reasoning === 'boolean'
|
|
474
584
|
? cObj.reasoning
|
|
475
585
|
: (typeof rObj?.reasoning === 'boolean' ? rObj.reasoning : (typeof rec?.reasoning === 'boolean' ? rec.reasoning : inferReasoning(mId)));
|
|
476
|
-
|
|
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 };
|
|
477
588
|
};
|
|
478
589
|
|
|
479
590
|
const activeSpecs = resolveSpecs(activeModelId);
|
|
480
591
|
|
|
481
592
|
providers.push({
|
|
482
593
|
id,
|
|
483
|
-
name: preset?.name || id,
|
|
594
|
+
name: preset?.name || customEntry?.displayName || id,
|
|
595
|
+
isCustom: !preset,
|
|
484
596
|
api: customEntry?.api || preset?.api || 'openai-completions',
|
|
485
597
|
baseUrl: customEntry?.baseUrl || preset?.defaultBaseUrl || '',
|
|
598
|
+
headers: customEntry?.headers && typeof customEntry.headers === 'object' ? customEntry.headers : {},
|
|
486
599
|
hint: preset?.hint || '',
|
|
487
600
|
keyless: Boolean(preset?.keyless),
|
|
488
601
|
configured: hasAuth,
|
|
489
|
-
authSource: authEntry?.key ? 'auth.json' : authEntry?.access ? 'oauth' : envHasKey ? 'env' : preset?.keyless && customEntry ? 'local' : '',
|
|
490
|
-
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) : ''),
|
|
491
604
|
defaultModel: activeModelId,
|
|
492
605
|
contextWindow: activeSpecs.contextWindow,
|
|
493
606
|
maxTokens: activeSpecs.maxTokens,
|
|
494
607
|
reasoning: activeSpecs.reasoning,
|
|
495
608
|
recommendedModels: preset?.recommendedModels || [],
|
|
496
609
|
models: modelList,
|
|
610
|
+
modelDetails: modelList.map(mId => ({ id: mId, ...resolveSpecs(mId) })),
|
|
497
611
|
});
|
|
498
612
|
|
|
499
613
|
if (hasAuth) {
|
|
500
|
-
for (const mId of modelList.slice(0,
|
|
614
|
+
for (const mId of modelList.slice(0, 20)) {
|
|
501
615
|
const specs = resolveSpecs(mId);
|
|
502
616
|
configuredModels.push({
|
|
503
617
|
id: `${id}/${mId}`,
|
|
504
618
|
provider: id,
|
|
505
619
|
model: mId,
|
|
506
620
|
label: `${mId}`,
|
|
507
|
-
providerName: preset?.name || id,
|
|
621
|
+
providerName: preset?.name || customEntry?.displayName || id,
|
|
508
622
|
contextWindow: specs.contextWindow,
|
|
509
623
|
maxTokens: specs.maxTokens,
|
|
510
624
|
reasoning: specs.reasoning,
|
|
@@ -634,7 +748,9 @@ export function listRoles(agentDir = resolvePiAgentDir()) {
|
|
|
634
748
|
const raw = readJsonSafe(customPath, []);
|
|
635
749
|
const custom = Array.isArray(raw) ? raw.filter(r => r && r.id && r.name) : [];
|
|
636
750
|
const merged = new Map();
|
|
637
|
-
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
|
+
}
|
|
638
754
|
for (const role of custom) {
|
|
639
755
|
const existing = merged.get(role.id);
|
|
640
756
|
merged.set(role.id, {
|
|
@@ -643,9 +759,13 @@ export function listRoles(agentDir = resolvePiAgentDir()) {
|
|
|
643
759
|
phase: String(role.phase || existing?.phase || '自定义').trim(),
|
|
644
760
|
tone: ['sky', 'emerald', 'violet', 'amber'].includes(role.tone) ? role.tone : (existing?.tone || 'sky'),
|
|
645
761
|
builtin: Boolean(existing?.builtin),
|
|
762
|
+
customized: Boolean(existing?.builtin),
|
|
646
763
|
description: String(role.description || existing?.description || '').trim(),
|
|
647
764
|
systemPrompt: String(role.systemPrompt || existing?.systemPrompt || '').trim(),
|
|
648
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) : [],
|
|
649
769
|
});
|
|
650
770
|
}
|
|
651
771
|
return [...merged.values()];
|
|
@@ -672,6 +792,9 @@ export function saveRole(input, agentDir = resolvePiAgentDir()) {
|
|
|
672
792
|
description: String(input?.description || '').trim().slice(0, 200),
|
|
673
793
|
systemPrompt: String(input?.systemPrompt || '').trim().slice(0, 6000),
|
|
674
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))] : [],
|
|
675
798
|
};
|
|
676
799
|
arr.push(entry);
|
|
677
800
|
writeJsonSafe(customPath, arr);
|
|
@@ -707,6 +830,7 @@ function readMcpFile(filePath, scope) {
|
|
|
707
830
|
headers: cfg?.headers && typeof cfg.headers === 'object' ? cfg.headers : {},
|
|
708
831
|
timeout: typeof cfg?.timeout === 'number' ? cfg.timeout : undefined,
|
|
709
832
|
exposure: MCP_EXPOSURES.includes(cfg?.exposure) ? cfg.exposure : 'codemode',
|
|
833
|
+
toolExposure: cfg?.toolExposure && typeof cfg.toolExposure === 'object' && !Array.isArray(cfg.toolExposure) ? cfg.toolExposure : {},
|
|
710
834
|
description: typeof cfg?.description === 'string' ? cfg.description : '',
|
|
711
835
|
enabled: cfg?.enabled !== false && cfg?.disabled !== true,
|
|
712
836
|
}));
|
|
@@ -789,6 +913,14 @@ export function savePiMcpServer(input, workspace = process.cwd(), agentDir = res
|
|
|
789
913
|
}
|
|
790
914
|
const exposure = MCP_EXPOSURES.includes(input?.exposure) ? input.exposure : 'direct';
|
|
791
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
|
+
}
|
|
792
924
|
if (input?.enabled === false) entry.enabled = false;
|
|
793
925
|
doc.mcpServers[name] = entry;
|
|
794
926
|
writeJsonSafe(filePath, doc);
|
|
@@ -1130,3 +1262,595 @@ export function resetCladoPlatformDocs(agentDir = resolvePiAgentDir()) {
|
|
|
1130
1262
|
if (defaultReference) writeFileSync(referencePath, defaultReference, 'utf8');
|
|
1131
1263
|
return { ok: true, ...ensureCladoPlatformDocs(agentDir) };
|
|
1132
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
|
+
}
|