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.
@@ -10,17 +10,24 @@ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync }
10
10
  import { basename, extname, join, relative, resolve } from 'node:path';
11
11
  import {
12
12
  createAgentSession,
13
+ createCodemodeExtension,
14
+ createMcpExtension,
15
+ createToolSearchExtension,
13
16
  DefaultResourceLoader,
14
17
  SessionManager,
15
18
  SettingsManager,
16
19
  } from '@earendil-works/pi-coding-agent';
17
20
  import {
18
21
  createCladoModelRuntime,
22
+ listPiMcpServers,
19
23
  readCladoPlatformContext,
24
+ readMemoryBundle,
25
+ readPluginParams,
20
26
  readRuntimeSettings,
21
27
  resolvePiAgentDir,
22
28
  resolveRole,
23
29
  } from './pi-config.js';
30
+ import { createCladoGuardAndHooksExtension } from './pi-hooks-perms.js';
24
31
  import { createCladoPiTools } from './clado-tools.js';
25
32
  import { workspacePath } from '../workspace/documents.js';
26
33
 
@@ -294,6 +301,72 @@ export function deleteSession(stateDir, id, agentDir = resolvePiAgentDir()) {
294
301
  return { deleted: next.length !== list.length, id };
295
302
  }
296
303
 
304
+ export function clearArchivedSessions(stateDir, agentDir = resolvePiAgentDir()) {
305
+ const list = ensureDefaultSessions(stateDir, agentDir);
306
+ const archived = list.filter(s => s.archived);
307
+ let removed = 0;
308
+ for (const s of archived) {
309
+ const r = deleteSession(stateDir, s.id, agentDir);
310
+ if (r.deleted) removed++;
311
+ }
312
+ return { ok: true, removed };
313
+ }
314
+
315
+ export function exportSessionTranscript(stateDir, id, format = 'md', agentDir = resolvePiAgentDir()) {
316
+ const session = getSessionMeta(stateDir, id, agentDir, { includeAll: true });
317
+ if (!session) throw new Error('找不到目标会话。');
318
+ const msgs = Array.isArray(session.messages) ? session.messages : [];
319
+ if (format === 'json') {
320
+ return {
321
+ ok: true,
322
+ format: 'json',
323
+ fileName: `${safeSessionId(session.id)}.json`,
324
+ content: JSON.stringify({
325
+ id: session.id,
326
+ title: session.title,
327
+ roleId: session.roleId,
328
+ model: session.model || '',
329
+ createdAt: session.createdAt,
330
+ updatedAt: session.updatedAt,
331
+ archived: Boolean(session.archived),
332
+ messages: msgs,
333
+ }, null, 2) + '\n',
334
+ };
335
+ }
336
+ const lines = [
337
+ `# ${session.title || session.id}`,
338
+ '',
339
+ `- 会话 ID: \`${session.id}\``,
340
+ `- 角色: \`${session.roleId}\``,
341
+ ...(session.model ? [`- 模型: \`${session.model}\``] : []),
342
+ `- 导出时间: ${new Date().toISOString()}`,
343
+ '',
344
+ '---',
345
+ '',
346
+ ];
347
+ for (const m of msgs) {
348
+ const who = m.role === 'user' ? '## User' : m.role === 'system' ? '## System' : '## Assistant';
349
+ lines.push(who, '');
350
+ if (m.thinking) {
351
+ lines.push('<details><summary>Thinking</summary>', '', m.thinking, '', '</details>', '');
352
+ }
353
+ if (m.text) lines.push(String(m.text), '');
354
+ if (Array.isArray(m.tools) && m.tools.length) {
355
+ lines.push('**Tools:**', '');
356
+ for (const t of m.tools) {
357
+ lines.push(`- \`${t.name}\` (${t.status || 'done'})${t.summary ? ': ' + String(t.summary).slice(0, 160) : ''}`);
358
+ }
359
+ lines.push('');
360
+ }
361
+ }
362
+ return {
363
+ ok: true,
364
+ format: 'md',
365
+ fileName: `${safeSessionId(session.id)}.md`,
366
+ content: lines.join('\n'),
367
+ };
368
+ }
369
+
297
370
  export function captureCanvasSnapshot(documentRoot, file) {
298
371
  if (!documentRoot || !file) return null;
299
372
  try {
@@ -560,11 +633,60 @@ export function createPiBridge({
560
633
  automationOps = null,
561
634
  } = {}) {
562
635
  const liveRuns = new Map();
636
+ const warmSessions = new Map(); // `${workspace}::${cleanId}` -> { session, loader, sm, mr, modelKey, roleId, agentDir, stateDir, turnHooksRef, needsReload, notifications, extensionErrors }
563
637
  const pairNoProgressStreak = new Map(); // sorted pair key -> consecutive no-progress cross-session sends
564
638
  const SUBSTANTIVE_TOOLS = new Set([
565
639
  'clado_create', 'clado_update', 'clado_nodes', 'clado_links', 'clado_documents', 'clado_batch',
566
640
  'edit', 'write', 'bash', 'ask_user', 'canvas_objects_upsert', 'canvas_objects_delete',
567
641
  ]);
642
+ const createBuiltInPiExtensions = (agentDir, { workspace = '', getAskUser = null, getRoleTools = null } = {}) => [
643
+ { name: 'codemode', factory: createCodemodeExtension(), replaceable: true, builtin: true },
644
+ { name: 'tool-search', factory: createToolSearchExtension(), replaceable: true, builtin: true },
645
+ { name: 'mcp', factory: createMcpExtension({ logPath: join(agentDir, 'mcp.log') }), replaceable: true, builtin: true },
646
+ { name: 'clado-guard-hooks', factory: createCladoGuardAndHooksExtension({ workspace, agentDir, getAskUser, getRoleTools }), replaceable: true, builtin: true },
647
+ ];
648
+ const shutdownAndDisposeSession = async session => {
649
+ if (!session) return;
650
+ try {
651
+ if (session.extensionRunner?.hasHandlers?.('session_shutdown')) {
652
+ await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'exit' });
653
+ }
654
+ } catch {}
655
+ try { session.dispose?.(); } catch {}
656
+ };
657
+ const bindSessionForClado = async (session, entry) => {
658
+ await session.bindExtensions({
659
+ mode: 'print',
660
+ uiContext: {
661
+ notify(msg, level = 'info') {
662
+ if (!msg) return;
663
+ const note = { level: String(level || 'info'), message: String(msg), ts: Date.now() };
664
+ entry.notifications.push(note);
665
+ if (entry.notifications.length > 30) entry.notifications.splice(0, entry.notifications.length - 30);
666
+ try {
667
+ if (level === 'error' || level === 'warning') {
668
+ entry.turnHooksRef?.emit?.({ type: 'status', text: `[Pi ${level}] ${msg}` });
669
+ }
670
+ } catch {}
671
+ },
672
+ },
673
+ commandContextActions: {
674
+ waitForIdle: () => session.waitForIdle(),
675
+ reload: async () => {
676
+ await session.reload();
677
+ },
678
+ newSession: async () => ({ cancelled: true }),
679
+ fork: async () => ({ cancelled: true }),
680
+ navigateTree: async () => ({ cancelled: true }),
681
+ switchSession: async () => ({ cancelled: true }),
682
+ },
683
+ onError(err) {
684
+ const text = err?.error ? `${err.extensionPath || 'extension'}: ${err.error}` : String(err || 'Extension error');
685
+ entry.extensionErrors.push({ message: text, ts: Date.now() });
686
+ if (entry.extensionErrors.length > 20) entry.extensionErrors.splice(0, entry.extensionErrors.length - 20);
687
+ },
688
+ });
689
+ };
568
690
  const pairKeyOf = (a, b) => [String(a || ''), String(b || '')].sort().join('::');
569
691
  const resetProgressForSession = sid => {
570
692
  const clean = String(sid || '');
@@ -817,6 +939,57 @@ export function createPiBridge({
817
939
  });
818
940
  });
819
941
 
942
+ const turnId = 'turn_' + randomUUID().replace(/-/g, '').slice(0, 10);
943
+ let liveActivity = '正在思考并准备上下文…';
944
+ let sseDeltaType = '';
945
+ let sseDeltaBuf = '';
946
+ let sseDeltaTimer = null;
947
+
948
+ const flushSseDelta = () => {
949
+ if (sseDeltaTimer) {
950
+ clearTimeout(sseDeltaTimer);
951
+ sseDeltaTimer = null;
952
+ }
953
+ if (sseDeltaType && sseDeltaBuf) {
954
+ events?.emit(workspace, 'agent.stream', {
955
+ sessionId: cleanId,
956
+ roleId: role.id,
957
+ roleName: role.name,
958
+ turnId,
959
+ type: sseDeltaType,
960
+ text: sseDeltaBuf,
961
+ activity: liveActivity,
962
+ });
963
+ }
964
+ sseDeltaType = '';
965
+ sseDeltaBuf = '';
966
+ };
967
+
968
+ const emitSseStream = ev => {
969
+ if (!events || !ev || !ev.type) return;
970
+ if (ev.type === 'text' || ev.type === 'thinking') {
971
+ const chunk = String(ev.text || '');
972
+ if (!chunk) return;
973
+ if (sseDeltaType && sseDeltaType !== ev.type) flushSseDelta();
974
+ sseDeltaType = ev.type;
975
+ sseDeltaBuf += chunk;
976
+ if (!sseDeltaTimer) {
977
+ sseDeltaTimer = setTimeout(flushSseDelta, 32);
978
+ sseDeltaTimer.unref?.();
979
+ }
980
+ return;
981
+ }
982
+ flushSseDelta();
983
+ events.emit(workspace, 'agent.stream', {
984
+ sessionId: cleanId,
985
+ roleId: role.id,
986
+ roleName: role.name,
987
+ turnId,
988
+ ...ev,
989
+ activity: liveActivity,
990
+ });
991
+ };
992
+
820
993
  let substantiveToolsCount = 0;
821
994
  const markSubstantiveProgress = toolName => {
822
995
  if (SUBSTANTIVE_TOOLS.has(toolName)) {
@@ -826,10 +999,25 @@ export function createPiBridge({
826
999
  };
827
1000
 
828
1001
  const emitWrapped = ev => {
1002
+ if (ev?.type === 'thinking') liveActivity = '正在深度思考…';
1003
+ else if (ev?.type === 'text') liveActivity = '正在生成回复…';
1004
+ else if (ev?.type === 'tool') {
1005
+ if (ev.status === 'running') {
1006
+ liveActivity = `正在执行 ${ev.name || '工具'}${ev.argsSummary ? ' · ' + ev.argsSummary : ''}`;
1007
+ } else if (ev.status === 'failed' || ev.isError) {
1008
+ liveActivity = `${ev.name || '工具'} 执行失败,正在诊断并修复…`;
1009
+ } else {
1010
+ liveActivity = '工具执行完成,正在继续…';
1011
+ }
1012
+ } else if (ev?.type === 'steer') liveActivity = '已收到中途插话,正在调整方向…';
1013
+ else if (ev?.type === 'status' && ev.text) liveActivity = ev.text;
1014
+ else if (ev?.type === 'done' || ev?.type === 'error') liveActivity = '';
1015
+
829
1016
  if (ev?.type === 'tool' && ev.status === 'completed' && !ev.isError) {
830
1017
  markSubstantiveProgress(ev.name);
831
1018
  }
832
1019
  if (ev?.type === 'ask_user') {
1020
+ liveActivity = '等待你的确认…';
833
1021
  markSubstantiveProgress('ask_user');
834
1022
  recordedQuestions.push({
835
1023
  questionId: ev.questionId,
@@ -846,6 +1034,7 @@ export function createPiBridge({
846
1034
  automationRuleId,
847
1035
  });
848
1036
  }
1037
+ emitSseStream(ev);
849
1038
  emit(ev);
850
1039
  };
851
1040
 
@@ -915,6 +1104,7 @@ export function createPiBridge({
915
1104
  const toolLog = [];
916
1105
  const blocks = [];
917
1106
  let session = null;
1107
+ let activeWarmEntry = null;
918
1108
  let unsub = null;
919
1109
  let abortedByUser = false;
920
1110
  let piSessionFile = meta.piSessionFile || '';
@@ -978,6 +1168,20 @@ export function createPiBridge({
978
1168
 
979
1169
  const runState = {
980
1170
  sessionId: cleanId,
1171
+ turnId,
1172
+ getLiveAssistant() {
1173
+ return {
1174
+ id: 'live_' + turnId,
1175
+ turnId,
1176
+ role: 'assistant',
1177
+ text: assistantText,
1178
+ tools: toolLog.map(t => ({ ...t })),
1179
+ blocks: blocks.map(b => (b?.type === 'tools' ? { ...b, tools: b.tools.map(t => ({ ...t })) } : { ...b })),
1180
+ questions: recordedQuestions.map(q => ({ ...q })),
1181
+ activity: liveActivity || 'Pi 正在思考与执行…',
1182
+ streaming: true,
1183
+ };
1184
+ },
981
1185
  answer(questionId, answerText) {
982
1186
  const waiter = pendingQuestions.get(questionId);
983
1187
  if (!waiter) return false;
@@ -1012,6 +1216,8 @@ export function createPiBridge({
1012
1216
  },
1013
1217
  };
1014
1218
  liveRuns.set(`${workspace}::${cleanId}`, runState);
1219
+ emitSseStream({ type: 'turn_start', userMessage: userMsg, title: autoTitle || meta.title, phase: meta.phase, tone: meta.tone });
1220
+ events?.emit(workspace, 'agent.sessions', { action: 'started', sessionId: cleanId, roleId: role.id, title: autoTitle || meta.title });
1015
1221
 
1016
1222
  const persistAssistantTurn = ({ stopped = false, errorMsg = '' } = {}) => {
1017
1223
  const suffixParts = [];
@@ -1102,8 +1308,76 @@ export function createPiBridge({
1102
1308
  }
1103
1309
 
1104
1310
  const platformContext = readCladoPlatformContext(agentDir);
1311
+ const pluginParamsBundle = readPluginParams(workspace, stateDir, agentDir);
1312
+ const pluginParamEntries = Object.entries(pluginParamsBundle?.items || {});
1313
+ const PROTECTED_ENV_KEYS = new Set(['PATH', 'HOME', 'USER', 'SHELL', 'PWD', 'NODE_ENV', 'CLADO_PI_AGENT_DIR']);
1314
+ const injectedParamLines = [];
1315
+ for (const [pluginId, cfg] of pluginParamEntries) {
1316
+ const envObj = cfg?.env && typeof cfg.env === 'object' ? cfg.env : {};
1317
+ const paramsObj = cfg?.params && typeof cfg.params === 'object' ? cfg.params : {};
1318
+ const envKeys = [];
1319
+ for (const [k, v] of Object.entries(envObj)) {
1320
+ if (!k || PROTECTED_ENV_KEYS.has(k)) continue;
1321
+ envKeys.push(k);
1322
+ if (!sessionFactory) process.env[k] = String(v ?? '');
1323
+ }
1324
+ const hasParams = Object.keys(paramsObj).length > 0;
1325
+ if (hasParams || envKeys.length) {
1326
+ injectedParamLines.push(
1327
+ `- ${pluginId}:`
1328
+ + (hasParams ? ` params=${JSON.stringify(paramsObj)}` : '')
1329
+ + (envKeys.length ? ` envKeys=[${envKeys.join(', ')}]` : '')
1330
+ );
1331
+ }
1332
+ }
1333
+ const pluginParamsContext = injectedParamLines.length
1334
+ ? `\n\n## 插件与扩展注入参数\n以下参数由用户在 Clado 设置中心为当前工作区/插件配置(环境变量已注入进程环境):\n${injectedParamLines.join('\n')}`
1335
+ : '';
1105
1336
 
1106
- if (sessionFactory) {
1337
+ const trimmedCommand = String(text || '').trim();
1338
+ const isReloadCmd = !handoffFrom && (/^\/reload(?:\s|$)/i.test(trimmedCommand));
1339
+ const isCompactCmd = !handoffFrom && (/^\/compact(?:\s|$)/i.test(trimmedCommand));
1340
+
1341
+ if (isReloadCmd) {
1342
+ emitWrapped({ type: 'status', text: '正在执行 Pi 原生热重载(/reload)…' });
1343
+ const summary = await reloadSession({
1344
+ workspace,
1345
+ stateDir,
1346
+ sessionId: cleanId,
1347
+ roleId: role.id,
1348
+ modelSpec: modelSpec || meta.model,
1349
+ });
1350
+ const mcpTools = summary.mcpTools || [];
1351
+ const lines = [
1352
+ '### Pi 原生热重载完成 (`/reload`)',
1353
+ '',
1354
+ `- **已加载扩展** (${summary.extensions.length}):${summary.extensions.length ? summary.extensions.map(e => '`' + e + '`').join('、') : '无'}`,
1355
+ `- **已配置 MCP 服务** (${summary.mcpServers.length}):${summary.mcpServers.length ? summary.mcpServers.map(s => '`' + s.name + '` (' + s.type + '/' + (s.exposure || 'codemode') + (s.enabled ? '' : '·已禁用') + ')').join('、') : '无'}`,
1356
+ `- **活跃 MCP 工具** (${mcpTools.length}):${mcpTools.length ? mcpTools.slice(0, 24).map(t => '`' + t + '`').join('、') + (mcpTools.length > 24 ? ` 等共 ${mcpTools.length} 项` : '') : '暂无直接暴露工具(若 MCP 使用 codemode/deferred 模式,将按需通过 codemode 或 tool_search 调用)'}`,
1357
+ `- **全部活跃工具** (${summary.activeTools.length}) · **Skills** (${summary.skillsCount}) · **Prompt 命令** (${summary.promptsCount})`,
1358
+ `- **已同步热重载其它会话**:${summary.reloadedPeers || 0} 个`,
1359
+ ];
1360
+ if (summary.errors?.length) {
1361
+ lines.push('', '**诊断警告 / 错误:**');
1362
+ for (const e of summary.errors.slice(0, 8)) lines.push(`- ${e}`);
1363
+ }
1364
+ const reply = lines.join('\n');
1365
+ appendTextDelta(reply);
1366
+ emitWrapped({ type: 'text', text: reply });
1367
+ } else if (isCompactCmd) {
1368
+ const customInstructions = trimmedCommand.replace(/^\/compact\s*/i, '').trim();
1369
+ emitWrapped({ type: 'status', text: '正在压缩当前会话上下文…' });
1370
+ const res = await compactSession({ workspace, stateDir, sessionId: cleanId, customInstructions, allowDuringSelfRun: true });
1371
+ if (res.contextUsage) {
1372
+ latestContextUsage = res.contextUsage;
1373
+ emitWrapped({ type: 'usage', usage: res.contextUsage });
1374
+ }
1375
+ const reply = res.skipped
1376
+ ? `当前会话暂无可压缩历史:${res.reason || ''}`
1377
+ : `已完成上下文压缩(当前占用 ${res.contextUsage?.usedPercent ?? 0}%)。`;
1378
+ appendTextDelta(reply);
1379
+ emitWrapped({ type: 'text', text: reply });
1380
+ } else if (sessionFactory) {
1107
1381
  const factoryEmit = ev => {
1108
1382
  if (ev?.type === 'thinking' && ev.text) appendThinkingDelta(ev.text);
1109
1383
  if (ev?.type === 'text' && ev.text) appendTextDelta(ev.text);
@@ -1122,6 +1396,7 @@ export function createPiBridge({
1122
1396
  sessionId: cleanId,
1123
1397
  role,
1124
1398
  platformContext,
1399
+ pluginParams: pluginParamsBundle?.items || {},
1125
1400
  text,
1126
1401
  canvas,
1127
1402
  cladoTools,
@@ -1149,64 +1424,200 @@ export function createPiBridge({
1149
1424
  Math.max(4096, Math.floor(triggerBudgetTokens * 0.45))
1150
1425
  );
1151
1426
  const modelOverrideKey = `${chosenModel.provider}/${chosenModel.id}`;
1152
- sm.applyOverrides({
1153
- defaultThinkingLevel: runtimeSettings.thinkingLevel,
1154
- transport: runtimeSettings.transport,
1155
- hideThinkingBlock: runtimeSettings.hideThinkingBlock,
1156
- cacheWarming: runtimeSettings.cacheWarming,
1157
- compaction: {
1158
- enabled: runtimeSettings.compactionEnabled,
1159
- reserveTokens: effectiveReserveTokens,
1160
- keepRecentTokens: effectiveKeepRecentTokens,
1161
- modelOverrides: {
1162
- [modelOverrideKey]: {
1163
- reserveTokens: effectiveReserveTokens,
1164
- keepRecentTokens: effectiveKeepRecentTokens,
1427
+ const applyRuntimeOverrides = targetSm => {
1428
+ targetSm.applyOverrides({
1429
+ defaultThinkingLevel: runtimeSettings.thinkingLevel,
1430
+ transport: runtimeSettings.transport,
1431
+ hideThinkingBlock: runtimeSettings.hideThinkingBlock,
1432
+ cacheWarming: runtimeSettings.cacheWarming,
1433
+ compaction: {
1434
+ enabled: runtimeSettings.compactionEnabled,
1435
+ reserveTokens: effectiveReserveTokens,
1436
+ keepRecentTokens: effectiveKeepRecentTokens,
1437
+ modelOverrides: {
1438
+ [modelOverrideKey]: {
1439
+ reserveTokens: effectiveReserveTokens,
1440
+ keepRecentTokens: effectiveKeepRecentTokens,
1441
+ },
1165
1442
  },
1166
1443
  },
1444
+ retry: {
1445
+ enabled: runtimeSettings.retryEnabled,
1446
+ maxRetries: runtimeSettings.maxRetries,
1447
+ },
1448
+ });
1449
+ };
1450
+ applyRuntimeOverrides(sm);
1451
+
1452
+ const sessionKey = `${workspace}::${cleanId}`;
1453
+ const existingWarm = warmSessions.get(sessionKey);
1454
+ const canReuseWarm = Boolean(
1455
+ existingWarm
1456
+ && existingWarm.session
1457
+ && existingWarm.modelKey === modelOverrideKey
1458
+ && existingWarm.roleId === role.id
1459
+ && existingWarm.agentDir === agentDir
1460
+ && existingWarm.pluginParamsSig === pluginParamsContext
1461
+ );
1462
+
1463
+ const currentHooks = {
1464
+ emit: emitWrapped,
1465
+ waitForUserAnswer,
1466
+ canvas,
1467
+ onCardChanges: (toolName, res) => {
1468
+ markSubstantiveProgress(toolName);
1469
+ if (Array.isArray(res?.cardChanges)) {
1470
+ for (const ch of res.cardChanges) {
1471
+ emitSystem(workspace, `card.${ch.action}`, {
1472
+ file: ch.file,
1473
+ card: ch.card,
1474
+ addedTags: ch.addedTags,
1475
+ removedTags: ch.removedTags,
1476
+ originSessionId: cleanId,
1477
+ originRoleId: role.id,
1478
+ automationRuleId,
1479
+ });
1480
+ if ((ch.addedTags?.length || 0) > 0 || (ch.removedTags?.length || 0) > 0) {
1481
+ emitSystem(workspace, 'tag.changed', {
1482
+ file: ch.file,
1483
+ card: ch.card,
1484
+ addedTags: ch.addedTags,
1485
+ removedTags: ch.removedTags,
1486
+ originSessionId: cleanId,
1487
+ originRoleId: role.id,
1488
+ automationRuleId,
1489
+ });
1490
+ }
1491
+ }
1492
+ }
1167
1493
  },
1168
- retry: {
1169
- enabled: runtimeSettings.retryEnabled,
1170
- maxRetries: runtimeSettings.maxRetries,
1171
- },
1172
- });
1494
+ };
1173
1495
 
1174
- const loader = new DefaultResourceLoader({
1175
- cwd: workspace,
1176
- agentDir,
1177
- settingsManager: sm,
1178
- noThemes: true,
1179
- packageCommandOutput: 'capture',
1180
- appendSystemPrompt: [
1181
- role.systemPrompt,
1182
- platformContext,
1183
- ].filter(Boolean),
1184
- });
1185
- await loader.reload();
1186
-
1187
- const sessionManager = (piSessionFile && existsSync(piSessionFile))
1188
- ? SessionManager.open(piSessionFile)
1189
- : SessionManager.create(workspace, sessionsDir(stateDir));
1190
- const resolvedFile = sessionManager.getSessionFile?.() || '';
1191
- if (resolvedFile) {
1192
- piSessionFile = resolvedFile;
1193
- upsertSessionMeta(stateDir, { id: cleanId, piSessionFile }, agentDir);
1496
+ if (canReuseWarm) {
1497
+ activeWarmEntry = existingWarm;
1498
+ activeWarmEntry.turnHooksRef.current = currentHooks;
1499
+ applyRuntimeOverrides(activeWarmEntry.sm);
1500
+ if (activeWarmEntry.needsReload) {
1501
+ emitWrapped({ type: 'status', text: '检测到 MCP / 扩展配置已更新,正在热重载 Pi 会话…' });
1502
+ try {
1503
+ await activeWarmEntry.session.reload();
1504
+ activeWarmEntry.needsReload = false;
1505
+ } catch {
1506
+ await shutdownAndDisposeSession(activeWarmEntry.session);
1507
+ warmSessions.delete(sessionKey);
1508
+ activeWarmEntry = null;
1509
+ }
1510
+ }
1511
+ } else if (existingWarm) {
1512
+ await shutdownAndDisposeSession(existingWarm.session);
1513
+ warmSessions.delete(sessionKey);
1194
1514
  }
1195
1515
 
1196
- const created = await createAgentSession({
1197
- cwd: workspace,
1198
- agentDir,
1199
- modelRuntime: mr,
1200
- model: chosenModel,
1201
- settingsManager: sm,
1202
- resourceLoader: loader,
1203
- sessionManager,
1204
- customTools: cladoTools,
1205
- });
1206
- session = created.session;
1516
+ if (!activeWarmEntry) {
1517
+ const turnHooksRef = { current: currentHooks };
1518
+ const delegatedCladoTools = createCladoPiTools({
1519
+ workspace,
1520
+ stateDir,
1521
+ workspaceService,
1522
+ events,
1523
+ emit: ev => turnHooksRef.current?.emit?.(ev),
1524
+ waitForUserAnswer: (...a) => turnHooksRef.current?.waitForUserAnswer?.(...a),
1525
+ sessionOps: {
1526
+ currentSessionId: cleanId,
1527
+ currentRoleId: role.id,
1528
+ currentRoleName: role.name,
1529
+ list: ({ sinceMinutes = 0, includeArchived = false } = {}) =>
1530
+ listSessions(stateDir, { includeArchived, includeMessages: false, sinceMinutes, agentDir }),
1531
+ read: ({ sessionId: targetId, limit = 12 }) =>
1532
+ readSessionTranscript(stateDir, targetId, { limit, agentDir }),
1533
+ open: ({ roleId: targetRoleId, title = '', reuseLatest = true }) =>
1534
+ openOrCreatePeerSession(stateDir, { roleId: targetRoleId, title, reuseLatest, agentDir }),
1535
+ send: ({ targetSessionId, targetRoleId, message, wait = false }) =>
1536
+ sendCrossSessionMessage({
1537
+ workspace,
1538
+ stateDir,
1539
+ documentRoot,
1540
+ fromSessionId: cleanId,
1541
+ fromRoleId: role.id,
1542
+ fromRoleName: role.name,
1543
+ targetSessionId,
1544
+ targetRoleId,
1545
+ message,
1546
+ canvas: turnHooksRef.current?.canvas || canvas,
1547
+ wait,
1548
+ }),
1549
+ },
1550
+ automationOps,
1551
+ onCardChanges: (...a) => turnHooksRef.current?.onCardChanges?.(...a),
1552
+ });
1553
+
1554
+ const memoryBundle = readMemoryBundle(workspace, agentDir);
1555
+ const scopedRulesContext = memoryBundle.rules.length
1556
+ ? ['# Project Scoped Rules (.clado/rules/)', ...memoryBundle.rules.map(r => `## Rule: ${r.name}\n${r.content.trim()}`)].join('\n\n')
1557
+ : '';
1558
+ const loader = new DefaultResourceLoader({
1559
+ cwd: workspace,
1560
+ agentDir,
1561
+ settingsManager: sm,
1562
+ noThemes: true,
1563
+ packageCommandOutput: 'capture',
1564
+ extensionFactories: createBuiltInPiExtensions(agentDir, {
1565
+ workspace,
1566
+ getAskUser: () => turnHooksRef.current?.askUser || null,
1567
+ getRoleTools: () => ({ tools: role.tools || [], disabledTools: role.disabledTools || [] }),
1568
+ }),
1569
+ appendSystemPrompt: [
1570
+ role.systemPrompt,
1571
+ platformContext,
1572
+ scopedRulesContext,
1573
+ pluginParamsContext,
1574
+ ].filter(Boolean),
1575
+ });
1576
+ await loader.reload();
1577
+
1578
+ const sessionManager = (piSessionFile && existsSync(piSessionFile))
1579
+ ? SessionManager.open(piSessionFile)
1580
+ : SessionManager.create(workspace, sessionsDir(stateDir));
1581
+ const resolvedFile = sessionManager.getSessionFile?.() || '';
1582
+ if (resolvedFile) {
1583
+ piSessionFile = resolvedFile;
1584
+ upsertSessionMeta(stateDir, { id: cleanId, piSessionFile }, agentDir);
1585
+ }
1586
+
1587
+ const created = await createAgentSession({
1588
+ cwd: workspace,
1589
+ agentDir,
1590
+ modelRuntime: mr,
1591
+ model: chosenModel,
1592
+ settingsManager: sm,
1593
+ resourceLoader: loader,
1594
+ sessionManager,
1595
+ customTools: delegatedCladoTools,
1596
+ });
1597
+ activeWarmEntry = {
1598
+ session: created.session,
1599
+ loader,
1600
+ sm,
1601
+ mr,
1602
+ modelKey: modelOverrideKey,
1603
+ roleId: role.id,
1604
+ agentDir,
1605
+ stateDir,
1606
+ pluginParamsSig: pluginParamsContext,
1607
+ turnHooksRef,
1608
+ needsReload: false,
1609
+ notifications: [],
1610
+ extensionErrors: [],
1611
+ };
1612
+ await bindSessionForClado(created.session, activeWarmEntry);
1613
+ warmSessions.set(sessionKey, activeWarmEntry);
1614
+ }
1615
+
1616
+ session = activeWarmEntry.session;
1207
1617
  try {
1208
- if (runtimeSettings.thinkingLevel && typeof session.setThinkingLevel === 'function') {
1209
- session.setThinkingLevel(runtimeSettings.thinkingLevel);
1618
+ const effectiveThink = role.thinkingLevel || runtimeSettings.thinkingLevel;
1619
+ if (effectiveThink && typeof session.setThinkingLevel === 'function') {
1620
+ session.setThinkingLevel(effectiveThink);
1210
1621
  }
1211
1622
  } catch {}
1212
1623
 
@@ -1689,8 +2100,11 @@ export function createPiBridge({
1689
2100
  }
1690
2101
  });
1691
2102
 
1692
- const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom, agentDir });
1693
- await session.prompt(promptText);
2103
+ const rawSlash = !handoffFrom && trimmedCommand.startsWith('/');
2104
+ const promptText = rawSlash
2105
+ ? trimmedCommand
2106
+ : buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom, agentDir });
2107
+ await session.prompt(promptText, { expandPromptTemplates: true });
1694
2108
  let finalUsage = readContextUsageSnapshot();
1695
2109
  if (finalUsage) {
1696
2110
  latestContextUsage = finalUsage;
@@ -1758,6 +2172,7 @@ export function createPiBridge({
1758
2172
  });
1759
2173
  }
1760
2174
  } finally {
2175
+ flushSseDelta();
1761
2176
  if (draftActive) {
1762
2177
  draftActive = false;
1763
2178
  events?.emit(workspace, 'canvas.draft', { active: false });
@@ -1767,14 +2182,214 @@ export function createPiBridge({
1767
2182
  }
1768
2183
  liveRuns.delete(`${workspace}::${cleanId}`);
1769
2184
  try { unsub?.(); } catch {}
1770
- try { session?.dispose?.(); } catch {}
2185
+ if (activeWarmEntry) {
2186
+ activeWarmEntry.turnHooksRef.current = null;
2187
+ if (activeWarmEntry.needsReload) {
2188
+ activeWarmEntry.session.reload()
2189
+ .then(() => { activeWarmEntry.needsReload = false; })
2190
+ .catch(() => {});
2191
+ }
2192
+ } else if (session) {
2193
+ await shutdownAndDisposeSession(session);
2194
+ }
2195
+ }
2196
+ }
2197
+
2198
+ const lastRuntimeSnapshotByWorkspace = new Map();
2199
+
2200
+ const waitBrieflyForMcpTools = async (session, enabledMcpServers, maxWaitMs = 2400) => {
2201
+ const hasDirect = (enabledMcpServers || []).some(s => s.enabled && s.exposure === 'direct');
2202
+ if (!hasDirect) {
2203
+ if ((enabledMcpServers || []).some(s => s.enabled)) {
2204
+ await new Promise(r => setTimeout(r, 250));
2205
+ }
2206
+ return;
2207
+ }
2208
+ const deadline = Date.now() + maxWaitMs;
2209
+ while (Date.now() < deadline) {
2210
+ const tools = session.getActiveToolNames?.() || [];
2211
+ if (tools.some(t => t.startsWith('mcp__'))) {
2212
+ // Give sibling servers a tiny beat to finish too
2213
+ await new Promise(r => setTimeout(r, 150));
2214
+ return;
2215
+ }
2216
+ await new Promise(r => setTimeout(r, 120));
2217
+ }
2218
+ };
2219
+
2220
+ const collectRuntimeSnapshot = (workspace, agentDir, session, loader, entryErrors = [], entryNotes = []) => {
2221
+ const mcpServers = listPiMcpServers(workspace, agentDir);
2222
+ const activeTools = session?.getActiveToolNames?.() || [];
2223
+ const allTools = (session?.getAllTools?.() || []).map(t => t.name);
2224
+ const mcpTools = [...new Set([...activeTools, ...allTools])].filter(t => t.startsWith('mcp__'));
2225
+ const extRes = loader?.getExtensions?.() || { extensions: [], errors: [], warnings: [] };
2226
+ const extensions = (extRes.extensions || []).map(e => e.path || e.resolvedPath || 'extension');
2227
+ const errors = [
2228
+ ...(extRes.errors || []).map(e => `${e.path || 'extension'}: ${e.error}`),
2229
+ ...(extRes.warnings || []).map(w => `${w.path || 'extension'}: ${w.warning}`),
2230
+ ...(entryErrors || []).map(e => e.message),
2231
+ ...(entryNotes || []).filter(n => n.level === 'error' || n.level === 'warning').map(n => n.message),
2232
+ ];
2233
+ const skillsCount = (loader?.getSkills?.()?.skills || []).length;
2234
+ const promptsCount = (loader?.getPrompts?.()?.prompts || []).length;
2235
+ const snap = {
2236
+ reloadedAt: new Date().toISOString(),
2237
+ extensions,
2238
+ mcpServers,
2239
+ mcpTools,
2240
+ activeTools,
2241
+ allTools,
2242
+ skillsCount,
2243
+ promptsCount,
2244
+ errors: [...new Set(errors)],
2245
+ };
2246
+ lastRuntimeSnapshotByWorkspace.set(workspace, snap);
2247
+ return snap;
2248
+ };
2249
+
2250
+ async function reloadWorkspaceSessions(workspace) {
2251
+ const prefix = workspace ? `${workspace}::` : '';
2252
+ let reloadedCount = 0;
2253
+ let deferredCount = 0;
2254
+ let firstReloadedEntry = null;
2255
+ for (const [key, entry] of warmSessions.entries()) {
2256
+ if (prefix && !key.startsWith(prefix)) continue;
2257
+ if (liveRuns.has(key)) {
2258
+ entry.needsReload = true;
2259
+ deferredCount++;
2260
+ continue;
2261
+ }
2262
+ try {
2263
+ entry.notifications.length = 0;
2264
+ entry.extensionErrors.length = 0;
2265
+ await entry.session.reload();
2266
+ entry.needsReload = false;
2267
+ reloadedCount++;
2268
+ if (!firstReloadedEntry) firstReloadedEntry = entry;
2269
+ } catch {
2270
+ await shutdownAndDisposeSession(entry.session);
2271
+ warmSessions.delete(key);
2272
+ }
2273
+ }
2274
+ if (firstReloadedEntry) {
2275
+ const agentDir = firstReloadedEntry.agentDir || resolvePiAgentDir();
2276
+ await waitBrieflyForMcpTools(firstReloadedEntry.session, listPiMcpServers(workspace, agentDir));
2277
+ collectRuntimeSnapshot(
2278
+ workspace,
2279
+ agentDir,
2280
+ firstReloadedEntry.session,
2281
+ firstReloadedEntry.loader,
2282
+ firstReloadedEntry.extensionErrors,
2283
+ firstReloadedEntry.notifications
2284
+ );
2285
+ }
2286
+ return { reloadedCount, deferredCount };
2287
+ }
2288
+
2289
+ async function reloadSession({ workspace, stateDir, sessionId = '', roleId = 'architect', modelSpec = '' } = {}) {
2290
+ const agentDir = resolvePiAgentDir();
2291
+ const cleanId = sessionId ? safeSessionId(sessionId) : '';
2292
+ const targetKey = cleanId ? `${workspace}::${cleanId}` : '';
2293
+ const mcpServers = listPiMcpServers(workspace, agentDir);
2294
+ let reloadedPeers = 0;
2295
+
2296
+ // 1. Reload other warm sessions in this workspace
2297
+ for (const [key, entry] of warmSessions.entries()) {
2298
+ if (!key.startsWith(`${workspace}::`) || key === targetKey) continue;
2299
+ if (liveRuns.has(key)) {
2300
+ entry.needsReload = true;
2301
+ } else {
2302
+ try {
2303
+ entry.notifications.length = 0;
2304
+ entry.extensionErrors.length = 0;
2305
+ await entry.session.reload();
2306
+ entry.needsReload = false;
2307
+ reloadedPeers++;
2308
+ } catch {
2309
+ await shutdownAndDisposeSession(entry.session);
2310
+ warmSessions.delete(key);
2311
+ }
2312
+ }
2313
+ }
2314
+
2315
+ // 2. If target warm session exists, use Pi's native session.reload()
2316
+ const existing = targetKey ? warmSessions.get(targetKey) : [...warmSessions.entries()].find(([k]) => k.startsWith(`${workspace}::`))?.[1];
2317
+ if (existing && existing.session) {
2318
+ existing.notifications.length = 0;
2319
+ existing.extensionErrors.length = 0;
2320
+ await existing.session.reload();
2321
+ existing.needsReload = false;
2322
+ await waitBrieflyForMcpTools(existing.session, mcpServers);
2323
+ const snap = collectRuntimeSnapshot(workspace, agentDir, existing.session, existing.loader, existing.extensionErrors, existing.notifications);
2324
+ return { ok: true, mode: 'native_session_reload', reloadedPeers, ...snap };
2325
+ }
2326
+
2327
+ // 3. Otherwise create a clean bound session probe (or warm session when sessionId is provided) to load & verify MCP/extensions natively
2328
+ const sm = SettingsManager.create(workspace, agentDir);
2329
+ const loader = new DefaultResourceLoader({
2330
+ cwd: workspace,
2331
+ agentDir,
2332
+ settingsManager: sm,
2333
+ noThemes: true,
2334
+ packageCommandOutput: 'capture',
2335
+ extensionFactories: createBuiltInPiExtensions(agentDir, { workspace }),
2336
+ });
2337
+ await loader.reload();
2338
+
2339
+ let probeSession = null;
2340
+ const probeEntry = { notifications: [], extensionErrors: [], turnHooksRef: { current: null } };
2341
+ try {
2342
+ const mr = await createCladoModelRuntime(agentDir);
2343
+ const chosenModel = await resolvePiModel(mr, sm, modelSpec).catch(() => null);
2344
+ const created = await createAgentSession({
2345
+ cwd: workspace,
2346
+ agentDir,
2347
+ modelRuntime: mr,
2348
+ ...(chosenModel ? { model: chosenModel } : {}),
2349
+ settingsManager: sm,
2350
+ resourceLoader: loader,
2351
+ sessionManager: SessionManager.inMemory(),
2352
+ });
2353
+ probeSession = created.session;
2354
+ await bindSessionForClado(probeSession, probeEntry);
2355
+ await waitBrieflyForMcpTools(probeSession, mcpServers);
2356
+ const snap = collectRuntimeSnapshot(workspace, agentDir, probeSession, loader, probeEntry.extensionErrors, probeEntry.notifications);
2357
+ return { ok: true, mode: 'native_fresh_reload', reloadedPeers, ...snap };
2358
+ } finally {
2359
+ if (probeSession) await shutdownAndDisposeSession(probeSession);
1771
2360
  }
1772
2361
  }
1773
2362
 
1774
- async function compactSession({ workspace, stateDir, sessionId, customInstructions = '' }) {
2363
+ async function disposeWarmSession(workspace, sessionId) {
2364
+ const key = `${workspace}::${safeSessionId(sessionId)}`;
2365
+ const entry = warmSessions.get(key);
2366
+ if (!entry) return false;
2367
+ warmSessions.delete(key);
2368
+ await shutdownAndDisposeSession(entry.session);
2369
+ return true;
2370
+ }
2371
+
2372
+ function inspectRuntime(workspace) {
2373
+ const prefix = workspace ? `${workspace}::` : '';
2374
+ const warmEntries = [...warmSessions.entries()]
2375
+ .filter(([k]) => !prefix || k.startsWith(prefix))
2376
+ .map(([, v]) => v);
2377
+ if (warmEntries.length) {
2378
+ const first = warmEntries[0];
2379
+ const agentDir = first.agentDir || resolvePiAgentDir();
2380
+ const snap = collectRuntimeSnapshot(workspace, agentDir, first.session, first.loader, first.extensionErrors, first.notifications);
2381
+ return { warmSessions: warmEntries.length, ...snap };
2382
+ }
2383
+ const cached = lastRuntimeSnapshotByWorkspace.get(workspace);
2384
+ return cached
2385
+ ? { warmSessions: 0, ...cached }
2386
+ : { warmSessions: 0, mcpTools: [], activeTools: [], extensions: [], errors: [] };
2387
+ }
2388
+
2389
+ async function compactSession({ workspace, stateDir, sessionId, customInstructions = '', allowDuringSelfRun = false }) {
1775
2390
  const cleanId = safeSessionId(sessionId);
1776
2391
  const runKey = `${workspace}::${cleanId}`;
1777
- if (liveRuns.has(runKey)) {
2392
+ if (!allowDuringSelfRun && liveRuns.has(runKey)) {
1778
2393
  throw new Error('该会话正在执行中,请等待当前回合完成或先点击停止后再压缩上下文。');
1779
2394
  }
1780
2395
  const agentDir = resolvePiAgentDir();
@@ -1844,16 +2459,40 @@ export function createPiBridge({
1844
2459
  });
1845
2460
  return { ok: true, contextUsage, session: updated };
1846
2461
  } finally {
1847
- try { session?.dispose?.(); } catch {}
2462
+ await shutdownAndDisposeSession(session);
1848
2463
  }
1849
2464
  }
1850
2465
 
2466
+ function overlayLiveSession(workspace, item) {
2467
+ if (!item || !item.id) return item;
2468
+ const run = liveRuns.get(`${workspace}::${item.id}`);
2469
+ if (!run || typeof run.getLiveAssistant !== 'function') return item;
2470
+ const liveMsg = run.getLiveAssistant();
2471
+ const msgs = Array.isArray(item.messages) ? item.messages.slice() : null;
2472
+ if (msgs && !msgs.some(m => m && (m.id === liveMsg.id || m.turnId === liveMsg.turnId))) {
2473
+ msgs.push(liveMsg);
2474
+ }
2475
+ return {
2476
+ ...item,
2477
+ status: 'running',
2478
+ ...(msgs ? { messages: msgs } : {}),
2479
+ };
2480
+ }
2481
+
1851
2482
  return {
1852
2483
  runTurn,
1853
2484
  compactSession,
2485
+ reloadSession,
2486
+ reloadWorkspaceSessions,
2487
+ disposeWarmSession,
2488
+ inspectRuntime,
1854
2489
  sendCrossSessionMessage,
1855
2490
  readSessionTranscript,
1856
2491
  openOrCreatePeerSession,
2492
+ overlayLiveSession,
2493
+ overlayLiveSessions(workspace, list) {
2494
+ return Array.isArray(list) ? list.map(s => overlayLiveSession(workspace, s)) : [];
2495
+ },
1857
2496
  listActiveRuns(workspace) {
1858
2497
  const prefix = workspace ? `${workspace}::` : '';
1859
2498
  return [...liveRuns.entries()]
@@ -1885,9 +2524,12 @@ export function createPiBridge({
1885
2524
  return targets.length;
1886
2525
  },
1887
2526
  async closeAll() {
1888
- const all = [...liveRuns.values()];
2527
+ const allRuns = [...liveRuns.values()];
1889
2528
  liveRuns.clear();
1890
- await Promise.allSettled(all.map(r => r.abort()));
2529
+ await Promise.allSettled(allRuns.map(r => r.abort()));
2530
+ const allWarm = [...warmSessions.values()];
2531
+ warmSessions.clear();
2532
+ await Promise.allSettled(allWarm.map(e => shutdownAndDisposeSession(e.session)));
1891
2533
  },
1892
2534
  };
1893
2535
  }