evolcore 0.0.40 → 0.0.41-test.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/claude-runner.js +21 -106
  5. package/dist/agents/codex-runner.js +451 -231
  6. package/dist/agents/ecagent-runner.js +30 -11
  7. package/dist/agents/gemini-runner.js +26 -6
  8. package/dist/agents/runner-types.js +11 -3
  9. package/dist/aun/ability-device-routing.js +26 -0
  10. package/dist/aun/aid/client.js +1 -1
  11. package/dist/aun/group/identity.js +8 -0
  12. package/dist/aun/msg/managed-operation.js +4 -4
  13. package/dist/aun/msg/p2p.js +27 -7
  14. package/dist/aun/storage/download.js +30 -0
  15. package/dist/aun/storage/index.js +14 -6
  16. package/dist/channels/aun.js +33 -4
  17. package/dist/channels/daemon.js +24 -4
  18. package/dist/cli/agent-command.js +2 -0
  19. package/dist/cli/agent-create.js +98 -19
  20. package/dist/cli/agent.js +10 -3
  21. package/dist/cli/aun-commands.js +82 -22
  22. package/dist/cli/daemon-commands.js +19 -10
  23. package/dist/cli/index.js +1 -1
  24. package/dist/cli/restart-monitor.js +17 -0
  25. package/dist/cli/session-command.js +128 -13
  26. package/dist/cli/stats.js +60 -4
  27. package/dist/cli/trigger-command.js +2 -2
  28. package/dist/config/access-policy.js +2 -0
  29. package/dist/config/config-operation-service.js +17 -6
  30. package/dist/config/gateway-config.js +1 -1
  31. package/dist/config/peer-role-resolver.js +10 -8
  32. package/dist/core/agent-application-service.js +11 -1
  33. package/dist/core/agent-ipc-registration.js +4 -0
  34. package/dist/core/auth/agent-delegation.js +80 -5
  35. package/dist/core/auth/authorization-audit.js +20 -3
  36. package/dist/core/auth/operation-catalog.js +8 -0
  37. package/dist/core/command/agent-control.js +91 -12
  38. package/dist/core/command/command-handler.js +57 -46
  39. package/dist/core/command/connect-menu.js +23 -2
  40. package/dist/core/command/menu-catalog.js +1 -0
  41. package/dist/core/command/menu-handler.js +38 -101
  42. package/dist/core/command/menu-protocol.js +9 -2
  43. package/dist/core/command/role-menu.js +7 -6
  44. package/dist/core/command/slash-gate.js +13 -10
  45. package/dist/core/command/slash-handler.js +34 -98
  46. package/dist/core/event-catalog.js +15 -0
  47. package/dist/core/ipc-registration.js +18 -1
  48. package/dist/core/memory/consolidation-trigger.js +1 -1
  49. package/dist/core/message/aun-ipc-sender.js +26 -5
  50. package/dist/core/message/aun-request-registry.js +97 -3
  51. package/dist/core/message/im-renderer.js +4 -0
  52. package/dist/core/message/message-admission.js +8 -4
  53. package/dist/core/message/message-bridge.js +40 -6
  54. package/dist/core/message/message-log.js +55 -0
  55. package/dist/core/message/message-queue.js +5 -5
  56. package/dist/core/message/response-engine.js +310 -136
  57. package/dist/core/model/model-catalog.js +7 -6
  58. package/dist/core/ownership/owner-resolver.js +2 -2
  59. package/dist/core/permission/ec-command-parser.js +110 -5
  60. package/dist/core/permission/tool-policy.js +28 -7
  61. package/dist/core/session/session-capsule.js +197 -0
  62. package/dist/core/session/session-manager.js +148 -14
  63. package/dist/core/session/session-mapper.js +2 -0
  64. package/dist/index.js +3 -3
  65. package/dist/ipc.js +22 -8
  66. package/dist/stats/budget.js +1 -1
  67. package/dist/stats/db.js +15 -0
  68. package/dist/stats/index.js +2 -2
  69. package/dist/stats/price-resolver.js +304 -5
  70. package/dist/stats/query.js +82 -3
  71. package/dist/stats/writer.js +38 -5
  72. package/dist/trigger/feedback.js +18 -7
  73. package/dist/trigger/manager.js +20 -3
  74. package/dist/trigger/parser.js +6 -3
  75. package/dist/trigger/patch.js +1 -1
  76. package/dist/trigger/system-definitions.js +43 -7
  77. package/dist/trigger/validation.js +13 -5
  78. package/dist/utils/error-utils.js +14 -0
  79. package/dist/utils/npm-ops.js +2 -1
  80. package/dist/utils/package-version-info.js +1 -1
  81. package/dist/utils/upgrade-jobs.js +45 -5
  82. package/kits/docs/INDEX.md +1 -1
  83. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  84. package/kits/docs/evolcore/INDEX.md +2 -1
  85. package/kits/docs/evolcore/agent-create.md +3 -2
  86. package/kits/docs/evolcore/agent.md +1 -1
  87. package/kits/docs/evolcore/config.md +1 -1
  88. package/kits/docs/evolcore/event.md +1 -0
  89. package/kits/docs/evolcore/fs.md +5 -0
  90. package/kits/docs/evolcore/menu-protocol.md +32 -0
  91. package/kits/docs/evolcore/msg.md +17 -1
  92. package/kits/docs/evolcore/session.md +14 -0
  93. package/kits/schemas/agent-config.schema.13.json +15 -0
  94. package/kits/skills/aid-ability/SKILL.md +35 -6
  95. package/kits/templates/session-capsule/recovery.md +5 -0
  96. package/kits/templates/session-capsule/renew.md +5 -0
  97. package/kits/templates/system-fragments/bootstrap.md +6 -6
  98. package/kits/templates/system-fragments/channel.md +1 -1
  99. package/package.json +3 -3
  100. package/dist/stats/billing.js +0 -215
@@ -18,7 +18,7 @@ import { loadSchema } from '../../config/schema-registry.js';
18
18
  import { rolePermissionFields, rolePermissionFieldOptions, rolePermissionFieldPatterns, validateRoleConfig, } from '../../config/role-schema.js';
19
19
  import { groupInfo, groupList, groupDirectoryErrorCode } from '../../aun/group/index.js';
20
20
  import { aidLookup, isValidAid } from '../../aun/aid/identity.js';
21
- import { isExplicitGroupId } from '../../aun/group/index.js';
21
+ import { isExplicitGroupId, isLegacyNamedGroupIdHint } from '../../aun/group/index.js';
22
22
  import { readJsonFile, readLastJsonlLine, scanChatDirs, scanMetaFiles } from '../session/session-fs-store.js';
23
23
  import { constrainResolvedModelForRole } from '../model/model-permission.js';
24
24
  import { resolveRuntimePermissionMode, resolveRuntimeStringField } from '../role/runtime-policy.js';
@@ -992,15 +992,16 @@ function privateHistoryTargets(self) {
992
992
  }).sort((a, b) => a.peerKey.localeCompare(b.peerKey));
993
993
  }
994
994
  function chatIsGroup(chat) {
995
- if (isExplicitGroupId(chat.channelId))
996
- return true;
997
995
  const active = readJsonFile(path.join(chat.dirPath, 'active.json'));
998
996
  if (active?.chatType === 'group' || active?.metadata?.groupId)
999
997
  return true;
1000
- return scanMetaFiles(chat.dirPath).some(metaFile => {
998
+ if (active?.chatType === 'private')
999
+ return false;
1000
+ const historicalGroup = scanMetaFiles(chat.dirPath).some(metaFile => {
1001
1001
  const session = readLastJsonlLine(path.join(chat.dirPath, metaFile));
1002
1002
  return session?.chatType === 'group' || !!session?.metadata?.groupId;
1003
1003
  });
1004
+ return historicalGroup || isLegacyNamedGroupIdHint(chat.channelId);
1004
1005
  }
1005
1006
  function assignmentResponse(self, target, config, changed, relationRevision) {
1006
1007
  return {
@@ -1021,7 +1022,7 @@ function normalizeTarget(value, self) {
1021
1022
  const peerAid = stringArg(value.peerAid);
1022
1023
  if (!peerAid)
1023
1024
  throw invalidTarget(self, 'target.peerAid');
1024
- if (!isValidAid(peerAid) || isExplicitGroupId(peerAid))
1025
+ if (!isValidAid(peerAid))
1025
1026
  throw invalidTargetValue(self, 'target.peerAid');
1026
1027
  return { kind, peerAid, peerKey: formatPeerKey('aun', peerAid) };
1027
1028
  }
@@ -1362,7 +1363,7 @@ function readRelation(peerKey, self) {
1362
1363
  function relationTargetKind(config, channelId, known = { groups: new Set(), privates: new Set() }) {
1363
1364
  if (config.targetKind)
1364
1365
  return config.targetKind;
1365
- if (known.groups.has(channelId) || isExplicitGroupId(channelId))
1366
+ if (known.groups.has(channelId) || isLegacyNamedGroupIdHint(channelId))
1366
1367
  return 'group';
1367
1368
  if (known.privates.has(channelId))
1368
1369
  return 'private';
@@ -47,22 +47,25 @@ const commands = ['/new', '/pwd', '/help', '/evolhelp', '/status', '/restart', '
47
47
  const deprecatedCommands = ['/clear'];
48
48
  commands.push('/diag');
49
49
  const exactBoundaryCommands = new Set(['/pause', '/resume', '/stop', '/pair', '/diag']);
50
- /** Parse the execution command without treating it as a quick/result command. */
50
+ /** Parse fullaccess controls and one-shot prompts without command-prefix ambiguity. */
51
51
  export function parseFullAccessCommand(content) {
52
52
  const match = content.match(/^\s*(\/fa|\/fullaccess)(?=\s|$)([\s\S]*)$/);
53
53
  if (!match)
54
54
  return { matched: false };
55
+ const raw = match[2].trim();
56
+ const command = match[1];
57
+ if (raw === '')
58
+ return { matched: true, command, action: 'status', raw };
59
+ if (raw === 'on')
60
+ return { matched: true, command, action: 'on', raw };
61
+ if (raw === 'off')
62
+ return { matched: true, command, action: 'off', raw };
55
63
  return {
56
64
  matched: true,
57
- command: match[1],
58
- action: match[2].trim() === ''
59
- ? 'status'
60
- : match[2].trim() === 'on'
61
- ? 'on'
62
- : match[2].trim() === 'off'
63
- ? 'off'
64
- : 'invalid',
65
- raw: match[2].trim(),
65
+ command,
66
+ action: 'prompt',
67
+ prompt: raw,
68
+ raw,
66
69
  };
67
70
  }
68
71
  // 命令别名映射
@@ -37,7 +37,7 @@ import { launchMonitorAndConfirm, resolveMonitorLaunch, cleanupMonitorStage, isP
37
37
  import { scanInstances } from '../../utils/instance-registry.js';
38
38
  import { guardIdleCommand, guardGroupSlashCommand, guardKnownCommand, guardRoleCommand, guardThreadCommand, isRecognizedSlashCommand, normalizeSlashContent, parseFullAccessCommand, probeSessionActivity, } from './slash-gate.js';
39
39
  import { MAX_AUN_ATTACHMENT_SIZE } from '../../aun/msg/upload.js';
40
- import { DEFAULT_SESSION_LOOP_SECONDS, MAX_SESSION_LOOP_SECONDS, MIN_SESSION_LOOP_SECONDS, refreshSessionLoopTarget, resolveCurrentSessionLoopTarget, sessionLoopPayload, validateIdleSeconds, writeSessionLoopConfig, } from '../session/session-idle-monitor.js';
40
+ import { DEFAULT_SESSION_LOOP_SECONDS, MAX_SESSION_LOOP_SECONDS, MIN_SESSION_LOOP_SECONDS, refreshSessionLoopTarget, resolveCurrentSessionLoopTarget, resolveSessionLoopTarget, sessionLoopPayload, validateIdleSeconds, writeSessionLoopConfig, } from '../session/session-idle-monitor.js';
41
41
  const allEfforts = CONFIGURABLE_EFFORTS;
42
42
  const PERMISSION_MODE_KEYS = PUBLIC_PERMISSION_MODES;
43
43
  function defaultSlashChatmode(field) {
@@ -631,6 +631,9 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
631
631
  }
632
632
  const fullAccessControl = parseFullAccessCommand(normalizedContent);
633
633
  if (fullAccessControl.matched) {
634
+ if (fullAccessControl.action === 'prompt') {
635
+ return { kind: 'command.error', text: '❌ /fa <任务信息> 只能由用户直接发送' };
636
+ }
634
637
  if (activeChatType === 'group' || source === 'card-trigger') {
635
638
  return { kind: 'command.error', text: '❌ /fa 仅支持私聊中的当前 EC 会话' };
636
639
  }
@@ -848,7 +851,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
848
851
  const appendProcessCommands = (lines) => {
849
852
  if (!isDaemonOwner)
850
853
  return;
851
- lines.push('', '🛠️ 进程级运维:', ' /restart - 重启服务', ' /upgrade - 检查版本更新', ' /reload [aid] - 热重载 Agent 配置', ' /fa [on|off] - 查看或切换当前 EC 会话 fullaccess', ' /pair - 获取远程控制配对码', ' /diag <问题描述> - 邀请或追加远程诊断;/diag stop 撤销授权');
854
+ lines.push('', '🛠️ 进程级运维:', ' /restart - 重启服务', ' /upgrade - 检查版本更新', ' /reload [aid] - 热重载 Agent 配置', ' /fa [on|off|<任务信息>] - 查看/切换会话 fullaccess,或单次执行任务', ' /pair - 获取远程控制配对码', ' /diag <问题描述> - 邀请或追加远程诊断;/diag stop 撤销授权');
852
855
  };
853
856
  if (!isAdmin && activeChatType === 'group') {
854
857
  const lines = [
@@ -980,7 +983,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
980
983
  ...(isDaemonOwner ? [
981
984
  ' /restart - 重启服务',
982
985
  ' /reload [aid] - 热重载 Agent 配置',
983
- ' /fa [on|off] - 查看或切换当前 EC 会话 fullaccess',
986
+ ' /fa [on|off|<任务信息>] - 查看/切换会话 fullaccess,或单次执行任务',
984
987
  ' /pair - 获取远程控制配对码',
985
988
  ] : []),
986
989
  ...(!isDaemonOwner && isAdmin ? [
@@ -1140,7 +1143,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1140
1143
  cmds.push({ command: '/observable', args: '[true|false]', description: '查看或切换观察者模式', category: '运维', roles: ['owner'] });
1141
1144
  }
1142
1145
  if (isDaemonOwner) {
1143
- cmds.push({ command: '/fa', aliases: ['/fullaccess'], args: '[on|off]', description: '查看或切换当前 EC 会话 fullaccess', category: '权限管理', roles: ['daemon-owner'] });
1146
+ cmds.push({ command: '/fa', aliases: ['/fullaccess'], args: '[on|off|<任务信息>]', description: '查看/切换当前 EC 会话 fullaccess,或单次执行 fullaccess 任务', category: '权限管理', roles: ['daemon-owner'] });
1144
1147
  cmds.push({ command: '/restart', description: '重启服务', category: '运维', roles: ['daemon-owner'] });
1145
1148
  cmds.push({ command: '/upgrade', description: '检查版本更新', category: '运维', roles: ['daemon-owner'] });
1146
1149
  cmds.push({ command: '/reload', args: '[aid]', description: '热重载 Agent 配置', category: '运维', roles: ['daemon-owner'] });
@@ -1381,7 +1384,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1381
1384
  initiatorId: userId,
1382
1385
  kind: {
1383
1386
  kind: 'command-card',
1384
- title: '🔌 切换 Agent',
1387
+ title: '🔌 新会话默认 Baseagent',
1385
1388
  buttons: available.map((a) => ({
1386
1389
  label: a === activeBaseagent ? `✓ ${a}` : a,
1387
1390
  command: `/baseagent ${a}`,
@@ -1400,9 +1403,9 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1400
1403
  const list = available.map((a) => `${a === activeBaseagent ? ' ✓' : ' '} ${a}`).join('\n');
1401
1404
  const canSwitchAgent = isOwner && !groupSlash;
1402
1405
  if (canSwitchAgent) {
1403
- return { kind: 'command.result', text: `当前 Baseagent: ${activeBaseagent}\n\n可用:\n${list}\n用法: /baseagent <name>` };
1406
+ return { kind: 'command.result', text: `新会话默认 Baseagent: ${activeBaseagent}\n\n可用:\n${list}\n用法: /baseagent <name>` };
1404
1407
  }
1405
- return { kind: 'command.result', text: `当前 Baseagent: ${activeBaseagent}` };
1408
+ return { kind: 'command.result', text: `新会话默认 Baseagent: ${activeBaseagent}` };
1406
1409
  }
1407
1410
  if (!available.includes(args)) {
1408
1411
  return { kind: 'command.error', text: `❌ 未知 Agent: ${args}\n可用: ${available.join(', ')}` };
@@ -1412,103 +1415,17 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1412
1415
  }
1413
1416
  const currentSession = await getExistingSessionForCommand();
1414
1417
  const previousBaseagent = owningAgent.baseagent || this.parseDefaultBaseagent();
1415
- const currentTopicThreadId = sessionTopicThreadId(currentSession);
1416
- if (currentSession && currentTopicThreadId) {
1417
- const rotation = await withIdleTopicBackend(currentSession.id, currentTopicThreadId, async (current) => {
1418
- try {
1419
- owningAgent.setActiveBaseagent(args);
1420
- }
1421
- catch (error) {
1422
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
1423
- }
1424
- try {
1425
- const result = await this.sessionManager.rotateTopicBackend({
1426
- sessionId: current.id,
1427
- // withIdleTopicBackend 已校验 sessionTopicThreadId(current) === currentTopicThreadId
1428
- expectedThreadId: currentTopicThreadId,
1429
- baseagent: args,
1430
- });
1431
- return { ok: true, result };
1432
- }
1433
- catch (error) {
1434
- try {
1435
- owningAgent.setActiveBaseagent(previousBaseagent);
1436
- }
1437
- catch { }
1438
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
1439
- }
1440
- }, currentSession);
1441
- if (!rotation.ok) {
1442
- if (rotation.reason === 'busy')
1443
- return { kind: 'command.error', text: '⚠️ 当前话题会话忙碌,无法切换 baseagent,请稍后再试' };
1444
- if (rotation.reason === 'unknown')
1445
- return { kind: 'command.error', text: '⚠️ 当前话题会话状态未知,无法安全切换 baseagent,请稍后再试' };
1446
- return { kind: 'command.error', text: `❌ baseagent 切换失败:${rotation.reason === 'missing' ? '当前话题会话不存在' : '状态未知'}` };
1447
- }
1448
- if (!rotation.value.ok)
1449
- return { kind: 'command.error', text: `❌ baseagent 切换失败:${rotation.value.error}` };
1450
- this.eventBus.publish({ type: 'agent:baseagent-changed', aid: owningAgent.aid, baseagent: args, previousBaseagent, scope: 'agent', timestamp: Date.now() });
1451
- return {
1452
- kind: 'system.notice',
1453
- text: `✓ 当前话题已切换 Baseagent: ${previousBaseagent} → ${args}\n 话题会话 ID 保持不变: ${currentSession.id}`,
1454
- subtype: 'session.created',
1455
- };
1456
- }
1457
- await interruptPausedSessionBeforeReplacement(currentSession);
1458
1418
  try {
1459
1419
  owningAgent.setActiveBaseagent(args);
1460
1420
  }
1461
1421
  catch (error) {
1462
1422
  return { kind: 'command.error', text: `❌ ${error instanceof Error ? error.message : String(error)}` };
1463
1423
  }
1464
- let newSession;
1465
- try {
1466
- newSession = await this.sessionManager.createNewSession(channel, channelId, owningAgent.projectPath, undefined, args, currentSession?.metadata, { previousBaseagent, baseagentChanged: previousBaseagent !== args });
1467
- }
1468
- catch (error) {
1469
- try {
1470
- owningAgent.setActiveBaseagent(previousBaseagent);
1471
- }
1472
- catch { }
1473
- return { kind: 'command.error', text: `❌ 创建新会话失败:${error instanceof Error ? error.message : String(error)}` };
1474
- }
1475
- if (currentSession) {
1476
- const previousAgent = getActiveAgentIfAvailable();
1477
- if (previousAgent) {
1478
- await previousAgent.clearSession(currentSession.id, currentSession.agentSessionId || '', currentSession.projectPath);
1479
- await previousAgent.closeSession(currentSession.id);
1480
- }
1481
- }
1482
1424
  this.eventBus.publish({ type: 'agent:baseagent-changed', aid: owningAgent.aid, baseagent: args, previousBaseagent, scope: 'agent', timestamp: Date.now() });
1483
- // 与 /new 一致:按 关系>角色>agent 解析新 backend 实际生效的 model/effort,
1484
- // 而不是只显示 baseagent 名。
1485
- const newBaseagentRunner = this.getAgent(channel, newSession.baseagent);
1486
- const newModelTarget = resolveSlashRelationTarget.call(this, {
1487
- session: newSession,
1488
- channel,
1489
- channelId,
1490
- userId,
1491
- selfAID,
1492
- role: newSession.identity?.role || identity.role,
1493
- chatType,
1494
- });
1495
- const newModelSelector = 'error' in newModelTarget
1496
- ? { self: selfAID ?? newSession.selfAID ?? this.resolveSelfAID(channel) }
1497
- : newModelTarget;
1498
- let sessionModelConfig = {};
1499
- try {
1500
- sessionModelConfig = (resolveEffective(newModelSelector, { cache: true }).baseagents || {})[args] || {};
1501
- }
1502
- catch { }
1503
- const sessionBackendModel = sessionModelConfig.model || newBaseagentRunner?.getModel?.() || owningAgent?.model;
1504
- const sessionBackendEffort = sessionModelConfig.effort
1505
- ?? newBaseagentRunner?.getEffort?.()
1506
- ?? owningAgent?.effort;
1507
- const sessionBackendBits = [args, sessionBackendModel, sessionBackendEffort].filter(Boolean).join(' · ');
1508
1425
  return {
1509
- kind: 'system.notice',
1510
- text: `✓ 已切换新后端 : ${sessionBackendBits}`,
1511
- subtype: 'session.created',
1426
+ kind: 'command.result',
1427
+ text: `✓ 新会话默认 Baseagent: ${previousBaseagent} → ${args}`
1428
+ + (currentSession ? `\n当前会话继续使用 ${currentSession.baseagent}。` : ''),
1512
1429
  };
1513
1430
  }
1514
1431
  // /model 命令:查看或切换模型/推理强度
@@ -2854,13 +2771,32 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2854
2771
  : mentionModeTarget.scope === 'relation' ? '本群' : 'Agent 全局';
2855
2772
  const chatModeLine = `会话模式: ${chatMode}`;
2856
2773
  const mentionModeLine = `@ 处理模式(${mentionScopeLabel}): ${mentionMode}`;
2774
+ const statusControlLines = [];
2775
+ const fullAccessPrincipalId = authSubject.principalId;
2776
+ if (session.chatType === 'private'
2777
+ && authSubject.isDaemonOwner
2778
+ && fullAccessPrincipalId
2779
+ && session.selfAID
2780
+ && isAgentFullAccessOwner(session.selfAID, fullAccessPrincipalId)
2781
+ && sessionFullAccessStatus(session, fullAccessPrincipalId).effective) {
2782
+ statusControlLines.push('fullaccess: 开启');
2783
+ }
2784
+ if (canAccessSlashOperation('session.loop.current', 'relation')) {
2785
+ const loopTarget = resolveSessionLoopTarget(session);
2786
+ if (loopTarget) {
2787
+ const loopStatus = sessionLoopPayload(loopTarget);
2788
+ if (loopStatus.value === true && typeof loopStatus.idleSeconds === 'number') {
2789
+ statusControlLines.push(`loop 周期: ${loopStatus.idleSeconds} 秒`);
2790
+ }
2791
+ }
2792
+ }
2857
2793
  if (isAdmin) {
2858
2794
  const gitInfo = await getGitWorkingDirInfo(session.projectPath);
2859
2795
  lines.push(`📊 ${isThread ? '话题' : '会话'}状态 (Agent: ${agentName}):`, `渠道: ${this.resolveChannelType(channel)} / 项目: ${projectName} / 会话: ${displaySessionTitle(session.name, '(未命名)')}`, `会话ID: ${session.id}`, `项目路径: ${session.projectPath}`);
2860
2796
  if (gitInfo) {
2861
2797
  lines.push(`Git: ${gitInfo}`);
2862
2798
  }
2863
- lines.push(`会话状态: ${sessionStatus} / 轮数: ${sessionTurns} / 已记录子任务数: ${sessionSubtasks}`, sessionRoleLine, chatModeLine, mentionModeLine);
2799
+ lines.push(`会话状态: ${sessionStatus} / 轮数: ${sessionTurns} / 已记录子任务数: ${sessionSubtasks}`, sessionRoleLine, chatModeLine, mentionModeLine, ...statusControlLines);
2864
2800
  if (health.consecutiveErrors > 0) {
2865
2801
  lines.push(`异常计数: ${health.consecutiveErrors}`);
2866
2802
  }
@@ -2868,7 +2804,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2868
2804
  }
2869
2805
  else {
2870
2806
  lines.push(`📊 ${isThread ? '话题' : '会话'}状态 (Agent: ${agentName}):`, `渠道: ${channel} / 项目: ${projectName} / ${session.baseagent}会话`);
2871
- lines.push(`状态: ${sessionStatus} / 轮数: ${sessionTurns} / 已记录子任务数: ${sessionSubtasks}`, sessionRoleLine, chatModeLine, mentionModeLine, `最后活跃: ${timeStr}`);
2807
+ lines.push(`状态: ${sessionStatus} / 轮数: ${sessionTurns} / 已记录子任务数: ${sessionSubtasks}`, sessionRoleLine, chatModeLine, mentionModeLine, ...statusControlLines, `最后活跃: ${timeStr}`);
2872
2808
  }
2873
2809
  if (health.lastError) {
2874
2810
  lines.push('');
@@ -124,6 +124,21 @@ const CATALOG = [
124
124
  { path: 'timestamp', type: 'number' },
125
125
  ],
126
126
  },
127
+ {
128
+ type: 'session:backend-recovery',
129
+ namespace: 'session',
130
+ name: 'backend-recovery',
131
+ description: '底层会话异常恢复完成并接收恢复摘要',
132
+ fields: [
133
+ { path: 'sessionId', type: 'string' },
134
+ { path: 'agentAid', type: 'string', optional: true },
135
+ { path: 'baseagent', type: 'string' },
136
+ { path: 'sourceAgentSessionId', type: 'string', optional: true },
137
+ { path: 'agentSessionId', type: 'string' },
138
+ { path: 'capsuleId', type: 'string' },
139
+ { path: 'timestamp', type: 'number' },
140
+ ],
141
+ },
127
142
  {
128
143
  type: 'session:switched',
129
144
  namespace: 'session',
@@ -663,7 +663,7 @@ export function registerOperationIpcProviders({ ipcServer, sessionManager, messa
663
663
  const authorization = await authorizeManagedAgentOperation({ ...params, targetAid: command.aid }, command.operation);
664
664
  if (!authorization.ok)
665
665
  return authorization;
666
- const { storageDownload, storageLs, storageRm, storageQuota } = await import('../aun/storage/index.js');
666
+ const { storageDownload, storageGetByShare, storageLs, storageRm, storageQuota } = await import('../aun/storage/index.js');
667
667
  if (command.sub === 'ls')
668
668
  return storageLs(authorization.aid, command.prefix);
669
669
  if (command.sub === 'quota')
@@ -675,6 +675,23 @@ export function registerOperationIpcProviders({ ipcServer, sessionManager, messa
675
675
  const session = await sessionManager.getSessionById(params.sessionId);
676
676
  if (!session)
677
677
  return { ok: false, code: 'SESSION_NOT_FOUND', error: 'current session not found' };
678
+ if (command.sub === 'get-by-share') {
679
+ if (!command.shareId)
680
+ return { ok: false, code: 'INVALID_ARGUMENT', error: 'get-by-share requires a share_id' };
681
+ const defaultName = `share-${command.shareId}`;
682
+ const destination = path.resolve(authorization.sessionRuntimeDir ?? session.projectPath, command.localPath ?? defaultName);
683
+ const roots = [session.projectPath, authorization.sessionRuntimeDir].filter((root) => !!root).map(root => fs.realpathSync(root));
684
+ let parent = path.dirname(destination);
685
+ while (!fs.existsSync(parent) && path.dirname(parent) !== parent)
686
+ parent = path.dirname(parent);
687
+ const realParent = fs.realpathSync(parent);
688
+ if (!roots.some(root => isSameOrDescendant(destination, root) && isSameOrDescendant(realParent, root))
689
+ || isHClassPath(destination) || isLClassPath(destination)
690
+ || (fs.existsSync(destination) && (!fs.lstatSync(destination).isFile() || fs.lstatSync(destination).isSymbolicLink()))) {
691
+ return { ok: false, code: 'INVALID_LOCAL_PATH', error: 'Download destination must be an unprotected project/TMPDIR file' };
692
+ }
693
+ return storageGetByShare(authorization.aid, command.shareId, destination);
694
+ }
678
695
  const defaultName = path.basename(command.url.replace(/^https?:\/\//, '').split('/').slice(1).join('/'));
679
696
  const destination = path.resolve(session.projectPath, command.localPath ?? defaultName);
680
697
  const roots = [session.projectPath, authorization.sessionRuntimeDir].filter((root) => !!root).map(root => fs.realpathSync(root));
@@ -62,7 +62,7 @@ export function seedConsolidationCheckTrigger(manager, owner, packageRoot = getP
62
62
  permissionMode: 'bypass', onError: 'fail', noopSentinel: '[[NOOP]]',
63
63
  },
64
64
  feedback: { strategy: 'silent' },
65
- reliability: { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 0, backoffMs: 30_000 } },
65
+ reliability: { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 1, backoffMs: 30_000 } },
66
66
  });
67
67
  const dir = manager.triggerDir(definition.id);
68
68
  fs.mkdirSync(dir, { recursive: true });
@@ -1,3 +1,4 @@
1
+ import { resolveAunSendDevice } from '../../aun/ability-device-routing.js';
1
2
  import crypto from 'crypto';
2
3
  import { authorizeDelegatedAunMsgSend, } from '../auth/agent-delegation.js';
3
4
  import { formatChannelKey, tryParseChannelKey } from '../channel-loader.js';
@@ -14,7 +15,8 @@ import { sameGroupAid } from '../../aun/group/identity.js';
14
15
  import { resolveThreadRouteTarget } from '../thread/thread-route.js';
15
16
  import { isTopicThreadId, parseMainTopicId, safeFormatMainTopicId, sessionLocalTopicId } from '../thread/topic-id.js';
16
17
  import { ThreadService } from '../thread/thread-service.js';
17
- import { getAunRequestRegistry, requestTtlSeconds } from './aun-request-registry.js';
18
+ import { getAunRequestRegistry, requestDiagnostics, requestTtlSeconds } from './aun-request-registry.js';
19
+ import { parseJsonObjectArgument } from '../permission/ec-command-parser.js';
18
20
  const TASK_ID_MESSAGE_PAYLOAD_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file']);
19
21
  /** payload.debug 只是诊断字段:取不到时照常发送,不带 debug。 */
20
22
  async function resolveOutboundDebug(resolver, sessionId) {
@@ -242,18 +244,21 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
242
244
  });
243
245
  const sender = async (params) => {
244
246
  let textFile;
247
+ let payloadFile;
245
248
  try {
246
249
  if (params.argv !== undefined) {
247
250
  const command = resolveManagedSendArgv(params.argv);
248
251
  textFile = command.textFile;
252
+ payloadFile = command.payloadFile;
249
253
  params = { ...params, ...command };
250
254
  }
251
255
  else if (!params.aid || !params.to || !params.scope) {
252
256
  return { ok: false, code: 'INVALID_REQUEST', error: 'Managed AUN sends require command parameters' };
253
257
  }
258
+ params.deviceId = resolveAunSendDevice(params.deviceId, params.scope, params.payload);
254
259
  }
255
260
  catch (error) {
256
- return { ok: false, code: 'INVALID_ARGUMENT', error: error instanceof Error ? error.message : String(error) };
261
+ return { ok: false, code: error.code ?? 'INVALID_ARGUMENT', error: error instanceof Error ? error.message : String(error) };
257
262
  }
258
263
  // 活跃任务走内存上下文;调试会话(--as-session)和已结束的会话没有内存记录,
259
264
  // 这时从会话本身重建,否则跨话题复查会静默不创建(getTaskRuntimeContext 返回 null)。
@@ -331,7 +336,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
331
336
  ? { selfAid: delegation.grant.selfAid, projectPath: runtime.projectPath,
332
337
  sessionRuntimeDir: delegation.grant.sessionRuntimeDir, cwd: runtime.projectPath }
333
338
  : undefined;
334
- if ((textFile || params.file) && !fileScope)
339
+ if ((textFile || payloadFile || params.file) && !fileScope)
335
340
  throw new Error('Current task project context is unavailable');
336
341
  if (textFile) {
337
342
  const text = new TextDecoder('utf-8', { fatal: true }).decode(readTriggerLocalFile(textFile, fileScope));
@@ -339,9 +344,14 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
339
344
  throw new Error('Message file must contain nonempty UTF-8 text');
340
345
  params.payload = { type: 'text', text };
341
346
  }
347
+ if (payloadFile) {
348
+ const raw = new TextDecoder('utf-8', { fatal: true }).decode(readTriggerLocalFile(payloadFile, fileScope));
349
+ params.payload = parseJsonObjectArgument(raw, '--payload-file');
350
+ }
342
351
  if (params.file) {
343
352
  params.file = { ...params.file, filePath: resolveAttachmentLocalPath(params.file.filePath, fileScope) };
344
353
  }
354
+ params.deviceId = resolveAunSendDevice(params.deviceId, params.scope, params.payload);
345
355
  if (params.payload && params.rawPayload !== true)
346
356
  params.payload = withAunAttention(params.payload);
347
357
  const currentRelation = runtime?.channel === 'aun' && runtime.selfAid === params.aid
@@ -351,7 +361,11 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
351
361
  ? params.payload.thread_id.trim() : params.thread ?? (currentRelation ? runtime?.threadId : undefined);
352
362
  }
353
363
  catch (error) {
354
- return { ok: false, code: 'INVALID_LOCAL_FILE', error: error instanceof Error ? error.message : String(error) };
364
+ return {
365
+ ok: false,
366
+ code: error?.code ?? 'INVALID_LOCAL_FILE',
367
+ error: error instanceof Error ? error.message : String(error),
368
+ };
355
369
  }
356
370
  const inst = channelInstances.find((candidate) => {
357
371
  if (candidate.channelType !== 'aun')
@@ -469,6 +483,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
469
483
  preparedRequest = getAunRequestRegistry().prepare({
470
484
  selfAid: params.aid,
471
485
  targetAid: params.to,
486
+ targetDeviceId: params.deviceId,
472
487
  payload,
473
488
  timeoutMs: params.timeoutMs ?? 60_000,
474
489
  ...(runtime && delegation.grant ? { origin: {
@@ -602,6 +617,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
602
617
  }
603
618
  const sent = await ch.sendDaemonMsg({
604
619
  to: params.to,
620
+ deviceId: params.deviceId,
605
621
  payload,
606
622
  rawPayload: params.rawPayload,
607
623
  ttl: requestTtl,
@@ -616,7 +632,10 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
616
632
  const request = getAunRequestRegistry().markFailed(params.aid, preparedRequest.requestId, transportError);
617
633
  if (request?.state === 'completed') {
618
634
  return { ok: true, request_id: preparedRequest.requestId, request_state: request.state,
619
- response: request.responsePayload, transport_error: transportError, retryable: false, sent: true };
635
+ ...(request.responsePayload ? { response: request.responsePayload } : {}),
636
+ ...(request.responses ? { responses: request.responses } : {}),
637
+ ...(request ? { request_diagnostics: requestDiagnostics(request) } : {}),
638
+ transport_error: transportError, retryable: false, sent: true };
620
639
  }
621
640
  return { ...sent, ok: false, request_id: preparedRequest.requestId, request_state: request?.state ?? 'failed' };
622
641
  }
@@ -627,6 +646,8 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
627
646
  request_id: preparedRequest.requestId,
628
647
  request_state: completed?.state ?? 'unknown',
629
648
  ...(completed?.responsePayload ? { response: completed.responsePayload } : {}),
649
+ ...(completed?.responses ? { responses: completed.responses } : {}),
650
+ ...(completed ? { request_diagnostics: requestDiagnostics(completed) } : {}),
630
651
  };
631
652
  }
632
653
  if (params.thread && params.checkEveryMs !== undefined && sent.ok && sent.message_id && threadRoute) {
@@ -3,6 +3,31 @@ import path from 'path';
3
3
  import crypto from 'crypto';
4
4
  import { resolvePaths } from '../../paths.js';
5
5
  import { appendJsonlDurable } from '../session/session-fs-store.js';
6
+ import { isAidWideDeviceStatusQuery } from '../../aun/ability-device-routing.js';
7
+ export function requestDiagnostics(record) {
8
+ const ignoredReason = record.lastIgnoredResponse?.reason;
9
+ const unresolved = record.state !== 'completed' && record.state !== 'failed';
10
+ return {
11
+ state: record.state,
12
+ ...(record.responseMode ? { responseMode: record.responseMode } : {}),
13
+ ...(record.responses ? { responseCount: record.responses.length } : {}),
14
+ ...(record.targetDeviceId ? { targetDeviceId: record.targetDeviceId } : {}),
15
+ ...(record.responseDeviceId ? { responseDeviceId: record.responseDeviceId } : {}),
16
+ ...(record.transportStatus ? { transportStatus: record.transportStatus } : {}),
17
+ ackReceived: !!record.ackMessageId,
18
+ ...(record.ackMessageId ? { ackMessageId: record.ackMessageId } : {}),
19
+ ...(record.deadlineAt !== undefined ? { deadlineAt: record.deadlineAt } : {}),
20
+ updatedAt: record.updatedAt,
21
+ ...(record.lastIgnoredResponse ? { lastIgnoredResponse: record.lastIgnoredResponse } : {}),
22
+ ...(unresolved && (ignoredReason === 'response_device_mismatch' || ignoredReason === 'response_device_id_missing')
23
+ ? { reason: ignoredReason }
24
+ : record.state === 'pending' && record.ackMessageId
25
+ ? { reason: 'provider_ack_without_final_result' }
26
+ : record.state === 'pending'
27
+ ? { reason: 'no_final_response_before_deadline' }
28
+ : {}),
29
+ };
30
+ }
6
31
  const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
7
32
  const MAX_TIMER_MS = 2_147_483_647;
8
33
  /** AUN message.send accepts volatile TTL values from 1 through 3600 seconds. */
@@ -107,6 +132,7 @@ export class AunRequestRegistry {
107
132
  const record = {
108
133
  selfAid: params.selfAid,
109
134
  targetAid: params.targetAid,
135
+ ...(params.targetDeviceId ? { targetDeviceId: params.targetDeviceId } : {}),
110
136
  requestId: chosen,
111
137
  correlationKind,
112
138
  correlationKeys: keys,
@@ -115,6 +141,15 @@ export class AunRequestRegistry {
115
141
  createdAt: now,
116
142
  updatedAt: now,
117
143
  deadlineAt: now + timeoutMs,
144
+ ...(!params.targetDeviceId && isAidWideDeviceStatusQuery(params.payload) ? {
145
+ responseMode: 'all_devices',
146
+ responseCorrelation: {
147
+ abilityPath: params.payload.ability_path,
148
+ definitionId: params.payload.definition_id,
149
+ operationId: params.payload.operation_id,
150
+ },
151
+ responses: [],
152
+ } : {}),
118
153
  };
119
154
  const payload = { ...params.payload };
120
155
  if (!requestId && !callId)
@@ -136,6 +171,9 @@ export class AunRequestRegistry {
136
171
  const current = this.get(selfAid, requestId);
137
172
  if (current?.state === 'completed' || current?.state === 'failed')
138
173
  return current;
174
+ if (current?.responseMode === 'all_devices' && current.responses?.length) {
175
+ return this.update(selfAid, requestId, { state: 'completed', error });
176
+ }
139
177
  return this.update(selfAid, requestId, { state: 'failed', error });
140
178
  }
141
179
  update(selfAid, requestId, patch) {
@@ -170,9 +208,51 @@ export class AunRequestRegistry {
170
208
  const payload = params.payload;
171
209
  const keys = [stringValue(payload.request_id), stringValue(payload.call_id)].filter((value) => !!value);
172
210
  for (const key of keys) {
173
- const record = this.records.get(this.key(params.selfAid, key));
211
+ const record = this.get(params.selfAid, key);
174
212
  if (!record || record.targetAid !== params.fromAid || ['failed', 'completed'].includes(record.state))
175
213
  continue;
214
+ if (record.targetDeviceId && record.targetDeviceId !== params.fromDeviceId) {
215
+ const reason = params.fromDeviceId
216
+ ? 'response_device_mismatch'
217
+ : 'response_device_id_missing';
218
+ return this.updateWithoutNotify(params.selfAid, record.requestId, {
219
+ lastIgnoredResponse: {
220
+ messageId: params.messageId,
221
+ ...(params.fromDeviceId ? { responseDeviceId: params.fromDeviceId } : {}),
222
+ reason,
223
+ receivedAt: Date.now(),
224
+ },
225
+ ignoredResponseCount: (record.ignoredResponseCount ?? 0) + 1,
226
+ });
227
+ }
228
+ if (record.responseMode === 'all_devices') {
229
+ // Device identity is authenticated transport metadata, never payload data.
230
+ // Keep each device's terminal result and do not finish on the first one.
231
+ if (!stringValue(params.fromDeviceId) || !record.deadlineAt || Date.now() >= record.deadlineAt)
232
+ continue;
233
+ const expected = record.responseCorrelation;
234
+ if (payload.type !== 'ability' || !['ack', 'result'].includes(String(payload.role))
235
+ || payload.ability_path !== expected?.abilityPath
236
+ || payload.definition_id !== expected?.definitionId
237
+ || payload.operation_id !== expected?.operationId)
238
+ continue;
239
+ if (this.isIntermediateResponse(payload)) {
240
+ return this.updateWithoutNotify(params.selfAid, record.requestId, {
241
+ ackMessageId: params.messageId, ackPayload: payload,
242
+ });
243
+ }
244
+ const responses = record.responses ?? [];
245
+ if (responses.some(response => response.responseDeviceId === params.fromDeviceId))
246
+ return record;
247
+ return this.updateWithoutNotify(params.selfAid, record.requestId, {
248
+ responses: [...responses, {
249
+ responseMessageId: params.messageId,
250
+ responseDeviceId: params.fromDeviceId,
251
+ responsePayload: payload,
252
+ receivedAt: Date.now(),
253
+ }],
254
+ });
255
+ }
176
256
  if (this.isIntermediateResponse(payload)) {
177
257
  return this.updateWithoutNotify(params.selfAid, record.requestId, {
178
258
  ackMessageId: params.messageId,
@@ -182,6 +262,7 @@ export class AunRequestRegistry {
182
262
  const updated = this.update(params.selfAid, record.requestId, {
183
263
  state: 'completed',
184
264
  responseMessageId: params.messageId,
265
+ ...(params.fromDeviceId ? { responseDeviceId: params.fromDeviceId } : {}),
185
266
  responsePayload: payload,
186
267
  });
187
268
  return updated;
@@ -191,6 +272,11 @@ export class AunRequestRegistry {
191
272
  get(selfAid, requestId) {
192
273
  this.ensureLoaded(selfAid);
193
274
  const record = this.records.get(this.key(selfAid, requestId));
275
+ if (record?.responseMode === 'all_devices' && !['failed', 'completed'].includes(record.state)
276
+ && record.deadlineAt !== undefined && record.deadlineAt <= Date.now()) {
277
+ const state = record.responses?.length ? 'completed' : 'pending';
278
+ return record.state === state ? record : this.update(selfAid, record.requestId, { state });
279
+ }
194
280
  if (record && record.state === 'sent' && record.deadlineAt !== undefined && record.deadlineAt <= Date.now()) {
195
281
  return this.update(selfAid, record.requestId, { state: 'pending' });
196
282
  }
@@ -202,8 +288,16 @@ export class AunRequestRegistry {
202
288
  return current;
203
289
  const normalizedTimeoutMs = normalizeTimeoutMs(timeoutMs);
204
290
  const waitMs = Math.max(0, Math.min(normalizedTimeoutMs, current.deadlineAt ? current.deadlineAt - Date.now() : normalizedTimeoutMs));
291
+ const finishWindow = () => {
292
+ const record = this.get(selfAid, requestId);
293
+ if (!record || ['completed', 'failed', 'unknown'].includes(record.state))
294
+ return record;
295
+ return this.update(selfAid, requestId, {
296
+ state: record.responseMode === 'all_devices' && record.responses?.length ? 'completed' : 'pending',
297
+ });
298
+ };
205
299
  if (waitMs === 0)
206
- return this.update(selfAid, requestId, { state: 'pending' });
300
+ return finishWindow();
207
301
  return new Promise(resolve => {
208
302
  const key = this.key(selfAid, requestId);
209
303
  const callback = (record) => { clearTimeout(timer); resolve(record); };
@@ -215,7 +309,7 @@ export class AunRequestRegistry {
215
309
  return;
216
310
  if (this.waiters.get(key)?.size === 0)
217
311
  this.waiters.delete(key);
218
- resolve(this.update(selfAid, requestId, { state: 'pending' }));
312
+ resolve(finishWindow());
219
313
  }, waitMs);
220
314
  });
221
315
  }