evolcore 0.0.46 → 0.0.48
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 +93 -0
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +139 -39
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +43 -18
- package/dist/agents/codex/app-server-client.js +32 -23
- package/dist/agents/codex-runner.js +31 -16
- package/dist/agents/ecagent-runner.js +7 -4
- package/dist/agents/gemini-runner.js +5 -2
- package/dist/agents/runner-types.js +5 -21
- package/dist/aun/aid/agentmd.js +5 -1
- package/dist/aun/group/fs-download.js +1 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +100 -32
- package/dist/channels/daemon.js +10 -26
- package/dist/cli/aun-commands.js +86 -51
- package/dist/cli/code-stats.js +19 -8
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +65 -76
- package/dist/cli/daemon-lifecycle-client.js +17 -3
- package/dist/cli/directory.js +7 -1
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +2 -8
- package/dist/cli/init-channel.js +6 -8
- package/dist/cli/init.js +74 -46
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/restart-monitor.js +104 -28
- package/dist/cli/role.js +61 -17
- package/dist/cli/stats.js +3 -3
- package/dist/cli/task-context.js +83 -15
- package/dist/cli/thread-command.js +16 -51
- package/dist/cli/upgrade-command.js +4 -2
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-manager.js +31 -23
- package/dist/config/daemon-services.js +30 -3
- package/dist/config/gateway-config.js +2 -2
- package/dist/config/invoke-ipc-service.js +6 -4
- package/dist/config/peer-bind-code.js +3 -4
- package/dist/config/peer-book-store.js +59 -218
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +161 -6
- package/dist/config/provider-ipc-service.js +56 -11
- package/dist/config/provider-menu-request.js +24 -5
- package/dist/config/provider-templates.js +127 -0
- package/dist/config/providers-config.js +59 -8
- package/dist/config/providers-management.js +467 -49
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +228 -20
- package/dist/config/schema-registry.js +6 -2
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +10 -5
- package/dist/core/auth/agent-delegation.js +10 -4
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +3 -0
- package/dist/core/auth/delegation-diagnostics.js +56 -15
- package/dist/core/auth/operation-authorizer.js +26 -1
- package/dist/core/auth/operation-catalog.js +28 -64
- package/dist/core/capability/providers/codex-capability-provider.js +7 -8
- package/dist/core/channel-loader.js +18 -0
- package/dist/core/command/agent-control.js +32 -0
- package/dist/core/command/command-handler.js +81 -85
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +65 -153
- package/dist/core/command/menu-protocol.js +7 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +30 -49
- package/dist/core/command/team-workspace-items.js +81 -12
- package/dist/core/command/team-workspace-team.js +9 -71
- package/dist/core/command/topic-slash.js +9 -30
- package/dist/core/daemon-bootstrap.js +19 -10
- package/dist/core/daemon-control.js +8 -10
- package/dist/core/daemon-lifecycle.js +50 -40
- package/dist/core/evolagent-registry.js +22 -3
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/host-snapshot.js +9 -4
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +31 -8
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +6 -4
- package/dist/core/memory/consolidation.js +6 -6
- package/dist/core/message/aun-ipc-sender.js +165 -55
- package/dist/core/message/im-renderer.js +1 -1
- package/dist/core/message/message-bridge.js +51 -334
- package/dist/core/message/message-log.js +5 -0
- package/dist/core/message/message-queue.js +22 -0
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +429 -116
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/ownership/owner-resolver.js +355 -60
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/relation/peer-identity.js +28 -2
- package/dist/core/relation/same-owner-proof.js +81 -111
- package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +49 -14
- package/dist/core/session/session-fs-store.js +91 -35
- package/dist/core/session/session-manager.js +68 -24
- package/dist/core/session/session-mapper.js +14 -34
- package/dist/core/session/session-transcript.js +5 -1
- package/dist/core/task/task-activity-store.js +84 -0
- package/dist/core/task/task-image-resources.js +1 -1
- package/dist/core/task/task-recovery-service.js +12 -0
- package/dist/core/thread/command-parser.js +7 -12
- package/dist/core/thread/thread-context-storage.js +3 -2
- package/dist/core/thread/thread-operation.js +2 -13
- package/dist/core/thread/thread-service.js +15 -46
- package/dist/directory/owner-directory-admission.js +1 -1
- package/dist/directory/owner-directory-cache.js +45 -28
- package/dist/directory/owner-directory-markdown.js +13 -1
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/eck/message-renderer.js +84 -24
- package/dist/ecweb/basic-settings-service.js +3 -1
- package/dist/ecweb/message-context-service.js +1 -1
- package/dist/ecweb/pairing.js +4 -3
- package/dist/ecweb/providers-service.js +26 -1
- package/dist/ecweb/runtime/lifecycle.js +82 -23
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +6 -17
- package/dist/event-center/registry.js +13 -2
- package/dist/event-center/runtime.js +103 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +129 -93
- package/dist/ipc.js +15 -3
- package/dist/outputs/events.js +62 -0
- package/dist/outputs/protocol.js +102 -0
- package/dist/outputs/service.js +279 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +89 -4
- package/dist/services/ipc-operation.js +4 -15
- package/dist/services/pack-manager.js +12 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +1 -1
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/role-budget.js +5 -2
- package/dist/stats/writer.js +10 -6
- package/dist/trigger/audit.js +7 -0
- package/dist/trigger/authorization.js +105 -11
- package/dist/trigger/feedback.js +10 -0
- package/dist/trigger/history.js +37 -11
- package/dist/trigger/ipc-service.js +12 -1
- package/dist/trigger/manager.js +1 -0
- package/dist/trigger/scheduler.js +11 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +9 -3
- package/dist/trigger/state.js +7 -0
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/aid-bind.js +155 -18
- package/dist/utils/atomic-write.js +3 -3
- package/dist/utils/cross-platform.js +97 -31
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +40 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/instance-registry.js +61 -0
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/process-introspect.js +158 -8
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/upgrade-jobs.js +4 -4
- package/dist/utils/windows-shell-trust.js +2 -0
- package/dist/workbench/protocol.js +80 -0
- package/dist/workbench/service.js +359 -0
- package/ecagent/dist/types.d.ts +6 -2
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +2 -2
- package/kits/docs/evolcore/aid.md +3 -1
- package/kits/docs/evolcore/config.md +12 -0
- package/kits/docs/evolcore/directory.md +22 -3
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +133 -5
- package/kits/docs/evolcore/role.md +80 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/team-workspace.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +14 -15
- package/kits/docs/evolcore/tool-authorization.md +5 -0
- package/kits/docs/evolcore/trigger.md +10 -0
- package/kits/eck_message_manifest.json +12 -0
- package/kits/provider-templates.json +1213 -0
- package/kits/rules/04-relation.md +3 -3
- package/kits/schemas/_meta.json +14 -2
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/ec-group/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +19 -72
- package/kits/skills/ec-provider/SKILL.md +221 -0
- package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/skills/thread-ops/SKILL.md +34 -21
- package/kits/templates/message-fragments/group-batch-item.md +1 -1
- package/kits/templates/message-fragments/group-batch.md +1 -1
- package/kits/templates/message-fragments/inject-default.md +1 -1
- package/kits/templates/message-fragments/interrupt-insert.md +1 -0
- package/kits/templates/message-fragments/item-group.md +1 -1
- package/kits/templates/message-fragments/item-private.md +1 -1
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/message-fragments/trigger-session.md +1 -1
- package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
- package/kits/templates/roles/admin.json +2 -19
- package/kits/templates/roles/member.json +0 -3
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +3 -3
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +1 -1
- package/kits/templates/system-fragments/thread.md +6 -5
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +4 -1
- package/scripts/agent-template/shared/common.mjs +2 -3
- package/scripts/agent-template/shared/template-contract.mjs +2 -1
- package/scripts/agent-template/shared/template-package.mjs +9 -2
- package/scripts/agent-template/shared/template-runtime.mjs +20 -5
- package/scripts/agent-template/team-pack.mjs +6 -3
- package/dist/cli/peer.js +0 -127
- package/dist/config/peer-operation-service.js +0 -132
- package/dist/config/peer-request-service.js +0 -532
- package/dist/core/command/connect-menu.js +0 -624
|
@@ -3,6 +3,11 @@ import fs from 'fs';
|
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import { fileURLToPath } from 'url';
|
|
5
5
|
import { getPackageRoot } from '../paths.js';
|
|
6
|
+
// Embedded by bin/ec-build.mjs; loaded processes retain these values across rebuilds.
|
|
7
|
+
// @evolcore-build-identity:start
|
|
8
|
+
export const RUNTIME_BUILD_ID = "sha256:76e20a438d3936bb3420763f";
|
|
9
|
+
export const RUNTIME_BUILD_TIME = "2026-11-14T05:54:02.439Z";
|
|
10
|
+
// @evolcore-build-identity:end
|
|
6
11
|
let cachedVersion;
|
|
7
12
|
let cachedFlavor;
|
|
8
13
|
let cachedStartStamp;
|
|
@@ -170,10 +175,23 @@ export function computeBuildId(distDir) {
|
|
|
170
175
|
try {
|
|
171
176
|
const hash = crypto.createHash('sha256');
|
|
172
177
|
for (const relative of collectFiles(distDir)) {
|
|
178
|
+
const normalized = relative.replaceAll(path.sep, '/');
|
|
179
|
+
if (['build-identity.json', 'build-identity.json.tmp'].includes(normalized))
|
|
180
|
+
continue;
|
|
173
181
|
const full = path.join(distDir, relative);
|
|
174
|
-
|
|
182
|
+
let content = fs.readFileSync(full);
|
|
183
|
+
if (normalized === 'utils/evolcore-version.js') {
|
|
184
|
+
// Match the build writer without excluding changes to this module's implementation.
|
|
185
|
+
content = Buffer.from(content.toString('utf8').replace(/^\/\/ @evolcore-build-identity:start\r?\n[\s\S]*?^\/\/ @evolcore-build-identity:end[ \t]*(?=\r?$)/gm, [
|
|
186
|
+
'// @evolcore-build-identity:start',
|
|
187
|
+
'export const RUNTIME_BUILD_ID = null;',
|
|
188
|
+
'export const RUNTIME_BUILD_TIME = null;',
|
|
189
|
+
'// @evolcore-build-identity:end',
|
|
190
|
+
].join('\n')));
|
|
191
|
+
}
|
|
192
|
+
hash.update(normalized);
|
|
175
193
|
hash.update('\0');
|
|
176
|
-
hash.update(
|
|
194
|
+
hash.update(content);
|
|
177
195
|
hash.update('\0');
|
|
178
196
|
}
|
|
179
197
|
return `sha256:${hash.digest('hex').slice(0, 24)}`;
|
|
@@ -184,56 +202,21 @@ export function computeBuildId(distDir) {
|
|
|
184
202
|
}
|
|
185
203
|
export function readBuildIdentity(distDir, version) {
|
|
186
204
|
return {
|
|
187
|
-
id:
|
|
205
|
+
id: readBuildMarker(distDir)?.id ?? null,
|
|
188
206
|
entry: path.join(distDir, 'index.js'),
|
|
189
207
|
...(version ? { version } : {}),
|
|
190
208
|
};
|
|
191
209
|
}
|
|
192
|
-
|
|
193
|
-
async function readBuildTreeAsync(root, hashFiles = true) {
|
|
194
|
-
let latestMtime = 0;
|
|
210
|
+
function readBuildMarker(distDir) {
|
|
195
211
|
try {
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
if (!hashFiles && entry.name === 'node_modules')
|
|
201
|
-
continue;
|
|
202
|
-
const full = path.join(directory, entry.name);
|
|
203
|
-
if (entry.isDirectory())
|
|
204
|
-
await collect(full);
|
|
205
|
-
else if (entry.isFile())
|
|
206
|
-
files.push(full);
|
|
207
|
-
}
|
|
208
|
-
};
|
|
209
|
-
await collect(root);
|
|
210
|
-
const hash = crypto.createHash('sha256');
|
|
211
|
-
for (let offset = 0; offset < files.length; offset += 8) {
|
|
212
|
-
const batch = await Promise.all(files.slice(offset, offset + 8).map(async (file) => {
|
|
213
|
-
const [content, stat] = await Promise.all([
|
|
214
|
-
hashFiles ? fs.promises.readFile(file) : undefined,
|
|
215
|
-
/\.(js|ts)$/.test(file) ? fs.promises.stat(file) : undefined,
|
|
216
|
-
]);
|
|
217
|
-
return { file, content, stat };
|
|
218
|
-
}));
|
|
219
|
-
for (const { file, content, stat } of batch) {
|
|
220
|
-
if (stat)
|
|
221
|
-
latestMtime = Math.max(latestMtime, stat.mtimeMs);
|
|
222
|
-
if (content) {
|
|
223
|
-
hash.update(path.relative(root, file).replaceAll(path.sep, '/'));
|
|
224
|
-
hash.update('\0');
|
|
225
|
-
hash.update(content);
|
|
226
|
-
hash.update('\0');
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
return { id: hashFiles ? `sha256:${hash.digest('hex').slice(0, 24)}` : null, latestMtime };
|
|
231
|
-
}
|
|
232
|
-
catch {
|
|
233
|
-
return { id: null, latestMtime };
|
|
212
|
+
const marker = JSON.parse(fs.readFileSync(path.join(distDir, 'build-identity.json'), 'utf8'));
|
|
213
|
+
if (/^sha256:[a-f0-9]{24}$/.test(marker?.id) && typeof marker.builtAt === 'string'
|
|
214
|
+
&& Number.isFinite(Date.parse(marker.builtAt)))
|
|
215
|
+
return marker;
|
|
234
216
|
}
|
|
217
|
+
catch { /* Older or incomplete builds have no identity; never fall back to a tree scan. */ }
|
|
235
218
|
}
|
|
236
|
-
/**
|
|
219
|
+
/** Capture the imported runtime identity before background work or later rebuilds. */
|
|
237
220
|
export function createEvolcoreStartupDiagnostics(entryUrl) {
|
|
238
221
|
const packageRoot = getPackageRoot();
|
|
239
222
|
const runtimeEntry = fileURLToPath(entryUrl);
|
|
@@ -241,46 +224,34 @@ export function createEvolcoreStartupDiagnostics(entryUrl) {
|
|
|
241
224
|
const runtimeIsDist = path.resolve(path.dirname(runtimeEntry)) === path.resolve(diskDistDir);
|
|
242
225
|
return {
|
|
243
226
|
state: 'pending', runtimeIsDist, diskDistDir, diskDistId: null,
|
|
244
|
-
runtimeBuildIdentity: { id:
|
|
227
|
+
runtimeBuildIdentity: { id: runtimeIsDist ? RUNTIME_BUILD_ID : null,
|
|
228
|
+
entry: runtimeEntry, version: readInstalledEvolcoreVersion() },
|
|
245
229
|
};
|
|
246
230
|
}
|
|
247
231
|
export async function reportEvolcoreStartup(entryUrl, report, diagnostics = createEvolcoreStartupDiagnostics(entryUrl)) {
|
|
248
232
|
const packageRoot = getPackageRoot();
|
|
249
233
|
const { runtimeIsDist, diskDistDir } = diagnostics;
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
]);
|
|
254
|
-
const diskDistId = dist.id;
|
|
255
|
-
const runtimeBuildIdentity = {
|
|
256
|
-
id: runtimeIsDist ? diskDistId : null,
|
|
257
|
-
entry: path.join(diskDistDir, 'index.js'),
|
|
258
|
-
version: readInstalledEvolcoreVersion(),
|
|
259
|
-
};
|
|
260
|
-
// Publish both IDs together. Pending/failed reads must never claim a match.
|
|
234
|
+
const marker = readBuildMarker(diskDistDir);
|
|
235
|
+
const diskDistId = marker?.id ?? null;
|
|
236
|
+
const runtimeBuildIdentity = diagnostics.runtimeBuildIdentity;
|
|
261
237
|
Object.assign(diagnostics, {
|
|
262
|
-
state: diskDistId === null ? 'unavailable' : 'ready',
|
|
238
|
+
state: diskDistId === null || (runtimeIsDist && runtimeBuildIdentity.id === null) ? 'unavailable' : 'ready', diskDistId,
|
|
263
239
|
});
|
|
264
240
|
const isLinked = fs.existsSync(path.join(packageRoot, '.git'));
|
|
265
241
|
const directoryType = runtimeIsDist ? (isLinked ? '开发仓/dist' : '安装路径/dist') : '源码(tsx)';
|
|
266
|
-
const latestMtime = source?.latestMtime ?? dist.latestMtime;
|
|
267
242
|
let version = '?';
|
|
268
243
|
try {
|
|
269
244
|
version = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version;
|
|
270
245
|
}
|
|
271
246
|
catch { }
|
|
272
|
-
const formatTime = (milliseconds) => {
|
|
273
|
-
const date = new Date(milliseconds);
|
|
274
|
-
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`;
|
|
275
|
-
};
|
|
276
247
|
console.error(`[EvolCore] EvolCore v${version}`);
|
|
277
248
|
console.error(`[EvolCore] 执行类型: ${directoryType}`);
|
|
278
249
|
console.error(`[EvolCore] 包路径: ${packageRoot}`);
|
|
279
|
-
console.error(`[EvolCore]
|
|
250
|
+
console.error(`[EvolCore] 构建时间: ${runtimeIsDist ? (RUNTIME_BUILD_TIME ?? '?') : 'source'}`);
|
|
280
251
|
console.error('[EvolCore] ✓ Version info printed');
|
|
281
252
|
const diskBuildId = diskDistId;
|
|
282
253
|
console.error(`[EvolCore] 运行 build ID: ${runtimeIsDist ? (runtimeBuildIdentity.id ?? '?') : 'source'}`);
|
|
283
254
|
console.error(`[EvolCore] 磁盘 dist build ID: ${diskBuildId ?? '?'}`);
|
|
284
|
-
report(`[Build] runtimeMode=${runtimeIsDist ? 'dist' : 'source'} runtimeBuildId=${runtimeBuildIdentity.id ?? 'source'} diskDistBuildId=${diskBuildId ?? 'unknown'} match=${runtimeIsDist && runtimeBuildIdentity.id !== null && runtimeBuildIdentity.id === diskBuildId}`);
|
|
255
|
+
report(`[Build] runtimeMode=${runtimeIsDist ? 'dist' : 'source'} runtimeBuildId=${runtimeBuildIdentity.id ?? (runtimeIsDist ? 'unknown' : 'source')} diskDistBuildId=${diskBuildId ?? 'unknown'} match=${runtimeIsDist && runtimeBuildIdentity.id !== null && runtimeBuildIdentity.id === diskBuildId}`);
|
|
285
256
|
return diagnostics;
|
|
286
257
|
}
|
|
@@ -308,6 +308,67 @@ export function scanInstances(options = {}) {
|
|
|
308
308
|
}
|
|
309
309
|
return status;
|
|
310
310
|
}
|
|
311
|
+
/** Observe the IPC target only; the restart monitor still owns election and cleanup. */
|
|
312
|
+
export async function hasLiveMain(pid) {
|
|
313
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
314
|
+
return false;
|
|
315
|
+
let record;
|
|
316
|
+
try {
|
|
317
|
+
record = JSON.parse(await fs.promises.readFile(path.join(instanceDir(), mainFileName(pid)), 'utf8'));
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
if (error instanceof SyntaxError || error.code === 'ENOENT')
|
|
321
|
+
return false;
|
|
322
|
+
throw error;
|
|
323
|
+
}
|
|
324
|
+
if (record?.pid !== pid || !Number.isFinite(record.startedAt) || record.startedAt <= 0)
|
|
325
|
+
return false;
|
|
326
|
+
// A fresh identity lookup already confirms liveness after the OS query.
|
|
327
|
+
// Fall back conservatively only when the creation time is unavailable.
|
|
328
|
+
const actual = await getProcessStartTimeAsync(pid, { fresh: true });
|
|
329
|
+
return actual !== null ? startTimeMatches(record.startedAt, actual) : await isProcessRunningAsync(pid);
|
|
330
|
+
}
|
|
331
|
+
/** Read-only launch observation; never block the daemon's shutdown IPC with a full process scan. */
|
|
332
|
+
export async function hasLiveRestartMonitor(options = {}) {
|
|
333
|
+
const directory = instanceDir();
|
|
334
|
+
let files;
|
|
335
|
+
try {
|
|
336
|
+
files = await fs.promises.readdir(directory);
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
if (error.code === 'ENOENT')
|
|
340
|
+
return false;
|
|
341
|
+
throw error;
|
|
342
|
+
}
|
|
343
|
+
for (const file of files) {
|
|
344
|
+
const match = /^restart-monitor-(\d+)\.json$/.exec(file);
|
|
345
|
+
if (!match)
|
|
346
|
+
continue;
|
|
347
|
+
const pid = Number(match[1]);
|
|
348
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || pid === options.excludePid
|
|
349
|
+
|| (options.pid !== undefined && pid !== options.pid))
|
|
350
|
+
continue;
|
|
351
|
+
let record;
|
|
352
|
+
try {
|
|
353
|
+
record = JSON.parse(await fs.promises.readFile(path.join(directory, file), 'utf8'));
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
if (error instanceof SyntaxError || error.code === 'ENOENT')
|
|
357
|
+
continue;
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
360
|
+
if (record?.pid !== pid || !Number.isFinite(record.startedAt) || record.startedAt <= 0
|
|
361
|
+
|| (options.requestId !== undefined && record.requestId !== options.requestId)
|
|
362
|
+
|| (options.phase !== undefined && record.phase !== options.phase))
|
|
363
|
+
continue;
|
|
364
|
+
if (!await isProcessRunningAsync(pid))
|
|
365
|
+
continue;
|
|
366
|
+
const actual = await getProcessStartTimeAsync(pid, { fresh: true });
|
|
367
|
+
if (actual !== null ? startTimeMatches(record.startedAt, actual) : await isProcessRunningAsync(pid))
|
|
368
|
+
return true;
|
|
369
|
+
}
|
|
370
|
+
return false;
|
|
371
|
+
}
|
|
311
372
|
/**
|
|
312
373
|
* 清理所有非自己 PID 的残留文件。仍活着的旧实例进程会被 SIGKILL。
|
|
313
374
|
* 发送终止信号前重新核验身份;无法核验或终止失败时保留登记供后续处理。
|
package/dist/utils/msg-diag.js
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
* killing the wrong process).
|
|
8
8
|
*/
|
|
9
9
|
import fs from 'fs';
|
|
10
|
+
import os from 'os';
|
|
11
|
+
import path from 'path';
|
|
10
12
|
import { execFile, spawnSync } from 'child_process';
|
|
11
13
|
const isWindows = process.platform === 'win32';
|
|
12
14
|
const isMacOS = process.platform === 'darwin';
|
|
@@ -73,13 +75,16 @@ export async function getProcessStartTimeAsync(pid, options = {}) {
|
|
|
73
75
|
const query = (async () => {
|
|
74
76
|
let startedAt;
|
|
75
77
|
if (isWindows) {
|
|
76
|
-
|
|
77
|
-
`(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToUniversalTime().ToString('o')`], 8000);
|
|
78
|
-
startedAt = parseCimDate(output) ?? parseDateString(output);
|
|
78
|
+
startedAt = await readWindowsStartTimeAsync(pid);
|
|
79
79
|
if (startedAt === null) {
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
startedAt =
|
|
80
|
+
const output = await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command',
|
|
81
|
+
`(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToUniversalTime().ToString('o')`], 8000);
|
|
82
|
+
startedAt = parseCimDate(output) ?? parseDateString(output);
|
|
83
|
+
if (startedAt === null) {
|
|
84
|
+
const fallback = await processQuery('wmic', ['process', 'where', `ProcessId=${pid}`, 'get', 'CreationDate', '/value'], 5000);
|
|
85
|
+
const creation = fallback.match(/CreationDate=([^\r\n]+)/)?.[1]?.trim();
|
|
86
|
+
startedAt = creation ? parseCimDate(creation) ?? parseDateString(creation) : null;
|
|
87
|
+
}
|
|
83
88
|
}
|
|
84
89
|
}
|
|
85
90
|
else if (isMacOS) {
|
|
@@ -231,6 +236,30 @@ function getStartTimeMacOS(pid) {
|
|
|
231
236
|
}
|
|
232
237
|
// ── Windows ──
|
|
233
238
|
function getStartTimeWindows(pid) {
|
|
239
|
+
const query = createWindowsProcessQuery(WINDOWS_WMI_SNAPSHOT_SCRIPT, pid);
|
|
240
|
+
if (query) {
|
|
241
|
+
try {
|
|
242
|
+
const result = spawnSync(query.command, query.args, {
|
|
243
|
+
encoding: 'utf8', timeout: 2000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'],
|
|
244
|
+
});
|
|
245
|
+
const startedAt = parseWindowsPidStartTime(result.status === 0 ? result.stdout || '' : '', pid);
|
|
246
|
+
if (startedAt !== null) {
|
|
247
|
+
// The queried child may have exited before WMI returned its row.
|
|
248
|
+
try {
|
|
249
|
+
process.kill(pid, 0);
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
if (error.code !== 'EPERM')
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
return startedAt;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
catch { /* Retain the legacy transports if the script host cannot run. */ }
|
|
259
|
+
finally {
|
|
260
|
+
query.dispose();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
234
263
|
const fromPwsh = winPowerShellCreationDate(pid);
|
|
235
264
|
if (fromPwsh !== null)
|
|
236
265
|
return fromPwsh;
|
|
@@ -276,6 +305,8 @@ const SNAPSHOT_TTL_MS = 5000;
|
|
|
276
305
|
* 传 `{ fresh: true }` 可强制重新采集(例如清理前需要最新状态)。
|
|
277
306
|
*/
|
|
278
307
|
export function getProcessSnapshot(options = {}) {
|
|
308
|
+
if (options.fresh)
|
|
309
|
+
invalidateProcessSnapshot();
|
|
279
310
|
const now = Date.now();
|
|
280
311
|
if (!options.fresh && snapshotCache && now - snapshotCache.at < SNAPSHOT_TTL_MS) {
|
|
281
312
|
return snapshotCache.snapshot;
|
|
@@ -284,8 +315,10 @@ export function getProcessSnapshot(options = {}) {
|
|
|
284
315
|
snapshotCache = { at: now, snapshot };
|
|
285
316
|
return snapshot;
|
|
286
317
|
}
|
|
287
|
-
/**
|
|
318
|
+
/** Fresh requests start a new generation; ordinary callers share current work. */
|
|
288
319
|
export async function getProcessSnapshotAsync(options = {}) {
|
|
320
|
+
if (options.fresh)
|
|
321
|
+
invalidateProcessSnapshot();
|
|
289
322
|
if (!options.fresh && snapshotCache && Date.now() - snapshotCache.at < SNAPSHOT_TTL_MS) {
|
|
290
323
|
return snapshotCache.snapshot;
|
|
291
324
|
}
|
|
@@ -294,7 +327,7 @@ export async function getProcessSnapshotAsync(options = {}) {
|
|
|
294
327
|
const generation = snapshotGeneration;
|
|
295
328
|
const query = (async () => {
|
|
296
329
|
const snapshot = isWindows
|
|
297
|
-
?
|
|
330
|
+
? await readWindowsSnapshotAsync()
|
|
298
331
|
?? { complete: false, startedAt: new Map(), commandLines: new Map() }
|
|
299
332
|
: readProcessSnapshot();
|
|
300
333
|
if (generation === snapshotGeneration)
|
|
@@ -329,7 +362,124 @@ function readProcessSnapshot() {
|
|
|
329
362
|
return { complete: false, startedAt: new Map(), commandLines: new Map() };
|
|
330
363
|
}
|
|
331
364
|
const WINDOWS_SNAPSHOT_SCRIPT = 'Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | ConvertTo-Json -Compress';
|
|
365
|
+
// Query the same WMI provider without loading PowerShell and its CIM module.
|
|
366
|
+
// ASCII JSON escapes preserve command lines regardless of the host code page.
|
|
367
|
+
const WINDOWS_WMI_SNAPSHOT_SCRIPT = String.raw `
|
|
368
|
+
function text(value) {
|
|
369
|
+
return '"' + String(value).replace(/[\\"\u0000-\u001f\u007f-\uffff]/g, function (ch) {
|
|
370
|
+
return '\\u' + ('0000' + ch.charCodeAt(0).toString(16)).slice(-4);
|
|
371
|
+
}) + '"';
|
|
372
|
+
}
|
|
373
|
+
var service = GetObject('winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2');
|
|
374
|
+
var query = 'SELECT ProcessId,CreationDate,CommandLine FROM Win32_Process';
|
|
375
|
+
if (WScript.Arguments.length) query += ' WHERE ProcessId=' + Number(WScript.Arguments(0));
|
|
376
|
+
var processes = new Enumerator(service.ExecQuery(query));
|
|
377
|
+
var rows = [];
|
|
378
|
+
for (; !processes.atEnd(); processes.moveNext()) {
|
|
379
|
+
var item = processes.item();
|
|
380
|
+
rows.push('{"ProcessId":' + Number(item.ProcessId)
|
|
381
|
+
+ ',"CreationDate":' + (item.CreationDate == null ? 'null' : text(item.CreationDate))
|
|
382
|
+
+ ',"CommandLine":' + (item.CommandLine == null ? 'null' : text(item.CommandLine)) + '}');
|
|
383
|
+
}
|
|
384
|
+
WScript.Echo('[' + rows.join(',') + ']');
|
|
385
|
+
`;
|
|
386
|
+
let windowsWmiScriptAvailable = true;
|
|
387
|
+
/** Prepare a private WMI script; callers must dispose it after the query. */
|
|
388
|
+
export function createWindowsProcessQuery(script, pid) {
|
|
389
|
+
if (!windowsWmiScriptAvailable)
|
|
390
|
+
return null;
|
|
391
|
+
let directory;
|
|
392
|
+
let file;
|
|
393
|
+
const dispose = () => {
|
|
394
|
+
// Remove only the two entries created here; never recursively remove a temp root.
|
|
395
|
+
if (file) {
|
|
396
|
+
try {
|
|
397
|
+
fs.unlinkSync(file);
|
|
398
|
+
}
|
|
399
|
+
catch { }
|
|
400
|
+
}
|
|
401
|
+
if (directory) {
|
|
402
|
+
try {
|
|
403
|
+
fs.rmdirSync(directory);
|
|
404
|
+
}
|
|
405
|
+
catch { }
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
try {
|
|
409
|
+
const command = path.join(process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows', 'System32', 'cscript.exe');
|
|
410
|
+
if (!fs.existsSync(command)) {
|
|
411
|
+
windowsWmiScriptAvailable = false;
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
directory = fs.mkdtempSync(path.join(os.tmpdir(), 'evolcore-process-snapshot-'));
|
|
415
|
+
file = path.join(directory, 'snapshot.js');
|
|
416
|
+
fs.writeFileSync(file, script, { flag: 'wx', mode: 0o600 });
|
|
417
|
+
return { command, args: ['//Nologo', '//E:JScript', file, ...(pid === undefined ? [] : [String(pid)])], dispose };
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
windowsWmiScriptAvailable = false;
|
|
421
|
+
dispose();
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
/** Query the same creation-time provider without starting PowerShell for every PID. */
|
|
426
|
+
async function readWindowsStartTimeAsync(pid) {
|
|
427
|
+
const query = createWindowsProcessQuery(WINDOWS_WMI_SNAPSHOT_SCRIPT, pid);
|
|
428
|
+
if (!query)
|
|
429
|
+
return null;
|
|
430
|
+
try {
|
|
431
|
+
return parseWindowsPidStartTime(await processQuery(query.command, query.args, 2000), pid);
|
|
432
|
+
}
|
|
433
|
+
finally {
|
|
434
|
+
query.dispose();
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
/** Both identity entry points accept only the exact requested PID. */
|
|
438
|
+
function parseWindowsPidStartTime(output, pid) {
|
|
439
|
+
const snapshot = parseWindowsSnapshot(output);
|
|
440
|
+
if (!snapshot || snapshot.pids?.size !== 1 || !snapshot.pids.has(pid)) {
|
|
441
|
+
// An empty selection can be an exited PID; unusable output keeps fallbacks.
|
|
442
|
+
if (!snapshot || snapshot.pids?.size)
|
|
443
|
+
windowsWmiScriptAvailable = false;
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
return snapshot.startedAt.get(pid) ?? null;
|
|
447
|
+
}
|
|
448
|
+
function parseWindowsWmiSnapshot(output) {
|
|
449
|
+
const snapshot = parseWindowsSnapshot(output);
|
|
450
|
+
// An empty/truncated successful response cannot prove that other PIDs exited.
|
|
451
|
+
if (snapshot?.pids?.has(process.pid))
|
|
452
|
+
return snapshot;
|
|
453
|
+
windowsWmiScriptAvailable = false;
|
|
454
|
+
return null;
|
|
455
|
+
}
|
|
456
|
+
async function readWindowsSnapshotAsync() {
|
|
457
|
+
const query = createWindowsProcessQuery(WINDOWS_WMI_SNAPSHOT_SCRIPT);
|
|
458
|
+
if (query) {
|
|
459
|
+
try {
|
|
460
|
+
const snapshot = parseWindowsWmiSnapshot(await processQuery(query.command, query.args, 2000));
|
|
461
|
+
if (snapshot)
|
|
462
|
+
return snapshot;
|
|
463
|
+
}
|
|
464
|
+
finally {
|
|
465
|
+
query.dispose();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return parseWindowsSnapshot(await processQuery('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], 8000));
|
|
469
|
+
}
|
|
332
470
|
function readWindowsSnapshot() {
|
|
471
|
+
const query = createWindowsProcessQuery(WINDOWS_WMI_SNAPSHOT_SCRIPT);
|
|
472
|
+
if (query) {
|
|
473
|
+
try {
|
|
474
|
+
const result = spawnSync(query.command, query.args, { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
|
|
475
|
+
const snapshot = parseWindowsWmiSnapshot(result.status === 0 ? result.stdout || '' : '');
|
|
476
|
+
if (snapshot)
|
|
477
|
+
return snapshot;
|
|
478
|
+
}
|
|
479
|
+
finally {
|
|
480
|
+
query.dispose();
|
|
481
|
+
}
|
|
482
|
+
}
|
|
333
483
|
const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_SNAPSHOT_SCRIPT], { encoding: 'utf-8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
|
|
334
484
|
return result.status === 0 ? parseWindowsSnapshot(result.stdout || '') : null;
|
|
335
485
|
}
|
|
@@ -2,7 +2,7 @@ import fs from 'fs';
|
|
|
2
2
|
import { spawnSync } from 'child_process';
|
|
3
3
|
import { performance } from 'node:perf_hooks';
|
|
4
4
|
import { isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
5
|
-
import { parseCimDate } from './process-introspect.js';
|
|
5
|
+
import { createWindowsProcessQuery, parseCimDate } from './process-introspect.js';
|
|
6
6
|
function runnerKind(name) {
|
|
7
7
|
const normalized = name.toLowerCase();
|
|
8
8
|
if (normalized.includes('codex'))
|
|
@@ -164,7 +164,52 @@ function readUnixPsMetrics() {
|
|
|
164
164
|
}
|
|
165
165
|
return metrics;
|
|
166
166
|
}
|
|
167
|
+
// Read the same counters as CIM without loading PowerShell on every sample.
|
|
168
|
+
// Escape non-ASCII names so cscript's console code page cannot corrupt JSON.
|
|
169
|
+
const WINDOWS_WMI_METRICS_SCRIPT = String.raw `
|
|
170
|
+
function text(value) {
|
|
171
|
+
return '"' + String(value).replace(/[\\"\u0000-\u001f\u007f-\uffff]/g, function (ch) {
|
|
172
|
+
return '\\u' + ('0000' + ch.charCodeAt(0).toString(16)).slice(-4);
|
|
173
|
+
}) + '"';
|
|
174
|
+
}
|
|
175
|
+
var service = GetObject('winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2');
|
|
176
|
+
var processes = new Enumerator(service.ExecQuery('SELECT ProcessId,ParentProcessId,Name,WorkingSetSize,KernelModeTime,UserModeTime,CreationDate FROM Win32_Process'));
|
|
177
|
+
var rows = [];
|
|
178
|
+
for (; !processes.atEnd(); processes.moveNext()) {
|
|
179
|
+
var item = processes.item();
|
|
180
|
+
rows.push('{"ProcessId":' + Number(item.ProcessId)
|
|
181
|
+
+ ',"ParentProcessId":' + Number(item.ParentProcessId)
|
|
182
|
+
+ ',"Name":' + text(item.Name)
|
|
183
|
+
+ ',"WorkingSetSize":' + text(item.WorkingSetSize)
|
|
184
|
+
+ ',"KernelModeTime":' + text(item.KernelModeTime)
|
|
185
|
+
+ ',"UserModeTime":' + text(item.UserModeTime)
|
|
186
|
+
+ ',"CreationDate":' + (item.CreationDate == null ? 'null' : text(item.CreationDate)) + '}');
|
|
187
|
+
}
|
|
188
|
+
WScript.Echo('[' + rows.join(',') + ']');
|
|
189
|
+
`;
|
|
190
|
+
let windowsWmiMetricsAvailable = true;
|
|
167
191
|
function readWindowsMetrics() {
|
|
192
|
+
const query = windowsWmiMetricsAvailable ? createWindowsProcessQuery(WINDOWS_WMI_METRICS_SCRIPT) : null;
|
|
193
|
+
if (query) {
|
|
194
|
+
try {
|
|
195
|
+
const result = spawnSync(query.command, query.args, {
|
|
196
|
+
encoding: 'utf8', timeout: 2000, windowsHide: true,
|
|
197
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
198
|
+
});
|
|
199
|
+
if (result.status === 0) {
|
|
200
|
+
const metrics = parseWindowsMetrics(result.stdout || '');
|
|
201
|
+
// Empty or incomplete output must not replace a working sample.
|
|
202
|
+
if (metrics.some(metric => metric.pid === process.pid && typeof metric.startId === 'number'))
|
|
203
|
+
return metrics;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
catch { /* Keep the CIM fallback for blocked or unavailable script hosts. */ }
|
|
207
|
+
finally {
|
|
208
|
+
query.dispose();
|
|
209
|
+
}
|
|
210
|
+
// Do not add a failed script-host timeout to every subsequent sample.
|
|
211
|
+
windowsWmiMetricsAvailable = false;
|
|
212
|
+
}
|
|
168
213
|
const command = [
|
|
169
214
|
'Get-CimInstance Win32_Process',
|
|
170
215
|
"Select-Object ProcessId,ParentProcessId,Name,WorkingSetSize,KernelModeTime,UserModeTime,@{Name='CreationDate';Expression={if ($_.CreationDate) {$_.CreationDate.ToUniversalTime().ToString('o')}}}",
|
|
@@ -178,8 +223,11 @@ function readWindowsMetrics() {
|
|
|
178
223
|
});
|
|
179
224
|
if (result.status !== 0 || !result.stdout?.trim())
|
|
180
225
|
return [];
|
|
226
|
+
return parseWindowsMetrics(result.stdout);
|
|
227
|
+
}
|
|
228
|
+
function parseWindowsMetrics(output) {
|
|
181
229
|
try {
|
|
182
|
-
const parsed = JSON.parse(
|
|
230
|
+
const parsed = JSON.parse(output.replace(/^\uFEFF/, ''));
|
|
183
231
|
const rows = Array.isArray(parsed) ? parsed : [parsed];
|
|
184
232
|
return rows.map((row) => ({
|
|
185
233
|
pid: Number(row.ProcessId),
|
|
@@ -7,7 +7,7 @@ import { AGENT_DELEGATION_TOKEN_ENV } from '../core/auth/agent-delegation.js';
|
|
|
7
7
|
import { atomicWriteJson, withFileLock } from './atomic-write.js';
|
|
8
8
|
import { comparePackageVersions, isLinkedInstall, preparePackageCache } from './npm-ops.js';
|
|
9
9
|
import { isProcessRunning, launchMonitorAndConfirm, resolveCliEntry } from './cross-platform.js';
|
|
10
|
-
import { scanInstances } from './instance-registry.js';
|
|
10
|
+
import { hasLiveRestartMonitor, scanInstances } from './instance-registry.js';
|
|
11
11
|
import { createRestartRequest, readRestartRequest, removeRestartRequest, shouldSuppressRealRestart, updateRestartRequest } from './restart-safety.js';
|
|
12
12
|
import { isPackageVersionInfoFresh, refreshManagedPackageVersions, resolveUpgradeDistTag, resolveVersionInfoPackage, VERSION_INFO_PACKAGES } from './package-version-info.js';
|
|
13
13
|
import { loadDaemonConfig } from '../config-store.js';
|
|
@@ -236,7 +236,7 @@ function jobs() {
|
|
|
236
236
|
}
|
|
237
237
|
/** Called under active.lock; never start another job during monitor handoff. */
|
|
238
238
|
function reconcileUpgradeJobs(existing) {
|
|
239
|
-
const monitors = scanInstances().restartMonitors.filter(item => item.alive);
|
|
239
|
+
const monitors = scanInstances({ kind: 'restart-monitor', includeAidActivity: false }).restartMonitors.filter(item => item.alive);
|
|
240
240
|
for (const job of existing.sort((left, right) => right.createdAt - left.createdAt)) {
|
|
241
241
|
const liveMonitor = !!job.monitorPid && isProcessRunning(job.monitorPid);
|
|
242
242
|
const liveLauncher = !!job.launcherPid && isProcessRunning(job.launcherPid);
|
|
@@ -283,7 +283,7 @@ export async function startUpgradeJob(requestId, scope, options = {}) {
|
|
|
283
283
|
const active = reconcileUpgradeJobs(existing);
|
|
284
284
|
if (active)
|
|
285
285
|
return { job: active, reused: true };
|
|
286
|
-
if (scanInstances().restartMonitors.some(item => item.alive)) {
|
|
286
|
+
if (scanInstances({ kind: 'restart-monitor', includeAidActivity: false }).restartMonitors.some(item => item.alive)) {
|
|
287
287
|
throw Object.assign(new Error('A restart transaction is still running'), { code: 'CONFLICT' });
|
|
288
288
|
}
|
|
289
289
|
const now = Date.now();
|
|
@@ -385,7 +385,7 @@ async function runUpgradeJob(job) {
|
|
|
385
385
|
}, () => false, {
|
|
386
386
|
requestId, timeoutMs: 8_000, logFilePath: path.join(resolvePaths().logs, `restart-launch-${requestId}.log`),
|
|
387
387
|
onSpawn: pid => { updateRestartRequest(pending, requestId, { launcherPid: pid }); updateUpgradeJob(job.jobId, { launcherPid: pid }); },
|
|
388
|
-
isPendingInRegistry: () =>
|
|
388
|
+
isPendingInRegistry: () => hasLiveRestartMonitor({ requestId }),
|
|
389
389
|
});
|
|
390
390
|
handedOff = launch.ok || launch.pending === true;
|
|
391
391
|
if (!handedOff) {
|
|
@@ -223,6 +223,8 @@ function fileAccessFailure(filePath, cause) {
|
|
|
223
223
|
}, cause);
|
|
224
224
|
}
|
|
225
225
|
function rememberSignature(key, stat, error) {
|
|
226
|
+
if (error && ['SIGNATURE_PROBE_TIMEOUT', 'POWERSHELL_START_FAILED', 'SIGNATURE_PROBE_FAILED'].includes(error.reason))
|
|
227
|
+
return;
|
|
226
228
|
signatureCache.set(key, { size: stat.size, mtimeMs: stat.mtimeMs, error });
|
|
227
229
|
while (signatureCache.size > MAX_CACHE_ENTRIES) {
|
|
228
230
|
const oldest = signatureCache.keys().next().value;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
export const WORKBENCH_EVENT = 'team.workbench.changed';
|
|
2
|
+
export const WORKBENCH_TYPES = ['snapshot', 'history', 'changes'].map(action => `services.workbench.${action}`);
|
|
3
|
+
export const WORKBENCH_MODULES = ['runtime', 'currentTasks', 'recentExecutions', 'history'];
|
|
4
|
+
export const isWorkbenchType = (type) => WORKBENCH_TYPES.includes(type);
|
|
5
|
+
export function workbenchRequestSchema(type) {
|
|
6
|
+
const action = type.split('.').at(-1);
|
|
7
|
+
const properties = { protocolVersion: { const: 1 } };
|
|
8
|
+
const required = ['protocolVersion'];
|
|
9
|
+
if (action === 'snapshot')
|
|
10
|
+
Object.assign(properties, {
|
|
11
|
+
limit: { type: 'integer', minimum: 1, maximum: 12 }, waitForIndex: { type: 'boolean' },
|
|
12
|
+
});
|
|
13
|
+
if (action === 'history')
|
|
14
|
+
Object.assign(properties, {
|
|
15
|
+
from: { type: 'integer', minimum: 0 }, to: { type: 'integer', minimum: 0 },
|
|
16
|
+
limit: { type: 'integer', minimum: 1, maximum: 20 }, pageCursor: { type: 'string', maxLength: 512 },
|
|
17
|
+
});
|
|
18
|
+
if (action === 'changes') {
|
|
19
|
+
properties.cursor = { type: 'string', maxLength: 128 };
|
|
20
|
+
required.push('cursor');
|
|
21
|
+
}
|
|
22
|
+
return { type: 'object', additionalProperties: false, required: ['type', 'request_id', 'data'], properties: {
|
|
23
|
+
type: { const: type }, request_id: { type: 'string', minLength: 1, maxLength: 128 },
|
|
24
|
+
data: { type: 'object', additionalProperties: false, required, properties },
|
|
25
|
+
} };
|
|
26
|
+
}
|
|
27
|
+
export function workbenchResponseSchema(type) {
|
|
28
|
+
const timestamp = { type: 'integer', minimum: 0 };
|
|
29
|
+
const state = { enum: ['starting', 'running', 'waiting', 'paused', 'interrupting', 'completed', 'interrupted', 'error', 'timeout', 'unknown'] };
|
|
30
|
+
const availability = { enum: ['ready', 'building', 'unsupported', 'unavailable'] };
|
|
31
|
+
const coverage = { enum: ['complete', 'partial', 'retained'] };
|
|
32
|
+
const task = { type: 'object', additionalProperties: false,
|
|
33
|
+
required: ['id', 'title', 'state', 'startedAt', 'updatedAt', 'detailAvailable'], properties: {
|
|
34
|
+
id: { type: 'string', maxLength: 256 }, title: { type: 'string', maxLength: 200 }, state,
|
|
35
|
+
startedAt: timestamp, updatedAt: timestamp, completedAt: timestamp,
|
|
36
|
+
detailAvailable: { type: 'boolean' }, threadId: { type: 'string', maxLength: 512 },
|
|
37
|
+
} };
|
|
38
|
+
const historyEntry = { type: 'object', additionalProperties: false,
|
|
39
|
+
required: ['id', 'taskId', 'title', 'state', 'at', 'detailAvailable'], properties: {
|
|
40
|
+
id: { type: 'string', maxLength: 256 }, taskId: { type: 'string', maxLength: 256 },
|
|
41
|
+
title: { type: 'string', maxLength: 200 }, state, at: timestamp,
|
|
42
|
+
detailAvailable: { type: 'boolean' }, threadId: { type: 'string', maxLength: 512 },
|
|
43
|
+
} };
|
|
44
|
+
const taskModule = { type: 'object', additionalProperties: false,
|
|
45
|
+
required: ['availability', 'coverage', 'items', 'truncated'], properties: {
|
|
46
|
+
availability, coverage, items: { type: 'array', maxItems: 12, items: task }, truncated: { type: 'boolean' },
|
|
47
|
+
} };
|
|
48
|
+
const properties = {
|
|
49
|
+
protocol: { const: 'evol.workbench' }, protocolVersion: { const: 1 },
|
|
50
|
+
sourceAid: { type: 'string', minLength: 3, maxLength: 256 }, generatedAt: timestamp,
|
|
51
|
+
revision: { type: 'string', pattern: '^[a-f0-9]{24}$' },
|
|
52
|
+
cursor: { type: 'string', pattern: '^[a-f0-9]{24}\\.\\d+$', maxLength: 128 },
|
|
53
|
+
notifications: { anyOf: [{ type: 'null' }, { type: 'object', additionalProperties: false,
|
|
54
|
+
required: ['busAid', 'event'], properties: { busAid: { type: 'string' }, event: { const: WORKBENCH_EVENT } } }] },
|
|
55
|
+
};
|
|
56
|
+
const required = Object.keys(properties);
|
|
57
|
+
if (type.endsWith('.changes')) {
|
|
58
|
+
properties.changedModules = { type: 'array', uniqueItems: true, maxItems: 4, items: { enum: WORKBENCH_MODULES } };
|
|
59
|
+
properties.reset = { type: 'boolean' };
|
|
60
|
+
required.push('changedModules', 'reset');
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
properties.modules = { type: 'object', additionalProperties: false, required: WORKBENCH_MODULES, properties: {
|
|
64
|
+
runtime: { type: 'object', additionalProperties: false,
|
|
65
|
+
required: ['availability', 'coverage', 'status', 'workState', 'activeTaskCount'], properties: {
|
|
66
|
+
availability, coverage, status: { enum: ['running', 'stopped', 'disabled', 'error', 'unknown'] },
|
|
67
|
+
workState: { enum: ['working', 'idle', 'unknown'] }, activeTaskCount: { type: 'integer', minimum: 0 },
|
|
68
|
+
} },
|
|
69
|
+
currentTasks: taskModule, recentExecutions: taskModule,
|
|
70
|
+
history: { type: 'object', additionalProperties: false,
|
|
71
|
+
required: ['availability', 'coverage', 'items', 'nextCursor', 'from', 'to', 'oldestRetainedAt', 'truncated'], properties: {
|
|
72
|
+
availability, coverage, items: { type: 'array', maxItems: 20, items: historyEntry },
|
|
73
|
+
nextCursor: { anyOf: [{ type: 'null' }, { type: 'string', maxLength: 512 }] },
|
|
74
|
+
from: timestamp, to: timestamp, oldestRetainedAt: { anyOf: [{ type: 'null' }, timestamp] }, truncated: { type: 'boolean' },
|
|
75
|
+
} },
|
|
76
|
+
} };
|
|
77
|
+
required.push('modules');
|
|
78
|
+
}
|
|
79
|
+
return { type: 'object', additionalProperties: false, required, properties };
|
|
80
|
+
}
|