evolcore 0.0.43-test.4 → 0.0.43-test.6

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 (186) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ecmsg.js +437 -91
  3. package/dist/agents/baseagent-availability.js +19 -4
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +14 -3
  7. package/dist/agents/codex-runner.js +18 -23
  8. package/dist/aun/aid/agentmd.js +25 -0
  9. package/dist/aun/aid/control-aid.js +15 -0
  10. package/dist/aun/aid/identity.js +8 -0
  11. package/dist/aun/aid/ownership-operation.js +12 -3
  12. package/dist/aun/group/invite-service.js +3 -2
  13. package/dist/aun/service-proxy.js +18 -6
  14. package/dist/channels/aun.js +99 -23
  15. package/dist/channels/daemon.js +2 -2
  16. package/dist/cli/agent-create.js +19 -7
  17. package/dist/cli/aid-bind-command.js +3 -0
  18. package/dist/cli/aun-commands.js +19 -4
  19. package/dist/cli/code-stats.js +451 -213
  20. package/dist/cli/ctl-command.js +1 -3
  21. package/dist/cli/daemon-commands.js +42 -4
  22. package/dist/cli/directory.js +3 -1
  23. package/dist/cli/ecmsg-gateway.js +206 -0
  24. package/dist/cli/index.js +6 -0
  25. package/dist/cli/init.js +120 -13
  26. package/dist/cli/provider-command.js +82 -5
  27. package/dist/cli/restart-monitor.js +35 -24
  28. package/dist/cli/stats.js +8 -1
  29. package/dist/cli/task-context.js +41 -1
  30. package/dist/cli/watch-logs.js +6 -4
  31. package/dist/config/boot-log.js +16 -3
  32. package/dist/config/builtin-roles.js +2 -2
  33. package/dist/config/config-manager.js +5 -14
  34. package/dist/config/daemon-services.js +1 -0
  35. package/dist/config/peer-role-resolver.js +6 -6
  36. package/dist/config/provider-identity-migration.js +277 -0
  37. package/dist/config/provider-identity.js +37 -0
  38. package/dist/config/provider-ipc-service.js +40 -3
  39. package/dist/config/provider-local-sync.js +155 -0
  40. package/dist/config/providers-config.js +45 -4
  41. package/dist/config/providers-management.js +242 -76
  42. package/dist/config/providers.js +4 -1
  43. package/dist/config/role-service.js +8 -8
  44. package/dist/config/role-store.js +22 -22
  45. package/dist/config/schema-migration.js +143 -86
  46. package/dist/config/snapshot.js +70 -41
  47. package/dist/core/agent-runtime.js +48 -9
  48. package/dist/core/auth/auth-gateway.js +5 -3
  49. package/dist/core/auth/delegation-diagnostics.js +6 -2
  50. package/dist/core/auth/operation-authorizer.js +3 -1
  51. package/dist/core/auth/operation-catalog.js +6 -4
  52. package/dist/core/baseagent-loader.js +114 -11
  53. package/dist/core/channel-loader.js +36 -13
  54. package/dist/core/channel-runtime.js +112 -42
  55. package/dist/core/command/cli-intent-parser.js +2 -1
  56. package/dist/core/command/command-handler.js +16 -11
  57. package/dist/core/command/menu-handler.js +8 -3
  58. package/dist/core/command/menu-protocol.js +80 -7
  59. package/dist/core/command/provider-menu.js +4 -2
  60. package/dist/core/command/role-menu.js +29 -17
  61. package/dist/core/command/slash-handler.js +52 -16
  62. package/dist/core/daemon-control.js +42 -15
  63. package/dist/core/daemon-lifecycle.js +411 -67
  64. package/dist/core/handoff/dispatcher.js +9 -3
  65. package/dist/core/handoff/runtime.js +139 -45
  66. package/dist/core/handoff/store.js +190 -2
  67. package/dist/core/handoff/types.js +5 -0
  68. package/dist/core/initialization/service.js +7 -6
  69. package/dist/core/ipc-registration.js +5 -4
  70. package/dist/core/lifecycle-notice.js +10 -4
  71. package/dist/core/message/aun-ipc-sender.js +83 -5
  72. package/dist/core/message/message-admission.js +2 -0
  73. package/dist/core/message/message-bridge.js +53 -4
  74. package/dist/core/message/message-queue.js +46 -4
  75. package/dist/core/message/pending-hints.js +4 -10
  76. package/dist/core/message/response-engine.js +33 -25
  77. package/dist/core/message/send-options.js +40 -0
  78. package/dist/core/message/send-routing.js +320 -0
  79. package/dist/core/ownership/owner-resolver.js +112 -8
  80. package/dist/core/permission/ec-command-parser.js +159 -16
  81. package/dist/core/permission/readonly-shell-query.js +66 -7
  82. package/dist/core/permission/tool-error-code.js +13 -1
  83. package/dist/core/permission/tool-policy.js +74 -20
  84. package/dist/core/relation/same-owner-proof.js +131 -0
  85. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  86. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  87. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  88. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  89. package/dist/core/session/session-fs-store.js +164 -3
  90. package/dist/core/session/session-idle-monitor.js +103 -17
  91. package/dist/core/session/session-manager.js +105 -18
  92. package/dist/core/thread/thread-route.js +5 -2
  93. package/dist/directory/owner-directory-admission.js +26 -1
  94. package/dist/directory/owner-directory-cache.js +739 -109
  95. package/dist/directory/owner-directory-markdown.js +146 -36
  96. package/dist/directory/owner-directory-query-operation.js +6 -3
  97. package/dist/directory/owner-directory-scope.js +12 -0
  98. package/dist/directory/owner-directory-search.js +5 -1
  99. package/dist/directory/owner-directory-store.js +28 -0
  100. package/dist/ecweb/basic-settings-service.js +15 -1
  101. package/dist/ecweb/message-context-service.js +2 -2
  102. package/dist/ecweb/providers-service.js +3 -1
  103. package/dist/ecweb/runtime/lifecycle.js +26 -15
  104. package/dist/ecweb/runtime/supervisor.js +120 -51
  105. package/dist/index.js +551 -250
  106. package/dist/paths.js +2 -1
  107. package/dist/proxy/manager.js +40 -17
  108. package/dist/proxy/service-supervisor.js +67 -33
  109. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  110. package/dist/trigger/application-service.js +4 -1
  111. package/dist/trigger/audit.js +19 -4
  112. package/dist/trigger/authorization.js +14 -5
  113. package/dist/trigger/event-source.js +4 -0
  114. package/dist/trigger/feedback.js +26 -2
  115. package/dist/trigger/history.js +176 -7
  116. package/dist/trigger/manager.js +1 -3
  117. package/dist/trigger/scheduler.js +81 -8
  118. package/dist/trigger/system-definitions.js +2 -2
  119. package/dist/trigger/validation.js +4 -0
  120. package/dist/utils/autostart.js +2 -2
  121. package/dist/utils/cross-platform.js +188 -12
  122. package/dist/utils/host-info.js +11 -8
  123. package/dist/utils/npm-ops.js +48 -0
  124. package/dist/utils/process-introspect.js +64 -1
  125. package/dist/utils/public-suffix.js +5811 -0
  126. package/dist/utils/startup-trace.js +160 -19
  127. package/dist/utils/windows-autostart.js +41 -7
  128. package/ecagent/dist/harness/env/nodejs.js +46 -2
  129. package/kits/docs/aun/ABILITY_CALLING.md +6 -6
  130. package/kits/docs/channels/aun.md +1 -1
  131. package/kits/docs/channels/feishu.md +2 -2
  132. package/kits/docs/context-assembly.md +20 -4
  133. package/kits/docs/evolcore/INDEX.md +5 -3
  134. package/kits/docs/evolcore/agent.md +2 -2
  135. package/kits/docs/evolcore/aid.md +8 -2
  136. package/kits/docs/evolcore/ctl.md +15 -5
  137. package/kits/docs/evolcore/directory.md +48 -15
  138. package/kits/docs/evolcore/group.md +8 -8
  139. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  140. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  141. package/kits/docs/evolcore/menu-protocol.md +32 -3
  142. package/kits/docs/evolcore/msg.md +38 -30
  143. package/kits/docs/evolcore/provider.md +57 -5
  144. package/kits/docs/evolcore/response.md +2 -2
  145. package/kits/docs/evolcore/thread-chain.md +11 -13
  146. package/kits/docs/evolcore/tool-authorization.md +17 -0
  147. package/kits/docs/evolcore/trigger.md +2 -2
  148. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  149. package/kits/docs/prompt-loading-architecture.md +30 -20
  150. package/kits/eck_manifest.auxiliary.json +5 -5
  151. package/kits/eck_manifest.json +44 -32
  152. package/kits/eck_manifest.memory.json +18 -18
  153. package/kits/eck_message_manifest.json +3 -3
  154. package/kits/rules/01-overview.md +1 -1
  155. package/kits/rules/06-channel.md +7 -8
  156. package/kits/schemas/_meta.json +7 -1
  157. package/kits/schemas/daemon.schema.1.json +5 -0
  158. package/kits/schemas/daemon.schema.2.json +5 -0
  159. package/kits/schemas/daemon.schema.3.json +2 -1
  160. package/kits/schemas/daemon.schema.4.json +2 -1
  161. package/kits/schemas/daemon.schema.5.json +2 -1
  162. package/kits/schemas/daemon.schema.6.json +1 -1
  163. package/kits/schemas/daemon.schema.7.json +1 -1
  164. package/kits/schemas/daemon.schema.8.json +2 -1
  165. package/kits/schemas/daemon.schema.9.json +2 -1
  166. package/kits/schemas/providers.schema.2.json +74 -0
  167. package/kits/schemas/role-registry.schema.1.json +2 -2
  168. package/kits/schemas/single-session.schema.1.json +1 -1
  169. package/kits/schemas/single-session.schema.2.json +1 -1
  170. package/kits/schemas/single-session.schema.3.json +1 -1
  171. package/kits/skills/aid-ability/SKILL.md +7 -7
  172. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  173. package/kits/skills/ec-group/SKILL.md +8 -5
  174. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  175. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  176. package/kits/skills/ec-trigger/SKILL.md +9 -9
  177. package/kits/skills/ec-trigger/references/examples.md +1 -1
  178. package/kits/skills/thread-ops/SKILL.md +10 -10
  179. package/kits/templates/system-fragments/channel.md +5 -5
  180. package/kits/templates/system-fragments/commands.md +7 -6
  181. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  182. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  183. package/kits/templates/system-fragments/reply.md +48 -28
  184. package/kits/templates/system-fragments/session.md +3 -10
  185. package/kits/templates/system-fragments/thread.md +5 -5
  186. package/package.json +4 -4
@@ -8,6 +8,8 @@ import { getProcessStartTime, parseCimDate } from './process-introspect.js';
8
8
  import { resolveTrustedWindowsCmdPath } from './windows-shell-trust.js';
9
9
  const execFileAsync = promisify(execFile);
10
10
  const CLI_PROBE_FAILURE_BACKOFF_MS = 5_000;
11
+ export const CODEX_CLI_PROBE_TIMEOUT_MS = 9_000;
12
+ export const CODEX_CLI_PROBE_RETRY_TIMEOUT_MS = 15_000;
11
13
  const CLI_PROBE_PACKAGES = {
12
14
  codex: '@openai/codex',
13
15
  claude: '@anthropic-ai/claude-code',
@@ -184,18 +186,57 @@ export function invalidateCliProbes() {
184
186
  cliProbeCache.clear();
185
187
  }
186
188
  function cliProbeTimeouts(command, options) {
187
- return options.timeouts?.length ? options.timeouts : command === 'codex' ? [3_000, 15_000] : [3_000];
189
+ return options.timeouts?.length ? options.timeouts : command === 'codex'
190
+ ? [CODEX_CLI_PROBE_TIMEOUT_MS, CODEX_CLI_PROBE_RETRY_TIMEOUT_MS] : [3_000];
191
+ }
192
+ /** The stock npm shim adds cmd + node before Codex, outside a reliable Windows timeout. */
193
+ function codexProbeExecutable(executable) {
194
+ if (!isWindows || !/\.(?:cmd|bat)$/i.test(executable))
195
+ return executable;
196
+ try {
197
+ const shim = fs.readFileSync(executable, 'utf8');
198
+ // Preserve custom launchers. Only the stock npm entry for this installation
199
+ // may be shortened for read-only --version/app-server --help probes.
200
+ if (!/^@ECHO off\r?\nGOTO start\r?\n/i.test(shim)
201
+ || !shim.includes('%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js'))
202
+ return executable;
203
+ const packageFile = path.join(path.dirname(executable), 'node_modules', '@openai', 'codex', 'package.json');
204
+ const manifest = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
205
+ if (manifest.name !== '@openai/codex' || manifest.bin?.codex !== 'bin/codex.js')
206
+ return executable;
207
+ const arch = process.arch === 'x64' ? 'x86_64' : process.arch === 'arm64' ? 'aarch64' : null;
208
+ if (!arch)
209
+ return executable;
210
+ let vendorRoot;
211
+ try {
212
+ const platformFile = createRequire(packageFile).resolve(`@openai/codex-win32-${process.arch}/package.json`);
213
+ vendorRoot = path.join(path.dirname(platformFile), 'vendor');
214
+ }
215
+ catch {
216
+ vendorRoot = path.join(path.dirname(packageFile), 'vendor');
217
+ }
218
+ const binary = path.join(vendorRoot, `${arch}-pc-windows-msvc`, 'bin', 'codex.exe');
219
+ if (fs.statSync(binary).isFile())
220
+ return binary;
221
+ }
222
+ catch { /* Incomplete or non-npm installations retain their configured entrypoint. */ }
223
+ return executable;
188
224
  }
189
225
  function prepareCliProbe(command, args, options = {}) {
190
226
  const executable = options.executable ?? resolveProbePath(command);
191
227
  if (!executable)
192
228
  throw Object.assign(new Error(`${command} CLI not found`), { code: 'ENOENT' });
193
- const launchCommand = buildCliLaunchCommand(executable, args);
229
+ const probeExecutable = command === 'codex'
230
+ && (args.length === 1 && args[0] === '--version'
231
+ || args.length === 2 && args[0] === 'app-server' && args[1] === '--help')
232
+ ? codexProbeExecutable(executable) : executable;
233
+ const launchCommand = buildCliLaunchCommand(probeExecutable, args);
194
234
  const launch = launchCommand;
195
235
  const identity = `${probeInstallationIdentity(command, executable)}|${cliFileIdentity(launch.launcherPath)}`;
196
236
  const key = JSON.stringify([command, args]);
197
237
  let entry = cliProbeCache.get(key);
198
- if (!entry || entry.identity !== identity || (entry.retryAt !== undefined && Date.now() >= entry.retryAt)) {
238
+ if (!entry || entry.identity !== identity || (entry.retryAt !== undefined && Date.now() >= entry.retryAt)
239
+ || (entry.output !== undefined && options.validateOutput && !options.validateOutput(entry.output))) {
199
240
  entry = { identity };
200
241
  cliProbeCache.set(key, entry);
201
242
  }
@@ -207,10 +248,23 @@ function prepareCliProbe(command, args, options = {}) {
207
248
  };
208
249
  }
209
250
  function failCliProbe(entry, error) {
251
+ entry.output = undefined;
210
252
  entry.error = error;
211
253
  entry.retryAt = Date.now() + CLI_PROBE_FAILURE_BACKOFF_MS;
212
254
  throw error;
213
255
  }
256
+ function validateCliProbeOutput(output, stderr, options) {
257
+ if (options.validateOutput && !options.validateOutput(output)) {
258
+ throw Object.assign(new Error('CLI probe returned invalid output'), {
259
+ code: 'INVALID_PROBE_OUTPUT', status: 0, stdout: output, stderr,
260
+ });
261
+ }
262
+ return output;
263
+ }
264
+ function isRetryableCliProbeError(error) {
265
+ const code = error?.code;
266
+ return code === 'ETIMEDOUT' || code === 'INVALID_PROBE_OUTPUT';
267
+ }
214
268
  export function probeCliSync(command, args, options = {}) {
215
269
  const request = prepareCliProbe(command, args, options);
216
270
  if (request.entry.output !== undefined)
@@ -220,15 +274,16 @@ export function probeCliSync(command, args, options = {}) {
220
274
  for (const [index, timeout] of cliProbeTimeouts(command, options).entries()) {
221
275
  const startedAt = Date.now();
222
276
  try {
223
- return request.entry.output = execFileSync(request.command, request.args, {
277
+ const output = execFileSync(request.command, request.args, {
224
278
  encoding: 'utf8', timeout, windowsHide: true,
225
279
  windowsVerbatimArguments: request.launch.windowsVerbatimArguments,
226
280
  stdio: ['ignore', 'pipe', 'pipe'],
227
281
  });
282
+ return request.entry.output = validateCliProbeOutput(output, undefined, options);
228
283
  }
229
284
  catch (error) {
230
285
  options.onFailure?.(args, startedAt, error, timeout, request.launch);
231
- if (error.code !== 'ETIMEDOUT' || index === cliProbeTimeouts(command, options).length - 1)
286
+ if (!isRetryableCliProbeError(error) || index === cliProbeTimeouts(command, options).length - 1)
232
287
  return failCliProbe(request.entry, error);
233
288
  }
234
289
  }
@@ -240,8 +295,15 @@ export async function probeCli(command, args, options = {}) {
240
295
  return request.entry.output;
241
296
  if (request.entry.error !== undefined)
242
297
  throw request.entry.error;
243
- if (request.entry.pending)
244
- return request.entry.pending;
298
+ if (request.entry.pending) {
299
+ const output = await request.entry.pending;
300
+ try {
301
+ return validateCliProbeOutput(output, undefined, options);
302
+ }
303
+ catch (error) {
304
+ return failCliProbe(request.entry, error);
305
+ }
306
+ }
245
307
  const run = async () => {
246
308
  const timeouts = cliProbeTimeouts(command, options);
247
309
  for (const [index, timeout] of timeouts.entries()) {
@@ -258,8 +320,14 @@ export async function probeCli(command, args, options = {}) {
258
320
  Object.assign(error, { stdout, stderr, path: request.command, spawnargs: request.args });
259
321
  reject(error);
260
322
  }
261
- else
262
- resolve(stdout);
323
+ else {
324
+ try {
325
+ resolve(validateCliProbeOutput(stdout, stderr, options));
326
+ }
327
+ catch (validationError) {
328
+ reject(validationError);
329
+ }
330
+ }
263
331
  });
264
332
  child.stdin?.end();
265
333
  });
@@ -267,7 +335,7 @@ export async function probeCli(command, args, options = {}) {
267
335
  }
268
336
  catch (error) {
269
337
  options.onFailure?.(args, startedAt, error, timeout, request.launch);
270
- if (error.code !== 'ETIMEDOUT' || index === timeouts.length - 1)
338
+ if (!isRetryableCliProbeError(error) || index === timeouts.length - 1)
271
339
  return failCliProbe(request.entry, error);
272
340
  }
273
341
  }
@@ -703,6 +771,42 @@ export function isProcessRunning(pid) {
703
771
  return e.code === 'EPERM';
704
772
  }
705
773
  }
774
+ const processLivenessQueries = new Map();
775
+ /** Share concurrent Windows probes, but never cache liveness across checks. */
776
+ export async function isProcessRunningAsync(pid) {
777
+ if (!Number.isInteger(pid) || pid <= 0)
778
+ return false;
779
+ if (!isWindows)
780
+ return isProcessRunning(pid);
781
+ const pending = processLivenessQueries.get(pid);
782
+ if (pending)
783
+ return pending;
784
+ const query = (async () => {
785
+ try {
786
+ const { stdout } = await execFileAsync('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], {
787
+ encoding: 'utf8', timeout: 3000, windowsHide: true,
788
+ });
789
+ if (new RegExp(`,"${pid}",`, 'i').test(stdout))
790
+ return true;
791
+ }
792
+ catch { /* Retain the conservative native fallback on query failure. */ }
793
+ try {
794
+ process.kill(pid, 0);
795
+ return true;
796
+ }
797
+ catch (error) {
798
+ return error.code === 'EPERM';
799
+ }
800
+ })();
801
+ processLivenessQueries.set(pid, query);
802
+ try {
803
+ return await query;
804
+ }
805
+ finally {
806
+ if (processLivenessQueries.get(pid) === query)
807
+ processLivenessQueries.delete(pid);
808
+ }
809
+ }
706
810
  function isWindowsProcessRunning(pid) {
707
811
  try {
708
812
  const result = spawnSync('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], { encoding: 'utf-8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
@@ -881,7 +985,7 @@ export function findProcessByPort(port) {
881
985
  const pids = new Set();
882
986
  try {
883
987
  if (isWindows) {
884
- const result = spawnSync('netstat', ['-ano', '-p', 'TCP'], { encoding: 'utf-8', windowsHide: true });
988
+ const result = spawnSync('netstat', ['-ano', '-p', 'TCP'], { encoding: 'utf-8', windowsHide: true, timeout: 3000 });
885
989
  const output = result.stdout || '';
886
990
  for (const line of output.split('\n')) {
887
991
  // 形如: TCP 0.0.0.0:42705 0.0.0.0:0 LISTENING 23004
@@ -896,7 +1000,7 @@ export function findProcessByPort(port) {
896
1000
  }
897
1001
  }
898
1002
  else {
899
- const output = execFileSync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], { encoding: 'utf-8' }).trim();
1003
+ const output = execFileSync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], { encoding: 'utf-8', timeout: 3000 }).trim();
900
1004
  for (const line of output.split('\n')) {
901
1005
  const pid = parseInt(line.trim(), 10);
902
1006
  if (pid && pid !== process.pid)
@@ -907,6 +1011,55 @@ export function findProcessByPort(port) {
907
1011
  catch { /* netstat/lsof missing or no match */ }
908
1012
  return [...pids];
909
1013
  }
1014
+ let tcpListenersQuery;
1015
+ /**
1016
+ * Share concurrent Windows port scans, without retaining stale ownership data.
1017
+ * Missing optional lsof yields no known PIDs; callers must still bind/probe the service.
1018
+ */
1019
+ export async function findProcessByPortAsync(port) {
1020
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
1021
+ throw new Error('Invalid TCP port');
1022
+ let output;
1023
+ if (isWindows) {
1024
+ const query = tcpListenersQuery ??= execFileAsync('netstat', ['-ano', '-p', 'TCP'], {
1025
+ encoding: 'utf8', windowsHide: true, timeout: 3000, maxBuffer: 4 * 1024 * 1024,
1026
+ }).then(result => result.stdout);
1027
+ try {
1028
+ output = (await query) ?? '';
1029
+ }
1030
+ finally {
1031
+ if (tcpListenersQuery === query)
1032
+ tcpListenersQuery = undefined;
1033
+ }
1034
+ }
1035
+ else {
1036
+ try {
1037
+ output = ((await execFileAsync('lsof', ['-ti', `tcp:${port}`, '-sTCP:LISTEN'], {
1038
+ encoding: 'utf8', timeout: 3000,
1039
+ })).stdout ?? '');
1040
+ }
1041
+ catch (error) {
1042
+ const detail = error;
1043
+ // lsof is optional on Unix, as in the synchronous port lookup.
1044
+ if (detail.code === 'ENOENT')
1045
+ return [];
1046
+ // lsof uses exit 1, with no output, to report an empty selection.
1047
+ if (detail.code === 1 && !detail.stdout?.trim() && !detail.stderr?.trim())
1048
+ return [];
1049
+ throw error;
1050
+ }
1051
+ }
1052
+ const pids = new Set();
1053
+ for (const line of output.split('\n')) {
1054
+ const match = isWindows ? line.match(/:(\d+)\s+\S+\s+LISTENING\s+(\d+)/i) : null;
1055
+ if (isWindows && (!match || Number(match[1]) !== port))
1056
+ continue;
1057
+ const pid = Number(isWindows ? match[2] : line.trim());
1058
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)
1059
+ pids.add(pid);
1060
+ }
1061
+ return [...pids];
1062
+ }
910
1063
  export function getProcessInfo(pid) {
911
1064
  try {
912
1065
  if (isWindows) {
@@ -986,6 +1139,29 @@ function parseDateString(value) {
986
1139
  * Cross-platform command existence check.
987
1140
  */
988
1141
  const _commandExistsCache = new Map();
1142
+ const commandExistsPending = new Map();
1143
+ /** Daemon inventory probes must not block IPC on where/which. */
1144
+ export async function commandExistsAsync(cmd) {
1145
+ const cached = _commandExistsCache.get(cmd);
1146
+ if (cached !== undefined)
1147
+ return cached;
1148
+ const existing = commandExistsPending.get(cmd);
1149
+ if (existing)
1150
+ return existing;
1151
+ const pending = execFileAsync(isWindows ? 'where.exe' : 'which', [cmd], {
1152
+ encoding: 'utf8', windowsHide: true, timeout: 3_000,
1153
+ }).then(() => true, () => false);
1154
+ commandExistsPending.set(cmd, pending);
1155
+ try {
1156
+ const exists = await pending;
1157
+ _commandExistsCache.set(cmd, exists);
1158
+ return exists;
1159
+ }
1160
+ finally {
1161
+ if (commandExistsPending.get(cmd) === pending)
1162
+ commandExistsPending.delete(cmd);
1163
+ }
1164
+ }
989
1165
  export function commandExists(cmd) {
990
1166
  const cached = _commandExistsCache.get(cmd);
991
1167
  if (cached !== undefined)
@@ -17,7 +17,7 @@ import { execFile } from 'node:child_process';
17
17
  import { readSystemMemoryUsage } from './system-memory.js';
18
18
  import { getPackageRoot } from '../paths.js';
19
19
  import { WEB_PACKAGE_NAME } from '../product.js';
20
- import { buildCliLaunchCommand, resolveProbePath } from './cross-platform.js';
20
+ import { probeCli, resolveProbePath } from './cross-platform.js';
21
21
  function readJsonVersion(filePath) {
22
22
  try {
23
23
  const pkg = JSON.parse(fs.readFileSync(filePath, 'utf8'));
@@ -195,8 +195,8 @@ function runExec(command, args, timeoutMs, windowsVerbatimArguments = false) {
195
195
  * 按 PATH 探测一个 CLI 的版本。
196
196
  *
197
197
  * 不能直接 execFile('claude'):Windows 上 npm 装的是 claude.cmd,Node 25 对 .cmd
198
- * 直接 spawn 会报 EINVAL。走 resolveProbePath + buildCliLaunchCommand,与
199
- * baseagent 探测同一套启动规则(.cmd 经受信任的 cmd.exe 转发)。
198
+ * 直接 spawn 会报 EINVAL。复用 baseagent 的探测缓存和在途请求,保留原生
199
+ * Codex 入口探测及 .cmd 经受信任 cmd.exe 转发的规则。
200
200
  */
201
201
  async function probeCliVersion(command, args, timeoutMs) {
202
202
  try {
@@ -207,9 +207,10 @@ async function probeCliVersion(command, args, timeoutMs) {
207
207
  const raw = await runExec(command, args, timeoutMs);
208
208
  return raw.ok ? firstVersionLine(raw.stdout) : null;
209
209
  }
210
- const launch = buildCliLaunchCommand(executable, args);
211
- const result = await runExec(launch.command, launch.args, timeoutMs, launch.windowsVerbatimArguments);
212
- return result.ok ? firstVersionLine(result.stdout) : null;
210
+ const output = await probeCli(command, args, {
211
+ executable, timeouts: [timeoutMs], validateOutput: value => firstVersionLine(value) !== null,
212
+ });
213
+ return firstVersionLine(output);
213
214
  }
214
215
  catch {
215
216
  return null;
@@ -299,8 +300,10 @@ async function probeBundledClaudeVersion() {
299
300
  const executable = resolveBundledClaudeExecutable();
300
301
  if (!executable)
301
302
  return null;
302
- const result = await runExec(executable, ['--version'], 8000);
303
- return result.ok ? firstVersionLine(result.stdout) : null;
303
+ const output = await probeCli('bundled-claude', ['--version'], {
304
+ executable, timeouts: [8000], validateOutput: value => firstVersionLine(value) !== null,
305
+ });
306
+ return firstVersionLine(output);
304
307
  }
305
308
  catch {
306
309
  return null;
@@ -334,6 +334,9 @@ export function getLocalVersion() {
334
334
  * 未安装或查询失败返回 null。
335
335
  */
336
336
  export function resolveGlobalPkg(pkgName) {
337
+ const local = resolveBundledPkg(pkgName);
338
+ if (local)
339
+ return local;
337
340
  try {
338
341
  const npm = resolveNpmInvocation();
339
342
  const globalRoot = execFileSync(npm.command, [...npm.argsPrefix, 'root', '-g'], {
@@ -356,6 +359,51 @@ export function resolveGlobalPkg(pkgName) {
356
359
  catch { /* not found */ }
357
360
  return null;
358
361
  }
362
+ function resolveBundledPkg(pkgName) {
363
+ if (pkgName !== WEB_PACKAGE_NAME)
364
+ return null;
365
+ const candidates = [
366
+ ...(isLinkedInstall() ? [path.join(getPackageRoot(), 'ecweb', 'package.json')] : []),
367
+ path.join(targetPackageRoot(), 'node_modules', ...pkgName.split('/'), 'package.json'),
368
+ ];
369
+ for (const file of candidates) {
370
+ try {
371
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
372
+ if (pkg.name === pkgName && typeof pkg.version === 'string')
373
+ return { version: pkg.version, path: file };
374
+ }
375
+ catch { /* Try the next installation layout. */ }
376
+ }
377
+ return null;
378
+ }
379
+ /** Runtime callers must not block IPC and CLI probe callbacks while locating npm packages. */
380
+ export async function resolveGlobalPkgAsync(pkgName) {
381
+ const local = resolveBundledPkg(pkgName);
382
+ if (local)
383
+ return local;
384
+ try {
385
+ const npm = resolveNpmInvocation();
386
+ const { stdout } = await execFileAsync(npm.command, [...npm.argsPrefix, 'root', '-g'], {
387
+ encoding: 'utf8', timeout: 10_000, windowsHide: true,
388
+ });
389
+ const globalRoot = stdout.trim();
390
+ const candidates = [
391
+ ...(pkgName === WEB_PACKAGE_NAME
392
+ ? [path.join(globalRoot, MAIN_PACKAGE_NAME, 'node_modules', ...pkgName.split('/'), 'package.json')] : []),
393
+ path.join(globalRoot, ...pkgName.split('/'), 'package.json'),
394
+ ];
395
+ for (const file of candidates) {
396
+ try {
397
+ const pkg = JSON.parse(await fs.promises.readFile(file, 'utf8'));
398
+ if (pkg.name === pkgName && typeof pkg.version === 'string')
399
+ return { version: pkg.version, path: file };
400
+ }
401
+ catch { /* Try the next installation layout. */ }
402
+ }
403
+ }
404
+ catch { /* npm unavailable or package not installed. */ }
405
+ return null;
406
+ }
359
407
  /**
360
408
  * 查询 npm registry 上指定包的最新版本。
361
409
  * 使用 HTTP fetch 直接查 registry API,不依赖 npm CLI。
@@ -7,7 +7,7 @@
7
7
  * killing the wrong process).
8
8
  */
9
9
  import fs from 'fs';
10
- import { spawnSync } from 'child_process';
10
+ import { execFile, spawnSync } from 'child_process';
11
11
  const isWindows = process.platform === 'win32';
12
12
  const isMacOS = process.platform === 'darwin';
13
13
  function readLinuxClockTicks() {
@@ -52,6 +52,69 @@ function approximateSelfStartTime() {
52
52
  */
53
53
  const START_TIME_CACHE_TTL_MS = 5000;
54
54
  const startTimeCache = new Map();
55
+ const startTimeQueries = new Map();
56
+ /** Daemon lifecycle queries must not block IPC, probes or startup timers. */
57
+ export async function getProcessStartTimeAsync(pid) {
58
+ if (!Number.isInteger(pid) || pid <= 0)
59
+ return null;
60
+ if (pid === process.pid)
61
+ 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;
68
+ const query = (async () => {
69
+ let startedAt;
70
+ 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);
74
+ 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;
78
+ }
79
+ }
80
+ else if (isMacOS) {
81
+ startedAt = parseDateString(await processQuery('ps', ['-p', String(pid), '-o', 'lstart='], 5000));
82
+ }
83
+ else {
84
+ startedAt = getStartTimeLinux(pid);
85
+ }
86
+ // Do not cache an identity for a child that exited during the query.
87
+ if (startedAt !== null) {
88
+ try {
89
+ process.kill(pid, 0);
90
+ }
91
+ catch (error) {
92
+ if (error.code !== 'EPERM')
93
+ startedAt = null;
94
+ }
95
+ }
96
+ if (startedAt === null)
97
+ startTimeCache.delete(pid);
98
+ else
99
+ startTimeCache.set(pid, { at: Date.now(), startedAt });
100
+ return startedAt;
101
+ })();
102
+ startTimeQueries.set(pid, query);
103
+ try {
104
+ return await query;
105
+ }
106
+ finally {
107
+ if (startTimeQueries.get(pid) === query)
108
+ startTimeQueries.delete(pid);
109
+ }
110
+ }
111
+ function processQuery(command, args, timeout) {
112
+ return new Promise(resolve => {
113
+ execFile(command, args, { encoding: 'utf8', timeout, windowsHide: true }, (error, stdout) => {
114
+ resolve(error ? '' : stdout.replace(/^\uFEFF/, '').trim());
115
+ });
116
+ });
117
+ }
55
118
  /**
56
119
  * 获取进程启动时间(Unix 毫秒)。
57
120
  * 拿不到时返回 null,调用方应保守处理(不杀该 PID)。