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
@@ -7,8 +7,8 @@
7
7
  */
8
8
  import { spawn } from 'node:child_process';
9
9
  import path from 'node:path';
10
- import { buildTriggerScriptLaunch } from '../trigger/script-sandbox.js';
11
- import { sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
10
+ import { buildTriggerScriptLaunch, runPrepareWithDeadline } from '../trigger/script-sandbox.js';
11
+ import { isCredentialEnvironmentName, sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
12
12
  import { resolveRuntimePermissionMode } from '../core/role/runtime-policy.js';
13
13
  import { resolvePhaseOneExecutionSandbox } from '../core/permission/mode.js';
14
14
  import { killProcessTree, resolveCommandPath } from '../utils/cross-platform.js';
@@ -76,7 +76,9 @@ export class ScriptRunner {
76
76
  launch = this.buildLaunch(pack, handler, event, executable, scriptPath, scriptArgs);
77
77
  if (launch.prepare) {
78
78
  try {
79
- await launch.prepare();
79
+ // 探针必须设上限:沙箱 provisioning 挂住时这里会无限等待,dispatcher 的
80
+ // 槽位永不释放,并发打满后整个事件中心停摆。探针本身响应 abort。
81
+ await runPrepareWithDeadline(launch.prepare);
80
82
  }
81
83
  catch (error) {
82
84
  // 沙箱不可用 → 降级:清掉这次 launch,改用无沙箱配置重跑。
@@ -88,7 +90,10 @@ export class ScriptRunner {
88
90
  }
89
91
  catch (error) {
90
92
  const code = error.code;
91
- if (code === 'RUNTIME_NOT_FOUND' || code === 'INVALID_RUNTIME') {
93
+ if (code === 'RUNTIME_NOT_FOUND' || code === 'INVALID_RUNTIME' || code === 'SCRIPT_SANDBOX_UNAVAILABLE') {
94
+ // 拒跑而不是降级:`SCRIPT_SANDBOX_UNAVAILABLE` 来自「拿不到工程目录」这类
95
+ // 本该 fail-closed 的情况(见 event-center/daemon.ts 的 fail-closed 注释)。
96
+ // 把它当沙箱缺失降级,等于把"边界不可证明"变成"无边界执行"。
92
97
  return finish({ outcome: 'error', exitCode: 126, error: { code: String(code), message: errorMessage(error) }, stdoutPreview: '', stderrPreview: '' });
93
98
  }
94
99
  // 沙箱构造失败(缺 codex / 缺 bubblewrap / 平台不支持)→ 降级执行。
@@ -144,11 +149,11 @@ export class ScriptRunner {
144
149
  }
145
150
  /** 构造启动配置:fullaccess(或 bypass+owner)→ 无沙箱;否则 trigger 沙箱。 */
146
151
  buildLaunch(pack, handler, event, executable, scriptPath, scriptArgs) {
152
+ const publisherRole = this.deps.resolvePeerRole?.(event.publisher) ?? undefined;
147
153
  const effective = this.deps.permissionMode
148
154
  ? this.deps.permissionMode()
149
- : resolveRuntimePermissionMode({ selfAid: this.deps.aid }).effectiveValue;
155
+ : resolveRuntimePermissionMode({ selfAid: this.deps.aid, role: publisherRole }).effectiveValue;
150
156
  // 传发布方角色:只有 bypass + owner 才免沙箱(与 trigger 的 owner-bypass 同语义)。
151
- const publisherRole = this.deps.resolvePeerRole?.(event.publisher) ?? undefined;
152
157
  const sandboxDecision = resolvePhaseOneExecutionSandbox(effective, publisherRole);
153
158
  const ecEnv = this.buildEcEnv(pack, event);
154
159
  if (sandboxDecision.state === 'off') {
@@ -163,6 +168,7 @@ export class ScriptRunner {
163
168
  allowed: true,
164
169
  scope: 'agent',
165
170
  permissionMode: effective,
171
+ role: publisherRole,
166
172
  };
167
173
  const trigger = this.syntheticTrigger(pack, handler, executable);
168
174
  const launch = buildTriggerScriptLaunch({
@@ -332,6 +338,7 @@ export class ScriptRunner {
332
338
  }
333
339
  /** 脚本契约 stdin(detailed-design §六)。 */
334
340
  buildStdin(pack, event) {
341
+ const projectPath = this.deps.getProjectPath();
335
342
  return JSON.stringify({
336
343
  v: 1,
337
344
  pack: { name: pack.name, dir: pack.dir },
@@ -344,7 +351,9 @@ export class ScriptRunner {
344
351
  ...(event.schemaVersion !== undefined ? { schemaVersion: event.schemaVersion } : {}),
345
352
  data: event.data,
346
353
  },
347
- agent: { aid: this.deps.aid },
354
+ // File-producing handlers use the scoped project root. Do not make them
355
+ // infer an Agent installation directory that may deny sandbox writes.
356
+ agent: { aid: this.deps.aid, ...(projectPath ? { dir: projectPath } : {}) },
348
357
  paths: { ledger: pack.paths.ledger, logs: pack.paths.logsDir },
349
358
  });
350
359
  }
@@ -352,5 +361,7 @@ export class ScriptRunner {
352
361
  function isExcludedEnv(key) {
353
362
  if (ENVIRONMENT_EXCLUDES.includes(key))
354
363
  return true;
364
+ if (isCredentialEnvironmentName(key))
365
+ return true;
355
366
  return key.toUpperCase().startsWith('EVOLCORE_');
356
367
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 事件中心(Event Center)共享类型。
2
+ * 事件中心(Event Center)共享类型与 SDK 门面适配。
3
3
  * 设计:docs/event-center/detailed-design.md;Schema:docs/event-center/schema/。
4
4
  */
5
5
  /** 带稳定错误码的错误。 */
@@ -49,3 +49,11 @@ export function eventListenerOff(client, event, subscription, handler) {
49
49
  catch { /* 已失效 */ } };
50
50
  return () => { };
51
51
  }
52
+ /** SDK 0.5.34 stores each Bus role under JSON.stringify([aid, role]). */
53
+ export function getSdkBusBinding(facade, busAid) {
54
+ const buses = facade?.buses;
55
+ if (!(buses instanceof Map))
56
+ return undefined;
57
+ // Prefer the Bus role when the same AID also has publisher/subscriber bindings.
58
+ return buses.get(JSON.stringify([busAid, 'bus'])) ?? buses.get(busAid);
59
+ }
@@ -14,6 +14,24 @@ export const EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
14
14
  export const ROLE_NAME_PATTERN = /^[a-z0-9_-]+$/;
15
15
  export const SCRIPT_EXTENSIONS = ['mjs', 'cjs', 'js', 'py', 'sh', 'ps1'];
16
16
  export const RUNTIME_WHITELIST = ['node', 'python', 'bash', 'powershell'];
17
+ /**
18
+ * 扩展名 → 运行时的本地映射(已知扩展名恒有值)。
19
+ *
20
+ * 不复用 `script-runner` 的 `inferRuntime`:`validation → script-runner →
21
+ * pack-loader → validation` 会成环。两边本来就是同一张表,这里只保证校验期能判自洽。
22
+ */
23
+ function runtimeForExtension(script) {
24
+ const ext = script.split('.').pop()?.toLowerCase();
25
+ if (ext === 'mjs' || ext === 'cjs' || ext === 'js')
26
+ return 'node';
27
+ if (ext === 'py')
28
+ return 'python';
29
+ if (ext === 'sh')
30
+ return 'bash';
31
+ if (ext === 'ps1')
32
+ return 'powershell';
33
+ return undefined;
34
+ }
17
35
  const TTL_CEILING = 3600;
18
36
  const TIMEOUT_MIN = 1000;
19
37
  const TIMEOUT_MAX = 300_000;
@@ -170,6 +188,15 @@ function validateHandler(raw, errors) {
170
188
  if (raw.runtime !== undefined && !RUNTIME_WHITELIST.includes(raw.runtime)) {
171
189
  errors.push(`handler.runtime must be one of ${RUNTIME_WHITELIST.join('/')}`);
172
190
  }
191
+ else if (script !== undefined && raw.runtime !== undefined) {
192
+ // runtime 与扩展名必须自洽:`runtime: "python"` 配 `.mjs` 能过枚举校验,却在
193
+ // 运行时才因解释器不认脚本而失败。schema 也这么写("推断不出判校验失败"),
194
+ // 这里提前到加载期。
195
+ const inferred = runtimeForExtension(script);
196
+ if (inferred !== undefined && inferred !== raw.runtime) {
197
+ errors.push(`handler.runtime "${String(raw.runtime)}" does not match the script extension (expected "${inferred}"): ${script}`);
198
+ }
199
+ }
173
200
  if (raw.args !== undefined) {
174
201
  if (!Array.isArray(raw.args) || raw.args.some(item => typeof item !== 'string'))
175
202
  errors.push('handler.args must be an array of strings');
@@ -368,10 +395,12 @@ export function validateCenterConfig(raw) {
368
395
  const rateExtra = Object.keys(raw.rateLimit).filter(key => !['perMinute', 'perHour'].includes(key));
369
396
  if (rateExtra.length)
370
397
  errors.push(`rateLimit has unknown fields: ${rateExtra.join(', ')}`);
371
- rateLimit = {
372
- perMinute: intInRange(raw.rateLimit.perMinute, 'rateLimit.perMinute', 1, Number.MAX_SAFE_INTEGER, errors) ?? 60,
373
- perHour: intInRange(raw.rateLimit.perHour, 'rateLimit.perHour', 1, Number.MAX_SAFE_INTEGER, errors) ?? 600,
374
- };
398
+ const perMinute = intInRange(raw.rateLimit.perMinute, 'rateLimit.perMinute', 1, Number.MAX_SAFE_INTEGER, errors) ?? 60;
399
+ const perHour = intInRange(raw.rateLimit.perHour, 'rateLimit.perHour', 1, Number.MAX_SAFE_INTEGER, errors) ?? 600;
400
+ // 分钟额度大于小时额度时小时那格永远轮不到,配置读起来像是生效其实没用。
401
+ if (perMinute > perHour)
402
+ errors.push('rateLimit.perMinute must be <= rateLimit.perHour');
403
+ rateLimit = { perMinute, perHour };
375
404
  }
376
405
  }
377
406
  const rules = {};
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // 【重要】最先加载环境变量,确保后续模块初始化时可用
2
2
  import dotenv from 'dotenv';
3
3
  import path from 'path';
4
+ import { resolveProjectDefaultPath } from './utils/project-path.js';
4
5
  import { ensureDataDirs, resolvePaths, eckDebugDir, daemonControlDir, daemonQueuePath, daemonMessageDedupPath, isDevMode } from './paths.js';
5
6
  // 立即加载 .env 文件(在其他模块导入之前)
6
7
  try {
@@ -31,13 +32,14 @@ import { GeminiAgentPlugin } from './agents/gemini-runner.js';
31
32
  // 不要静态导入 ecagent-runner:它连带整个 ecagent 运行时(typebox 占了模块图
32
33
  // 三分之一的 resolve),而绝大多数部署并不使用 ecagent。这里用懒加载外壳。
33
34
  import { EcagentAgentPluginLazy } from './agents/ecagent-plugin-lazy.js';
34
- import { registerBuiltinChannelPlugins } from './channels/builtin-plugins.js';
35
+ import { AUNChannelPlugin } from './channels/aun.js';
35
36
  import { registerAbilityPlatform } from './ability/daemon.js';
36
37
  import { assertAunEncryptionSeedPolicy } from './aun/aid/encryption-seed-policy.js';
37
38
  import { BindService } from './utils/aid-bind.js';
38
39
  import { buildEnvelope } from './core/message/message-utils.js';
39
40
  import { ResponseEngine } from './core/message/response-engine.js';
40
41
  import { MessageQueue } from './core/message/message-queue.js';
42
+ import { wasInterruptHintConsumed } from './core/message/pending-hints.js';
41
43
  import { MessageBridge } from './core/message/message-bridge.js';
42
44
  import { readFastaunVersion, readInstalledEvolcoreVersion, createEvolcoreStartupDiagnostics, reportEvolcoreStartup, } from './utils/evolcore-version.js';
43
45
  import { recoverAllRoleMutationsSync } from './core/command/role-menu.js';
@@ -46,7 +48,7 @@ import { startDaemonControlAid } from './core/daemon-control.js';
46
48
  import { createDelegationAuthorizer } from './core/auth/delegation-authorization.js';
47
49
  import { registerProxyIpcExecutor } from './proxy/ipc-service.js';
48
50
  import { ownerResolver, getDaemonOwners, getPrimaryOwner } from './core/ownership/owner-resolver.js';
49
- import { StartupTaskQueue, StartupGate, discoverStartupWork, recoverStartupObserverHints, StartupHandoffRecovery, resumePendingSessions, createDaemonShutdown, daemonConversationTotalExecutionMs, daemonConversationWatchdogMs, daemonIdleTimeoutMs, startupTaskReadiness, } from './core/daemon-lifecycle.js';
51
+ import { StartupTaskQueue, startupConnectionBudget, StartupGate, discoverStartupWork, recoverStartupObserverHints, StartupHandoffRecovery, resumePendingSessions, createDaemonShutdown, daemonConversationTotalExecutionMs, daemonConversationWatchdogMs, daemonIdleTimeoutMs, startupTaskReadiness, } from './core/daemon-lifecycle.js';
50
52
  import { createLifecycleNoticeService } from './core/lifecycle-notice.js';
51
53
  import { BootstrapService, createBootstrapCompletionHandler, createBootstrapOwnerBoundHandler } from './core/bootstrap-service.js';
52
54
  import { MessageCache } from './core/message/message-cache.js';
@@ -123,10 +125,6 @@ async function main() {
123
125
  // managed root before any runner or task runtime is initialized.
124
126
  ensureProcessManagedTempDir();
125
127
  const buildDiagnostics = createEvolcoreStartupDiagnostics(import.meta.url);
126
- void trace.track('daemon.versionReport', () => reportEvolcoreStartup(import.meta.url, message => logger.info(message), buildDiagnostics), undefined, { initialPhase: 'running' }).catch(error => {
127
- buildDiagnostics.state = 'unavailable';
128
- logger.warn(`[Build] startup diagnostics unavailable: ${error instanceof Error ? error.message : String(error)}`);
129
- });
130
128
  trace.mark('daemon.sdkFilter');
131
129
  installChannelSdkConsoleFilter();
132
130
  console.error('[EvolCore] ✓ Console filter installed');
@@ -264,15 +262,27 @@ async function main() {
264
262
  let startupEcwebState = 'waiting';
265
263
  const priorityStartupGate = new StartupGate();
266
264
  const normalStartupGate = new StartupGate();
267
- // Audit needs genuine task Ready; optional services can also start degraded.
268
- const taskReadyGate = new StartupGate();
269
265
  const waitForBackgroundStartup = async () => await normalStartupGate.promise !== 'cancelled' && !startupCancelled;
270
266
  onShutdown(() => {
271
267
  startupCancelled = true;
272
268
  cancelStartupClassification();
273
269
  priorityStartupGate.settle('cancelled');
274
270
  normalStartupGate.settle('cancelled');
275
- taskReadyGate.settle('cancelled');
271
+ });
272
+ // Full-tree build hashing is diagnostic I/O, not a prerequisite for tasks.
273
+ // Keep status pending until the background release instead of competing
274
+ // with recovery metadata reads. Bootstrap-only daemons have no task gate.
275
+ void trace.track('daemon.versionReport', async (phase) => {
276
+ if (!bindBootstrapMode) {
277
+ phase('waiting', 'normal Ready');
278
+ if (!await waitForBackgroundStartup())
279
+ return false;
280
+ }
281
+ phase('running');
282
+ return reportEvolcoreStartup(import.meta.url, message => logger.info(message), buildDiagnostics);
283
+ }, undefined, { initialPhase: 'waiting' }).catch(error => {
284
+ buildDiagnostics.state = 'unavailable';
285
+ logger.warn(`[Build] startup diagnostics unavailable: ${error instanceof Error ? error.message : String(error)}`);
276
286
  });
277
287
  // ECWeb has one lifecycle owner: the daemon. The CLI may have started an
278
288
  // instance just before spawning us; the supervisor adopts it when healthy,
@@ -395,6 +405,7 @@ async function main() {
395
405
  sessionManager.registerFileAdapter(new GeminiSessionFileAdapter());
396
406
  sessionManager.registerFileAdapter(new EcagentSessionFileAdapter());
397
407
  let capturedStartupQueue;
408
+ let startupQueueSnapshot;
398
409
  const startupQueueCaptured = new Promise(resolve => { capturedStartupQueue = resolve; });
399
410
  let discoveredStartupWork;
400
411
  const agentWorkPriority = new Map();
@@ -410,7 +421,7 @@ async function main() {
410
421
  const startupWorkPromise = trace.track('daemon.startupWorkDiscovery', () => discoverStartupWork({
411
422
  agentAids: startupAgents.map(agent => agent.aid), daemonTriggerAid,
412
423
  primaryAid: primaryAgent?.aid, sessionsRoot: paths.sessionsDir, queuePath: daemonQueuePath(),
413
- onQueueCaptured: capturedStartupQueue,
424
+ onQueueCaptured: snapshot => { startupQueueSnapshot = snapshot; capturedStartupQueue(); },
414
425
  onScan: timing => { scanTimings.push(timing); },
415
426
  onDiagnostics: timing => {
416
427
  trace.setMeta('recoveryScan.eventLoop', JSON.stringify(timing));
@@ -421,7 +432,7 @@ async function main() {
421
432
  return;
422
433
  agentWorkPriority.set(aid, true);
423
434
  agentWorkResolvers.get(aid)?.(true);
424
- logger.info(`[startup] Recovery work identified: aid=${aid} source=${reason}; admitting Runner/AUN while scan continues`);
435
+ logger.info(`[startup] Recovery work identified: aid=${aid} source=${reason}; admitting Runner while scan continues`);
425
436
  },
426
437
  onAgentDiscovered: (aid, plan) => {
427
438
  if (startupCancelled)
@@ -636,7 +647,10 @@ async function main() {
636
647
  await registerBuiltinChannelPlugins(channelLoader);
637
648
  // Ready control/recovery connections take the next available slot. Idle AUN
638
649
  // may use spare capacity without waiting for unrelated work classification.
639
- const connectionQueue = new StartupTaskQueue(2, 50);
650
+ const connectionBudget = startupConnectionBudget();
651
+ trace.setMeta('connectionAdmission', JSON.stringify({ ...connectionBudget, intervalMs: 50 }));
652
+ logger.info(`[startup] Channel connection admission: cpuParallelism=${connectionBudget.cpuParallelism} concurrency=${connectionBudget.concurrency} intervalMs=50`);
653
+ const connectionQueue = new StartupTaskQueue(connectionBudget.concurrency, 50);
640
654
  const schedulerQueue = new StartupTaskQueue(2, 50);
641
655
  channelLoader.setConnectionAdmission(instance => connectionQueue.run(() => instance.connect(), () => !startupCancelled && !instance.lifecycle?.signal.aborted));
642
656
  daemonPluginLifecycle.defer(() => { connectionQueue.stop(); schedulerQueue.stop(); }, 'startup admission');
@@ -762,6 +776,7 @@ async function main() {
762
776
  processor.setInteractionRouter(interactionRouter);
763
777
  // 创建消息队列
764
778
  const startupHintsReady = new Set();
779
+ const startupSessionsReady = new Set();
765
780
  let startupHandoffRecovery;
766
781
  let sessionIdleRestoreState = 'waiting';
767
782
  const messageQueue = new MessageQueue(async (message) => {
@@ -774,12 +789,15 @@ async function main() {
774
789
  }, {
775
790
  persistencePath: daemonQueuePath(),
776
791
  dedupPath: daemonMessageDedupPath(),
792
+ wasObserverHintConsumed: message => wasInterruptHintConsumed(paths.sessionsDir, message),
777
793
  blockedReason: (message, sessionId) => {
778
794
  const aid = message.selfAID || agentRegistry.resolveByChannel(message.channel)?.aid;
779
795
  if (!aid || !startupRunnerReady.has(aid))
780
796
  return;
781
797
  if (!startupHintsReady.has(aid))
782
798
  return 'startup observer hint registration';
799
+ if (!startupSessionsReady.has(aid))
800
+ return 'startup session recovery registration';
783
801
  const handoffBlocked = startupHandoffRecovery?.blockedReason(aid, sessionId);
784
802
  if (handoffBlocked)
785
803
  return handoffBlocked;
@@ -813,7 +831,18 @@ async function main() {
813
831
  // is deliberately dropped here and reclaimed from active.json by its scheduler.
814
832
  // Capture queued inputs before restorePersisted rewrites their snapshot.
815
833
  await startupQueueCaptured;
816
- messageQueue.restorePersisted(false);
834
+ if (startupQueueSnapshot) {
835
+ for (const bucket of [...startupQueueSnapshot.queues, ...(startupQueueSnapshot.active ?? [])]) {
836
+ for (const item of bucket.items) {
837
+ const message = item.message;
838
+ const parts = bucket.queueKey.split('::');
839
+ const sessionId = message.boundSessionId || (parts.length >= 3 ? parts[1] : parts[0]);
840
+ sessionManager.registerSessionRoute(sessionId, message);
841
+ }
842
+ }
843
+ }
844
+ // An unreadable snapshot must fail restoration, never be overwritten as an empty queue.
845
+ messageQueue.restorePersisted(false, startupQueueSnapshot);
817
846
  const droppedTriggerSessionIds = new Set(messageQueue.consumeDroppedTriggerSessionIds());
818
847
  // 进程退出时立即刷盘队列状态(防止 debounce 期间的消息丢失)
819
848
  onShutdown(() => messageQueue.persistQueuesImmediate());
@@ -1028,7 +1057,6 @@ async function main() {
1028
1057
  };
1029
1058
  const startupTriggerReady = new Set();
1030
1059
  const startupTriggerFailed = new Set();
1031
- const startupSessionsReady = new Set();
1032
1060
  const startupTriggerPromises = new Map();
1033
1061
  const defaultPolicy = createDefaultChannelPolicy();
1034
1062
  processor.registerChannel(daemonChannel, defaultPolicy, { channelType: 'daemon' });
@@ -1037,7 +1065,7 @@ async function main() {
1037
1065
  // ── MessageBridge:Channel ↔ Core 消息桥梁 ──
1038
1066
  trace.mark('daemon.messageBridge');
1039
1067
  const defaultProjectPath = primaryAgent?.projectPath
1040
- ?? defaults.projects?.defaultPath
1068
+ ?? resolveProjectDefaultPath(defaults.projects?.defaultPath)
1041
1069
  ?? path.join(paths.root, 'projects', 'default');
1042
1070
  const isContactBindChannelReady = (channelKey) => {
1043
1071
  const inst = channelInstances.find(candidate => candidate.adapter.channelKey === channelKey);
@@ -1141,7 +1169,7 @@ async function main() {
1141
1169
  sendLifecycleNoticeForChannel: instance => lifecycleNotices.online(instance),
1142
1170
  trySendPendingRestartNotice,
1143
1171
  sessionsDir: paths.sessionsDir,
1144
- isStartupRecoveryPending: () => startupRecoveryPending,
1172
+ isStartupRecoveryPending: aid => startupRecoveryPending && !startupHintsReady.has(aid),
1145
1173
  isCancelled: () => startupCancelled,
1146
1174
  refreshAunAuthorization: async (aid) => {
1147
1175
  const view = await ownerResolver.refresh(aid, { source: 'startup' });
@@ -1236,7 +1264,7 @@ async function main() {
1236
1264
  priorityRelease: priorityStartupGate.status,
1237
1265
  optionalRelease: normalStartupGate.status,
1238
1266
  ecweb: startupEcwebState === 'waiting' && ecwebSupervisor?.status().enabled ? 'waiting'
1239
- : startupEcwebState === 'failed' ? 'failed' : ecwebSupervisor?.status().state ?? 'disabled',
1267
+ : ecwebSupervisor?.status().state ?? 'disabled',
1240
1268
  backgroundRecovery: {
1241
1269
  handoff: startupHandoffRecovery?.status() ?? { completed: 0, total: triggerStartupAgents.length, retrying: 0 },
1242
1270
  sessionIdle: sessionIdleRestoreState,
@@ -1373,6 +1401,7 @@ async function main() {
1373
1401
  reload: (aid, options) => reloadCoordinator.reload(aid, options),
1374
1402
  hooks: reloadHooks,
1375
1403
  hotLoad: coreHotLoadAgent,
1404
+ unload: agentRuntimeOperations.unload,
1376
1405
  resync: coreResyncAgents,
1377
1406
  create: async (options) => {
1378
1407
  const { agentCreateNonInteractive } = await import('./cli/agent-create.js');
@@ -1403,11 +1432,21 @@ async function main() {
1403
1432
  channelInstances,
1404
1433
  hotLoad: coreHotLoadAgent,
1405
1434
  activate: completeAgentBootstrap,
1435
+ activatePrepared: async (aid) => bootstrapService.completeBootstrap(aid, { allowSuppliedOwnerPending: true }),
1406
1436
  });
1407
1437
  initializationServiceForOwnerRecovery = agentInitializationService;
1408
1438
  agentApplicationService.setInitializationService(agentInitializationService);
1409
1439
  cmdHandler.setAgentApplicationService(agentApplicationService);
1410
1440
  setAgentTemplateService(createAgentTemplateRuntime({
1441
+ holdHandoff: (aid, token) => handoffRuntime.holdAgent(aid, token),
1442
+ initialization: agentInitializationService, application: agentApplicationService,
1443
+ usable: aid => {
1444
+ const agent = agentRegistry.get(aid);
1445
+ return !!agent && agent.config.enabled !== false && agentMap.has(`${aid}::${agent.baseagent}`)
1446
+ && channelInstances.some(instance => instance.channelType === 'aun'
1447
+ && instance.channel.getAidState?.()?.aid === aid
1448
+ && instance.channel.getAidState?.()?.status === 'connected');
1449
+ },
1411
1450
  registry: agentRegistry, coordinator: reloadCoordinator,
1412
1451
  reloadInsideGate: async (aid) => { await agentRegistry.reload(aid, reloadHooks); },
1413
1452
  getControl: () => controlChannel,
@@ -1558,28 +1597,17 @@ async function main() {
1558
1597
  return [instance, trace.startTask('daemon.channelConnect', owner ? `aid=${owner.aid}; channel=${channel}` : channel, { initialPhase: 'waiting' })];
1559
1598
  }));
1560
1599
  logger.info(`🚀 EvolCore core is ready; connecting ${channelInstances.length} channel(s) in background`);
1561
- const backgroundConnections = new Set();
1562
1600
  const connectOptions = {
1563
1601
  sharedAdmission: true,
1564
1602
  beforeConnect: async (instance) => {
1565
1603
  const owner = agentRegistry.resolveByChannel(instance.adapter.channelKey)
1566
1604
  ?? agentRegistry.resolveByChannel(instance.adapter.channelName);
1567
1605
  const timing = channelConnectTimings.get(instance);
1568
- if (owner && instance.channelType === 'aun') {
1569
- timing?.phase('waiting', 'Agent work classification');
1570
- const priority = await agentWorkReady.get(owner.aid);
1571
- if (priority === undefined) {
1572
- if (startupCancelled)
1573
- return false;
1574
- throw new Error(`Work classification unavailable for ${owner.aid}`);
1575
- }
1576
- if (!priority)
1577
- backgroundConnections.add(instance);
1578
- }
1579
1606
  // Transport and authenticated control messages do not require a model runner.
1580
1607
  if (startupCancelled || owner?.status === 'disabled')
1581
1608
  return false;
1582
- timing?.phase('queued', backgroundConnections.has(instance) ? 'idle connection admission' : 'priority connection admission');
1609
+ const priority = !owner || instance.channelType !== 'aun' || agentWorkPriority.get(owner.aid) === true;
1610
+ timing?.phase('queued', priority ? 'priority connection admission' : 'idle connection admission');
1583
1611
  return true;
1584
1612
  },
1585
1613
  shouldConnect: (instance) => {
@@ -1592,8 +1620,14 @@ async function main() {
1592
1620
  onConnected: markChannelConnected,
1593
1621
  connect: async (instance) => {
1594
1622
  const timing = channelConnectTimings.get(instance);
1623
+ const owner = agentRegistry.resolveByChannel(instance.adapter.channelKey)
1624
+ ?? agentRegistry.resolveByChannel(instance.adapter.channelName);
1595
1625
  try {
1596
- const started = await connectionQueue.run(() => { timing.phase('running'); return instance.connect(); }, () => !startupCancelled && channelInstances.includes(instance) && !instance.lifecycle?.signal.aborted, backgroundConnections.has(instance) ? 'background' : 'foreground');
1626
+ const started = await connectionQueue.run(() => {
1627
+ timing.phase('running');
1628
+ return instance.connect();
1629
+ }, () => !startupCancelled && channelInstances.includes(instance) && !instance.lifecycle?.signal.aborted, () => owner && instance.channelType === 'aun'
1630
+ ? (agentWorkPriority.get(owner.aid) ? 'foreground' : 'background') : 'foreground');
1597
1631
  timing(started ? 'ok' : 'cancelled');
1598
1632
  return started;
1599
1633
  }
@@ -1636,7 +1670,7 @@ async function main() {
1636
1670
  const finishConnections = trace.startTask('daemon.channelConnectionsReady', `aun=${aunInstances.length}; other=${externalInstances.length}; control AUN tracked separately`, { summary: true });
1637
1671
  const aunConnections = connectAfter(aunInstances);
1638
1672
  void aunConnections.catch(() => { });
1639
- // Agent AUN and Runner admission can progress as each scan finishes.
1673
+ // Agent AUN transport progresses independently; classification prioritizes queued work.
1640
1674
  // Cross-Agent channel routes and local recovery still need the complete plan.
1641
1675
  const startupWork = await startupWorkPromise.catch(error => {
1642
1676
  finishConnections('failed');
@@ -1712,8 +1746,8 @@ async function main() {
1712
1746
  await sessionIdleMonitor.activate({
1713
1747
  waitForBackground: async () => {
1714
1748
  sessionIdleRestoreState = 'waiting';
1715
- phase('waiting', 'normal Ready');
1716
- admitted = await taskReadyGate.promise === 'ready' && !startupCancelled;
1749
+ phase('waiting', 'background startup');
1750
+ admitted = await waitForBackgroundStartup();
1717
1751
  if (admitted) {
1718
1752
  sessionIdleRestoreState = 'restoring';
1719
1753
  phase('running');
@@ -1766,8 +1800,6 @@ async function main() {
1766
1800
  });
1767
1801
  // 统一 channel:health 跨通道通知(仅 auth_error)
1768
1802
  registerChannelHealthNotifications({ eventBus, channelInstances, agentRegistry });
1769
- // Observer hints retain foreground precedence. Handoff history is scanned
1770
- // only after actual task Ready and protects only its affected sessions.
1771
1803
  void trace.track('daemon.observerHintsComplete', () => recoverStartupObserverHints({
1772
1804
  channelInstances,
1773
1805
  recoveryAids: triggerStartupAgents.map(agent => agent.aid),
@@ -1789,10 +1821,13 @@ async function main() {
1789
1821
  }), undefined, { summary: true })
1790
1822
  .catch(error => logger.error('[startup] observer hint registration failed:', error));
1791
1823
  void trace.track('daemon.handoffRecoveryComplete', async (phase) => {
1792
- phase('waiting', 'normal Ready');
1824
+ phase('waiting', 'background startup');
1793
1825
  let admitted = false;
1794
1826
  await startupHandoffRecovery.run(async () => {
1795
- admitted = await taskReadyGate.promise === 'ready' && !startupCancelled;
1827
+ // Handoff scanning is background recovery and must not depend on a
1828
+ // genuine task Ready. normalStartupGate carries a 30s degraded release,
1829
+ // so a single never-ready Agent can no longer keep the scan unstarted.
1830
+ admitted = await normalStartupGate.promise !== 'cancelled' && !startupCancelled;
1796
1831
  if (admitted) {
1797
1832
  phase('running');
1798
1833
  trace.point('daemon.handoffRecovery');
@@ -1831,12 +1866,16 @@ async function main() {
1831
1866
  if (startupCancelled)
1832
1867
  return false;
1833
1868
  phase('running');
1834
- resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap,
1869
+ await resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap,
1835
1870
  pendingSessions });
1836
1871
  startupSessionsReady.add(agent.aid);
1837
1872
  checkStartupTaskReady();
1838
1873
  }, `aid=${agent.aid}; sessions=${pendingSessions.length}`, { initialPhase: 'waiting' });
1839
1874
  }));
1875
+ if (startupWork.recoveryIndexAids.size && !startupCancelled
1876
+ && !messageQueue.completeRecoveryIndex([...startupWork.recoveryIndexAids])) {
1877
+ logger.warn('[startup] Recovery index could not be persisted; retaining compatibility scan for the next start');
1878
+ }
1840
1879
  settleSessionRecovery(startupCancelled ? 'cancelled' : 'ok');
1841
1880
  })().catch(error => {
1842
1881
  settleSessionRecovery('failed');
@@ -1912,7 +1951,6 @@ async function main() {
1912
1951
  return;
1913
1952
  normalTaskState = state;
1914
1953
  taskReadinessSettled = true;
1915
- taskReadyGate.settle(state);
1916
1954
  normalStartupGate.settle(state);
1917
1955
  if (state === 'ready') {
1918
1956
  trace.tasksReady();
@@ -1941,7 +1979,6 @@ async function main() {
1941
1979
  normalTaskState = 'failed';
1942
1980
  priorityStartupGate.settle('failed');
1943
1981
  normalStartupGate.settle('failed');
1944
- taskReadyGate.settle('failed');
1945
1982
  settleStartupTaskReady('failed');
1946
1983
  logger.error('[startup] Task runtime dispatch failed:', error);
1947
1984
  });
@@ -1987,7 +2024,6 @@ async function main() {
1987
2024
  cancelStartupClassification();
1988
2025
  priorityStartupGate.settle('cancelled');
1989
2026
  normalStartupGate.settle('cancelled');
1990
- taskReadyGate.settle('cancelled');
1991
2027
  void startupCpuProfile?.stop('shutdown');
1992
2028
  stopReadinessObservers();
1993
2029
  settleStartupTaskReady('cancelled');
@@ -2055,3 +2091,21 @@ if (isMainScript(import.meta.url)) {
2055
2091
  process.exit(1);
2056
2092
  });
2057
2093
  }
2094
+ async function registerBuiltinChannelPlugins(channelLoader) {
2095
+ channelLoader.register(new AUNChannelPlugin());
2096
+ const providers = [
2097
+ ['feishu', async () => new (await import('./channels/feishu.js')).FeishuChannelPlugin()],
2098
+ ['wechat', async () => new (await import('./channels/wechat.js')).WechatChannelPlugin()],
2099
+ ['dingtalk', async () => new (await import('./channels/dingtalk.js')).DingtalkChannelPlugin()],
2100
+ ['qqbot', async () => new (await import('./channels/qqbot.js')).QQBotChannelPlugin()],
2101
+ ['wecom', async () => new (await import('./channels/wecom.js')).WecomChannelPlugin()],
2102
+ ];
2103
+ for (const [channelType, load] of providers) {
2104
+ try {
2105
+ channelLoader.register(await load());
2106
+ }
2107
+ catch (error) {
2108
+ channelLoader.recordProviderFailure(channelType, error);
2109
+ }
2110
+ }
2111
+ }
package/dist/ipc.js CHANGED
@@ -9,7 +9,7 @@ import { execFile } from 'node:child_process';
9
9
  import { logger, logOwnershipEvent } from './utils/logger.js';
10
10
  import { withMenuProcessingTime, logMenuRequestCompleted, logMenuRequestReceived } from './core/command/menu-protocol.js';
11
11
  import { fileCache } from './core/daemon-file-cache.js';
12
- import { DAEMON_RUNTIME_EPOCH_ENV } from './cli/task-context.js';
12
+ import { DAEMON_RUNTIME_EPOCH_ENV, isTrustedFullAccessRuntimeContext } from './cli/task-context.js';
13
13
  import { HANDOFF_QUERY_MAX_LIMIT, HANDOFF_STATES } from './core/handoff/types.js';
14
14
  import { AgentReloadBusyError } from './core/agent-reload-coordinator.js';
15
15
  import { getPackageRoot, getWindowsInstanceSocketPathCandidates, normalizeIpcEndpoint, resolvePaths } from './paths.js';
@@ -22,7 +22,8 @@ import { normalizeAunMentionEntries } from './aun/msg/mention-schema.js';
22
22
  import { remoteAccessService } from './core/auth/remote-access-store.js';
23
23
  import { setModelCatalogDaemonOwner } from './core/model/model-catalog.js';
24
24
  import { RUNTIME_ENVIRONMENT_NAMES, setRuntimeEnvironmentOverride } from './config/runtime-env.js';
25
- import { MAIN_CLI_BIN, SESSION_ID_ENV } from './product.js';
25
+ import { MAIN_CLI_BIN, MESSAGE_CLI_BIN, SESSION_ID_ENV } from './product.js';
26
+ import { canonicalizeEvolcoreCommandArgv } from './core/permission/ec-command-parser.js';
26
27
  import { ownerResolver } from './core/ownership/owner-resolver.js';
27
28
  import { parseOwnershipCommand, executeOwnershipCommand, ownershipFailure } from './aun/aid/ownership-operation.js';
28
29
  import { ECWEB_SERVICE_PROTOCOL, validateEcwebClientProtocolRequirements, } from './contracts/ecweb-service-protocol.js';
@@ -69,6 +70,7 @@ const LOCAL_CONTROL_COMMANDS = new Set([
69
70
  'evolagent.list',
70
71
  'evolagent.show',
71
72
  'evolagent.reload',
73
+ 'evolagent.lifecycle',
72
74
  'evolagent.load',
73
75
  'evolagent.resync',
74
76
  'menu.exec',
@@ -1159,11 +1161,13 @@ export class IpcServer {
1159
1161
  // 否则绑定原始命令 argv。收发方等执行参数由 daemon 在授权后另行补全。
1160
1162
  const expectedArgv = executionSpec
1161
1163
  ? [...executionSpec.argv]
1162
- : [
1163
- MAIN_CLI_BIN,
1164
- ...(cmd.type === 'menu-client.request' ? ['menu-client'] : []),
1165
- ...cmd.argv,
1166
- ];
1164
+ : cmd.type === 'aun-msg-send' && cmd.argv[0] === MESSAGE_CLI_BIN
1165
+ ? canonicalizeEvolcoreCommandArgv(cmd.argv)
1166
+ : [
1167
+ MAIN_CLI_BIN,
1168
+ ...(cmd.type === 'menu-client.request' ? ['menu-client'] : []),
1169
+ ...cmd.argv,
1170
+ ];
1167
1171
  const expectedHash = hashDelegatedCommandArgv(expectedArgv, executionSpec);
1168
1172
  if (!expectedHash || cmd.delegationCommandHash !== expectedHash) {
1169
1173
  return this.diagnosticRejection('command_hash_mismatch', cmd);
@@ -2734,6 +2738,22 @@ export class IpcServer {
2734
2738
  return { ok: false, error: e?.message || String(e) };
2735
2739
  }
2736
2740
  }
2741
+ case 'evolagent.lifecycle': {
2742
+ if (cmd.sessionId !== undefined || cmd.delegationToken !== undefined) {
2743
+ return { ok: false, code: 'NOT_ALLOWED', error: 'Managed callers must use agent.op' };
2744
+ }
2745
+ if (!['enable', 'disable', 'delete'].includes(cmd.action) || typeof cmd.aid !== 'string') {
2746
+ return { ok: false, code: 'INVALID_ARGS', error: 'Invalid Agent lifecycle operation' };
2747
+ }
2748
+ if (!this.agentApplicationService) {
2749
+ return { ok: false, code: 'NOT_CONFIGURED', error: 'Agent application service is not configured' };
2750
+ }
2751
+ return cmd.action === 'delete'
2752
+ ? await this.agentApplicationService.delete(cmd.aid, cmd.purge === true)
2753
+ : cmd.action === 'disable'
2754
+ ? await this.agentApplicationService.disable(cmd.aid, cmd.force === true)
2755
+ : await this.agentApplicationService.enable(cmd.aid, cmd.force === true);
2756
+ }
2737
2757
  case 'evolagent.reload': {
2738
2758
  const name = cmd.name;
2739
2759
  if (!name || typeof name !== 'string')
@@ -3083,10 +3103,16 @@ export class IpcServer {
3083
3103
  return { kind: 'local-control' };
3084
3104
  }
3085
3105
  const context = sessionId ? this.taskRuntimeContextProvider?.({ sessionId }) : undefined;
3106
+ // fullaccess 必须由 daemon 校验过的 context 推出,不能取请求体里的自报值:
3107
+ // `isTrustedFullAccessRuntimeContext` 四个条件合判,少一个就等于放宽了别处
3108
+ // 正在用的安全边界(见 cli/task-context.ts)。
3109
+ const fullAccess = isTrustedFullAccessRuntimeContext(context);
3086
3110
  return {
3087
3111
  kind: 'managed',
3088
3112
  ...(context?.selfAid ? { selfAid: context.selfAid } : {}),
3089
3113
  ...(context?.peerRole ? { peerRole: context.peerRole } : {}),
3114
+ ...(fullAccess ? { fullAccess: true } : {}),
3115
+ ...(fullAccess && context?.authorizedBy ? { authorizedBy: context.authorizedBy } : {}),
3090
3116
  };
3091
3117
  }
3092
3118
  hasValidControlToken(value) {
package/dist/product.js CHANGED
@@ -7,6 +7,7 @@
7
7
  export const PRODUCT_DISPLAY_NAME = 'EvolCore';
8
8
  export const MAIN_PACKAGE_NAME = 'evolcore';
9
9
  export const MAIN_CLI_BIN = 'ec';
10
+ export const MESSAGE_CLI_BIN = 'ecmsg';
10
11
  export const RESTART_REQUEST_ID_ENV = 'EVOLCORE_RESTART_REQUEST_ID';
11
12
  export const CHANNEL_LOGS_ENV = 'CHANNEL_LOGS';
12
13
  export const WEB_PACKAGE_NAME = 'ec-web';