evolcore 0.0.45 → 0.0.47

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +22 -6
  12. package/dist/agents/codex/app-server-client.js +34 -27
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/group/fs-download.js +1 -1
  18. package/dist/aun/menu/client.js +142 -182
  19. package/dist/aun/rpc/client.js +33 -17
  20. package/dist/aun/service-proxy.js +6 -23
  21. package/dist/channels/aun.js +675 -120
  22. package/dist/channels/daemon.js +1 -1
  23. package/dist/cli/agent-create.js +37 -10
  24. package/dist/cli/agent-template.js +105 -84
  25. package/dist/cli/agent.js +31 -18
  26. package/dist/cli/daemon-commands.js +42 -56
  27. package/dist/cli/daemon-lifecycle-client.js +55 -19
  28. package/dist/cli/directory.js +12 -4
  29. package/dist/cli/ecmsg-gateway.js +5 -2
  30. package/dist/cli/events-command.js +2 -1
  31. package/dist/cli/init-channel.js +2 -2
  32. package/dist/cli/init.js +57 -21
  33. package/dist/cli/integrity-command.js +2 -0
  34. package/dist/cli/managed-command-guard.js +20 -1
  35. package/dist/cli/menu-client.js +7 -5
  36. package/dist/cli/restart-monitor.js +135 -46
  37. package/dist/cli/services-command.js +28 -5
  38. package/dist/cli/task-context.js +83 -15
  39. package/dist/cli/upgrade-command.js +4 -2
  40. package/dist/config/config-field-policy.js +24 -0
  41. package/dist/config/config-manager.js +49 -19
  42. package/dist/config/peer-book-store.js +167 -127
  43. package/dist/config/peer-role-resolver.js +24 -4
  44. package/dist/config/provider-identity-migration.js +158 -6
  45. package/dist/config/provider-identity.js +10 -4
  46. package/dist/config/provider-ipc-service.js +10 -2
  47. package/dist/config/provider-local-sync.js +2 -2
  48. package/dist/config/providers-config.js +95 -10
  49. package/dist/config/providers-import.js +4 -6
  50. package/dist/config/providers.js +14 -3
  51. package/dist/config/role-store.js +1 -1
  52. package/dist/config/schema-migration.js +123 -16
  53. package/dist/config/schema-registry.js +6 -2
  54. package/dist/config-store.js +9 -1
  55. package/dist/core/agent-application-service.js +56 -29
  56. package/dist/core/agent-create-status.js +3 -1
  57. package/dist/core/agent-creation-claim.js +1 -0
  58. package/dist/core/agent-ipc-registration.js +2 -2
  59. package/dist/core/agent-reload-coordinator.js +38 -1
  60. package/dist/core/agent-runtime.js +91 -43
  61. package/dist/core/auth/agent-delegation.js +13 -3
  62. package/dist/core/auth/delegation-diagnostics.js +56 -15
  63. package/dist/core/auth/operation-authorizer.js +2 -2
  64. package/dist/core/auth/operation-catalog.js +3 -3
  65. package/dist/core/bootstrap-service.js +3 -0
  66. package/dist/core/capability/capability-manager.js +3 -1
  67. package/dist/core/channel-loader.js +29 -3
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-control.js +6 -5
  70. package/dist/core/command/agent-template-menu.js +32 -97
  71. package/dist/core/command/eventcenter-menu.js +61 -13
  72. package/dist/core/command/menu-catalog.js +11 -4
  73. package/dist/core/command/menu-handler.js +39 -12
  74. package/dist/core/command/menu-protocol.js +8 -16
  75. package/dist/core/command/skill-slash.js +6 -2
  76. package/dist/core/command/slash-handler.js +4 -6
  77. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  78. package/dist/core/command/team-workspace-management-store.js +83 -0
  79. package/dist/core/command/team-workspace-management.js +1 -2
  80. package/dist/core/command/team-workspace-team.js +26 -3
  81. package/dist/core/daemon-bootstrap.js +11 -9
  82. package/dist/core/daemon-control.js +4 -7
  83. package/dist/core/daemon-lifecycle.js +189 -143
  84. package/dist/core/evolagent-registry.js +50 -2
  85. package/dist/core/evolagent.js +2 -1
  86. package/dist/core/file-integrity/read.js +9 -16
  87. package/dist/core/file-integrity/store.js +94 -34
  88. package/dist/core/handoff/dispatcher.js +33 -7
  89. package/dist/core/handoff/runtime.js +8 -0
  90. package/dist/core/host-snapshot.js +9 -4
  91. package/dist/core/inference/text-inference.js +12 -2
  92. package/dist/core/initialization/service.js +22 -4
  93. package/dist/core/invoke/invoke-service.js +24 -3
  94. package/dist/core/ipc-registration.js +7 -3
  95. package/dist/core/memory/consolidation.js +6 -6
  96. package/dist/core/message/aun-ipc-sender.js +109 -7
  97. package/dist/core/message/contact-admission.js +6 -2
  98. package/dist/core/message/message-bridge.js +13 -0
  99. package/dist/core/message/message-queue.js +131 -30
  100. package/dist/core/message/pending-hints.js +8 -0
  101. package/dist/core/message/response-engine.js +48 -2
  102. package/dist/core/message/send-routing.js +3 -12
  103. package/dist/core/model/catalog-service.js +13 -0
  104. package/dist/core/model/model-catalog.js +57 -18
  105. package/dist/core/ownership/owner-resolver.js +27 -10
  106. package/dist/core/pack-auth.js +163 -31
  107. package/dist/core/pack-install.js +42 -1
  108. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  109. package/dist/core/permission/ec-command-parser.js +3 -1
  110. package/dist/core/permission/shell-environment.js +23 -0
  111. package/dist/core/rate-window.js +6 -1
  112. package/dist/core/relation/peer-identity.js +5 -1
  113. package/dist/core/relation/same-owner-proof.js +2 -1
  114. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  115. package/dist/core/session/session-file-health.js +36 -7
  116. package/dist/core/session/session-idle-monitor.js +0 -1
  117. package/dist/core/session/session-manager.js +14 -0
  118. package/dist/core/session/session-title.js +26 -6
  119. package/dist/core/skill/index-generator.js +3 -4
  120. package/dist/core/task/task-image-resources.js +1 -1
  121. package/dist/core/thread/thread-service.js +0 -1
  122. package/dist/core/thread/topic-id.js +8 -0
  123. package/dist/directory/owner-directory-admission.js +17 -0
  124. package/dist/directory/owner-directory-cache.js +3 -1
  125. package/dist/directory/owner-directory-markdown.js +145 -23
  126. package/dist/directory/owner-directory-policy.js +23 -0
  127. package/dist/directory/owner-directory-query-operation.js +20 -6
  128. package/dist/directory/owner-directory-search.js +47 -0
  129. package/dist/eck/message-renderer.js +171 -32
  130. package/dist/ecweb/basic-settings-service.js +7 -3
  131. package/dist/ecweb/providers-service.js +17 -10
  132. package/dist/ecweb/runtime/lifecycle.js +65 -16
  133. package/dist/ecweb/runtime/supervisor.js +79 -50
  134. package/dist/event-center/admission-materializer.js +1 -1
  135. package/dist/event-center/bus-gate.js +48 -4
  136. package/dist/event-center/bus-host.js +3 -3
  137. package/dist/event-center/center-config.js +57 -28
  138. package/dist/event-center/dispatcher.js +8 -0
  139. package/dist/event-center/event-log.js +69 -27
  140. package/dist/event-center/index-generator.js +6 -1
  141. package/dist/event-center/ipc-operation.js +66 -25
  142. package/dist/event-center/pack-loader.js +12 -55
  143. package/dist/event-center/pack-manager.js +5 -3
  144. package/dist/event-center/registry.js +48 -52
  145. package/dist/event-center/runtime.js +219 -81
  146. package/dist/event-center/script-runner.js +18 -7
  147. package/dist/event-center/types.js +9 -1
  148. package/dist/event-center/validation.js +33 -4
  149. package/dist/index.js +132 -75
  150. package/dist/ipc.js +35 -8
  151. package/dist/product.js +1 -0
  152. package/dist/proxy/manager.js +52 -11
  153. package/dist/proxy/service-supervisor.js +265 -67
  154. package/dist/services/dispatcher.js +26 -3
  155. package/dist/services/idempotency.js +128 -0
  156. package/dist/services/identity.js +3 -27
  157. package/dist/services/index-generator.js +5 -1
  158. package/dist/services/index.js +244 -45
  159. package/dist/services/ipc-operation.js +164 -20
  160. package/dist/services/pack-manager.js +37 -9
  161. package/dist/services/router.js +100 -31
  162. package/dist/services/script-runner.js +15 -4
  163. package/dist/services/service-payload.js +50 -2
  164. package/dist/services/validation.js +107 -3
  165. package/dist/trigger/scheduler.js +18 -4
  166. package/dist/trigger/script-sandbox.js +39 -2
  167. package/dist/trigger/state.js +7 -0
  168. package/dist/utils/aid-bind.js +155 -18
  169. package/dist/utils/atomic-write.js +3 -3
  170. package/dist/utils/cross-platform.js +59 -16
  171. package/dist/utils/error-utils.js +26 -1
  172. package/dist/utils/instance-registry.js +94 -35
  173. package/dist/utils/process-introspect.js +187 -27
  174. package/dist/utils/project-path.js +47 -3
  175. package/dist/utils/upgrade-jobs.js +4 -4
  176. package/dist/utils/windows-shell-trust.js +174 -68
  177. package/kits/docs/context-assembly.md +3 -3
  178. package/kits/docs/evolcore/agent.md +28 -10
  179. package/kits/docs/evolcore/aid.md +3 -1
  180. package/kits/docs/evolcore/config.md +22 -0
  181. package/kits/docs/evolcore/directory.md +46 -12
  182. package/kits/docs/evolcore/event-center.md +6 -6
  183. package/kits/docs/evolcore/group-collaboration.md +1 -1
  184. package/kits/docs/evolcore/menu-client.md +7 -5
  185. package/kits/docs/evolcore/menu-protocol.md +5 -3
  186. package/kits/docs/evolcore/msg.md +10 -3
  187. package/kits/docs/evolcore/provider.md +17 -5
  188. package/kits/docs/evolcore/services.md +145 -12
  189. package/kits/docs/evolcore/thread-chain.md +17 -9
  190. package/kits/docs/prompt-loading-architecture.md +4 -4
  191. package/kits/eck_message_manifest.json +46 -3
  192. package/kits/rules/04-relation.md +10 -2
  193. package/kits/rules/06-channel.md +2 -1
  194. package/kits/schemas/providers.schema.2.json +1 -0
  195. package/kits/skills/ec-group/SKILL.md +4 -0
  196. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  197. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  198. package/kits/skills/thread-ops/SKILL.md +8 -5
  199. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  200. package/kits/templates/message-fragments/group-batch.md +1 -0
  201. package/kits/templates/message-fragments/item-group.md +4 -0
  202. package/kits/templates/message-fragments/item-private.md +4 -0
  203. package/kits/templates/message-fragments/thread-context.md +1 -1
  204. package/kits/templates/system-fragments/commands.md +5 -5
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +11 -7
  207. package/package.json +3 -2
  208. package/scripts/agent-template/index.mjs +9 -4
  209. package/scripts/agent-template/inspect.mjs +16 -9
  210. package/scripts/agent-template/shared/plan.mjs +3 -33
  211. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  212. package/scripts/agent-template/shared/template-package.mjs +119 -10
  213. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  214. package/scripts/agent-template/shared/template.mjs +5 -5
  215. package/scripts/agent-template/team-pack.mjs +245 -0
  216. package/scripts/agent-template/team-preview.mjs +111 -0
  217. package/scripts/aid-batch/identity-batch.mjs +143 -0
  218. package/dist/ability/versions.js +0 -32
  219. package/dist/aun/model-headers.js +0 -17
  220. package/dist/channels/builtin-plugins.js +0 -19
  221. package/dist/core/command/team-workspace-initializer.js +0 -2
  222. package/dist/core/command/team-workspace-job-store.js +0 -88
  223. package/dist/core/command/team-workspace-management-service.js +0 -2
  224. package/dist/core/contact-bind-registry.js +0 -27
  225. package/dist/event-center/ledger.js +0 -52
  226. package/dist/services/reply.js +0 -55
  227. package/kits/templates/message-fragments/item.md +0 -3
  228. package/scripts/agent-template/pack.mjs +0 -169
@@ -7,9 +7,13 @@
7
7
  * killing the wrong process).
8
8
  */
9
9
  import fs from 'fs';
10
+ import os from 'os';
11
+ import path from 'path';
10
12
  import { execFile, spawnSync } from 'child_process';
11
13
  const isWindows = process.platform === 'win32';
12
14
  const isMacOS = process.platform === 'darwin';
15
+ // ps localizes weekday/month names; Date.parse requires the C locale here.
16
+ const C_LOCALE_ENV = { LC_ALL: 'C', LANG: 'C' };
13
17
  function readLinuxClockTicks() {
14
18
  if (process.platform !== 'linux')
15
19
  return 100;
@@ -46,39 +50,45 @@ function approximateSelfStartTime() {
46
50
  /**
47
51
  * 身份校验路径上同一个 PID 会被连着查两三次(`sameProcess()` 在优雅停止前后各查一次,
48
52
  * 端口候选还要再查一次),Windows 上每次都是一整个 PowerShell 进程(约 0.5–1s)。
49
- * 启动时间对同一个 PID 是常量,缓存复用没有语义风险;PID 复用要落到同一个缓存槽里
50
- * 需要在一个 TTL 内退出并复刻出同一个 PID,实际不可能,且 `startTimeMatches` 本身
51
- * 有 2s 容差。TTL 取短一些,避免让「进程已换人」的判断比容差更迟钝。
53
+ * 普通观测短时复用缓存。终止进程前必须传 fresh,避免 PID 在缓存期内被其他进程复用。
52
54
  */
53
55
  const START_TIME_CACHE_TTL_MS = 5000;
54
56
  const startTimeCache = new Map();
55
57
  const startTimeQueries = new Map();
56
58
  /** Daemon lifecycle queries must not block IPC, probes or startup timers. */
57
- export async function getProcessStartTimeAsync(pid) {
59
+ export async function getProcessStartTimeAsync(pid, options = {}) {
58
60
  if (!Number.isInteger(pid) || pid <= 0)
59
61
  return null;
60
62
  if (pid === process.pid)
61
63
  return getProcessStartTime(pid);
62
- const cached = startTimeCache.get(pid);
63
- if (cached && Date.now() - cached.at < START_TIME_CACHE_TTL_MS)
64
- return cached.startedAt;
65
- const pending = startTimeQueries.get(pid);
66
- if (pending)
67
- return pending;
64
+ if (!options.fresh) {
65
+ const cached = startTimeCache.get(pid);
66
+ if (cached && Date.now() - cached.at < START_TIME_CACHE_TTL_MS)
67
+ return cached.startedAt;
68
+ const pending = startTimeQueries.get(pid);
69
+ if (pending)
70
+ return pending;
71
+ }
72
+ else {
73
+ startTimeCache.delete(pid);
74
+ }
68
75
  const query = (async () => {
69
76
  let startedAt;
70
77
  if (isWindows) {
71
- const output = await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command',
72
- `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToUniversalTime().ToString('o')`], 8000);
73
- startedAt = parseCimDate(output) ?? parseDateString(output);
78
+ startedAt = await readWindowsStartTimeAsync(pid);
74
79
  if (startedAt === null) {
75
- const fallback = await processQuery('wmic', ['process', 'where', `ProcessId=${pid}`, 'get', 'CreationDate', '/value'], 5000);
76
- const creation = fallback.match(/CreationDate=([^\r\n]+)/)?.[1]?.trim();
77
- startedAt = creation ? parseCimDate(creation) ?? parseDateString(creation) : null;
80
+ const output = await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command',
81
+ `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToUniversalTime().ToString('o')`], 8000);
82
+ startedAt = parseCimDate(output) ?? parseDateString(output);
83
+ if (startedAt === null) {
84
+ const fallback = await processQuery('wmic', ['process', 'where', `ProcessId=${pid}`, 'get', 'CreationDate', '/value'], 5000);
85
+ const creation = fallback.match(/CreationDate=([^\r\n]+)/)?.[1]?.trim();
86
+ startedAt = creation ? parseCimDate(creation) ?? parseDateString(creation) : null;
87
+ }
78
88
  }
79
89
  }
80
90
  else if (isMacOS) {
81
- startedAt = parseDateString(await processQuery('ps', ['-p', String(pid), '-o', 'lstart='], 5000));
91
+ startedAt = parseDateString(await processQuery('ps', ['-p', String(pid), '-o', 'lstart='], 5000, { ...process.env, ...C_LOCALE_ENV }));
82
92
  }
83
93
  else {
84
94
  startedAt = getStartTimeLinux(pid);
@@ -93,24 +103,28 @@ export async function getProcessStartTimeAsync(pid) {
93
103
  startedAt = null;
94
104
  }
95
105
  }
96
- if (startedAt === null)
97
- startTimeCache.delete(pid);
98
- else
99
- startTimeCache.set(pid, { at: Date.now(), startedAt });
100
106
  return startedAt;
101
107
  })();
102
108
  startTimeQueries.set(pid, query);
103
109
  try {
104
- return await query;
110
+ const startedAt = await query;
111
+ // An older lookup must not overwrite a newer, explicitly refreshed result.
112
+ if (startTimeQueries.get(pid) === query) {
113
+ if (startedAt === null)
114
+ startTimeCache.delete(pid);
115
+ else
116
+ startTimeCache.set(pid, { at: Date.now(), startedAt });
117
+ }
118
+ return startedAt;
105
119
  }
106
120
  finally {
107
121
  if (startTimeQueries.get(pid) === query)
108
122
  startTimeQueries.delete(pid);
109
123
  }
110
124
  }
111
- function processQuery(command, args, timeout) {
125
+ function processQuery(command, args, timeout, env) {
112
126
  return new Promise(resolve => {
113
- execFile(command, args, { encoding: 'utf8', timeout, windowsHide: true }, (error, stdout) => {
127
+ execFile(command, args, { encoding: 'utf8', timeout, windowsHide: true, env }, (error, stdout) => {
114
128
  resolve(error ? '' : stdout.replace(/^\uFEFF/, '').trim());
115
129
  });
116
130
  });
@@ -119,16 +133,20 @@ function processQuery(command, args, timeout) {
119
133
  * 获取进程启动时间(Unix 毫秒)。
120
134
  * 拿不到时返回 null,调用方应保守处理(不杀该 PID)。
121
135
  */
122
- export function getProcessStartTime(pid) {
136
+ export function getProcessStartTime(pid, options = {}) {
123
137
  if (pid === process.pid) {
124
138
  // 自身不查 CIM:近似值已在容差内,省掉一次 PowerShell 进程启动。
125
139
  if (selfStartTime === null)
126
140
  selfStartTime = approximateSelfStartTime();
127
141
  return selfStartTime;
128
142
  }
143
+ if (options.fresh) {
144
+ startTimeCache.delete(pid);
145
+ startTimeQueries.delete(pid);
146
+ }
129
147
  const cached = startTimeCache.get(pid);
130
148
  const now = Date.now();
131
- if (cached && now - cached.at < START_TIME_CACHE_TTL_MS)
149
+ if (!options.fresh && cached && now - cached.at < START_TIME_CACHE_TTL_MS)
132
150
  return cached.startedAt;
133
151
  const startedAt = readProcessStartTime(pid);
134
152
  // 只缓存成功结果:查不到往往是权限或瞬时失败,缓存成 null 会掩盖后续可查到的情形。
@@ -142,6 +160,7 @@ export function getProcessStartTime(pid) {
142
160
  export function resetSelfStartTimeCache() {
143
161
  selfStartTime = null;
144
162
  startTimeCache.clear();
163
+ startTimeQueries.clear();
145
164
  }
146
165
  function readProcessStartTime(pid) {
147
166
  try {
@@ -207,6 +226,7 @@ function getStartTimeMacOS(pid) {
207
226
  encoding: 'utf-8',
208
227
  timeout: 5000,
209
228
  stdio: ['pipe', 'pipe', 'pipe'],
229
+ env: { ...process.env, ...C_LOCALE_ENV },
210
230
  });
211
231
  const out = result.stdout?.trim();
212
232
  if (!out)
@@ -216,6 +236,30 @@ function getStartTimeMacOS(pid) {
216
236
  }
217
237
  // ── Windows ──
218
238
  function getStartTimeWindows(pid) {
239
+ const query = createWindowsSnapshotQuery(pid);
240
+ if (query) {
241
+ try {
242
+ const result = spawnSync(query.command, query.args, {
243
+ encoding: 'utf8', timeout: 2000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'],
244
+ });
245
+ const startedAt = parseWindowsPidStartTime(result.status === 0 ? result.stdout || '' : '', pid);
246
+ if (startedAt !== null) {
247
+ // The queried child may have exited before WMI returned its row.
248
+ try {
249
+ process.kill(pid, 0);
250
+ }
251
+ catch (error) {
252
+ if (error.code !== 'EPERM')
253
+ return null;
254
+ }
255
+ return startedAt;
256
+ }
257
+ }
258
+ catch { /* Retain the legacy transports if the script host cannot run. */ }
259
+ finally {
260
+ query.dispose();
261
+ }
262
+ }
219
263
  const fromPwsh = winPowerShellCreationDate(pid);
220
264
  if (fromPwsh !== null)
221
265
  return fromPwsh;
@@ -279,7 +323,7 @@ export async function getProcessSnapshotAsync(options = {}) {
279
323
  const generation = snapshotGeneration;
280
324
  const query = (async () => {
281
325
  const snapshot = isWindows
282
- ? parseWindowsSnapshot(await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], 8000))
326
+ ? await readWindowsSnapshotAsync()
283
327
  ?? { complete: false, startedAt: new Map(), commandLines: new Map() }
284
328
  : readProcessSnapshot();
285
329
  if (generation === snapshotGeneration)
@@ -314,7 +358,123 @@ function readProcessSnapshot() {
314
358
  return { complete: false, startedAt: new Map(), commandLines: new Map() };
315
359
  }
316
360
  const WINDOWS_SNAPSHOT_SCRIPT = 'Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | ConvertTo-Json -Compress';
361
+ // Query the same WMI provider without loading PowerShell and its CIM module.
362
+ // ASCII JSON escapes preserve command lines regardless of the host code page.
363
+ const WINDOWS_WMI_SNAPSHOT_SCRIPT = String.raw `
364
+ function text(value) {
365
+ return '"' + String(value).replace(/[\\"\u0000-\u001f\u007f-\uffff]/g, function (ch) {
366
+ return '\\u' + ('0000' + ch.charCodeAt(0).toString(16)).slice(-4);
367
+ }) + '"';
368
+ }
369
+ var service = GetObject('winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2');
370
+ var query = 'SELECT ProcessId,CreationDate,CommandLine FROM Win32_Process';
371
+ if (WScript.Arguments.length) query += ' WHERE ProcessId=' + Number(WScript.Arguments(0));
372
+ var processes = new Enumerator(service.ExecQuery(query));
373
+ var rows = [];
374
+ for (; !processes.atEnd(); processes.moveNext()) {
375
+ var item = processes.item();
376
+ rows.push('{"ProcessId":' + Number(item.ProcessId)
377
+ + ',"CreationDate":' + (item.CreationDate == null ? 'null' : text(item.CreationDate))
378
+ + ',"CommandLine":' + (item.CommandLine == null ? 'null' : text(item.CommandLine)) + '}');
379
+ }
380
+ WScript.Echo('[' + rows.join(',') + ']');
381
+ `;
382
+ let windowsWmiScriptAvailable = true;
383
+ function createWindowsSnapshotQuery(pid) {
384
+ if (!windowsWmiScriptAvailable)
385
+ return null;
386
+ let directory;
387
+ let file;
388
+ const dispose = () => {
389
+ // Remove only the two entries created here; never recursively remove a temp root.
390
+ if (file) {
391
+ try {
392
+ fs.unlinkSync(file);
393
+ }
394
+ catch { }
395
+ }
396
+ if (directory) {
397
+ try {
398
+ fs.rmdirSync(directory);
399
+ }
400
+ catch { }
401
+ }
402
+ };
403
+ try {
404
+ const command = path.join(process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows', 'System32', 'cscript.exe');
405
+ if (!fs.existsSync(command)) {
406
+ windowsWmiScriptAvailable = false;
407
+ return null;
408
+ }
409
+ directory = fs.mkdtempSync(path.join(os.tmpdir(), 'evolcore-process-snapshot-'));
410
+ file = path.join(directory, 'snapshot.js');
411
+ fs.writeFileSync(file, WINDOWS_WMI_SNAPSHOT_SCRIPT, { flag: 'wx', mode: 0o600 });
412
+ return { command, args: ['//Nologo', '//E:JScript', file, ...(pid === undefined ? [] : [String(pid)])], dispose };
413
+ }
414
+ catch {
415
+ windowsWmiScriptAvailable = false;
416
+ dispose();
417
+ return null;
418
+ }
419
+ }
420
+ /** Query the same creation-time provider without starting PowerShell for every PID. */
421
+ async function readWindowsStartTimeAsync(pid) {
422
+ const query = createWindowsSnapshotQuery(pid);
423
+ if (!query)
424
+ return null;
425
+ try {
426
+ return parseWindowsPidStartTime(await processQuery(query.command, query.args, 2000), pid);
427
+ }
428
+ finally {
429
+ query.dispose();
430
+ }
431
+ }
432
+ /** Both identity entry points accept only the exact requested PID. */
433
+ function parseWindowsPidStartTime(output, pid) {
434
+ const snapshot = parseWindowsSnapshot(output);
435
+ if (!snapshot || snapshot.pids?.size !== 1 || !snapshot.pids.has(pid)) {
436
+ // An empty selection can be an exited PID; unusable output keeps fallbacks.
437
+ if (!snapshot || snapshot.pids?.size)
438
+ windowsWmiScriptAvailable = false;
439
+ return null;
440
+ }
441
+ return snapshot.startedAt.get(pid) ?? null;
442
+ }
443
+ function parseWindowsWmiSnapshot(output) {
444
+ const snapshot = parseWindowsSnapshot(output);
445
+ // An empty/truncated successful response cannot prove that other PIDs exited.
446
+ if (snapshot?.pids?.has(process.pid))
447
+ return snapshot;
448
+ windowsWmiScriptAvailable = false;
449
+ return null;
450
+ }
451
+ async function readWindowsSnapshotAsync() {
452
+ const query = createWindowsSnapshotQuery();
453
+ if (query) {
454
+ try {
455
+ const snapshot = parseWindowsWmiSnapshot(await processQuery(query.command, query.args, 2000));
456
+ if (snapshot)
457
+ return snapshot;
458
+ }
459
+ finally {
460
+ query.dispose();
461
+ }
462
+ }
463
+ return parseWindowsSnapshot(await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], 8000));
464
+ }
317
465
  function readWindowsSnapshot() {
466
+ const query = createWindowsSnapshotQuery();
467
+ if (query) {
468
+ try {
469
+ const result = spawnSync(query.command, query.args, { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
470
+ const snapshot = parseWindowsWmiSnapshot(result.status === 0 ? result.stdout || '' : '');
471
+ if (snapshot)
472
+ return snapshot;
473
+ }
474
+ finally {
475
+ query.dispose();
476
+ }
477
+ }
318
478
  const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], { encoding: 'utf-8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
319
479
  return result.status === 0 ? parseWindowsSnapshot(result.stdout || '') : null;
320
480
  }
@@ -1,6 +1,52 @@
1
1
  import fs from 'fs';
2
2
  import os from 'os';
3
3
  import path from 'path';
4
+ const PROJECT_ENV_REFERENCE = /\$(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)\})/gu;
5
+ const PROJECT_ENV_SYNTAX = /\$\{|\$ENV:|\$[A-Za-z_][A-Za-z0-9_]*/u;
6
+ /** Configuration reads preserve references; only path consumers resolve them. */
7
+ export function hasProjectPathEnvironmentReference(value) {
8
+ return value.search(PROJECT_ENV_REFERENCE) !== -1;
9
+ }
10
+ export function assertProjectPathReference(value) {
11
+ const literal = value.replace(PROJECT_ENV_REFERENCE, '');
12
+ if (/\$ENV:/u.test(value) || /\$\{/u.test(literal)) {
13
+ throw Object.assign(new Error('projects.defaultPath supports only $VAR or ${VAR} environment references'), {
14
+ code: 'INVALID_ARGUMENT',
15
+ });
16
+ }
17
+ }
18
+ /** Validate stored syntax without requiring the deployment environment to exist. */
19
+ export function assertProjectPathConfig(value, options = {}) {
20
+ assertProjectPathReference(value);
21
+ if (!hasProjectPathEnvironmentReference(value) && !pathForPlatform(options.platform ?? process.platform).isAbsolute(value)) {
22
+ throw new Error('projects.defaultPath must be an absolute path or use environment references');
23
+ }
24
+ }
25
+ export function resolveProjectDefaultPath(value, options = {}) {
26
+ if (!value)
27
+ return value;
28
+ assertProjectPathReference(value);
29
+ // Keep existing literal paths and omitted-path fallbacks unchanged.
30
+ if (!hasProjectPathEnvironmentReference(value))
31
+ return value;
32
+ const resolved = value.replace(PROJECT_ENV_REFERENCE, (_match, plain, braced) => {
33
+ const variable = (plain || braced);
34
+ const replacement = process.env[variable]?.trim();
35
+ if (!replacement) {
36
+ throw Object.assign(new Error(`projects.defaultPath references unset or empty environment variable ${variable}`), {
37
+ code: 'INVALID_ARGUMENT',
38
+ });
39
+ }
40
+ return replacement;
41
+ });
42
+ if (PROJECT_ENV_SYNTAX.test(resolved) || resolved.includes('\0')
43
+ || !pathForPlatform(options.platform ?? process.platform).isAbsolute(resolved)) {
44
+ throw Object.assign(new Error('projects.defaultPath must resolve to an absolute path without nested environment references'), {
45
+ code: 'INVALID_ARGUMENT',
46
+ });
47
+ }
48
+ return resolved;
49
+ }
4
50
  function pathForPlatform(platform) {
5
51
  return platform === 'win32' ? path.win32 : path.posix;
6
52
  }
@@ -51,9 +97,7 @@ export function defaultProjectsRoot(evolcoreRoot, options = {}) {
51
97
  return pathImpl.join(evolcoreRoot, 'projects');
52
98
  }
53
99
  export function agentProjectRootFromDefaults(defaults, evolcoreRoot, options = {}) {
54
- const platform = options.platform ?? process.platform;
55
- const pathImpl = pathForPlatform(platform);
56
- const configuredRoot = defaults?.projects?.defaultPath
100
+ const configuredRoot = resolveProjectDefaultPath(defaults?.projects?.defaultPath, options)
57
101
  || defaultProjectsRoot(evolcoreRoot, options);
58
102
  return sanitizeProjectRoot(configuredRoot, options);
59
103
  }
@@ -7,7 +7,7 @@ import { AGENT_DELEGATION_TOKEN_ENV } from '../core/auth/agent-delegation.js';
7
7
  import { atomicWriteJson, withFileLock } from './atomic-write.js';
8
8
  import { comparePackageVersions, isLinkedInstall, preparePackageCache } from './npm-ops.js';
9
9
  import { isProcessRunning, launchMonitorAndConfirm, resolveCliEntry } from './cross-platform.js';
10
- import { scanInstances } from './instance-registry.js';
10
+ import { hasLiveRestartMonitor, scanInstances } from './instance-registry.js';
11
11
  import { createRestartRequest, readRestartRequest, removeRestartRequest, shouldSuppressRealRestart, updateRestartRequest } from './restart-safety.js';
12
12
  import { isPackageVersionInfoFresh, refreshManagedPackageVersions, resolveUpgradeDistTag, resolveVersionInfoPackage, VERSION_INFO_PACKAGES } from './package-version-info.js';
13
13
  import { loadDaemonConfig } from '../config-store.js';
@@ -236,7 +236,7 @@ function jobs() {
236
236
  }
237
237
  /** Called under active.lock; never start another job during monitor handoff. */
238
238
  function reconcileUpgradeJobs(existing) {
239
- const monitors = scanInstances().restartMonitors.filter(item => item.alive);
239
+ const monitors = scanInstances({ kind: 'restart-monitor', includeAidActivity: false }).restartMonitors.filter(item => item.alive);
240
240
  for (const job of existing.sort((left, right) => right.createdAt - left.createdAt)) {
241
241
  const liveMonitor = !!job.monitorPid && isProcessRunning(job.monitorPid);
242
242
  const liveLauncher = !!job.launcherPid && isProcessRunning(job.launcherPid);
@@ -283,7 +283,7 @@ export async function startUpgradeJob(requestId, scope, options = {}) {
283
283
  const active = reconcileUpgradeJobs(existing);
284
284
  if (active)
285
285
  return { job: active, reused: true };
286
- if (scanInstances().restartMonitors.some(item => item.alive)) {
286
+ if (scanInstances({ kind: 'restart-monitor', includeAidActivity: false }).restartMonitors.some(item => item.alive)) {
287
287
  throw Object.assign(new Error('A restart transaction is still running'), { code: 'CONFLICT' });
288
288
  }
289
289
  const now = Date.now();
@@ -385,7 +385,7 @@ async function runUpgradeJob(job) {
385
385
  }, () => false, {
386
386
  requestId, timeoutMs: 8_000, logFilePath: path.join(resolvePaths().logs, `restart-launch-${requestId}.log`),
387
387
  onSpawn: pid => { updateRestartRequest(pending, requestId, { launcherPid: pid }); updateUpgradeJob(job.jobId, { launcherPid: pid }); },
388
- isPendingInRegistry: () => scanInstances().restartMonitors.some(item => item.alive && item.record.requestId === requestId),
388
+ isPendingInRegistry: () => hasLiveRestartMonitor({ requestId }),
389
389
  });
390
390
  handedOff = launch.ok || launch.pending === true;
391
391
  if (!handedOff) {