evolcore 0.0.43-test.5 → 0.0.43-test.7

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 (259) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +281 -81
  3. package/dist/agents/baseagent-availability.js +20 -5
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +36 -3
  7. package/dist/agents/codex-runner.js +75 -8
  8. package/dist/aun/group/invite-service.js +3 -2
  9. package/dist/aun/msg/p2p.js +6 -1
  10. package/dist/aun/service-proxy.js +18 -6
  11. package/dist/channels/aun.js +306 -30
  12. package/dist/cli/agent-create.js +18 -8
  13. package/dist/cli/aun-commands.js +9 -1
  14. package/dist/cli/daemon-commands.js +34 -65
  15. package/dist/cli/daemon-lifecycle-client.js +61 -0
  16. package/dist/cli/ecmsg-gateway.js +38 -3
  17. package/dist/cli/events-command.js +73 -0
  18. package/dist/cli/index.js +31 -14
  19. package/dist/cli/init.js +75 -0
  20. package/dist/cli/invoke-command.js +182 -0
  21. package/dist/cli/managed-command-guard.js +6 -1
  22. package/dist/cli/provider-command.js +1 -1
  23. package/dist/cli/restart-monitor.js +67 -50
  24. package/dist/cli/services-command.js +111 -0
  25. package/dist/cli/task-context.js +38 -1
  26. package/dist/cli/team-workspace-command.js +134 -0
  27. package/dist/cli/thread-command.js +6 -2
  28. package/dist/cli/watch-logs.js +6 -4
  29. package/dist/cli/watch-msg.js +1 -1
  30. package/dist/config/boot-log.js +6 -4
  31. package/dist/config/builtin-roles.js +2 -2
  32. package/dist/config/config-field-policy.js +2 -2
  33. package/dist/config/config-manager.js +1 -8
  34. package/dist/config/invoke-ipc-service.js +118 -0
  35. package/dist/config/peer-role-resolver.js +1 -1
  36. package/dist/config/provider-identity-migration.js +92 -17
  37. package/dist/config/provider-local-sync.js +2 -0
  38. package/dist/config/providers-config.js +13 -0
  39. package/dist/config/providers-management.js +100 -10
  40. package/dist/config/role-service.js +8 -8
  41. package/dist/config/role-store.js +22 -22
  42. package/dist/config/schema-migration.js +86 -88
  43. package/dist/config/snapshot.js +70 -41
  44. package/dist/config-store.js +2 -1
  45. package/dist/core/agent-reload-coordinator.js +6 -4
  46. package/dist/core/agent-runtime.js +146 -15
  47. package/dist/core/auth/delegation-authorization.js +66 -0
  48. package/dist/core/auth/operation-catalog.js +20 -0
  49. package/dist/core/baseagent-loader.js +75 -42
  50. package/dist/core/channel-loader.js +45 -13
  51. package/dist/core/channel-runtime.js +116 -45
  52. package/dist/core/command/agent-control.js +1 -1
  53. package/dist/core/command/agent-storage-menu.js +1 -1
  54. package/dist/core/command/chatmode-config.js +2 -36
  55. package/dist/core/command/command-handler.js +58 -16
  56. package/dist/core/command/data-root-resolver.js +32 -23
  57. package/dist/core/command/eventcenter-menu.js +338 -0
  58. package/dist/core/command/menu-catalog.js +8 -0
  59. package/dist/core/command/menu-handler.js +206 -87
  60. package/dist/core/command/menu-protocol.js +142 -22
  61. package/dist/core/command/menu-query-batch.js +194 -0
  62. package/dist/core/command/role-menu.js +27 -15
  63. package/dist/core/command/slash-gate.js +1 -1
  64. package/dist/core/command/slash-handler.js +34 -42
  65. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  66. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  67. package/dist/core/command/team-workspace-initializer.js +2 -0
  68. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  69. package/dist/core/command/team-workspace-job-store.js +88 -0
  70. package/dist/core/command/team-workspace-management-service.js +2 -0
  71. package/dist/core/command/team-workspace-management-store.js +96 -0
  72. package/dist/core/command/team-workspace-management.js +265 -0
  73. package/dist/core/command/team-workspace-members-menu.js +88 -0
  74. package/dist/core/command/team-workspace-store.js +612 -0
  75. package/dist/core/command/team-workspace-team.js +193 -0
  76. package/dist/core/daemon-control.js +45 -15
  77. package/dist/core/daemon-lifecycle.js +478 -75
  78. package/dist/core/handoff/dispatcher.js +9 -3
  79. package/dist/core/handoff/runtime.js +130 -42
  80. package/dist/core/handoff/store.js +190 -2
  81. package/dist/core/handoff/types.js +5 -0
  82. package/dist/core/initialization/service.js +4 -4
  83. package/dist/core/invoke/executors/index.js +13 -0
  84. package/dist/core/invoke/executors/media.js +283 -0
  85. package/dist/core/invoke/executors/text.js +198 -0
  86. package/dist/core/invoke/invoke-service.js +157 -0
  87. package/dist/core/invoke/style-router.js +48 -0
  88. package/dist/core/invoke/types.js +19 -0
  89. package/dist/core/ipc-registration.js +51 -11
  90. package/dist/core/lifecycle-notice.js +10 -4
  91. package/dist/core/memory/consolidation.js +7 -5
  92. package/dist/core/message/aun-ipc-sender.js +149 -19
  93. package/dist/core/message/im-renderer.js +28 -84
  94. package/dist/core/message/message-bridge.js +57 -4
  95. package/dist/core/message/message-queue.js +46 -4
  96. package/dist/core/message/message-utils.js +10 -2
  97. package/dist/core/message/peer-mode.js +7 -34
  98. package/dist/core/message/pending-hints.js +4 -10
  99. package/dist/core/message/response-engine.js +163 -52
  100. package/dist/core/message/send-options.js +7 -4
  101. package/dist/core/message/send-routing.js +55 -7
  102. package/dist/core/ownership/owner-resolver.js +8 -0
  103. package/dist/core/permission/ec-command-parser.js +14 -3
  104. package/dist/core/permission/protected-paths.js +12 -2
  105. package/dist/core/permission/shell-environment.js +9 -0
  106. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  107. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  108. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  109. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  110. package/dist/core/session/session-file-health.js +243 -0
  111. package/dist/core/session/session-fs-store.js +163 -3
  112. package/dist/core/session/session-idle-monitor.js +9 -1
  113. package/dist/core/session/session-manager.js +36 -2
  114. package/dist/core/task/task-recovery-service.js +13 -2
  115. package/dist/core/thread/command-parser.js +9 -2
  116. package/dist/core/thread/thread-operation.js +21 -2
  117. package/dist/core/thread/thread-route.js +13 -2
  118. package/dist/directory/owner-directory-admission.js +42 -30
  119. package/dist/directory/owner-directory-cache.js +143 -126
  120. package/dist/directory/owner-directory-query-operation.js +9 -8
  121. package/dist/eck/kit-renderer.js +7 -5
  122. package/dist/ecweb/basic-settings-service.js +1 -1
  123. package/dist/ecweb/message-context-service.js +0 -4
  124. package/dist/ecweb/runtime/lifecycle.js +14 -8
  125. package/dist/ecweb/runtime/supervisor.js +62 -30
  126. package/dist/event-center/admission-materializer.js +114 -0
  127. package/dist/event-center/bus-gate.js +136 -0
  128. package/dist/event-center/bus-host.js +290 -0
  129. package/dist/event-center/bus-resolver.js +120 -0
  130. package/dist/event-center/center-config.js +100 -0
  131. package/dist/event-center/client-factory.js +50 -0
  132. package/dist/event-center/daemon.js +45 -0
  133. package/dist/event-center/directory-source.js +53 -0
  134. package/dist/event-center/dispatcher.js +157 -0
  135. package/dist/event-center/event-log.js +110 -0
  136. package/dist/event-center/index-generator.js +63 -0
  137. package/dist/event-center/ipc-operation.js +308 -0
  138. package/dist/event-center/ledger.js +52 -0
  139. package/dist/event-center/pack-loader.js +202 -0
  140. package/dist/event-center/pack-manager.js +85 -0
  141. package/dist/event-center/registry.js +238 -0
  142. package/dist/event-center/runtime.js +641 -0
  143. package/dist/event-center/script-runner.js +356 -0
  144. package/dist/event-center/types.js +35 -0
  145. package/dist/event-center/validation.js +413 -0
  146. package/dist/index.js +751 -268
  147. package/dist/ipc.js +66 -12
  148. package/dist/paths.js +20 -0
  149. package/dist/product.js +14 -0
  150. package/dist/proxy/manager.js +43 -18
  151. package/dist/proxy/service-supervisor.js +78 -35
  152. package/dist/response-system/engines/v1/index.js +0 -1
  153. package/dist/response-system/modes/single-session/index.js +1 -1
  154. package/dist/services/dispatcher.js +100 -0
  155. package/dist/services/idempotency.js +90 -0
  156. package/dist/services/identity.js +52 -0
  157. package/dist/services/index-generator.js +70 -0
  158. package/dist/services/index.js +449 -0
  159. package/dist/services/ipc-operation.js +458 -0
  160. package/dist/services/ledger.js +52 -0
  161. package/dist/services/message-log.js +112 -0
  162. package/dist/services/pack-manager.js +204 -0
  163. package/dist/services/reply.js +55 -0
  164. package/dist/services/router.js +95 -0
  165. package/dist/services/script-runner.js +422 -0
  166. package/dist/services/service-payload.js +70 -0
  167. package/dist/services/types.js +18 -0
  168. package/dist/services/validation.js +297 -0
  169. package/dist/trigger/application-service.js +21 -1
  170. package/dist/trigger/audit.js +19 -4
  171. package/dist/trigger/authorization.js +14 -5
  172. package/dist/trigger/event-source.js +1 -1
  173. package/dist/trigger/history.js +176 -7
  174. package/dist/trigger/ipc-service.js +3 -1
  175. package/dist/trigger/manager.js +1 -3
  176. package/dist/trigger/scheduler.js +78 -5
  177. package/dist/trigger/script-sandbox.js +118 -22
  178. package/dist/utils/cross-platform.js +175 -13
  179. package/dist/utils/evolcore-version.js +69 -27
  180. package/dist/utils/host-info.js +11 -8
  181. package/dist/utils/instance-registry.js +19 -13
  182. package/dist/utils/npm-ops.js +48 -0
  183. package/dist/utils/process-introspect.js +109 -10
  184. package/dist/utils/startup-trace.js +222 -44
  185. package/dist/utils/windows-shell-trust.js +80 -6
  186. package/kits/docs/INDEX.md +2 -2
  187. package/kits/docs/aun/ABILITY_CALLING.md +10 -17
  188. package/kits/docs/context-assembly.md +1 -1
  189. package/kits/docs/evolcore/INDEX.md +5 -2
  190. package/kits/docs/evolcore/ability.md +4 -0
  191. package/kits/docs/evolcore/aid.md +1 -1
  192. package/kits/docs/evolcore/ctl.md +2 -1
  193. package/kits/docs/evolcore/event-center.md +207 -0
  194. package/kits/docs/evolcore/file-navigation.md +10 -264
  195. package/kits/docs/evolcore/fs.md +3 -2
  196. package/kits/docs/evolcore/group.md +2 -2
  197. package/kits/docs/evolcore/memory-architecture.md +2 -0
  198. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  199. package/kits/docs/evolcore/menu-protocol.md +21 -0
  200. package/kits/docs/evolcore/msg.md +27 -8
  201. package/kits/docs/evolcore/provider.md +23 -3
  202. package/kits/docs/evolcore/response.md +5 -5
  203. package/kits/docs/evolcore/services.md +277 -0
  204. package/kits/docs/evolcore/task.md +2 -0
  205. package/kits/docs/evolcore/team-workspace.md +41 -0
  206. package/kits/eck_manifest.json +45 -7
  207. package/kits/eck_message_manifest.json +3 -3
  208. package/kits/rules/02-navigation.md +10 -1
  209. package/kits/rules/06-channel.md +5 -6
  210. package/kits/schemas/_meta.json +17 -6
  211. package/kits/schemas/agent-config.schema.19.json +5 -7
  212. package/kits/schemas/agent-config.schema.20.json +936 -0
  213. package/kits/schemas/daemon.schema.1.json +5 -0
  214. package/kits/schemas/daemon.schema.2.json +5 -0
  215. package/kits/schemas/daemon.schema.3.json +2 -1
  216. package/kits/schemas/daemon.schema.4.json +2 -1
  217. package/kits/schemas/daemon.schema.5.json +2 -1
  218. package/kits/schemas/daemon.schema.6.json +1 -1
  219. package/kits/schemas/daemon.schema.7.json +1 -1
  220. package/kits/schemas/daemon.schema.8.json +2 -1
  221. package/kits/schemas/daemon.schema.9.json +2 -1
  222. package/kits/schemas/relation-config.schema.12.json +2 -3
  223. package/kits/schemas/role-config.schema.2.json +4 -4
  224. package/kits/schemas/role-registry.schema.1.json +2 -2
  225. package/kits/schemas/single-session.schema.1.json +1 -1
  226. package/kits/schemas/single-session.schema.2.json +1 -1
  227. package/kits/schemas/single-session.schema.3.json +1 -1
  228. package/kits/skills/.switches.json +1 -5
  229. package/kits/skills/ability/SKILL.md +56 -0
  230. package/kits/skills/ability/references/calling.md +56 -0
  231. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  232. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  233. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  234. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  235. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  236. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  237. package/kits/skills/ec-group/SKILL.md +8 -5
  238. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  239. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  240. package/kits/skills/ec-trigger/SKILL.md +4 -4
  241. package/kits/skills/personal-assistant/SKILL.md +6 -6
  242. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  243. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  244. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  245. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  246. package/kits/skills/thread-ops/SKILL.md +10 -10
  247. package/kits/templates/system-fragments/channel.md +3 -3
  248. package/kits/templates/system-fragments/commands.md +9 -7
  249. package/kits/templates/system-fragments/reply.md +2 -6
  250. package/kits/templates/system-fragments/session.md +1 -1
  251. package/kits/templates/system-fragments/thread.md +11 -9
  252. package/package.json +5 -6
  253. package/dist/cli/pa-workspace-command.js +0 -225
  254. package/dist/core/command/pa-workspace-store.js +0 -468
  255. package/dist/core/relation/pa-team.js +0 -132
  256. package/kits/docs/evolcore/pa-workspace.md +0 -51
  257. package/kits/skills/aid-ability/SKILL.md +0 -244
  258. package/kits/skills/ec-ability/SKILL.md +0 -67
  259. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -1,5 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
+ import { createInterface } from 'node:readline';
4
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
3
5
  // 文件系统非法字符(Windows 最严格):< > : " / \ | ? *
4
6
  // 还有控制字符 0x00-0x1F。我们把这些字符编码为 %XX(hex 大写)。
5
7
  // `%` 本身也要转义为 %25,保证可逆。
@@ -461,6 +463,67 @@ export function readLastJsonlLine(filePath) {
461
463
  fs.closeSync(fd);
462
464
  }
463
465
  }
466
+ /** Async tail reader with the same committed-record rules as the sync readers. */
467
+ export async function readLastJsonlLineAsync(filePath, strict = false) {
468
+ let handle;
469
+ try {
470
+ handle = await fs.promises.open(filePath, 'r');
471
+ }
472
+ catch (error) {
473
+ if (error.code === 'ENOENT')
474
+ return undefined;
475
+ throw error;
476
+ }
477
+ try {
478
+ let cursor = (await handle.stat()).size;
479
+ let carry = Buffer.alloc(0);
480
+ let skipUncommitted = strict;
481
+ const parse = (raw, offset) => {
482
+ const line = raw.toString('utf8').trim();
483
+ if (!line)
484
+ return undefined;
485
+ if (strict)
486
+ return parseJsonlLineStrict(line, filePath, offset);
487
+ try {
488
+ return JSON.parse(line);
489
+ }
490
+ catch {
491
+ return undefined;
492
+ }
493
+ };
494
+ while (cursor > 0) {
495
+ const start = Math.max(0, cursor - 64 * 1024);
496
+ const chunk = Buffer.allocUnsafe(cursor - start);
497
+ let offset = 0;
498
+ while (offset < chunk.length) {
499
+ const { bytesRead } = await handle.read(chunk, offset, chunk.length - offset, start + offset);
500
+ if (!bytesRead)
501
+ throw new Error(`short JSONL read at ${filePath}:${start + offset}`);
502
+ offset += bytesRead;
503
+ }
504
+ const buffer = Buffer.concat([chunk, carry]);
505
+ let end = buffer.length;
506
+ let newline = buffer.lastIndexOf(0x0a);
507
+ while (newline >= 0) {
508
+ if (skipUncommitted)
509
+ skipUncommitted = false;
510
+ else {
511
+ const result = parse(buffer.subarray(newline + 1, end), start + newline + 1);
512
+ if (result !== undefined)
513
+ return result;
514
+ }
515
+ end = newline;
516
+ newline = end > 0 ? buffer.lastIndexOf(0x0a, end - 1) : -1;
517
+ }
518
+ carry = Buffer.from(buffer.subarray(0, end));
519
+ cursor = start;
520
+ }
521
+ return skipUncommitted ? undefined : parse(carry, 0);
522
+ }
523
+ finally {
524
+ await handle.close();
525
+ }
526
+ }
464
527
  export function readAllJsonlLines(filePath) {
465
528
  try {
466
529
  const content = fs.readFileSync(filePath, 'utf-8');
@@ -482,6 +545,100 @@ export function readAllJsonlLines(filePath) {
482
545
  throw e;
483
546
  }
484
547
  }
548
+ export async function visitSessionHistory(file, visit, onMalformed) {
549
+ const stream = fs.createReadStream(file, { encoding: 'utf8' });
550
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
551
+ let index = 0;
552
+ try {
553
+ for await (const line of lines) {
554
+ const lineIndex = index++;
555
+ if (index % 256 === 0)
556
+ await yieldToIo();
557
+ if (!line.trim())
558
+ continue;
559
+ let event;
560
+ try {
561
+ event = JSON.parse(line);
562
+ }
563
+ catch {
564
+ onMalformed?.();
565
+ continue;
566
+ }
567
+ visit(event, lineIndex);
568
+ }
569
+ }
570
+ finally {
571
+ lines.close();
572
+ stream.destroy();
573
+ }
574
+ }
575
+ export async function readAllJsonlLinesAsync(filePath) {
576
+ let content;
577
+ try {
578
+ content = await fs.promises.readFile(filePath, 'utf8');
579
+ }
580
+ catch (error) {
581
+ if (error.code === 'ENOENT')
582
+ return [];
583
+ throw error;
584
+ }
585
+ const results = [];
586
+ for (const line of content.split('\n')) {
587
+ if (!line.trim())
588
+ continue;
589
+ try {
590
+ results.push(JSON.parse(line));
591
+ }
592
+ catch { /* skip corrupt line */ }
593
+ }
594
+ return results;
595
+ }
596
+ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey, options) {
597
+ if (!selfAID || selfAID === '.' || selfAID === '..')
598
+ throw new Error('invalid selfAID');
599
+ const sessionsDir = path.join(sessionsRoot, encodeSegment(selfAID), 'sessions');
600
+ let entries;
601
+ try {
602
+ entries = await fs.promises.readdir(sessionsDir, { withFileTypes: true });
603
+ }
604
+ catch (error) {
605
+ if (error.code === 'ENOENT')
606
+ return [];
607
+ throw error;
608
+ }
609
+ const results = [];
610
+ for (let offset = 0; offset < entries.length; offset += 8) {
611
+ const batch = await Promise.all(entries.slice(offset, offset + 8).map(async (entry) => {
612
+ if (!entry.isDirectory())
613
+ return undefined;
614
+ const parsed = tryParseChannelSessionKey(entry.name);
615
+ if (!parsed)
616
+ return undefined;
617
+ const key = parsed.channelType === 'daemon' ? 'daemon'
618
+ : `${parsed.channelType}#${selfAID}#${parsed.channelName}`;
619
+ if (channelKey && key !== channelKey)
620
+ return undefined;
621
+ const dirPath = path.join(sessionsDir, entry.name);
622
+ let payload;
623
+ try {
624
+ payload = await fs.promises.readdir(dirPath, { withFileTypes: true });
625
+ }
626
+ catch (error) {
627
+ if (error.code === 'ENOENT')
628
+ return undefined;
629
+ throw error;
630
+ }
631
+ if (!payload.some(isSessionPayload))
632
+ return undefined;
633
+ return { channelType: parsed.channelType, selfAID, channelId: parsed.channelId,
634
+ channelKey: key, channelSessionKey: entry.name, dirPath, ...(options?.includeEntries ? { entries: payload } : {}) };
635
+ }));
636
+ for (const chat of batch)
637
+ if (chat)
638
+ results.push(chat);
639
+ }
640
+ return results.sort((a, b) => a.dirPath < b.dirPath ? -1 : a.dirPath > b.dirPath ? 1 : 0);
641
+ }
485
642
  /**
486
643
  * Scan the current per-Agent layout:
487
644
  * `agents/<aid>/sessions/<channelSessionKey>/`.
@@ -539,14 +696,17 @@ export function scanChatDirs(sessionsRoot) {
539
696
  }
540
697
  function hasSessionPayload(dirPath) {
541
698
  try {
542
- return fs.readdirSync(dirPath, { withFileTypes: true }).some(entry => (entry.isFile() && (entry.name === 'active.json'
543
- || entry.name === 'messages.jsonl'
544
- || (entry.name.startsWith('meta_') && entry.name.endsWith('.jsonl')))) || (entry.isDirectory() && entry.name === '_threads'));
699
+ return fs.readdirSync(dirPath, { withFileTypes: true }).some(isSessionPayload);
545
700
  }
546
701
  catch {
547
702
  return false;
548
703
  }
549
704
  }
705
+ function isSessionPayload(entry) {
706
+ return (entry.isFile() && (entry.name === 'active.json' || entry.name === 'messages.jsonl'
707
+ || (entry.name.startsWith('meta_') && entry.name.endsWith('.jsonl'))))
708
+ || (entry.isDirectory() && entry.name === '_threads');
709
+ }
550
710
  /**
551
711
  * Scan non-canonical single-level v3 keys. The runtime ignores these entries;
552
712
  * only the explicit migration planner may copy them into their canonical key.
@@ -184,6 +184,7 @@ export class SessionIdleMonitor {
184
184
  generations = new Map();
185
185
  knownSessionIdleTriggerIds = new Set();
186
186
  taskEncryption = new Map();
187
+ persistedState;
187
188
  started = false;
188
189
  active = false;
189
190
  onTaskTerminal = (event) => {
@@ -664,12 +665,19 @@ export class SessionIdleMonitor {
664
665
  ...(state.onceRequestId ? { onceRequestId: state.onceRequestId } : {}),
665
666
  };
666
667
  }
668
+ const snapshot = { version: 2, sessions };
669
+ const serialized = JSON.stringify(snapshot);
670
+ // Startup restores many timers; unchanged state needs no repeated fsync.
671
+ if (serialized === this.persistedState)
672
+ return true;
667
673
  try {
668
674
  fs.mkdirSync(path.dirname(this.options.statePath), { recursive: true });
669
- atomicWriteJson(this.options.statePath, { version: 2, sessions });
675
+ atomicWriteJson(this.options.statePath, snapshot);
676
+ this.persistedState = serialized;
670
677
  return true;
671
678
  }
672
679
  catch (error) {
680
+ this.persistedState = undefined;
673
681
  this.warn(`Failed to persist session idle state at ${this.options.statePath}`, error);
674
682
  return false;
675
683
  }
@@ -5,7 +5,7 @@ import { logger } from '../../utils/logger.js';
5
5
  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
- import { chatDirPath, generateSessionId, formatTimestamp, atomicWriteJson, atomicWriteText, appendJsonl, appendJsonlDurable, fsyncJsonlFile, readJsonFile, readLastJsonlLine, readLastJsonlLineStrict, readAllJsonlLines, scanChatDirs, scanMetaFiles, ensureChatDir, readThreadIndex, writeThreadIndex, compactJsonlTail, SESSION_META_COMPACT_POLICY, } from './session-fs-store.js';
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
9
  import { sessionToFile, fileToSession, formatSessionKey, DEFAULT_THREAD_ID, normalizeTopicLabel, 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';
@@ -949,6 +949,31 @@ export class SessionManager {
949
949
  }
950
950
  return results;
951
951
  }
952
+ async findAllSessionsInChatAsync(chatDir) {
953
+ const sessions = [];
954
+ for (const [dir, strict] of [[chatDir, false], [path.join(chatDir, '_threads'), true]]) {
955
+ let names;
956
+ try {
957
+ names = await fs.promises.readdir(dir);
958
+ }
959
+ catch (error) {
960
+ if (error.code === 'ENOENT')
961
+ continue;
962
+ throw error;
963
+ }
964
+ const files = names.filter(name => name.startsWith('meta_') && name.endsWith('.jsonl')).sort();
965
+ for (let offset = 0; offset < files.length; offset += 4) {
966
+ const batch = await Promise.all(files.slice(offset, offset + 4).map(async (name) => {
967
+ const file = await readLastJsonlLineAsync(path.join(dir, name), strict);
968
+ return file ? fileToSession(file) : undefined;
969
+ }));
970
+ for (const session of batch)
971
+ if (session)
972
+ sessions.push(session);
973
+ }
974
+ }
975
+ return sessions;
976
+ }
952
977
  /**
953
978
  * 按 sessionId 定位 meta 文件。逐个 id 全量 scanChatDirs 在几百个 chat 目录下
954
979
  * 单次约 50ms,启动时批量查询(SessionIdleMonitor 恢复 170+ 会话)会同步阻塞数秒,
@@ -2092,7 +2117,7 @@ export class SessionManager {
2092
2117
  return [];
2093
2118
  }
2094
2119
  const archiveFilter = options.archiveFilter ?? 'active';
2095
- const sessions = this.findAllSessionsInChat(chatDir, true)
2120
+ const sessions = (await this.findAllSessionsInChatAsync(chatDir))
2096
2121
  .filter(session => {
2097
2122
  if (archiveFilter === 'all')
2098
2123
  return true;
@@ -2644,6 +2669,15 @@ export class SessionManager {
2644
2669
  return null;
2645
2670
  return adapter.readFirstMessage(projectPath, agentSessionId, agentAid);
2646
2671
  }
2672
+ async readSessionMenuSummary(projectPath, agentSessionId, baseagent, agentAid) {
2673
+ const adapter = this.getFileAdapter(baseagent);
2674
+ if (!adapter)
2675
+ return { turns: 0, firstMessage: null };
2676
+ if (adapter.readMenuSummary)
2677
+ return adapter.readMenuSummary(projectPath, agentSessionId, agentAid);
2678
+ return { turns: adapter.getFileInfo(projectPath, agentSessionId, agentAid).turns,
2679
+ firstMessage: adapter.readFirstMessage(projectPath, agentSessionId, agentAid) };
2680
+ }
2647
2681
  readSessionLastUserMessage(projectPath, agentSessionId, baseagent, agentAid) {
2648
2682
  const adapter = this.getFileAdapter(baseagent);
2649
2683
  if (!adapter)
@@ -71,7 +71,7 @@ export class TaskRecoveryService {
71
71
  if (request.automatic && (!request.expectedTaskId || !Number.isSafeInteger(request.expectedGeneration))) {
72
72
  return result('not_recoverable', '自动恢复必须指定原任务及其版本', false);
73
73
  }
74
- const session = await this.deps.sessions.getSessionById(request.sessionId);
74
+ let session = await this.deps.sessions.getSessionById(request.sessionId);
75
75
  if (!session || session.deletedAt || (request.agentAid && session.selfAID !== request.agentAid)) {
76
76
  return result('not_found', '目标会话不存在或不属于当前 Agent', false);
77
77
  }
@@ -97,12 +97,23 @@ export class TaskRecoveryService {
97
97
  return result('waiting_interaction', '任务正在等待必要输入或审批,请先完成交互');
98
98
  }
99
99
  let runner;
100
+ const binding = JSON.stringify([session.selfAID, session.baseagent, session.agentSessionId, session.processingState, state]);
100
101
  try {
101
- runner = this.deps.getRunner(session);
102
+ runner = await this.deps.getRunner(session);
102
103
  }
103
104
  catch {
104
105
  return result('not_recoverable', '原 baseagent 当前不可用', false);
105
106
  }
107
+ if (request.signal?.aborted)
108
+ return result('not_recoverable', '恢复请求已取消', false);
109
+ // First-use loading can yield for seconds. A stop, replacement turn or
110
+ // backend change during that wait must invalidate this recovery attempt.
111
+ const latest = await this.deps.sessions.getSessionById(request.sessionId);
112
+ if (!latest || latest.deletedAt || binding !== JSON.stringify([
113
+ latest.selfAID, latest.baseagent, latest.agentSessionId, latest.processingState, latest.metadata?.turnState,
114
+ ]))
115
+ return result('stale', '等待 Runner 期间会话状态已变化,已忽略过期恢复请求');
116
+ session = latest;
106
117
  if (!request.automatic && this.deps.resumePause(session.id)) {
107
118
  return result('resumed_pause', '✓ 已继续暂停的任务');
108
119
  }
@@ -8,7 +8,7 @@ const VALUE_OPTIONS = new Set(['--self', '--agent', '--format', '--name', '--lab
8
8
  const OPTIONS = {
9
9
  peers: [], list: ['--status', '--label', '--unlabeled', '--sort', '--page', '--limit'],
10
10
  show: [], history: ['--limit', '--before', '--after'],
11
- create: ['--name', '--label', '--status', '--group'], rename: [], label: ['--clear'], status: [],
11
+ create: ['--name', '--label', '--status', '--group', '--private'], rename: [], label: ['--clear'], 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
  };
@@ -120,7 +120,14 @@ export function resolveThreadCommandArgv(argv, context = {}) {
120
120
  if (command === 'create') {
121
121
  if (!text('--name')?.trim())
122
122
  throw new Error('Topic name is required');
123
- Object.assign(request, { name: text('--name'), label: text('--label'), topicStatus: status, peerKind: options.has('--group') ? 'group' : 'private' });
123
+ // 对端类型:显式 `--group` / `--private` 优先;都没写时留空,由执行层按
124
+ // 关系证据推断(群里漏写 --group 曾被记成 private,之后 scope 判定全错)。
125
+ const explicitPeerKind = options.has('--group') ? 'group'
126
+ : options.has('--private') ? 'private' : undefined;
127
+ Object.assign(request, {
128
+ name: text('--name'), label: text('--label'), topicStatus: status,
129
+ ...(explicitPeerKind ? { peerKind: explicitPeerKind } : {}),
130
+ });
124
131
  }
125
132
  if (command === 'rename') {
126
133
  if (!positional[1].trim())
@@ -1,6 +1,22 @@
1
1
  import { logger } from '../../utils/logger.js';
2
+ import { readAunPeerKind } from '../relation/peer-identity.js';
2
3
  import { ThreadService, normalizeThreadPeer } from './thread-service.js';
3
4
  import { isMainSessionThreadId, isTopicThreadId, safeFormatMainTopicId } from './topic-id.js';
5
+ /**
6
+ * 建话题时对端类型的默认来源:本地关系证据(agent.md 缓存 / 关系配置)。
7
+ * 证据不可用时不阻塞建话题,按私聊兜底——与发送路径的判定口径一致。
8
+ */
9
+ function inferThreadPeerKind(selfAid, peer) {
10
+ try {
11
+ const kind = readAunPeerKind(selfAid, peer).kind;
12
+ if (kind === 'group' || kind === 'private')
13
+ return kind;
14
+ }
15
+ catch {
16
+ // 关系证据读取失败不算错误。
17
+ }
18
+ return 'private';
19
+ }
4
20
  /**
5
21
  * Emit the existing cross-device rename event after a local rename succeeds.
6
22
  * Storage stays in ThreadService; transport stays in the operation layer.
@@ -140,10 +156,13 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
140
156
  case 'create': {
141
157
  if (!request.peer || !request.name)
142
158
  return { ok: false, code: 'MISSING_ARGS', error: 'peer and name required' };
159
+ // 没显式写 --group / --private 时按关系证据推断:群话题被记成 private
160
+ // 会让后续 scope 选择、群规则、通知范围全部走错。
161
+ const peerKind = request.peerKind ?? inferThreadPeerKind(selfAid, request.peer);
143
162
  const result = await threadService.createThread({
144
163
  selfAid,
145
164
  peer: request.peer,
146
- peerKind: request.peerKind ?? 'private',
165
+ peerKind,
147
166
  name: request.name,
148
167
  label: request.label ?? undefined,
149
168
  topicStatus: request.topicStatus,
@@ -155,7 +174,7 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
155
174
  to: request.peer,
156
175
  threadId: result.threadId,
157
176
  topicName: result.name,
158
- peerKind: request.peerKind ?? 'private',
177
+ peerKind,
159
178
  // 与 rename 相同:授权链需要托管上下文,宿主调用则留空(跳过通知)。
160
179
  originSessionId: request.originSessionId,
161
180
  delegationToken: request.delegationToken,
@@ -11,11 +11,19 @@ import { isMainSessionThreadId, resolveThreadRef } from './topic-id.js';
11
11
  *
12
12
  * 话题必须存在于本端:话题查索引,主话题查该关系的 active session。
13
13
  * 返回 undefined 表示该引用不能作为跨话题路由依据。
14
+ *
15
+ * `options.allowSelfTarget`(self-address):`target` 是本端自己的 AID 时,
16
+ * 它不是「话题对端」而是「收件人」,与 `entry.peer` 天然不一致。此时跳过
17
+ * 一致性校验,仍按引用返回话题条目——话题归属不变,变的只是投给谁。
14
18
  */
15
- export function resolveThreadRouteTarget(selfAid, threadRef, scope, target) {
19
+ export function resolveThreadRouteTarget(selfAid, threadRef, scope, target, options = {}) {
16
20
  if (!selfAid)
17
21
  return undefined;
18
22
  const normalizedSelf = selfAid.replace(/^@/, '');
23
+ // 自发:收件人是本端,不能拿它和话题对端比。
24
+ const selfTargeted = options.allowSelfTarget === true
25
+ && target !== undefined
26
+ && target.replace(/^@/, '').toLowerCase() === normalizedSelf.toLowerCase();
19
27
  const resolved = resolveThreadRef(threadRef, normalizedSelf);
20
28
  if (resolved.kind === 'invalid' || resolved.kind === 'current')
21
29
  return undefined;
@@ -26,7 +34,7 @@ export function resolveThreadRouteTarget(selfAid, threadRef, scope, target) {
26
34
  const effectiveTarget = peerFromRef ?? target;
27
35
  if (!effectiveTarget)
28
36
  return undefined;
29
- if (target !== undefined && peerFromRef !== undefined) {
37
+ if (target !== undefined && peerFromRef !== undefined && !selfTargeted) {
30
38
  const normalizedTarget = target.replace(/^@/, '');
31
39
  const matches = scope === 'group'
32
40
  ? sameGroupAid(peerFromRef, normalizedTarget)
@@ -76,6 +84,9 @@ export function resolveThreadRouteTarget(selfAid, threadRef, scope, target) {
76
84
  }
77
85
  if (target === undefined)
78
86
  return entry;
87
+ // 自发:收件人是本端,话题归属仍由 entry.peer 决定,不做一致性校验。
88
+ if (selfTargeted)
89
+ return entry;
79
90
  const normalizedTarget = target.replace(/^@/, '');
80
91
  const matches = scope === 'group'
81
92
  ? sameGroupAid(entry.peer, normalizedTarget)
@@ -42,11 +42,10 @@ export function liveOwnerDirectoryCache(selfAid) {
42
42
  * 时按 AID 临时读一次本地快照重新渲染,产出同样的字节。后者多一次读盘,
43
43
  * 但保证"配置一改,注入就变",不必等到下一条入站消息。
44
44
  *
45
- * **ownerAid 必须取自 authorization.json,不能用 `ownerResolver` 猜。** 离线时
46
- * 解析器只能给出 known owner(可能来自过期缓存或另一条关系),一旦与授权文件里的
47
- * grantee/owner 对不上,`scopeAccess` 就不是 authorized,`directoryGone()` 随之
48
- * 判真,`refreshMarkdown` 会把 `directory.md` 删掉——一个只读的开关变更变成删注入源。
49
- * 授权文件缺失时直接返回 false:没有授权就没有可渲染的内容,也不该动现有文件。
45
+ * **ownerAid 取自本地快照信封,不用 `ownerResolver` 猜。** 离线时解析器只能给出
46
+ * known owner(可能来自过期缓存或另一条关系),一旦与快照里的 owner 对不上,
47
+ * `directoryGone()` 会判真,`refreshMarkdown` 会把 `directory.md` 删掉——一个只读的
48
+ * 开关变更变成删注入源。快照不存在时直接返回 false:没有可渲染的内容,也不该动现有文件。
50
49
  */
51
50
  export function refreshDirectoryMarkdown(selfAid) {
52
51
  const live = liveOwnerDirectoryCache(selfAid);
@@ -55,7 +54,7 @@ export function refreshDirectoryMarkdown(selfAid) {
55
54
  return true;
56
55
  }
57
56
  const directory = path.join(agentDir(selfAid), 'directory');
58
- const ownerAid = authorizedOwnerAid(directory, selfAid);
57
+ const ownerAid = snapshotOwnerAid(directory, selfAid);
59
58
  if (!ownerAid)
60
59
  return false;
61
60
  try {
@@ -68,18 +67,18 @@ export function refreshDirectoryMarkdown(selfAid) {
68
67
  }
69
68
  }
70
69
  /**
71
- * 从 `authorization.json` 读出授权是的哪个 Owner。只认与本 agent 匹配的凭证。
70
+ * 从本地快照信封(`contacts.json`)里读出这份名录属于哪个 Owner。
72
71
  *
73
- * 与 `OwnerDirectoryCache.loadGrant` 同一条判据,但不依赖缓存实例——这里只是
74
- * 为了在无活缓存时找到一个与磁盘授权一致的 ownerAid,好让 `scopeAccess` 有据可查。
72
+ * 这是 ownerAid 的**唯一来源**:`authorization.json` 已废弃,不再读取。
73
+ * 快照自带 `ownerAid` 与 `granteeAid`,能自证归属,不需要外部凭证佐证。
75
74
  */
76
- export function authorizedOwnerAid(directory, selfAid) {
75
+ export function snapshotOwnerAid(directory, selfAid) {
77
76
  try {
78
- const raw = JSON.parse(fs.readFileSync(path.join(directory, 'authorization.json'), 'utf8'));
77
+ const raw = JSON.parse(fs.readFileSync(path.join(directory, 'contacts.json'), 'utf8'));
79
78
  if (!raw || typeof raw !== 'object' || Array.isArray(raw))
80
79
  return undefined;
81
80
  const record = raw;
82
- if (record.granteeAid !== selfAid)
81
+ if (record.schemaVersion !== 2 || record.granteeAid !== selfAid)
83
82
  return undefined;
84
83
  const ownerAid = typeof record.ownerAid === 'string' ? record.ownerAid.trim() : '';
85
84
  return ownerAid || undefined;
@@ -101,8 +100,6 @@ export async function refreshOwnerDirectory(selfAid) {
101
100
  const live = liveOwnerDirectoryCache(selfAid);
102
101
  const scope = OWNER_DIRECTORY_SCOPES[0];
103
102
  if (live) {
104
- if (live.scopeAccess(scope) !== 'authorized')
105
- return { pulled: false, regenerated: false };
106
103
  let timer;
107
104
  try {
108
105
  // 空 digests = 无条件拉取,不做摘要比对。
@@ -135,8 +132,6 @@ export async function syncOwnerDirectoryForLookup(selfAid) {
135
132
  if (!cache)
136
133
  return false;
137
134
  const scope = OWNER_DIRECTORY_SCOPES[0];
138
- if (cache.scopeAccess(scope) !== 'authorized')
139
- return false;
140
135
  const before = cache.readSnapshot(scope)?.contentDigest;
141
136
  // 把 pending 里带的通知 digest 一起传下去:与共享缓存一致时 0 次网络请求。
142
137
  // 未命中的场景恰恰常发生在"通知刚到、共享缓存已拉过",不传等于白拉一次。
@@ -166,9 +161,16 @@ export async function prepareOwnerDirectoryAdmission(selfAid, aid) {
166
161
  if (ownerResolver.owner(selfAid) !== live.ownerAid)
167
162
  return;
168
163
  const scope = OWNER_DIRECTORY_SCOPES[0];
169
- if (live.cache.scopeAccess(scope) !== 'authorized')
170
- return;
171
- const found = live.cache.readSnapshot(scope)?.entries.some(entry => entry.aid === aid) ?? false;
164
+ // 坏快照解析会抛:这里只是准入前的预热,读不出来就当未命中,交给准入路径自己判。
165
+ const snapshotEntries = (() => {
166
+ try {
167
+ return live.cache.readSnapshot(scope)?.entries;
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ })();
173
+ const found = snapshotEntries?.some(entry => entry.aid === aid) ?? false;
172
174
  if (found) {
173
175
  // 已知成员:只允许一次后台刷新,不阻塞本条消息的处理。
174
176
  void live.cache.lookupByAid(scope, aid).catch(() => { });
@@ -209,26 +211,36 @@ export function readOwnerDirectoryMembership(selfAid, aid, appOwned = false) {
209
211
  const directory = path.join(agentDir(selfAid), 'directory');
210
212
  // "从未接入名录"与"接入过但当前不可用"是两种结论,判据是盘上有没有痕迹。
211
213
  // 原子写的热备名(`*.json_`)由 existsAtomic 负责,业务层不关心后缀。
212
- const configured = existsAtomic(path.join(directory, 'authorization.json'))
213
- || existsAtomic(path.join(directory, 'contacts.json'));
214
- if (!configured && !appOwned)
215
- return undefined;
216
- const ownerAid = ownerResolver.owner(selfAid);
214
+ const configured = existsAtomic(path.join(directory, 'contacts.json'));
215
+ if (!configured) {
216
+ // 没有名录文件:普通消息准入保持旧行为(交给调用方的开关/白名单判断);
217
+ // App 侧一律按目录不可用处理,不因"没数据"放宽。
218
+ if (!appOwned)
219
+ return undefined;
220
+ logDirectoryAdmissionUnavailable(selfAid, aid, 'snapshot_missing');
221
+ return { category: 'unavailable' };
222
+ }
223
+ // ownerAid 优先取快照信封:它自证归属,离线也能用。解析器只在没有快照时兜底。
224
+ const snapshotOwner = snapshotOwnerAid(directory, selfAid);
225
+ const resolvedOwner = ownerResolver.owner(selfAid);
226
+ // 协议 Owner 已解析、却与快照归属不同:名录是上一个 Owner 的,不能拿做过期准入。
227
+ // 解析不出来(离线、共识过期)不算冲突——那一侧交给快照信封自证。
228
+ if (snapshotOwner && resolvedOwner && snapshotOwner !== resolvedOwner) {
229
+ logDirectoryAdmissionUnavailable(selfAid, aid, 'owner_mismatch', resolvedOwner);
230
+ return { category: 'unavailable' };
231
+ }
232
+ const ownerAid = snapshotOwner ?? resolvedOwner;
217
233
  if (!ownerAid) {
218
234
  logDirectoryAdmissionUnavailable(selfAid, aid, 'owner_unresolved');
219
235
  return { category: 'unavailable' };
220
236
  }
221
237
  try {
238
+ const scope = OWNER_DIRECTORY_SCOPES[0];
222
239
  const relationVersion = appOwned ? ownerResolver.snapshot(selfAid).consensus?.relation_version : undefined;
223
240
  if (appOwned && (!Number.isSafeInteger(relationVersion) || (relationVersion ?? 0) <= 0))
224
241
  return { category: 'unavailable' };
225
242
  const cache = new OwnerDirectoryCache({ selfAid, ownerAid, directory, relationVersion });
226
- const scope = OWNER_DIRECTORY_SCOPES[0];
227
- const accessReason = cache.scopeAccessUnavailableReason(scope);
228
- if (accessReason) {
229
- logDirectoryAdmissionUnavailable(selfAid, aid, accessReason, ownerAid);
230
- return { category: 'unavailable' };
231
- }
243
+ // 判据只有一条:快照文件在不在。授权凭证不参与任何判断。
232
244
  const snapshot = cache.readSnapshot(scope);
233
245
  if (!snapshot) {
234
246
  logDirectoryAdmissionUnavailable(selfAid, aid, existsAtomic(path.join(directory, `${scope}.json`)) ? 'snapshot_invalid' : 'snapshot_missing', ownerAid);