evolcore 0.0.43-test.4 → 0.0.43-test.5

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 (129) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/bin/ecmsg.js +354 -91
  3. package/dist/agents/codex-runner.js +12 -17
  4. package/dist/aun/aid/agentmd.js +25 -0
  5. package/dist/aun/aid/control-aid.js +15 -0
  6. package/dist/aun/aid/identity.js +8 -0
  7. package/dist/aun/aid/ownership-operation.js +12 -3
  8. package/dist/channels/aun.js +30 -17
  9. package/dist/channels/daemon.js +2 -2
  10. package/dist/cli/agent-create.js +4 -2
  11. package/dist/cli/aid-bind-command.js +3 -0
  12. package/dist/cli/aun-commands.js +10 -3
  13. package/dist/cli/code-stats.js +451 -213
  14. package/dist/cli/ctl-command.js +1 -3
  15. package/dist/cli/daemon-commands.js +12 -3
  16. package/dist/cli/directory.js +3 -1
  17. package/dist/cli/ecmsg-gateway.js +204 -0
  18. package/dist/cli/index.js +6 -0
  19. package/dist/cli/init.js +45 -13
  20. package/dist/cli/provider-command.js +82 -5
  21. package/dist/cli/restart-monitor.js +11 -19
  22. package/dist/cli/stats.js +8 -1
  23. package/dist/cli/task-context.js +3 -0
  24. package/dist/config/boot-log.js +12 -1
  25. package/dist/config/config-manager.js +4 -13
  26. package/dist/config/daemon-services.js +1 -0
  27. package/dist/config/peer-role-resolver.js +5 -5
  28. package/dist/config/provider-identity-migration.js +202 -0
  29. package/dist/config/provider-identity.js +37 -0
  30. package/dist/config/provider-ipc-service.js +40 -3
  31. package/dist/config/provider-local-sync.js +153 -0
  32. package/dist/config/providers-config.js +32 -4
  33. package/dist/config/providers-management.js +144 -68
  34. package/dist/config/providers.js +4 -1
  35. package/dist/config/schema-migration.js +67 -3
  36. package/dist/core/agent-runtime.js +4 -2
  37. package/dist/core/auth/auth-gateway.js +5 -3
  38. package/dist/core/auth/delegation-diagnostics.js +6 -2
  39. package/dist/core/auth/operation-authorizer.js +3 -1
  40. package/dist/core/auth/operation-catalog.js +6 -4
  41. package/dist/core/command/cli-intent-parser.js +2 -1
  42. package/dist/core/command/command-handler.js +11 -6
  43. package/dist/core/command/menu-protocol.js +4 -2
  44. package/dist/core/command/provider-menu.js +4 -2
  45. package/dist/core/command/role-menu.js +2 -2
  46. package/dist/core/command/slash-handler.js +52 -16
  47. package/dist/core/handoff/runtime.js +9 -3
  48. package/dist/core/initialization/service.js +4 -3
  49. package/dist/core/message/aun-ipc-sender.js +81 -3
  50. package/dist/core/message/message-admission.js +2 -0
  51. package/dist/core/message/response-engine.js +23 -23
  52. package/dist/core/message/send-options.js +40 -0
  53. package/dist/core/message/send-routing.js +310 -0
  54. package/dist/core/ownership/owner-resolver.js +111 -8
  55. package/dist/core/permission/ec-command-parser.js +148 -15
  56. package/dist/core/permission/readonly-shell-query.js +66 -7
  57. package/dist/core/permission/tool-error-code.js +13 -1
  58. package/dist/core/permission/tool-policy.js +74 -20
  59. package/dist/core/relation/same-owner-proof.js +131 -0
  60. package/dist/core/session/session-idle-monitor.js +94 -16
  61. package/dist/core/session/session-manager.js +69 -16
  62. package/dist/core/thread/thread-route.js +5 -2
  63. package/dist/directory/owner-directory-cache.js +686 -97
  64. package/dist/directory/owner-directory-markdown.js +146 -36
  65. package/dist/directory/owner-directory-query-operation.js +2 -2
  66. package/dist/directory/owner-directory-scope.js +12 -0
  67. package/dist/directory/owner-directory-search.js +5 -1
  68. package/dist/directory/owner-directory-store.js +28 -0
  69. package/dist/ecweb/basic-settings-service.js +15 -1
  70. package/dist/ecweb/message-context-service.js +2 -2
  71. package/dist/ecweb/providers-service.js +3 -1
  72. package/dist/ecweb/runtime/lifecycle.js +18 -9
  73. package/dist/ecweb/runtime/supervisor.js +76 -24
  74. package/dist/index.js +4 -0
  75. package/dist/paths.js +2 -1
  76. package/dist/proxy/manager.js +2 -0
  77. package/dist/proxy/service-supervisor.js +2 -2
  78. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  79. package/dist/trigger/application-service.js +1 -0
  80. package/dist/trigger/event-source.js +4 -0
  81. package/dist/trigger/feedback.js +26 -2
  82. package/dist/trigger/scheduler.js +3 -3
  83. package/dist/trigger/system-definitions.js +2 -2
  84. package/dist/trigger/validation.js +4 -0
  85. package/dist/utils/autostart.js +2 -2
  86. package/dist/utils/cross-platform.js +36 -8
  87. package/dist/utils/public-suffix.js +5811 -0
  88. package/dist/utils/windows-autostart.js +41 -7
  89. package/ecagent/dist/harness/env/nodejs.js +46 -2
  90. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  91. package/kits/docs/channels/aun.md +1 -1
  92. package/kits/docs/channels/feishu.md +2 -2
  93. package/kits/docs/context-assembly.md +20 -4
  94. package/kits/docs/evolcore/INDEX.md +2 -1
  95. package/kits/docs/evolcore/agent.md +2 -2
  96. package/kits/docs/evolcore/aid.md +8 -2
  97. package/kits/docs/evolcore/ctl.md +13 -4
  98. package/kits/docs/evolcore/directory.md +48 -15
  99. package/kits/docs/evolcore/group.md +6 -6
  100. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  101. package/kits/docs/evolcore/menu-protocol.md +32 -3
  102. package/kits/docs/evolcore/msg.md +28 -27
  103. package/kits/docs/evolcore/provider.md +39 -5
  104. package/kits/docs/evolcore/response.md +1 -1
  105. package/kits/docs/evolcore/thread-chain.md +11 -13
  106. package/kits/docs/evolcore/tool-authorization.md +17 -0
  107. package/kits/docs/evolcore/trigger.md +2 -2
  108. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  109. package/kits/docs/prompt-loading-architecture.md +30 -20
  110. package/kits/eck_manifest.auxiliary.json +5 -5
  111. package/kits/eck_manifest.json +28 -28
  112. package/kits/eck_manifest.memory.json +18 -18
  113. package/kits/rules/01-overview.md +1 -1
  114. package/kits/rules/06-channel.md +3 -3
  115. package/kits/schemas/_meta.json +7 -1
  116. package/kits/schemas/providers.schema.2.json +74 -0
  117. package/kits/schemas/role-registry.schema.1.json +1 -1
  118. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  119. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  120. package/kits/skills/ec-trigger/SKILL.md +5 -5
  121. package/kits/skills/ec-trigger/references/examples.md +1 -1
  122. package/kits/templates/system-fragments/channel.md +5 -5
  123. package/kits/templates/system-fragments/commands.md +3 -2
  124. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  125. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  126. package/kits/templates/system-fragments/reply.md +47 -28
  127. package/kits/templates/system-fragments/session.md +2 -9
  128. package/kits/templates/system-fragments/thread.md +5 -5
  129. package/package.json +2 -3
package/CHANGELOG.md CHANGED
@@ -5,6 +5,52 @@
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ ## 0.0.43-test.5 (2026-11-07)
9
+
10
+ ### 身份、Owner 与联系人
11
+
12
+ - Agent 常驻设定改用 personal/soul/ 分册,迁移旧 persona.md;移除 ec agent persona 命令,保留已有设定的覆盖保护。
13
+ - 显示名跟随签名名片刷新,移除一次性自我介绍注入;支持关闭首次欢迎消息,并在创建 Agent 时指定和校验 Provider。
14
+ - 新增 App 联系人准入协议及 allowAllContacts 总开关,完善黑名单、临时授权、Owner 名录范围、缓存同步和备注维护;出站联系前按需核验 Owner,未准入时向本端 Owner 申请。
15
+ - 同 Owner 默认角色适用于签名名片及协议归属核验通过的内部 Agent;敏感操作前重新核验,身份变化后使授权缓存失效。
16
+ - 名录查询统一为 ec directory list/info,移除 find/show 别名;完善分页、搜索、结构化错误及文件变化检测。
17
+ - 普通 Agent 新建 Owner 关系时要求目标为验签通过的 human;已激活但尚未绑定的 Agent 支持启动补绑定,拒绝记录可显式清除;协议关系确认后清理旧 Owner 配置字段。
18
+
19
+ ### 对话、模型与自动化
20
+
21
+ - 新增 paactive 私聊模式,通过可靠 activity 展示助理活动;群聊统一使用 proactive,输出遵循活动显示配置。
22
+ - 统一模型容量解析,按当前 Provider 计算自动压缩阈值,更新模型与价格数据;修正压缩后上下文用量,并增加手动压缩进度通知。
23
+ - ecagent 支持只读访问入站附件并校验真实路径;非法工具参数转为可恢复错误,摘要失败不再自动重试。
24
+ - Trigger 跟随 Agent 当前基座,阻止恢复基座不匹配的任务;支持静默结果和带自定义提示词的单次闲置触发。
25
+ - 完善任务取消、子进程清理和失败反馈;输入已提交而结果不明时不重复提交,明确上下文超限不进入通用重试。
26
+
27
+ ### 消息与权限
28
+
29
+ - 新增 ecmsg 统一发送入口,统一话题路由、复查和加密选项,并支持向其他渠道的既有会话投递;非 AUN 会话可发送当前会话的纯文本回复。
30
+ - AUN Menu 请求与响应使用独立 control 消息流,响应强制加密;模型信息、Slash 回执及运行状态使用结构化通知。
31
+ - 完善 Fullaccess 委托核验、授权审计、PowerShell 与跨 Shell 参数解析,以及只读查询和路径范围判断;可信 Fullaccess 任务可读取原始日志。
32
+ - 停止向 Owner 观察通道转发 thought.put 返回结果,完善工具参数错误与权限拒绝的归因。
33
+
34
+ ### 能力插件与工作区
35
+
36
+ - 新增按 Agent 或主机 AID 管理的能力插件平台,支持开发、构建、安装、授权、发布、升级及回滚,并提供 EC Web 管理入口。
37
+ - 支持多种进程运行时,完善能力发现、多设备结果、请求关联、契约校验和重放保护;资源代理增加批量存储与工作区读取。
38
+ - PA 工作区增加项目索引、清空和锁定操作,完善初始化、迁移与路径规范;任务图片按活动保存为可校验的不可变资源。
39
+
40
+ ### Provider、安装与运行管理
41
+
42
+ - Provider 改用基于域名的稳定 ID,增加 v2 Schema、旧 ID 别名及引用迁移;迁移冲突时保留原配置并阻止启动,环境变量地址需提供有效域名。
43
+ - 支持同步本机 Provider 与默认模型配置,完善地址固化、导入合并、接口风格保存和配置写入顺序。
44
+ - 并行初始化 Agent,按就绪状态门控消息、渠道和管理操作;完善启动耗时、动作日志及并行停机。
45
+ - 强化受管服务与 EC Web 的实例身份、串行生命周期、健康检查和恢复计数;支持跨平台协作退出,阻止旧进程未停止时启动替代实例。
46
+ - 完善 Windows 安装卸载、编码、PATH、自启动诊断及确认后修复;强化控制 AID 材料校验和 CLI 探测,裸跑 ec 显示帮助,移除 ec handoff 入口。
47
+ - PA 看板入口改为独立服务页面,仅为同源本机请求签发令牌;看板服务需单独部署。
48
+
49
+ ### 依赖与兼容性
50
+
51
+ - AUN SDK 最低兼容版本提升至 0.5.32;Node.js 要求保持 >=22.16.0,配套 ec-web@0.0.43-test.5,EC Web 服务协议为 1.5。
52
+ - Agent、Relation、Role Schema 分别收敛为 v19、v12、v2;兼容的 Agent v20 与 Relation v13 配置启动时备份迁移,自定义 Role v3 需人工调整。
53
+
8
54
  ## 0.0.43-test.4 (2026-11-06)
9
55
 
10
56
  ### 模型、会话与自动化
package/bin/ecmsg.js CHANGED
@@ -1,26 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * `ecmsg` —— `ec msg` 的轻量等价入口。
3
+ * `ecmsg` —— 统一发送网关。
4
4
  *
5
- * 动机:`ec msg send` 单次约 1.4s,其中 95% 是 CLI 模块图加载
6
- * (agent-delegation 单模块 382ms、task-context 429ms、aun-commands 更重)。
7
- * daemon 侧本来就自己解析 argv(aun-ipc-sender 调 resolveManagedSendArgv),
8
- * CLI 只负责透传,所以这条命令不需要那套模块。
5
+ * 设计依据:`docs/send-routing/unified-send-routing-plan.md`
9
6
  *
10
- * 语义:`ecmsg <args...>` ≡ `ec msg <args...>`。例如
11
- * ecmsg send <from> <to> --content 'hi' ≡ ec msg send <from> <to> --content 'hi'
7
+ * 职责边界(第一期):
8
+ * - 只做**路由**:解析目标三元组、判跨话题、决定复查与加密,然后分派给
9
+ * 现有的内部发送通道。
10
+ * - 不改写任何内部通道的实现。`ec msg send` / `ec group send` / `ec ctl send`
11
+ * 全部保持原状可用。
12
12
  *
13
- * 为什么必须走 ec-command-parser 归一而不是自己拼字符串:委托审批按「规范化
14
- * argv 的 sha256」arm(codex-runner 的 armApprovedDelegationCommand)。`ecmsg`
15
- * 必须归一到 `['ec','msg',...]`,才能与策略层 arm 的哈希对上;否则 daemon 返回
16
- * INVALID_DELEGATION,且会绕过复合命令拦截与会话身份绑定,成为冒充发送的后门。
13
+ * 为什么必须有这一层:
14
+ * 模型面对三种写法时必须先判断"用哪种",判断错就失败。网关把判断收敛为一
15
+ * 次确定性解析,并把"跨话题才要复查""同话题不许建复查""加密看对端是否 AUN"
16
+ * 这些条件约束全部在参数层消化,不下放给模型记规则。
17
17
  *
18
- * 性能约束:本文件只允许 import node 内建模块 + ec-command-parser(纯函数,
19
- * 实测 8ms)。**不要** import agent-delegation.js(382ms)——哈希算法在下面
20
- * 内联实现,与 hashDelegatedCommandArgv 逐字节一致,改动时两处必须同步。
18
+ * 委托哈希约束(关键):
19
+ * 审批按「规范化 argv 的 sha256」arm(codex-runner 的
20
+ * armApprovedDelegationCommand),而 `ec-command-parser` 把 `ecmsg` 归一为
21
+ * `['ec','msg',...]`。网关必须用归一化后的 argv 计算哈希,否则 daemon 侧
22
+ * 算不出匹配的 arm,必然 INVALID_DELEGATION。
23
+ *
24
+ * 本文件只负责 IO:读环境、加载 dist 模块、IPC、渲染回执。
25
+ * 参数解析与下游 argv 构造在 `dist/cli/ecmsg-gateway.js`(纯函数,可单测)。
21
26
  */
22
27
  import net from 'node:net';
23
- import fs from 'node:fs';
24
28
  import path from 'node:path';
25
29
  import crypto from 'node:crypto';
26
30
  import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -33,27 +37,46 @@ const ENV_CODEX_SESSION_TOKEN = 'EVOLCORE_CODEX_SESSION_TOKEN';
33
37
  const ENV_TASK_RUNTIME_CONTEXT = 'EVOLCORE_TASK_RUNTIME_CONTEXT';
34
38
  const ENV_SESSION_ID = 'EVOLCORE_SESSION_ID';
35
39
  const ENV_EXECUTION_SPEC = 'EVOLCORE_DELEGATED_EXECUTION_SPEC';
36
- /** 与 src/product.ts 的 MAIN_CLI_BIN 一致。 */
37
40
  const MAIN_CLI_BIN = 'ec';
38
41
 
39
- function fail(message) {
40
- process.stderr.write(`❌ ${message}\n`);
41
- process.exit(1);
42
- }
42
+ const HELP = `用法: ecmsg send '<正文>' [选项]
43
+ ecmsg send '<正文>' --thread <话题id>
44
+ ecmsg send '<正文>' --to <对端ID>
45
+
46
+ 发送目标(三选一,优先级从高到低):
47
+ (省略) 回复当前会话的对端/群
48
+ --thread <话题id> 发到指定话题;只接受 thread-… 或 main:<aidA>:<aidB>
49
+ --to <对端ID> 发到指定对端
50
+
51
+ 复查:
52
+ 跨话题(对端或话题与会话不同)自动创建复查 Trigger,默认 20m;
53
+ --check-every <时长> 自定义复查周期(5m/30m/2h/1d)
54
+ 同话题永不创建复查;此时传 --check-every 只在回执里说明,不报错。
55
+
56
+ 加密:
57
+ --encrypt yes|no|auto 默认 auto:被对端消息触发时跟随该消息,否则明文
58
+ 只有目标对端在 AUN 网络上才能加密;非 AUN 目标用 yes 会被拒绝。
59
+
60
+ 正文来源:
61
+ '<正文>' 位置参数
62
+ --text-from-file <path> 从文件读取
63
+ --file <path> 附件(可配 --as image|video|voice|file、--text 说明)
64
+ --link <url> [--title T] 链接卡片
65
+ --payload '<json>' 自定义 payload
66
+
67
+ 其它:
68
+ --format json 输出 JSON 回执
69
+ --help 显示本帮助
70
+
71
+ 示例:
72
+ ecmsg send '收到,稍后回你'
73
+ ecmsg send '问题已记录' --thread thread-1793851439746-7477-6351
74
+ ecmsg send '进度如何' --to wang.agentid.pub --check-every 10m
75
+ ecmsg send '报告在这里' --file ./report.md --as file
76
+ `;
77
+
78
+ // ── 委托哈希(与 agent-delegation.ts 逐字节一致,改动时两处必须同步) ──
43
79
 
44
- const HELP = [
45
- '用法: ecmsg <msg 子命令及参数>',
46
- ' ecmsg 等价于 ec msg,参数原样透传:',
47
- '',
48
- " ecmsg send <from> <to> --content '正文'",
49
- ' ecmsg send <from> <to> --file <path>',
50
- ' ecmsg history <from> <to> --limit 20',
51
- '',
52
- '非托管环境请直接使用 ec msg。',
53
- '',
54
- ].join('\n');
55
-
56
- /** 与 hashDelegatedCommandSpec 一致:v1 + 直接序列化原对象(顺序敏感,不可重排)。 */
57
80
  function hashExecutionSpec(spec) {
58
81
  if (!spec || typeof spec !== 'object') return undefined;
59
82
  const values = [
@@ -77,10 +100,6 @@ function hashExecutionSpec(spec) {
77
100
  .digest('hex');
78
101
  }
79
102
 
80
- /**
81
- * 与 src/core/auth/agent-delegation.ts 的 hashDelegatedCommandArgv 逐字节一致。
82
- * v1 无执行规格;v2 绑定执行规格(argv 必须与之相同)。
83
- */
84
103
  function hashDelegatedCommandArgv(argv, executionSpec) {
85
104
  if (!Array.isArray(argv) || argv.length === 0) return undefined;
86
105
  if (argv.some(value => typeof value !== 'string' || value.includes('\0'))) return undefined;
@@ -94,7 +113,7 @@ function hashDelegatedCommandArgv(argv, executionSpec) {
94
113
  .digest('hex');
95
114
  }
96
115
 
97
- /** 读执行规格:仅在 argv 完全匹配当前命令时才生效(同 readDelegatedExecutionSpec)。 */
116
+ /** 读执行规格:仅在 argv 完全匹配当前命令时才生效。 */
98
117
  function readDelegatedExecutionSpec(normalizedArgv, env) {
99
118
  const raw = env[ENV_EXECUTION_SPEC]?.trim();
100
119
  if (!raw || raw.length > 16 * 1024) return undefined;
@@ -109,19 +128,8 @@ function readDelegatedExecutionSpec(normalizedArgv, env) {
109
128
  return spec;
110
129
  }
111
130
 
112
- /**
113
- * 复用 dist/paths.js 的端点解析(实测 7ms)。
114
- *
115
- * 不要在这里手写管道名:root 的规范化规则(大小写、尾分隔符、canonical 变体)
116
- * 一旦漂移,就会连不上 daemon。用官方实现是唯一可靠做法。
117
- */
118
- async function resolveSocketPath() {
119
- const pathsUrl = pathToFileURL(path.join(repoRoot, 'dist', 'paths.js')).href;
120
- const { resolvePaths } = await import(pathsUrl);
121
- return resolvePaths().socket;
122
- }
131
+ // ── daemon IPC ──
123
132
 
124
- /** 一次请求一个连接:与 src/ipc.ts 的 ipcQueryOnce 同协议(单行 JSON + \n)。 */
125
133
  function queryDaemonOnce(socketPath, payload, timeoutMs = 120_000) {
126
134
  return new Promise(resolve => {
127
135
  let settled = false;
@@ -131,7 +139,7 @@ function queryDaemonOnce(socketPath, payload, timeoutMs = 120_000) {
131
139
  if (settled) return;
132
140
  settled = true;
133
141
  if (timer) clearTimeout(timer);
134
- try { socket.destroy(); } catch {}
142
+ try { socket.destroy(); } catch { /* ignore */ }
135
143
  resolve(value);
136
144
  };
137
145
  const socket = net.createConnection(socketPath);
@@ -148,82 +156,337 @@ function queryDaemonOnce(socketPath, payload, timeoutMs = 120_000) {
148
156
  });
149
157
  }
150
158
 
159
+ const distUrl = relative => pathToFileURL(path.join(repoRoot, 'dist', relative)).href;
160
+ const BUILD_HINT = 'ecmsg 需要已构建的 dist,请先 npm run build';
161
+
162
+ async function loadDist(relative) {
163
+ try {
164
+ return await import(distUrl(relative));
165
+ } catch {
166
+ return undefined;
167
+ }
168
+ }
169
+
170
+ // ── 错误输出 ──
171
+
172
+ let jsonOutput = false;
173
+
174
+ function fail(message, code, extra = {}) {
175
+ if (jsonOutput) {
176
+ process.stdout.write(`${JSON.stringify({ ok: false, code: code ?? 'ECMSG_FAILED', error: message, ...extra })}\n`);
177
+ } else {
178
+ // 错误码在文本模式下也要可见:排查时靠它区分"参数写错"和"被权限拒绝"。
179
+ process.stderr.write(`❌ ${message}${code ? ` [${code}]` : ''}\n`);
180
+ if (extra.hint) process.stderr.write(` ${extra.hint}\n`);
181
+ }
182
+ process.exit(1);
183
+ }
184
+
185
+ /** `--format json` 的预扫描:参数解析失败时也要按 JSON 报错,所以先看一遍。 */
186
+ function wantsJsonOutput(args) {
187
+ for (let index = 0; index < args.length; index++) {
188
+ const token = args[index];
189
+ if (token === '--') return false;
190
+ if (token === '--format') return args[index + 1] === 'json';
191
+ if (token.startsWith('--format=')) return token.slice('--format='.length) === 'json';
192
+ }
193
+ return false;
194
+ }
195
+
196
+ // ── 主流程 ──
197
+
151
198
  async function main() {
152
- const args = process.argv.slice(2);
153
- if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
199
+ const argv = process.argv.slice(2);
200
+ if (argv.length === 0) { process.stdout.write(HELP); return; }
201
+ if (argv[0] === '--help' || argv[0] === '-h' || argv[0] === 'help') {
154
202
  process.stdout.write(HELP);
155
203
  return;
156
204
  }
157
205
 
206
+ const sub = argv[0];
207
+ if (sub !== 'send') {
208
+ fail(`ecmsg 目前只支持 send(收到 ${sub})`, 'NOT_IMPLEMENTED',
209
+ { hint: sub === 'history' ? '查看历史请用 ec msg history' : '用 --help 查看发送用法' });
210
+ }
211
+
212
+ const routing = await loadDist('core/message/send-routing.js');
213
+ const gateway = await loadDist('cli/ecmsg-gateway.js');
214
+ if (!routing || !gateway) fail(BUILD_HINT, 'BUILD_REQUIRED');
215
+
216
+ jsonOutput = wantsJsonOutput(argv.slice(1));
217
+ const parsed = gateway.parseGatewayArgs(argv.slice(1));
218
+ if (!parsed.ok) fail(parsed.error, 'INVALID_ARGUMENT');
219
+ const { route: routeOpts, passthrough, text } = parsed;
220
+ if (routeOpts.help) { process.stdout.write(HELP); return; }
221
+ jsonOutput = jsonOutput || routeOpts.format === 'json';
222
+
158
223
  const sessionId = process.env[ENV_SESSION_ID]?.trim();
159
224
  const delegationToken = process.env[ENV_DELEGATION_TOKEN]?.trim()
160
225
  || process.env[ENV_CODEX_SESSION_TOKEN]?.trim();
161
- if (!sessionId) fail('ecmsg 只能在托管会话内使用(缺少 EVOLCORE_SESSION_ID)。宿主终端请用 ec msg。');
162
- if (!delegationToken) fail('ecmsg 需要会话委托凭证(缺少 EVOLCORE_DELEGATION_TOKEN)。请改用 ec msg。');
163
-
164
- // 归一化:['ecmsg','send','A','B'] -> ['ec','msg','send','A','B']
165
- const parserUrl = pathToFileURL(path.join(repoRoot, 'dist', 'core', 'permission', 'ec-command-parser.js')).href;
166
- let normalizeEvolcoreCommandArgv;
167
- try {
168
- ({ normalizeEvolcoreCommandArgv } = await import(parserUrl));
169
- } catch {
170
- fail('ecmsg 需要已构建的 dist。请先 npm run build,或改用 ec msg。');
226
+ if (!sessionId) {
227
+ fail('ecmsg 只能在 EvolCore 托管会话内使用(缺少 EVOLCORE_SESSION_ID)。宿主终端请用 ec msg send。',
228
+ 'NO_SESSION');
171
229
  }
172
- const normalizedArgv = normalizeEvolcoreCommandArgv(['ecmsg', ...args]);
173
- if (normalizedArgv[0] !== MAIN_CLI_BIN || normalizedArgv[1] !== 'msg') {
174
- fail(`无法把参数规范化为 ec msg:${JSON.stringify(normalizedArgv.slice(0, 4))}`);
175
- }
176
-
177
- const executionSpec = readDelegatedExecutionSpec(normalizedArgv, process.env);
178
- const delegationCommandHash = hashDelegatedCommandArgv(normalizedArgv, executionSpec);
179
-
180
- // daemon 按 resolveManagedSendArgv(params.argv) 解析,argv[0] 必须是 'msg'。
181
- const daemonArgv = normalizedArgv.slice(1);
230
+ if (!delegationToken) fail('ecmsg 需要会话委托凭证(缺少 EVOLCORE_DELEGATION_TOKEN)。', 'DELEGATION_REQUIRED');
182
231
 
183
- const runtimeCtx = (() => {
232
+ const runtime = (() => {
184
233
  const raw = process.env[ENV_TASK_RUNTIME_CONTEXT];
185
234
  if (!raw) return undefined;
186
235
  try { return JSON.parse(raw); } catch { return undefined; }
187
236
  })();
237
+ if (!runtime?.selfAid || !runtime?.channel || !runtime?.chatType) {
238
+ fail('运行时上下文不完整(缺少 selfAid/channel/chatType),无法确定本端与对端',
239
+ 'CONTEXT_INCOMPLETE');
240
+ }
188
241
 
189
- const result = await queryDaemonOnce(await resolveSocketPath(), {
242
+ // 空字符串也算"有正文"会把空消息推给下游;这里按去空白后的内容判断。
243
+ const hasBody = text.some(part => part.trim().length > 0)
244
+ || passthrough.some(flag => gateway.BODY_FLAGS.has(flag));
245
+ if (!hasBody) fail('缺少正文', 'INVALID_ARGUMENT', { hint: "例:ecmsg send '收到'" });
246
+
247
+ // 话题索引:只有 --thread 是独立话题时才真读盘,其余情况零 IO。
248
+ const deps = {};
249
+ if (gateway.needsThreadIndexLookup(routeOpts.thread)) {
250
+ const threadModule = await loadDist('core/thread/thread-service.js');
251
+ if (!threadModule) fail(BUILD_HINT, 'BUILD_REQUIRED');
252
+ let entry;
253
+ try {
254
+ entry = threadModule.ThreadService.findThreadById(runtime.selfAid, routeOpts.thread);
255
+ } catch {
256
+ entry = undefined;
257
+ }
258
+ deps.resolveThread = threadId => {
259
+ if (!entry || entry.threadId !== threadId) return undefined;
260
+ return {
261
+ threadId: entry.threadId,
262
+ selfAid: runtime.selfAid,
263
+ peer: {
264
+ channelType: entry.channelType ?? 'aun',
265
+ peerKind: entry.peerKind,
266
+ id: entry.peer,
267
+ },
268
+ };
269
+ };
270
+ }
271
+
272
+ const outcome = routing.resolveSendRoute(
273
+ {
274
+ thread: routeOpts.thread,
275
+ to: routeOpts.to,
276
+ from: routeOpts.from,
277
+ checkEvery: routeOpts.checkEvery,
278
+ encrypt: routeOpts.encrypt,
279
+ noEncrypt: routeOpts.noEncrypt === true,
280
+ // auto 的判据:本轮是否带着入站消息的加密态。有该状态说明是回复对端消息,
281
+ // 沿用它的加密方式;没有(如 trigger 唤醒发起)则明文。
282
+ inboundTriggered: runtime.inboundEncrypted !== undefined,
283
+ inboundEncrypted: runtime.inboundEncrypted === true,
284
+ },
285
+ {
286
+ selfAid: runtime.selfAid,
287
+ channelType: runtime.channel,
288
+ chatType: runtime.chatType === 'group' ? 'group' : 'private',
289
+ peerId: runtime.peerId ?? runtime.channelId,
290
+ threadId: routing.isThreadTopicId(runtime.threadId) ? runtime.threadId : undefined,
291
+ },
292
+ deps,
293
+ );
294
+
295
+ if (!outcome.ok) fail(outcome.message, outcome.code, outcome.hint ? { hint: outcome.hint } : {});
296
+
297
+ // `--to` 推导到主话题时,投递要求本端已有与目标的主会话。这里先查一次,
298
+ // 免得把"还没跟这个人聊过"报成一句从 daemon 冒出来的 TOPIC_NOT_FOUND。
299
+ // 查询异常一律放行,判定权仍归 daemon。
300
+ if (runtime.channel === 'aun' && !routeOpts.thread
301
+ && outcome.source?.peer === 'to' && outcome.peer.peerKind === 'private') {
302
+ const threadModule = await loadDist('core/thread/thread-service.js');
303
+ let exists = true;
304
+ if (threadModule) {
305
+ try {
306
+ exists = !!threadModule.ThreadService.findMainSessionEntry(runtime.selfAid, outcome.peer.id);
307
+ } catch {
308
+ exists = true;
309
+ }
310
+ }
311
+ if (!exists) {
312
+ fail(`与 ${outcome.peer.id} 还没有主会话记录,无法以主话题发送`, 'TOPIC_NOT_FOUND',
313
+ { hint: '先给对方发一条消息建立会话,或用 --thread 指定已有话题' });
314
+ }
315
+ }
316
+
317
+ // ── 分派 ──
318
+ const dispatch = gateway.decideDispatch(outcome, text, passthrough, runtime.channel);
319
+ if (dispatch.kind === 'reject') {
320
+ fail(dispatch.message, dispatch.code, dispatch.hint ? { hint: dispatch.hint } : {});
321
+ }
322
+ if (dispatch.kind === 'session') {
323
+ await dispatchSessionChannel(outcome, text, runtime, sessionId, delegationToken, routing, argv);
324
+ return;
325
+ }
326
+
327
+ const daemonArgv = dispatch.argv;
328
+
329
+ // 委托哈希必须覆盖**实际下发的 argv**:daemon 在 `aun-msg-send` 带 argv 时按
330
+ // `['ec', ...cmd.argv]` 重算并比对(ipc.ts 的 DELEGATED_ARGV_ENDPOINTS 闸门)。
331
+ // 网关下发的 argv 与调用方写的简化式不同(补了 from/to 与加密二态),
332
+ // 拿简化式算哈希必然 command_hash_mismatch。
333
+ if (readDelegatedExecutionSpec([MAIN_CLI_BIN, ...daemonArgv], process.env)) {
334
+ // 被安全输出 helper 包过的调用带执行规格,daemon 侧无对应字段可比对,这里无法绑定。
335
+ fail('ecmsg 不支持在安全输出包装内调用', 'UNSUPPORTED_WRAPPER');
336
+ }
337
+ const delegationCommandHash = hashDelegatedCommandArgv([MAIN_CLI_BIN, ...daemonArgv]);
338
+
339
+ let socketPath;
340
+ try {
341
+ const paths = await loadDist('paths.js');
342
+ socketPath = paths.resolvePaths().socket;
343
+ } catch {
344
+ fail(BUILD_HINT, 'BUILD_REQUIRED');
345
+ }
346
+
347
+ const result = await queryDaemonOnce(socketPath, {
190
348
  type: 'aun-msg-send',
191
349
  argv: daemonArgv,
192
350
  delegationToken,
193
351
  ...(delegationCommandHash ? { delegationCommandHash } : {}),
194
352
  originSessionId: sessionId,
195
- ...(runtimeCtx?.messageId ? { originMessageId: runtimeCtx.messageId } : {}),
353
+ ...(runtime.messageId ? { originMessageId: runtime.messageId } : {}),
196
354
  ...(process.env.EVOLCORE_DAEMON_RUNTIME_EPOCH
197
355
  ? { daemonRuntimeEpoch: process.env.EVOLCORE_DAEMON_RUNTIME_EPOCH }
198
356
  : {}),
199
357
  });
200
358
 
201
- if (!result) fail('无法连接 EvolCore daemon(AUN_DAEMON_UNAVAILABLE)。');
359
+ if (!result) fail('无法连接 EvolCore daemon(AUN_DAEMON_UNAVAILABLE)', 'DAEMON_UNAVAILABLE');
202
360
  if (!result.ok) {
203
- fail([
361
+ fail(
362
+ [result.error ?? 'Send failed',
363
+ result.request_id ? `request_id=${result.request_id}` : '',
364
+ result.detail_code ? `detail_code=${result.detail_code}` : ''].filter(Boolean).join(' · '),
204
365
  result.code ?? 'AUN_SEND_FAILED',
205
- result.error ?? 'Send failed',
206
- result.request_id ? `request_id=${result.request_id}` : '',
207
- result.detail_code ? `detail_code=${result.detail_code}` : '',
208
- ].filter(Boolean).join(' · '));
366
+ result.contact_request ? { contact_request: result.contact_request } : {},
367
+ );
209
368
  }
210
369
 
211
- const formatIndex = args.indexOf('--format');
212
- const wantJson = formatIndex >= 0 && args[formatIndex + 1] === 'json';
213
- if (wantJson) {
214
- process.stdout.write(`${JSON.stringify(result)}\n`);
370
+ renderReceipt(outcome, result, routing, gateway);
371
+ }
372
+
373
+ /**
374
+ * 回执:路由信息前置且为实际生效值。
375
+ *
376
+ * 调用方在发送前不一定知道(或记错了)from/to,回执回显是唯一确认手段;
377
+ * 由系统补全的项标注来源(会话/传入/推导),让调用方知道该核对什么。
378
+ */
379
+ function renderReceipt(route, result, routing, gateway) {
380
+ const routeLine = routing.formatRouteReceipt(route);
381
+
382
+ if (jsonOutput) {
383
+ process.stdout.write(`${JSON.stringify({
384
+ ok: true,
385
+ from: route.self,
386
+ to: route.peer.id,
387
+ thread: route.threadId,
388
+ chatType: route.peer.peerKind,
389
+ crossTopic: route.crossTopic,
390
+ checkEveryMs: route.checkEveryMs,
391
+ checkEveryDefaulted: route.checkEveryDefaulted,
392
+ checkEveryIgnored: route.checkEveryIgnored,
393
+ encrypt: route.encrypt,
394
+ encryptResolved: route.encryptResolved,
395
+ message_id: result.message_id,
396
+ seq: result.seq,
397
+ status: result.status,
398
+ trigger_id: result.trigger_id,
399
+ })}\n`);
215
400
  return;
216
401
  }
402
+
217
403
  if (result.request_id) {
218
- process.stdout.write(`sent message_id=${result.message_id ?? '-'} request_id=${result.request_id} state=${result.request_state ?? '-'}\n`);
404
+ process.stdout.write(
405
+ `✓ 已发送 ${routeLine} message_id=${result.message_id ?? '-'}`
406
+ + ` request_id=${result.request_id} state=${result.request_state ?? '-'}\n`,
407
+ );
219
408
  return;
220
409
  }
410
+
221
411
  const seq = result.seq ?? result.message?.seq ?? '-';
222
- process.stdout.write(`✓ 已发送 message_id=${result.message_id ?? '-'} seq=${seq} status=${result.status ?? '-'}\n`);
223
- if (result.trigger_id) process.stdout.write(`✓ 复查 Trigger ${result.trigger_id}\n`);
224
- else if (result.trigger_error) {
225
- process.stderr.write(`⚠ 复查 Trigger 未创建: ${result.trigger_error}(消息已发出,需要复查请手动 ec trigger create)\n`);
412
+ process.stdout.write(
413
+ `✓ 已发送 ${routeLine} message_id=${result.message_id ?? '-'} seq=${seq} status=${result.status ?? '-'}\n`,
414
+ );
415
+
416
+ if (route.crossTopic) {
417
+ const duration = gateway.formatDuration(route.checkEveryMs);
418
+ const label = route.checkEveryDefaulted ? `默认 ${duration}` : duration;
419
+ process.stdout.write(`✓ 已建复查(${label}) trigger_id=${result.trigger_id ?? '(未返回)'}\n`);
420
+ }
421
+ if (route.checkEveryIgnored) process.stdout.write('· 同话题,未创建复查\n');
422
+ if (result.trigger_error) {
423
+ process.stderr.write(`⚠ 复查 Trigger 未创建: ${result.trigger_error}\n`);
424
+ }
425
+ }
426
+
427
+ /**
428
+ * 非 AUN 渠道的发送分派。
429
+ *
430
+ * 现状(P3 实测结论):非 AUN 只有 `ctl send` 一条通道,而它的目标**固定为
431
+ * 当前会话的 channelId**(`command-handler.ts` 的 `/send` 分支直接用
432
+ * `session.channelId`,不接受目标参数)。因此:
433
+ *
434
+ * - 同话题(目标就是当前会话对端)→ 可以发,走 ctl。
435
+ * - 跨话题(目标不是当前对端)→ 无可用通道,明确失败。
436
+ *
437
+ * 不做"降级发到当前会话"——那会把消息发给错的联系人,比失败危险得多。
438
+ * 非 AUN 跨话题能力待后续接入(见计划 P3-5)。
439
+ *
440
+ * 委托凭证:`ctl` 分支用 `validate()`(消费审批语义),但会话级 grant 命中
441
+ * `activeHashBySession` 时 `commandHash` 不参与判定,因此这里只需带上 token。
442
+ */
443
+ async function dispatchSessionChannel(route, text, runtime, sessionId, delegationToken, routing, cliArgv) {
444
+ const body = text.join(' ');
445
+
446
+ let socketPath;
447
+ try {
448
+ const paths = await loadDist('paths.js');
449
+ socketPath = paths.resolvePaths().socket;
450
+ } catch {
451
+ fail(BUILD_HINT, 'BUILD_REQUIRED');
452
+ }
453
+
454
+ // 关键:同话题走 ctl 通道,但委托哈希不能交给 ipc 层按 `['ec','ctl','send',...]`
455
+ // 自动推导——策略层 arm 的是 `['ec','msg','send',...]`(ecmsg 归一到 ec msg)。
456
+ // 必须显式传入同一个归一化 argv 的哈希,否则必然 command_hash_mismatch。
457
+ const parser = await loadDist('core/permission/ec-command-parser.js');
458
+ if (!parser) fail(BUILD_HINT, 'BUILD_REQUIRED');
459
+ const normalizedArgv = parser.canonicalizeEvolcoreCommandArgv(['ecmsg', ...cliArgv]);
460
+ const executionSpec = readDelegatedExecutionSpec(normalizedArgv, process.env);
461
+ const delegationCommandHash = hashDelegatedCommandArgv(normalizedArgv, executionSpec);
462
+
463
+ const result = await queryDaemonOnce(socketPath, {
464
+ type: 'ctl',
465
+ argv: ['ctl', 'send', body],
466
+ sessionId,
467
+ delegationToken,
468
+ ...(delegationCommandHash ? { delegationCommandHash } : {}),
469
+ }, 30_000);
470
+
471
+ if (!result) fail('无法连接 EvolCore daemon(DAEMON_UNAVAILABLE)', 'DAEMON_UNAVAILABLE');
472
+ if (!result.ok) fail(result.error ?? 'Send failed', result.code ?? 'SEND_FAILED');
473
+
474
+ const routeLine = routing.formatRouteReceipt(route);
475
+ if (jsonOutput) {
476
+ process.stdout.write(`${JSON.stringify({
477
+ ok: true,
478
+ from: route.self,
479
+ to: route.peer.id,
480
+ thread: route.threadId,
481
+ chatType: route.peer.peerKind,
482
+ crossTopic: false,
483
+ message_id: null,
484
+ status: 'sent',
485
+ })}\n`);
486
+ return;
226
487
  }
488
+ // ctl 通道没有 message_id,如实写出而不是假装有
489
+ process.stdout.write(`✓ 已发送 ${routeLine} status=sent message_id=n/a\n`);
227
490
  }
228
491
 
229
492
  void main();
@@ -111,8 +111,9 @@ function parseCodexRetryProgress(message) {
111
111
  return undefined;
112
112
  return { count, limit };
113
113
  }
114
- function createCodexRetryMetadataError(message, state) {
114
+ function createCodexRetryMetadataError(message, state, executionOutcome) {
115
115
  const error = new Error(message);
116
+ error.codexExecutionOutcome = executionOutcome;
116
117
  if (state.modelRetryCount !== undefined)
117
118
  error.codexRetryCount = state.modelRetryCount;
118
119
  if (state.modelRetryLimit !== undefined)
@@ -334,22 +335,14 @@ function logCodexProbeFailure(args, startedAt, error, timeoutMs, launch) {
334
335
  })}`);
335
336
  }
336
337
  function probeCodexCli(args, executable) {
337
- return probeCliSync('codex', args, { executable, onFailure: logCodexProbeFailure });
338
+ return probeCliSync('codex', args, {
339
+ executable, onFailure: logCodexProbeFailure,
340
+ validateOutput: args[0] === '--version' ? output => parseCodexCliVersion(output) !== null : undefined,
341
+ });
338
342
  }
339
343
  export function getCodexCliVersion(executable) {
340
- const startedAt = Date.now();
341
344
  try {
342
- const output = probeCodexCli(['--version'], executable);
343
- const version = parseCodexCliVersion(output);
344
- if (!version) {
345
- logCodexProbeFailure(['--version'], startedAt, {
346
- code: 'INVALID_VERSION_OUTPUT',
347
- message: 'Codex CLI version output could not be parsed',
348
- status: 0,
349
- stdout: output,
350
- }, CODEX_CLI_PROBE_TIMEOUT_MS);
351
- }
352
- return version;
345
+ return parseCodexCliVersion(probeCodexCli(['--version'], executable));
353
346
  }
354
347
  catch {
355
348
  return null;
@@ -444,7 +437,9 @@ async function probeCodexAppServerAvailabilityAsync() {
444
437
  // version gate passes, so the decision order is unchanged.
445
438
  const appServerProbe = probeCli('codex', ['app-server', '--help'], options);
446
439
  appServerProbe.catch(() => { });
447
- version = parseCodexCliVersion(await probeCli('codex', ['--version'], options)) ?? undefined;
440
+ version = parseCodexCliVersion(await probeCli('codex', ['--version'], {
441
+ ...options, validateOutput: output => parseCodexCliVersion(output) !== null,
442
+ })) ?? undefined;
448
443
  if (!version)
449
444
  return { available: false, reason: '无法读取 Codex CLI 版本。' };
450
445
  if (!isCodexCliVersionSupported(version)) {
@@ -5638,7 +5633,7 @@ export class CodexRunner {
5638
5633
  lastReportedUsage: state.tokenUsage?.last,
5639
5634
  })}`);
5640
5635
  if (isRetryableError(new Error(turn.error.message))) {
5641
- throw createCodexRetryMetadataError(turn.error.message, state);
5636
+ throw createCodexRetryMetadataError(turn.error.message, state, 'failed');
5642
5637
  }
5643
5638
  yield { type: 'error', error: turn.error.message, errorType: toAgentErrorType(turn.error.message) };
5644
5639
  }
@@ -5674,7 +5669,7 @@ export class CodexRunner {
5674
5669
  break;
5675
5670
  }
5676
5671
  if (isRetryableError(new Error(message))) {
5677
- throw createCodexRetryMetadataError(message, state);
5672
+ throw createCodexRetryMetadataError(message, state, params.willRetry === false ? 'failed' : 'unknown');
5678
5673
  }
5679
5674
  yield { type: 'error', error: message, errorType: toAgentErrorType(message) };
5680
5675
  break;