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
|
@@ -103,6 +103,41 @@ function cleanEnv() {
|
|
|
103
103
|
function reportPidReused(pid, log) {
|
|
104
104
|
log(`Process ${pid} no longer refers to the recorded daemon; treating the original process as exited`);
|
|
105
105
|
}
|
|
106
|
+
async function giveWindowsDaemonTimeToExit(pid, deadline) {
|
|
107
|
+
// WMI can capture the old daemon early in enumeration, even if it exits
|
|
108
|
+
// before the result arrives. Observe the acknowledged daemon first, within
|
|
109
|
+
// the existing shutdown budget, then inspect the complete process table.
|
|
110
|
+
// This is only a scheduling hint: every exit still needs full inspection or
|
|
111
|
+
// the authoritative liveness check, and signals still need fresh identity.
|
|
112
|
+
while (performance.now() < deadline) {
|
|
113
|
+
try {
|
|
114
|
+
process.kill(pid, 0);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return;
|
|
118
|
+
} // Either gone or not observable: let the full scan decide.
|
|
119
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(20, Math.max(0, deadline - performance.now()))));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** Observe the captured child while the ready file is still absent. */
|
|
123
|
+
export async function waitForRestartReadySignal(readySignal, childExited, timeoutMs, confirmLiveness) {
|
|
124
|
+
const deadline = performance.now() + timeoutMs;
|
|
125
|
+
while (true) {
|
|
126
|
+
if (childExited())
|
|
127
|
+
return 'exited';
|
|
128
|
+
if (fs.existsSync(readySignal)) {
|
|
129
|
+
if (!await confirmLiveness() || childExited())
|
|
130
|
+
return 'exited';
|
|
131
|
+
if (fs.existsSync(readySignal))
|
|
132
|
+
return 'ready';
|
|
133
|
+
// A disappearing candidate does not shorten the normal wait budget.
|
|
134
|
+
}
|
|
135
|
+
const remaining = deadline - performance.now();
|
|
136
|
+
if (remaining <= 0)
|
|
137
|
+
return 'timeout';
|
|
138
|
+
await sleep(Math.min(100, remaining));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
106
141
|
export async function cmdRestartMonitor() {
|
|
107
142
|
// Defense in depth: a unit test that accidentally executes the real restart
|
|
108
143
|
// path must not detach a persistent daemon from the test worker.
|
|
@@ -281,12 +316,36 @@ export async function cmdRestartMonitor() {
|
|
|
281
316
|
// instance registry cannot see them. Their strict environment markers make
|
|
282
317
|
// them safe to reap globally on every real restart. Keep one process-table
|
|
283
318
|
// snapshot for both orphan categories; each Windows CIM scan is expensive.
|
|
284
|
-
|
|
319
|
+
// The HOME-scoped IPC request authenticates with control.token and binds its
|
|
320
|
+
// acknowledgement to the probed daemon PID. It asks that daemon to stop
|
|
321
|
+
// itself; it does not authorize an OS signal. A complete scan that already
|
|
322
|
+
// excludes this PID also confirms its exit, avoiding a second scan. Signals
|
|
323
|
+
// still require fresh identity checks, and any further cleanup invalidates
|
|
324
|
+
// the snapshot used by the final residual-process guard below.
|
|
325
|
+
const earlyGracefulPid = await trace.waitForDependency(requestDaemonShutdown(p.socket, DAEMON_SHUTDOWN_TIMEOUT_MS, 'restart-monitor')
|
|
326
|
+
.catch(error => {
|
|
327
|
+
log(`Early graceful shutdown request failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
328
|
+
return null;
|
|
329
|
+
}), 'old daemon shutdown acknowledgement');
|
|
330
|
+
const windowsExitDeadline = platform.isWindows && earlyGracefulPid !== null
|
|
331
|
+
? performance.now() + 30_000 : undefined;
|
|
332
|
+
if (windowsExitDeadline !== undefined && earlyGracefulPid !== null) {
|
|
333
|
+
// This observation only chooses when to scan; it never proves exit,
|
|
334
|
+
// authorizes a signal or replaces the residual-process check.
|
|
335
|
+
await trace.waitForDependency(giveWindowsDaemonTimeToExit(earlyGracefulPid, windowsExitDeadline), 'old daemon cooperative exit window');
|
|
336
|
+
}
|
|
337
|
+
const beforeStopSnapshot = await trace.waitForDependency(getProcessSnapshotAsync({ fresh: true }), 'process inspection during shutdown');
|
|
338
|
+
const exitConfirmedBySnapshot = earlyGracefulPid !== null && beforeStopSnapshot.complete
|
|
339
|
+
&& beforeStopSnapshot.pids?.has(earlyGracefulPid) === false;
|
|
340
|
+
const earlyGracefulExited = exitConfirmedBySnapshot || earlyGracefulPid !== null && await trace.waitForDependency(platform.waitForProcessExit(earlyGracefulPid, windowsExitDeadline === undefined
|
|
341
|
+
? 30_000 : Math.max(0, Math.ceil(windowsExitDeadline - performance.now()))), 'old daemon exit');
|
|
285
342
|
let oldStatus = scanInstances({ includeAidActivity: false, processSnapshot: beforeStopSnapshot });
|
|
286
343
|
const orphanSnapshot = findOrphanProcesses(oldStatus, beforeStopSnapshot);
|
|
344
|
+
let stoppedSnapshot = exitConfirmedBySnapshot ? beforeStopSnapshot : undefined;
|
|
287
345
|
{
|
|
288
346
|
const leakedTestDaemons = orphanSnapshot.filter(o => o.confirmedTestDaemon);
|
|
289
347
|
if (leakedTestDaemons.length > 0) {
|
|
348
|
+
stoppedSnapshot = undefined;
|
|
290
349
|
const killed = await killOrphans(leakedTestDaemons);
|
|
291
350
|
log(`Cleaned ${killed.length} leaked test daemon(s): ${killed.join(', ')}`);
|
|
292
351
|
}
|
|
@@ -307,7 +366,7 @@ export async function cmdRestartMonitor() {
|
|
|
307
366
|
const pids = runtimeOrphans.map(o => o.pid).join(', ');
|
|
308
367
|
log(`Stopping unregistered EvolCore process(es): ${pids}`);
|
|
309
368
|
const orphanPids = new Set(runtimeOrphans.map(orphan => orphan.pid));
|
|
310
|
-
const ping = await trace.waitForDependency(requestDaemonShutdown(p.socket, DAEMON_SHUTDOWN_TIMEOUT_MS, 'restart-monitor orphan cleanup', orphanPids), 'old daemon shutdown acknowledgement');
|
|
369
|
+
const ping = earlyGracefulPid !== null && orphanPids.has(earlyGracefulPid) ? earlyGracefulPid : await trace.waitForDependency(requestDaemonShutdown(p.socket, DAEMON_SHUTDOWN_TIMEOUT_MS, 'restart-monitor orphan cleanup', orphanPids), 'old daemon shutdown acknowledgement');
|
|
311
370
|
const retiredOrphans = new Set();
|
|
312
371
|
for (const orphan of runtimeOrphans) {
|
|
313
372
|
if (orphan.pid !== ping) {
|
|
@@ -320,7 +379,8 @@ export async function cmdRestartMonitor() {
|
|
|
320
379
|
const exited = await trace.waitForDependency(Promise.all(runtimeOrphans.map(async (orphan) => {
|
|
321
380
|
if (retiredOrphans.has(orphan.pid))
|
|
322
381
|
return true;
|
|
323
|
-
if (
|
|
382
|
+
if (orphan.pid === earlyGracefulPid ? earlyGracefulExited
|
|
383
|
+
: await platform.waitForProcessExit(orphan.pid, orphan.pid === ping ? 30_000 : 10_000))
|
|
324
384
|
return true;
|
|
325
385
|
if (await isRecordedProcessGone(orphan.pid, orphan.startedAt))
|
|
326
386
|
return true;
|
|
@@ -338,14 +398,16 @@ export async function cmdRestartMonitor() {
|
|
|
338
398
|
invalidateProcessSnapshot();
|
|
339
399
|
const snapshot = await trace.waitForDependency(getProcessSnapshotAsync({ fresh: true }), 'process inspection after orphan cleanup');
|
|
340
400
|
oldStatus = scanInstances({ includeAidActivity: false, processSnapshot: snapshot });
|
|
401
|
+
stoppedSnapshot = snapshot;
|
|
341
402
|
}
|
|
342
403
|
// 等待所有活 main 进程退出(可能不止一个)
|
|
343
404
|
const aliveMains = oldStatus.mains.filter(m => m.alive);
|
|
344
405
|
if (aliveMains.length > 0) {
|
|
406
|
+
stoppedSnapshot = undefined;
|
|
345
407
|
const oldPids = aliveMains.map(m => m.record.pid);
|
|
346
408
|
const expectedStarts = new Map(aliveMains.map(m => [m.record.pid, m.record.startedAt]));
|
|
347
409
|
log(`Monitoring ${oldPids.length} main process(es): ${oldPids.join(', ')}`);
|
|
348
|
-
const gracefulPid = await trace.waitForDependency(requestDaemonShutdown(p.socket, DAEMON_SHUTDOWN_TIMEOUT_MS, 'restart-monitor', new Set(oldPids)), 'old daemon shutdown acknowledgement');
|
|
410
|
+
const gracefulPid = earlyGracefulPid !== null && expectedStarts.has(earlyGracefulPid) ? earlyGracefulPid : await trace.waitForDependency(requestDaemonShutdown(p.socket, DAEMON_SHUTDOWN_TIMEOUT_MS, 'restart-monitor', new Set(oldPids)), 'old daemon shutdown acknowledgement');
|
|
349
411
|
log(`Graceful shutdown request ${gracefulPid === null ? 'was not accepted' : `accepted by PID ${gracefulPid}`}`);
|
|
350
412
|
// 没有收到 IPC shutdown 确认的进程才走信号兜底
|
|
351
413
|
const retiredPids = new Set();
|
|
@@ -369,8 +431,9 @@ export async function cmdRestartMonitor() {
|
|
|
369
431
|
if (retiredPids.has(oldPid))
|
|
370
432
|
return true;
|
|
371
433
|
const expectedStartedAt = expectedStarts.get(oldPid);
|
|
372
|
-
//
|
|
373
|
-
|
|
434
|
+
// Reuse the authenticated shutdown's exit result, including its timeout;
|
|
435
|
+
// a PID-addressed fallback below still verifies the current identity.
|
|
436
|
+
if (oldPid === earlyGracefulPid ? earlyGracefulExited : await platform.waitForProcessExit(oldPid, 30_000)) {
|
|
374
437
|
log(`Process ${oldPid} has exited`);
|
|
375
438
|
return true;
|
|
376
439
|
}
|
|
@@ -410,8 +473,13 @@ export async function cmdRestartMonitor() {
|
|
|
410
473
|
// watchdog has successfully loaded.
|
|
411
474
|
// Shutdown changed the process table. A cached pre-shutdown snapshot can
|
|
412
475
|
// otherwise classify the exited daemon as an unregistered runtime process.
|
|
413
|
-
|
|
414
|
-
|
|
476
|
+
// A complete snapshot collected after the acknowledged daemon exited, or
|
|
477
|
+
// after orphan cleanup, is the final guard for this same synchronous phase.
|
|
478
|
+
// Any later main shutdown above invalidates it and requires a fresh view.
|
|
479
|
+
if (!stoppedSnapshot)
|
|
480
|
+
invalidateProcessSnapshot();
|
|
481
|
+
const afterStopSnapshot = stoppedSnapshot
|
|
482
|
+
?? await trace.waitForDependency(getProcessSnapshotAsync({ fresh: true }), 'process inspection after shutdown');
|
|
415
483
|
const remainingStatus = scanInstances({ includeAidActivity: false, processSnapshot: afterStopSnapshot });
|
|
416
484
|
const remaining = findOrphanProcesses(remainingStatus, afterStopSnapshot);
|
|
417
485
|
const remainingMains = remainingStatus.mains.filter(item => item.alive);
|
|
@@ -437,7 +505,7 @@ export async function cmdRestartMonitor() {
|
|
|
437
505
|
else if (otherHome.length) {
|
|
438
506
|
log(`Other HOME orphan processes left running: ${otherHome.map(o => o.pid).join(', ')}`);
|
|
439
507
|
}
|
|
440
|
-
const stoppedCodex = await stopCodexAppServerOrphans();
|
|
508
|
+
const stoppedCodex = await trace.waitForDependency(stopCodexAppServerOrphans(afterStopSnapshot), 'registered Codex child cleanup');
|
|
441
509
|
if (stoppedCodex)
|
|
442
510
|
log(`Cleaned ${stoppedCodex} EvolCore codex app-server orphan(s)`);
|
|
443
511
|
try {
|
|
@@ -1235,7 +1303,20 @@ async function spawnAndWaitReady(p, log, timeout, trace) {
|
|
|
1235
1303
|
[CHANNEL_LOGS_ENV]: process.env[CHANNEL_LOGS_ENV] || 'false',
|
|
1236
1304
|
}
|
|
1237
1305
|
});
|
|
1306
|
+
// Detached children also emit an error on spawn failure. Keep an observer
|
|
1307
|
+
// for that path even when no foreground caller is waiting for the exit.
|
|
1308
|
+
let spawnFailed = false;
|
|
1309
|
+
child.once('error', error => {
|
|
1310
|
+
spawnFailed = true;
|
|
1311
|
+
log(`Daemon process error: ${error.message}`);
|
|
1312
|
+
});
|
|
1238
1313
|
const childPid = child.pid;
|
|
1314
|
+
fs.closeSync(out);
|
|
1315
|
+
fs.closeSync(err);
|
|
1316
|
+
if (childPid === undefined) {
|
|
1317
|
+
log('Could not spawn daemon: no child PID');
|
|
1318
|
+
return false;
|
|
1319
|
+
}
|
|
1239
1320
|
trace.setMeta('daemonPid', String(childPid));
|
|
1240
1321
|
trace.mark('monitor.waitReady', undefined, { initialPhase: 'running' });
|
|
1241
1322
|
if (foreground) {
|
|
@@ -1246,27 +1327,22 @@ async function spawnAndWaitReady(p, log, timeout, trace) {
|
|
|
1246
1327
|
}
|
|
1247
1328
|
else
|
|
1248
1329
|
child.unref();
|
|
1249
|
-
fs.closeSync(out);
|
|
1250
|
-
fs.closeSync(err);
|
|
1251
1330
|
log(`Spawned new process PID: ${childPid}, waiting for ready signal...`);
|
|
1252
|
-
const childExited = () => child.exitCode !== null || child.signalCode !== null;
|
|
1331
|
+
const childExited = () => spawnFailed || child.exitCode !== null || child.signalCode !== null;
|
|
1253
1332
|
const isChildRunning = async () => !childExited() && await trace.waitForDependency(platform.isProcessRunningAsync(childPid), 'daemon process liveness') && !childExited();
|
|
1254
|
-
//
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
if (
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
trace.finish(true);
|
|
1268
|
-
return true;
|
|
1269
|
-
}
|
|
1333
|
+
// The captured handle reports early exit. Only verify OS liveness after a
|
|
1334
|
+
// ready candidate is present or when the timeout recovery needs it.
|
|
1335
|
+
const ready = await trace.waitForDependency(waitForRestartReadySignal(p.readySignal, childExited, timeout, isChildRunning), 'daemon ready.signal');
|
|
1336
|
+
if (ready === 'exited') {
|
|
1337
|
+
log('Process exited before ready signal');
|
|
1338
|
+
if (requireEcweb)
|
|
1339
|
+
await trace.waitForDependency(stopEcwebForRestart(p, ecwebPort, log), 'ECWeb shutdown confirmation');
|
|
1340
|
+
return false;
|
|
1341
|
+
}
|
|
1342
|
+
if (ready === 'ready') {
|
|
1343
|
+
log('Daemon ready; managed services are supervised independently');
|
|
1344
|
+
trace.finish(true);
|
|
1345
|
+
return true;
|
|
1270
1346
|
}
|
|
1271
1347
|
const ping = await trace.waitForDependency(ipcQuery(p.socket, { type: 'ping' }, platform.isWindows ? 5_000 : 1_000), 'daemon IPC ping response');
|
|
1272
1348
|
if (ping?.pong === true && ping.pid === childPid && await isChildRunning()) {
|
package/dist/cli/task-context.js
CHANGED
|
@@ -16,6 +16,22 @@ const generatedProcessManagedTempDirs = new Set();
|
|
|
16
16
|
const preparedWindowsSessionRuntimeDirs = new Set();
|
|
17
17
|
const pendingSessionRuntimeDirs = new Map();
|
|
18
18
|
let processTempCleanupRegistered = false;
|
|
19
|
+
export class SessionRuntimeError extends Error {
|
|
20
|
+
stage;
|
|
21
|
+
directory;
|
|
22
|
+
code = 'SESSION_RUNTIME_UNAVAILABLE';
|
|
23
|
+
systemCode;
|
|
24
|
+
constructor(stage, directory, cause) {
|
|
25
|
+
const failure = cause;
|
|
26
|
+
const systemCode = failure?.killed || failure?.code === 'ETIMEDOUT'
|
|
27
|
+
? 'ETIMEDOUT' : failure?.code === undefined ? undefined : String(failure.code);
|
|
28
|
+
super(`SESSION_RUNTIME_UNAVAILABLE: managed session TMPDIR is unavailable or untrusted (${stage}${systemCode ? `; ${systemCode}` : ''})`, { cause });
|
|
29
|
+
this.stage = stage;
|
|
30
|
+
this.directory = directory;
|
|
31
|
+
this.name = 'SessionRuntimeError';
|
|
32
|
+
this.systemCode = systemCode;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
19
35
|
function isPlainObject(value) {
|
|
20
36
|
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
21
37
|
}
|
|
@@ -225,16 +241,44 @@ function sessionRuntimeName(sessionId) {
|
|
|
225
241
|
* runner filesystem policy, so the runtime directory only needs a portable
|
|
226
242
|
* writable ACL rather than host-user secrecy.
|
|
227
243
|
*/
|
|
228
|
-
|
|
244
|
+
// Reapplying an inheritable ACE can walk a large existing session tree.
|
|
245
|
+
// Read only its root DACL first; use the original grant if evidence is absent.
|
|
246
|
+
const WINDOWS_SESSION_ACL_CHECK = `
|
|
247
|
+
$ErrorActionPreference='Stop'
|
|
248
|
+
$acl=[System.IO.Directory]::GetAccessControl($env:EVOLCORE_SESSION_RUNTIME_ACL_PATH)
|
|
249
|
+
$rules=@($acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]))
|
|
250
|
+
$modify=[System.Security.AccessControl.FileSystemRights]::Modify
|
|
251
|
+
$inherit=[System.Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
|
|
252
|
+
$ok=@($rules | Where-Object { $_.IdentityReference.Value -eq 'S-1-5-32-545' -and $_.AccessControlType -eq 'Allow' -and ($_.FileSystemRights -band $modify) -eq $modify -and ($_.InheritanceFlags -band $inherit) -eq $inherit -and $_.PropagationFlags -eq 'None' }).Count -gt 0
|
|
253
|
+
if ($ok -and @($rules | Where-Object { $_.AccessControlType -eq 'Deny' }).Count -eq 0) { 'ready' }
|
|
254
|
+
`;
|
|
255
|
+
function windowsSessionAclQuery(directory) {
|
|
256
|
+
return {
|
|
257
|
+
command: path.join(process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
258
|
+
args: ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SESSION_ACL_CHECK],
|
|
259
|
+
options: { windowsHide: true, timeout: 2_000, env: { ...process.env, EVOLCORE_SESSION_RUNTIME_ACL_PATH: directory } },
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
function ensureWindowsSessionRuntimeAccess(directory, existing) {
|
|
229
263
|
if (process.platform !== 'win32' || preparedWindowsSessionRuntimeDirs.has(directory))
|
|
230
264
|
return;
|
|
265
|
+
if (existing) {
|
|
266
|
+
const query = windowsSessionAclQuery(directory);
|
|
267
|
+
try {
|
|
268
|
+
if (execFileSync(query.command, query.args, { ...query.options, encoding: 'utf8' }).trim() === 'ready') {
|
|
269
|
+
preparedWindowsSessionRuntimeDirs.add(directory);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
catch { /* Unknown ACL: retain the original grant and failure behavior. */ }
|
|
274
|
+
}
|
|
231
275
|
const icacls = path.join(process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows', 'System32', 'icacls.exe');
|
|
232
276
|
execFileSync(icacls, [
|
|
233
277
|
directory,
|
|
234
278
|
'/grant',
|
|
235
279
|
'*S-1-5-32-545:(OI)(CI)M',
|
|
236
280
|
'/Q',
|
|
237
|
-
], { windowsHide: true, stdio: 'pipe' });
|
|
281
|
+
], { windowsHide: true, stdio: 'pipe', timeout: 10_000 });
|
|
238
282
|
preparedWindowsSessionRuntimeDirs.add(directory);
|
|
239
283
|
}
|
|
240
284
|
/** Whether a task-provided runtime directory is a stable EvolCore session root. */
|
|
@@ -289,7 +333,7 @@ export function getManagedTaskTempDir(runtimeEnv) {
|
|
|
289
333
|
&& path.resolve(contextDir) === path.resolve(configured)
|
|
290
334
|
&& isManagedSessionRuntimeDir(configured);
|
|
291
335
|
if (!trusted) {
|
|
292
|
-
throw new
|
|
336
|
+
throw new SessionRuntimeError('validate', configured);
|
|
293
337
|
}
|
|
294
338
|
return path.resolve(configured);
|
|
295
339
|
}
|
|
@@ -303,15 +347,24 @@ export function ensureSessionRuntimeDir(sessionId) {
|
|
|
303
347
|
return undefined;
|
|
304
348
|
const root = systemTempRoot();
|
|
305
349
|
const directory = path.join(root, sessionRuntimeName(sessionId));
|
|
350
|
+
let stage = 'create-root';
|
|
306
351
|
try {
|
|
307
352
|
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
308
|
-
|
|
309
|
-
|
|
353
|
+
stage = 'create-session';
|
|
354
|
+
const created = fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
355
|
+
stage = 'grant-access';
|
|
356
|
+
ensureWindowsSessionRuntimeAccess(directory, created === undefined);
|
|
357
|
+
stage = 'create-locks';
|
|
310
358
|
fs.mkdirSync(path.join(directory, 'locks'), { recursive: true, mode: 0o700 });
|
|
311
|
-
|
|
359
|
+
stage = 'validate';
|
|
360
|
+
if (!isManagedSessionRuntimeDir(directory, root))
|
|
361
|
+
throw new SessionRuntimeError(stage, directory);
|
|
362
|
+
return directory;
|
|
312
363
|
}
|
|
313
|
-
catch {
|
|
314
|
-
|
|
364
|
+
catch (error) {
|
|
365
|
+
if (error instanceof SessionRuntimeError)
|
|
366
|
+
throw error;
|
|
367
|
+
throw new SessionRuntimeError(stage, directory, error);
|
|
315
368
|
}
|
|
316
369
|
}
|
|
317
370
|
/** Await ACL preparation without blocking unrelated sessions or daemon I/O. */
|
|
@@ -324,21 +377,36 @@ export async function ensureSessionRuntimeDirAsync(sessionId) {
|
|
|
324
377
|
if (pending)
|
|
325
378
|
return pending;
|
|
326
379
|
const prepare = (async () => {
|
|
380
|
+
let stage = 'create-root';
|
|
327
381
|
try {
|
|
328
382
|
await fs.promises.mkdir(root, { recursive: true, mode: 0o700 });
|
|
329
|
-
|
|
383
|
+
stage = 'create-session';
|
|
384
|
+
const created = await fs.promises.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
385
|
+
stage = 'grant-access';
|
|
330
386
|
if (process.platform === 'win32' && !preparedWindowsSessionRuntimeDirs.has(directory)) {
|
|
331
|
-
const
|
|
332
|
-
await new Promise(
|
|
333
|
-
execFile(
|
|
387
|
+
const query = windowsSessionAclQuery(directory);
|
|
388
|
+
const alreadyGranted = created === undefined && await new Promise(resolve => {
|
|
389
|
+
execFile(query.command, query.args, query.options, (error, stdout) => resolve(!error && String(stdout).trim() === 'ready'));
|
|
334
390
|
});
|
|
391
|
+
if (!alreadyGranted) {
|
|
392
|
+
const icacls = path.join(process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows', 'System32', 'icacls.exe');
|
|
393
|
+
await new Promise((resolve, reject) => {
|
|
394
|
+
execFile(icacls, [directory, '/grant', '*S-1-5-32-545:(OI)(CI)M', '/Q'], { windowsHide: true, timeout: 10_000 }, error => error ? reject(error) : resolve());
|
|
395
|
+
});
|
|
396
|
+
}
|
|
335
397
|
preparedWindowsSessionRuntimeDirs.add(directory);
|
|
336
398
|
}
|
|
399
|
+
stage = 'create-locks';
|
|
337
400
|
await fs.promises.mkdir(path.join(directory, 'locks'), { recursive: true, mode: 0o700 });
|
|
338
|
-
|
|
401
|
+
stage = 'validate';
|
|
402
|
+
if (!isManagedSessionRuntimeDir(directory, root))
|
|
403
|
+
throw new SessionRuntimeError(stage, directory);
|
|
404
|
+
return directory;
|
|
339
405
|
}
|
|
340
|
-
catch {
|
|
341
|
-
|
|
406
|
+
catch (error) {
|
|
407
|
+
if (error instanceof SessionRuntimeError)
|
|
408
|
+
throw error;
|
|
409
|
+
throw new SessionRuntimeError(stage, directory, error);
|
|
342
410
|
}
|
|
343
411
|
})();
|
|
344
412
|
pendingSessionRuntimeDirs.set(directory, prepare);
|
|
@@ -73,9 +73,11 @@ export async function cmdUpgrade(argv) {
|
|
|
73
73
|
: await ipcHostQuery(resolvePaths().socket, command, 120_000, { throwOnError: true });
|
|
74
74
|
if (!raw)
|
|
75
75
|
throw Object.assign(new Error('无法连接 EvolCore daemon'), { code: 'DAEMON_UNAVAILABLE' });
|
|
76
|
-
//
|
|
76
|
+
// Upgrade executors return Menu responses directly; other IPC paths may wrap them.
|
|
77
|
+
// Authentication can also reject the request before the Menu adapter runs.
|
|
77
78
|
const envelope = raw;
|
|
78
|
-
const payload = envelope.
|
|
79
|
+
const payload = envelope.type === 'menu.response'
|
|
80
|
+
? raw : envelope.response ?? envelope.data?.response;
|
|
79
81
|
if (payload && typeof payload === 'object' && payload.type === 'menu.response') {
|
|
80
82
|
response = parseMenuResponse(payload);
|
|
81
83
|
}
|
|
@@ -371,15 +371,18 @@ export function assertContactBookV2Ready() {
|
|
|
371
371
|
return;
|
|
372
372
|
const issues = [];
|
|
373
373
|
const contactMigrationAgentSchemaMax = 6;
|
|
374
|
-
const
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
374
|
+
const versions = new Map();
|
|
375
|
+
const supportedVersions = (name, minimumVersion) => {
|
|
376
|
+
let supported = versions.get(name);
|
|
377
|
+
if (!supported) {
|
|
378
|
+
supported = listSchemaVersions(name).filter(version => version >= minimumVersion);
|
|
379
|
+
versions.set(name, supported);
|
|
380
|
+
}
|
|
381
|
+
return supported;
|
|
382
|
+
};
|
|
378
383
|
/** 当前 Agent 配置版本:介于迁移上限与它之间的版本都由别处校验,本门禁放行。 */
|
|
379
384
|
const agentConfigCurrentVersion = currentVersion('agent-config');
|
|
380
|
-
const
|
|
381
|
-
const relationSchemas = supportedSchemas('relation-config', 5);
|
|
382
|
-
const inspect = (file, schemas, skipNewerAgentSchema = false) => {
|
|
385
|
+
const inspect = (file, name, minimumVersion, skipNewerAgentSchema = false) => {
|
|
383
386
|
let value;
|
|
384
387
|
try {
|
|
385
388
|
value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
@@ -389,7 +392,6 @@ export function assertContactBookV2Ready() {
|
|
|
389
392
|
return;
|
|
390
393
|
}
|
|
391
394
|
value = stripLegacyAunGatewayConfig(value, file, message => configWarn(message));
|
|
392
|
-
const candidates = Array.isArray(schemas) ? schemas : [schemas];
|
|
393
395
|
const schemaVersion = value?.$schema_version;
|
|
394
396
|
if (skipNewerAgentSchema && typeof schemaVersion === 'number'
|
|
395
397
|
&& schemaVersion > contactMigrationAgentSchemaMax
|
|
@@ -402,12 +404,22 @@ export function assertContactBookV2Ready() {
|
|
|
402
404
|
// 仍然拒绝——那是本程序不认识的未来格式。
|
|
403
405
|
return;
|
|
404
406
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
407
|
+
const supported = supportedVersions(name, minimumVersion);
|
|
408
|
+
// Healthy files only need their own schema. Keep the full historical
|
|
409
|
+
// fallback for malformed/legacy input, including the previous diagnostics.
|
|
410
|
+
if (typeof schemaVersion === 'number' && supported.includes(schemaVersion)
|
|
411
|
+
&& loadSchema(name, schemaVersion).validate(value))
|
|
412
|
+
return;
|
|
413
|
+
let lastSchema;
|
|
414
|
+
for (const version of supported) {
|
|
415
|
+
lastSchema = loadSchema(name, version);
|
|
416
|
+
if (lastSchema.validate(value))
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const detail = (lastSchema?.validate.errors ?? [])
|
|
420
|
+
.map(error => `${error.instancePath || '/'} ${error.message}`)
|
|
421
|
+
.join('; ');
|
|
422
|
+
issues.push({ file, detail });
|
|
411
423
|
};
|
|
412
424
|
const walkRelationConfigs = (dir) => {
|
|
413
425
|
if (!fs.existsSync(dir))
|
|
@@ -429,14 +441,14 @@ export function assertContactBookV2Ready() {
|
|
|
429
441
|
const agentFile = path.join(dir, 'config.json');
|
|
430
442
|
if (!fs.existsSync(agentFile))
|
|
431
443
|
continue;
|
|
432
|
-
inspect(agentFile,
|
|
444
|
+
inspect(agentFile, 'agent-config', contactMigrationAgentSchemaMax, true);
|
|
433
445
|
const contactFile = path.join(dir, 'contact.json');
|
|
434
446
|
if (fs.existsSync(contactFile)) {
|
|
435
|
-
inspect(contactFile,
|
|
447
|
+
inspect(contactFile, 'contact-book', 2);
|
|
436
448
|
inspectContactBookDomain(contactFile, agentFile, issues);
|
|
437
449
|
}
|
|
438
450
|
for (const relationFile of walkRelationConfigs(path.join(dir, 'relations'))) {
|
|
439
|
-
inspect(relationFile,
|
|
451
|
+
inspect(relationFile, 'relation-config', 5);
|
|
440
452
|
}
|
|
441
453
|
}
|
|
442
454
|
const correctionReceipt = path.join(root, 'data', 'contact-book-v2-relation-role-authority.json');
|
|
@@ -151,10 +151,10 @@ function managementRoleMapForAgent(selfAid, changes) {
|
|
|
151
151
|
if (parsed.channelType !== 'aun' || !isValidAid(parsed.channelId))
|
|
152
152
|
continue;
|
|
153
153
|
const config = readTransactionJson(path.join(relationsRoot, peerKey, 'config.json'), changes);
|
|
154
|
-
if (readAunPeerKind(selfAid, parsed.channelId, { relation: config }).kind !== 'private')
|
|
155
|
-
continue;
|
|
156
154
|
if (config?.targetKind !== 'group' && config?.role === 'admin' && roles[parsed.channelId] !== 'owner') {
|
|
157
|
-
|
|
155
|
+
if (readAunPeerKind(selfAid, parsed.channelId, { relation: config }).kind === 'private') {
|
|
156
|
+
roles[parsed.channelId] = 'admin';
|
|
157
|
+
}
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
160
|
return roles;
|
|
@@ -174,7 +174,14 @@ export function synchronizeAllManagementPeersSync() {
|
|
|
174
174
|
for (const entry of entries) {
|
|
175
175
|
if (!entry.isDirectory() || !isValidAid(entry.name) || !fs.existsSync(agentConfig(entry.name)))
|
|
176
176
|
continue;
|
|
177
|
-
|
|
177
|
+
// Startup has not observed protocol ownership yet. Do not erase its old
|
|
178
|
+
// display projection just to recreate it on the first verified update.
|
|
179
|
+
// Permission consumers resolve ownership independently of this field.
|
|
180
|
+
if (mutateContactBookSyncInternal({
|
|
181
|
+
selfAid: entry.name,
|
|
182
|
+
actor: 'management-role-sync',
|
|
183
|
+
mutation: { type: 'sync-management-roles' },
|
|
184
|
+
}, [], true).changed)
|
|
178
185
|
changed += 1;
|
|
179
186
|
}
|
|
180
187
|
return changed;
|
|
@@ -201,18 +208,18 @@ export function recoverAllPeerBookMutationsSync() {
|
|
|
201
208
|
}
|
|
202
209
|
return recovered;
|
|
203
210
|
}
|
|
204
|
-
function mutateContactBookSyncInternal(request, transactionChanges) {
|
|
211
|
+
function mutateContactBookSyncInternal(request, transactionChanges, deferUnobservedOwner = false) {
|
|
205
212
|
const selfAid = normalizeAid(request.selfAid, 'self AID');
|
|
206
213
|
const release = acquireAgentLock(selfAid);
|
|
207
214
|
try {
|
|
208
|
-
return mutateContactBookLocked({ ...request, selfAid }, transactionChanges);
|
|
215
|
+
return mutateContactBookLocked({ ...request, selfAid }, transactionChanges, deferUnobservedOwner);
|
|
209
216
|
}
|
|
210
217
|
finally {
|
|
211
218
|
release();
|
|
212
219
|
}
|
|
213
220
|
}
|
|
214
221
|
/** The caller owns the contact lock; the entire critical section is synchronous. */
|
|
215
|
-
function mutateContactBookLocked(request, transactionChanges) {
|
|
222
|
+
function mutateContactBookLocked(request, transactionChanges, deferUnobservedOwner = false) {
|
|
216
223
|
const selfAid = request.selfAid;
|
|
217
224
|
recoverMutation(selfAid);
|
|
218
225
|
const file = agentPeerConfig(selfAid);
|
|
@@ -228,7 +235,7 @@ function mutateContactBookLocked(request, transactionChanges) {
|
|
|
228
235
|
validateTransactionChanges(selfAid, transactionChanges);
|
|
229
236
|
const next = cloneBook(current);
|
|
230
237
|
applyMutation(next, request.mutation, selfAid, transactionChanges);
|
|
231
|
-
synchronizeManagementRoles(next, selfAid, transactionChanges);
|
|
238
|
+
synchronizeManagementRoles(next, selfAid, transactionChanges, deferUnobservedOwner);
|
|
232
239
|
if (request.mutation.type === 'replace') {
|
|
233
240
|
const errors = validateConfig(ConfigTarget.Peer, next);
|
|
234
241
|
if (errors.length)
|
|
@@ -456,13 +463,14 @@ function applyMutation(book, mutation, selfAid, changes = []) {
|
|
|
456
463
|
}
|
|
457
464
|
throw new PeerMutationError('INVALID_MUTATION', `Unsupported Contact Book mutation: ${String(mutation?.type)}`);
|
|
458
465
|
}
|
|
459
|
-
function synchronizeManagementRoles(book, selfAid, changes) {
|
|
466
|
+
function synchronizeManagementRoles(book, selfAid, changes, deferUnobservedOwner = false) {
|
|
460
467
|
const roles = managementRoleMapForAgent(selfAid, changes);
|
|
468
|
+
const ownershipPending = deferUnobservedOwner && ownerResolver.snapshot(selfAid).checkedAt === undefined;
|
|
461
469
|
for (const [primaryId, entry] of Object.entries(book.contacts)) {
|
|
462
470
|
book.contacts[primaryId] = compactEntry({
|
|
463
471
|
...entry,
|
|
464
472
|
...(roles[primaryId] === 'owner' ? { status: undefined, pendingRequest: undefined, declinedAt: undefined } : {}),
|
|
465
|
-
managementRole: roles[primaryId],
|
|
473
|
+
managementRole: roles[primaryId] ?? (ownershipPending && entry.managementRole === 'owner' ? 'owner' : undefined),
|
|
466
474
|
});
|
|
467
475
|
}
|
|
468
476
|
for (const [primaryId, managementRole] of Object.entries(roles)) {
|