evolcore 0.0.43-test.7 → 0.0.43-test.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +22 -9
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/claude-runner.js +1 -1
  9. package/dist/aun/aid/agentmd.js +56 -1
  10. package/dist/aun/aid/client.js +3 -1
  11. package/dist/aun/menu/client.js +3 -2
  12. package/dist/aun/msg/p2p.js +1 -1
  13. package/dist/channels/aun.js +47 -32
  14. package/dist/cli/agent-command.js +5 -0
  15. package/dist/cli/agent-create.js +5 -1
  16. package/dist/cli/agent-template.js +124 -0
  17. package/dist/cli/aun-commands.js +2 -2
  18. package/dist/cli/ctl-command.js +2 -1
  19. package/dist/cli/daemon-commands.js +5 -0
  20. package/dist/cli/ecmsg-gateway.js +2 -2
  21. package/dist/cli/events-command.js +45 -9
  22. package/dist/cli/index.js +29 -0
  23. package/dist/cli/net-check.js +1 -1
  24. package/dist/cli/restart-monitor.js +115 -36
  25. package/dist/cli/services-command.js +29 -3
  26. package/dist/cli/thread-command.js +97 -11
  27. package/dist/config/boot-log.js +8 -8
  28. package/dist/config/schema-migration.js +41 -16
  29. package/dist/core/agent-ipc-registration.js +25 -4
  30. package/dist/core/agent-runtime.js +2 -0
  31. package/dist/core/auth/operation-authorizer.js +2 -0
  32. package/dist/core/auth/operation-catalog.js +11 -2
  33. package/dist/core/channel-runtime.js +16 -9
  34. package/dist/core/command/agent-control.js +11 -1
  35. package/dist/core/command/agent-template-menu.js +147 -0
  36. package/dist/core/command/command-handler.js +27 -6
  37. package/dist/core/command/eventcenter-menu.js +158 -28
  38. package/dist/core/command/menu-catalog.js +8 -1
  39. package/dist/core/command/menu-handler.js +18 -6
  40. package/dist/core/command/menu-protocol.js +11 -2
  41. package/dist/core/daemon-control.js +14 -0
  42. package/dist/core/daemon-lifecycle.js +262 -189
  43. package/dist/core/handoff/runtime.js +42 -10
  44. package/dist/core/ipc-registration.js +5 -1
  45. package/dist/core/legacy-rename.js +41 -0
  46. package/dist/core/message/aun-ipc-sender.js +118 -13
  47. package/dist/core/message/im-renderer.js +88 -1
  48. package/dist/core/message/message-queue.js +66 -15
  49. package/dist/core/message/pending-hints.js +29 -5
  50. package/dist/core/message/response-engine.js +37 -7
  51. package/dist/core/message/send-routing.js +13 -6
  52. package/dist/core/pack-auth.js +94 -0
  53. package/dist/core/pack-install.js +194 -0
  54. package/dist/core/permission/ec-command-parser.js +49 -16
  55. package/dist/core/rate-window.js +48 -0
  56. package/dist/core/relation/peer-identity.js +28 -0
  57. package/dist/core/session/session-fs-store.js +66 -26
  58. package/dist/core/session/session-idle-monitor.js +59 -19
  59. package/dist/core/session/session-manager.js +13 -4
  60. package/dist/core/thread/thread-route.js +2 -2
  61. package/dist/core/thread/thread-service.js +52 -3
  62. package/dist/eck/kit-renderer.js +1 -1
  63. package/dist/eck/message-renderer.js +2 -0
  64. package/dist/event-center/admission-materializer.js +22 -12
  65. package/dist/event-center/bus-gate.js +20 -2
  66. package/dist/event-center/bus-host.js +46 -29
  67. package/dist/event-center/bus-resolver.js +1 -1
  68. package/dist/event-center/center-config.js +41 -14
  69. package/dist/event-center/daemon.js +1 -2
  70. package/dist/event-center/directory-source.js +3 -1
  71. package/dist/event-center/index-generator.js +12 -2
  72. package/dist/event-center/ipc-operation.js +140 -25
  73. package/dist/event-center/pack-loader.js +61 -56
  74. package/dist/event-center/pack-manager.js +2 -2
  75. package/dist/event-center/registry.js +242 -17
  76. package/dist/event-center/runtime.js +271 -75
  77. package/dist/event-center/types.js +20 -4
  78. package/dist/event-center/validation.js +34 -12
  79. package/dist/index.js +147 -44
  80. package/dist/ipc.js +44 -4
  81. package/dist/paths.js +2 -2
  82. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  83. package/dist/services/index.js +3 -3
  84. package/dist/services/ipc-operation.js +99 -7
  85. package/dist/services/pack-manager.js +17 -6
  86. package/dist/services/router.js +8 -5
  87. package/dist/services/validation.js +5 -5
  88. package/dist/trigger/scheduler.js +38 -0
  89. package/dist/trigger/script-sandbox.js +52 -2
  90. package/dist/utils/npm-ops.js +2 -1
  91. package/dist/utils/package-version-info.js +6 -3
  92. package/kits/docs/aun/ABILITY_CALLING.md +4 -3
  93. package/kits/docs/context-assembly.md +1 -1
  94. package/kits/docs/evolcore/INDEX.md +3 -3
  95. package/kits/docs/evolcore/agent.md +22 -1
  96. package/kits/docs/evolcore/event-center.md +30 -10
  97. package/kits/docs/evolcore/fs.md +4 -3
  98. package/kits/docs/evolcore/menu-protocol.md +7 -1
  99. package/kits/docs/evolcore/msg.md +8 -8
  100. package/kits/docs/evolcore/response.md +2 -2
  101. package/kits/docs/evolcore/services.md +27 -10
  102. package/kits/docs/evolcore/thread-chain.md +15 -3
  103. package/kits/rules/06-channel.md +1 -0
  104. package/kits/skills/ability/references/calling.md +2 -2
  105. package/kits/skills/ec-group/SKILL.md +5 -8
  106. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  107. package/kits/skills/ec-trigger/SKILL.md +4 -4
  108. package/kits/skills/thread-ops/SKILL.md +10 -10
  109. package/kits/templates/message-fragments/item.md +1 -1
  110. package/kits/templates/system-fragments/channel.md +1 -1
  111. package/kits/templates/system-fragments/commands.md +1 -1
  112. package/kits/templates/system-fragments/reply.md +1 -0
  113. package/kits/templates/system-fragments/thread.md +3 -2
  114. package/package.json +4 -3
  115. package/scripts/agent-template/index.mjs +40 -0
  116. package/scripts/agent-template/inspect.mjs +240 -0
  117. package/scripts/agent-template/overlay.mjs +71 -0
  118. package/scripts/agent-template/pack.mjs +169 -0
  119. package/scripts/agent-template/shared/common.mjs +235 -0
  120. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  121. package/scripts/agent-template/shared/plan.mjs +129 -0
  122. package/scripts/agent-template/shared/team-schema.json +70 -0
  123. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  124. package/scripts/agent-template/shared/template-package.mjs +265 -0
  125. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  126. package/scripts/agent-template/shared/template.mjs +142 -0
  127. package/dist/event-center/client-factory.js +0 -50
@@ -0,0 +1,194 @@
1
+ /**
2
+ * 事件包 / 服务包的受控安装与卸载。
3
+ *
4
+ * 为什么需要这一层:`agents/<aid>/events` 与 `agents/<aid>/services` 是 L 类受保护路径,
5
+ * agent 自己的 Write / Bash 一律被 `checkLClassWrite` 拒(提示语就写着"请使用对应的
6
+ * EvolCore 受控命令")。所以安装包必须由 daemon 代写——agent 只负责把包目录放在
7
+ * 普通工作区里,然后调 `ec events pack add` / `ec services pack add`。
8
+ *
9
+ * 这一层只做文件系统搬运:校验仍由各模块的加载器(pack-loader / pack-manager)在
10
+ * reload 时完成,安装时不重复实现一套语义,避免两套规则漂移。
11
+ */
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ /** 包安装期间的运行时产物:不该被拷进新包,也不该被 `pack add` 覆盖。 */
15
+ const PACK_RUNTIME_ENTRIES = new Set(['ledger.jsonl', '.idempotency.jsonl', 'logs', '.state.json', '.index.md']);
16
+ /** 包名:英文短横线/下划线,防止 `..` 或路径分隔符把写入引出目标根。 */
17
+ const PACK_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
18
+ function assertPackName(name) {
19
+ if (!PACK_NAME.test(name)) {
20
+ throw Object.assign(new Error(`invalid pack name: ${name} (expected ${PACK_NAME})`), { code: 'INVALID_PACK_NAME' });
21
+ }
22
+ }
23
+ /** 递归列出源目录里的常规文件(相对路径)。符号链接一律拒绝:包必须自包含。 */
24
+ function collectFiles(root) {
25
+ const out = [];
26
+ const walk = (dir, prefix) => {
27
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
28
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
29
+ const absolute = path.join(dir, entry.name);
30
+ if (entry.isSymbolicLink()) {
31
+ throw Object.assign(new Error(`pack must not contain symlinks: ${relative}`), { code: 'PACK_CONTAINS_SYMLINK' });
32
+ }
33
+ if (entry.isDirectory()) {
34
+ if (PACK_RUNTIME_ENTRIES.has(entry.name))
35
+ continue;
36
+ walk(absolute, relative);
37
+ continue;
38
+ }
39
+ if (!entry.isFile())
40
+ continue;
41
+ if (PACK_RUNTIME_ENTRIES.has(entry.name))
42
+ continue;
43
+ out.push(relative);
44
+ }
45
+ };
46
+ walk(root, '');
47
+ return out;
48
+ }
49
+ /**
50
+ * 安装一个包:先复制到 `.pending-<rand>`,再整体 rename 到位。
51
+ * 中途失败不会留下半个包(对加载器而言"目录存在但缺文件"= invalid,会污染台账)。
52
+ */
53
+ export function installPack(request) {
54
+ const sourceDir = path.resolve(request.sourceDir);
55
+ if (!fs.existsSync(sourceDir) || !fs.statSync(sourceDir).isDirectory()) {
56
+ throw Object.assign(new Error(`source directory not found: ${sourceDir}`), { code: 'PACK_SOURCE_NOT_FOUND' });
57
+ }
58
+ const manifestPath = path.join(sourceDir, request.manifestFile);
59
+ let migratedFrom;
60
+ if (!fs.existsSync(manifestPath)) {
61
+ const legacyPath = request.legacyManifestFile ? path.join(sourceDir, request.legacyManifestFile) : undefined;
62
+ if (!legacyPath || !fs.existsSync(legacyPath)) {
63
+ throw Object.assign(new Error(`source is missing ${request.manifestFile}: ${sourceDir}`), { code: 'PACK_MANIFEST_NOT_FOUND' });
64
+ }
65
+ // 旧名一次性改名,之后流程与规范名完全一致。
66
+ fs.renameSync(legacyPath, manifestPath);
67
+ migratedFrom = request.legacyManifestFile;
68
+ }
69
+ const name = request.name?.trim() || path.basename(sourceDir);
70
+ assertPackName(name);
71
+ const targetRoot = path.resolve(request.targetRoot);
72
+ const targetDir = path.join(targetRoot, name);
73
+ // 已安装的判定看 manifest,不看目录是否存在:`pack remove` 会留下归档日志目录,
74
+ // 那是个"残留目录"而不是"已安装的包",应当允许直接装回去。
75
+ if (fs.existsSync(path.join(targetDir, request.manifestFile))) {
76
+ throw Object.assign(new Error(`pack already installed: ${name} (run "pack remove ${name}" first)`), { code: 'PACK_ALREADY_EXISTS' });
77
+ }
78
+ const files = collectFiles(sourceDir);
79
+ fs.mkdirSync(targetRoot, { recursive: true });
80
+ // 残留目录(只有 logs/ 等运行时产物):原地写回,不删目录也不动归档日志。
81
+ if (fs.existsSync(targetDir)) {
82
+ for (const relative of files) {
83
+ const destination = path.join(targetDir, relative);
84
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
85
+ fs.copyFileSync(path.join(sourceDir, relative), destination);
86
+ }
87
+ return { pack: name, dir: targetDir, files: files.length, intoArchived: true, ...(migratedFrom ? { migratedFrom } : {}) };
88
+ }
89
+ // 首次安装:写临时目录再整体 rename,避免中途失败留下半个包。
90
+ const pending = path.join(targetRoot, `.pending-${name}-${process.pid}-${Date.now()}`);
91
+ try {
92
+ for (const relative of files) {
93
+ const destination = path.join(pending, relative);
94
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
95
+ fs.copyFileSync(path.join(sourceDir, relative), destination);
96
+ }
97
+ fs.renameSync(pending, targetDir);
98
+ }
99
+ catch (error) {
100
+ fs.rmSync(pending, { recursive: true, force: true });
101
+ throw error;
102
+ }
103
+ return { pack: name, dir: targetDir, files: files.length, ...(migratedFrom ? { migratedFrom } : {}) };
104
+ }
105
+ /** 卸载后在包目录留下的标记文件:加载器据此跳过"只有归档历史"的空壳目录。 */
106
+ export const PACK_ARCHIVED_MARKER = '.archived';
107
+ function archiveStamp(now = new Date()) {
108
+ const pad = (value, width = 2) => String(value).padStart(width, '0');
109
+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
110
+ }
111
+ /**
112
+ * 卸载一个包。
113
+ *
114
+ * 默认**归档**运行时产物而不是删除:`logs/` 下的日志与 `ledger.jsonl` 整体移进
115
+ * `logs/archive-<时间戳>/`,然后删掉 manifest 与脚本,目录里只留这份归档和一个
116
+ * `.archived` 标记。这样重新安装不会和上次的日志混在一起(新旧各在各的目录),
117
+ * 想彻底删干净用 `purge`。
118
+ */
119
+ export function removePack(options) {
120
+ assertPackName(options.pack);
121
+ const targetRoot = path.resolve(options.targetRoot);
122
+ const targetDir = path.join(targetRoot, options.pack);
123
+ if (!fs.existsSync(targetDir)) {
124
+ return { pack: options.pack, dir: targetDir, removed: false };
125
+ }
126
+ if (options.purge === true) {
127
+ fs.rmSync(targetDir, { recursive: true, force: true });
128
+ return { pack: options.pack, dir: targetDir, removed: true };
129
+ }
130
+ // ① 归档:logs/ 下的日志 + 包根下的 ledger / 幂等记录,一起移进归档子目录。
131
+ const logsDir = path.join(targetDir, 'logs');
132
+ const archiveName = `archive-${archiveStamp()}`;
133
+ const archiveDir = path.join(logsDir, archiveName);
134
+ const archived = [];
135
+ const moveInto = (from) => {
136
+ if (!fs.existsSync(from))
137
+ return;
138
+ fs.mkdirSync(archiveDir, { recursive: true });
139
+ fs.renameSync(from, path.join(archiveDir, path.basename(from)));
140
+ archived.push(path.basename(from));
141
+ };
142
+ try {
143
+ for (const entry of fs.readdirSync(logsDir, { withFileTypes: true })) {
144
+ if (entry.isDirectory() && entry.name.startsWith('archive-'))
145
+ continue;
146
+ const absolute = path.join(logsDir, entry.name);
147
+ if (entry.isDirectory()) {
148
+ fs.rmSync(absolute, { recursive: true, force: true });
149
+ continue;
150
+ }
151
+ moveInto(absolute);
152
+ }
153
+ }
154
+ catch { /* logs/ 不存在:没有可归档的日志 */ }
155
+ for (const name of ['ledger.jsonl', '.idempotency.jsonl']) {
156
+ moveInto(path.join(targetDir, name));
157
+ }
158
+ // ② 删声明与脚本(保留 logs/ 与 .archived)。
159
+ for (const relative of collectFiles(targetDir)) {
160
+ fs.rmSync(path.join(targetDir, relative), { force: true });
161
+ }
162
+ for (const entry of fs.readdirSync(targetDir, { withFileTypes: true })) {
163
+ if (entry.name === 'logs' || entry.name === PACK_ARCHIVED_MARKER)
164
+ continue;
165
+ fs.rmSync(path.join(targetDir, entry.name), { recursive: true, force: true });
166
+ }
167
+ // ③ 标记:加载器据此把这些目录当作"已卸载、留了历史",不报 invalid。
168
+ if (archived.length > 0) {
169
+ fs.mkdirSync(targetDir, { recursive: true });
170
+ fs.writeFileSync(path.join(targetDir, PACK_ARCHIVED_MARKER), JSON.stringify({ archivedAt: new Date().toISOString(), archive: `logs/${archiveName}`, files: archived }, null, 2) + String.fromCharCode(10), 'utf8');
171
+ return { pack: options.pack, dir: targetDir, removed: true, archivedTo: `logs/${archiveName}` };
172
+ }
173
+ // 没有任何运行时产物:目录已成空壳,直接删掉。
174
+ fs.rmSync(targetDir, { recursive: true, force: true });
175
+ return { pack: options.pack, dir: targetDir, removed: true };
176
+ }
177
+ /** `pack list`:列出目标根下看起来像包的目录。 */
178
+ export function listPackDirs(targetRoot, manifestFile) {
179
+ let entries;
180
+ try {
181
+ entries = fs.readdirSync(path.resolve(targetRoot), { withFileTypes: true });
182
+ }
183
+ catch {
184
+ return [];
185
+ }
186
+ return entries
187
+ .filter(entry => entry.isDirectory() && !entry.name.startsWith('.') && !entry.name.startsWith('_'))
188
+ .sort((left, right) => left.name.localeCompare(right.name))
189
+ .map(entry => ({
190
+ pack: entry.name,
191
+ dir: path.join(path.resolve(targetRoot), entry.name),
192
+ installed: fs.existsSync(path.join(path.resolve(targetRoot), entry.name, manifestFile)),
193
+ }));
194
+ }
@@ -386,11 +386,12 @@ const APPLY_PATCH_EXECUTABLE_BASENAMES = new Set([
386
386
  'apply_patch.ps1',
387
387
  ]);
388
388
  const EVOLCORE_SUBCOMMANDS = new Set([
389
- 'ability', 'agent', 'aid', 'bench', 'config', 'events', 'peer', 'ctl', 'data', 'diag', 'diagnose',
389
+ 'ability', 'agent', 'aid', 'bench', 'config', 'events', 'services', 'peer', 'ctl', 'data', 'diag', 'diagnose',
390
390
  'fs', 'gateway', 'group', 'init', 'link-rules', 'logs', 'menu-client',
391
391
  'mode', 'model', 'msg', 'mv', 'net', 'queue', 'response', 'restart',
392
392
  'restart-monitor', 'rpc', 'start', 'stats', 'status', 'stop', 'storage', 'task',
393
393
  'trigger', 'proxy', 'version', 'watch', 'session', 'team', 'upgrade', 'update',
394
+ 'directory', 'getmeta', 'integrity', 'invoke', 'memory', 'provider', 'role', 'skill', 'thread',
394
395
  ]);
395
396
  // Development/install entrypoints that are part of this repository's CLI.
396
397
  // Only these exact relative paths are canonicalized; arbitrary Node scripts
@@ -3417,7 +3418,7 @@ export function isReadOnlyEcCommand(toolName, input) {
3417
3418
  export function containsUnresolvedManagedTmpDirReference(argv) {
3418
3419
  return argv.some(value => /(?:\\\$TMPDIR|\\\$\{TMPDIR\})/i.test(value));
3419
3420
  }
3420
- function hasExecutableProactiveSendPayload(argv, scope, bodyStart = 5) {
3421
+ function hasExecutableProactiveSendPayload(argv, scope, bodyStart = 5, options = {}) {
3421
3422
  if (!argv || argv[0] !== 'ec' || argv[1] !== scope || argv[2] !== 'send')
3422
3423
  return false;
3423
3424
  const positionals = [];
@@ -3449,8 +3450,16 @@ function hasExecutableProactiveSendPayload(argv, scope, bodyStart = 5) {
3449
3450
  const operand = argv[++index];
3450
3451
  if (operand === undefined || operand.startsWith('--'))
3451
3452
  return false;
3452
- if (value === '--file' || value === '--text-from-file')
3453
- return false;
3453
+ if (value === '--file' || value === '--text-from-file') {
3454
+ // 文件附件同样是向对端的意图表达:它和正文一起出现时不改变语义,
3455
+ // 单独出现时也把内容真实投递给了对端。只保留路径的确定性校验。
3456
+ if (!options.allowAttachment || !isDeterministicFilePath(operand))
3457
+ return false;
3458
+ if (modes.has('file'))
3459
+ return false;
3460
+ modes.set('file', operand);
3461
+ continue;
3462
+ }
3454
3463
  if (value === '--app' || value === '--aun-path')
3455
3464
  return false;
3456
3465
  if (value === '--format' && operand !== 'json')
@@ -3471,7 +3480,13 @@ function hasExecutableProactiveSendPayload(argv, scope, bodyStart = 5) {
3471
3480
  modes.set('payload-file', operand);
3472
3481
  }
3473
3482
  }
3474
- if (modes.size > 1 || (modes.size > 0 && positionals.length > 0))
3483
+ // 正文、链接、payload、payload-file 之间互斥;文件附件允许和正文一起出现。
3484
+ const contentModes = [...modes.keys()].filter(key => key !== 'file');
3485
+ if (contentModes.length > 1)
3486
+ return false;
3487
+ if (contentModes.length > 0 && positionals.length > 0)
3488
+ return false;
3489
+ if (contentModes.length > 0 && modes.has('file'))
3475
3490
  return false;
3476
3491
  if (modes.has('link')) {
3477
3492
  try {
@@ -3493,6 +3508,8 @@ function hasExecutableProactiveSendPayload(argv, scope, bodyStart = 5) {
3493
3508
  }
3494
3509
  if (modes.has('payload-file'))
3495
3510
  return true;
3511
+ if (modes.has('file'))
3512
+ return true;
3496
3513
  return positionals.join(' ').length > 0;
3497
3514
  }
3498
3515
  function parseEvolcoreSendArgv(argv) {
@@ -3576,16 +3593,21 @@ export function isExactEvolcoreSendCommandForSession(toolName, input, channelId,
3576
3593
  // 托管简化式:目标就是当前会话对端,无需在 argv 里写 from/to。
3577
3594
  // 这正是 `ecmsg send '<正文>'` 归一后的形态,必须被认作意图表达。
3578
3595
  if (isManagedSimplifiedSend(argv)) {
3579
- return hasExecutableProactiveSendPayload(argv, argv[1], 3);
3596
+ return hasExecutableProactiveSendPayload(argv, argv[1], 3, { allowAttachment: true });
3580
3597
  }
3581
- const parsed = parseEvolcoreSendArgv(argv);
3582
- if (!parsed || parsed.action !== 'send')
3583
- return false;
3598
+ // 完整式:argv[3]/argv[4] 必须是本人和当前会话目标。这里不复用
3599
+ // parseEvolcoreSendArgv:带 --file 的合法发送会被它归类成 file 动作,
3600
+ // 门禁据此误判"本轮没有发送",正文+文件一起回复的回合永远清不了计数。
3584
3601
  const expectedScope = chatType === 'group' ? 'group' : 'msg';
3585
- return parsed.scope === expectedScope
3586
- && parsed.targetId === channelId
3587
- && parsed.sourceId === selfAid
3588
- && hasExecutableProactiveSendPayload(argv, expectedScope);
3602
+ if (argv[1] !== expectedScope || argv[2] !== 'send')
3603
+ return false;
3604
+ const sourceId = argv[3];
3605
+ const targetId = argv[4];
3606
+ if (!sourceId || !targetId || sourceId.startsWith('--') || targetId.startsWith('--'))
3607
+ return false;
3608
+ return sourceId === selfAid
3609
+ && targetId === channelId
3610
+ && hasExecutableProactiveSendPayload(argv, expectedScope, 5, { allowAttachment: true });
3589
3611
  }
3590
3612
  /**
3591
3613
  * 逐项诊断 proactive 发送命令被拒的具体原因。只读 argv 与(可选的)会话参数,
@@ -3597,8 +3619,11 @@ export function describeProactiveSendCommandFailure(toolName, input, session) {
3597
3619
  return undefined;
3598
3620
  const commandText = [input.command, input.input, ...(Array.isArray(input.commandArgv) ? input.commandArgv : [])]
3599
3621
  .filter((value) => typeof value === 'string').join(' ');
3600
- if (!/\bec(?:\.cmd|\.exe)?\s+(?:group|msg)\s+send\b/i.test(commandText))
3622
+ // `ecmsg send` 是 `ec msg send` 的同义词,诊断必须同样认得,否则别名写法
3623
+ // 被拒时只会掉进"上一轮未包含意图表达"的笼统提示,模型拿不到可操作原因。
3624
+ if (!/\bec(?:\.cmd|\.exe)?\s+(?:group|msg)\s+send\b|\becmsg(?:\.cmd|\.exe|\.ps1)?\s+send\b/i.test(commandText)) {
3601
3625
  return undefined;
3626
+ }
3602
3627
  const result = parseProactiveToolCommand(toolName, input);
3603
3628
  if (!result)
3604
3629
  return '当前汇报命令未通过规范解析:只支持单次、字面量的发送调用,请将发送作为独立工具调用。';
@@ -3613,6 +3638,13 @@ export function describeProactiveSendCommandFailure(toolName, input, session) {
3613
3638
  // --help / -h 是只读的参数查询,不是发送调用,更不该计入 proactive 违规计数。
3614
3639
  if (argv.includes('--help') || argv.includes('-h'))
3615
3640
  return undefined;
3641
+ // 托管简化式(`ecmsg send '<正文>'`):from/to 由当前会话推断,
3642
+ // 不应再按"缺少发送者与目标"给建议,只可能是发送内容或参数无效。
3643
+ if (isManagedSimplifiedSend(argv)) {
3644
+ return '发送命令被拒:正文或参数无效——正文不能为空(或带 --file/--text-from-file 等发送内容);'
3645
+ + '--link 的值必须是 http(s) URL;--payload 的值必须是 JSON 对象;'
3646
+ + '--file/--text-from-file 的值必须是确定的文件路径。';
3647
+ }
3616
3648
  const scope = argv[1];
3617
3649
  const prefix = '发送命令被拒:';
3618
3650
  const expectedForm = `ec ${scope} send ${session?.selfAid ?? '<selfAid>'} `
@@ -3655,8 +3687,9 @@ export function describeProactiveSendCommandFailure(toolName, input, session) {
3655
3687
  return `${prefix}目标必须是当前会话${scope === 'group' ? '群' : '对端'} ${session.channelId},命令里写的是 ${to};`
3656
3688
  + `要联系其他对象请走 --thread 跨话题发送(ec thread list <对方AID> 选中话题后加 --check-every)。`;
3657
3689
  }
3658
- return `${prefix}发送者与目标正确,但正文或参数无效——正文不能为空;--file/--text-from-file 属于文件发送,`
3659
- + '不在普通回复放行范围;--link 的值必须是 http(s) URL;--payload 的值必须是 JSON 对象;--payload-file 的值必须是确定的文件路径。';
3690
+ return `${prefix}发送者与目标正确,但正文或参数无效——正文不能为空(或带 --file/--text-from-file 等发送内容);`
3691
+ + '--link 的值必须是 http(s) URL;--payload 的值必须是 JSON 对象;--payload-file 的值必须是确定的文件路径;'
3692
+ + '--file/--text-from-file 的值必须是确定的文件路径。';
3660
3693
  }
3661
3694
  /** 与 CLI `isValidAid` 同一规则;parser 不依赖 AID 模块,避免引入身份存储副作用。 */
3662
3695
  function looksLikeAid(value) {
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 分钟/小时双窗口限流,按 key 独立计数。
3
+ *
4
+ * 事件侧与服务侧共用同一份算法:两侧都是「按来源 AID 限制调用频率」,
5
+ * 差别只在额度来源(services-config.json 的 rateLimit vs events-config.json 的 rateLimit)。
6
+ * 抽出来是为了避免两套滑动窗口各自漂移——限流行为不一致比没有限流更难排查。
7
+ */
8
+ const MINUTE_MS = 60_000;
9
+ const HOUR_MS = 3_600_000;
10
+ export class RateWindow {
11
+ windows = new Map();
12
+ /** 记一次消费;超限时不计数并给出 retryAfter。 */
13
+ consume(key, quota, now = Date.now()) {
14
+ let window = this.windows.get(key);
15
+ if (!window) {
16
+ window = { minuteStart: now, minuteCount: 0, hourStart: now, hourCount: 0 };
17
+ this.windows.set(key, window);
18
+ }
19
+ if (now - window.minuteStart >= MINUTE_MS) {
20
+ window.minuteStart = now;
21
+ window.minuteCount = 0;
22
+ }
23
+ if (now - window.hourStart >= HOUR_MS) {
24
+ window.hourStart = now;
25
+ window.hourCount = 0;
26
+ }
27
+ if (window.minuteCount >= quota.perMinute) {
28
+ return { allow: false, retryAfter: Math.max(1, Math.ceil((window.minuteStart + MINUTE_MS - now) / 1000)) };
29
+ }
30
+ if (window.hourCount >= quota.perHour) {
31
+ return { allow: false, retryAfter: Math.max(1, Math.ceil((window.hourStart + HOUR_MS - now) / 1000)) };
32
+ }
33
+ window.minuteCount++;
34
+ window.hourCount++;
35
+ return { allow: true };
36
+ }
37
+ /** 定期清理空窗口,避免长期运行后按 AID 无限增长。 */
38
+ prune(now = Date.now()) {
39
+ for (const [key, window] of this.windows) {
40
+ if (now - window.hourStart >= HOUR_MS && now - window.minuteStart >= HOUR_MS)
41
+ this.windows.delete(key);
42
+ }
43
+ }
44
+ /** 清空全部窗口(配置切换 / 关闭时)。 */
45
+ reset() {
46
+ this.windows.clear();
47
+ }
48
+ }
@@ -155,6 +155,14 @@ export class PeerIdentityCache {
155
155
  const peerKey = formatPeerKey(channelType, peerId);
156
156
  return path.join(agentDir, 'relations', peerKey, 'peer-identity.json');
157
157
  }
158
+ /**
159
+ * 本端 AID 不是「对端」。agentDir 恒为 <agentsDir>/<selfAid>,因此可以直接
160
+ * 从目录名判断;命中时所有写盘路径都必须跳过,避免建出 `aun#<self>/`。
161
+ */
162
+ static isSelfPeer(peerId, agentDir) {
163
+ const selfAid = path.basename(path.normalize(agentDir)).trim().toLowerCase();
164
+ return !!selfAid && selfAid === String(peerId || '').trim().toLowerCase();
165
+ }
158
166
  /**
159
167
  * 从文件读取缓存
160
168
  * @returns PeerIdentity | null(缓存不存在)
@@ -246,6 +254,8 @@ export class PeerIdentityCache {
246
254
  lastCheckedAt: now,
247
255
  source,
248
256
  };
257
+ if (this.isSelfPeer(peerId, agentDir))
258
+ return identity;
249
259
  const filePath = this.getFilePath(channelType, peerId, agentDir);
250
260
  try {
251
261
  fs.mkdirSync(path.join(path.dirname(filePath), 'shared'), { recursive: true });
@@ -284,6 +294,8 @@ export class PeerIdentityCache {
284
294
  lastCheckedAt: Date.now(),
285
295
  source: 'unknown',
286
296
  };
297
+ if (this.isSelfPeer(peerId, agentDir))
298
+ return identity;
287
299
  const filePath = this.getFilePath(channelType, peerId, agentDir);
288
300
  try {
289
301
  fs.mkdirSync(path.join(path.dirname(filePath), 'shared'), { recursive: true });
@@ -329,6 +341,22 @@ export class PeerIdentityCache {
329
341
  };
330
342
  }
331
343
  peerId = peerId.trim();
344
+ // 本端不是「对端」。跨话题自派会走 AUN 一跳(发给本端),若照常解析并落盘,
345
+ // relations/ 下就会多出 `aun#<self>/` 这种「我↔我」目录,污染对端名录和
346
+ // 后续的关系判定。这里只返回内存身份,不读也不写关系缓存。
347
+ if (this.isSelfPeer(peerId, agentDir)) {
348
+ return {
349
+ aid: peerId,
350
+ type: 'agent',
351
+ isMachine: true,
352
+ isAgent: true,
353
+ agentMdHash: '',
354
+ agentMdUpdatedAt: 0,
355
+ verifiedAt: 0,
356
+ lastCheckedAt: Date.now(),
357
+ source: 'unknown',
358
+ };
359
+ }
332
360
  // 1. 缓存检查
333
361
  if (!forceRefresh && !this.needsRefresh(channelType, peerId, agentDir)) {
334
362
  const cached = this.get(channelType, peerId, agentDir);
@@ -2,6 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { createInterface } from 'node:readline';
4
4
  import { setImmediate as yieldToIo } from 'node:timers/promises';
5
+ import { performance } from 'node:perf_hooks';
5
6
  // 文件系统非法字符(Windows 最严格):< > : " / \ | ? *
6
7
  // 还有控制字符 0x00-0x1F。我们把这些字符编码为 %XX(hex 大写)。
7
8
  // `%` 本身也要转义为 %25,保证可逆。
@@ -464,8 +465,9 @@ export function readLastJsonlLine(filePath) {
464
465
  }
465
466
  }
466
467
  /** Async tail reader with the same committed-record rules as the sync readers. */
467
- export async function readLastJsonlLineAsync(filePath, strict = false) {
468
+ export async function readLastJsonlLineAsync(filePath, strict = false, timing) {
468
469
  let handle;
470
+ let started = timing ? performance.now() : 0;
469
471
  try {
470
472
  handle = await fs.promises.open(filePath, 'r');
471
473
  }
@@ -474,21 +476,40 @@ export async function readLastJsonlLineAsync(filePath, strict = false) {
474
476
  return undefined;
475
477
  throw error;
476
478
  }
479
+ finally {
480
+ if (timing)
481
+ timing.openMs += performance.now() - started;
482
+ }
477
483
  try {
478
- let cursor = (await handle.stat()).size;
484
+ started = timing ? performance.now() : 0;
485
+ let cursor;
486
+ try {
487
+ cursor = (await handle.stat()).size;
488
+ }
489
+ finally {
490
+ if (timing)
491
+ timing.statMs += performance.now() - started;
492
+ }
479
493
  let carry = Buffer.alloc(0);
480
494
  let skipUncommitted = strict;
481
495
  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);
496
+ const parseStarted = timing ? performance.now() : 0;
487
497
  try {
488
- return JSON.parse(line);
498
+ const line = raw.toString('utf8').trim();
499
+ if (!line)
500
+ return undefined;
501
+ if (strict)
502
+ return parseJsonlLineStrict(line, filePath, offset);
503
+ try {
504
+ return JSON.parse(line);
505
+ }
506
+ catch {
507
+ return undefined;
508
+ }
489
509
  }
490
- catch {
491
- return undefined;
510
+ finally {
511
+ if (timing)
512
+ timing.parseMs += performance.now() - parseStarted;
492
513
  }
493
514
  };
494
515
  while (cursor > 0) {
@@ -496,7 +517,17 @@ export async function readLastJsonlLineAsync(filePath, strict = false) {
496
517
  const chunk = Buffer.allocUnsafe(cursor - start);
497
518
  let offset = 0;
498
519
  while (offset < chunk.length) {
499
- const { bytesRead } = await handle.read(chunk, offset, chunk.length - offset, start + offset);
520
+ started = timing ? performance.now() : 0;
521
+ let bytesRead;
522
+ try {
523
+ ({ bytesRead } = await handle.read(chunk, offset, chunk.length - offset, start + offset));
524
+ }
525
+ finally {
526
+ if (timing)
527
+ timing.readMs += performance.now() - started;
528
+ }
529
+ if (timing)
530
+ timing.bytes += bytesRead;
500
531
  if (!bytesRead)
501
532
  throw new Error(`short JSONL read at ${filePath}:${start + offset}`);
502
533
  offset += bytesRead;
@@ -521,7 +552,14 @@ export async function readLastJsonlLineAsync(filePath, strict = false) {
521
552
  return skipUncommitted ? undefined : parse(carry, 0);
522
553
  }
523
554
  finally {
524
- await handle.close();
555
+ started = timing ? performance.now() : 0;
556
+ try {
557
+ await handle.close();
558
+ }
559
+ finally {
560
+ if (timing)
561
+ timing.closeMs += performance.now() - started;
562
+ }
525
563
  }
526
564
  }
527
565
  export function readAllJsonlLines(filePath) {
@@ -607,17 +645,19 @@ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey,
607
645
  throw error;
608
646
  }
609
647
  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) => {
648
+ let next = 0;
649
+ const workers = await Promise.allSettled(Array.from({ length: Math.min(8, entries.length) }, async () => {
650
+ while (next < entries.length) {
651
+ const entry = entries[next++];
612
652
  if (!entry.isDirectory())
613
- return undefined;
653
+ continue;
614
654
  const parsed = tryParseChannelSessionKey(entry.name);
615
655
  if (!parsed)
616
- return undefined;
656
+ continue;
617
657
  const key = parsed.channelType === 'daemon' ? 'daemon'
618
658
  : `${parsed.channelType}#${selfAID}#${parsed.channelName}`;
619
659
  if (channelKey && key !== channelKey)
620
- return undefined;
660
+ continue;
621
661
  const dirPath = path.join(sessionsDir, entry.name);
622
662
  let payload;
623
663
  try {
@@ -625,18 +665,18 @@ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey,
625
665
  }
626
666
  catch (error) {
627
667
  if (error.code === 'ENOENT')
628
- return undefined;
668
+ continue;
629
669
  throw error;
630
670
  }
631
671
  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
- }
672
+ continue;
673
+ results.push({ channelType: parsed.channelType, selfAID, channelId: parsed.channelId,
674
+ channelKey: key, channelSessionKey: entry.name, dirPath, ...(options?.includeEntries ? { entries: payload } : {}) });
675
+ }
676
+ }));
677
+ for (const worker of workers)
678
+ if (worker.status === 'rejected')
679
+ throw worker.reason;
640
680
  return results.sort((a, b) => a.dirPath < b.dirPath ? -1 : a.dirPath > b.dirPath ? 1 : 0);
641
681
  }
642
682
  /**