evolcore 0.0.47 → 0.0.49

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 (266) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +143 -40
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +34 -17
  8. package/dist/agents/codex-runner.js +36 -17
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/msg/p2p.js +2 -1
  14. package/dist/aun/service-proxy.js +4 -2
  15. package/dist/build-identity.json +1 -0
  16. package/dist/channels/aun.js +722 -295
  17. package/dist/channels/daemon.js +9 -25
  18. package/dist/cli/aun-commands.js +86 -51
  19. package/dist/cli/code-stats.js +19 -8
  20. package/dist/cli/command-log.js +1 -1
  21. package/dist/cli/daemon-commands.js +44 -43
  22. package/dist/cli/directory.js +13 -2
  23. package/dist/cli/ecmsg-gateway.js +5 -2
  24. package/dist/cli/index.js +9 -9
  25. package/dist/cli/init-channel.js +4 -6
  26. package/dist/cli/init.js +72 -50
  27. package/dist/cli/invoke-command.js +1 -1
  28. package/dist/cli/managed-command-guard.js +2 -0
  29. package/dist/cli/model.js +20 -5
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/quota.js +89 -0
  32. package/dist/cli/role.js +62 -17
  33. package/dist/cli/services-command.js +1 -0
  34. package/dist/cli/stats.js +3 -3
  35. package/dist/cli/team-workspace-command.js +56 -2
  36. package/dist/cli/thread-command.js +16 -51
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-field-policy.js +71 -1
  40. package/dist/config/config-manager.js +13 -7
  41. package/dist/config/daemon-services.js +30 -3
  42. package/dist/config/gateway-config.js +2 -2
  43. package/dist/config/invoke-ipc-service.js +6 -4
  44. package/dist/config/peer-bind-code.js +3 -4
  45. package/dist/config/peer-book-store.js +62 -229
  46. package/dist/config/peer-book.js +26 -27
  47. package/dist/config/peer-role-resolver.js +16 -1
  48. package/dist/config/provider-identity-migration.js +4 -1
  49. package/dist/config/provider-ipc-service.js +56 -11
  50. package/dist/config/provider-menu-request.js +24 -5
  51. package/dist/config/provider-templates.js +127 -0
  52. package/dist/config/providers-config.js +67 -12
  53. package/dist/config/providers-management.js +477 -51
  54. package/dist/config/resolved-config-op.js +3 -2
  55. package/dist/config/role-command-service.js +248 -1
  56. package/dist/config/schema-migration.js +105 -4
  57. package/dist/core/agent-application-service.js +6 -1
  58. package/dist/core/agent-runtime.js +4 -0
  59. package/dist/core/auth/agent-delegation.js +2 -1
  60. package/dist/core/auth/auth-gateway.js +2 -1
  61. package/dist/core/auth/delegation-authorization.js +36 -26
  62. package/dist/core/auth/operation-authorizer.js +25 -0
  63. package/dist/core/auth/operation-catalog.js +37 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/cli-intent-parser.js +13 -0
  68. package/dist/core/command/command-handler.js +126 -87
  69. package/dist/core/command/menu-catalog.js +1 -0
  70. package/dist/core/command/menu-handler.js +67 -150
  71. package/dist/core/command/menu-protocol.js +31 -1
  72. package/dist/core/command/provider-menu.js +13 -3
  73. package/dist/core/command/remote-shell.js +565 -0
  74. package/dist/core/command/role-menu.js +47 -23
  75. package/dist/core/command/slash-handler.js +26 -43
  76. package/dist/core/command/team-workspace-items.js +81 -12
  77. package/dist/core/command/team-workspace-team.js +9 -71
  78. package/dist/core/command/topic-slash.js +9 -30
  79. package/dist/core/daemon-bootstrap.js +8 -1
  80. package/dist/core/daemon-control.js +64 -8
  81. package/dist/core/daemon-lifecycle.js +16 -2
  82. package/dist/core/evolagent-registry.js +20 -3
  83. package/dist/core/file-integrity/store.js +2 -0
  84. package/dist/core/handoff/runtime.js +37 -1
  85. package/dist/core/inference/text-inference.js +3 -1
  86. package/dist/core/initialization/service.js +11 -6
  87. package/dist/core/interaction-router.js +3 -0
  88. package/dist/core/invoke/executors/text.js +72 -19
  89. package/dist/core/ipc-registration.js +3 -1
  90. package/dist/core/message/aun-ipc-sender.js +279 -107
  91. package/dist/core/message/contact-admission.js +91 -6
  92. package/dist/core/message/contact-pending-inbound.js +113 -0
  93. package/dist/core/message/contact-thread-approval.js +212 -0
  94. package/dist/core/message/im-renderer.js +41 -2
  95. package/dist/core/message/message-admission.js +5 -39
  96. package/dist/core/message/message-bridge.js +140 -370
  97. package/dist/core/message/message-log.js +29 -0
  98. package/dist/core/message/message-queue.js +119 -15
  99. package/dist/core/message/message-utils.js +8 -0
  100. package/dist/core/message/response-engine.js +580 -134
  101. package/dist/core/message/send-routing.js +5 -1
  102. package/dist/core/model/catalog-service.js +31 -11
  103. package/dist/core/model/config-scope.js +6 -14
  104. package/dist/core/model/model-capabilities.js +22 -4
  105. package/dist/core/model/model-catalog.js +1 -0
  106. package/dist/core/model/model-diagnostics.js +19 -0
  107. package/dist/core/model/model-fallback.js +13 -2
  108. package/dist/core/ownership/owner-resolver.js +328 -50
  109. package/dist/core/pack-auth.js +3 -0
  110. package/dist/core/pack-install.js +1 -1
  111. package/dist/core/permission/ec-command-parser.js +106 -19
  112. package/dist/core/permission/protected-paths.js +6 -6
  113. package/dist/core/permission/services-path-acl.js +451 -0
  114. package/dist/core/permission/tool-policy.js +5 -1
  115. package/dist/core/relation/peer-identity.js +36 -1
  116. package/dist/core/relation/same-owner-proof.js +81 -112
  117. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  118. package/dist/core/session/session-file-health.js +13 -7
  119. package/dist/core/session/session-fs-store.js +91 -35
  120. package/dist/core/session/session-manager.js +68 -24
  121. package/dist/core/session/session-mapper.js +14 -34
  122. package/dist/core/session/session-transcript.js +5 -1
  123. package/dist/core/task/task-activity-store.js +84 -0
  124. package/dist/core/task/task-recovery-service.js +13 -0
  125. package/dist/core/thread/command-parser.js +7 -12
  126. package/dist/core/thread/thread-context-storage.js +3 -2
  127. package/dist/core/thread/thread-operation.js +2 -13
  128. package/dist/core/thread/thread-service.js +15 -46
  129. package/dist/core/thread/topic-id.js +15 -0
  130. package/dist/directory/owner-directory-admission.js +12 -9
  131. package/dist/directory/owner-directory-cache.js +64 -28
  132. package/dist/directory/owner-directory-markdown.js +14 -2
  133. package/dist/directory/owner-directory-policy.js +5 -30
  134. package/dist/directory/owner-directory-query-operation.js +29 -3
  135. package/dist/directory/owner-directory-remarks.js +11 -3
  136. package/dist/directory/owner-directory-request-operation.js +5 -2
  137. package/dist/eck/kit-renderer.js +1 -1
  138. package/dist/eck/message-renderer.js +112 -29
  139. package/dist/ecweb/basic-settings-service.js +3 -1
  140. package/dist/ecweb/message-context-service.js +1 -1
  141. package/dist/ecweb/pairing.js +4 -3
  142. package/dist/ecweb/providers-service.js +26 -1
  143. package/dist/ecweb/runtime/lifecycle.js +18 -8
  144. package/dist/ecweb/runtime/proxy-access.js +74 -0
  145. package/dist/ecweb/runtime/supervisor.js +36 -6
  146. package/dist/event-center/center-config.js +9 -5
  147. package/dist/event-center/dispatcher.js +10 -1
  148. package/dist/event-center/ipc-operation.js +19 -0
  149. package/dist/event-center/registry.js +29 -3
  150. package/dist/event-center/runtime.js +106 -11
  151. package/dist/event-center/script-runner.js +5 -5
  152. package/dist/index.js +96 -59
  153. package/dist/ipc.js +38 -3
  154. package/dist/outputs/authorization.js +16 -0
  155. package/dist/outputs/cards.js +336 -0
  156. package/dist/outputs/events.js +63 -0
  157. package/dist/outputs/protocol.js +103 -0
  158. package/dist/outputs/service.js +266 -0
  159. package/dist/paths.js +3 -0
  160. package/dist/proxy/manager.js +43 -13
  161. package/dist/services/index.js +114 -5
  162. package/dist/services/ipc-operation.js +88 -15
  163. package/dist/services/pack-manager.js +13 -1
  164. package/dist/services/router.js +21 -6
  165. package/dist/services/script-runner.js +5 -4
  166. package/dist/services/service-payload.js +13 -7
  167. package/dist/services/validation.js +1 -1
  168. package/dist/stats/budget.js +2 -2
  169. package/dist/stats/db.js +19 -0
  170. package/dist/stats/index.js +1 -1
  171. package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
  172. package/dist/stats/normalizer.js +2 -0
  173. package/dist/stats/query.js +35 -27
  174. package/dist/stats/quota-query.js +95 -0
  175. package/dist/stats/role-budget.js +5 -2
  176. package/dist/stats/writer.js +10 -6
  177. package/dist/trigger/audit.js +7 -0
  178. package/dist/trigger/authorization.js +105 -11
  179. package/dist/trigger/feedback.js +10 -0
  180. package/dist/trigger/history.js +37 -11
  181. package/dist/trigger/ipc-service.js +12 -1
  182. package/dist/trigger/manager.js +1 -0
  183. package/dist/trigger/scheduler.js +7 -5
  184. package/dist/trigger/script-executor.js +2 -1
  185. package/dist/trigger/script-sandbox.js +21 -3
  186. package/dist/trigger/validation.js +22 -0
  187. package/dist/utils/atomic-write.js +22 -8
  188. package/dist/utils/cross-platform.js +73 -26
  189. package/dist/utils/error-dict.json +94 -4
  190. package/dist/utils/error-utils.js +27 -4
  191. package/dist/utils/evolcore-version.js +36 -65
  192. package/dist/utils/host-info.js +100 -1
  193. package/dist/utils/msg-diag.js +1 -0
  194. package/dist/utils/npm-ops.js +43 -8
  195. package/dist/utils/process-introspect.js +12 -7
  196. package/dist/utils/process-tree.js +50 -2
  197. package/dist/utils/windows-shell-trust.js +2 -0
  198. package/dist/workbench/protocol.js +80 -0
  199. package/dist/workbench/service.js +359 -0
  200. package/ecagent/dist/types.d.ts +6 -2
  201. package/kits/docs/context-assembly.md +1 -1
  202. package/kits/docs/evolcore/INDEX.md +4 -2
  203. package/kits/docs/evolcore/aid.md +25 -0
  204. package/kits/docs/evolcore/config.md +16 -1
  205. package/kits/docs/evolcore/directory.md +30 -12
  206. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  207. package/kits/docs/evolcore/model.md +10 -0
  208. package/kits/docs/evolcore/msg.md +9 -0
  209. package/kits/docs/evolcore/peer.md +19 -65
  210. package/kits/docs/evolcore/provider.md +124 -4
  211. package/kits/docs/evolcore/quota.md +54 -0
  212. package/kits/docs/evolcore/role.md +83 -0
  213. package/kits/docs/evolcore/services.md +6 -6
  214. package/kits/docs/evolcore/stats.md +2 -0
  215. package/kits/docs/evolcore/team-workspace.md +1 -1
  216. package/kits/docs/evolcore/thread-chain.md +14 -15
  217. package/kits/docs/evolcore/tool-authorization.md +5 -0
  218. package/kits/docs/evolcore/trigger.md +12 -0
  219. package/kits/eck_message_manifest.json +12 -0
  220. package/kits/provider-templates.json +1213 -0
  221. package/kits/rules/04-relation.md +3 -3
  222. package/kits/schemas/_meta.json +14 -2
  223. package/kits/schemas/agent-config.schema.20.json +24 -0
  224. package/kits/schemas/contact-book.schema.4.json +52 -0
  225. package/kits/schemas/providers.schema.3.json +200 -0
  226. package/kits/skills/.switches.json +8 -0
  227. package/kits/skills/ability/references/calling.md +1 -1
  228. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  229. package/kits/skills/ec-group/SKILL.md +2 -2
  230. package/kits/skills/ec-identity/SKILL.md +19 -72
  231. package/kits/skills/ec-provider/SKILL.md +270 -0
  232. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  233. package/kits/skills/ec-trigger/SKILL.md +1 -1
  234. package/kits/skills/thread-ops/SKILL.md +34 -21
  235. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  236. package/kits/templates/message-fragments/group-batch.md +1 -1
  237. package/kits/templates/message-fragments/inject-default.md +1 -1
  238. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  239. package/kits/templates/message-fragments/item-group.md +1 -1
  240. package/kits/templates/message-fragments/item-private.md +1 -1
  241. package/kits/templates/message-fragments/thread-context.md +1 -1
  242. package/kits/templates/message-fragments/trigger-session.md +1 -1
  243. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  244. package/kits/templates/roles/admin.json +2 -19
  245. package/kits/templates/roles/member.json +0 -3
  246. package/kits/templates/roles/visitor.json +1 -0
  247. package/kits/templates/system-fragments/baseagent.md +6 -0
  248. package/kits/templates/system-fragments/commands.md +4 -3
  249. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  250. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  251. package/kits/templates/system-fragments/relation.md +1 -1
  252. package/kits/templates/system-fragments/thread.md +7 -5
  253. package/kits/templates/system-fragments/venue.md +11 -0
  254. package/package.json +6 -4
  255. package/scripts/agent-template/inspect.mjs +50 -11
  256. package/scripts/agent-template/shared/common.mjs +11 -6
  257. package/scripts/agent-template/shared/team-schema.json +6 -4
  258. package/scripts/agent-template/shared/template-contract.mjs +62 -11
  259. package/scripts/agent-template/shared/template-package.mjs +189 -21
  260. package/scripts/agent-template/shared/template-runtime.mjs +54 -6
  261. package/scripts/agent-template/shared/template.mjs +2 -2
  262. package/scripts/agent-template/team-pack.mjs +52 -14
  263. package/dist/cli/peer.js +0 -127
  264. package/dist/config/peer-operation-service.js +0 -132
  265. package/dist/config/peer-request-service.js +0 -532
  266. package/dist/core/command/connect-menu.js +0 -624
@@ -0,0 +1,451 @@
1
+ /**
2
+ * 服务包目录(`agents/<aid>/services`)的 NTFS ACL 加固。
3
+ *
4
+ * ## 为什么需要这一层
5
+ *
6
+ * scoped 沙箱的写保护由两层组成:policy(`--sandbox-state-json` 的 entries)与 ACL。
7
+ * `services` 的 policy 侧没有 write 授权,写拒绝由「默认拒绝」承担;ACL 侧则可能因为
8
+ * 历史授权(手工 `icacls /grant`、跨机器拷贝带过来的 ACE、codex setup 重跑)而留下
9
+ * **非继承的写授权**。一旦 policy 放宽,就没有第二层兜底。
10
+ *
11
+ * 本模块只做 ACL 一层,判据是:**服务脚本永远不能改写自己的代码和声明**。
12
+ *
13
+ * ## 两条规则
14
+ *
15
+ * - **A(清理)**:移除「非继承 + Allow + 含写权限 + 主体是沙箱组或外来机器 SID」的 ACE。
16
+ * 显式子级 Allow 的优先级高于父级继承 DENY,所以只靠规则 B 拦不住 `artifact-nav/`
17
+ * 这类目录上的残留授权(ACE 求值顺序:显式 Deny → 显式 Allow → 继承 Deny → 继承 Allow)。
18
+ * - **B(兜底)**:在 `services` 根加一条 `(OI)(CI)` 的 DENY(写相关位)。
19
+ * 这条会继承到全树,且能扛住将来重新出现的 Allow。
20
+ *
21
+ * ## 为什么 DENY 不含读位
22
+ *
23
+ * Codex 的 `access: 'deny'` 连读一起拒。服务脚本要读自己的 `pack.json`、要能被执行,
24
+ * 所以只拒写数据 / 追加 / 写属性 / 删除 / 改 DACL / 改所有者这些位,`RX` 位保留。
25
+ *
26
+ * 平台:仅 `win32`。其他平台 `hardenServicesAcl` 直接返回 `changed: false`。
27
+ */
28
+ import { execFile, execFileSync } from 'node:child_process';
29
+ import fs from 'node:fs';
30
+ import path from 'node:path';
31
+ /** 沙箱账户所在的本地组。codex setup 创建,`CodexSandboxOffline/Online` 都是它的成员。 */
32
+ export const SERVICES_SANDBOX_GROUP = 'CodexSandboxUsers';
33
+ /**
34
+ * 判定「含写权限」的位掩码:写数据、追加、写扩展属性、写属性、删除、删子项、
35
+ * 改 DACL、改所有者,外加两个泛用位。
36
+ *
37
+ * 实测参照值:`(M)` = 1245631 (0x1301BF) 命中;`(RX)` = 1179817 (0x1200A9) 不命中;
38
+ * `(R)` = 1179785 (0x120089) 不命中;`(F)` = 2032127 (0x1F01FF) 命中。
39
+ */
40
+ export const SERVICES_WRITE_RIGHTS = 0x2 | 0x4 | 0x10 | 0x100
41
+ | 0x40 | 0x10000
42
+ | 0x40000 | 0x80000
43
+ | 0x10000000 | 0x40000000;
44
+ /**
45
+ * 施加 DENY 时只用的具体写位:写数据 / 追加 / 写扩展属性 / 写属性 / 删除 / 删子项 /
46
+ * 改 DACL / 改所有者。
47
+ *
48
+ * **不含** `GENERIC_ALL` / `GENERIC_WRITE`:泛用位的展开涵盖读,会把 `RX` 一起拒掉。
49
+ */
50
+ export const SERVICES_DENY_WRITE_RIGHTS = 0x2 | 0x4 | 0x10 | 0x100
51
+ | 0x40 | 0x10000
52
+ | 0x40000 | 0x80000;
53
+ /** 一条 ACE 是否授予写能力。 */
54
+ export function grantsWrite(ace) {
55
+ return ace.allow && (ace.rights & SERVICES_WRITE_RIGHTS) !== 0;
56
+ }
57
+ /**
58
+ * 外来机器 SID:`S-1-5-21-<machine>-<rid>`,且 machine 部分不等于本机。
59
+ *
60
+ * 本机的 `CodexSandboxUsers` / 宿主用户都以本机 machine SID 为前缀,永远不会被判为外来。
61
+ * `S-1-5-18`(SYSTEM)、`S-1-5-32-*`(内置组)不是 `S-1-5-21` 形态,天然排除。
62
+ */
63
+ export function isForeignMachineSid(sid, localMachineSid) {
64
+ if (!localMachineSid)
65
+ return false;
66
+ if (!/^S-1-5-21-/i.test(sid))
67
+ return false;
68
+ return sid.toLowerCase() !== localMachineSid.toLowerCase()
69
+ && !sid.toLowerCase().startsWith(`${localMachineSid.toLowerCase()}-`);
70
+ }
71
+ /**
72
+ * 纯函数:给定某个目录的 DACL 快照,算出要做什么。不碰文件系统,可任意平台单测。
73
+ */
74
+ export function planServicesAclRepair(aces, options) {
75
+ const removeSids = new Set();
76
+ const violations = [];
77
+ for (const ace of aces) {
78
+ if (!ace.allow || ace.inherited || !grantsWrite(ace))
79
+ continue;
80
+ const sandbox = options.sandboxSid && ace.sid.toLowerCase() === options.sandboxSid.toLowerCase();
81
+ const foreign = isForeignMachineSid(ace.sid, options.localMachineSid);
82
+ if (!sandbox && !foreign)
83
+ continue;
84
+ removeSids.add(ace.sid);
85
+ violations.push(`explicit ${ace.allow ? 'Allow' : 'Deny'} write ACE for ${sandbox ? 'sandbox group' : 'foreign SID'} ${ace.sid} (rights=0x${ace.rights.toString(16)})`);
86
+ }
87
+ // 已有一条覆盖全部写位的 DENY 时不再重复施加。
88
+ //
89
+ // **继承的 DENY 也算覆盖**:根上的 `(OI)(CI)` DENY 会向下继承到整棵树,子目录
90
+ // 看到的正是那条继承 ACE。只认非继承的会把每个子目录都判成"缺 DENY",
91
+ // 于是 `hardenServicesAcl` 每次都觉得有事可做——幂等性就没了。
92
+ const denyCovered = !!options.sandboxSid && aces.some(ace => !ace.allow
93
+ && ace.sid.toLowerCase() === options.sandboxSid.toLowerCase()
94
+ && (ace.rights & SERVICES_DENY_WRITE_RIGHTS) === SERVICES_DENY_WRITE_RIGHTS);
95
+ return {
96
+ removeSids: [...removeSids],
97
+ needsDenyWrite: !!options.sandboxSid && !denyCovered,
98
+ violations,
99
+ };
100
+ }
101
+ /**
102
+ * 读取一棵目录树上的 ACL。
103
+ *
104
+ * 返回 `sandboxSid` / `localMachineSid` 供调用方复用;`sandboxSid` 为 `undefined`
105
+ * 表示本机没有 `CodexSandboxUsers` 组(未安装/未 provisioning codex),此时**没有可加固对象**。
106
+ */
107
+ export function readServicesAcl(dir) {
108
+ if (process.platform !== 'win32')
109
+ return { sandboxSid: undefined, localMachineSid: undefined, entries: [] };
110
+ const output = execFileSync(powershellPath(), [
111
+ '-NoProfile', '-NonInteractive', '-EncodedCommand', encodePowerShell(READ_ACL_SCRIPT),
112
+ ], {
113
+ windowsHide: true,
114
+ timeout: 20_000,
115
+ encoding: 'utf8',
116
+ env: {
117
+ ...process.env,
118
+ EVOLCORE_SERVICES_ACL_ROOT: dir,
119
+ EVOLCORE_SERVICES_SANDBOX_GROUP: SERVICES_SANDBOX_GROUP,
120
+ },
121
+ });
122
+ return parseAclOutput(output);
123
+ }
124
+ /** 已经审计过的目录。进程内去重:每个 services 树只跑一次。 */
125
+ const auditedRoots = new Set();
126
+ /**
127
+ * 后台加固:启动路径上不阻塞,且每个目录只跑一次。
128
+ *
129
+ * 读一次 DACL 需要约 0.5s(PowerShell 子进程 + 递归 Get-Acl),挂在 daemon 启动的
130
+ * 同步路径上会明显拖慢 `ec start`。这里改成 fire-and-forget:不 await、不抛错,
131
+ * 失败只写日志——加固是兜底层,晚几百毫秒生效没有影响。
132
+ *
133
+ * 同步版本 `hardenServicesAcl` 仍保留给 `pack add` 与 `repair-acl` 这类需要
134
+ * 「说完就改完」的场景。
135
+ */
136
+ export function scheduleServicesAclHarden(dir, log) {
137
+ const key = path.resolve(dir).toLowerCase();
138
+ if (auditedRoots.has(key))
139
+ return;
140
+ auditedRoots.add(key);
141
+ // setImmediate:让出当前 tick,启动流程先把包加载完。
142
+ setImmediate(() => {
143
+ void hardenServicesAclAsync(dir).then(result => {
144
+ if (result.errors.length > 0) {
145
+ log(`services ACL hardening failed for ${dir}: ${result.errors.join('; ')}`);
146
+ }
147
+ else if (result.changed) {
148
+ const removed = result.plans.flatMap(item => item.plan.removeSids).length;
149
+ log(`services ACL hardened for ${dir} (removed ${removed} explicit write grant(s))`);
150
+ }
151
+ }).catch(error => {
152
+ log(`services ACL hardening threw for ${dir}: ${errorMessage(error)}`);
153
+ });
154
+ });
155
+ }
156
+ /**
157
+ * 异步版加固:子进程不阻塞事件循环。
158
+ *
159
+ * 与同步版逻辑一致,只是把两次 `execFileSync` 换成 `execFile`。给
160
+ * `scheduleServicesAclHarden` 用——那里在 daemon 事件循环里跑,阻塞 0.5s 会
161
+ * 拖慢同时进行的包执行与 IPC 应答。
162
+ */
163
+ async function hardenServicesAclAsync(dir) {
164
+ if (process.platform !== 'win32')
165
+ return { changed: false, plans: [], errors: [] };
166
+ const root = path.resolve(dir);
167
+ if (!fs.existsSync(root))
168
+ return { changed: false, plans: [], errors: [] };
169
+ let snapshot;
170
+ try {
171
+ snapshot = parseAclOutput(await readAclRaw(root));
172
+ }
173
+ catch (error) {
174
+ return { changed: false, plans: [], errors: [`read ACL failed: ${errorMessage(error)}`] };
175
+ }
176
+ if (!snapshot.sandboxSid)
177
+ return { changed: false, plans: [], errors: [] };
178
+ const { plans, changes } = planServicesAclTree(root, snapshot);
179
+ if (changes.length === 0)
180
+ return { changed: false, plans, errors: [] };
181
+ try {
182
+ await writeAclRaw(snapshot.sandboxSid, changes);
183
+ }
184
+ catch (error) {
185
+ return { changed: false, plans, errors: [`apply ACL failed: ${errorMessage(error)}`] };
186
+ }
187
+ return { changed: true, plans, errors: [] };
188
+ }
189
+ /** 跑读取脚本,返回原始 stdout。异步:不阻塞事件循环。 */
190
+ function readAclRaw(dir) {
191
+ return new Promise((resolve, reject) => {
192
+ execFile(powershellPath(), [
193
+ '-NoProfile', '-NonInteractive', '-EncodedCommand', encodePowerShell(READ_ACL_SCRIPT),
194
+ ], {
195
+ windowsHide: true,
196
+ timeout: 20_000,
197
+ encoding: 'utf8',
198
+ env: {
199
+ ...process.env,
200
+ EVOLCORE_SERVICES_ACL_ROOT: dir,
201
+ EVOLCORE_SERVICES_SANDBOX_GROUP: SERVICES_SANDBOX_GROUP,
202
+ },
203
+ }, (error, stdout) => {
204
+ if (error)
205
+ reject(error);
206
+ else
207
+ resolve(String(stdout));
208
+ });
209
+ });
210
+ }
211
+ /** 施加计划。异步:不阻塞事件循环。 */
212
+ function writeAclRaw(sandboxSid, items) {
213
+ return new Promise((resolve, reject) => {
214
+ execFile(powershellPath(), [
215
+ '-NoProfile', '-NonInteractive', '-EncodedCommand', encodePowerShell(WRITE_ACL_SCRIPT),
216
+ ], {
217
+ windowsHide: true,
218
+ timeout: 20_000,
219
+ encoding: 'utf8',
220
+ env: {
221
+ ...process.env,
222
+ EVOLCORE_SERVICES_ACL_PLAN: encodeAclChanges(sandboxSid, items),
223
+ },
224
+ }, error => {
225
+ if (error)
226
+ reject(error);
227
+ else
228
+ resolve();
229
+ });
230
+ });
231
+ }
232
+ /** 把 PowerShell 的 JSON 解析成结构。 */
233
+ function parseAclOutput(output) {
234
+ const parsed = JSON.parse(extractJson(output));
235
+ const rows = Array.isArray(parsed) ? parsed : [parsed];
236
+ const sandboxSid = rows.find(row => row.kind === 'sandbox')?.sid ?? undefined;
237
+ const localMachineSid = rows.find(row => row.kind === 'machine')?.sid ?? undefined;
238
+ const byPath = new Map();
239
+ for (const row of rows) {
240
+ if (row.kind !== 'ace')
241
+ continue;
242
+ const entryPath = String(row.path);
243
+ const ace = {
244
+ sid: String(row.sid),
245
+ allow: row.allow === true,
246
+ inherited: row.inherited === true,
247
+ inheritOnly: row.inheritOnly === true,
248
+ // PowerShell 的 FileSystemRights 是有符号 int;泛用位会让它变负。
249
+ rights: Number(row.rights) >>> 0,
250
+ };
251
+ const list = byPath.get(entryPath);
252
+ if (list)
253
+ list.push(ace);
254
+ else
255
+ byPath.set(entryPath, [ace]);
256
+ }
257
+ return {
258
+ sandboxSid,
259
+ localMachineSid,
260
+ entries: [...byPath.entries()].map(([entryPath, aces]) => ({ path: entryPath, aces })),
261
+ };
262
+ }
263
+ /**
264
+ * 对一棵 `services` 目录树施加加固(幂等)。
265
+ *
266
+ * 调用点是运维动作,不在热路径上:`pack add` 之后、`ec services repair-acl`、
267
+ * `ec services doctor` 的报告。**失败不抛出**——加固失败不该让装包回滚,
268
+ * 调用方根据返回的 `errors` 记 `warn`。
269
+ */
270
+ export function hardenServicesAcl(dir) {
271
+ if (process.platform !== 'win32')
272
+ return { changed: false, plans: [], errors: [] };
273
+ const root = path.resolve(dir);
274
+ if (!fs.existsSync(root))
275
+ return { changed: false, plans: [], errors: [] };
276
+ let snapshot;
277
+ try {
278
+ snapshot = readServicesAcl(root);
279
+ }
280
+ catch (error) {
281
+ return { changed: false, plans: [], errors: [`read ACL failed: ${errorMessage(error)}`] };
282
+ }
283
+ if (!snapshot.sandboxSid)
284
+ return { changed: false, plans: [], errors: [] };
285
+ const { plans, changes } = planServicesAclTree(root, snapshot);
286
+ if (changes.length === 0)
287
+ return { changed: false, plans, errors: [] };
288
+ try {
289
+ execFileSync(powershellPath(), [
290
+ '-NoProfile', '-NonInteractive', '-EncodedCommand', encodePowerShell(WRITE_ACL_SCRIPT),
291
+ ], {
292
+ windowsHide: true,
293
+ timeout: 20_000,
294
+ encoding: 'utf8',
295
+ env: {
296
+ ...process.env,
297
+ EVOLCORE_SERVICES_ACL_PLAN: encodeAclChanges(snapshot.sandboxSid, changes),
298
+ },
299
+ });
300
+ }
301
+ catch (error) {
302
+ return { changed: false, plans, errors: [`apply ACL failed: ${errorMessage(error)}`] };
303
+ }
304
+ return { changed: true, plans, errors: [] };
305
+ }
306
+ /** Both execution modes apply the same tree policy and only add an inheritable DENY at the root. */
307
+ function planServicesAclTree(root, snapshot) {
308
+ const plans = snapshot.entries.map(entry => ({
309
+ path: entry.path,
310
+ plan: planServicesAclRepair(entry.aces, snapshot),
311
+ }));
312
+ const changes = plans.filter(item => item.plan.removeSids.length > 0 || item.plan.needsDenyWrite)
313
+ .map(item => ({
314
+ path: item.path,
315
+ removeSids: item.plan.removeSids,
316
+ denyWrite: item.plan.needsDenyWrite && samePath(item.path, root),
317
+ }));
318
+ return { plans, changes };
319
+ }
320
+ function encodeAclChanges(sandboxSid, items) {
321
+ return Buffer.from(JSON.stringify({ sandboxSid, denyRights: SERVICES_DENY_WRITE_RIGHTS, items }), 'utf8').toString('base64');
322
+ }
323
+ function powershellPath() {
324
+ return path.join(process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
325
+ }
326
+ /**
327
+ * 从 PowerShell 输出里取出 JSON 正文。
328
+ *
329
+ * PowerShell 5.1 在 `-EncodedCommand` 下仍可能把 progress 记录以 CLIXML 形式吐到
330
+ * stdout(LocalAccounts 模块加载时必现)。`$ProgressPreference` 只压得住一部分路径,
331
+ * 所以这里再兜一次:找第一个 `[{` / `{`,从那里截到最后一个配对括号。
332
+ */
333
+ function extractJson(output) {
334
+ const trimmed = output.trim();
335
+ if (trimmed.startsWith('[') || trimmed.startsWith('{'))
336
+ return trimmed || '[]';
337
+ const arrayStart = trimmed.indexOf('[{');
338
+ const objectStart = trimmed.indexOf('{"');
339
+ const candidates = [arrayStart, objectStart].filter(index => index >= 0);
340
+ if (candidates.length === 0)
341
+ return '[]';
342
+ const start = Math.min(...candidates);
343
+ const end = trimmed.lastIndexOf(trimmed[start] === '[' ? ']' : '}');
344
+ if (end < start)
345
+ return '[]';
346
+ return trimmed.slice(start, end + 1);
347
+ }
348
+ /**
349
+ * `-EncodedCommand` 要 UTF-16LE 的 base64。
350
+ *
351
+ * 用 `-Command` 传多行脚本会被 Win32 参数转义咬到(换行折叠、引号配对错乱),
352
+ * 表现为脚本"静默只跑了一部分"——不报错、结果不对,最难查。编码后整段原样送达。
353
+ */
354
+ function encodePowerShell(script) {
355
+ return Buffer.from(script, 'utf16le').toString('base64');
356
+ }
357
+ function samePath(left, right) {
358
+ return path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase();
359
+ }
360
+ function errorMessage(error) {
361
+ return error instanceof Error ? error.message : String(error);
362
+ }
363
+ /**
364
+ * 导出 ACL:沙箱组 SID、本机 machine SID、以及树内每个对象的每条 ACE。
365
+ *
366
+ * 用 `Get-Acl` 而不是 `icacls`:后者的输出随系统语言变化(中文 Windows 上是
367
+ * 「已成功处理」),且把 `(OI)(CI)` 之类折叠成简写,解析不可靠。
368
+ *
369
+ * **脚本本身保持完全静态**(参数全走环境变量),好处是可以脱离 Node 单独做
370
+ * 语法校验:`[Parser]::ParseFile` 一次就能发现括号/引号错误,而不是等到真跑。
371
+ */
372
+ const READ_ACL_SCRIPT = `
373
+ $ErrorActionPreference='Stop'
374
+ # Get-LocalGroup 首次加载 LocalAccounts 模块会写 progress 记录,走 stderr 时被
375
+ # Node 转成 CLIXML 噪声。一律静音,输出只留 JSON。
376
+ $ProgressPreference='SilentlyContinue'
377
+ $root = $env:EVOLCORE_SERVICES_ACL_ROOT
378
+ $group = Get-LocalGroup -Name $env:EVOLCORE_SERVICES_SANDBOX_GROUP -ErrorAction SilentlyContinue
379
+ $sandbox = if ($group) { $group.SID.Value } else { $null }
380
+ $machine = if ($sandbox) { $sandbox -replace '-[0-9]+$','' } else { $null }
381
+ $rows = New-Object System.Collections.ArrayList
382
+ [void]$rows.Add([pscustomobject]@{ kind='sandbox'; sid=$sandbox })
383
+ [void]$rows.Add([pscustomobject]@{ kind='machine'; sid=$machine })
384
+ $targets = @(Get-Item -LiteralPath $root -Force -ErrorAction SilentlyContinue)
385
+ $targets += @(Get-ChildItem -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue)
386
+ foreach ($target in $targets) {
387
+ if ($null -eq $target) { continue }
388
+ try { $acl = Get-Acl -LiteralPath $target.FullName } catch { continue }
389
+ foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
390
+ [void]$rows.Add([pscustomobject]@{
391
+ kind = 'ace'
392
+ path = $target.FullName
393
+ sid = $rule.IdentityReference.Value
394
+ allow = ($rule.AccessControlType -eq 'Allow')
395
+ inherited = [bool]$rule.IsInherited
396
+ inheritOnly = (([string]$rule.PropagationFlags) -match 'InheritOnly')
397
+ rights = [int]$rule.FileSystemRights
398
+ })
399
+ }
400
+ }
401
+ ConvertTo-Json -InputObject @($rows) -Compress -Depth 5
402
+ `;
403
+ /**
404
+ * 施加计划:先移除显式 Allow,再按需加 DENY。
405
+ *
406
+ * 计划走 base64 环境变量传进来——直接拼进 `-Command` 会被路径里的引号/空格咬到。
407
+ * 脚本同样是静态的,`denyRights` 也从计划里取。
408
+ */
409
+ const WRITE_ACL_SCRIPT = `
410
+ $ErrorActionPreference='Stop'
411
+ $payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:EVOLCORE_SERVICES_ACL_PLAN)) | ConvertFrom-Json
412
+ $writeBits = [System.Security.AccessControl.FileSystemRights]$payload.denyRights
413
+ $sandboxSid = [System.Security.Principal.SecurityIdentifier]$payload.sandboxSid
414
+ $inherit = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
415
+ $none = [System.Security.AccessControl.PropagationFlags]'None'
416
+ foreach ($item in $payload.items) {
417
+ $acl = Get-Acl -LiteralPath $item.path
418
+ $changed = $false
419
+ foreach ($sid in @($item.removeSids)) {
420
+ # 显式 Allow ACE(IsInherited=false)逐条摘掉:按身份 + 类型 + 继承标志精确匹配,
421
+ # 用 RemoveAccessRuleSpecific——RemoveAccessRuleAll 只按 identity/type 匹配且
422
+ # 生成的规则不带继承标志,遇到 (OI)(CI) 的 ACE 匹配不上,会静默不动作。
423
+ $explicit = $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier])
424
+ foreach ($rule in @($explicit)) {
425
+ if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -eq $sid) {
426
+ [void]$acl.RemoveAccessRuleSpecific($rule)
427
+ $changed = $true
428
+ }
429
+ }
430
+ }
431
+ if ($item.denyWrite) {
432
+ # 必须比对**写位**,不能只看"有 DENY 就算"。
433
+ # 实测踩过:目录上本来就继承着 DENY(R)(只读位),只看类型会把写防护误判成
434
+ # 已存在,DENY(写) 永远加不上去——加固"成功"但什么都没生效。
435
+ $writeMask = [int]$writeBits
436
+ $hasDeny = $false
437
+ foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
438
+ if ($rule.AccessControlType -ne 'Deny') { continue }
439
+ if ($rule.IdentityReference.Value -ne $payload.sandboxSid) { continue }
440
+ if ((([int]$rule.FileSystemRights) -band $writeMask) -eq $writeMask) { $hasDeny = $true }
441
+ }
442
+ if (-not $hasDeny) {
443
+ $deny = [System.Security.AccessControl.FileSystemAccessRule]::new(
444
+ $sandboxSid, $writeBits, $inherit, $none, [System.Security.AccessControl.AccessControlType]::Deny)
445
+ [void]$acl.AddAccessRule($deny)
446
+ $changed = $true
447
+ }
448
+ }
449
+ if ($changed) { Set-Acl -LiteralPath $item.path -AclObject $acl }
450
+ }
451
+ `;
@@ -2652,6 +2652,7 @@ export function evaluateToolPreflight(toolName, input, context) {
2652
2652
  const parserOptions = {
2653
2653
  verifyShellExecutable: process.platform === 'win32',
2654
2654
  managedTempDir: context.managedTempDir,
2655
+ posixShell: stringShellCarrier?.posixShell,
2655
2656
  ...(context.sessionCredential
2656
2657
  ? { expectedCredentialToken: context.sessionCredential }
2657
2658
  : {}),
@@ -2748,7 +2749,10 @@ export function evaluateToolPreflight(toolName, input, context) {
2748
2749
  };
2749
2750
  }
2750
2751
  if (ecCommand.issue === 'unsupported-escape') {
2751
- return { behavior: 'deny', input, message: '🔒 EC 内联文本不支持 PowerShell `n;请使用字面量 \\n。', policyCode: 'ec_shell_unsupported_escape' };
2752
+ const message = shellDialect === 'powershell'
2753
+ ? '🔒 EC 内联文本不支持 PowerShell `n;请使用字面量 \\n。'
2754
+ : `🔒 ${literalShellParseRemedy({ issue: ecCommand.issue, dialect: 'posix' })}`;
2755
+ return { behavior: 'deny', input, message, policyCode: 'ec_shell_unsupported_escape' };
2752
2756
  }
2753
2757
  if (ecCommand.issue === 'lossy-cmd-shim') {
2754
2758
  return { behavior: 'deny', input, message: '🔒 PowerShell 调用 ec.cmd 会截断物理多行参数;请保持原有 ec ... 调用,由 PowerShell 原生 shim 无损传递。', policyCode: 'ec_shell_lossy_cmd_shim' };
@@ -90,6 +90,19 @@ export function parsePeerKey(key) {
90
90
  channelId: decodeURIComponent(key.slice(idx + 1)),
91
91
  };
92
92
  }
93
+ /** Normalize a bare AID or encoded relation key; strict callers also validate external selectors. */
94
+ export function normalizePeerKey(input, options = {}) {
95
+ const raw = (input || '').trim();
96
+ if (!raw)
97
+ throw new Error('Peer must not be empty');
98
+ const { channelType, channelId } = raw.includes('#')
99
+ ? parsePeerKey(raw) : { channelType: 'aun', channelId: raw };
100
+ if (!channelType || !channelId || (options.strict && (!/^[a-z][a-z0-9_-]*$/.test(channelType) || !channelId.trim()
101
+ || /[\x00-\x1f\x7f]/.test(channelId)
102
+ || (channelType === 'aun' && !isValidAid(channelId)))))
103
+ throw new Error('Invalid peer selector');
104
+ return formatPeerKey(channelType, channelId);
105
+ }
93
106
  /** Read type evidence without network access or any AID-shape fallback. */
94
107
  export function readAunPeerKind(selfAid, peerAid, options = {}) {
95
108
  if (!isValidAid(selfAid) || !isValidAid(peerAid)) {
@@ -223,6 +236,25 @@ export class PeerIdentityCache {
223
236
  : maxAgeMs;
224
237
  return cached.lastCheckedAt === 0 || Date.now() - cached.lastCheckedAt > effectiveMaxAge;
225
238
  }
239
+ /**
240
+ * 本地 agent.md 是否已与缓存快照不同。
241
+ *
242
+ * 名录同步和 SDK 的 `agentmd.changed` 观察会独立刷新本地 agent.md,但
243
+ * `peer-identity.json` 有 30 天时效;只靠 `lastCheckedAt` 会让名片改名
244
+ * 最长 30 天才生效。命中缓存时比对本地文件哈希,变了就走同步路径;
245
+ * 读不到本地文件则维持缓存。
246
+ */
247
+ static localAgentMdChanged(peerId, cached, aunPath) {
248
+ let content;
249
+ try {
250
+ content = fs.readFileSync(agentMdPath(peerId, aunPath), 'utf-8');
251
+ }
252
+ catch {
253
+ return false;
254
+ }
255
+ const hash = 'sha256:' + crypto.createHash('sha256').update(content, 'utf-8').digest('hex');
256
+ return hash !== cached.agentMdHash;
257
+ }
226
258
  /**
227
259
  * 从 agent.md 更新身份信息
228
260
  * @param source 'agentmd'(验签通过)或 'agentmd-unverified'(内容可解析但验签未过)
@@ -364,10 +396,13 @@ export class PeerIdentityCache {
364
396
  // 1. 缓存检查
365
397
  if (!forceRefresh && !this.needsRefresh(channelType, peerId, agentDir)) {
366
398
  const cached = this.get(channelType, peerId, agentDir);
367
- if (cached) {
399
+ if (cached && !this.localAgentMdChanged(peerId, cached, resolvedAunPath)) {
368
400
  logger.debug(`[PeerIdentityCache] Cache hit: ${channelType}#${peerId} type=${cached.type} age=${Math.floor((Date.now() - cached.lastCheckedAt) / 1000 / 60 / 60 / 24)}d`);
369
401
  return cached;
370
402
  }
403
+ if (cached) {
404
+ logger.debug(`[PeerIdentityCache] Local agent.md changed since cache: ${channelType}#${peerId}, refreshing`);
405
+ }
371
406
  }
372
407
  const cachePath = this.getFilePath(channelType, peerId, agentDir);
373
408
  const revision = this.invalidationRevisions.get(cachePath) ?? 0;