evolcore 0.0.47 → 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 +56 -1
- 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 +34 -17
- 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/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +81 -24
- package/dist/channels/daemon.js +9 -25
- 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 +44 -43
- 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 +4 -6
- package/dist/cli/init.js +72 -50
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/role.js +61 -17
- package/dist/cli/stats.js +3 -3
- package/dist/cli/thread-command.js +16 -51
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-manager.js +2 -6
- 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 +62 -229
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +4 -1
- 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 +105 -4
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +4 -0
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +3 -0
- package/dist/core/auth/operation-authorizer.js +25 -0
- 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 +61 -149
- 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 +26 -43
- 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 +8 -1
- package/dist/core/daemon-control.js +7 -7
- package/dist/core/evolagent-registry.js +14 -1
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +11 -6
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +2 -1
- 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 +328 -50
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/relation/peer-identity.js +23 -1
- package/dist/core/relation/same-owner-proof.js +81 -112
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +13 -7
- 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-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 +18 -8
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +4 -2
- 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 +92 -59
- package/dist/ipc.js +13 -2
- 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 +7 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +9 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/cross-platform.js +73 -26
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +27 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/process-introspect.js +12 -7
- package/dist/utils/process-tree.js +50 -2
- 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/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 +123 -3
- 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
|
@@ -4,7 +4,7 @@ import { trustedExecutionIdentityInput } from '../core/auth/agent-delegation.js'
|
|
|
4
4
|
import { authorizeOperation, buildAuthSubject } from '../core/auth/auth-gateway.js';
|
|
5
5
|
import { ownerResolver, refreshOwnershipForAuthorization } from '../core/ownership/owner-resolver.js';
|
|
6
6
|
import { isManagementRole } from '../config/builtin-roles.js';
|
|
7
|
-
import { checkRoleAccess,
|
|
7
|
+
import { checkRoleAccess, resolveFreshPeerRoleDetail, roleToSessionIdentity, authorizationConfigRevision } from '../config/peer-role-resolver.js';
|
|
8
8
|
import { validateModelSelectionForRole } from '../core/model/model-permission.js';
|
|
9
9
|
import { isValidAunDeliveryForChannel } from '../core/message/outbound.js';
|
|
10
10
|
import { sessionTopicThreadId } from '../core/thread/topic-id.js';
|
|
@@ -18,10 +18,10 @@ export function originFromActorSession(session, authenticatedPeerId, authenticat
|
|
|
18
18
|
const sessionChannelKey = session.metadata?.channelKey || session.channel;
|
|
19
19
|
const channelKey = authenticatedChannelKey || sessionChannelKey;
|
|
20
20
|
const sameConversation = channelKey === sessionChannelKey;
|
|
21
|
-
if (authenticatedChatType && (authenticatedChatType === 'group') !== (session.chatType === 'group')) {
|
|
21
|
+
if (sameConversation && authenticatedChatType && (authenticatedChatType === 'group') !== (session.chatType === 'group')) {
|
|
22
22
|
return undefined;
|
|
23
23
|
}
|
|
24
|
-
const isGroup = authenticatedChatType === 'group'
|
|
24
|
+
const isGroup = authenticatedChatType ? authenticatedChatType === 'group' : session.chatType === 'group';
|
|
25
25
|
const channelId = isGroup ? session.channelId : peerId;
|
|
26
26
|
// 只有话题会让 origin 变成 `thread`;主话题(含 `main:<a>:<b>` 规范 id)
|
|
27
27
|
// 在 Trigger 里仍用 `session: 'main'` 表达,主话题 id 不写进 origin.threadId。
|
|
@@ -29,7 +29,8 @@ export function originFromActorSession(session, authenticatedPeerId, authenticat
|
|
|
29
29
|
const sessionKind = topicThreadId ? 'thread' : 'main';
|
|
30
30
|
return {
|
|
31
31
|
channelKey,
|
|
32
|
-
channelType: session.channelType
|
|
32
|
+
channelType: (sameConversation ? session.channelType : undefined)
|
|
33
|
+
|| tryParseChannelKey(channelKey)?.type || channelKey,
|
|
33
34
|
channelId,
|
|
34
35
|
session: sessionKind,
|
|
35
36
|
threadId: topicThreadId,
|
|
@@ -38,6 +39,64 @@ export function originFromActorSession(session, authenticatedPeerId, authenticat
|
|
|
38
39
|
delivery: isGroup ? { chatType: 'group', groupId: channelId } : { chatType: 'private' },
|
|
39
40
|
};
|
|
40
41
|
}
|
|
42
|
+
const executionContexts = new WeakMap();
|
|
43
|
+
/** Only internal delivery code may bind execution authority; wire metadata cannot grant it. */
|
|
44
|
+
export async function bindTriggerExecutionIdentity(message, definition, identity) {
|
|
45
|
+
const current = identity ?? await resolveTriggerExecutionIdentity(definition);
|
|
46
|
+
if (!message.triggerMeta)
|
|
47
|
+
throw new Error('Trigger execution metadata is missing');
|
|
48
|
+
if (current.selfAid !== definition.agentAid)
|
|
49
|
+
throw new Error('Trigger identity belongs to another Agent');
|
|
50
|
+
const snapshot = JSON.parse(JSON.stringify(definition));
|
|
51
|
+
if (current.control && snapshot.origin?.channelKey !== 'daemon')
|
|
52
|
+
throw new Error('Trigger control identity mismatch');
|
|
53
|
+
executionContexts.set(message.triggerMeta, { definition: snapshot, identity: current,
|
|
54
|
+
runId: message.triggerMeta?.runId, attemptId: message.triggerMeta?.attemptId });
|
|
55
|
+
}
|
|
56
|
+
export async function currentTriggerExecutionIdentity(message, selfAid) {
|
|
57
|
+
const context = message.triggerMeta ? executionContexts.get(message.triggerMeta) : undefined;
|
|
58
|
+
if (!context || context.identity.selfAid !== selfAid || context.definition.id !== message.triggerMeta?.triggerId
|
|
59
|
+
|| context.runId !== message.triggerMeta?.runId || context.attemptId !== message.triggerMeta?.attemptId)
|
|
60
|
+
return undefined;
|
|
61
|
+
if (!context.identity.control && context.identity.revision !== authorizationConfigRevision(selfAid)) {
|
|
62
|
+
context.identity = await resolveTriggerExecutionIdentity(context.definition);
|
|
63
|
+
}
|
|
64
|
+
return context.identity;
|
|
65
|
+
}
|
|
66
|
+
export async function resolveTriggerExecutionIdentity(definition) {
|
|
67
|
+
const origin = definition.origin;
|
|
68
|
+
if (!origin?.peerId)
|
|
69
|
+
throw new Error('Trigger creator identity is missing');
|
|
70
|
+
const channelType = origin.channelType || tryParseChannelKey(origin.channelKey)?.type || origin.channelKey;
|
|
71
|
+
const chatType = origin.delivery?.chatType ?? 'private';
|
|
72
|
+
const conversationId = chatType === 'group' ? origin.channelId : origin.peerId;
|
|
73
|
+
const control = origin.channelKey === 'daemon' && channelType === 'daemon';
|
|
74
|
+
if (control)
|
|
75
|
+
return { selfAid: definition.agentAid, actorId: origin.peerId, role: 'none', channelType,
|
|
76
|
+
originChannelKey: origin.channelKey, conversationId, peerKey: `daemon#${encodeURIComponent(conversationId)}`,
|
|
77
|
+
control: true, revision: '', actor: { operatorId: origin.peerId, operatorChannelKey: origin.channelKey,
|
|
78
|
+
operatorChannelType: channelType, principalStatus: 'unmapped' }, rolePolicy: '' };
|
|
79
|
+
const detail = await resolveFreshPeerRoleDetail({ selfAid: definition.agentAid,
|
|
80
|
+
channelKey: origin.channelKey, channelType, chatType, actorId: origin.peerId, conversationId });
|
|
81
|
+
const creator = definition.creator;
|
|
82
|
+
if (creator && ['error', 'conflict'].includes(creator.actor.principalStatus)) {
|
|
83
|
+
throw Object.assign(new Error('Trigger creator principal could not be verified at creation'), { retryable: false });
|
|
84
|
+
}
|
|
85
|
+
if (creator && (creator.actor.operatorId !== origin.peerId || creator.actor.operatorChannelKey !== origin.channelKey
|
|
86
|
+
|| creator.actor.operatorChannelType !== channelType || creator.chatType !== chatType
|
|
87
|
+
|| creator.conversationId !== conversationId || creator.actor.principalId !== detail.actor.principalId
|
|
88
|
+
|| creator.actor.principalStatus !== detail.actor.principalStatus)) {
|
|
89
|
+
throw Object.assign(new Error('Trigger creator identity has changed'), { retryable: false });
|
|
90
|
+
}
|
|
91
|
+
if (detail.authorizationFailure) {
|
|
92
|
+
throw Object.assign(new Error(detail.authorizationFailure.reason), { retryable: detail.authorizationFailure.retryable });
|
|
93
|
+
}
|
|
94
|
+
return { selfAid: definition.agentAid, actor: detail.actor, actorId: origin.peerId,
|
|
95
|
+
role: control ? 'none' : detail.effectiveRole ?? 'none', channelType, originChannelKey: origin.channelKey,
|
|
96
|
+
conversationId, peerKey: `${channelType}#${encodeURIComponent(conversationId)}`, control,
|
|
97
|
+
revision: authorizationConfigRevision(definition.agentAid),
|
|
98
|
+
rolePolicy: JSON.stringify((await import('../config/roles.js')).getRoleDefinition(detail.effectiveRole ?? '', definition.agentAid)) };
|
|
99
|
+
}
|
|
41
100
|
export function daemonPrivilegedTriggerReason(definition) {
|
|
42
101
|
if (definition.origin?.channelKey === 'daemon' || definition.origin?.channelType === 'daemon') {
|
|
43
102
|
return 'daemon/control-origin Trigger';
|
|
@@ -226,9 +285,13 @@ export async function authorizeTriggerExecution(definition, dependencies) {
|
|
|
226
285
|
});
|
|
227
286
|
const originType = origin.channelType || tryParseChannelKey(origin.channelKey)?.type;
|
|
228
287
|
const requiresDaemonOwner = definition.execution.permissionMode === 'fullaccess';
|
|
229
|
-
|
|
230
|
-
&& (requiresDaemonOwner ? view.subjectAid === ownerResolver.getDaemonAid() : originType === 'aun'))
|
|
231
|
-
|
|
288
|
+
const unavailableOwnership = ownership.find(view => view.consensusStatus === 'unavailable'
|
|
289
|
+
&& (requiresDaemonOwner ? view.subjectAid === ownerResolver.getDaemonAid() : originType === 'aun'));
|
|
290
|
+
if (unavailableOwnership) {
|
|
291
|
+
return {
|
|
292
|
+
allowed: false, retryable: unavailableOwnership.refreshFailure?.kind !== 'permanent',
|
|
293
|
+
reason: unavailableOwnership.refreshFailure?.reason ?? 'Ownership authorization evidence is temporarily unavailable',
|
|
294
|
+
};
|
|
232
295
|
}
|
|
233
296
|
if (definition.execution.permissionMode === 'fullaccess') {
|
|
234
297
|
if (!definition.authorizedBy) {
|
|
@@ -240,7 +303,14 @@ export async function authorizeTriggerExecution(definition, dependencies) {
|
|
|
240
303
|
}
|
|
241
304
|
}
|
|
242
305
|
if (definition.execution.permissionMode === 'fullaccess') {
|
|
243
|
-
|
|
306
|
+
try {
|
|
307
|
+
return { allowed: true, scope: 'daemon', permissionMode: 'fullaccess',
|
|
308
|
+
identity: await resolveTriggerExecutionIdentity(definition) };
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
return { allowed: false, retryable: error.retryable === true,
|
|
312
|
+
reason: error instanceof Error ? error.message : String(error) };
|
|
313
|
+
}
|
|
244
314
|
}
|
|
245
315
|
if (origin.channelKey === 'daemon') {
|
|
246
316
|
const subject = buildAuthSubject({
|
|
@@ -269,6 +339,7 @@ export async function authorizeTriggerExecution(definition, dependencies) {
|
|
|
269
339
|
allowed: true,
|
|
270
340
|
scope: 'daemon',
|
|
271
341
|
permissionMode: definition.execution.permissionMode ?? 'bypass',
|
|
342
|
+
identity: await resolveTriggerExecutionIdentity(definition),
|
|
272
343
|
}
|
|
273
344
|
: { allowed: false, reason: decision.reason };
|
|
274
345
|
}
|
|
@@ -277,7 +348,7 @@ export async function authorizeTriggerExecution(definition, dependencies) {
|
|
|
277
348
|
return { allowed: false, reason: 'trigger origin channel type is missing' };
|
|
278
349
|
const chatType = triggerOriginChatType(origin);
|
|
279
350
|
const conversationId = chatType === 'group' ? origin.channelId : origin.peerId;
|
|
280
|
-
const roleDetail =
|
|
351
|
+
const roleDetail = await resolveFreshPeerRoleDetail({
|
|
281
352
|
selfAid: definition.agentAid,
|
|
282
353
|
channelKey: origin.channelKey,
|
|
283
354
|
channelType,
|
|
@@ -287,8 +358,18 @@ export async function authorizeTriggerExecution(definition, dependencies) {
|
|
|
287
358
|
});
|
|
288
359
|
const role = roleDetail.effectiveRole;
|
|
289
360
|
if (!checkRoleAccess(role, definition.agentAid)) {
|
|
361
|
+
if (roleDetail.authorizationFailure)
|
|
362
|
+
return { allowed: false, ...roleDetail.authorizationFailure };
|
|
290
363
|
return { allowed: false, reason: `trigger creator no longer has access (role=${role ?? 'none'})` };
|
|
291
364
|
}
|
|
365
|
+
let identity;
|
|
366
|
+
try {
|
|
367
|
+
identity = await resolveTriggerExecutionIdentity(definition);
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
return { allowed: false, retryable: error.retryable === true,
|
|
371
|
+
reason: error instanceof Error ? error.message : String(error) };
|
|
372
|
+
}
|
|
292
373
|
const subject = buildAuthSubject({
|
|
293
374
|
selfAid: definition.agentAid,
|
|
294
375
|
actorId: origin.peerId,
|
|
@@ -346,6 +427,7 @@ export async function authorizeTriggerExecution(definition, dependencies) {
|
|
|
346
427
|
scope: privilegedReason && hasDaemonTriggerAuthority(subject) ? 'daemon' : 'agent',
|
|
347
428
|
permissionMode: permissionDecision.effectiveValue,
|
|
348
429
|
role: role ?? undefined,
|
|
430
|
+
identity,
|
|
349
431
|
};
|
|
350
432
|
}
|
|
351
433
|
export async function authenticatedTriggerActor(dependencies, agentAid, actorSessionId, delegationToken, delegationCommandHash, controlToken, contextOnly = false) {
|
|
@@ -398,6 +480,15 @@ export async function authenticatedTriggerActor(dependencies, agentAid, actorSes
|
|
|
398
480
|
export async function authenticatedTriggerActorFromGrant(dependencies, agentAid, grant) {
|
|
399
481
|
const actorSession = await dependencies.sessionManager.getSessionById(grant.sessionId);
|
|
400
482
|
const actorOrigin = actorSession ? originFromActorSession(actorSession, grant.actorId, grant.channel, grant.chatType) : undefined;
|
|
483
|
+
// A Trigger may execute in a daemon or recipient session while its grant remains bound to the creator.
|
|
484
|
+
if (actorOrigin && actorSession && grant.channel !== (actorSession.metadata?.channelKey || actorSession.channel)) {
|
|
485
|
+
actorOrigin.channelType = grant.channelType;
|
|
486
|
+
const { parsePeerKey } = await import('../core/relation/peer-identity.js');
|
|
487
|
+
const conversationId = parsePeerKey(grant.peerKey).channelId;
|
|
488
|
+
actorOrigin.channelId = conversationId;
|
|
489
|
+
actorOrigin.delivery = grant.chatType === 'group'
|
|
490
|
+
? { chatType: 'group', groupId: conversationId } : { chatType: 'private' };
|
|
491
|
+
}
|
|
401
492
|
if (!actorSession || !actorOrigin?.peerId)
|
|
402
493
|
throw new Error('trigger actor session has no authenticated peer');
|
|
403
494
|
if (grant.actorId !== actorOrigin.peerId) {
|
|
@@ -406,7 +497,7 @@ export async function authenticatedTriggerActorFromGrant(dependencies, agentAid,
|
|
|
406
497
|
const actorChatType = triggerOriginChatType(actorOrigin);
|
|
407
498
|
await refreshOwnershipForAuthorization(agentAid, { allowTransient: true, includeDaemon: true });
|
|
408
499
|
const actorConversationId = actorChatType === 'group' ? actorOrigin.channelId : actorOrigin.peerId;
|
|
409
|
-
const roleDetail =
|
|
500
|
+
const roleDetail = await resolveFreshPeerRoleDetail({
|
|
410
501
|
selfAid: agentAid,
|
|
411
502
|
channelKey: grant.channel,
|
|
412
503
|
channelType: grant.channelType,
|
|
@@ -433,7 +524,10 @@ export async function authenticatedTriggerActorFromGrant(dependencies, agentAid,
|
|
|
433
524
|
throw new Error('cross-agent Trigger operations require DaemonOwner');
|
|
434
525
|
}
|
|
435
526
|
if (subject.dataScope !== 'daemon' && !checkRoleAccess(currentRole, agentAid)) {
|
|
436
|
-
throw new Error(
|
|
527
|
+
throw Object.assign(new Error(roleDetail.authorizationFailure?.reason
|
|
528
|
+
?? 'trigger actor no longer has access to this agent'), {
|
|
529
|
+
retryable: roleDetail.authorizationFailure?.retryable === true,
|
|
530
|
+
});
|
|
437
531
|
}
|
|
438
532
|
const permissionDecision = subject.processRole === 'fullaccess-run'
|
|
439
533
|
? { effectiveValue: 'fullaccess' }
|
package/dist/trigger/feedback.js
CHANGED
|
@@ -5,6 +5,7 @@ import { TASK_RECOVERY_PROMPT } from '../core/task/task-recovery-service.js';
|
|
|
5
5
|
import { ExecutionTimeoutError, OrphanedTargetSessionError, isRetryableError } from '../utils/error-utils.js';
|
|
6
6
|
import { isTopicThreadId, sessionThreadKind, sessionTopicThreadId } from '../core/thread/topic-id.js';
|
|
7
7
|
import { readSessionLoopOnceConfig, resolveSessionLoopTarget } from '../core/session/session-idle-monitor.js';
|
|
8
|
+
import { bindTriggerExecutionIdentity } from './authorization.js';
|
|
8
9
|
const FEEDBACK_DEADLINE_MS = 30_000;
|
|
9
10
|
const TARGET_SESSION_CANCEL_GRACE_MS = 1_000;
|
|
10
11
|
const TARGET_SESSION_OUTCOME_GRACE_MS = 5_000;
|
|
@@ -308,6 +309,15 @@ export class TriggerFeedbackDispatcher {
|
|
|
308
309
|
: {}),
|
|
309
310
|
},
|
|
310
311
|
};
|
|
312
|
+
if (!eventSession)
|
|
313
|
+
await bindTriggerExecutionIdentity(message, input.trigger, input.executionIdentity);
|
|
314
|
+
else {
|
|
315
|
+
// These sources are produced in-process from the exact, verified original session.
|
|
316
|
+
await bindTriggerExecutionIdentity(message, { ...input.trigger, agentAid: targetAgentAid, creator: undefined,
|
|
317
|
+
origin: { channelKey: target.channelKey, channelType, channelId: target.channelId,
|
|
318
|
+
peerId: message.triggerMeta.originPeerId, session: target.session,
|
|
319
|
+
delivery: targetDelivery } });
|
|
320
|
+
}
|
|
311
321
|
outcome = this.waitForTriggerOutcome(input.runId, input.attemptId, delivery.signal);
|
|
312
322
|
let missingSince;
|
|
313
323
|
let observedTaskId;
|
package/dist/trigger/history.js
CHANGED
|
@@ -258,23 +258,43 @@ export class TriggerHistoryStore {
|
|
|
258
258
|
return latest;
|
|
259
259
|
}
|
|
260
260
|
stats(triggerId) {
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
261
|
+
return this.readRunSummaries([triggerId], false).get(triggerId).stats;
|
|
262
|
+
}
|
|
263
|
+
/** One fresh scan for a list response; delivery state is still resolved at read time. */
|
|
264
|
+
summaries(triggerIds) {
|
|
265
|
+
return this.readRunSummaries(triggerIds, true);
|
|
266
|
+
}
|
|
267
|
+
readRunSummaries(triggerIds, includeLatest) {
|
|
268
|
+
const summaries = new Map([...new Set(triggerIds)].map(id => [id, {
|
|
269
|
+
legacy: { fireCount: 0, failCount: 0 },
|
|
270
|
+
current: { fireCount: 0, failCount: 0 },
|
|
271
|
+
legacyMatched: false,
|
|
272
|
+
latestFinishedAt: -1,
|
|
273
|
+
latestRun: undefined,
|
|
274
|
+
}]));
|
|
275
|
+
if (!summaries.size)
|
|
276
|
+
return new Map();
|
|
265
277
|
for (const line of this.readLines()) {
|
|
266
278
|
const event = parseHistoryEvent(line, this.agentAid);
|
|
267
|
-
|
|
279
|
+
const summary = event && summaries.get(event.triggerId);
|
|
280
|
+
if (!event || !summary)
|
|
281
|
+
continue;
|
|
282
|
+
// latestRuns historically follows append order, including legacy foreign
|
|
283
|
+
// records. Statistics and archive flags remain scoped to this Agent.
|
|
284
|
+
if (includeLatest && isRunEvent(event))
|
|
285
|
+
summary.latestRun = event.audit;
|
|
286
|
+
if (event.agentAid !== this.agentAid)
|
|
268
287
|
continue;
|
|
288
|
+
const { legacy, current } = summary;
|
|
269
289
|
if (isLegacyEvent(event)) {
|
|
270
|
-
legacyMatched = true;
|
|
290
|
+
summary.legacyMatched = true;
|
|
271
291
|
const fireCount = nonNegativeInteger(event.legacyRecord.fireCount);
|
|
272
292
|
const failCount = nonNegativeInteger(event.legacyRecord.failCount);
|
|
273
293
|
legacy.fireCount = Math.max(legacy.fireCount, fireCount ?? 0);
|
|
274
294
|
legacy.failCount = Math.max(legacy.failCount, failCount ?? 0);
|
|
275
295
|
const lastFiredAt = finiteNumber(event.legacyRecord.lastFiredAt);
|
|
276
|
-
if (lastFiredAt !== undefined && lastFiredAt > latestFinishedAt) {
|
|
277
|
-
latestFinishedAt = lastFiredAt;
|
|
296
|
+
if (lastFiredAt !== undefined && lastFiredAt > summary.latestFinishedAt) {
|
|
297
|
+
summary.latestFinishedAt = lastFiredAt;
|
|
278
298
|
legacy.lastFiredAt = lastFiredAt;
|
|
279
299
|
legacy.lastResult = event.legacyRecord.lastResult === 'failed' ? 'failed' : 'completed';
|
|
280
300
|
}
|
|
@@ -283,6 +303,8 @@ export class TriggerHistoryStore {
|
|
|
283
303
|
if (!isRunEvent(event))
|
|
284
304
|
continue;
|
|
285
305
|
const record = hydrateTriggerAudit(event.audit);
|
|
306
|
+
if (includeLatest)
|
|
307
|
+
summary.latestRun = record;
|
|
286
308
|
if (record.status !== 'completed'
|
|
287
309
|
&& record.status !== 'degraded'
|
|
288
310
|
&& record.status !== 'noop'
|
|
@@ -292,13 +314,17 @@ export class TriggerHistoryStore {
|
|
|
292
314
|
current.fireCount += 1;
|
|
293
315
|
if (record.status === 'failed')
|
|
294
316
|
current.failCount += 1;
|
|
295
|
-
if (record.finishedAt > latestFinishedAt) {
|
|
296
|
-
latestFinishedAt = record.finishedAt;
|
|
317
|
+
if (record.finishedAt > summary.latestFinishedAt) {
|
|
318
|
+
summary.latestFinishedAt = record.finishedAt;
|
|
297
319
|
current.lastFiredAt = record.finishedAt;
|
|
298
320
|
current.lastResult = record.status === 'failed' ? 'failed' : record.status === 'interrupted' ? 'interrupted' : 'completed';
|
|
299
321
|
}
|
|
300
322
|
}
|
|
301
|
-
return
|
|
323
|
+
return new Map([...summaries].map(([id, summary]) => [id, {
|
|
324
|
+
...(summary.latestRun ? { latestRun: hydrateTriggerAudit(summary.latestRun) } : {}),
|
|
325
|
+
stats: this.mergeRunStats(summary.legacyMatched ? summary.legacy : undefined, summary.current),
|
|
326
|
+
hasLegacyArchive: summary.legacyMatched,
|
|
327
|
+
}]));
|
|
302
328
|
}
|
|
303
329
|
hasSkippedSchedule(triggerId, scheduledAt) {
|
|
304
330
|
for (const line of this.readLines()) {
|
|
@@ -114,7 +114,18 @@ export function prepareTriggerCreateDefinition(rawDefinition, agentAid, actor, d
|
|
|
114
114
|
feedback: rawDefinition.feedback,
|
|
115
115
|
operatorPeers: undefined,
|
|
116
116
|
});
|
|
117
|
-
const materialized = validateTriggerCreateBaseagent({ ...rawDefinition, origin: actor.origin, operatorPeers
|
|
117
|
+
const materialized = validateTriggerCreateBaseagent({ ...rawDefinition, origin: actor.origin, operatorPeers, creator: actor.control ? undefined : {
|
|
118
|
+
actor: {
|
|
119
|
+
operatorId: actor.subject.actorId ?? actor.origin.peerId,
|
|
120
|
+
operatorChannelKey: actor.subject.channel ?? actor.origin.channelKey,
|
|
121
|
+
operatorChannelType: actor.subject.channelType ?? actor.origin.channelType,
|
|
122
|
+
principalId: actor.subject.principalId,
|
|
123
|
+
principalStatus: (actor.subject.channelType ?? actor.origin.channelType) === 'aun' ? 'native_aid'
|
|
124
|
+
: actor.subject.principalId ? 'mapped' : 'unmapped',
|
|
125
|
+
},
|
|
126
|
+
chatType: actor.subject.chatType ?? actor.origin.delivery?.chatType ?? 'private',
|
|
127
|
+
conversationId: actor.subject.conversationId ?? actor.origin.channelId,
|
|
128
|
+
} }, agentAid, dependencies);
|
|
118
129
|
let definition = normalizeTriggerDefinition(materialized);
|
|
119
130
|
if (definition.labels?.kind === 'cross-thread-review') {
|
|
120
131
|
definition.labels = { ...definition.labels, originAuthorization: 'creator-session-v1' };
|
package/dist/trigger/manager.js
CHANGED
|
@@ -95,6 +95,7 @@ export class TriggerDefinitionManager {
|
|
|
95
95
|
const origin = mergeOrigin(existing.origin, rawInput.origin);
|
|
96
96
|
const updated = normalizeTriggerDefinition({
|
|
97
97
|
...rawInput,
|
|
98
|
+
creator: existing.creator,
|
|
98
99
|
id: triggerId,
|
|
99
100
|
...(origin ? { origin } : {}),
|
|
100
101
|
}, { now: Date.now() });
|
|
@@ -170,8 +170,8 @@ export class TriggerRuntimeScheduler {
|
|
|
170
170
|
return this.manager.list(opts);
|
|
171
171
|
}
|
|
172
172
|
listItems(definitions) {
|
|
173
|
-
const
|
|
174
|
-
return definitions.map(definition => this.buildListItem(definition,
|
|
173
|
+
const summaries = this.audit.summaries(definitions.map(definition => definition.id));
|
|
174
|
+
return definitions.map(definition => this.buildListItem(definition, summaries.get(definition.id)?.latestRun, this.stats(definition.id, summaries.get(definition.id))));
|
|
175
175
|
}
|
|
176
176
|
listItem(definition) {
|
|
177
177
|
return this.buildListItem(definition, this.audit.recent(definition.id, 1)[0], this.stats(definition.id));
|
|
@@ -272,9 +272,9 @@ export class TriggerRuntimeScheduler {
|
|
|
272
272
|
return { ...preview, error: err?.message || String(err) };
|
|
273
273
|
}
|
|
274
274
|
}
|
|
275
|
-
stats(triggerId) {
|
|
276
|
-
const historyStats = this.audit.stats(triggerId);
|
|
277
|
-
const merged = this.manager.history.hasLegacyArchive(triggerId)
|
|
275
|
+
stats(triggerId, summary) {
|
|
276
|
+
const historyStats = summary?.stats ?? this.audit.stats(triggerId);
|
|
277
|
+
const merged = (summary?.hasLegacyArchive ?? this.manager.history.hasLegacyArchive(triggerId))
|
|
278
278
|
? historyStats
|
|
279
279
|
: mergeStats(this.manager.legacyStats(triggerId), historyStats);
|
|
280
280
|
const schedule = this.state.readSchedule(triggerId);
|
|
@@ -1045,6 +1045,7 @@ export class TriggerRuntimeScheduler {
|
|
|
1045
1045
|
if (definition.execution.type === 'target_session') {
|
|
1046
1046
|
const feedbackResult = await this.feedback.dispatchTargetSession({
|
|
1047
1047
|
trigger: definition,
|
|
1048
|
+
executionIdentity: executionAuthorization?.identity,
|
|
1048
1049
|
runId,
|
|
1049
1050
|
attemptId: `${runId}:attempt:${attempt}`,
|
|
1050
1051
|
firedAt,
|
|
@@ -1121,6 +1122,7 @@ export class TriggerRuntimeScheduler {
|
|
|
1121
1122
|
});
|
|
1122
1123
|
const daemonReply = await this.daemonChannel.converse(prompt, {
|
|
1123
1124
|
trigger: definition,
|
|
1125
|
+
executionIdentity: executionAuthorization?.identity,
|
|
1124
1126
|
runId,
|
|
1125
1127
|
attemptId,
|
|
1126
1128
|
firedAt,
|
|
@@ -45,13 +45,14 @@ export class TriggerScriptExecutor {
|
|
|
45
45
|
};
|
|
46
46
|
let launch;
|
|
47
47
|
try {
|
|
48
|
-
launch = buildTriggerScriptLaunch({
|
|
48
|
+
launch = await buildTriggerScriptLaunch({
|
|
49
49
|
trigger: input.trigger,
|
|
50
50
|
triggerDir: input.triggerDir,
|
|
51
51
|
scriptPath: scriptAbs,
|
|
52
52
|
scriptArgs,
|
|
53
53
|
projectPath: input.projectPath,
|
|
54
54
|
executionAuthorization: input.executionAuthorization,
|
|
55
|
+
signal: input.signal,
|
|
55
56
|
});
|
|
56
57
|
await launch.prepare?.(input.signal);
|
|
57
58
|
}
|
|
@@ -5,7 +5,7 @@ import { createRequire } from 'node:module';
|
|
|
5
5
|
import { pathToFileURL } from 'node:url';
|
|
6
6
|
import { spawn } from 'node:child_process';
|
|
7
7
|
import { resolveCodexCliPath } from '../agents/baseagent.js';
|
|
8
|
-
import {
|
|
8
|
+
import { ensureSessionRuntimeDirAsync } from '../cli/task-context.js';
|
|
9
9
|
import { buildBubblewrapCommand, buildHClassGuardCommand, resolveBubblewrapPath, } from '../core/permission/sandbox-runtime.js';
|
|
10
10
|
import { resolvePhaseOneExecutionSandbox } from '../core/permission/mode.js';
|
|
11
11
|
import { isCredentialEnvironmentName, sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
|
|
@@ -90,7 +90,8 @@ const SCRIPT_ENVIRONMENT_EXCLUDES = [
|
|
|
90
90
|
* 这是有意的:绕过必须显式,不能让调用方吞掉错误后自己 spawn。
|
|
91
91
|
* 走 daemon scope 时调用方必须向用户明示「本次执行没有沙箱」。
|
|
92
92
|
*/
|
|
93
|
-
export function buildTriggerScriptLaunch(input) {
|
|
93
|
+
export async function buildTriggerScriptLaunch(input) {
|
|
94
|
+
input.signal?.throwIfAborted();
|
|
94
95
|
const authorization = input.executionAuthorization;
|
|
95
96
|
if (!authorization?.allowed || !authorization.scope)
|
|
96
97
|
throw new Error('Trigger execution authorization is missing');
|
|
@@ -147,9 +148,14 @@ export function buildTriggerScriptLaunch(input) {
|
|
|
147
148
|
+ 'Fedora: `dnf install bubblewrap`; Arch: `pacman -S bubblewrap`), '
|
|
148
149
|
+ 'or execute the script through daemon scope / fullaccess and tell the user that no sandbox is applied.');
|
|
149
150
|
}
|
|
150
|
-
const runtimeRoot =
|
|
151
|
+
const runtimeRoot = await ensureSessionRuntimeDirAsync(`trigger:${input.trigger.agentAid}:${input.trigger.id}`);
|
|
152
|
+
input.signal?.throwIfAborted();
|
|
151
153
|
if (!runtimeRoot)
|
|
152
154
|
throw new Error('scoped Trigger runtime directory is unavailable');
|
|
155
|
+
// ACL preparation yields to other work. Recheck directory identities before staging.
|
|
156
|
+
assertRealDirectory(root, 'EvolCore root');
|
|
157
|
+
assertRealDirectory(projectPath, 'Trigger project path');
|
|
158
|
+
assertRealDirectory(triggerDir, 'Trigger directory');
|
|
153
159
|
assertRealDirectory(runtimeRoot, 'scoped Trigger runtime root');
|
|
154
160
|
if (isSameOrDescendant(path.dirname(runtimeRoot), projectPath)) {
|
|
155
161
|
throw new Error('scoped Trigger project must not contain the shared temporary directory');
|
|
@@ -257,6 +257,7 @@ function normalizeV3Phase2(raw, opts) {
|
|
|
257
257
|
createdAt,
|
|
258
258
|
updatedAt,
|
|
259
259
|
origin: normalizeOrigin(raw.origin),
|
|
260
|
+
creator: normalizeCreator(raw.creator),
|
|
260
261
|
source: normalizeSource(raw.source),
|
|
261
262
|
execution: normalizeExecution(raw.execution, { id }),
|
|
262
263
|
feedback: normalizeFeedback(raw.feedback, agentAid),
|
|
@@ -282,6 +283,27 @@ function normalizeV3Phase2(raw, opts) {
|
|
|
282
283
|
validateTriggerSemantics(definition);
|
|
283
284
|
return definition;
|
|
284
285
|
}
|
|
286
|
+
function normalizeCreator(value) {
|
|
287
|
+
if (value === undefined)
|
|
288
|
+
return undefined;
|
|
289
|
+
if (!isObject(value))
|
|
290
|
+
throw new Error('trigger creator must be an object');
|
|
291
|
+
const creator = value;
|
|
292
|
+
const actor = creator.actor;
|
|
293
|
+
if (!isObject(actor) || !['native_aid', 'mapped', 'unmapped', 'error', 'conflict'].includes(String(actor.principalStatus))
|
|
294
|
+
|| !['private', 'group'].includes(creator.chatType))
|
|
295
|
+
throw new Error('trigger creator identity is invalid');
|
|
296
|
+
return {
|
|
297
|
+
actor: {
|
|
298
|
+
operatorId: requiredString(actor.operatorId, 'creator.actor.operatorId'),
|
|
299
|
+
operatorChannelKey: requiredString(actor.operatorChannelKey, 'creator.actor.operatorChannelKey'),
|
|
300
|
+
operatorChannelType: requiredString(actor.operatorChannelType, 'creator.actor.operatorChannelType'),
|
|
301
|
+
principalId: optionalString(actor.principalId),
|
|
302
|
+
principalStatus: actor.principalStatus,
|
|
303
|
+
},
|
|
304
|
+
chatType: creator.chatType, conversationId: requiredString(creator.conversationId, 'creator.conversationId'),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
285
307
|
/** 操作主体列表:字符串数组、去重、截断到 16 项;保证落盘值可直接用于权限比对。 */
|
|
286
308
|
function normalizeOperatorPeers(value) {
|
|
287
309
|
if (value === undefined || value === null)
|
|
@@ -4,7 +4,7 @@ import { createRequire } from 'module';
|
|
|
4
4
|
import { execFileSync, execFile, spawn, spawnSync } from 'child_process';
|
|
5
5
|
import { promisify, TextDecoder } from 'util';
|
|
6
6
|
import fs from 'fs';
|
|
7
|
-
import { getProcessStartTime, parseCimDate } from './process-introspect.js';
|
|
7
|
+
import { createWindowsProcessQuery, getProcessSnapshot, getProcessStartTime, parseCimDate } from './process-introspect.js';
|
|
8
8
|
import { requireTrustedWindowsCmdPath, requireTrustedWindowsCmdPathAsync, WindowsShellTrustError, } from './windows-shell-trust.js';
|
|
9
9
|
import { logger } from './logger.js';
|
|
10
10
|
const execFileAsync = promisify(execFile);
|
|
@@ -990,33 +990,47 @@ export function findProcessesWithCommandLine(pattern) {
|
|
|
990
990
|
// stable literal anchor first, then apply the requested regex locally.
|
|
991
991
|
const anchor = windowsProcessSearchAnchor(pattern);
|
|
992
992
|
const escapedAnchor = anchor.replace(/'/g, "''");
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
if (
|
|
993
|
+
// Reuse the native WMI transport, but keep enumeration fresh and retain
|
|
994
|
+
// the original literal pre-filter. Wildcard anchors keep the old query.
|
|
995
|
+
let rows;
|
|
996
|
+
if (/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(anchor)) {
|
|
997
|
+
try {
|
|
998
|
+
const snapshot = getProcessSnapshot({ fresh: true });
|
|
999
|
+
if (snapshot.complete)
|
|
1000
|
+
rows = [...snapshot.commandLines]
|
|
1001
|
+
.filter(([, command]) => command.toLowerCase().includes(anchor.toLowerCase()))
|
|
1002
|
+
.map(([pid, commandLine]) => ({ ProcessId: pid, CommandLine: commandLine }));
|
|
1003
|
+
}
|
|
1004
|
+
catch { /* Retain the original query if snapshot collection failed. */ }
|
|
1005
|
+
}
|
|
1006
|
+
if (rows === undefined) {
|
|
1007
|
+
const script = `$a='${escapedAnchor}'; Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -like ('*' + $a + '*') } | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`;
|
|
1008
|
+
const result = spawnSync('powershell', ['-NoProfile', '-Command', script], { encoding: null, timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
|
|
1009
|
+
const raw = decodeWindowsOutput(result.stdout).trim();
|
|
1010
|
+
if (!raw)
|
|
1011
|
+
return [];
|
|
997
1012
|
const parsed = JSON.parse(raw);
|
|
998
|
-
|
|
999
|
-
const matcherCandidates = [pattern, pattern.replace(/\\\\/g, '\\')]
|
|
1000
|
-
.filter((value, index, values) => values.indexOf(value) === index)
|
|
1001
|
-
.map((value) => {
|
|
1002
|
-
try {
|
|
1003
|
-
return new RegExp(value, 'i');
|
|
1004
|
-
}
|
|
1005
|
-
catch {
|
|
1006
|
-
return null;
|
|
1007
|
-
}
|
|
1008
|
-
})
|
|
1009
|
-
.filter((value) => value !== null);
|
|
1010
|
-
return rows
|
|
1011
|
-
.filter(row => Number.isInteger(row.ProcessId) && row.ProcessId !== process.pid)
|
|
1012
|
-
.filter(row => {
|
|
1013
|
-
const commandLine = row.CommandLine || '';
|
|
1014
|
-
const normalized = commandLine.replace(/\\/g, '/');
|
|
1015
|
-
return matcherCandidates.some(matcher => matcher.test(commandLine) || matcher.test(normalized));
|
|
1016
|
-
})
|
|
1017
|
-
.map(row => ({ pid: row.ProcessId, commandLine: row.CommandLine || '' }));
|
|
1013
|
+
rows = !parsed ? [] : Array.isArray(parsed) ? parsed : [parsed];
|
|
1018
1014
|
}
|
|
1019
|
-
|
|
1015
|
+
const matcherCandidates = [pattern, pattern.replace(/\\\\/g, '\\')]
|
|
1016
|
+
.filter((value, index, values) => values.indexOf(value) === index)
|
|
1017
|
+
.map((value) => {
|
|
1018
|
+
try {
|
|
1019
|
+
return new RegExp(value, 'i');
|
|
1020
|
+
}
|
|
1021
|
+
catch {
|
|
1022
|
+
return null;
|
|
1023
|
+
}
|
|
1024
|
+
})
|
|
1025
|
+
.filter((value) => value !== null);
|
|
1026
|
+
return rows
|
|
1027
|
+
.filter(row => Number.isInteger(row.ProcessId) && row.ProcessId !== process.pid)
|
|
1028
|
+
.filter(row => {
|
|
1029
|
+
const commandLine = row.CommandLine || '';
|
|
1030
|
+
const normalized = commandLine.replace(/\\/g, '/');
|
|
1031
|
+
return matcherCandidates.some(matcher => matcher.test(commandLine) || matcher.test(normalized));
|
|
1032
|
+
})
|
|
1033
|
+
.map(row => ({ pid: row.ProcessId, commandLine: row.CommandLine || '' }));
|
|
1020
1034
|
}
|
|
1021
1035
|
else {
|
|
1022
1036
|
const output = execFileSync('pgrep', ['-f', pattern], { encoding: 'utf-8' }).trim();
|
|
@@ -1117,9 +1131,42 @@ export async function findProcessByPortAsync(port) {
|
|
|
1117
1131
|
}
|
|
1118
1132
|
return [...pids];
|
|
1119
1133
|
}
|
|
1134
|
+
const WINDOWS_WMI_PROCESS_INFO_SCRIPT = String.raw `
|
|
1135
|
+
var service = GetObject('winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2');
|
|
1136
|
+
var rows = new Enumerator(service.ExecQuery('SELECT ProcessId,WorkingSetSize,CreationDate FROM Win32_Process WHERE ProcessId=' + Number(WScript.Arguments(0))));
|
|
1137
|
+
for (; !rows.atEnd(); rows.moveNext()) {
|
|
1138
|
+
var item = rows.item();
|
|
1139
|
+
WScript.Echo('{"ProcessId":' + Number(item.ProcessId)
|
|
1140
|
+
+ ',"WorkingSetSize":' + Number(item.WorkingSetSize)
|
|
1141
|
+
+ ',"CreationDate":' + (item.CreationDate == null ? 'null' : '"' + String(item.CreationDate) + '"') + '}');
|
|
1142
|
+
}
|
|
1143
|
+
`;
|
|
1120
1144
|
export function getProcessInfo(pid) {
|
|
1121
1145
|
try {
|
|
1122
1146
|
if (isWindows) {
|
|
1147
|
+
const query = createWindowsProcessQuery(WINDOWS_WMI_PROCESS_INFO_SCRIPT, pid);
|
|
1148
|
+
if (query) {
|
|
1149
|
+
try {
|
|
1150
|
+
const result = spawnSync(query.command, query.args, {
|
|
1151
|
+
encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
|
|
1152
|
+
});
|
|
1153
|
+
if (result.status === 0) {
|
|
1154
|
+
const row = JSON.parse(result.stdout || '');
|
|
1155
|
+
const memory = Number(row?.WorkingSetSize);
|
|
1156
|
+
const createdAt = typeof row?.CreationDate === 'string' ? parseCimDate(row.CreationDate) : null;
|
|
1157
|
+
if (row?.ProcessId === pid && Number.isFinite(memory) && memory > 0 && createdAt !== null) {
|
|
1158
|
+
return {
|
|
1159
|
+
memory: String(Math.round(memory / 1024)),
|
|
1160
|
+
uptime: formatUptime(Math.max(0, Math.floor((Date.now() - createdAt) / 1000))),
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
catch { /* Keep the original transports when WMI scripting is unavailable. */ }
|
|
1166
|
+
finally {
|
|
1167
|
+
query.dispose();
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1123
1170
|
// WMIC was removed from recent Windows installations. Prefer the
|
|
1124
1171
|
// supported CIM API and keep WMIC as a compatibility fallback.
|
|
1125
1172
|
const psScript = `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}' | Select-Object WorkingSetSize,CreationDate | ConvertTo-Json -Compress)`;
|