evolcore 0.0.47 → 0.0.49
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 +90 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +143 -40
- 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 +36 -17
- 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/msg/p2p.js +2 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +722 -295
- 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 +13 -2
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +9 -9
- 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/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +62 -17
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/stats.js +3 -3
- package/dist/cli/team-workspace-command.js +56 -2
- 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-field-policy.js +71 -1
- package/dist/config/config-manager.js +13 -7
- 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 +67 -12
- package/dist/config/providers-management.js +477 -51
- package/dist/config/resolved-config-op.js +3 -2
- 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 +36 -26
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +37 -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/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +126 -87
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +67 -150
- package/dist/core/command/menu-protocol.js +31 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/remote-shell.js +565 -0
- 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 +64 -8
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +20 -3
- 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 +3 -1
- package/dist/core/message/aun-ipc-sender.js +279 -107
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +41 -2
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +140 -370
- package/dist/core/message/message-log.js +29 -0
- package/dist/core/message/message-queue.js +119 -15
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +580 -134
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/ownership/owner-resolver.js +328 -50
- package/dist/core/pack-auth.js +3 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +106 -19
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/permission/services-path-acl.js +451 -0
- package/dist/core/permission/tool-policy.js +5 -1
- package/dist/core/relation/peer-identity.js +36 -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 +13 -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/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +12 -9
- package/dist/directory/owner-directory-cache.js +64 -28
- package/dist/directory/owner-directory-markdown.js +14 -2
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +112 -29
- 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 +36 -6
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +29 -3
- package/dist/event-center/runtime.js +106 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +96 -59
- package/dist/ipc.js +38 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +63 -0
- package/dist/outputs/protocol.js +103 -0
- package/dist/outputs/service.js +266 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +114 -5
- package/dist/services/ipc-operation.js +88 -15
- package/dist/services/pack-manager.js +13 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +2 -2
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/quota-query.js +95 -0
- 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 +21 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/atomic-write.js +22 -8
- 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/host-info.js +100 -1
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/npm-ops.js +43 -8
- 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 +4 -2
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +16 -1
- package/kits/docs/evolcore/directory.md +30 -12
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +124 -4
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +83 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/stats.md +2 -0
- 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 +12 -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/agent-config.schema.20.json +24 -0
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +8 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- 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 +270 -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/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- 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 +7 -5
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +50 -11
- package/scripts/agent-template/shared/common.mjs +11 -6
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +62 -11
- package/scripts/agent-template/shared/template-package.mjs +189 -21
- package/scripts/agent-template/shared/template-runtime.mjs +54 -6
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +52 -14
- 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
|
@@ -81,7 +81,9 @@ export function getRoleBudgetStatus(evolcoreHome, req) {
|
|
|
81
81
|
hard_blocked: pct >= 100,
|
|
82
82
|
};
|
|
83
83
|
}
|
|
84
|
-
function resolveRoleUsageLimits(role, selfAid) {
|
|
84
|
+
export function resolveRoleUsageLimits(role, selfAid) {
|
|
85
|
+
if (isManagementRole(role))
|
|
86
|
+
return null;
|
|
85
87
|
const roleDef = getRoleDefinition(role, selfAid);
|
|
86
88
|
if (!roleDef)
|
|
87
89
|
return null;
|
|
@@ -94,9 +96,10 @@ function resolveRoleUsageLimits(role, selfAid) {
|
|
|
94
96
|
return null;
|
|
95
97
|
}
|
|
96
98
|
function hasExplicitUsageLimit(limits) {
|
|
97
|
-
return limits.enabled
|
|
99
|
+
return limits.enabled !== undefined
|
|
98
100
|
|| limits.resetMode != null
|
|
99
101
|
|| limits.currency != null
|
|
102
|
+
|| (Object.hasOwn(limits, 'limitAmount') && limits.limitAmount === null)
|
|
100
103
|
|| limits.limitAmount != null
|
|
101
104
|
|| limits.costBasis != null
|
|
102
105
|
|| limits.scope != null;
|
package/dist/stats/writer.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { getDb, resetStatsDb, startDailyRollupMaintenance } from './db.js';
|
|
5
5
|
import { normalizeUsage } from './normalizer.js';
|
|
6
|
-
import { resolvePrices } from './
|
|
6
|
+
import { resolvePrices } from './model-resolver.js';
|
|
7
7
|
import { logger } from '../utils/logger.js';
|
|
8
8
|
export function insertUsageEvent(evolcoreHome, event, gatewayPricing, modelCalls) {
|
|
9
9
|
if (modelCalls?.some(call => call.source === 'subagent')) {
|
|
@@ -72,14 +72,15 @@ function writeUsageEvent(db, event, prices) {
|
|
|
72
72
|
db.exec('BEGIN');
|
|
73
73
|
db.prepare(`
|
|
74
74
|
INSERT INTO usage_events
|
|
75
|
-
(ts, agent_aid, peer_key, usage_subject_key, role, peer_type, session_id, model,
|
|
75
|
+
(ts, agent_aid, peer_key, usage_subject_key, role, peer_type, session_id, model,
|
|
76
|
+
provider_id, base_url, billing_fn,
|
|
76
77
|
input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens,
|
|
77
78
|
cache_hit_tokens, cache_miss_tokens, image_tokens, total_context_tokens,
|
|
78
79
|
turns, duration_ms, context_window_pct,
|
|
79
80
|
cost_official_usd, cost_official_cny, cost_gateway_usd, cost_gateway_cny)
|
|
80
81
|
VALUES
|
|
81
|
-
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
82
|
-
`).run(event.ts, event.agent_aid, event.peer_key, event.usage_subject_key ?? event.peer_key ?? '', event.role ?? '', event.peer_type ?? null, event.session_id ?? null, event.model, event.billing_fn, event.input_tokens, event.output_tokens, event.cache_creation_tokens, event.cache_read_tokens, event.cache_hit_tokens ?? null, event.cache_miss_tokens ?? null, event.image_tokens ?? null, event.total_context_tokens ?? null, event.turns, event.duration_ms ?? null, event.context_window_pct ?? null, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
|
|
82
|
+
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
83
|
+
`).run(event.ts, event.agent_aid, event.peer_key, event.usage_subject_key ?? event.peer_key ?? '', event.role ?? '', event.peer_type ?? null, event.session_id ?? null, event.model, event.provider_id ?? null, event.base_url ?? null, event.billing_fn, event.input_tokens, event.output_tokens, event.cache_creation_tokens, event.cache_read_tokens, event.cache_hit_tokens ?? null, event.cache_miss_tokens ?? null, event.image_tokens ?? null, event.total_context_tokens ?? null, event.turns, event.duration_ms ?? null, event.context_window_pct ?? null, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
|
|
83
84
|
// 写时增量:累加到日级预聚合表(grain 与 db.ts rebuildDailyRollup 一致)。
|
|
84
85
|
db.prepare(`
|
|
85
86
|
INSERT INTO usage_daily
|
|
@@ -223,6 +224,8 @@ function resolveCallPrices(evolcoreHome, r, gatewayPricing) {
|
|
|
223
224
|
peer_key: r.peer_key,
|
|
224
225
|
session_id: r.session_id,
|
|
225
226
|
model: r.model || 'unknown',
|
|
227
|
+
provider_id: r.provider_id,
|
|
228
|
+
base_url: r.base_url,
|
|
226
229
|
turns: 1,
|
|
227
230
|
});
|
|
228
231
|
return resolvePrices(evolcoreHome, event, gatewayPricing);
|
|
@@ -238,10 +241,11 @@ export function insertModelCalls(evolcoreHome, rows, gatewayPricing) {
|
|
|
238
241
|
const stmt = db.prepare(`
|
|
239
242
|
INSERT INTO model_calls
|
|
240
243
|
(ts, task_id, session_id, agent_session_id, agent_aid, peer_key, call_index, model,
|
|
244
|
+
provider_id, base_url,
|
|
241
245
|
source, provider_thread_id, request_id, message_id, input_tokens, output_tokens, cache_creation_tokens,
|
|
242
246
|
cache_read_tokens, context_tokens, max_tokens, auto_compact_tokens, degraded,
|
|
243
247
|
cost_official_usd, cost_official_cny, cost_gateway_usd, cost_gateway_cny)
|
|
244
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
248
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
245
249
|
`);
|
|
246
250
|
// 价格解析在读事务外算好:resolvePrices 可能读价格表文件,避免拖长写锁。
|
|
247
251
|
const priced = rows.map(r => {
|
|
@@ -256,7 +260,7 @@ export function insertModelCalls(evolcoreHome, rows, gatewayPricing) {
|
|
|
256
260
|
});
|
|
257
261
|
db.exec('BEGIN');
|
|
258
262
|
for (const { r, prices } of priced) {
|
|
259
|
-
stmt.run(r.ts, r.task_id, r.session_id ?? null, r.agent_session_id ?? null, r.agent_aid, r.peer_key, r.call_index, r.model, r.source ?? 'request', r.provider_thread_id ?? null, r.request_id ?? null, r.message_id ?? null, r.input_tokens, r.output_tokens, r.cache_creation_tokens, r.cache_read_tokens, r.context_tokens ?? null, r.max_tokens ?? null, r.auto_compact_tokens ?? null, r.degraded, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
|
|
263
|
+
stmt.run(r.ts, r.task_id, r.session_id ?? null, r.agent_session_id ?? null, r.agent_aid, r.peer_key, r.call_index, r.model, r.provider_id ?? null, r.base_url ?? null, r.source ?? 'request', r.provider_thread_id ?? null, r.request_id ?? null, r.message_id ?? null, r.input_tokens, r.output_tokens, r.cache_creation_tokens, r.cache_read_tokens, r.context_tokens ?? null, r.max_tokens ?? null, r.auto_compact_tokens ?? null, r.degraded, prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null);
|
|
260
264
|
}
|
|
261
265
|
db.exec('COMMIT');
|
|
262
266
|
}
|
package/dist/trigger/audit.js
CHANGED
|
@@ -75,6 +75,13 @@ export class TriggerAuditLogger {
|
|
|
75
75
|
}
|
|
76
76
|
return latest;
|
|
77
77
|
}
|
|
78
|
+
summaries(triggerIds) {
|
|
79
|
+
const ids = [...new Set(triggerIds)];
|
|
80
|
+
if (this.history)
|
|
81
|
+
return this.history.summaries(ids);
|
|
82
|
+
const latest = this.latest(ids);
|
|
83
|
+
return new Map(ids.map(id => [id, { latestRun: latest.get(id), stats: this.stats(id) }]));
|
|
84
|
+
}
|
|
78
85
|
/**
|
|
79
86
|
* 汇总某 trigger 的运行统计。绑定 history 时读取长期历史;未绑定时保留旧的
|
|
80
87
|
* 日志扫描行为,供兼容调用使用。skipped 和 dry-run 不计入 fireCount。
|
|
@@ -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');
|
|
@@ -196,6 +202,18 @@ export function buildTriggerScriptLaunch(input) {
|
|
|
196
202
|
filesystemEntry(snapshotDir, 'read'),
|
|
197
203
|
filesystemEntry(workDir, 'write'),
|
|
198
204
|
filesystemEntry(windowsBackend.home, 'deny'),
|
|
205
|
+
// 服务包:脚本不能改写自己的代码与声明,只能读。
|
|
206
|
+
//
|
|
207
|
+
// 当前行为本来就是这样(`root: read` + 没有任何条目给 services 授 write),
|
|
208
|
+
// 这条的价值是把它从「依赖默认拒绝」变成显式声明:将来若有重构把 services
|
|
209
|
+
// 纳入 write 范围(例如为缓存/worker 方案放权),这里仍然读-写不对称。
|
|
210
|
+
//
|
|
211
|
+
// **不能写 `deny`**:Codex 的 deny 连读一起拒,而服务脚本要读自己的
|
|
212
|
+
// pack.json。真需要拦写也拦不住显式子级 Allow——那由 ACL 层负责
|
|
213
|
+
// (见 src/core/permission/services-path-acl.ts)。
|
|
214
|
+
...(input.trigger.labels?.kind === 'services'
|
|
215
|
+
? [filesystemEntry(path.join(root, 'agents', input.trigger.agentAid, 'services'), 'read')]
|
|
216
|
+
: []),
|
|
199
217
|
...Object.entries(filesystem).flatMap(([value, access]) => typeof access === 'number' ? [] : [{
|
|
200
218
|
path: /[*?[\]]/.test(value)
|
|
201
219
|
? { type: 'glob_pattern', pattern: value }
|
|
@@ -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)
|
|
@@ -295,14 +295,7 @@ export async function withFileLock(file, action, timeoutMs = 30000) {
|
|
|
295
295
|
export async function atomicReplaceJson(file, value) {
|
|
296
296
|
const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
297
297
|
try {
|
|
298
|
-
|
|
299
|
-
try {
|
|
300
|
-
fs.writeFileSync(fd, JSON.stringify(value, null, 2) + '\n', 'utf8');
|
|
301
|
-
fs.fsyncSync(fd);
|
|
302
|
-
}
|
|
303
|
-
finally {
|
|
304
|
-
fs.closeSync(fd);
|
|
305
|
-
}
|
|
298
|
+
writeSyncedReplacement(temporary, JSON.stringify(value, null, 2) + '\n', 'wx');
|
|
306
299
|
const deadline = Date.now() + 5000;
|
|
307
300
|
for (let attempt = 0;; attempt++) {
|
|
308
301
|
try {
|
|
@@ -321,6 +314,27 @@ export async function atomicReplaceJson(file, value) {
|
|
|
321
314
|
fs.rmSync(temporary, { force: true });
|
|
322
315
|
}
|
|
323
316
|
}
|
|
317
|
+
/** Strict synchronous replacement without a hot backup; callers serialize writes to the same file. */
|
|
318
|
+
export function atomicReplaceJsonSync(file, value) {
|
|
319
|
+
const temporary = `${file}.pending`;
|
|
320
|
+
try {
|
|
321
|
+
writeSyncedReplacement(temporary, JSON.stringify(value), 'w');
|
|
322
|
+
atomicReplaceFile(temporary, file, { allowInPlaceFallback: false });
|
|
323
|
+
}
|
|
324
|
+
finally {
|
|
325
|
+
fs.rmSync(temporary, { force: true });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function writeSyncedReplacement(temporary, content, flags) {
|
|
329
|
+
const fd = fs.openSync(temporary, flags, 0o600);
|
|
330
|
+
try {
|
|
331
|
+
fs.writeFileSync(fd, content, 'utf8');
|
|
332
|
+
fs.fsyncSync(fd);
|
|
333
|
+
}
|
|
334
|
+
finally {
|
|
335
|
+
fs.closeSync(fd);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
324
338
|
const retryableCodes = new Set(['EPERM', 'EACCES', 'EBUSY']);
|
|
325
339
|
const delays = [10, 25, 50, 100];
|
|
326
340
|
const pause = new Int32Array(new SharedArrayBuffer(4));
|