cladogram 0.6.0-beta.6 → 0.6.0-beta.8

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,13 +10,18 @@ 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
+ readPluginParams,
20
25
  readRuntimeSettings,
21
26
  resolvePiAgentDir,
22
27
  resolveRole,
@@ -560,11 +565,59 @@ export function createPiBridge({
560
565
  automationOps = null,
561
566
  } = {}) {
562
567
  const liveRuns = new Map();
568
+ const warmSessions = new Map(); // `${workspace}::${cleanId}` -> { session, loader, sm, mr, modelKey, roleId, agentDir, stateDir, turnHooksRef, needsReload, notifications, extensionErrors }
563
569
  const pairNoProgressStreak = new Map(); // sorted pair key -> consecutive no-progress cross-session sends
564
570
  const SUBSTANTIVE_TOOLS = new Set([
565
571
  'clado_create', 'clado_update', 'clado_nodes', 'clado_links', 'clado_documents', 'clado_batch',
566
572
  'edit', 'write', 'bash', 'ask_user', 'canvas_objects_upsert', 'canvas_objects_delete',
567
573
  ]);
574
+ const createBuiltInPiExtensions = agentDir => [
575
+ { name: 'codemode', factory: createCodemodeExtension(), replaceable: true, builtin: true },
576
+ { name: 'tool-search', factory: createToolSearchExtension(), replaceable: true, builtin: true },
577
+ { name: 'mcp', factory: createMcpExtension({ logPath: join(agentDir, 'mcp.log') }), replaceable: true, builtin: true },
578
+ ];
579
+ const shutdownAndDisposeSession = async session => {
580
+ if (!session) return;
581
+ try {
582
+ if (session.extensionRunner?.hasHandlers?.('session_shutdown')) {
583
+ await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'exit' });
584
+ }
585
+ } catch {}
586
+ try { session.dispose?.(); } catch {}
587
+ };
588
+ const bindSessionForClado = async (session, entry) => {
589
+ await session.bindExtensions({
590
+ mode: 'print',
591
+ uiContext: {
592
+ notify(msg, level = 'info') {
593
+ if (!msg) return;
594
+ const note = { level: String(level || 'info'), message: String(msg), ts: Date.now() };
595
+ entry.notifications.push(note);
596
+ if (entry.notifications.length > 30) entry.notifications.splice(0, entry.notifications.length - 30);
597
+ try {
598
+ if (level === 'error' || level === 'warning') {
599
+ entry.turnHooksRef?.emit?.({ type: 'status', text: `[Pi ${level}] ${msg}` });
600
+ }
601
+ } catch {}
602
+ },
603
+ },
604
+ commandContextActions: {
605
+ waitForIdle: () => session.waitForIdle(),
606
+ reload: async () => {
607
+ await session.reload();
608
+ },
609
+ newSession: async () => ({ cancelled: true }),
610
+ fork: async () => ({ cancelled: true }),
611
+ navigateTree: async () => ({ cancelled: true }),
612
+ switchSession: async () => ({ cancelled: true }),
613
+ },
614
+ onError(err) {
615
+ const text = err?.error ? `${err.extensionPath || 'extension'}: ${err.error}` : String(err || 'Extension error');
616
+ entry.extensionErrors.push({ message: text, ts: Date.now() });
617
+ if (entry.extensionErrors.length > 20) entry.extensionErrors.splice(0, entry.extensionErrors.length - 20);
618
+ },
619
+ });
620
+ };
568
621
  const pairKeyOf = (a, b) => [String(a || ''), String(b || '')].sort().join('::');
569
622
  const resetProgressForSession = sid => {
570
623
  const clean = String(sid || '');
@@ -817,6 +870,57 @@ export function createPiBridge({
817
870
  });
818
871
  });
819
872
 
873
+ const turnId = 'turn_' + randomUUID().replace(/-/g, '').slice(0, 10);
874
+ let liveActivity = '正在思考并准备上下文…';
875
+ let sseDeltaType = '';
876
+ let sseDeltaBuf = '';
877
+ let sseDeltaTimer = null;
878
+
879
+ const flushSseDelta = () => {
880
+ if (sseDeltaTimer) {
881
+ clearTimeout(sseDeltaTimer);
882
+ sseDeltaTimer = null;
883
+ }
884
+ if (sseDeltaType && sseDeltaBuf) {
885
+ events?.emit(workspace, 'agent.stream', {
886
+ sessionId: cleanId,
887
+ roleId: role.id,
888
+ roleName: role.name,
889
+ turnId,
890
+ type: sseDeltaType,
891
+ text: sseDeltaBuf,
892
+ activity: liveActivity,
893
+ });
894
+ }
895
+ sseDeltaType = '';
896
+ sseDeltaBuf = '';
897
+ };
898
+
899
+ const emitSseStream = ev => {
900
+ if (!events || !ev || !ev.type) return;
901
+ if (ev.type === 'text' || ev.type === 'thinking') {
902
+ const chunk = String(ev.text || '');
903
+ if (!chunk) return;
904
+ if (sseDeltaType && sseDeltaType !== ev.type) flushSseDelta();
905
+ sseDeltaType = ev.type;
906
+ sseDeltaBuf += chunk;
907
+ if (!sseDeltaTimer) {
908
+ sseDeltaTimer = setTimeout(flushSseDelta, 32);
909
+ sseDeltaTimer.unref?.();
910
+ }
911
+ return;
912
+ }
913
+ flushSseDelta();
914
+ events.emit(workspace, 'agent.stream', {
915
+ sessionId: cleanId,
916
+ roleId: role.id,
917
+ roleName: role.name,
918
+ turnId,
919
+ ...ev,
920
+ activity: liveActivity,
921
+ });
922
+ };
923
+
820
924
  let substantiveToolsCount = 0;
821
925
  const markSubstantiveProgress = toolName => {
822
926
  if (SUBSTANTIVE_TOOLS.has(toolName)) {
@@ -826,10 +930,25 @@ export function createPiBridge({
826
930
  };
827
931
 
828
932
  const emitWrapped = ev => {
933
+ if (ev?.type === 'thinking') liveActivity = '正在深度思考…';
934
+ else if (ev?.type === 'text') liveActivity = '正在生成回复…';
935
+ else if (ev?.type === 'tool') {
936
+ if (ev.status === 'running') {
937
+ liveActivity = `正在执行 ${ev.name || '工具'}${ev.argsSummary ? ' · ' + ev.argsSummary : ''}`;
938
+ } else if (ev.status === 'failed' || ev.isError) {
939
+ liveActivity = `${ev.name || '工具'} 执行失败,正在诊断并修复…`;
940
+ } else {
941
+ liveActivity = '工具执行完成,正在继续…';
942
+ }
943
+ } else if (ev?.type === 'steer') liveActivity = '已收到中途插话,正在调整方向…';
944
+ else if (ev?.type === 'status' && ev.text) liveActivity = ev.text;
945
+ else if (ev?.type === 'done' || ev?.type === 'error') liveActivity = '';
946
+
829
947
  if (ev?.type === 'tool' && ev.status === 'completed' && !ev.isError) {
830
948
  markSubstantiveProgress(ev.name);
831
949
  }
832
950
  if (ev?.type === 'ask_user') {
951
+ liveActivity = '等待你的确认…';
833
952
  markSubstantiveProgress('ask_user');
834
953
  recordedQuestions.push({
835
954
  questionId: ev.questionId,
@@ -846,6 +965,7 @@ export function createPiBridge({
846
965
  automationRuleId,
847
966
  });
848
967
  }
968
+ emitSseStream(ev);
849
969
  emit(ev);
850
970
  };
851
971
 
@@ -915,6 +1035,7 @@ export function createPiBridge({
915
1035
  const toolLog = [];
916
1036
  const blocks = [];
917
1037
  let session = null;
1038
+ let activeWarmEntry = null;
918
1039
  let unsub = null;
919
1040
  let abortedByUser = false;
920
1041
  let piSessionFile = meta.piSessionFile || '';
@@ -978,6 +1099,20 @@ export function createPiBridge({
978
1099
 
979
1100
  const runState = {
980
1101
  sessionId: cleanId,
1102
+ turnId,
1103
+ getLiveAssistant() {
1104
+ return {
1105
+ id: 'live_' + turnId,
1106
+ turnId,
1107
+ role: 'assistant',
1108
+ text: assistantText,
1109
+ tools: toolLog.map(t => ({ ...t })),
1110
+ blocks: blocks.map(b => (b?.type === 'tools' ? { ...b, tools: b.tools.map(t => ({ ...t })) } : { ...b })),
1111
+ questions: recordedQuestions.map(q => ({ ...q })),
1112
+ activity: liveActivity || 'Pi 正在思考与执行…',
1113
+ streaming: true,
1114
+ };
1115
+ },
981
1116
  answer(questionId, answerText) {
982
1117
  const waiter = pendingQuestions.get(questionId);
983
1118
  if (!waiter) return false;
@@ -1012,6 +1147,8 @@ export function createPiBridge({
1012
1147
  },
1013
1148
  };
1014
1149
  liveRuns.set(`${workspace}::${cleanId}`, runState);
1150
+ emitSseStream({ type: 'turn_start', userMessage: userMsg, title: autoTitle || meta.title, phase: meta.phase, tone: meta.tone });
1151
+ events?.emit(workspace, 'agent.sessions', { action: 'started', sessionId: cleanId, roleId: role.id, title: autoTitle || meta.title });
1015
1152
 
1016
1153
  const persistAssistantTurn = ({ stopped = false, errorMsg = '' } = {}) => {
1017
1154
  const suffixParts = [];
@@ -1102,8 +1239,76 @@ export function createPiBridge({
1102
1239
  }
1103
1240
 
1104
1241
  const platformContext = readCladoPlatformContext(agentDir);
1242
+ const pluginParamsBundle = readPluginParams(workspace, stateDir, agentDir);
1243
+ const pluginParamEntries = Object.entries(pluginParamsBundle?.items || {});
1244
+ const PROTECTED_ENV_KEYS = new Set(['PATH', 'HOME', 'USER', 'SHELL', 'PWD', 'NODE_ENV', 'CLADO_PI_AGENT_DIR']);
1245
+ const injectedParamLines = [];
1246
+ for (const [pluginId, cfg] of pluginParamEntries) {
1247
+ const envObj = cfg?.env && typeof cfg.env === 'object' ? cfg.env : {};
1248
+ const paramsObj = cfg?.params && typeof cfg.params === 'object' ? cfg.params : {};
1249
+ const envKeys = [];
1250
+ for (const [k, v] of Object.entries(envObj)) {
1251
+ if (!k || PROTECTED_ENV_KEYS.has(k)) continue;
1252
+ envKeys.push(k);
1253
+ if (!sessionFactory) process.env[k] = String(v ?? '');
1254
+ }
1255
+ const hasParams = Object.keys(paramsObj).length > 0;
1256
+ if (hasParams || envKeys.length) {
1257
+ injectedParamLines.push(
1258
+ `- ${pluginId}:`
1259
+ + (hasParams ? ` params=${JSON.stringify(paramsObj)}` : '')
1260
+ + (envKeys.length ? ` envKeys=[${envKeys.join(', ')}]` : '')
1261
+ );
1262
+ }
1263
+ }
1264
+ const pluginParamsContext = injectedParamLines.length
1265
+ ? `\n\n## 插件与扩展注入参数\n以下参数由用户在 Clado 设置中心为当前工作区/插件配置(环境变量已注入进程环境):\n${injectedParamLines.join('\n')}`
1266
+ : '';
1105
1267
 
1106
- if (sessionFactory) {
1268
+ const trimmedCommand = String(text || '').trim();
1269
+ const isReloadCmd = !handoffFrom && (/^\/reload(?:\s|$)/i.test(trimmedCommand));
1270
+ const isCompactCmd = !handoffFrom && (/^\/compact(?:\s|$)/i.test(trimmedCommand));
1271
+
1272
+ if (isReloadCmd) {
1273
+ emitWrapped({ type: 'status', text: '正在执行 Pi 原生热重载(/reload)…' });
1274
+ const summary = await reloadSession({
1275
+ workspace,
1276
+ stateDir,
1277
+ sessionId: cleanId,
1278
+ roleId: role.id,
1279
+ modelSpec: modelSpec || meta.model,
1280
+ });
1281
+ const mcpTools = summary.mcpTools || [];
1282
+ const lines = [
1283
+ '### Pi 原生热重载完成 (`/reload`)',
1284
+ '',
1285
+ `- **已加载扩展** (${summary.extensions.length}):${summary.extensions.length ? summary.extensions.map(e => '`' + e + '`').join('、') : '无'}`,
1286
+ `- **已配置 MCP 服务** (${summary.mcpServers.length}):${summary.mcpServers.length ? summary.mcpServers.map(s => '`' + s.name + '` (' + s.type + '/' + (s.exposure || 'codemode') + (s.enabled ? '' : '·已禁用') + ')').join('、') : '无'}`,
1287
+ `- **活跃 MCP 工具** (${mcpTools.length}):${mcpTools.length ? mcpTools.slice(0, 24).map(t => '`' + t + '`').join('、') + (mcpTools.length > 24 ? ` 等共 ${mcpTools.length} 项` : '') : '暂无直接暴露工具(若 MCP 使用 codemode/deferred 模式,将按需通过 codemode 或 tool_search 调用)'}`,
1288
+ `- **全部活跃工具** (${summary.activeTools.length}) · **Skills** (${summary.skillsCount}) · **Prompt 命令** (${summary.promptsCount})`,
1289
+ `- **已同步热重载其它会话**:${summary.reloadedPeers || 0} 个`,
1290
+ ];
1291
+ if (summary.errors?.length) {
1292
+ lines.push('', '**诊断警告 / 错误:**');
1293
+ for (const e of summary.errors.slice(0, 8)) lines.push(`- ${e}`);
1294
+ }
1295
+ const reply = lines.join('\n');
1296
+ appendTextDelta(reply);
1297
+ emitWrapped({ type: 'text', text: reply });
1298
+ } else if (isCompactCmd) {
1299
+ const customInstructions = trimmedCommand.replace(/^\/compact\s*/i, '').trim();
1300
+ emitWrapped({ type: 'status', text: '正在压缩当前会话上下文…' });
1301
+ const res = await compactSession({ workspace, stateDir, sessionId: cleanId, customInstructions, allowDuringSelfRun: true });
1302
+ if (res.contextUsage) {
1303
+ latestContextUsage = res.contextUsage;
1304
+ emitWrapped({ type: 'usage', usage: res.contextUsage });
1305
+ }
1306
+ const reply = res.skipped
1307
+ ? `当前会话暂无可压缩历史:${res.reason || ''}`
1308
+ : `已完成上下文压缩(当前占用 ${res.contextUsage?.usedPercent ?? 0}%)。`;
1309
+ appendTextDelta(reply);
1310
+ emitWrapped({ type: 'text', text: reply });
1311
+ } else if (sessionFactory) {
1107
1312
  const factoryEmit = ev => {
1108
1313
  if (ev?.type === 'thinking' && ev.text) appendThinkingDelta(ev.text);
1109
1314
  if (ev?.type === 'text' && ev.text) appendTextDelta(ev.text);
@@ -1122,6 +1327,7 @@ export function createPiBridge({
1122
1327
  sessionId: cleanId,
1123
1328
  role,
1124
1329
  platformContext,
1330
+ pluginParams: pluginParamsBundle?.items || {},
1125
1331
  text,
1126
1332
  canvas,
1127
1333
  cladoTools,
@@ -1149,61 +1355,187 @@ export function createPiBridge({
1149
1355
  Math.max(4096, Math.floor(triggerBudgetTokens * 0.45))
1150
1356
  );
1151
1357
  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,
1358
+ const applyRuntimeOverrides = targetSm => {
1359
+ targetSm.applyOverrides({
1360
+ defaultThinkingLevel: runtimeSettings.thinkingLevel,
1361
+ transport: runtimeSettings.transport,
1362
+ hideThinkingBlock: runtimeSettings.hideThinkingBlock,
1363
+ cacheWarming: runtimeSettings.cacheWarming,
1364
+ compaction: {
1365
+ enabled: runtimeSettings.compactionEnabled,
1366
+ reserveTokens: effectiveReserveTokens,
1367
+ keepRecentTokens: effectiveKeepRecentTokens,
1368
+ modelOverrides: {
1369
+ [modelOverrideKey]: {
1370
+ reserveTokens: effectiveReserveTokens,
1371
+ keepRecentTokens: effectiveKeepRecentTokens,
1372
+ },
1165
1373
  },
1166
1374
  },
1375
+ retry: {
1376
+ enabled: runtimeSettings.retryEnabled,
1377
+ maxRetries: runtimeSettings.maxRetries,
1378
+ },
1379
+ });
1380
+ };
1381
+ applyRuntimeOverrides(sm);
1382
+
1383
+ const sessionKey = `${workspace}::${cleanId}`;
1384
+ const existingWarm = warmSessions.get(sessionKey);
1385
+ const canReuseWarm = Boolean(
1386
+ existingWarm
1387
+ && existingWarm.session
1388
+ && existingWarm.modelKey === modelOverrideKey
1389
+ && existingWarm.roleId === role.id
1390
+ && existingWarm.agentDir === agentDir
1391
+ && existingWarm.pluginParamsSig === pluginParamsContext
1392
+ );
1393
+
1394
+ const currentHooks = {
1395
+ emit: emitWrapped,
1396
+ waitForUserAnswer,
1397
+ canvas,
1398
+ onCardChanges: (toolName, res) => {
1399
+ markSubstantiveProgress(toolName);
1400
+ if (Array.isArray(res?.cardChanges)) {
1401
+ for (const ch of res.cardChanges) {
1402
+ emitSystem(workspace, `card.${ch.action}`, {
1403
+ file: ch.file,
1404
+ card: ch.card,
1405
+ addedTags: ch.addedTags,
1406
+ removedTags: ch.removedTags,
1407
+ originSessionId: cleanId,
1408
+ originRoleId: role.id,
1409
+ automationRuleId,
1410
+ });
1411
+ if ((ch.addedTags?.length || 0) > 0 || (ch.removedTags?.length || 0) > 0) {
1412
+ emitSystem(workspace, 'tag.changed', {
1413
+ file: ch.file,
1414
+ card: ch.card,
1415
+ addedTags: ch.addedTags,
1416
+ removedTags: ch.removedTags,
1417
+ originSessionId: cleanId,
1418
+ originRoleId: role.id,
1419
+ automationRuleId,
1420
+ });
1421
+ }
1422
+ }
1423
+ }
1167
1424
  },
1168
- retry: {
1169
- enabled: runtimeSettings.retryEnabled,
1170
- maxRetries: runtimeSettings.maxRetries,
1171
- },
1172
- });
1425
+ };
1173
1426
 
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);
1427
+ if (canReuseWarm) {
1428
+ activeWarmEntry = existingWarm;
1429
+ activeWarmEntry.turnHooksRef.current = currentHooks;
1430
+ applyRuntimeOverrides(activeWarmEntry.sm);
1431
+ if (activeWarmEntry.needsReload) {
1432
+ emitWrapped({ type: 'status', text: '检测到 MCP / 扩展配置已更新,正在热重载 Pi 会话…' });
1433
+ try {
1434
+ await activeWarmEntry.session.reload();
1435
+ activeWarmEntry.needsReload = false;
1436
+ } catch {
1437
+ await shutdownAndDisposeSession(activeWarmEntry.session);
1438
+ warmSessions.delete(sessionKey);
1439
+ activeWarmEntry = null;
1440
+ }
1441
+ }
1442
+ } else if (existingWarm) {
1443
+ await shutdownAndDisposeSession(existingWarm.session);
1444
+ warmSessions.delete(sessionKey);
1194
1445
  }
1195
1446
 
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;
1447
+ if (!activeWarmEntry) {
1448
+ const turnHooksRef = { current: currentHooks };
1449
+ const delegatedCladoTools = createCladoPiTools({
1450
+ workspace,
1451
+ stateDir,
1452
+ workspaceService,
1453
+ events,
1454
+ emit: ev => turnHooksRef.current?.emit?.(ev),
1455
+ waitForUserAnswer: (...a) => turnHooksRef.current?.waitForUserAnswer?.(...a),
1456
+ sessionOps: {
1457
+ currentSessionId: cleanId,
1458
+ currentRoleId: role.id,
1459
+ currentRoleName: role.name,
1460
+ list: ({ sinceMinutes = 0, includeArchived = false } = {}) =>
1461
+ listSessions(stateDir, { includeArchived, includeMessages: false, sinceMinutes, agentDir }),
1462
+ read: ({ sessionId: targetId, limit = 12 }) =>
1463
+ readSessionTranscript(stateDir, targetId, { limit, agentDir }),
1464
+ open: ({ roleId: targetRoleId, title = '', reuseLatest = true }) =>
1465
+ openOrCreatePeerSession(stateDir, { roleId: targetRoleId, title, reuseLatest, agentDir }),
1466
+ send: ({ targetSessionId, targetRoleId, message, wait = false }) =>
1467
+ sendCrossSessionMessage({
1468
+ workspace,
1469
+ stateDir,
1470
+ documentRoot,
1471
+ fromSessionId: cleanId,
1472
+ fromRoleId: role.id,
1473
+ fromRoleName: role.name,
1474
+ targetSessionId,
1475
+ targetRoleId,
1476
+ message,
1477
+ canvas: turnHooksRef.current?.canvas || canvas,
1478
+ wait,
1479
+ }),
1480
+ },
1481
+ automationOps,
1482
+ onCardChanges: (...a) => turnHooksRef.current?.onCardChanges?.(...a),
1483
+ });
1484
+
1485
+ const loader = new DefaultResourceLoader({
1486
+ cwd: workspace,
1487
+ agentDir,
1488
+ settingsManager: sm,
1489
+ noThemes: true,
1490
+ packageCommandOutput: 'capture',
1491
+ extensionFactories: createBuiltInPiExtensions(agentDir),
1492
+ appendSystemPrompt: [
1493
+ role.systemPrompt,
1494
+ platformContext,
1495
+ pluginParamsContext,
1496
+ ].filter(Boolean),
1497
+ });
1498
+ await loader.reload();
1499
+
1500
+ const sessionManager = (piSessionFile && existsSync(piSessionFile))
1501
+ ? SessionManager.open(piSessionFile)
1502
+ : SessionManager.create(workspace, sessionsDir(stateDir));
1503
+ const resolvedFile = sessionManager.getSessionFile?.() || '';
1504
+ if (resolvedFile) {
1505
+ piSessionFile = resolvedFile;
1506
+ upsertSessionMeta(stateDir, { id: cleanId, piSessionFile }, agentDir);
1507
+ }
1508
+
1509
+ const created = await createAgentSession({
1510
+ cwd: workspace,
1511
+ agentDir,
1512
+ modelRuntime: mr,
1513
+ model: chosenModel,
1514
+ settingsManager: sm,
1515
+ resourceLoader: loader,
1516
+ sessionManager,
1517
+ customTools: delegatedCladoTools,
1518
+ });
1519
+ activeWarmEntry = {
1520
+ session: created.session,
1521
+ loader,
1522
+ sm,
1523
+ mr,
1524
+ modelKey: modelOverrideKey,
1525
+ roleId: role.id,
1526
+ agentDir,
1527
+ stateDir,
1528
+ pluginParamsSig: pluginParamsContext,
1529
+ turnHooksRef,
1530
+ needsReload: false,
1531
+ notifications: [],
1532
+ extensionErrors: [],
1533
+ };
1534
+ await bindSessionForClado(created.session, activeWarmEntry);
1535
+ warmSessions.set(sessionKey, activeWarmEntry);
1536
+ }
1537
+
1538
+ session = activeWarmEntry.session;
1207
1539
  try {
1208
1540
  if (runtimeSettings.thinkingLevel && typeof session.setThinkingLevel === 'function') {
1209
1541
  session.setThinkingLevel(runtimeSettings.thinkingLevel);
@@ -1689,8 +2021,11 @@ export function createPiBridge({
1689
2021
  }
1690
2022
  });
1691
2023
 
1692
- const promptText = buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom, agentDir });
1693
- await session.prompt(promptText);
2024
+ const rawSlash = !handoffFrom && trimmedCommand.startsWith('/');
2025
+ const promptText = rawSlash
2026
+ ? trimmedCommand
2027
+ : buildTurnContextBlock({ workspace, role, canvas, text, handoffFrom, agentDir });
2028
+ await session.prompt(promptText, { expandPromptTemplates: true });
1694
2029
  let finalUsage = readContextUsageSnapshot();
1695
2030
  if (finalUsage) {
1696
2031
  latestContextUsage = finalUsage;
@@ -1758,6 +2093,7 @@ export function createPiBridge({
1758
2093
  });
1759
2094
  }
1760
2095
  } finally {
2096
+ flushSseDelta();
1761
2097
  if (draftActive) {
1762
2098
  draftActive = false;
1763
2099
  events?.emit(workspace, 'canvas.draft', { active: false });
@@ -1767,14 +2103,214 @@ export function createPiBridge({
1767
2103
  }
1768
2104
  liveRuns.delete(`${workspace}::${cleanId}`);
1769
2105
  try { unsub?.(); } catch {}
1770
- try { session?.dispose?.(); } catch {}
2106
+ if (activeWarmEntry) {
2107
+ activeWarmEntry.turnHooksRef.current = null;
2108
+ if (activeWarmEntry.needsReload) {
2109
+ activeWarmEntry.session.reload()
2110
+ .then(() => { activeWarmEntry.needsReload = false; })
2111
+ .catch(() => {});
2112
+ }
2113
+ } else if (session) {
2114
+ await shutdownAndDisposeSession(session);
2115
+ }
2116
+ }
2117
+ }
2118
+
2119
+ const lastRuntimeSnapshotByWorkspace = new Map();
2120
+
2121
+ const waitBrieflyForMcpTools = async (session, enabledMcpServers, maxWaitMs = 2400) => {
2122
+ const hasDirect = (enabledMcpServers || []).some(s => s.enabled && s.exposure === 'direct');
2123
+ if (!hasDirect) {
2124
+ if ((enabledMcpServers || []).some(s => s.enabled)) {
2125
+ await new Promise(r => setTimeout(r, 250));
2126
+ }
2127
+ return;
2128
+ }
2129
+ const deadline = Date.now() + maxWaitMs;
2130
+ while (Date.now() < deadline) {
2131
+ const tools = session.getActiveToolNames?.() || [];
2132
+ if (tools.some(t => t.startsWith('mcp__'))) {
2133
+ // Give sibling servers a tiny beat to finish too
2134
+ await new Promise(r => setTimeout(r, 150));
2135
+ return;
2136
+ }
2137
+ await new Promise(r => setTimeout(r, 120));
2138
+ }
2139
+ };
2140
+
2141
+ const collectRuntimeSnapshot = (workspace, agentDir, session, loader, entryErrors = [], entryNotes = []) => {
2142
+ const mcpServers = listPiMcpServers(workspace, agentDir);
2143
+ const activeTools = session?.getActiveToolNames?.() || [];
2144
+ const allTools = (session?.getAllTools?.() || []).map(t => t.name);
2145
+ const mcpTools = [...new Set([...activeTools, ...allTools])].filter(t => t.startsWith('mcp__'));
2146
+ const extRes = loader?.getExtensions?.() || { extensions: [], errors: [], warnings: [] };
2147
+ const extensions = (extRes.extensions || []).map(e => e.path || e.resolvedPath || 'extension');
2148
+ const errors = [
2149
+ ...(extRes.errors || []).map(e => `${e.path || 'extension'}: ${e.error}`),
2150
+ ...(extRes.warnings || []).map(w => `${w.path || 'extension'}: ${w.warning}`),
2151
+ ...(entryErrors || []).map(e => e.message),
2152
+ ...(entryNotes || []).filter(n => n.level === 'error' || n.level === 'warning').map(n => n.message),
2153
+ ];
2154
+ const skillsCount = (loader?.getSkills?.()?.skills || []).length;
2155
+ const promptsCount = (loader?.getPrompts?.()?.prompts || []).length;
2156
+ const snap = {
2157
+ reloadedAt: new Date().toISOString(),
2158
+ extensions,
2159
+ mcpServers,
2160
+ mcpTools,
2161
+ activeTools,
2162
+ allTools,
2163
+ skillsCount,
2164
+ promptsCount,
2165
+ errors: [...new Set(errors)],
2166
+ };
2167
+ lastRuntimeSnapshotByWorkspace.set(workspace, snap);
2168
+ return snap;
2169
+ };
2170
+
2171
+ async function reloadWorkspaceSessions(workspace) {
2172
+ const prefix = workspace ? `${workspace}::` : '';
2173
+ let reloadedCount = 0;
2174
+ let deferredCount = 0;
2175
+ let firstReloadedEntry = null;
2176
+ for (const [key, entry] of warmSessions.entries()) {
2177
+ if (prefix && !key.startsWith(prefix)) continue;
2178
+ if (liveRuns.has(key)) {
2179
+ entry.needsReload = true;
2180
+ deferredCount++;
2181
+ continue;
2182
+ }
2183
+ try {
2184
+ entry.notifications.length = 0;
2185
+ entry.extensionErrors.length = 0;
2186
+ await entry.session.reload();
2187
+ entry.needsReload = false;
2188
+ reloadedCount++;
2189
+ if (!firstReloadedEntry) firstReloadedEntry = entry;
2190
+ } catch {
2191
+ await shutdownAndDisposeSession(entry.session);
2192
+ warmSessions.delete(key);
2193
+ }
2194
+ }
2195
+ if (firstReloadedEntry) {
2196
+ const agentDir = firstReloadedEntry.agentDir || resolvePiAgentDir();
2197
+ await waitBrieflyForMcpTools(firstReloadedEntry.session, listPiMcpServers(workspace, agentDir));
2198
+ collectRuntimeSnapshot(
2199
+ workspace,
2200
+ agentDir,
2201
+ firstReloadedEntry.session,
2202
+ firstReloadedEntry.loader,
2203
+ firstReloadedEntry.extensionErrors,
2204
+ firstReloadedEntry.notifications
2205
+ );
1771
2206
  }
2207
+ return { reloadedCount, deferredCount };
1772
2208
  }
1773
2209
 
1774
- async function compactSession({ workspace, stateDir, sessionId, customInstructions = '' }) {
2210
+ async function reloadSession({ workspace, stateDir, sessionId = '', roleId = 'architect', modelSpec = '' } = {}) {
2211
+ const agentDir = resolvePiAgentDir();
2212
+ const cleanId = sessionId ? safeSessionId(sessionId) : '';
2213
+ const targetKey = cleanId ? `${workspace}::${cleanId}` : '';
2214
+ const mcpServers = listPiMcpServers(workspace, agentDir);
2215
+ let reloadedPeers = 0;
2216
+
2217
+ // 1. Reload other warm sessions in this workspace
2218
+ for (const [key, entry] of warmSessions.entries()) {
2219
+ if (!key.startsWith(`${workspace}::`) || key === targetKey) continue;
2220
+ if (liveRuns.has(key)) {
2221
+ entry.needsReload = true;
2222
+ } else {
2223
+ try {
2224
+ entry.notifications.length = 0;
2225
+ entry.extensionErrors.length = 0;
2226
+ await entry.session.reload();
2227
+ entry.needsReload = false;
2228
+ reloadedPeers++;
2229
+ } catch {
2230
+ await shutdownAndDisposeSession(entry.session);
2231
+ warmSessions.delete(key);
2232
+ }
2233
+ }
2234
+ }
2235
+
2236
+ // 2. If target warm session exists, use Pi's native session.reload()
2237
+ const existing = targetKey ? warmSessions.get(targetKey) : [...warmSessions.entries()].find(([k]) => k.startsWith(`${workspace}::`))?.[1];
2238
+ if (existing && existing.session) {
2239
+ existing.notifications.length = 0;
2240
+ existing.extensionErrors.length = 0;
2241
+ await existing.session.reload();
2242
+ existing.needsReload = false;
2243
+ await waitBrieflyForMcpTools(existing.session, mcpServers);
2244
+ const snap = collectRuntimeSnapshot(workspace, agentDir, existing.session, existing.loader, existing.extensionErrors, existing.notifications);
2245
+ return { ok: true, mode: 'native_session_reload', reloadedPeers, ...snap };
2246
+ }
2247
+
2248
+ // 3. Otherwise create a clean bound session probe (or warm session when sessionId is provided) to load & verify MCP/extensions natively
2249
+ const sm = SettingsManager.create(workspace, agentDir);
2250
+ const loader = new DefaultResourceLoader({
2251
+ cwd: workspace,
2252
+ agentDir,
2253
+ settingsManager: sm,
2254
+ noThemes: true,
2255
+ packageCommandOutput: 'capture',
2256
+ extensionFactories: createBuiltInPiExtensions(agentDir),
2257
+ });
2258
+ await loader.reload();
2259
+
2260
+ let probeSession = null;
2261
+ const probeEntry = { notifications: [], extensionErrors: [], turnHooksRef: { current: null } };
2262
+ try {
2263
+ const mr = await createCladoModelRuntime(agentDir);
2264
+ const chosenModel = await resolvePiModel(mr, sm, modelSpec).catch(() => null);
2265
+ const created = await createAgentSession({
2266
+ cwd: workspace,
2267
+ agentDir,
2268
+ modelRuntime: mr,
2269
+ ...(chosenModel ? { model: chosenModel } : {}),
2270
+ settingsManager: sm,
2271
+ resourceLoader: loader,
2272
+ sessionManager: SessionManager.inMemory(),
2273
+ });
2274
+ probeSession = created.session;
2275
+ await bindSessionForClado(probeSession, probeEntry);
2276
+ await waitBrieflyForMcpTools(probeSession, mcpServers);
2277
+ const snap = collectRuntimeSnapshot(workspace, agentDir, probeSession, loader, probeEntry.extensionErrors, probeEntry.notifications);
2278
+ return { ok: true, mode: 'native_fresh_reload', reloadedPeers, ...snap };
2279
+ } finally {
2280
+ if (probeSession) await shutdownAndDisposeSession(probeSession);
2281
+ }
2282
+ }
2283
+
2284
+ async function disposeWarmSession(workspace, sessionId) {
2285
+ const key = `${workspace}::${safeSessionId(sessionId)}`;
2286
+ const entry = warmSessions.get(key);
2287
+ if (!entry) return false;
2288
+ warmSessions.delete(key);
2289
+ await shutdownAndDisposeSession(entry.session);
2290
+ return true;
2291
+ }
2292
+
2293
+ function inspectRuntime(workspace) {
2294
+ const prefix = workspace ? `${workspace}::` : '';
2295
+ const warmEntries = [...warmSessions.entries()]
2296
+ .filter(([k]) => !prefix || k.startsWith(prefix))
2297
+ .map(([, v]) => v);
2298
+ if (warmEntries.length) {
2299
+ const first = warmEntries[0];
2300
+ const agentDir = first.agentDir || resolvePiAgentDir();
2301
+ const snap = collectRuntimeSnapshot(workspace, agentDir, first.session, first.loader, first.extensionErrors, first.notifications);
2302
+ return { warmSessions: warmEntries.length, ...snap };
2303
+ }
2304
+ const cached = lastRuntimeSnapshotByWorkspace.get(workspace);
2305
+ return cached
2306
+ ? { warmSessions: 0, ...cached }
2307
+ : { warmSessions: 0, mcpTools: [], activeTools: [], extensions: [], errors: [] };
2308
+ }
2309
+
2310
+ async function compactSession({ workspace, stateDir, sessionId, customInstructions = '', allowDuringSelfRun = false }) {
1775
2311
  const cleanId = safeSessionId(sessionId);
1776
2312
  const runKey = `${workspace}::${cleanId}`;
1777
- if (liveRuns.has(runKey)) {
2313
+ if (!allowDuringSelfRun && liveRuns.has(runKey)) {
1778
2314
  throw new Error('该会话正在执行中,请等待当前回合完成或先点击停止后再压缩上下文。');
1779
2315
  }
1780
2316
  const agentDir = resolvePiAgentDir();
@@ -1844,16 +2380,40 @@ export function createPiBridge({
1844
2380
  });
1845
2381
  return { ok: true, contextUsage, session: updated };
1846
2382
  } finally {
1847
- try { session?.dispose?.(); } catch {}
2383
+ await shutdownAndDisposeSession(session);
2384
+ }
2385
+ }
2386
+
2387
+ function overlayLiveSession(workspace, item) {
2388
+ if (!item || !item.id) return item;
2389
+ const run = liveRuns.get(`${workspace}::${item.id}`);
2390
+ if (!run || typeof run.getLiveAssistant !== 'function') return item;
2391
+ const liveMsg = run.getLiveAssistant();
2392
+ const msgs = Array.isArray(item.messages) ? item.messages.slice() : null;
2393
+ if (msgs && !msgs.some(m => m && (m.id === liveMsg.id || m.turnId === liveMsg.turnId))) {
2394
+ msgs.push(liveMsg);
1848
2395
  }
2396
+ return {
2397
+ ...item,
2398
+ status: 'running',
2399
+ ...(msgs ? { messages: msgs } : {}),
2400
+ };
1849
2401
  }
1850
2402
 
1851
2403
  return {
1852
2404
  runTurn,
1853
2405
  compactSession,
2406
+ reloadSession,
2407
+ reloadWorkspaceSessions,
2408
+ disposeWarmSession,
2409
+ inspectRuntime,
1854
2410
  sendCrossSessionMessage,
1855
2411
  readSessionTranscript,
1856
2412
  openOrCreatePeerSession,
2413
+ overlayLiveSession,
2414
+ overlayLiveSessions(workspace, list) {
2415
+ return Array.isArray(list) ? list.map(s => overlayLiveSession(workspace, s)) : [];
2416
+ },
1857
2417
  listActiveRuns(workspace) {
1858
2418
  const prefix = workspace ? `${workspace}::` : '';
1859
2419
  return [...liveRuns.entries()]
@@ -1885,9 +2445,12 @@ export function createPiBridge({
1885
2445
  return targets.length;
1886
2446
  },
1887
2447
  async closeAll() {
1888
- const all = [...liveRuns.values()];
2448
+ const allRuns = [...liveRuns.values()];
1889
2449
  liveRuns.clear();
1890
- await Promise.allSettled(all.map(r => r.abort()));
2450
+ await Promise.allSettled(allRuns.map(r => r.abort()));
2451
+ const allWarm = [...warmSessions.values()];
2452
+ warmSessions.clear();
2453
+ await Promise.allSettled(allWarm.map(e => shutdownAndDisposeSession(e.session)));
1891
2454
  },
1892
2455
  };
1893
2456
  }