evolcore 0.0.48 → 0.0.50
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 +97 -0
- package/bin/ecmsg.js +9 -4
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +164 -0
- package/dist/ability/caller/contract.js +102 -0
- package/dist/ability/caller/daemon.js +158 -0
- package/dist/ability/caller/service.js +380 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +10 -3
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +173 -1
- package/dist/agent-template/runtime.js +285 -8
- package/dist/agent-template/service.js +1159 -40
- package/dist/agent-template/types.js +2 -1
- package/dist/agents/baseagent-availability.js +27 -3
- package/dist/agents/baseagent-capability-adapter.js +102 -0
- package/dist/agents/baseagent-plugin-descriptor.js +274 -0
- package/dist/agents/baseagent-plugin-loader.js +145 -0
- package/dist/agents/baseagent.js +68 -2
- package/dist/agents/claude-gateway/agent-registration.js +389 -0
- package/dist/agents/claude-gateway/binding.js +96 -0
- package/dist/agents/claude-gateway/inbox.js +138 -0
- package/dist/agents/claude-gateway/index.js +125 -0
- package/dist/agents/claude-gateway/listing.js +330 -0
- package/dist/agents/claude-gateway/router.js +328 -0
- package/dist/agents/claude-gateway/sessions.js +128 -0
- package/dist/agents/claude-gateway/terminal.js +250 -0
- package/dist/agents/claude-gateway/transcript.js +272 -0
- package/dist/agents/claude-gateway/types.js +14 -0
- package/dist/agents/claude-runner.js +6 -10
- package/dist/agents/codex-runner.js +9 -2
- package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
- package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
- package/dist/agents/gemini/index.js +51 -0
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/group/invite-service.js +6 -36
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +31 -2
- package/dist/aun/msg/upload.js +126 -3
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +1175 -457
- package/dist/cli/ability-command.js +42 -0
- package/dist/cli/agent-command.js +20 -1
- package/dist/cli/agent-create.js +78 -18
- package/dist/cli/agent-template.js +5 -3
- package/dist/cli/agent.js +91 -0
- package/dist/cli/aun-commands.js +92 -34
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +245 -101
- package/dist/cli/directory.js +6 -1
- package/dist/cli/ecmsg-gateway.js +11 -9
- package/dist/cli/index.js +30 -5
- package/dist/cli/init.js +39 -63
- package/dist/cli/managed-command-guard.js +3 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/model.js +20 -5
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/quota.js +89 -0
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/role.js +1 -0
- package/dist/cli/services-command.js +12 -9
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +78 -12
- package/dist/config/access-policy.js +16 -3
- package/dist/config/config-field-policy.js +88 -9
- package/dist/config/config-manager.js +97 -47
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +9 -8
- package/dist/config/owner-config.js +0 -16
- package/dist/config/peer-role-resolver.js +1 -7
- package/dist/config/providers-config.js +107 -20
- package/dist/config/providers-management.js +45 -21
- package/dist/config/resolved-config-op.js +4 -44
- package/dist/config/schema-migration.js +78 -5
- package/dist/config/schema-registry.js +52 -7
- package/dist/config-store.js +1309 -17
- package/dist/core/agent-application-service.js +220 -1
- package/dist/core/agent-ipc-registration.js +19 -2
- package/dist/core/agent-reload-coordinator.js +5 -0
- package/dist/core/agent-runtime.js +198 -54
- package/dist/core/auth/agent-delegation.js +14 -0
- package/dist/core/auth/delegation-authorization.js +33 -26
- package/dist/core/auth/operation-authorizer.js +16 -1
- package/dist/core/auth/operation-catalog.js +59 -7
- package/dist/core/baseagent-loader.js +30 -3
- package/dist/core/capability/capability-manager.js +16 -7
- package/dist/core/channel-runtime.js +4 -2
- package/dist/core/command/agent-control.js +20 -2
- package/dist/core/command/agent-template-menu.js +4 -3
- package/dist/core/command/cli-intent-parser.js +28 -0
- package/dist/core/command/command-handler.js +45 -2
- package/dist/core/command/menu-catalog.js +20 -4
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +97 -73
- package/dist/core/command/menu-protocol.js +29 -0
- package/dist/core/command/menu-query-batch.js +2 -2
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/slash-handler.js +17 -26
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/topic-slash.js +7 -1
- package/dist/core/daemon-bootstrap.js +0 -4
- package/dist/core/daemon-control.js +58 -1
- package/dist/core/daemon-lifecycle.js +29 -7
- package/dist/core/evolagent-registry.js +18 -9
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/core/host-snapshot.js +8 -3
- package/dist/core/initialization/service.js +3 -0
- package/dist/core/interaction-router.js +130 -0
- package/dist/core/ipc-registration.js +5 -0
- package/dist/core/memory/consolidation-context.js +2 -1
- package/dist/core/memory/consolidation.js +35 -64
- package/dist/core/message/aun-ipc-sender.js +213 -74
- package/dist/core/message/aun-request-registry.js +31 -0
- 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 +40 -1
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +197 -45
- package/dist/core/message/message-log.js +32 -0
- package/dist/core/message/message-queue.js +102 -18
- package/dist/core/message/peer-mode.js +15 -4
- package/dist/core/message/response-engine.js +174 -26
- package/dist/core/message/send-options.js +37 -3
- package/dist/core/message/send-routing.js +11 -7
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-catalog.js +5 -5
- 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 +12 -86
- package/dist/core/pack-auth.js +7 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +288 -77
- package/dist/core/permission/protected-paths.js +64 -9
- package/dist/core/permission/services-path-acl.js +458 -0
- package/dist/core/permission/tool-policy.js +26 -10
- package/dist/core/relation/peer-identity.js +13 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
- package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
- package/dist/core/session/session-manager.js +47 -10
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/skill/index-generator.js +2 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/task/task-recovery-service.js +1 -0
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +4 -2
- package/dist/core/thread/thread-operation.js +25 -10
- package/dist/core/thread/thread-service.js +294 -55
- package/dist/core/thread/topic-id.js +67 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/directory/owner-directory-admission.js +11 -8
- package/dist/directory/owner-directory-cache.js +19 -0
- package/dist/directory/owner-directory-markdown.js +1 -1
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +3 -2
- package/dist/eck/message-renderer.js +28 -5
- package/dist/ecweb/basic-settings-service.js +5 -9
- package/dist/ecweb/providers-service.js +4 -2
- package/dist/ecweb/runtime/supervisor.js +36 -8
- 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 +20 -5
- package/dist/event-center/runtime.js +10 -7
- package/dist/index.js +120 -41
- package/dist/ipc.js +83 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +3 -2
- package/dist/outputs/protocol.js +1 -0
- package/dist/outputs/service.js +2 -15
- package/dist/paths.js +48 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +188 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +29 -2
- package/dist/services/dispatcher.js +23 -5
- package/dist/services/host/main.js +388 -0
- package/dist/services/host/protocol.js +118 -0
- package/dist/services/host/resident.js +310 -0
- package/dist/services/host-client.js +386 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +203 -0
- package/dist/services/host-runtime.js +802 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +204 -22
- package/dist/services/ipc-operation.js +288 -44
- package/dist/services/pack-manager.js +1 -0
- package/dist/services/script-runner.js +515 -83
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +109 -4
- package/dist/stats/budget.js +1 -1
- package/dist/stats/model-resolver.js +2 -2
- package/dist/stats/quota-query.js +95 -0
- package/dist/trigger/application-service.js +6 -4
- package/dist/trigger/local-files.js +19 -9
- package/dist/trigger/scheduler.js +22 -12
- package/dist/trigger/script-sandbox.js +51 -8
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +173 -1
- package/dist/utils/logger.js +2 -2
- package/dist/utils/media-cache.js +190 -43
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/windows-shell-trust.js +7 -3
- package/dist/workbench/service.js +1 -1
- package/kits/docs/INDEX.md +3 -2
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/evolcore/INDEX.md +9 -6
- package/kits/docs/evolcore/agent.md +36 -1
- package/kits/docs/evolcore/aid.md +45 -3
- package/kits/docs/evolcore/config.md +5 -2
- package/kits/docs/evolcore/directory.md +8 -9
- package/kits/docs/evolcore/group.md +2 -1
- package/kits/docs/evolcore/memory-tags.md +2 -0
- package/kits/docs/evolcore/menu-client.md +3 -3
- package/kits/docs/evolcore/menu-protocol.md +7 -0
- package/kits/docs/evolcore/model.md +3 -0
- package/kits/docs/evolcore/msg.md +77 -10
- package/kits/docs/evolcore/pay.md +34 -0
- package/kits/docs/evolcore/provider.md +22 -1
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +3 -0
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/thread-chain.md +2 -0
- package/kits/docs/evolcore/tool-authorization.md +10 -0
- package/kits/docs/evolcore/trigger.md +2 -0
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +7 -0
- package/kits/rules/06-channel.md +3 -3
- package/kits/schemas/_meta.json +38 -5
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/agent-config.schema.21.json +974 -0
- package/kits/schemas/agent-config.schema.22.json +977 -0
- package/kits/schemas/agent-config.schema.23.json +958 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/providers.schema.3.json +18 -2
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +17 -1
- package/kits/skills/ability/SKILL.md +229 -34
- package/kits/skills/ability/STRUCTURE.md +333 -0
- package/kits/skills/ability/references/cli.md +208 -0
- package/kits/skills/ability/references/development.md +107 -37
- package/kits/skills/ability/references/management.md +106 -46
- package/kits/skills/ability/references/runtime-protocol.md +65 -63
- package/kits/skills/agent-output-cards/SKILL.md +64 -0
- package/kits/skills/ec-group/SKILL.md +8 -6
- package/kits/skills/ec-group/TASK.md +186 -0
- package/kits/skills/ec-group/WORKLOG.md +180 -0
- package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
- package/kits/skills/ec-pay/SKILL.md +101 -0
- package/kits/skills/ec-pay/references/pay-cli.md +110 -0
- package/kits/skills/ec-provider/SKILL.md +58 -9
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +135 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +5 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/reply.md +1 -0
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +27 -128
- package/kits/templates/system-fragments/venue.md +27 -0
- package/package.json +4 -5
- package/scripts/agent-template/inspect.mjs +79 -29
- package/scripts/agent-template/overlay.mjs +20 -2
- package/scripts/agent-template/shared/common.mjs +24 -6
- package/scripts/agent-template/shared/team-schema.json +23 -5
- package/scripts/agent-template/shared/template-contract.mjs +107 -17
- package/scripts/agent-template/shared/template-package.mjs +254 -29
- package/scripts/agent-template/shared/template-runtime.mjs +145 -2
- package/scripts/agent-template/shared/template.mjs +67 -9
- package/scripts/agent-template/team-pack.mjs +132 -41
- package/scripts/agent-template/team-preview.mjs +249 -5
- package/kits/docs/aun/ABILITY_CALLING.md +0 -280
- package/kits/docs/evolcore/ability.md +0 -185
- package/kits/skills/ability/references/calling.md +0 -56
- package/kits/skills/ability/references/contract-checklist.md +0 -37
- package/kits/skills/ability/references/recovery.md +0 -27
- /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
|
@@ -5,15 +5,21 @@
|
|
|
5
5
|
* 不涉及「本机有没有包能接」(那是 pack-manager 的事),也不涉及
|
|
6
6
|
* 「这条消息来自谁」(那是准入的事)。三层判据互不推导。
|
|
7
7
|
*/
|
|
8
|
-
/** 请求 type
|
|
9
|
-
const SERVICE_REQUEST = /^services(\.[A-Za-z0-9_-]+){0,
|
|
10
|
-
/** 应答 type:请求 type + .result
|
|
11
|
-
const SERVICE_RESULT = /^services(\.[A-Za-z0-9_-]+){0,
|
|
12
|
-
/** listen
|
|
13
|
-
const SERVICE_WILDCARD = /^services(\.[A-Za-z0-9_-]+){0,
|
|
8
|
+
/** 请求 type:最多三段 action 路径,例如 services.outputs.cards.snapshot。 */
|
|
9
|
+
const SERVICE_REQUEST = /^services(\.[A-Za-z0-9_-]+){0,3}$/;
|
|
10
|
+
/** 应答 type:请求 type + .result。 */
|
|
11
|
+
const SERVICE_RESULT = /^services(\.[A-Za-z0-9_-]+){0,3}\.result$/;
|
|
12
|
+
/** listen 可用的通配形式:最多两段路径后接末段整段 *。 */
|
|
13
|
+
const SERVICE_WILDCARD = /^services(\.[A-Za-z0-9_-]+){0,2}\.\*$/;
|
|
14
|
+
/** Owner-private read projections are ephemeral control replies. Business
|
|
15
|
+
* service replies keep their normal durable delivery semantics. */
|
|
16
|
+
export function isProjectionServiceResult(type) {
|
|
17
|
+
return typeof type === 'string'
|
|
18
|
+
&& /^services\.(?:outputs\.(?:(?:snapshot|list|detail|changes)|cards\.(?:snapshot|list|detail|changes))|workbench\.(?:snapshot|changes|history))\.result$/.test(type);
|
|
19
|
+
}
|
|
14
20
|
/**
|
|
15
21
|
* SERVICE_REQUEST 与 SERVICE_RESULT 有意重叠:
|
|
16
|
-
* `services.order.result`
|
|
22
|
+
* `services.order.result` 同时匹配两条;
|
|
17
23
|
* 靠 result 优先消解——先判应答,再判请求。
|
|
18
24
|
*
|
|
19
25
|
* 因此 `services.result` 既是合法请求(裸 services 的 action),也是裸 `services` 的应答;
|
|
@@ -27,7 +27,22 @@ function runtimeForExtension(script) {
|
|
|
27
27
|
}
|
|
28
28
|
const TIMEOUT_MIN = 1000;
|
|
29
29
|
const TIMEOUT_MAX = 300_000;
|
|
30
|
-
|
|
30
|
+
/**
|
|
31
|
+
* handler.name / handler.description 的长度上限。
|
|
32
|
+
*
|
|
33
|
+
* 比包级 `description`(200)更严:这两个字段会进 `services.skill` 的渲染文本,
|
|
34
|
+
* 而 skill 是给**另一个 Agent 读的**。一个包有 10 个 type 时,每个 200 字就是
|
|
35
|
+
* 2000 字噪音。收紧到 24 / 120,并配合 skill 渲染时的单行截断。
|
|
36
|
+
*/
|
|
37
|
+
export const HANDLER_NAME_MAX = 24;
|
|
38
|
+
export const HANDLER_DESCRIPTION_MAX = 120;
|
|
39
|
+
/**
|
|
40
|
+
* 脚本默认超时。必须**短于**调用方的等待期(`SERVICE_CALL_TIMEOUT_MS`,12 秒),
|
|
41
|
+
* 否则脚本的默认执行窗口比调用方愿意等的时间还长:每次都必然白跑,
|
|
42
|
+
* 调用方只看到 NO_RESULT 而服务端还在跑。
|
|
43
|
+
*/
|
|
44
|
+
export const DEFAULT_HANDLER_TIMEOUT_MS = 10_000;
|
|
45
|
+
const TIMEOUT_DEFAULT = DEFAULT_HANDLER_TIMEOUT_MS;
|
|
31
46
|
const QUOTA_DEFAULT_BUILTIN = { perMinute: 20, perHour: 200 };
|
|
32
47
|
const QUOTA_DEFAULT_SERVICE = { perMinute: 50, perHour: 1000 };
|
|
33
48
|
function isRecord(value) {
|
|
@@ -44,6 +59,20 @@ function optionalString(value, field, errors, max) {
|
|
|
44
59
|
errors.push(`${field} is too long (max ${max})`);
|
|
45
60
|
return value;
|
|
46
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* handler 的展示性文本(`name` / `description`)。
|
|
64
|
+
*
|
|
65
|
+
* 与 `optionalString` 的差别只有一点:**纯空白视为未声明**。这两个字段只用于展示,
|
|
66
|
+
* 写一个空串和没写没有任何区别;保留空串反而会让 `describe` 输出里出现
|
|
67
|
+
* `"name": ""`,调用方无法区分「有标题但为空」和「没标题」。
|
|
68
|
+
*/
|
|
69
|
+
function optionalLabel(value, field, max, errors) {
|
|
70
|
+
const text = optionalString(value, field, errors, max);
|
|
71
|
+
if (text === undefined)
|
|
72
|
+
return undefined;
|
|
73
|
+
const trimmed = text.trim();
|
|
74
|
+
return trimmed ? trimmed : undefined;
|
|
75
|
+
}
|
|
47
76
|
function intInRange(value, field, min, max, errors) {
|
|
48
77
|
if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
|
|
49
78
|
errors.push(`${field} must be an integer between ${min} and ${max}`);
|
|
@@ -118,10 +147,12 @@ function validateHandler(raw, errors) {
|
|
|
118
147
|
errors.push('listen[].handler must be an object');
|
|
119
148
|
return undefined;
|
|
120
149
|
}
|
|
121
|
-
const extra = Object.keys(raw).filter(key => !['script', 'runtime', 'args', 'timeoutMs'].includes(key));
|
|
150
|
+
const extra = Object.keys(raw).filter(key => !['script', 'runtime', 'args', 'timeoutMs', 'name', 'description', 'mode', 'resident'].includes(key));
|
|
122
151
|
if (extra.length)
|
|
123
152
|
errors.push(`listen[].handler has unknown fields: ${extra.join(', ')}`);
|
|
124
153
|
const script = validateScriptPath(raw.script, errors);
|
|
154
|
+
const name = optionalLabel(raw.name, 'listen[].handler.name', HANDLER_NAME_MAX, errors);
|
|
155
|
+
const description = optionalLabel(raw.description, 'listen[].handler.description', HANDLER_DESCRIPTION_MAX, errors);
|
|
125
156
|
if (raw.runtime !== undefined && !RUNTIME_WHITELIST.includes(raw.runtime)) {
|
|
126
157
|
errors.push(`listen[].handler.runtime must be one of ${RUNTIME_WHITELIST.join('/')}`);
|
|
127
158
|
}
|
|
@@ -140,6 +171,7 @@ function validateHandler(raw, errors) {
|
|
|
140
171
|
const timeoutMs = raw.timeoutMs === undefined
|
|
141
172
|
? TIMEOUT_DEFAULT
|
|
142
173
|
: intInRange(raw.timeoutMs, 'listen[].handler.timeoutMs', TIMEOUT_MIN, TIMEOUT_MAX, errors);
|
|
174
|
+
const mode = validateHandlerMode(raw.mode, raw.resident, errors);
|
|
143
175
|
if (script === undefined)
|
|
144
176
|
return undefined;
|
|
145
177
|
return {
|
|
@@ -147,6 +179,60 @@ function validateHandler(raw, errors) {
|
|
|
147
179
|
...(raw.runtime !== undefined ? { runtime: raw.runtime } : {}),
|
|
148
180
|
...(Array.isArray(raw.args) ? { args: raw.args } : {}),
|
|
149
181
|
timeoutMs: timeoutMs ?? TIMEOUT_DEFAULT,
|
|
182
|
+
...(name !== undefined ? { name } : {}),
|
|
183
|
+
...(description !== undefined ? { description } : {}),
|
|
184
|
+
...(mode !== undefined ? { mode: mode.mode } : {}),
|
|
185
|
+
...(mode?.resident ? { resident: mode.resident } : {}),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* `handler.mode` / `handler.resident` 校验。
|
|
190
|
+
*
|
|
191
|
+
* `resident` 子对象只在 `mode:"resident"` 时有意义——其他形态下出现就报错,
|
|
192
|
+
* 因为静默忽略会让作者以为调参生效了,而实际写的是个死配置。
|
|
193
|
+
*/
|
|
194
|
+
function validateHandlerMode(rawMode, rawResident, errors) {
|
|
195
|
+
if (rawMode !== undefined && rawMode !== 'spawn' && rawMode !== 'resident') {
|
|
196
|
+
errors.push('listen[].handler.mode must be "spawn" or "resident"');
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
// 未声明时**不落默认值**:让"没写"与"显式写 spawn"在输出里可区分——
|
|
200
|
+
// 否则 describe/status 会显示一个用户从未写过的 mode,排查时容易误判。
|
|
201
|
+
const declared = rawMode === 'spawn' || rawMode === 'resident' ? rawMode : undefined;
|
|
202
|
+
const mode = declared ?? 'spawn';
|
|
203
|
+
if (rawResident === undefined)
|
|
204
|
+
return declared ? { mode: declared } : undefined;
|
|
205
|
+
if (mode !== 'resident') {
|
|
206
|
+
errors.push('listen[].handler.resident is only meaningful when handler.mode is "resident"');
|
|
207
|
+
return declared ? { mode: declared } : undefined;
|
|
208
|
+
}
|
|
209
|
+
if (!isRecord(rawResident)) {
|
|
210
|
+
errors.push('listen[].handler.resident must be an object');
|
|
211
|
+
return { mode: declared };
|
|
212
|
+
}
|
|
213
|
+
const extra = Object.keys(rawResident).filter(key => !['startTimeoutMs', 'softTimeoutMs', 'hardTimeoutAfter'].includes(key));
|
|
214
|
+
if (extra.length)
|
|
215
|
+
errors.push(`listen[].handler.resident has unknown fields: ${extra.join(', ')}`);
|
|
216
|
+
const startTimeoutMs = rawResident.startTimeoutMs === undefined
|
|
217
|
+
? undefined
|
|
218
|
+
: intInRange(rawResident.startTimeoutMs, 'listen[].handler.resident.startTimeoutMs', TIMEOUT_MIN, 120_000, errors);
|
|
219
|
+
const softTimeoutMs = rawResident.softTimeoutMs === undefined
|
|
220
|
+
? undefined
|
|
221
|
+
: intInRange(rawResident.softTimeoutMs, 'listen[].handler.resident.softTimeoutMs', TIMEOUT_MIN, TIMEOUT_MAX, errors);
|
|
222
|
+
const hardTimeoutAfter = rawResident.hardTimeoutAfter === undefined
|
|
223
|
+
? undefined
|
|
224
|
+
: intInRange(rawResident.hardTimeoutAfter, 'listen[].handler.resident.hardTimeoutAfter', 1, 100, errors);
|
|
225
|
+
return {
|
|
226
|
+
...(declared ? { mode: declared } : {}),
|
|
227
|
+
...((startTimeoutMs ?? softTimeoutMs ?? hardTimeoutAfter) !== undefined
|
|
228
|
+
? {
|
|
229
|
+
resident: {
|
|
230
|
+
...(startTimeoutMs !== undefined ? { startTimeoutMs } : {}),
|
|
231
|
+
...(softTimeoutMs !== undefined ? { softTimeoutMs } : {}),
|
|
232
|
+
...(hardTimeoutAfter !== undefined ? { hardTimeoutAfter } : {}),
|
|
233
|
+
},
|
|
234
|
+
}
|
|
235
|
+
: {}),
|
|
150
236
|
};
|
|
151
237
|
}
|
|
152
238
|
function validateListenEntry(raw, errors) {
|
|
@@ -366,7 +452,7 @@ export function validateRouterConfig(raw) {
|
|
|
366
452
|
const errors = [];
|
|
367
453
|
if (!isRecord(raw))
|
|
368
454
|
return { ok: false, errors: ['services-config.json must be a JSON object'] };
|
|
369
|
-
const extra = Object.keys(raw).filter(key => !['v', 'enabled', 'rateLimit', 'rules'].includes(key));
|
|
455
|
+
const extra = Object.keys(raw).filter(key => !['v', 'enabled', 'rateLimit', 'rules', 'host'].includes(key));
|
|
370
456
|
if (extra.length)
|
|
371
457
|
errors.push(`unknown top-level fields: ${extra.join(', ')}`);
|
|
372
458
|
if (raw.v !== 1)
|
|
@@ -391,11 +477,30 @@ export function validateRouterConfig(raw) {
|
|
|
391
477
|
}
|
|
392
478
|
}
|
|
393
479
|
const rules = validateRules(raw.rules, errors);
|
|
480
|
+
const host = validateHostConfig(raw.host, errors);
|
|
394
481
|
if (errors.length)
|
|
395
482
|
return { ok: false, errors };
|
|
396
483
|
return {
|
|
397
484
|
ok: true,
|
|
398
485
|
errors: [],
|
|
399
|
-
value: { v: 1, enabled: raw.enabled !== false, rateLimit, rules },
|
|
486
|
+
value: { v: 1, enabled: raw.enabled !== false, rateLimit, rules, ...(host ? { host } : {}) },
|
|
400
487
|
};
|
|
401
488
|
}
|
|
489
|
+
/**
|
|
490
|
+
* `host` 段。当前只认 `enabled`;P3 的自管理参数(空闲窗口、间隔分级)上线时在这里扩,
|
|
491
|
+
* **未知字段一律报错**——静默忽略会让用户以为开关生效了。
|
|
492
|
+
*/
|
|
493
|
+
function validateHostConfig(raw, errors) {
|
|
494
|
+
if (raw === undefined)
|
|
495
|
+
return undefined;
|
|
496
|
+
if (!isRecord(raw)) {
|
|
497
|
+
errors.push('host must be an object');
|
|
498
|
+
return undefined;
|
|
499
|
+
}
|
|
500
|
+
const extra = Object.keys(raw).filter(key => key !== 'enabled');
|
|
501
|
+
if (extra.length)
|
|
502
|
+
errors.push(`host has unknown fields: ${extra.join(', ')}`);
|
|
503
|
+
if (raw.enabled !== undefined && typeof raw.enabled !== 'boolean')
|
|
504
|
+
errors.push('host.enabled must be a boolean');
|
|
505
|
+
return { ...(raw.enabled !== undefined ? { enabled: raw.enabled } : {}) };
|
|
506
|
+
}
|
package/dist/stats/budget.js
CHANGED
|
@@ -72,7 +72,7 @@ export function getBudgetStatus(evolcoreHome, agentAid, peerKey) {
|
|
|
72
72
|
const dailyRemaining = Math.max(0, dailyLimit - dailyUsed);
|
|
73
73
|
const dailyPct = isFinite(dailyLimit) && dailyLimit > 0 ? (dailyUsed / dailyLimit) * 100 : 0;
|
|
74
74
|
const monthlyLimit = cfg.monthly_usd ?? Infinity;
|
|
75
|
-
const monthlyUsed =
|
|
75
|
+
const monthlyUsed = _calcMonthUsd(evolcoreHome, agentAid);
|
|
76
76
|
const monthlyRemaining = Math.max(0, monthlyLimit - monthlyUsed);
|
|
77
77
|
const monthlyPct = isFinite(monthlyLimit) && monthlyLimit > 0 ? (monthlyUsed / monthlyLimit) * 100 : 0;
|
|
78
78
|
// 取 daily/monthly 中更高的百分比作为整体判断依据
|
|
@@ -10,7 +10,7 @@ import { logger } from '../utils/logger.js';
|
|
|
10
10
|
/** 汇率合法区间:超出视为接口异常,回退默认值,避免金额被单个脏值整体扭曲。 */
|
|
11
11
|
export const MIN_USD_TO_CNY = 3;
|
|
12
12
|
export const MAX_USD_TO_CNY = 15;
|
|
13
|
-
export const DEFAULT_USD_TO_CNY = 7
|
|
13
|
+
export const DEFAULT_USD_TO_CNY = 7;
|
|
14
14
|
export function normalizeUsdToCny(raw) {
|
|
15
15
|
const n = typeof raw === 'number' ? raw : NaN;
|
|
16
16
|
return Number.isFinite(n) && n >= MIN_USD_TO_CNY && n <= MAX_USD_TO_CNY ? n : undefined;
|
|
@@ -721,7 +721,7 @@ export function resolvePrices(evolcoreHome, event, gatewayPricing) {
|
|
|
721
721
|
gatewayCost = officialCost;
|
|
722
722
|
}
|
|
723
723
|
// ── 3. 转换为统一格式 ───────────────────────────────────────────────────
|
|
724
|
-
// 计费函数按价格行币种只产出一种货币(接口价恒为 USD)。用网关汇率(usd_to_cny,缺省 7
|
|
724
|
+
// 计费函数按价格行币种只产出一种货币(接口价恒为 USD)。用网关汇率(usd_to_cny,缺省 7)
|
|
725
725
|
// 补齐另一种货币:有 usd 缺 cny → cny=usd*rate;有 cny 缺 usd → usd=cny/rate。
|
|
726
726
|
const rate = normalizeUsdToCny(gatewayPricing?.usdToCny) ?? DEFAULT_USD_TO_CNY;
|
|
727
727
|
const toPair = (c) => {
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { isValidAid } from '../aun/aid/validation.js';
|
|
3
|
+
import { agentConfig, resolveRoot } from '../paths.js';
|
|
4
|
+
import { resolveFreshPeerRoleDetail } from '../config/peer-role-resolver.js';
|
|
5
|
+
import { normalizePeerKey, parsePeerKey, readAunPeerKind } from '../core/relation/peer-identity.js';
|
|
6
|
+
import { getBudgetStatus } from './budget.js';
|
|
7
|
+
import { getRoleBudgetStatus } from './role-budget.js';
|
|
8
|
+
export class QuotaQueryError extends Error {
|
|
9
|
+
code;
|
|
10
|
+
constructor(code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Shared request parsing for CLI output, authorization intents and daemon execution. */
|
|
16
|
+
export function parseQuotaCommand(input) {
|
|
17
|
+
const args = input[0] === 'quota' ? input.slice(1) : input;
|
|
18
|
+
if (args[0] !== 'status')
|
|
19
|
+
throw new QuotaQueryError('INVALID_ARGUMENT', 'Usage: ec quota status [--self <aid>] [--peer <aid|channel#id>] [--format text|json]');
|
|
20
|
+
const values = new Map();
|
|
21
|
+
for (let i = 1; i < args.length; i++) {
|
|
22
|
+
const [flag, ...inline] = args[i].split('=');
|
|
23
|
+
if (!['--self', '--peer', '--format'].includes(flag) || values.has(flag)) {
|
|
24
|
+
throw new QuotaQueryError('INVALID_ARGUMENT', `Unknown or duplicate quota option: ${args[i]}`);
|
|
25
|
+
}
|
|
26
|
+
const value = inline.length ? inline.join('=') : args[++i];
|
|
27
|
+
if (!value?.trim() || value.startsWith('-'))
|
|
28
|
+
throw new QuotaQueryError('INVALID_ARGUMENT', `${flag} requires a value`);
|
|
29
|
+
values.set(flag, value.trim());
|
|
30
|
+
}
|
|
31
|
+
const selfAid = values.get('--self');
|
|
32
|
+
if (selfAid && !isValidAid(selfAid))
|
|
33
|
+
throw new QuotaQueryError('INVALID_SELF', '--self must be a valid Agent AID');
|
|
34
|
+
const format = values.get('--format') ?? 'text';
|
|
35
|
+
if (format !== 'text' && format !== 'json')
|
|
36
|
+
throw new QuotaQueryError('INVALID_ARGUMENT', '--format must be text or json');
|
|
37
|
+
const peer = values.get('--peer');
|
|
38
|
+
return { selfAid, peerKey: peer ? normalizeQuotaPeer(peer) : undefined, format };
|
|
39
|
+
}
|
|
40
|
+
function normalizeQuotaPeer(value) {
|
|
41
|
+
try {
|
|
42
|
+
return normalizePeerKey(value, { strict: true });
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
throw new QuotaQueryError('INVALID_PEER', '--peer must be a valid AID or channel#id');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export async function queryQuota(command, context) {
|
|
49
|
+
const selfAid = command.selfAid ?? context.selfAid;
|
|
50
|
+
if (!selfAid)
|
|
51
|
+
throw new QuotaQueryError('INVALID_SELF', 'Host terminal queries require --self <agent-aid>');
|
|
52
|
+
const sameAgent = selfAid === context.selfAid;
|
|
53
|
+
if (!sameAgent && !context.allowOtherAgent)
|
|
54
|
+
throw new QuotaQueryError('SCOPE_MISMATCH', 'Only the current Agent quota can be queried');
|
|
55
|
+
if (!fs.existsSync(agentConfig(selfAid)))
|
|
56
|
+
throw new QuotaQueryError('AGENT_NOT_FOUND', `Agent does not exist: ${selfAid}`);
|
|
57
|
+
const currentPeerKey = sameAgent && context.peerKey ? normalizeQuotaPeer(context.peerKey) : undefined;
|
|
58
|
+
const peerKey = command.peerKey ?? currentPeerKey;
|
|
59
|
+
if (!context.canReadAgent && (!peerKey || peerKey !== currentPeerKey)) {
|
|
60
|
+
throw new QuotaQueryError('NOT_ALLOWED', 'Only the current relation quota can be queried');
|
|
61
|
+
}
|
|
62
|
+
const home = resolveRoot();
|
|
63
|
+
const agentBudget = getBudgetStatus(home, selfAid);
|
|
64
|
+
let relation = null;
|
|
65
|
+
let blocked = agentBudget.hard_blocked;
|
|
66
|
+
if (peerKey) {
|
|
67
|
+
const { channelType, channelId } = parsePeerKey(peerKey);
|
|
68
|
+
const current = sameAgent && peerKey === currentPeerKey;
|
|
69
|
+
const chatType = current ? context.chatType ?? 'private' : 'private';
|
|
70
|
+
if (!current && channelType === 'aun' && readAunPeerKind(selfAid, channelId).kind === 'group') {
|
|
71
|
+
throw new QuotaQueryError('GROUP_CONTEXT_REQUIRED', 'Query a group quota from its current conversation so the member identity is known');
|
|
72
|
+
}
|
|
73
|
+
if (chatType === 'group' && !context.actorId)
|
|
74
|
+
throw new QuotaQueryError('GROUP_CONTEXT_REQUIRED', 'The current group member identity is required');
|
|
75
|
+
const actorId = current ? context.actorId || channelId : channelId;
|
|
76
|
+
const detail = await resolveFreshPeerRoleDetail({
|
|
77
|
+
selfAid, channelType, channelKey: current && context.channelKey ? context.channelKey : `${channelType}#${selfAid}#main`,
|
|
78
|
+
chatType, actorId, conversationId: channelId,
|
|
79
|
+
});
|
|
80
|
+
if (detail.authorizationFailure)
|
|
81
|
+
throw new QuotaQueryError('ROLE_UNAVAILABLE', detail.authorizationFailure.reason);
|
|
82
|
+
const roleQuota = getRoleBudgetStatus(home, { selfAid, role: detail.effectiveRole, channelType, chatType, channelId, peerId: actorId });
|
|
83
|
+
const relationBudget = getBudgetStatus(home, selfAid, peerKey);
|
|
84
|
+
blocked ||= relationBudget.hard_blocked || roleQuota.hard_blocked;
|
|
85
|
+
relation = {
|
|
86
|
+
peerKey, actorId, chatType, roleSource: detail.source, budgetUsageScope: 'agent',
|
|
87
|
+
budget: context.canReadAgent ? relationBudget : null, roleQuota,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
ok: true, selfAid,
|
|
92
|
+
agent: { visible: context.canReadAgent, budget: context.canReadAgent ? agentBudget : null },
|
|
93
|
+
relation, hard_blocked: blocked,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -41,12 +41,12 @@ export class TriggerSchedulerRegistry {
|
|
|
41
41
|
}
|
|
42
42
|
return { enabled, today: { calls, failures } };
|
|
43
43
|
}
|
|
44
|
-
async replace(agentAid, createScheduler) {
|
|
44
|
+
async replace(agentAid, createScheduler, admit) {
|
|
45
45
|
await this.schedulers.get(agentAid)?.stop();
|
|
46
46
|
const scheduler = createScheduler();
|
|
47
47
|
this.schedulers.set(agentAid, scheduler);
|
|
48
48
|
try {
|
|
49
|
-
await scheduler.init();
|
|
49
|
+
await scheduler.init(admit);
|
|
50
50
|
}
|
|
51
51
|
catch (error) {
|
|
52
52
|
logger.error(`[Trigger] Scheduler init failed for ${agentAid}: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -86,8 +86,10 @@ export class TriggerSchedulerRegistry {
|
|
|
86
86
|
await Promise.all([...this.schedulers.values()].map(scheduler => scheduler.waitForIdle(timeoutMs)));
|
|
87
87
|
}
|
|
88
88
|
async suspendForDaemonExit() {
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
// Mark all resumable runs suspended before yielding: daemon queue interruption
|
|
90
|
+
// starts as soon as this method returns its promise. Listeners may be async.
|
|
91
|
+
const suspending = [...this.schedulers.values()].map(scheduler => scheduler.suspendForDaemonExit());
|
|
92
|
+
await Promise.all([...suspending, this.notify(listener => listener.suspending?.())]);
|
|
91
93
|
}
|
|
92
94
|
}
|
|
93
95
|
export function createTriggerChannelResolver({ agentRegistry, channelInstances, daemonChannel, daemonTriggerOwner, }) {
|
|
@@ -114,6 +114,12 @@ function assertSessionRuntimeScope(candidate, runtime, errorMessage) {
|
|
|
114
114
|
throw new Error(errorMessage);
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
|
+
function sameFileIdentity(left, right) {
|
|
118
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
119
|
+
}
|
|
120
|
+
function sameFileMetadata(left, right) {
|
|
121
|
+
return left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
|
|
122
|
+
}
|
|
117
123
|
export function readManagedLocalFile(input, scope, kind) {
|
|
118
124
|
const sourceLabel = kind === 'trigger' ? 'Trigger input' : 'Attachment source';
|
|
119
125
|
const resolved = resolveManagedLocalPath(input, scope, kind);
|
|
@@ -126,16 +132,21 @@ export function readManagedLocalFile(input, scope, kind) {
|
|
|
126
132
|
const descriptor = fs.openSync(resolved, fs.constants.O_RDONLY | noFollow);
|
|
127
133
|
try {
|
|
128
134
|
const opened = fs.fstatSync(descriptor);
|
|
129
|
-
|
|
130
|
-
|
|
135
|
+
const openedPath = fs.lstatSync(resolved);
|
|
136
|
+
// Windows path and handle stats can report different dev/ino values for the
|
|
137
|
+
// same file. Compare identities within each API and metadata across APIs;
|
|
138
|
+
// retain the additional path-to-handle identity check on POSIX.
|
|
139
|
+
if (!opened.isFile() || !openedPath.isFile() || openedPath.isSymbolicLink()
|
|
140
|
+
|| !sameFileIdentity(openedPath, expected) || !sameFileMetadata(openedPath, expected)
|
|
141
|
+
|| (process.platform !== 'win32' && !sameFileIdentity(opened, expected))
|
|
142
|
+
|| !sameFileMetadata(opened, expected)
|
|
143
|
+
|| (scope && (opened.nlink !== 1 || openedPath.nlink !== 1))
|
|
131
144
|
|| resolveManagedLocalPath(input, scope, kind) !== resolved) {
|
|
132
145
|
throw new Error(`${sourceLabel} changed during validation`);
|
|
133
146
|
}
|
|
134
147
|
if (opened.size > TRIGGER_LOCAL_FILE_LIMIT) {
|
|
135
148
|
throw new Error(`${sourceLabel} exceeds the 4 MiB limit`);
|
|
136
149
|
}
|
|
137
|
-
const openedMtime = opened.mtimeMs;
|
|
138
|
-
const openedCtime = opened.ctimeMs;
|
|
139
150
|
const buffer = Buffer.alloc(Math.min(opened.size + 1, TRIGGER_LOCAL_FILE_LIMIT + 1));
|
|
140
151
|
let length = 0;
|
|
141
152
|
while (length < buffer.length) {
|
|
@@ -146,11 +157,10 @@ export function readManagedLocalFile(input, scope, kind) {
|
|
|
146
157
|
}
|
|
147
158
|
const afterRead = fs.fstatSync(descriptor);
|
|
148
159
|
const afterPath = fs.lstatSync(resolved);
|
|
149
|
-
if (length !== opened.size || afterRead.
|
|
150
|
-
|| afterRead
|
|
151
|
-
|| afterPath
|
|
152
|
-
|| !afterPath.isFile() || afterPath.isSymbolicLink()
|
|
153
|
-
|| afterPath.size !== opened.size || afterPath.mtimeMs !== openedMtime || afterPath.ctimeMs !== openedCtime
|
|
160
|
+
if (length !== opened.size || !afterRead.isFile()
|
|
161
|
+
|| !sameFileIdentity(afterRead, opened) || !sameFileMetadata(afterRead, opened)
|
|
162
|
+
|| !sameFileIdentity(afterPath, expected)
|
|
163
|
+
|| !afterPath.isFile() || afterPath.isSymbolicLink() || !sameFileMetadata(afterPath, opened)
|
|
154
164
|
|| (scope && (afterRead.nlink !== 1 || afterPath.nlink !== 1))
|
|
155
165
|
|| resolveManagedLocalPath(input, scope, kind) !== resolved) {
|
|
156
166
|
throw new Error(`${sourceLabel} changed during reading`);
|
|
@@ -84,7 +84,7 @@ export class TriggerRuntimeScheduler {
|
|
|
84
84
|
});
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
|
-
async init() {
|
|
87
|
+
async init(admit) {
|
|
88
88
|
const stopped = this.stop();
|
|
89
89
|
const generation = this.lifecycleGeneration;
|
|
90
90
|
await stopped;
|
|
@@ -95,17 +95,27 @@ export class TriggerRuntimeScheduler {
|
|
|
95
95
|
await this.audit.initializeHistory?.();
|
|
96
96
|
if (this.stopping || generation !== this.lifecycleGeneration)
|
|
97
97
|
return;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
this.
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
98
|
+
// Shared history imports must register before bounded startup admission;
|
|
99
|
+
// otherwise each queue wave scans the same global audit files again.
|
|
100
|
+
const initialize = async () => {
|
|
101
|
+
if (this.stopping || generation !== this.lifecycleGeneration)
|
|
102
|
+
return;
|
|
103
|
+
await this.recoverOpenRuns();
|
|
104
|
+
if (this.stopping || generation !== this.lifecycleGeneration)
|
|
105
|
+
return;
|
|
106
|
+
for (const definition of this.manager.list()) {
|
|
107
|
+
if (this.recoveredOneShotIds.has(definition.id))
|
|
108
|
+
continue;
|
|
109
|
+
this.schedule(definition);
|
|
110
|
+
}
|
|
111
|
+
this.recoveredOneShotIds.clear();
|
|
112
|
+
this.initialized = true;
|
|
113
|
+
logger.info(`[Trigger] scheduler initialized for ${this.manager.agentAid}`);
|
|
114
|
+
};
|
|
115
|
+
if (admit)
|
|
116
|
+
await admit(initialize);
|
|
117
|
+
else
|
|
118
|
+
await initialize();
|
|
109
119
|
}
|
|
110
120
|
async stop() {
|
|
111
121
|
this.lifecycleGeneration++;
|
|
@@ -193,6 +193,8 @@ export async function buildTriggerScriptLaunch(input) {
|
|
|
193
193
|
process.execPath,
|
|
194
194
|
path.dirname(process.execPath),
|
|
195
195
|
snapshotDir,
|
|
196
|
+
// 服务常驻宿主:包脚本快照根(只读)。不传时这里是空数组,行为不变。
|
|
197
|
+
...(input.extraReadRoots ?? []),
|
|
196
198
|
].filter(value => fs.existsSync(value));
|
|
197
199
|
const entries = [
|
|
198
200
|
{ path: { type: 'special', value: { kind: 'root' } },
|
|
@@ -201,7 +203,16 @@ export async function buildTriggerScriptLaunch(input) {
|
|
|
201
203
|
filesystemEntry(projectPath, readonly ? 'read' : 'write'),
|
|
202
204
|
filesystemEntry(snapshotDir, 'read'),
|
|
203
205
|
filesystemEntry(workDir, 'write'),
|
|
206
|
+
// 额外可写根(服务宿主的工作目录)。不存在时 `filesystemEntry` 仍是合法条目,
|
|
207
|
+
// 但策略里指向不存在的路径不会生效,所以调用方必须先建好目录。
|
|
208
|
+
...(input.extraWriteRoots ?? []).map(value => filesystemEntry(value, 'write')),
|
|
204
209
|
filesystemEntry(windowsBackend.home, 'deny'),
|
|
210
|
+
// 这里不再为 `services` 单独追加条目。`services` 已由
|
|
211
|
+
// `getExistingLClassReadOnlyTargets` 纳入 L 类只读目标,win32 下写保护由
|
|
212
|
+
// 「没有任何条目授 write」+ ACL 的 DENY(写) 共同承担(见
|
|
213
|
+
// src/core/permission/services-path-acl.ts)。原先那条按
|
|
214
|
+
// `trigger.labels.kind === 'services'` 分流的 read 条目是空操作:实测有它无它,
|
|
215
|
+
// 服务脚本对 services 树的 list / read / write 结果完全相同。
|
|
205
216
|
...Object.entries(filesystem).flatMap(([value, access]) => typeof access === 'number' ? [] : [{
|
|
206
217
|
path: /[*?[\]]/.test(value)
|
|
207
218
|
? { type: 'glob_pattern', pattern: value }
|
|
@@ -236,7 +247,7 @@ export async function buildTriggerScriptLaunch(input) {
|
|
|
236
247
|
env: { ...env, CODEX_HOME: windowsBackend.home },
|
|
237
248
|
cleanup,
|
|
238
249
|
};
|
|
239
|
-
launch.prepare = signal => verifyWindowsReadIsolation(launch, sandboxArgs, runDir, workDir, signal);
|
|
250
|
+
launch.prepare = signal => verifyWindowsReadIsolation(launch, sandboxArgs, runDir, workDir, signal, input.verifyGrandchild === true);
|
|
240
251
|
return launch;
|
|
241
252
|
}
|
|
242
253
|
const launch = sandboxDecision.state === 'off'
|
|
@@ -254,7 +265,14 @@ export async function buildTriggerScriptLaunch(input) {
|
|
|
254
265
|
const separator = launch.args.indexOf('--');
|
|
255
266
|
if (separator < 0)
|
|
256
267
|
throw new Error('bubblewrap launch is missing its command separator');
|
|
257
|
-
const runMountArgs = [
|
|
268
|
+
const runMountArgs = [
|
|
269
|
+
'--ro-bind', runDir, runDir,
|
|
270
|
+
'--bind', workDir, workDir,
|
|
271
|
+
...(input.extraWriteRoots ?? []).flatMap(root => ['--bind', root, root]),
|
|
272
|
+
// 额外只读根(服务宿主的包脚本快照根)。bwrap 里**没有挂载就等于不存在**,
|
|
273
|
+
// 与 Windows 侧的 read 策略条目是同一件事的两平台写法,必须成对出现。
|
|
274
|
+
...(input.extraReadRoots ?? []).flatMap(root => ['--ro-bind', root, root]),
|
|
275
|
+
];
|
|
258
276
|
if (!launch.args.slice(0, separator).includes('--chdir'))
|
|
259
277
|
runMountArgs.push('--chdir', projectPath);
|
|
260
278
|
launch.args.splice(separator, 0, ...runMountArgs);
|
|
@@ -363,7 +381,7 @@ function assertRealDirectory(value, label) {
|
|
|
363
381
|
function samePath(left, right) {
|
|
364
382
|
return isSameOrDescendant(left, right) && isSameOrDescendant(right, left);
|
|
365
383
|
}
|
|
366
|
-
function readScriptSnapshot(value, triggerDir) {
|
|
384
|
+
export function readScriptSnapshot(value, triggerDir) {
|
|
367
385
|
const scriptPath = path.resolve(value);
|
|
368
386
|
const validate = () => {
|
|
369
387
|
if (!isSameOrDescendant(scriptPath, triggerDir))
|
|
@@ -427,7 +445,7 @@ const SCRIPT_STAGING_FILE_COUNT = 2_000;
|
|
|
427
445
|
* `preserveNodeModuleType` 统一合成,避免 `wx` 冲突)。每个文件走与入口相同的
|
|
428
446
|
* lstat/fd 校验(防 TOCTOU/软链),越界文件直接抛错走沙箱不可用降级。
|
|
429
447
|
*/
|
|
430
|
-
function stageScriptSnapshot(scriptSource, triggerDir, scriptBytes, snapshotDir) {
|
|
448
|
+
export function stageScriptSnapshot(scriptSource, triggerDir, scriptBytes, snapshotDir) {
|
|
431
449
|
const scriptName = path.basename(scriptSource);
|
|
432
450
|
const scriptPath = path.join(snapshotDir, scriptName);
|
|
433
451
|
fs.writeFileSync(scriptPath, scriptBytes, { flag: 'wx', mode: 0o400 });
|
|
@@ -465,7 +483,7 @@ function stageScriptSnapshot(scriptSource, triggerDir, scriptBytes, snapshotDir)
|
|
|
465
483
|
stage(scriptDir, '');
|
|
466
484
|
return scriptPath;
|
|
467
485
|
}
|
|
468
|
-
function preserveNodeModuleType(runtime, scriptPath, snapshotDir) {
|
|
486
|
+
export function preserveNodeModuleType(runtime, scriptPath, snapshotDir) {
|
|
469
487
|
if (!/^node(?:\.exe)?$/i.test(path.basename(runtime)) || path.extname(scriptPath) !== '.js')
|
|
470
488
|
return;
|
|
471
489
|
let current = path.dirname(scriptPath);
|
|
@@ -525,7 +543,7 @@ function filesystemEntry(value, access) {
|
|
|
525
543
|
* (证明 deny 真的被沙箱执行;这一步失败说明沙箱没起效,必须拒跑)
|
|
526
544
|
* 3. 在 workDir 写文件 → 必须成功(证明 scoped 路径没有把整个文件系统锁死)
|
|
527
545
|
*/
|
|
528
|
-
async function verifyWindowsReadIsolation(launch, sandboxArgs, runDir, workDir, signal) {
|
|
546
|
+
async function verifyWindowsReadIsolation(launch, sandboxArgs, runDir, workDir, signal, verifyGrandchild = false) {
|
|
529
547
|
signal?.throwIfAborted();
|
|
530
548
|
const canary = path.join(runDir, 'read-isolation-canary');
|
|
531
549
|
const writableProbe = path.join(workDir, 'write-isolation-probe');
|
|
@@ -546,6 +564,30 @@ async function verifyWindowsReadIsolation(launch, sandboxArgs, runDir, workDir,
|
|
|
546
564
|
'fs.writeFileSync(process.argv[2], "allowed");',
|
|
547
565
|
'process.stdout.write("evolcore-trigger-sandbox-ready");',
|
|
548
566
|
].join('\n');
|
|
567
|
+
// 孙进程版:沙箱内的这个 node 再 spawn 一个 node,由**后者**去读 deny 路径。
|
|
568
|
+
// 服务宿主正是这个形状(宿主 → 脚本次进程),直接子进程被拦不能证明孙进程也被拦。
|
|
569
|
+
const grandchildDenyProbe = [
|
|
570
|
+
'const { spawn } = require("node:child_process");',
|
|
571
|
+
'const inner = [',
|
|
572
|
+
' "const fs = require(\\"node:fs\\");",',
|
|
573
|
+
' "let denied = false;",',
|
|
574
|
+
' "try { fs.readFileSync(process.argv[1]); } catch (e) {",',
|
|
575
|
+
' "if (e.code === \\"EACCES\\" || e.code === \\"EPERM\\" || e.code === \\"ENOENT\\") denied = true; else throw e;",',
|
|
576
|
+
' "}",',
|
|
577
|
+
' "process.stdout.write(denied ? \\"denied\\" : \\"readable\\");",',
|
|
578
|
+
'].join("\\n");',
|
|
579
|
+
'const child = spawn(process.execPath, ["-e", inner, process.argv[1]], { stdio: ["ignore", "pipe", "inherit"] });',
|
|
580
|
+
'let out = "";',
|
|
581
|
+
'child.stdout.on("data", b => { out += b.toString(); });',
|
|
582
|
+
'child.on("close", code => {',
|
|
583
|
+
' if (code !== 0) { process.stderr.write("grandchild probe exited " + code); process.exit(92); }',
|
|
584
|
+
' if (out.trim() !== "denied") {',
|
|
585
|
+
' process.stderr.write("grandchild escaped the sandbox: denied path was readable from a grandchild process");',
|
|
586
|
+
' process.exit(90);',
|
|
587
|
+
' }',
|
|
588
|
+
' process.stdout.write("evolcore-trigger-sandbox-ready");',
|
|
589
|
+
'});',
|
|
590
|
+
].join('\n');
|
|
549
591
|
const withExtraEntry = (extra) => {
|
|
550
592
|
const args = [...sandboxArgs];
|
|
551
593
|
const stateIndex = args.indexOf('--sandbox-state-json') + 1;
|
|
@@ -558,10 +600,11 @@ async function verifyWindowsReadIsolation(launch, sandboxArgs, runDir, workDir,
|
|
|
558
600
|
};
|
|
559
601
|
try {
|
|
560
602
|
await runWindowsIsolationProbe(launch, withExtraEntry(filesystemEntry(canary, 'read')), readProbe, [canary], signal);
|
|
561
|
-
await runWindowsIsolationProbe(launch, withExtraEntry(filesystemEntry(canary, 'deny')), denyProbe, [canary, writableProbe], signal);
|
|
603
|
+
await runWindowsIsolationProbe(launch, withExtraEntry(filesystemEntry(canary, 'deny')), verifyGrandchild ? grandchildDenyProbe : denyProbe, verifyGrandchild ? [canary] : [canary, writableProbe], signal);
|
|
562
604
|
}
|
|
563
605
|
catch (error) {
|
|
564
|
-
throw new Error(`Windows sandbox cannot prove scoped read isolation
|
|
606
|
+
throw new Error(`Windows sandbox cannot prove scoped read isolation${verifyGrandchild ? ' (including grandchild processes)' : ''}; `
|
|
607
|
+
+ `scoped execution is refused: ${error?.message || String(error)}`, { cause: error });
|
|
565
608
|
}
|
|
566
609
|
finally {
|
|
567
610
|
try {
|
package/dist/utils/aid-bind.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomBytes, randomUUID, timingSafeEqual, createHash } from 'crypto';
|
|
2
|
+
import os from 'node:os';
|
|
2
3
|
import { loadAgent } from '../config-store.js';
|
|
3
4
|
import { isValidAid } from '../aun/aid/validation.js';
|
|
4
5
|
import { ownerResolver } from '../core/ownership/owner-resolver.js';
|
|
@@ -42,6 +43,8 @@ export class BindService {
|
|
|
42
43
|
return { ok: true, taskId: session.id, expiresAt: session.expiresAt, qrData: {
|
|
43
44
|
type: 'evolcore.bind', version: readInstalledEvolcoreVersion(),
|
|
44
45
|
platform: process.platform === 'win32' ? 'windows' : process.platform,
|
|
46
|
+
// 机器名随二维码带给 App:主机列表的默认显示名要用它,而不是 agent 的名字。
|
|
47
|
+
hostName: os.hostname(),
|
|
45
48
|
bindType: session.bindType, subjectAid, receiverAid: this.options.receiverAid,
|
|
46
49
|
token: session.token, expiresAt: session.expiresAt,
|
|
47
50
|
} };
|
|
@@ -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));
|