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
package/CHANGELOG.md CHANGED
@@ -5,6 +5,44 @@
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ ## 0.0.47 (2026-11-12)
9
+
10
+ ### 消息、会话与恢复
11
+
12
+ - 统一私聊、群聊和批次消息信封,明确来源关系、群角色及消息 ID;兼容旧信封,修复历史会话标题清理与导入候选识别。
13
+ - 队列恢复按消费账本和精确会话路由重建,跳过已覆盖历史;持久化失败保留顺序重试,恢复失败阻止不完整任务启动。
14
+ - Trigger 中断恢复沿用原执行尝试,使用独立投递标识继续处理,保留既有消费去重记录。
15
+ - 修复 Codex 0.164 已更新 Provider 索引、文件头仍旧时续聊被拒绝的问题;保留原线程、历史、备份和中断恢复,并完善冲突诊断。
16
+ - 修复 Windows Codex 会话索引与实际文件采用不同路径写法时的误报,区分索引缺失、字段异常与路径解析失败。
17
+
18
+ ### 身份、模板与权限
19
+
20
+ - 恢复 Evol App 扫码绑定,按请求指纹复用处理结果;提交后回执丢失时保留待确认状态,避免重复提交,允许提交前失败重新检查。
21
+ - 恢复 active Agent 的配置补绑;EC Web 初始化与页面入口核验主机 Owner,绑定待确认期间阻止重复发起。
22
+ - 统一多成员模板的检查、选择冻结、打包和安装协议,支持内部成员引用;异常恢复复用已确认的身份准备、绑定及 Owner 共识结果。
23
+ - 区分发送方关系与群角色,群默认角色缺失时回落 visitor;服务查看要求 member 及以上,禁止为保留服务类型配置调用规则。
24
+
25
+ ### 启动、升级与运行管理
26
+
27
+ - EC Web 启动不再等待 Agent 恢复;非启动必需依赖按需加载,主机信息探测移至后台,复用配置、关系扫描和状态查询快照,渠道连接并发上限设为八。
28
+ - 优化 Windows 进程查询和重启等待,提前请求旧进程优雅退出;通过子进程退出事件确认托管 EC Web 停止,Codex 子进程停止改用异步处理。
29
+ - 停机时取消待执行的所有权回调,停止耗时记录覆盖下线通知和渠道关闭阶段。
30
+ - 修复配置缺失时 Agent 无法停用、重复删除与卸载清理问题;修复升级监控暂存目录遗漏运行脚本,并兼容升级接口直接返回的 Menu 响应。
31
+ - Menu 短连接使用 SDK 标准事件接收响应,沿用渠道加密配置;远程作业等待过滤重复或乱序进度并释放连接资源。
32
+
33
+ ### 配置与内部维护
34
+
35
+ - Provider 自动迁移遇到规划冲突时保留现有配置、输出具体诊断并继续启动;写入前重新校验引用和连接设置。
36
+ - 避免配置迁移重复写入未变化内容,完善 Windows 文件替换重试、只读属性恢复与中断回滚,保留原始失败原因。
37
+ - 初始化使用当前 Schema 版本;Provider 同步遵循模型启用策略,旧 ID 迁移保留接口风格、模型列表和策略。
38
+ - 复用权限已满足的会话临时目录,目录准备失败时返回明确的不可重试错误。
39
+ - 完善内置资源完整性检查,整合渠道、关系、模板、工作区和台账模块,保留旧格式迁移及写入前保护。
40
+
41
+ ### 兼容要求
42
+
43
+ - 需要 Node.js >=22.16.0、@agentunion/fastaun ^0.5.34,配套 ec-web@0.0.47。
44
+ - Invoke 尚未完成,本版不将其列为可用功能;相关测试继续跳过。
45
+
8
46
  ## 0.0.46 (2026-11-11)
9
47
 
10
48
  ### 消息、会话与恢复
@@ -1,5 +1,4 @@
1
1
  import { assertRunnerModelAllowed, getRunnerCatalog, peekRunnerCatalog, catalogEfforts, resolveCatalogModel, assertCatalogSelectable } from '../core/model/model-catalog.js';
2
- import { query, forkSession as sdkForkSession, getSessionMessages as sdkGetSessionMessages, resolveSettings as sdkResolveSettings, } from '@anthropic-ai/claude-agent-sdk';
3
2
  import { spawn } from 'child_process';
4
3
  import { createRequire } from 'module';
5
4
  import { ensureDir } from '../utils/atomic-write.js';
@@ -445,6 +444,7 @@ function resolveClaudeSettingsDirectory(runtimeEnv) {
445
444
  async function assertClaudeSettingSourcesHaveLiteralSandboxPaths(cwd, settingSources, managedSettings) {
446
445
  if (process.platform !== 'linux' || settingSources.length === 0)
447
446
  return;
447
+ const { resolveSettings: sdkResolveSettings } = await import('@anthropic-ai/claude-agent-sdk');
448
448
  const resolved = await sdkResolveSettings({ cwd, settingSources, managedSettings });
449
449
  for (const source of resolved.sources) {
450
450
  const filesystem = source.settings.sandbox?.filesystem;
@@ -2784,6 +2784,9 @@ export class AgentRunner {
2784
2784
  : undefined;
2785
2785
  if (dependencies?.status === 'missing')
2786
2786
  throw createClaudeSandboxDependencyError(dependencies);
2787
+ // Load before creating temporary settings, so an import failure cannot
2788
+ // leave a partially prepared query behind.
2789
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
2787
2790
  const capabilityOptions = await this.resolveCapabilityRunOptions(projectPath);
2788
2791
  const managedSettings = callPermissionMode === 'fullaccess'
2789
2792
  ? undefined
@@ -3383,6 +3386,7 @@ export class AgentRunner {
3383
3386
  const resolvedModel = catalog && callModel
3384
3387
  ? resolveClaudeModelContext(resolveCatalogModel(catalog, callModel), catalog)
3385
3388
  : undefined;
3389
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
3386
3390
  return query({
3387
3391
  prompt,
3388
3392
  options: {
@@ -3624,10 +3628,12 @@ export class AgentRunner {
3624
3628
  return fs.existsSync(sessionFile) ? sessionFile : null;
3625
3629
  }
3626
3630
  async forkSession(agentSessionId, projectPath, title) {
3631
+ const { forkSession: sdkForkSession } = await import('@anthropic-ai/claude-agent-sdk');
3627
3632
  const result = await sdkForkSession(agentSessionId, { dir: projectPath, title });
3628
3633
  return result.sessionId;
3629
3634
  }
3630
3635
  async forkSessionAt(agentSessionId, projectPath, assistantMessageId, title) {
3636
+ const { forkSession: sdkForkSession } = await import('@anthropic-ai/claude-agent-sdk');
3631
3637
  const result = await sdkForkSession(agentSessionId, {
3632
3638
  dir: projectPath,
3633
3639
  upToMessageId: assistantMessageId,
@@ -3636,11 +3642,13 @@ export class AgentRunner {
3636
3642
  return result.sessionId;
3637
3643
  }
3638
3644
  async getSessionMessages(agentSessionId, projectPath) {
3645
+ const { getSessionMessages: sdkGetSessionMessages } = await import('@anthropic-ai/claude-agent-sdk');
3639
3646
  return sdkGetSessionMessages(agentSessionId, { dir: projectPath });
3640
3647
  }
3641
3648
  async rewindFiles(agentSessionId, projectPath, userMessageId) {
3642
3649
  logger.info(`[RewindFiles] agentSessionId=${agentSessionId} userMessageId=${userMessageId}`);
3643
3650
  const stderrChunks = [];
3651
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
3644
3652
  const tempQuery = query({
3645
3653
  prompt: '',
3646
3654
  options: {
@@ -9,7 +9,7 @@ import fs from 'fs';
9
9
  import path from 'path';
10
10
  import { ensureProcessManagedTempDir } from '../../cli/task-context.js';
11
11
  import { getPackageRoot, resolvePaths } from '../../paths.js';
12
- import { killProcess } from '../../utils/cross-platform.js';
12
+ import { killProcessAsync } from '../../utils/cross-platform.js';
13
13
  import { isCurrentManagedHookLauncher } from './diagnostics.js';
14
14
  import { registerCodexAppServerProcess, unregisterCodexAppServerProcess, } from './app-server-registry.js';
15
15
  const BUILT_IN_CODEX_PROVIDER_IDS = new Set(['openai']);
@@ -444,35 +444,44 @@ export class CodexAppServerClient {
444
444
  this.cleanupManagedHookRuntime();
445
445
  return;
446
446
  }
447
- // 优雅关闭:先关闭 stdin,然后发送 SIGTERM,等待进程退出
448
- proc.stdin.end();
449
- if (process.platform === 'win32' && proc.pid)
450
- killProcess(proc.pid, false);
451
- else
452
- proc.kill('SIGTERM');
453
- // 等待进程退出,最多等待 5 秒
454
- await new Promise((resolve) => {
455
- let exited = false;
456
- const timeout = setTimeout(() => {
457
- if (exited)
458
- return;
447
+ // Observe this child before closing stdin or dispatching termination. The
448
+ // Windows command is asynchronous, so its exit can arrive while we await it.
449
+ let exited = proc.exitCode !== null || proc.signalCode !== null;
450
+ let resolveExit;
451
+ const exit = new Promise(resolve => { resolveExit = resolve; });
452
+ const onExit = () => { exited = true; resolveExit(); };
453
+ proc.once('exit', onExit);
454
+ let timeout;
455
+ try {
456
+ if (!exited)
457
+ proc.stdin.end();
458
+ if (!exited) {
459
+ if (process.platform === 'win32' && proc.pid)
460
+ await killProcessAsync(proc.pid, false);
461
+ else
462
+ proc.kill('SIGTERM');
463
+ }
464
+ if (exited)
465
+ return;
466
+ // Retain the original five-second grace period after the termination
467
+ // command settles; an observed exit cancels escalation.
468
+ await Promise.race([exit, new Promise(resolve => { timeout = setTimeout(resolve, 5_000); })]);
469
+ if (!exited) {
459
470
  logger.warn('[CodexAppServer] Process did not exit after SIGTERM, sending SIGKILL');
460
471
  try {
461
472
  if (process.platform === 'win32' && proc.pid)
462
- killProcess(proc.pid, true);
473
+ await killProcessAsync(proc.pid, true);
463
474
  else
464
475
  proc.kill('SIGKILL');
465
476
  }
466
477
  catch { }
467
- resolve();
468
- }, 5000);
469
- proc.once('exit', () => {
470
- exited = true;
471
- clearTimeout(timeout);
472
- resolve();
473
- });
474
- });
475
- this.cleanupManagedHookRuntime();
478
+ }
479
+ }
480
+ finally {
481
+ clearTimeout(timeout);
482
+ proc.off('exit', onExit);
483
+ this.cleanupManagedHookRuntime();
484
+ }
476
485
  }
477
486
  async ensureStarted() {
478
487
  if (this.initialized)
@@ -1,5 +1,4 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { StorageLowLevel, StorageVFS } from '@agentunion/fastaun';
3
2
  export const DEFAULT_FS_CAT_BYTES = 128 * 1024;
4
3
  export const MAX_FS_CAT_BYTES = 128 * 1024;
5
4
  export class FsReadBudgetError extends Error {
@@ -46,6 +45,7 @@ async function downloadWithinBudget(url, maxBytes, headers) {
46
45
  }
47
46
  export async function readPersonalFsBytesWithinBudget(client, path, maxBytes, options) {
48
47
  validateFsReadBudget(maxBytes);
48
+ const { StorageLowLevel, StorageVFS } = await import('@agentunion/fastaun');
49
49
  const lowlevel = new StorageLowLevel(client);
50
50
  const getObject = lowlevel.getObject.bind(lowlevel);
51
51
  lowlevel.getObject = params => getObject({ ...params, offset: 0, limit: maxBytes + 1 });
@@ -3794,7 +3794,7 @@ export class AUNChannel {
3794
3794
  return;
3795
3795
  }
3796
3796
  // bind.request:Evol App 绑定请求。绕过白名单透传原始 payload JSON 给 bridge,
3797
- // 由控制 AID 的 onMessage 处理器(BindService.handleRequest)解析并回 bind.response。
3797
+ // 由控制 AID 的 BindService 校验扫码凭证,再通过统一 Ownership 服务发起协议绑定。
3798
3798
  // 透传 encrypted:bind.response 须与请求的加密/明文对称(见 onMessage 处理)。
3799
3799
  if (p2pPayloadType === AUNChannel.BIND_REQUEST_TYPE) {
3800
3800
  this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq);
@@ -5042,8 +5042,8 @@ export class AUNChannel {
5042
5042
  if (!config)
5043
5043
  return undefined;
5044
5044
  const lifecycle = resolveAgentLifecycle(config);
5045
- // Legacy Owner hints are initialization inputs; active Agents need no automatic bind reconciliation.
5046
- if (lifecycle === null || lifecycle === 'active')
5045
+ // Existing active Agents may still carry an unfulfilled configured binding target.
5046
+ if (lifecycle === null)
5047
5047
  return undefined;
5048
5048
  return firstConfiguredOwner(config);
5049
5049
  }
@@ -5108,12 +5108,23 @@ export class AUNChannel {
5108
5108
  const attemptKey = JSON.stringify([subjectAid, ownerAid]);
5109
5109
  if (AUNChannel.configuredOwnerBindAttempts.has(attemptKey))
5110
5110
  return;
5111
- // Claim before awaiting submission: an error or lost receipt must not cause automatic resends.
5111
+ // Reserve across channel recreation while preparation is in flight. Only entering
5112
+ // an SDK mutation consumes the attempt; a lost receipt must never release it.
5112
5113
  AUNChannel.configuredOwnerBindAttempts.add(attemptKey);
5113
- logger.info(`${this.logPrefix()} Submitting configured Owner binding invitation: `
5114
- + `subject=${subjectAid} owner=${ownerAid} consensus=${current.consensusStatus}`);
5115
- await ownerResolver.bind(subjectAid, ownerAid, () => this.isCurrentConfiguredOwnerBind(client, epoch) && this.configuredOwnerAid() === ownerAid
5116
- && !ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid));
5114
+ let submissionStarted = false;
5115
+ try {
5116
+ await ownerResolver.bind(subjectAid, ownerAid, () => this.isCurrentConfiguredOwnerBind(client, epoch) && this.configuredOwnerAid() === ownerAid
5117
+ && !ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid), () => {
5118
+ submissionStarted = true;
5119
+ logger.info(`${this.logPrefix()} Submitting configured Owner binding invitation: `
5120
+ + `subject=${subjectAid} owner=${ownerAid} consensus=${current.consensusStatus}`);
5121
+ });
5122
+ }
5123
+ catch (error) {
5124
+ if (!submissionStarted)
5125
+ AUNChannel.configuredOwnerBindAttempts.delete(attemptKey);
5126
+ throw error;
5127
+ }
5117
5128
  }
5118
5129
  /** 判断 terminal_failed 的 reason 是否属于"被踢"类 */
5119
5130
  isKickReason(reason) {
@@ -48,7 +48,7 @@ export class DaemonChannel {
48
48
  // 启动前跑一次 expire 扫描(成本低,只读少量小文件)
49
49
  this.runExpireCleanupSafely();
50
50
  const runId = ctx.runId;
51
- const pendingId = ctx.attemptId ?? runId;
51
+ const pendingId = ctx.deliveryId ?? ctx.attemptId ?? runId;
52
52
  const messageId = pendingId;
53
53
  const startedAt = Date.now();
54
54
  const remainingExecutionMs = typeof ctx.executionDeadlineAt === 'number'
@@ -18,7 +18,7 @@ import { ecwebVersionRequirementError, resolveEcwebLaunchCommand } from '../ecwe
18
18
  import { stopEcwebForRestart } from '../ecweb/runtime/lifecycle.js';
19
19
  import { resolveEcwebExternalUrl, fetchRemotePairingCode, buildEcwebPairingUrl } from '../ecweb/pairing.js';
20
20
  import { isHostChinese } from '../utils/locale.js';
21
- import { scanInstances, cleanupInstances, findOrphanProcesses } from '../utils/instance-registry.js';
21
+ import { scanInstances, hasLiveMain, hasLiveRestartMonitor, cleanupInstances, findOrphanProcesses } from '../utils/instance-registry.js';
22
22
  import { filterLogFiles, deriveLogTypes, computePreChecked, validateLogTypes, shortLogName as shortLogNameLocal, isWatchLogFile } from './watch-logs.js';
23
23
  import { printCodeStats } from './code-stats.js';
24
24
  import { StartupTracer, STARTUP_TRACE_ID_ENV, formatMs, formatSlowestSpans, findTraceRecord } from '../utils/startup-trace.js';
@@ -322,14 +322,15 @@ async function launchPackageLifecycle(source, log, options = {}) {
322
322
  const result = await platform.launchMonitorAndConfirm(args, env, pid => requestId
323
323
  ? readRestartRequest(path.join(root, 'data', 'daemon', 'control', 'restart-pending.json'), requestId)?.status === 'accepted'
324
324
  || readRestartRequest(path.join(root, 'data', 'daemon', 'control', 'restart-pending.json'), requestId)?.status === 'ready'
325
- : scanInstances().restartMonitors.some(item => item.alive && item.record.pid === pid), pid => scanInstances().restartMonitors.some(item => item.alive
326
- && item.record.pid !== pid
327
- && (!requestId || (item.record.requestId === requestId && item.record.phase === 'accepted'))), {
325
+ : hasLiveRestartMonitor({ pid }),
326
+ // Launch confirmation only observes monitors. Probing the still-running
327
+ // daemon here adds process-table queries to each unsuccessful poll.
328
+ pid => hasLiveRestartMonitor({ excludePid: pid, ...(requestId ? { requestId, phase: 'accepted' } : {}) }), {
328
329
  requestId,
329
330
  logFilePath: requestId ? path.join(root, 'logs', `restart-launch-${requestId}.log`) : undefined,
330
331
  onSpawn: pid => { if (requestId)
331
332
  updateRestartRequest(path.join(root, 'data', 'daemon', 'control', 'restart-pending.json'), requestId, { launcherPid: pid }); },
332
- isPendingInRegistry: () => !!requestId && scanInstances().restartMonitors.some(item => item.alive && item.record.requestId === requestId),
333
+ isPendingInRegistry: () => requestId ? hasLiveRestartMonitor({ requestId }) : false,
333
334
  });
334
335
  if (!result.ok && !result.pending && launch.stageDir)
335
336
  platform.cleanupMonitorStage(launch.stageDir);
@@ -1209,18 +1210,19 @@ export async function cmdRestart(opts = {}) {
1209
1210
  console.log(` ${describeRunMode()}`);
1210
1211
  if (!await ensureCodexHookBeforeLifecycle())
1211
1212
  return;
1212
- const initialStatus = scanInstances();
1213
1213
  const socketPath = resolvePaths().socket;
1214
1214
  const ping = await probeDaemon(socketPath);
1215
- if (ping && !hasVisibleDaemonPid(initialStatus, ping)) {
1216
- // Only pay for a cross-host process-table scan when the IPC PID is not
1217
- // present in our registry. This is the exceptional PID-namespace case;
1218
- // healthy restarts no longer scan every Node process before stopping.
1219
- const initialRuntimeOrphans = findOrphanProcesses().filter(orphan => isRuntimeOrphan(orphan));
1220
- if (await tryDelegatedDaemonRestart(socketPath))
1221
- return;
1222
- if (initialRuntimeOrphans.length === 0 && rejectPidIsolatedLifecycle('restart', initialStatus, ping))
1223
- return;
1215
+ if (ping && !await hasLiveMain(ping.pid)) {
1216
+ // Keep the full PID-namespace fallback for unregistered/unobservable targets.
1217
+ // Normal restarts only inspect the responding PID, without AID activity logs.
1218
+ const initialStatus = scanInstances({ includeAidActivity: false });
1219
+ if (!hasVisibleDaemonPid(initialStatus, ping)) {
1220
+ const initialRuntimeOrphans = findOrphanProcesses(initialStatus).filter(orphan => isRuntimeOrphan(orphan));
1221
+ if (await tryDelegatedDaemonRestart(socketPath))
1222
+ return;
1223
+ if (initialRuntimeOrphans.length === 0 && rejectPidIsolatedLifecycle('restart', initialStatus, ping))
1224
+ return;
1225
+ }
1224
1226
  }
1225
1227
  // The shared launchPackageLifecycle path delegates to launchMonitorAndConfirm;
1226
1228
  // the monitor retains shutdown, orphan checks, build and rollback ownership.
@@ -3313,7 +3315,7 @@ function renderEcwebStatus(status) {
3313
3315
  }
3314
3316
  }
3315
3317
  else if (status.startupState === 'waiting') {
3316
- console.log('🔭 ECWeb: 等待优先恢复组放行,将与空闲 Agent 一起启动');
3318
+ console.log('🔭 ECWeb: 等待启动');
3317
3319
  }
3318
3320
  else if (status.startupState === 'starting' && status.status !== 'process-not-ready') {
3319
3321
  console.log('🔭 ECWeb: 正在启动,等待健康检查');
@@ -3451,6 +3453,8 @@ export async function startEcwebIfEnabled(p, options = {}) {
3451
3453
  console.log(`⚠ ECWeb 进程存活但 daemon 未就绪: ${readiness.error || 'unknown'}`);
3452
3454
  if (externalUrl)
3453
3455
  console.log(` 外网访问: ${externalUrl}`);
3456
+ if (readiness.ready)
3457
+ await printEcwebPairingInfo(cfg);
3454
3458
  return true;
3455
3459
  }
3456
3460
  }
@@ -3513,14 +3517,11 @@ export async function startEcwebIfEnabled(p, options = {}) {
3513
3517
  startedAt = getProcessStartTime(pid);
3514
3518
  let processAlive = false;
3515
3519
  let readiness = null;
3516
- let pair = null;
3517
3520
  for (let i = 0; i < 40; i++) {
3518
3521
  const registered = readEcwebInstanceEntries(p).find(entry => entry.record.pid === pid)?.record;
3519
3522
  processAlive = registered ? await probeEcwebLiveness(registered.port, registered) : false;
3520
3523
  if (processAlive) {
3521
3524
  readiness = await probeEcwebReadiness(port);
3522
- if (readiness.ready)
3523
- pair = await fetchRemotePairingCode();
3524
3525
  break;
3525
3526
  }
3526
3527
  await sleep(250);
@@ -3533,15 +3534,8 @@ export async function startEcwebIfEnabled(p, options = {}) {
3533
3534
  if (!readiness?.ready) {
3534
3535
  console.log(`⚠ ECWeb 进程存活但 daemon 未就绪: ${readiness?.error || 'unknown'}`);
3535
3536
  }
3536
- else if (pair) {
3537
- const mins = Math.max(0, Math.round((pair.expiresAt - Date.now()) / 60000));
3538
- console.log(` 配对码: ${pair.code} (约 ${mins} 分钟内有效,仅可配对一次,已配对过的浏览器无需重新配对)`);
3539
- const pairingUrl = buildEcwebPairingUrl(cfg, pair.code);
3540
- if (pairingUrl)
3541
- console.log(` 一键登录: ${pairingUrl}`);
3542
- }
3543
3537
  else {
3544
- console.log(' daemon 尚未提供配对码;EvolCore 启动后可通过 /pair 或 ECWeb 页面获取');
3538
+ await printEcwebPairingInfo(cfg);
3545
3539
  }
3546
3540
  return true;
3547
3541
  }
@@ -3566,24 +3560,18 @@ export async function startEcwebIfEnabled(p, options = {}) {
3566
3560
  return false;
3567
3561
  }
3568
3562
  }
3569
- /** 显示 ecweb 访问信息 + 配对码(启动后 ecweb 需要一点时间起 HTTP,故重试几次)。 */
3570
- async function printEcwebAccess(port) {
3571
- console.log(`🔭 ECWeb http://localhost:${port}`);
3572
- let pair = null;
3573
- for (let i = 0; i < 10 && !pair; i++) {
3574
- pair = await fetchRemotePairingCode();
3575
- if (!pair)
3576
- await sleep(300);
3577
- }
3563
+ /** 新启动和复用已有 ECWeb 时,统一显示 daemon 提供的配对信息。 */
3564
+ async function printEcwebPairingInfo(config) {
3565
+ const pair = await fetchRemotePairingCode();
3578
3566
  if (pair) {
3579
3567
  const mins = Math.max(0, Math.round((pair.expiresAt - Date.now()) / 60000));
3580
3568
  console.log(` 配对码: ${pair.code} (约 ${mins} 分钟内有效,仅可配对一次,token 缓存 7 天,有访问自动续期)`);
3581
- const pairingUrl = buildEcwebPairingUrl(loadDaemonConfig(), pair.code);
3569
+ const pairingUrl = buildEcwebPairingUrl(config, pair.code);
3582
3570
  if (pairingUrl)
3583
3571
  console.log(` 一键登录: ${pairingUrl}`);
3584
3572
  }
3585
3573
  else {
3586
- console.log(' 配对码: 暂不可用(稍后重试 ec watch web,或查看 logs/watch-web.log)');
3574
+ console.log(' 配对码: 暂不可用(稍后重新运行 ec init --web,或在本机 ECWeb 页面获取)');
3587
3575
  }
3588
3576
  }
3589
3577
  async function cmdWatchWeb() {
@@ -3606,7 +3594,7 @@ async function cmdWatchWeb() {
3606
3594
  const ok = await startEcwebIfEnabled(p, { forceRestart: true });
3607
3595
  if (!ok)
3608
3596
  process.exit(1); // 失败原因已由 startEcwebIfEnabled 打印
3609
- // 启动成功的访问信息已由 startEcwebIfEnabled 打印,无需 printEcwebAccess 重复输出
3597
+ // 启动成功的访问信息已由 startEcwebIfEnabled 打印。
3610
3598
  }
3611
3599
  function sleep(ms) {
3612
3600
  return new Promise(resolve => setTimeout(resolve, ms));
@@ -44,11 +44,14 @@ export async function isRecordedProcessGone(pid, expectedStartedAt) {
44
44
  return !startTimeMatches(expectedStartedAt, actual);
45
45
  }
46
46
  /** Clean up only registered, identity-verified EvolCore Codex app-server children. */
47
- export async function stopCodexAppServerOrphans() {
47
+ export async function stopCodexAppServerOrphans(snapshot) {
48
48
  const entries = listCodexAppServerProcesses();
49
49
  if (entries.length === 0)
50
50
  return 0;
51
- const codexProcs = new Set(platform.findProcesses('codex app-server'));
51
+ // The restart monitor already captured all Windows command lines after the
52
+ // daemon exited. Reuse that enumeration, but never its stale signal authority.
53
+ const reuseSnapshot = platform.isWindows && snapshot?.complete;
54
+ const codexProcs = reuseSnapshot ? undefined : new Set(platform.findProcesses('codex app-server'));
52
55
  const exits = [];
53
56
  for (const entry of entries) {
54
57
  const { pid, startedAt } = entry.record;
@@ -58,7 +61,18 @@ export async function stopCodexAppServerOrphans() {
58
61
  unregisterCodexAppServerProcess(entry.filePath);
59
62
  continue;
60
63
  }
61
- if (!codexProcs.has(pid))
64
+ if (reuseSnapshot) {
65
+ const command = snapshot.commandLines.get(pid) ?? '';
66
+ const capturedStart = snapshot.startedAt.get(pid);
67
+ if (capturedStart === undefined || !startTimeMatches(startedAt, capturedStart))
68
+ continue;
69
+ // Native executables and npm's cmd wrapper both carry the app-server
70
+ // token. Registration and fresh identity verification scope termination.
71
+ if (!/(?:^|[\\/"'\s])codex(?:\.(?:exe|cmd|bat|js|mjs))?(?=$|["'\s])/i.test(command)
72
+ || !/(?:^|["'\s^])app-server(?=$|["'\s^])/.test(command))
73
+ continue;
74
+ }
75
+ else if (!codexProcs.has(pid))
62
76
  continue;
63
77
  if (platform.killProcess(pid, true)) {
64
78
  // Signal acceptance is not proof of exit. Confirm children concurrently
@@ -179,11 +179,11 @@ async function reloadAgentAfterBind(aid) {
179
179
  console.log(' ✓ agent owner 已热重载');
180
180
  }
181
181
  else if (result?.error) {
182
- console.log(` ⚠ agent owner 已写入配置,热重载失败:${result.error}`);
182
+ console.log(` ⚠ Agent Owner 协议绑定已确认,热重载失败:${result.error}`);
183
183
  }
184
184
  }
185
185
  catch {
186
- console.log(' ⚠ agent owner 已写入配置,daemon 未响应热重载;下次启动生效');
186
+ console.log(' ⚠ Agent Owner 协议绑定已确认,daemon 未响应热重载;下次启动恢复');
187
187
  }
188
188
  }
189
189
  async function printQr(qrData) {
package/dist/cli/init.js CHANGED
@@ -8,6 +8,7 @@ import { scanInstances } from '../utils/instance-registry.js';
8
8
  import { saveDefaultsSafe, loadDaemonConfig, saveDaemonConfig } from '../config-store.js';
9
9
  import { currentVersion } from '../config/schema-registry.js';
10
10
  import { DEFAULT_ECWEB_PORT, ecwebService, setEcwebEnabled } from '../config/daemon-services.js';
11
+ import { resolveEcwebExternalUrl } from '../ecweb/pairing.js';
11
12
  import { ensureControlAgentMd, generateControlAid, hasLocalControlIdentity, missingControlIdentityMessage, resolveControlAidDomain, submitControlAidRegistration, } from '../aun/aid/control-aid.js';
12
13
  import { isValidAid } from '../aun/aid/validation.js';
13
14
  /**
@@ -366,7 +367,12 @@ export async function cmdInitWeb(dependencies = {}) {
366
367
  }
367
368
  const currentConfig = (dependencies.loadConfig ?? loadDaemonConfig)();
368
369
  const port = ecwebService(currentConfig.services)?.port ?? DEFAULT_ECWEB_PORT;
369
- console.log(`\nECweb 初始化: http://localhost:${port}/init`);
370
+ const externalUrl = resolveEcwebExternalUrl(currentConfig);
371
+ console.log('\nECweb 初始化:');
372
+ console.log(` 本地访问: http://localhost:${port}/init`);
373
+ if (externalUrl)
374
+ console.log(` 外网访问: ${externalUrl}/init`);
375
+ console.log(' 远程首次访问需要配对;已有有效 token 可直接继续。');
370
376
  return true;
371
377
  }
372
378
  // ==================== Main ====================