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
|
@@ -0,0 +1,1183 @@
|
|
|
1
|
+
/** Host runner for a single-task DSH process and a persistent native Session. */
|
|
2
|
+
import fsp from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
6
|
+
import { createInterface } from 'node:readline';
|
|
7
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
8
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
9
|
+
import { isDshSessionBusyError } from '../../utils/error-utils.js';
|
|
10
|
+
import { logger } from '../../utils/logger.js';
|
|
11
|
+
import { hasTrustedFullAccessContext, unsettledInterruptError, withInterruptDeadline, parseAsyncUserQuestions, resolveRunInference } from '../../core/baseagent/runner-types.js';
|
|
12
|
+
import { DSH_PROTOCOL, DSH_VERSION, DSH_EFFORTS, DSH_IMAGE_LIMITS } from './index.js';
|
|
13
|
+
import { resolveRoot } from '../../paths.js';
|
|
14
|
+
import { getPackageRoot } from '../../paths.js';
|
|
15
|
+
import { getManagedTaskTempDir } from '../../cli/task-context.js';
|
|
16
|
+
import { buildHClassGuardCommand } from '../../core/permission/sandbox-runtime.js';
|
|
17
|
+
import { normalizeExecutionPermissionMode, normalizePermissionMode, resolvePhaseOneExecutionSandbox } from '../../core/permission/mode.js';
|
|
18
|
+
import { evaluateToolPreflight, checkReadonly, checkDangerousCommand } from '../../core/permission/tool-policy.js';
|
|
19
|
+
import { requestDangerousCommandPermissionResult } from '../../core/permission/approval-gateway.js';
|
|
20
|
+
import { sanitizeShellExecutionEnvironment } from '../../core/permission/shell-environment.js';
|
|
21
|
+
import { killProcessTree } from '../../utils/cross-platform.js';
|
|
22
|
+
import { assertProviderModelAllowed } from '../../config/providers-config.js';
|
|
23
|
+
import { auditToolPreflightDenial } from '../../core/auth/authorization-audit.js';
|
|
24
|
+
import { assertOwnershipAuthorization } from '../../core/ownership/owner-resolver.js';
|
|
25
|
+
import { getProviderCatalog, applyProviderModelOverrides, adaptCatalogModels, catalogHash } from '../../core/model/model-catalog.js';
|
|
26
|
+
import { readAgentCompactThreshold, resolveAgentContextPolicy } from '../../core/model/model-capabilities.js';
|
|
27
|
+
import { resolveEffective } from '../../config/config-manager.js';
|
|
28
|
+
import { normalizeCapabilityTypeConfig, resolveCapabilityEnabled } from '../../core/capability/types.js';
|
|
29
|
+
import { dshAuthorizationFailure } from './runtime/authorization.js';
|
|
30
|
+
import { isModelAllowedForRoleBaseagent, getRoleModelPermission } from '../../core/model/model-permission.js';
|
|
31
|
+
import { DshNativeResourceRegistry } from './resources.js';
|
|
32
|
+
import { readDshNativeHistory } from './session-file-adapter.js';
|
|
33
|
+
import { RUNTIME_HOME_ENV, SELF_AID_ENV } from '../../product.js';
|
|
34
|
+
const NATIVE_PROTOCOL = DSH_PROTOCOL;
|
|
35
|
+
function object(value) { return !!value && typeof value === 'object' && !Array.isArray(value); }
|
|
36
|
+
function errorText(error) { return error instanceof Error ? error.message : String(error); }
|
|
37
|
+
const launches = new WeakMap();
|
|
38
|
+
function normalizeLaunchPath(value) { return process.platform === 'win32' ? value.toLowerCase() : value; }
|
|
39
|
+
function sameLaunchTask(left, right) {
|
|
40
|
+
return !!right && ['sessionId', 'taskId', 'turnId', 'generation'].every(key => left[key] === right[key]);
|
|
41
|
+
}
|
|
42
|
+
async function authorizeLaunch(input) {
|
|
43
|
+
input.signal.throwIfAborted();
|
|
44
|
+
const permission = input.permission;
|
|
45
|
+
if (permission.selfAid !== input.agentAid || !permission.revalidateExecutionIdentity
|
|
46
|
+
|| !sameLaunchTask(input.identity, permission.turn) || (permission.taskId && permission.taskId !== input.identity.taskId)) {
|
|
47
|
+
throw new Error('DSH_SHARED_TASK_AUTHORITY_REQUIRED');
|
|
48
|
+
}
|
|
49
|
+
await assertOwnershipAuthorization(permission);
|
|
50
|
+
input.signal.throwIfAborted();
|
|
51
|
+
if (!sameLaunchTask(input.identity, permission.turn))
|
|
52
|
+
throw new Error('DSH_SHARED_TASK_AUTHORITY_CHANGED');
|
|
53
|
+
}
|
|
54
|
+
async function authorizeLaunchSession(input, registry, project) {
|
|
55
|
+
if (input.nativeSessionId === null) {
|
|
56
|
+
if (input.sessionBindingRevision !== undefined)
|
|
57
|
+
throw new Error('DSH_SESSION_BINDING_MISMATCH');
|
|
58
|
+
registry.assertSessionUnbound(input.agentAid, input.identity.sessionId);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (!input.sessionBindingRevision)
|
|
62
|
+
throw new Error('DSH_SESSION_NOT_BOUND');
|
|
63
|
+
const binding = await registry.resolveSession(input.agentAid, input.identity.sessionId, input.sessionBindingRevision);
|
|
64
|
+
if (binding.nativeSessionId !== input.nativeSessionId || binding.nativeResourceId !== input.nativeResourceId
|
|
65
|
+
|| binding.registrationRevision !== input.registrationRevision || binding.projectPath !== normalizeLaunchPath(project)) {
|
|
66
|
+
throw new Error('DSH_SESSION_BINDING_MISMATCH');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function safeLaunchIdentity(input) {
|
|
70
|
+
if (!input || !Number.isSafeInteger(input.generation) || input.generation < 0
|
|
71
|
+
|| ['sessionId', 'taskId', 'turnId', 'inputId'].some(key => typeof input[key] !== 'string'
|
|
72
|
+
|| !String(input[key]).length || String(input[key]).length > 256
|
|
73
|
+
|| /[\x00-\x1f]/.test(String(input[key]))))
|
|
74
|
+
throw new Error('DSH_SHARED_TASK_INVALID');
|
|
75
|
+
return Object.freeze({ sessionId: input.sessionId, taskId: input.taskId, turnId: input.turnId,
|
|
76
|
+
generation: input.generation, inputId: input.inputId });
|
|
77
|
+
}
|
|
78
|
+
export async function prepareDshNativeLaunch(input, registry = new DshNativeResourceRegistry()) {
|
|
79
|
+
const identity = safeLaunchIdentity(input.identity);
|
|
80
|
+
input = { ...input, identity };
|
|
81
|
+
if (!['run', 'compact', 'history'].includes(input.operation)
|
|
82
|
+
|| (input.nativeSessionId === null ? input.operation !== 'run'
|
|
83
|
+
: typeof input.nativeSessionId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,255}$/.test(input.nativeSessionId))) {
|
|
84
|
+
throw new Error('DSH_SHARED_TASK_INVALID');
|
|
85
|
+
}
|
|
86
|
+
await authorizeLaunch(input);
|
|
87
|
+
const registration = await registry.resolve(input.agentAid, input.nativeResourceId, input.registrationRevision);
|
|
88
|
+
if (!path.isAbsolute(input.projectPath))
|
|
89
|
+
throw new Error('DSH_SHARED_PROJECT_INVALID');
|
|
90
|
+
const project = await fsp.realpath(input.projectPath);
|
|
91
|
+
if (!(await fsp.stat(project)).isDirectory())
|
|
92
|
+
throw new Error('DSH_SHARED_PROJECT_INVALID');
|
|
93
|
+
await authorizeLaunchSession(input, registry, project);
|
|
94
|
+
const managed = input.permission.managedTempDir;
|
|
95
|
+
if (!managed || !path.isAbsolute(managed))
|
|
96
|
+
throw new Error('DSH_SHARED_TEMP_INVALID');
|
|
97
|
+
const temporary = await fsp.realpath(managed);
|
|
98
|
+
if (normalizeLaunchPath(temporary) !== normalizeLaunchPath(path.resolve(managed)) || !(await fsp.stat(temporary)).isDirectory()) {
|
|
99
|
+
throw new Error('DSH_SHARED_TEMP_INVALID');
|
|
100
|
+
}
|
|
101
|
+
await authorizeLaunch(input);
|
|
102
|
+
const runtimePath = await fsp.mkdtemp(path.join(temporary, 'dsh-native-'));
|
|
103
|
+
const env = {};
|
|
104
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
105
|
+
if (/^(PATH|PATHEXT|SYSTEMROOT|WINDIR|COMSPEC|PROGRAMFILES|PROGRAMFILES\(X86\)|PROGRAMDATA|USERPROFILE|HOME|HOMEDRIVE|HOMEPATH|APPDATA|LOCALAPPDATA|LANG|LC_ALL|TERM)$/i.test(key))
|
|
106
|
+
env[key] = value;
|
|
107
|
+
}
|
|
108
|
+
Object.assign(env, { DSH_PACKAGE_PATH: registration.installation.packagePath,
|
|
109
|
+
[RUNTIME_HOME_ENV]: resolveRoot(), [SELF_AID_ENV]: input.agentAid,
|
|
110
|
+
DSH_HOME: registration.resource.homePath, TMPDIR: temporary, TEMP: temporary, TMP: temporary,
|
|
111
|
+
DSH_TELEMETRY_DISABLED: '1' });
|
|
112
|
+
if (registration.installation.kind === 'desktop')
|
|
113
|
+
env.ELECTRON_RUN_AS_NODE = '1';
|
|
114
|
+
const binding = Object.freeze({ launchId: randomUUID(), installationId: registration.installation.installationId,
|
|
115
|
+
installationRevision: registration.installation.revision, nativeResourceId: registration.resource.nativeResourceId,
|
|
116
|
+
resourceRevision: registration.resource.revision, projectPath: normalizeLaunchPath(project),
|
|
117
|
+
nativeSessionId: input.nativeSessionId, operation: input.operation, identity });
|
|
118
|
+
const launch = Object.freeze({ executablePath: registration.installation.executablePath,
|
|
119
|
+
args: Object.freeze(['--expose-internals', path.join(getPackageRoot(), 'dist', 'agents', 'dsh', 'runtime', 'entry.js')]),
|
|
120
|
+
env: Object.freeze(env), cwd: project, runtimePath, binding });
|
|
121
|
+
launches.set(launch, { input, registry, registration, temporary, phase: 'prepared' });
|
|
122
|
+
return launch;
|
|
123
|
+
}
|
|
124
|
+
export async function writeDshNativeStartup(launch, pipe) {
|
|
125
|
+
const state = launches.get(launch);
|
|
126
|
+
if (!state || state.phase !== 'prepared')
|
|
127
|
+
throw new Error('DSH_SHARED_STARTUP_ALREADY_CONSUMED');
|
|
128
|
+
state.phase = 'writing';
|
|
129
|
+
try {
|
|
130
|
+
await authorizeLaunch(state.input);
|
|
131
|
+
const current = await state.registry.resolve(state.input.agentAid, state.input.nativeResourceId, state.input.registrationRevision);
|
|
132
|
+
if (current.installation.revision !== state.registration.installation.revision
|
|
133
|
+
|| current.resource.revision !== state.registration.resource.revision)
|
|
134
|
+
throw new Error('DSH_SHARED_RESOURCE_CHANGED');
|
|
135
|
+
await authorizeLaunchSession(state.input, state.registry, launch.cwd);
|
|
136
|
+
if ((await fsp.readdir(launch.runtimePath)).length || (await fsp.lstat(launch.runtimePath)).isSymbolicLink()
|
|
137
|
+
|| normalizeLaunchPath(await fsp.realpath(launch.runtimePath)) !== normalizeLaunchPath(launch.runtimePath))
|
|
138
|
+
throw new Error('DSH_SHARED_TEMP_INVALID');
|
|
139
|
+
await authorizeLaunch(state.input);
|
|
140
|
+
state.mcpApprovals = state.input.permission.systemSessionCheck ? {} : { ...current.mcpApprovals };
|
|
141
|
+
const payload = JSON.stringify({ packagePath: current.installation.packagePath, homePath: current.resource.homePath,
|
|
142
|
+
profilePath: current.resource.profilePath, projectPath: launch.cwd, runtimePath: launch.runtimePath,
|
|
143
|
+
taskBinding: launch.binding, approvedMcpServers: state.mcpApprovals });
|
|
144
|
+
if (Buffer.byteLength(payload) > 64 * 1024 || pipe.destroyed || !pipe.writable)
|
|
145
|
+
throw new Error('DSH_SHARED_STARTUP_INVALID');
|
|
146
|
+
await new Promise((resolve, reject) => {
|
|
147
|
+
const onError = (error) => { pipe.removeListener('error', onError); reject(error); };
|
|
148
|
+
pipe.once('error', onError);
|
|
149
|
+
pipe.end(payload, () => { pipe.removeListener('error', onError); resolve(); });
|
|
150
|
+
});
|
|
151
|
+
state.phase = 'sent';
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
state.phase = 'closed';
|
|
155
|
+
pipe.destroy();
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
export async function revalidateDshNativeLaunch(launch) {
|
|
160
|
+
const state = launches.get(launch);
|
|
161
|
+
if (!state || state.phase === 'closed')
|
|
162
|
+
throw new Error('DSH_SHARED_STARTUP_INVALID');
|
|
163
|
+
const current = await state.registry.resolve(state.input.agentAid, state.input.nativeResourceId, state.input.registrationRevision);
|
|
164
|
+
if (state.mcpApprovals && Object.entries(state.mcpApprovals).some(([name, fingerprint]) => current.mcpApprovals?.[name] !== fingerprint)) {
|
|
165
|
+
throw new Error('DSH_MCP_AUTHORIZATION_REVOKED');
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
export async function recordDshNativeCreatedSession(launch, nativeSessionId) {
|
|
169
|
+
const state = launches.get(launch);
|
|
170
|
+
if (!state || state.phase !== 'sent' || state.creationRecorded || launch.binding.nativeSessionId !== null
|
|
171
|
+
|| launch.binding.operation !== 'run')
|
|
172
|
+
throw new Error('DSH_SHARED_CREATION_RECEIPT_INVALID');
|
|
173
|
+
state.creationRecorded = true;
|
|
174
|
+
await authorizeLaunch(state.input);
|
|
175
|
+
const binding = await state.registry.recordCreatedSession({ agentAid: state.input.agentAid,
|
|
176
|
+
nativeResourceId: state.input.nativeResourceId, registrationRevision: state.input.registrationRevision,
|
|
177
|
+
nativeSessionId, projectPath: launch.cwd, identity: state.input.identity, permission: state.input.permission });
|
|
178
|
+
return binding.revision;
|
|
179
|
+
}
|
|
180
|
+
export async function disposeDshNativeLaunch(launch) {
|
|
181
|
+
const state = launches.get(launch);
|
|
182
|
+
if (!state)
|
|
183
|
+
throw new Error('DSH_SHARED_STARTUP_INVALID');
|
|
184
|
+
state.phase = 'closed';
|
|
185
|
+
const relative = path.relative(state.temporary, launch.runtimePath);
|
|
186
|
+
if (!relative || relative.startsWith('..') || path.isAbsolute(relative))
|
|
187
|
+
throw new Error('DSH_SHARED_TEMP_INVALID');
|
|
188
|
+
try {
|
|
189
|
+
if ((await fsp.lstat(launch.runtimePath)).isSymbolicLink()
|
|
190
|
+
|| normalizeLaunchPath(await fsp.realpath(launch.runtimePath)) !== normalizeLaunchPath(launch.runtimePath))
|
|
191
|
+
throw new Error('DSH_SHARED_TEMP_INVALID');
|
|
192
|
+
await fsp.rm(launch.runtimePath, { recursive: true });
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (error.code !== 'ENOENT')
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** Copy only inline image bytes: local paths are never read or forwarded. */
|
|
200
|
+
function imageInput(images = []) {
|
|
201
|
+
const reject = (reason) => {
|
|
202
|
+
throw Object.assign(new Error(`DSH_IMAGE_INPUT_INVALID: ${reason}`), { code: 'DSH_IMAGE_INPUT_INVALID' });
|
|
203
|
+
};
|
|
204
|
+
if (images.length > DSH_IMAGE_LIMITS.count)
|
|
205
|
+
reject('At most 20 images are accepted per message');
|
|
206
|
+
let total = 0;
|
|
207
|
+
return images.map(image => {
|
|
208
|
+
if (typeof image?.data !== 'string' || !image.data.length
|
|
209
|
+
|| image.data.length > 4 * Math.ceil(DSH_IMAGE_LIMITS.bytes / 3))
|
|
210
|
+
reject('Image data is missing or exceeds 20 MiB');
|
|
211
|
+
const bytes = Buffer.from(image.data, 'base64');
|
|
212
|
+
if (!bytes.length || bytes.toString('base64') !== image.data)
|
|
213
|
+
reject('Image data must be canonical base64');
|
|
214
|
+
if (bytes.length > DSH_IMAGE_LIMITS.bytes || (total += bytes.length) > DSH_IMAGE_LIMITS.totalBytes) {
|
|
215
|
+
reject('Image bytes exceed the per-image or 40 MiB message limit');
|
|
216
|
+
}
|
|
217
|
+
const detected = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? 'image/png'
|
|
218
|
+
: bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 ? 'image/jpeg'
|
|
219
|
+
: ['GIF87a', 'GIF89a'].includes(bytes.subarray(0, 6).toString()) ? 'image/gif'
|
|
220
|
+
: bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP' ? 'image/webp' : undefined;
|
|
221
|
+
if (!detected || (image.mimeType !== undefined && image.mimeType !== detected))
|
|
222
|
+
reject('Unsupported image type or MIME mismatch');
|
|
223
|
+
return { data: image.data, mimeType: detected };
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
/** A bounded consumer queue; a failed consumer cancels the owned producer in its iterator finally. */
|
|
227
|
+
class EventQueue {
|
|
228
|
+
items = [];
|
|
229
|
+
wake;
|
|
230
|
+
ended = false;
|
|
231
|
+
push(event) {
|
|
232
|
+
if (this.ended)
|
|
233
|
+
return;
|
|
234
|
+
if (this.items.length >= 4096)
|
|
235
|
+
throw new Error('DSH event consumer exceeded its queue limit');
|
|
236
|
+
this.items.push(event);
|
|
237
|
+
this.wake?.();
|
|
238
|
+
this.wake = undefined;
|
|
239
|
+
}
|
|
240
|
+
end() { this.ended = true; this.wake?.(); this.wake = undefined; }
|
|
241
|
+
async *read() {
|
|
242
|
+
while (true) {
|
|
243
|
+
const item = this.items.shift();
|
|
244
|
+
if (item) {
|
|
245
|
+
yield item;
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (this.ended)
|
|
249
|
+
return;
|
|
250
|
+
await new Promise(resolve => { this.wake = resolve; });
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
export class DshRunner {
|
|
255
|
+
host;
|
|
256
|
+
name = 'dsh';
|
|
257
|
+
retryInputSemantics = 'at_most_once';
|
|
258
|
+
capabilities = { compact: true, taskRecovery: true, fullaccess: true,
|
|
259
|
+
fork: true, forkAtTurn: true, forkAtMessage: true, askUserQuestion: true };
|
|
260
|
+
pendingForks = new Map();
|
|
261
|
+
mode = 'readonly';
|
|
262
|
+
disposed = false;
|
|
263
|
+
permissions = new Map();
|
|
264
|
+
bindings = new Map();
|
|
265
|
+
executions = new Map();
|
|
266
|
+
streams = new Map();
|
|
267
|
+
gateway;
|
|
268
|
+
sendPrompt;
|
|
269
|
+
// The descriptor factory selects shared mode only after explicit resource validation.
|
|
270
|
+
constructor(host) {
|
|
271
|
+
this.host = host;
|
|
272
|
+
// Capture the implementation now: AgentLoader later wraps the public dispose method with this scope.
|
|
273
|
+
host.lifecycle.defer(this.dispose.bind(this), 'dsh runner');
|
|
274
|
+
}
|
|
275
|
+
setPermissionContext(sessionId, context) { this.permissions.set(sessionId, context); }
|
|
276
|
+
setPermissionGateway(gateway) { this.gateway = gateway; }
|
|
277
|
+
setSendPrompt(fn) { this.sendPrompt = fn; }
|
|
278
|
+
setMode(mode) { this.mode = normalizePermissionMode(mode).mode; }
|
|
279
|
+
getMode() { return this.mode; }
|
|
280
|
+
async getModelCatalog() {
|
|
281
|
+
const providerId = this.host.config.provider;
|
|
282
|
+
if (providerId === undefined) {
|
|
283
|
+
const { getDshNativeCatalog } = await import('./resources.js');
|
|
284
|
+
return getDshNativeCatalog(this.host.config, this.host.aid);
|
|
285
|
+
}
|
|
286
|
+
if (typeof providerId !== 'string')
|
|
287
|
+
throw new Error('DSH Provider is required');
|
|
288
|
+
const provider = this.host.resolveProvider(providerId);
|
|
289
|
+
this.validateProvider(provider);
|
|
290
|
+
const snapshot = applyProviderModelOverrides(await getProviderCatalog(providerId, provider.serviceType, false, true), provider.modelOverrides, provider.modelPolicy);
|
|
291
|
+
const models = adaptCatalogModels(snapshot.models, this.name);
|
|
292
|
+
return { ...snapshot, revision: catalogHash({ revision: snapshot.revision, models }), models };
|
|
293
|
+
}
|
|
294
|
+
async listModels() { return (await this.getModelCatalog()).models.map(model => model.id); }
|
|
295
|
+
async getAvailableEfforts(model) {
|
|
296
|
+
const entry = (await this.getModelCatalog()).models.find(item => item.id === model);
|
|
297
|
+
return entry?.reasoningLevels ?? [];
|
|
298
|
+
}
|
|
299
|
+
validateProvider(provider) {
|
|
300
|
+
if (!['claude', 'anthropic', 'anthropic-messages', 'messages'].includes(provider.style)) {
|
|
301
|
+
throw new Error('DSH requires a Messages-compatible Provider');
|
|
302
|
+
}
|
|
303
|
+
if (Object.keys(provider.headers ?? {}).length || Object.keys(provider.queryParams ?? {}).length) {
|
|
304
|
+
throw new Error('DSH custom Provider headers/query parameters are not supported');
|
|
305
|
+
}
|
|
306
|
+
if (!provider.apiKey)
|
|
307
|
+
throw new Error('DSH Provider API key is missing');
|
|
308
|
+
}
|
|
309
|
+
updateSessionId(sessionId, nativeId) { this.bindings.set(sessionId, nativeId); }
|
|
310
|
+
hasActiveStream(sessionId) { return this.executions.has(sessionId) || this.streams.has(sessionId); }
|
|
311
|
+
hasActiveOperation(sessionId, taskId) {
|
|
312
|
+
const run = this.executions.get(sessionId);
|
|
313
|
+
return !!run && (!taskId || run.identity.taskId === taskId);
|
|
314
|
+
}
|
|
315
|
+
getExecutionState(sessionId) {
|
|
316
|
+
const run = this.executions.get(sessionId);
|
|
317
|
+
return !run ? 'idle' : run.abort.signal.aborted ? 'interrupting' : 'running';
|
|
318
|
+
}
|
|
319
|
+
registerStream(key, stream, target) {
|
|
320
|
+
const run = this.executions.get(key);
|
|
321
|
+
if (run && target && !this.matches(run, target))
|
|
322
|
+
return;
|
|
323
|
+
this.streams.set(key, { stream, target });
|
|
324
|
+
}
|
|
325
|
+
cleanupStream(key, target) {
|
|
326
|
+
const current = this.streams.get(key);
|
|
327
|
+
if (target && current?.target && (current.target.taskId !== target.taskId || current.target.generation !== target.generation))
|
|
328
|
+
return;
|
|
329
|
+
this.streams.delete(key);
|
|
330
|
+
}
|
|
331
|
+
matches(run, target) {
|
|
332
|
+
return !target || (run.identity.taskId === target.taskId && run.identity.generation === target.generation);
|
|
333
|
+
}
|
|
334
|
+
async runQuery(sessionId, prompt, projectPath, initialNativeId, images, systemPrompt, _sessionManager, override = {}, runtimeEnv = {}) {
|
|
335
|
+
const inputImages = imageInput(images);
|
|
336
|
+
const run = this.start(sessionId, projectPath, override, false);
|
|
337
|
+
run.nativeId = override.recovery?.agentSessionId ?? (override.backend?.kind === 'topic'
|
|
338
|
+
? override.backend.agentSessionId ?? undefined : initialNativeId ?? this.bindings.get(sessionId));
|
|
339
|
+
// Register ownership synchronously, before any dependency probe or process startup can await.
|
|
340
|
+
run.done = this.execute(run, prompt, systemPrompt, initialNativeId, override, runtimeEnv, inputImages);
|
|
341
|
+
const self = this;
|
|
342
|
+
return (async function* () {
|
|
343
|
+
try {
|
|
344
|
+
yield* run.queue.read();
|
|
345
|
+
}
|
|
346
|
+
finally {
|
|
347
|
+
if (!run.stopped)
|
|
348
|
+
await self.interrupt(sessionId, run.identity);
|
|
349
|
+
}
|
|
350
|
+
})();
|
|
351
|
+
}
|
|
352
|
+
start(sessionId, projectPath, override, compact) {
|
|
353
|
+
if (this.disposed || this.host.signal.aborted)
|
|
354
|
+
throw new Error('DSH runner disposed');
|
|
355
|
+
const previous = this.executions.get(sessionId);
|
|
356
|
+
if (previous)
|
|
357
|
+
throw previous.abort.signal.aborted ? unsettledInterruptError(this.name) : new Error('DSH session is busy');
|
|
358
|
+
const identity = override.turn ?? { sessionId, taskId: randomUUID(), turnId: randomUUID(), generation: 0, inputId: randomUUID() };
|
|
359
|
+
if (identity.sessionId !== sessionId || !Number.isSafeInteger(identity.generation) || identity.generation < 0) {
|
|
360
|
+
throw new Error('DSH run identity does not match session');
|
|
361
|
+
}
|
|
362
|
+
const permission = this.permissions.get(sessionId);
|
|
363
|
+
if (!permission)
|
|
364
|
+
throw new Error('DSH requires a Host permission context');
|
|
365
|
+
if (!compact && !override.turn)
|
|
366
|
+
throw new Error('DSH execution requires the Host task/input identity');
|
|
367
|
+
if (permission.selfAid && permission.selfAid !== this.host.aid)
|
|
368
|
+
throw new Error('DSH permission identity does not match Runner');
|
|
369
|
+
if ((permission.taskId && permission.taskId !== identity.taskId)
|
|
370
|
+
|| (permission.turn && (permission.turn.sessionId !== sessionId || permission.turn.turnId !== identity.turnId
|
|
371
|
+
|| permission.turn.taskId !== identity.taskId || permission.turn.generation !== identity.generation))) {
|
|
372
|
+
throw new Error('DSH permission context belongs to another task generation');
|
|
373
|
+
}
|
|
374
|
+
const mode = normalizeExecutionPermissionMode(override.permissionMode ?? this.mode);
|
|
375
|
+
if (mode === 'fullaccess') {
|
|
376
|
+
if (!override.turn || !permission.turn || !hasTrustedFullAccessContext(permission) || !permission.revalidateExecutionIdentity
|
|
377
|
+
|| permission.systemSessionCheck)
|
|
378
|
+
throw new Error('DSH requires current Host fullaccess authorization');
|
|
379
|
+
const authorization = permission.executionPermission;
|
|
380
|
+
if ((authorization.agentAid && authorization.agentAid !== this.host.aid)
|
|
381
|
+
|| (authorization.sessionId && authorization.sessionId !== sessionId)) {
|
|
382
|
+
throw new Error('DSH fullaccess authorization belongs to another Agent or session');
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const run = { identity: { ...identity }, projectPath: path.resolve(projectPath),
|
|
386
|
+
mode, permission,
|
|
387
|
+
...(mode === 'fullaccess' ? { fullAccessAuthorization: JSON.stringify(permission.executionPermission) } : {}),
|
|
388
|
+
queue: new EventQueue(), abort: new AbortController(), done: Promise.resolve(),
|
|
389
|
+
stopped: false, opened: false, accepted: false, compact, stderr: '', seq: 0, toolNames: new Map(), injections: Promise.resolve() };
|
|
390
|
+
this.executions.set(sessionId, run);
|
|
391
|
+
return run;
|
|
392
|
+
}
|
|
393
|
+
async execute(run, prompt, systemPrompt, initialNativeId, override, runtimeEnv, images = []) {
|
|
394
|
+
const started = Date.now();
|
|
395
|
+
try {
|
|
396
|
+
if (!run.compact && !systemPrompt?.trim())
|
|
397
|
+
throw new Error('DSH requires the current Host system prompt');
|
|
398
|
+
const validatedInference = { ...resolveRunInference('dsh', Object.fromEntries(['maxOutputTokens', 'temperature', 'stop']
|
|
399
|
+
.filter(key => this.host.config[key] !== undefined).map(key => [key, this.host.config[key]]))),
|
|
400
|
+
...resolveRunInference('dsh', override.inference) };
|
|
401
|
+
await this.revalidate(run);
|
|
402
|
+
const managedTempDir = getManagedTaskTempDir(runtimeEnv) ?? run.permission.managedTempDir;
|
|
403
|
+
if (!managedTempDir || !path.isAbsolute(managedTempDir))
|
|
404
|
+
throw new Error('DSH requires a session-owned TMPDIR');
|
|
405
|
+
if (runtimeEnv.TMPDIR && path.resolve(runtimeEnv.TMPDIR) !== path.resolve(managedTempDir))
|
|
406
|
+
throw new Error('DSH TMPDIR mismatch');
|
|
407
|
+
await fsp.mkdir(managedTempDir, { recursive: true, mode: 0o700 });
|
|
408
|
+
let model = '';
|
|
409
|
+
let nativeId;
|
|
410
|
+
let opened;
|
|
411
|
+
const providerId = override.provider ?? this.host.config.provider;
|
|
412
|
+
const selectedModel = override.model ?? this.host.config.model;
|
|
413
|
+
const effort = override.effortMode === 'model_default' ? undefined : override.effort ?? this.host.config.effort;
|
|
414
|
+
if (effort !== undefined && !DSH_EFFORTS.includes(effort)) {
|
|
415
|
+
throw new Error(`DSH unsupported reasoning effort: ${String(effort)}`);
|
|
416
|
+
}
|
|
417
|
+
let provider;
|
|
418
|
+
let catalog;
|
|
419
|
+
let imageIn;
|
|
420
|
+
if (selectedModel !== undefined) {
|
|
421
|
+
if (typeof selectedModel !== 'string' || !selectedModel.trim())
|
|
422
|
+
throw new Error('DSH model is invalid');
|
|
423
|
+
model = selectedModel;
|
|
424
|
+
}
|
|
425
|
+
if (providerId !== undefined) {
|
|
426
|
+
if (typeof providerId !== 'string' || !providerId.trim())
|
|
427
|
+
throw new Error('DSH Provider is invalid');
|
|
428
|
+
provider = this.host.resolveProvider(providerId);
|
|
429
|
+
this.validateProvider(provider);
|
|
430
|
+
if (model)
|
|
431
|
+
assertProviderModelAllowed(model, provider);
|
|
432
|
+
catalog = applyProviderModelOverrides(await getProviderCatalog(providerId, provider.serviceType, false, true), provider.modelOverrides, provider.modelPolicy);
|
|
433
|
+
imageIn = catalog.models.find(entry => entry.id === model)?.imageIn;
|
|
434
|
+
}
|
|
435
|
+
{
|
|
436
|
+
const registry = new DshNativeResourceRegistry();
|
|
437
|
+
const requested = override.recovery?.agentSessionId ?? (override.backend?.kind === 'topic'
|
|
438
|
+
? override.backend.agentSessionId : initialNativeId ?? this.bindings.get(run.identity.sessionId));
|
|
439
|
+
let session;
|
|
440
|
+
try {
|
|
441
|
+
session = await registry.sessionForTask(this.host.aid, run.identity.sessionId);
|
|
442
|
+
}
|
|
443
|
+
catch (error) {
|
|
444
|
+
if (!(error instanceof Error) || error.message !== 'DSH_SESSION_NOT_BOUND' || requested || run.compact)
|
|
445
|
+
throw error;
|
|
446
|
+
}
|
|
447
|
+
const resourceId = session?.nativeResourceId ?? this.host.config.nativeResourceId;
|
|
448
|
+
const registrationRevision = session?.registrationRevision ?? this.host.config.nativeRegistrationRevision;
|
|
449
|
+
// An authorized existing binding pins its original resource. Host
|
|
450
|
+
// defaults select only new conversations, never migrate native history.
|
|
451
|
+
if (typeof resourceId !== 'string' || typeof registrationRevision !== 'string')
|
|
452
|
+
throw new Error('DSH_RESOURCE_NOT_REGISTERED');
|
|
453
|
+
nativeId = session?.nativeSessionId ?? null;
|
|
454
|
+
if (requested && requested !== nativeId)
|
|
455
|
+
throw new Error('DSH_SESSION_BINDING_MISMATCH');
|
|
456
|
+
if (override.asyncQuestionAnswer && override.asyncQuestionAnswer.providerThreadId !== nativeId) {
|
|
457
|
+
throw new Error('DSH async question backend changed before resume');
|
|
458
|
+
}
|
|
459
|
+
run.nativeId = nativeId ?? undefined;
|
|
460
|
+
run.nativeSessionBindingRevision = session?.revision;
|
|
461
|
+
run.nativeLaunch = await prepareDshNativeLaunch({ agentAid: this.host.aid,
|
|
462
|
+
nativeResourceId: resourceId, registrationRevision,
|
|
463
|
+
sessionBindingRevision: session?.revision, projectPath: run.projectPath, nativeSessionId: nativeId,
|
|
464
|
+
operation: run.compact ? 'compact' : 'run', identity: run.identity, permission: run.permission, signal: run.abort.signal }, registry);
|
|
465
|
+
run.projectPath = run.nativeLaunch.cwd;
|
|
466
|
+
await this.launch(run, run.nativeLaunch.executablePath, [...run.nativeLaunch.args], { ...run.nativeLaunch.env });
|
|
467
|
+
const init = await this.bounded(run.request('initialize', { protocol: NATIVE_PROTOCOL, binding: run.nativeLaunch.binding }), 'DSH native initialize');
|
|
468
|
+
if (init?.protocol !== NATIVE_PROTOCOL || init.dshVersion !== DSH_VERSION || init.platform !== process.platform
|
|
469
|
+
|| init.storageMode !== 'native-shared' || !isDeepStrictEqual(init.binding, run.nativeLaunch.binding)) {
|
|
470
|
+
throw new Error('DSH native handshake mismatch');
|
|
471
|
+
}
|
|
472
|
+
await this.revalidate(run);
|
|
473
|
+
const sandbox = resolvePhaseOneExecutionSandbox(run.mode, run.permission.role);
|
|
474
|
+
const effective = resolveEffective({ self: this.host.aid }, { cache: true });
|
|
475
|
+
opened = await this.openNativeSession(run, { protocol: NATIVE_PROTOCOL, identity: run.identity,
|
|
476
|
+
nativeSessionId: nativeId, cwd: run.projectPath, systemPrompt: systemPrompt ?? null,
|
|
477
|
+
...(model ? { model } : {}),
|
|
478
|
+
...(effort === undefined ? {} : { effort }),
|
|
479
|
+
...(override.effortMode === 'model_default' ? { effortMode: 'model_default' } : {}),
|
|
480
|
+
...(provider ? { connection: { providerId, baseUrl: provider.baseUrl, apiKey: provider.apiKey, imageIn } } : {}),
|
|
481
|
+
toolEnv: sanitizeShellExecutionEnvironment({ ...runtimeEnv, EVOLCORE_HOME: resolveRoot(),
|
|
482
|
+
TMPDIR: managedTempDir, TEMP: managedTempDir, TMP: managedTempDir }),
|
|
483
|
+
inference: validatedInference, sandboxMode: sandbox.state === 'off' || run.permission.systemSessionSandbox === 'off'
|
|
484
|
+
? 'danger-full-access' : run.mode === 'readonly' ? 'read-only' : 'workspace-write',
|
|
485
|
+
nativeSkillPolicy: { enabled: effective.baseagentSkills === true && !run.permission.systemSessionCheck,
|
|
486
|
+
...normalizeCapabilityTypeConfig(effective.capabilities?.dsh?.skill) } });
|
|
487
|
+
if (typeof opened.model !== 'string' || !opened.model)
|
|
488
|
+
throw new Error('DSH native model evidence is missing');
|
|
489
|
+
if (model && opened.model !== model)
|
|
490
|
+
throw new Error('DSH native model selection mismatch');
|
|
491
|
+
model = opened.model;
|
|
492
|
+
if (provider)
|
|
493
|
+
assertProviderModelAllowed(model, provider);
|
|
494
|
+
run.nativeModel = model;
|
|
495
|
+
await this.revalidate(run);
|
|
496
|
+
}
|
|
497
|
+
if (typeof opened?.nativeSessionId !== 'string' || (nativeId && opened.nativeSessionId !== nativeId))
|
|
498
|
+
throw new Error('DSH native binding mismatch');
|
|
499
|
+
run.nativeId = opened.nativeSessionId;
|
|
500
|
+
run.opened = true;
|
|
501
|
+
run.abort.signal.throwIfAborted();
|
|
502
|
+
const binding = run.compact ? 'already_active'
|
|
503
|
+
: await this.host.onSessionIdUpdate(run.identity.sessionId, opened.nativeSessionId, { turn: run.identity });
|
|
504
|
+
if (!['activated', 'already_active', 'legacy_updated'].includes(binding))
|
|
505
|
+
throw new Error(`DSH binding rejected: ${binding}`);
|
|
506
|
+
if (run.nativeLaunch?.binding.nativeSessionId === null) {
|
|
507
|
+
run.nativeSessionBindingRevision = await recordDshNativeCreatedSession(run.nativeLaunch, opened.nativeSessionId);
|
|
508
|
+
}
|
|
509
|
+
this.bindings.set(run.identity.sessionId, opened.nativeSessionId);
|
|
510
|
+
run.queue.push({ type: 'session_id', sessionId: opened.nativeSessionId });
|
|
511
|
+
run.abort.signal.throwIfAborted();
|
|
512
|
+
await this.revalidate(run);
|
|
513
|
+
let autoCompactThresholdTokens;
|
|
514
|
+
if (!run.compact && nativeId !== null) {
|
|
515
|
+
const contextWindow = Number.isSafeInteger(opened.contextWindow) && opened.contextWindow > 0
|
|
516
|
+
? opened.contextWindow : undefined;
|
|
517
|
+
const configuredThreshold = readAgentCompactThreshold(this.host.aid, 'dsh');
|
|
518
|
+
autoCompactThresholdTokens = resolveAgentContextPolicy('dsh', model, catalog, configuredThreshold, contextWindow)
|
|
519
|
+
.outerAutoCompactTokens;
|
|
520
|
+
}
|
|
521
|
+
const result = await run.request(run.compact ? 'session/compact' : 'run/start', {
|
|
522
|
+
identity: run.identity, prompt, ...(images.length ? { images } : {}),
|
|
523
|
+
...(autoCompactThresholdTokens === undefined ? {} : { autoCompactThresholdTokens }),
|
|
524
|
+
});
|
|
525
|
+
if (!object(result))
|
|
526
|
+
throw new Error('Invalid DSH operation result');
|
|
527
|
+
if (object(result.requestFailure)) {
|
|
528
|
+
const failure = result.requestFailure;
|
|
529
|
+
if (typeof failure.message !== 'string' || failure.message.length > 16384
|
|
530
|
+
|| (failure.status !== undefined && (!Number.isInteger(failure.status) || failure.status < 100 || failure.status > 599))) {
|
|
531
|
+
throw new Error('Invalid DSH request failure');
|
|
532
|
+
}
|
|
533
|
+
throw Object.assign(new Error(`DSH request failed${failure.status === undefined ? '' : ` (HTTP ${failure.status})`}: ${failure.message}`), {
|
|
534
|
+
...(typeof failure.code === 'string' ? { code: failure.code } : {}),
|
|
535
|
+
...(failure.status === undefined ? {} : { status: failure.status }),
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
run.result = result;
|
|
539
|
+
await this.bounded(run.request('session/close'), 'DSH session close');
|
|
540
|
+
run.process.stdin.end();
|
|
541
|
+
await this.bounded(run.exit, 'DSH process exit');
|
|
542
|
+
run.stopped = true;
|
|
543
|
+
if (!run.compact) {
|
|
544
|
+
run.queue.push({ type: 'state_changed', state: 'idle' });
|
|
545
|
+
run.queue.push({ type: 'complete', result: result.text ?? '', isError: result.isError === true,
|
|
546
|
+
...(run.usage ? { tokenUsage: run.usage } : {}), ...(run.contextUsage ? { contextUsage: run.contextUsage } : {}),
|
|
547
|
+
terminalReason: run.abort.signal.aborted ? 'interrupted' : result.reason, model, durationMs: Date.now() - started });
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
catch (error) {
|
|
551
|
+
run.failure = error instanceof Error ? error : new Error(String(error));
|
|
552
|
+
try {
|
|
553
|
+
await this.terminate(run);
|
|
554
|
+
}
|
|
555
|
+
catch { /* Retain run ownership until process exit is confirmed. */ }
|
|
556
|
+
if (run.stopped && !run.compact) {
|
|
557
|
+
run.queue.push({ type: 'state_changed', state: 'idle' });
|
|
558
|
+
run.queue.push({ type: 'complete', isError: true, ...(run.usage ? { tokenUsage: run.usage } : {}),
|
|
559
|
+
errors: [errorText(error)], terminalReason: run.abort.signal.aborted ? 'interrupted' : 'error' });
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
finally {
|
|
563
|
+
if (!run.process)
|
|
564
|
+
run.stopped = true;
|
|
565
|
+
if (run.stopped) {
|
|
566
|
+
if (this.executions.get(run.identity.sessionId) === run)
|
|
567
|
+
this.executions.delete(run.identity.sessionId);
|
|
568
|
+
if (run.nativeLaunch)
|
|
569
|
+
await disposeDshNativeLaunch(run.nativeLaunch).catch(() => { });
|
|
570
|
+
run.queue.end();
|
|
571
|
+
}
|
|
572
|
+
else {
|
|
573
|
+
// The consumer sees failure but the session remains locked while the writer can still run.
|
|
574
|
+
run.queue.push({ type: 'error', error: 'DSH stop was not confirmed', errorType: 'unknown' });
|
|
575
|
+
run.queue.end();
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
async openNativeSession(run, params) {
|
|
580
|
+
const waits = [500, 1000, 3000];
|
|
581
|
+
for (let attempt = 0;; attempt++) {
|
|
582
|
+
run.abort.signal.throwIfAborted();
|
|
583
|
+
await this.revalidate(run);
|
|
584
|
+
try {
|
|
585
|
+
return await this.bounded(run.request('session/open', params), 'DSH native session/open');
|
|
586
|
+
}
|
|
587
|
+
catch (error) {
|
|
588
|
+
if (params.nativeSessionId === null || !isDshSessionBusyError(error))
|
|
589
|
+
throw error;
|
|
590
|
+
const waitMs = waits[attempt];
|
|
591
|
+
if (waitMs === undefined) {
|
|
592
|
+
throw Object.assign(new Error('DSH_SESSION_BUSY: the native session still has an active writer', { cause: error }), { code: 'DSH_SESSION_BUSY' });
|
|
593
|
+
}
|
|
594
|
+
run.queue.push({ type: 'status', subtype: 'session_busy', message: '正在等待 DeepSeek Harness 释放会话' });
|
|
595
|
+
// Retry only the unopened lease. No input has been accepted, and every
|
|
596
|
+
// attempt revalidates the original task's current authority.
|
|
597
|
+
await delay(waitMs, undefined, { signal: run.abort.signal });
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
async launch(run, executable, args, env) {
|
|
602
|
+
let command = executable;
|
|
603
|
+
let argv = args;
|
|
604
|
+
if (process.platform === 'linux') {
|
|
605
|
+
const guarded = buildHClassGuardCommand(command, argv, resolveRoot(), {
|
|
606
|
+
selfAid: this.host.aid, protectEvolcoreFilesystem: run.mode !== 'fullaccess',
|
|
607
|
+
});
|
|
608
|
+
if (!guarded)
|
|
609
|
+
throw new Error('DSH requires the Host protected-filesystem guard');
|
|
610
|
+
command = guarded.command;
|
|
611
|
+
argv = guarded.args;
|
|
612
|
+
}
|
|
613
|
+
else if (process.platform !== 'win32')
|
|
614
|
+
throw new Error('DSH supports Linux and Windows only');
|
|
615
|
+
const child = spawn(command, argv, { cwd: run.projectPath, env,
|
|
616
|
+
stdio: run.nativeLaunch ? ['pipe', 'pipe', 'pipe', 'pipe'] : ['pipe', 'pipe', 'pipe'],
|
|
617
|
+
windowsHide: process.platform === 'win32' });
|
|
618
|
+
run.process = child;
|
|
619
|
+
const pending = new Map();
|
|
620
|
+
let nextId = 0;
|
|
621
|
+
const fail = (error) => { for (const item of pending.values())
|
|
622
|
+
item.reject(error); pending.clear(); };
|
|
623
|
+
child.stderr.on('data', data => { run.stderr = (run.stderr + data.toString()).slice(-8192); });
|
|
624
|
+
run.exit = new Promise(resolve => {
|
|
625
|
+
child.once('error', error => { fail(error); if (!child.pid) {
|
|
626
|
+
run.stopped = true;
|
|
627
|
+
resolve();
|
|
628
|
+
} });
|
|
629
|
+
child.once('close', () => { run.stopped = true; fail(new Error('DSH transport closed')); resolve(); });
|
|
630
|
+
});
|
|
631
|
+
run.request = (method, params = {}) => new Promise((resolve, reject) => {
|
|
632
|
+
if (run.stopped || child.stdin.destroyed) {
|
|
633
|
+
reject(new Error('DSH transport is closed'));
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
const id = ++nextId;
|
|
637
|
+
pending.set(id, { resolve, reject });
|
|
638
|
+
const boundParams = run.nativeLaunch && method !== 'initialize' ? { ...params, identity: run.identity } : params;
|
|
639
|
+
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params: boundParams }) + '\n', error => {
|
|
640
|
+
if (error) {
|
|
641
|
+
pending.delete(id);
|
|
642
|
+
reject(error);
|
|
643
|
+
}
|
|
644
|
+
});
|
|
645
|
+
});
|
|
646
|
+
let bufferBytes = 0;
|
|
647
|
+
child.stdout.on('data', (chunk) => {
|
|
648
|
+
bufferBytes += chunk.length;
|
|
649
|
+
if (bufferBytes > 8 * 1024 * 1024) {
|
|
650
|
+
const error = new Error('DSH protocol frame exceeded limit');
|
|
651
|
+
run.failure = error;
|
|
652
|
+
fail(error);
|
|
653
|
+
void this.terminate(run).catch(() => { });
|
|
654
|
+
}
|
|
655
|
+
if (chunk.includes(10))
|
|
656
|
+
bufferBytes = 0;
|
|
657
|
+
});
|
|
658
|
+
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
659
|
+
lines.on('line', line => {
|
|
660
|
+
void (async () => {
|
|
661
|
+
const frame = JSON.parse(line);
|
|
662
|
+
if (!object(frame) || frame.jsonrpc !== '2.0')
|
|
663
|
+
throw new Error('Invalid DSH JSON-RPC frame');
|
|
664
|
+
if (typeof frame.method === 'string' && frame.id !== undefined) {
|
|
665
|
+
if (frame.method !== 'tool/preflight')
|
|
666
|
+
throw new Error('Unknown DSH Host request');
|
|
667
|
+
try {
|
|
668
|
+
const result = await this.preflight(run, frame.params);
|
|
669
|
+
// Synchronous Host policy hooks may have queued corrections while deciding this tool.
|
|
670
|
+
await run.injections;
|
|
671
|
+
if (!child.stdin.destroyed)
|
|
672
|
+
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: frame.id, result }) + '\n');
|
|
673
|
+
}
|
|
674
|
+
catch (error) {
|
|
675
|
+
const failure = dshAuthorizationFailure(error, run.abort.signal.aborted);
|
|
676
|
+
logger.warn(`[DshRunner] Tool authorization failed: session=${run.identity.sessionId} code=${failure.errorDetailCode}`);
|
|
677
|
+
if (!child.stdin.destroyed)
|
|
678
|
+
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: frame.id,
|
|
679
|
+
result: { ...failure, input: object(frame.params?.input) ? frame.params.input : {}, hash: frame.params?.hash } }) + '\n');
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
else if (typeof frame.method === 'string')
|
|
683
|
+
this.notify(run, frame.method, frame.params);
|
|
684
|
+
else {
|
|
685
|
+
const item = pending.get(frame.id);
|
|
686
|
+
if (!item)
|
|
687
|
+
throw new Error('DSH returned an unknown request ID');
|
|
688
|
+
pending.delete(frame.id);
|
|
689
|
+
if (frame.error)
|
|
690
|
+
item.reject(new Error(`DSH request failed: ${frame.error.message}`));
|
|
691
|
+
else
|
|
692
|
+
item.resolve(frame.result);
|
|
693
|
+
}
|
|
694
|
+
})().catch(error => { run.failure = new Error(errorText(error)); fail(run.failure); void this.terminate(run).catch(() => { }); });
|
|
695
|
+
});
|
|
696
|
+
await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
|
|
697
|
+
if (run.nativeLaunch)
|
|
698
|
+
await writeDshNativeStartup(run.nativeLaunch, child.stdio[3]);
|
|
699
|
+
}
|
|
700
|
+
checkIdentity(run, params) {
|
|
701
|
+
if (!object(params) || params.protocol !== NATIVE_PROTOCOL || !object(params.identity)
|
|
702
|
+
|| Object.keys(run.identity).some(key => params.identity[key] !== run.identity[key])
|
|
703
|
+
|| this.executions.get(run.identity.sessionId) !== run)
|
|
704
|
+
throw new Error('DSH event identity mismatch');
|
|
705
|
+
if (run.nativeId && params.nativeSessionId !== run.nativeId)
|
|
706
|
+
throw new Error('DSH native event identity mismatch');
|
|
707
|
+
}
|
|
708
|
+
notify(run, method, params) {
|
|
709
|
+
this.checkIdentity(run, params);
|
|
710
|
+
if (!Number.isSafeInteger(params.seq) || params.seq !== run.seq + 1)
|
|
711
|
+
throw new Error('DSH event sequence gap');
|
|
712
|
+
run.seq = params.seq;
|
|
713
|
+
if (run.abort.signal.aborted && !['usage', 'tool_result'].includes(method))
|
|
714
|
+
return;
|
|
715
|
+
if (method === 'input_accepted') {
|
|
716
|
+
if (params.inputId !== run.identity.inputId || run.accepted)
|
|
717
|
+
throw new Error('DSH duplicate or mismatched input receipt');
|
|
718
|
+
run.accepted = true;
|
|
719
|
+
run.queue.push({ type: 'input_accepted', inputId: params.inputId });
|
|
720
|
+
}
|
|
721
|
+
else if (method === 'text' && typeof params.text === 'string') {
|
|
722
|
+
run.queue.push({ type: 'text', text: params.text, turn: params.turn, assistantUuid: params.messageId });
|
|
723
|
+
}
|
|
724
|
+
else if (method === 'activity')
|
|
725
|
+
run.queue.push({ type: 'heartbeat', source: params.source === 'compaction' ? 'compaction' : 'text' });
|
|
726
|
+
else if (method === 'user_question') {
|
|
727
|
+
const request = params.request;
|
|
728
|
+
if (!object(request) || request.providerThreadId !== run.nativeId || request.providerTurnId !== run.identity.turnId
|
|
729
|
+
|| typeof request.itemId !== 'string' || run.question)
|
|
730
|
+
throw new Error('Invalid DSH question binding');
|
|
731
|
+
const questions = parseAsyncUserQuestions(request.questions);
|
|
732
|
+
run.question = { itemId: request.itemId, questions, answers: new Set() };
|
|
733
|
+
run.queue.push({ type: 'user_question', request: { providerThreadId: run.nativeId,
|
|
734
|
+
providerTurnId: run.identity.turnId, itemId: request.itemId, questions } });
|
|
735
|
+
}
|
|
736
|
+
else if (method === 'state') {
|
|
737
|
+
// Native idle precedes flush/disposal; Host idle is emitted only after the writer exits.
|
|
738
|
+
if (params.state === 'running')
|
|
739
|
+
run.queue.push({ type: 'state_changed', state: 'running' });
|
|
740
|
+
else if (params.state !== 'idle')
|
|
741
|
+
throw new Error('Invalid DSH native state');
|
|
742
|
+
}
|
|
743
|
+
else if (method === 'usage') {
|
|
744
|
+
if (params.tokenUsage !== undefined)
|
|
745
|
+
run.usage = this.validateUsage(params.tokenUsage);
|
|
746
|
+
if (params.contextUsage !== undefined) {
|
|
747
|
+
const context = params.contextUsage;
|
|
748
|
+
if (!object(context) || !Number.isSafeInteger(context.totalTokens) || context.totalTokens < 0
|
|
749
|
+
|| !Number.isSafeInteger(context.maxTokens) || context.maxTokens <= 0 || typeof context.model !== 'string') {
|
|
750
|
+
throw new Error('Invalid DSH context usage');
|
|
751
|
+
}
|
|
752
|
+
run.contextUsage = { totalTokens: context.totalTokens, maxTokens: context.maxTokens,
|
|
753
|
+
percentage: context.totalTokens / context.maxTokens * 100, model: context.model,
|
|
754
|
+
// DSH's route may use advisory capacity defaults; never present them as gateway-verified.
|
|
755
|
+
contextWindowSource: 'safe-fallback' };
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
else if (method === 'compact') {
|
|
759
|
+
if (!Number.isSafeInteger(params.preTokens) || params.preTokens < 0)
|
|
760
|
+
throw new Error('Invalid DSH compaction tokens');
|
|
761
|
+
run.queue.push({ type: 'compact', preTokens: params.preTokens, durationMs: params.durationMs });
|
|
762
|
+
}
|
|
763
|
+
else if (method === 'compaction_status') {
|
|
764
|
+
if (!['started', 'completed', 'failed'].includes(params.state))
|
|
765
|
+
throw new Error('Invalid DSH compaction state');
|
|
766
|
+
run.queue.push({ type: 'status', subtype: `compaction_${params.state}`, message: `DSH compaction ${params.state}` });
|
|
767
|
+
}
|
|
768
|
+
else if (method === 'compaction_warning') {
|
|
769
|
+
logger.warn(`[DshRunner] Pre-turn compaction failed: session=${run.identity.sessionId}`);
|
|
770
|
+
}
|
|
771
|
+
else if (method === 'tool_use') {
|
|
772
|
+
run.toolNames.set(params.callId, params.name);
|
|
773
|
+
run.queue.push({ type: 'tool_use', name: params.name, input: params.input, callId: params.callId });
|
|
774
|
+
}
|
|
775
|
+
else if (method === 'tool_result') {
|
|
776
|
+
if (!run.toolNames.has(params.callId))
|
|
777
|
+
throw new Error('DSH tool result has no call');
|
|
778
|
+
run.toolNames.delete(params.callId);
|
|
779
|
+
run.queue.push({ type: 'tool_result', name: params.name, callId: params.callId, result: params.result,
|
|
780
|
+
isError: params.isError === true, executed: params.executed === true,
|
|
781
|
+
...(Number.isInteger(params.exitCode) ? { exitCode: params.exitCode } : {}),
|
|
782
|
+
...(typeof params.errorCode === 'string' ? { errorCode: params.errorCode } : {}), cancelled: params.cancelled === true,
|
|
783
|
+
executionState: params.cancelled ? 'interrupted' : params.blocked ? 'blocked' : params.isError ? 'failed' : 'completed',
|
|
784
|
+
policyCode: params.policyCode,
|
|
785
|
+
...(typeof params.requestId === 'string' ? { requestId: params.requestId, approvalRequestId: params.requestId,
|
|
786
|
+
decisionSource: params.decisionSource, errorDetailCode: params.errorDetailCode } : {}) });
|
|
787
|
+
}
|
|
788
|
+
else
|
|
789
|
+
throw new Error(`Unsupported DSH event: ${method}`);
|
|
790
|
+
}
|
|
791
|
+
validateUsage(value) {
|
|
792
|
+
if (!object(value))
|
|
793
|
+
throw new Error('Invalid DSH token usage');
|
|
794
|
+
const result = {};
|
|
795
|
+
for (const key of ['input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens',
|
|
796
|
+
'reasoning_tokens', 'total_tokens']) {
|
|
797
|
+
if (value[key] === undefined)
|
|
798
|
+
continue;
|
|
799
|
+
if (!Number.isSafeInteger(value[key]) || value[key] < 0)
|
|
800
|
+
throw new Error('Invalid DSH token count');
|
|
801
|
+
result[key] = value[key];
|
|
802
|
+
}
|
|
803
|
+
if (result.input_tokens === undefined || result.output_tokens === undefined)
|
|
804
|
+
throw new Error('Incomplete DSH token usage');
|
|
805
|
+
if (value.iterations !== undefined) {
|
|
806
|
+
if (!Array.isArray(value.iterations) || value.iterations.length > 4096)
|
|
807
|
+
throw new Error('Invalid DSH usage iterations');
|
|
808
|
+
result.iterations = value.iterations.map(item => this.validateUsage(item));
|
|
809
|
+
}
|
|
810
|
+
return result;
|
|
811
|
+
}
|
|
812
|
+
async preflight(run, params) {
|
|
813
|
+
this.checkIdentity(run, params);
|
|
814
|
+
if (!object(params.input) || typeof params.hash !== 'string' || typeof params.callId !== 'string')
|
|
815
|
+
throw new Error('Invalid tool preflight');
|
|
816
|
+
const hash = createHash('sha256').update(JSON.stringify({ name: params.name, input: params.input })).digest('hex');
|
|
817
|
+
if (params.hash !== hash)
|
|
818
|
+
throw new Error('DSH tool arguments hash mismatch');
|
|
819
|
+
const deny = (reason, policyCode = 'dsh_host_denied') => {
|
|
820
|
+
auditToolPreflightDenial({ toolName: params.name, policyCode, reason, sessionId: run.identity.sessionId,
|
|
821
|
+
taskId: run.identity.taskId, callId: params.callId, selfAid: this.host.aid, agentAid: this.host.aid,
|
|
822
|
+
permissionMode: run.mode, channel: run.permission.channel, actorId: run.permission.userId, role: run.permission.role,
|
|
823
|
+
summary: `DSH tool=${String(params.name).slice(0, 64)}` });
|
|
824
|
+
return { allow: false, input: params.input, hash, reason, policyCode };
|
|
825
|
+
};
|
|
826
|
+
if (run.abort.signal.aborted)
|
|
827
|
+
return deny('Task cancelled');
|
|
828
|
+
await this.revalidate(run);
|
|
829
|
+
const pause = run.permission.pauseController;
|
|
830
|
+
if (pause?.isPauseRequested() || pause?.isPaused())
|
|
831
|
+
run.queue.push({ type: 'state_changed', state: 'requires_action' });
|
|
832
|
+
const pauseResult = await pause?.waitAtToolBoundary(run.abort.signal);
|
|
833
|
+
if (pauseResult === 'cancelled')
|
|
834
|
+
return deny('Tool boundary pause cancelled');
|
|
835
|
+
if (pauseResult === 'released')
|
|
836
|
+
run.queue.push({ type: 'state_changed', state: 'running' });
|
|
837
|
+
if (run.abort.signal.aborted)
|
|
838
|
+
return deny('Task cancelled');
|
|
839
|
+
await this.revalidate(run);
|
|
840
|
+
if (params.name === 'skill') {
|
|
841
|
+
if (run.nativeLaunch) {
|
|
842
|
+
const effective = resolveEffective({ self: this.host.aid }, { cache: true });
|
|
843
|
+
return effective.baseagentSkills === true && !run.permission.systemSessionCheck
|
|
844
|
+
&& typeof params.input.name === 'string'
|
|
845
|
+
&& resolveCapabilityEnabled(effective.capabilities?.dsh?.skill, params.input.name) !== false
|
|
846
|
+
? { allow: true, input: params.input, hash } : deny('Native skill is disabled by current Host policy', 'dsh_skill_disabled');
|
|
847
|
+
}
|
|
848
|
+
return deny('Native launch is required', 'dsh_native_launch_required');
|
|
849
|
+
}
|
|
850
|
+
if (params.name === 'ask_user_question') {
|
|
851
|
+
return { allow: true, input: params.input, hash };
|
|
852
|
+
}
|
|
853
|
+
if (run.nativeLaunch && params.nativeMcp === true
|
|
854
|
+
&& (typeof params.name === 'string' && params.name.startsWith('mcp__')
|
|
855
|
+
|| ['list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource'].includes(params.name))) {
|
|
856
|
+
const context = run.permission;
|
|
857
|
+
const system = context.systemSessionCheck?.(params.name, params.input);
|
|
858
|
+
if (system && !system.allow)
|
|
859
|
+
return deny(system.reason, system.code);
|
|
860
|
+
const policy = context.policyHook?.(params.name, params.input);
|
|
861
|
+
if (policy?.block)
|
|
862
|
+
return deny(policy.reason ?? 'Host policy denied', policy.policyCode);
|
|
863
|
+
const before = context.preToolUsePolicyHook?.(params.name, params.input);
|
|
864
|
+
if (before?.block)
|
|
865
|
+
return deny(before.reason ?? 'Host policy denied', before.policyCode);
|
|
866
|
+
if (run.mode === 'readonly')
|
|
867
|
+
return deny('Readonly mode does not allow external MCP execution', 'readonly_mcp');
|
|
868
|
+
let approval;
|
|
869
|
+
if (run.mode === 'request') {
|
|
870
|
+
const sendPrompt = context.sendPrompt ?? this.sendPrompt;
|
|
871
|
+
if (!this.gateway || !sendPrompt)
|
|
872
|
+
return deny('MCP approval channel is unavailable');
|
|
873
|
+
approval = await this.gateway.requestPermissionResult(run.identity.sessionId, params.name, params.input, sendPrompt, { ...context, selfAid: this.host.aid, taskId: run.identity.taskId,
|
|
874
|
+
permissionMode: run.mode, abortSignal: run.abort.signal }, `DSH MCP: ${params.name}`, '执行已授权原生 MCP 的工具调用');
|
|
875
|
+
if (approval.decision !== 'allow')
|
|
876
|
+
return { ...deny(approval.reason ?? 'MCP approval denied', approval.policyCode ?? 'dsh_mcp_denied'),
|
|
877
|
+
requestId: approval.requestId, decisionSource: approval.decisionSource, errorDetailCode: approval.errorDetailCode };
|
|
878
|
+
}
|
|
879
|
+
await this.revalidate(run);
|
|
880
|
+
return { allow: true, input: params.input, hash, ...(approval ? { requestId: approval.requestId,
|
|
881
|
+
decisionSource: approval.decisionSource, errorDetailCode: approval.errorDetailCode } : {}) };
|
|
882
|
+
}
|
|
883
|
+
// Native image reads use the same file-path policy as text reads. The native
|
|
884
|
+
// tool retains responsibility for model modality, decoding and image limits.
|
|
885
|
+
const names = { read: 'Read', read_image: 'Read', write: 'Write', edit: 'Edit', bash: 'Bash', pwsh: 'Bash',
|
|
886
|
+
web_search: 'WebSearch', web_fetch: 'WebFetch' };
|
|
887
|
+
const name = names[params.name];
|
|
888
|
+
if (!name || (params.name === 'pwsh') !== (process.platform === 'win32') && name === 'Bash')
|
|
889
|
+
return deny('Tool is not enabled');
|
|
890
|
+
if (params.input.run_in_background || params.input.sandbox_mode || params.input.sandboxMode
|
|
891
|
+
|| params.input.sandbox_permissions || params.input.dangerouslyDisableSandbox)
|
|
892
|
+
return deny('Detached execution and native escalation are disabled');
|
|
893
|
+
const cwd = typeof params.input.workdir === 'string' ? path.resolve(run.projectPath, params.input.workdir) : run.projectPath;
|
|
894
|
+
const input = { ...params.input };
|
|
895
|
+
if (typeof input.file_path === 'string')
|
|
896
|
+
input.file_path = path.resolve(run.projectPath, input.file_path);
|
|
897
|
+
if (params.name === 'pwsh') {
|
|
898
|
+
// Use the same verified PowerShell carrier parser as existing Windows runners.
|
|
899
|
+
const { requireTrustedWindowsShellExecutable } = await import('../../utils/windows-shell-trust.js');
|
|
900
|
+
if (typeof params.pwshPath !== 'string' || !path.isAbsolute(params.pwshPath))
|
|
901
|
+
return deny('DSH PowerShell path is unavailable');
|
|
902
|
+
input.commandArgv = [requireTrustedWindowsShellExecutable(params.pwshPath, 'powershell'), '-NoProfile', '-NonInteractive', '-Command', input.command];
|
|
903
|
+
}
|
|
904
|
+
const context = run.permission;
|
|
905
|
+
const system = context.systemSessionCheck?.(name, input);
|
|
906
|
+
if (system && !system.allow)
|
|
907
|
+
return deny(system.reason, system.code);
|
|
908
|
+
if (run.mode === 'fullaccess') {
|
|
909
|
+
await this.revalidate(run);
|
|
910
|
+
if (run.abort.signal.aborted)
|
|
911
|
+
return deny('Task cancelled');
|
|
912
|
+
delete input.commandArgv;
|
|
913
|
+
return { allow: true, input, hash };
|
|
914
|
+
}
|
|
915
|
+
const policy = context.policyHook?.(name, input);
|
|
916
|
+
if (policy?.block)
|
|
917
|
+
return deny(policy.reason ?? 'Host policy denied', policy.policyCode);
|
|
918
|
+
const beforeTool = context.preToolUsePolicyHook?.(name, input);
|
|
919
|
+
if (beforeTool?.block)
|
|
920
|
+
return deny(beforeTool.reason ?? 'Host policy denied', beforeTool.policyCode);
|
|
921
|
+
const checked = evaluateToolPreflight(name, input, { sessionId: run.identity.sessionId, managedTempDir: context.managedTempDir,
|
|
922
|
+
selfAid: this.host.aid, channel: context.channel, userId: context.userId, role: context.role,
|
|
923
|
+
projectPath: cwd, workspacePath: run.projectPath, permissionMode: run.mode, allowProtectedMetadata: false });
|
|
924
|
+
if (checked.behavior === 'deny')
|
|
925
|
+
return deny(checked.message, checked.policyCode);
|
|
926
|
+
let approval;
|
|
927
|
+
if (!system && checked.behavior !== 'allow') {
|
|
928
|
+
if (run.mode === 'readonly') {
|
|
929
|
+
const readonly = checkReadonly(name, checked.input, run.projectPath, { sessionId: run.identity.sessionId,
|
|
930
|
+
managedTempDir: context.managedTempDir, grantedReadRoots: context.grantedReadRoots, selfAid: this.host.aid,
|
|
931
|
+
channel: context.channel, peerId: context.userId, role: context.role });
|
|
932
|
+
if (readonly.behavior === 'deny')
|
|
933
|
+
return deny(readonly.message, readonly.policyCode);
|
|
934
|
+
}
|
|
935
|
+
else {
|
|
936
|
+
const danger = checkDangerousCommand(name, checked.input);
|
|
937
|
+
if (run.mode === 'auto' && danger.isDangerous)
|
|
938
|
+
return deny(`auto mode: ${danger.reason}`);
|
|
939
|
+
if (run.mode === 'request' || run.mode === 'bypass') {
|
|
940
|
+
const decision = await requestDangerousCommandPermissionResult(this.gateway, run.identity.sessionId, name, checked.input, context.sendPrompt ?? this.sendPrompt, { ...context, selfAid: this.host.aid, taskId: run.identity.taskId,
|
|
941
|
+
permissionMode: run.mode, abortSignal: run.abort.signal }, 'dsh', run.mode);
|
|
942
|
+
if (decision.matched)
|
|
943
|
+
approval = decision.result;
|
|
944
|
+
if (decision.matched && decision.result.decision === 'deny') {
|
|
945
|
+
return { ...deny(decision.result.reason ?? 'Approval denied', decision.result.policyCode ?? 'dsh_approval_denied'),
|
|
946
|
+
requestId: decision.result.requestId, decisionSource: decision.result.decisionSource,
|
|
947
|
+
errorDetailCode: decision.result.errorDetailCode };
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
await this.revalidate(run);
|
|
953
|
+
if (run.abort.signal.aborted)
|
|
954
|
+
return deny('Task cancelled');
|
|
955
|
+
const updated = { ...params.input, ...checked.input };
|
|
956
|
+
delete updated.commandArgv;
|
|
957
|
+
return { allow: true, input: updated, hash, managedCommand: checked.behavior === 'allow' && checked.reason === 'ec-command',
|
|
958
|
+
...(approval ? { requestId: approval.requestId, decisionSource: approval.decisionSource,
|
|
959
|
+
errorDetailCode: approval.errorDetailCode } : {}) };
|
|
960
|
+
}
|
|
961
|
+
bounded(promise, label) {
|
|
962
|
+
return withInterruptDeadline(promise, label, Number(this.host.config.startupTimeoutMs ?? 30000));
|
|
963
|
+
}
|
|
964
|
+
async revalidate(run) {
|
|
965
|
+
const context = run.permission;
|
|
966
|
+
const assertCurrent = () => {
|
|
967
|
+
run.abort.signal.throwIfAborted();
|
|
968
|
+
if (this.permissions.get(run.identity.sessionId) !== context)
|
|
969
|
+
throw new Error('DSH Host task context was replaced');
|
|
970
|
+
if ((context.taskId && context.taskId !== run.identity.taskId)
|
|
971
|
+
|| (context.turn && (context.turn.sessionId !== run.identity.sessionId || context.turn.turnId !== run.identity.turnId
|
|
972
|
+
|| context.turn.taskId !== run.identity.taskId || context.turn.generation !== run.identity.generation))) {
|
|
973
|
+
throw new Error('DSH Host task identity changed');
|
|
974
|
+
}
|
|
975
|
+
if (run.mode === 'fullaccess' && (!hasTrustedFullAccessContext(context)
|
|
976
|
+
|| !context.turn || !context.revalidateExecutionIdentity || context.systemSessionCheck
|
|
977
|
+
|| JSON.stringify(context.executionPermission) !== run.fullAccessAuthorization)) {
|
|
978
|
+
throw new Error('DSH Host fullaccess authorization changed or expired');
|
|
979
|
+
}
|
|
980
|
+
};
|
|
981
|
+
assertCurrent();
|
|
982
|
+
if (run.nativeLaunch)
|
|
983
|
+
await revalidateDshNativeLaunch(run.nativeLaunch);
|
|
984
|
+
if (run.nativeLaunch && (run.nativeSessionBindingRevision || run.nativeLaunch.binding.nativeSessionId !== null)) {
|
|
985
|
+
const session = await new DshNativeResourceRegistry().sessionForTask(this.host.aid, run.identity.sessionId);
|
|
986
|
+
if (session.nativeResourceId !== run.nativeLaunch.binding.nativeResourceId
|
|
987
|
+
|| session.nativeSessionId !== (run.nativeId ?? run.nativeLaunch.binding.nativeSessionId)
|
|
988
|
+
|| session.revision !== run.nativeSessionBindingRevision
|
|
989
|
+
|| session.projectPath !== run.nativeLaunch.binding.projectPath)
|
|
990
|
+
throw new Error('DSH_SESSION_BINDING_MISMATCH');
|
|
991
|
+
assertCurrent();
|
|
992
|
+
}
|
|
993
|
+
// Channel executions carry the authenticated actor; direct Host test harnesses supply only their own validator.
|
|
994
|
+
if (context.actor)
|
|
995
|
+
await assertOwnershipAuthorization(context);
|
|
996
|
+
else
|
|
997
|
+
await context.revalidateExecutionIdentity?.();
|
|
998
|
+
assertCurrent();
|
|
999
|
+
if (run.nativeModel) {
|
|
1000
|
+
const policy = getRoleModelPermission(context.role, this.name, this.host.aid);
|
|
1001
|
+
if (!isModelAllowedForRoleBaseagent(context.role, this.name, run.nativeModel, undefined, this.host.aid)
|
|
1002
|
+
|| (policy.constrained && !policy.allowOverride && policy.defaultModel !== undefined
|
|
1003
|
+
&& policy.defaultModel !== run.nativeModel))
|
|
1004
|
+
throw new Error('DSH_NATIVE_MODEL_NOT_ALLOWED');
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
async terminate(run) {
|
|
1008
|
+
const child = run.process;
|
|
1009
|
+
if (!child) {
|
|
1010
|
+
run.stopped = true;
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (run.stopped)
|
|
1014
|
+
return;
|
|
1015
|
+
if (run.opened && run.request) {
|
|
1016
|
+
try {
|
|
1017
|
+
await withInterruptDeadline(run.request('run/cancel', { identity: run.identity }), 'DSH cancel', 2000);
|
|
1018
|
+
}
|
|
1019
|
+
catch { /* The owned process range still needs termination. */ }
|
|
1020
|
+
}
|
|
1021
|
+
child.stdin.end();
|
|
1022
|
+
try {
|
|
1023
|
+
await withInterruptDeadline(run.exit, 'DSH EOF', 2000);
|
|
1024
|
+
}
|
|
1025
|
+
catch {
|
|
1026
|
+
if (child.pid)
|
|
1027
|
+
killProcessTree(child.pid, true);
|
|
1028
|
+
await withInterruptDeadline(run.exit, 'DSH process termination', 5000);
|
|
1029
|
+
}
|
|
1030
|
+
run.stopped = true;
|
|
1031
|
+
}
|
|
1032
|
+
async interrupt(sessionId, target) {
|
|
1033
|
+
const run = this.executions.get(sessionId);
|
|
1034
|
+
if (!run || !this.matches(run, target))
|
|
1035
|
+
return { closed: true };
|
|
1036
|
+
run.abort.abort(new Error('DSH task interrupted'));
|
|
1037
|
+
this.gateway?.cancelAll(sessionId, 'interrupted');
|
|
1038
|
+
try {
|
|
1039
|
+
await withInterruptDeadline(this.terminate(run), 'DSH interrupt', Number(this.host.config.interruptTimeoutMs ?? 10000));
|
|
1040
|
+
await withInterruptDeadline(run.done, 'DSH writer drain', 5000);
|
|
1041
|
+
}
|
|
1042
|
+
catch (error) {
|
|
1043
|
+
throw unsettledInterruptError(this.name, error);
|
|
1044
|
+
}
|
|
1045
|
+
return { closed: run.stopped, ...(run.accepted ? {} : { cancelledInputIds: [run.identity.inputId] }) };
|
|
1046
|
+
}
|
|
1047
|
+
async closeSession(sessionId) {
|
|
1048
|
+
await this.interrupt(sessionId);
|
|
1049
|
+
this.permissions.delete(sessionId);
|
|
1050
|
+
this.streams.delete(sessionId);
|
|
1051
|
+
}
|
|
1052
|
+
async compactSession(sessionId, nativeId, projectPath, override = {}) {
|
|
1053
|
+
const started = Date.now();
|
|
1054
|
+
// Compaction is a separate idle maintenance operation; it cannot inherit a retired task's tool authority.
|
|
1055
|
+
const run = this.start(sessionId, projectPath, override, true);
|
|
1056
|
+
const permission = this.permissions.get(sessionId);
|
|
1057
|
+
run.done = this.execute(run, '', undefined, nativeId, { ...override, recovery: { agentSessionId: nativeId } }, { TMPDIR: permission?.managedTempDir ?? '' });
|
|
1058
|
+
await run.done;
|
|
1059
|
+
if (run.failure)
|
|
1060
|
+
return { ok: false, code: run.abort.signal.aborted ? 'aborted' : 'sdk_error', message: run.failure.message, durationMs: Date.now() - started };
|
|
1061
|
+
const result = run.result;
|
|
1062
|
+
if (!result || (result.changed && !(Number.isInteger(result.startSeq) && Number.isInteger(result.summarySeq)
|
|
1063
|
+
&& Number.isInteger(result.endSeq) && result.startSeq < result.summarySeq && result.summarySeq < result.endSeq))) {
|
|
1064
|
+
return { ok: false, code: 'missing_boundary', message: 'DSH compaction completion evidence is missing', durationMs: Date.now() - started };
|
|
1065
|
+
}
|
|
1066
|
+
return { ok: true, durationMs: Date.now() - started, eventCount: result.changed ? 3 : 0,
|
|
1067
|
+
...(Number.isSafeInteger(result.shadowedTokenCount) ? { preTokens: result.shadowedTokenCount } : {}) };
|
|
1068
|
+
}
|
|
1069
|
+
compact(...args) { return this.compactSession(...args); }
|
|
1070
|
+
injectUserMessage(sessionId, text) {
|
|
1071
|
+
const run = this.executions.get(sessionId);
|
|
1072
|
+
// Native flush/input receipt can trail an already-running tool boundary.
|
|
1073
|
+
if (!run?.request || !run.opened || run.compact || run.abort.signal.aborted || run.stopped || !text.trim())
|
|
1074
|
+
return;
|
|
1075
|
+
run.injections = run.injections.then(async () => {
|
|
1076
|
+
await this.revalidate(run);
|
|
1077
|
+
await this.bounded(run.request('run/inject', { identity: run.identity, text }), 'DSH correction injection');
|
|
1078
|
+
});
|
|
1079
|
+
void run.injections.catch(error => {
|
|
1080
|
+
run.failure = new Error(errorText(error));
|
|
1081
|
+
void this.terminate(run).catch(() => { });
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
async steerAsyncQuestionAnswer(sessionId, answer) {
|
|
1085
|
+
const run = this.executions.get(sessionId);
|
|
1086
|
+
if (!run || run.stopped || run.abort.signal.aborted || !run.question)
|
|
1087
|
+
return 'inactive';
|
|
1088
|
+
if (answer.providerThreadId !== run.nativeId || answer.questionItemId !== run.question.itemId
|
|
1089
|
+
|| !run.question.questions.some(question => question.title === answer.question)
|
|
1090
|
+
|| run.question.answers.has(answer.requestId))
|
|
1091
|
+
throw new Error('DSH question answer is stale or belongs to another request');
|
|
1092
|
+
await this.revalidate(run);
|
|
1093
|
+
const result = await this.bounded(run.request('question/answer', { identity: run.identity, answer }), 'DSH question answer');
|
|
1094
|
+
if (result?.accepted !== true)
|
|
1095
|
+
throw new Error('DSH question answer was not accepted');
|
|
1096
|
+
run.question.answers.add(answer.requestId);
|
|
1097
|
+
if (run.question.answers.size === run.question.questions.length)
|
|
1098
|
+
run.question = undefined;
|
|
1099
|
+
return 'accepted';
|
|
1100
|
+
}
|
|
1101
|
+
/** Read the registered native session through DSH's persistence API. */
|
|
1102
|
+
async historyOperation(nativeId, projectPath) {
|
|
1103
|
+
if (this.disposed || this.host.signal.aborted)
|
|
1104
|
+
throw new Error('DSH runner disposed');
|
|
1105
|
+
const events = await readDshNativeHistory(this.host.aid, nativeId, projectPath, this.host.signal);
|
|
1106
|
+
if (!events)
|
|
1107
|
+
throw new Error('DSH_SESSION_NOT_BOUND');
|
|
1108
|
+
return events;
|
|
1109
|
+
}
|
|
1110
|
+
async getSessionMessages(nativeId, projectPath) {
|
|
1111
|
+
const events = await this.historyOperation(nativeId, projectPath);
|
|
1112
|
+
return events.flatMap(event => {
|
|
1113
|
+
const data = event.data;
|
|
1114
|
+
const type = event.type === 'user/message' || event.type === 'tool/result' ? 'user'
|
|
1115
|
+
: event.type === 'assistant/message' ? 'assistant' : ['system/message', 'developer/message'].includes(event.type) ? 'system' : undefined;
|
|
1116
|
+
if (!type)
|
|
1117
|
+
return [];
|
|
1118
|
+
const native = event.type === 'user/message' ? data : data.message;
|
|
1119
|
+
const content = event.type === 'tool/result' ? [{ type: 'tool_result', tool_use_id: native.toolCallId,
|
|
1120
|
+
content: native.content, is_error: native.isError === true }]
|
|
1121
|
+
: native.content.map((block) => {
|
|
1122
|
+
if (block.type !== 'tool-call')
|
|
1123
|
+
return block;
|
|
1124
|
+
let input;
|
|
1125
|
+
try {
|
|
1126
|
+
input = JSON.parse(block.arguments);
|
|
1127
|
+
}
|
|
1128
|
+
catch {
|
|
1129
|
+
input = block.arguments;
|
|
1130
|
+
}
|
|
1131
|
+
return { type: 'tool_use', id: block.id, name: block.name, input };
|
|
1132
|
+
});
|
|
1133
|
+
return [{ type, uuid: `dsh-${event.seq}`, session_id: nativeId,
|
|
1134
|
+
message: { ...native, role: type, content }, parent_tool_use_id: null }];
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
async forkSession(nativeId, projectPath, _title, context) {
|
|
1138
|
+
return this.prepareFork(nativeId, projectPath, context);
|
|
1139
|
+
}
|
|
1140
|
+
async forkSessionAt(nativeId, projectPath, messageId, _title, context) {
|
|
1141
|
+
if (!/^dsh-\d+$/.test(messageId))
|
|
1142
|
+
throw new Error('DSH_FORK_ANCHOR_INVALID');
|
|
1143
|
+
return this.prepareFork(nativeId, projectPath, context, messageId);
|
|
1144
|
+
}
|
|
1145
|
+
async prepareFork(source, projectPath, context, anchor) {
|
|
1146
|
+
if (!context?.authorization || this.disposed || this.executions.has(context.sessionId))
|
|
1147
|
+
throw new Error('DSH_FORK_UNAVAILABLE');
|
|
1148
|
+
const registry = new DshNativeResourceRegistry();
|
|
1149
|
+
const binding = await registry.assertForkSource(this.host.aid, source, projectPath, context.sessionId, context.authorization);
|
|
1150
|
+
for (const [id, pending] of this.pendingForks)
|
|
1151
|
+
if (pending.expiresAt <= Date.now())
|
|
1152
|
+
this.pendingForks.delete(id);
|
|
1153
|
+
if (this.pendingForks.size >= 64)
|
|
1154
|
+
throw new Error('DSH_FORK_LIMIT');
|
|
1155
|
+
const id = randomUUID();
|
|
1156
|
+
this.pendingForks.set(id, { source, sourceRevision: binding.revision, projectPath, context, anchor, expiresAt: Date.now() + 300_000 });
|
|
1157
|
+
return id;
|
|
1158
|
+
}
|
|
1159
|
+
async commitSessionFork(nativeId, target, context) {
|
|
1160
|
+
const pending = this.pendingForks.get(nativeId);
|
|
1161
|
+
this.pendingForks.delete(nativeId);
|
|
1162
|
+
if (!pending || pending.expiresAt <= Date.now() || context.sessionId !== pending.context.sessionId
|
|
1163
|
+
|| !context.authorization || context.authorization.principalId !== pending.context.authorization?.principalId
|
|
1164
|
+
|| context.authorization.actorId !== pending.context.authorization?.actorId)
|
|
1165
|
+
throw new Error('DSH_FORK_RECEIPT_INVALID');
|
|
1166
|
+
const registry = new DshNativeResourceRegistry();
|
|
1167
|
+
const current = await registry.assertForkSource(this.host.aid, pending.source, pending.projectPath, context.sessionId, context.authorization);
|
|
1168
|
+
if (current.revision !== pending.sourceRevision)
|
|
1169
|
+
throw new Error('DSH_SESSION_CHANGED');
|
|
1170
|
+
await registry.commitFork(this.host.aid, pending.source, pending.projectPath, context.sessionId, context.authorization, target, nativeId, pending.anchor, this.host.signal);
|
|
1171
|
+
}
|
|
1172
|
+
async dispose() {
|
|
1173
|
+
this.disposed = true;
|
|
1174
|
+
const results = await Promise.allSettled([...this.executions.keys()].map(key => this.interrupt(key)));
|
|
1175
|
+
const errors = results.filter(result => result.status === 'rejected');
|
|
1176
|
+
if (errors.length)
|
|
1177
|
+
throw new AggregateError(errors.map(result => result.reason), 'DSH disposal did not settle every execution');
|
|
1178
|
+
this.permissions.clear();
|
|
1179
|
+
this.streams.clear();
|
|
1180
|
+
this.bindings.clear();
|
|
1181
|
+
this.pendingForks.clear();
|
|
1182
|
+
}
|
|
1183
|
+
}
|