evolcore 0.0.50 → 0.0.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -2
- package/bin/ec-build.mjs +60 -0
- package/bin/ecmsg.js +65 -63
- package/dist/ability/caller/command.js +24 -15
- package/dist/ability/caller/contract.js +24 -9
- package/dist/ability/caller/credential-files.js +132 -0
- package/dist/ability/caller/daemon.js +32 -7
- package/dist/ability/caller/schema-view.js +157 -0
- package/dist/ability/caller/service.js +202 -63
- package/dist/ability/interop-v1.js +156 -113
- package/dist/agent-template/jobs.js +14 -110
- package/dist/agent-template/runtime.js +331 -193
- package/dist/agent-template/service.js +1029 -1104
- package/dist/agent-template/share.js +103 -0
- package/dist/agent-template/tool-runner.js +25 -0
- package/dist/agent-template/types.js +10 -3
- package/dist/agents/claude/availability.js +94 -0
- package/dist/agents/claude/capability-provider.js +154 -0
- package/dist/agents/claude/index.js +145 -0
- package/dist/agents/{claude-runner.js → claude/runner.js} +74 -158
- package/dist/agents/claude/session-file-adapter.js +246 -0
- package/dist/agents/codex/app-server-client.js +90 -10
- package/dist/agents/codex/availability.js +164 -0
- package/dist/agents/codex/capability-provider.js +138 -0
- package/dist/agents/codex/cli.js +38 -0
- package/dist/agents/codex/index.js +345 -0
- package/dist/agents/codex/mcp-elicitation.js +135 -0
- package/dist/agents/{codex-runner.js → codex/runner.js} +648 -382
- package/dist/agents/codex/session-file-adapter.js +834 -0
- package/dist/agents/dsh/availability.js +28 -0
- package/dist/agents/dsh/capability-provider.js +56 -0
- package/dist/agents/dsh/desktop-locations.ps1 +66 -0
- package/dist/agents/dsh/desktop-probe.cjs +37 -0
- package/dist/agents/dsh/index.js +98 -0
- package/dist/agents/dsh/installation.js +400 -0
- package/dist/agents/dsh/resources.js +755 -0
- package/dist/agents/dsh/runner.js +1183 -0
- package/dist/agents/dsh/runtime/README.md +243 -0
- package/dist/agents/dsh/runtime/authorization.js +23 -0
- package/dist/agents/dsh/runtime/bridge.js +837 -0
- package/dist/agents/dsh/runtime/config.js +271 -0
- package/dist/agents/dsh/runtime/entry.js +229 -0
- package/dist/agents/dsh/runtime/session-inspector.js +340 -0
- package/dist/agents/dsh/runtime/tool-policy.js +49 -0
- package/dist/agents/dsh/session-file-adapter.js +145 -0
- package/dist/agents/ecagent/index.js +215 -0
- package/dist/agents/{ecagent-runner.js → ecagent/runner.js} +592 -106
- package/dist/agents/ecagent/session-file-adapter.js +134 -0
- package/dist/agents/gemini/index.js +55 -10
- package/dist/agents/gemini/{gemini-runner.js → runner.js} +4 -9
- package/dist/aun/ability-device-routing.js +11 -17
- package/dist/aun/aid/agentmd.js +27 -1
- package/dist/aun/aid/managed-operation.js +6 -4
- package/dist/aun/group/invite-service.js +1 -1
- package/dist/aun/menu/client.js +1 -1
- package/dist/aun/msg/history.js +1 -1
- package/dist/aun/msg/managed-operation.js +93 -21
- package/dist/aun/msg/p2p.js +6 -6
- package/dist/aun/service-proxy.js +1 -1
- package/dist/aun/storage/index.js +242 -0
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +180 -43
- package/dist/channels/daemon.js +3 -2
- package/dist/channels/dingtalk.js +1 -1
- package/dist/channels/feishu.js +9 -9
- package/dist/channels/qqbot.js +1 -1
- package/dist/channels/wechat.js +2 -2
- package/dist/channels/wecom.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/agent-registration.js +13 -13
- package/dist/{agents/claude-gateway → claude-gateway}/binding.js +3 -3
- package/dist/{agents/claude-gateway → claude-gateway}/inbox.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/index.js +2 -2
- package/dist/{agents/claude-gateway → claude-gateway}/listing.js +3 -3
- package/dist/{agents/claude-gateway → claude-gateway}/router.js +4 -4
- package/dist/{agents/claude-gateway → claude-gateway}/sessions.js +2 -2
- package/dist/{agents/claude-gateway → claude-gateway}/terminal.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/transcript.js +1 -1
- package/dist/cli/ability-command.js +8 -5
- package/dist/cli/ability-output.js +182 -0
- package/dist/cli/agent-command.js +1 -1
- package/dist/cli/agent-create.js +123 -42
- package/dist/cli/agent-template.js +400 -29
- package/dist/cli/agent.js +14 -11
- package/dist/cli/aun-commands.js +167 -111
- package/dist/cli/daemon-commands.js +38 -8
- package/dist/cli/data-command.js +1 -1
- package/dist/cli/debug-mode.js +9 -0
- package/dist/cli/directory.js +1 -2
- package/dist/cli/ecmsg-gateway.js +55 -19
- package/dist/cli/fs-command.js +67 -39
- package/dist/cli/index.js +25 -11
- package/dist/cli/init.js +124 -29
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +1 -1
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/services-command.js +24 -1
- package/dist/cli/skill-command.js +4 -4
- package/dist/cli/task-context.js +24 -14
- package/dist/cli/team-workspace-command.js +50 -52
- package/dist/cli/thread-command.js +3 -2
- package/dist/cli/trigger-command.js +47 -12
- package/dist/cli/watch-logs.js +2 -1
- package/dist/config/boot-log.js +3 -0
- package/dist/config/builtin-role-templates.js +1 -1
- package/dist/config/config-field-policy.js +10 -6
- package/dist/config/config-manager.js +33 -12
- package/dist/config/gateway-config.js +21 -37
- package/dist/config/invoke-ipc-service.js +1 -1
- package/dist/config/owner-config.js +5 -3
- package/dist/config/peer-book-store.js +2 -3
- package/dist/config/peer-book.js +2 -2
- package/dist/config/peer-role-resolver.js +2 -2
- package/dist/config/provider-identity-migration.js +24 -105
- package/dist/config/provider-ipc-service.js +13 -3
- package/dist/config/provider-local-sync.js +4 -1
- package/dist/config/provider-menu-request.js +21 -3
- package/dist/config/provider-templates.js +1 -1
- package/dist/config/providers-config.js +39 -15
- package/dist/config/providers-import.js +3 -3
- package/dist/config/providers-management.js +74 -99
- package/dist/config/schema-migration.js +177 -11
- package/dist/config/schema-registry.js +1 -1
- package/dist/config-store.js +38 -50
- package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +9 -9
- package/dist/core/{agent-create-status.js → agent/agent-create-status.js} +112 -4
- package/dist/core/{agent-creation-claim.js → agent/agent-creation-claim.js} +3 -3
- package/dist/core/{agent-ipc-registration.js → agent/agent-ipc-registration.js} +102 -25
- package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +61 -1
- package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +53 -27
- package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +12 -12
- package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
- package/dist/core/auth/agent-delegation.js +1 -8
- package/dist/core/auth/delegation-authorization.js +28 -0
- package/dist/core/auth/operation-authorizer.js +7 -4
- package/dist/core/auth/operation-catalog.js +34 -5
- package/dist/core/baseagent/baseagent-availability.js +197 -0
- package/dist/core/baseagent/baseagent-capability-adapter.js +288 -0
- package/dist/core/baseagent/baseagent-config-shared.js +56 -0
- package/dist/core/baseagent/baseagent-identity.js +68 -0
- package/dist/core/{baseagent-loader.js → baseagent/baseagent-loader.js} +62 -6
- package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
- package/dist/{agents → core/baseagent}/baseagent-plugin-descriptor.js +107 -24
- package/dist/core/baseagent/baseagent-plugin-loader.js +367 -0
- package/dist/core/baseagent/baseagent.js +157 -0
- package/dist/{agents → core/baseagent}/runner-types.js +36 -4
- package/dist/core/capability/capability-manager.js +79 -30
- package/dist/core/capability/providers/claude-capability-provider.js +2 -154
- package/dist/core/capability/providers/codex-capability-provider.js +2 -136
- package/dist/core/{channel-loader.js → channel/channel-loader.js} +226 -38
- package/dist/core/{channel-runtime.js → channel/channel-runtime.js} +18 -18
- package/dist/core/command/agent-control.js +60 -15
- package/dist/core/command/agent-template-menu.js +21 -9
- package/dist/core/command/agentmd-menu-request.js +19 -8
- package/dist/core/command/agentmd-menu.js +14 -5
- package/dist/core/command/command-handler.js +127 -57
- package/dist/core/command/context-policy-menu.js +122 -0
- package/dist/core/command/data-root-resolver.js +157 -20
- package/dist/core/command/memory-slash.js +6 -6
- package/dist/core/command/menu-catalog.js +80 -20
- package/dist/core/command/menu-handler.js +305 -25
- package/dist/core/command/menu-protocol.js +42 -8
- package/dist/core/command/menu-query-batch.js +9 -5
- package/dist/core/command/provider-menu.js +7 -11
- package/dist/core/command/role-menu.js +1 -1
- package/dist/core/command/skill-slash.js +17 -5
- package/dist/core/command/slash-gate.js +2 -4
- package/dist/core/command/slash-handler.js +127 -96
- package/dist/core/command/team-workspace-team.js +3 -3
- package/dist/core/command/topic-slash.js +10 -10
- package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -14
- package/dist/core/{daemon-control.js → daemon/daemon-control.js} +46 -20
- package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +15 -15
- package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +3 -3
- package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +98 -38
- package/dist/core/{lifecycle-notice.js → daemon/lifecycle-notice.js} +4 -5
- package/dist/core/file-integrity/store.js +1 -1
- package/dist/core/handoff/ipc-registration.js +3 -3
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/{agents → core/inference}/request-identity.js +2 -2
- package/dist/core/inference/text-inference.js +4 -4
- package/dist/core/{bootstrap-messages.js → initialization/bootstrap-messages.js} +10 -10
- package/dist/core/{bootstrap-service.js → initialization/bootstrap-service.js} +24 -23
- package/dist/core/initialization/service.js +54 -9
- package/dist/core/invoke/executors/media.js +1 -1
- package/dist/core/invoke/executors/text.js +1 -1
- package/dist/core/memory/consolidation-context.js +1 -1
- package/dist/core/memory/consolidation-trigger.js +9 -3
- package/dist/core/memory/consolidation.js +4 -4
- package/dist/core/memory/memory-admin.js +6 -6
- package/dist/core/memory/memory-writer.js +1 -1
- package/dist/core/memory/relation-idle-monitor.js +1 -1
- package/dist/core/message/aun-ipc-sender.js +114 -75
- package/dist/core/message/aun-request-registry.js +13 -5
- package/dist/core/message/auto-mention-gate.js +1 -1
- package/dist/core/message/contact-admission.js +1 -1
- package/dist/core/message/im-renderer.js +19 -0
- package/dist/core/{interaction-router.js → message/interaction-router.js} +4 -4
- package/dist/core/message/items-formatter.js +5 -5
- package/dist/core/message/message-admission.js +1 -1
- package/dist/core/message/message-bridge.js +135 -54
- package/dist/core/message/message-queue.js +83 -4
- package/dist/core/message/message-utils.js +1 -1
- package/dist/core/message/peer-mode.js +1 -1
- package/dist/core/message/response-engine.js +347 -163
- package/dist/core/message/send-options.js +9 -6
- package/dist/core/message/send-routing.js +45 -109
- package/dist/core/message/stream-idle-monitor.js +1 -1
- package/dist/core/{data-migration.js → migration/data-migration.js} +29 -1
- package/dist/core/model/catalog-service.js +29 -8
- package/dist/core/model/model-capabilities.js +88 -0
- package/dist/core/model/model-catalog.js +14 -3
- package/dist/core/model/model-diagnostics.js +4 -4
- package/dist/core/ownership/owner-resolver.js +95 -15
- package/dist/core/{pack-auth.js → pack/pack-auth.js} +30 -3
- package/dist/core/{pack-install.js → pack/pack-install.js} +95 -17
- package/dist/core/permission/approval-gateway.js +9 -18
- package/dist/core/permission/ec-command-parser.js +70 -34
- package/dist/core/permission/managed-file.js +234 -0
- package/dist/core/permission/protected-paths.js +56 -0
- package/dist/core/permission/sandbox-runtime.js +267 -3
- package/dist/core/permission/session-path-grants.js +1 -1
- package/dist/core/permission/shell-environment.js +15 -1
- package/dist/core/plugin/plugin-lifecycle.js +442 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +2 -246
- package/dist/core/session/adapters/codex-session-file-adapter.js +2 -566
- package/dist/core/session/adapters/ecagent-session-file-adapter.js +2 -134
- package/dist/core/{background-session → session/background}/session-cleanup.js +2 -2
- package/dist/core/{background-session → session/background}/types.js +1 -1
- package/dist/core/session/session-file-health.js +2 -272
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +29 -2
- package/dist/core/session/session-terminal.js +185 -0
- package/dist/core/session/session-title.js +8 -11
- package/dist/core/{system-session → session/system}/memory.js +43 -9
- package/dist/core/{system-session → session/system}/registry.js +1 -1
- package/dist/core/{system-session → session/system}/types.js +1 -1
- package/dist/core/skill/index-generator.js +1 -0
- package/dist/core/task/task-activity-store.js +112 -0
- package/dist/core/task/task-recovery-service.js +2 -2
- package/dist/core/thread/ipc-operation.js +2 -2
- package/dist/core/thread/thread-operation.js +2 -1
- package/dist/core/thread/thread-route.js +5 -3
- package/dist/core/thread/thread-service.js +14 -4
- package/dist/directory/{owner-directory-admission.js → admission.js} +3 -3
- package/dist/directory/{owner-directory-cache.js → cache.js} +90 -8
- package/dist/directory/{owner-directory-markdown.js → markdown.js} +2 -2
- package/dist/directory/{owner-directory-query-operation.js → query-operation.js} +83 -9
- package/dist/directory/{owner-directory-search.js → search.js} +50 -2
- package/dist/directory/{owner-directory-store.js → store.js} +2 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/manifest-engine.js +64 -2
- package/dist/eck/message-renderer.js +35 -0
- package/dist/ecweb/basic-settings-service.js +9 -3
- package/dist/{contracts → ecweb/contracts}/ecweb-service-protocol.js +2 -1
- package/dist/ecweb/dsh-native-service.js +413 -0
- package/dist/ecweb/providers-service.js +1 -1
- package/dist/ecweb/runtime/lifecycle.js +1 -1
- package/dist/ecweb/runtime/supervisor.js +1 -1
- package/dist/event-center/center-config.js +2 -2
- package/dist/event-center/dispatcher.js +1 -1
- package/dist/event-center/ipc-operation.js +12 -3
- package/dist/event-center/pack-loader.js +2 -2
- package/dist/event-center/registry.js +6 -6
- package/dist/event-center/runtime.js +2 -2
- package/dist/index.js +71 -42
- package/dist/ipc.js +103 -10
- package/dist/outputs/authorization.js +27 -0
- package/dist/outputs/events.js +10 -1
- package/dist/outputs/panel-cards.js +960 -0
- package/dist/paths.js +12 -0
- package/dist/pay/command.js +1 -1
- package/dist/pay/runtime.js +18 -10
- package/dist/response-system/engines/v1/proactive-flow.js +1 -1
- package/dist/services/dispatcher.js +2 -2
- package/dist/services/host/main.js +10 -1
- package/dist/services/host/protocol.js +9 -2
- package/dist/services/host/resident.js +37 -0
- package/dist/services/host-client.js +12 -0
- package/dist/services/host-recycle.js +8 -3
- package/dist/services/host-runtime.js +54 -15
- package/dist/services/index.js +83 -19
- package/dist/services/ipc-operation.js +303 -38
- package/dist/services/pack-manager.js +2 -2
- package/dist/services/router.js +43 -3
- package/dist/services/script-runner.js +34 -25
- package/dist/services/service-payload.js +28 -1
- package/dist/services/validation.js +28 -2
- package/dist/stats/context-usage.js +110 -0
- package/dist/stats/model-resolver.js +103 -17
- package/dist/stats/query.js +5 -0
- package/dist/trigger/application-service.js +3 -2
- package/dist/trigger/authorization.js +36 -33
- package/dist/trigger/ipc-service.js +4 -4
- package/dist/trigger/local-files.js +8 -176
- package/dist/trigger/manager.js +2 -2
- package/dist/trigger/parser.js +48 -0
- package/dist/trigger/scheduler.js +14 -2
- package/dist/trigger/script-executor.js +21 -0
- package/dist/trigger/script-sandbox.js +57 -243
- package/dist/trigger/system-definitions.js +25 -0
- package/dist/trigger/validation.js +1 -1
- package/dist/utils/atomic-write.js +88 -1
- package/dist/utils/cross-platform.js +4 -42
- package/dist/utils/error-dict.json +22 -1
- package/dist/utils/error-utils.js +193 -6
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +1 -1
- package/dist/utils/logger.js +3 -1
- package/dist/utils/media-cache.js +99 -4
- package/dist/utils/startup-trace.js +20 -4
- package/dist/utils/welcome.js +64 -20
- package/ecagent/README.md +35 -0
- package/ecagent/dist/agent-loop.js +80 -30
- package/ecagent/dist/harness/env/nodejs.d.ts +16 -0
- package/ecagent/dist/harness/env/nodejs.js +49 -20
- package/ecagent/dist/harness/messages.js +3 -2
- package/ecagent/dist/harness/types.d.ts +1 -0
- package/ecagent/dist/runtime/types.d.ts +2 -0
- package/ecagent/dist/runtime/utils/validation.d.ts +7 -1
- package/ecagent/dist/runtime/utils/validation.js +42 -0
- package/ecagent/dist/types.d.ts +2 -0
- package/kits/docs/INDEX.md +1 -1
- package/kits/docs/channels/feishu.md +1 -1
- package/kits/docs/evolcore/INDEX.md +10 -7
- package/kits/docs/evolcore/agent-create.md +2 -0
- package/kits/docs/evolcore/agent.md +100 -13
- package/kits/docs/evolcore/aid.md +19 -3
- package/kits/docs/evolcore/config.md +94 -0
- package/kits/docs/evolcore/ctl.md +2 -1
- package/kits/docs/evolcore/ec-capabilities.md +7 -10
- package/kits/docs/evolcore/ecweb-lifecycle.md +5 -1
- package/kits/docs/evolcore/event.md +1 -1
- package/kits/docs/evolcore/fs.md +49 -3
- package/kits/docs/evolcore/group.md +3 -3
- package/kits/docs/evolcore/memory-consolidation.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +24 -2
- package/kits/docs/evolcore/model.md +9 -1
- package/kits/docs/evolcore/msg.md +30 -28
- package/kits/docs/evolcore/pay.md +8 -20
- package/kits/docs/evolcore/plugin.md +74 -0
- package/kits/docs/evolcore/provider.md +8 -2
- package/kits/docs/evolcore/rpc.md +2 -2
- package/kits/docs/evolcore/skill.md +17 -1
- package/kits/docs/evolcore/stats.md +5 -0
- package/kits/docs/evolcore/storage.md +22 -0
- package/kits/docs/evolcore/thread-chain.md +19 -10
- package/kits/docs/evolcore/tool-authorization.md +4 -0
- package/kits/docs/evolcore/trigger.md +89 -13
- package/kits/docs/identity/AID_PROFILE_SPEC.md +1 -1
- package/kits/docs/venues/feishu-group.md +3 -2
- package/kits/docs/venues/feishu-private.md +3 -2
- package/kits/rules/02-navigation.md +20 -13
- package/kits/rules/06-channel.md +18 -2
- package/kits/schemas/_meta.json +8 -4
- package/kits/schemas/agent-config.schema.23.json +19 -3
- package/kits/schemas/agent-config.schema.24.json +986 -0
- package/kits/schemas/agent-config.schema.25.json +986 -0
- package/kits/schemas/daemon.schema.11.json +487 -0
- package/kits/schemas/daemon.schema.12.json +505 -0
- package/kits/schemas/defaults.schema.8.json +484 -0
- package/kits/schemas/providers.schema.1.json +1 -1
- package/kits/schemas/providers.schema.2.json +1 -1
- package/kits/schemas/providers.schema.3.json +8 -2
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ability/SKILL.md +194 -27
- package/kits/skills/ability/STRUCTURE.md +5 -0
- package/kits/skills/agent-output-cards/SKILL.md +90 -54
- package/kits/skills/agent-output-cards/examples/html-surface.json +11 -0
- package/kits/skills/agent-output-cards/examples/meeting-followups.json +16 -0
- package/kits/skills/agent-output-cards/examples/meeting-latest.json +24 -0
- package/kits/skills/agent-output-cards/examples/project-metrics.json +16 -0
- package/kits/skills/agent-output-cards/examples/quick-links.json +18 -0
- package/kits/skills/agent-output-cards/examples/surface.html +8 -0
- package/kits/skills/agent-template-project/SKILL.md +51 -0
- package/kits/skills/agent-template-project/references/01-collect-and-pack.md +174 -0
- package/kits/skills/agent-template-project/references/02-upload-and-share.md +109 -0
- package/kits/skills/agent-template-project/references/03-download-and-install.md +189 -0
- package/kits/skills/agent-template-project/references/04-upgrade-and-recovery.md +74 -0
- package/kits/skills/agent-template-project/references/05-publish-to-platform.md +62 -0
- package/kits/skills/ec-group/SKILL.md +3 -3
- package/kits/skills/ec-group-collaboration/SKILL.md +4 -4
- package/kits/skills/ec-identity/SKILL.md +9 -6
- package/kits/skills/ec-pay/SKILL.md +163 -41
- package/kits/skills/ec-provider/SKILL.md +5 -5
- package/kits/skills/ec-service-call/SKILL.md +3 -0
- package/kits/skills/ec-skill/SKILL.md +25 -9
- package/kits/skills/ec-skill/scripts/cli.mjs +7 -7
- package/kits/skills/ec-skill/scripts/skill.mjs +55 -41
- package/kits/skills/ec-skill/scripts/template/SKILL.md.tmpl +9 -0
- package/kits/skills/ec-trigger/SKILL.md +2 -2
- package/kits/skills/personal-assistant/SKILL.md +22 -22
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +1 -1
- package/kits/skills/scrapling-article-fetch/SKILL.md +5 -5
- package/kits/skills/thread-ops/SKILL.md +19 -9
- package/kits/skills/wechat-article-media-download/SKILL.md +2 -2
- package/kits/skills/wechat-article-reader/SKILL.md +2 -2
- package/kits/templates/system-fragments/commands.md +1 -1
- package/kits/templates/system-fragments/personal-assistant.md +2 -2
- package/kits/templates/system-fragments/reply.md +14 -9
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +10 -5
- package/package.json +6 -5
- package/scripts/agent-template/index.mjs +7 -1
- package/scripts/agent-template/inspect.mjs +81 -35
- package/scripts/agent-template/overlay.mjs +110 -4
- package/scripts/agent-template/shared/common.mjs +36 -4
- package/scripts/agent-template/shared/plan.mjs +4 -2
- package/scripts/agent-template/shared/service-packs.mjs +104 -0
- package/scripts/agent-template/shared/team-schema.json +467 -54
- package/scripts/agent-template/shared/template-contract.mjs +70 -68
- package/scripts/agent-template/shared/template-package.mjs +153 -36
- package/scripts/agent-template/shared/template-runtime.mjs +76 -64
- package/scripts/agent-template/shared/template.mjs +11 -46
- package/scripts/agent-template/team-pack.mjs +451 -35
- package/scripts/agent-template/team-preview.mjs +75 -226
- package/scripts/aid-batch/identity-batch.mjs +1 -1
- package/dist/agents/baseagent-availability.js +0 -176
- package/dist/agents/baseagent-capability-adapter.js +0 -102
- package/dist/agents/baseagent-plugin-loader.js +0 -145
- package/dist/agents/baseagent.js +0 -816
- package/dist/agents/codex/catalog.js +0 -80
- package/dist/agents/ecagent-plugin-lazy.js +0 -41
- package/dist/agents/tool-time-context.js +0 -55
- package/dist/core/legacy-rename.js +0 -41
- package/dist/core/plugin-lifecycle.js +0 -137
- package/dist/core/rate-window.js +0 -53
- package/dist/core/runner-reload-transaction.js +0 -60
- package/dist/core/runtime-lock.js +0 -90
- package/dist/core/soul.js +0 -66
- package/dist/core/system-session/grants.js +0 -40
- package/dist/directory/owner-directory-agentmd-sync.js +0 -89
- package/dist/directory/owner-directory-request-operation.js +0 -79
- package/dist/directory/owner-directory-text.js +0 -60
- package/kits/skills/ec-pay/references/pay-cli.md +0 -110
- /package/dist/agents/gemini/{gemini-capability-provider.js → capability-provider.js} +0 -0
- /package/dist/agents/gemini/{gemini-session-file-adapter.js → session-file-adapter.js} +0 -0
- /package/dist/{agents/claude-gateway → claude-gateway}/types.js +0 -0
- /package/dist/core/{system-channels.js → channel/system-channels.js} +0 -0
- /package/dist/core/{daemon-file-cache.js → daemon/daemon-file-cache.js} +0 -0
- /package/dist/core/{event-bus.js → event/event-bus.js} +0 -0
- /package/dist/core/{event-catalog.js → event/event-catalog.js} +0 -0
- /package/dist/core/{pack-ledger.js → pack/pack-ledger.js} +0 -0
- /package/dist/directory/{owner-directory-identity.js → identity.js} +0 -0
- /package/dist/directory/{owner-directory-policy.js → policy.js} +0 -0
- /package/dist/directory/{owner-directory-remarks.js → remarks.js} +0 -0
- /package/dist/directory/{owner-directory-scope.js → scope.js} +0 -0
- /package/dist/{contracts → ecweb/contracts}/ecweb-instance.js +0 -0
- /package/kits/templates/{bootstrap-welcome.md → bootstrap-intro.md} +0 -0
|
@@ -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,7 +4245,7 @@ export class ResponseEngine {
|
|
|
4062
4245
|
}
|
|
4063
4246
|
})();
|
|
4064
4247
|
// ─── 响应模式解析(插件化机制中枢)───
|
|
4065
|
-
//
|
|
4248
|
+
// chatmode 覆写只决定投递方式;响应模式仍负责装配运行时策略。
|
|
4066
4249
|
const systemOrServicePeer = isSystemOrServicePeer(peerType);
|
|
4067
4250
|
const triggerChatModeOverride = systemOrServicePeer && message.source !== 'trigger'
|
|
4068
4251
|
? undefined : message.triggerMeta?.chatModeOverride;
|
|
@@ -4076,32 +4259,21 @@ export class ResponseEngine {
|
|
|
4076
4259
|
peerType,
|
|
4077
4260
|
channelType: currentChannelType,
|
|
4078
4261
|
});
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4082
|
-
|
|
4083
|
-
|
|
4084
|
-
|
|
4085
|
-
|
|
4086
|
-
|
|
4087
|
-
|
|
4088
|
-
? this.resolveEffectiveChatmodeForSession(session, channelKey, message.channelId)
|
|
4089
|
-
: undefined;
|
|
4090
|
-
const effectiveChatMode = triggerChatModeOverride && sessionChatModeSource
|
|
4091
|
-
? chatModeForScene(triggerChatModeOverride, { channelType: currentChannelType, chatType,
|
|
4092
|
-
peerType: session.metadata?.peerType, role: peerRole })
|
|
4093
|
-
: sessionChatModeSource ?? (chatType === 'group'
|
|
4094
|
-
? 'proactive'
|
|
4095
|
-
: systemOrServicePeer
|
|
4096
|
-
? 'interactive'
|
|
4097
|
-
: triggerChatModeOverride
|
|
4098
|
-
? chatModeForScene(triggerChatModeOverride, { channelType: currentChannelType, chatType, peerType, role: peerRole })
|
|
4099
|
-
: chatModeFallback);
|
|
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
|
+
});
|
|
4100
4271
|
const responseModeAgentDir = selfAid ? resolveAgentDir(selfAid) : undefined;
|
|
4101
4272
|
// mentionMode:顶层通用参数(先读出备用,投递/入队策略后续接入)
|
|
4102
4273
|
const mentionMode = effectiveAgentConfig?.mentionMode ?? 'disabled';
|
|
4103
|
-
|
|
4104
|
-
|
|
4274
|
+
// 主动模式的 Trigger / system 输入也必须装配策略,供托管 PreToolUse 校验。
|
|
4275
|
+
const resolvedMode = !responseModeAgentDir
|
|
4276
|
+
|| ((triggerChatModeOverride || systemOrServicePeer) && effectiveChatMode !== 'proactive')
|
|
4105
4277
|
? null
|
|
4106
4278
|
: this.responseCoordinator.resolveMode(effectiveAgentConfig?.responseMode, // 标量:关系级>agent级>注册表首选
|
|
4107
4279
|
effectiveChatMode, effectiveAgentConfig?.responseModeParams, // 按模式分桶的参数字典
|
|
@@ -4400,7 +4572,7 @@ export class ResponseEngine {
|
|
|
4400
4572
|
this.interruptedSessions.set(session.id, 'proactive_circuit_break');
|
|
4401
4573
|
void adapter.send(withEnvelopeReplyContext(envelope, taskReplyContext()), {
|
|
4402
4574
|
kind: 'result.text',
|
|
4403
|
-
text: '⚠️
|
|
4575
|
+
text: '⚠️ 这个任务卡住了,我先停下了。请重新说明一下需求。',
|
|
4404
4576
|
isFinal: true,
|
|
4405
4577
|
}).catch(error => {
|
|
4406
4578
|
logger.warn(`[ResponseEngine] circuit break channel send failed: session=${session.id} error=${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -4523,7 +4695,7 @@ export class ResponseEngine {
|
|
|
4523
4695
|
? undefined : effectiveAgentConfig?.baseagents?.[modelBaseagent];
|
|
4524
4696
|
// Preserve actionable connection failures before default-model discovery
|
|
4525
4697
|
// intentionally folds transport diagnostics into MODEL_UNAVAILABLE.
|
|
4526
|
-
if (configuredBaseagent?.provider) {
|
|
4698
|
+
if (configuredBaseagent?.provider && !usesNativeModelSelection(modelBaseagent, configuredBaseagent)) {
|
|
4527
4699
|
const provider = resolveProviderServiceForBaseagent(configuredBaseagent.provider, modelBaseagent);
|
|
4528
4700
|
if (!provider.apiKey?.trim())
|
|
4529
4701
|
throw new Error(`Provider ${provider.providerId} has no API key`);
|
|
@@ -4531,7 +4703,9 @@ export class ResponseEngine {
|
|
|
4531
4703
|
const triggerModel = message.triggerMeta?.modelOverride;
|
|
4532
4704
|
let agentModel;
|
|
4533
4705
|
let modelFailure;
|
|
4706
|
+
let nativeModelSelection = false;
|
|
4534
4707
|
try {
|
|
4708
|
+
nativeModelSelection = usesNativeModelSelection(modelBaseagent, configuredBaseagent);
|
|
4535
4709
|
agentModel = typeof triggerModel === 'string' && triggerModel.trim()
|
|
4536
4710
|
? triggerModel
|
|
4537
4711
|
: (await resolveRuntimeBaseagentModelSelection(modelBaseagent, configuredBaseagent))?.model;
|
|
@@ -4549,7 +4723,7 @@ export class ResponseEngine {
|
|
|
4549
4723
|
}
|
|
4550
4724
|
const hasModel = (typeof agentModel === 'string' && agentModel.trim().length > 0)
|
|
4551
4725
|
|| (typeof triggerModel === 'string' && triggerModel.trim().length > 0);
|
|
4552
|
-
if (modelBaseagent !== 'unknown' && !hasModel) {
|
|
4726
|
+
if (modelBaseagent !== 'unknown' && !hasModel && !nativeModelSelection) {
|
|
4553
4727
|
logger.warn(`[ResponseEngine] No Agent-level model configured: agent=${selfAid ?? session.selfAID ?? '<none>'} baseagent=${modelBaseagent} session=${session.id}`);
|
|
4554
4728
|
this.touchAgentActivity(channelKey);
|
|
4555
4729
|
adapter.send(envelope, {
|
|
@@ -4677,7 +4851,15 @@ export class ResponseEngine {
|
|
|
4677
4851
|
...(activityChatType === 'private' ? { peerId: activityChannelId } : {}),
|
|
4678
4852
|
item,
|
|
4679
4853
|
...(activityId ? { activityId } : {}),
|
|
4680
|
-
}, {
|
|
4854
|
+
}, {
|
|
4855
|
+
projectPath: absoluteProjectPath,
|
|
4856
|
+
allowedRoots: [
|
|
4857
|
+
...toolImageReadRoots,
|
|
4858
|
+
...(toolImageAttachmentSelfAid
|
|
4859
|
+
? getExistingSelfAttachmentDirs(resolveRoot(), { selfAid: toolImageAttachmentSelfAid })
|
|
4860
|
+
: []),
|
|
4861
|
+
],
|
|
4862
|
+
});
|
|
4681
4863
|
}
|
|
4682
4864
|
catch (error) {
|
|
4683
4865
|
logger.warn(`[ResponseEngine] task activity record failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -4686,6 +4868,22 @@ export class ResponseEngine {
|
|
|
4686
4868
|
send: async (payload) => {
|
|
4687
4869
|
if (turnLease && !this.turnCoordinator.canPublish(turnLease)) {
|
|
4688
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
|
+
}
|
|
4689
4887
|
logger.info(`[ResponseEngine] outbound.suppressed ${JSON.stringify({
|
|
4690
4888
|
reason: 'stale_turn',
|
|
4691
4889
|
kind: payload.kind,
|
|
@@ -4806,6 +5004,7 @@ export class ResponseEngine {
|
|
|
4806
5004
|
taskId,
|
|
4807
5005
|
renderer,
|
|
4808
5006
|
suppressActivities: shouldSuppress(),
|
|
5007
|
+
agentSessionId: session.agentSessionId,
|
|
4809
5008
|
});
|
|
4810
5009
|
// Idle notify/warn are operational diagnostic notices. Keep them on the
|
|
4811
5010
|
// current task's renderer so envelope, stale-turn, background, and
|
|
@@ -4974,7 +5173,7 @@ export class ResponseEngine {
|
|
|
4974
5173
|
? resolvedMode.mode.configureRun(modeProcessCtx)
|
|
4975
5174
|
: undefined;
|
|
4976
5175
|
const modePolicyHook = runModeConfig?.policyHook;
|
|
4977
|
-
// 系统会话:路径 / 工具由 system
|
|
5176
|
+
// 系统会话:路径 / 工具由 session/system 模块判定,与角色体系无关。
|
|
4978
5177
|
// 有标记就只走模块,不挂模式策略、不算授权表、不并 runtime grant。
|
|
4979
5178
|
const sessionMetadata = session.metadata;
|
|
4980
5179
|
const declaredSessionType = session.sessionType ?? (typeof sessionMetadata?.sessionType === 'string' ? sessionMetadata.sessionType : undefined);
|
|
@@ -5048,6 +5247,9 @@ export class ResponseEngine {
|
|
|
5048
5247
|
});
|
|
5049
5248
|
})();
|
|
5050
5249
|
toolImageReadRoots = [absoluteProjectPath, ...grantedReadRoots, ...(sessionRuntimeDir ? [sessionRuntimeDir] : [])];
|
|
5250
|
+
toolImageAttachmentSelfAid = pathGrantIdentity && normalizeBaseagent(agent.name).canonical === 'codex'
|
|
5251
|
+
? selfAid
|
|
5252
|
+
: undefined;
|
|
5051
5253
|
// 设置权限审批的交互上下文(支持交互卡片)
|
|
5052
5254
|
const permissionContext = {
|
|
5053
5255
|
sendPrompt: permissionPromptForOrigin,
|
|
@@ -5063,14 +5265,21 @@ export class ResponseEngine {
|
|
|
5063
5265
|
chatmode: effectiveChatMode,
|
|
5064
5266
|
// 系统会话没有角色
|
|
5065
5267
|
role: systemSessionMarker ? undefined : peerRole,
|
|
5066
|
-
|
|
5268
|
+
revalidateExecutionIdentity: async () => {
|
|
5269
|
+
if (triggerExecutionIdentity) {
|
|
5067
5270
|
const current = selfAid ? await currentTriggerExecutionIdentity(message, selfAid) : undefined;
|
|
5068
5271
|
if (!current || current.role !== triggerExecutionIdentity.role
|
|
5069
5272
|
|| current.rolePolicy !== triggerExecutionIdentity.rolePolicy
|
|
5070
5273
|
|| current.actor.principalId !== triggerExecutionIdentity.actor.principalId) {
|
|
5071
5274
|
throw new Error('Trigger execution authorization changed');
|
|
5072
5275
|
}
|
|
5073
|
-
}
|
|
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
|
+
},
|
|
5074
5283
|
...(authorizationIdentity?.control ? { trustedProcessRole: 'daemon-service' } : {}),
|
|
5075
5284
|
internalContactAuthorization: !systemSessionMarker && configChannelType === 'aun' && configChatType === 'private'
|
|
5076
5285
|
&& !!selfAid && !!configActorId && (sameOwnerQualification(selfAid, configActorId) === 'matched'
|
|
@@ -5652,6 +5861,7 @@ export class ResponseEngine {
|
|
|
5652
5861
|
}
|
|
5653
5862
|
modelOverride = {
|
|
5654
5863
|
...(modelOverride || {}),
|
|
5864
|
+
onInputSubmitted: () => this.messageQueue?.markInputSubmitted?.(session.id, taskId),
|
|
5655
5865
|
...(message.taskRecovery
|
|
5656
5866
|
? { recovery: { agentSessionId: message.taskRecovery.agentSessionId } }
|
|
5657
5867
|
: {}),
|
|
@@ -6199,7 +6409,7 @@ export class ResponseEngine {
|
|
|
6199
6409
|
selfAid,
|
|
6200
6410
|
peerId: configActorId || undefined,
|
|
6201
6411
|
// 系统会话(如记忆整理)的消息 peerId 是后台伪对端 `bg:<kind>`,推出来的 peerKey 不是
|
|
6202
|
-
// 它要操作的关系;目标关系由发起方写在 session.metadata.peerKey,与 system
|
|
6412
|
+
// 它要操作的关系;目标关系由发起方写在 session.metadata.peerKey,与 session/system
|
|
6203
6413
|
// 模块的读写边界同源。ec memory 写盘读的是这里,必须用它。
|
|
6204
6414
|
// 局部 peerKey(delegation grant / stats / 响应模式)保持伪对端不变,二者此处有意不一致。
|
|
6205
6415
|
peerKey: systemSessionContext?.peerKey ?? peerKey,
|
|
@@ -6322,7 +6532,7 @@ export class ResponseEngine {
|
|
|
6322
6532
|
fullAccessRunnerInvoked = true;
|
|
6323
6533
|
}
|
|
6324
6534
|
if (message.asyncQuestionAnswer) {
|
|
6325
|
-
if (session.baseagent
|
|
6535
|
+
if (!['codex', 'dsh'].includes(session.baseagent) || runAgentSessionId !== message.asyncQuestionAnswer.providerThreadId) {
|
|
6326
6536
|
throw new Error('Async question backend changed before queued resume');
|
|
6327
6537
|
}
|
|
6328
6538
|
if (!(await this.asyncQuestions?.validateQueuedAnswer(session, message.asyncQuestionAnswer))) {
|
|
@@ -6454,16 +6664,22 @@ export class ResponseEngine {
|
|
|
6454
6664
|
if (!(await this.turnCoordinator.markStatus(session, attemptTurnLease, 'waiting_interaction'))) {
|
|
6455
6665
|
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6456
6666
|
}
|
|
6457
|
-
|
|
6458
|
-
|
|
6459
|
-
|
|
6460
|
-
|
|
6667
|
+
if (session.baseagent !== 'dsh') {
|
|
6668
|
+
await agent.interrupt(session.id, {
|
|
6669
|
+
taskId: attemptTurnLease.taskId,
|
|
6670
|
+
generation: attemptTurnLease.generation,
|
|
6671
|
+
});
|
|
6672
|
+
}
|
|
6461
6673
|
if (!this.turnCoordinator.isCurrent(attemptTurnLease))
|
|
6462
6674
|
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6463
6675
|
}
|
|
6464
6676
|
await renderer.flush(false);
|
|
6465
6677
|
await this.asyncQuestions.present(session, request, message, adapter, envelope);
|
|
6466
|
-
|
|
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';
|
|
6467
6683
|
}
|
|
6468
6684
|
catch (error) {
|
|
6469
6685
|
if (blocking)
|
|
@@ -6738,6 +6954,9 @@ export class ResponseEngine {
|
|
|
6738
6954
|
expected: turnLease?.generation,
|
|
6739
6955
|
current: this.turnCoordinator.current(session).generation,
|
|
6740
6956
|
});
|
|
6957
|
+
// 被打断的回合已经产出的正文必须送到对端:模型输出过就等于已进入下一轮上下文,
|
|
6958
|
+
// 无声丢弃会让对端既收不到正文、又需要重发一次。这里只补投内容,不做任何「被打断」告知。
|
|
6959
|
+
await this.deliverInterruptedTurnOutput(message, adapter, envelope, renderer, session, taskId);
|
|
6741
6960
|
return;
|
|
6742
6961
|
}
|
|
6743
6962
|
if (!commitDecision.ok) {
|
|
@@ -6754,6 +6973,8 @@ export class ResponseEngine {
|
|
|
6754
6973
|
expected: turnLease?.generation,
|
|
6755
6974
|
current: this.turnCoordinator.current(session).generation,
|
|
6756
6975
|
});
|
|
6976
|
+
// 判定过期只影响提交,不影响已产出正文的投递。
|
|
6977
|
+
await this.deliverInterruptedTurnOutput(message, adapter, envelope, renderer, session, taskId);
|
|
6757
6978
|
return;
|
|
6758
6979
|
}
|
|
6759
6980
|
const reason = streamResult.protocolIncompleteReason || commitDecision.reason;
|
|
@@ -6890,7 +7111,7 @@ export class ResponseEngine {
|
|
|
6890
7111
|
this.eventBus.publish({ type: 'runner:file-sent', sessionId: session.id, filePath: resolvedPath, channel: targetInfo.adapter.channelName });
|
|
6891
7112
|
sent++;
|
|
6892
7113
|
if (isCrossChannel) {
|
|
6893
|
-
await adapter.send(envelope, { kind: 'system.notice', text:
|
|
7114
|
+
await adapter.send(envelope, { kind: 'system.notice', text: `文件已通过 ${targetLabel} 发送`, subtype: 'health' });
|
|
6894
7115
|
}
|
|
6895
7116
|
}
|
|
6896
7117
|
catch (error) {
|
|
@@ -6917,6 +7138,8 @@ export class ResponseEngine {
|
|
|
6917
7138
|
this.agentDelegationRegistry?.revokeTask(session.id, taskId, 'replaced');
|
|
6918
7139
|
logger.info(`[ResponseEngine] Stale turn stopped before final flush: session=${session.id} task=${taskId}`);
|
|
6919
7140
|
await this.publishTriggerExecutionInterrupted(message, adapter, envelope, 'stale_turn', taskCausation);
|
|
7141
|
+
// 过期只意味着「不再属于当前回合」,不意味着内容作废:已产出的正文照样投出去。
|
|
7142
|
+
await this.deliverInterruptedTurnOutput(message, adapter, envelope, renderer, session, taskId);
|
|
6920
7143
|
return;
|
|
6921
7144
|
}
|
|
6922
7145
|
const terminalInterrupt = isExpectedStreamInterrupt(streamResult.terminalReason, this.interruptedSessions.get(session.id));
|
|
@@ -6926,7 +7149,7 @@ export class ResponseEngine {
|
|
|
6926
7149
|
const streamRecoverable = !permissionTerminalFailure
|
|
6927
7150
|
&& !isExpectedTerminalInterrupt(streamResult.terminalReason)
|
|
6928
7151
|
&& (isRecoverableProtocolFailure(streamResult.subtype, streamResult.protocolIncompleteReason)
|
|
6929
|
-
||
|
|
7152
|
+
|| isRecoverableError(new Error(getStreamErrorText(streamResult))));
|
|
6930
7153
|
sentErrorAsSystemError = await projectTerminalReply({
|
|
6931
7154
|
isCurrent: () => !turnLease || this.turnCoordinator.canPublish(turnLease),
|
|
6932
7155
|
isInterrupted: () => terminalInterrupt || isNonErrorInterruptReason(this.interruptedSessions.get(session.id)),
|
|
@@ -6940,13 +7163,13 @@ export class ResponseEngine {
|
|
|
6940
7163
|
sendError: async () => {
|
|
6941
7164
|
if (this.isTrustedDaemonTrigger(message))
|
|
6942
7165
|
return false;
|
|
6943
|
-
const errorText =
|
|
7166
|
+
const errorText = getStreamErrorMessage(streamResult, false);
|
|
6944
7167
|
const subtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || getStreamErrorText(streamResult)), streamResult.subtype, streamResult.terminalReason);
|
|
6945
7168
|
const reason = normalizeCoreErrorReason(streamResult.terminalReason);
|
|
6946
7169
|
await adapter.send(envelope, {
|
|
6947
7170
|
kind: 'system.error',
|
|
6948
7171
|
text: errorText,
|
|
6949
|
-
...(subtype
|
|
7172
|
+
...(isConclusiveErrorSubtype(subtype) ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
|
|
6950
7173
|
subtype,
|
|
6951
7174
|
...(reason ? { reason } : {}),
|
|
6952
7175
|
recoverable: streamRecoverable,
|
|
@@ -6978,10 +7201,12 @@ export class ResponseEngine {
|
|
|
6978
7201
|
this.modelFallbackMap.set(session.id, curFbState);
|
|
6979
7202
|
}
|
|
6980
7203
|
}
|
|
6981
|
-
//
|
|
7204
|
+
// 被中断(新消息打断)时不能直接丢掉已产出的正文:新 task 接管的是「后续输入」,
|
|
7205
|
+
// 旧 task 已经输出过的内容仍属于对端该看到的结果。这里改走补投,跳过正常 flush 即可。
|
|
6982
7206
|
const preFlushInterrupt = this.interruptedSessions.get(session.id);
|
|
6983
7207
|
if (terminalInterrupt || isNonErrorInterruptReason(preFlushInterrupt)) {
|
|
6984
|
-
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);
|
|
6985
7210
|
}
|
|
6986
7211
|
else {
|
|
6987
7212
|
// Flush 剩余内容(文件标记已在 flush 时自动移除)
|
|
@@ -7068,7 +7293,7 @@ export class ResponseEngine {
|
|
|
7068
7293
|
: getStreamErrorMessage(streamResult, false);
|
|
7069
7294
|
const rawSubtype = streamResult.subtype || 'agent_error';
|
|
7070
7295
|
const coreSubtype = normalizeCoreErrorSubtype(new Error(streamRawErrorText || errorSummary), rawSubtype, streamResult.terminalReason);
|
|
7071
|
-
const effectiveSubtype = coreSubtype
|
|
7296
|
+
const effectiveSubtype = isConclusiveErrorSubtype(coreSubtype) ? coreSubtype : rawSubtype;
|
|
7072
7297
|
const errorType = prefixErrorType(ERROR_PREFIX.AGENT, effectiveSubtype);
|
|
7073
7298
|
const coreReason = permissionTerminalFailure
|
|
7074
7299
|
? normalizeCoreErrorReason(permissionTerminalFailure.reason)
|
|
@@ -7084,7 +7309,7 @@ export class ResponseEngine {
|
|
|
7084
7309
|
...(coreReason ? { reason: coreReason } : {}),
|
|
7085
7310
|
recoverable: streamRecoverable,
|
|
7086
7311
|
message: userErrorSummary,
|
|
7087
|
-
...(coreSubtype
|
|
7312
|
+
...(isConclusiveErrorSubtype(coreSubtype) ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
|
|
7088
7313
|
durationMs: Date.now() - startTime,
|
|
7089
7314
|
numTurns: streamResult.numTurns,
|
|
7090
7315
|
toolCallCount: streamResult.toolUseCount ?? 0,
|
|
@@ -7105,7 +7330,7 @@ export class ResponseEngine {
|
|
|
7105
7330
|
kind: 'result.error',
|
|
7106
7331
|
text: userErrorSummary,
|
|
7107
7332
|
recoverable: streamRecoverable,
|
|
7108
|
-
...(coreSubtype
|
|
7333
|
+
...(isConclusiveErrorSubtype(coreSubtype) ? {} : streamRawErrorText ? { raw: streamRawErrorText } : {}),
|
|
7109
7334
|
subtype: coreSubtype,
|
|
7110
7335
|
...(coreReason ? { reason: coreReason } : {}),
|
|
7111
7336
|
}).catch(() => { });
|
|
@@ -7208,6 +7433,7 @@ export class ResponseEngine {
|
|
|
7208
7433
|
// cost 含原价(official)与网关实际价(gateway)两套,由 insertUsageEvent 写库时一并算出。
|
|
7209
7434
|
let turnCost = { official: null, gateway: null };
|
|
7210
7435
|
let statsCacheHitRate = 0;
|
|
7436
|
+
let preparedPricing;
|
|
7211
7437
|
if (streamResult.tokenUsage) {
|
|
7212
7438
|
try {
|
|
7213
7439
|
const statsAgentAid = session.selfAID || message.selfAID || '';
|
|
@@ -7218,7 +7444,11 @@ export class ResponseEngine {
|
|
|
7218
7444
|
const ctxPct = streamResult.contextUsage?.percentage;
|
|
7219
7445
|
// 网关价格缓存(/v1/models 的 pricing/effective_pricing,1h TTL)由当前 runner 提供,
|
|
7220
7446
|
// 同时携带实际连接来源,供 usage_events 记录 Provider 维度。
|
|
7221
|
-
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;
|
|
7222
7452
|
const event = normalizeUsage(streamResult.tokenUsage, {
|
|
7223
7453
|
ts: Date.now(),
|
|
7224
7454
|
agent_aid: statsAgentAid,
|
|
@@ -7287,18 +7517,18 @@ export class ResponseEngine {
|
|
|
7287
7517
|
cache_read_tokens: sum.cache_read_tokens,
|
|
7288
7518
|
cache_creation_tokens: sum.cache_creation_tokens,
|
|
7289
7519
|
// 顶层 cost_usd/cost_cny 保持向后兼容 = 网关实际价
|
|
7290
|
-
cost_usd: roundCostForOutput(sum.cost_gateway_usd),
|
|
7291
|
-
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,
|
|
7292
7522
|
call_count: sum.calls,
|
|
7293
7523
|
cost: {
|
|
7294
|
-
official: {
|
|
7524
|
+
official: sum.officialPricedCalls > 0 ? {
|
|
7295
7525
|
usd: roundCostForOutput(sum.cost_official_usd),
|
|
7296
7526
|
cny: roundCostForOutput(sum.cost_official_cny),
|
|
7297
|
-
},
|
|
7298
|
-
gateway: {
|
|
7527
|
+
} : null,
|
|
7528
|
+
gateway: sum.gatewayPricedCalls > 0 ? {
|
|
7299
7529
|
usd: roundCostForOutput(sum.cost_gateway_usd),
|
|
7300
7530
|
cny: roundCostForOutput(sum.cost_gateway_cny),
|
|
7301
|
-
},
|
|
7531
|
+
} : null,
|
|
7302
7532
|
},
|
|
7303
7533
|
};
|
|
7304
7534
|
}
|
|
@@ -7316,15 +7546,9 @@ export class ResponseEngine {
|
|
|
7316
7546
|
}
|
|
7317
7547
|
else {
|
|
7318
7548
|
// cost 同时给原价(official)与网关实际价(gateway);顶层 cost_usd/cost_cny 保持向后兼容 = 网关价。
|
|
7319
|
-
const
|
|
7320
|
-
const
|
|
7321
|
-
const
|
|
7322
|
-
official: {
|
|
7323
|
-
usd: roundCostForOutput(turnCost.official?.usd ?? 0),
|
|
7324
|
-
cny: roundCostForOutput(turnCost.official?.cny ?? 0),
|
|
7325
|
-
},
|
|
7326
|
-
gateway: { usd: gatewayUsd, cny: gatewayCny },
|
|
7327
|
-
};
|
|
7549
|
+
const turnCostBlock = pricePairForOutput(turnCost);
|
|
7550
|
+
const gatewayUsd = turnCostBlock.gateway?.usd ?? null;
|
|
7551
|
+
const gatewayCny = turnCostBlock.gateway?.cny ?? null;
|
|
7328
7552
|
// 最后一次访问:本轮可能有多次大模型调用(numTurns>1),整轮的 turnCostBlock 不等于
|
|
7329
7553
|
// 最后一次的价。用 lastModelCall.tokenUsage 单独走一遍 resolvePrices(与落库同一套定价逻辑),
|
|
7330
7554
|
// 得到「最后一次访问」自己的原价 + 网关价。
|
|
@@ -7336,16 +7560,8 @@ export class ResponseEngine {
|
|
|
7336
7560
|
ts: Date.now(), agent_aid: '', peer_key: '', session_id: session.id,
|
|
7337
7561
|
model: lastModel, turns: 1,
|
|
7338
7562
|
});
|
|
7339
|
-
const lp = resolvePrices(resolveRoot(), lastEvent,
|
|
7340
|
-
|
|
7341
|
-
const lpGwCny = roundCostForOutput(lp.gateway?.cny ?? lp.official?.cny ?? 0);
|
|
7342
|
-
lastModelCall = { ...lastModelCall, cost: {
|
|
7343
|
-
official: {
|
|
7344
|
-
usd: roundCostForOutput(lp.official?.usd ?? 0),
|
|
7345
|
-
cny: roundCostForOutput(lp.official?.cny ?? 0),
|
|
7346
|
-
},
|
|
7347
|
-
gateway: { usd: lpGwUsd, cny: lpGwCny },
|
|
7348
|
-
} };
|
|
7563
|
+
const lp = resolvePrices(resolveRoot(), lastEvent, preparedPricing);
|
|
7564
|
+
lastModelCall = { ...lastModelCall, cost: pricePairForOutput(lp) };
|
|
7349
7565
|
}
|
|
7350
7566
|
catch { /* 价格解析失败时不附 cost,不影响回执 */ }
|
|
7351
7567
|
}
|
|
@@ -7495,7 +7711,7 @@ export class ResponseEngine {
|
|
|
7495
7711
|
if (!isUserInterrupt && ownsTimeoutTerminal)
|
|
7496
7712
|
await this.askForConnection(error, message, session);
|
|
7497
7713
|
const recoverable = !isUserInterrupt && !error?._replyDeliveryFailed
|
|
7498
|
-
&& (error === timeoutControl?.error ? timeoutControl?.recoverable === true :
|
|
7714
|
+
&& (error === timeoutControl?.error ? timeoutControl?.recoverable === true : isRecoverableError(error));
|
|
7499
7715
|
if (isUserInterrupt) {
|
|
7500
7716
|
await this.publishTriggerExecutionInterrupted(message, adapter, envelope, interruptReason ?? 'stale_turn', taskCausation);
|
|
7501
7717
|
}
|
|
@@ -7514,7 +7730,7 @@ export class ResponseEngine {
|
|
|
7514
7730
|
}
|
|
7515
7731
|
const totalExecutionMs = error instanceof ExecutionTimeoutError ? error.timeoutMs : this.totalExecutionLimitMs();
|
|
7516
7732
|
const rawErrorText = getErrorRawText(error);
|
|
7517
|
-
const safeRawErrorText =
|
|
7733
|
+
const safeRawErrorText = isConclusiveErrorSubtype(errType) ? undefined : rawErrorText;
|
|
7518
7734
|
const procStatus = errType === ErrorType.SDK_TIMEOUT || isTotalExecutionTimeout ? 'timeout'
|
|
7519
7735
|
: errType === ErrorType.STREAM_ERROR ? 'interrupted'
|
|
7520
7736
|
: 'error';
|
|
@@ -7675,7 +7891,7 @@ export class ResponseEngine {
|
|
|
7675
7891
|
: modelFallbackExhaustedMessage
|
|
7676
7892
|
? ErrorType.MODEL_UNAVAILABLE
|
|
7677
7893
|
: normalizeCoreErrorSubtype(error, undefined, isTotalExecutionTimeout || isTimeout ? 'timeout' : undefined);
|
|
7678
|
-
const distinctRawErrorText = errorSubtype
|
|
7894
|
+
const distinctRawErrorText = isConclusiveErrorSubtype(errorSubtype)
|
|
7679
7895
|
? undefined
|
|
7680
7896
|
: rawErrorText && !userMessage.includes(rawErrorText)
|
|
7681
7897
|
? rawErrorText
|
|
@@ -7749,6 +7965,8 @@ export class ResponseEngine {
|
|
|
7749
7965
|
finally {
|
|
7750
7966
|
if (proactiveCircuitBreakTimer)
|
|
7751
7967
|
clearTimeout(proactiveCircuitBreakTimer);
|
|
7968
|
+
// 兜底:正常路径已由补投取走;这里清掉任何残留,避免长期运行下按 task 累积。
|
|
7969
|
+
this.heldStaleOutput.delete(taskId);
|
|
7752
7970
|
if (this.activeTaskSpans.get(session.id)?.taskId === taskId) {
|
|
7753
7971
|
this.activeTaskSpans.delete(session.id);
|
|
7754
7972
|
if (runnerSelfAid)
|
|
@@ -7844,6 +8062,9 @@ export class ResponseEngine {
|
|
|
7844
8062
|
}
|
|
7845
8063
|
}
|
|
7846
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;
|
|
7847
8068
|
if (!session.agentSessionId || !canCompactAgent(agent)) {
|
|
7848
8069
|
logger.debug(`[ResponseEngine] Auto compact skipped: session=${session.id} agentSessionId=${session.agentSessionId || 'none'} canCompact=${canCompactAgent(agent)} agent=${agent.name}`);
|
|
7849
8070
|
return;
|
|
@@ -7854,23 +8075,34 @@ export class ResponseEngine {
|
|
|
7854
8075
|
const model = modelOverride?.model || agent.getModel?.();
|
|
7855
8076
|
if (!model)
|
|
7856
8077
|
return;
|
|
8078
|
+
const contextBaseagent = agent.name === 'claude' || agent.name === 'codex' ? agent.name : undefined;
|
|
8079
|
+
const configuredThreshold = contextBaseagent ? readAgentCompactThreshold(session.selfAID, contextBaseagent) : undefined;
|
|
7857
8080
|
let policy;
|
|
7858
8081
|
try {
|
|
7859
8082
|
const catalog = modelOverride?.provider
|
|
7860
8083
|
? await getRunnerCatalog(agent.name, undefined, { providerId: modelOverride.provider })
|
|
7861
8084
|
: await agent.getModelCatalog?.();
|
|
7862
|
-
|
|
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
|
+
}
|
|
7863
8092
|
}
|
|
7864
8093
|
catch (error) {
|
|
7865
|
-
logger.debug(`[ResponseEngine] Auto compact
|
|
7866
|
-
|
|
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 };
|
|
7867
8099
|
}
|
|
7868
8100
|
if (!policy || ctx.totalTokens < policy.autoCompactTokens) {
|
|
7869
8101
|
logger.debug(`[ResponseEngine] Auto compact skipped: session=${session.id} ctx=${ctx.totalTokens}/${policy?.autoCompactTokens ?? 'unknown'}`);
|
|
7870
8102
|
return;
|
|
7871
8103
|
}
|
|
7872
8104
|
logger.info(`[ResponseEngine] Auto compact at task.start: session=${session.id} model=${model} contextWindow=${policy.contextWindow} totalTokens=${ctx.totalTokens} autoCompactTokens=${policy.autoCompactTokens}`);
|
|
7873
|
-
await this.emitOperationalNotice(renderer,
|
|
8105
|
+
await this.emitOperationalNotice(renderer, formatCompactingNotice(ctx.totalTokens), 'info', 'auto-compact-start');
|
|
7874
8106
|
await renderer.flush();
|
|
7875
8107
|
this.announcedCompactStarts.add(session.id);
|
|
7876
8108
|
try {
|
|
@@ -7898,57 +8130,7 @@ export class ResponseEngine {
|
|
|
7898
8130
|
}
|
|
7899
8131
|
}
|
|
7900
8132
|
async readLastModelCallContextUsage(sessionId, agentSessionId) {
|
|
7901
|
-
|
|
7902
|
-
const { getDb, openReadonlyDb, getDbPath } = await import('../../stats/db.js');
|
|
7903
|
-
const root = resolveRoot();
|
|
7904
|
-
const writerDb = getDb(root);
|
|
7905
|
-
const db = writerDb || openReadonlyDb(getDbPath(root));
|
|
7906
|
-
if (!db)
|
|
7907
|
-
return undefined;
|
|
7908
|
-
const shouldClose = !writerDb;
|
|
7909
|
-
try {
|
|
7910
|
-
const row = db.prepare(`SELECT model, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens,
|
|
7911
|
-
context_tokens, max_tokens
|
|
7912
|
-
FROM model_calls
|
|
7913
|
-
WHERE session_id = ?
|
|
7914
|
-
AND agent_session_id = ?
|
|
7915
|
-
AND COALESCE(degraded, 0) = 0
|
|
7916
|
-
ORDER BY ts DESC, call_index DESC
|
|
7917
|
-
LIMIT 1`).get(sessionId, agentSessionId);
|
|
7918
|
-
if (!row)
|
|
7919
|
-
return undefined;
|
|
7920
|
-
const model = row.model || '';
|
|
7921
|
-
const recordedTotalTokens = row.context_tokens ?? undefined;
|
|
7922
|
-
let totalTokens;
|
|
7923
|
-
if (recordedTotalTokens && recordedTotalTokens > 0) {
|
|
7924
|
-
totalTokens = recordedTotalTokens;
|
|
7925
|
-
}
|
|
7926
|
-
else {
|
|
7927
|
-
totalTokens = contextTokensForUsage({
|
|
7928
|
-
input_tokens: row.input_tokens,
|
|
7929
|
-
output_tokens: row.output_tokens,
|
|
7930
|
-
cache_creation_input_tokens: row.cache_creation_tokens,
|
|
7931
|
-
cache_read_input_tokens: row.cache_read_tokens,
|
|
7932
|
-
}, model);
|
|
7933
|
-
}
|
|
7934
|
-
if (totalTokens <= 0)
|
|
7935
|
-
return undefined;
|
|
7936
|
-
const maxTokens = row.max_tokens ?? 0;
|
|
7937
|
-
if (!(recordedTotalTokens && recordedTotalTokens > 0) && maxTokens > 0 && totalTokens > maxTokens * 1.05) {
|
|
7938
|
-
logger.warn(`[ResponseEngine] Ignoring implausible context_tokens: session=${sessionId} totalTokens=${totalTokens} maxTokens=${maxTokens}`);
|
|
7939
|
-
return undefined;
|
|
7940
|
-
}
|
|
7941
|
-
return { totalTokens };
|
|
7942
|
-
}
|
|
7943
|
-
finally {
|
|
7944
|
-
if (shouldClose)
|
|
7945
|
-
db.close();
|
|
7946
|
-
}
|
|
7947
|
-
}
|
|
7948
|
-
catch (err) {
|
|
7949
|
-
logger.debug(`[ResponseEngine] Failed to read last model call context usage: ${err}`);
|
|
7950
|
-
return undefined;
|
|
7951
|
-
}
|
|
8133
|
+
return readLastModelCallContextUsage(sessionId, agentSessionId);
|
|
7952
8134
|
}
|
|
7953
8135
|
/**
|
|
7954
8136
|
* 解析会话和项目路径
|
|
@@ -8257,6 +8439,7 @@ export class ResponseEngine {
|
|
|
8257
8439
|
if (event.type === 'heartbeat')
|
|
8258
8440
|
continue;
|
|
8259
8441
|
if (event.type === 'user_question') {
|
|
8442
|
+
assertDeclaredBaseagentCapability(agent.name, 'C25');
|
|
8260
8443
|
if (!onAsyncQuestion)
|
|
8261
8444
|
throw new Error('Async question has no delivery context');
|
|
8262
8445
|
const interrupted = await onAsyncQuestion({
|
|
@@ -8841,13 +9024,15 @@ export class ResponseEngine {
|
|
|
8841
9024
|
}
|
|
8842
9025
|
if (original)
|
|
8843
9026
|
removePendingToolInput(original);
|
|
8844
|
-
|
|
9027
|
+
const toolResultFailed = isToolResultFailure(event);
|
|
9028
|
+
if (toolResultFailed || event.error || event.exitCode !== undefined) {
|
|
8845
9029
|
const command = typeof original?.input?.command === 'string'
|
|
8846
9030
|
? original.input.command
|
|
8847
9031
|
: typeof original?.input?.input === 'string'
|
|
8848
9032
|
? original.input.input
|
|
8849
9033
|
: undefined;
|
|
8850
|
-
|
|
9034
|
+
const diagnosticLevel = toolResultFailed || event.error ? 'warn' : 'debug';
|
|
9035
|
+
logger[diagnosticLevel](`[ResponseEngine] tool.result.diagnostic ${JSON.stringify({
|
|
8851
9036
|
sessionId: session.id,
|
|
8852
9037
|
taskId: turnLease?.taskId ?? 'none',
|
|
8853
9038
|
toolName: event.name,
|
|
@@ -8855,7 +9040,7 @@ export class ResponseEngine {
|
|
|
8855
9040
|
correlationId: event.correlationId ?? 'none',
|
|
8856
9041
|
command: command ? diagnosticPreview(command) : undefined,
|
|
8857
9042
|
isError: event.isError === true,
|
|
8858
|
-
decision: event.decision ?? 'error',
|
|
9043
|
+
decision: event.decision ?? (toolResultFailed ? 'error' : 'allow'),
|
|
8859
9044
|
decisionSource: event.decisionSource ?? 'runner',
|
|
8860
9045
|
executed: event.executed,
|
|
8861
9046
|
executionState: event.executionState,
|
|
@@ -8902,7 +9087,6 @@ export class ResponseEngine {
|
|
|
8902
9087
|
}
|
|
8903
9088
|
// 从 tool_use 阶段缓存的描述中回溯
|
|
8904
9089
|
const cachedDesc = event.callId ? toolDescByCallId.get(event.callId) : undefined;
|
|
8905
|
-
const toolResultFailed = isToolResultFailure(event);
|
|
8906
9090
|
if (toolResultFailed && !shouldSuppress()) {
|
|
8907
9091
|
hasErrorResult = true;
|
|
8908
9092
|
const errorMsg = getToolResultErrorText(event) + diagnosticSuffix;
|
|
@@ -9131,7 +9315,7 @@ export class ResponseEngine {
|
|
|
9131
9315
|
}
|
|
9132
9316
|
// ── 出站协议辅助:buildEnvelope / sendInteractionPayload ──
|
|
9133
9317
|
// Phase 3 of outbound unification: callers (permission flow, CommandHandler
|
|
9134
|
-
// interaction cards,
|
|
9318
|
+
// interaction cards, Claude runner AskUserQuestion / ExitPlanMode) should
|
|
9135
9319
|
// produce `{ kind: 'interaction', interaction, fallbackText }` and dispatch
|
|
9136
9320
|
// via `adapter.send(envelope, payload)` instead of calling
|
|
9137
9321
|
// `adapter.sendInteraction(...)` directly. These helpers centralise the
|