evolcore 0.0.47 → 0.0.48

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 (218) hide show
  1. package/CHANGELOG.md +56 -1
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +139 -39
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +34 -17
  8. package/dist/agents/codex-runner.js +31 -16
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/service-proxy.js +4 -2
  14. package/dist/build-identity.json +1 -0
  15. package/dist/channels/aun.js +81 -24
  16. package/dist/channels/daemon.js +9 -25
  17. package/dist/cli/aun-commands.js +86 -51
  18. package/dist/cli/code-stats.js +19 -8
  19. package/dist/cli/command-log.js +1 -1
  20. package/dist/cli/daemon-commands.js +44 -43
  21. package/dist/cli/directory.js +7 -1
  22. package/dist/cli/ecmsg-gateway.js +5 -2
  23. package/dist/cli/index.js +2 -8
  24. package/dist/cli/init-channel.js +4 -6
  25. package/dist/cli/init.js +72 -50
  26. package/dist/cli/invoke-command.js +1 -1
  27. package/dist/cli/provider-command.js +74 -13
  28. package/dist/cli/role.js +61 -17
  29. package/dist/cli/stats.js +3 -3
  30. package/dist/cli/thread-command.js +16 -51
  31. package/dist/config/boot-log.js +3 -9
  32. package/dist/config/builtin-roles.js +5 -7
  33. package/dist/config/config-manager.js +2 -6
  34. package/dist/config/daemon-services.js +30 -3
  35. package/dist/config/gateway-config.js +2 -2
  36. package/dist/config/invoke-ipc-service.js +6 -4
  37. package/dist/config/peer-bind-code.js +3 -4
  38. package/dist/config/peer-book-store.js +62 -229
  39. package/dist/config/peer-book.js +26 -27
  40. package/dist/config/peer-role-resolver.js +16 -1
  41. package/dist/config/provider-identity-migration.js +4 -1
  42. package/dist/config/provider-ipc-service.js +56 -11
  43. package/dist/config/provider-menu-request.js +24 -5
  44. package/dist/config/provider-templates.js +127 -0
  45. package/dist/config/providers-config.js +59 -8
  46. package/dist/config/providers-management.js +467 -49
  47. package/dist/config/role-command-service.js +248 -1
  48. package/dist/config/schema-migration.js +105 -4
  49. package/dist/core/agent-application-service.js +6 -1
  50. package/dist/core/agent-runtime.js +4 -0
  51. package/dist/core/auth/agent-delegation.js +2 -1
  52. package/dist/core/auth/auth-gateway.js +2 -1
  53. package/dist/core/auth/delegation-authorization.js +3 -0
  54. package/dist/core/auth/operation-authorizer.js +25 -0
  55. package/dist/core/auth/operation-catalog.js +28 -64
  56. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  57. package/dist/core/channel-loader.js +18 -0
  58. package/dist/core/command/agent-control.js +32 -0
  59. package/dist/core/command/command-handler.js +81 -85
  60. package/dist/core/command/menu-catalog.js +1 -0
  61. package/dist/core/command/menu-handler.js +61 -149
  62. package/dist/core/command/menu-protocol.js +7 -1
  63. package/dist/core/command/provider-menu.js +13 -3
  64. package/dist/core/command/role-menu.js +47 -23
  65. package/dist/core/command/slash-handler.js +26 -43
  66. package/dist/core/command/team-workspace-items.js +81 -12
  67. package/dist/core/command/team-workspace-team.js +9 -71
  68. package/dist/core/command/topic-slash.js +9 -30
  69. package/dist/core/daemon-bootstrap.js +8 -1
  70. package/dist/core/daemon-control.js +7 -7
  71. package/dist/core/evolagent-registry.js +14 -1
  72. package/dist/core/file-integrity/store.js +2 -0
  73. package/dist/core/handoff/runtime.js +37 -1
  74. package/dist/core/inference/text-inference.js +3 -1
  75. package/dist/core/initialization/service.js +11 -6
  76. package/dist/core/interaction-router.js +3 -0
  77. package/dist/core/invoke/executors/text.js +72 -19
  78. package/dist/core/ipc-registration.js +2 -1
  79. package/dist/core/message/aun-ipc-sender.js +165 -55
  80. package/dist/core/message/im-renderer.js +1 -1
  81. package/dist/core/message/message-bridge.js +51 -334
  82. package/dist/core/message/message-log.js +5 -0
  83. package/dist/core/message/message-queue.js +22 -0
  84. package/dist/core/message/message-utils.js +8 -0
  85. package/dist/core/message/response-engine.js +429 -116
  86. package/dist/core/message/send-routing.js +5 -1
  87. package/dist/core/model/catalog-service.js +31 -11
  88. package/dist/core/model/model-capabilities.js +22 -4
  89. package/dist/core/model/model-catalog.js +1 -0
  90. package/dist/core/ownership/owner-resolver.js +328 -50
  91. package/dist/core/permission/protected-paths.js +6 -6
  92. package/dist/core/relation/peer-identity.js +23 -1
  93. package/dist/core/relation/same-owner-proof.js +81 -112
  94. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  95. package/dist/core/session/session-file-health.js +13 -7
  96. package/dist/core/session/session-fs-store.js +91 -35
  97. package/dist/core/session/session-manager.js +68 -24
  98. package/dist/core/session/session-mapper.js +14 -34
  99. package/dist/core/session/session-transcript.js +5 -1
  100. package/dist/core/task/task-activity-store.js +84 -0
  101. package/dist/core/task/task-recovery-service.js +12 -0
  102. package/dist/core/thread/command-parser.js +7 -12
  103. package/dist/core/thread/thread-context-storage.js +3 -2
  104. package/dist/core/thread/thread-operation.js +2 -13
  105. package/dist/core/thread/thread-service.js +15 -46
  106. package/dist/directory/owner-directory-admission.js +1 -1
  107. package/dist/directory/owner-directory-cache.js +45 -28
  108. package/dist/directory/owner-directory-markdown.js +13 -1
  109. package/dist/directory/owner-directory-query-operation.js +29 -3
  110. package/dist/directory/owner-directory-remarks.js +11 -3
  111. package/dist/eck/message-renderer.js +84 -24
  112. package/dist/ecweb/basic-settings-service.js +3 -1
  113. package/dist/ecweb/message-context-service.js +1 -1
  114. package/dist/ecweb/pairing.js +4 -3
  115. package/dist/ecweb/providers-service.js +26 -1
  116. package/dist/ecweb/runtime/lifecycle.js +18 -8
  117. package/dist/ecweb/runtime/proxy-access.js +74 -0
  118. package/dist/ecweb/runtime/supervisor.js +4 -2
  119. package/dist/event-center/registry.js +13 -2
  120. package/dist/event-center/runtime.js +103 -11
  121. package/dist/event-center/script-runner.js +5 -5
  122. package/dist/index.js +92 -59
  123. package/dist/ipc.js +13 -2
  124. package/dist/outputs/events.js +62 -0
  125. package/dist/outputs/protocol.js +102 -0
  126. package/dist/outputs/service.js +279 -0
  127. package/dist/paths.js +3 -0
  128. package/dist/proxy/manager.js +43 -13
  129. package/dist/services/index.js +89 -4
  130. package/dist/services/ipc-operation.js +4 -15
  131. package/dist/services/pack-manager.js +12 -1
  132. package/dist/services/router.js +21 -6
  133. package/dist/services/script-runner.js +5 -4
  134. package/dist/services/validation.js +1 -1
  135. package/dist/stats/budget.js +1 -1
  136. package/dist/stats/db.js +19 -0
  137. package/dist/stats/index.js +1 -1
  138. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  139. package/dist/stats/normalizer.js +2 -0
  140. package/dist/stats/query.js +35 -27
  141. package/dist/stats/role-budget.js +5 -2
  142. package/dist/stats/writer.js +10 -6
  143. package/dist/trigger/audit.js +7 -0
  144. package/dist/trigger/authorization.js +105 -11
  145. package/dist/trigger/feedback.js +10 -0
  146. package/dist/trigger/history.js +37 -11
  147. package/dist/trigger/ipc-service.js +12 -1
  148. package/dist/trigger/manager.js +1 -0
  149. package/dist/trigger/scheduler.js +7 -5
  150. package/dist/trigger/script-executor.js +2 -1
  151. package/dist/trigger/script-sandbox.js +9 -3
  152. package/dist/trigger/validation.js +22 -0
  153. package/dist/utils/cross-platform.js +73 -26
  154. package/dist/utils/error-dict.json +94 -4
  155. package/dist/utils/error-utils.js +27 -4
  156. package/dist/utils/evolcore-version.js +36 -65
  157. package/dist/utils/msg-diag.js +1 -0
  158. package/dist/utils/process-introspect.js +12 -7
  159. package/dist/utils/process-tree.js +50 -2
  160. package/dist/utils/windows-shell-trust.js +2 -0
  161. package/dist/workbench/protocol.js +80 -0
  162. package/dist/workbench/service.js +359 -0
  163. package/ecagent/dist/types.d.ts +6 -2
  164. package/kits/docs/context-assembly.md +1 -1
  165. package/kits/docs/evolcore/INDEX.md +2 -2
  166. package/kits/docs/evolcore/config.md +12 -0
  167. package/kits/docs/evolcore/directory.md +22 -3
  168. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  169. package/kits/docs/evolcore/model.md +10 -0
  170. package/kits/docs/evolcore/peer.md +19 -65
  171. package/kits/docs/evolcore/provider.md +123 -3
  172. package/kits/docs/evolcore/role.md +80 -0
  173. package/kits/docs/evolcore/services.md +6 -6
  174. package/kits/docs/evolcore/team-workspace.md +1 -1
  175. package/kits/docs/evolcore/thread-chain.md +14 -15
  176. package/kits/docs/evolcore/tool-authorization.md +5 -0
  177. package/kits/docs/evolcore/trigger.md +10 -0
  178. package/kits/eck_message_manifest.json +12 -0
  179. package/kits/provider-templates.json +1213 -0
  180. package/kits/rules/04-relation.md +3 -3
  181. package/kits/schemas/_meta.json +14 -2
  182. package/kits/schemas/contact-book.schema.4.json +52 -0
  183. package/kits/schemas/providers.schema.3.json +200 -0
  184. package/kits/skills/.switches.json +4 -0
  185. package/kits/skills/ability/references/calling.md +1 -1
  186. package/kits/skills/ec-group/SKILL.md +2 -2
  187. package/kits/skills/ec-identity/SKILL.md +19 -72
  188. package/kits/skills/ec-provider/SKILL.md +221 -0
  189. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  190. package/kits/skills/ec-trigger/SKILL.md +1 -1
  191. package/kits/skills/thread-ops/SKILL.md +34 -21
  192. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  193. package/kits/templates/message-fragments/group-batch.md +1 -1
  194. package/kits/templates/message-fragments/inject-default.md +1 -1
  195. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  196. package/kits/templates/message-fragments/item-group.md +1 -1
  197. package/kits/templates/message-fragments/item-private.md +1 -1
  198. package/kits/templates/message-fragments/thread-context.md +1 -1
  199. package/kits/templates/message-fragments/trigger-session.md +1 -1
  200. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  201. package/kits/templates/roles/admin.json +2 -19
  202. package/kits/templates/roles/member.json +0 -3
  203. package/kits/templates/system-fragments/baseagent.md +6 -0
  204. package/kits/templates/system-fragments/commands.md +3 -3
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +1 -1
  207. package/kits/templates/system-fragments/thread.md +6 -5
  208. package/package.json +6 -4
  209. package/scripts/agent-template/inspect.mjs +4 -1
  210. package/scripts/agent-template/shared/common.mjs +2 -3
  211. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  212. package/scripts/agent-template/shared/template-package.mjs +9 -2
  213. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  214. package/scripts/agent-template/team-pack.mjs +6 -3
  215. package/dist/cli/peer.js +0 -127
  216. package/dist/config/peer-operation-service.js +0 -132
  217. package/dist/config/peer-request-service.js +0 -532
  218. package/dist/core/command/connect-menu.js +0 -624
@@ -6,7 +6,7 @@ import { encodePath } from '../../utils/cross-platform.js';
6
6
  import { readRunnerEventSummary } from './runner-event-summary.js';
7
7
  import { isInternalInjectedUserMessage, isToolResultMessage } from './session-transcript.js';
8
8
  import { chatDirPath, generateSessionId, formatTimestamp, atomicWriteJson, atomicWriteText, appendJsonl, appendJsonlDurable, fsyncJsonlFile, readJsonFile, readLastJsonlLine, readLastJsonlLineStrict, readAllJsonlLines, scanChatDirs, scanMetaFiles, ensureChatDir, readThreadIndex, writeThreadIndex, compactJsonlTail, SESSION_META_COMPACT_POLICY, readLastJsonlLineAsync, } from './session-fs-store.js';
9
- import { sessionToFile, fileToSession, formatSessionKey, DEFAULT_THREAD_ID, normalizeTopicLabel, normalizeTopicStatus, } from './session-mapper.js';
9
+ import { sessionToFile, fileToSession, formatSessionKey, DEFAULT_THREAD_ID, normalizeTopicStatus, } from './session-mapper.js';
10
10
  import { tryParseChannelKey } from '../channel-loader.js';
11
11
  import { isMainSession, isMainSessionThreadId, isTopicSession, isTopicThreadId, mainTopicPeer, safeFormatMainTopicId, sessionLocalTopicId, sessionTopicThreadId, } from '../thread/topic-id.js';
12
12
  import { isSystemControlChannel } from '../system-channels.js';
@@ -40,7 +40,10 @@ const MAX_FORK_HISTORY_ITEM_TEXT_BYTES = 16 * 1024;
40
40
  const MAX_FORK_HISTORY_TOOL_VALUE_BYTES = 8 * 1024;
41
41
  const MAX_FORK_HISTORY_PAGE_JSON_BYTES = 128 * 1024;
42
42
  function cleanForkHistoryUserText(text) {
43
- let cleaned = text.replace(/^【新消息插入】\s*/, '')
43
+ // 历史兼容:旧格式把整段消息包进「【新消息插入】…【请根据前后消息酌情处理】」,
44
+ // 会话记录里已写入这类文本,必须继续剥掉才会得到干净的 fork 历史。
45
+ // 新格式的标记由模板渲染成单独一行(message-fragments/interrupt-insert.md),同样在此剥掉。
46
+ let cleaned = text.replace(/^【(?:新消息插入|中断后新消息)[^】]*】[ \t]*\n?/, '')
44
47
  .replace(/\s*【(?:请无视之前中断继续处理|请根据前后消息酌情处理)】$/, '').trim();
45
48
  if (cleaned.startsWith('‹')) {
46
49
  const newline = cleaned.indexOf('\n');
@@ -788,7 +791,6 @@ export class SessionManager {
788
791
  session.agentSessionId = latestId;
789
792
  session.baseagent = latest.baseagent;
790
793
  if (!opts?.topicMutation) {
791
- session.label = latest.label;
792
794
  session.topicStatus = latest.topicStatus;
793
795
  }
794
796
  // Merge metadata at field level as well. A caller can hold a stale
@@ -1375,7 +1377,7 @@ export class SessionManager {
1375
1377
  return result;
1376
1378
  }
1377
1379
  // ─── Session lifecycle ───
1378
- async getOrCreateSession(channel, channelId, defaultProjectPath, threadId, metadata, name, userId, chatType, baseagent, selfAID, channelType, peerType, identity, label, topicStatus) {
1380
+ async getOrCreateSession(channel, channelId, defaultProjectPath, threadId, metadata, name, userId, chatType, baseagent, selfAID, channelType, peerType, identity, topicStatus) {
1379
1381
  if (isSystemControlChannel(channel) || isSystemControlChannel(channelType)) {
1380
1382
  throw new Error(`[SessionManager] system control channel is sessionless. channel="${channel}"`);
1381
1383
  }
@@ -1390,7 +1392,7 @@ export class SessionManager {
1390
1392
  const identityConversationId = chatType === 'group' ? (metadata?.groupId || channelId) : userId;
1391
1393
  // 主话题的 id(`main:<aid>:<aid>`)不是话题会话目录键:它必须落到 chat 根目录。
1392
1394
  if (isTopicThreadId(threadId)) {
1393
- const session = this.getOrCreateThreadSession(channel, channelId, threadId, defaultProjectPath, metadata, name, baseagent, selfAID, channelType, peerType, chatType, label, topicStatus);
1395
+ const session = this.getOrCreateThreadSession(channel, channelId, threadId, defaultProjectPath, metadata, name, baseagent, selfAID, channelType, peerType, chatType, topicStatus);
1394
1396
  session.identity = identity ?? this.resolveIdentity(channel, userId, chatType, identityConversationId);
1395
1397
  return session;
1396
1398
  }
@@ -1693,7 +1695,7 @@ export class SessionManager {
1693
1695
  current.metadata = metadata;
1694
1696
  this.persistSession(current, 'sync', { turnStateMutation: true });
1695
1697
  }
1696
- getOrCreateThreadSession(channel, channelId, threadId, defaultProjectPath, metadata, name, baseagent, selfAID, channelType, peerType, chatType, label, topicStatus) {
1698
+ getOrCreateThreadSession(channel, channelId, threadId, defaultProjectPath, metadata, name, baseagent, selfAID, channelType, peerType, chatType, topicStatus) {
1697
1699
  const topicMetadata = { ...(metadata ?? {}) };
1698
1700
  delete topicMetadata.sessionLoop;
1699
1701
  delete topicMetadata.sessionLoopOnce;
@@ -1774,8 +1776,7 @@ export class SessionManager {
1774
1776
  chatType: effectiveChatType,
1775
1777
  metadata: topicMetadata,
1776
1778
  name: name || '话题会话',
1777
- label: normalizeTopicLabel(label),
1778
- topicStatus: topicStatus ? normalizeTopicStatus(topicStatus) : 'pending',
1779
+ topicStatus: topicStatus ? normalizeTopicStatus(topicStatus) : 'active',
1779
1780
  createdAt: Date.now(),
1780
1781
  updatedAt: Date.now(),
1781
1782
  };
@@ -1796,8 +1797,7 @@ export class SessionManager {
1796
1797
  channelType: channelType ?? 'aun',
1797
1798
  peerKind: effectiveChatType === 'group' ? 'group' : 'private',
1798
1799
  name: session.name,
1799
- label: normalizeTopicLabel(label) ?? null,
1800
- topicStatus: session.topicStatus ?? 'pending',
1800
+ topicStatus: session.topicStatus ?? 'active',
1801
1801
  now: session.createdAt ?? Date.now(),
1802
1802
  });
1803
1803
  this.eventBus.publish({
@@ -1847,7 +1847,6 @@ export class SessionManager {
1847
1847
  channelType: input.channelType,
1848
1848
  peerKind: input.peerKind,
1849
1849
  name: input.name || '话题会话',
1850
- label: input.label ?? null,
1851
1850
  topicStatus: input.topicStatus,
1852
1851
  createdAt: input.now,
1853
1852
  lastActiveAt: input.now,
@@ -2223,15 +2222,14 @@ export class SessionManager {
2223
2222
  this.persistSession(current, 'sync');
2224
2223
  return true;
2225
2224
  }
2226
- async setTopicLabel(sessionId, label) {
2227
- const normalized = normalizeTopicLabel(label);
2228
- const loaded = this.loadSessionForUpdate(sessionId);
2229
- if (!loaded || !isTopicSession(loaded.current))
2230
- return false;
2231
- loaded.current.label = normalized;
2232
- this.persistSession(loaded.current, 'sync', { topicMutation: true });
2233
- return true;
2234
- }
2225
+ /**
2226
+ * 话题状态的唯一写入口。
2227
+ *
2228
+ * 会话文件与 agent 级索引是两份数据,`ec thread list` 只读索引。所有状态写入
2229
+ * 都走这里(CLI 经 `ThreadService.statusThread` 会多写一次索引;菜单 action 和
2230
+ * 入站的 `closed → active` 回退只经过这里),因此由本方法兜底同步索引,
2231
+ * 否则列表会一直显示旧状态直到 `rebuild-index`。
2232
+ */
2235
2233
  async setTopicStatus(sessionId, status) {
2236
2234
  const normalized = normalizeTopicStatus(status);
2237
2235
  const loaded = this.loadSessionForUpdate(sessionId);
@@ -2239,8 +2237,47 @@ export class SessionManager {
2239
2237
  return false;
2240
2238
  loaded.current.topicStatus = normalized;
2241
2239
  this.persistSession(loaded.current, 'sync', { topicMutation: true });
2240
+ this.syncTopicStatusToAgentIndex(loaded.current, normalized);
2242
2241
  return true;
2243
2242
  }
2243
+ /**
2244
+ * 把状态写回 agent 级索引的既有条目。
2245
+ *
2246
+ * 只更新已存在的条目,**不新建**:索引条目的创建归 `upsertAgentThreadIndex`,
2247
+ * 那里会补 name / peerKind / createdAt 等字段;这里若凭空插入条目,会得到一条
2248
+ * 缺字段的残条目。找不到条目(索引尚未建立)时静默跳过,等 rebuild-index 补齐。
2249
+ */
2250
+ syncTopicStatusToAgentIndex(session, status) {
2251
+ const selfAid = session.selfAID;
2252
+ const threadId = sessionTopicThreadId(session);
2253
+ // 与 upsertAgentThreadIndex 同口径:主会话、daemon 内部会话不是真实话题。
2254
+ if (!selfAid || !threadId || !threadId.startsWith('thread-'))
2255
+ return;
2256
+ if (session.channelType === 'daemon')
2257
+ return;
2258
+ const peer = session.chatType === 'group'
2259
+ ? (session.metadata?.groupId || session.channelId)
2260
+ : session.channelId;
2261
+ if (!peer)
2262
+ return;
2263
+ try {
2264
+ const indexPath = agentThreadIndexPath(selfAid);
2265
+ const raw = readJsonFile(indexPath);
2266
+ if (!raw || !Array.isArray(raw.threads))
2267
+ return;
2268
+ const entry = raw.threads.find((t) => t.threadId === threadId
2269
+ && String(t.peer ?? '').toLowerCase() === peer.toLowerCase());
2270
+ if (!entry || entry.topicStatus === status)
2271
+ return;
2272
+ entry.topicStatus = status;
2273
+ entry.lastActiveAt = Date.now();
2274
+ atomicWriteJson(indexPath, raw);
2275
+ }
2276
+ catch (error) {
2277
+ // 索引是派生数据:写失败不能连累已经成功的会话状态写入。
2278
+ logger.warn(`[SessionManager] 话题状态同步索引失败 session=${session.id}: ${error}`);
2279
+ }
2280
+ }
2244
2281
  async unbindSession(sessionId) {
2245
2282
  const found = this.findSessionFileById(sessionId);
2246
2283
  if (!found)
@@ -2537,8 +2574,7 @@ export class SessionManager {
2537
2574
  agentSessionId: forkedAgentSessionId,
2538
2575
  metadata,
2539
2576
  name: options.name || `${sourceSession.name || '会话'} · 第 ${options.sourceTurn} 轮`,
2540
- label: normalizeTopicLabel(options.label === undefined ? sourceSession.label : options.label),
2541
- topicStatus: options.topicStatus ? normalizeTopicStatus(options.topicStatus) : 'pending',
2577
+ topicStatus: options.topicStatus ? normalizeTopicStatus(options.topicStatus) : 'active',
2542
2578
  createdAt: now,
2543
2579
  updatedAt: now,
2544
2580
  };
@@ -2701,11 +2737,13 @@ export class SessionManager {
2701
2737
  return { turns: adapter.getFileInfo(projectPath, agentSessionId, agentAid).turns,
2702
2738
  firstMessage: adapter.readFirstMessage(projectPath, agentSessionId, agentAid) };
2703
2739
  }
2704
- readSessionLastUserMessage(projectPath, agentSessionId, baseagent, agentAid) {
2740
+ async readSessionLastUserMessage(projectPath, agentSessionId, baseagent, agentAid) {
2705
2741
  const adapter = this.getFileAdapter(baseagent);
2706
2742
  if (!adapter)
2707
2743
  return null;
2708
- return adapter.readLastUserMessage(projectPath, agentSessionId, agentAid);
2744
+ return adapter.readLastUserMessageAsync
2745
+ ? adapter.readLastUserMessageAsync(projectPath, agentSessionId, agentAid)
2746
+ : adapter.readLastUserMessage(projectPath, agentSessionId, agentAid);
2709
2747
  }
2710
2748
  getSessionFileInfo(projectPath, agentSessionId, baseagent, agentAid) {
2711
2749
  if (!baseagent) {
@@ -2719,6 +2757,12 @@ export class SessionManager {
2719
2757
  }
2720
2758
  return adapter.getFileInfo(projectPath, agentSessionId, agentAid);
2721
2759
  }
2760
+ async getSessionFileInfoAsync(projectPath, agentSessionId, baseagent, agentAid) {
2761
+ const adapter = this.getFileAdapter(baseagent);
2762
+ return adapter?.getFileInfoAsync
2763
+ ? adapter.getFileInfoAsync(projectPath, agentSessionId, agentAid)
2764
+ : this.getSessionFileInfo(projectPath, agentSessionId, baseagent, agentAid);
2765
+ }
2722
2766
  getRunnerTaskHistory(sessionId) {
2723
2767
  return readRunnerEventSummary(resolvePaths().logs, sessionId);
2724
2768
  }
@@ -2,21 +2,19 @@ import { formatTimestamp } from './session-fs-store.js';
2
2
  import { classifyThreadId, sessionThreadKind } from '../thread/topic-id.js';
3
3
  /** Default topic component used by the stable session routing key. */
4
4
  export const DEFAULT_THREAD_ID = 'main';
5
- export function normalizeTopicLabel(value) {
6
- if (value === undefined || value === null)
7
- return undefined;
8
- if (typeof value !== 'string')
9
- throw new Error('label 必须是字符串或 null');
10
- const label = value.trim();
11
- if (label.length > 100 || /[\x00-\x1F\x7F]/.test(label)) {
12
- throw new Error('label 最多 100 个字符,且不能包含控制字符');
13
- }
14
- return label || undefined;
15
- }
5
+ /**
6
+ * 话题状态只有三态:`active`(默认)、`closed`(模型判定讨论完毕,收到新消息自动回退)、
7
+ * `archived`(不可响应)。
8
+ *
9
+ * 旧数据里的 `pending` / `in_progress` / `completed` 一律读作 `active`:它们曾经把
10
+ * 任务进度混进话题状态,现在进度由 summary 承载、分类由话题名承载。
11
+ */
16
12
  export function normalizeTopicStatus(value) {
17
- if (value === 'pending' || value === 'in_progress' || value === 'completed' || value === 'archived')
13
+ if (value === 'active' || value === 'closed' || value === 'archived')
18
14
  return value;
19
- throw new Error('topicStatus 必须是 pending、in_progress、completed 或 archived');
15
+ if (value === 'pending' || value === 'in_progress' || value === 'completed')
16
+ return 'active';
17
+ throw new Error('topicStatus 必须是 active、closed 或 archived');
20
18
  }
21
19
  /** Resolve the public archived query flag while keeping omitted values backward compatible. */
22
20
  export function resolveTopicArchiveFilter(value) {
@@ -28,26 +26,11 @@ export function resolveTopicArchiveFilter(value) {
28
26
  return 'all';
29
27
  throw new Error('archived 必须是布尔值或 "all"');
30
28
  }
31
- export function readTopicLabel(payload) {
32
- if (!payload || typeof payload !== 'object')
33
- return undefined;
34
- const fields = payload;
35
- try {
36
- const label = fields.label === undefined ? fields.lable : fields.label;
37
- return label === '归档' && fields.label === undefined ? undefined : normalizeTopicLabel(label);
38
- }
39
- catch {
40
- return undefined;
41
- }
42
- }
43
29
  export function readTopicStatus(payload) {
44
30
  if (!payload || typeof payload !== 'object')
45
31
  return undefined;
46
32
  try {
47
- const fields = payload;
48
- if (fields.topicStatus === undefined && fields.lable === '归档')
49
- return 'archived';
50
- return normalizeTopicStatus(fields.topicStatus);
33
+ return normalizeTopicStatus(payload.topicStatus);
51
34
  }
52
35
  catch {
53
36
  return undefined;
@@ -123,8 +106,7 @@ export function sessionToFile(session) {
123
106
  projectPath: session.projectPath,
124
107
  agentSessionId: session.agentSessionId ?? null,
125
108
  name: session.name ?? null,
126
- ...(session.label ? { label: session.label } : {}),
127
- ...(kind.kind === 'topic' ? { topicStatus: session.topicStatus ?? 'pending' } : {}),
109
+ ...(kind.kind === 'topic' ? { topicStatus: session.topicStatus ?? 'active' } : {}),
128
110
  activeTask: session.processingState ?? null,
129
111
  metadata,
130
112
  createdAt: session.createdAt,
@@ -179,11 +161,9 @@ export function fileToSession(file) {
179
161
  projectPath: file.projectPath,
180
162
  agentSessionId: file.agentSessionId ?? undefined,
181
163
  name: file.name ?? undefined,
182
- ...(isTopic && (file.label || (file.lable && file.lable !== '归档'))
183
- ? { label: file.label || file.lable } : {}),
184
164
  ...(isTopic ? { topicStatus: file.topicStatus
185
165
  ? normalizeTopicStatus(file.topicStatus)
186
- : file.lable === '归档' ? 'archived' : 'pending' } : {}),
166
+ : 'active' } : {}),
187
167
  processingState: file.activeTask ?? undefined,
188
168
  metadata,
189
169
  createdAt: file.createdAt,
@@ -50,7 +50,11 @@ function extractText(message) {
50
50
  }
51
51
  function extractUserText(message) {
52
52
  let text = extractText(message);
53
- text = text.replace(/^【新消息插入】\s*/, '')
53
+ // 历史兼容:旧格式把整段消息包进「【新消息插入】…【请根据前后消息酌情处理】」,
54
+ // 会话记录里已写入这类文本,解析时必须剥掉。「请无视之前中断继续处理」是更早的
55
+ // 变体,现已无代码生成,仅旧记录中存在。新格式的标记由模板渲染成单独一行
56
+ // (见 message-fragments/interrupt-insert.md),同样在此剥掉,避免污染摘要与标题。
57
+ text = text.replace(/^【(?:新消息插入|中断后新消息)[^】]*】[ \t]*\n?/, '')
54
58
  .replace(/\s*【(?:请无视之前中断继续处理|请根据前后消息酌情处理)】$/, '').trim();
55
59
  if (text.startsWith('‹')) {
56
60
  const newline = text.indexOf('\n');
@@ -5,6 +5,28 @@ import { agentTaskActivityDir } from '../../paths.js';
5
5
  import { MENU_RESPONSE_MAX_BYTES, MENU_RESPONSE_SAFETY_MARGIN_BYTES } from '../command/menu-protocol.js';
6
6
  import { TaskImageResources } from './task-image-resources.js';
7
7
  import { logger } from '../../utils/logger.js';
8
+ const mutationListeners = new Set();
9
+ /** Synchronous after the atomic disk commit, so projections never observe an older status. */
10
+ export function onTaskActivityMutation(listener) {
11
+ mutationListeners.add(listener);
12
+ return () => { mutationListeners.delete(listener); };
13
+ }
14
+ function committed(selfAid, taskId, meta) {
15
+ for (const listener of mutationListeners) {
16
+ try {
17
+ listener({ selfAid, taskId, ...(meta ? { meta: clone(meta) } : {}) });
18
+ }
19
+ catch (error) {
20
+ logger.warn(`[TaskActivityStore] projection notification failed: ${String(error)}`);
21
+ }
22
+ }
23
+ }
24
+ export function taskActivityTitle(value) {
25
+ if (typeof value !== 'string')
26
+ return undefined;
27
+ const label = Array.from(value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ').replace(/\s+/g, ' ').trim()).slice(0, 200).join('');
28
+ return label && !['默认会话', '话题会话', 'Default session', 'Topic session'].includes(label) ? label : undefined;
29
+ }
8
30
  const LIST_TEXT_BYTES = 1024;
9
31
  const LIST_LIMIT = 100;
10
32
  const MARKER = '[中间内容已省略]';
@@ -131,9 +153,12 @@ export class TaskActivityStore {
131
153
  taskStatus: input.taskStatus ?? 'running',
132
154
  createdAt: now,
133
155
  updatedAt: now,
156
+ ...(input.threadId ? { threadId: input.threadId } : {}),
157
+ ...(taskActivityTitle(input.title) ? { title: taskActivityTitle(input.title) } : {}),
134
158
  };
135
159
  fs.mkdirSync(taskDir(this.selfAid), { recursive: true, mode: 0o700 });
136
160
  writeAtomic(taskFile(this.selfAid, input.taskId), `${metaLine(meta)}\n`);
161
+ committed(this.selfAid, input.taskId, meta);
137
162
  return meta;
138
163
  }
139
164
  createTask(input) {
@@ -188,6 +213,7 @@ export class TaskActivityStore {
188
213
  throw new Error('Task metadata unavailable');
189
214
  const updatedMeta = { ...meta, updatedAt: Date.now() };
190
215
  writeAtomic(taskFile(this.selfAid, input.taskId), `${metaLine(updatedMeta)}\n${loaded.records.map(item => JSON.stringify(item)).join('\n')}${loaded.records.length ? '\n' : ''}${JSON.stringify(record)}\n`);
216
+ committed(this.selfAid, input.taskId, updatedMeta);
191
217
  return record;
192
218
  }
193
219
  updateStatus(taskId, status) {
@@ -197,6 +223,63 @@ export class TaskActivityStore {
197
223
  const meta = { ...loaded.meta, taskStatus: status, updatedAt: Date.now() };
198
224
  const lines = [metaLine(meta), ...loaded.records.map(record => JSON.stringify(record))];
199
225
  writeAtomic(taskFile(this.selfAid, taskId), `${lines.join('\n')}\n`);
226
+ committed(this.selfAid, taskId, meta);
227
+ }
228
+ /** One startup rebuild. Reads only bounded metadata heads, never task bodies. */
229
+ async listMeta(limit = 2048) {
230
+ const bounded = Math.min(2048, Math.max(1, Math.floor(limit)));
231
+ const items = [];
232
+ let scanned = 0;
233
+ let truncated = false;
234
+ let dir;
235
+ try {
236
+ dir = await fs.promises.opendir(taskDir(this.selfAid));
237
+ }
238
+ catch (error) {
239
+ if (error.code === 'ENOENT')
240
+ return { items, truncated };
241
+ throw error;
242
+ }
243
+ for await (const entry of dir) {
244
+ if (++scanned > bounded) {
245
+ truncated = true;
246
+ break;
247
+ }
248
+ if (!entry.isFile() || !entry.name.endsWith('.jsonl'))
249
+ continue;
250
+ let handle;
251
+ try {
252
+ const candidate = path.join(taskDir(this.selfAid), entry.name);
253
+ // Do not follow a link swapped in between readdir and open.
254
+ const before = await fs.promises.lstat(candidate);
255
+ if (!before.isFile() || before.isSymbolicLink())
256
+ continue;
257
+ handle = await fs.promises.open(candidate, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
258
+ const head = Buffer.alloc(8192);
259
+ const { bytesRead } = await handle.read(head, 0, head.length, 0);
260
+ const text = head.subarray(0, bytesRead).toString('utf8');
261
+ const end = text.indexOf('\n');
262
+ if (end < 0) {
263
+ truncated = true;
264
+ continue;
265
+ }
266
+ const meta = JSON.parse(text.slice(0, end));
267
+ if (meta.type !== 'meta' || meta.version !== 1 || meta.selfAid !== this.selfAid
268
+ || typeof meta.taskId !== 'string' || !/^task-[A-Za-z0-9._:-]+$/.test(meta.taskId)
269
+ || entry.name !== `${safeTaskId(meta.taskId)}.jsonl`
270
+ || !Number.isSafeInteger(meta.createdAt) || !Number.isSafeInteger(meta.updatedAt)
271
+ || meta.createdAt < 0 || meta.updatedAt < 0)
272
+ continue;
273
+ items.push(meta);
274
+ }
275
+ catch {
276
+ truncated = true;
277
+ }
278
+ finally {
279
+ await handle?.close();
280
+ }
281
+ }
282
+ return { items, truncated };
200
283
  }
201
284
  readList(taskId, offset, limit) {
202
285
  const loaded = readJsonl(this.selfAid, taskId);
@@ -265,5 +348,6 @@ export class TaskActivityStore {
265
348
  deleteTask(taskId) {
266
349
  fs.rmSync(taskFile(this.selfAid, taskId), { force: true });
267
350
  new TaskImageResources(this.selfAid).deleteTask(taskId);
351
+ committed(this.selfAid, taskId);
268
352
  }
269
353
  }
@@ -1,3 +1,5 @@
1
+ import { bindTriggerExecutionIdentity } from '../../trigger/authorization.js';
2
+ import { normalizeTriggerDefinition } from '../../trigger/validation.js';
1
3
  import { replyContextFromSession } from '../message/message-utils.js';
2
4
  import { sessionTopicThreadId } from '../thread/topic-id.js';
3
5
  export const TASK_RECOVERY_PROMPT = '继续当前会话尚未完成的任务。先核对最新用户指令、已有结果和任务状态;若已完成、用户已停止或正在等待必要输入/审批,则不要重复执行。对可能已产生副作用的步骤先核实结果,再继续未完成的工作。';
@@ -186,6 +188,16 @@ export class TaskRecoveryService {
186
188
  };
187
189
  // Keep the completion promise alive for Trigger cancellation, but release
188
190
  // the dequeue gate as soon as admission is durable (never await the run).
191
+ if (trigger && session.selfAID) {
192
+ await bindTriggerExecutionIdentity(message, normalizeTriggerDefinition({
193
+ $schema_version: 3.1, id: trigger.triggerId, agentAid: session.selfAID, name: 'task-recovery',
194
+ origin: { channelKey: message.channel, channelType, channelId: session.channelId,
195
+ peerId, session: sessionTopicThreadId(session) ? 'thread' : 'main',
196
+ delivery: session.chatType === 'group' ? { chatType: 'group', groupId: session.channelId } : { chatType: 'private' } },
197
+ source: { type: 'once' }, execution: { type: 'target_session', prompt: TASK_RECOVERY_PROMPT },
198
+ feedback: { strategy: 'origin' },
199
+ }));
200
+ }
189
201
  let admitted;
190
202
  const persisted = new Promise(resolve => { admitted = resolve; });
191
203
  const completion = this.deps.queue.enqueue(session.id, message, session.projectPath, {
@@ -2,13 +2,13 @@ import { isValidAid } from '../../aun/aid/validation.js';
2
2
  import { parseTimeArg, TIME_ARG_FORMATS } from '../../cli/cli-argv.js';
3
3
  import { normalizeThreadPeer } from './thread-service.js';
4
4
  import { resolveThreadRef } from './topic-id.js';
5
- const STATUSES = new Set(['pending', 'in_progress', 'completed', 'archived']);
5
+ const STATUSES = new Set(['active', 'closed', 'archived']);
6
6
  const COMMON_OPTIONS = ['--self', '--format', '--json'];
7
- const VALUE_OPTIONS = new Set(['--self', '--agent', '--format', '--name', '--label', '--status', '--sort', '--page', '--limit', '--before', '--after', '--if-rev']);
7
+ const VALUE_OPTIONS = new Set(['--self', '--agent', '--format', '--name', '--status', '--sort', '--page', '--limit', '--before', '--after', '--if-rev']);
8
8
  const OPTIONS = {
9
- peers: [], list: ['--status', '--label', '--unlabeled', '--sort', '--page', '--limit'],
9
+ peers: [], list: ['--status', '--sort', '--page', '--limit'],
10
10
  show: [], history: ['--limit', '--before', '--after'],
11
- create: ['--name', '--label', '--status', '--group', '--private'], rename: [], label: ['--clear'], status: [],
11
+ create: ['--name', '--status', '--group', '--private'], rename: [], status: [],
12
12
  delete: [], 'rebuild-index': ['--check', '--agent'], 'check-index': ['--agent'],
13
13
  'summary-show': [], 'summary-set': ['--name', '--if-rev'], 'summary-log': [], 'summary-clear': [],
14
14
  };
@@ -77,7 +77,7 @@ export function resolveThreadCommandArgv(argv, context = {}) {
77
77
  if (sort !== undefined && sort !== 'recent' && sort !== 'created')
78
78
  throw new Error('Invalid sort order');
79
79
  const maximum = ['peers', 'rebuild-index', 'check-index'].includes(command) ? 0
80
- : ['rename', 'status', 'label'].includes(command) ? 2 : command === 'summary-set' ? Infinity : 1;
80
+ : ['rename', 'status'].includes(command) ? 2 : command === 'summary-set' ? Infinity : 1;
81
81
  const minimum = maximum === 0 ? 0 : ['rename', 'status', 'summary-set'].includes(command) ? 2 : 1;
82
82
  if (positional.length < minimum || positional.length > maximum)
83
83
  throw new Error('Invalid thread arguments');
@@ -112,7 +112,7 @@ export function resolveThreadCommandArgv(argv, context = {}) {
112
112
  }
113
113
  if (command === 'list')
114
114
  Object.assign(request, {
115
- status, label: text('--label'), unlabeled: options.has('--unlabeled'), sort,
115
+ status, sort,
116
116
  page: number('--page', 1), limit: number('--limit', 1),
117
117
  });
118
118
  if (command === 'history')
@@ -125,7 +125,7 @@ export function resolveThreadCommandArgv(argv, context = {}) {
125
125
  const explicitPeerKind = options.has('--group') ? 'group'
126
126
  : options.has('--private') ? 'private' : undefined;
127
127
  Object.assign(request, {
128
- name: text('--name'), label: text('--label'), topicStatus: status,
128
+ name: text('--name'), topicStatus: status,
129
129
  ...(explicitPeerKind ? { peerKind: explicitPeerKind } : {}),
130
130
  });
131
131
  }
@@ -134,11 +134,6 @@ export function resolveThreadCommandArgv(argv, context = {}) {
134
134
  throw new Error('Topic name is required');
135
135
  request.name = positional[1];
136
136
  }
137
- if (command === 'label') {
138
- if (options.has('--clear') ? positional.length !== 1 : positional.length !== 2)
139
- throw new Error('Specify a label or --clear');
140
- request.label = options.has('--clear') ? null : positional[1];
141
- }
142
137
  if (command === 'status')
143
138
  request.topicStatus = status;
144
139
  if (command === 'rebuild-index')
@@ -81,8 +81,9 @@ export class ThreadContextStorage {
81
81
  const ts = typeof m?.ts === 'number' ? m.ts : undefined;
82
82
  if (ts === undefined || ts <= afterTimestamp || ts > now)
83
83
  return false;
84
- // 只算真实对话消息
85
- return m.dir === 'in' || m.dir === 'out';
84
+ // 只算**对端发来**的消息。本端自己在这段窗口里发的汇报(dir='out')不是
85
+ // 「来源话题有新指示」,把它们算进来会让每次跨话题发送都自带一条假空洞提示。
86
+ return m.dir === 'in';
86
87
  });
87
88
  if (hits.length === 0)
88
89
  return { hasNewMessages: false, count: 0 };
@@ -87,8 +87,6 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
87
87
  selfAid,
88
88
  peer: request.peer,
89
89
  status: request.status,
90
- label: request.label ?? undefined,
91
- unlabeled: request.unlabeled,
92
90
  sort: request.sort,
93
91
  page: request.page,
94
92
  limit: request.limit,
@@ -130,10 +128,10 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
130
128
  warning = `索引异常:${result.missing} 条 session 文件缺失(数据问题),${result.stale} 条属性与文件不一致(写盘时序)`;
131
129
  }
132
130
  else if (result.missing > 0) {
133
- warning = `索引异常:${result.missing} 条 session 文件缺失,rebuild-index 后相关话题的 rename/label/status 改动将回退`;
131
+ warning = `索引异常:${result.missing} 条 session 文件缺失,rebuild-index 后相关话题的 rename/status 改动将回退`;
134
132
  }
135
133
  else if (result.stale > 0) {
136
- warning = `索引轻微不一致:${result.stale} 条话题属性(name/label/status)与 session 文件最后一行不同步,rebuild-index 可修复`;
134
+ warning = `索引轻微不一致:${result.stale} 条话题属性(name/status)与 session 文件最后一行不同步,rebuild-index 可修复`;
137
135
  }
138
136
  return { ok: true, result, indexWarning: warning };
139
137
  }
@@ -164,7 +162,6 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
164
162
  peer: request.peer,
165
163
  peerKind,
166
164
  name: request.name,
167
- label: request.label ?? undefined,
168
165
  topicStatus: request.topicStatus,
169
166
  });
170
167
  if (sendSystemMsg) {
@@ -208,14 +205,6 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
208
205
  });
209
206
  return { ok: true, result };
210
207
  }
211
- case 'label': {
212
- const { peer, threadId } = request;
213
- if (!peer || !isTopicThreadId(threadId)) {
214
- return { ok: false, code: 'MISSING_ARGS', error: '标签只适用于话题(主话题没有标签)' };
215
- }
216
- await threadService.labelThread({ selfAid, peer, threadId, label: request.label ?? null });
217
- return { ok: true };
218
- }
219
208
  case 'status': {
220
209
  const { peer, threadId } = request;
221
210
  if (!peer || !isTopicThreadId(threadId) || !request.topicStatus) {