evolcore 0.0.49 → 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 (250) hide show
  1. package/CHANGELOG.md +64 -1
  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 +280 -6
  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 +4 -1
  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 +29 -1
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +537 -189
  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/ecmsg-gateway.js +11 -9
  54. package/dist/cli/index.js +23 -4
  55. package/dist/cli/init.js +39 -63
  56. package/dist/cli/managed-command-guard.js +1 -0
  57. package/dist/cli/menu-client.js +32 -7
  58. package/dist/cli/pay-command.js +30 -0
  59. package/dist/cli/provider-command.js +6 -2
  60. package/dist/cli/restart-monitor.js +2 -2
  61. package/dist/cli/services-command.js +11 -9
  62. package/dist/cli/thread-command.js +78 -12
  63. package/dist/config/access-policy.js +16 -3
  64. package/dist/config/config-field-policy.js +17 -8
  65. package/dist/config/config-manager.js +86 -46
  66. package/dist/config/config-operation-service.js +22 -1
  67. package/dist/config/gateway-config.js +9 -8
  68. package/dist/config/owner-config.js +0 -16
  69. package/dist/config/peer-role-resolver.js +1 -7
  70. package/dist/config/providers-config.js +99 -16
  71. package/dist/config/providers-management.js +35 -19
  72. package/dist/config/resolved-config-op.js +1 -42
  73. package/dist/config/schema-migration.js +78 -5
  74. package/dist/config/schema-registry.js +52 -7
  75. package/dist/config-store.js +1309 -17
  76. package/dist/core/agent-application-service.js +220 -1
  77. package/dist/core/agent-ipc-registration.js +19 -2
  78. package/dist/core/agent-reload-coordinator.js +5 -0
  79. package/dist/core/agent-runtime.js +198 -54
  80. package/dist/core/auth/agent-delegation.js +14 -0
  81. package/dist/core/auth/operation-authorizer.js +16 -1
  82. package/dist/core/auth/operation-catalog.js +50 -7
  83. package/dist/core/baseagent-loader.js +30 -3
  84. package/dist/core/capability/capability-manager.js +16 -7
  85. package/dist/core/channel-runtime.js +4 -2
  86. package/dist/core/command/agent-control.js +20 -2
  87. package/dist/core/command/agent-template-menu.js +4 -3
  88. package/dist/core/command/cli-intent-parser.js +15 -0
  89. package/dist/core/command/menu-catalog.js +20 -4
  90. package/dist/core/command/menu-file-path.js +70 -0
  91. package/dist/core/command/menu-handler.js +91 -72
  92. package/dist/core/command/menu-protocol.js +5 -0
  93. package/dist/core/command/menu-query-batch.js +2 -2
  94. package/dist/core/command/private-mention-menu.js +71 -0
  95. package/dist/core/command/slash-handler.js +17 -26
  96. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  97. package/dist/core/command/topic-slash.js +7 -1
  98. package/dist/core/daemon-bootstrap.js +0 -4
  99. package/dist/core/daemon-control.js +2 -1
  100. package/dist/core/daemon-lifecycle.js +13 -5
  101. package/dist/core/evolagent-registry.js +12 -7
  102. package/dist/core/handoff/runtime.js +1 -1
  103. package/dist/core/host-snapshot.js +8 -3
  104. package/dist/core/initialization/service.js +3 -0
  105. package/dist/core/interaction-router.js +130 -0
  106. package/dist/core/ipc-registration.js +4 -0
  107. package/dist/core/memory/consolidation-context.js +2 -1
  108. package/dist/core/memory/consolidation.js +35 -64
  109. package/dist/core/message/aun-ipc-sender.js +98 -21
  110. package/dist/core/message/aun-request-registry.js +31 -0
  111. package/dist/core/message/message-bridge.js +105 -6
  112. package/dist/core/message/message-log.js +8 -0
  113. package/dist/core/message/message-queue.js +5 -3
  114. package/dist/core/message/peer-mode.js +15 -4
  115. package/dist/core/message/response-engine.js +23 -8
  116. package/dist/core/message/send-options.js +37 -3
  117. package/dist/core/message/send-routing.js +11 -7
  118. package/dist/core/model/model-catalog.js +5 -5
  119. package/dist/core/ownership/owner-resolver.js +12 -86
  120. package/dist/core/pack-auth.js +4 -0
  121. package/dist/core/permission/ec-command-parser.js +182 -58
  122. package/dist/core/permission/protected-paths.js +64 -9
  123. package/dist/core/permission/services-path-acl.js +9 -2
  124. package/dist/core/permission/tool-policy.js +21 -9
  125. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  126. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  127. package/dist/core/session/session-manager.js +47 -10
  128. package/dist/core/session/session-mapper.js +16 -0
  129. package/dist/core/skill/index-generator.js +2 -3
  130. package/dist/core/skill/switch-resolver.js +3 -0
  131. package/dist/core/thread/command-parser.js +4 -1
  132. package/dist/core/thread/ipc-operation.js +4 -2
  133. package/dist/core/thread/thread-operation.js +25 -10
  134. package/dist/core/thread/thread-service.js +294 -55
  135. package/dist/core/thread/topic-id.js +52 -2
  136. package/dist/core/thread/types.js +15 -1
  137. package/dist/eck/kit-renderer.js +2 -1
  138. package/dist/ecweb/basic-settings-service.js +5 -9
  139. package/dist/ecweb/providers-service.js +4 -2
  140. package/dist/index.js +116 -41
  141. package/dist/ipc.js +58 -2
  142. package/dist/paths.js +48 -1
  143. package/dist/pay/command.js +38 -0
  144. package/dist/pay/protocol.js +136 -0
  145. package/dist/pay/runtime.js +188 -0
  146. package/dist/pay/service.js +384 -0
  147. package/dist/pay/store.js +81 -0
  148. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  149. package/dist/services/dispatcher.js +23 -5
  150. package/dist/services/host/main.js +388 -0
  151. package/dist/services/host/protocol.js +118 -0
  152. package/dist/services/host/resident.js +310 -0
  153. package/dist/services/host-client.js +386 -0
  154. package/dist/services/host-deploy.js +180 -0
  155. package/dist/services/host-launch.js +117 -0
  156. package/dist/services/host-recycle.js +203 -0
  157. package/dist/services/host-runtime.js +802 -0
  158. package/dist/services/idempotency.js +44 -86
  159. package/dist/services/index-generator.js +4 -3
  160. package/dist/services/index.js +176 -18
  161. package/dist/services/ipc-operation.js +204 -44
  162. package/dist/services/script-runner.js +515 -83
  163. package/dist/services/validation.js +109 -4
  164. package/dist/trigger/application-service.js +6 -4
  165. package/dist/trigger/local-files.js +19 -9
  166. package/dist/trigger/scheduler.js +22 -12
  167. package/dist/trigger/script-sandbox.js +51 -20
  168. package/dist/utils/aid-bind.js +3 -0
  169. package/dist/utils/evolcore-version.js +2 -2
  170. package/dist/utils/host-info.js +73 -0
  171. package/dist/utils/logger.js +2 -2
  172. package/dist/utils/media-cache.js +190 -43
  173. package/dist/utils/restart-safety.js +14 -1
  174. package/dist/utils/system-memory.js +113 -25
  175. package/dist/utils/systemd-lifecycle.js +154 -0
  176. package/dist/utils/windows-shell-trust.js +7 -3
  177. package/kits/docs/INDEX.md +3 -2
  178. 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
  179. package/kits/docs/channels/aun.md +1 -1
  180. package/kits/docs/evolcore/INDEX.md +7 -6
  181. package/kits/docs/evolcore/agent.md +36 -1
  182. package/kits/docs/evolcore/aid.md +20 -3
  183. package/kits/docs/evolcore/config.md +1 -1
  184. package/kits/docs/evolcore/group.md +2 -1
  185. package/kits/docs/evolcore/memory-tags.md +2 -0
  186. package/kits/docs/evolcore/menu-client.md +3 -3
  187. package/kits/docs/evolcore/menu-protocol.md +7 -0
  188. package/kits/docs/evolcore/model.md +3 -0
  189. package/kits/docs/evolcore/msg.md +68 -10
  190. package/kits/docs/evolcore/pay.md +34 -0
  191. package/kits/docs/evolcore/provider.md +21 -0
  192. package/kits/docs/evolcore/services.md +46 -18
  193. package/kits/docs/evolcore/thread-chain.md +2 -0
  194. package/kits/docs/evolcore/tool-authorization.md +10 -0
  195. package/kits/rules/01-overview.md +11 -32
  196. package/kits/rules/02-navigation.md +7 -0
  197. package/kits/rules/06-channel.md +3 -3
  198. package/kits/schemas/_meta.json +38 -5
  199. package/kits/schemas/agent-config.schema.21.json +974 -0
  200. package/kits/schemas/agent-config.schema.22.json +977 -0
  201. package/kits/schemas/agent-config.schema.23.json +958 -0
  202. package/kits/schemas/daemon.schema.10.json +373 -0
  203. package/kits/schemas/daemon.schema.9.json +12 -0
  204. package/kits/schemas/defaults.schema.7.json +472 -0
  205. package/kits/schemas/providers.schema.3.json +18 -2
  206. package/kits/schemas/relation-config.schema.13.json +289 -0
  207. package/kits/skills/.switches.json +13 -1
  208. package/kits/skills/ability/SKILL.md +229 -34
  209. package/kits/skills/ability/STRUCTURE.md +333 -0
  210. package/kits/skills/ability/references/cli.md +208 -0
  211. package/kits/skills/ability/references/development.md +107 -37
  212. package/kits/skills/ability/references/management.md +106 -46
  213. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  214. package/kits/skills/agent-output-cards/SKILL.md +12 -5
  215. package/kits/skills/ec-group/SKILL.md +8 -6
  216. package/kits/skills/ec-group/TASK.md +186 -0
  217. package/kits/skills/ec-group/WORKLOG.md +180 -0
  218. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  219. package/kits/skills/ec-pay/SKILL.md +101 -0
  220. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  221. package/kits/skills/ec-provider/SKILL.md +1 -1
  222. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  223. package/kits/skills/ec-service-call/SKILL.md +135 -0
  224. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  225. package/kits/skills/ec-trigger/SKILL.md +1 -1
  226. package/kits/templates/memory-consolidation/notes.md +2 -2
  227. package/kits/templates/memory-consolidation/workflow.md +46 -0
  228. package/kits/templates/system-fragments/channel.md +13 -4
  229. package/kits/templates/system-fragments/commands.md +4 -3
  230. package/kits/templates/system-fragments/reply.md +1 -0
  231. package/kits/templates/system-fragments/session.md +1 -1
  232. package/kits/templates/system-fragments/thread.md +27 -129
  233. package/kits/templates/system-fragments/venue.md +16 -0
  234. package/package.json +4 -5
  235. package/scripts/agent-template/inspect.mjs +37 -23
  236. package/scripts/agent-template/overlay.mjs +20 -2
  237. package/scripts/agent-template/shared/common.mjs +16 -4
  238. package/scripts/agent-template/shared/team-schema.json +20 -4
  239. package/scripts/agent-template/shared/template-contract.mjs +53 -13
  240. package/scripts/agent-template/shared/template-package.mjs +90 -26
  241. package/scripts/agent-template/shared/template-runtime.mjs +111 -1
  242. package/scripts/agent-template/shared/template.mjs +65 -7
  243. package/scripts/agent-template/team-pack.mjs +89 -33
  244. package/scripts/agent-template/team-preview.mjs +249 -5
  245. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  246. package/kits/docs/evolcore/ability.md +0 -185
  247. package/kits/skills/ability/references/calling.md +0 -56
  248. package/kits/skills/ability/references/contract-checklist.md +0 -37
  249. package/kits/skills/ability/references/recovery.md +0 -27
  250. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -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
  *
@@ -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
  }
@@ -1,9 +1,11 @@
1
1
  import fs from 'fs';
2
2
  import os from 'os';
3
+ import path from 'node:path';
3
4
  function readNumber(filePath) {
4
5
  try {
5
- const value = Number(fs.readFileSync(filePath, 'utf8').trim());
6
- return Number.isFinite(value) && value >= 0 ? value : null;
6
+ const raw = fs.readFileSync(filePath, 'utf8').trim();
7
+ const value = /^\d+$/u.test(raw) ? Number(raw) : NaN;
8
+ return Number.isSafeInteger(value) && value >= 0 ? value : null;
7
9
  }
8
10
  catch {
9
11
  return null;
@@ -19,39 +21,125 @@ export function parseCgroupV2MemoryStat(input) {
19
21
  }
20
22
  return values;
21
23
  }
24
+ function readText(file) {
25
+ try {
26
+ return fs.readFileSync(file, 'utf8').trim();
27
+ }
28
+ catch {
29
+ return '';
30
+ }
31
+ }
32
+ function memoryHierarchies(cgroupRoot) {
33
+ if (cgroupRoot !== '/sys/fs/cgroup') {
34
+ return [{ directory: cgroupRoot, mountPoint: cgroupRoot, version: 2 }];
35
+ }
36
+ const memberships = readText('/proc/self/cgroup').split('\n')
37
+ .map(line => line.match(/^\d+:([^:]*):(\/.*)$/u))
38
+ .filter((match) => match !== null);
39
+ const hierarchies = [];
40
+ const decode = (value) => value.replace(/\\([0-7]{3})/gu, (_match, octal) => String.fromCharCode(Number.parseInt(octal, 8)));
41
+ for (const line of readText('/proc/self/mountinfo').split('\n')) {
42
+ const [mount, filesystem] = line.split(' - ');
43
+ if (!mount || !filesystem)
44
+ continue;
45
+ const fields = mount.split(' ');
46
+ const [type, , options = ''] = filesystem.split(' ');
47
+ if (type !== 'cgroup2' && !(type === 'cgroup' && options.split(',').includes('memory')))
48
+ continue;
49
+ if (!fields[3] || !fields[4])
50
+ continue;
51
+ const version = type === 'cgroup2' ? 2 : 1;
52
+ const member = memberships.find(match => version === 2
53
+ ? match[1] === '' : match[1].split(',').includes('memory'));
54
+ if (!member)
55
+ continue;
56
+ const mountPoint = decode(fields[4]);
57
+ const relative = path.posix.relative(decode(fields[3]), member[2]);
58
+ const suffix = relative === '..' || relative.startsWith('../') ? member[2] : relative;
59
+ const directory = path.posix.resolve(mountPoint, `./${suffix}`);
60
+ if (directory === mountPoint || directory.startsWith(`${mountPoint}/`)) {
61
+ hierarchies.push({ directory, mountPoint, version });
62
+ }
63
+ }
64
+ if (hierarchies.length === 0) {
65
+ for (const [mountPoint, version] of [['/sys/fs/cgroup', 2], ['/sys/fs/cgroup/memory', 1]]) {
66
+ const member = memberships.find(match => version === 2
67
+ ? match[1] === '' : match[1].split(',').includes('memory'));
68
+ const directory = path.posix.resolve(mountPoint, `.${member?.[2] ?? '/'}`);
69
+ if (directory === mountPoint || directory.startsWith(`${mountPoint}/`)) {
70
+ hierarchies.push({ directory, mountPoint, version });
71
+ }
72
+ }
73
+ }
74
+ return hierarchies;
75
+ }
22
76
  /**
23
77
  * System memory for the current container/host namespace.
24
78
  *
25
- * Linux cgroup v2 uses memory.current - memory.stat:file so the value matches
26
- * common host/container dashboards: anonymous + kernel memory, excluding
27
- * reclaimable filesystem page cache. Other environments fall back to the
28
- * portable total - available calculation exposed by Node.js.
79
+ * Total is bounded by visible cgroup hard limits, including ancestors. Usage
80
+ * excludes filesystem cache when available. Free is hard-limit headroom;
81
+ * available also includes the cache estimate, bounded by parent headroom and
82
+ * host free memory. These are estimates, not guarantees of future allocation.
29
83
  */
30
84
  export function readSystemMemoryUsage(cgroupRoot = '/sys/fs/cgroup') {
31
- const memTotal = os.totalmem();
32
- const memAvailable = os.freemem();
85
+ const hostTotal = os.totalmem();
86
+ const hostAvailable = os.freemem();
87
+ let memTotal = hostTotal;
33
88
  if (process.platform === 'linux') {
34
- const current = readNumber(`${cgroupRoot}/memory.current`);
35
- if (current !== null) {
36
- try {
37
- const stat = parseCgroupV2MemoryStat(fs.readFileSync(`${cgroupRoot}/memory.stat`, 'utf8'));
38
- const fileCache = stat.get('file');
39
- if (fileCache !== undefined) {
40
- const memUsed = Math.max(0, current - fileCache);
41
- return {
42
- memTotal,
43
- memUsed,
44
- memFree: Math.max(0, memTotal - memUsed),
45
- memAvailable,
46
- memorySource: 'cgroup-v2-current-minus-file',
47
- cgroupCurrent: current,
48
- fileCache,
49
- };
89
+ let headroom = hostAvailable;
90
+ let available = hostAvailable;
91
+ let usage;
92
+ for (const hierarchy of memoryHierarchies(cgroupRoot)) {
93
+ let directory = hierarchy.directory;
94
+ while (true) {
95
+ const limit = readNumber(`${directory}/${hierarchy.version === 2 ? 'memory.max' : 'memory.limit_in_bytes'}`);
96
+ const current = readNumber(`${directory}/${hierarchy.version === 2 ? 'memory.current' : 'memory.usage_in_bytes'}`);
97
+ const stat = parseCgroupV2MemoryStat(readText(`${directory}/memory.stat`));
98
+ const cache = hierarchy.version === 2 ? stat.get('file') : stat.get('total_cache') ?? stat.get('cache');
99
+ if (directory === hierarchy.directory && current !== null) {
100
+ usage = { current, cache, version: hierarchy.version };
101
+ }
102
+ // v1's unlimited sentinel exceeds safe integer precision and is ignored.
103
+ if (limit !== null) {
104
+ memTotal = Math.min(memTotal, limit);
105
+ if (current !== null) {
106
+ headroom = Math.min(headroom, Math.max(0, limit - current));
107
+ available = Math.min(available, Math.max(0, limit - Math.max(0, current - (cache ?? 0))));
108
+ }
50
109
  }
110
+ if (directory === hierarchy.mountPoint)
111
+ break;
112
+ directory = path.posix.dirname(directory);
113
+ }
114
+ }
115
+ if (usage) {
116
+ const { current, cache, version } = usage;
117
+ const memUsed = Math.min(memTotal, Math.max(0, current - (cache ?? 0)));
118
+ return {
119
+ memTotal, memUsed,
120
+ memFree: Math.min(headroom, Math.max(0, memTotal - current)),
121
+ memAvailable: Math.min(available, Math.max(0, memTotal - memUsed)),
122
+ memorySource: version === 2
123
+ ? cache === undefined ? 'cgroup-v2-current' : 'cgroup-v2-current-minus-file'
124
+ : cache === undefined ? 'cgroup-v1-usage' : 'cgroup-v1-usage-minus-cache',
125
+ cgroupCurrent: current,
126
+ ...(cache === undefined ? {} : { fileCache: cache }),
127
+ };
128
+ }
129
+ // Even if usage files are unreadable, keep a discovered hard limit and use
130
+ // Node's container-aware availability instead of subtracting host metrics.
131
+ if (memTotal < hostTotal) {
132
+ let memAvailable = 0;
133
+ try {
134
+ memAvailable = process.availableMemory();
51
135
  }
52
- catch { /* fall through to portable OS metrics */ }
136
+ catch { /* conservative fallback */ }
137
+ memAvailable = Number.isFinite(memAvailable) ? Math.max(0, Math.min(memTotal, hostAvailable, memAvailable)) : 0;
138
+ return { memTotal, memUsed: memTotal - memAvailable, memFree: memAvailable,
139
+ memAvailable, memorySource: 'runtime-available' };
53
140
  }
54
141
  }
142
+ const memAvailable = Math.max(0, Math.min(memTotal, hostAvailable));
55
143
  return {
56
144
  memTotal,
57
145
  memUsed: Math.max(0, memTotal - memAvailable),
@@ -0,0 +1,154 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { execFile } from 'child_process';
4
+ import { promisify } from 'util';
5
+ import { withFileLock } from './atomic-write.js';
6
+ import { getProcessStartTime, startTimeMatches } from './process-introspect.js';
7
+ import { readRestartRequest, updateRestartRequest } from './restart-safety.js';
8
+ const execFileAsync = promisify(execFile);
9
+ const SHOW_PROPERTIES = 'Id,LoadState,ActiveState,MainPID,ControlGroup,InvocationID';
10
+ function processCgroup(pid) {
11
+ const groups = fs.readFileSync(`/proc/${pid}/cgroup`, 'utf8').trim().split('\n')
12
+ .map(line => line.match(/^\d+:([^:]*):(\/.*)$/))
13
+ .filter(match => match && (match[1] === '' || match[1].split(',').includes('name=systemd')))
14
+ .map(match => match[2]);
15
+ if (groups.length !== 1 || path.posix.normalize(groups[0]) !== groups[0]) {
16
+ throw new Error(`Cannot determine systemd cgroup for daemon PID ${pid}`);
17
+ }
18
+ return groups[0];
19
+ }
20
+ function assertIdentity(pid, startedAt) {
21
+ if (!Number.isInteger(pid) || pid <= 1 || !Number.isFinite(startedAt)
22
+ || !startTimeMatches(startedAt, getProcessStartTime(pid, { fresh: true }))) {
23
+ throw new Error(`Daemon identity changed or is unavailable (PID ${pid}); refusing systemd restart`);
24
+ }
25
+ }
26
+ function hasAncestor(pid, ancestor) {
27
+ const visited = new Set();
28
+ while (pid > 1 && visited.size < 64 && !visited.has(pid)) {
29
+ if (pid === ancestor)
30
+ return true;
31
+ visited.add(pid);
32
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
33
+ pid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
34
+ }
35
+ return false;
36
+ }
37
+ function scopeArgs(scope) {
38
+ return scope === 'user' ? ['--user'] : ['--system'];
39
+ }
40
+ /** Inspect the target daemon, never the calling CLI's cgroup or environment. */
41
+ export async function discoverSystemdService(pid, startedAt) {
42
+ if (process.platform !== 'linux')
43
+ return null;
44
+ assertIdentity(pid, startedAt);
45
+ const controlGroup = processCgroup(pid);
46
+ // The innermost unit owns the process. An ancestor user@/docker service is
47
+ // not ownership when a session/container scope is nested underneath it.
48
+ const units = controlGroup.split('/').filter(part => /\.(service|scope)$/.test(part));
49
+ const unit = units.at(-1);
50
+ if (!unit?.endsWith('.service'))
51
+ return null;
52
+ if (!/^[a-zA-Z0-9_:@.\\-]+\.service$/.test(unit) || unit.startsWith('-')) {
53
+ throw new Error('Invalid systemd service name in daemon cgroup');
54
+ }
55
+ // A container may expose a host cgroup while having its own PID namespace.
56
+ // Never ask a host/container manager to restart an enclosing host service.
57
+ if (fs.readFileSync('/proc/1/comm', 'utf8').trim() !== 'systemd') {
58
+ throw new Error('Daemon has a service cgroup but its systemd manager is not visible; restart from the owning host');
59
+ }
60
+ const userManager = controlGroup.match(/\/user@(\d+)\.service\//);
61
+ const scope = userManager ? 'user' : 'system';
62
+ if (userManager && Number(userManager[1]) !== process.getuid?.()) {
63
+ throw new Error('User systemd restart requires the owning user and its user manager');
64
+ }
65
+ const { stdout } = await execFileAsync('systemctl', [
66
+ ...scopeArgs(scope), '--no-ask-password', 'show', `--property=${SHOW_PROPERTIES}`, '--', unit,
67
+ ], { encoding: 'utf8', timeout: 5_000, maxBuffer: 64 * 1024 });
68
+ const properties = Object.fromEntries(stdout.trim().split('\n').map(line => {
69
+ const equals = line.indexOf('=');
70
+ return [line.slice(0, equals), line.slice(equals + 1)];
71
+ }));
72
+ const mainPid = Number(properties.MainPID);
73
+ if (properties.Id !== unit || properties.LoadState !== 'loaded' || properties.ActiveState !== 'active'
74
+ || properties.ControlGroup !== controlGroup
75
+ || !/^[a-f0-9]{32}$/.test(properties.InvocationID)
76
+ || !Number.isInteger(mainPid) || mainPid <= 1
77
+ || !hasAncestor(pid, mainPid) || processCgroup(mainPid) !== controlGroup) {
78
+ throw new Error(`Cannot verify daemon ownership by ${scope} unit ${unit}; service was not stopped`);
79
+ }
80
+ const command = fs.readFileSync(`/proc/${mainPid}/cmdline`, 'utf8').split('\0');
81
+ if (!command.includes('start') || !command.includes('--foreground')) {
82
+ throw new Error(`Unit ${unit} does not run start --foreground; automatic systemd restart is unsupported`);
83
+ }
84
+ assertIdentity(pid, startedAt);
85
+ return { scope, unit, controlGroup, invocationId: properties.InvocationID, mainPid, daemonPid: pid, daemonStartedAt: startedAt };
86
+ }
87
+ /** Persist ownership before submission: systemd can kill this caller before execFile resolves. */
88
+ export async function submitSystemdRestart(file, requestId, service) {
89
+ await withFileLock(`${file}.systemd.lock`, async () => {
90
+ const pending = readRestartRequest(file, requestId);
91
+ if (!pending || pending.status !== 'requested' || pending.backend) {
92
+ throw new Error('Restart request changed or was already submitted');
93
+ }
94
+ const current = await discoverSystemdService(service.daemonPid, service.daemonStartedAt);
95
+ if (!current || current.invocationId !== service.invocationId || current.unit !== service.unit
96
+ || current.scope !== service.scope || current.controlGroup !== service.controlGroup) {
97
+ throw new Error('Systemd ownership changed before restart submission');
98
+ }
99
+ if (!updateRestartRequest(file, requestId, {
100
+ backend: 'systemd', systemd: service, deadline: Date.now() + 120_000,
101
+ }))
102
+ throw new Error('Restart request changed before systemd submission');
103
+ try {
104
+ await execFileAsync('systemctl', [
105
+ ...scopeArgs(service.scope), '--no-ask-password', '--no-block', 'restart', '--', service.unit,
106
+ ], { encoding: 'utf8', timeout: 5_000, maxBuffer: 64 * 1024 });
107
+ updateRestartRequest(file, requestId, { status: 'accepted' });
108
+ }
109
+ catch (error) {
110
+ const reason = error instanceof Error ? error.message : String(error);
111
+ // A timeout can happen after the job was enqueued. Keep the durable
112
+ // binding so a replacement can still prove ready; forbid another restart.
113
+ const uncertain = error.killed === true;
114
+ updateRestartRequest(file, requestId, { ...(uncertain ? {} : { status: 'failed' }), reason });
115
+ throw error;
116
+ }
117
+ });
118
+ }
119
+ /** Called only after this daemon has written its own ready signal. */
120
+ export async function completeSystemdRestart(file) {
121
+ const pending = readRestartRequest(file);
122
+ if (pending?.backend !== 'systemd' || !pending.systemd
123
+ || !['requested', 'accepted'].includes(pending.status))
124
+ return false;
125
+ return withFileLock(`${file}.systemd.lock`, async () => {
126
+ const request = readRestartRequest(file, pending.requestId);
127
+ if (!request?.systemd || !['requested', 'accepted'].includes(request.status))
128
+ return false;
129
+ if (!await resumeSystemdRestart(file))
130
+ return false;
131
+ const startedAt = getProcessStartTime(process.pid, { fresh: true });
132
+ if (!startedAt)
133
+ return false;
134
+ return updateRestartRequest(file, request.requestId, {
135
+ status: 'ready', daemonPid: process.pid, daemonStartedAt: startedAt,
136
+ });
137
+ });
138
+ }
139
+ /** The foreground launcher must preserve pure-restart intent on the new invocation. */
140
+ export async function resumeSystemdRestart(file) {
141
+ const request = readRestartRequest(file);
142
+ if (request?.backend !== 'systemd' || !request.systemd
143
+ || !['requested', 'accepted'].includes(request.status))
144
+ return null;
145
+ const startedAt = getProcessStartTime(process.pid, { fresh: true });
146
+ if (!startedAt || startedAt <= request.systemd.daemonStartedAt)
147
+ return null;
148
+ const service = await discoverSystemdService(process.pid, startedAt);
149
+ if (!service || service.unit !== request.systemd.unit || service.scope !== request.systemd.scope
150
+ || service.controlGroup !== request.systemd.controlGroup
151
+ || service.invocationId === request.systemd.invocationId)
152
+ return null;
153
+ return request;
154
+ }
@@ -246,16 +246,20 @@ function cacheKey(filePath) {
246
246
  * the existing parser behavior; only Windows enters the Authenticode path.
247
247
  */
248
248
  export function isTrustedWindowsShellExecutable(executable, kind) {
249
- if (process.platform !== 'win32')
250
- return true;
251
249
  try {
252
- verifyWindowsShellExecutable(executable, kind);
250
+ requireTrustedWindowsShellExecutable(executable, kind);
253
251
  return true;
254
252
  }
255
253
  catch {
256
254
  return false;
257
255
  }
258
256
  }
257
+ /** Preserve the concrete failure for EC permission checks and CLI diagnostics. */
258
+ export function requireTrustedWindowsShellExecutable(executable, kind) {
259
+ if (process.platform !== 'win32')
260
+ return executable;
261
+ return verifyWindowsShellExecutable(executable, kind);
262
+ }
259
263
  function verifyWindowsShellExecutable(executable, kind) {
260
264
  const resolved = resolveShellPath(executable, kind);
261
265
  if (!resolved) {