evolcore 0.0.43-test.6 → 0.0.43-test.8

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 (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -24,14 +24,47 @@ const SCRIPT_ENVIRONMENT_EXCLUDES = [
24
24
  'GOOGLE_API_KEY',
25
25
  'ECAGENT_API_KEY',
26
26
  ];
27
+ /**
28
+ * 构造 Trigger / 事件 / 服务脚本的启动配置。
29
+ *
30
+ * ## 三条执行路径(只此三条,其余组合一律 fail-closed)
31
+ *
32
+ * | 路径 | 判据 | 沙箱 | 平台 | 说明 |
33
+ * | --- | --- | --- | --- | --- |
34
+ * | daemon | `authorization.scope === 'daemon'` | **无** | 全平台 | 直接 spawn,继承 `process.env`(不清洗密钥) |
35
+ * | 无沙箱 | `permissionMode === 'fullaccess'`,或 `bypass` + `role === 'owner'` | **无** | 全平台 | 由 `:66` 与 `resolvePhaseOneExecutionSandbox` 判定;本函数在 fullaccess 时直接抛错要求走 daemon scope |
36
+ * | scoped | 其余非 fullaccess 模式 | **有** | Linux / Windows | macOS 不支持,见 `:70` |
37
+ *
38
+ * ## scoped 路径的沙箱后端(当前实现)
39
+ *
40
+ * - **Linux**:系统 `bubblewrap`(`--ro-bind / /` + `--tmpfs` 遮蔽 L/H-class 路径)。
41
+ * 不依赖 Codex。系统包缺失时报 `bubblewrap is required for scoped Trigger script isolation`。
42
+ * - **Windows**:**借用 `@openai/codex` 的 Windows 沙箱**(`codex.exe sandbox`
43
+ * 子命令 + `codex-windows-sandbox-setup.exe` 施加的 NTFS ACL)。
44
+ * Codex 在这里只当「沙箱宿主」用,与 baseagent 是 claude 还是 codex **无关**,
45
+ * 也不碰模型/认证/会话。这是已知的硬依赖:`package.json` 并未声明它,
46
+ * 需要用户在机器上全局安装。
47
+ * - **macOS**:**不支持**(`:70`)。没有可用后端,scoped 脚本一律拒跑。
48
+ *
49
+ * 三者的失败语义一致:要么跑在有隔离的沙箱里,要么拒跑(`SCRIPT_SANDBOX_UNAVAILABLE` /
50
+ * 退出码 126),不存在「静默降级成无沙箱」。
51
+ *
52
+ * ## 临时绕过(沙箱不可用时)
53
+ *
54
+ * 若机器上装不了 bubblewrap / codex,或 macOS 需要临时跑通,只能显式选择
55
+ * **daemon scope** 或 **fullaccess / bypass+owner**——两者都**没有沙箱**。
56
+ * 这是有意的:绕过必须显式,不能让调用方吞掉错误后自己 spawn。
57
+ * 走 daemon scope 时调用方必须向用户明示「本次执行没有沙箱」。
58
+ */
27
59
  export function buildTriggerScriptLaunch(input) {
28
60
  const authorization = input.executionAuthorization;
29
61
  if (!authorization?.allowed || !authorization.scope)
30
62
  throw new Error('Trigger execution authorization is missing');
31
63
  const runtime = resolveRuntime(input.trigger.execution.script?.runtime || '');
32
64
  if (authorization.scope === 'daemon') {
65
+ // daemon scope:无沙箱,全平台可用。注意 env 是原样继承,KEY/TOKEN 不清洗。
33
66
  const launch = buildCliLaunchCommand(runtime, [input.scriptPath, ...input.scriptArgs]);
34
- return { ...launch, cwd: input.projectPath, env: process.env };
67
+ return { ...launch, cwd: input.projectPath, env: process.env, sandboxAbsent: 'daemon-scope' };
35
68
  }
36
69
  if (!authorization.permissionMode || authorization.permissionMode === 'fullaccess') {
37
70
  throw new Error('scoped Trigger execution requires an effective non-fullaccess permission mode');
@@ -39,10 +72,15 @@ export function buildTriggerScriptLaunch(input) {
39
72
  const sandboxDecision = resolvePhaseOneExecutionSandbox(authorization.permissionMode, authorization.role);
40
73
  const readonly = sandboxDecision.permissionMode === 'readonly';
41
74
  if (process.platform !== 'linux' && process.platform !== 'win32') {
42
- throw new Error('scoped Trigger script isolation is unavailable on this host');
75
+ throw new Error(`scoped Trigger script isolation is unavailable on platform "${process.platform}" `
76
+ + '(supported: linux via bubblewrap, win32 via the Codex Windows sandbox). '
77
+ + 'On macOS there is no backend yet: either run this work on Linux/Windows, '
78
+ + 'or execute the script through daemon scope / fullaccess and tell the user that no sandbox is applied.');
43
79
  }
44
80
  if (process.platform === 'win32' && path.extname(runtime).toLowerCase() !== '.exe') {
45
- throw new Error('scoped Windows Trigger scripts require a native executable runtime');
81
+ throw new Error(`scoped Windows Trigger scripts require a native executable runtime (got "${runtime}"). `
82
+ + 'Use runtime "node" (resolves to node.exe) or another .exe; '
83
+ + '.mjs/.js script files are fine — only the runtime must be a native executable.');
46
84
  }
47
85
  const projectPath = resolveRealDirectory(input.projectPath, 'Trigger project path');
48
86
  const triggerDir = resolveRealDirectory(input.triggerDir, 'Trigger directory');
@@ -70,7 +108,10 @@ export function buildTriggerScriptLaunch(input) {
70
108
  }
71
109
  const bubblewrap = process.platform === 'linux' ? resolveBubblewrapPath() : undefined;
72
110
  if (process.platform === 'linux' && !bubblewrap) {
73
- throw new Error('bubblewrap is required for scoped Trigger script isolation');
111
+ throw new Error('bubblewrap is required for scoped Trigger script isolation. '
112
+ + 'Install it via your package manager (Debian/Ubuntu: `apt install bubblewrap`; '
113
+ + 'Fedora: `dnf install bubblewrap`; Arch: `pacman -S bubblewrap`), '
114
+ + 'or execute the script through daemon scope / fullaccess and tell the user that no sandbox is applied.');
74
115
  }
75
116
  const runtimeRoot = ensureSessionRuntimeDir(`trigger:${input.trigger.agentAid}:${input.trigger.id}`);
76
117
  if (!runtimeRoot)
@@ -94,8 +135,7 @@ export function buildTriggerScriptLaunch(input) {
94
135
  const snapshotDir = path.join(runDir, 'script');
95
136
  fs.mkdirSync(workDir, { mode: 0o700 });
96
137
  fs.mkdirSync(snapshotDir, { mode: 0o700 });
97
- const scriptPath = path.join(snapshotDir, path.basename(input.scriptPath));
98
- fs.writeFileSync(scriptPath, scriptBytes, { flag: 'wx', mode: 0o400 });
138
+ const scriptPath = stageScriptSnapshot(input.scriptPath, triggerDir, scriptBytes, snapshotDir);
99
139
  preserveNodeModuleType(runtime, input.scriptPath, snapshotDir);
100
140
  const env = buildSandboxEnvironment(workDir);
101
141
  const scriptArgs = [scriptPath, ...input.scriptArgs];
@@ -195,20 +235,50 @@ function resolveRuntime(value) {
195
235
  throw new Error(`script runtime is unavailable: ${runtime}`);
196
236
  return fs.realpathSync.native(executable);
197
237
  }
238
+ /**
239
+ * 解析 Windows scoped 沙箱宿主。
240
+ *
241
+ * **这里就是「EvolCore 依赖 Codex」的全部来源。** Codex 只作为 Windows 沙箱的
242
+ * 执行宿主(`codex.exe sandbox` + `codex-windows-sandbox-setup.exe` 施加的 ACL),
243
+ * 与 baseagent 无关,也不涉及模型调用。替代方案(landstrip / srt)尚未接入。
244
+ *
245
+ * 失败分三类,各自的修复动作不同,报错里会明确区分:
246
+ * 1. 没装 Codex → 全局安装
247
+ * 2. 装了但缺平台包 → 重装(npm 的 optional 依赖常因超时被静默丢弃)
248
+ * 3. 装了但沙箱未 provisioning → 在宿主终端跑一次 elevated setup
249
+ *
250
+ * 三类都失败时,唯一出路是改用 daemon scope / fullaccess(无沙箱)。
251
+ */
198
252
  function resolveWindowsBackend() {
253
+ const noSandboxHint = 'Alternatively, execute the script through daemon scope or fullaccess '
254
+ + '(no sandbox is applied) and tell the user explicitly.';
199
255
  const codexPath = resolveCodexCliPath();
200
- if (!codexPath)
201
- throw new Error('Codex CLI is required for scoped Windows Trigger script isolation');
256
+ if (!codexPath) {
257
+ throw new Error('Codex CLI is required for scoped Windows Trigger script isolation, but `codex` was not found on PATH. '
258
+ + 'EvolCore only uses it as the Windows sandbox host — install it with `npm install -g @openai/codex`, '
259
+ + 'then re-run. ' + noSandboxHint);
260
+ }
202
261
  let command = codexPath;
203
262
  if (path.extname(command).toLowerCase() !== '.exe') {
204
263
  const packageFile = path.join(path.dirname(codexPath), 'node_modules', '@openai', 'codex', 'package.json');
205
264
  const platformName = `@openai/codex-win32-${process.arch}`;
206
- const platformFile = createRequire(packageFile).resolve(`${platformName}/package.json`);
265
+ let platformFile;
266
+ try {
267
+ platformFile = createRequire(packageFile).resolve(`${platformName}/package.json`);
268
+ }
269
+ catch (error) {
270
+ throw new Error(`Codex is installed but its Windows native package "${platformName}" is missing `
271
+ + `(${error?.message || String(error)}). npm silently drops optional packages on download timeout; `
272
+ + 'reinstall Codex with a longer timeout, e.g. `npm install -g @openai/codex --fetch-timeout=600000`. '
273
+ + noSandboxHint, { cause: error });
274
+ }
207
275
  const target = process.arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';
208
276
  command = path.join(path.dirname(platformFile), 'vendor', target, 'bin', 'codex.exe');
209
277
  }
210
- if (!fs.statSync(command).isFile())
211
- throw new Error('native Codex executable is unavailable');
278
+ if (!fs.statSync(command).isFile()) {
279
+ throw new Error(`Codex is installed but the native sandbox executable is missing at "${command}". `
280
+ + 'Reinstall Codex (`npm install -g @openai/codex`). ' + noSandboxHint);
281
+ }
212
282
  const home = resolveRealDirectory(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), 'Codex control home');
213
283
  let marker;
214
284
  try {
@@ -227,7 +297,14 @@ function resolveWindowsBackend() {
227
297
  || users.online?.username !== 'CodexSandboxOnline' || typeof users.online?.password !== 'string' || !users.online.password
228
298
  || !fs.existsSync(path.join(home, '.sandbox-bin'))
229
299
  || !fs.readdirSync(path.join(home, '.sandbox-bin')).some(name => /^codex-command-runner-.+\.exe$/.test(name))) {
230
- throw new Error('Windows restricted-read sandbox must be prepared in the host terminal; automatic elevation and host fallback are disabled');
300
+ throw new Error(`Codex's Windows restricted-read sandbox is not provisioned in "${home}" `
301
+ + `(expected setup_marker version ${WINDOWS_SANDBOX_SETUP_VERSION}, sandbox users `
302
+ + 'CodexSandboxOffline/Online, and a codex-command-runner-*.exe in .sandbox-bin). '
303
+ + 'Automatic elevation is disabled by design — run the elevated setup once in a host terminal: '
304
+ + 'Codex Desktop → Windows Sandbox settings → setup/repair (elevated, accept one UAC prompt). '
305
+ + 'Then verify with `codex doctor --json` (backend=elevated, provisioning=complete) and '
306
+ + '`codex sandbox -- cmd /c whoami` (should show CodexSandboxOffline/Online, not your desktop user). '
307
+ + 'Troubleshooting: kits/docs/evolcore/codex-windows-sandbox.md. ' + noSandboxHint);
231
308
  }
232
309
  return { command: fs.realpathSync.native(command), home };
233
310
  }
@@ -297,6 +374,57 @@ function readScriptSnapshot(value, triggerDir) {
297
374
  fs.closeSync(descriptor);
298
375
  }
299
376
  }
377
+ /** 暂存总量上限:脚本目录可能混入大文件(数据/日志),超限拒跑沙箱而不是拖垮磁盘。 */
378
+ const SCRIPT_STAGING_TOTAL_LIMIT = 32 * 1024 * 1024;
379
+ /** 暂存文件数上限:node_modules/.git 已跳过,剩余仍超此数说明目录不是脚手架。 */
380
+ const SCRIPT_STAGING_FILE_COUNT = 2_000;
381
+ /**
382
+ * 暂存脚本快照:入口脚本(原 `readScriptSnapshot` 字节)+ 其所在目录的兄弟文件树。
383
+ *
384
+ * 原实现只写入口单文件,相对导入(`./lib/*.mjs`)在暂存目录里不存在——沙箱一生效
385
+ * 就 `ERR_MODULE_NOT_FOUND`,沙箱降级(fallback 跑原路径)时反而能跑,症状时隐时现。
386
+ * 现在按原目录结构整树暂存(跳过 node_modules/.git 与顶层 package.json——后者由
387
+ * `preserveNodeModuleType` 统一合成,避免 `wx` 冲突)。每个文件走与入口相同的
388
+ * lstat/fd 校验(防 TOCTOU/软链),越界文件直接抛错走沙箱不可用降级。
389
+ */
390
+ function stageScriptSnapshot(scriptSource, triggerDir, scriptBytes, snapshotDir) {
391
+ const scriptName = path.basename(scriptSource);
392
+ const scriptPath = path.join(snapshotDir, scriptName);
393
+ fs.writeFileSync(scriptPath, scriptBytes, { flag: 'wx', mode: 0o400 });
394
+ const scriptDir = path.dirname(path.resolve(scriptSource));
395
+ assertRealDirectory(scriptDir, 'Trigger script directory');
396
+ let total = scriptBytes.length;
397
+ let count = 1;
398
+ const stage = (dir, rel) => {
399
+ const entries = fs.readdirSync(dir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
400
+ for (const entry of entries) {
401
+ const name = entry.name;
402
+ const relPath = rel ? path.join(rel, name) : name;
403
+ if (!rel && (name === scriptName || name === 'package.json' || name === 'node_modules' || name === '.git'))
404
+ continue;
405
+ if (entry.isSymbolicLink())
406
+ throw new Error(`script snapshot must not contain symlinks: ${relPath}`);
407
+ if (entry.isDirectory()) {
408
+ fs.mkdirSync(path.join(snapshotDir, relPath), { mode: 0o700 });
409
+ stage(path.join(dir, name), relPath);
410
+ }
411
+ else if (entry.isFile()) {
412
+ if (++count > SCRIPT_STAGING_FILE_COUNT)
413
+ throw new Error(`script snapshot exceeds ${SCRIPT_STAGING_FILE_COUNT} files`);
414
+ const bytes = readScriptSnapshot(path.join(dir, name), triggerDir);
415
+ total += bytes.length;
416
+ if (total > SCRIPT_STAGING_TOTAL_LIMIT)
417
+ throw new Error('script snapshot exceeds 32 MiB total');
418
+ fs.writeFileSync(path.join(snapshotDir, relPath), bytes, { flag: 'wx', mode: 0o400 });
419
+ }
420
+ else {
421
+ throw new Error(`script snapshot has unsupported entry: ${relPath}`);
422
+ }
423
+ }
424
+ };
425
+ stage(scriptDir, '');
426
+ return scriptPath;
427
+ }
300
428
  function preserveNodeModuleType(runtime, scriptPath, snapshotDir) {
301
429
  if (!/^node(?:\.exe)?$/i.test(path.basename(runtime)) || path.extname(scriptPath) !== '.js')
302
430
  return;
@@ -340,6 +468,20 @@ function getScriptEnvironmentExcludes() {
340
468
  function filesystemEntry(value, access) {
341
469
  return { path: { type: 'path', path: path.resolve(value) }, access };
342
470
  }
471
+ /**
472
+ * 证明 Windows 沙箱的文件策略确实被执行。
473
+ *
474
+ * 这里验证的是「**显式 deny 生效**」,不是「默认拒绝读」——Codex 的 Windows
475
+ * 沙箱与 Linux 的 `--ro-bind / /` 同为「默认放行 + 显式 deny」语义:策略里
476
+ * `{ kind: 'root' }` 给 read,其余 deny 条目在其上做减法。因此拿一个不在
477
+ * deny 列表里的路径去期望 EACCES 永远不成立,只会把每次脚本执行都判成失败。
478
+ *
479
+ * 三步:
480
+ * 1. 读 canary 且策略里显式给 `read` → 必须成功(证明「能读」,策略未被整体拒绝)
481
+ * 2. 同一个 canary 在策略里显式给 `deny` → 必须 EACCES/EPERM
482
+ * (证明 deny 真的被沙箱执行;这一步失败说明沙箱没起效,必须拒跑)
483
+ * 3. 在 workDir 写文件 → 必须成功(证明 scoped 路径没有把整个文件系统锁死)
484
+ */
343
485
  async function verifyWindowsReadIsolation(launch, sandboxArgs, runDir, workDir, signal) {
344
486
  signal?.throwIfAborted();
345
487
  const canary = path.join(runDir, 'read-isolation-canary');
@@ -350,26 +492,30 @@ async function verifyWindowsReadIsolation(launch, sandboxArgs, runDir, workDir,
350
492
  'if (fs.readFileSync(process.argv[1], "utf8") !== "evolcore-read-isolation-canary") process.exit(91);',
351
493
  'process.stdout.write("evolcore-trigger-sandbox-ready");',
352
494
  ].join('\n');
353
- const probe = [
495
+ // 策略里显式 deny 的同一个文件必须读不到;能读到就说明沙箱没执行策略。
496
+ const denyProbe = [
354
497
  'const fs = require("node:fs");',
355
498
  'let denied = false;',
356
499
  'try { fs.readFileSync(process.argv[1]); } catch (error) {',
357
- 'if (error.code === "EACCES" || error.code === "EPERM") denied = true; else throw error;',
500
+ 'if (error.code === "EACCES" || error.code === "EPERM" || error.code === "ENOENT") denied = true; else throw error;',
358
501
  '}',
359
- 'if (!denied) { process.stderr.write("read isolation is not enforced"); process.exit(90); }',
502
+ 'if (!denied) { process.stderr.write("deny enforcement is not applied: denied path was readable"); process.exit(90); }',
360
503
  'fs.writeFileSync(process.argv[2], "allowed");',
361
504
  'process.stdout.write("evolcore-trigger-sandbox-ready");',
362
505
  ].join('\n');
363
- try {
364
- const readArgs = [...sandboxArgs];
365
- const stateIndex = readArgs.indexOf('--sandbox-state-json') + 1;
366
- const readState = JSON.parse(readArgs[stateIndex]);
367
- readState.permissionProfile.file_system.entries.push(filesystemEntry(canary, 'read'));
368
- readArgs[stateIndex] = JSON.stringify(readState);
369
- if (readArgs[stateIndex].length > 20_000)
506
+ const withExtraEntry = (extra) => {
507
+ const args = [...sandboxArgs];
508
+ const stateIndex = args.indexOf('--sandbox-state-json') + 1;
509
+ const state = JSON.parse(args[stateIndex]);
510
+ state.permissionProfile.file_system.entries.push(extra);
511
+ args[stateIndex] = JSON.stringify(state);
512
+ if (args[stateIndex].length > 20_000)
370
513
  throw new Error('filesystem probe policy exceeds the command-line budget');
371
- await runWindowsIsolationProbe(launch, readArgs, readProbe, [canary], signal);
372
- await runWindowsIsolationProbe(launch, sandboxArgs, probe, [canary, writableProbe], signal);
514
+ return args;
515
+ };
516
+ try {
517
+ await runWindowsIsolationProbe(launch, withExtraEntry(filesystemEntry(canary, 'read')), readProbe, [canary], signal);
518
+ await runWindowsIsolationProbe(launch, withExtraEntry(filesystemEntry(canary, 'deny')), denyProbe, [canary, writableProbe], signal);
373
519
  }
374
520
  catch (error) {
375
521
  throw new Error(`Windows sandbox cannot prove scoped read isolation; Trigger script execution is refused: ${error?.message || String(error)}`, { cause: error });
@@ -5,7 +5,7 @@ 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 } from './windows-shell-trust.js';
8
+ import { resolveTrustedWindowsCmdPath, resolveTrustedWindowsCmdPathAsync } from './windows-shell-trust.js';
9
9
  const execFileAsync = promisify(execFile);
10
10
  const CLI_PROBE_FAILURE_BACKOFF_MS = 5_000;
11
11
  export const CODEX_CLI_PROBE_TIMEOUT_MS = 9_000;
@@ -222,7 +222,7 @@ function codexProbeExecutable(executable) {
222
222
  catch { /* Incomplete or non-npm installations retain their configured entrypoint. */ }
223
223
  return executable;
224
224
  }
225
- function prepareCliProbe(command, args, options = {}) {
225
+ function resolveCliProbe(command, args, options) {
226
226
  const executable = options.executable ?? resolveProbePath(command);
227
227
  if (!executable)
228
228
  throw Object.assign(new Error(`${command} CLI not found`), { code: 'ENOENT' });
@@ -230,14 +230,17 @@ function prepareCliProbe(command, args, options = {}) {
230
230
  && (args.length === 1 && args[0] === '--version'
231
231
  || args.length === 2 && args[0] === 'app-server' && args[1] === '--help')
232
232
  ? codexProbeExecutable(executable) : executable;
233
- const launchCommand = buildCliLaunchCommand(probeExecutable, args);
233
+ return { executable, probeExecutable };
234
+ }
235
+ function prepareCliProbe(command, args, options = {}, resolved = resolveCliProbe(command, args, options), resolveWindowsCmd) {
236
+ const launchCommand = buildCliLaunchCommand(resolved.probeExecutable, args, { resolveWindowsCmd });
234
237
  const launch = launchCommand;
235
- const identity = `${probeInstallationIdentity(command, executable)}|${cliFileIdentity(launch.launcherPath)}`;
238
+ const identity = `${probeInstallationIdentity(command, resolved.executable)}|${cliFileIdentity(launch.launcherPath)}`;
236
239
  const key = JSON.stringify([command, args]);
237
240
  let entry = cliProbeCache.get(key);
238
241
  if (!entry || entry.identity !== identity || (entry.retryAt !== undefined && Date.now() >= entry.retryAt)
239
242
  || (entry.output !== undefined && options.validateOutput && !options.validateOutput(entry.output))) {
240
- entry = { identity };
243
+ entry = { identity, launcherPath: launch.launcherPath };
241
244
  cliProbeCache.set(key, entry);
242
245
  }
243
246
  return {
@@ -290,7 +293,13 @@ export function probeCliSync(command, args, options = {}) {
290
293
  throw new Error('CLI probe exhausted');
291
294
  }
292
295
  export async function probeCli(command, args, options = {}) {
293
- const request = prepareCliProbe(command, args, options);
296
+ const resolved = resolveCliProbe(command, args, options);
297
+ let resolveWindowsCmd;
298
+ if (isWindows && /\.(?:cmd|bat)$/i.test(resolved.probeExecutable)) {
299
+ const trustedCmd = await resolveTrustedWindowsCmdPathAsync();
300
+ resolveWindowsCmd = () => trustedCmd;
301
+ }
302
+ const request = prepareCliProbe(command, args, options, resolved, resolveWindowsCmd);
294
303
  if (request.entry.output !== undefined)
295
304
  return request.entry.output;
296
305
  if (request.entry.error !== undefined)
@@ -352,9 +361,14 @@ export async function probeCli(command, args, options = {}) {
352
361
  /** Non-blocking version lookup used by status menus. */
353
362
  export function cachedCliVersion(command) {
354
363
  try {
355
- const { entry } = prepareCliProbe(command, ['--version']);
356
- if (entry.output !== undefined)
364
+ const executable = resolveProbePath(command);
365
+ if (!executable)
366
+ return null;
367
+ const entry = cliProbeCache.get(JSON.stringify([command, ['--version']]));
368
+ if (entry?.output !== undefined
369
+ && entry.identity === `${probeInstallationIdentity(command, executable)}|${cliFileIdentity(entry.launcherPath)}`) {
357
370
  return entry.output.match(/\b\d+\.\d+\.\d+(?:[-+][\w.-]+)?/)?.[0] ?? null;
371
+ }
358
372
  void probeCli(command, ['--version']).catch(() => { });
359
373
  }
360
374
  catch { /* Missing CLI. */ }
@@ -909,11 +923,11 @@ export function killProcessTree(pid, force = false) {
909
923
  export async function waitForProcessExit(pid, timeoutMs = 10_000, intervalMs = 250) {
910
924
  const deadline = Date.now() + timeoutMs;
911
925
  while (Date.now() < deadline) {
912
- if (!isProcessRunning(pid))
926
+ if (!await isProcessRunningAsync(pid))
913
927
  return true;
914
928
  await new Promise(resolve => setTimeout(resolve, intervalMs));
915
929
  }
916
- return !isProcessRunning(pid);
930
+ return !await isProcessRunningAsync(pid);
917
931
  }
918
932
  /**
919
933
  * Cross-platform process search by command line pattern.
@@ -189,39 +189,81 @@ export function readBuildIdentity(distDir, version) {
189
189
  ...(version ? { version } : {}),
190
190
  };
191
191
  }
192
- export function reportEvolcoreStartup(entryUrl, report) {
193
- const packageRoot = getPackageRoot();
194
- const runtimeEntry = fileURLToPath(entryUrl);
195
- const diskDistDir = path.join(packageRoot, 'dist');
196
- const runtimeIsDist = path.resolve(path.dirname(runtimeEntry)) === path.resolve(diskDistDir);
197
- const runtimeBuildIdentity = readBuildIdentity(runtimeIsDist ? path.dirname(runtimeEntry) : diskDistDir, readInstalledEvolcoreVersion());
198
- const diskDistId = runtimeBuildIdentity.id;
199
- if (!runtimeIsDist)
200
- runtimeBuildIdentity.id = null;
201
- const isLinked = fs.existsSync(path.join(packageRoot, '.git'));
202
- const directoryType = runtimeIsDist ? (isLinked ? '开发仓/dist' : '安装路径/dist') : '源码(tsx)';
203
- const scanDir = runtimeIsDist ? path.join(packageRoot, 'dist') : path.join(packageRoot, 'src');
192
+ /** Keep the same content hash as computeBuildId without blocking the event loop. */
193
+ async function readBuildTreeAsync(root, hashFiles = true) {
204
194
  let latestMtime = 0;
205
- const scanRecursive = (directory) => {
206
- try {
207
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
208
- if (entry.name === 'node_modules')
195
+ try {
196
+ const files = [];
197
+ const collect = async (directory) => {
198
+ const entries = await fs.promises.readdir(directory, { withFileTypes: true });
199
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
200
+ if (!hashFiles && entry.name === 'node_modules')
209
201
  continue;
210
202
  const full = path.join(directory, entry.name);
211
- if (entry.isDirectory()) {
212
- scanRecursive(full);
213
- continue;
214
- }
215
- if (entry.name.endsWith('.js') || entry.name.endsWith('.ts')) {
216
- const modifiedAt = fs.statSync(full).mtimeMs;
217
- if (modifiedAt > latestMtime)
218
- latestMtime = modifiedAt;
203
+ if (entry.isDirectory())
204
+ await collect(full);
205
+ else if (entry.isFile())
206
+ files.push(full);
207
+ }
208
+ };
209
+ await collect(root);
210
+ const hash = crypto.createHash('sha256');
211
+ for (let offset = 0; offset < files.length; offset += 8) {
212
+ const batch = await Promise.all(files.slice(offset, offset + 8).map(async (file) => {
213
+ const [content, stat] = await Promise.all([
214
+ hashFiles ? fs.promises.readFile(file) : undefined,
215
+ /\.(js|ts)$/.test(file) ? fs.promises.stat(file) : undefined,
216
+ ]);
217
+ return { file, content, stat };
218
+ }));
219
+ for (const { file, content, stat } of batch) {
220
+ if (stat)
221
+ latestMtime = Math.max(latestMtime, stat.mtimeMs);
222
+ if (content) {
223
+ hash.update(path.relative(root, file).replaceAll(path.sep, '/'));
224
+ hash.update('\0');
225
+ hash.update(content);
226
+ hash.update('\0');
219
227
  }
220
228
  }
221
229
  }
222
- catch { }
230
+ return { id: hashFiles ? `sha256:${hash.digest('hex').slice(0, 24)}` : null, latestMtime };
231
+ }
232
+ catch {
233
+ return { id: null, latestMtime };
234
+ }
235
+ }
236
+ /** Cheap initial status; the full build identity is published after hashing. */
237
+ export function createEvolcoreStartupDiagnostics(entryUrl) {
238
+ const packageRoot = getPackageRoot();
239
+ const runtimeEntry = fileURLToPath(entryUrl);
240
+ const diskDistDir = path.join(packageRoot, 'dist');
241
+ const runtimeIsDist = path.resolve(path.dirname(runtimeEntry)) === path.resolve(diskDistDir);
242
+ return {
243
+ state: 'pending', runtimeIsDist, diskDistDir, diskDistId: null,
244
+ runtimeBuildIdentity: { id: null, entry: path.join(diskDistDir, 'index.js'), version: readInstalledEvolcoreVersion() },
245
+ };
246
+ }
247
+ export async function reportEvolcoreStartup(entryUrl, report, diagnostics = createEvolcoreStartupDiagnostics(entryUrl)) {
248
+ const packageRoot = getPackageRoot();
249
+ const { runtimeIsDist, diskDistDir } = diagnostics;
250
+ const [dist, source] = await Promise.all([
251
+ readBuildTreeAsync(diskDistDir),
252
+ runtimeIsDist ? undefined : readBuildTreeAsync(path.join(packageRoot, 'src'), false),
253
+ ]);
254
+ const diskDistId = dist.id;
255
+ const runtimeBuildIdentity = {
256
+ id: runtimeIsDist ? diskDistId : null,
257
+ entry: path.join(diskDistDir, 'index.js'),
258
+ version: readInstalledEvolcoreVersion(),
223
259
  };
224
- scanRecursive(scanDir);
260
+ // Publish both IDs together. Pending/failed reads must never claim a match.
261
+ Object.assign(diagnostics, {
262
+ state: diskDistId === null ? 'unavailable' : 'ready', runtimeBuildIdentity, diskDistId,
263
+ });
264
+ const isLinked = fs.existsSync(path.join(packageRoot, '.git'));
265
+ const directoryType = runtimeIsDist ? (isLinked ? '开发仓/dist' : '安装路径/dist') : '源码(tsx)';
266
+ const latestMtime = source?.latestMtime ?? dist.latestMtime;
225
267
  let version = '?';
226
268
  try {
227
269
  version = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version;
@@ -240,5 +282,5 @@ export function reportEvolcoreStartup(entryUrl, report) {
240
282
  console.error(`[EvolCore] 运行 build ID: ${runtimeIsDist ? (runtimeBuildIdentity.id ?? '?') : 'source'}`);
241
283
  console.error(`[EvolCore] 磁盘 dist build ID: ${diskBuildId ?? '?'}`);
242
284
  report(`[Build] runtimeMode=${runtimeIsDist ? 'dist' : 'source'} runtimeBuildId=${runtimeBuildIdentity.id ?? 'source'} diskDistBuildId=${diskBuildId ?? 'unknown'} match=${runtimeIsDist && runtimeBuildIdentity.id !== null && runtimeBuildIdentity.id === diskBuildId}`);
243
- return { runtimeIsDist, runtimeBuildIdentity, diskDistDir, diskDistId };
285
+ return diagnostics;
244
286
  }
@@ -33,14 +33,14 @@ function safeParseJson(filePath) {
33
33
  return null;
34
34
  }
35
35
  }
36
- function lazySnapshot() {
37
- let cached = null;
36
+ function lazySnapshot(initial) {
37
+ let cached = initial ?? null;
38
38
  return {
39
39
  get() {
40
40
  cached ??= getProcessSnapshot();
41
41
  return cached;
42
42
  },
43
- taken: () => cached !== null,
43
+ provided: () => initial !== undefined,
44
44
  };
45
45
  }
46
46
  /**
@@ -56,6 +56,12 @@ function isAlive(pid, recordedStartedAt, snapshot) {
56
56
  const actual = getProcessStartTime(pid);
57
57
  return actual === null ? true : startTimeMatches(recordedStartedAt, actual);
58
58
  }
59
+ // A caller-scoped snapshot already covers this phase; avoid one tasklist per record.
60
+ if (snapshot.provided()) {
61
+ const verdict = snapshotProcessState(snapshot.get(), pid, recordedStartedAt);
62
+ if (verdict !== 'unknown')
63
+ return verdict === 'alive';
64
+ }
59
65
  // 廉价前置探测:不存在就直接判定为死,省掉整张进程表。
60
66
  if (!isProcessRunning(pid))
61
67
  return false;
@@ -115,7 +121,7 @@ export function removeMain(pid) {
115
121
  * @returns 当前进程是否赢家。false 表示应该让出(删自己的 record + exit)。
116
122
  */
117
123
  export function isMainWinner() {
118
- const status = scanInstances();
124
+ const status = scanInstances({ kind: 'main', includeAidActivity: false });
119
125
  const aliveMains = status.mains.filter(m => m.alive);
120
126
  if (aliveMains.length <= 1)
121
127
  return { winner: true };
@@ -173,7 +179,7 @@ export function removeRestartMonitor(pid) {
173
179
  * Post-write 自检:与 isMainWinner 同语义,用于 restart-monitor。
174
180
  */
175
181
  export function isRestartMonitorWinner() {
176
- const status = scanInstances();
182
+ const status = scanInstances({ kind: 'restart-monitor', includeAidActivity: false });
177
183
  const alive = status.restartMonitors.filter(m => m.alive);
178
184
  if (alive.length <= 1)
179
185
  return { winner: true };
@@ -243,10 +249,10 @@ export function readAidLastActivity(pid) {
243
249
  *
244
250
  * 损坏的 JSON 文件直接删除。aid-*.jsonl 在 scan 时不解析,由调用方按需读取。
245
251
  */
246
- export function scanInstances() {
252
+ export function scanInstances(options = {}) {
247
253
  // 惰性快照:每条记录先做廉价的单 pid 存活探测,只有确实活着才需要整张进程表。
248
254
  // 启动路径上绝大多数时候目录里只有本进程的记录或已死记录,这样可省掉约 0.45s。
249
- const snapshot = lazySnapshot();
255
+ const snapshot = lazySnapshot(options.processSnapshot);
250
256
  const status = {
251
257
  mains: [],
252
258
  restartMonitors: [],
@@ -264,12 +270,12 @@ export function scanInstances() {
264
270
  }
265
271
  for (const file of files) {
266
272
  const filePath = path.join(dir, file);
267
- if (file.startsWith('main-') && file.endsWith('.json')) {
273
+ if (file.startsWith('main-') && file.endsWith('.json') && options.kind !== 'restart-monitor') {
268
274
  const record = safeParseJson(filePath);
269
275
  if (record && record.pid && record.startedAt) {
270
276
  const alive = isAlive(record.pid, record.startedAt, snapshot);
271
277
  status.mains.push({ record, alive });
272
- if (alive) {
278
+ if (alive && options.includeAidActivity !== false) {
273
279
  // 合并所有活 main 的 AID 活动记录(按 ts 取最新)
274
280
  for (const [aid, info] of readAidLastActivity(record.pid)) {
275
281
  const prev = status.aidLastActivity.get(aid);
@@ -286,7 +292,7 @@ export function scanInstances() {
286
292
  catch { }
287
293
  }
288
294
  }
289
- else if (file.startsWith('restart-monitor-') && file.endsWith('.json')) {
295
+ else if (file.startsWith('restart-monitor-') && file.endsWith('.json') && options.kind !== 'main') {
290
296
  const record = safeParseJson(filePath);
291
297
  if (record && record.pid && record.startedAt) {
292
298
  const alive = isAlive(record.pid, record.startedAt, snapshot);
@@ -428,7 +434,7 @@ export function isEvolCoreMainCommand(cmdline, packageRoot = getPackageRoot()) {
428
434
  *
429
435
  * 不会主动 kill——清理由调用方决定。
430
436
  */
431
- export function findOrphanProcesses(status = scanInstances()) {
437
+ export function findOrphanProcesses(status = scanInstances({ includeAidActivity: false }), snapshot = getProcessSnapshot()) {
432
438
  // 1. 已登记 PID(自己 HOME 下的 main + 自己进程)。调用方刚扫过登记簿时可直接传入,
433
439
  // Windows 上每次 scanInstances 都要为活实例跑一遍 CIM 查询。
434
440
  const known = new Set([process.pid]);
@@ -449,8 +455,8 @@ export function findOrphanProcesses(status = scanInstances()) {
449
455
  // 所以先用快照里的命令行过滤,只对真正的 EvolCore 入口做后续探测。
450
456
  // 优先用启动期已经采过的进程快照:它同样带命令行,省掉这里再拉一次全表 CIM。
451
457
  // 快照不可用(非 Windows、或 CIM 查询失败)时回退到主动枚举。
452
- const snapshot = getProcessSnapshot();
453
- const candidates = snapshot.complete
458
+ // Linux identity snapshots do not contain command lines; retain native enumeration.
459
+ const candidates = snapshot.complete && isWindows
454
460
  ? [...snapshot.commandLines.entries()]
455
461
  .filter(([pid]) => pid !== process.pid)
456
462
  .map(([pid, commandLine]) => ({ pid, commandLine }))
@@ -493,7 +493,7 @@ export async function queryPackageVersion(pkg, selection, signal, distTag = 'lat
493
493
  return isPackageVersion(version) ? { version, registry, npmConfig: selection.npmConfig } : null;
494
494
  }
495
495
  /** No registry lookup: callers must validate cache freshness before each install. */
496
- export async function installExactPackageVersion(pkg, target, registry, resolveInstalled, npmConfig) {
496
+ export async function installExactPackageVersion(pkg, target, registry, resolveInstalled, npmConfig, beforeInstall) {
497
497
  if (![MAIN_PACKAGE_NAME, WEB_PACKAGE_NAME].includes(pkg)
498
498
  || !isPackageVersion(target) || normalizeVersionRegistry(registry) !== registry) {
499
499
  return { status: 'failed', error: 'Invalid cached install target' };
@@ -510,6 +510,7 @@ export async function installExactPackageVersion(pkg, target, registry, resolveI
510
510
  result = { status: 'no-update', from };
511
511
  return;
512
512
  }
513
+ await beforeInstall?.();
513
514
  for (let attempt = 0; attempt < 2; attempt++) {
514
515
  try {
515
516
  await npmInstallGlobal(`${pkg}@${target}`, { registry, preferOffline: true, npmConfig });
@@ -273,11 +273,14 @@ export async function applyCachedPackageUpgrades(names = AUTO_UPGRADE_PACKAGES,
273
273
  }
274
274
  else {
275
275
  options.log?.(`Applying cached version information: ${name}@${entry.latestVersion}`);
276
- result = await installExactPackageVersion(name, entry.latestVersion, registry, () => resolveVersionInfoPackage(name), options.npmConfig ?? entry.npmConfig);
276
+ result = await installExactPackageVersion(name, entry.latestVersion, registry, () => resolveVersionInfoPackage(name), options.npmConfig ?? entry.npmConfig, options.beforeInstall ? () => options.beforeInstall(name) : undefined);
277
277
  }
278
278
  }
279
- catch {
280
- result = { status: 'failed', error: 'Cached upgrade could not acquire installation lock or read installed version' };
279
+ catch (error) {
280
+ const reason = error instanceof Error && error.message === 'Package backup unavailable; upgrade was not attempted'
281
+ ? error.message
282
+ : 'Cached upgrade could not acquire installation lock or read installed version';
283
+ result = { status: 'failed', error: reason };
281
284
  }
282
285
  if (result.status === 'upgraded' || result.status === 'failed') {
283
286
  await recordPackageUpgrade(name, {