evolcore 0.0.46 → 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 (54) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/agents/claude-runner.js +9 -1
  3. package/dist/agents/codex/app-server-client.js +32 -23
  4. package/dist/aun/group/fs-download.js +1 -1
  5. package/dist/channels/aun.js +19 -8
  6. package/dist/channels/daemon.js +1 -1
  7. package/dist/cli/daemon-commands.js +27 -39
  8. package/dist/cli/daemon-lifecycle-client.js +17 -3
  9. package/dist/cli/init-channel.js +2 -2
  10. package/dist/cli/init.js +7 -1
  11. package/dist/cli/restart-monitor.js +104 -28
  12. package/dist/cli/task-context.js +83 -15
  13. package/dist/cli/upgrade-command.js +4 -2
  14. package/dist/config/config-manager.js +29 -17
  15. package/dist/config/peer-book-store.js +18 -10
  16. package/dist/config/provider-identity-migration.js +157 -5
  17. package/dist/config/schema-migration.js +123 -16
  18. package/dist/config/schema-registry.js +6 -2
  19. package/dist/core/agent-runtime.js +6 -5
  20. package/dist/core/auth/agent-delegation.js +8 -3
  21. package/dist/core/auth/delegation-diagnostics.js +56 -15
  22. package/dist/core/auth/operation-authorizer.js +1 -1
  23. package/dist/core/command/menu-handler.js +4 -4
  24. package/dist/core/command/slash-handler.js +4 -6
  25. package/dist/core/daemon-bootstrap.js +11 -9
  26. package/dist/core/daemon-control.js +1 -3
  27. package/dist/core/daemon-lifecycle.js +50 -40
  28. package/dist/core/evolagent-registry.js +8 -2
  29. package/dist/core/host-snapshot.js +9 -4
  30. package/dist/core/initialization/service.js +22 -4
  31. package/dist/core/ipc-registration.js +4 -3
  32. package/dist/core/memory/consolidation.js +6 -6
  33. package/dist/core/ownership/owner-resolver.js +27 -10
  34. package/dist/core/relation/peer-identity.js +5 -1
  35. package/dist/core/relation/same-owner-proof.js +2 -1
  36. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  37. package/dist/core/session/session-file-health.js +36 -7
  38. package/dist/core/task/task-image-resources.js +1 -1
  39. package/dist/ecweb/runtime/lifecycle.js +64 -15
  40. package/dist/ecweb/runtime/supervisor.js +2 -15
  41. package/dist/index.js +37 -34
  42. package/dist/ipc.js +2 -1
  43. package/dist/trigger/scheduler.js +4 -0
  44. package/dist/trigger/state.js +7 -0
  45. package/dist/utils/aid-bind.js +155 -18
  46. package/dist/utils/atomic-write.js +3 -3
  47. package/dist/utils/cross-platform.js +24 -5
  48. package/dist/utils/error-utils.js +13 -0
  49. package/dist/utils/instance-registry.js +61 -0
  50. package/dist/utils/process-introspect.js +152 -7
  51. package/dist/utils/upgrade-jobs.js +4 -4
  52. package/kits/docs/evolcore/aid.md +3 -1
  53. package/kits/docs/evolcore/provider.md +10 -2
  54. package/package.json +2 -2
@@ -1,28 +1,165 @@
1
- import { randomUUID } from 'crypto';
1
+ import { randomBytes, randomUUID, timingSafeEqual, createHash } from 'crypto';
2
+ import { loadAgent } from '../config-store.js';
3
+ import { isValidAid } from '../aun/aid/validation.js';
4
+ import { ownerResolver } from '../core/ownership/owner-resolver.js';
5
+ import { readInstalledEvolcoreVersion } from './evolcore-version.js';
2
6
  const BIND_TTL_MS = 10 * 60 * 1000;
3
- const deferredMessage = 'Evol App ownership binding is deferred; use ec aid bind <ownerAid> [--subject <subjectAid>]';
4
7
  export class BindService {
5
- constructor(_options) { }
6
- startCleanup() { }
7
- stopCleanup() { }
8
- begin(_request) {
9
- return {
10
- ok: true,
11
- taskId: randomUUID(),
12
- qrData: {},
13
- expiresAt: Date.now() + BIND_TTL_MS,
8
+ options;
9
+ sessions = new Map();
10
+ cleanup;
11
+ constructor(options) {
12
+ this.options = options;
13
+ }
14
+ startCleanup() {
15
+ if (this.cleanup)
16
+ return;
17
+ this.cleanup = setInterval(() => this.expireSessions(), 60_000);
18
+ this.cleanup.unref?.();
19
+ }
20
+ stopCleanup() { clearInterval(this.cleanup); this.cleanup = undefined; }
21
+ begin(request) {
22
+ this.expireSessions();
23
+ if (!['daemon', 'agent'].includes(request.bindType) || 'ownerMode' in request) {
24
+ return { ok: false, code: 'INVALID_ARGUMENT', error: 'Select a daemon or Agent binding; use Ownership transfer to replace an Owner' };
25
+ }
26
+ const subjectAid = request.bindType === 'daemon' ? this.options.receiverAid : request.targetAid;
27
+ if (!subjectAid || !isValidAid(subjectAid)
28
+ || (request.bindType === 'agent' && (subjectAid === this.options.receiverAid || !loadAgent(subjectAid)))) {
29
+ return { ok: false, code: 'SUBJECT_UNAVAILABLE', error: 'Binding requires a local subject AID' };
30
+ }
31
+ if (this.sessions.size >= 128)
32
+ return { ok: false, code: 'BIND_CAPACITY', error: 'Too many pending binding sessions' };
33
+ const ttl = request.ttlMs ?? BIND_TTL_MS;
34
+ if (!Number.isFinite(ttl) || ttl <= 0 || ttl > BIND_TTL_MS) {
35
+ return { ok: false, code: 'INVALID_ARGUMENT', error: 'Binding TTL must be between 1 and 600000 milliseconds' };
36
+ }
37
+ const session = {
38
+ id: randomUUID(), token: randomBytes(32).toString('base64url'), bindType: request.bindType,
39
+ subjectAid, expiresAt: Date.now() + ttl, status: 'pending',
14
40
  };
41
+ this.sessions.set(session.id, session);
42
+ return { ok: true, taskId: session.id, expiresAt: session.expiresAt, qrData: {
43
+ type: 'evolcore.bind', version: readInstalledEvolcoreVersion(),
44
+ platform: process.platform === 'win32' ? 'windows' : process.platform,
45
+ bindType: session.bindType, subjectAid, receiverAid: this.options.receiverAid,
46
+ token: session.token, expiresAt: session.expiresAt,
47
+ } };
15
48
  }
16
- status(_taskId) {
17
- return { ok: false, code: 'OWNERSHIP_APP_DEFERRED', error: deferredMessage };
49
+ async status(taskId) {
50
+ this.expireSessions();
51
+ const session = this.sessions.get(taskId);
52
+ if (!session)
53
+ return { ok: false, code: 'BIND_SESSION_INVALID', error: 'Binding session does not exist' };
54
+ if (session.status !== 'cancelled' && session.ownerAid) {
55
+ try {
56
+ const state = await ownerResolver.status(session.subjectAid, { force: true });
57
+ session.status = this.confirmsOwner(session, state) ? 'bound' : 'pending';
58
+ }
59
+ catch (error) {
60
+ session.status = 'pending';
61
+ const code = error?.code;
62
+ return { ok: false,
63
+ code: typeof code === 'string' && /^[A-Za-z0-9_]{1,64}$/.test(code) ? code : 'OWNERSHIP_UNAVAILABLE',
64
+ error: 'Unable to verify current Ownership consensus' };
65
+ }
66
+ }
67
+ return { ok: true, taskId, status: session.status,
68
+ ...(session.status === 'bound' ? { boundAid: session.ownerAid } : {}) };
18
69
  }
19
- cancel(_taskId) {
20
- return { ok: false, code: 'OWNERSHIP_APP_DEFERRED', error: deferredMessage };
70
+ cancel(taskId) {
71
+ const session = this.sessions.get(taskId);
72
+ if (!session)
73
+ return { ok: false, code: 'BIND_SESSION_INVALID', error: 'Binding session does not exist' };
74
+ if (session.ownerAid)
75
+ return { ok: false, code: 'BIND_PENDING', error: 'An accepted Ownership request cannot be cancelled by cancelling its QR session' };
76
+ session.status = 'cancelled';
77
+ return { ok: true, taskId, status: 'cancelled' };
21
78
  }
22
- async handleRequest(payload, _fromAid) {
79
+ async handleRequest(payload, fromAid, encrypted = false) {
23
80
  if (payload?.type !== 'bind.request')
24
81
  return null;
25
- return { type: 'bind.response', bindType: payload.bindType === 'agent' ? 'agent' : 'daemon', success: false,
26
- error: { code: 'OWNERSHIP_APP_DEFERRED', message: deferredMessage } };
82
+ this.expireSessions();
83
+ const response = (code, message) => ({
84
+ type: 'bind.response', bindType: payload.bindType === 'agent' ? 'agent' : 'daemon', success: false,
85
+ ...(typeof payload.creationId === 'string' && payload.creationId.length <= 128 ? { creationId: payload.creationId } : {}),
86
+ error: { code, message },
87
+ });
88
+ if (!encrypted)
89
+ return response('ENCRYPTION_REQUIRED', 'Binding requires an encrypted identity message');
90
+ if (!isValidAid(fromAid))
91
+ return response('INVALID_SENDER', 'Binding requires an authenticated sender AID');
92
+ const session = [...this.sessions.values()].find(item => typeof payload.token === 'string'
93
+ && Buffer.byteLength(payload.token) === Buffer.byteLength(item.token)
94
+ && timingSafeEqual(Buffer.from(payload.token), Buffer.from(item.token)));
95
+ if (!session) {
96
+ return await this.options.handleAppBindRequest?.(payload, fromAid, encrypted)
97
+ ?? response('BIND_SESSION_INVALID', 'Binding session is invalid; refresh the QR code');
98
+ }
99
+ if (payload.bindType !== session.bindType
100
+ || (payload.subjectAid !== undefined && payload.subjectAid !== session.subjectAid)
101
+ || (payload.targetAid !== undefined && payload.targetAid !== session.subjectAid)) {
102
+ return response('BIND_CONFLICT', 'Binding subject does not match the QR session');
103
+ }
104
+ if (typeof payload.creationId !== 'string' || !payload.creationId.trim() || payload.creationId.length > 128) {
105
+ return response('INVALID_CREATION_ID', 'Binding requires a creationId');
106
+ }
107
+ if (payload.timestamp !== undefined && (typeof payload.timestamp !== 'number' || !Number.isFinite(payload.timestamp)
108
+ || Math.abs(Date.now() - payload.timestamp) > BIND_TTL_MS))
109
+ return response('REQUEST_EXPIRED', 'Binding request has expired');
110
+ const ownerAid = fromAid.toLowerCase();
111
+ const fingerprint = createHash('sha256').update(JSON.stringify({
112
+ ownerAid, creationId: payload.creationId, bindType: payload.bindType,
113
+ subjectAid: session.subjectAid, clientName: payload.clientName, deviceName: payload.deviceName,
114
+ platform: payload.platform, appVersion: payload.appVersion, timestamp: payload.timestamp,
115
+ })).digest('hex');
116
+ if (session.ownerAid) {
117
+ if (session.ownerAid !== ownerAid || session.fingerprint !== fingerprint)
118
+ return response('BIND_CONFLICT', 'Binding request conflicts with an accepted request');
119
+ return session.flight ?? session.response;
120
+ }
121
+ if (session.status !== 'pending' || session.expiresAt <= Date.now())
122
+ return response('BIND_SESSION_EXPIRED', 'Binding QR session is no longer valid');
123
+ session.ownerAid = ownerAid;
124
+ session.creationId = payload.creationId;
125
+ session.fingerprint = fingerprint;
126
+ const work = async () => {
127
+ try {
128
+ const state = await ownerResolver.bind(session.subjectAid, ownerAid, () => session.status !== 'cancelled', () => { session.submissionStarted = true; });
129
+ const bound = this.confirmsOwner(session, state);
130
+ session.status = bound ? 'bound' : 'pending';
131
+ return { type: 'bind.response', bindType: session.bindType, creationId: session.creationId,
132
+ success: true, subjectAid: session.subjectAid, ownerAid, status: bound ? 'bound' : 'pending' };
133
+ }
134
+ catch (error) {
135
+ if (session.submissionStarted)
136
+ return { type: 'bind.response', bindType: session.bindType,
137
+ creationId: session.creationId, success: true, subjectAid: session.subjectAid, ownerAid, status: 'unknown' };
138
+ session.ownerAid = undefined;
139
+ session.fingerprint = undefined;
140
+ const code = error?.code;
141
+ return response(typeof code === 'string' && /^[A-Za-z0-9_]{1,64}$/.test(code) ? code : 'BIND_FAILED', 'Binding preparation failed; query Ownership before retrying');
142
+ }
143
+ };
144
+ session.flight = work();
145
+ try {
146
+ return session.response = await session.flight;
147
+ }
148
+ finally {
149
+ session.flight = undefined;
150
+ }
151
+ }
152
+ confirmsOwner(session, state) {
153
+ return state.consensusStatus === 'consensus' && state.ownerAid === session.ownerAid
154
+ && state.consensus?.sub_aid === session.subjectAid && state.consensus.lock === 'locked'
155
+ && state.authorizationStatus === 'verified' && !state.refreshFailure;
156
+ }
157
+ expireSessions() {
158
+ for (const [id, session] of this.sessions) {
159
+ if (!session.ownerAid && session.status === 'pending' && session.expiresAt <= Date.now())
160
+ session.status = 'expired';
161
+ if (!session.flight && session.expiresAt + BIND_TTL_MS <= Date.now())
162
+ this.sessions.delete(id);
163
+ }
27
164
  }
28
165
  }
@@ -324,8 +324,8 @@ export async function atomicReplaceJson(file, value) {
324
324
  const retryableCodes = new Set(['EPERM', 'EACCES', 'EBUSY']);
325
325
  const delays = [10, 25, 50, 100];
326
326
  const pause = new Int32Array(new SharedArrayBuffer(4));
327
- /** Retry brief file-handle contention without opening or deleting the live file. */
328
- export function atomicReplaceFile(source, destination) {
327
+ /** Retry brief contention; disable allowInPlaceFallback when replacement must remain atomic. */
328
+ export function atomicReplaceFile(source, destination, options = {}) {
329
329
  let lastError;
330
330
  for (let attempt = 0;; attempt += 1) {
331
331
  try {
@@ -341,7 +341,7 @@ export function atomicReplaceFile(source, destination) {
341
341
  }
342
342
  }
343
343
  const code = lastError?.code;
344
- if (process.platform === 'win32' && code === 'EPERM') {
344
+ if (options.allowInPlaceFallback !== false && process.platform === 'win32' && code === 'EPERM') {
345
345
  // Some Windows file projections deny renaming an open JSON target. Keep
346
346
  // its inode and use atomicWrite's hot-backup/stable-write fallback instead.
347
347
  atomicWrite(destination, fs.readFileSync(source, 'utf8'));
@@ -506,21 +506,21 @@ export async function launchMonitorAndConfirm(args, env, isAliveInRegistry, hasO
506
506
  catch (error) {
507
507
  diagnostic(`Spawn callback failed: ${error.message}`);
508
508
  }
509
- const accepted = () => isAliveInRegistry(childPid) || hasOtherLiveMonitor(childPid);
509
+ const accepted = async () => await isAliveInRegistry(childPid) || await hasOtherLiveMonitor(childPid);
510
510
  const deadline = Date.now() + (options.timeoutMs ?? 15_000);
511
511
  while (Date.now() < deadline) {
512
512
  await new Promise(resolve => setTimeout(resolve, 300));
513
- if (accepted())
513
+ if (await accepted())
514
514
  return finish({ ok: true, pid: childPid });
515
515
  if (spawnError)
516
516
  return finish({ ok: false, pid: childPid, reason: spawnError });
517
- if (exited && !options.isPendingInRegistry?.()) {
517
+ if (exited && !await options.isPendingInRegistry?.()) {
518
518
  return finish({ ok: false, pid: childPid, reason: `进程已退出,exit=${exitCode}, signal=${exitSignal ?? 'none'}` });
519
519
  }
520
520
  }
521
- if (accepted())
521
+ if (await accepted())
522
522
  return finish({ ok: true, pid: childPid });
523
- if ((!exited && isProcessRunning(childPid)) || options.isPendingInRegistry?.()) {
523
+ if ((!exited && await isProcessRunningAsync(childPid)) || await options.isPendingInRegistry?.()) {
524
524
  return finish({
525
525
  ok: false,
526
526
  pid: childPid,
@@ -894,6 +894,25 @@ export function killProcess(pid, force = false) {
894
894
  return !isProcessRunning(pid);
895
895
  }
896
896
  }
897
+ /** Same process-tree termination as killProcess, without blocking Windows I/O. */
898
+ export async function killProcessAsync(pid, force = false) {
899
+ if (!Number.isInteger(pid) || pid <= 0)
900
+ return false;
901
+ if (!isWindows)
902
+ return killProcess(pid, force);
903
+ try {
904
+ const args = ['/PID', String(pid), '/T'];
905
+ if (force)
906
+ args.push('/F');
907
+ await execFileAsync('taskkill', args, {
908
+ encoding: 'utf-8', timeout: 10_000, windowsHide: true,
909
+ });
910
+ return true;
911
+ }
912
+ catch {
913
+ return !await isProcessRunningAsync(pid);
914
+ }
915
+ }
897
916
  /**
898
917
  * Terminate exactly one process, without recursively terminating its children.
899
918
  *
@@ -103,6 +103,7 @@ export var ErrorType;
103
103
  ErrorType["COMPACTION_FAILED"] = "compaction_failed";
104
104
  ErrorType["MODEL_UNAVAILABLE"] = "model_unavailable";
105
105
  ErrorType["SESSION_UNAVAILABLE"] = "session_unavailable";
106
+ ErrorType["SESSION_RUNTIME_UNAVAILABLE"] = "session_runtime_unavailable";
106
107
  ErrorType["SANDBOX_INITIALIZATION_FAILED"] = "sandbox_initialization_failed";
107
108
  ErrorType["SANDBOX_DEPENDENCIES_MISSING"] = "sandbox_dependencies_missing";
108
109
  ErrorType["CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE"] = "codex_sandbox_userns_unavailable";
@@ -466,7 +467,13 @@ const GATEWAY_REQUEST_TIMEOUT_PATTERN = /\bgateway request timed out\b/i;
466
467
  function hasRetryableHttpStatus(text) {
467
468
  return RETRYABLE_HTTP_STATUS_PATTERN.test(text);
468
469
  }
470
+ function isSessionRuntimeError(error) {
471
+ return error?.code === 'SESSION_RUNTIME_UNAVAILABLE'
472
+ || String(error?.message ?? error ?? '').startsWith('SESSION_RUNTIME_UNAVAILABLE:');
473
+ }
469
474
  export function classifyError(error) {
475
+ if (isSessionRuntimeError(error))
476
+ return ErrorType.SESSION_RUNTIME_UNAVAILABLE;
470
477
  if (isWindowsShellTrustError(error))
471
478
  return ErrorType.UNKNOWN;
472
479
  if (isUnattendedInputRequired(error))
@@ -552,6 +559,8 @@ export function classifyError(error) {
552
559
  * 注意:401 认证错误不可重试(API Key 无效不会因重试恢复)
553
560
  */
554
561
  export function isRetryableError(error) {
562
+ if (isSessionRuntimeError(error))
563
+ return false;
555
564
  if (isWindowsShellTrustError(error))
556
565
  return false;
557
566
  if (isUnattendedInputRequired(error))
@@ -617,6 +626,10 @@ function sandboxInitializationErrorMessage(error, prefix) {
617
626
  return `${prefix}执行沙箱启动失败(sandbox_initialization_failed),当前操作未执行;请查看原始诊断并运行 ec diagnose 排查`;
618
627
  }
619
628
  export function getErrorMessage(error, terminalReason, includeEmoji = true) {
629
+ if (isSessionRuntimeError(error)) {
630
+ const message = typeof error === 'string' ? error : error.message ?? error.code;
631
+ return `${includeEmoji ? '❌ ' : ''}会话临时目录准备或安全校验失败,本轮未继续执行。${message}。请检查对应阶段的目录权限或超时原因;不会退回共享临时目录。`;
632
+ }
620
633
  if (isWindowsShellTrustError(error)) {
621
634
  return `${includeEmoji ? '❌ ' : ''}${resolveErrorMessage(error)}`;
622
635
  }
@@ -308,6 +308,67 @@ export function scanInstances(options = {}) {
308
308
  }
309
309
  return status;
310
310
  }
311
+ /** Observe the IPC target only; the restart monitor still owns election and cleanup. */
312
+ export async function hasLiveMain(pid) {
313
+ if (!Number.isSafeInteger(pid) || pid <= 0)
314
+ return false;
315
+ let record;
316
+ try {
317
+ record = JSON.parse(await fs.promises.readFile(path.join(instanceDir(), mainFileName(pid)), 'utf8'));
318
+ }
319
+ catch (error) {
320
+ if (error instanceof SyntaxError || error.code === 'ENOENT')
321
+ return false;
322
+ throw error;
323
+ }
324
+ if (record?.pid !== pid || !Number.isFinite(record.startedAt) || record.startedAt <= 0)
325
+ return false;
326
+ // A fresh identity lookup already confirms liveness after the OS query.
327
+ // Fall back conservatively only when the creation time is unavailable.
328
+ const actual = await getProcessStartTimeAsync(pid, { fresh: true });
329
+ return actual !== null ? startTimeMatches(record.startedAt, actual) : await isProcessRunningAsync(pid);
330
+ }
331
+ /** Read-only launch observation; never block the daemon's shutdown IPC with a full process scan. */
332
+ export async function hasLiveRestartMonitor(options = {}) {
333
+ const directory = instanceDir();
334
+ let files;
335
+ try {
336
+ files = await fs.promises.readdir(directory);
337
+ }
338
+ catch (error) {
339
+ if (error.code === 'ENOENT')
340
+ return false;
341
+ throw error;
342
+ }
343
+ for (const file of files) {
344
+ const match = /^restart-monitor-(\d+)\.json$/.exec(file);
345
+ if (!match)
346
+ continue;
347
+ const pid = Number(match[1]);
348
+ if (!Number.isSafeInteger(pid) || pid <= 0 || pid === options.excludePid
349
+ || (options.pid !== undefined && pid !== options.pid))
350
+ continue;
351
+ let record;
352
+ try {
353
+ record = JSON.parse(await fs.promises.readFile(path.join(directory, file), 'utf8'));
354
+ }
355
+ catch (error) {
356
+ if (error instanceof SyntaxError || error.code === 'ENOENT')
357
+ continue;
358
+ throw error;
359
+ }
360
+ if (record?.pid !== pid || !Number.isFinite(record.startedAt) || record.startedAt <= 0
361
+ || (options.requestId !== undefined && record.requestId !== options.requestId)
362
+ || (options.phase !== undefined && record.phase !== options.phase))
363
+ continue;
364
+ if (!await isProcessRunningAsync(pid))
365
+ continue;
366
+ const actual = await getProcessStartTimeAsync(pid, { fresh: true });
367
+ if (actual !== null ? startTimeMatches(record.startedAt, actual) : await isProcessRunningAsync(pid))
368
+ return true;
369
+ }
370
+ return false;
371
+ }
311
372
  /**
312
373
  * 清理所有非自己 PID 的残留文件。仍活着的旧实例进程会被 SIGKILL。
313
374
  * 发送终止信号前重新核验身份;无法核验或终止失败时保留登记供后续处理。
@@ -7,6 +7,8 @@
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';
@@ -73,13 +75,16 @@ export async function getProcessStartTimeAsync(pid, options = {}) {
73
75
  const query = (async () => {
74
76
  let startedAt;
75
77
  if (isWindows) {
76
- const output = await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command',
77
- `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToUniversalTime().ToString('o')`], 8000);
78
- startedAt = parseCimDate(output) ?? parseDateString(output);
78
+ startedAt = await readWindowsStartTimeAsync(pid);
79
79
  if (startedAt === null) {
80
- const fallback = await processQuery('wmic', ['process', 'where', `ProcessId=${pid}`, 'get', 'CreationDate', '/value'], 5000);
81
- const creation = fallback.match(/CreationDate=([^\r\n]+)/)?.[1]?.trim();
82
- 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
+ }
83
88
  }
84
89
  }
85
90
  else if (isMacOS) {
@@ -231,6 +236,30 @@ function getStartTimeMacOS(pid) {
231
236
  }
232
237
  // ── Windows ──
233
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
+ }
234
263
  const fromPwsh = winPowerShellCreationDate(pid);
235
264
  if (fromPwsh !== null)
236
265
  return fromPwsh;
@@ -294,7 +323,7 @@ export async function getProcessSnapshotAsync(options = {}) {
294
323
  const generation = snapshotGeneration;
295
324
  const query = (async () => {
296
325
  const snapshot = isWindows
297
- ? parseWindowsSnapshot(await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], 8000))
326
+ ? await readWindowsSnapshotAsync()
298
327
  ?? { complete: false, startedAt: new Map(), commandLines: new Map() }
299
328
  : readProcessSnapshot();
300
329
  if (generation === snapshotGeneration)
@@ -329,7 +358,123 @@ function readProcessSnapshot() {
329
358
  return { complete: false, startedAt: new Map(), commandLines: new Map() };
330
359
  }
331
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
+ }
332
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
+ }
333
478
  const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], { encoding: 'utf-8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
334
479
  return result.status === 0 ? parseWindowsSnapshot(result.stdout || '') : null;
335
480
  }
@@ -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) {
@@ -139,7 +139,9 @@ Owner 目录同步在连接可用时建立单条核验和暂态故障退避链
139
139
 
140
140
  Ownership 任务事件、修改本地 Owner 配置、相关名片或 Owner 关系材料变更只失效缓存,不主动发起复核。连接首次就绪、断线恢复和缓存到期均不触发提前刷新;下次实际消息、查询或授权需要 Owner 时才等待核验。相同任务事件和连接通知去重,无关对端、普通文件变更不触发失效。远端 Owner 的 Storage 事件只在本机确实收到时生效,不能假定事件完整覆盖远端变化。Owner 绑定提交前及修改 Owner 的授权仍要求显式核验成功。
141
141
 
142
- 处于 `created`、`ownerpending` 或 `bootstrapping` 生命周期的普通 Agent 在 AUN 连接就绪后,优先取根级 `config.json.owner`,缺失时兼容旧 `owners` 数组的首个非空 AID;沿用首个配置 Owner 的选择规则,不向数组内所有 AID 发送邀约。没有绑定目标、生命周期无效或已经 `active` 时静默跳过,不因遗留配置重新绑定。存在绑定目标且新鲜协议状态为 `unbound`、`released` 或 `single_sided` 时,每个 Agent 对同一 Owner 在本进程内最多自动提交一次绑定邀约。已有协议共识时不提交,也不自动转让 Owner。提交前记录 INFO 日志 `Submitting configured Owner binding invitation`,包含主体、目标 Owner 和协议状态;提交结果与失败继续记录 `EC_OWNERSHIP` 的 `bind.result` / `bind.failed`。等待确认、提交失败或回执不明均不定时重发,断线重连和渠道重建也不会再次提交;需要重发时显式执行绑定命令。自动尝试记录只保存在内存,不持久化;进程重启后重新检查并允许再自动提交一次。
142
+ 普通 Agent 在 AUN 连接就绪后,优先取根级 `config.json.owner`,缺失时兼容旧 `owners` 数组的首个非空 AID;沿用首个配置 Owner 的选择规则,不向数组内所有 AID 发送邀约。`created`、`ownerpending`、`bootstrapping` 和保留旧绑定目标的 `active` Agent 均参与检查;没有目标或生命周期无效时静默跳过。存在绑定目标且新鲜协议状态为 `unbound`、`released` 或 `single_sided` 时,每个 Agent 对同一 Owner 在本进程内最多进入一次 SDK 绑定变更。已有协议共识时不提交,也不自动转让 Owner。准备期间预留并发占位,实际进入 SDK 变更前才消耗次数并记录 INFO 日志 `Submitting configured Owner binding invitation`;目标身份核验、最终共识查询或连接校验失败且尚未进入 SDK 时释放占位,可在后续连接就绪时重新检查,不安排定时重试。进入 SDK 后的失败或回执不明继续保留次数,断线重连和渠道重建不重发。提交结果与失败沿用 `EC_OWNERSHIP` 的 `bind.result` / `bind.failed`。自动尝试记录仅在内存中,进程重启后可重新检查;新版一次性初始化另按持久提交记录恢复,已提交或结果不明时只核验共识,不重复发送。
143
+
144
+ App 的 `type: bind.request` 是扫码请求适配入口,先核验加密信封、扫码令牌、固定主体和请求指纹,再与 CLI 一样调用 `OwnerResolver.bind`,由 SDK 发送标准 `type: aun.ownership.sdk.v1` 协议邀约。普通 daemon 与 bootstrap 控制通道使用同一个适配器,不再一律返回 `OWNERSHIP_APP_DEFERRED`。同一扫码会话的并发与重放请求复用原结果,SDK 变更后的未知回执不重发;`bind.response.success` 只表示受理,只有实时共识确认目标 Owner、sub 和 `lock=locked` 才返回 `bound`。控制通道的 `pureIdentity` 不拦截 SDK 协议邀约,仍不参与普通 Agent 的配置补绑。
143
145
 
144
146
  普通 Agent 的创建、手动绑定、启动补绑定和转让,在提交关系修改前实时读取目标 Owner 的远端已验签名片,要求名片 AID 匹配且 `type: human`;非 human 返回 `INVALID_OWNER`,无法读取、未验签、类型缺失或名片不匹配返回 `OWNER_IDENTITY_UNAVAILABLE`。接受绑定或转让邀约也执行此限制;当前进程没有请求投影时,先从历史消息定位原请求的目标用于类型预检,原请求真实性及固定参与方仍由 SDK 在提交时核验。拒绝邀约不受目标类型限制。该限制面向普通 Agent,不把 daemon Control AID 的身份规则改成 Agent 规则,也不追溯修改已有协议关系。
145
147