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.
- package/CHANGELOG.md +38 -0
- package/dist/agents/claude-runner.js +9 -1
- package/dist/agents/codex/app-server-client.js +32 -23
- package/dist/aun/group/fs-download.js +1 -1
- package/dist/channels/aun.js +19 -8
- package/dist/channels/daemon.js +1 -1
- package/dist/cli/daemon-commands.js +27 -39
- package/dist/cli/daemon-lifecycle-client.js +17 -3
- package/dist/cli/init-channel.js +2 -2
- package/dist/cli/init.js +7 -1
- package/dist/cli/restart-monitor.js +104 -28
- package/dist/cli/task-context.js +83 -15
- package/dist/cli/upgrade-command.js +4 -2
- package/dist/config/config-manager.js +29 -17
- package/dist/config/peer-book-store.js +18 -10
- package/dist/config/provider-identity-migration.js +157 -5
- package/dist/config/schema-migration.js +123 -16
- package/dist/config/schema-registry.js +6 -2
- package/dist/core/agent-runtime.js +6 -5
- package/dist/core/auth/agent-delegation.js +8 -3
- package/dist/core/auth/delegation-diagnostics.js +56 -15
- package/dist/core/auth/operation-authorizer.js +1 -1
- package/dist/core/command/menu-handler.js +4 -4
- package/dist/core/command/slash-handler.js +4 -6
- package/dist/core/daemon-bootstrap.js +11 -9
- package/dist/core/daemon-control.js +1 -3
- package/dist/core/daemon-lifecycle.js +50 -40
- package/dist/core/evolagent-registry.js +8 -2
- package/dist/core/host-snapshot.js +9 -4
- package/dist/core/initialization/service.js +22 -4
- package/dist/core/ipc-registration.js +4 -3
- package/dist/core/memory/consolidation.js +6 -6
- package/dist/core/ownership/owner-resolver.js +27 -10
- package/dist/core/relation/peer-identity.js +5 -1
- package/dist/core/relation/same-owner-proof.js +2 -1
- package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
- package/dist/core/session/session-file-health.js +36 -7
- package/dist/core/task/task-image-resources.js +1 -1
- package/dist/ecweb/runtime/lifecycle.js +64 -15
- package/dist/ecweb/runtime/supervisor.js +2 -15
- package/dist/index.js +37 -34
- package/dist/ipc.js +2 -1
- package/dist/trigger/scheduler.js +4 -0
- package/dist/trigger/state.js +7 -0
- package/dist/utils/aid-bind.js +155 -18
- package/dist/utils/atomic-write.js +3 -3
- package/dist/utils/cross-platform.js +24 -5
- package/dist/utils/error-utils.js +13 -0
- package/dist/utils/instance-registry.js +61 -0
- package/dist/utils/process-introspect.js +152 -7
- package/dist/utils/upgrade-jobs.js +4 -4
- package/kits/docs/evolcore/aid.md +3 -1
- package/kits/docs/evolcore/provider.md +10 -2
- package/package.json +2 -2
|
@@ -23,7 +23,7 @@ import { resolveGlobalPkg } from '../../utils/npm-ops.js';
|
|
|
23
23
|
import { executeUpgradeAction, parseUpgradeMode } from '../../utils/upgrade-jobs.js';
|
|
24
24
|
import { launchMonitorAndConfirm, resolveCliEntry, isProcessRunning } from '../../utils/cross-platform.js';
|
|
25
25
|
import { cachedCliVersion } from '../../utils/cross-platform.js';
|
|
26
|
-
import {
|
|
26
|
+
import { hasLiveRestartMonitor } from '../../utils/instance-registry.js';
|
|
27
27
|
import { loadDefaults, loadDaemonConfig } from '../../config-store.js';
|
|
28
28
|
import { buildEcwebPairingUrl } from '../../ecweb/pairing.js';
|
|
29
29
|
import { WEB_PACKAGE_NAME, RESTART_REQUEST_ID_ENV, RUNTIME_HOME_ENV, SESSION_ID_ENV } from '../../product.js';
|
|
@@ -5007,7 +5007,7 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
|
|
|
5007
5007
|
data: { reasonCode: 'RESTART_ENTRY_MISSING', entry: monitorEntry.entry },
|
|
5008
5008
|
};
|
|
5009
5009
|
}
|
|
5010
|
-
if (
|
|
5010
|
+
if (await hasLiveRestartMonitor()
|
|
5011
5011
|
|| !createRestartRequest(pendingFile, restartInfo, isProcessRunning)) {
|
|
5012
5012
|
return { error: '已有重启请求正在处理,请等待其结果,不要重复发起。', code: 'RESTART_ALREADY_PENDING' };
|
|
5013
5013
|
}
|
|
@@ -5022,12 +5022,12 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
|
|
|
5022
5022
|
[SESSION_ID_ENV]: '',
|
|
5023
5023
|
[AGENT_DELEGATION_TOKEN_ENV]: '',
|
|
5024
5024
|
[RESTART_REQUEST_ID_ENV]: requestId,
|
|
5025
|
-
}, () => accepted(), () =>
|
|
5025
|
+
}, () => accepted(), () => hasLiveRestartMonitor({ requestId, phase: 'accepted' }), {
|
|
5026
5026
|
requestId,
|
|
5027
5027
|
timeoutMs: 8_000,
|
|
5028
5028
|
logFilePath,
|
|
5029
5029
|
onSpawn: pid => { updateRestartRequest(pendingFile, requestId, { launcherPid: pid }); },
|
|
5030
|
-
isPendingInRegistry: () =>
|
|
5030
|
+
isPendingInRegistry: () => hasLiveRestartMonitor({ requestId }),
|
|
5031
5031
|
});
|
|
5032
5032
|
if (!restartLaunch.ok) {
|
|
5033
5033
|
if (restartLaunch.pending) {
|
|
@@ -38,7 +38,7 @@ import { normalizePermissionMode as normalizePermissionModeContract, PUBLIC_PERM
|
|
|
38
38
|
import { isManagementRole } from '../../config/builtin-roles.js';
|
|
39
39
|
import { isSystemControlChannel } from '../system-channels.js';
|
|
40
40
|
import { launchMonitorAndConfirm, resolveMonitorLaunch, cleanupMonitorStage, isProcessRunning } from '../../utils/cross-platform.js';
|
|
41
|
-
import {
|
|
41
|
+
import { hasLiveRestartMonitor } from '../../utils/instance-registry.js';
|
|
42
42
|
import { guardIdleCommand, guardGroupSlashCommand, guardKnownCommand, guardRoleCommand, guardThreadCommand, isRecognizedSlashCommand, normalizeSlashContent, parseFullAccessCommand, probeSessionActivity, } from './slash-gate.js';
|
|
43
43
|
import { MAX_AUN_ATTACHMENT_SIZE } from '../../aun/msg/upload.js';
|
|
44
44
|
import { DEFAULT_SESSION_LOOP_SECONDS, MAX_SESSION_LOOP_PROMPT_LENGTH, MAX_SESSION_LOOP_SECONDS, MIN_SESSION_LOOP_SECONDS, refreshSessionLoopTarget, resolveCurrentSessionLoopTarget, resolveSessionLoopTarget, sessionLoopPayload, validateIdleSeconds, writeSessionLoopConfig, } from '../session/session-idle-monitor.js';
|
|
@@ -3256,19 +3256,17 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
|
|
|
3256
3256
|
const controlDir = daemonControlDir();
|
|
3257
3257
|
fs.mkdirSync(controlDir, { recursive: true });
|
|
3258
3258
|
const pendingFile = path.join(controlDir, 'restart-pending.json');
|
|
3259
|
-
if (
|
|
3259
|
+
if (await hasLiveRestartMonitor()
|
|
3260
3260
|
|| !createRestartRequest(pendingFile, restartInfo, isProcessRunning)) {
|
|
3261
3261
|
if (monitorEntry.stageDir)
|
|
3262
3262
|
cleanupMonitorStage(monitorEntry.stageDir);
|
|
3263
3263
|
return { code: 'RESTART_PENDING_CONFIRMATION', reason: '已有重启请求正在处理', requestId: restartInfo.requestId };
|
|
3264
3264
|
}
|
|
3265
|
-
const confirmation = await launchMonitorAndConfirm([...monitorEntry.args, 'restart-monitor', autoUpgrade ? '--apply-package-upgrades' : '--skip-package-upgrades'], { EVOLCORE_HOME: resolvePaths().root, ...monitorEntry.env, [RESTART_REQUEST_ID_ENV]: restartInfo.requestId }, pid =>
|
|
3266
|
-
&& m.record.requestId === restartInfo.requestId && m.record.phase === 'accepted'), pid => scanInstances().restartMonitors.some(m => m.alive && m.record.pid !== pid
|
|
3267
|
-
&& m.record.requestId === restartInfo.requestId && m.record.phase === 'accepted'), {
|
|
3265
|
+
const confirmation = await launchMonitorAndConfirm([...monitorEntry.args, 'restart-monitor', autoUpgrade ? '--apply-package-upgrades' : '--skip-package-upgrades'], { EVOLCORE_HOME: resolvePaths().root, ...monitorEntry.env, [RESTART_REQUEST_ID_ENV]: restartInfo.requestId }, pid => hasLiveRestartMonitor({ pid, requestId: restartInfo.requestId, phase: 'accepted' }), pid => hasLiveRestartMonitor({ excludePid: pid, requestId: restartInfo.requestId, phase: 'accepted' }), {
|
|
3268
3266
|
requestId: restartInfo.requestId,
|
|
3269
3267
|
logFilePath: path.join(resolvePaths().logs, `restart-launch-${restartInfo.requestId}.log`),
|
|
3270
3268
|
onSpawn: pid => { updateRestartRequest(pendingFile, restartInfo.requestId, { launcherPid: pid }); },
|
|
3271
|
-
isPendingInRegistry: () =>
|
|
3269
|
+
isPendingInRegistry: () => hasLiveRestartMonitor({ requestId: restartInfo.requestId }),
|
|
3272
3270
|
});
|
|
3273
3271
|
if (!confirmation.ok) {
|
|
3274
3272
|
if (confirmation.pending) {
|
|
@@ -13,6 +13,7 @@ import { controlReplyContext } from './message/outbound.js';
|
|
|
13
13
|
import { TriggerDefinitionManager } from '../trigger/manager.js';
|
|
14
14
|
import { seedUpgradeCheckTrigger } from '../trigger/system-definitions.js';
|
|
15
15
|
import { ownerResolver } from './ownership/owner-resolver.js';
|
|
16
|
+
import { ecwebInitializationService } from './initialization/service.js';
|
|
16
17
|
export function detectAvailableBaseagents() {
|
|
17
18
|
// 与 init/ECWeb 的探测保持同一判据;claude 在这里也走内置二进制,
|
|
18
19
|
// 不再只看 PATH——否则 daemon 会对外声明一个实际跑不起来的 baseagent。
|
|
@@ -35,6 +36,7 @@ export async function runBindBootstrapDaemon(daemonCfg) {
|
|
|
35
36
|
receiverAid: daemonCfg.aid,
|
|
36
37
|
getAvailableBaseagents: detectAvailableBaseagents,
|
|
37
38
|
getUptimeSeconds: () => Math.floor(process.uptime()),
|
|
39
|
+
handleAppBindRequest: (payload, senderAid, encrypted) => ecwebInitializationService.handleAppBindRequest(payload, senderAid, encrypted),
|
|
38
40
|
});
|
|
39
41
|
bindService.startCleanup();
|
|
40
42
|
ownerResolver.setDaemonAid(daemonCfg.aid);
|
|
@@ -55,13 +57,6 @@ export async function runBindBootstrapDaemon(daemonCfg) {
|
|
|
55
57
|
aunTrace: daemonCfg.debug?.aunTrace,
|
|
56
58
|
aunSdkLog: daemonCfg.debug?.aunSdkLog,
|
|
57
59
|
});
|
|
58
|
-
try {
|
|
59
|
-
await controlChannel.connect();
|
|
60
|
-
logger.info(`✓ 控制 AID 已连接: ${daemonCfg.aid}`);
|
|
61
|
-
}
|
|
62
|
-
catch (error) {
|
|
63
|
-
logger.warn(`控制 AID 首连失败(后台自动重连,不影响 bootstrap IPC): ${error?.message || error}`);
|
|
64
|
-
}
|
|
65
60
|
controlChannel.onMessage(async (opts) => {
|
|
66
61
|
const text = (opts.content || '').trim();
|
|
67
62
|
let parsed = null;
|
|
@@ -71,11 +66,18 @@ export async function runBindBootstrapDaemon(daemonCfg) {
|
|
|
71
66
|
catch {
|
|
72
67
|
parsed = null;
|
|
73
68
|
}
|
|
74
|
-
const response = parsed ? await bindService.handleRequest(parsed, opts.peerId) : null;
|
|
69
|
+
const response = parsed ? await bindService.handleRequest(parsed, opts.peerId, opts.encrypted === true) : null;
|
|
75
70
|
if (response) {
|
|
76
|
-
await controlChannel.
|
|
71
|
+
await controlChannel.sendStructuredOrThrow(opts.channelId, response, controlReplyContext(opts));
|
|
77
72
|
}
|
|
78
73
|
});
|
|
74
|
+
try {
|
|
75
|
+
await controlChannel.connect();
|
|
76
|
+
logger.info(`✓ 控制 AID 已连接: ${daemonCfg.aid}`);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
logger.warn(`控制 AID 首连失败(后台自动重连,不影响 bootstrap IPC): ${error?.message || error}`);
|
|
80
|
+
}
|
|
79
81
|
const controlToken = crypto.randomBytes(32).toString('base64url');
|
|
80
82
|
fs.mkdirSync(path.dirname(resolvePaths().controlToken), { recursive: true });
|
|
81
83
|
fs.writeFileSync(resolvePaths().controlToken, controlToken, { mode: 0o600 });
|
|
@@ -15,7 +15,6 @@ import { resolvePaths } from '../paths.js';
|
|
|
15
15
|
import { ownerResolver, OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, OWNERSHIP_CACHE_MAX_AGE_MS } from './ownership/owner-resolver.js';
|
|
16
16
|
import { subscribeUpgradeJob } from '../utils/upgrade-jobs.js';
|
|
17
17
|
import { subscribeTemplateJob } from '../agent-template/service.js';
|
|
18
|
-
import { ecwebInitializationService } from './initialization/service.js';
|
|
19
18
|
const controlMenuDeduper = new MenuRequestDeduper();
|
|
20
19
|
export function startDaemonControlAid({ daemonCfg, cmdHandler, bindService, diagService, getProcessOwners, ecwebSupervisor, onServiceProxyManager, connectChannel, startupTrace, waitForServices, }) {
|
|
21
20
|
if (!daemonCfg.aid)
|
|
@@ -120,8 +119,7 @@ export function startDaemonControlAid({ daemonCfg, cmdHandler, bindService, diag
|
|
|
120
119
|
}
|
|
121
120
|
};
|
|
122
121
|
if (bindService && parsed?.type === 'bind.request') {
|
|
123
|
-
const response = await
|
|
124
|
-
?? await bindService.handleRequest(parsed, opts.peerId);
|
|
122
|
+
const response = await bindService.handleRequest(parsed, opts.peerId, opts.encrypted === true);
|
|
125
123
|
if (response) {
|
|
126
124
|
await controlChannel.sendStructuredOrThrow(opts.channelId, response, controlReplyContext(opts));
|
|
127
125
|
}
|
|
@@ -111,35 +111,37 @@ export async function discoverStartupWork(options) {
|
|
|
111
111
|
else
|
|
112
112
|
plan.requiredExternalAids.add(aid);
|
|
113
113
|
};
|
|
114
|
-
const queueStarted = Date.now();
|
|
115
|
-
let queueItems = 0;
|
|
116
|
-
let queueFiles = 0;
|
|
117
114
|
let queueSnapshot;
|
|
118
|
-
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
115
|
+
const queueCapture = (async () => {
|
|
116
|
+
const queueStarted = Date.now();
|
|
117
|
+
let queueItems = 0;
|
|
118
|
+
let queueFiles = 0;
|
|
119
|
+
try {
|
|
120
|
+
const queue = await json(options.queuePath);
|
|
121
|
+
if (queue !== undefined) {
|
|
122
|
+
queueFiles = 1;
|
|
123
|
+
queueSnapshot = parseQueueSnapshot(queue);
|
|
124
|
+
for (const bucket of [...queueSnapshot.queues, ...(queueSnapshot.active ?? [])]) {
|
|
125
|
+
for (const item of bucket.items) {
|
|
126
|
+
queueItems++;
|
|
127
|
+
noteMessage(item.message, bucket.queueKey);
|
|
128
|
+
for (const part of item.parts ?? [])
|
|
129
|
+
noteMessage(part.message, bucket.queueKey);
|
|
130
|
+
}
|
|
129
131
|
}
|
|
130
132
|
}
|
|
131
133
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
134
|
+
catch (error) {
|
|
135
|
+
plan.recoveryIndexAids.clear();
|
|
136
|
+
for (const aid of known)
|
|
137
|
+
uncertain(aid, error);
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
options.onScan?.({ phase: 'queue', durationMs: Date.now() - queueStarted, files: queueFiles, items: queueItems });
|
|
141
|
+
options.onQueueCaptured?.(queueSnapshot);
|
|
142
|
+
}
|
|
143
|
+
return Date.now();
|
|
144
|
+
})();
|
|
143
145
|
const triggerDir = options.triggerDir ?? agentTriggersDir;
|
|
144
146
|
const scanTriggers = async (aid) => {
|
|
145
147
|
const started = Date.now();
|
|
@@ -190,10 +192,13 @@ export async function discoverStartupWork(options) {
|
|
|
190
192
|
const loopStart = performance.eventLoopUtilization();
|
|
191
193
|
loopDelay.enable();
|
|
192
194
|
try {
|
|
193
|
-
await Promise.all([daemonTriggerScan, ...Array.from({ length: Math.min(4, aids.length) }, async () => {
|
|
195
|
+
await Promise.all([queueCapture, daemonTriggerScan, ...Array.from({ length: Math.min(4, aids.length) }, async () => {
|
|
194
196
|
while (next < aids.length) {
|
|
195
197
|
const aid = aids[next++];
|
|
196
198
|
const scanSessions = async () => {
|
|
199
|
+
// Trigger evidence is independent of the queue. Session history and
|
|
200
|
+
// idle classification still require the captured recovery index.
|
|
201
|
+
const now = await queueCapture;
|
|
197
202
|
// A complete queue snapshot covers executions, including consumed hints.
|
|
198
203
|
// Do not enumerate historical chat/topic directories on the normal path.
|
|
199
204
|
if (hasIndexedRecovery(queueSnapshot, aid))
|
|
@@ -304,7 +309,7 @@ export async function discoverStartupWork(options) {
|
|
|
304
309
|
options.onScan?.({ phase: 'sessions', aid, durationMs: Date.now() - started, files, directories: chats,
|
|
305
310
|
directoryMs, threadDirectoryMs, metadataMs, readMaxMs, io });
|
|
306
311
|
};
|
|
307
|
-
//
|
|
312
|
+
// Start independent read-only evidence under the four-owner budget.
|
|
308
313
|
// Positive work can admit a busy owner early; idle classification
|
|
309
314
|
// still waits for both scans and the primary's daemon-owned Triggers.
|
|
310
315
|
await Promise.all([
|
|
@@ -324,7 +329,7 @@ export async function discoverStartupWork(options) {
|
|
|
324
329
|
}
|
|
325
330
|
return plan;
|
|
326
331
|
}
|
|
327
|
-
/** One concurrent channel connection per CPU
|
|
332
|
+
/** One concurrent channel connection per available CPU, capped at eight. */
|
|
328
333
|
export function startupConnectionBudget() {
|
|
329
334
|
let cpuParallelism = 1;
|
|
330
335
|
try {
|
|
@@ -333,7 +338,7 @@ export function startupConnectionBudget() {
|
|
|
333
338
|
cpuParallelism = available;
|
|
334
339
|
}
|
|
335
340
|
catch { /* Retain the one-CPU budget when detection is unavailable. */ }
|
|
336
|
-
return { cpuParallelism, concurrency: cpuParallelism };
|
|
341
|
+
return { cpuParallelism, concurrency: Math.min(cpuParallelism, 8) };
|
|
337
342
|
}
|
|
338
343
|
/** Bounded admission for startup side effects. Dependency waits belong outside this queue. */
|
|
339
344
|
export class StartupTaskQueue {
|
|
@@ -657,6 +662,15 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
|
|
|
657
662
|
if (shutdownInProgress)
|
|
658
663
|
return;
|
|
659
664
|
shutdownInProgress = true;
|
|
665
|
+
// Include pre-teardown notices and quiescing in the real stop boundary.
|
|
666
|
+
const trace = new StartupTracer('daemon', {
|
|
667
|
+
kind: 'stop',
|
|
668
|
+
traceId: traceId || undefined,
|
|
669
|
+
processStartMs: Date.now(),
|
|
670
|
+
});
|
|
671
|
+
trace.setMeta('signal', signal || shutdownSignal);
|
|
672
|
+
trace.setMeta('via', traceId ? 'ipc' : 'signal');
|
|
673
|
+
const preparationStartedAt = Date.now();
|
|
660
674
|
cancelStartup?.();
|
|
661
675
|
if (signal)
|
|
662
676
|
shutdownSignal = signal;
|
|
@@ -672,6 +686,8 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
|
|
|
672
686
|
// 异步的(发送前 await ownerResolver.refresh)。若不等它,stopOwnership 会在准入
|
|
673
687
|
// 恢复执行前清空 resolver,snapshot() 重建空 subject 后一律判 unavailable,
|
|
674
688
|
// 下线通知就会被 CONTACT_DENIED 拦下。
|
|
689
|
+
const offlineStartedAt = Date.now();
|
|
690
|
+
trace.addSpan('daemon.shutdown', preparationStartedAt, offlineStartedAt);
|
|
675
691
|
try {
|
|
676
692
|
await withDeadline(lifecycleNotices?.sendOffline(shutdownSignal), OFFLINE_TOTAL_BUDGET_MS);
|
|
677
693
|
}
|
|
@@ -679,6 +695,10 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
|
|
|
679
695
|
// A synchronous throw must not abort the exit; the notice is best-effort.
|
|
680
696
|
logger.warn(`[Shutdown] offline notice failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
681
697
|
}
|
|
698
|
+
finally {
|
|
699
|
+
trace.addSpan('daemon.offlineNotices', offlineStartedAt, Date.now());
|
|
700
|
+
}
|
|
701
|
+
const quiesceStartedAt = Date.now();
|
|
682
702
|
// Detaching ownership emits invalidations. Stop listeners first so those
|
|
683
703
|
// invalidations cannot enqueue refreshes against a resolver being destroyed.
|
|
684
704
|
for (const channel of [...channelInstances.map(instance => instance.channel), controlChannel]) {
|
|
@@ -697,17 +717,7 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
|
|
|
697
717
|
const pid = process.pid;
|
|
698
718
|
const ppid = process.ppid;
|
|
699
719
|
logger.info(`\n\nShutting down gracefully... (signal=${shutdownSignal}, pid=${pid}, ppid=${ppid})`);
|
|
700
|
-
|
|
701
|
-
// daemon 可能已经跑了几小时。traceId 由 `ec stop` 通过 IPC 带进来,
|
|
702
|
-
// 没有的话(信号退出、超时兜底)自己生成一条独立的记录。
|
|
703
|
-
const trace = new StartupTracer('daemon', {
|
|
704
|
-
kind: 'stop',
|
|
705
|
-
traceId: traceId || undefined,
|
|
706
|
-
processStartMs: Date.now(),
|
|
707
|
-
});
|
|
708
|
-
trace.setMeta('signal', shutdownSignal);
|
|
709
|
-
trace.setMeta('via', traceId ? 'ipc' : 'signal');
|
|
710
|
-
trace.addSpan('daemon.shutdown', trace.startedAtMs, Date.now());
|
|
720
|
+
trace.addSpan('daemon.quiesceChannels', quiesceStartedAt, Date.now());
|
|
711
721
|
const ipcStopStartedAt = Date.now();
|
|
712
722
|
ipcServer.stopCpuTracking();
|
|
713
723
|
ipcServer.stop();
|
|
@@ -101,7 +101,9 @@ export class EvolAgentRegistry {
|
|
|
101
101
|
this.registerErrorAgent(raw, `${precheck.code}: ${precheck.detail}`);
|
|
102
102
|
continue;
|
|
103
103
|
}
|
|
104
|
-
|
|
104
|
+
// Reuse the mtime-checked reads populated during enumeration; changes
|
|
105
|
+
// still reload through ConfigManager's normal atomic reader.
|
|
106
|
+
const merged = resolveEffective({ self: expandedRaw.aid }, { cache: true });
|
|
105
107
|
const agent = new EvolAgent(raw, merged);
|
|
106
108
|
ensureAgentDirSkeleton(expandedRaw.aid);
|
|
107
109
|
ensureInitialRoleRegistry(expandedRaw.aid);
|
|
@@ -230,12 +232,16 @@ export class EvolAgentRegistry {
|
|
|
230
232
|
list() {
|
|
231
233
|
return [...this.agents.values()].map(a => this.toInfo(a));
|
|
232
234
|
}
|
|
235
|
+
/** Current runtime instances, including disabled/error Agents, without display-file reads. */
|
|
236
|
+
allAgents() {
|
|
237
|
+
return [...this.agents.values()];
|
|
238
|
+
}
|
|
233
239
|
invalidateAgentDisplayCache(aid) {
|
|
234
240
|
invalidateAgentDisplayName(aid);
|
|
235
241
|
this.personalNameCache.delete(aid);
|
|
236
242
|
}
|
|
237
243
|
runnableAgents() {
|
|
238
|
-
return
|
|
244
|
+
return this.allAgents().filter(a => a.status === 'stopped');
|
|
239
245
|
}
|
|
240
246
|
getSkipped() {
|
|
241
247
|
return [...this.skipped];
|
|
@@ -150,11 +150,15 @@ export function createHostSnapshotProvider(deps) {
|
|
|
150
150
|
staticState.cachedAt = new Date().toISOString();
|
|
151
151
|
writeStaticCache({ virtualization: staticState.virtualization, runtimes: staticState.runtimes, cachedAt: staticState.cachedAt });
|
|
152
152
|
};
|
|
153
|
-
const
|
|
153
|
+
const getHost = () => {
|
|
154
154
|
const host = readHostInfo(versions.evolcore, resolvePaths().root, { runtimes: staticState.runtimes });
|
|
155
155
|
host.os.virtualization = staticState.virtualization;
|
|
156
156
|
// CPU 只有 daemon 有采样值;采样未启动时宁可给 null,也不给一个骗人的数字。
|
|
157
157
|
host.hardware.cpuUsagePercent = deps.getSystemCpuPercent?.() ?? null;
|
|
158
|
+
return host;
|
|
159
|
+
};
|
|
160
|
+
const getSnapshot = () => {
|
|
161
|
+
const host = getHost();
|
|
158
162
|
const agents = deps.agentRegistry.list();
|
|
159
163
|
let totalPending = 0;
|
|
160
164
|
let totalProcessing = 0;
|
|
@@ -201,7 +205,8 @@ export function createHostSnapshotProvider(deps) {
|
|
|
201
205
|
},
|
|
202
206
|
};
|
|
203
207
|
};
|
|
204
|
-
//
|
|
205
|
-
|
|
206
|
-
|
|
208
|
+
// The daemon schedules these informational child processes after Ready.
|
|
209
|
+
if (deps.autoProbe !== false)
|
|
210
|
+
setImmediate(() => { void probe(); });
|
|
211
|
+
return { getHost, getSnapshot, refresh: probe };
|
|
207
212
|
}
|
|
@@ -134,7 +134,9 @@ export class EcwebInitializationService {
|
|
|
134
134
|
return ownerResolver.bind(aid, owner);
|
|
135
135
|
}
|
|
136
136
|
async verifiedOwner(state, force = true, source = 'initialization.operation') {
|
|
137
|
-
|
|
137
|
+
return this.applyVerifiedOwner(state, await this.ownership(state.controlAid, force, source));
|
|
138
|
+
}
|
|
139
|
+
applyVerifiedOwner(state, view) {
|
|
138
140
|
const owner = view.consensusStatus === 'consensus' && view.ownerAid && isValidAid(view.ownerAid)
|
|
139
141
|
&& view.ownerAid !== state.controlAid ? view.ownerAid : undefined;
|
|
140
142
|
if (owner && state.ownerAid && state.ownerAid !== owner)
|
|
@@ -240,13 +242,23 @@ export class EcwebInitializationService {
|
|
|
240
242
|
}
|
|
241
243
|
}
|
|
242
244
|
const bindingPending = !!state.binding?.ownerAid && ['pending', 'unknown'].includes(state.binding.status);
|
|
243
|
-
const
|
|
245
|
+
const ownership = await this.ownership(state.controlAid, true, bindingPending ? 'initialization.binding' : 'initialization.view');
|
|
246
|
+
const ownerAid = this.applyVerifiedOwner(state, ownership);
|
|
247
|
+
const pending = bindingPending || ['requesting', 'submitted'].includes(ownership.requestStatus ?? '')
|
|
248
|
+
|| (ownership.task?.operation === 'bind' && ownership.task.status === 'pending');
|
|
249
|
+
const ownershipStatus = ownerAid ? 'bound' : ownership.consensusStatus === 'single_sided' ? 'pending'
|
|
250
|
+
: ['unbound', 'released'].includes(ownership.consensusStatus) ? pending ? 'pending' : 'unbound' : 'unknown';
|
|
244
251
|
const binding = state.binding;
|
|
245
252
|
const scannable = binding?.status === 'created' && binding.expiresAt > this.now();
|
|
246
253
|
return {
|
|
247
254
|
status: state.step === 'ready' ? 'completed' : state.step === 'welcome' ? 'pending' : 'in_progress',
|
|
248
255
|
step: ownerAid ? state.step === 'welcome' || state.step === 'binding' ? 'configuration' : state.step : state.step === 'welcome' ? 'welcome' : 'binding',
|
|
249
256
|
controlAid: state.controlAid, ownerAid: ownerAid ?? null, updatedAt: state.updatedAt,
|
|
257
|
+
ownership: {
|
|
258
|
+
status: ownershipStatus, consensusStatus: ownership.consensusStatus,
|
|
259
|
+
code: ownership.refreshFailure?.code ?? null,
|
|
260
|
+
reason: ownership.refreshFailure?.reason ?? ownership.reason ?? null,
|
|
261
|
+
},
|
|
250
262
|
binding: binding ? {
|
|
251
263
|
id: binding.id, status: binding.status === 'bound' && !ownerAid ? 'unknown' : binding.status,
|
|
252
264
|
expiresAt: binding.expiresAt,
|
|
@@ -420,8 +432,14 @@ export class EcwebInitializationService {
|
|
|
420
432
|
return { status: 200, body: { success: true, data: await this.view(state) } };
|
|
421
433
|
}
|
|
422
434
|
if (input.method === 'POST' && (pathname === '/api/init/binding-sessions' || pathname === '/api/init/binding-sessions/refresh')) {
|
|
423
|
-
|
|
424
|
-
|
|
435
|
+
const data = await this.view(state);
|
|
436
|
+
const ownership = data.ownership;
|
|
437
|
+
if (ownership.status === 'bound')
|
|
438
|
+
return { status: 200, body: { success: true, data } };
|
|
439
|
+
if (ownership.status === 'unknown')
|
|
440
|
+
fail('OWNERSHIP_UNAVAILABLE', ownership.reason || '主机 Owner 状态暂时无法确认,请重试', 503);
|
|
441
|
+
if (ownership.status === 'pending')
|
|
442
|
+
return { status: 202, body: { success: true, data } };
|
|
425
443
|
if (state.binding?.ownerAid)
|
|
426
444
|
fail('BIND_PENDING', '绑定已提交,请先在 EVOL APP 确认并查询结果,不能重复创建', 409);
|
|
427
445
|
if (pathname.endsWith('/refresh') || !state.binding || state.binding.expiresAt <= this.now()) {
|
|
@@ -355,9 +355,11 @@ export function registerDaemonIpc({ lifecycle, ipcServer, agentRegistry, agentDe
|
|
|
355
355
|
}
|
|
356
356
|
export function createIpcStatusProvider(dependencies) {
|
|
357
357
|
return () => {
|
|
358
|
+
// One fresh projection per request; channel and activity views share it.
|
|
359
|
+
const agents = dependencies.agentRegistry.list();
|
|
358
360
|
const channels = {};
|
|
359
361
|
const channelsByType = {};
|
|
360
|
-
const channelRuntime = dependencies.getChannelRuntimeSnapshot?.();
|
|
362
|
+
const channelRuntime = dependencies.getChannelRuntimeSnapshot?.(agents);
|
|
361
363
|
for (const instance of dependencies.channelInstances) {
|
|
362
364
|
const name = instance.adapter.channelName;
|
|
363
365
|
const channelType = instance.channelType || name;
|
|
@@ -383,7 +385,6 @@ export function createIpcStatusProvider(dependencies) {
|
|
|
383
385
|
names.push(channelName);
|
|
384
386
|
}
|
|
385
387
|
const snapshot = dependencies.statsCollector.getSnapshot();
|
|
386
|
-
const agents = dependencies.agentRegistry.list();
|
|
387
388
|
const runtimeError = dependencies.getAgentRuntimeError();
|
|
388
389
|
const build = dependencies.getBuildDiagnostics();
|
|
389
390
|
return {
|
|
@@ -427,7 +428,7 @@ export function createIpcStatusProvider(dependencies) {
|
|
|
427
428
|
...(channelRuntime ? { channelRuntime } : {}),
|
|
428
429
|
queue: { pending: dependencies.messageQueue.getGlobalQueueLength(), processing: dependencies.messageQueue.getGlobalProcessingCount() },
|
|
429
430
|
...(dependencies.getTriggerSummary ? { triggers: dependencies.getTriggerSummary() } : {}),
|
|
430
|
-
...(dependencies.getStatusSnapshot ? dependencies.getStatusSnapshot() : {}),
|
|
431
|
+
...(dependencies.getStatusSnapshot ? dependencies.getStatusSnapshot(agents) : {}),
|
|
431
432
|
...(dependencies.getServiceProxySnapshot ? { serviceProxy: dependencies.getServiceProxySnapshot() } : {}),
|
|
432
433
|
stats: {
|
|
433
434
|
received: snapshot.lastHour.received,
|
|
@@ -1147,15 +1147,15 @@ export function createConsolidationSessionFinalizer({ sessionManager, getAgent,
|
|
|
1147
1147
|
// 用 sessionId 无状态重算路径,不依赖 spec 传递——保证即使 spec 不传 runtimeDir
|
|
1148
1148
|
// 字段,目录也能在会话结束后被清掉。
|
|
1149
1149
|
if (sessionId) {
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1150
|
+
try {
|
|
1151
|
+
const runtimeDir = ensureSessionRuntimeDir(sessionId);
|
|
1152
|
+
if (runtimeDir) {
|
|
1153
1153
|
fs.rmSync(runtimeDir, { recursive: true, force: true });
|
|
1154
1154
|
logger.debug(`[Memory] 清理 runtime 目录: ${runtimeDir}`);
|
|
1155
1155
|
}
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
}
|
|
1156
|
+
}
|
|
1157
|
+
catch (cleanupError) {
|
|
1158
|
+
logger.warn(`[Memory] runtime 目录清理失败(session=${sessionId}): ${cleanupError?.message}`);
|
|
1159
1159
|
}
|
|
1160
1160
|
}
|
|
1161
1161
|
}
|
|
@@ -646,7 +646,7 @@ export class OwnerResolver {
|
|
|
646
646
|
logger.warn(`[ownership] Failed to persist rejected binding for ${task.sub_aid}: ${reason}`);
|
|
647
647
|
}
|
|
648
648
|
}
|
|
649
|
-
async bind(subjectAid, ownerAid, isCurrent) {
|
|
649
|
+
async bind(subjectAid, ownerAid, isCurrent, onSubmissionStart) {
|
|
650
650
|
this.assertAid(subjectAid);
|
|
651
651
|
this.assertAid(ownerAid);
|
|
652
652
|
if (ownerAid === subjectAid)
|
|
@@ -661,11 +661,22 @@ export class OwnerResolver {
|
|
|
661
661
|
if (subject.binding) {
|
|
662
662
|
if (subject.binding.ownerAid !== ownerAid)
|
|
663
663
|
throw new OwnershipError('BIND_CONFLICT', 'Another owner binding is in progress');
|
|
664
|
+
if (onSubmissionStart) {
|
|
665
|
+
if (subject.binding.submission.started)
|
|
666
|
+
onSubmissionStart();
|
|
667
|
+
else
|
|
668
|
+
subject.binding.submission.listeners.add(onSubmissionStart);
|
|
669
|
+
}
|
|
664
670
|
return subject.binding.promise;
|
|
665
671
|
}
|
|
666
672
|
const previousTask = subject.view.task;
|
|
667
|
-
const
|
|
668
|
-
|
|
673
|
+
const submission = { started: false, listeners: new Set(onSubmissionStart ? [onSubmissionStart] : []) };
|
|
674
|
+
const promise = this.submitBinding(subjectAid, ownerAid, subject, assertCurrent, () => {
|
|
675
|
+
submission.started = true;
|
|
676
|
+
for (const listener of submission.listeners)
|
|
677
|
+
listener();
|
|
678
|
+
});
|
|
679
|
+
subject.binding = { ownerAid, promise, submission };
|
|
669
680
|
try {
|
|
670
681
|
const result = await promise;
|
|
671
682
|
const task = result.task;
|
|
@@ -943,14 +954,14 @@ export class OwnerResolver {
|
|
|
943
954
|
this.configuredOwners.clear();
|
|
944
955
|
this.configuredOwnerFileRevision.clear();
|
|
945
956
|
}
|
|
946
|
-
async submitBinding(subjectAid, ownerAid, subject, assertCurrent) {
|
|
957
|
+
async submitBinding(subjectAid, ownerAid, subject, assertCurrent, onSubmissionStart) {
|
|
947
958
|
const generation = subject.generation;
|
|
948
959
|
let replaced = false;
|
|
949
960
|
subject.view = { ...subject.view, requestedOwnerAid: ownerAid, requestStatus: 'requesting', task: undefined };
|
|
950
961
|
try {
|
|
951
962
|
await this.assertAgentOwner(subjectAid, ownerAid);
|
|
952
963
|
assertCurrent();
|
|
953
|
-
const local = await this.tryLocalBind(subjectAid, ownerAid, assertCurrent);
|
|
964
|
+
const local = await this.tryLocalBind(subjectAid, ownerAid, assertCurrent, onSubmissionStart);
|
|
954
965
|
if (local) {
|
|
955
966
|
if (subject.client && subject.generation !== generation) {
|
|
956
967
|
throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during local binding');
|
|
@@ -988,6 +999,7 @@ export class OwnerResolver {
|
|
|
988
999
|
}
|
|
989
1000
|
this.applyConsensus(subjectAid, subject, current);
|
|
990
1001
|
assertCurrent();
|
|
1002
|
+
onSubmissionStart?.();
|
|
991
1003
|
const task = this.task(await client.bindOwneraid(ownerAid));
|
|
992
1004
|
if (attached && (subject.client !== client || subject.generation !== generation)) {
|
|
993
1005
|
replaced = true;
|
|
@@ -1333,7 +1345,7 @@ export class OwnerResolver {
|
|
|
1333
1345
|
catch { }
|
|
1334
1346
|
}
|
|
1335
1347
|
}
|
|
1336
|
-
async tryLocalBind(subjectAid, ownerAid, assertCurrent) {
|
|
1348
|
+
async tryLocalBind(subjectAid, ownerAid, assertCurrent, onSubmissionStart) {
|
|
1337
1349
|
let store;
|
|
1338
1350
|
let ownerClient;
|
|
1339
1351
|
let subClient;
|
|
@@ -1352,6 +1364,7 @@ export class OwnerResolver {
|
|
|
1352
1364
|
|| !['agent', 'human'].includes(ownerClient.getType()) || subClient.getType() !== 'agent')
|
|
1353
1365
|
return undefined;
|
|
1354
1366
|
assertCurrent();
|
|
1367
|
+
onSubmissionStart?.();
|
|
1355
1368
|
invoked = true;
|
|
1356
1369
|
const task = this.task(await ownerClient.bindSubaid(subjectAid));
|
|
1357
1370
|
if (!task || task.operation !== 'bind' || task.sub_aid !== subjectAid || task.owner_aid !== ownerAid
|
|
@@ -1525,10 +1538,14 @@ export class OwnerResolver {
|
|
|
1525
1538
|
}
|
|
1526
1539
|
notify(subjectAid, ownerAid) {
|
|
1527
1540
|
for (const listener of this.listeners) {
|
|
1528
|
-
queueMicrotask(() => {
|
|
1529
|
-
listener
|
|
1530
|
-
|
|
1531
|
-
|
|
1541
|
+
queueMicrotask(() => {
|
|
1542
|
+
if (!this.listeners.has(listener))
|
|
1543
|
+
return;
|
|
1544
|
+
try {
|
|
1545
|
+
listener(subjectAid, ownerAid);
|
|
1546
|
+
}
|
|
1547
|
+
catch { }
|
|
1548
|
+
});
|
|
1532
1549
|
}
|
|
1533
1550
|
}
|
|
1534
1551
|
invalidateRelatedSubjects(changedAid, targetAid) {
|
|
@@ -21,6 +21,9 @@ export function parseAgentMdFrontmatter(content) {
|
|
|
21
21
|
const end = lines.slice(1).findIndex(line => line.trim() === '---');
|
|
22
22
|
if (end < 0)
|
|
23
23
|
return {};
|
|
24
|
+
// Lifecycle clients only use peer-key helpers; parsing keeps the same
|
|
25
|
+
// synchronous YAML implementation without loading it into those clients.
|
|
26
|
+
const { parse: parseYaml } = requirePeerIdentityDependency('yaml');
|
|
24
27
|
try {
|
|
25
28
|
const parsed = parseYaml(lines.slice(1, end + 1).join('\n'));
|
|
26
29
|
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
@@ -64,12 +67,13 @@ function normalizeCachedIdentity(raw) {
|
|
|
64
67
|
import * as fs from 'fs';
|
|
65
68
|
import * as path from 'path';
|
|
66
69
|
import * as crypto from 'crypto';
|
|
67
|
-
import {
|
|
70
|
+
import { createRequire } from 'node:module';
|
|
68
71
|
import { logger } from '../../utils/logger.js';
|
|
69
72
|
import { agentDir as resolveAgentDir, agentMdPath } from '../../paths.js';
|
|
70
73
|
import { ConfigTarget, mutateConfig, read } from '../../config/config-manager.js';
|
|
71
74
|
import { isValidAid } from '../../aun/aid/validation.js';
|
|
72
75
|
import { resolveAunTargetKind, verifiedPeerType, } from '../../aun/group/identity.js';
|
|
76
|
+
const requirePeerIdentityDependency = createRequire(import.meta.url);
|
|
73
77
|
/**
|
|
74
78
|
* peerKey: 关系层路由键,格式 `<channelType>#<urlEncode(channelId)>`。
|
|
75
79
|
* 群聊场景下 channelId = groupId,所有发言者共用同一个 peerKey。
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { createHash } from 'crypto';
|
|
2
|
-
import { agentmdGet } from '../../aun/aid/agentmd.js';
|
|
3
2
|
import { isValidAid } from '../../aun/aid/validation.js';
|
|
4
3
|
import { parseAgentMdFrontmatter } from './peer-identity.js';
|
|
5
4
|
export const SAME_OWNER_MAX_AGE_MS = 30_000;
|
|
@@ -64,6 +63,8 @@ export async function prepareSameOwnerProof(selfAid, peerAid) {
|
|
|
64
63
|
const generation = runtime.generation;
|
|
65
64
|
const startedAt = Date.now();
|
|
66
65
|
const query = async () => {
|
|
66
|
+
// Lifecycle CLI commands never need profile verification or the AUN SDK.
|
|
67
|
+
const { agentmdGet } = await import('../../aun/aid/agentmd.js');
|
|
67
68
|
const cards = await Promise.all([selfAid, peerAid].map(aid => agentmdGet(aid, { store: runtime.store, withVerification: true, remoteOnly: true })));
|
|
68
69
|
const profiles = cards.map((card, index) => {
|
|
69
70
|
if (card.source !== 'remote' || card.verification.status !== 'verified')
|
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
* Reads Claude Agent SDK session files from ~/.claude/projects/{encodedPath}/{sessionId}.jsonl
|
|
5
5
|
* and wraps sdkListSessions for name synchronization.
|
|
6
6
|
*/
|
|
7
|
-
import { listSessions as sdkListSessions } from '@anthropic-ai/claude-agent-sdk';
|
|
8
7
|
import { encodePath } from '../../../utils/cross-platform.js';
|
|
9
8
|
import { logger } from '../../../utils/logger.js';
|
|
10
9
|
import { buildCliSessionPreview } from '../session-title.js';
|
|
@@ -207,6 +206,7 @@ export class ClaudeSessionFileAdapter {
|
|
|
207
206
|
}
|
|
208
207
|
async listSdkSessions(projectPath) {
|
|
209
208
|
try {
|
|
209
|
+
const { listSessions: sdkListSessions } = await import('@anthropic-ai/claude-agent-sdk');
|
|
210
210
|
const sessions = await sdkListSessions({ dir: projectPath });
|
|
211
211
|
return sessions.map(s => ({
|
|
212
212
|
sessionId: s.sessionId,
|