evolcore 0.0.49 → 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 +103 -3
- package/bin/ec-build.mjs +60 -0
- package/bin/ecmsg.js +64 -57
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +173 -0
- package/dist/ability/caller/contract.js +117 -0
- package/dist/ability/caller/credential-files.js +132 -0
- package/dist/ability/caller/daemon.js +183 -0
- package/dist/ability/caller/schema-view.js +157 -0
- package/dist/ability/caller/service.js +519 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +156 -106
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +79 -3
- package/dist/agent-template/runtime.js +459 -47
- package/dist/agent-template/service.js +1242 -198
- package/dist/agent-template/share.js +103 -0
- package/dist/agent-template/tool-runner.js +25 -0
- package/dist/agent-template/types.js +10 -2
- 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} +78 -166
- 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} +652 -383
- 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 +96 -0
- package/dist/agents/{gemini-runner.js → gemini/runner.js} +18 -23
- package/dist/{core/session/adapters/gemini-session-file-adapter.js → agents/gemini/session-file-adapter.js} +2 -2
- package/dist/aun/ability-device-routing.js +11 -17
- package/dist/aun/aid/agentmd.js +27 -1
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/aid/managed-operation.js +6 -4
- package/dist/aun/group/invite-service.js +7 -37
- package/dist/aun/group/operations.js +6 -0
- 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/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +32 -4
- package/dist/aun/msg/upload.js +126 -3
- 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 +698 -213
- 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/claude-gateway/agent-registration.js +389 -0
- package/dist/claude-gateway/binding.js +96 -0
- package/dist/claude-gateway/inbox.js +138 -0
- package/dist/claude-gateway/index.js +125 -0
- package/dist/claude-gateway/listing.js +330 -0
- package/dist/claude-gateway/router.js +328 -0
- package/dist/claude-gateway/sessions.js +128 -0
- package/dist/claude-gateway/terminal.js +250 -0
- package/dist/claude-gateway/transcript.js +272 -0
- package/dist/claude-gateway/types.js +14 -0
- package/dist/cli/ability-command.js +45 -0
- package/dist/cli/ability-output.js +182 -0
- package/dist/cli/agent-command.js +21 -2
- package/dist/cli/agent-create.js +197 -56
- package/dist/cli/agent-template.js +400 -27
- package/dist/cli/agent.js +105 -11
- package/dist/cli/aun-commands.js +237 -123
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +283 -109
- 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 +64 -26
- package/dist/cli/fs-command.js +67 -39
- package/dist/cli/index.js +45 -12
- package/dist/cli/init.js +161 -90
- package/dist/cli/managed-command-guard.js +3 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/model.js +1 -1
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/restart-monitor.js +4 -4
- package/dist/cli/services-command.js +35 -10
- 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 +81 -14
- package/dist/cli/trigger-command.js +47 -12
- package/dist/cli/watch-logs.js +2 -1
- package/dist/config/access-policy.js +16 -3
- package/dist/config/boot-log.js +3 -0
- package/dist/config/builtin-role-templates.js +1 -1
- package/dist/config/config-field-policy.js +26 -13
- package/dist/config/config-manager.js +113 -52
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +29 -44
- package/dist/config/invoke-ipc-service.js +1 -1
- package/dist/config/owner-config.js +5 -19
- package/dist/config/peer-book-store.js +2 -3
- package/dist/config/peer-book.js +2 -2
- package/dist/config/peer-role-resolver.js +3 -9
- 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 +138 -31
- package/dist/config/providers-import.js +3 -3
- package/dist/config/providers-management.js +109 -118
- package/dist/config/resolved-config-op.js +1 -42
- package/dist/config/schema-migration.js +254 -15
- package/dist/config/schema-registry.js +53 -8
- package/dist/config-store.js +1343 -63
- package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +228 -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} +119 -25
- package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +65 -0
- package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +249 -79
- package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +23 -18
- package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
- package/dist/core/auth/agent-delegation.js +15 -8
- package/dist/core/auth/delegation-authorization.js +28 -0
- package/dist/core/auth/operation-authorizer.js +20 -2
- package/dist/core/auth/operation-catalog.js +80 -8
- 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} +89 -6
- package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
- package/dist/core/baseagent/baseagent-plugin-descriptor.js +357 -0
- 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 +91 -33
- 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} +21 -19
- package/dist/core/command/agent-control.js +80 -17
- package/dist/core/command/agent-template-menu.js +23 -10
- package/dist/core/command/agentmd-menu-request.js +19 -8
- package/dist/core/command/agentmd-menu.js +14 -5
- package/dist/core/command/cli-intent-parser.js +15 -0
- 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 +95 -19
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +392 -93
- package/dist/core/command/menu-protocol.js +47 -8
- package/dist/core/command/menu-query-batch.js +9 -5
- package/dist/core/command/private-mention-menu.js +71 -0
- 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 +143 -121
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/team-workspace-team.js +3 -3
- package/dist/core/command/topic-slash.js +16 -10
- package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -18
- package/dist/core/{daemon-control.js → daemon/daemon-control.js} +48 -21
- package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +28 -20
- package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +10 -5
- package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +101 -37
- 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 +2 -2
- 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 +57 -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 +3 -2
- package/dist/core/memory/consolidation-trigger.js +9 -3
- package/dist/core/memory/consolidation.js +39 -68
- 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 +204 -88
- package/dist/core/message/aun-request-registry.js +44 -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} +131 -1
- 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 +239 -59
- package/dist/core/message/message-log.js +8 -0
- package/dist/core/message/message-queue.js +88 -7
- package/dist/core/message/message-utils.js +1 -1
- package/dist/core/message/peer-mode.js +16 -5
- package/dist/core/message/response-engine.js +351 -152
- package/dist/core/message/send-options.js +44 -7
- package/dist/core/message/send-routing.js +55 -115
- 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 +18 -7
- package/dist/core/model/model-diagnostics.js +4 -4
- package/dist/core/ownership/owner-resolver.js +107 -101
- package/dist/core/{pack-auth.js → pack/pack-auth.js} +34 -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 +242 -82
- package/dist/core/permission/managed-file.js +234 -0
- package/dist/core/permission/protected-paths.js +120 -9
- package/dist/core/permission/sandbox-runtime.js +267 -3
- package/dist/core/permission/services-path-acl.js +9 -2
- package/dist/core/permission/session-path-grants.js +1 -1
- package/dist/core/permission/shell-environment.js +15 -1
- package/dist/core/permission/tool-policy.js +21 -9
- package/dist/core/plugin/plugin-lifecycle.js +442 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +2 -242
- package/dist/core/session/adapters/codex-session-file-adapter.js +2 -562
- 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 +76 -12
- package/dist/core/session/session-mapper.js +16 -0
- 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 +3 -3
- package/dist/core/skill/switch-resolver.js +3 -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/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +6 -4
- package/dist/core/thread/thread-operation.js +27 -11
- package/dist/core/thread/thread-route.js +5 -3
- package/dist/core/thread/thread-service.js +307 -58
- package/dist/core/thread/topic-id.js +52 -2
- package/dist/core/thread/types.js +15 -1
- 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 +3 -2
- package/dist/eck/manifest-engine.js +64 -2
- package/dist/eck/message-renderer.js +35 -0
- package/dist/ecweb/basic-settings-service.js +12 -10
- 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 +5 -3
- 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 +181 -77
- package/dist/ipc.js +161 -12
- 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 +60 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +196 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +30 -3
- package/dist/services/dispatcher.js +25 -7
- package/dist/services/host/main.js +397 -0
- package/dist/services/host/protocol.js +125 -0
- package/dist/services/host/resident.js +347 -0
- package/dist/services/host-client.js +398 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +208 -0
- package/dist/services/host-runtime.js +841 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +258 -36
- package/dist/services/ipc-operation.js +503 -78
- package/dist/services/pack-manager.js +2 -2
- package/dist/services/router.js +43 -3
- package/dist/services/script-runner.js +541 -100
- package/dist/services/service-payload.js +28 -1
- package/dist/services/validation.js +136 -5
- 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 +9 -6
- package/dist/trigger/authorization.js +36 -33
- package/dist/trigger/ipc-service.js +4 -4
- package/dist/trigger/local-files.js +8 -166
- package/dist/trigger/manager.js +2 -2
- package/dist/trigger/parser.js +48 -0
- package/dist/trigger/scheduler.js +35 -13
- package/dist/trigger/script-executor.js +21 -0
- package/dist/trigger/script-sandbox.js +77 -232
- package/dist/trigger/system-definitions.js +25 -0
- package/dist/trigger/validation.js +1 -1
- package/dist/utils/aid-bind.js +3 -0
- 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 +74 -1
- package/dist/utils/logger.js +5 -3
- package/dist/utils/media-cache.js +284 -42
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/startup-trace.js +20 -4
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/welcome.js +64 -20
- package/dist/utils/windows-shell-trust.js +7 -3
- 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 +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/channels/feishu.md +1 -1
- package/kits/docs/evolcore/INDEX.md +13 -9
- package/kits/docs/evolcore/agent-create.md +2 -0
- package/kits/docs/evolcore/agent.md +133 -11
- package/kits/docs/evolcore/aid.md +39 -6
- package/kits/docs/evolcore/config.md +95 -1
- 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 +5 -4
- package/kits/docs/evolcore/memory-consolidation.md +1 -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 +31 -2
- package/kits/docs/evolcore/model.md +12 -1
- package/kits/docs/evolcore/msg.md +96 -36
- package/kits/docs/evolcore/pay.md +22 -0
- package/kits/docs/evolcore/plugin.md +74 -0
- package/kits/docs/evolcore/provider.md +29 -2
- package/kits/docs/evolcore/rpc.md +2 -2
- package/kits/docs/evolcore/services.md +46 -18
- 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 +20 -9
- package/kits/docs/evolcore/tool-authorization.md +14 -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/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +20 -6
- package/kits/rules/06-channel.md +20 -4
- package/kits/schemas/_meta.json +42 -5
- 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 +974 -0
- 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.10.json +373 -0
- package/kits/schemas/daemon.schema.11.json +487 -0
- package/kits/schemas/daemon.schema.12.json +505 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -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 +26 -4
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +17 -1
- package/kits/skills/ability/SKILL.md +395 -33
- package/kits/skills/ability/STRUCTURE.md +338 -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 +80 -37
- 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 +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 +5 -5
- package/kits/skills/ec-identity/SKILL.md +9 -6
- package/kits/skills/ec-pay/SKILL.md +223 -0
- package/kits/skills/ec-provider/SKILL.md +6 -6
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +138 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -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 +3 -3
- 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/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +5 -4
- package/kits/templates/system-fragments/personal-assistant.md +2 -2
- package/kits/templates/system-fragments/reply.md +15 -9
- package/kits/templates/system-fragments/session.md +2 -2
- package/kits/templates/system-fragments/thread.md +30 -127
- package/kits/templates/system-fragments/venue.md +16 -0
- package/package.json +7 -7
- package/scripts/agent-template/index.mjs +7 -1
- package/scripts/agent-template/inspect.mjs +99 -39
- package/scripts/agent-template/overlay.mjs +126 -2
- package/scripts/agent-template/shared/common.mjs +49 -5
- 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 +468 -39
- package/scripts/agent-template/shared/template-contract.mjs +93 -51
- package/scripts/agent-template/shared/template-package.mjs +225 -44
- package/scripts/agent-template/shared/template-runtime.mjs +137 -15
- package/scripts/agent-template/shared/template.mjs +31 -8
- package/scripts/agent-template/team-pack.mjs +528 -56
- package/scripts/agent-template/team-preview.mjs +102 -9
- package/scripts/aid-batch/identity-batch.mjs +1 -1
- package/dist/agents/baseagent-availability.js +0 -152
- package/dist/agents/baseagent.js +0 -750
- 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/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/gemini-capability-provider.js → agents/gemini/capability-provider.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
|
@@ -6,8 +6,10 @@ import fs from 'fs';
|
|
|
6
6
|
import os from 'os';
|
|
7
7
|
import crypto from 'crypto';
|
|
8
8
|
import { MAIN_CLI_BIN } from '../../product.js';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
9
|
+
import { formatCompactingNotice, readLastModelCallContextUsage } from '../../stats/context-usage.js';
|
|
10
|
+
import { BaseagentRunnerUnavailableError, hasCompact, numericToken, formatAsyncQuestionAnswer, parseAsyncUserQuestions, } from '../baseagent/runner-types.js';
|
|
11
|
+
import { loadedBaseagentIds } from '../baseagent/baseagent-availability.js';
|
|
12
|
+
import { getExistingSelfAttachmentDirs } from '../permission/protected-paths.js';
|
|
11
13
|
import { isDiagnosticSessionActive } from '../command/diag-service.js';
|
|
12
14
|
import { evaluateInboundAdmissionPreflight, evaluateOrdinaryInboundAdmission } from './message-admission.js';
|
|
13
15
|
import { authorizeAccess, authorizeOperation, authorizeFreshOperation, buildAuthSubject } from '../auth/auth-gateway.js';
|
|
@@ -15,35 +17,35 @@ import { prepareSameOwnerProof, sameOwnerQualification, requiresSameOwnerProof }
|
|
|
15
17
|
import { getRoleDefinition } from '../../config/roles.js';
|
|
16
18
|
import { buildTaskRuntimeEnv, ensureRuntimeLockDir, ensureSessionRuntimeDirAsync } from '../../cli/task-context.js';
|
|
17
19
|
import { BUILTIN_SESSION_PATH_GRANTS, mergeRuntimeGrantsForSession, resolveGrantedReadRoots, } from '../permission/session-path-grants.js';
|
|
18
|
-
import { buildSystemSessionContext, getSystemSessionModule, isSystemSessionType, readSystemSessionMarker } from '../
|
|
20
|
+
import { buildSystemSessionContext, getSystemSessionModule, isSystemSessionType, readSystemSessionMarker } from '../session/system/registry.js';
|
|
19
21
|
import { IMRenderer } from './im-renderer.js';
|
|
20
22
|
import { projectSubtaskStarted, projectSubtaskTerminal } from './subtask-tool-projection.js';
|
|
21
23
|
import { TaskActivityStore, taskActivityTitle } from '../task/task-activity-store.js';
|
|
22
24
|
import { notifyWorkbenchRuntimeChanged } from '../../workbench/service.js';
|
|
23
25
|
import { createSendFileMarkerPattern } from './file-markers.js';
|
|
24
|
-
import { hasOwnerDirectoryMarkdown } from '../../directory/
|
|
25
|
-
import { EMPTY_IDENTITY, readOwnerDirectoryIdentity } from '../../directory/
|
|
26
|
+
import { hasOwnerDirectoryMarkdown } from '../../directory/markdown.js';
|
|
27
|
+
import { EMPTY_IDENTITY, readOwnerDirectoryIdentity } from '../../directory/identity.js';
|
|
26
28
|
import { createDecisionInferenceProvider, createTextInferenceProvider } from '../inference/text-inference.js';
|
|
27
29
|
import { StreamIdleMonitor } from './stream-idle-monitor.js';
|
|
28
30
|
import { logger } from '../../utils/logger.js';
|
|
29
31
|
import { isHostChinese } from '../../utils/locale.js';
|
|
30
|
-
import { ExecutionTimeoutError, OrphanedTargetSessionError, UnattendedInputRequiredError, isExecutionFailure, getErrorMessage, getErrorRawText, getToolResultErrorText, classifyError, normalizeCoreErrorReason, normalizeCoreErrorSubtype, ErrorType, ERROR_PREFIX, isInfraError, isAbortTerminalReason, prefixErrorType, isRetryableError, isContextTooLongText,
|
|
32
|
+
import { ExecutionTimeoutError, OrphanedTargetSessionError, UnattendedInputRequiredError, isExecutionFailure, getErrorMessage, getErrorRawText, getToolResultErrorText, classifyError, normalizeCoreErrorReason, normalizeCoreErrorSubtype, ErrorType, ERROR_PREFIX, isInfraError, isAbortTerminalReason, prefixErrorType, isRetryableError, isRecoverableError, isContextTooLongText, isConclusiveErrorSubtype } from '../../utils/error-utils.js';
|
|
31
33
|
import { readEvolcoreRuntimeFlavor, tagErrorTextWithEvolcoreVersion } from '../../utils/evolcore-version.js';
|
|
32
34
|
import { describeProactiveSendCommandFailure, isExactEvolcoreSendCommandForSession, isReadOnlyEcCommand, isThreadRoutedEvolcoreSendCommand, parseCodexToolCommand, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from '../permission/ec-command-parser.js';
|
|
33
35
|
import { resolveThreadRouteTarget } from '../thread/thread-route.js';
|
|
34
|
-
import { isMainSession, isTopicSession, isTopicThreadId, sessionLocalTopicId, sessionTopicThreadId } from '../thread/topic-id.js';
|
|
36
|
+
import { isMainSession, isMainTopicId, isTopicSession, isTopicThreadId, mainTopicPeer, sessionLocalTopicId, sessionTopicThreadId } from '../thread/topic-id.js';
|
|
35
37
|
import { summarizeToolInputForDisplay, toolInputForDisplay } from '../../utils/tool-summary.js';
|
|
36
38
|
import { agentDataDir, agentDir as resolveAgentDir, agentMdPath, agentSoulDir, getPackageRoot, resolveRoot, resolvePaths, debugSessionsDir } from '../../paths.js';
|
|
37
39
|
import { renderKitSections, resolveSessionManifest, DEFAULT_MANIFEST_FILE } from '../../eck/kit-renderer.js';
|
|
38
40
|
import { renderMessageBody } from '../../eck/message-renderer.js';
|
|
39
41
|
import { readLocalSelfIdentity } from '../../services/identity.js';
|
|
40
|
-
import { isOwnerDirectoryContact } from '../../directory/
|
|
42
|
+
import { isOwnerDirectoryContact } from '../../directory/admission.js';
|
|
41
43
|
import { syncGroupRulesContext } from '../../eck/group-rules-sync.js';
|
|
42
44
|
import { claimHints, commitHintClaim, releaseHintClaim, peekHints, hintsToSubMessages, composeHintFallback, OBSERVER_HINT_FAILURE_MESSAGES, } from './pending-hints.js';
|
|
43
45
|
import { createRootCausation, deriveCausation, normalizeCausation } from '../causation/context.js';
|
|
44
46
|
import { recordCausationLink, recordCausationSpan } from '../causation/audit.js';
|
|
45
|
-
import { normalizeBaseagent, resolveBaseagentModelSelection, resolveRuntimeBaseagentModelSelection } from '
|
|
46
|
-
import { renderActionAsText } from '
|
|
47
|
+
import { normalizeBaseagent, resolveBaseagentModelSelection, resolveRuntimeBaseagentModelSelection, usesNativeModelSelection } from '../baseagent/baseagent.js';
|
|
48
|
+
import { renderActionAsText } from './interaction-router.js';
|
|
47
49
|
import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
|
|
48
50
|
import { buildEnvelope, isInteractionSendAccepted, isNoopText, messageNoopSentinel, replyContextFromSession, sendInteractionPayload, withEnvelopeReplyContext } from './message-utils.js';
|
|
49
51
|
import { chatModeForScene, isSystemOrServicePeer, resolveChatMode } from './peer-mode.js';
|
|
@@ -66,14 +68,14 @@ import { errorQuestionRule } from '../../utils/error-utils.js';
|
|
|
66
68
|
import { catalogHash, clearModelCatalogCache, getRunnerCatalog } from '../model/model-catalog.js';
|
|
67
69
|
import { probeTextModel } from '../invoke/executors/text.js';
|
|
68
70
|
import { assertProviderModelAllowed } from '../../config/providers-config.js';
|
|
69
|
-
import { resolveCatalogAutoCompactPolicy } from '../model/model-capabilities.js';
|
|
70
|
-
import { resolveNativeConnectionForRepair } from '
|
|
71
|
+
import { resolveCatalogAutoCompactPolicy, readAgentCompactThreshold, resolveAgentContextPolicy } from '../model/model-capabilities.js';
|
|
72
|
+
import { resolveNativeConnectionForRepair } from '../baseagent/baseagent.js';
|
|
71
73
|
import { resolveProviderService, resolveProviderServiceForBaseagent } from '../../config/providers.js';
|
|
72
74
|
import { resolveAgentLifecycle } from '../../config/lifecycle.js';
|
|
73
75
|
import { authorizationConfigRevision, checkRoleAccess, getFirstStaticAgentOwner, listStaticAgentAdmins, listStaticAgentOwners, resolvePeerRoleDetail, roleToSessionIdentity, } from '../../config/peer-role-resolver.js';
|
|
74
76
|
import { insertUsageEvent, insertContextBreakdown, insertModelCalls } from '../../stats/writer.js';
|
|
75
77
|
import { normalizeUsage } from '../../stats/normalizer.js';
|
|
76
|
-
import { resolvePrices, roundCostForOutput } from '../../stats/model-resolver.js';
|
|
78
|
+
import { resolvePrices, roundCostForOutput, prepareUsagePricing, pricePairForOutput } from '../../stats/model-resolver.js';
|
|
77
79
|
import { getBudgetStatus } from '../../stats/budget.js';
|
|
78
80
|
import { formatUsageSubjectKey, getRoleBudgetStatus } from '../../stats/role-budget.js';
|
|
79
81
|
import { snapshot } from './response-snapshot.js';
|
|
@@ -88,6 +90,7 @@ import { normalizeToolErrorClassification } from '../permission/tool-error-code.
|
|
|
88
90
|
import { normalizeExecutionPermissionMode } from '../permission/mode.js';
|
|
89
91
|
import { buildToolLifecycleEventKey } from '../audit/event-key.js';
|
|
90
92
|
import { aunMessageTranscriptUuid } from '../session/session-transcript.js';
|
|
93
|
+
import { assertDeclaredBaseagentCapability } from '../baseagent/baseagent-capability-adapter.js';
|
|
91
94
|
import { assertAgentPolicyAuthorization } from '../role/runtime-policy.js';
|
|
92
95
|
import { auditFullAccessEvent } from '../auth/authorization-audit.js';
|
|
93
96
|
import { REPLY_DELIVERY_FAILED_REASON, TaskRecoveryService, isTaskRecoveryCurrent } from '../task/task-recovery-service.js';
|
|
@@ -115,9 +118,23 @@ export function resolveMessageChannelType(options, message) {
|
|
|
115
118
|
}
|
|
116
119
|
const QUESTION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
117
120
|
/** Pending async questions outlive the originating turn, but never change its backend binding. */
|
|
118
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* 带 --thread 的跨话题发送:话题合法即视为合法发送。
|
|
123
|
+
*
|
|
124
|
+
* 独立话题查索引;主话题只校验「含本端」——首次联系时目标会话还不存在,
|
|
125
|
+
* 不能因为索引里查不到就把一次合法发送判成未表达意图。
|
|
126
|
+
*/
|
|
119
127
|
function isThreadRoutedSendForSelf(toolName, toolInput, selfAid) {
|
|
120
|
-
return isThreadRoutedEvolcoreSendCommand(toolName, toolInput, selfAid, (scope, threadId, target) =>
|
|
128
|
+
return isThreadRoutedEvolcoreSendCommand(toolName, toolInput, selfAid, (scope, threadId, target) => {
|
|
129
|
+
if (!selfAid)
|
|
130
|
+
return false;
|
|
131
|
+
if (isMainTopicId(threadId)) {
|
|
132
|
+
if (!mainTopicPeer(threadId, selfAid))
|
|
133
|
+
return false;
|
|
134
|
+
return target === undefined || !!resolveThreadRouteTarget(selfAid, threadId, scope, target);
|
|
135
|
+
}
|
|
136
|
+
return !!resolveThreadRouteTarget(selfAid, threadId, scope, target);
|
|
137
|
+
});
|
|
121
138
|
}
|
|
122
139
|
class AsyncQuestionCancelledError extends Error {
|
|
123
140
|
}
|
|
@@ -126,6 +143,7 @@ export class AsyncQuestionService {
|
|
|
126
143
|
registered = new Map();
|
|
127
144
|
deliveries = new Map();
|
|
128
145
|
blockingWaiters = new Map();
|
|
146
|
+
submissions = new Map();
|
|
129
147
|
constructor(deps) {
|
|
130
148
|
this.deps = deps;
|
|
131
149
|
}
|
|
@@ -213,6 +231,7 @@ export class AsyncQuestionService {
|
|
|
213
231
|
};
|
|
214
232
|
const record = existing ?? {
|
|
215
233
|
version: 1, id, sessionId: session.id, selfAid: session.selfAID,
|
|
234
|
+
baseagent: session.baseagent, questionIndex: index, batchSize: questions.length,
|
|
216
235
|
providerThreadId: request.providerThreadId, providerTurnId: request.providerTurnId,
|
|
217
236
|
itemId: request.itemId, question,
|
|
218
237
|
origin: {
|
|
@@ -293,7 +312,7 @@ export class AsyncQuestionService {
|
|
|
293
312
|
}
|
|
294
313
|
async validSession(record) {
|
|
295
314
|
const session = await this.deps.getSession(record.sessionId);
|
|
296
|
-
if (!session || session.baseagent !== 'codex' || session.selfAID !== record.selfAid
|
|
315
|
+
if (!session || session.baseagent !== (record.baseagent ?? 'codex') || session.selfAID !== record.selfAid
|
|
297
316
|
|| session.agentSessionId !== record.providerThreadId
|
|
298
317
|
|| session.channel !== record.origin.channel
|
|
299
318
|
|| session.channelType !== record.origin.channelType
|
|
@@ -303,6 +322,24 @@ export class AsyncQuestionService {
|
|
|
303
322
|
return undefined;
|
|
304
323
|
return session;
|
|
305
324
|
}
|
|
325
|
+
/** A stopped DSH tool resumes once the entire persisted blocking batch is answered. */
|
|
326
|
+
resumeBatch(record) {
|
|
327
|
+
const batch = fs.readdirSync(this.directory(record.selfAid)).filter(name => /^aq-[a-f0-9]{40}\.json$/.test(name))
|
|
328
|
+
.map(name => this.read(record.selfAid, name.slice(0, -5)))
|
|
329
|
+
.filter((item) => !!item && item.sessionId === record.sessionId
|
|
330
|
+
&& item.baseagent === record.baseagent && item.providerThreadId === record.providerThreadId
|
|
331
|
+
&& item.providerTurnId === record.providerTurnId && item.itemId === record.itemId);
|
|
332
|
+
if (batch.length !== record.batchSize || batch.some(item => item.status === 'cancelled')) {
|
|
333
|
+
throw new Error('DSH question batch is incomplete or cancelled');
|
|
334
|
+
}
|
|
335
|
+
if (batch.some(item => item.id !== record.id && item.status !== 'answered'))
|
|
336
|
+
return undefined;
|
|
337
|
+
return batch.sort((a, b) => (a.questionIndex ?? 0) - (b.questionIndex ?? 0)).map(item => ({
|
|
338
|
+
requestId: item.id, providerThreadId: item.providerThreadId, questionItemId: item.itemId,
|
|
339
|
+
question: item.question.title, answer: item.answer,
|
|
340
|
+
...(item.interruptedTools?.length ? { interruptedTools: item.interruptedTools } : {}),
|
|
341
|
+
}));
|
|
342
|
+
}
|
|
306
343
|
/** Recheck persisted answers after queue delays/restarts, immediately before a provider run. */
|
|
307
344
|
async validateQueuedAnswer(session, answer) {
|
|
308
345
|
if (!session.selfAID)
|
|
@@ -391,7 +428,13 @@ export class AsyncQuestionService {
|
|
|
391
428
|
current.answer = answer;
|
|
392
429
|
current.status = 'submitting';
|
|
393
430
|
this.save(current);
|
|
394
|
-
|
|
431
|
+
const batchKey = JSON.stringify([current.selfAid, current.sessionId, current.providerThreadId, current.itemId]);
|
|
432
|
+
const previous = this.submissions.get(batchKey) ?? Promise.resolve();
|
|
433
|
+
const submission = previous.catch(() => { }).then(async () => {
|
|
434
|
+
// Different cards of one batch may be answered concurrently. Persist each settlement
|
|
435
|
+
// before the next submit checks whether this is the last answer required for resume.
|
|
436
|
+
if (!(await this.validSession(current)))
|
|
437
|
+
throw new Error('Async question binding or authorization changed before submission');
|
|
395
438
|
await this.deps.submit(current, session, {
|
|
396
439
|
requestId: current.id, providerThreadId: current.providerThreadId,
|
|
397
440
|
questionItemId: current.itemId, question: current.question.title, answer,
|
|
@@ -399,6 +442,10 @@ export class AsyncQuestionService {
|
|
|
399
442
|
});
|
|
400
443
|
current.status = 'answered';
|
|
401
444
|
this.save(current);
|
|
445
|
+
});
|
|
446
|
+
this.submissions.set(batchKey, submission);
|
|
447
|
+
try {
|
|
448
|
+
await submission;
|
|
402
449
|
this.registered.delete(record.id);
|
|
403
450
|
this.resolveBlocking(record.id);
|
|
404
451
|
try {
|
|
@@ -418,6 +465,10 @@ export class AsyncQuestionService {
|
|
|
418
465
|
logger.warn(`[AsyncQuestions] answer submission failed: request=${record.id} error=${String(error)}`);
|
|
419
466
|
throw error;
|
|
420
467
|
}
|
|
468
|
+
finally {
|
|
469
|
+
if (this.submissions.get(batchKey) === submission)
|
|
470
|
+
this.submissions.delete(batchKey);
|
|
471
|
+
}
|
|
421
472
|
}, {
|
|
422
473
|
initiatorId: record.origin.peerId, initiatorChannelKey: adapter.channelKey,
|
|
423
474
|
blocking: record.blocking,
|
|
@@ -853,6 +904,51 @@ function addNestedShellDiagnosticFinding(findings, candidate) {
|
|
|
853
904
|
return;
|
|
854
905
|
findings.push(diagnosticFinding('nested-shell-escaping-risk', '命令包含嵌套 Shell 包装层', '尽量直接提交单层 Shell 命令;需要 heredoc 或 JSON 时,减少外层转义和包装。', '中', candidate.source, candidate.commandOffset, candidate.commandOffset + candidate.command.length));
|
|
855
906
|
}
|
|
907
|
+
/** 只有真正交给 Shell 执行、且失败输出印证了转义折叠时才提示,避免误报。 */
|
|
908
|
+
const SHELL_TOOL_NAME_SET = new Set(['Shell', 'Bash', 'bash', 'shell', 'shell_command']);
|
|
909
|
+
/**
|
|
910
|
+
* 输出里出现这些片段,说明脚本收到的路径少了分隔符——反斜杠成了转义序列,把后面的
|
|
911
|
+
* `\U`、`\a`、`\R` 吃掉了。两种形态:盘符后直接接目录名(`C:Usersagentcp`),
|
|
912
|
+
* 或路径中途某个目录名与下一段粘在一起(`…\evolcore\UsersagentcpAppData`)。
|
|
913
|
+
*/
|
|
914
|
+
const ESCAPE_COLLAPSE_OUTPUT_EVIDENCE = [
|
|
915
|
+
/SyntaxError: (?:Invalid hexadecimal|Bad character|Invalid Unicode) escape sequence/,
|
|
916
|
+
/\b[A-Za-z]:(?:Users|Windows|ProgramData|Program)[A-Za-z0-9_]{2,}/u,
|
|
917
|
+
/[\\/](?:Users|AppData|Roaming|ProgramData|Windows|Desktop|Documents)(?=[a-z0-9_])/u,
|
|
918
|
+
];
|
|
919
|
+
/** 内联脚本的引号区间:`node -e "…"`、`python -c "…"` 之类。 */
|
|
920
|
+
function findInlineScriptSpan(command) {
|
|
921
|
+
for (const match of command.matchAll(/(?:^|[\s;&|('"=])-(?:e|c|p)\s+"/gu)) {
|
|
922
|
+
const quoteStart = (match.index ?? 0) + match[0].length - 1;
|
|
923
|
+
let index = quoteStart + 1;
|
|
924
|
+
while (index < command.length) {
|
|
925
|
+
if (command[index] === '\\') {
|
|
926
|
+
index += 2;
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
if (command[index] === '"')
|
|
930
|
+
return { start: quoteStart + 1, end: index };
|
|
931
|
+
index++;
|
|
932
|
+
}
|
|
933
|
+
return { start: quoteStart + 1, end: command.length };
|
|
934
|
+
}
|
|
935
|
+
return undefined;
|
|
936
|
+
}
|
|
937
|
+
function addShellEscapeCollapseFinding(findings, candidate, toolName, eventText) {
|
|
938
|
+
if (!SHELL_TOOL_NAME_SET.has(toolName))
|
|
939
|
+
return;
|
|
940
|
+
if (!ESCAPE_COLLAPSE_OUTPUT_EVIDENCE.some(pattern => pattern.test(eventText)))
|
|
941
|
+
return;
|
|
942
|
+
const span = findInlineScriptSpan(candidate.command);
|
|
943
|
+
if (!span)
|
|
944
|
+
return;
|
|
945
|
+
const body = candidate.command.slice(span.start, span.end);
|
|
946
|
+
const backslash = body.indexOf('\\');
|
|
947
|
+
if (backslash < 0)
|
|
948
|
+
return;
|
|
949
|
+
findings.push(diagnosticFinding('shell-inline-script-backslash-collapse', '引号内脚本里的反斜杠被当成转义序列', '双引号不会改写反斜杠:`\\U`、`\\a` 这类会原样进入脚本,被当成转义序列,字符被吃掉甚至直接 SyntaxError。'
|
|
950
|
+
+ '把路径写成正斜杠(`C:/Users/...`),或在脚本里按脚本语言再转义一次(写 `\\\\`)。', '高', candidate.source, span.start + backslash, span.start + Math.min(backslash + 2, body.length)));
|
|
951
|
+
}
|
|
856
952
|
function addJsonArrayDiagnosticFinding(findings, input, displayInput) {
|
|
857
953
|
const rawArgv = isStringArgv(input.commandArgv) ? input.commandArgv : undefined;
|
|
858
954
|
const parsedArgv = rawArgv ?? (typeof input.command === 'string'
|
|
@@ -930,6 +1026,10 @@ function diagnoseToolInput(original, event, deadline) {
|
|
|
930
1026
|
const candidates = diagnosticCandidates(input, displayInput);
|
|
931
1027
|
if (Date.now() > deadline)
|
|
932
1028
|
return undefined;
|
|
1029
|
+
// 转义折叠要用真实失败输出做证据,不能用被裁剪过的展示文本。
|
|
1030
|
+
const eventText = typeof event.error === 'string' && event.error
|
|
1031
|
+
? event.error
|
|
1032
|
+
: typeof event.result === 'string' ? event.result : '';
|
|
933
1033
|
const findings = [];
|
|
934
1034
|
for (const candidate of candidates) {
|
|
935
1035
|
if (Date.now() > deadline)
|
|
@@ -938,6 +1038,7 @@ function diagnoseToolInput(original, event, deadline) {
|
|
|
938
1038
|
addHeredocDiagnosticFindings(findings, candidate);
|
|
939
1039
|
addApplyPatchCompositionFinding(findings, candidate);
|
|
940
1040
|
addNestedShellDiagnosticFinding(findings, candidate);
|
|
1041
|
+
addShellEscapeCollapseFinding(findings, candidate, original.name, eventText);
|
|
941
1042
|
}
|
|
942
1043
|
if (Date.now() <= deadline)
|
|
943
1044
|
addJsonArrayDiagnosticFinding(findings, input, displayInput);
|
|
@@ -1330,7 +1431,9 @@ function getStreamRawErrorText(result, fallback) {
|
|
|
1330
1431
|
return candidates.find((part) => typeof part === 'string' && part.trim().length > 0);
|
|
1331
1432
|
}
|
|
1332
1433
|
function getStreamErrorMessage(result, includeEmoji = false) {
|
|
1333
|
-
|
|
1434
|
+
// 合成错误帧是上游给出的错误原文,比 subtype/terminalReason 拼出来的串更能定位原因,
|
|
1435
|
+
// 优先拿它去分类;分类不出时 getErrorMessage 会把原文带上。
|
|
1436
|
+
const raw = result.syntheticDiagnosticText || getStreamErrorText(result);
|
|
1334
1437
|
return getErrorMessage(new Error(raw), result.terminalReason, includeEmoji);
|
|
1335
1438
|
}
|
|
1336
1439
|
function streamHitContextLimit(result) {
|
|
@@ -1477,6 +1580,12 @@ export class ResponseEngine {
|
|
|
1477
1580
|
primaryRunnerKey;
|
|
1478
1581
|
daemonTriggerOwnerAid;
|
|
1479
1582
|
interruptedSessions = new Map(); // sessionId → reason ('new_message' | 'stop' | ...)
|
|
1583
|
+
/**
|
|
1584
|
+
* 回合被判过期后,renderer 交出来却卡在 canPublish 门禁上的正文:taskId → 文本片段。
|
|
1585
|
+
* 门禁拦下的那一刻 buffer 已经清空,事后再从 renderer 里也捞不回来,所以在这里兜住,
|
|
1586
|
+
* 由收尾的补投统一发出。模型输出过就算数,不能因为判定过期就没收。
|
|
1587
|
+
*/
|
|
1588
|
+
heldStaleOutput = new Map();
|
|
1480
1589
|
timeoutErrors = new Map();
|
|
1481
1590
|
activeTimeoutHandlers = new Map();
|
|
1482
1591
|
/** sessionId → 已成功的模型降级状态(进程重启清零) */
|
|
@@ -1656,6 +1765,29 @@ export class ResponseEngine {
|
|
|
1656
1765
|
return 'interactive';
|
|
1657
1766
|
}
|
|
1658
1767
|
}
|
|
1768
|
+
resolveTaskChatMode(message, session, context) {
|
|
1769
|
+
if (this.isTrustedDaemonTrigger(message)
|
|
1770
|
+
&& message.channelId === `trigger:${message.triggerMeta.triggerId}`)
|
|
1771
|
+
return 'interactive';
|
|
1772
|
+
const sessionChatMode = message.source === 'trigger'
|
|
1773
|
+
&& !readSystemSessionMarker(session.metadata)
|
|
1774
|
+
? this.resolveEffectiveChatmodeForSession(session, context.channelKey, message.channelId)
|
|
1775
|
+
: undefined;
|
|
1776
|
+
if (sessionChatMode) {
|
|
1777
|
+
return context.triggerOverride
|
|
1778
|
+
? chatModeForScene(context.triggerOverride, {
|
|
1779
|
+
...context, peerType: session.metadata?.peerType,
|
|
1780
|
+
})
|
|
1781
|
+
: sessionChatMode;
|
|
1782
|
+
}
|
|
1783
|
+
if (context.chatType === 'group')
|
|
1784
|
+
return 'proactive';
|
|
1785
|
+
if (isSystemOrServicePeer(context.peerType))
|
|
1786
|
+
return 'interactive';
|
|
1787
|
+
return context.triggerOverride
|
|
1788
|
+
? chatModeForScene(context.triggerOverride, context)
|
|
1789
|
+
: context.fallback;
|
|
1790
|
+
}
|
|
1659
1791
|
/** 获取可用 agent 列表 */
|
|
1660
1792
|
getAvailableAgents() {
|
|
1661
1793
|
return [...this.agentMap.keys()];
|
|
@@ -2111,18 +2243,22 @@ export class ResponseEngine {
|
|
|
2111
2243
|
})).allow;
|
|
2112
2244
|
}
|
|
2113
2245
|
async submitAsyncQuestionAnswer(record, session, answer) {
|
|
2114
|
-
const
|
|
2246
|
+
const baseagent = record.baseagent ?? 'codex';
|
|
2247
|
+
const runner = await this.ensureAgent(record.origin.channel, baseagent, record.selfAid);
|
|
2115
2248
|
if (!runner.steerAsyncQuestionAnswer)
|
|
2116
|
-
throw new Error(
|
|
2249
|
+
throw new Error(`${baseagent} async input is unavailable`);
|
|
2117
2250
|
if (await runner.steerAsyncQuestionAnswer(session.id, answer) === 'accepted')
|
|
2118
2251
|
return;
|
|
2252
|
+
const answers = baseagent === 'dsh' ? this.asyncQuestions?.resumeBatch(record) : [answer];
|
|
2253
|
+
if (!answers)
|
|
2254
|
+
return;
|
|
2119
2255
|
if (!this.messageQueue)
|
|
2120
2256
|
throw new Error('Async question resume queue is unavailable');
|
|
2121
2257
|
// The queue owns idle-thread restoration and a fresh task/permission context.
|
|
2122
2258
|
// Keep the exact Session/backend identity; never create a new topic for an old card.
|
|
2123
2259
|
await this.messageQueue.enqueuePersisted(session.id, {
|
|
2124
|
-
...record.origin, content: formatAsyncQuestionAnswer(
|
|
2125
|
-
asyncQuestionAnswer: answer, boundSessionId: session.id, baseagent
|
|
2260
|
+
...record.origin, content: answers.map(formatAsyncQuestionAnswer).join('\n'),
|
|
2261
|
+
asyncQuestionAnswer: answer, boundSessionId: session.id, baseagent,
|
|
2126
2262
|
source: 'card-trigger', messageId: `async-answer-${record.id}`,
|
|
2127
2263
|
timestamp: Date.now(), receivedAt: Date.now(),
|
|
2128
2264
|
encrypted: record.envelope.replyContext?.metadata?.encrypted,
|
|
@@ -2397,7 +2533,7 @@ export class ResponseEngine {
|
|
|
2397
2533
|
}
|
|
2398
2534
|
/**
|
|
2399
2535
|
* 出站 payload.debug 的会话侧字段(不含 sentAt,由发送方盖戳)。
|
|
2400
|
-
* 供 agent 经
|
|
2536
|
+
* 供 agent 经 ecmsg 委托发送的路径使用,
|
|
2401
2537
|
* 与 IMRenderer 回复路径写入的 debug 同构。会话不存在返回 undefined。
|
|
2402
2538
|
*/
|
|
2403
2539
|
async getOutboundDebug(sessionId) {
|
|
@@ -2626,7 +2762,7 @@ export class ResponseEngine {
|
|
|
2626
2762
|
const active = this.activeRenderers.get(sessionId);
|
|
2627
2763
|
if (!active || active.suppressActivities)
|
|
2628
2764
|
return;
|
|
2629
|
-
void this.emitOperationalNotice(active.renderer,
|
|
2765
|
+
void this.readLastModelCallContextUsage(sessionId, active.agentSessionId || '').then(ctx => this.emitOperationalNotice(active.renderer, formatCompactingNotice(ctx?.totalTokens), 'info', 'compact-start'))
|
|
2630
2766
|
.catch(error => logger.warn(`[ResponseEngine] compact-start notice send failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
2631
2767
|
}
|
|
2632
2768
|
async emitOperationalNotice(renderer, text, severity, subtype) {
|
|
@@ -2681,7 +2817,8 @@ export class ResponseEngine {
|
|
|
2681
2817
|
: modelOverride;
|
|
2682
2818
|
// text event 在进入 renderer 前已经剔除了上下文超限错误行。保留缓冲中的
|
|
2683
2819
|
// 有效正文,由 sendOperationalNotice 先 flush,避免恢复过程丢失已有模型输出。
|
|
2684
|
-
await this.
|
|
2820
|
+
const contextUsage = await this.readLastModelCallContextUsage(session.id, session.agentSessionId);
|
|
2821
|
+
await this.emitOperationalNotice(renderer, formatCompactingNotice(contextUsage?.totalTokens), 'warn', 'compact-trigger');
|
|
2685
2822
|
await renderer.flush();
|
|
2686
2823
|
this.announcedCompactStarts.add(session.id);
|
|
2687
2824
|
let compacted;
|
|
@@ -2992,7 +3129,7 @@ export class ResponseEngine {
|
|
|
2992
3129
|
originTriggerId: trigger.triggerId,
|
|
2993
3130
|
messageId: opts.messageId ?? message.messageId ?? runId,
|
|
2994
3131
|
error,
|
|
2995
|
-
recoverable: opts.recoverable ??
|
|
3132
|
+
recoverable: opts.recoverable ?? isRecoverableError(new Error(error)),
|
|
2996
3133
|
targetChannel: message.channel,
|
|
2997
3134
|
targetChannelId: message.channelId,
|
|
2998
3135
|
fireTime: trigger.fireTime ?? 0,
|
|
@@ -3024,6 +3161,50 @@ export class ResponseEngine {
|
|
|
3024
3161
|
causation: causation ?? message.causation,
|
|
3025
3162
|
});
|
|
3026
3163
|
}
|
|
3164
|
+
/**
|
|
3165
|
+
* 被打断的回合里模型已经产出的正文,必须送到对端。
|
|
3166
|
+
*
|
|
3167
|
+
* 模型只要输出过,内容就已经进入会话上下文;对端收不到只意味着「产出被丢弃」,
|
|
3168
|
+
* 而不是「这轮没发生」。所以收尾只做一件事:把尚未发出的正文补投出去。
|
|
3169
|
+
* 不发任何「被打断 / 请重发」的告知——那会把一次内容丢失伪装成需要人工重试,
|
|
3170
|
+
* 也会让对方把它当成新消息再起一轮。
|
|
3171
|
+
*
|
|
3172
|
+
* 补投绕过 renderer 的 stale 门禁(那里会整条静默丢弃),但绝不重放 agent:
|
|
3173
|
+
* 重放会与抢占本轮的回合争同一个 session。
|
|
3174
|
+
*/
|
|
3175
|
+
async deliverInterruptedTurnOutput(message, adapter, envelope, renderer, session, taskId) {
|
|
3176
|
+
// Trigger / bg-session 有自己的收尾通道,且它们的产物不经对话正文投递。
|
|
3177
|
+
if (this.isTrustedDaemonTrigger(message) || this.isTrustedBgSession(message))
|
|
3178
|
+
return;
|
|
3179
|
+
// ① 门禁已经拦下的正文(renderer buffer 已被清空,只能从暂存取回)。
|
|
3180
|
+
const held = this.heldStaleOutput.get(taskId) ?? [];
|
|
3181
|
+
this.heldStaleOutput.delete(taskId);
|
|
3182
|
+
// ② 还没交出去的正文(含 proactive 的终稿)。
|
|
3183
|
+
let drained = '';
|
|
3184
|
+
try {
|
|
3185
|
+
drained = renderer.drainUnsentText();
|
|
3186
|
+
}
|
|
3187
|
+
catch (error) {
|
|
3188
|
+
logger.warn(`[ResponseEngine] interrupted output drain failed: task=${taskId} error=${error instanceof Error ? error.message : String(error)}`);
|
|
3189
|
+
}
|
|
3190
|
+
const text = [...held, drained].filter(part => part.trim()).join('\n');
|
|
3191
|
+
if (!text.trim()) {
|
|
3192
|
+
logger.info(`[ResponseEngine] interrupted turn had no unsent output: task=${taskId}`);
|
|
3193
|
+
return;
|
|
3194
|
+
}
|
|
3195
|
+
try {
|
|
3196
|
+
await adapter.send(withEnvelopeReplyContext(envelope, {
|
|
3197
|
+
...replyContextFromSession(session),
|
|
3198
|
+
sessionId: session.id,
|
|
3199
|
+
threadId: sessionTopicThreadId(session) ?? session.metadata?.replyContext?.threadId,
|
|
3200
|
+
}), { kind: 'result.text', text, isFinal: true });
|
|
3201
|
+
logger.info(`[ResponseEngine] interrupted output delivered: task=${taskId} length=${text.length} channel=${message.channel}`);
|
|
3202
|
+
}
|
|
3203
|
+
catch (error) {
|
|
3204
|
+
// 补投失败不能影响中断收尾本身,只留痕。
|
|
3205
|
+
logger.warn(`[ResponseEngine] interrupted output delivery failed: task=${taskId} error=${error instanceof Error ? error.message : String(error)}`);
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3027
3208
|
/** Close the internal daemon conversation before returning from an interrupted Trigger turn. */
|
|
3028
3209
|
async publishTriggerExecutionInterrupted(message, adapter, envelope, reason, causation, generation) {
|
|
3029
3210
|
const interruption = reason === 'stale_generation'
|
|
@@ -3077,7 +3258,7 @@ export class ResponseEngine {
|
|
|
3077
3258
|
static COMMAND_PREFIXES = [
|
|
3078
3259
|
'/new', '/pwd', '/help', '/status', '/restart',
|
|
3079
3260
|
'/model', '/effort', '/agent', '/slist', '/session', '/rename', '/repair', '/fork',
|
|
3080
|
-
'/stop', '/pause', '/resume', '/
|
|
3261
|
+
'/stop', '/pause', '/resume', '/compact', '/renew', '/del', '/perm', '/file', '/check',
|
|
3081
3262
|
'/s ', '/name ', '/rewind', '/rw', '/rw ', '/activity', '/observable', '/chatmode',
|
|
3082
3263
|
'/aid', '/upgrade', '/update', '/evolagent', '/pair ', '/memory',
|
|
3083
3264
|
];
|
|
@@ -3823,6 +4004,7 @@ export class ResponseEngine {
|
|
|
3823
4004
|
// 静默丢弃而不是发送给 Agent(命令已在 MessageBridge 层处理过)
|
|
3824
4005
|
const rawContent = message.content.replace(/^(>[^\n]*\n)+\n?/, '').trim();
|
|
3825
4006
|
if (!message.executionPermissionOverride
|
|
4007
|
+
&& !message.literalModelInput
|
|
3826
4008
|
&& rawContent.startsWith('/')
|
|
3827
4009
|
&& this.isKnownCommand(rawContent)) {
|
|
3828
4010
|
logger.warn(`[ResponseEngine] Command leaked past MessageBridge, dropped: "${rawContent.substring(0, 40)}"`);
|
|
@@ -3866,6 +4048,7 @@ export class ResponseEngine {
|
|
|
3866
4048
|
let taskActivityStatus = 'running';
|
|
3867
4049
|
const taskActivityStore = runnerSelfAid ? new TaskActivityStore(runnerSelfAid) : undefined;
|
|
3868
4050
|
let toolImageReadRoots = [];
|
|
4051
|
+
let toolImageAttachmentSelfAid;
|
|
3869
4052
|
if (taskActivityStore) {
|
|
3870
4053
|
try {
|
|
3871
4054
|
const activityChatType = chatType === 'group' ? 'group' : 'private';
|
|
@@ -4062,9 +4245,10 @@ export class ResponseEngine {
|
|
|
4062
4245
|
}
|
|
4063
4246
|
})();
|
|
4064
4247
|
// ─── 响应模式解析(插件化机制中枢)───
|
|
4065
|
-
//
|
|
4248
|
+
// chatmode 覆写只决定投递方式;响应模式仍负责装配运行时策略。
|
|
4066
4249
|
const systemOrServicePeer = isSystemOrServicePeer(peerType);
|
|
4067
|
-
const triggerChatModeOverride = systemOrServicePeer
|
|
4250
|
+
const triggerChatModeOverride = systemOrServicePeer && message.source !== 'trigger'
|
|
4251
|
+
? undefined : message.triggerMeta?.chatModeOverride;
|
|
4068
4252
|
// chatmode 是顶层字典(agent 级与关系级同名,已由 ConfigManager 逐键合并)。
|
|
4069
4253
|
// 实际生效值由对端类型选键(private/nothuman/group),出厂默认走 schema。
|
|
4070
4254
|
const chatModeFallback = resolveChatMode({
|
|
@@ -4075,20 +4259,21 @@ export class ResponseEngine {
|
|
|
4075
4259
|
peerType,
|
|
4076
4260
|
channelType: currentChannelType,
|
|
4077
4261
|
});
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4082
|
-
|
|
4083
|
-
|
|
4084
|
-
|
|
4085
|
-
|
|
4086
|
-
|
|
4262
|
+
const effectiveChatMode = this.resolveTaskChatMode(message, session, {
|
|
4263
|
+
channelKey,
|
|
4264
|
+
channelType: currentChannelType,
|
|
4265
|
+
chatType,
|
|
4266
|
+
peerType,
|
|
4267
|
+
role: peerRole,
|
|
4268
|
+
fallback: chatModeFallback,
|
|
4269
|
+
triggerOverride: triggerChatModeOverride,
|
|
4270
|
+
});
|
|
4087
4271
|
const responseModeAgentDir = selfAid ? resolveAgentDir(selfAid) : undefined;
|
|
4088
4272
|
// mentionMode:顶层通用参数(先读出备用,投递/入队策略后续接入)
|
|
4089
4273
|
const mentionMode = effectiveAgentConfig?.mentionMode ?? 'disabled';
|
|
4090
|
-
|
|
4091
|
-
|
|
4274
|
+
// 主动模式的 Trigger / system 输入也必须装配策略,供托管 PreToolUse 校验。
|
|
4275
|
+
const resolvedMode = !responseModeAgentDir
|
|
4276
|
+
|| ((triggerChatModeOverride || systemOrServicePeer) && effectiveChatMode !== 'proactive')
|
|
4092
4277
|
? null
|
|
4093
4278
|
: this.responseCoordinator.resolveMode(effectiveAgentConfig?.responseMode, // 标量:关系级>agent级>注册表首选
|
|
4094
4279
|
effectiveChatMode, effectiveAgentConfig?.responseModeParams, // 按模式分桶的参数字典
|
|
@@ -4387,7 +4572,7 @@ export class ResponseEngine {
|
|
|
4387
4572
|
this.interruptedSessions.set(session.id, 'proactive_circuit_break');
|
|
4388
4573
|
void adapter.send(withEnvelopeReplyContext(envelope, taskReplyContext()), {
|
|
4389
4574
|
kind: 'result.text',
|
|
4390
|
-
text: '⚠️
|
|
4575
|
+
text: '⚠️ 这个任务卡住了,我先停下了。请重新说明一下需求。',
|
|
4391
4576
|
isFinal: true,
|
|
4392
4577
|
}).catch(error => {
|
|
4393
4578
|
logger.warn(`[ResponseEngine] circuit break channel send failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -4510,7 +4695,7 @@ export class ResponseEngine {
|
|
|
4510
4695
|
? undefined : effectiveAgentConfig?.baseagents?.[modelBaseagent];
|
|
4511
4696
|
// Preserve actionable connection failures before default-model discovery
|
|
4512
4697
|
// intentionally folds transport diagnostics into MODEL_UNAVAILABLE.
|
|
4513
|
-
if (configuredBaseagent?.provider) {
|
|
4698
|
+
if (configuredBaseagent?.provider && !usesNativeModelSelection(modelBaseagent, configuredBaseagent)) {
|
|
4514
4699
|
const provider = resolveProviderServiceForBaseagent(configuredBaseagent.provider, modelBaseagent);
|
|
4515
4700
|
if (!provider.apiKey?.trim())
|
|
4516
4701
|
throw new Error(`Provider ${provider.providerId} has no API key`);
|
|
@@ -4518,7 +4703,9 @@ export class ResponseEngine {
|
|
|
4518
4703
|
const triggerModel = message.triggerMeta?.modelOverride;
|
|
4519
4704
|
let agentModel;
|
|
4520
4705
|
let modelFailure;
|
|
4706
|
+
let nativeModelSelection = false;
|
|
4521
4707
|
try {
|
|
4708
|
+
nativeModelSelection = usesNativeModelSelection(modelBaseagent, configuredBaseagent);
|
|
4522
4709
|
agentModel = typeof triggerModel === 'string' && triggerModel.trim()
|
|
4523
4710
|
? triggerModel
|
|
4524
4711
|
: (await resolveRuntimeBaseagentModelSelection(modelBaseagent, configuredBaseagent))?.model;
|
|
@@ -4536,7 +4723,7 @@ export class ResponseEngine {
|
|
|
4536
4723
|
}
|
|
4537
4724
|
const hasModel = (typeof agentModel === 'string' && agentModel.trim().length > 0)
|
|
4538
4725
|
|| (typeof triggerModel === 'string' && triggerModel.trim().length > 0);
|
|
4539
|
-
if (modelBaseagent !== 'unknown' && !hasModel) {
|
|
4726
|
+
if (modelBaseagent !== 'unknown' && !hasModel && !nativeModelSelection) {
|
|
4540
4727
|
logger.warn(`[ResponseEngine] No Agent-level model configured: agent=${selfAid ?? session.selfAID ?? '<none>'} baseagent=${modelBaseagent} session=${session.id}`);
|
|
4541
4728
|
this.touchAgentActivity(channelKey);
|
|
4542
4729
|
adapter.send(envelope, {
|
|
@@ -4664,7 +4851,15 @@ export class ResponseEngine {
|
|
|
4664
4851
|
...(activityChatType === 'private' ? { peerId: activityChannelId } : {}),
|
|
4665
4852
|
item,
|
|
4666
4853
|
...(activityId ? { activityId } : {}),
|
|
4667
|
-
}, {
|
|
4854
|
+
}, {
|
|
4855
|
+
projectPath: absoluteProjectPath,
|
|
4856
|
+
allowedRoots: [
|
|
4857
|
+
...toolImageReadRoots,
|
|
4858
|
+
...(toolImageAttachmentSelfAid
|
|
4859
|
+
? getExistingSelfAttachmentDirs(resolveRoot(), { selfAid: toolImageAttachmentSelfAid })
|
|
4860
|
+
: []),
|
|
4861
|
+
],
|
|
4862
|
+
});
|
|
4668
4863
|
}
|
|
4669
4864
|
catch (error) {
|
|
4670
4865
|
logger.warn(`[ResponseEngine] task activity record failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -4673,6 +4868,22 @@ export class ResponseEngine {
|
|
|
4673
4868
|
send: async (payload) => {
|
|
4674
4869
|
if (turnLease && !this.turnCoordinator.canPublish(turnLease)) {
|
|
4675
4870
|
snapshot.pushOutbound(session.id, taskId, { kind: payload.kind, decision: 'suppressed-stale-turn' });
|
|
4871
|
+
// 正文已经离开 renderer 的 buffer,门禁不放行就等于把它扔了。先扣在本回合名下,
|
|
4872
|
+
// 交给收尾的补投发出;非正文类(活动/状态/错误提示)照旧丢弃。
|
|
4873
|
+
const suppressedText = payload.kind === 'result.text'
|
|
4874
|
+
? payload.text
|
|
4875
|
+
: payload.kind === 'activity.batch'
|
|
4876
|
+
? payload.items
|
|
4877
|
+
.filter(it => it.kind === 'text'
|
|
4878
|
+
|| (it.kind === 'summary' && it.is_error !== true))
|
|
4879
|
+
.map(it => ('text' in it ? it.text : ''))
|
|
4880
|
+
.join('')
|
|
4881
|
+
: '';
|
|
4882
|
+
if (suppressedText.trim()) {
|
|
4883
|
+
const held = this.heldStaleOutput.get(taskId) ?? [];
|
|
4884
|
+
held.push(suppressedText);
|
|
4885
|
+
this.heldStaleOutput.set(taskId, held);
|
|
4886
|
+
}
|
|
4676
4887
|
logger.info(`[ResponseEngine] outbound.suppressed ${JSON.stringify({
|
|
4677
4888
|
reason: 'stale_turn',
|
|
4678
4889
|
kind: payload.kind,
|
|
@@ -4793,6 +5004,7 @@ export class ResponseEngine {
|
|
|
4793
5004
|
taskId,
|
|
4794
5005
|
renderer,
|
|
4795
5006
|
suppressActivities: shouldSuppress(),
|
|
5007
|
+
agentSessionId: session.agentSessionId,
|
|
4796
5008
|
});
|
|
4797
5009
|
// Idle notify/warn are operational diagnostic notices. Keep them on the
|
|
4798
5010
|
// current task's renderer so envelope, stale-turn, background, and
|
|
@@ -4961,7 +5173,7 @@ export class ResponseEngine {
|
|
|
4961
5173
|
? resolvedMode.mode.configureRun(modeProcessCtx)
|
|
4962
5174
|
: undefined;
|
|
4963
5175
|
const modePolicyHook = runModeConfig?.policyHook;
|
|
4964
|
-
// 系统会话:路径 / 工具由 system
|
|
5176
|
+
// 系统会话:路径 / 工具由 session/system 模块判定,与角色体系无关。
|
|
4965
5177
|
// 有标记就只走模块,不挂模式策略、不算授权表、不并 runtime grant。
|
|
4966
5178
|
const sessionMetadata = session.metadata;
|
|
4967
5179
|
const declaredSessionType = session.sessionType ?? (typeof sessionMetadata?.sessionType === 'string' ? sessionMetadata.sessionType : undefined);
|
|
@@ -5035,6 +5247,9 @@ export class ResponseEngine {
|
|
|
5035
5247
|
});
|
|
5036
5248
|
})();
|
|
5037
5249
|
toolImageReadRoots = [absoluteProjectPath, ...grantedReadRoots, ...(sessionRuntimeDir ? [sessionRuntimeDir] : [])];
|
|
5250
|
+
toolImageAttachmentSelfAid = pathGrantIdentity && normalizeBaseagent(agent.name).canonical === 'codex'
|
|
5251
|
+
? selfAid
|
|
5252
|
+
: undefined;
|
|
5038
5253
|
// 设置权限审批的交互上下文(支持交互卡片)
|
|
5039
5254
|
const permissionContext = {
|
|
5040
5255
|
sendPrompt: permissionPromptForOrigin,
|
|
@@ -5050,14 +5265,21 @@ export class ResponseEngine {
|
|
|
5050
5265
|
chatmode: effectiveChatMode,
|
|
5051
5266
|
// 系统会话没有角色
|
|
5052
5267
|
role: systemSessionMarker ? undefined : peerRole,
|
|
5053
|
-
|
|
5268
|
+
revalidateExecutionIdentity: async () => {
|
|
5269
|
+
if (triggerExecutionIdentity) {
|
|
5054
5270
|
const current = selfAid ? await currentTriggerExecutionIdentity(message, selfAid) : undefined;
|
|
5055
5271
|
if (!current || current.role !== triggerExecutionIdentity.role
|
|
5056
5272
|
|| current.rolePolicy !== triggerExecutionIdentity.rolePolicy
|
|
5057
5273
|
|| current.actor.principalId !== triggerExecutionIdentity.actor.principalId) {
|
|
5058
5274
|
throw new Error('Trigger execution authorization changed');
|
|
5059
5275
|
}
|
|
5060
|
-
}
|
|
5276
|
+
}
|
|
5277
|
+
// Persistent switches remain live policy even after a Runner has started.
|
|
5278
|
+
// Do not recurse through assertCurrentExecutionAuthorization/ownership here.
|
|
5279
|
+
if (permissionContext.executionPermission) {
|
|
5280
|
+
await this.assertCurrentFullAccessExecutionAuthorization(permissionContext.executionPermission, agent);
|
|
5281
|
+
}
|
|
5282
|
+
},
|
|
5061
5283
|
...(authorizationIdentity?.control ? { trustedProcessRole: 'daemon-service' } : {}),
|
|
5062
5284
|
internalContactAuthorization: !systemSessionMarker && configChannelType === 'aun' && configChatType === 'private'
|
|
5063
5285
|
&& !!selfAid && !!configActorId && (sameOwnerQualification(selfAid, configActorId) === 'matched'
|
|
@@ -5639,6 +5861,7 @@ export class ResponseEngine {
|
|
|
5639
5861
|
}
|
|
5640
5862
|
modelOverride = {
|
|
5641
5863
|
...(modelOverride || {}),
|
|
5864
|
+
onInputSubmitted: () => this.messageQueue?.markInputSubmitted?.(session.id, taskId),
|
|
5642
5865
|
...(message.taskRecovery
|
|
5643
5866
|
? { recovery: { agentSessionId: message.taskRecovery.agentSessionId } }
|
|
5644
5867
|
: {}),
|
|
@@ -5846,6 +6069,8 @@ export class ResponseEngine {
|
|
|
5846
6069
|
?? session.metadata?.mentionMode
|
|
5847
6070
|
?? message.mentionMode
|
|
5848
6071
|
?? undefined,
|
|
6072
|
+
// 私聊 @ 策略只从 Agent 级取:没有服务器下发值,也没有关系级覆盖。
|
|
6073
|
+
privateMentionMode: effectiveAgentConfig?.privateMentionMode ?? 'disabled',
|
|
5849
6074
|
groupHistoryAvailable: canUseGroupHistory('ec.group.history'),
|
|
5850
6075
|
clientType: message.clientType || undefined,
|
|
5851
6076
|
permissionMode: effectivePermissionMode,
|
|
@@ -6184,7 +6409,7 @@ export class ResponseEngine {
|
|
|
6184
6409
|
selfAid,
|
|
6185
6410
|
peerId: configActorId || undefined,
|
|
6186
6411
|
// 系统会话(如记忆整理)的消息 peerId 是后台伪对端 `bg:<kind>`,推出来的 peerKey 不是
|
|
6187
|
-
// 它要操作的关系;目标关系由发起方写在 session.metadata.peerKey,与 system
|
|
6412
|
+
// 它要操作的关系;目标关系由发起方写在 session.metadata.peerKey,与 session/system
|
|
6188
6413
|
// 模块的读写边界同源。ec memory 写盘读的是这里,必须用它。
|
|
6189
6414
|
// 局部 peerKey(delegation grant / stats / 响应模式)保持伪对端不变,二者此处有意不一致。
|
|
6190
6415
|
peerKey: systemSessionContext?.peerKey ?? peerKey,
|
|
@@ -6307,7 +6532,7 @@ export class ResponseEngine {
|
|
|
6307
6532
|
fullAccessRunnerInvoked = true;
|
|
6308
6533
|
}
|
|
6309
6534
|
if (message.asyncQuestionAnswer) {
|
|
6310
|
-
if (session.baseagent
|
|
6535
|
+
if (!['codex', 'dsh'].includes(session.baseagent) || runAgentSessionId !== message.asyncQuestionAnswer.providerThreadId) {
|
|
6311
6536
|
throw new Error('Async question backend changed before queued resume');
|
|
6312
6537
|
}
|
|
6313
6538
|
if (!(await this.asyncQuestions?.validateQueuedAnswer(session, message.asyncQuestionAnswer))) {
|
|
@@ -6439,16 +6664,22 @@ export class ResponseEngine {
|
|
|
6439
6664
|
if (!(await this.turnCoordinator.markStatus(session, attemptTurnLease, 'waiting_interaction'))) {
|
|
6440
6665
|
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6441
6666
|
}
|
|
6442
|
-
|
|
6443
|
-
|
|
6444
|
-
|
|
6445
|
-
|
|
6667
|
+
if (session.baseagent !== 'dsh') {
|
|
6668
|
+
await agent.interrupt(session.id, {
|
|
6669
|
+
taskId: attemptTurnLease.taskId,
|
|
6670
|
+
generation: attemptTurnLease.generation,
|
|
6671
|
+
});
|
|
6672
|
+
}
|
|
6446
6673
|
if (!this.turnCoordinator.isCurrent(attemptTurnLease))
|
|
6447
6674
|
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6448
6675
|
}
|
|
6449
6676
|
await renderer.flush(false);
|
|
6450
6677
|
await this.asyncQuestions.present(session, request, message, adapter, envelope);
|
|
6451
|
-
|
|
6678
|
+
if (blocking && session.baseagent === 'dsh'
|
|
6679
|
+
&& !(await this.turnCoordinator.markStatus(session, attemptTurnLease, 'running'))) {
|
|
6680
|
+
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6681
|
+
}
|
|
6682
|
+
return blocking && session.baseagent !== 'dsh';
|
|
6452
6683
|
}
|
|
6453
6684
|
catch (error) {
|
|
6454
6685
|
if (blocking)
|
|
@@ -6723,6 +6954,9 @@ export class ResponseEngine {
|
|
|
6723
6954
|
expected: turnLease?.generation,
|
|
6724
6955
|
current: this.turnCoordinator.current(session).generation,
|
|
6725
6956
|
});
|
|
6957
|
+
// 被打断的回合已经产出的正文必须送到对端:模型输出过就等于已进入下一轮上下文,
|
|
6958
|
+
// 无声丢弃会让对端既收不到正文、又需要重发一次。这里只补投内容,不做任何「被打断」告知。
|
|
6959
|
+
await this.deliverInterruptedTurnOutput(message, adapter, envelope, renderer, session, taskId);
|
|
6726
6960
|
return;
|
|
6727
6961
|
}
|
|
6728
6962
|
if (!commitDecision.ok) {
|
|
@@ -6739,6 +6973,8 @@ export class ResponseEngine {
|
|
|
6739
6973
|
expected: turnLease?.generation,
|
|
6740
6974
|
current: this.turnCoordinator.current(session).generation,
|
|
6741
6975
|
});
|
|
6976
|
+
// 判定过期只影响提交,不影响已产出正文的投递。
|
|
6977
|
+
await this.deliverInterruptedTurnOutput(message, adapter, envelope, renderer, session, taskId);
|
|
6742
6978
|
return;
|
|
6743
6979
|
}
|
|
6744
6980
|
const reason = streamResult.protocolIncompleteReason || commitDecision.reason;
|
|
@@ -6875,7 +7111,7 @@ export class ResponseEngine {
|
|
|
6875
7111
|
this.eventBus.publish({ type: 'runner:file-sent', sessionId: session.id, filePath: resolvedPath, channel: targetInfo.adapter.channelName });
|
|
6876
7112
|
sent++;
|
|
6877
7113
|
if (isCrossChannel) {
|
|
6878
|
-
await adapter.send(envelope, { kind: 'system.notice', text:
|
|
7114
|
+
await adapter.send(envelope, { kind: 'system.notice', text: `文件已通过 ${targetLabel} 发送`, subtype: 'health' });
|
|
6879
7115
|
}
|
|
6880
7116
|
}
|
|
6881
7117
|
catch (error) {
|
|
@@ -6902,6 +7138,8 @@ export class ResponseEngine {
|
|
|
6902
7138
|
this.agentDelegationRegistry?.revokeTask(session.id, taskId, 'replaced');
|
|
6903
7139
|
logger.info(`[ResponseEngine] Stale turn stopped before final flush: session=${session.id} task=${taskId}`);
|
|
6904
7140
|
await this.publishTriggerExecutionInterrupted(message, adapter, envelope, 'stale_turn', taskCausation);
|
|
7141
|
+
// 过期只意味着「不再属于当前回合」,不意味着内容作废:已产出的正文照样投出去。
|
|
7142
|
+
await this.deliverInterruptedTurnOutput(message, adapter, envelope, renderer, session, taskId);
|
|
6905
7143
|
return;
|
|
6906
7144
|
}
|
|
6907
7145
|
const terminalInterrupt = isExpectedStreamInterrupt(streamResult.terminalReason, this.interruptedSessions.get(session.id));
|
|
@@ -6911,7 +7149,7 @@ export class ResponseEngine {
|
|
|
6911
7149
|
const streamRecoverable = !permissionTerminalFailure
|
|
6912
7150
|
&& !isExpectedTerminalInterrupt(streamResult.terminalReason)
|
|
6913
7151
|
&& (isRecoverableProtocolFailure(streamResult.subtype, streamResult.protocolIncompleteReason)
|
|
6914
|
-
||
|
|
7152
|
+
|| isRecoverableError(new Error(getStreamErrorText(streamResult))));
|
|
6915
7153
|
sentErrorAsSystemError = await projectTerminalReply({
|
|
6916
7154
|
isCurrent: () => !turnLease || this.turnCoordinator.canPublish(turnLease),
|
|
6917
7155
|
isInterrupted: () => terminalInterrupt || isNonErrorInterruptReason(this.interruptedSessions.get(session.id)),
|
|
@@ -6925,13 +7163,13 @@ export class ResponseEngine {
|
|
|
6925
7163
|
sendError: async () => {
|
|
6926
7164
|
if (this.isTrustedDaemonTrigger(message))
|
|
6927
7165
|
return false;
|
|
6928
|
-
const errorText =
|
|
7166
|
+
const errorText = getStreamErrorMessage(streamResult, false);
|
|
6929
7167
|
const subtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || getStreamErrorText(streamResult)), streamResult.subtype, streamResult.terminalReason);
|
|
6930
7168
|
const reason = normalizeCoreErrorReason(streamResult.terminalReason);
|
|
6931
7169
|
await adapter.send(envelope, {
|
|
6932
7170
|
kind: 'system.error',
|
|
6933
7171
|
text: errorText,
|
|
6934
|
-
...(subtype
|
|
7172
|
+
...(isConclusiveErrorSubtype(subtype) ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
|
|
6935
7173
|
subtype,
|
|
6936
7174
|
...(reason ? { reason } : {}),
|
|
6937
7175
|
recoverable: streamRecoverable,
|
|
@@ -6963,10 +7201,12 @@ export class ResponseEngine {
|
|
|
6963
7201
|
this.modelFallbackMap.set(session.id, curFbState);
|
|
6964
7202
|
}
|
|
6965
7203
|
}
|
|
6966
|
-
//
|
|
7204
|
+
// 被中断(新消息打断)时不能直接丢掉已产出的正文:新 task 接管的是「后续输入」,
|
|
7205
|
+
// 旧 task 已经输出过的内容仍属于对端该看到的结果。这里改走补投,跳过正常 flush 即可。
|
|
6967
7206
|
const preFlushInterrupt = this.interruptedSessions.get(session.id);
|
|
6968
7207
|
if (terminalInterrupt || isNonErrorInterruptReason(preFlushInterrupt)) {
|
|
6969
|
-
logger.info(`[ResponseEngine]
|
|
7208
|
+
logger.info(`[ResponseEngine] Flushing unsent output for interrupted task=${taskId} reason=${preFlushInterrupt ?? streamResult.terminalReason}`);
|
|
7209
|
+
await this.deliverInterruptedTurnOutput(message, adapter, envelope, renderer, session, taskId);
|
|
6970
7210
|
}
|
|
6971
7211
|
else {
|
|
6972
7212
|
// Flush 剩余内容(文件标记已在 flush 时自动移除)
|
|
@@ -7053,7 +7293,7 @@ export class ResponseEngine {
|
|
|
7053
7293
|
: getStreamErrorMessage(streamResult, false);
|
|
7054
7294
|
const rawSubtype = streamResult.subtype || 'agent_error';
|
|
7055
7295
|
const coreSubtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || errorSummary), rawSubtype, streamResult.terminalReason);
|
|
7056
|
-
const effectiveSubtype = coreSubtype
|
|
7296
|
+
const effectiveSubtype = isConclusiveErrorSubtype(coreSubtype) ? coreSubtype : rawSubtype;
|
|
7057
7297
|
const errorType = prefixErrorType(ERROR_PREFIX.AGENT, effectiveSubtype);
|
|
7058
7298
|
const coreReason = permissionTerminalFailure
|
|
7059
7299
|
? normalizeCoreErrorReason(permissionTerminalFailure.reason)
|
|
@@ -7069,7 +7309,7 @@ export class ResponseEngine {
|
|
|
7069
7309
|
...(coreReason ? { reason: coreReason } : {}),
|
|
7070
7310
|
recoverable: streamRecoverable,
|
|
7071
7311
|
message: userErrorSummary,
|
|
7072
|
-
...(coreSubtype
|
|
7312
|
+
...(isConclusiveErrorSubtype(coreSubtype) ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
|
|
7073
7313
|
durationMs: Date.now() - startTime,
|
|
7074
7314
|
numTurns: streamResult.numTurns,
|
|
7075
7315
|
toolCallCount: streamResult.toolUseCount ?? 0,
|
|
@@ -7090,7 +7330,7 @@ export class ResponseEngine {
|
|
|
7090
7330
|
kind: 'result.error',
|
|
7091
7331
|
text: userErrorSummary,
|
|
7092
7332
|
recoverable: streamRecoverable,
|
|
7093
|
-
...(coreSubtype
|
|
7333
|
+
...(isConclusiveErrorSubtype(coreSubtype) ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
|
|
7094
7334
|
subtype: coreSubtype,
|
|
7095
7335
|
...(coreReason ? { reason: coreReason } : {}),
|
|
7096
7336
|
}).catch(() => { });
|
|
@@ -7193,6 +7433,7 @@ export class ResponseEngine {
|
|
|
7193
7433
|
// cost 含原价(official)与网关实际价(gateway)两套,由 insertUsageEvent 写库时一并算出。
|
|
7194
7434
|
let turnCost = { official: null, gateway: null };
|
|
7195
7435
|
let statsCacheHitRate = 0;
|
|
7436
|
+
let preparedPricing;
|
|
7196
7437
|
if (streamResult.tokenUsage) {
|
|
7197
7438
|
try {
|
|
7198
7439
|
const statsAgentAid = session.selfAID || message.selfAID || '';
|
|
@@ -7203,7 +7444,11 @@ export class ResponseEngine {
|
|
|
7203
7444
|
const ctxPct = streamResult.contextUsage?.percentage;
|
|
7204
7445
|
// 网关价格缓存(/v1/models 的 pricing/effective_pricing,1h TTL)由当前 runner 提供,
|
|
7205
7446
|
// 同时携带实际连接来源,供 usage_events 记录 Provider 维度。
|
|
7206
|
-
const gwPricing = agent.getGatewayPricing?.()
|
|
7447
|
+
const gwPricing = await prepareUsagePricing(agent.getGatewayPricing?.(), [
|
|
7448
|
+
statsModel, streamResult.lastModelCall?.model || statsModel,
|
|
7449
|
+
...(streamResult.modelCalls?.map(call => call.model || statsModel) ?? []),
|
|
7450
|
+
]);
|
|
7451
|
+
preparedPricing = gwPricing;
|
|
7207
7452
|
const event = normalizeUsage(streamResult.tokenUsage, {
|
|
7208
7453
|
ts: Date.now(),
|
|
7209
7454
|
agent_aid: statsAgentAid,
|
|
@@ -7272,18 +7517,18 @@ export class ResponseEngine {
|
|
|
7272
7517
|
cache_read_tokens: sum.cache_read_tokens,
|
|
7273
7518
|
cache_creation_tokens: sum.cache_creation_tokens,
|
|
7274
7519
|
// 顶层 cost_usd/cost_cny 保持向后兼容 = 网关实际价
|
|
7275
|
-
cost_usd: roundCostForOutput(sum.cost_gateway_usd),
|
|
7276
|
-
cost_cny: roundCostForOutput(sum.cost_gateway_cny),
|
|
7520
|
+
cost_usd: sum.gatewayPricedCalls > 0 ? roundCostForOutput(sum.cost_gateway_usd) : null,
|
|
7521
|
+
cost_cny: sum.gatewayPricedCalls > 0 ? roundCostForOutput(sum.cost_gateway_cny) : null,
|
|
7277
7522
|
call_count: sum.calls,
|
|
7278
7523
|
cost: {
|
|
7279
|
-
official: {
|
|
7524
|
+
official: sum.officialPricedCalls > 0 ? {
|
|
7280
7525
|
usd: roundCostForOutput(sum.cost_official_usd),
|
|
7281
7526
|
cny: roundCostForOutput(sum.cost_official_cny),
|
|
7282
|
-
},
|
|
7283
|
-
gateway: {
|
|
7527
|
+
} : null,
|
|
7528
|
+
gateway: sum.gatewayPricedCalls > 0 ? {
|
|
7284
7529
|
usd: roundCostForOutput(sum.cost_gateway_usd),
|
|
7285
7530
|
cny: roundCostForOutput(sum.cost_gateway_cny),
|
|
7286
|
-
},
|
|
7531
|
+
} : null,
|
|
7287
7532
|
},
|
|
7288
7533
|
};
|
|
7289
7534
|
}
|
|
@@ -7301,15 +7546,9 @@ export class ResponseEngine {
|
|
|
7301
7546
|
}
|
|
7302
7547
|
else {
|
|
7303
7548
|
// cost 同时给原价(official)与网关实际价(gateway);顶层 cost_usd/cost_cny 保持向后兼容 = 网关价。
|
|
7304
|
-
const
|
|
7305
|
-
const
|
|
7306
|
-
const
|
|
7307
|
-
official: {
|
|
7308
|
-
usd: roundCostForOutput(turnCost.official?.usd ?? 0),
|
|
7309
|
-
cny: roundCostForOutput(turnCost.official?.cny ?? 0),
|
|
7310
|
-
},
|
|
7311
|
-
gateway: { usd: gatewayUsd, cny: gatewayCny },
|
|
7312
|
-
};
|
|
7549
|
+
const turnCostBlock = pricePairForOutput(turnCost);
|
|
7550
|
+
const gatewayUsd = turnCostBlock.gateway?.usd ?? null;
|
|
7551
|
+
const gatewayCny = turnCostBlock.gateway?.cny ?? null;
|
|
7313
7552
|
// 最后一次访问:本轮可能有多次大模型调用(numTurns>1),整轮的 turnCostBlock 不等于
|
|
7314
7553
|
// 最后一次的价。用 lastModelCall.tokenUsage 单独走一遍 resolvePrices(与落库同一套定价逻辑),
|
|
7315
7554
|
// 得到「最后一次访问」自己的原价 + 网关价。
|
|
@@ -7321,16 +7560,8 @@ export class ResponseEngine {
|
|
|
7321
7560
|
ts: Date.now(), agent_aid: '', peer_key: '', session_id: session.id,
|
|
7322
7561
|
model: lastModel, turns: 1,
|
|
7323
7562
|
});
|
|
7324
|
-
const lp = resolvePrices(resolveRoot(), lastEvent,
|
|
7325
|
-
|
|
7326
|
-
const lpGwCny = roundCostForOutput(lp.gateway?.cny ?? lp.official?.cny ?? 0);
|
|
7327
|
-
lastModelCall = { ...lastModelCall, cost: {
|
|
7328
|
-
official: {
|
|
7329
|
-
usd: roundCostForOutput(lp.official?.usd ?? 0),
|
|
7330
|
-
cny: roundCostForOutput(lp.official?.cny ?? 0),
|
|
7331
|
-
},
|
|
7332
|
-
gateway: { usd: lpGwUsd, cny: lpGwCny },
|
|
7333
|
-
} };
|
|
7563
|
+
const lp = resolvePrices(resolveRoot(), lastEvent, preparedPricing);
|
|
7564
|
+
lastModelCall = { ...lastModelCall, cost: pricePairForOutput(lp) };
|
|
7334
7565
|
}
|
|
7335
7566
|
catch { /* 价格解析失败时不附 cost,不影响回执 */ }
|
|
7336
7567
|
}
|
|
@@ -7480,7 +7711,7 @@ export class ResponseEngine {
|
|
|
7480
7711
|
if (!isUserInterrupt && ownsTimeoutTerminal)
|
|
7481
7712
|
await this.askForConnection(error, message, session);
|
|
7482
7713
|
const recoverable = !isUserInterrupt && !error?._replyDeliveryFailed
|
|
7483
|
-
&& (error === timeoutControl?.error ? timeoutControl?.recoverable === true :
|
|
7714
|
+
&& (error === timeoutControl?.error ? timeoutControl?.recoverable === true : isRecoverableError(error));
|
|
7484
7715
|
if (isUserInterrupt) {
|
|
7485
7716
|
await this.publishTriggerExecutionInterrupted(message, adapter, envelope, interruptReason ?? 'stale_turn', taskCausation);
|
|
7486
7717
|
}
|
|
@@ -7499,7 +7730,7 @@ export class ResponseEngine {
|
|
|
7499
7730
|
}
|
|
7500
7731
|
const totalExecutionMs = error instanceof ExecutionTimeoutError ? error.timeoutMs : this.totalExecutionLimitMs();
|
|
7501
7732
|
const rawErrorText = getErrorRawText(error);
|
|
7502
|
-
const safeRawErrorText =
|
|
7733
|
+
const safeRawErrorText = isConclusiveErrorSubtype(errType) ? undefined : rawErrorText;
|
|
7503
7734
|
const procStatus = errType === ErrorType.SDK_TIMEOUT || isTotalExecutionTimeout ? 'timeout'
|
|
7504
7735
|
: errType === ErrorType.STREAM_ERROR ? 'interrupted'
|
|
7505
7736
|
: 'error';
|
|
@@ -7660,7 +7891,7 @@ export class ResponseEngine {
|
|
|
7660
7891
|
: modelFallbackExhaustedMessage
|
|
7661
7892
|
? ErrorType.MODEL_UNAVAILABLE
|
|
7662
7893
|
: normalizeCoreErrorSubtype(error, undefined, isTotalExecutionTimeout || isTimeout ? 'timeout' : undefined);
|
|
7663
|
-
const distinctRawErrorText = errorSubtype
|
|
7894
|
+
const distinctRawErrorText = isConclusiveErrorSubtype(errorSubtype)
|
|
7664
7895
|
? undefined
|
|
7665
7896
|
: rawErrorText && !userMessage.includes(rawErrorText)
|
|
7666
7897
|
? rawErrorText
|
|
@@ -7734,6 +7965,8 @@ export class ResponseEngine {
|
|
|
7734
7965
|
finally {
|
|
7735
7966
|
if (proactiveCircuitBreakTimer)
|
|
7736
7967
|
clearTimeout(proactiveCircuitBreakTimer);
|
|
7968
|
+
// 兜底:正常路径已由补投取走;这里清掉任何残留,避免长期运行下按 task 累积。
|
|
7969
|
+
this.heldStaleOutput.delete(taskId);
|
|
7737
7970
|
if (this.activeTaskSpans.get(session.id)?.taskId === taskId) {
|
|
7738
7971
|
this.activeTaskSpans.delete(session.id);
|
|
7739
7972
|
if (runnerSelfAid)
|
|
@@ -7829,6 +8062,9 @@ export class ResponseEngine {
|
|
|
7829
8062
|
}
|
|
7830
8063
|
}
|
|
7831
8064
|
async runPendingAutoCompactAtTaskStart(session, agent, absoluteProjectPath, renderer, modelOverride, beforeCompact) {
|
|
8065
|
+
// DSH checks fresh native pressure under its writer lease before admitting this turn.
|
|
8066
|
+
if (agent.name === 'dsh')
|
|
8067
|
+
return;
|
|
7832
8068
|
if (!session.agentSessionId || !canCompactAgent(agent)) {
|
|
7833
8069
|
logger.debug(`[ResponseEngine] Auto compact skipped: session=${session.id} agentSessionId=${session.agentSessionId || 'none'} canCompact=${canCompactAgent(agent)} agent=${agent.name}`);
|
|
7834
8070
|
return;
|
|
@@ -7839,23 +8075,34 @@ export class ResponseEngine {
|
|
|
7839
8075
|
const model = modelOverride?.model || agent.getModel?.();
|
|
7840
8076
|
if (!model)
|
|
7841
8077
|
return;
|
|
8078
|
+
const contextBaseagent = agent.name === 'claude' || agent.name === 'codex' ? agent.name : undefined;
|
|
8079
|
+
const configuredThreshold = contextBaseagent ? readAgentCompactThreshold(session.selfAID, contextBaseagent) : undefined;
|
|
7842
8080
|
let policy;
|
|
7843
8081
|
try {
|
|
7844
8082
|
const catalog = modelOverride?.provider
|
|
7845
8083
|
? await getRunnerCatalog(agent.name, undefined, { providerId: modelOverride.provider })
|
|
7846
8084
|
: await agent.getModelCatalog?.();
|
|
7847
|
-
|
|
8085
|
+
if (contextBaseagent === 'codex') {
|
|
8086
|
+
const resolved = resolveAgentContextPolicy(contextBaseagent, model, catalog, configuredThreshold);
|
|
8087
|
+
policy = { contextWindow: resolved.executionContextWindowTokens, autoCompactTokens: resolved.effectiveAutoCompactThresholdTokens };
|
|
8088
|
+
}
|
|
8089
|
+
else {
|
|
8090
|
+
policy = resolveCatalogAutoCompactPolicy(catalog, model);
|
|
8091
|
+
}
|
|
7848
8092
|
}
|
|
7849
8093
|
catch (error) {
|
|
7850
|
-
logger.debug(`[ResponseEngine] Auto compact
|
|
7851
|
-
|
|
8094
|
+
logger.debug(`[ResponseEngine] Auto compact catalog unavailable: session=${session.id}`, error);
|
|
8095
|
+
if (!contextBaseagent || (contextBaseagent !== 'codex' && configuredThreshold === undefined))
|
|
8096
|
+
return;
|
|
8097
|
+
const resolved = resolveAgentContextPolicy(contextBaseagent, model, undefined, configuredThreshold);
|
|
8098
|
+
policy = { contextWindow: resolved.executionContextWindowTokens, autoCompactTokens: resolved.effectiveAutoCompactThresholdTokens };
|
|
7852
8099
|
}
|
|
7853
8100
|
if (!policy || ctx.totalTokens < policy.autoCompactTokens) {
|
|
7854
8101
|
logger.debug(`[ResponseEngine] Auto compact skipped: session=${session.id} ctx=${ctx.totalTokens}/${policy?.autoCompactTokens ?? 'unknown'}`);
|
|
7855
8102
|
return;
|
|
7856
8103
|
}
|
|
7857
8104
|
logger.info(`[ResponseEngine] Auto compact at task.start: session=${session.id} model=${model} contextWindow=${policy.contextWindow} totalTokens=${ctx.totalTokens} autoCompactTokens=${policy.autoCompactTokens}`);
|
|
7858
|
-
await this.emitOperationalNotice(renderer,
|
|
8105
|
+
await this.emitOperationalNotice(renderer, formatCompactingNotice(ctx.totalTokens), 'info', 'auto-compact-start');
|
|
7859
8106
|
await renderer.flush();
|
|
7860
8107
|
this.announcedCompactStarts.add(session.id);
|
|
7861
8108
|
try {
|
|
@@ -7883,57 +8130,7 @@ export class ResponseEngine {
|
|
|
7883
8130
|
}
|
|
7884
8131
|
}
|
|
7885
8132
|
async readLastModelCallContextUsage(sessionId, agentSessionId) {
|
|
7886
|
-
|
|
7887
|
-
const { getDb, openReadonlyDb, getDbPath } = await import('../../stats/db.js');
|
|
7888
|
-
const root = resolveRoot();
|
|
7889
|
-
const writerDb = getDb(root);
|
|
7890
|
-
const db = writerDb || openReadonlyDb(getDbPath(root));
|
|
7891
|
-
if (!db)
|
|
7892
|
-
return undefined;
|
|
7893
|
-
const shouldClose = !writerDb;
|
|
7894
|
-
try {
|
|
7895
|
-
const row = db.prepare(`SELECT model, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens,
|
|
7896
|
-
context_tokens, max_tokens
|
|
7897
|
-
FROM model_calls
|
|
7898
|
-
WHERE session_id = ?
|
|
7899
|
-
AND agent_session_id = ?
|
|
7900
|
-
AND COALESCE(degraded, 0) = 0
|
|
7901
|
-
ORDER BY ts DESC, call_index DESC
|
|
7902
|
-
LIMIT 1`).get(sessionId, agentSessionId);
|
|
7903
|
-
if (!row)
|
|
7904
|
-
return undefined;
|
|
7905
|
-
const model = row.model || '';
|
|
7906
|
-
const recordedTotalTokens = row.context_tokens ?? undefined;
|
|
7907
|
-
let totalTokens;
|
|
7908
|
-
if (recordedTotalTokens && recordedTotalTokens > 0) {
|
|
7909
|
-
totalTokens = recordedTotalTokens;
|
|
7910
|
-
}
|
|
7911
|
-
else {
|
|
7912
|
-
totalTokens = contextTokensForUsage({
|
|
7913
|
-
input_tokens: row.input_tokens,
|
|
7914
|
-
output_tokens: row.output_tokens,
|
|
7915
|
-
cache_creation_input_tokens: row.cache_creation_tokens,
|
|
7916
|
-
cache_read_input_tokens: row.cache_read_tokens,
|
|
7917
|
-
}, model);
|
|
7918
|
-
}
|
|
7919
|
-
if (totalTokens <= 0)
|
|
7920
|
-
return undefined;
|
|
7921
|
-
const maxTokens = row.max_tokens ?? 0;
|
|
7922
|
-
if (!(recordedTotalTokens && recordedTotalTokens > 0) && maxTokens > 0 && totalTokens > maxTokens * 1.05) {
|
|
7923
|
-
logger.warn(`[ResponseEngine] Ignoring implausible context_tokens: session=${sessionId} totalTokens=${totalTokens} maxTokens=${maxTokens}`);
|
|
7924
|
-
return undefined;
|
|
7925
|
-
}
|
|
7926
|
-
return { totalTokens };
|
|
7927
|
-
}
|
|
7928
|
-
finally {
|
|
7929
|
-
if (shouldClose)
|
|
7930
|
-
db.close();
|
|
7931
|
-
}
|
|
7932
|
-
}
|
|
7933
|
-
catch (err) {
|
|
7934
|
-
logger.debug(`[ResponseEngine] Failed to read last model call context usage: ${err}`);
|
|
7935
|
-
return undefined;
|
|
7936
|
-
}
|
|
8133
|
+
return readLastModelCallContextUsage(sessionId, agentSessionId);
|
|
7937
8134
|
}
|
|
7938
8135
|
/**
|
|
7939
8136
|
* 解析会话和项目路径
|
|
@@ -8242,6 +8439,7 @@ export class ResponseEngine {
|
|
|
8242
8439
|
if (event.type === 'heartbeat')
|
|
8243
8440
|
continue;
|
|
8244
8441
|
if (event.type === 'user_question') {
|
|
8442
|
+
assertDeclaredBaseagentCapability(agent.name, 'C25');
|
|
8245
8443
|
if (!onAsyncQuestion)
|
|
8246
8444
|
throw new Error('Async question has no delivery context');
|
|
8247
8445
|
const interrupted = await onAsyncQuestion({
|
|
@@ -8826,13 +9024,15 @@ export class ResponseEngine {
|
|
|
8826
9024
|
}
|
|
8827
9025
|
if (original)
|
|
8828
9026
|
removePendingToolInput(original);
|
|
8829
|
-
|
|
9027
|
+
const toolResultFailed = isToolResultFailure(event);
|
|
9028
|
+
if (toolResultFailed || event.error || event.exitCode !== undefined) {
|
|
8830
9029
|
const command = typeof original?.input?.command === 'string'
|
|
8831
9030
|
? original.input.command
|
|
8832
9031
|
: typeof original?.input?.input === 'string'
|
|
8833
9032
|
? original.input.input
|
|
8834
9033
|
: undefined;
|
|
8835
|
-
|
|
9034
|
+
const diagnosticLevel = toolResultFailed || event.error ? 'warn' : 'debug';
|
|
9035
|
+
logger[diagnosticLevel](`[ResponseEngine] tool.result.diagnostic ${JSON.stringify({
|
|
8836
9036
|
sessionId: session.id,
|
|
8837
9037
|
taskId: turnLease?.taskId ?? 'none',
|
|
8838
9038
|
toolName: event.name,
|
|
@@ -8840,7 +9040,7 @@ export class ResponseEngine {
|
|
|
8840
9040
|
correlationId: event.correlationId ?? 'none',
|
|
8841
9041
|
command: command ? diagnosticPreview(command) : undefined,
|
|
8842
9042
|
isError: event.isError === true,
|
|
8843
|
-
decision: event.decision ?? 'error',
|
|
9043
|
+
decision: event.decision ?? (toolResultFailed ? 'error' : 'allow'),
|
|
8844
9044
|
decisionSource: event.decisionSource ?? 'runner',
|
|
8845
9045
|
executed: event.executed,
|
|
8846
9046
|
executionState: event.executionState,
|
|
@@ -8887,7 +9087,6 @@ export class ResponseEngine {
|
|
|
8887
9087
|
}
|
|
8888
9088
|
// 从 tool_use 阶段缓存的描述中回溯
|
|
8889
9089
|
const cachedDesc = event.callId ? toolDescByCallId.get(event.callId) : undefined;
|
|
8890
|
-
const toolResultFailed = isToolResultFailure(event);
|
|
8891
9090
|
if (toolResultFailed && !shouldSuppress()) {
|
|
8892
9091
|
hasErrorResult = true;
|
|
8893
9092
|
const errorMsg = getToolResultErrorText(event) + diagnosticSuffix;
|
|
@@ -9116,7 +9315,7 @@ export class ResponseEngine {
|
|
|
9116
9315
|
}
|
|
9117
9316
|
// ── 出站协议辅助:buildEnvelope / sendInteractionPayload ──
|
|
9118
9317
|
// Phase 3 of outbound unification: callers (permission flow, CommandHandler
|
|
9119
|
-
// interaction cards,
|
|
9318
|
+
// interaction cards, Claude runner AskUserQuestion / ExitPlanMode) should
|
|
9120
9319
|
// produce `{ kind: 'interaction', interaction, fallbackText }` and dispatch
|
|
9121
9320
|
// via `adapter.send(envelope, payload)` instead of calling
|
|
9122
9321
|
// `adapter.sendInteraction(...)` directly. These helpers centralise the
|