evolcore 0.0.48 → 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 (112) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/agent-template/runtime.js +5 -2
  3. package/dist/agents/codex-runner.js +5 -1
  4. package/dist/aun/msg/p2p.js +2 -1
  5. package/dist/build-identity.json +1 -1
  6. package/dist/channels/aun.js +643 -273
  7. package/dist/cli/directory.js +6 -1
  8. package/dist/cli/index.js +7 -1
  9. package/dist/cli/managed-command-guard.js +2 -0
  10. package/dist/cli/model.js +20 -5
  11. package/dist/cli/quota.js +89 -0
  12. package/dist/cli/role.js +1 -0
  13. package/dist/cli/services-command.js +1 -0
  14. package/dist/cli/team-workspace-command.js +56 -2
  15. package/dist/config/config-field-policy.js +71 -1
  16. package/dist/config/config-manager.js +11 -1
  17. package/dist/config/providers-config.js +8 -4
  18. package/dist/config/providers-management.js +11 -3
  19. package/dist/config/resolved-config-op.js +3 -2
  20. package/dist/core/auth/delegation-authorization.js +33 -26
  21. package/dist/core/auth/operation-catalog.js +9 -0
  22. package/dist/core/command/cli-intent-parser.js +13 -0
  23. package/dist/core/command/command-handler.js +45 -2
  24. package/dist/core/command/menu-handler.js +6 -1
  25. package/dist/core/command/menu-protocol.js +24 -0
  26. package/dist/core/command/remote-shell.js +565 -0
  27. package/dist/core/daemon-control.js +57 -1
  28. package/dist/core/daemon-lifecycle.js +16 -2
  29. package/dist/core/evolagent-registry.js +6 -2
  30. package/dist/core/ipc-registration.js +1 -0
  31. package/dist/core/message/aun-ipc-sender.js +118 -56
  32. package/dist/core/message/contact-admission.js +91 -6
  33. package/dist/core/message/contact-pending-inbound.js +113 -0
  34. package/dist/core/message/contact-thread-approval.js +212 -0
  35. package/dist/core/message/im-renderer.js +40 -1
  36. package/dist/core/message/message-admission.js +5 -39
  37. package/dist/core/message/message-bridge.js +92 -39
  38. package/dist/core/message/message-log.js +24 -0
  39. package/dist/core/message/message-queue.js +97 -15
  40. package/dist/core/message/response-engine.js +151 -18
  41. package/dist/core/model/config-scope.js +6 -14
  42. package/dist/core/model/model-diagnostics.js +19 -0
  43. package/dist/core/model/model-fallback.js +13 -2
  44. package/dist/core/pack-auth.js +3 -0
  45. package/dist/core/pack-install.js +1 -1
  46. package/dist/core/permission/ec-command-parser.js +106 -19
  47. package/dist/core/permission/services-path-acl.js +451 -0
  48. package/dist/core/permission/tool-policy.js +5 -1
  49. package/dist/core/relation/peer-identity.js +13 -0
  50. package/dist/core/task/task-recovery-service.js +1 -0
  51. package/dist/core/thread/topic-id.js +15 -0
  52. package/dist/directory/owner-directory-admission.js +11 -8
  53. package/dist/directory/owner-directory-cache.js +19 -0
  54. package/dist/directory/owner-directory-markdown.js +1 -1
  55. package/dist/directory/owner-directory-policy.js +5 -30
  56. package/dist/directory/owner-directory-request-operation.js +5 -2
  57. package/dist/eck/kit-renderer.js +1 -1
  58. package/dist/eck/message-renderer.js +28 -5
  59. package/dist/ecweb/runtime/supervisor.js +36 -8
  60. package/dist/event-center/center-config.js +9 -5
  61. package/dist/event-center/dispatcher.js +10 -1
  62. package/dist/event-center/ipc-operation.js +19 -0
  63. package/dist/event-center/registry.js +20 -5
  64. package/dist/event-center/runtime.js +10 -7
  65. package/dist/index.js +4 -0
  66. package/dist/ipc.js +25 -1
  67. package/dist/outputs/authorization.js +16 -0
  68. package/dist/outputs/cards.js +336 -0
  69. package/dist/outputs/events.js +3 -2
  70. package/dist/outputs/protocol.js +1 -0
  71. package/dist/outputs/service.js +2 -15
  72. package/dist/services/index.js +29 -5
  73. package/dist/services/ipc-operation.js +84 -0
  74. package/dist/services/pack-manager.js +1 -0
  75. package/dist/services/service-payload.js +13 -7
  76. package/dist/stats/budget.js +1 -1
  77. package/dist/stats/model-resolver.js +2 -2
  78. package/dist/stats/quota-query.js +95 -0
  79. package/dist/trigger/script-sandbox.js +12 -0
  80. package/dist/utils/atomic-write.js +22 -8
  81. package/dist/utils/evolcore-version.js +2 -2
  82. package/dist/utils/host-info.js +100 -1
  83. package/dist/utils/npm-ops.js +43 -8
  84. package/dist/workbench/service.js +1 -1
  85. package/kits/docs/evolcore/INDEX.md +2 -0
  86. package/kits/docs/evolcore/aid.md +25 -0
  87. package/kits/docs/evolcore/config.md +4 -1
  88. package/kits/docs/evolcore/directory.md +8 -9
  89. package/kits/docs/evolcore/msg.md +9 -0
  90. package/kits/docs/evolcore/provider.md +1 -1
  91. package/kits/docs/evolcore/quota.md +54 -0
  92. package/kits/docs/evolcore/role.md +3 -0
  93. package/kits/docs/evolcore/stats.md +2 -0
  94. package/kits/docs/evolcore/trigger.md +2 -0
  95. package/kits/schemas/agent-config.schema.20.json +24 -0
  96. package/kits/skills/.switches.json +4 -0
  97. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  98. package/kits/skills/ec-provider/SKILL.md +57 -8
  99. package/kits/templates/roles/visitor.json +1 -0
  100. package/kits/templates/system-fragments/commands.md +1 -0
  101. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  102. package/kits/templates/system-fragments/thread.md +1 -0
  103. package/kits/templates/system-fragments/venue.md +11 -0
  104. package/package.json +2 -2
  105. package/scripts/agent-template/inspect.mjs +46 -10
  106. package/scripts/agent-template/shared/common.mjs +9 -3
  107. package/scripts/agent-template/shared/team-schema.json +6 -4
  108. package/scripts/agent-template/shared/template-contract.mjs +60 -10
  109. package/scripts/agent-template/shared/template-package.mjs +182 -21
  110. package/scripts/agent-template/shared/template-runtime.mjs +35 -2
  111. package/scripts/agent-template/shared/template.mjs +2 -2
  112. package/scripts/agent-template/team-pack.mjs +46 -11
@@ -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)) {
@@ -193,6 +193,7 @@ export class TaskRecoveryService {
193
193
  $schema_version: 3.1, id: trigger.triggerId, agentAid: session.selfAID, name: 'task-recovery',
194
194
  origin: { channelKey: message.channel, channelType, channelId: session.channelId,
195
195
  peerId, session: sessionTopicThreadId(session) ? 'thread' : 'main',
196
+ threadId: sessionTopicThreadId(session),
196
197
  delivery: session.chatType === 'group' ? { chatType: 'group', groupId: session.channelId } : { chatType: 'private' } },
197
198
  source: { type: 'once' }, execution: { type: 'target_session', prompt: TASK_RECOVERY_PROMPT },
198
199
  feedback: { strategy: 'origin' },
@@ -126,6 +126,21 @@ export function isMainSessionThreadId(value) {
126
126
  export function isTopicThreadId(value) {
127
127
  return typeof value === 'string' && value !== '' && !isMainSessionThreadId(value);
128
128
  }
129
+ /**
130
+ * Normalize a local thread identity for the specified relation. Explicit main IDs
131
+ * must name these two peers; topic IDs still need their caller's index checks.
132
+ * Main identities remain local and must never be emitted as wire thread_id.
133
+ */
134
+ export function normalizeThreadIdForPeer(value, selfAid, peerId) {
135
+ if (isTopicThreadId(value))
136
+ return value;
137
+ if (!isMainSessionThreadId(value))
138
+ return undefined;
139
+ const main = safeFormatMainTopicId(selfAid, peerId);
140
+ if (typeof value === 'string' && isMainTopicId(value) && canonicalizeMainTopicId(value) !== main)
141
+ return undefined;
142
+ return main;
143
+ }
129
144
  /** 别名:旧代码中广泛使用的 isSubTopicThreadId,语义与 isTopicThreadId 完全一致。 */
130
145
  export const isSubTopicThreadId = isTopicThreadId;
131
146
  /**
@@ -247,37 +247,40 @@ export function readOwnerDirectoryMembership(selfAid, aid, appOwned = false) {
247
247
  return { category: 'unavailable' };
248
248
  }
249
249
  const effectiveAllowExternalContacts = resolveAllowExternalContacts(selfAid, snapshot);
250
+ // `blockedAids` 是快照级字段,与调用方是否 appOwned 无关:以前只在 appOwned 分支里
251
+ // 计算,导致团队校验(不传 appOwned)读到 blocked=undefined,被屏蔽的联系人仍能被
252
+ // 拉进团队。这里统一算出来,两个分支共用。
253
+ const blocked = snapshot.blockedAids?.includes(aid) ?? false;
250
254
  if (appOwned) {
251
255
  const entry = snapshot.entries.find(item => item.aid === aid);
252
- const blocked = snapshot.blockedAids?.includes(aid) ?? false;
253
256
  const scopeExcluded = entry?.agent_scope?.mode === 'selected' && !entry.agent_scope.agent_aids.includes(selfAid);
254
257
  const internal = entry ? isInternalEntry(entry, ownerRefAid(snapshot, ownerAid)) : undefined;
255
258
  return { category: entry ? (entry.type === 'agent' ? 'agent' : entry.type === 'human' ? 'human' : 'other') : 'not_found',
256
259
  entry, blocked, scopeExcluded, internal, effectiveAllowExternalContacts };
257
260
  }
258
261
  if (aid === ownerAid || snapshot.owner?.aid === aid) {
259
- return { category: 'owner', internal: true, effectiveAllowExternalContacts };
262
+ return { category: 'owner', internal: true, blocked, effectiveAllowExternalContacts };
260
263
  }
261
264
  if (snapshot.personalAssistant?.aid === aid) {
262
- return { category: 'assistant', internal: true, effectiveAllowExternalContacts };
265
+ return { category: 'assistant', internal: true, blocked, effectiveAllowExternalContacts };
263
266
  }
264
267
  if (aid === selfAid)
265
- return { category: 'agent', internal: true, effectiveAllowExternalContacts };
268
+ return { category: 'agent', internal: true, blocked, effectiveAllowExternalContacts };
266
269
  const entry = snapshot.entries.find(item => item.aid === aid);
267
270
  if (!entry)
268
- return { category: 'not_found', effectiveAllowExternalContacts };
271
+ return { category: 'not_found', blocked, effectiveAllowExternalContacts };
269
272
  // 内外判据只有一个来源:Owner 身份块里的 aid。
270
273
  const ownerRef = ownerRefAid(snapshot, ownerAid);
271
274
  const internal = isInternalEntry(entry, ownerRef);
272
275
  const type = entry.type;
273
276
  if (type === 'agent')
274
- return { category: 'agent', internal, entry, effectiveAllowExternalContacts };
277
+ return { category: 'agent', internal, entry, blocked, effectiveAllowExternalContacts };
275
278
  if (type === 'human')
276
- return { category: 'human', internal, entry, effectiveAllowExternalContacts };
279
+ return { category: 'human', internal, entry, blocked, effectiveAllowExternalContacts };
277
280
  // 协议外的 type(`ai`、`codeagent`、缺失…)落 `other`:它既不是会发消息的
278
281
  // agent/human,也不是协议允许的 service/device/org/custom/host,用途未知。
279
282
  // 准入仍按内外分档(与宿主类型一致),只是不假装知道它是什么。
280
- return { category: 'other', internal, entry, effectiveAllowExternalContacts };
283
+ return { category: 'other', internal, entry, blocked, effectiveAllowExternalContacts };
281
284
  }
282
285
  catch (error) {
283
286
  const code = error && typeof error === 'object' && 'code' in error
@@ -1018,6 +1018,7 @@ export class OwnerDirectoryCache {
1018
1018
  for (const scope of OWNER_DIRECTORY_SCOPES)
1019
1019
  this._writeSyncStamp(scope);
1020
1020
  this.refreshMarkdown();
1021
+ this.notifySnapshotApplied();
1021
1022
  return true;
1022
1023
  }
1023
1024
  const fetched = this._readSharedCache();
@@ -1117,6 +1118,23 @@ export class OwnerDirectoryCache {
1117
1118
  *
1118
1119
  * 完整性由阶段一保证(`_assertComplete`);这里只跳过"拉取之后权限被撤"的范围。
1119
1120
  */
1121
+ notifySnapshotApplied() {
1122
+ if (!this.canApply())
1123
+ return;
1124
+ try {
1125
+ this.options.onSnapshotApplied?.();
1126
+ }
1127
+ catch (error) {
1128
+ logger.warn('[OwnerDirectoryCache] onSnapshotApplied failed:', error);
1129
+ }
1130
+ }
1131
+ /** Used only while durable inbound messages await approval. Honors Owner-wide backoff. */
1132
+ async reconcilePendingContacts() {
1133
+ if (!this.readPendingUpdate())
1134
+ await this.handleOwnerChangedEvent(this.options.ownerAid);
1135
+ await this.processPendingIfNeeded();
1136
+ await this.applyFromSharedCache();
1137
+ }
1120
1138
  async _applyAll(fetched) {
1121
1139
  const apply = async () => {
1122
1140
  if (!this.canApply())
@@ -1140,6 +1158,7 @@ export class OwnerDirectoryCache {
1140
1158
  const epoch = coordinatorFor(this.options.ownerAid).epoch;
1141
1159
  if (epoch)
1142
1160
  this.appliedGeneration = epoch.generation;
1161
+ this.notifySnapshotApplied();
1143
1162
  }
1144
1163
  // ── 共享缓存($EVOLCORE_HOME/data/owner-directory/<ownerAid>/) ────────────
1145
1164
  _sharedCacheDir() {
@@ -170,7 +170,7 @@ export function renderOwnerDirectoryMarkdown(input) {
170
170
  '- `ec directory refresh`:立即同步一次,然后重算本文件。怀疑名录过期时用。',
171
171
  '- `ec directory blocked`:查被拉黑的主体。名录里不渲染黑名单,要判断某人能不能联系就查这个。',
172
172
  '- `ec directory request <AID> [--note <说明>]`:给一个**还不在名录里**的人发加好友申请。',
173
- ' 只表示申请已提交,要等 Owner 在 App 上处理并同步名录后,才可能联系得上。',
173
+ ' 向目标发送显式好友邀请,仅表示已提交;普通消息出站无需先入录,入站仍按当前许可判断。',
174
174
  '- 需要名片原文时:`ec aid agentmd get <AID>`。',
175
175
  `- **备注不走命令**:直接写 \`${remarksExamplePath(input)}\`,frontmatter 用 \`aid\`/\`remark\`/\`updated_at\`,正文写「什么事找他」,写完 \`ec directory refresh\`。文件名须与 \`aid\` 一致,否则整条作废。`,
176
176
  ];
@@ -13,8 +13,8 @@ import { ConfigTarget, read } from '../config/config-manager.js';
13
13
  /**
14
14
  * 外部联系开关的最终值:**显式配置 > 个人助理判据 > false**。
15
15
  *
16
- * 个人助理要联系 Owner 之外的人,所以对自己默认打开;其余 agent 默认关闭,
17
- * 只有明确有外部业务需求时才由 Owner 打开。准入、注入、查询三处共用这一个判据。
16
+ * 个人助理默认接收外部联系人的入站;其余 agent 默认关闭,
17
+ * 可由 Owner 打开。普通出站不使用此开关。
18
18
  */
19
19
  export function resolveAllowExternalContacts(selfAid, snapshot,
20
20
  /** 显式配置;缺省时从配置文件读。测试用来固定优先级。 */
@@ -100,32 +100,7 @@ export function resolveOwnerDirectoryRenderPolicy(selfAid, snapshot) {
100
100
  allowedAids: policy.allowedAids ?? [],
101
101
  };
102
102
  }
103
- /**
104
- * 单条名录条目当前能不能联系。`ec directory info/list` 用它,`directory.md` 用上面
105
- * 那份快照——两边读的是同一组开关,口径必须一致,否则会出现"目录里标着能联系、
106
- * 发出去却被拒"。
107
- *
108
- * 判据顺序照搬准入:总开关 > 名单(白名单命中即通)> 内部档 / 外部档。
109
- * 黑名单**参与**这里:它是 Owner 显式指定的拒绝,总开关也翻不动它。
110
- */
111
- export function resolveEntryContactable(selfAid, snapshot, entry) {
112
- let policy;
113
- try {
114
- policy = readAccessPolicy(selfAid);
115
- }
116
- catch {
117
- // 配置读不出不等于"谁都不能联系":外部档仍按"显式配置 > 个人助理判据"回落,
118
- // 与注入侧口径保持一致(那份快照在同样的失败下也只关掉外部与总开关)。
119
- return entry.internal === true || resolveAllowExternalContacts(selfAid, snapshot) === true;
120
- }
121
- if (policy.deniedAids?.includes(entry.aid))
122
- return false;
123
- if (entry.internal === true)
124
- return policy.allowInternalContacts !== false;
125
- if (policy.allowedAids?.includes(entry.aid))
126
- return true;
127
- if (policy.allowAllContacts === true)
128
- return true;
129
- // 同 `resolveOwnerDirectoryRenderPolicy`:传 undefined 让函数自己去读显式配置。
130
- return resolveAllowExternalContacts(selfAid, snapshot) === true;
103
+ /** Ordinary outbound messaging is independent of inbound contact admission. */
104
+ export function resolveEntryContactable(_selfAid, _snapshot, _entry) {
105
+ return true;
131
106
  }