evolcore 0.0.48 → 0.0.50

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 (302) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/bin/ecmsg.js +9 -4
  3. package/dist/ability/caller/authorization.js +21 -0
  4. package/dist/ability/caller/command.js +164 -0
  5. package/dist/ability/caller/contract.js +102 -0
  6. package/dist/ability/caller/daemon.js +158 -0
  7. package/dist/ability/caller/service.js +380 -0
  8. package/dist/ability/command-contract.js +5 -0
  9. package/dist/ability/daemon.js +5 -1
  10. package/dist/ability/interop-v1.js +10 -3
  11. package/dist/ability/management.js +1 -0
  12. package/dist/agent-template/jobs.js +173 -1
  13. package/dist/agent-template/runtime.js +285 -8
  14. package/dist/agent-template/service.js +1159 -40
  15. package/dist/agent-template/types.js +2 -1
  16. package/dist/agents/baseagent-availability.js +27 -3
  17. package/dist/agents/baseagent-capability-adapter.js +102 -0
  18. package/dist/agents/baseagent-plugin-descriptor.js +274 -0
  19. package/dist/agents/baseagent-plugin-loader.js +145 -0
  20. package/dist/agents/baseagent.js +68 -2
  21. package/dist/agents/claude-gateway/agent-registration.js +389 -0
  22. package/dist/agents/claude-gateway/binding.js +96 -0
  23. package/dist/agents/claude-gateway/inbox.js +138 -0
  24. package/dist/agents/claude-gateway/index.js +125 -0
  25. package/dist/agents/claude-gateway/listing.js +330 -0
  26. package/dist/agents/claude-gateway/router.js +328 -0
  27. package/dist/agents/claude-gateway/sessions.js +128 -0
  28. package/dist/agents/claude-gateway/terminal.js +250 -0
  29. package/dist/agents/claude-gateway/transcript.js +272 -0
  30. package/dist/agents/claude-gateway/types.js +14 -0
  31. package/dist/agents/claude-runner.js +6 -10
  32. package/dist/agents/codex-runner.js +9 -2
  33. package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
  34. package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
  35. package/dist/agents/gemini/index.js +51 -0
  36. package/dist/aun/aid/control-aid.js +52 -32
  37. package/dist/aun/group/invite-service.js +6 -36
  38. package/dist/aun/group/operations.js +6 -0
  39. package/dist/aun/msg/mention-schema.js +1 -1
  40. package/dist/aun/msg/p2p.js +31 -2
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +1175 -457
  44. package/dist/cli/ability-command.js +42 -0
  45. package/dist/cli/agent-command.js +20 -1
  46. package/dist/cli/agent-create.js +78 -18
  47. package/dist/cli/agent-template.js +5 -3
  48. package/dist/cli/agent.js +91 -0
  49. package/dist/cli/aun-commands.js +92 -34
  50. package/dist/cli/bench.js +5 -2
  51. package/dist/cli/config.js +22 -6
  52. package/dist/cli/daemon-commands.js +245 -101
  53. package/dist/cli/directory.js +6 -1
  54. package/dist/cli/ecmsg-gateway.js +11 -9
  55. package/dist/cli/index.js +30 -5
  56. package/dist/cli/init.js +39 -63
  57. package/dist/cli/managed-command-guard.js +3 -0
  58. package/dist/cli/menu-client.js +32 -7
  59. package/dist/cli/model.js +20 -5
  60. package/dist/cli/pay-command.js +30 -0
  61. package/dist/cli/provider-command.js +6 -2
  62. package/dist/cli/quota.js +89 -0
  63. package/dist/cli/restart-monitor.js +2 -2
  64. package/dist/cli/role.js +1 -0
  65. package/dist/cli/services-command.js +12 -9
  66. package/dist/cli/team-workspace-command.js +56 -2
  67. package/dist/cli/thread-command.js +78 -12
  68. package/dist/config/access-policy.js +16 -3
  69. package/dist/config/config-field-policy.js +88 -9
  70. package/dist/config/config-manager.js +97 -47
  71. package/dist/config/config-operation-service.js +22 -1
  72. package/dist/config/gateway-config.js +9 -8
  73. package/dist/config/owner-config.js +0 -16
  74. package/dist/config/peer-role-resolver.js +1 -7
  75. package/dist/config/providers-config.js +107 -20
  76. package/dist/config/providers-management.js +45 -21
  77. package/dist/config/resolved-config-op.js +4 -44
  78. package/dist/config/schema-migration.js +78 -5
  79. package/dist/config/schema-registry.js +52 -7
  80. package/dist/config-store.js +1309 -17
  81. package/dist/core/agent-application-service.js +220 -1
  82. package/dist/core/agent-ipc-registration.js +19 -2
  83. package/dist/core/agent-reload-coordinator.js +5 -0
  84. package/dist/core/agent-runtime.js +198 -54
  85. package/dist/core/auth/agent-delegation.js +14 -0
  86. package/dist/core/auth/delegation-authorization.js +33 -26
  87. package/dist/core/auth/operation-authorizer.js +16 -1
  88. package/dist/core/auth/operation-catalog.js +59 -7
  89. package/dist/core/baseagent-loader.js +30 -3
  90. package/dist/core/capability/capability-manager.js +16 -7
  91. package/dist/core/channel-runtime.js +4 -2
  92. package/dist/core/command/agent-control.js +20 -2
  93. package/dist/core/command/agent-template-menu.js +4 -3
  94. package/dist/core/command/cli-intent-parser.js +28 -0
  95. package/dist/core/command/command-handler.js +45 -2
  96. package/dist/core/command/menu-catalog.js +20 -4
  97. package/dist/core/command/menu-file-path.js +70 -0
  98. package/dist/core/command/menu-handler.js +97 -73
  99. package/dist/core/command/menu-protocol.js +29 -0
  100. package/dist/core/command/menu-query-batch.js +2 -2
  101. package/dist/core/command/private-mention-menu.js +71 -0
  102. package/dist/core/command/remote-shell.js +565 -0
  103. package/dist/core/command/slash-handler.js +17 -26
  104. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  105. package/dist/core/command/topic-slash.js +7 -1
  106. package/dist/core/daemon-bootstrap.js +0 -4
  107. package/dist/core/daemon-control.js +58 -1
  108. package/dist/core/daemon-lifecycle.js +29 -7
  109. package/dist/core/evolagent-registry.js +18 -9
  110. package/dist/core/handoff/runtime.js +1 -1
  111. package/dist/core/host-snapshot.js +8 -3
  112. package/dist/core/initialization/service.js +3 -0
  113. package/dist/core/interaction-router.js +130 -0
  114. package/dist/core/ipc-registration.js +5 -0
  115. package/dist/core/memory/consolidation-context.js +2 -1
  116. package/dist/core/memory/consolidation.js +35 -64
  117. package/dist/core/message/aun-ipc-sender.js +213 -74
  118. package/dist/core/message/aun-request-registry.js +31 -0
  119. package/dist/core/message/contact-admission.js +91 -6
  120. package/dist/core/message/contact-pending-inbound.js +113 -0
  121. package/dist/core/message/contact-thread-approval.js +212 -0
  122. package/dist/core/message/im-renderer.js +40 -1
  123. package/dist/core/message/message-admission.js +5 -39
  124. package/dist/core/message/message-bridge.js +197 -45
  125. package/dist/core/message/message-log.js +32 -0
  126. package/dist/core/message/message-queue.js +102 -18
  127. package/dist/core/message/peer-mode.js +15 -4
  128. package/dist/core/message/response-engine.js +174 -26
  129. package/dist/core/message/send-options.js +37 -3
  130. package/dist/core/message/send-routing.js +11 -7
  131. package/dist/core/model/config-scope.js +6 -14
  132. package/dist/core/model/model-catalog.js +5 -5
  133. package/dist/core/model/model-diagnostics.js +19 -0
  134. package/dist/core/model/model-fallback.js +13 -2
  135. package/dist/core/ownership/owner-resolver.js +12 -86
  136. package/dist/core/pack-auth.js +7 -0
  137. package/dist/core/pack-install.js +1 -1
  138. package/dist/core/permission/ec-command-parser.js +288 -77
  139. package/dist/core/permission/protected-paths.js +64 -9
  140. package/dist/core/permission/services-path-acl.js +458 -0
  141. package/dist/core/permission/tool-policy.js +26 -10
  142. package/dist/core/relation/peer-identity.js +13 -0
  143. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  144. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  145. package/dist/core/session/session-manager.js +47 -10
  146. package/dist/core/session/session-mapper.js +16 -0
  147. package/dist/core/skill/index-generator.js +2 -3
  148. package/dist/core/skill/switch-resolver.js +3 -0
  149. package/dist/core/task/task-recovery-service.js +1 -0
  150. package/dist/core/thread/command-parser.js +4 -1
  151. package/dist/core/thread/ipc-operation.js +4 -2
  152. package/dist/core/thread/thread-operation.js +25 -10
  153. package/dist/core/thread/thread-service.js +294 -55
  154. package/dist/core/thread/topic-id.js +67 -2
  155. package/dist/core/thread/types.js +15 -1
  156. package/dist/directory/owner-directory-admission.js +11 -8
  157. package/dist/directory/owner-directory-cache.js +19 -0
  158. package/dist/directory/owner-directory-markdown.js +1 -1
  159. package/dist/directory/owner-directory-policy.js +5 -30
  160. package/dist/directory/owner-directory-request-operation.js +5 -2
  161. package/dist/eck/kit-renderer.js +3 -2
  162. package/dist/eck/message-renderer.js +28 -5
  163. package/dist/ecweb/basic-settings-service.js +5 -9
  164. package/dist/ecweb/providers-service.js +4 -2
  165. package/dist/ecweb/runtime/supervisor.js +36 -8
  166. package/dist/event-center/center-config.js +9 -5
  167. package/dist/event-center/dispatcher.js +10 -1
  168. package/dist/event-center/ipc-operation.js +19 -0
  169. package/dist/event-center/registry.js +20 -5
  170. package/dist/event-center/runtime.js +10 -7
  171. package/dist/index.js +120 -41
  172. package/dist/ipc.js +83 -3
  173. package/dist/outputs/authorization.js +16 -0
  174. package/dist/outputs/cards.js +336 -0
  175. package/dist/outputs/events.js +3 -2
  176. package/dist/outputs/protocol.js +1 -0
  177. package/dist/outputs/service.js +2 -15
  178. package/dist/paths.js +48 -1
  179. package/dist/pay/command.js +38 -0
  180. package/dist/pay/protocol.js +136 -0
  181. package/dist/pay/runtime.js +188 -0
  182. package/dist/pay/service.js +384 -0
  183. package/dist/pay/store.js +81 -0
  184. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  185. package/dist/services/dispatcher.js +23 -5
  186. package/dist/services/host/main.js +388 -0
  187. package/dist/services/host/protocol.js +118 -0
  188. package/dist/services/host/resident.js +310 -0
  189. package/dist/services/host-client.js +386 -0
  190. package/dist/services/host-deploy.js +180 -0
  191. package/dist/services/host-launch.js +117 -0
  192. package/dist/services/host-recycle.js +203 -0
  193. package/dist/services/host-runtime.js +802 -0
  194. package/dist/services/idempotency.js +44 -86
  195. package/dist/services/index-generator.js +4 -3
  196. package/dist/services/index.js +204 -22
  197. package/dist/services/ipc-operation.js +288 -44
  198. package/dist/services/pack-manager.js +1 -0
  199. package/dist/services/script-runner.js +515 -83
  200. package/dist/services/service-payload.js +13 -7
  201. package/dist/services/validation.js +109 -4
  202. package/dist/stats/budget.js +1 -1
  203. package/dist/stats/model-resolver.js +2 -2
  204. package/dist/stats/quota-query.js +95 -0
  205. package/dist/trigger/application-service.js +6 -4
  206. package/dist/trigger/local-files.js +19 -9
  207. package/dist/trigger/scheduler.js +22 -12
  208. package/dist/trigger/script-sandbox.js +51 -8
  209. package/dist/utils/aid-bind.js +3 -0
  210. package/dist/utils/atomic-write.js +22 -8
  211. package/dist/utils/evolcore-version.js +2 -2
  212. package/dist/utils/host-info.js +173 -1
  213. package/dist/utils/logger.js +2 -2
  214. package/dist/utils/media-cache.js +190 -43
  215. package/dist/utils/npm-ops.js +43 -8
  216. package/dist/utils/restart-safety.js +14 -1
  217. package/dist/utils/system-memory.js +113 -25
  218. package/dist/utils/systemd-lifecycle.js +154 -0
  219. package/dist/utils/windows-shell-trust.js +7 -3
  220. package/dist/workbench/service.js +1 -1
  221. package/kits/docs/INDEX.md +3 -2
  222. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
  223. package/kits/docs/channels/aun.md +1 -1
  224. package/kits/docs/evolcore/INDEX.md +9 -6
  225. package/kits/docs/evolcore/agent.md +36 -1
  226. package/kits/docs/evolcore/aid.md +45 -3
  227. package/kits/docs/evolcore/config.md +5 -2
  228. package/kits/docs/evolcore/directory.md +8 -9
  229. package/kits/docs/evolcore/group.md +2 -1
  230. package/kits/docs/evolcore/memory-tags.md +2 -0
  231. package/kits/docs/evolcore/menu-client.md +3 -3
  232. package/kits/docs/evolcore/menu-protocol.md +7 -0
  233. package/kits/docs/evolcore/model.md +3 -0
  234. package/kits/docs/evolcore/msg.md +77 -10
  235. package/kits/docs/evolcore/pay.md +34 -0
  236. package/kits/docs/evolcore/provider.md +22 -1
  237. package/kits/docs/evolcore/quota.md +54 -0
  238. package/kits/docs/evolcore/role.md +3 -0
  239. package/kits/docs/evolcore/services.md +46 -18
  240. package/kits/docs/evolcore/stats.md +2 -0
  241. package/kits/docs/evolcore/thread-chain.md +2 -0
  242. package/kits/docs/evolcore/tool-authorization.md +10 -0
  243. package/kits/docs/evolcore/trigger.md +2 -0
  244. package/kits/rules/01-overview.md +11 -32
  245. package/kits/rules/02-navigation.md +7 -0
  246. package/kits/rules/06-channel.md +3 -3
  247. package/kits/schemas/_meta.json +38 -5
  248. package/kits/schemas/agent-config.schema.20.json +24 -0
  249. package/kits/schemas/agent-config.schema.21.json +974 -0
  250. package/kits/schemas/agent-config.schema.22.json +977 -0
  251. package/kits/schemas/agent-config.schema.23.json +958 -0
  252. package/kits/schemas/daemon.schema.10.json +373 -0
  253. package/kits/schemas/daemon.schema.9.json +12 -0
  254. package/kits/schemas/defaults.schema.7.json +472 -0
  255. package/kits/schemas/providers.schema.3.json +18 -2
  256. package/kits/schemas/relation-config.schema.13.json +289 -0
  257. package/kits/skills/.switches.json +17 -1
  258. package/kits/skills/ability/SKILL.md +229 -34
  259. package/kits/skills/ability/STRUCTURE.md +333 -0
  260. package/kits/skills/ability/references/cli.md +208 -0
  261. package/kits/skills/ability/references/development.md +107 -37
  262. package/kits/skills/ability/references/management.md +106 -46
  263. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  264. package/kits/skills/agent-output-cards/SKILL.md +64 -0
  265. package/kits/skills/ec-group/SKILL.md +8 -6
  266. package/kits/skills/ec-group/TASK.md +186 -0
  267. package/kits/skills/ec-group/WORKLOG.md +180 -0
  268. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  269. package/kits/skills/ec-pay/SKILL.md +101 -0
  270. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  271. package/kits/skills/ec-provider/SKILL.md +58 -9
  272. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  273. package/kits/skills/ec-service-call/SKILL.md +135 -0
  274. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  275. package/kits/skills/ec-trigger/SKILL.md +1 -1
  276. package/kits/templates/memory-consolidation/notes.md +2 -2
  277. package/kits/templates/memory-consolidation/workflow.md +46 -0
  278. package/kits/templates/roles/visitor.json +1 -0
  279. package/kits/templates/system-fragments/channel.md +13 -4
  280. package/kits/templates/system-fragments/commands.md +5 -3
  281. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  282. package/kits/templates/system-fragments/reply.md +1 -0
  283. package/kits/templates/system-fragments/session.md +1 -1
  284. package/kits/templates/system-fragments/thread.md +27 -128
  285. package/kits/templates/system-fragments/venue.md +27 -0
  286. package/package.json +4 -5
  287. package/scripts/agent-template/inspect.mjs +79 -29
  288. package/scripts/agent-template/overlay.mjs +20 -2
  289. package/scripts/agent-template/shared/common.mjs +24 -6
  290. package/scripts/agent-template/shared/team-schema.json +23 -5
  291. package/scripts/agent-template/shared/template-contract.mjs +107 -17
  292. package/scripts/agent-template/shared/template-package.mjs +254 -29
  293. package/scripts/agent-template/shared/template-runtime.mjs +145 -2
  294. package/scripts/agent-template/shared/template.mjs +67 -9
  295. package/scripts/agent-template/team-pack.mjs +132 -41
  296. package/scripts/agent-template/team-preview.mjs +249 -5
  297. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  298. package/kits/docs/evolcore/ability.md +0 -185
  299. package/kits/skills/ability/references/calling.md +0 -56
  300. package/kits/skills/ability/references/contract-checklist.md +0 -37
  301. package/kits/skills/ability/references/recovery.md +0 -27
  302. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -5,8 +5,8 @@ import { fileURLToPath } from 'url';
5
5
  import { getPackageRoot } from '../paths.js';
6
6
  // Embedded by bin/ec-build.mjs; loaded processes retain these values across rebuilds.
7
7
  // @evolcore-build-identity:start
8
- export const RUNTIME_BUILD_ID = "sha256:76e20a438d3936bb3420763f";
9
- export const RUNTIME_BUILD_TIME = "2026-11-14T05:54:02.439Z";
8
+ export const RUNTIME_BUILD_ID = "sha256:3561d8e3c0e3ce13b94f99d2";
9
+ export const RUNTIME_BUILD_TIME = "2026-11-17T15:02:32.541Z";
10
10
  // @evolcore-build-identity:end
11
11
  let cachedVersion;
12
12
  let cachedFlavor;
@@ -128,6 +128,105 @@ function readDisk(evolcoreHomePath) {
128
128
  return { evolcoreHomePath, availableBytes: null, totalBytes: null };
129
129
  }
130
130
  }
131
+ function readText(file) {
132
+ try {
133
+ return fs.readFileSync(file, 'utf8').trim();
134
+ }
135
+ catch {
136
+ return null;
137
+ }
138
+ }
139
+ function parseQuota(quota, period) {
140
+ if (!quota || !period || !/^\d+$/u.test(quota) || !/^\d+$/u.test(period))
141
+ return null;
142
+ const value = Number(quota) / Number(period);
143
+ return Number.isFinite(value) && value > 0 ? value : null;
144
+ }
145
+ /** Resolve the process's own CPU hierarchy, including nonstandard mount points. */
146
+ function cpuHierarchies() {
147
+ const memberships = (readText('/proc/self/cgroup') ?? '').split('\n')
148
+ .map(line => line.match(/^\d+:([^:]*):(\/.*)$/u))
149
+ .filter((match) => match !== null);
150
+ const hierarchies = [];
151
+ const unescapePath = (value) => value.replace(/\\([0-7]{3})/gu, (_match, octal) => String.fromCharCode(Number.parseInt(octal, 8)));
152
+ for (const line of (readText('/proc/self/mountinfo') ?? '').split('\n')) {
153
+ const [mount, filesystem] = line.split(' - ');
154
+ if (!mount || !filesystem)
155
+ continue;
156
+ const fields = mount.split(' ');
157
+ const [type, , options = ''] = filesystem.split(' ');
158
+ if (type !== 'cgroup2' && !(type === 'cgroup' && options.split(',').includes('cpu')))
159
+ continue;
160
+ if (!fields[3] || !fields[4])
161
+ continue;
162
+ const version = type === 'cgroup2' ? 2 : 1;
163
+ const member = memberships.find(match => version === 2
164
+ ? match[1] === '' : match[1].split(',').includes('cpu'));
165
+ if (!member)
166
+ continue;
167
+ const root = unescapePath(fields[3]);
168
+ const mountPoint = unescapePath(fields[4]);
169
+ const relative = path.posix.relative(root, member[2]);
170
+ // A cgroup namespace can expose membership relative to the mounted root.
171
+ const suffix = relative === '..' || relative.startsWith('../') ? member[2] : relative;
172
+ const directory = path.posix.resolve(mountPoint, `./${suffix}`);
173
+ if (directory !== mountPoint && !directory.startsWith(`${mountPoint}/`))
174
+ continue;
175
+ hierarchies.push({ directory, mountPoint, version });
176
+ }
177
+ // Conventional namespace-root mounts also work when procfs is unavailable.
178
+ if (hierarchies.length === 0) {
179
+ for (const [mountPoint, version] of [
180
+ ['/sys/fs/cgroup', 2], ['/sys/fs/cgroup/cpu', 1],
181
+ ['/sys/fs/cgroup/cpu,cpuacct', 1], ['/sys/fs/cgroup/cpuacct,cpu', 1],
182
+ ]) {
183
+ const member = memberships.find(match => version === 2
184
+ ? match[1] === '' : match[1].split(',').includes('cpu'));
185
+ const directory = path.posix.resolve(mountPoint, `.${member?.[2] ?? '/'}`);
186
+ if (directory === mountPoint || directory.startsWith(`${mountPoint}/`)) {
187
+ hierarchies.push({ directory, mountPoint, version });
188
+ }
189
+ }
190
+ }
191
+ return hierarchies;
192
+ }
193
+ /**
194
+ * CPU capacity available to this process. Linux quota/period may be fractional;
195
+ * availableParallelism alone reports an integer suitable for worker counts.
196
+ * Read afresh so live container quota changes are reflected without a restart.
197
+ */
198
+ export function readEffectiveCpuCount() {
199
+ let count = 1;
200
+ try {
201
+ const parallelism = os.availableParallelism();
202
+ if (Number.isInteger(parallelism) && parallelism > 0)
203
+ count = parallelism;
204
+ else
205
+ count = Math.max(1, os.cpus().length);
206
+ }
207
+ catch {
208
+ try {
209
+ count = Math.max(1, os.cpus().length);
210
+ }
211
+ catch { /* retain one CPU */ }
212
+ }
213
+ if (process.platform !== 'linux')
214
+ return count;
215
+ for (const hierarchy of cpuHierarchies()) {
216
+ let directory = hierarchy.directory;
217
+ while (true) {
218
+ const quota = hierarchy.version === 2
219
+ ? parseQuota(...(readText(`${directory}/cpu.max`) ?? '').split(/\s+/u))
220
+ : parseQuota(readText(`${directory}/cpu.cfs_quota_us`) ?? undefined, readText(`${directory}/cpu.cfs_period_us`) ?? undefined);
221
+ if (quota !== null)
222
+ count = Math.min(count, quota);
223
+ if (directory === hierarchy.mountPoint)
224
+ break;
225
+ directory = path.posix.dirname(directory);
226
+ }
227
+ }
228
+ return count;
229
+ }
131
230
  function readCpuModel() {
132
231
  try {
133
232
  const model = os.cpus()[0]?.model?.trim().replace(/\s+/gu, ' ');
@@ -156,6 +255,7 @@ export function readHostInfo(evolcoreVersion, evolcoreHomePath, options = {}) {
156
255
  os: {
157
256
  platform,
158
257
  platformName: detectPlatformName(platform),
258
+ productName: null,
159
259
  release: readOsReleaseVersion(),
160
260
  distributionId: release.id,
161
261
  version: release.version,
@@ -164,7 +264,7 @@ export function readHostInfo(evolcoreVersion, evolcoreHomePath, options = {}) {
164
264
  },
165
265
  hardware: {
166
266
  architecture: process.arch,
167
- cpuCount: os.cpus().length,
267
+ cpuCount: readEffectiveCpuCount(),
168
268
  cpuModel: readCpuModel(),
169
269
  memoryTotalBytes: memInfo.memTotal,
170
270
  memoryUsedBytes: memInfo.memUsed,
@@ -274,6 +374,78 @@ export async function probeVirtualization() {
274
374
  return 'unknown';
275
375
  }
276
376
  }
377
+ /** Windows 11 的 build 分界:22000 是 21H2 首发 build,Windows 10 最高到 19045。 */
378
+ const WINDOWS_11_MIN_BUILD = 22000;
379
+ /**
380
+ * 完整 OS 产品名。只能异步:Windows 走注册表(约 50ms 子进程),Linux 读
381
+ * os-release 的 PRETTY_NAME。macOS 没有等价的廉价来源,返回 null 由界面回落
382
+ * 到 platformName + release。
383
+ *
384
+ * Windows 不能直接用 ProductName:微软为兼容性在 Windows 11 上仍把它写成
385
+ * "Windows 10 Pro"(本机实测 ProductName=Windows 10 Pro,CurrentBuild=26200,
386
+ * 而 Caption 报的是 Windows 11 专业版)。所以产品名里的主版本必须按 build 号纠正,
387
+ * 不能用 `os.release()` 的 "10.0.x"——Win10 和 Win11 的主版本号都是 10.0。
388
+ */
389
+ export async function probeOsProductName() {
390
+ try {
391
+ if (process.platform === 'win32') {
392
+ const { ok, stdout } = await runExec('reg', [
393
+ 'query', 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion',
394
+ ], 4000);
395
+ if (!ok)
396
+ return null;
397
+ return readWindowsProductName(stdout);
398
+ }
399
+ if (process.platform === 'linux') {
400
+ const pretty = readOsReleasePrettyName();
401
+ if (pretty)
402
+ return pretty;
403
+ const release = readOsRelease();
404
+ return release.version ? `${release.id ?? 'Linux'} ${release.version}` : null;
405
+ }
406
+ return null;
407
+ }
408
+ catch {
409
+ return null;
410
+ }
411
+ }
412
+ /**
413
+ * 从 `reg query ...\CurrentVersion` 的输出里拼出可信的 Windows 产品名。
414
+ *
415
+ * 注册表值本身在 Win11 上是错的,唯一可靠的版本判据是 CurrentBuild。产品名可能有
416
+ * 本地化后缀("专业版"/"Pro"),所以只替换 "Windows <主版本>" 这一小段,其余原样
417
+ * 保留。build 就读不到时宁可返回原值,也不猜版本。
418
+ */
419
+ export function readWindowsProductName(registryOutput) {
420
+ const values = new Map();
421
+ for (const line of registryOutput.split(/\r?\n/u)) {
422
+ // 每行形如 " ProductName REG_SZ Windows 10 Pro"
423
+ const match = line.match(/^\s{2,}(\S+)\s+REG_(?:SZ|EXPAND_SZ)\s+(.+)$/u);
424
+ if (match)
425
+ values.set(match[1], match[2].trim());
426
+ }
427
+ const productName = values.get('ProductName');
428
+ if (!productName)
429
+ return null;
430
+ const build = Number(values.get('CurrentBuild') ?? values.get('CurrentBuildNumber') ?? '');
431
+ if (!Number.isSafeInteger(build) || build <= 0)
432
+ return productName;
433
+ const expectedMajor = build >= WINDOWS_11_MIN_BUILD ? 11 : 10;
434
+ // ProductName 的写法固定是 "Windows <主版本> <edition>";只认这个前缀,避免误改其它片段。
435
+ return productName.replace(/^Windows\s+(\d+)/u, (_all, major) => (Number(major) === expectedMajor ? `Windows ${major}` : `Windows ${expectedMajor}`));
436
+ }
437
+ /** Linux 发行版的 PRETTY_NAME,已含版本号,是最接近 Windows ProductName 的字段。 */
438
+ function readOsReleasePrettyName() {
439
+ try {
440
+ for (const line of fs.readFileSync('/etc/os-release', 'utf8').split(/\r?\n/u)) {
441
+ const match = line.match(/^PRETTY_NAME=(.*)$/u);
442
+ if (match)
443
+ return match[1].replace(/^"|"$/gu, '').trim() || null;
444
+ }
445
+ }
446
+ catch { }
447
+ return null;
448
+ }
277
449
  // 不要求词边界:go 输出是 "go1.27.0",数字前面紧跟字母,\b 会挡住匹配。
278
450
  const SEMVER = /\d+\.\d+\.\d+(?:[-+][\w.-]+)?/u;
279
451
  function firstVersionLine(output) {
@@ -271,7 +271,7 @@ export function ownershipErrorCode(error, fallback = 'OWNERSHIP_OPERATION_FAILED
271
271
  }
272
272
  export function logOwnershipEvent(event, fields, failed = false) {
273
273
  const record = { schema: 'ec.ownership.v1', event };
274
- for (const key of ['subjectAid', 'ownerAid', 'actorAid', 'localAid', 'configuredOwnerAid']) {
274
+ for (const key of ['subjectAid', 'ownerAid', 'actorAid', 'localAid']) {
275
275
  const value = fields[key];
276
276
  if (typeof value === 'string' && value.length <= 253
277
277
  && /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?){2,}$/.test(value)) {
@@ -308,7 +308,7 @@ export function logOwnershipEvent(event, fields, failed = false) {
308
308
  if (typeof fields.relationVersion === 'number' && Number.isSafeInteger(fields.relationVersion)
309
309
  && fields.relationVersion >= 0)
310
310
  record.relationVersion = fields.relationVersion;
311
- for (const key of ['attemptId', 'processId', 'durationMs', 'maxAgeMs', 'timeoutMs', 'configuredOwnerCount']) {
311
+ for (const key of ['attemptId', 'processId', 'durationMs', 'maxAgeMs', 'timeoutMs']) {
312
312
  const value = fields[key];
313
313
  if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)
314
314
  record[key] = value;
@@ -11,7 +11,7 @@ import path from 'path';
11
11
  import fs from 'fs';
12
12
  import crypto from 'crypto';
13
13
  import { logger } from './logger.js';
14
- import { agentRelationDir } from '../paths.js';
14
+ import { agentRelationDir, agentAttachmentsDir, agentAttachmentIndexDir, } from '../paths.js';
15
15
  import { parsePeerKey } from '../core/relation/peer-identity.js';
16
16
  import { isSameOrDescendant } from '../core/permission/protected-paths.js';
17
17
  // ── 常量 ──────────────────────────────────────────────────────────────────────
@@ -112,68 +112,149 @@ export async function validateImage(buffer, opts) {
112
112
  }
113
113
  return { mime: type.mime };
114
114
  }
115
- function relationAttachmentsDir(selfAid, peerKey) {
115
+ /** 旧版附件目录(升级前的落点,仅用于兼容读取)。 */
116
+ function legacyRelationAttachmentsDir(selfAid, peerKey) {
116
117
  parsePeerKey(peerKey);
117
118
  return path.join(agentRelationDir(selfAid, peerKey), 'attachments');
118
119
  }
119
- /** Save one inbound image as a stable, peer-scoped attachment owned by the daemon. */
120
- export function saveRelationAttachment(buffer, selfAid, peerKey, mimeType) {
121
- const extension = RELATION_ATTACHMENT_EXTENSIONS[mimeType];
122
- if (!extension)
123
- throw new Error(`Unsupported relation attachment MIME type: ${mimeType}`);
124
- if (buffer.length < 1 || buffer.length > RELATION_ATTACHMENT_MAX_BYTES) {
125
- throw new Error(`Relation attachment must be between 1 byte and ${RELATION_ATTACHMENT_MAX_BYTES} bytes`);
126
- }
127
- const directory = relationAttachmentsDir(selfAid, peerKey);
120
+ /** 关系归属索引文件:`$AGENT_DIR/attachments/index/<peerKey>.jsonl`。 */
121
+ function attachmentIndexPath(selfAid, peerKey) {
122
+ parsePeerKey(peerKey);
123
+ return path.join(agentAttachmentIndexDir(selfAid), `${peerKey}.jsonl`);
124
+ }
125
+ function ensureDir(directory) {
128
126
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
129
127
  if (process.platform !== 'win32')
130
128
  fs.chmodSync(directory, 0o700);
129
+ }
130
+ /** 读取索引文件的全部记录;文件不存在时返回空数组。 */
131
+ function readIndexRecords(indexPath) {
132
+ let text;
133
+ try {
134
+ text = fs.readFileSync(indexPath, 'utf8');
135
+ }
136
+ catch {
137
+ return [];
138
+ }
139
+ const records = [];
140
+ for (const line of text.split('\n')) {
141
+ if (!line.trim())
142
+ continue;
143
+ try {
144
+ records.push(JSON.parse(line));
145
+ }
146
+ catch { /* skip malformed line */ }
147
+ }
148
+ return records;
149
+ }
150
+ function appendIndexRecord(indexPath, metadata) {
151
+ fs.appendFileSync(indexPath, `${JSON.stringify(metadata)}\n`, { mode: 0o600 });
152
+ }
153
+ /**
154
+ * 在 agent 级附件目录里为 `filename` 找一个落点。
155
+ *
156
+ * 规则(2026-11-16 起):
157
+ * - 同名文件存在且 **大小与 sha256 都相同** → 复用已有文件,不新增副本;
158
+ * - 同名但内容不同 → 依次尝试 `<base>-1<ext>`、`<base>-2<ext>`…,已存在同名候选时
159
+ * 同样先做内容比对,命中即复用;
160
+ * - 全部空闲 → 用原始文件名。
161
+ */
162
+ /** 与附件本体同级的保留名:索引子目录不能用作用户文件名。 */
163
+ const RESERVED_ATTACHMENT_NAMES = new Set(['index']);
164
+ function resolveAttachmentTarget(directory, filename, buffer, sha256) {
165
+ const ext = path.extname(filename);
166
+ const base = ext ? filename.slice(0, -ext.length) : filename;
167
+ for (let index = 0; index < 10_000; index++) {
168
+ const candidate = index === 0 ? filename : `${base}-${index}${ext}`;
169
+ // 保留名(如 index 子目录)不能作为附件本体名,直接跳到下一个编号。
170
+ if (RESERVED_ATTACHMENT_NAMES.has(candidate.toLowerCase()))
171
+ continue;
172
+ const candidatePath = path.join(directory, candidate);
173
+ if (!fs.existsSync(candidatePath)) {
174
+ return { filename: candidate, filePath: candidatePath, reused: false };
175
+ }
176
+ try {
177
+ const stat = fs.lstatSync(candidatePath);
178
+ // 目录(如 index/)不是可复用候选,跳过后继续找编号。
179
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== buffer.length)
180
+ continue;
181
+ const existingSha = crypto.createHash('sha256').update(fs.readFileSync(candidatePath)).digest('hex');
182
+ if (existingSha === sha256)
183
+ return { filename: candidate, filePath: candidatePath, reused: true };
184
+ }
185
+ catch {
186
+ continue;
187
+ }
188
+ }
189
+ throw new Error(`Too many same-name attachments in agent attachment directory: ${filename}`);
190
+ }
191
+ /**
192
+ * Save one attachment (image or arbitrary file).
193
+ *
194
+ * 文件本体进 agent 级目录(按内容去重,同一份文件发给多个对端只占一份磁盘);
195
+ * 归属信息追加到该对端的索引 `$AGENT_DIR/attachments/index/<peerKey>.jsonl`,
196
+ * 保留「这段关系什么时候收发过什么」的痕迹。
197
+ */
198
+ export function saveRelationAttachment(buffer, selfAid, peerKey, mimeType, opts = {}) {
199
+ const originalName = opts.filename ? sanitizeFileName(opts.filename) : '';
200
+ let extension;
201
+ if (opts.allowAnyExtension && originalName) {
202
+ extension = path.extname(originalName);
203
+ }
204
+ else {
205
+ extension = RELATION_ATTACHMENT_EXTENSIONS[mimeType] ?? '';
206
+ if (!extension)
207
+ throw new Error(`Unsupported relation attachment MIME type: ${mimeType}`);
208
+ }
209
+ if (buffer.length < 1 || buffer.length > RELATION_ATTACHMENT_MAX_BYTES) {
210
+ throw new Error(`Relation attachment must be between 1 byte and ${RELATION_ATTACHMENT_MAX_BYTES} bytes`);
211
+ }
212
+ const directory = agentAttachmentsDir(selfAid);
213
+ ensureDir(directory);
214
+ const indexDir = agentAttachmentIndexDir(selfAid);
215
+ ensureDir(indexDir);
131
216
  const attachmentId = crypto.randomBytes(16).toString('hex');
132
- const filename = `${attachmentId}${extension}`;
133
- const filePath = path.join(directory, filename);
134
- const metadataPath = path.join(directory, `${attachmentId}.json`);
217
+ const requestedName = originalName || `${attachmentId}${extension}`;
135
218
  const sha256 = crypto.createHash('sha256').update(buffer).digest('hex');
219
+ const target = resolveAttachmentTarget(directory, requestedName, buffer, sha256);
136
220
  const metadata = {
137
- version: 1, attachmentId, selfAid, peerKey, filename, mimeType,
138
- sha256, size: buffer.length, createdAt: Date.now(),
221
+ version: 1, attachmentId, selfAid, peerKey,
222
+ filename: requestedName, storage: target.filename, mimeType,
223
+ sha256, size: buffer.length, direction: opts.direction ?? 'in', createdAt: Date.now(),
139
224
  };
140
- fs.writeFileSync(filePath, buffer, { flag: 'wx', mode: 0o600 });
141
- fs.writeFileSync(metadataPath, JSON.stringify(metadata), { flag: 'wx', mode: 0o600 });
142
- return { ...metadata, filePath };
225
+ if (!target.reused) {
226
+ fs.writeFileSync(target.filePath, buffer, { flag: 'wx', mode: 0o600 });
227
+ }
228
+ // 索引一律追加:同一份内容收发 N 次就有 N 条记录,文件本体只落一份。
229
+ appendIndexRecord(attachmentIndexPath(selfAid, peerKey), metadata);
230
+ return { ...metadata, filePath: target.filePath };
143
231
  }
144
232
  /** Resolve an attachment only inside the authenticated Agent/peer relation. */
145
233
  export function readRelationAttachment(selfAid, peerKey, attachmentSource) {
146
- const attachmentId = RELATION_ATTACHMENT_ID_RE.test(attachmentSource)
234
+ // 兼容三种输入:新版文件名(会话内认知名)、旧版 32 位 hex ID、绝对路径。
235
+ const basename = path.basename(attachmentSource);
236
+ const legacyId = RELATION_ATTACHMENT_ID_RE.test(attachmentSource)
147
237
  ? attachmentSource
148
- : path.basename(attachmentSource, path.extname(attachmentSource));
149
- if (!RELATION_ATTACHMENT_ID_RE.test(attachmentId))
150
- throw new Error('Invalid attachment ID');
151
- const directory = relationAttachmentsDir(selfAid, peerKey);
152
- const metadataPath = path.join(directory, `${attachmentId}.json`);
153
- const metadataStat = fs.lstatSync(metadataPath);
154
- if (!metadataStat.isFile() || metadataStat.isSymbolicLink())
155
- throw new Error('Attachment metadata must be a regular file');
156
- const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'));
157
- if (metadata.version !== 1 || metadata.attachmentId !== attachmentId
158
- || metadata.selfAid !== selfAid || metadata.peerKey !== peerKey
159
- || RELATION_ATTACHMENT_EXTENSIONS[metadata.mimeType] === undefined
160
- || metadata.filename !== `${attachmentId}${RELATION_ATTACHMENT_EXTENSIONS[metadata.mimeType]}`) {
238
+ : (RELATION_ATTACHMENT_ID_RE.test(path.basename(basename, path.extname(basename)))
239
+ ? path.basename(basename, path.extname(basename))
240
+ : '');
241
+ const metadata = resolveIndexedMetadata(selfAid, peerKey, basename)
242
+ ?? (legacyId ? resolveLegacyMetadata(selfAid, peerKey, legacyId, basename) : null);
243
+ if (!metadata)
244
+ throw new Error('Attachment metadata not found');
245
+ if (metadata.version !== 1 || metadata.selfAid !== selfAid || metadata.peerKey !== peerKey) {
161
246
  throw new Error('Attachment ownership metadata mismatch');
162
247
  }
163
- const filePath = path.join(directory, metadata.filename);
164
- const stat = fs.lstatSync(filePath);
248
+ const attachmentId = metadata.attachmentId;
249
+ if (!RELATION_ATTACHMENT_ID_RE.test(attachmentId))
250
+ throw new Error('Invalid attachment ID');
251
+ const realPath = resolveAttachmentFile(selfAid, peerKey, metadata);
252
+ const stat = fs.lstatSync(realPath);
165
253
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== metadata.size
166
254
  || stat.size < 1 || stat.size > RELATION_ATTACHMENT_MAX_BYTES) {
167
255
  throw new Error('Attachment file is missing or invalid');
168
256
  }
169
- const realDirectory = fs.realpathSync(directory);
170
- const realPath = fs.realpathSync(filePath);
171
- if (!isSameOrDescendant(realPath, realDirectory))
172
- throw new Error('Attachment path escaped its relation directory');
173
- if (path.isAbsolute(attachmentSource) && fs.realpathSync(attachmentSource) !== realPath) {
174
- throw new Error('Attachment path does not match the current relation');
175
- }
176
- const buffer = fs.readFileSync(filePath);
257
+ const buffer = fs.readFileSync(realPath);
177
258
  const sha256 = crypto.createHash('sha256').update(buffer).digest('hex');
178
259
  if (sha256 !== metadata.sha256)
179
260
  throw new Error('Attachment content hash mismatch');
@@ -185,6 +266,72 @@ export function readRelationAttachment(selfAid, peerKey, attachmentSource) {
185
266
  buffer,
186
267
  };
187
268
  }
269
+ /** 旧版:`<peerKey>/attachments/<id>.json` + `<id><ext>`,仍在关系目录里。 */
270
+ function resolveLegacyMetadata(selfAid, peerKey, legacyId, requestedBasename) {
271
+ const directory = legacyRelationAttachmentsDir(selfAid, peerKey);
272
+ const legacyPath = path.join(directory, `${legacyId}.json`);
273
+ try {
274
+ const stat = fs.lstatSync(legacyPath);
275
+ if (!stat.isFile() || stat.isSymbolicLink())
276
+ return null;
277
+ const raw = JSON.parse(fs.readFileSync(legacyPath, 'utf8'));
278
+ if (!raw || typeof raw !== 'object')
279
+ return null;
280
+ // 旧记录没有 storage/direction 字段,落盘名按旧约定推导。
281
+ const filename = typeof raw.filename === 'string' ? raw.filename : '';
282
+ return {
283
+ ...raw,
284
+ filename: requestedBasename || filename,
285
+ storage: filename,
286
+ direction: 'in',
287
+ };
288
+ }
289
+ catch {
290
+ return null;
291
+ }
292
+ }
293
+ /** 新版:`$AGENT_DIR/attachments/index/<peerKey>.jsonl` 里按 filename 取最后一条。 */
294
+ function resolveIndexedMetadata(selfAid, peerKey, filename) {
295
+ if (!filename || filename.includes('\0') || filename === '.' || filename === '..'
296
+ || path.basename(filename) !== filename) {
297
+ throw new Error('Invalid attachment name');
298
+ }
299
+ const records = readIndexRecords(attachmentIndexPath(selfAid, peerKey));
300
+ for (let index = records.length - 1; index >= 0; index--) {
301
+ const record = records[index];
302
+ if (record.filename === filename || record.storage === filename || record.attachmentId === filename)
303
+ return record;
304
+ }
305
+ return null;
306
+ }
307
+ /** 取文件本体路径:新版在 agent 级目录,旧版回落到关系目录。 */
308
+ function resolveAttachmentFile(selfAid, peerKey, metadata) {
309
+ const storage = typeof metadata.storage === 'string' && metadata.storage
310
+ ? metadata.storage
311
+ : metadata.filename;
312
+ if (!storage || path.basename(storage) !== storage)
313
+ throw new Error('Invalid attachment storage name');
314
+ const agentDirPath = agentAttachmentsDir(selfAid);
315
+ const agentCandidate = path.join(agentDirPath, storage);
316
+ if (fs.existsSync(agentCandidate)) {
317
+ const realRoot = fs.realpathSync(agentDirPath);
318
+ const realPath = fs.realpathSync(agentCandidate);
319
+ if (!isSameOrDescendant(realPath, realRoot))
320
+ throw new Error('Attachment path escaped the agent attachment directory');
321
+ return realPath;
322
+ }
323
+ // 旧版附件仍在关系目录里。
324
+ const legacyDir = legacyRelationAttachmentsDir(selfAid, peerKey);
325
+ const legacyCandidate = path.join(legacyDir, storage);
326
+ if (fs.existsSync(legacyCandidate)) {
327
+ const realRoot = fs.realpathSync(legacyDir);
328
+ const realPath = fs.realpathSync(legacyCandidate);
329
+ if (!isSameOrDescendant(realPath, realRoot))
330
+ throw new Error('Attachment path escaped its relation directory');
331
+ return realPath;
332
+ }
333
+ throw new Error('Attachment file is missing or invalid');
334
+ }
188
335
  /**
189
336
  * 把已下载的附件 Buffer 转成入站图片条目(供 baseagent 视觉通道)。
190
337
  *
@@ -194,7 +194,14 @@ async function canSudoNonInteractively() {
194
194
  export async function npmInstallGlobal(pkg, options = {}) {
195
195
  const npm = resolveNpmInvocation();
196
196
  const registry = options.registry ? normalizeRegistry(options.registry) : undefined;
197
- const npmArgs = ['install', '-g', pkg, ...(registry ? ['--registry', registry] : []), ...npmConfigArgs(options.npmConfig), ...(options.preferOffline ? ['--prefer-offline'] : [])];
197
+ // Override inherited npmrc/env cache modes when recovering from stale metadata.
198
+ const cacheArgs = options.preferOnline
199
+ ? ['--prefer-online', '--prefer-offline=false', '--offline=false']
200
+ : options.preferOffline ? ['--prefer-offline'] : [];
201
+ const npmArgs = [
202
+ 'install', '-g', pkg, ...(registry ? ['--registry', registry] : []),
203
+ ...npmConfigArgs(options.npmConfig), ...cacheArgs,
204
+ ];
198
205
  try {
199
206
  await execFileAsync(npm.command, [...npm.argsPrefix, ...npmArgs], {
200
207
  timeout: options.timeoutMs ?? 180000,
@@ -492,7 +499,30 @@ export async function queryPackageVersion(pkg, selection, signal, distTag = 'lat
492
499
  : await fetchLatestVersion(pkg, 10000, signal, registry, distTag);
493
500
  return isPackageVersion(version) ? { version, registry, npmConfig: selection.npmConfig } : null;
494
501
  }
495
- /** No registry lookup: callers must validate cache freshness before each install. */
502
+ function npmFailureCode(error) {
503
+ const failure = error;
504
+ if (typeof failure?.code === 'string' && /^[A-Z][A-Z0-9_]+$/.test(failure.code))
505
+ return failure.code;
506
+ // execFile reports the numeric exit status; npm's own error code is in stderr.
507
+ const output = [failure?.stderr, failure?.message].filter(value => typeof value === 'string').join('\n');
508
+ return output.match(/(?:^|\n)npm (?:error|ERR!) code ([A-Z][A-Z0-9_]+)\b/)?.[1];
509
+ }
510
+ function formatPackageInstallFailure(error, phase) {
511
+ const failure = error;
512
+ const stderr = typeof failure?.stderr === 'string' ? failure.stderr.trim() : '';
513
+ const errorLines = stderr.split('\n').filter(line => /^npm (?:error|ERR!)\s/.test(line));
514
+ const detail = (errorLines.length ? errorLines.join('\n') : stderr
515
+ || (typeof failure?.message === 'string' ? failure.message : String(error)))
516
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
517
+ .replace(/https?:\/\/[^\s"'<>]+/gi, '[registry]')
518
+ .replace(/(\b[\w-]*(?:token|password|secret|api[_-]?key|credential|authorization|_auth)[\w-]*["']?\s*[:=]\s*)(?:(?:Bearer|Basic)\s+)?(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1[redacted]')
519
+ .replace(/\b(?:Bearer|Basic)\s+[^\s,;]+/gi, '[redacted]')
520
+ .replace(/\bnpm_[a-z0-9]+\b/gi, '[redacted]')
521
+ .replace(/\s+/g, ' ').trim().slice(0, 1_000);
522
+ const code = npmFailureCode(error);
523
+ return `Package ${phase} failed${code ? ` (${code})` : ''}${detail ? `: ${detail}` : ''}`;
524
+ }
525
+ /** No target version lookup: callers validate the cached target; ETARGET retries refresh dependency metadata. */
496
526
  export async function installExactPackageVersion(pkg, target, registry, resolveInstalled, npmConfig, beforeInstall) {
497
527
  if (![MAIN_PACKAGE_NAME, WEB_PACKAGE_NAME].includes(pkg)
498
528
  || !isPackageVersion(target) || normalizeVersionRegistry(registry) !== registry) {
@@ -511,20 +541,25 @@ export async function installExactPackageVersion(pkg, target, registry, resolveI
511
541
  return;
512
542
  }
513
543
  await beforeInstall?.();
544
+ let preferOnline = false;
514
545
  for (let attempt = 0; attempt < 2; attempt++) {
546
+ let phase = 'installation';
515
547
  try {
516
- await npmInstallGlobal(`${pkg}@${target}`, { registry, preferOffline: true, npmConfig });
548
+ await npmInstallGlobal(`${pkg}@${target}`, {
549
+ registry, preferOffline: !preferOnline, preferOnline, npmConfig,
550
+ });
551
+ phase = 'version verification';
517
552
  const actual = resolveInstalled()?.version;
518
553
  if (!actual || !isPackageVersion(actual) || comparePackageVersions(actual, target) < 0) {
519
- throw new Error('Installed version did not reach the cached target');
554
+ throw new Error(`Installed ${pkg} version is ${actual ?? 'unavailable'} (target ${target})`);
520
555
  }
521
556
  result = { status: 'upgraded', from, to: actual };
522
557
  return;
523
558
  }
524
- catch {
525
- // npm stderr can contain private registry credentials. Persist a safe
526
- // diagnostic; npm's existing permission/transport behavior is retained.
527
- result = { status: 'failed', from, to: target, error: 'Exact package installation or version verification failed' };
559
+ catch (error) {
560
+ if (phase === 'installation' && npmFailureCode(error) === 'ETARGET')
561
+ preferOnline = true;
562
+ result = { status: 'failed', from, to: target, error: formatPackageInstallFailure(error, phase) };
528
563
  }
529
564
  }
530
565
  });
@@ -5,7 +5,15 @@ const REAL_RESTART_TEST_OVERRIDE = 'EVOLCORE_ALLOW_REAL_RESTART_IN_TEST';
5
5
  export function readRestartRequest(filePath, requestId) {
6
6
  try {
7
7
  const request = JSON.parse(fs.readFileSync(filePath, 'utf8'));
8
- return request?.requestId === requestId ? request : null;
8
+ if (!request?.requestId || (requestId && request.requestId !== requestId))
9
+ return null;
10
+ // A failed unit may never start a replacement process. Readers can still
11
+ // observe a terminal timeout without requiring a surviving supervisor.
12
+ if (request.backend === 'systemd' && ['requested', 'accepted'].includes(request.status)
13
+ && request.deadline && request.deadline <= Date.now()) {
14
+ return { ...request, status: 'timeout', reason: 'Systemd replacement did not confirm ready before the restart deadline' };
15
+ }
16
+ return request;
9
17
  }
10
18
  catch {
11
19
  return null;
@@ -15,6 +23,9 @@ export function createRestartRequest(filePath, request, isProcessAlive) {
15
23
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
16
24
  try {
17
25
  const previous = JSON.parse(fs.readFileSync(filePath, 'utf8'));
26
+ if (previous.backend === 'systemd' && ['requested', 'accepted'].includes(previous.status)
27
+ && Number(previous.deadline) > Date.now())
28
+ return false;
18
29
  if ([previous.launcherPid, previous.monitorPid]
19
30
  .some(pid => typeof pid === 'number' && isProcessAlive(pid))
20
31
  || Date.now() - Number(previous.updatedAt ?? previous.timestamp ?? 0) < 30_000)
@@ -39,6 +50,8 @@ export function updateRestartRequest(filePath, requestId, update) {
39
50
  const request = readRestartRequest(filePath, requestId);
40
51
  if (!request)
41
52
  return false;
53
+ if (['ready', 'failed', 'timeout'].includes(request.status) && update.status && update.status !== request.status)
54
+ return false;
42
55
  atomicWriteJson(filePath, { ...request, ...update, updatedAt: Date.now() });
43
56
  return true;
44
57
  }