evolcore 0.0.43-test.8 → 0.0.46

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 (204) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +13 -5
  12. package/dist/agents/codex/app-server-client.js +2 -4
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/menu/client.js +142 -182
  18. package/dist/aun/rpc/client.js +33 -17
  19. package/dist/aun/service-proxy.js +6 -23
  20. package/dist/channels/aun.js +656 -112
  21. package/dist/cli/agent-create.js +37 -10
  22. package/dist/cli/agent-template.js +105 -84
  23. package/dist/cli/agent.js +31 -18
  24. package/dist/cli/daemon-commands.js +15 -17
  25. package/dist/cli/daemon-lifecycle-client.js +40 -18
  26. package/dist/cli/directory.js +12 -4
  27. package/dist/cli/ecmsg-gateway.js +5 -2
  28. package/dist/cli/events-command.js +2 -1
  29. package/dist/cli/init.js +50 -20
  30. package/dist/cli/integrity-command.js +2 -0
  31. package/dist/cli/managed-command-guard.js +20 -1
  32. package/dist/cli/menu-client.js +7 -5
  33. package/dist/cli/restart-monitor.js +33 -20
  34. package/dist/cli/services-command.js +28 -5
  35. package/dist/config/config-field-policy.js +24 -0
  36. package/dist/config/config-manager.js +20 -2
  37. package/dist/config/peer-book-store.js +152 -120
  38. package/dist/config/peer-role-resolver.js +24 -4
  39. package/dist/config/provider-identity-migration.js +1 -1
  40. package/dist/config/provider-identity.js +10 -4
  41. package/dist/config/provider-ipc-service.js +10 -2
  42. package/dist/config/provider-local-sync.js +2 -2
  43. package/dist/config/providers-config.js +95 -10
  44. package/dist/config/providers-import.js +4 -6
  45. package/dist/config/providers.js +14 -3
  46. package/dist/config/role-store.js +1 -1
  47. package/dist/config-store.js +9 -1
  48. package/dist/core/agent-application-service.js +56 -29
  49. package/dist/core/agent-create-status.js +3 -1
  50. package/dist/core/agent-creation-claim.js +1 -0
  51. package/dist/core/agent-ipc-registration.js +2 -2
  52. package/dist/core/agent-reload-coordinator.js +38 -1
  53. package/dist/core/agent-runtime.js +85 -38
  54. package/dist/core/auth/agent-delegation.js +5 -0
  55. package/dist/core/auth/operation-authorizer.js +1 -1
  56. package/dist/core/auth/operation-catalog.js +3 -3
  57. package/dist/core/bootstrap-service.js +3 -0
  58. package/dist/core/capability/capability-manager.js +3 -1
  59. package/dist/core/channel-loader.js +29 -3
  60. package/dist/core/channel-runtime.js +1 -1
  61. package/dist/core/command/agent-control.js +6 -5
  62. package/dist/core/command/agent-template-menu.js +32 -97
  63. package/dist/core/command/eventcenter-menu.js +61 -13
  64. package/dist/core/command/menu-catalog.js +11 -4
  65. package/dist/core/command/menu-handler.js +35 -8
  66. package/dist/core/command/menu-protocol.js +8 -16
  67. package/dist/core/command/skill-slash.js +6 -2
  68. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  69. package/dist/core/command/team-workspace-management-store.js +83 -0
  70. package/dist/core/command/team-workspace-management.js +1 -2
  71. package/dist/core/command/team-workspace-team.js +26 -3
  72. package/dist/core/daemon-control.js +3 -4
  73. package/dist/core/daemon-lifecycle.js +146 -110
  74. package/dist/core/evolagent-registry.js +42 -0
  75. package/dist/core/evolagent.js +2 -1
  76. package/dist/core/file-integrity/read.js +9 -16
  77. package/dist/core/file-integrity/store.js +94 -34
  78. package/dist/core/handoff/dispatcher.js +33 -7
  79. package/dist/core/handoff/runtime.js +8 -0
  80. package/dist/core/inference/text-inference.js +12 -2
  81. package/dist/core/invoke/invoke-service.js +24 -3
  82. package/dist/core/ipc-registration.js +3 -0
  83. package/dist/core/message/aun-ipc-sender.js +109 -7
  84. package/dist/core/message/contact-admission.js +6 -2
  85. package/dist/core/message/message-bridge.js +13 -0
  86. package/dist/core/message/message-queue.js +131 -30
  87. package/dist/core/message/pending-hints.js +8 -0
  88. package/dist/core/message/response-engine.js +48 -2
  89. package/dist/core/message/send-routing.js +3 -12
  90. package/dist/core/model/catalog-service.js +13 -0
  91. package/dist/core/model/model-catalog.js +57 -18
  92. package/dist/core/pack-auth.js +163 -31
  93. package/dist/core/pack-install.js +42 -1
  94. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  95. package/dist/core/permission/ec-command-parser.js +3 -1
  96. package/dist/core/permission/shell-environment.js +23 -0
  97. package/dist/core/rate-window.js +6 -1
  98. package/dist/core/session/session-idle-monitor.js +0 -1
  99. package/dist/core/session/session-manager.js +14 -0
  100. package/dist/core/session/session-title.js +26 -6
  101. package/dist/core/skill/index-generator.js +3 -4
  102. package/dist/core/thread/thread-service.js +0 -1
  103. package/dist/core/thread/topic-id.js +8 -0
  104. package/dist/directory/owner-directory-admission.js +17 -0
  105. package/dist/directory/owner-directory-cache.js +3 -1
  106. package/dist/directory/owner-directory-markdown.js +145 -23
  107. package/dist/directory/owner-directory-policy.js +23 -0
  108. package/dist/directory/owner-directory-query-operation.js +20 -6
  109. package/dist/directory/owner-directory-search.js +47 -0
  110. package/dist/eck/message-renderer.js +171 -32
  111. package/dist/ecweb/basic-settings-service.js +7 -3
  112. package/dist/ecweb/providers-service.js +17 -10
  113. package/dist/ecweb/runtime/lifecycle.js +1 -1
  114. package/dist/ecweb/runtime/supervisor.js +77 -35
  115. package/dist/event-center/admission-materializer.js +1 -1
  116. package/dist/event-center/bus-gate.js +48 -4
  117. package/dist/event-center/bus-host.js +3 -3
  118. package/dist/event-center/center-config.js +57 -28
  119. package/dist/event-center/dispatcher.js +8 -0
  120. package/dist/event-center/event-log.js +69 -27
  121. package/dist/event-center/index-generator.js +6 -1
  122. package/dist/event-center/ipc-operation.js +66 -25
  123. package/dist/event-center/pack-loader.js +12 -55
  124. package/dist/event-center/pack-manager.js +5 -3
  125. package/dist/event-center/registry.js +48 -52
  126. package/dist/event-center/runtime.js +219 -81
  127. package/dist/event-center/script-runner.js +18 -7
  128. package/dist/event-center/types.js +9 -1
  129. package/dist/event-center/validation.js +33 -4
  130. package/dist/index.js +96 -42
  131. package/dist/ipc.js +33 -7
  132. package/dist/product.js +1 -0
  133. package/dist/proxy/manager.js +52 -11
  134. package/dist/proxy/service-supervisor.js +265 -67
  135. package/dist/services/dispatcher.js +26 -3
  136. package/dist/services/idempotency.js +128 -0
  137. package/dist/services/identity.js +3 -27
  138. package/dist/services/index-generator.js +5 -1
  139. package/dist/services/index.js +244 -45
  140. package/dist/services/ipc-operation.js +164 -20
  141. package/dist/services/pack-manager.js +37 -9
  142. package/dist/services/router.js +100 -31
  143. package/dist/services/script-runner.js +15 -4
  144. package/dist/services/service-payload.js +50 -2
  145. package/dist/services/validation.js +107 -3
  146. package/dist/trigger/scheduler.js +14 -4
  147. package/dist/trigger/script-sandbox.js +39 -2
  148. package/dist/utils/cross-platform.js +35 -11
  149. package/dist/utils/error-utils.js +13 -1
  150. package/dist/utils/instance-registry.js +33 -35
  151. package/dist/utils/process-introspect.js +35 -20
  152. package/dist/utils/project-path.js +47 -3
  153. package/dist/utils/windows-shell-trust.js +174 -68
  154. package/kits/docs/context-assembly.md +3 -3
  155. package/kits/docs/evolcore/agent.md +28 -10
  156. package/kits/docs/evolcore/config.md +22 -0
  157. package/kits/docs/evolcore/directory.md +46 -12
  158. package/kits/docs/evolcore/event-center.md +6 -6
  159. package/kits/docs/evolcore/group-collaboration.md +1 -1
  160. package/kits/docs/evolcore/menu-client.md +7 -5
  161. package/kits/docs/evolcore/menu-protocol.md +5 -3
  162. package/kits/docs/evolcore/msg.md +10 -3
  163. package/kits/docs/evolcore/provider.md +7 -3
  164. package/kits/docs/evolcore/services.md +145 -12
  165. package/kits/docs/evolcore/thread-chain.md +17 -9
  166. package/kits/docs/prompt-loading-architecture.md +4 -4
  167. package/kits/eck_message_manifest.json +46 -3
  168. package/kits/rules/04-relation.md +10 -2
  169. package/kits/rules/06-channel.md +2 -1
  170. package/kits/schemas/providers.schema.2.json +1 -0
  171. package/kits/skills/ec-group/SKILL.md +4 -0
  172. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  173. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  174. package/kits/skills/thread-ops/SKILL.md +8 -5
  175. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  176. package/kits/templates/message-fragments/group-batch.md +1 -0
  177. package/kits/templates/message-fragments/item-group.md +4 -0
  178. package/kits/templates/message-fragments/item-private.md +4 -0
  179. package/kits/templates/message-fragments/thread-context.md +1 -1
  180. package/kits/templates/system-fragments/commands.md +5 -5
  181. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  182. package/kits/templates/system-fragments/relation.md +11 -7
  183. package/package.json +3 -2
  184. package/scripts/agent-template/index.mjs +9 -4
  185. package/scripts/agent-template/inspect.mjs +16 -9
  186. package/scripts/agent-template/shared/plan.mjs +3 -33
  187. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  188. package/scripts/agent-template/shared/template-package.mjs +119 -10
  189. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  190. package/scripts/agent-template/shared/template.mjs +5 -5
  191. package/scripts/agent-template/team-pack.mjs +245 -0
  192. package/scripts/agent-template/team-preview.mjs +111 -0
  193. package/scripts/aid-batch/identity-batch.mjs +143 -0
  194. package/dist/ability/versions.js +0 -32
  195. package/dist/aun/model-headers.js +0 -17
  196. package/dist/channels/builtin-plugins.js +0 -19
  197. package/dist/core/command/team-workspace-initializer.js +0 -2
  198. package/dist/core/command/team-workspace-job-store.js +0 -88
  199. package/dist/core/command/team-workspace-management-service.js +0 -2
  200. package/dist/core/contact-bind-registry.js +0 -27
  201. package/dist/event-center/ledger.js +0 -52
  202. package/dist/services/reply.js +0 -55
  203. package/kits/templates/message-fragments/item.md +0 -3
  204. package/scripts/agent-template/pack.mjs +0 -169
@@ -1,7 +1,7 @@
1
1
  /**
2
- * services.* 命名空间的形状判定。
2
+ * services.* 命名空间的请求与应答格式。
3
3
  *
4
- * 这里只回答「这条 payload.type 是不是服务消息、是请求还是应答」,
4
+ * 这里只处理消息类型识别、监听匹配和应答构造,
5
5
  * 不涉及「本机有没有包能接」(那是 pack-manager 的事),也不涉及
6
6
  * 「这条消息来自谁」(那是准入的事)。三层判据互不推导。
7
7
  */
@@ -68,3 +68,51 @@ export function matchesListen(listenType, actualType) {
68
68
  export function resultTypeFor(requestType) {
69
69
  return requestType.endsWith('.result') ? requestType : `${requestType}.result`;
70
70
  }
71
+ /** 成功:{type, request_id, ok:true, data}。 */
72
+ export function buildSuccessReply(requestType, requestId, data) {
73
+ const type = resultTypeFor(requestType);
74
+ return {
75
+ type,
76
+ requestId,
77
+ shouldSend: true,
78
+ payload: {
79
+ type,
80
+ request_id: requestId,
81
+ ok: true,
82
+ ...(data !== undefined ? { data } : {}),
83
+ },
84
+ };
85
+ }
86
+ /** 失败:{type, request_id, ok:false, error:{code,message}}。 */
87
+ export function buildErrorReply(requestType, requestId, code, message, extra) {
88
+ const type = resultTypeFor(requestType);
89
+ return {
90
+ type,
91
+ requestId: requestId ?? '',
92
+ shouldSend: true,
93
+ payload: {
94
+ type,
95
+ request_id: requestId,
96
+ ok: false,
97
+ error: { code, message },
98
+ ...(extra ?? {}),
99
+ },
100
+ };
101
+ }
102
+ /** 静默:不回,调用方只能等到超时(blocked / unmatched=silent / 总闸关闭)。 */
103
+ export function buildSilentReply(requestType, requestId) {
104
+ return {
105
+ type: resultTypeFor(requestType),
106
+ requestId,
107
+ shouldSend: false,
108
+ payload: {},
109
+ };
110
+ }
111
+ /** 脚本执行结果 → 回复。noop 不回。 */
112
+ export function replyFromOutcome(requestType, requestId, outcome) {
113
+ if (outcome.outcome === 'noop')
114
+ return buildSilentReply(requestType, requestId);
115
+ if (outcome.outcome === 'success')
116
+ return buildSuccessReply(requestType, requestId, outcome.data);
117
+ return buildErrorReply(requestType, requestId, outcome.error?.code ?? 'HANDLER_FAILED', outcome.error?.message ?? 'service handler failed');
118
+ }
@@ -3,9 +3,28 @@
3
3
  * 约束 1:1 映射 docs/services/schema/{service,router}.schema.json;Schema 为权威,
4
4
  * 两者不一致改这里并同步 Schema。手写校验器(不引 ajv),失败逐条报错。
5
5
  */
6
- import { isListenableType } from './service-payload.js';
6
+ import { isListenableType, RESERVED_TYPES } from './service-payload.js';
7
7
  export const SCRIPT_EXTENSIONS = ['mjs', 'cjs', 'js', 'py', 'sh', 'ps1'];
8
8
  export const RUNTIME_WHITELIST = ['node', 'python', 'bash', 'powershell'];
9
+ /**
10
+ * 扩展名 → 运行时的本地映射(已知扩展名恒有值)。
11
+ *
12
+ * 不复用 `script-runner` 的 `inferRuntime`:`validation → script-runner →
13
+ * pack-manager → validation` 会成环,加载期 `RUNTIME_WHITELIST` 可能是 undefined。
14
+ * 两边本来就是同一张表,这里只保证校验期能判自洽。
15
+ */
16
+ function runtimeForExtension(script) {
17
+ const ext = script.split('.').pop()?.toLowerCase();
18
+ if (ext === 'mjs' || ext === 'cjs' || ext === 'js')
19
+ return 'node';
20
+ if (ext === 'py')
21
+ return 'python';
22
+ if (ext === 'sh')
23
+ return 'bash';
24
+ if (ext === 'ps1')
25
+ return 'powershell';
26
+ return undefined;
27
+ }
9
28
  const TIMEOUT_MIN = 1000;
10
29
  const TIMEOUT_MAX = 300_000;
11
30
  const TIMEOUT_DEFAULT = 30_000;
@@ -106,6 +125,15 @@ function validateHandler(raw, errors) {
106
125
  if (raw.runtime !== undefined && !RUNTIME_WHITELIST.includes(raw.runtime)) {
107
126
  errors.push(`listen[].handler.runtime must be one of ${RUNTIME_WHITELIST.join('/')}`);
108
127
  }
128
+ else if (script !== undefined && raw.runtime !== undefined) {
129
+ // runtime 与扩展名必须自洽:`runtime: "python"` 配 `.mjs` 能过枚举校验,却在
130
+ // 运行时才因解释器不认脚本而失败。schema 也这么写("推断不出判校验失败"),
131
+ // 这里提前到加载期。
132
+ const inferred = runtimeForExtension(script);
133
+ if (inferred !== undefined && inferred !== raw.runtime) {
134
+ errors.push(`listen[].handler.runtime "${String(raw.runtime)}" does not match the script extension (expected "${inferred}"): ${script}`);
135
+ }
136
+ }
109
137
  if (raw.args !== undefined && (!Array.isArray(raw.args) || raw.args.some(item => typeof item !== 'string'))) {
110
138
  errors.push('listen[].handler.args must be an array of strings');
111
139
  }
@@ -177,6 +205,11 @@ function validateReplyPolicy(raw, errors) {
177
205
  if (raw.payloadTypes !== undefined) {
178
206
  if (!Array.isArray(raw.payloadTypes))
179
207
  errors.push('reply.payloadTypes must be an array');
208
+ else if (raw.payloadTypes.length === 0) {
209
+ // 空数组在 schema 里也是合法的(items 约束对空数组无约束力),但它表达不了任何
210
+ // 回复形态——照原样放行会让 reply.allowed=true 却一个结果都不认。
211
+ errors.push('reply.payloadTypes must not be empty; omit it to accept "service-result"');
212
+ }
180
213
  else if (raw.payloadTypes.some(item => item !== 'service-result')) {
181
214
  errors.push('reply.payloadTypes only accepts "service-result"');
182
215
  }
@@ -256,14 +289,84 @@ function validateQuota(raw, field, fallback, errors) {
256
289
  errors.push(`${field} has unknown fields: ${extra.join(', ')}`);
257
290
  const perMinute = intInRange(raw.perMinute, `${field}.perMinute`, 1, Number.MAX_SAFE_INTEGER, errors);
258
291
  const perHour = intInRange(raw.perHour, `${field}.perHour`, 1, Number.MAX_SAFE_INTEGER, errors);
292
+ // 分钟额度大于小时额度时小时那格永远轮不到,配置读起来像是生效其实没用。
293
+ if (perMinute !== undefined && perHour !== undefined && perMinute > perHour) {
294
+ errors.push(`${field}.perMinute must be <= ${field}.perHour`);
295
+ }
259
296
  return { perMinute: perMinute ?? fallback.perMinute, perHour: perHour ?? fallback.perHour };
260
297
  }
298
+ /** 与 `event-center/validation.ts` 的 `AID_PATTERN` 同一份口径;两处独立声明,改一处要同步另一处。 */
299
+ const AID_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}$/;
300
+ function validateAidList(value, field, errors) {
301
+ if (value === undefined)
302
+ return [];
303
+ if (!Array.isArray(value)) {
304
+ errors.push(`${field} must be an array`);
305
+ return undefined;
306
+ }
307
+ const out = [];
308
+ for (const item of value) {
309
+ if (typeof item !== 'string' || !AID_PATTERN.test(item)) {
310
+ errors.push(`${field} contains an invalid AID: ${String(item)}`);
311
+ return undefined;
312
+ }
313
+ // 去重保序:手抄白名单时重复项很常见,静默去掉比报错更省事。
314
+ if (!out.includes(item))
315
+ out.push(item);
316
+ }
317
+ return out;
318
+ }
319
+ /**
320
+ * 校验 `rules`:`{ <service.type>: { allow: [aid...], deny: [aid...] } }`。
321
+ *
322
+ * 与事件中心的 rules 同构:联系人快照是基础集合,allow 额外放行,deny 优先剔除。
323
+ * 同一个 AID 同时出现在 allow 和 deny 里是配置错误——deny 会赢,写的人多半
324
+ * 以为 allow 会赢,必须报出来而不是静默按 deny 处理。
325
+ */
326
+ function validateRules(raw, errors) {
327
+ const rules = {};
328
+ if (!isRecord(raw)) {
329
+ if (raw !== undefined)
330
+ errors.push('rules must be an object');
331
+ return rules;
332
+ }
333
+ for (const [type, entry] of Object.entries(raw)) {
334
+ if (!isListenableType(type)) {
335
+ errors.push(`rules key must be a service type: ${type}`);
336
+ continue;
337
+ }
338
+ // 内置保留字不受 rules 约束:它们的准入是刻意分级的(ping 零信息全开、
339
+ // list 空壳、带 service 的统一拒绝),加 deny 会造出"被拒 vs 正常"的可区分
340
+ // 信号,正是分级要避免的枚举信道。存下来却不生效更糟——写入时就拒绝。
341
+ if (RESERVED_TYPES.has(type)) {
342
+ errors.push(`rules must not target a builtin reserved type: ${type} (builtin admission is fixed)`);
343
+ continue;
344
+ }
345
+ if (!isRecord(entry)) {
346
+ errors.push(`rules.${type} must be an object`);
347
+ continue;
348
+ }
349
+ const extra = Object.keys(entry).filter(key => !['allow', 'deny'].includes(key));
350
+ if (extra.length)
351
+ errors.push(`rules.${type} has unknown fields: ${extra.join(', ')}`);
352
+ const allow = validateAidList(entry.allow, `rules.${type}.allow`, errors);
353
+ const deny = validateAidList(entry.deny, `rules.${type}.deny`, errors);
354
+ if (!allow || !deny)
355
+ continue;
356
+ const overlap = allow.filter(aid => deny.includes(aid));
357
+ if (overlap.length) {
358
+ errors.push(`rules.${type} contains the same AID in allow and deny: ${overlap.join(', ')}`);
359
+ }
360
+ rules[type] = { allow, deny };
361
+ }
362
+ return rules;
363
+ }
261
364
  /** 校验 services-config.json 原始对象。 */
262
365
  export function validateRouterConfig(raw) {
263
366
  const errors = [];
264
367
  if (!isRecord(raw))
265
368
  return { ok: false, errors: ['services-config.json must be a JSON object'] };
266
- const extra = Object.keys(raw).filter(key => !['v', 'enabled', 'rateLimit'].includes(key));
369
+ const extra = Object.keys(raw).filter(key => !['v', 'enabled', 'rateLimit', 'rules'].includes(key));
267
370
  if (extra.length)
268
371
  errors.push(`unknown top-level fields: ${extra.join(', ')}`);
269
372
  if (raw.v !== 1)
@@ -287,11 +390,12 @@ export function validateRouterConfig(raw) {
287
390
  };
288
391
  }
289
392
  }
393
+ const rules = validateRules(raw.rules, errors);
290
394
  if (errors.length)
291
395
  return { ok: false, errors };
292
396
  return {
293
397
  ok: true,
294
398
  errors: [],
295
- value: { v: 1, enabled: raw.enabled === true, rateLimit },
399
+ value: { v: 1, enabled: raw.enabled === true, rateLimit, rules },
296
400
  };
297
401
  }
@@ -1,4 +1,5 @@
1
1
  import crypto from 'crypto';
2
+ import { templateInstallationGate } from '../agent-template/jobs.js';
2
3
  import fs from 'fs';
3
4
  import { CronExpressionParser } from 'cron-parser';
4
5
  import { logger } from '../utils/logger.js';
@@ -41,20 +42,27 @@ export class TriggerRuntimeScheduler {
41
42
  initialized = false;
42
43
  stopping = false;
43
44
  lifecycleGeneration = 0;
44
- mutationPaused = false;
45
+ mutationPauses = new Set();
46
+ get mutationPaused() { return this.mutationPauses.size > 0; }
45
47
  pendingMutationStarts = 0;
46
48
  /** Hold scheduling without changing definitions or consuming one-shot triggers. */
47
- async pauseForMutation() {
49
+ async pauseForMutation(token = Symbol('mutation')) {
48
50
  if (this.mutationPaused || this.running.size || this.runStartLocks.size || this.pendingMutationStarts) {
49
51
  throw Object.assign(new Error('Trigger scheduler has active work'), { code: 'AGENT_BUSY' });
50
52
  }
51
- this.mutationPaused = true;
53
+ this.mutationPauses.add(token);
52
54
  for (const timer of this.timers.values())
53
55
  clearTimeout(timer);
54
56
  this.timers.clear();
55
57
  this.eventSource?.stop();
58
+ let released = false;
56
59
  return async () => {
57
- this.mutationPaused = false;
60
+ if (released)
61
+ return;
62
+ released = true;
63
+ this.mutationPauses.delete(token);
64
+ if (this.mutationPaused)
65
+ return;
58
66
  if (!this.stopping)
59
67
  for (const definition of this.manager.list())
60
68
  this.schedule(definition);
@@ -480,6 +488,8 @@ export class TriggerRuntimeScheduler {
480
488
  }
481
489
  }
482
490
  async startRun(definition, payload) {
491
+ if (templateInstallationGate(this.manager.agentAid ?? definition.agentAid).blocked)
492
+ return { ok: false, runId: 'team-pending', triggerId: definition.id, status: 'skipped', reason: 'stopped' };
483
493
  if (this.mutationPaused)
484
494
  return { ok: false, runId: 'mutation', triggerId: definition.id, status: 'skipped', reason: 'stopped' };
485
495
  this.pendingMutationStarts++;
@@ -8,11 +8,45 @@ import { resolveCodexCliPath } from '../agents/baseagent.js';
8
8
  import { ensureSessionRuntimeDir } from '../cli/task-context.js';
9
9
  import { buildBubblewrapCommand, buildHClassGuardCommand, resolveBubblewrapPath, } from '../core/permission/sandbox-runtime.js';
10
10
  import { resolvePhaseOneExecutionSandbox } from '../core/permission/mode.js';
11
- import { sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
11
+ import { isCredentialEnvironmentName, sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
12
12
  import { buildCodexProtectedFilesystemRules, classifyProtectedPath, getExistingRelationAttachmentDirs, isSameOrDescendant, } from '../core/permission/protected-paths.js';
13
13
  import { resolveRoot } from '../paths.js';
14
14
  import { buildCliLaunchCommand, killProcess, resolveCommandPath } from '../utils/cross-platform.js';
15
15
  import { TRIGGER_LOCAL_FILE_LIMIT } from './local-files.js';
16
+ /**
17
+ * 沙箱探针(`prepare()`)的超时上限。
18
+ *
19
+ * 探针要在 Windows 上做两次真实子进程往返(可读 + 拒读),正常情况下几百毫秒。
20
+ * 但没有上限时一旦 provisioning 卡住(ACL 写入、codex 启动),调用方会无限等待:
21
+ * services / events 的 dispatcher 槽位永不释放,并发槽打满后整条流水线停摆。
22
+ */
23
+ export const SANDBOX_PREPARE_TIMEOUT_MS = 30_000;
24
+ /**
25
+ * 给 `prepare()` 套一层超时:超时即 abort,让探针内部杀掉子进程并退出。
26
+ *
27
+ * 只做 `Promise.race` 不够——被抛弃的探针仍在后台跑子进程。所以传 signal 进去,
28
+ * 让探针自己收尾;`race` 只负责让调用方尽快拿到失败。
29
+ */
30
+ export async function runPrepareWithDeadline(prepare, timeoutMs = SANDBOX_PREPARE_TIMEOUT_MS) {
31
+ const controller = new AbortController();
32
+ let timer;
33
+ const timeout = new Promise((_, reject) => {
34
+ timer = setTimeout(() => {
35
+ // 先 reject 再 abort:abort 会同步触发探针的 abort 监听,它自己的拒绝可能
36
+ // 抢在超时错误之前结算,导致调用方拿到的是 `aborted` 而不是稳定错误码。
37
+ reject(Object.assign(new Error(`sandbox prepare timed out after ${timeoutMs}ms`), { code: 'SCRIPT_SANDBOX_TIMEOUT' }));
38
+ controller.abort();
39
+ }, timeoutMs);
40
+ timer.unref?.();
41
+ });
42
+ try {
43
+ await Promise.race([prepare(controller.signal), timeout]);
44
+ }
45
+ finally {
46
+ if (timer)
47
+ clearTimeout(timer);
48
+ }
49
+ }
16
50
  const WINDOWS_SANDBOX_SETUP_VERSION = 5;
17
51
  const SCRIPT_ENVIRONMENT_EXCLUDES = [
18
52
  'CODEX_HOME',
@@ -462,7 +496,10 @@ function buildSandboxEnvironment(workDir) {
462
496
  };
463
497
  }
464
498
  function getScriptEnvironmentExcludes() {
465
- const dynamic = Object.keys(process.env).filter(key => key.toUpperCase().startsWith('EVOLCORE_'));
499
+ // 三类:固定名单、本机凭据命名的变量、EvolCore 自己的控制变量。
500
+ // 凭据类必须按名字扫——`GITHUB_TOKEN` / `AWS_SECRET_ACCESS_KEY` 不在固定名单里,
501
+ // 漏掉就会随 `inherit="all"` 原样进到脚本。
502
+ const dynamic = Object.keys(process.env).filter(key => key.toUpperCase().startsWith('EVOLCORE_') || isCredentialEnvironmentName(key));
466
503
  return [...new Set([...SCRIPT_ENVIRONMENT_EXCLUDES, ...dynamic])];
467
504
  }
468
505
  function filesystemEntry(value, access) {
@@ -5,7 +5,8 @@ import { execFileSync, execFile, spawn, spawnSync } from 'child_process';
5
5
  import { promisify, TextDecoder } from 'util';
6
6
  import fs from 'fs';
7
7
  import { getProcessStartTime, parseCimDate } from './process-introspect.js';
8
- import { resolveTrustedWindowsCmdPath, resolveTrustedWindowsCmdPathAsync } from './windows-shell-trust.js';
8
+ import { requireTrustedWindowsCmdPath, requireTrustedWindowsCmdPathAsync, WindowsShellTrustError, } from './windows-shell-trust.js';
9
+ import { logger } from './logger.js';
9
10
  const execFileAsync = promisify(execFile);
10
11
  const CLI_PROBE_FAILURE_BACKOFF_MS = 5_000;
11
12
  export const CODEX_CLI_PROBE_TIMEOUT_MS = 9_000;
@@ -63,6 +64,14 @@ function escapeWindowsCmdArgument(value) {
63
64
  escaped = `"${escaped}"`;
64
65
  return escaped.replace(WINDOWS_CMD_META_RE, '^$1');
65
66
  }
67
+ function failWindowsCliLaunch(error, executable) {
68
+ if (error instanceof WindowsShellTrustError) {
69
+ logger.warn(`[WindowsShellTrust] ${JSON.stringify({
70
+ code: error.code, reason: error.reason, executable, message: error.message, ...error.diagnostics,
71
+ })}`);
72
+ }
73
+ throw error;
74
+ }
66
75
  /** Build one argv-based CLI launch without consulting the parent terminal. */
67
76
  export function buildCliLaunchCommand(executable, args, options = {}) {
68
77
  const windows = options.isWindows ?? isWindows;
@@ -77,13 +86,16 @@ export function buildCliLaunchCommand(executable, args, options = {}) {
77
86
  launcherPath: executable,
78
87
  };
79
88
  }
80
- const resolveWindowsCmd = options.resolveWindowsCmd ?? resolveTrustedWindowsCmdPath;
81
- const launcherPath = resolveWindowsCmd(options.comSpec);
82
- if (!launcherPath) {
83
- throw Object.assign(new Error('未找到受信任的系统 cmd.exe,已拒绝启动 Windows CLI shim'), {
84
- code: 'EACCES',
85
- path: executable,
86
- });
89
+ let launcherPath;
90
+ try {
91
+ const resolved = (options.resolveWindowsCmd ?? requireTrustedWindowsCmdPath)(options.comSpec);
92
+ if (!resolved) {
93
+ throw new WindowsShellTrustError('CMD_UNAVAILABLE', '系统 cmd 解析器未返回可用路径', { executable });
94
+ }
95
+ launcherPath = resolved;
96
+ }
97
+ catch (error) {
98
+ return failWindowsCliLaunch(error, executable);
87
99
  }
88
100
  const shellCommand = [
89
101
  escapeWindowsCmdCommand(executable),
@@ -296,7 +308,13 @@ export async function probeCli(command, args, options = {}) {
296
308
  const resolved = resolveCliProbe(command, args, options);
297
309
  let resolveWindowsCmd;
298
310
  if (isWindows && /\.(?:cmd|bat)$/i.test(resolved.probeExecutable)) {
299
- const trustedCmd = await resolveTrustedWindowsCmdPathAsync();
311
+ let trustedCmd;
312
+ try {
313
+ trustedCmd = await requireTrustedWindowsCmdPathAsync();
314
+ }
315
+ catch (error) {
316
+ return failWindowsCliLaunch(error, resolved.probeExecutable);
317
+ }
300
318
  resolveWindowsCmd = () => trustedCmd;
301
319
  }
302
320
  const request = prepareCliProbe(command, args, options, resolved, resolveWindowsCmd);
@@ -520,10 +538,10 @@ export async function launchMonitorAndConfirm(args, env, isAliveInRegistry, hasO
520
538
  * in a checkout: `npm install -g` swaps the whole package directory, and the
521
539
  * monitor has ~170 lazy `await import()` sites, so a module it has not loaded
522
540
  * yet would come from the new version while the rest is still the old one.
523
- * Staging `dist/`, `bin/` and `kits/` keeps package-owned code and runtime
541
+ * Staging `dist/`, `bin/`, `kits/` and runtime scripts keeps package-owned code and runtime
524
542
  * schemas on one version.
525
543
  *
526
- * `dist/`, `bin/`, `kits/` and `package.json` are copied. `node_modules` is
544
+ * `dist/`, `bin/`, `kits/`, runtime scripts and `package.json` are copied. `node_modules` is
527
545
  * linked, because copying it is hundreds of MB. The link degrades in steps so
528
546
  * that no platform is left without a path forward:
529
547
  *
@@ -562,6 +580,12 @@ export function prepareMonitorStage(packageRoot, stageParent) {
562
580
  const kitsSource = path.join(packageRoot, 'kits');
563
581
  if (fs.existsSync(kitsSource))
564
582
  fs.cpSync(kitsSource, path.join(stageDir, 'kits'), { recursive: true });
583
+ for (const name of ['agent-template', 'aid-batch']) {
584
+ const scriptsSource = path.join(packageRoot, 'scripts', name);
585
+ if (fs.existsSync(scriptsSource)) {
586
+ fs.cpSync(scriptsSource, path.join(stageDir, 'scripts', name), { recursive: true });
587
+ }
588
+ }
565
589
  const pkgJson = path.join(packageRoot, 'package.json');
566
590
  if (fs.existsSync(pkgJson))
567
591
  fs.copyFileSync(pkgJson, path.join(stageDir, 'package.json'));
@@ -2,6 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { getPackageRoot, resolvePaths } from '../paths.js';
4
4
  import { logger } from './logger.js';
5
+ import { isWindowsShellTrustError } from './windows-shell-trust.js';
5
6
  import { CODEX_SANDBOX_USER_NAMESPACE_DISABLED_BY_APPARMOR, CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE, isClaudeSandboxDependencyFailure, isCodexSandboxUserNamespaceFailure, isSandboxInitializationFailure, } from '../core/permission/sandbox-runtime.js';
6
7
  /** A deadline imposed by an outer executor, handled by the ordinary task timeout path. */
7
8
  export class ExecutionTimeoutError extends Error {
@@ -113,7 +114,8 @@ export var ErrorType;
113
114
  })(ErrorType || (ErrorType = {}));
114
115
  const POLICY_REJECTION_PATTERN = /invalid prompt[\s\S]{0,240}flagged as potentially violating our usage policy|prompt was flagged as potentially violating our usage policy/i;
115
116
  export function isPolicyRejectedError(error) {
116
- return POLICY_REJECTION_PATTERN.test(getErrorRawText(error) ?? '');
117
+ const raw = getErrorRawText(error) ?? '';
118
+ return /Provider model policy rejected:/u.test(raw) || POLICY_REJECTION_PATTERN.test(raw);
117
119
  }
118
120
  export function getErrorRawText(error, seen = new Set()) {
119
121
  if (typeof error === 'string') {
@@ -465,6 +467,8 @@ function hasRetryableHttpStatus(text) {
465
467
  return RETRYABLE_HTTP_STATUS_PATTERN.test(text);
466
468
  }
467
469
  export function classifyError(error) {
470
+ if (isWindowsShellTrustError(error))
471
+ return ErrorType.UNKNOWN;
468
472
  if (isUnattendedInputRequired(error))
469
473
  return ErrorType.INPUT_REQUIRED;
470
474
  if (error?.code === 'RUNNER_INTERRUPT_UNCONFIRMED')
@@ -548,6 +552,8 @@ export function classifyError(error) {
548
552
  * 注意:401 认证错误不可重试(API Key 无效不会因重试恢复)
549
553
  */
550
554
  export function isRetryableError(error) {
555
+ if (isWindowsShellTrustError(error))
556
+ return false;
551
557
  if (isUnattendedInputRequired(error))
552
558
  return false;
553
559
  if (error?.code === 'RUNNER_INTERRUPT_UNCONFIRMED')
@@ -611,6 +617,12 @@ function sandboxInitializationErrorMessage(error, prefix) {
611
617
  return `${prefix}执行沙箱启动失败(sandbox_initialization_failed),当前操作未执行;请查看原始诊断并运行 ec diagnose 排查`;
612
618
  }
613
619
  export function getErrorMessage(error, terminalReason, includeEmoji = true) {
620
+ if (isWindowsShellTrustError(error)) {
621
+ return `${includeEmoji ? '❌ ' : ''}${resolveErrorMessage(error)}`;
622
+ }
623
+ if (/Provider model policy rejected:/u.test(getErrorRawText(error) ?? '')) {
624
+ return `${includeEmoji ? '⚠️ ' : ''}模型未获 Provider 策略允许,请检查对应服务类型的模型名单;不会自动换模型。`;
625
+ }
614
626
  if (isUnattendedInputRequired(error)) {
615
627
  return `${includeEmoji ? '⚠️ ' : ''}${UNATTENDED_INPUT_REQUIRED_MESSAGE}`;
616
628
  }
@@ -12,8 +12,8 @@ import fs from 'fs';
12
12
  import path from 'path';
13
13
  import { spawnSync } from 'child_process';
14
14
  import { getPackageRoot, resolvePaths, isDevMode } from '../paths.js';
15
- import { isProcessRunning, killProcess, isWindows, findProcessesWithCommandLine, decodeWindowsOutput } from './cross-platform.js';
16
- import { getProcessSnapshot, getProcessStartTime, snapshotProcessState, startTimeMatches, } from './process-introspect.js';
15
+ import { isProcessRunning, isProcessRunningAsync, killProcess, waitForProcessExit, isWindows, findProcessesWithCommandLine, decodeWindowsOutput } from './cross-platform.js';
16
+ import { getProcessSnapshot, getProcessStartTime, getProcessStartTimeAsync, snapshotProcessState, startTimeMatches, } from './process-introspect.js';
17
17
  import { isConfirmedLeakedTestDaemon, runtimeHomeFromEnv } from './restart-safety.js';
18
18
  import { atomicWriteJson } from './atomic-write.js';
19
19
  // ── Helpers ──
@@ -310,7 +310,8 @@ export function scanInstances(options = {}) {
310
310
  }
311
311
  /**
312
312
  * 清理所有非自己 PID 的残留文件。仍活着的旧实例进程会被 SIGKILL。
313
- * 返回被杀掉的 PID 列表。
313
+ * 发送终止信号前重新核验身份;无法核验或终止失败时保留登记供后续处理。
314
+ * 返回终止命令成功的 PID 列表。
314
315
  */
315
316
  export function cleanupInstances() {
316
317
  const dir = instanceDir();
@@ -326,33 +327,18 @@ export function cleanupInstances() {
326
327
  const killed = [];
327
328
  for (const file of files) {
328
329
  const filePath = path.join(dir, file);
329
- if (file.startsWith('main-') && file.endsWith('.json')) {
330
+ if ((file.startsWith('main-') || file.startsWith('restart-monitor-')) && file.endsWith('.json')) {
330
331
  const record = safeParseJson(filePath);
331
332
  if (record?.pid) {
332
333
  if (record.pid === process.pid)
333
334
  continue;
334
335
  if (isProcessRunning(record.pid)) {
335
- const actual = getProcessStartTime(record.pid);
336
+ const actual = getProcessStartTime(record.pid, { fresh: true });
337
+ if (actual === null && isProcessRunning(record.pid))
338
+ continue;
336
339
  if (startTimeMatches(record.startedAt, actual)) {
337
- killPid(record.pid);
338
- killed.push(record.pid);
339
- }
340
- }
341
- }
342
- try {
343
- fs.unlinkSync(filePath);
344
- }
345
- catch { }
346
- }
347
- else if (file.startsWith('restart-monitor-') && file.endsWith('.json')) {
348
- const record = safeParseJson(filePath);
349
- if (record?.pid) {
350
- if (record.pid === process.pid)
351
- continue;
352
- if (isProcessRunning(record.pid)) {
353
- const actual = getProcessStartTime(record.pid);
354
- if (startTimeMatches(record.startedAt, actual)) {
355
- killPid(record.pid);
340
+ if (!killProcess(record.pid, true))
341
+ continue;
356
342
  killed.push(record.pid);
357
343
  }
358
344
  }
@@ -389,10 +375,6 @@ export function removeAll(pid) {
389
375
  removeMain(target);
390
376
  removeAidLog(target);
391
377
  }
392
- // ── Internal ──
393
- function killPid(pid) {
394
- killProcess(pid, true);
395
- }
396
378
  function normalizeProcessPath(value) {
397
379
  return value.replace(/[\\/]+/g, '/').toLowerCase();
398
380
  }
@@ -470,13 +452,16 @@ export function findOrphanProcesses(status = scanInstances({ includeAidActivity:
470
452
  // 快照完整时它本身就是存活进程表,不需要再逐 pid 拉 tasklist。
471
453
  if (!snapshot.complete && !isProcessRunning(pid))
472
454
  continue;
473
- const cmdline = commandLine || readCmdline(pid);
455
+ // Bind command evidence to a captured identity before later signalling.
456
+ const startedAt = snapshot.startedAt.get(pid) ?? getProcessStartTime(pid, { fresh: true }) ?? undefined;
457
+ const cmdline = snapshot.startedAt.has(pid) && commandLine ? commandLine : readCmdline(pid);
474
458
  // 二次验证:入口必须是当前 EvolCore 包的 dist/index.js。
475
459
  if (!isEvolCoreMainCommand(cmdline))
476
460
  continue;
477
461
  const processEnv = readProcessEnvironment(pid);
478
462
  orphans.push({
479
463
  pid,
464
+ startedAt,
480
465
  evolcoreHome: processEnv ? runtimeHomeFromEnv(processEnv) : null,
481
466
  cmdline,
482
467
  confirmedTestDaemon: processEnv ? isConfirmedLeakedTestDaemon(processEnv) : false,
@@ -485,18 +470,31 @@ export function findOrphanProcesses(status = scanInstances({ includeAidActivity:
485
470
  return orphans;
486
471
  }
487
472
  /**
488
- * SIGKILL 所有传入的孤儿 PID。返回成功杀掉的 PID 列表(即调用后已停的)。
473
+ * SIGKILL 已核验身份的孤儿 PID,只返回确认原进程已退出的 PID。
489
474
  */
490
- export function killOrphans(orphans) {
491
- const killed = [];
475
+ export async function killOrphans(orphans) {
476
+ const confirmations = [];
492
477
  for (const o of orphans) {
493
478
  try {
494
- killProcess(o.pid, true);
495
- killed.push(o.pid);
479
+ const expectedStartedAt = o.startedAt;
480
+ if (expectedStartedAt === undefined)
481
+ continue;
482
+ if (!startTimeMatches(expectedStartedAt, await getProcessStartTimeAsync(o.pid, { fresh: true })))
483
+ continue;
484
+ if (!killProcess(o.pid, true))
485
+ continue;
486
+ // Keep identity probes sequential, but overlap independent exit waits.
487
+ confirmations.push(waitForProcessExit(o.pid, 2000).then(async (exited) => {
488
+ if (exited || !await isProcessRunningAsync(o.pid))
489
+ return o.pid;
490
+ const currentStartedAt = await getProcessStartTimeAsync(o.pid, { fresh: true });
491
+ // PID reuse proves the original exited; never signal the replacement.
492
+ return currentStartedAt !== null && !startTimeMatches(expectedStartedAt, currentStartedAt) ? o.pid : null;
493
+ }).catch(() => null));
496
494
  }
497
495
  catch { }
498
496
  }
499
- return killed;
497
+ return (await Promise.all(confirmations)).filter((pid) => pid !== null);
500
498
  }
501
499
  function readCmdline(pid) {
502
500
  if (isWindows) {