evolcore 0.0.50 → 0.0.51
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 +39 -2
- package/bin/ec-build.mjs +60 -0
- package/bin/ecmsg.js +65 -63
- package/dist/ability/caller/command.js +24 -15
- package/dist/ability/caller/contract.js +24 -9
- package/dist/ability/caller/credential-files.js +132 -0
- package/dist/ability/caller/daemon.js +32 -7
- package/dist/ability/caller/schema-view.js +157 -0
- package/dist/ability/caller/service.js +202 -63
- package/dist/ability/interop-v1.js +156 -113
- package/dist/agent-template/jobs.js +14 -110
- package/dist/agent-template/runtime.js +331 -193
- package/dist/agent-template/service.js +1029 -1104
- package/dist/agent-template/share.js +103 -0
- package/dist/agent-template/tool-runner.js +25 -0
- package/dist/agent-template/types.js +10 -3
- package/dist/agents/claude/availability.js +94 -0
- package/dist/agents/claude/capability-provider.js +154 -0
- package/dist/agents/claude/index.js +145 -0
- package/dist/agents/{claude-runner.js → claude/runner.js} +74 -158
- package/dist/agents/claude/session-file-adapter.js +246 -0
- package/dist/agents/codex/app-server-client.js +90 -10
- package/dist/agents/codex/availability.js +164 -0
- package/dist/agents/codex/capability-provider.js +138 -0
- package/dist/agents/codex/cli.js +38 -0
- package/dist/agents/codex/index.js +345 -0
- package/dist/agents/codex/mcp-elicitation.js +135 -0
- package/dist/agents/{codex-runner.js → codex/runner.js} +648 -382
- package/dist/agents/codex/session-file-adapter.js +834 -0
- package/dist/agents/dsh/availability.js +28 -0
- package/dist/agents/dsh/capability-provider.js +56 -0
- package/dist/agents/dsh/desktop-locations.ps1 +66 -0
- package/dist/agents/dsh/desktop-probe.cjs +37 -0
- package/dist/agents/dsh/index.js +98 -0
- package/dist/agents/dsh/installation.js +400 -0
- package/dist/agents/dsh/resources.js +755 -0
- package/dist/agents/dsh/runner.js +1183 -0
- package/dist/agents/dsh/runtime/README.md +243 -0
- package/dist/agents/dsh/runtime/authorization.js +23 -0
- package/dist/agents/dsh/runtime/bridge.js +837 -0
- package/dist/agents/dsh/runtime/config.js +271 -0
- package/dist/agents/dsh/runtime/entry.js +229 -0
- package/dist/agents/dsh/runtime/session-inspector.js +340 -0
- package/dist/agents/dsh/runtime/tool-policy.js +49 -0
- package/dist/agents/dsh/session-file-adapter.js +145 -0
- package/dist/agents/ecagent/index.js +215 -0
- package/dist/agents/{ecagent-runner.js → ecagent/runner.js} +592 -106
- package/dist/agents/ecagent/session-file-adapter.js +134 -0
- package/dist/agents/gemini/index.js +55 -10
- package/dist/agents/gemini/{gemini-runner.js → runner.js} +4 -9
- package/dist/aun/ability-device-routing.js +11 -17
- package/dist/aun/aid/agentmd.js +27 -1
- package/dist/aun/aid/managed-operation.js +6 -4
- package/dist/aun/group/invite-service.js +1 -1
- package/dist/aun/menu/client.js +1 -1
- package/dist/aun/msg/history.js +1 -1
- package/dist/aun/msg/managed-operation.js +93 -21
- package/dist/aun/msg/p2p.js +6 -6
- package/dist/aun/service-proxy.js +1 -1
- package/dist/aun/storage/index.js +242 -0
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +180 -43
- package/dist/channels/daemon.js +3 -2
- package/dist/channels/dingtalk.js +1 -1
- package/dist/channels/feishu.js +9 -9
- package/dist/channels/qqbot.js +1 -1
- package/dist/channels/wechat.js +2 -2
- package/dist/channels/wecom.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/agent-registration.js +13 -13
- package/dist/{agents/claude-gateway → claude-gateway}/binding.js +3 -3
- package/dist/{agents/claude-gateway → claude-gateway}/inbox.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/index.js +2 -2
- package/dist/{agents/claude-gateway → claude-gateway}/listing.js +3 -3
- package/dist/{agents/claude-gateway → claude-gateway}/router.js +4 -4
- package/dist/{agents/claude-gateway → claude-gateway}/sessions.js +2 -2
- package/dist/{agents/claude-gateway → claude-gateway}/terminal.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/transcript.js +1 -1
- package/dist/cli/ability-command.js +8 -5
- package/dist/cli/ability-output.js +182 -0
- package/dist/cli/agent-command.js +1 -1
- package/dist/cli/agent-create.js +123 -42
- package/dist/cli/agent-template.js +400 -29
- package/dist/cli/agent.js +14 -11
- package/dist/cli/aun-commands.js +167 -111
- package/dist/cli/daemon-commands.js +38 -8
- package/dist/cli/data-command.js +1 -1
- package/dist/cli/debug-mode.js +9 -0
- package/dist/cli/directory.js +1 -2
- package/dist/cli/ecmsg-gateway.js +55 -19
- package/dist/cli/fs-command.js +67 -39
- package/dist/cli/index.js +25 -11
- package/dist/cli/init.js +124 -29
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +1 -1
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/services-command.js +24 -1
- package/dist/cli/skill-command.js +4 -4
- package/dist/cli/task-context.js +24 -14
- package/dist/cli/team-workspace-command.js +50 -52
- package/dist/cli/thread-command.js +3 -2
- package/dist/cli/trigger-command.js +47 -12
- package/dist/cli/watch-logs.js +2 -1
- package/dist/config/boot-log.js +3 -0
- package/dist/config/builtin-role-templates.js +1 -1
- package/dist/config/config-field-policy.js +10 -6
- package/dist/config/config-manager.js +33 -12
- package/dist/config/gateway-config.js +21 -37
- package/dist/config/invoke-ipc-service.js +1 -1
- package/dist/config/owner-config.js +5 -3
- package/dist/config/peer-book-store.js +2 -3
- package/dist/config/peer-book.js +2 -2
- package/dist/config/peer-role-resolver.js +2 -2
- package/dist/config/provider-identity-migration.js +24 -105
- package/dist/config/provider-ipc-service.js +13 -3
- package/dist/config/provider-local-sync.js +4 -1
- package/dist/config/provider-menu-request.js +21 -3
- package/dist/config/provider-templates.js +1 -1
- package/dist/config/providers-config.js +39 -15
- package/dist/config/providers-import.js +3 -3
- package/dist/config/providers-management.js +74 -99
- package/dist/config/schema-migration.js +177 -11
- package/dist/config/schema-registry.js +1 -1
- package/dist/config-store.js +38 -50
- package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +9 -9
- package/dist/core/{agent-create-status.js → agent/agent-create-status.js} +112 -4
- package/dist/core/{agent-creation-claim.js → agent/agent-creation-claim.js} +3 -3
- package/dist/core/{agent-ipc-registration.js → agent/agent-ipc-registration.js} +102 -25
- package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +61 -1
- package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +53 -27
- package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +12 -12
- package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
- package/dist/core/auth/agent-delegation.js +1 -8
- package/dist/core/auth/delegation-authorization.js +28 -0
- package/dist/core/auth/operation-authorizer.js +7 -4
- package/dist/core/auth/operation-catalog.js +34 -5
- package/dist/core/baseagent/baseagent-availability.js +197 -0
- package/dist/core/baseagent/baseagent-capability-adapter.js +288 -0
- package/dist/core/baseagent/baseagent-config-shared.js +56 -0
- package/dist/core/baseagent/baseagent-identity.js +68 -0
- package/dist/core/{baseagent-loader.js → baseagent/baseagent-loader.js} +62 -6
- package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
- package/dist/{agents → core/baseagent}/baseagent-plugin-descriptor.js +107 -24
- package/dist/core/baseagent/baseagent-plugin-loader.js +367 -0
- package/dist/core/baseagent/baseagent.js +157 -0
- package/dist/{agents → core/baseagent}/runner-types.js +36 -4
- package/dist/core/capability/capability-manager.js +79 -30
- package/dist/core/capability/providers/claude-capability-provider.js +2 -154
- package/dist/core/capability/providers/codex-capability-provider.js +2 -136
- package/dist/core/{channel-loader.js → channel/channel-loader.js} +226 -38
- package/dist/core/{channel-runtime.js → channel/channel-runtime.js} +18 -18
- package/dist/core/command/agent-control.js +60 -15
- package/dist/core/command/agent-template-menu.js +21 -9
- package/dist/core/command/agentmd-menu-request.js +19 -8
- package/dist/core/command/agentmd-menu.js +14 -5
- package/dist/core/command/command-handler.js +127 -57
- package/dist/core/command/context-policy-menu.js +122 -0
- package/dist/core/command/data-root-resolver.js +157 -20
- package/dist/core/command/memory-slash.js +6 -6
- package/dist/core/command/menu-catalog.js +80 -20
- package/dist/core/command/menu-handler.js +305 -25
- package/dist/core/command/menu-protocol.js +42 -8
- package/dist/core/command/menu-query-batch.js +9 -5
- package/dist/core/command/provider-menu.js +7 -11
- package/dist/core/command/role-menu.js +1 -1
- package/dist/core/command/skill-slash.js +17 -5
- package/dist/core/command/slash-gate.js +2 -4
- package/dist/core/command/slash-handler.js +127 -96
- package/dist/core/command/team-workspace-team.js +3 -3
- package/dist/core/command/topic-slash.js +10 -10
- package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -14
- package/dist/core/{daemon-control.js → daemon/daemon-control.js} +46 -20
- package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +15 -15
- package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +3 -3
- package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +98 -38
- package/dist/core/{lifecycle-notice.js → daemon/lifecycle-notice.js} +4 -5
- package/dist/core/file-integrity/store.js +1 -1
- package/dist/core/handoff/ipc-registration.js +3 -3
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/{agents → core/inference}/request-identity.js +2 -2
- package/dist/core/inference/text-inference.js +4 -4
- package/dist/core/{bootstrap-messages.js → initialization/bootstrap-messages.js} +10 -10
- package/dist/core/{bootstrap-service.js → initialization/bootstrap-service.js} +24 -23
- package/dist/core/initialization/service.js +54 -9
- package/dist/core/invoke/executors/media.js +1 -1
- package/dist/core/invoke/executors/text.js +1 -1
- package/dist/core/memory/consolidation-context.js +1 -1
- package/dist/core/memory/consolidation-trigger.js +9 -3
- package/dist/core/memory/consolidation.js +4 -4
- package/dist/core/memory/memory-admin.js +6 -6
- package/dist/core/memory/memory-writer.js +1 -1
- package/dist/core/memory/relation-idle-monitor.js +1 -1
- package/dist/core/message/aun-ipc-sender.js +114 -75
- package/dist/core/message/aun-request-registry.js +13 -5
- package/dist/core/message/auto-mention-gate.js +1 -1
- package/dist/core/message/contact-admission.js +1 -1
- package/dist/core/message/im-renderer.js +19 -0
- package/dist/core/{interaction-router.js → message/interaction-router.js} +4 -4
- package/dist/core/message/items-formatter.js +5 -5
- package/dist/core/message/message-admission.js +1 -1
- package/dist/core/message/message-bridge.js +135 -54
- package/dist/core/message/message-queue.js +83 -4
- package/dist/core/message/message-utils.js +1 -1
- package/dist/core/message/peer-mode.js +1 -1
- package/dist/core/message/response-engine.js +347 -163
- package/dist/core/message/send-options.js +9 -6
- package/dist/core/message/send-routing.js +45 -109
- package/dist/core/message/stream-idle-monitor.js +1 -1
- package/dist/core/{data-migration.js → migration/data-migration.js} +29 -1
- package/dist/core/model/catalog-service.js +29 -8
- package/dist/core/model/model-capabilities.js +88 -0
- package/dist/core/model/model-catalog.js +14 -3
- package/dist/core/model/model-diagnostics.js +4 -4
- package/dist/core/ownership/owner-resolver.js +95 -15
- package/dist/core/{pack-auth.js → pack/pack-auth.js} +30 -3
- package/dist/core/{pack-install.js → pack/pack-install.js} +95 -17
- package/dist/core/permission/approval-gateway.js +9 -18
- package/dist/core/permission/ec-command-parser.js +70 -34
- package/dist/core/permission/managed-file.js +234 -0
- package/dist/core/permission/protected-paths.js +56 -0
- package/dist/core/permission/sandbox-runtime.js +267 -3
- package/dist/core/permission/session-path-grants.js +1 -1
- package/dist/core/permission/shell-environment.js +15 -1
- package/dist/core/plugin/plugin-lifecycle.js +442 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +2 -246
- package/dist/core/session/adapters/codex-session-file-adapter.js +2 -566
- package/dist/core/session/adapters/ecagent-session-file-adapter.js +2 -134
- package/dist/core/{background-session → session/background}/session-cleanup.js +2 -2
- package/dist/core/{background-session → session/background}/types.js +1 -1
- package/dist/core/session/session-file-health.js +2 -272
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +29 -2
- package/dist/core/session/session-terminal.js +185 -0
- package/dist/core/session/session-title.js +8 -11
- package/dist/core/{system-session → session/system}/memory.js +43 -9
- package/dist/core/{system-session → session/system}/registry.js +1 -1
- package/dist/core/{system-session → session/system}/types.js +1 -1
- package/dist/core/skill/index-generator.js +1 -0
- package/dist/core/task/task-activity-store.js +112 -0
- package/dist/core/task/task-recovery-service.js +2 -2
- package/dist/core/thread/ipc-operation.js +2 -2
- package/dist/core/thread/thread-operation.js +2 -1
- package/dist/core/thread/thread-route.js +5 -3
- package/dist/core/thread/thread-service.js +14 -4
- package/dist/directory/{owner-directory-admission.js → admission.js} +3 -3
- package/dist/directory/{owner-directory-cache.js → cache.js} +90 -8
- package/dist/directory/{owner-directory-markdown.js → markdown.js} +2 -2
- package/dist/directory/{owner-directory-query-operation.js → query-operation.js} +83 -9
- package/dist/directory/{owner-directory-search.js → search.js} +50 -2
- package/dist/directory/{owner-directory-store.js → store.js} +2 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/manifest-engine.js +64 -2
- package/dist/eck/message-renderer.js +35 -0
- package/dist/ecweb/basic-settings-service.js +9 -3
- package/dist/{contracts → ecweb/contracts}/ecweb-service-protocol.js +2 -1
- package/dist/ecweb/dsh-native-service.js +413 -0
- package/dist/ecweb/providers-service.js +1 -1
- package/dist/ecweb/runtime/lifecycle.js +1 -1
- package/dist/ecweb/runtime/supervisor.js +1 -1
- package/dist/event-center/center-config.js +2 -2
- package/dist/event-center/dispatcher.js +1 -1
- package/dist/event-center/ipc-operation.js +12 -3
- package/dist/event-center/pack-loader.js +2 -2
- package/dist/event-center/registry.js +6 -6
- package/dist/event-center/runtime.js +2 -2
- package/dist/index.js +71 -42
- package/dist/ipc.js +103 -10
- package/dist/outputs/authorization.js +27 -0
- package/dist/outputs/events.js +10 -1
- package/dist/outputs/panel-cards.js +960 -0
- package/dist/paths.js +12 -0
- package/dist/pay/command.js +1 -1
- package/dist/pay/runtime.js +18 -10
- package/dist/response-system/engines/v1/proactive-flow.js +1 -1
- package/dist/services/dispatcher.js +2 -2
- package/dist/services/host/main.js +10 -1
- package/dist/services/host/protocol.js +9 -2
- package/dist/services/host/resident.js +37 -0
- package/dist/services/host-client.js +12 -0
- package/dist/services/host-recycle.js +8 -3
- package/dist/services/host-runtime.js +54 -15
- package/dist/services/index.js +83 -19
- package/dist/services/ipc-operation.js +303 -38
- package/dist/services/pack-manager.js +2 -2
- package/dist/services/router.js +43 -3
- package/dist/services/script-runner.js +34 -25
- package/dist/services/service-payload.js +28 -1
- package/dist/services/validation.js +28 -2
- package/dist/stats/context-usage.js +110 -0
- package/dist/stats/model-resolver.js +103 -17
- package/dist/stats/query.js +5 -0
- package/dist/trigger/application-service.js +3 -2
- package/dist/trigger/authorization.js +36 -33
- package/dist/trigger/ipc-service.js +4 -4
- package/dist/trigger/local-files.js +8 -176
- package/dist/trigger/manager.js +2 -2
- package/dist/trigger/parser.js +48 -0
- package/dist/trigger/scheduler.js +14 -2
- package/dist/trigger/script-executor.js +21 -0
- package/dist/trigger/script-sandbox.js +57 -243
- package/dist/trigger/system-definitions.js +25 -0
- package/dist/trigger/validation.js +1 -1
- package/dist/utils/atomic-write.js +88 -1
- package/dist/utils/cross-platform.js +4 -42
- package/dist/utils/error-dict.json +22 -1
- package/dist/utils/error-utils.js +193 -6
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +1 -1
- package/dist/utils/logger.js +3 -1
- package/dist/utils/media-cache.js +99 -4
- package/dist/utils/startup-trace.js +20 -4
- package/dist/utils/welcome.js +64 -20
- package/ecagent/README.md +35 -0
- package/ecagent/dist/agent-loop.js +80 -30
- package/ecagent/dist/harness/env/nodejs.d.ts +16 -0
- package/ecagent/dist/harness/env/nodejs.js +49 -20
- package/ecagent/dist/harness/messages.js +3 -2
- package/ecagent/dist/harness/types.d.ts +1 -0
- package/ecagent/dist/runtime/types.d.ts +2 -0
- package/ecagent/dist/runtime/utils/validation.d.ts +7 -1
- package/ecagent/dist/runtime/utils/validation.js +42 -0
- package/ecagent/dist/types.d.ts +2 -0
- package/kits/docs/INDEX.md +1 -1
- package/kits/docs/channels/feishu.md +1 -1
- package/kits/docs/evolcore/INDEX.md +10 -7
- package/kits/docs/evolcore/agent-create.md +2 -0
- package/kits/docs/evolcore/agent.md +100 -13
- package/kits/docs/evolcore/aid.md +19 -3
- package/kits/docs/evolcore/config.md +94 -0
- package/kits/docs/evolcore/ctl.md +2 -1
- package/kits/docs/evolcore/ec-capabilities.md +7 -10
- package/kits/docs/evolcore/ecweb-lifecycle.md +5 -1
- package/kits/docs/evolcore/event.md +1 -1
- package/kits/docs/evolcore/fs.md +49 -3
- package/kits/docs/evolcore/group.md +3 -3
- package/kits/docs/evolcore/memory-consolidation.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +24 -2
- package/kits/docs/evolcore/model.md +9 -1
- package/kits/docs/evolcore/msg.md +30 -28
- package/kits/docs/evolcore/pay.md +8 -20
- package/kits/docs/evolcore/plugin.md +74 -0
- package/kits/docs/evolcore/provider.md +8 -2
- package/kits/docs/evolcore/rpc.md +2 -2
- package/kits/docs/evolcore/skill.md +17 -1
- package/kits/docs/evolcore/stats.md +5 -0
- package/kits/docs/evolcore/storage.md +22 -0
- package/kits/docs/evolcore/thread-chain.md +19 -10
- package/kits/docs/evolcore/tool-authorization.md +4 -0
- package/kits/docs/evolcore/trigger.md +89 -13
- package/kits/docs/identity/AID_PROFILE_SPEC.md +1 -1
- package/kits/docs/venues/feishu-group.md +3 -2
- package/kits/docs/venues/feishu-private.md +3 -2
- package/kits/rules/02-navigation.md +20 -13
- package/kits/rules/06-channel.md +18 -2
- package/kits/schemas/_meta.json +8 -4
- package/kits/schemas/agent-config.schema.23.json +19 -3
- package/kits/schemas/agent-config.schema.24.json +986 -0
- package/kits/schemas/agent-config.schema.25.json +986 -0
- package/kits/schemas/daemon.schema.11.json +487 -0
- package/kits/schemas/daemon.schema.12.json +505 -0
- package/kits/schemas/defaults.schema.8.json +484 -0
- package/kits/schemas/providers.schema.1.json +1 -1
- package/kits/schemas/providers.schema.2.json +1 -1
- package/kits/schemas/providers.schema.3.json +8 -2
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ability/SKILL.md +194 -27
- package/kits/skills/ability/STRUCTURE.md +5 -0
- package/kits/skills/agent-output-cards/SKILL.md +90 -54
- package/kits/skills/agent-output-cards/examples/html-surface.json +11 -0
- package/kits/skills/agent-output-cards/examples/meeting-followups.json +16 -0
- package/kits/skills/agent-output-cards/examples/meeting-latest.json +24 -0
- package/kits/skills/agent-output-cards/examples/project-metrics.json +16 -0
- package/kits/skills/agent-output-cards/examples/quick-links.json +18 -0
- package/kits/skills/agent-output-cards/examples/surface.html +8 -0
- package/kits/skills/agent-template-project/SKILL.md +51 -0
- package/kits/skills/agent-template-project/references/01-collect-and-pack.md +174 -0
- package/kits/skills/agent-template-project/references/02-upload-and-share.md +109 -0
- package/kits/skills/agent-template-project/references/03-download-and-install.md +189 -0
- package/kits/skills/agent-template-project/references/04-upgrade-and-recovery.md +74 -0
- package/kits/skills/agent-template-project/references/05-publish-to-platform.md +62 -0
- package/kits/skills/ec-group/SKILL.md +3 -3
- package/kits/skills/ec-group-collaboration/SKILL.md +4 -4
- package/kits/skills/ec-identity/SKILL.md +9 -6
- package/kits/skills/ec-pay/SKILL.md +163 -41
- package/kits/skills/ec-provider/SKILL.md +5 -5
- package/kits/skills/ec-service-call/SKILL.md +3 -0
- package/kits/skills/ec-skill/SKILL.md +25 -9
- package/kits/skills/ec-skill/scripts/cli.mjs +7 -7
- package/kits/skills/ec-skill/scripts/skill.mjs +55 -41
- package/kits/skills/ec-skill/scripts/template/SKILL.md.tmpl +9 -0
- package/kits/skills/ec-trigger/SKILL.md +2 -2
- package/kits/skills/personal-assistant/SKILL.md +22 -22
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +1 -1
- package/kits/skills/scrapling-article-fetch/SKILL.md +5 -5
- package/kits/skills/thread-ops/SKILL.md +19 -9
- package/kits/skills/wechat-article-media-download/SKILL.md +2 -2
- package/kits/skills/wechat-article-reader/SKILL.md +2 -2
- package/kits/templates/system-fragments/commands.md +1 -1
- package/kits/templates/system-fragments/personal-assistant.md +2 -2
- package/kits/templates/system-fragments/reply.md +14 -9
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +10 -5
- package/package.json +6 -5
- package/scripts/agent-template/index.mjs +7 -1
- package/scripts/agent-template/inspect.mjs +81 -35
- package/scripts/agent-template/overlay.mjs +110 -4
- package/scripts/agent-template/shared/common.mjs +36 -4
- package/scripts/agent-template/shared/plan.mjs +4 -2
- package/scripts/agent-template/shared/service-packs.mjs +104 -0
- package/scripts/agent-template/shared/team-schema.json +467 -54
- package/scripts/agent-template/shared/template-contract.mjs +70 -68
- package/scripts/agent-template/shared/template-package.mjs +153 -36
- package/scripts/agent-template/shared/template-runtime.mjs +76 -64
- package/scripts/agent-template/shared/template.mjs +11 -46
- package/scripts/agent-template/team-pack.mjs +451 -35
- package/scripts/agent-template/team-preview.mjs +75 -226
- package/scripts/aid-batch/identity-batch.mjs +1 -1
- package/dist/agents/baseagent-availability.js +0 -176
- package/dist/agents/baseagent-capability-adapter.js +0 -102
- package/dist/agents/baseagent-plugin-loader.js +0 -145
- package/dist/agents/baseagent.js +0 -816
- package/dist/agents/codex/catalog.js +0 -80
- package/dist/agents/ecagent-plugin-lazy.js +0 -41
- package/dist/agents/tool-time-context.js +0 -55
- package/dist/core/legacy-rename.js +0 -41
- package/dist/core/plugin-lifecycle.js +0 -137
- package/dist/core/rate-window.js +0 -53
- package/dist/core/runner-reload-transaction.js +0 -60
- package/dist/core/runtime-lock.js +0 -90
- package/dist/core/soul.js +0 -66
- package/dist/core/system-session/grants.js +0 -40
- package/dist/directory/owner-directory-agentmd-sync.js +0 -89
- package/dist/directory/owner-directory-request-operation.js +0 -79
- package/dist/directory/owner-directory-text.js +0 -60
- package/kits/skills/ec-pay/references/pay-cli.md +0 -110
- /package/dist/agents/gemini/{gemini-capability-provider.js → capability-provider.js} +0 -0
- /package/dist/agents/gemini/{gemini-session-file-adapter.js → session-file-adapter.js} +0 -0
- /package/dist/{agents/claude-gateway → claude-gateway}/types.js +0 -0
- /package/dist/core/{system-channels.js → channel/system-channels.js} +0 -0
- /package/dist/core/{daemon-file-cache.js → daemon/daemon-file-cache.js} +0 -0
- /package/dist/core/{event-bus.js → event/event-bus.js} +0 -0
- /package/dist/core/{event-catalog.js → event/event-catalog.js} +0 -0
- /package/dist/core/{pack-ledger.js → pack/pack-ledger.js} +0 -0
- /package/dist/directory/{owner-directory-identity.js → identity.js} +0 -0
- /package/dist/directory/{owner-directory-policy.js → policy.js} +0 -0
- /package/dist/directory/{owner-directory-remarks.js → remarks.js} +0 -0
- /package/dist/directory/{owner-directory-scope.js → scope.js} +0 -0
- /package/dist/{contracts → ecweb/contracts}/ecweb-instance.js +0 -0
- /package/kits/templates/{bootstrap-welcome.md → bootstrap-intro.md} +0 -0
|
@@ -1,32 +1,42 @@
|
|
|
1
|
-
import { assertRunnerModelAllowed, getRunnerCatalog, catalogEfforts, assertCatalogSelectable, resolveCatalogModel, } from '
|
|
1
|
+
import { assertRunnerModelAllowed, getRunnerCatalog, catalogEfforts, assertCatalogSelectable, resolveCatalogModel, } from '../../core/model/model-catalog.js';
|
|
2
2
|
// Ecagent/OpenAI API 不认识 Claude Code SDK 的窗口后缀,必须传入基础模型 ID。
|
|
3
|
-
import { stripContextWindowSuffix } from '
|
|
3
|
+
import { stripContextWindowSuffix } from '../../core/model/context-window-suffix.js';
|
|
4
4
|
import fs from 'fs';
|
|
5
|
-
import { assertOwnershipAuthorization } from '
|
|
5
|
+
import { assertOwnershipAuthorization } from '../../core/ownership/owner-resolver.js';
|
|
6
6
|
import path from 'path';
|
|
7
|
-
import { AgentHarness, DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, JsonlSessionRepo, NodeExecutionEnv, } from '
|
|
8
|
-
import { Type, createModels, createProvider, } from '
|
|
9
|
-
import { AssistantMessageEventStream } from '
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
7
|
+
import { AgentHarness, DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, JsonlSessionRepo, NodeExecutionEnv, formatSkillsForSystemPrompt, formatSkillInvocation, } from '../../../ecagent/dist/node.js';
|
|
8
|
+
import { Type, createModels, createProvider, } from '../../../ecagent/dist/runtime/index.js';
|
|
9
|
+
import { AssistantMessageEventStream } from '../../../ecagent/dist/runtime/utils/event-stream.js';
|
|
10
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
11
|
+
import { resolveEffective } from '../../config/config-manager.js';
|
|
12
|
+
import { resolveCapabilityEnabled } from '../../core/capability/types.js';
|
|
13
|
+
import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from '../../core/message/message-utils.js';
|
|
14
|
+
import { renderActionAsText } from '../../core/message/interaction-router.js';
|
|
15
|
+
import { DEFAULT_PERMISSION_MODE } from '../../types.js';
|
|
16
|
+
import { agentSessionsDir, resolveRoot } from '../../paths.js';
|
|
17
|
+
import { isValidAid } from '../../aun/aid/identity.js';
|
|
18
|
+
import { getExistingRelationAttachmentDirs } from '../../core/permission/protected-paths.js';
|
|
19
|
+
import { requestDangerousCommandPermission } from '../../core/permission/approval-gateway.js';
|
|
20
|
+
import { normalizeExecutionPermissionMode, normalizePermissionMode } from '../../core/permission/mode.js';
|
|
21
|
+
import { checkBashDescription, checkDangerousCommand, checkReadonly, evaluateToolPreflight } from '../../core/permission/tool-policy.js';
|
|
22
|
+
import { logger } from '../../utils/logger.js';
|
|
23
|
+
import { ErrorType, getErrorRawText, isContextTooLongText, isRequestTooLargeError } from '../../utils/error-utils.js';
|
|
24
|
+
import { summarizeToolInputForAudit } from '../../utils/tool-summary.js';
|
|
25
|
+
import { renderToolTime } from '../../eck/message-renderer.js';
|
|
26
|
+
import { auditToolPreflightDenial } from '../../core/auth/authorization-audit.js';
|
|
27
|
+
import { resolveEcagentConfig, discoverEcagentSkills, readEcagentProjectFile } from './index.js';
|
|
28
|
+
import { resolveRuntimeBaseagentModelSelection } from '../../core/baseagent/baseagent.js';
|
|
29
|
+
import { resolveProviderServiceForBaseagent } from '../../config/providers.js';
|
|
30
|
+
import { buildModelRequestHeaders } from '../../core/inference/request-identity.js';
|
|
31
|
+
import { getGatewayPricing as getSharedGatewayPricing } from '../../stats/model-resolver.js';
|
|
32
|
+
import { evolcoreAutoCompactTokens, resolveModelCapabilities } from '../../core/model/model-capabilities.js';
|
|
33
|
+
import { appendRequestPath } from '../../core/inference/request-identity.js';
|
|
34
|
+
import { getManagedTaskTempDir } from '../../cli/task-context.js';
|
|
35
|
+
import { buildAgentShellEnvironment } from '../../core/permission/shell-environment.js';
|
|
36
|
+
import { buildBubblewrapCommand, buildHClassGuardCommand } from '../../core/permission/sandbox-runtime.js';
|
|
37
|
+
import { resolvePhaseOneExecutionSandbox } from '../../core/permission/mode.js';
|
|
38
|
+
import { RUNTIME_HOME_ENV, SESSION_ID_ENV } from '../../product.js';
|
|
39
|
+
import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext, isOneMillionContextModel, resolveRunInference, parseAsyncUserQuestions } from '../../core/baseagent/runner-types.js';
|
|
30
40
|
const PROVIDER_ID = 'evolcore-gateway';
|
|
31
41
|
const DEFAULT_SYSTEM_PROMPT = `You are ecagent, the coding agent built into EvolCore.
|
|
32
42
|
Work directly in the current project. Inspect relevant files before changing them, keep edits scoped, and verify the result.
|
|
@@ -97,6 +107,7 @@ function createAssistantMessage(model) {
|
|
|
97
107
|
provider: model.provider,
|
|
98
108
|
model: model.id,
|
|
99
109
|
usage: emptyUsage(),
|
|
110
|
+
reportedUsage: {},
|
|
100
111
|
stopReason: 'stop',
|
|
101
112
|
timestamp: Date.now(),
|
|
102
113
|
};
|
|
@@ -180,7 +191,60 @@ function openAiMessages(context) {
|
|
|
180
191
|
.join('\n');
|
|
181
192
|
messages.push({ role: 'tool', tool_call_id: message.toolCallId, name: message.toolName, content });
|
|
182
193
|
}
|
|
183
|
-
return messages;
|
|
194
|
+
return repairOpenAiToolSequence(messages);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* 让 tool_calls / tool 的配对在发送前始终成立。
|
|
198
|
+
*
|
|
199
|
+
* OpenAI 兼容网关要求 assistant 的每个 tool_call 都有紧随其后的 tool 消息。
|
|
200
|
+
* 会话历史可能因为进程中断、旧版本在取消时漏写结果等原因缺一条,那样每次请求
|
|
201
|
+
* 都会 400,且自动压缩也救不回来(保留的尾部仍从这条 assistant 消息开始)。
|
|
202
|
+
* 这里补齐缺失的结果、丢弃无人认领的结果,坏历史不必删会话也能继续跑。
|
|
203
|
+
*/
|
|
204
|
+
export function repairOpenAiToolSequence(messages) {
|
|
205
|
+
const repaired = [];
|
|
206
|
+
let pending = null;
|
|
207
|
+
const flushPending = () => {
|
|
208
|
+
if (!pending)
|
|
209
|
+
return;
|
|
210
|
+
for (const call of pending) {
|
|
211
|
+
repaired.push({
|
|
212
|
+
role: 'tool',
|
|
213
|
+
tool_call_id: call.id,
|
|
214
|
+
name: call.name,
|
|
215
|
+
content: 'Tool result unavailable: this tool call was interrupted before it returned.',
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
pending = null;
|
|
219
|
+
};
|
|
220
|
+
for (const message of messages) {
|
|
221
|
+
if (message.role === 'assistant') {
|
|
222
|
+
flushPending();
|
|
223
|
+
const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
|
|
224
|
+
if (toolCalls.length > 0) {
|
|
225
|
+
pending = toolCalls.map(call => ({
|
|
226
|
+
id: typeof call?.id === 'string' ? call.id : '',
|
|
227
|
+
name: typeof call?.function?.name === 'string' ? call.function.name : '',
|
|
228
|
+
}));
|
|
229
|
+
}
|
|
230
|
+
repaired.push(message);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (message.role === 'tool') {
|
|
234
|
+
const id = typeof message.tool_call_id === 'string' ? message.tool_call_id : '';
|
|
235
|
+
const index = pending ? pending.findIndex(call => call.id === id) : -1;
|
|
236
|
+
// 没有对应 tool_call 的结果(重复、错序或历史残留)同样会触发 400。
|
|
237
|
+
if (index < 0)
|
|
238
|
+
continue;
|
|
239
|
+
pending.splice(index, 1);
|
|
240
|
+
repaired.push(message);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
flushPending();
|
|
244
|
+
repaired.push(message);
|
|
245
|
+
}
|
|
246
|
+
flushPending();
|
|
247
|
+
return repaired;
|
|
184
248
|
}
|
|
185
249
|
async function* readSseEvents(body) {
|
|
186
250
|
const reader = body.getReader();
|
|
@@ -240,13 +304,29 @@ function delay(ms, signal) {
|
|
|
240
304
|
signal?.addEventListener('abort', abort, { once: true });
|
|
241
305
|
});
|
|
242
306
|
}
|
|
243
|
-
function
|
|
307
|
+
function imageRequestKey(message, image, index) {
|
|
308
|
+
return `${message.timestamp}:${index}:${createHash('sha256').update(image.data).digest('hex')}`;
|
|
309
|
+
}
|
|
310
|
+
function requestImages(context) {
|
|
311
|
+
return context.messages.flatMap(message => typeof message.content === 'string' ? []
|
|
312
|
+
: message.content.flatMap((block, index) => block.type === 'image'
|
|
313
|
+
? [{ key: imageRequestKey(message, block, index), image: block }] : []));
|
|
314
|
+
}
|
|
315
|
+
function withoutOffloadedImages(context, offloaded) {
|
|
316
|
+
return { ...context, messages: context.messages.map(message => typeof message.content === 'string' ? message : {
|
|
317
|
+
...message, content: message.content.map((block, index) => block.type === 'image'
|
|
318
|
+
&& offloaded.has(imageRequestKey(message, block, index))
|
|
319
|
+
? { type: 'text', text: '[Earlier image omitted from model request to fit the request body limit.]' } : block),
|
|
320
|
+
}) };
|
|
321
|
+
}
|
|
322
|
+
function createOpenAiTransport(config, inference = {}, imageRecovery) {
|
|
244
323
|
const stream = (model, context, options) => {
|
|
245
324
|
const output = new AssistantMessageEventStream();
|
|
246
325
|
void (async () => {
|
|
247
326
|
const hasToolResults = context.messages.some(message => message.role === 'toolResult');
|
|
248
327
|
const attempts = hasToolResults ? 1 : Math.max(1, config.maxRetries + 1);
|
|
249
328
|
let lastError;
|
|
329
|
+
let recoveredImages = false;
|
|
250
330
|
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
251
331
|
let response;
|
|
252
332
|
let retryScheduled = false;
|
|
@@ -264,7 +344,7 @@ function createOpenAiTransport(config) {
|
|
|
264
344
|
controller.signal.throwIfAborted();
|
|
265
345
|
let payload = {
|
|
266
346
|
model: model.id,
|
|
267
|
-
messages: openAiMessages(context),
|
|
347
|
+
messages: openAiMessages(imageRecovery ? withoutOffloadedImages(context, imageRecovery.offloaded) : context),
|
|
268
348
|
tools: context.tools?.map(tool => ({
|
|
269
349
|
type: 'function',
|
|
270
350
|
function: { name: tool.name, description: tool.description, parameters: tool.parameters },
|
|
@@ -272,7 +352,10 @@ function createOpenAiTransport(config) {
|
|
|
272
352
|
tool_choice: context.tools?.length ? 'auto' : undefined,
|
|
273
353
|
stream: true,
|
|
274
354
|
stream_options: { include_usage: true },
|
|
275
|
-
max_tokens: options?.maxTokens ?? model.maxTokens,
|
|
355
|
+
max_tokens: inference.maxOutputTokens ?? options?.maxTokens ?? model.maxTokens,
|
|
356
|
+
...(inference.temperature !== undefined ? { temperature: inference.temperature } : {}),
|
|
357
|
+
...(inference.topP !== undefined ? { top_p: inference.topP } : {}),
|
|
358
|
+
...(inference.stop !== undefined ? { stop: inference.stop } : {}),
|
|
276
359
|
...(options?.reasoning ? { reasoning_effort: options.reasoning } : {}),
|
|
277
360
|
};
|
|
278
361
|
const replacement = await options?.onPayload?.(payload, model);
|
|
@@ -295,6 +378,18 @@ function createOpenAiTransport(config) {
|
|
|
295
378
|
controller.signal.throwIfAborted();
|
|
296
379
|
if (!response.ok) {
|
|
297
380
|
const body = truncate(await response.text(), 2_000);
|
|
381
|
+
if (response.status === 413 && imageRecovery && !recoveredImages) {
|
|
382
|
+
const images = requestImages(context).filter(item => !imageRecovery.offloaded.has(item.key));
|
|
383
|
+
if (images.length > 1) {
|
|
384
|
+
const keys = images.slice(0, -1).map(item => item.key);
|
|
385
|
+
// Commit before retrying. The original messages and attachments remain intact.
|
|
386
|
+
await imageRecovery.persist(keys);
|
|
387
|
+
keys.forEach(key => imageRecovery.offloaded.add(key));
|
|
388
|
+
recoveredImages = true;
|
|
389
|
+
attempt--;
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
298
393
|
const kind = response.status === 401 || response.status === 403 ? 'auth' : 'network';
|
|
299
394
|
const error = new Error(`[${kind}] Gateway HTTP ${response.status}: ${body || response.statusText}`);
|
|
300
395
|
throw error;
|
|
@@ -377,9 +472,8 @@ async function consumeOpenAiStream(output, body, model) {
|
|
|
377
472
|
message.content[call.contentIndex] = toolCall;
|
|
378
473
|
output.push({ type: 'toolcall_end', contentIndex: call.contentIndex, toolCall, partial: clonePartial(message) });
|
|
379
474
|
}
|
|
380
|
-
message.stopReason =
|
|
381
|
-
? 'toolUse'
|
|
382
|
-
: finishReason === 'length' ? 'length' : 'stop';
|
|
475
|
+
message.stopReason = finishReason === 'length' ? 'length'
|
|
476
|
+
: toolCalls.size > 0 || finishReason === 'tool_calls' ? 'toolUse' : 'stop';
|
|
383
477
|
message.responseId = responseId;
|
|
384
478
|
message.responseModel = responseModel;
|
|
385
479
|
message.timestamp = Date.now();
|
|
@@ -402,16 +496,27 @@ async function consumeOpenAiStream(output, body, model) {
|
|
|
402
496
|
responseId = typeof chunk.id === 'string' ? chunk.id : responseId;
|
|
403
497
|
responseModel = typeof chunk.model === 'string' ? chunk.model : responseModel;
|
|
404
498
|
if (chunk.usage) {
|
|
405
|
-
const
|
|
406
|
-
|
|
499
|
+
const reported = (value) => typeof value === 'number'
|
|
500
|
+
&& Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
501
|
+
const promptTokens = reported(chunk.usage.prompt_tokens);
|
|
502
|
+
const cachedTokens = reported(chunk.usage.prompt_tokens_details?.cached_tokens);
|
|
503
|
+
const outputTokens = reported(chunk.usage.completion_tokens);
|
|
504
|
+
const totalTokens = reported(chunk.usage.total_tokens)
|
|
505
|
+
?? (promptTokens !== undefined && outputTokens !== undefined ? promptTokens + outputTokens : undefined);
|
|
407
506
|
// OpenAI reports prompt_tokens inclusive of cached_tokens; ecagent's
|
|
408
507
|
// usage contract stores cacheRead separately so context totals do not
|
|
409
508
|
// double-count the cached portion.
|
|
410
|
-
message.
|
|
411
|
-
|
|
412
|
-
|
|
509
|
+
message.reportedUsage = {
|
|
510
|
+
...(promptTokens !== undefined ? { input: Math.max(0, promptTokens - (cachedTokens ?? 0)) } : {}),
|
|
511
|
+
...(outputTokens !== undefined ? { output: outputTokens } : {}),
|
|
512
|
+
...(cachedTokens !== undefined ? { cacheRead: cachedTokens } : {}),
|
|
513
|
+
...(totalTokens !== undefined ? { totalTokens } : {}),
|
|
514
|
+
};
|
|
515
|
+
message.usage.input = message.reportedUsage.input ?? 0;
|
|
516
|
+
message.usage.output = outputTokens ?? 0;
|
|
517
|
+
message.usage.cacheRead = cachedTokens ?? 0;
|
|
413
518
|
message.usage.cacheWrite = 0;
|
|
414
|
-
message.usage.totalTokens =
|
|
519
|
+
message.usage.totalTokens = totalTokens ?? 0;
|
|
415
520
|
}
|
|
416
521
|
const choice = chunk.choices?.[0];
|
|
417
522
|
if (!choice)
|
|
@@ -778,6 +883,8 @@ function extractToolResult(result) {
|
|
|
778
883
|
}
|
|
779
884
|
function errorType(message) {
|
|
780
885
|
const normalized = message.toLowerCase();
|
|
886
|
+
if (isRequestTooLargeError(message))
|
|
887
|
+
return ErrorType.REQUEST_TOO_LARGE;
|
|
781
888
|
if (normalized.includes('summarization failed') || normalized.includes('turn prefix summarization failed'))
|
|
782
889
|
return ErrorType.COMPACTION_FAILED;
|
|
783
890
|
if (normalized.includes('invalid jsonl session file') || normalized.includes('session file'))
|
|
@@ -795,7 +902,8 @@ export class EcagentRunner {
|
|
|
795
902
|
capabilities = {
|
|
796
903
|
taskRecovery: true,
|
|
797
904
|
fullaccess: true,
|
|
798
|
-
|
|
905
|
+
compact: true, fork: true, forkAtTurn: true, forkAtMessage: true,
|
|
906
|
+
askUserQuestion: true, planApproval: false, fileRewind: 'unsupported',
|
|
799
907
|
};
|
|
800
908
|
config;
|
|
801
909
|
agentAid;
|
|
@@ -807,6 +915,7 @@ export class EcagentRunner {
|
|
|
807
915
|
/** Serialize harness lifecycles that share one durable ecagent session file. */
|
|
808
916
|
sessionRunTails = new Map();
|
|
809
917
|
sessionRuns = new Map();
|
|
918
|
+
nativeSessionOperations = new Set();
|
|
810
919
|
activeStreams = new Map();
|
|
811
920
|
/** Queue identity prevents an old run's finally from consuming a new run's interrupt. */
|
|
812
921
|
pendingInterrupts = new Map();
|
|
@@ -965,6 +1074,11 @@ export class EcagentRunner {
|
|
|
965
1074
|
});
|
|
966
1075
|
}
|
|
967
1076
|
async runQuery(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, _sessionManager, modelOverride, runtimeEnv = {}) {
|
|
1077
|
+
modelOverride = { ...modelOverride, inference: resolveRunInference('ecagent', modelOverride?.inference) };
|
|
1078
|
+
const sourceId = modelOverride?.backend?.kind === 'topic' ? modelOverride.backend.agentSessionId
|
|
1079
|
+
: initialAgentSessionId ?? this.runtimes.get(sessionId)?.agentSessionId;
|
|
1080
|
+
if (sourceId && this.nativeSessionOperations.has(sourceId))
|
|
1081
|
+
throw new Error('ecagent session is being forked or compacted');
|
|
968
1082
|
// Keep managed tasks from silently inheriting the daemon-wide TMPDIR when
|
|
969
1083
|
// their session-owned runtime directory is unavailable.
|
|
970
1084
|
getManagedTaskTempDir(runtimeEnv);
|
|
@@ -976,7 +1090,7 @@ export class EcagentRunner {
|
|
|
976
1090
|
throw error;
|
|
977
1091
|
}
|
|
978
1092
|
const queue = new AsyncEventQueue();
|
|
979
|
-
const lifecycle = { queue, cancelled: false };
|
|
1093
|
+
const lifecycle = { queue, cancelled: false, nativeId: sourceId ?? undefined };
|
|
980
1094
|
const runs = this.sessionRuns.get(sessionId) ?? new Set();
|
|
981
1095
|
runs.add(lifecycle);
|
|
982
1096
|
this.sessionRuns.set(sessionId, runs);
|
|
@@ -1027,6 +1141,7 @@ export class EcagentRunner {
|
|
|
1027
1141
|
request.prompt = recovered.prompt;
|
|
1028
1142
|
request.systemPromptAppend = recovered.systemPrompt;
|
|
1029
1143
|
});
|
|
1144
|
+
lifecycle.nativeId = runtime.agentSessionId;
|
|
1030
1145
|
if (lifecycle.cancelled)
|
|
1031
1146
|
throw new Error('ecagent run interrupted');
|
|
1032
1147
|
if (previousRuntime !== runtime) {
|
|
@@ -1050,9 +1165,55 @@ export class EcagentRunner {
|
|
|
1050
1165
|
message: '未取得模型上下文参数,暂按保守窗口 ' + model.contextWindow + ' tokens 运行;这不代表模型官方上限。',
|
|
1051
1166
|
});
|
|
1052
1167
|
}
|
|
1053
|
-
const
|
|
1168
|
+
const shellEnv = buildAgentShellEnvironment({ ...request.runtimeEnv,
|
|
1169
|
+
[SESSION_ID_ENV]: request.sessionId, [RUNTIME_HOME_ENV]: resolveRoot() });
|
|
1170
|
+
const nodeEnv = new NodeExecutionEnv({ cwd: request.projectPath, shellEnv, inheritEnv: false,
|
|
1171
|
+
prepareShell: async (launch) => {
|
|
1172
|
+
const permission = this.permissionContexts.get(request.sessionId);
|
|
1173
|
+
await assertOwnershipAuthorization(permission);
|
|
1174
|
+
if (permission?.systemSessionCheck && permission.systemSessionSandbox === 'off')
|
|
1175
|
+
return launch;
|
|
1176
|
+
const sandbox = resolvePhaseOneExecutionSandbox(permissionMode, permission?.role);
|
|
1177
|
+
if (process.platform === 'linux') {
|
|
1178
|
+
const guarded = sandbox.state === 'off'
|
|
1179
|
+
? buildHClassGuardCommand(launch.command, launch.args, resolveRoot(), {
|
|
1180
|
+
selfAid: this.agentAid, protectEvolcoreFilesystem: !fullaccess
|
|
1181
|
+
})
|
|
1182
|
+
: buildBubblewrapCommand(launch.command, launch.args, {
|
|
1183
|
+
projectPath: launch.cwd, projectWritable: permissionMode !== 'readonly', selfAid: this.agentAid,
|
|
1184
|
+
writablePaths: shellEnv.TMPDIR ? [shellEnv.TMPDIR] : [],
|
|
1185
|
+
});
|
|
1186
|
+
if (!guarded)
|
|
1187
|
+
throw new Error('ecagent Shell requires the Host filesystem sandbox (bubblewrap unavailable)');
|
|
1188
|
+
return guarded;
|
|
1189
|
+
}
|
|
1190
|
+
if (process.platform === 'win32' && sandbox.state === 'active') {
|
|
1191
|
+
const { buildWindowsAgentSandboxLaunch } = await import('../../core/permission/sandbox-runtime.js');
|
|
1192
|
+
if (!shellEnv.TMPDIR)
|
|
1193
|
+
throw new Error('ecagent Shell requires a task temporary directory');
|
|
1194
|
+
return buildWindowsAgentSandboxLaunch({ command: launch.command, args: launch.args,
|
|
1195
|
+
projectPath: launch.cwd, temporary: shellEnv.TMPDIR, env: launch.env,
|
|
1196
|
+
selfAid: this.agentAid, readonly: permissionMode === 'readonly', signal: launch.signal });
|
|
1197
|
+
}
|
|
1198
|
+
if (sandbox.state === 'active')
|
|
1199
|
+
throw new Error('ecagent Shell filesystem sandbox is unavailable on this platform');
|
|
1200
|
+
return launch;
|
|
1201
|
+
},
|
|
1202
|
+
});
|
|
1203
|
+
const nativeContext = await this.loadNativeContext(request.sessionId, request.projectPath, permissionMode, request.systemPromptAppend);
|
|
1204
|
+
if (lifecycle.cancelled)
|
|
1205
|
+
throw new Error('ecagent run interrupted');
|
|
1054
1206
|
const models = createModels();
|
|
1055
|
-
const
|
|
1207
|
+
const offloaded = new Set();
|
|
1208
|
+
for (const entry of await runtime.session.getEntries()) {
|
|
1209
|
+
if (entry.type === 'custom' && entry.customType === 'evolcore_image_offload') {
|
|
1210
|
+
for (const key of entry.data.keys ?? [])
|
|
1211
|
+
offloaded.add(key);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
const transport = createOpenAiTransport(connection, request.modelOverride?.inference, {
|
|
1215
|
+
offloaded, persist: async (keys) => { await runtime.session.appendCustomEntry('evolcore_image_offload', { keys }); },
|
|
1216
|
+
});
|
|
1056
1217
|
models.setProvider(createProvider({
|
|
1057
1218
|
id: PROVIDER_ID,
|
|
1058
1219
|
name: 'EvolCore Gateway',
|
|
@@ -1072,8 +1233,11 @@ export class EcagentRunner {
|
|
|
1072
1233
|
model,
|
|
1073
1234
|
thinkingLevel: normalizeThinkingLevel(effort),
|
|
1074
1235
|
autoCompactWindow: model.autoCompactWindow,
|
|
1075
|
-
tools: createTools(nodeEnv, request.projectPath,
|
|
1076
|
-
|
|
1236
|
+
tools: [...createTools(nodeEnv, request.projectPath, {}, request.modelOverride?.bootstrapAgentMdPath, fullaccess, request.modelOverride?.personalSoulDir, this.permissionContexts.get(request.sessionId)?.systemSessionGrants, this.permissionContexts.get(request.sessionId)?.systemSessionCheck ? undefined : this.agentAid), this.createQuestionTool(request.sessionId),
|
|
1237
|
+
...(nativeContext.skills.length ? [this.createSkillTool(request.sessionId, request.projectPath, permissionMode, nativeContext.skills)] : [])]
|
|
1238
|
+
.map(tool => this.hostTool(tool, request.sessionId, lifecycle)),
|
|
1239
|
+
resources: { skills: nativeContext.skills },
|
|
1240
|
+
systemPrompt: [DEFAULT_SYSTEM_PROMPT, request.systemPromptAppend, nativeContext.prompt].filter(Boolean).join('\n\n'),
|
|
1077
1241
|
streamOptions: {
|
|
1078
1242
|
timeoutMs: connection.timeoutMs,
|
|
1079
1243
|
maxRetries: connection.maxRetries,
|
|
@@ -1081,6 +1245,11 @@ export class EcagentRunner {
|
|
|
1081
1245
|
},
|
|
1082
1246
|
});
|
|
1083
1247
|
runtime.harness = harness;
|
|
1248
|
+
// Custom entries preserve the actual system input without replaying it as a user message.
|
|
1249
|
+
harness.on('before_agent_start', async (event) => {
|
|
1250
|
+
await runtime.session.appendCustomEntry('evolcore_system_prompt', { content: event.systemPrompt, nativeSources: nativeContext.sources });
|
|
1251
|
+
return undefined;
|
|
1252
|
+
});
|
|
1084
1253
|
harness.on('session_before_compact', () => {
|
|
1085
1254
|
this.onCompactStart?.(request.sessionId);
|
|
1086
1255
|
compactStartedAt = Date.now();
|
|
@@ -1122,13 +1291,22 @@ export class EcagentRunner {
|
|
|
1122
1291
|
});
|
|
1123
1292
|
// 工具调用时间感知:ecagent 的 agent-loop 在每次模型请求前调用 transformContext,
|
|
1124
1293
|
// 此时本批工具结果已全部进入消息列表——这就是与 Claude PostToolBatch 对齐的停顿点。
|
|
1125
|
-
//
|
|
1126
|
-
harness.on('context', (
|
|
1127
|
-
const
|
|
1128
|
-
|
|
1294
|
+
// 只改请求副本,避免时间戳进入持久化消息。
|
|
1295
|
+
harness.on('context', ({ messages }) => {
|
|
1296
|
+
const last = messages.at(-1);
|
|
1297
|
+
if (last?.role !== 'toolResult')
|
|
1298
|
+
return;
|
|
1299
|
+
return { messages: [...messages.slice(0, -1), {
|
|
1300
|
+
...last, content: [...last.content, { type: 'text', text: renderToolTime() }],
|
|
1301
|
+
}] };
|
|
1129
1302
|
});
|
|
1130
1303
|
let inputAccepted = false;
|
|
1131
1304
|
const unsubscribe = harness.subscribe(async (event) => {
|
|
1305
|
+
if (event.type === 'message_end' && event.message.role === 'assistant') {
|
|
1306
|
+
const entry = (await runtime.session.getEntries()).at(-1);
|
|
1307
|
+
stats.assistantUuid = entry?.type === 'message' && entry.message.role === 'assistant'
|
|
1308
|
+
&& event.message.stopReason !== 'error' && event.message.stopReason !== 'aborted' ? entry.id : undefined;
|
|
1309
|
+
}
|
|
1132
1310
|
if (event.type === 'session_compact') {
|
|
1133
1311
|
if (compactHeartbeatTimer)
|
|
1134
1312
|
clearInterval(compactHeartbeatTimer);
|
|
@@ -1329,7 +1507,8 @@ export class EcagentRunner {
|
|
|
1329
1507
|
stats.textBlocks.set(contentIndex, { text: content, ended: true });
|
|
1330
1508
|
stats.text += content;
|
|
1331
1509
|
// Match Codex: only the completed body enters the common runner protocol.
|
|
1332
|
-
queue.push({ type: 'text', text: content, turn: stats.numTurns + 1
|
|
1510
|
+
queue.push({ type: 'text', text: content, turn: stats.numTurns + 1,
|
|
1511
|
+
...(stats.assistantUuid ? { assistantUuid: stats.assistantUuid } : {}) });
|
|
1333
1512
|
}
|
|
1334
1513
|
/** Recover a missing text_end from the final message, or the received deltas. */
|
|
1335
1514
|
finishTextBlocks(queue, stats, message) {
|
|
@@ -1345,6 +1524,8 @@ export class EcagentRunner {
|
|
|
1345
1524
|
}
|
|
1346
1525
|
}
|
|
1347
1526
|
mapHarnessEvent(queue, event, stats, model, effort) {
|
|
1527
|
+
if (event.type === 'message_start' && event.message.role === 'assistant')
|
|
1528
|
+
stats.assistantUuid = undefined;
|
|
1348
1529
|
if (event.type === 'message_update'
|
|
1349
1530
|
&& (event.assistantMessageEvent.type === 'thinking_start'
|
|
1350
1531
|
|| event.assistantMessageEvent.type === 'thinking_delta'
|
|
@@ -1355,6 +1536,7 @@ export class EcagentRunner {
|
|
|
1355
1536
|
if (event.type === 'message_update') {
|
|
1356
1537
|
const update = event.assistantMessageEvent;
|
|
1357
1538
|
if (update.type === 'text_start') {
|
|
1539
|
+
stats.assistantUuid = undefined;
|
|
1358
1540
|
if (!stats.textBlocks.has(update.contentIndex)) {
|
|
1359
1541
|
stats.textBlocks.set(update.contentIndex, { text: '', ended: false });
|
|
1360
1542
|
queue.push({ type: 'text_start', contentIndex: update.contentIndex, turn: stats.numTurns + 1 });
|
|
@@ -1374,7 +1556,10 @@ export class EcagentRunner {
|
|
|
1374
1556
|
return;
|
|
1375
1557
|
}
|
|
1376
1558
|
if (update.type === 'text_end') {
|
|
1377
|
-
|
|
1559
|
+
// Publish at message_end, after the native entry ID has been persisted.
|
|
1560
|
+
if (!stats.textBlocks.get(update.contentIndex)?.ended) {
|
|
1561
|
+
stats.textBlocks.set(update.contentIndex, { text: update.content, ended: false });
|
|
1562
|
+
}
|
|
1378
1563
|
return;
|
|
1379
1564
|
}
|
|
1380
1565
|
}
|
|
@@ -1384,7 +1569,8 @@ export class EcagentRunner {
|
|
|
1384
1569
|
}
|
|
1385
1570
|
if (event.type === 'tool_execution_start') {
|
|
1386
1571
|
this.finishTextBlocks(queue, stats);
|
|
1387
|
-
queue.push({ type: 'tool_use', name: event.toolName, input: event.args, callId: event.toolCallId, turn: stats.numTurns + 1
|
|
1572
|
+
queue.push({ type: 'tool_use', name: event.toolName, input: event.args, callId: event.toolCallId, turn: stats.numTurns + 1,
|
|
1573
|
+
...(stats.assistantUuid ? { assistantUuid: stats.assistantUuid } : {}) });
|
|
1388
1574
|
return;
|
|
1389
1575
|
}
|
|
1390
1576
|
if (event.type === 'tool_execution_end') {
|
|
@@ -1408,26 +1594,27 @@ export class EcagentRunner {
|
|
|
1408
1594
|
this.finishTextBlocks(queue, stats, event.message);
|
|
1409
1595
|
stats.textBlocks.clear();
|
|
1410
1596
|
stats.numTurns++;
|
|
1411
|
-
const usage = event.message.usage;
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1597
|
+
const usage = event.message.reportedUsage ?? (event.message.provider === PROVIDER_ID ? {} : event.message.usage);
|
|
1598
|
+
const tokenUsage = {};
|
|
1599
|
+
for (const [source, target] of [['input', 'input_tokens'], ['output', 'output_tokens'],
|
|
1600
|
+
['cacheRead', 'cache_read_input_tokens'], ['cacheWrite', 'cache_creation_input_tokens']]) {
|
|
1601
|
+
const value = usage[source];
|
|
1602
|
+
if (value === undefined)
|
|
1603
|
+
continue;
|
|
1604
|
+
tokenUsage[target] = value;
|
|
1605
|
+
stats.usage[target] = (stats.usage[target] ?? 0) + value;
|
|
1606
|
+
}
|
|
1420
1607
|
stats.modelCalls.push({
|
|
1421
1608
|
call_index: stats.modelCalls.length,
|
|
1422
1609
|
model: event.message.model || model.id,
|
|
1423
1610
|
request_id: event.message.responseId,
|
|
1424
1611
|
tokenUsage,
|
|
1425
|
-
contextUsage: this.contextUsage(model, tokenUsage, effort),
|
|
1612
|
+
contextUsage: usage.totalTokens === undefined ? undefined : this.contextUsage(model, tokenUsage, effort, usage.totalTokens),
|
|
1426
1613
|
});
|
|
1427
1614
|
}
|
|
1428
1615
|
}
|
|
1429
|
-
contextUsage(model, usage, effort) {
|
|
1430
|
-
const totalTokens = Number(usage.input_tokens ?? 0) + Number(usage.output_tokens ?? 0)
|
|
1616
|
+
contextUsage(model, usage, effort, reportedTotal) {
|
|
1617
|
+
const totalTokens = reportedTotal ?? Number(usage.input_tokens ?? 0) + Number(usage.output_tokens ?? 0)
|
|
1431
1618
|
+ Number(usage.cache_read_input_tokens ?? 0) + Number(usage.cache_creation_input_tokens ?? 0);
|
|
1432
1619
|
return {
|
|
1433
1620
|
totalTokens, maxTokens: model.contextWindow,
|
|
@@ -1437,6 +1624,223 @@ export class EcagentRunner {
|
|
|
1437
1624
|
model: model.id, effort,
|
|
1438
1625
|
};
|
|
1439
1626
|
}
|
|
1627
|
+
/** The Host owns execution and output admission for every installed tool. */
|
|
1628
|
+
hostTool(tool, sessionId, lifecycle) {
|
|
1629
|
+
return { ...tool, execute: async (id, args, signal, onUpdate) => {
|
|
1630
|
+
if (lifecycle.cancelled || signal?.aborted)
|
|
1631
|
+
throw new Error('Tool execution cancelled');
|
|
1632
|
+
await assertOwnershipAuthorization(this.permissionContexts.get(sessionId));
|
|
1633
|
+
if (lifecycle.cancelled || signal?.aborted)
|
|
1634
|
+
throw new Error('Tool execution cancelled');
|
|
1635
|
+
const validate = (result) => {
|
|
1636
|
+
if (!result || !Array.isArray(result.content)
|
|
1637
|
+
|| result.content.some(block => block.type === 'text' ? typeof block.text !== 'string'
|
|
1638
|
+
: block.type === 'image' ? typeof block.data !== 'string' || typeof block.mimeType !== 'string' : true)) {
|
|
1639
|
+
throw new Error(`Host rejected invalid result from ${tool.name}`);
|
|
1640
|
+
}
|
|
1641
|
+
return { ...result, content: result.content.map(block => block.type === 'text'
|
|
1642
|
+
? { ...block, text: truncate(block.text) } : block) };
|
|
1643
|
+
};
|
|
1644
|
+
const result = await tool.execute(id, args, signal, partial => {
|
|
1645
|
+
if (!lifecycle.cancelled && !signal?.aborted)
|
|
1646
|
+
onUpdate?.(validate(partial));
|
|
1647
|
+
});
|
|
1648
|
+
return validate(result);
|
|
1649
|
+
} };
|
|
1650
|
+
}
|
|
1651
|
+
async loadNativeContext(sessionId, projectPath, mode, hostPrompt = '') {
|
|
1652
|
+
const sources = [];
|
|
1653
|
+
// Background system jobs receive only the context explicitly assembled by their module.
|
|
1654
|
+
if (this.permissionContexts.get(sessionId)?.systemSessionCheck)
|
|
1655
|
+
return { prompt: '', skills: [], sources };
|
|
1656
|
+
await assertOwnershipAuthorization(this.permissionContexts.get(sessionId));
|
|
1657
|
+
const canRead = async (file) => !(await this.authorizeTool(sessionId, projectPath, mode, 'Read', { file_path: file })).block;
|
|
1658
|
+
const rules = [];
|
|
1659
|
+
const seen = new Set();
|
|
1660
|
+
for (const name of ['AGENTS.md', 'CLAUDE.md']) {
|
|
1661
|
+
const file = path.join(fs.realpathSync(projectPath), name);
|
|
1662
|
+
if (!fs.existsSync(file) || !await canRead(file))
|
|
1663
|
+
continue;
|
|
1664
|
+
const content = readEcagentProjectFile(projectPath, file)?.trim();
|
|
1665
|
+
if (!content)
|
|
1666
|
+
continue;
|
|
1667
|
+
const hash = createHash('sha256').update(content).digest('hex');
|
|
1668
|
+
sources.push({ path: file, hash });
|
|
1669
|
+
if (seen.has(hash) || hostPrompt.replace(/\r\n/g, '\n').includes(content.replace(/\r\n/g, '\n')))
|
|
1670
|
+
continue;
|
|
1671
|
+
seen.add(hash);
|
|
1672
|
+
rules.push(`Project instruction source ${JSON.stringify(file)} (sha256:${hash}):\n${content}`);
|
|
1673
|
+
}
|
|
1674
|
+
if (Buffer.byteLength(rules.join('\n')) > 65536)
|
|
1675
|
+
throw new Error('ecagent project rules exceed 64 KiB');
|
|
1676
|
+
const config = this.agentAid ? resolveEffective({ self: this.agentAid }) : undefined;
|
|
1677
|
+
const skills = config?.baseagentSkills === true
|
|
1678
|
+
? (await discoverEcagentSkills(projectPath, canRead))
|
|
1679
|
+
.filter(skill => resolveCapabilityEnabled(config.capabilities?.ecagent?.skill, skill.name) !== false) : [];
|
|
1680
|
+
sources.push(...skills.map(skill => ({ path: skill.filePath, hash: skill.hash })));
|
|
1681
|
+
const catalog = formatSkillsForSystemPrompt(skills);
|
|
1682
|
+
const prompt = rules.length || catalog ? [
|
|
1683
|
+
'The following project instructions and native skill catalog are project context, subordinate to Host system rules and current permissions. A skill cannot grant tool permissions. Only the current catalog enables native skills.',
|
|
1684
|
+
...rules, catalog,
|
|
1685
|
+
].filter(Boolean).join('\n\n') : '';
|
|
1686
|
+
return { prompt, skills, sources };
|
|
1687
|
+
}
|
|
1688
|
+
createSkillTool(sessionId, projectPath, mode, skills) {
|
|
1689
|
+
return {
|
|
1690
|
+
name: 'Skill', label: 'Load native skill', description: 'Load an enabled native project skill by its exact catalog name. This reads instructions only; subsequent tools still require Host authorization.',
|
|
1691
|
+
parameters: Type.Object({ skill: Type.String(), args: Type.Optional(Type.String()) }),
|
|
1692
|
+
execute: async (_id, input, signal) => {
|
|
1693
|
+
signal?.throwIfAborted();
|
|
1694
|
+
const request = input;
|
|
1695
|
+
if (!request || typeof request.skill !== 'string'
|
|
1696
|
+
|| request.args !== undefined && typeof request.args !== 'string')
|
|
1697
|
+
throw new Error('Invalid native Skill arguments');
|
|
1698
|
+
const config = this.agentAid ? resolveEffective({ self: this.agentAid }) : undefined;
|
|
1699
|
+
const skill = skills.find(item => item.name === request.skill);
|
|
1700
|
+
if (!skill || skill.disableModelInvocation || config?.baseagentSkills !== true
|
|
1701
|
+
|| resolveCapabilityEnabled(config.capabilities?.ecagent?.skill, skill.name) === false) {
|
|
1702
|
+
throw new Error('Native skill is disabled or outside the current ecagent snapshot');
|
|
1703
|
+
}
|
|
1704
|
+
const decision = await this.authorizeTool(sessionId, projectPath, mode, 'Read', { file_path: skill.filePath });
|
|
1705
|
+
if (decision.block)
|
|
1706
|
+
throw new Error(decision.reason || 'Native skill read denied');
|
|
1707
|
+
signal?.throwIfAborted();
|
|
1708
|
+
const content = formatSkillInvocation(skill, request.args);
|
|
1709
|
+
if (content.length > MAX_TOOL_OUTPUT)
|
|
1710
|
+
throw new Error('Native skill instructions exceed the tool output limit');
|
|
1711
|
+
return textResult(content, { sourcePath: skill.filePath, sha256: skill.hash });
|
|
1712
|
+
},
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
createQuestionTool(sessionId) {
|
|
1716
|
+
return {
|
|
1717
|
+
name: 'AskUserQuestion', label: 'Ask user',
|
|
1718
|
+
description: 'Ask blocking questions with optional choices and free text. Waits for an explicit user answer or cancellation; recommendations never answer a question.',
|
|
1719
|
+
parameters: Type.Object({ questions: Type.Array(Type.Object({
|
|
1720
|
+
title: Type.String({ minLength: 1, maxLength: 16384 }),
|
|
1721
|
+
options: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 4096 }), { minItems: 1, maxItems: 20 })),
|
|
1722
|
+
recommendedOption: Type.Optional(Type.String()),
|
|
1723
|
+
blocking: Type.Optional(Type.Literal(true)),
|
|
1724
|
+
}), { minItems: 1, maxItems: 20 }) }),
|
|
1725
|
+
execute: async (toolCallId, input, signal) => {
|
|
1726
|
+
const questions = parseAsyncUserQuestions(input.questions);
|
|
1727
|
+
if (new Set(questions.map(question => question.title)).size !== questions.length) {
|
|
1728
|
+
throw new Error('ecagent question titles must be unique');
|
|
1729
|
+
}
|
|
1730
|
+
if (questions.some(question => question.blocking === false
|
|
1731
|
+
|| question.recommendedOption && !question.options?.includes(question.recommendedOption))) {
|
|
1732
|
+
throw new Error('ecagent questions require blocking=true and recommendations from the option list');
|
|
1733
|
+
}
|
|
1734
|
+
const context = this.permissionContexts.get(sessionId);
|
|
1735
|
+
const router = context?.interactionRouter;
|
|
1736
|
+
const sendPrompt = context?.sendPrompt ?? this.sendPromptFn;
|
|
1737
|
+
if (!router || !context?.userId || context.approvalInteractionPolicy === 'deny'
|
|
1738
|
+
|| !(context.adapter && context.channelId) && !sendPrompt) {
|
|
1739
|
+
throw new Error('ecagent structured question requires an interactive Host route (C25)');
|
|
1740
|
+
}
|
|
1741
|
+
const answers = Object.create(null);
|
|
1742
|
+
for (const question of questions) {
|
|
1743
|
+
if (signal?.aborted)
|
|
1744
|
+
throw new Error('ecagent run interrupted');
|
|
1745
|
+
const id = `ecagent-ask-${randomUUID()}`;
|
|
1746
|
+
const options = question.options ?? [];
|
|
1747
|
+
const interaction = {
|
|
1748
|
+
type: 'interaction', id, sessionId, channelId: context.channelId ?? '',
|
|
1749
|
+
initiatorId: context.userId, blocking: true,
|
|
1750
|
+
kind: { kind: 'action', title: question.title,
|
|
1751
|
+
buttons: options.map((label, index) => ({ key: `opt-${index}`, label })),
|
|
1752
|
+
allowCustomInput: true,
|
|
1753
|
+
...(question.recommendedOption ? { recommendedOption: `opt-${options.indexOf(question.recommendedOption)}` } : {}),
|
|
1754
|
+
},
|
|
1755
|
+
fallback: { command: 'ask', acceptFreeText: true,
|
|
1756
|
+
buttonArgMap: Object.fromEntries(options.map((_, index) => [`opt-${index}`, String(index + 1)])),
|
|
1757
|
+
freeTextHint: '回复 /ask <序号或自定义内容>',
|
|
1758
|
+
},
|
|
1759
|
+
};
|
|
1760
|
+
let finish;
|
|
1761
|
+
let settled = false;
|
|
1762
|
+
const settlement = new Promise(resolve => {
|
|
1763
|
+
finish = value => { if (!settled) {
|
|
1764
|
+
settled = true;
|
|
1765
|
+
resolve(value);
|
|
1766
|
+
} };
|
|
1767
|
+
});
|
|
1768
|
+
const onAbort = () => {
|
|
1769
|
+
void router.cancel(id, 'interrupted').catch(error => {
|
|
1770
|
+
finish({ cancelled: 'interrupted' });
|
|
1771
|
+
logger.warn('[EcagentRunner] Question cancellation failed:', error);
|
|
1772
|
+
});
|
|
1773
|
+
};
|
|
1774
|
+
try {
|
|
1775
|
+
await context.turn?.onInteractionOpen?.({ interactionId: id, kind: 'ask_user', toolUseId: toolCallId });
|
|
1776
|
+
router.register(id, sessionId, async (action, values) => {
|
|
1777
|
+
if (signal?.aborted || settled || !action.trim())
|
|
1778
|
+
return false;
|
|
1779
|
+
if (action === 'cancel') {
|
|
1780
|
+
await context.turn?.onInteractionSettled?.(id, 'cancelled');
|
|
1781
|
+
finish({ cancelled: 'explicit_cancel' });
|
|
1782
|
+
return true;
|
|
1783
|
+
}
|
|
1784
|
+
const customText = action === '_custom_input'
|
|
1785
|
+
? typeof values?.custom_text === 'string' ? values.custom_text.trim() : ''
|
|
1786
|
+
: undefined;
|
|
1787
|
+
if (customText === '')
|
|
1788
|
+
return false;
|
|
1789
|
+
const numeric = /^\d+$/.test(action) ? Number(action) - 1 : -1;
|
|
1790
|
+
const key = /^opt-\d+$/.test(action) ? Number(action.slice(4)) : numeric;
|
|
1791
|
+
if (action.startsWith('opt-') && (key < 0 || key >= options.length))
|
|
1792
|
+
return false;
|
|
1793
|
+
const answer = customText ?? (key >= 0 && key < options.length ? options[key] : action.trim());
|
|
1794
|
+
await context.turn?.onInteractionSettled?.(id, 'answered');
|
|
1795
|
+
finish({ answer });
|
|
1796
|
+
return true;
|
|
1797
|
+
}, { initiatorId: context.userId, fallbackCommand: 'ask', retainOnRejected: true,
|
|
1798
|
+
onCancel: async (reason) => {
|
|
1799
|
+
if (settled)
|
|
1800
|
+
return;
|
|
1801
|
+
try {
|
|
1802
|
+
await context.turn?.onInteractionSettled?.(id, 'cancelled');
|
|
1803
|
+
}
|
|
1804
|
+
finally {
|
|
1805
|
+
finish({ cancelled: reason });
|
|
1806
|
+
}
|
|
1807
|
+
},
|
|
1808
|
+
});
|
|
1809
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1810
|
+
if (signal?.aborted)
|
|
1811
|
+
onAbort();
|
|
1812
|
+
else {
|
|
1813
|
+
await context.flushPending?.();
|
|
1814
|
+
if (signal?.aborted)
|
|
1815
|
+
onAbort();
|
|
1816
|
+
else if (context.adapter && context.channelId) {
|
|
1817
|
+
const receipt = await sendInteractionPayload(context.adapter, buildEnvelope({
|
|
1818
|
+
taskId: context.taskId, sessionId, channel: context.channel ?? context.adapter.channelName,
|
|
1819
|
+
channelId: context.channelId, agentName: context.agentName, chatmode: context.chatmode,
|
|
1820
|
+
replyContext: context.replyContext,
|
|
1821
|
+
}), interaction, renderActionAsText(interaction), context.replyContext);
|
|
1822
|
+
if (!isInteractionSendAccepted(receipt))
|
|
1823
|
+
throw new Error('ecagent question delivery failed');
|
|
1824
|
+
}
|
|
1825
|
+
else
|
|
1826
|
+
await sendPrompt(renderActionAsText(interaction));
|
|
1827
|
+
}
|
|
1828
|
+
const result = await settlement;
|
|
1829
|
+
if ('cancelled' in result) {
|
|
1830
|
+
void this.runtimes.get(sessionId)?.harness?.abort();
|
|
1831
|
+
throw new Error('ecagent run interrupted');
|
|
1832
|
+
}
|
|
1833
|
+
answers[question.title] = result.answer;
|
|
1834
|
+
}
|
|
1835
|
+
finally {
|
|
1836
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1837
|
+
await router.cancel(id, settled ? undefined : 'cancelled');
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
return { content: [{ type: 'text', text: JSON.stringify({ answers }) }], details: { answers } };
|
|
1841
|
+
},
|
|
1842
|
+
};
|
|
1843
|
+
}
|
|
1440
1844
|
async authorizeTool(sessionId, projectPath, mode, toolName, input, turn, callId) {
|
|
1441
1845
|
const decision = await this.evaluateToolPermission(sessionId, projectPath, mode, toolName, input, turn, callId);
|
|
1442
1846
|
return decision.block ? {
|
|
@@ -1497,7 +1901,7 @@ export class EcagentRunner {
|
|
|
1497
1901
|
}
|
|
1498
1902
|
};
|
|
1499
1903
|
// Bash description 格式约定先于一切放行分支(含 fullaccess 与系统会话)。
|
|
1500
|
-
// TODO(bash-description): 与
|
|
1904
|
+
// TODO(bash-description): 与 Claude runner 同因——该约束缺少验证,先短路放行;
|
|
1501
1905
|
// 恢复强制时把两个 runner 的开关一起打开。
|
|
1502
1906
|
if (process.env.EVOLCORE_BASH_DESCRIPTION_ENFORCE === '1') {
|
|
1503
1907
|
const descriptionCheck = checkBashDescription(toolName, input);
|
|
@@ -1524,6 +1928,9 @@ export class EcagentRunner {
|
|
|
1524
1928
|
await recordBlockedOperation(policy.policyCode ?? 'session_policy_hook');
|
|
1525
1929
|
return { block: true, reason: policy.reason || '当前会话策略拒绝此工具调用', details: { policyCode: policy.policyCode ?? 'session_policy_hook' } };
|
|
1526
1930
|
}
|
|
1931
|
+
// Native Skill only returns an admitted snapshot; its exact source receives a separate Read check.
|
|
1932
|
+
if (toolName === 'AskUserQuestion' || toolName === 'Skill')
|
|
1933
|
+
return {};
|
|
1527
1934
|
const preflight = evaluateToolPreflight(toolName, input, {
|
|
1528
1935
|
sessionId,
|
|
1529
1936
|
managedTempDir: permissionContext?.managedTempDir,
|
|
@@ -1545,7 +1952,7 @@ export class EcagentRunner {
|
|
|
1545
1952
|
return { block: true, reason: preflight.message, details: { policyCode: preflight.policyCode } };
|
|
1546
1953
|
}
|
|
1547
1954
|
if (preflight.behavior === 'allow')
|
|
1548
|
-
return {};
|
|
1955
|
+
return { input: preflight.input };
|
|
1549
1956
|
const checkedInput = preflight.input;
|
|
1550
1957
|
if (mode === 'readonly') {
|
|
1551
1958
|
const attachmentReadRoots = ['Read', 'Glob', 'Grep'].includes(toolName)
|
|
@@ -1565,7 +1972,7 @@ export class EcagentRunner {
|
|
|
1565
1972
|
});
|
|
1566
1973
|
return { block: true, reason: decision.message };
|
|
1567
1974
|
}
|
|
1568
|
-
return {};
|
|
1975
|
+
return { input: checkedInput };
|
|
1569
1976
|
}
|
|
1570
1977
|
const dangerous = checkDangerousCommand(toolName, checkedInput);
|
|
1571
1978
|
if (mode === 'auto') {
|
|
@@ -1573,11 +1980,13 @@ export class EcagentRunner {
|
|
|
1573
1980
|
await recordBlockedOperation('auto_dangerous_command', checkedInput);
|
|
1574
1981
|
return { block: true, reason: `危险操作已由 auto 模式拒绝:${dangerous.reason}` };
|
|
1575
1982
|
}
|
|
1576
|
-
return {};
|
|
1983
|
+
return { input: checkedInput };
|
|
1577
1984
|
}
|
|
1578
1985
|
const prompt = permissionContext?.sendPrompt ?? this.sendPromptFn;
|
|
1579
1986
|
const decision = await requestDangerousCommandPermission(this.permissionGateway, sessionId, toolName, checkedInput, prompt, permissionContext, `ecagent:${mode}`, mode);
|
|
1580
|
-
return decision.matched && decision.decision === 'deny'
|
|
1987
|
+
return decision.matched && decision.decision === 'deny'
|
|
1988
|
+
? { block: true, reason: '危险操作未获人工批准', details: { decisionSource: 'approval' } }
|
|
1989
|
+
: { input: checkedInput };
|
|
1581
1990
|
}
|
|
1582
1991
|
async interrupt(sessionKey) {
|
|
1583
1992
|
this.permissionContexts.get(sessionKey)?.pauseController?.cancel();
|
|
@@ -1644,31 +2053,15 @@ export class EcagentRunner {
|
|
|
1644
2053
|
if (this.permissionContexts.get(sessionId) === capturedPermissionContext)
|
|
1645
2054
|
this.permissionContexts.delete(sessionId);
|
|
1646
2055
|
}
|
|
1647
|
-
async clearSession(sessionId, agentSessionId, projectPath) {
|
|
1648
|
-
try {
|
|
1649
|
-
const currentRuntime = this.runtimes.get(sessionId);
|
|
1650
|
-
await this.interrupt(sessionId);
|
|
1651
|
-
this.assertInterruptSettled(sessionId);
|
|
1652
|
-
const env = new NodeExecutionEnv({ cwd: projectPath });
|
|
1653
|
-
const repo = new JsonlSessionRepo({ fs: env, sessionsRoot: this.sessionsRoot() });
|
|
1654
|
-
const metadata = (await repo.list({ cwd: path.resolve(projectPath) })).find(item => item.id === agentSessionId);
|
|
1655
|
-
if (metadata)
|
|
1656
|
-
await repo.delete(metadata);
|
|
1657
|
-
if (currentRuntime?.agentSessionId === agentSessionId
|
|
1658
|
-
&& this.runtimes.get(sessionId) === currentRuntime)
|
|
1659
|
-
this.runtimes.delete(sessionId);
|
|
1660
|
-
await this.onSessionIdUpdate?.(sessionId, '');
|
|
1661
|
-
return !!metadata;
|
|
1662
|
-
}
|
|
1663
|
-
catch (error) {
|
|
1664
|
-
logger.error('[EcagentRunner] clear failed:', error);
|
|
1665
|
-
return false;
|
|
1666
|
-
}
|
|
1667
|
-
}
|
|
1668
2056
|
async compactSession(sessionId, agentSessionId, projectPath, modelOverride) {
|
|
2057
|
+
if (this.nativeSessionOperations.has(agentSessionId))
|
|
2058
|
+
return { ok: false, code: 'invalid_state', message: 'ecagent session is being forked or compacted', durationMs: 0 };
|
|
2059
|
+
const inference = resolveRunInference('ecagent', modelOverride?.inference);
|
|
1669
2060
|
const startedAt = Date.now();
|
|
2061
|
+
this.nativeSessionOperations.add(agentSessionId);
|
|
1670
2062
|
try {
|
|
1671
|
-
if (this.
|
|
2063
|
+
if (this.hasActiveOperation(sessionId)
|
|
2064
|
+
|| [...this.sessionRuns.values()].some(runs => [...runs].some(run => run.nativeId === agentSessionId))) {
|
|
1672
2065
|
logger.warn(`[EcagentRunner] compact skipped while session ${sessionId} is active`);
|
|
1673
2066
|
return { ok: false, code: 'invalid_state', message: 'Session is active', durationMs: Date.now() - startedAt };
|
|
1674
2067
|
}
|
|
@@ -1686,7 +2079,7 @@ export class EcagentRunner {
|
|
|
1686
2079
|
const model = await this.resolveRunModel(compactModel, connection);
|
|
1687
2080
|
const env = new NodeExecutionEnv({ cwd: runtime.projectPath });
|
|
1688
2081
|
const models = createModels();
|
|
1689
|
-
const transport = createOpenAiTransport(connection);
|
|
2082
|
+
const transport = createOpenAiTransport(connection, inference);
|
|
1690
2083
|
models.setProvider(createProvider({
|
|
1691
2084
|
id: PROVIDER_ID, auth: { apiKey: { name: 'EvolCore gateway', login: async () => ({ type: 'api_key', key: connection.apiKey }), resolve: async () => ({ auth: { apiKey: connection.apiKey } }) } },
|
|
1692
2085
|
models: [model], api: transport,
|
|
@@ -1712,6 +2105,9 @@ export class EcagentRunner {
|
|
|
1712
2105
|
logger.error(`[EcagentRunner] compact failed: session=${sessionId} agent=${agentSessionId} code=${code} durationMs=${Date.now() - startedAt} error=${message}`);
|
|
1713
2106
|
return { ok: false, code, message, durationMs: Date.now() - startedAt };
|
|
1714
2107
|
}
|
|
2108
|
+
finally {
|
|
2109
|
+
this.nativeSessionOperations.delete(agentSessionId);
|
|
2110
|
+
}
|
|
1715
2111
|
}
|
|
1716
2112
|
compact(sessionId, agentSessionId, projectPath, modelOverride) {
|
|
1717
2113
|
return this.compactSession(sessionId, agentSessionId, projectPath, modelOverride);
|
|
@@ -1726,29 +2122,119 @@ export class EcagentRunner {
|
|
|
1726
2122
|
return null;
|
|
1727
2123
|
}
|
|
1728
2124
|
}
|
|
1729
|
-
async forkSession(agentSessionId, projectPath, title) {
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
2125
|
+
async forkSession(agentSessionId, projectPath, title, context) {
|
|
2126
|
+
return this.forkNativeSession(agentSessionId, projectPath, title, context);
|
|
2127
|
+
}
|
|
2128
|
+
async forkSessionAt(agentSessionId, projectPath, messageId, title, context) {
|
|
2129
|
+
if (!messageId?.trim())
|
|
2130
|
+
throw new Error('ecagent fork message anchor is missing');
|
|
2131
|
+
return this.forkNativeSession(agentSessionId, projectPath, title, context, messageId);
|
|
2132
|
+
}
|
|
2133
|
+
async forkNativeSession(agentSessionId, projectPath, title, context, messageId) {
|
|
2134
|
+
const bound = [...this.runtimes].filter(([, runtime]) => runtime.agentSessionId === agentSessionId);
|
|
2135
|
+
if (this.nativeSessionOperations.has(agentSessionId) || bound.some(([sessionId]) => this.hasActiveOperation(sessionId))
|
|
2136
|
+
|| [...this.sessionRuns.values()].some(runs => [...runs].some(run => run.nativeId === agentSessionId))
|
|
2137
|
+
|| context?.sessionId && this.hasActiveOperation(context.sessionId))
|
|
2138
|
+
throw new Error('ecagent fork source is busy');
|
|
2139
|
+
this.nativeSessionOperations.add(agentSessionId);
|
|
2140
|
+
try {
|
|
2141
|
+
await assertOwnershipAuthorization(this.permissionContexts.get(context?.sessionId ?? bound[0]?.[0]));
|
|
2142
|
+
const cwd = path.resolve(projectPath);
|
|
2143
|
+
const env = new NodeExecutionEnv({ cwd });
|
|
2144
|
+
const repo = new JsonlSessionRepo({ fs: env, sessionsRoot: this.sessionsRoot() });
|
|
2145
|
+
const source = (await repo.list({ cwd })).find(item => item.id === agentSessionId);
|
|
2146
|
+
if (!source)
|
|
2147
|
+
throw new Error(`ecagent session not found: ${agentSessionId}`);
|
|
2148
|
+
const actualPath = fs.realpathSync(source.path);
|
|
2149
|
+
const expectedPath = path.resolve(source.path);
|
|
2150
|
+
if (process.platform === 'win32' ? actualPath.toLowerCase() !== expectedPath.toLowerCase() : actualPath !== expectedPath) {
|
|
2151
|
+
throw new Error('ecagent fork source must not traverse symbolic links');
|
|
2152
|
+
}
|
|
2153
|
+
const session = await repo.open(source);
|
|
2154
|
+
const entries = await session.getEntries();
|
|
2155
|
+
if (new Set(entries.map(entry => entry.id)).size !== entries.length)
|
|
2156
|
+
throw new Error('ecagent fork message anchor is ambiguous');
|
|
2157
|
+
const branch = await session.getBranch();
|
|
2158
|
+
const boundary = messageId === undefined ? branch.length - 1 : branch.findIndex(entry => entry.id === messageId);
|
|
2159
|
+
if (boundary < 0)
|
|
2160
|
+
throw new Error('ecagent fork message anchor is missing or outside the active branch');
|
|
2161
|
+
const target = branch[boundary];
|
|
2162
|
+
if (messageId !== undefined && (target.type !== 'message'
|
|
2163
|
+
|| !['user', 'assistant', 'toolResult'].includes(target.message.role)))
|
|
2164
|
+
throw new Error('ecagent fork anchor is not a conversation message');
|
|
2165
|
+
const pending = new Set();
|
|
2166
|
+
for (const entry of branch.slice(0, boundary + 1)) {
|
|
2167
|
+
if (entry.type !== 'message')
|
|
2168
|
+
continue;
|
|
2169
|
+
const message = entry.message;
|
|
2170
|
+
if (message.role === 'toolResult') {
|
|
2171
|
+
if (!pending.delete(message.toolCallId))
|
|
2172
|
+
throw new Error('ecagent fork has an unmatched tool result');
|
|
2173
|
+
}
|
|
2174
|
+
else if (message.role === 'assistant' || message.role === 'user') {
|
|
2175
|
+
if (pending.size)
|
|
2176
|
+
throw new Error('ecagent fork splits an unfinished tool batch');
|
|
2177
|
+
if (message.role === 'assistant')
|
|
2178
|
+
for (const block of message.content) {
|
|
2179
|
+
if (block.type === 'toolCall') {
|
|
2180
|
+
if (pending.has(block.id))
|
|
2181
|
+
throw new Error('ecagent fork has duplicate tool calls');
|
|
2182
|
+
pending.add(block.id);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
if (pending.size)
|
|
2188
|
+
throw new Error('ecagent fork splits an unfinished tool batch; select a message after all tool results');
|
|
2189
|
+
// Native inclusive branch copy. Never copy mutable Host permissions or queued work.
|
|
2190
|
+
const fork = await repo.fork(source, { cwd, entryId: target.id, position: 'at', metadata: {} });
|
|
2191
|
+
if (title)
|
|
2192
|
+
await fork.appendSessionName(title);
|
|
2193
|
+
return (await fork.getMetadata()).id;
|
|
2194
|
+
}
|
|
2195
|
+
finally {
|
|
2196
|
+
this.nativeSessionOperations.delete(agentSessionId);
|
|
2197
|
+
}
|
|
1740
2198
|
}
|
|
1741
2199
|
async getSessionMessages(agentSessionId, projectPath) {
|
|
1742
2200
|
const session = await this.openSession(agentSessionId, projectPath);
|
|
1743
2201
|
const entries = await session.getEntries();
|
|
1744
2202
|
return entries.flatMap(entry => {
|
|
1745
|
-
|
|
2203
|
+
let type;
|
|
2204
|
+
let message;
|
|
2205
|
+
if (entry.type === 'message') {
|
|
2206
|
+
const native = entry.message;
|
|
2207
|
+
if (native.role === 'toolResult') {
|
|
2208
|
+
type = 'user';
|
|
2209
|
+
message = { ...native, role: type, content: [{ type: 'tool_result', tool_use_id: native.toolCallId,
|
|
2210
|
+
content: native.content, is_error: native.isError }] };
|
|
2211
|
+
}
|
|
2212
|
+
else if (native.role === 'user' || native.role === 'assistant') {
|
|
2213
|
+
type = native.role;
|
|
2214
|
+
message = { ...native, content: Array.isArray(native.content) ? native.content.map(block => block.type === 'toolCall' ? { type: 'tool_use', id: block.id, name: block.name, input: block.arguments } : block) : native.content };
|
|
2215
|
+
}
|
|
2216
|
+
else
|
|
2217
|
+
return [];
|
|
2218
|
+
}
|
|
2219
|
+
else if (entry.type === 'custom' && entry.customType === 'evolcore_system_prompt') {
|
|
2220
|
+
type = 'system';
|
|
2221
|
+
message = { role: type, content: entry.data.content };
|
|
2222
|
+
}
|
|
2223
|
+
else if (entry.type === 'compaction' || entry.type === 'branch_summary') {
|
|
2224
|
+
type = 'system';
|
|
2225
|
+
message = { role: type, content: entry.summary, subtype: entry.type };
|
|
2226
|
+
}
|
|
2227
|
+
else if (entry.type === 'custom_message') {
|
|
2228
|
+
type = 'system';
|
|
2229
|
+
message = { role: type, content: entry.content, subtype: entry.customType };
|
|
2230
|
+
}
|
|
2231
|
+
else
|
|
1746
2232
|
return [];
|
|
1747
2233
|
return [{
|
|
1748
|
-
type
|
|
2234
|
+
type,
|
|
1749
2235
|
uuid: entry.id,
|
|
1750
2236
|
session_id: agentSessionId,
|
|
1751
|
-
message
|
|
2237
|
+
message,
|
|
1752
2238
|
parent_tool_use_id: null,
|
|
1753
2239
|
}];
|
|
1754
2240
|
});
|