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,837 @@
|
|
|
1
|
+
/** Task bridge for the registered native DSH Home and Profile. */
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
7
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
|
+
import { dshAuthorizationFailure } from './authorization.js';
|
|
9
|
+
import { filterNativeSkills, nativeSkillPolicy, nativeToolSupported } from './tool-policy.js';
|
|
10
|
+
import { SELF_AID_ENV } from '../../../product.js';
|
|
11
|
+
export const NATIVE_SHARED_PROTOCOL = 'evolcore-dsh/2';
|
|
12
|
+
function protocolRecord(value) {
|
|
13
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
14
|
+
}
|
|
15
|
+
function protocolText(value, label) {
|
|
16
|
+
if (typeof value !== 'string' || !value.length || value.length > 256 || /[\x00-\x1f]/.test(value)) {
|
|
17
|
+
throw new Error(`DSH_SHARED_BINDING_INVALID: ${label}`);
|
|
18
|
+
}
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
function protocolProject(value) {
|
|
22
|
+
if (typeof value !== 'string' || !path.isAbsolute(value))
|
|
23
|
+
throw new Error('DSH_SHARED_BINDING_INVALID: projectPath');
|
|
24
|
+
const canonical = realpathSync(value);
|
|
25
|
+
return process.platform === 'win32' ? canonical.toLowerCase() : canonical;
|
|
26
|
+
}
|
|
27
|
+
export function sharedTaskIdentity(value) {
|
|
28
|
+
if (!protocolRecord(value) || !Number.isSafeInteger(value.generation) || value.generation < 0) {
|
|
29
|
+
throw new Error('DSH_SHARED_BINDING_INVALID: task identity');
|
|
30
|
+
}
|
|
31
|
+
return Object.freeze({ sessionId: protocolText(value.sessionId, 'sessionId'), taskId: protocolText(value.taskId, 'taskId'),
|
|
32
|
+
turnId: protocolText(value.turnId, 'turnId'), generation: value.generation, inputId: protocolText(value.inputId, 'inputId') });
|
|
33
|
+
}
|
|
34
|
+
export function validateNativeSharedTask(value, projectPath) {
|
|
35
|
+
if (!protocolRecord(value) || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(value.launchId)
|
|
36
|
+
|| !/^dsh-install-[a-f0-9]{64}$/.test(value.installationId)
|
|
37
|
+
|| !/^dsh-resource-[a-f0-9]{64}$/.test(value.nativeResourceId)
|
|
38
|
+
|| !/^[a-f0-9]{64}$/.test(value.installationRevision) || !/^[a-f0-9]{64}$/.test(value.resourceRevision)
|
|
39
|
+
|| !['run', 'compact', 'history'].includes(value.operation)) {
|
|
40
|
+
throw new Error('DSH_SHARED_BINDING_INVALID: launch or resource identity');
|
|
41
|
+
}
|
|
42
|
+
const project = protocolProject(value.projectPath);
|
|
43
|
+
if (project !== protocolProject(projectPath))
|
|
44
|
+
throw new Error('DSH_SHARED_BINDING_INVALID: project mismatch');
|
|
45
|
+
const validSession = value.nativeSessionId === null ? value.operation === 'run'
|
|
46
|
+
: typeof value.nativeSessionId === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,255}$/.test(value.nativeSessionId);
|
|
47
|
+
if (!validSession)
|
|
48
|
+
throw new Error('DSH_SHARED_BINDING_INVALID: nativeSessionId');
|
|
49
|
+
return Object.freeze({ launchId: value.launchId, installationId: value.installationId,
|
|
50
|
+
installationRevision: value.installationRevision, nativeResourceId: value.nativeResourceId,
|
|
51
|
+
resourceRevision: value.resourceRevision, projectPath: project, operation: value.operation,
|
|
52
|
+
nativeSessionId: value.nativeSessionId, identity: sharedTaskIdentity(value.identity) });
|
|
53
|
+
}
|
|
54
|
+
export function assertSharedTaskRequest(binding, method, params) {
|
|
55
|
+
if (!protocolRecord(params))
|
|
56
|
+
throw new Error('DSH_SHARED_BINDING_MISMATCH: invalid request');
|
|
57
|
+
if (method === 'initialize') {
|
|
58
|
+
if (params.protocol !== NATIVE_SHARED_PROTOCOL
|
|
59
|
+
|| JSON.stringify(validateNativeSharedTask(params.binding, binding.projectPath)) !== JSON.stringify(binding)) {
|
|
60
|
+
throw new Error('DSH_SHARED_BINDING_MISMATCH: handshake');
|
|
61
|
+
}
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (JSON.stringify(sharedTaskIdentity(params.identity)) !== JSON.stringify(binding.identity)) {
|
|
65
|
+
throw new Error('DSH_SHARED_BINDING_MISMATCH: task identity');
|
|
66
|
+
}
|
|
67
|
+
if (['session/open', 'history/open'].includes(method)) {
|
|
68
|
+
if (params.nativeSessionId !== binding.nativeSessionId || protocolProject(params.cwd) !== binding.projectPath) {
|
|
69
|
+
throw new Error('DSH_SHARED_BINDING_MISMATCH: session or project');
|
|
70
|
+
}
|
|
71
|
+
if (method === 'history/open' && binding.nativeSessionId === null)
|
|
72
|
+
throw new Error('DSH_SHARED_BINDING_MISMATCH: unbound history');
|
|
73
|
+
}
|
|
74
|
+
if (method === 'history/fork')
|
|
75
|
+
throw new Error('DSH_SHARED_OPERATION_UNAVAILABLE: fork binding is not implemented');
|
|
76
|
+
const allowed = { run: ['session/open', 'run/start', 'run/inject', 'run/cancel', 'question/answer'],
|
|
77
|
+
compact: ['session/open', 'session/compact', 'run/cancel'], history: ['history/open', 'history/read'] };
|
|
78
|
+
if (method !== 'session/close' && !allowed[binding.operation].includes(method)) {
|
|
79
|
+
throw new Error('DSH_SHARED_OPERATION_UNAVAILABLE: method is outside this task operation');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const inject = ['agents', 'sessions', 'systemPrompt', 'tools', 'workingDirectory',
|
|
83
|
+
'sessionPersistence', 'llm', 'subprocess', 'sandbox', 'sandboxPolicy', 'tokenMeter', 'attachments', 'userQuestions', 'skills',
|
|
84
|
+
'agentPresets', 'agentDefaultModel'];
|
|
85
|
+
const VERSION = '0.2.2-rc.5';
|
|
86
|
+
const MAX_TEXT = 4 * 1024 * 1024;
|
|
87
|
+
function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
|
|
88
|
+
function required(value, label) {
|
|
89
|
+
if (typeof value !== 'string' || !value.length)
|
|
90
|
+
throw new Error(`Invalid ${label}`);
|
|
91
|
+
return value;
|
|
92
|
+
}
|
|
93
|
+
function digest(value) { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); }
|
|
94
|
+
function keepsNativeRegistration(name) {
|
|
95
|
+
return name === 'skill' || name === 'web_search' || name === 'web_fetch';
|
|
96
|
+
}
|
|
97
|
+
function identity(value) {
|
|
98
|
+
if (!record(value) || !Number.isSafeInteger(value.generation) || value.generation < 0)
|
|
99
|
+
throw new Error('Invalid run identity');
|
|
100
|
+
return Object.freeze({ sessionId: required(value.sessionId, 'sessionId'), taskId: required(value.taskId, 'taskId'),
|
|
101
|
+
turnId: required(value.turnId, 'turnId'), generation: value.generation, inputId: required(value.inputId, 'inputId') });
|
|
102
|
+
}
|
|
103
|
+
export function createNativeSharedTaskBridge(binding, attachGuard, readiness) {
|
|
104
|
+
return { name: 'evolcore-dsh-native-shared',
|
|
105
|
+
inject,
|
|
106
|
+
apply: (ctx) => applyTaskBridge(ctx, { binding, attachGuard, readiness }) };
|
|
107
|
+
}
|
|
108
|
+
async function applyTaskBridge(ctx, shared) {
|
|
109
|
+
const PROTOCOL = NATIVE_SHARED_PROTOCOL;
|
|
110
|
+
const packagePath = required(process.env.DSH_PACKAGE_PATH, 'DSH_PACKAGE_PATH');
|
|
111
|
+
const requireDsh = createRequire(packagePath);
|
|
112
|
+
const load = (specifier) => import(pathToFileURL(requireDsh.resolve(specifier)).href);
|
|
113
|
+
const manifest = JSON.parse(readFileSync(packagePath, 'utf8'));
|
|
114
|
+
if (manifest.name !== '@deepseek-ai/dsh' || manifest.version !== VERSION)
|
|
115
|
+
throw new Error('Unsupported DSH package version');
|
|
116
|
+
const [{ JsonRpcLineTransport }, { createUserMessage, IMAGE_OFFLOAD_REQUIRED_CODE }, { setSandboxMode }, { deriveTurnTokenUsage }, { lastAssistantStreamChunk }, { admitEncodedImages }] = await Promise.all([
|
|
117
|
+
load('@deepseek-ai/dsh-sdk-protocol'), load('@deepseek-ai/dsh-llm'), load('@deepseek-ai/dsh-sandbox-policy'),
|
|
118
|
+
load('@deepseek-ai/dsh-token-meter/client'), load('@deepseek-ai/dsh-llm/assistant-stream'),
|
|
119
|
+
load('@deepseek-ai/dsh-attachment'),
|
|
120
|
+
]);
|
|
121
|
+
const { default: ShellProvider } = await load(process.platform === 'win32'
|
|
122
|
+
? '@deepseek-ai/dsh-pwsh-sandbox' : '@deepseek-ai/dsh-bash-sandbox');
|
|
123
|
+
let toolEnv = Object.freeze({});
|
|
124
|
+
let hostSandboxMode = 'workspace-write';
|
|
125
|
+
let executionPolicy;
|
|
126
|
+
const toolExecution = new AsyncLocalStorage();
|
|
127
|
+
class ManagedShellProvider extends ShellProvider {
|
|
128
|
+
constructor(scope, config) {
|
|
129
|
+
super(scope, config);
|
|
130
|
+
if (process.platform === 'win32')
|
|
131
|
+
executionPolicy = { pwshPath: this.pwshPath };
|
|
132
|
+
}
|
|
133
|
+
resolve(request) {
|
|
134
|
+
const spec = super.resolve({ ...request, env: { ...request.env, ...toolEnv } });
|
|
135
|
+
return toolExecution.getStore()?.managedCommand
|
|
136
|
+
? { ...spec, sandboxPolicy: { ...spec.sandboxPolicy, mode: 'danger-full-access' } }
|
|
137
|
+
: spec;
|
|
138
|
+
}
|
|
139
|
+
async confine(spec, policy, signal) {
|
|
140
|
+
const confined = await super.confine(spec, policy, signal);
|
|
141
|
+
if (process.platform !== 'win32' || hostSandboxMode === 'danger-full-access')
|
|
142
|
+
return confined;
|
|
143
|
+
const { buildWindowsAgentSandboxLaunch } = await import('../../../core/permission/sandbox-runtime.js');
|
|
144
|
+
if (!process.env.TMPDIR)
|
|
145
|
+
throw new Error('DSH_SHARED_TEMP_INVALID');
|
|
146
|
+
const guarded = await buildWindowsAgentSandboxLaunch({
|
|
147
|
+
command: confined.argv[0], args: confined.argv.slice(1), projectPath: spec.workdir,
|
|
148
|
+
temporary: process.env.TMPDIR, env: { ...process.env, ...spec.env },
|
|
149
|
+
selfAid: process.env[SELF_AID_ENV],
|
|
150
|
+
readonly: hostSandboxMode === 'read-only', signal,
|
|
151
|
+
});
|
|
152
|
+
spec.env = { ...spec.env, CODEX_HOME: guarded.env.CODEX_HOME };
|
|
153
|
+
return { ...confined, argv: [guarded.command, ...guarded.args] };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
await ctx.plugin(ManagedShellProvider);
|
|
157
|
+
const transport = new JsonRpcLineTransport(process.stdin, process.stdout);
|
|
158
|
+
const lifecycle = new AbortController();
|
|
159
|
+
let handle;
|
|
160
|
+
let runIdentity;
|
|
161
|
+
let openIdentity;
|
|
162
|
+
let operation;
|
|
163
|
+
let cancelRequested = false;
|
|
164
|
+
let opening;
|
|
165
|
+
let closing;
|
|
166
|
+
let streamSeq = 0;
|
|
167
|
+
let model;
|
|
168
|
+
let acceptsImages = false;
|
|
169
|
+
let lastText = '';
|
|
170
|
+
let terminal;
|
|
171
|
+
let failure;
|
|
172
|
+
const decisions = new Map();
|
|
173
|
+
const executed = new Set();
|
|
174
|
+
const admittedDefinitions = new Map();
|
|
175
|
+
const seenInputs = new Map();
|
|
176
|
+
const disposers = [];
|
|
177
|
+
disposers.push(ctx.on('llm/stream', (options, next) => handle && runIdentity && !cancelRequested
|
|
178
|
+
? recoverImageBodyLimit(options, next(), IMAGE_OFFLOAD_REQUIRED_CODE) : next()));
|
|
179
|
+
let turnEvents;
|
|
180
|
+
let iterations = [];
|
|
181
|
+
const compactions = new Map();
|
|
182
|
+
let history;
|
|
183
|
+
let pendingQuestion;
|
|
184
|
+
const usageFields = (sample) => sample ? {
|
|
185
|
+
input_tokens: sample.inputTokens ?? sample.uncachedInputTokens, output_tokens: sample.outputTokens,
|
|
186
|
+
...(sample.cacheReadTokens === undefined ? {} : { cache_read_input_tokens: sample.cacheReadTokens }),
|
|
187
|
+
...(sample.cacheWriteTokens === undefined ? {} : { cache_creation_input_tokens: sample.cacheWriteTokens }),
|
|
188
|
+
...(sample.reasoningTokens === undefined ? {} : { reasoning_tokens: sample.reasoningTokens }),
|
|
189
|
+
...(sample.totalTokens === undefined ? {} : { total_tokens: sample.totalTokens }),
|
|
190
|
+
} : undefined;
|
|
191
|
+
const notify = (method, data) => transport.notify(method, { protocol: PROTOCOL,
|
|
192
|
+
identity: runIdentity ?? openIdentity, nativeSessionId: handle?.agent.session.id, seq: ++streamSeq, ...data });
|
|
193
|
+
async function stop() {
|
|
194
|
+
cancelRequested = true;
|
|
195
|
+
handle?.agent.cancel({ kind: 'user' });
|
|
196
|
+
await opening;
|
|
197
|
+
handle?.agent.cancel({ kind: 'user' });
|
|
198
|
+
await operation?.catch(() => { });
|
|
199
|
+
if (handle) {
|
|
200
|
+
await handle.agent.whenIdle();
|
|
201
|
+
await ctx.sessions.flush(handle.agent.session);
|
|
202
|
+
}
|
|
203
|
+
return { stopped: true };
|
|
204
|
+
}
|
|
205
|
+
async function close() {
|
|
206
|
+
if (closing)
|
|
207
|
+
return closing;
|
|
208
|
+
closing = (async () => {
|
|
209
|
+
lifecycle.abort(new Error('DSH integration closed'));
|
|
210
|
+
await stop();
|
|
211
|
+
await handle?.dispose();
|
|
212
|
+
handle = undefined;
|
|
213
|
+
})();
|
|
214
|
+
return closing;
|
|
215
|
+
}
|
|
216
|
+
disposers.push(ctx.on('agent/error', ({ agent, error }) => {
|
|
217
|
+
if (handle?.agent === agent)
|
|
218
|
+
failure = error;
|
|
219
|
+
}));
|
|
220
|
+
disposers.push(ctx.on('agent/assistant-stream', payload => {
|
|
221
|
+
if (handle?.agent === payload.agent)
|
|
222
|
+
notify('activity', {});
|
|
223
|
+
}));
|
|
224
|
+
disposers.push(ctx.on('agent/status', ({ agent, status }) => {
|
|
225
|
+
if (handle?.agent === agent && runIdentity)
|
|
226
|
+
notify('state', { state: status });
|
|
227
|
+
}));
|
|
228
|
+
disposers.push(ctx.on('session/event', (session, event) => {
|
|
229
|
+
if (handle?.agent.session !== session || !runIdentity)
|
|
230
|
+
return;
|
|
231
|
+
const data = event.data;
|
|
232
|
+
if (event.type === 'turn/start') {
|
|
233
|
+
turnEvents = [];
|
|
234
|
+
iterations = [];
|
|
235
|
+
}
|
|
236
|
+
if (turnEvents)
|
|
237
|
+
turnEvents.push(event);
|
|
238
|
+
if (event.type === 'assistant/message') {
|
|
239
|
+
const text = data.message.content.filter((block) => block.type === 'text').map((block) => block.text).join('');
|
|
240
|
+
if (text) {
|
|
241
|
+
lastText = text;
|
|
242
|
+
notify('text', { text, turn: data.turn, messageId: `dsh-${event.seq}` });
|
|
243
|
+
}
|
|
244
|
+
const usage = data.usage ?? lastAssistantStreamChunk(data.stream, 'usage')?.usage;
|
|
245
|
+
if (usage)
|
|
246
|
+
iterations.push(usageFields(usage));
|
|
247
|
+
}
|
|
248
|
+
else if (event.type === 'assistant/attempt') {
|
|
249
|
+
const usage = lastAssistantStreamChunk(data.stream, 'usage')?.usage;
|
|
250
|
+
if (usage)
|
|
251
|
+
iterations.push(usageFields(usage));
|
|
252
|
+
}
|
|
253
|
+
else if (event.type === 'tool/call') {
|
|
254
|
+
let input;
|
|
255
|
+
try {
|
|
256
|
+
input = JSON.parse(data.arguments);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
input = { invalidArguments: true };
|
|
260
|
+
}
|
|
261
|
+
notify('tool_use', { name: data.name, input, callId: data.callId, turn: data.turn });
|
|
262
|
+
}
|
|
263
|
+
else if (event.type === 'turn/end') {
|
|
264
|
+
terminal = data.reason;
|
|
265
|
+
const usage = turnEvents ? usageFields(deriveTurnTokenUsage(turnEvents)) : undefined;
|
|
266
|
+
const pressure = ctx.tokenMeter.contextPressure(session);
|
|
267
|
+
notify('usage', {
|
|
268
|
+
...(usage ? { tokenUsage: { ...usage, ...(iterations.length ? { iterations } : {}) } } : {}),
|
|
269
|
+
...(Number.isSafeInteger(pressure.pressureTokens) && Number.isSafeInteger(pressure.contextWindow)
|
|
270
|
+
&& pressure.contextWindow > 0 ? { contextUsage: {
|
|
271
|
+
totalTokens: pressure.pressureTokens, maxTokens: pressure.contextWindow, model,
|
|
272
|
+
} } : {}),
|
|
273
|
+
});
|
|
274
|
+
turnEvents = undefined;
|
|
275
|
+
}
|
|
276
|
+
else if (event.type === 'compaction/start') {
|
|
277
|
+
compactions.set(data.compactionId, { startedAt: Date.now() });
|
|
278
|
+
notify('activity', { source: 'compaction' });
|
|
279
|
+
notify('compaction_status', { state: 'started' });
|
|
280
|
+
}
|
|
281
|
+
else if (event.type === 'compaction/summary') {
|
|
282
|
+
const compaction = compactions.get(data.compactionId);
|
|
283
|
+
if (compaction)
|
|
284
|
+
compaction.preTokens = data.shadowedTokenCount;
|
|
285
|
+
}
|
|
286
|
+
else if (event.type === 'compaction/end') {
|
|
287
|
+
const compaction = compactions.get(data.compactionId);
|
|
288
|
+
compactions.delete(data.compactionId);
|
|
289
|
+
notify('compaction_status', { state: data.error ? 'failed' : 'completed' });
|
|
290
|
+
if (!data.error && compaction && Number.isSafeInteger(compaction.preTokens)) {
|
|
291
|
+
notify('compact', { preTokens: compaction.preTokens, durationMs: Date.now() - compaction.startedAt });
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}));
|
|
295
|
+
disposers.push(ctx.on('tools/pre-execute', async (exec, next) => {
|
|
296
|
+
if (!handle || exec.agent !== handle.agent || !runIdentity || cancelRequested || exec.signal.aborted || !operation) {
|
|
297
|
+
return { kind: 'deny', reason: 'No current Host execution authority' };
|
|
298
|
+
}
|
|
299
|
+
const hash = digest({ name: exec.name, input: exec.arguments });
|
|
300
|
+
let result;
|
|
301
|
+
try {
|
|
302
|
+
result = await transport.request('tool/preflight', {
|
|
303
|
+
protocol: PROTOCOL, identity: runIdentity, nativeSessionId: handle.agent.session.id,
|
|
304
|
+
callId: exec.callId, name: exec.name, input: exec.arguments, hash, ...executionPolicy,
|
|
305
|
+
...((exec.name.startsWith('mcp__') || ['list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource'].includes(exec.name))
|
|
306
|
+
? { nativeMcp: true } : {}),
|
|
307
|
+
}, AbortSignal.any([exec.signal, lifecycle.signal]));
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
const failure = dshAuthorizationFailure(error, exec.signal.aborted || lifecycle.signal.aborted);
|
|
311
|
+
decisions.set(exec.token, { ...failure, hash });
|
|
312
|
+
return { kind: 'deny', reason: failure.reason };
|
|
313
|
+
}
|
|
314
|
+
if (!record(result) || result.hash !== hash || !record(result.input) || result.allow !== true
|
|
315
|
+
|| cancelRequested || exec.signal.aborted) {
|
|
316
|
+
const reason = typeof result?.reason === 'string' ? result.reason : 'Host denied this operation';
|
|
317
|
+
decisions.set(exec.token, { allow: false, hash, reason, policyCode: result?.policyCode,
|
|
318
|
+
requestId: result?.requestId, decisionSource: result?.decisionSource, errorDetailCode: result?.errorDetailCode });
|
|
319
|
+
return { kind: 'deny', reason };
|
|
320
|
+
}
|
|
321
|
+
decisions.set(exec.token, { allow: true, hash, input: Object.freeze(result.input), managedCommand: result.managedCommand === true,
|
|
322
|
+
requestId: result.requestId, decisionSource: result.decisionSource, errorDetailCode: result.errorDetailCode });
|
|
323
|
+
return next();
|
|
324
|
+
}));
|
|
325
|
+
const executionGuard = exec => {
|
|
326
|
+
const decision = decisions.get(exec.token);
|
|
327
|
+
if (exec.agent !== handle?.agent || !runIdentity || cancelRequested || !decision?.allow
|
|
328
|
+
|| !operation || exec.signal.aborted || executed.has(exec.token)
|
|
329
|
+
|| (keepsNativeRegistration(exec.name) && digest(decision.input) !== digest(exec.arguments))
|
|
330
|
+
|| admittedDefinitions.get(exec.name) !== ctx.tools.definitions(exec.agent).find((tool) => tool.name === exec.name)
|
|
331
|
+
|| decision.hash !== digest({ name: exec.name, input: exec.arguments }))
|
|
332
|
+
return 'Host tool authorization is missing or expired';
|
|
333
|
+
};
|
|
334
|
+
ctx.tools.guard(executionGuard);
|
|
335
|
+
shared.attachGuard(executionGuard);
|
|
336
|
+
disposers.push(ctx.on('tools/execute', (exec, next) => {
|
|
337
|
+
if (!keepsNativeRegistration(exec.name))
|
|
338
|
+
return next();
|
|
339
|
+
const decision = decisions.get(exec.token);
|
|
340
|
+
if (exec.agent !== handle?.agent || !decision?.allow || exec.signal.aborted || cancelRequested
|
|
341
|
+
|| decision.hash !== digest({ name: exec.name, input: exec.arguments }))
|
|
342
|
+
throw new Error('Host tool grant expired');
|
|
343
|
+
executed.add(exec.token);
|
|
344
|
+
return next();
|
|
345
|
+
}));
|
|
346
|
+
disposers.push(ctx.on('tools/result', (exec, result) => {
|
|
347
|
+
if (exec.agent !== handle?.agent)
|
|
348
|
+
return;
|
|
349
|
+
const decision = decisions.get(exec.token);
|
|
350
|
+
const didExecute = executed.delete(exec.token);
|
|
351
|
+
decisions.delete(exec.token);
|
|
352
|
+
notify('tool_result', { name: exec.name, callId: exec.callId,
|
|
353
|
+
result: result.content.filter((block) => block.type === 'text').map((block) => block.text).join('\n'),
|
|
354
|
+
isError: result.isError, executed: didExecute, blocked: !didExecute,
|
|
355
|
+
...(result.error?.info?.code ? { errorCode: result.error.info.code } : {}),
|
|
356
|
+
cancelled: ['ABORTED', 'ABORTED_BEFORE_DISPATCH'].includes(result.error?.info?.code),
|
|
357
|
+
...(record(result.value) && Number.isInteger(result.value.exitCode) ? { exitCode: result.value.exitCode } : {}),
|
|
358
|
+
...(record(result.value?.sandbox) ? { sandbox: result.value.sandbox } : {}),
|
|
359
|
+
...(decision?.policyCode ? { policyCode: decision.policyCode } : {}),
|
|
360
|
+
...(decision?.errorDetailCode ? { errorDetailCode: decision.errorDetailCode } : {}),
|
|
361
|
+
...(decision?.requestId ? { requestId: decision.requestId, decisionSource: decision.decisionSource,
|
|
362
|
+
} : {}), });
|
|
363
|
+
}));
|
|
364
|
+
// Native ask() waits indefinitely. Host cards are business input, never tool authorization.
|
|
365
|
+
disposers.push(ctx.on('user-questions/request', async (request, next) => {
|
|
366
|
+
if (request.agent !== handle?.agent)
|
|
367
|
+
return next();
|
|
368
|
+
if (!handle || !runIdentity || pendingQuestion || cancelRequested)
|
|
369
|
+
throw new Error('Question has no current Host run');
|
|
370
|
+
const providerThreadId = handle.agent.session.id;
|
|
371
|
+
const providerTurnId = runIdentity.turnId;
|
|
372
|
+
const itemId = randomUUID();
|
|
373
|
+
const questions = request.questions;
|
|
374
|
+
const signal = AbortSignal.any([request.signal ?? lifecycle.signal, lifecycle.signal]);
|
|
375
|
+
return new Promise((resolve, reject) => {
|
|
376
|
+
const abort = () => {
|
|
377
|
+
if (pendingQuestion?.itemId === itemId)
|
|
378
|
+
pendingQuestion = undefined;
|
|
379
|
+
reject(new Error('Host question cancelled'));
|
|
380
|
+
};
|
|
381
|
+
pendingQuestion = { itemId, questions, answers: new Map(), receipts: new Set(), resolve: value => {
|
|
382
|
+
signal.removeEventListener('abort', abort);
|
|
383
|
+
pendingQuestion = undefined;
|
|
384
|
+
resolve(value);
|
|
385
|
+
} };
|
|
386
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
387
|
+
if (signal.aborted) {
|
|
388
|
+
abort();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
notify('user_question', { request: { providerThreadId,
|
|
392
|
+
providerTurnId, itemId, questions: questions.map(question => ({
|
|
393
|
+
title: question.question + (question.detail ? `\n${question.detail}` : ''),
|
|
394
|
+
...(question.options ? { options: question.options.map(option => option.label) } : {}),
|
|
395
|
+
blocking: true,
|
|
396
|
+
})) } });
|
|
397
|
+
});
|
|
398
|
+
}));
|
|
399
|
+
async function readHistory(params) {
|
|
400
|
+
if (handle || operation || history)
|
|
401
|
+
throw new Error('Maintenance requires an unused session lease');
|
|
402
|
+
const reader = await ctx.sessionPersistence.open(required(params.nativeSessionId, 'nativeSessionId'), 'read', { signal: lifecycle.signal });
|
|
403
|
+
try {
|
|
404
|
+
const normalize = (value) => process.platform === 'win32' ? value.toLowerCase() : value;
|
|
405
|
+
if (!reader.header.cwd || normalize(reader.header.cwd) !== normalize(realpathSync(required(params.cwd, 'cwd')))) {
|
|
406
|
+
throw new Error('Native session belongs to another project');
|
|
407
|
+
}
|
|
408
|
+
const { events } = await reader.read(undefined, undefined, { signal: lifecycle.signal });
|
|
409
|
+
history = { header: reader.header, events };
|
|
410
|
+
return { count: events.length };
|
|
411
|
+
}
|
|
412
|
+
finally {
|
|
413
|
+
await reader.close();
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
async function open(params) {
|
|
417
|
+
if (handle || opening || closing)
|
|
418
|
+
throw new Error('Runtime accepts exactly one session lease');
|
|
419
|
+
openIdentity = identity(params.identity);
|
|
420
|
+
if (params.protocol !== PROTOCOL || !['read-only', 'workspace-write', 'danger-full-access'].includes(params.sandboxMode)) {
|
|
421
|
+
throw new Error('Unsupported execution profile');
|
|
422
|
+
}
|
|
423
|
+
const systemPrompt = params.systemPrompt === null ? null : required(params.systemPrompt, 'systemPrompt');
|
|
424
|
+
if (systemPrompt !== null && systemPrompt.length > MAX_TEXT)
|
|
425
|
+
throw new Error('System prompt exceeds limit');
|
|
426
|
+
const cwd = required(params.cwd, 'cwd');
|
|
427
|
+
const skillPolicy = nativeSkillPolicy(params.nativeSkillPolicy);
|
|
428
|
+
if (params.skills !== undefined) {
|
|
429
|
+
throw new Error('DSH_SHARED_OPERATION_UNAVAILABLE: this bridge inherits native skills');
|
|
430
|
+
}
|
|
431
|
+
let contextWindow;
|
|
432
|
+
async function admitSelection(selection) {
|
|
433
|
+
if (!selection?.provider || !selection.model)
|
|
434
|
+
throw new Error('DSH native default model is unavailable');
|
|
435
|
+
model = selection.model;
|
|
436
|
+
const modelInfo = await ctx.llm.resolveModelInfo(selection.provider, model);
|
|
437
|
+
const capacity = modelInfo.context?.contextWindow;
|
|
438
|
+
if (Number.isSafeInteger(capacity) && capacity > 0)
|
|
439
|
+
contextWindow = capacity;
|
|
440
|
+
acceptsImages = modelInfo.inputModalities?.includes('image') === true;
|
|
441
|
+
if (selection.reasoningEffort !== undefined
|
|
442
|
+
&& !modelInfo.reasoning?.efforts?.some((effort) => effort.id === selection.reasoningEffort)) {
|
|
443
|
+
throw new Error('Unsupported reasoning effort for the selected DSH model');
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
const inference = params.inference ?? {};
|
|
447
|
+
if (!record(inference))
|
|
448
|
+
throw new Error('Invalid inference controls');
|
|
449
|
+
for (const [key, value] of Object.entries(inference)) {
|
|
450
|
+
if (key === 'maxOutputTokens' && typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= 256000)
|
|
451
|
+
continue;
|
|
452
|
+
if (key === 'temperature' && typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 2)
|
|
453
|
+
continue;
|
|
454
|
+
if (key === 'stop' && Array.isArray(value) && value.length <= 16
|
|
455
|
+
&& value.every(item => typeof item === 'string' && item.length > 0 && item.length <= 1024))
|
|
456
|
+
continue;
|
|
457
|
+
throw new Error(`Unsupported or invalid inference parameter: ${key}`);
|
|
458
|
+
}
|
|
459
|
+
if (!record(params.toolEnv) || Object.values(params.toolEnv).some(value => typeof value !== 'string')) {
|
|
460
|
+
throw new Error('Invalid tool environment');
|
|
461
|
+
}
|
|
462
|
+
toolEnv = Object.freeze({ ...params.toolEnv });
|
|
463
|
+
if (params.effortMode !== undefined && params.effortMode !== 'model_default')
|
|
464
|
+
throw new Error('Invalid effort mode');
|
|
465
|
+
const defaultSelection = ctx.agentDefaultModel.currentSelection();
|
|
466
|
+
async function resolveSharedSelection(nativeSelection) {
|
|
467
|
+
if (params.connection === undefined)
|
|
468
|
+
return undefined;
|
|
469
|
+
const connection = params.connection;
|
|
470
|
+
if (!record(connection) || !/^provider-[0-9]{8}$/.test(connection.providerId)
|
|
471
|
+
|| typeof connection.apiKey !== 'string' || !connection.apiKey.trim() || connection.apiKey.length > 65536
|
|
472
|
+
|| typeof connection.baseUrl !== 'string' || connection.baseUrl.length > 4096
|
|
473
|
+
|| (connection.imageIn !== undefined && typeof connection.imageIn !== 'boolean')
|
|
474
|
+
|| Object.keys(connection).some(key => !['providerId', 'apiKey', 'baseUrl', 'imageIn'].includes(key))) {
|
|
475
|
+
throw new Error('DSH_SHARED_PROVIDER_INVALID');
|
|
476
|
+
}
|
|
477
|
+
let url;
|
|
478
|
+
try {
|
|
479
|
+
url = new URL(connection.baseUrl);
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
throw new Error('DSH_SHARED_PROVIDER_INVALID');
|
|
483
|
+
}
|
|
484
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
|
|
485
|
+
throw new Error('DSH_SHARED_PROVIDER_INVALID');
|
|
486
|
+
const selectedModel = required(params.model ?? nativeSelection?.model, 'model');
|
|
487
|
+
const route = `evolcore-${connection.providerId}`;
|
|
488
|
+
const { registerDeepSeekProvider, resolveAdapterOptions, catalogModelInfo } = await load('@deepseek-ai/dsh-llm-deepseek');
|
|
489
|
+
const { launchEnvironmentOf } = await load('@deepseek-ai/dsh-launch-environment');
|
|
490
|
+
const options = resolveAdapterOptions({ baseURL: connection.baseUrl, models: [{ id: selectedModel,
|
|
491
|
+
...(connection.imageIn === undefined ? {} : { inputModalities: connection.imageIn ? ['text', 'image'] : ['text'] }) }] }, launchEnvironmentOf(ctx));
|
|
492
|
+
// The connection exists only in this owned process. Never register it in
|
|
493
|
+
// native settings/credentials or mutate the desktop's selected model.
|
|
494
|
+
registerDeepSeekProvider(ctx, route, {
|
|
495
|
+
options: () => options, providerName: 'EvolCore',
|
|
496
|
+
resolveAuth: async () => ({ headers: { 'x-api-key': connection.apiKey } }),
|
|
497
|
+
discoverModels: async (provider) => options.models.map((entry) => catalogModelInfo(provider, entry)),
|
|
498
|
+
});
|
|
499
|
+
return { provider: route, model: selectedModel,
|
|
500
|
+
...(params.effort === undefined ? {} : { reasoningEffort: params.effort }) };
|
|
501
|
+
}
|
|
502
|
+
const agentOptions = { ...(inference.maxOutputTokens === undefined ? {} : { maxTokens: inference.maxOutputTokens }) };
|
|
503
|
+
const setup = async (agentCtx, agent) => {
|
|
504
|
+
if (agent.inbox.nextTurn.length || agent.inbox.nextStep.length)
|
|
505
|
+
throw new Error('Restored session has unresolved queued work');
|
|
506
|
+
const normalize = (value) => process.platform === 'win32' ? value.toLowerCase() : value;
|
|
507
|
+
if (!agent.session.header.cwd || normalize(realpathSync(agent.session.header.cwd)) !== shared.binding.projectPath
|
|
508
|
+
|| normalize(realpathSync(ctx.workingDirectory.get(agent.session))) !== shared.binding.projectPath) {
|
|
509
|
+
throw new Error('DSH_SHARED_BINDING_MISMATCH: native session belongs to another project');
|
|
510
|
+
}
|
|
511
|
+
const recordedPreset = ctx.agentPresets.presetForSession(agent.session);
|
|
512
|
+
const preset = await ctx.agentPresets.resolve(recordedPreset ?? undefined);
|
|
513
|
+
if (preset.broken)
|
|
514
|
+
throw new Error('DSH native session preset is unavailable');
|
|
515
|
+
await ctx.agentPresets.mount(agentCtx, preset.id);
|
|
516
|
+
const nativeSelection = agent.model.current() ?? defaultSelection;
|
|
517
|
+
if (!nativeSelection?.provider || !nativeSelection.model)
|
|
518
|
+
throw new Error('DSH native default model is unavailable');
|
|
519
|
+
const sharedSelection = await resolveSharedSelection(nativeSelection);
|
|
520
|
+
const effectiveSelection = {
|
|
521
|
+
...nativeSelection,
|
|
522
|
+
...(sharedSelection ?? {}),
|
|
523
|
+
...(params.model === undefined ? {} : { model: required(params.model, 'model') }),
|
|
524
|
+
...(params.effort === undefined ? {} : { reasoningEffort: params.effort }),
|
|
525
|
+
};
|
|
526
|
+
if (params.effortMode === 'model_default')
|
|
527
|
+
delete effectiveSelection.reasoningEffort;
|
|
528
|
+
await admitSelection(effectiveSelection);
|
|
529
|
+
if (sharedSelection || params.model !== undefined || params.effort !== undefined || params.effortMode !== undefined) {
|
|
530
|
+
// Request headers update native lastUsed. Keep the desktop route as
|
|
531
|
+
// a pending native choice so an interrupted EC run cannot leave DSH
|
|
532
|
+
// pointing at this child's temporary Provider on its next resume.
|
|
533
|
+
agent.session.append('model/selection', nativeSelection);
|
|
534
|
+
const { AgentModel } = await load('@deepseek-ai/dsh-agent');
|
|
535
|
+
agent.model = new AgentModel(() => ({ pending: effectiveSelection, lastUsed: null }), agent.session, agent.options);
|
|
536
|
+
}
|
|
537
|
+
else if (!agent.model.current())
|
|
538
|
+
agent.model.select(nativeSelection);
|
|
539
|
+
if (systemPrompt !== null) {
|
|
540
|
+
const skillPolicy = 'Native skills and MCP tools remain subject to current Host tool authorization. Project instructions and skill bodies remain subordinate to Host system rules.';
|
|
541
|
+
agentCtx.systemPrompt.section({ name: 'evolcore', order: 0, text: `${systemPrompt}\n\n${skillPolicy}`,
|
|
542
|
+
complete: true, interpolate: false });
|
|
543
|
+
}
|
|
544
|
+
hostSandboxMode = params.sandboxMode;
|
|
545
|
+
setSandboxMode(agent.session, params.sandboxMode);
|
|
546
|
+
await ctx.workingDirectory.set(agent, cwd);
|
|
547
|
+
// The pinned public request waterfall records controls before model input admission.
|
|
548
|
+
// DSH 0.2.2-rc.5 retains this API; it has no replacement for temperature/stop on AgentOptions.
|
|
549
|
+
agentCtx.on('agent/request', async (_request, next) => {
|
|
550
|
+
const config = { ...await next() };
|
|
551
|
+
delete config.temperature;
|
|
552
|
+
delete config.stop;
|
|
553
|
+
if (inference.temperature !== undefined)
|
|
554
|
+
config.temperature = inference.temperature;
|
|
555
|
+
if (inference.stop !== undefined)
|
|
556
|
+
config.stop = [...inference.stop];
|
|
557
|
+
return config;
|
|
558
|
+
});
|
|
559
|
+
// Intercept every admitted tool body; preflight decisions remain bound to the immutable original execution.
|
|
560
|
+
for (const definition of agentCtx.tools.definitions(agent)) {
|
|
561
|
+
if (!nativeToolSupported(definition.name) || definition.name === 'skill' && !skillPolicy.enabled) {
|
|
562
|
+
// A distinct disabled registration also tells the native skill catalog
|
|
563
|
+
// to clear its previous entries when the skill loader is unavailable.
|
|
564
|
+
agentCtx.tools.register({ ...definition }, { when: () => false });
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
// Keep native registration options, including the per-step web provider readiness checks.
|
|
568
|
+
if (keepsNativeRegistration(definition.name)) {
|
|
569
|
+
admittedDefinitions.set(definition.name, definition);
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
const wrapped = { ...definition, async execute(_args, exec) {
|
|
573
|
+
const decision = decisions.get(exec.token);
|
|
574
|
+
if (!decision?.allow || exec.signal.aborted || cancelRequested)
|
|
575
|
+
throw new Error('Host execution grant expired');
|
|
576
|
+
executed.add(exec.token);
|
|
577
|
+
// Host-validated EC commands retain daemon authorization; the outer Host guard remains active.
|
|
578
|
+
return toolExecution.run(decision, () => definition.execute(decision.input, exec));
|
|
579
|
+
} };
|
|
580
|
+
agentCtx.tools.register(wrapped);
|
|
581
|
+
admittedDefinitions.set(definition.name, wrapped);
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
const nativeSessionId = params.nativeSessionId === null ? randomUUID() : required(params.nativeSessionId, 'nativeSessionId');
|
|
585
|
+
const preset = params.nativeSessionId === null ? await ctx.agentPresets.resolve() : undefined;
|
|
586
|
+
const request = params.nativeSessionId === null
|
|
587
|
+
? { sessionId: nativeSessionId, meta: { cwd, ...(preset ? { agentPreset: preset.id } : {}) }, agentOptions, setup }
|
|
588
|
+
: { resumeSessionId: nativeSessionId, agentOptions, setup };
|
|
589
|
+
const restoreSkills = filterNativeSkills(ctx.skills, skillPolicy);
|
|
590
|
+
disposers.push(restoreSkills);
|
|
591
|
+
opening = (params.nativeSessionId === null ? ctx.agents.create(request) : ctx.agents.resume(request));
|
|
592
|
+
try {
|
|
593
|
+
const opened = await opening;
|
|
594
|
+
handle = opened;
|
|
595
|
+
if (cancelRequested) {
|
|
596
|
+
opened.agent.cancel({ kind: 'user' });
|
|
597
|
+
throw new Error('Session opening cancelled');
|
|
598
|
+
}
|
|
599
|
+
// A restored pending input is never silently resubmitted under this run identity.
|
|
600
|
+
// setup rejected pre-existing input. A working-directory update may have added a non-waking native context notice.
|
|
601
|
+
if (opened.agent.status !== 'idle')
|
|
602
|
+
throw new Error('Restored session started unexpected work');
|
|
603
|
+
await ctx.sessions.flush(opened.agent.session);
|
|
604
|
+
return { nativeSessionId, protocol: PROTOCOL, model, ...(contextWindow === undefined ? {} : { contextWindow }) };
|
|
605
|
+
}
|
|
606
|
+
finally {
|
|
607
|
+
opening = undefined;
|
|
608
|
+
if (!handle)
|
|
609
|
+
restoreSkills();
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
async function compactOpenSession() {
|
|
613
|
+
const agent = handle.agent;
|
|
614
|
+
const compaction = ctx.agentPresets.serviceFor(agent, 'compaction');
|
|
615
|
+
if (!compaction)
|
|
616
|
+
throw new Error('DSH compaction service is unavailable');
|
|
617
|
+
const result = await compaction.compactNow(agent, lifecycle.signal);
|
|
618
|
+
await ctx.sessions.flush(agent.session);
|
|
619
|
+
return result;
|
|
620
|
+
}
|
|
621
|
+
async function run(params) {
|
|
622
|
+
const incoming = identity(params.identity);
|
|
623
|
+
if (!handle || closing || cancelRequested || operation)
|
|
624
|
+
throw new Error('Runtime is not ready for execution');
|
|
625
|
+
if (JSON.stringify(incoming) !== JSON.stringify(openIdentity))
|
|
626
|
+
throw new Error('Run identity does not match session lease');
|
|
627
|
+
const prior = seenInputs.get(incoming.inputId);
|
|
628
|
+
if (prior)
|
|
629
|
+
return prior;
|
|
630
|
+
if (typeof params.prompt !== 'string')
|
|
631
|
+
throw new Error('Invalid prompt');
|
|
632
|
+
const prompt = params.prompt;
|
|
633
|
+
if (prompt.length > MAX_TEXT)
|
|
634
|
+
throw new Error('Prompt exceeds limit');
|
|
635
|
+
const images = params.images ?? [];
|
|
636
|
+
if (!Array.isArray(images) || images.some(image => !record(image) || typeof image.data !== 'string'
|
|
637
|
+
|| !['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(image.mimeType)
|
|
638
|
+
|| Object.keys(image).some(key => !['data', 'mimeType'].includes(key)))) {
|
|
639
|
+
throw new Error('DSH_IMAGE_INPUT_INVALID: Expected encoded image data and MIME type');
|
|
640
|
+
}
|
|
641
|
+
if (!prompt.trim() && !images.length)
|
|
642
|
+
throw new Error('Input requires text or images');
|
|
643
|
+
if (images.length && !acceptsImages) {
|
|
644
|
+
throw new Error(`BASEAGENT_CAPABILITY_UNSUPPORTED: Baseagent dsh model ${model} does not support C26 (image input)`);
|
|
645
|
+
}
|
|
646
|
+
const threshold = params.autoCompactThresholdTokens;
|
|
647
|
+
if (threshold !== undefined && (!Number.isSafeInteger(threshold) || threshold < 1 || shared.binding.nativeSessionId === null)) {
|
|
648
|
+
throw new Error('Invalid DSH automatic compaction threshold');
|
|
649
|
+
}
|
|
650
|
+
const task = (async () => {
|
|
651
|
+
let refs;
|
|
652
|
+
try {
|
|
653
|
+
refs = await admitEncodedImages(ctx.attachments, images.map(image => ({ data: image.data, mediaType: image.mimeType })));
|
|
654
|
+
}
|
|
655
|
+
catch (error) {
|
|
656
|
+
throw new Error(`DSH_IMAGE_INPUT_INVALID: ${error instanceof Error ? error.message : String(error)}`);
|
|
657
|
+
}
|
|
658
|
+
if (cancelRequested || closing || lifecycle.signal.aborted)
|
|
659
|
+
throw new Error('Input admission cancelled');
|
|
660
|
+
runIdentity = incoming;
|
|
661
|
+
if (threshold !== undefined) {
|
|
662
|
+
try {
|
|
663
|
+
const { pressureTokens } = ctx.tokenMeter.contextPressure(handle.agent.session);
|
|
664
|
+
if (Number.isSafeInteger(pressureTokens) && pressureTokens >= threshold)
|
|
665
|
+
await compactOpenSession();
|
|
666
|
+
}
|
|
667
|
+
catch {
|
|
668
|
+
// As with the Host check, a failed proactive compression does not reject the next input.
|
|
669
|
+
notify('compaction_warning', {});
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
if (cancelRequested || closing || lifecycle.signal.aborted)
|
|
673
|
+
throw new Error('Input admission cancelled');
|
|
674
|
+
const message = createUserMessage({ content: [{ type: 'text', text: prompt },
|
|
675
|
+
...refs.map((attachment) => ({ type: 'image', attachment }))], source: { kind: 'user' } });
|
|
676
|
+
handle.agent.followup(message);
|
|
677
|
+
await ctx.sessions.flush(handle.agent.session);
|
|
678
|
+
notify('input_accepted', { inputId: incoming.inputId, messageId: message.id });
|
|
679
|
+
await handle.agent.whenIdle();
|
|
680
|
+
// The native JSON-RPC transport serializes only Error.message. Return a
|
|
681
|
+
// bounded failure record so a gateway's custom text cannot erase HTTP 413.
|
|
682
|
+
// Never carry the Error cause (which may contain a raw response body).
|
|
683
|
+
if (failure) {
|
|
684
|
+
const facts = failure.failure;
|
|
685
|
+
if (typeof facts?.status !== 'number' || !Number.isInteger(facts.status) || facts.status < 100 || facts.status > 599)
|
|
686
|
+
throw failure;
|
|
687
|
+
return { stopped: true, reason: 'error', isError: true, requestFailure: {
|
|
688
|
+
message: String(failure.message ?? failure).slice(0, 16384),
|
|
689
|
+
...(typeof facts?.code === 'string' ? { code: facts.code.slice(0, 128) } : {}),
|
|
690
|
+
status: facts.status,
|
|
691
|
+
} };
|
|
692
|
+
}
|
|
693
|
+
if (!terminal)
|
|
694
|
+
throw new Error('DSH did not produce a terminal turn');
|
|
695
|
+
await ctx.sessions.flush(handle.agent.session);
|
|
696
|
+
return { stopped: true, reason: terminal.kind, text: lastText,
|
|
697
|
+
isError: terminal.kind !== 'completed' || cancelRequested };
|
|
698
|
+
})();
|
|
699
|
+
operation = task;
|
|
700
|
+
seenInputs.set(incoming.inputId, task);
|
|
701
|
+
try {
|
|
702
|
+
return await task;
|
|
703
|
+
}
|
|
704
|
+
finally {
|
|
705
|
+
if (operation === task)
|
|
706
|
+
operation = undefined;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
let initialized = false;
|
|
710
|
+
transport.onRequest(async (method, params = {}) => {
|
|
711
|
+
await shared.readiness;
|
|
712
|
+
assertSharedTaskRequest(shared.binding, method, params);
|
|
713
|
+
if (method !== 'initialize' && !initialized)
|
|
714
|
+
throw new Error('DSH shared handshake is required');
|
|
715
|
+
if (method === 'initialize') {
|
|
716
|
+
await ctx.get('loader')?.await();
|
|
717
|
+
if (params.protocol !== PROTOCOL)
|
|
718
|
+
throw new Error('Unsupported integration protocol');
|
|
719
|
+
initialized = true;
|
|
720
|
+
return { protocol: PROTOCOL, dshVersion: VERSION, platform: process.platform,
|
|
721
|
+
storageMode: 'native-shared', binding: shared.binding };
|
|
722
|
+
}
|
|
723
|
+
if (method === 'session/open')
|
|
724
|
+
return open(params);
|
|
725
|
+
if (method === 'history/open')
|
|
726
|
+
return readHistory(params);
|
|
727
|
+
if (method === 'history/read') {
|
|
728
|
+
if (!history || !Number.isSafeInteger(params.offset) || params.offset < 0)
|
|
729
|
+
throw new Error('Invalid history offset');
|
|
730
|
+
return { events: history.events.slice(params.offset, params.offset + 32) };
|
|
731
|
+
}
|
|
732
|
+
if (method === 'run/inject') {
|
|
733
|
+
if (!handle || !runIdentity || !operation || cancelRequested || handle.agent.status === 'idle'
|
|
734
|
+
|| JSON.stringify(identity(params.identity)) !== JSON.stringify(runIdentity))
|
|
735
|
+
throw new Error('Injection target is inactive');
|
|
736
|
+
const text = required(params.text, 'injection text');
|
|
737
|
+
if (text.length > MAX_TEXT)
|
|
738
|
+
throw new Error('Injection exceeds limit');
|
|
739
|
+
handle.agent.inject(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }));
|
|
740
|
+
return { accepted: true };
|
|
741
|
+
}
|
|
742
|
+
if (method === 'question/answer') {
|
|
743
|
+
if (!pendingQuestion || !handle || cancelRequested || JSON.stringify(identity(params.identity)) !== JSON.stringify(runIdentity)
|
|
744
|
+
|| params.answer?.providerThreadId !== handle.agent.session.id
|
|
745
|
+
|| params.answer?.questionItemId !== pendingQuestion.itemId)
|
|
746
|
+
throw new Error('Question binding changed');
|
|
747
|
+
const question = pendingQuestion.questions.find(item => item.question + (item.detail ? `\n${item.detail}` : '') === params.answer.question
|
|
748
|
+
&& !pendingQuestion.answers.has(item.id));
|
|
749
|
+
if (!question || pendingQuestion.receipts.has(params.answer.requestId))
|
|
750
|
+
throw new Error('Question is stale or already answered');
|
|
751
|
+
const value = required(params.answer.answer, 'answer');
|
|
752
|
+
pendingQuestion.receipts.add(required(params.answer.requestId, 'answer request id'));
|
|
753
|
+
const selected = question.options?.some(option => option.label === value) ? [value] : [];
|
|
754
|
+
pendingQuestion.answers.set(question.id, { id: question.id, selected, ...(selected.length ? {} : { custom: value }) });
|
|
755
|
+
if (pendingQuestion.answers.size === pendingQuestion.questions.length) {
|
|
756
|
+
pendingQuestion.resolve({ answers: pendingQuestion.questions.map(item => pendingQuestion.answers.get(item.id)) });
|
|
757
|
+
}
|
|
758
|
+
return { accepted: true };
|
|
759
|
+
}
|
|
760
|
+
if (method === 'run/start')
|
|
761
|
+
return run(params);
|
|
762
|
+
if (method === 'run/cancel') {
|
|
763
|
+
if (JSON.stringify(identity(params.identity)) !== JSON.stringify(openIdentity))
|
|
764
|
+
throw new Error('Stale cancel target');
|
|
765
|
+
return stop();
|
|
766
|
+
}
|
|
767
|
+
if (method === 'session/compact') {
|
|
768
|
+
if (!handle || operation || cancelRequested)
|
|
769
|
+
throw new Error('Session is busy or cancelled');
|
|
770
|
+
runIdentity = openIdentity;
|
|
771
|
+
const task = (async () => {
|
|
772
|
+
const result = await compactOpenSession();
|
|
773
|
+
return { changed: result !== null, ...(result ? { compactionId: result.compactionId,
|
|
774
|
+
startSeq: result.startSeq, summarySeq: result.summarySeq, endSeq: result.endSeq,
|
|
775
|
+
shadowedTokenCount: result.shadowedTokenCount } : {}) };
|
|
776
|
+
})();
|
|
777
|
+
operation = task;
|
|
778
|
+
try {
|
|
779
|
+
return await task;
|
|
780
|
+
}
|
|
781
|
+
finally {
|
|
782
|
+
if (operation === task)
|
|
783
|
+
operation = undefined;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
if (method === 'session/close') {
|
|
787
|
+
await close();
|
|
788
|
+
return { stopped: true };
|
|
789
|
+
}
|
|
790
|
+
throw new Error(`Unknown integration method: ${method}`);
|
|
791
|
+
});
|
|
792
|
+
ctx.effect(() => {
|
|
793
|
+
transport.start();
|
|
794
|
+
return async () => {
|
|
795
|
+
try {
|
|
796
|
+
await close();
|
|
797
|
+
}
|
|
798
|
+
finally {
|
|
799
|
+
for (const dispose of disposers)
|
|
800
|
+
dispose();
|
|
801
|
+
transport.close();
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
}, 'evolcore-dsh-transport');
|
|
805
|
+
}
|
|
806
|
+
/** Map an HTTP body rejection to DSH's durable image offload/retry seam. */
|
|
807
|
+
export async function* recoverImageBodyLimit(options, stream, offloadCode) {
|
|
808
|
+
let emittedContent = false;
|
|
809
|
+
for await (const chunk of stream) {
|
|
810
|
+
if (chunk.type === 'finish' && chunk.reason?.kind === 'error'
|
|
811
|
+
&& chunk.reason.failure?.status === 413 && !emittedContent && !options.signal?.aborted) {
|
|
812
|
+
const images = (options.messages ?? []).flatMap(message => message.role === 'assistant' ? []
|
|
813
|
+
: (message.content ?? []).filter(block => block.type === 'image' && block.offloaded !== true));
|
|
814
|
+
// Keep the newest image. A single image or text-only oversize request
|
|
815
|
+
// still needs explicit resizing/compaction; never degrade it to text.
|
|
816
|
+
if (images.length > 1) {
|
|
817
|
+
const sizes = images.map(image => {
|
|
818
|
+
const bytes = image.attachment?.bytes;
|
|
819
|
+
return typeof bytes === 'number' && Number.isSafeInteger(bytes) && bytes > 0 ? bytes : 1;
|
|
820
|
+
});
|
|
821
|
+
const target = sizes.reduce((sum, bytes) => sum + bytes, 0) / 2;
|
|
822
|
+
let removed = 0;
|
|
823
|
+
let count = 0;
|
|
824
|
+
while (count < sizes.length - 1 && removed < target)
|
|
825
|
+
removed += sizes[count++];
|
|
826
|
+
yield { ...chunk, reason: { ...chunk.reason, failure: {
|
|
827
|
+
...chunk.reason.failure, code: offloadCode, offloadImages: count,
|
|
828
|
+
message: 'HTTP 413: offload oldest retained images before retrying this model step',
|
|
829
|
+
} } };
|
|
830
|
+
continue;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
if (!['finish', 'usage'].includes(chunk.type))
|
|
834
|
+
emittedContent = true;
|
|
835
|
+
yield chunk;
|
|
836
|
+
}
|
|
837
|
+
}
|