evolcore 0.0.49 → 0.0.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (514) hide show
  1. package/CHANGELOG.md +103 -3
  2. package/bin/ec-build.mjs +60 -0
  3. package/bin/ecmsg.js +64 -57
  4. package/dist/ability/caller/authorization.js +21 -0
  5. package/dist/ability/caller/command.js +173 -0
  6. package/dist/ability/caller/contract.js +117 -0
  7. package/dist/ability/caller/credential-files.js +132 -0
  8. package/dist/ability/caller/daemon.js +183 -0
  9. package/dist/ability/caller/schema-view.js +157 -0
  10. package/dist/ability/caller/service.js +519 -0
  11. package/dist/ability/command-contract.js +5 -0
  12. package/dist/ability/daemon.js +5 -1
  13. package/dist/ability/interop-v1.js +156 -106
  14. package/dist/ability/management.js +1 -0
  15. package/dist/agent-template/jobs.js +79 -3
  16. package/dist/agent-template/runtime.js +459 -47
  17. package/dist/agent-template/service.js +1242 -198
  18. package/dist/agent-template/share.js +103 -0
  19. package/dist/agent-template/tool-runner.js +25 -0
  20. package/dist/agent-template/types.js +10 -2
  21. package/dist/agents/claude/availability.js +94 -0
  22. package/dist/agents/claude/capability-provider.js +154 -0
  23. package/dist/agents/claude/index.js +145 -0
  24. package/dist/agents/{claude-runner.js → claude/runner.js} +78 -166
  25. package/dist/agents/claude/session-file-adapter.js +246 -0
  26. package/dist/agents/codex/app-server-client.js +90 -10
  27. package/dist/agents/codex/availability.js +164 -0
  28. package/dist/agents/codex/capability-provider.js +138 -0
  29. package/dist/agents/codex/cli.js +38 -0
  30. package/dist/agents/codex/index.js +345 -0
  31. package/dist/agents/codex/mcp-elicitation.js +135 -0
  32. package/dist/agents/{codex-runner.js → codex/runner.js} +652 -383
  33. package/dist/agents/codex/session-file-adapter.js +834 -0
  34. package/dist/agents/dsh/availability.js +28 -0
  35. package/dist/agents/dsh/capability-provider.js +56 -0
  36. package/dist/agents/dsh/desktop-locations.ps1 +66 -0
  37. package/dist/agents/dsh/desktop-probe.cjs +37 -0
  38. package/dist/agents/dsh/index.js +98 -0
  39. package/dist/agents/dsh/installation.js +400 -0
  40. package/dist/agents/dsh/resources.js +755 -0
  41. package/dist/agents/dsh/runner.js +1183 -0
  42. package/dist/agents/dsh/runtime/README.md +243 -0
  43. package/dist/agents/dsh/runtime/authorization.js +23 -0
  44. package/dist/agents/dsh/runtime/bridge.js +837 -0
  45. package/dist/agents/dsh/runtime/config.js +271 -0
  46. package/dist/agents/dsh/runtime/entry.js +229 -0
  47. package/dist/agents/dsh/runtime/session-inspector.js +340 -0
  48. package/dist/agents/dsh/runtime/tool-policy.js +49 -0
  49. package/dist/agents/dsh/session-file-adapter.js +145 -0
  50. package/dist/agents/ecagent/index.js +215 -0
  51. package/dist/agents/{ecagent-runner.js → ecagent/runner.js} +592 -106
  52. package/dist/agents/ecagent/session-file-adapter.js +134 -0
  53. package/dist/agents/gemini/index.js +96 -0
  54. package/dist/agents/{gemini-runner.js → gemini/runner.js} +18 -23
  55. package/dist/{core/session/adapters/gemini-session-file-adapter.js → agents/gemini/session-file-adapter.js} +2 -2
  56. package/dist/aun/ability-device-routing.js +11 -17
  57. package/dist/aun/aid/agentmd.js +27 -1
  58. package/dist/aun/aid/control-aid.js +52 -32
  59. package/dist/aun/aid/managed-operation.js +6 -4
  60. package/dist/aun/group/invite-service.js +7 -37
  61. package/dist/aun/group/operations.js +6 -0
  62. package/dist/aun/menu/client.js +1 -1
  63. package/dist/aun/msg/history.js +1 -1
  64. package/dist/aun/msg/managed-operation.js +93 -21
  65. package/dist/aun/msg/mention-schema.js +1 -1
  66. package/dist/aun/msg/p2p.js +32 -4
  67. package/dist/aun/msg/upload.js +126 -3
  68. package/dist/aun/service-proxy.js +1 -1
  69. package/dist/aun/storage/index.js +242 -0
  70. package/dist/build-identity.json +1 -1
  71. package/dist/channels/aun.js +698 -213
  72. package/dist/channels/daemon.js +3 -2
  73. package/dist/channels/dingtalk.js +1 -1
  74. package/dist/channels/feishu.js +9 -9
  75. package/dist/channels/qqbot.js +1 -1
  76. package/dist/channels/wechat.js +2 -2
  77. package/dist/channels/wecom.js +1 -1
  78. package/dist/claude-gateway/agent-registration.js +389 -0
  79. package/dist/claude-gateway/binding.js +96 -0
  80. package/dist/claude-gateway/inbox.js +138 -0
  81. package/dist/claude-gateway/index.js +125 -0
  82. package/dist/claude-gateway/listing.js +330 -0
  83. package/dist/claude-gateway/router.js +328 -0
  84. package/dist/claude-gateway/sessions.js +128 -0
  85. package/dist/claude-gateway/terminal.js +250 -0
  86. package/dist/claude-gateway/transcript.js +272 -0
  87. package/dist/claude-gateway/types.js +14 -0
  88. package/dist/cli/ability-command.js +45 -0
  89. package/dist/cli/ability-output.js +182 -0
  90. package/dist/cli/agent-command.js +21 -2
  91. package/dist/cli/agent-create.js +197 -56
  92. package/dist/cli/agent-template.js +400 -27
  93. package/dist/cli/agent.js +105 -11
  94. package/dist/cli/aun-commands.js +237 -123
  95. package/dist/cli/bench.js +5 -2
  96. package/dist/cli/config.js +22 -6
  97. package/dist/cli/daemon-commands.js +283 -109
  98. package/dist/cli/data-command.js +1 -1
  99. package/dist/cli/debug-mode.js +9 -0
  100. package/dist/cli/directory.js +1 -2
  101. package/dist/cli/ecmsg-gateway.js +64 -26
  102. package/dist/cli/fs-command.js +67 -39
  103. package/dist/cli/index.js +45 -12
  104. package/dist/cli/init.js +161 -90
  105. package/dist/cli/managed-command-guard.js +3 -0
  106. package/dist/cli/menu-client.js +32 -7
  107. package/dist/cli/model.js +1 -1
  108. package/dist/cli/pay-command.js +30 -0
  109. package/dist/cli/provider-command.js +6 -2
  110. package/dist/cli/restart-monitor.js +4 -4
  111. package/dist/cli/services-command.js +35 -10
  112. package/dist/cli/skill-command.js +4 -4
  113. package/dist/cli/task-context.js +24 -14
  114. package/dist/cli/team-workspace-command.js +50 -52
  115. package/dist/cli/thread-command.js +81 -14
  116. package/dist/cli/trigger-command.js +47 -12
  117. package/dist/cli/watch-logs.js +2 -1
  118. package/dist/config/access-policy.js +16 -3
  119. package/dist/config/boot-log.js +3 -0
  120. package/dist/config/builtin-role-templates.js +1 -1
  121. package/dist/config/config-field-policy.js +26 -13
  122. package/dist/config/config-manager.js +113 -52
  123. package/dist/config/config-operation-service.js +22 -1
  124. package/dist/config/gateway-config.js +29 -44
  125. package/dist/config/invoke-ipc-service.js +1 -1
  126. package/dist/config/owner-config.js +5 -19
  127. package/dist/config/peer-book-store.js +2 -3
  128. package/dist/config/peer-book.js +2 -2
  129. package/dist/config/peer-role-resolver.js +3 -9
  130. package/dist/config/provider-identity-migration.js +24 -105
  131. package/dist/config/provider-ipc-service.js +13 -3
  132. package/dist/config/provider-local-sync.js +4 -1
  133. package/dist/config/provider-menu-request.js +21 -3
  134. package/dist/config/provider-templates.js +1 -1
  135. package/dist/config/providers-config.js +138 -31
  136. package/dist/config/providers-import.js +3 -3
  137. package/dist/config/providers-management.js +109 -118
  138. package/dist/config/resolved-config-op.js +1 -42
  139. package/dist/config/schema-migration.js +254 -15
  140. package/dist/config/schema-registry.js +53 -8
  141. package/dist/config-store.js +1343 -63
  142. package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +228 -9
  143. package/dist/core/{agent-create-status.js → agent/agent-create-status.js} +112 -4
  144. package/dist/core/{agent-creation-claim.js → agent/agent-creation-claim.js} +3 -3
  145. package/dist/core/{agent-ipc-registration.js → agent/agent-ipc-registration.js} +119 -25
  146. package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +65 -0
  147. package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +249 -79
  148. package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +23 -18
  149. package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
  150. package/dist/core/auth/agent-delegation.js +15 -8
  151. package/dist/core/auth/delegation-authorization.js +28 -0
  152. package/dist/core/auth/operation-authorizer.js +20 -2
  153. package/dist/core/auth/operation-catalog.js +80 -8
  154. package/dist/core/baseagent/baseagent-availability.js +197 -0
  155. package/dist/core/baseagent/baseagent-capability-adapter.js +288 -0
  156. package/dist/core/baseagent/baseagent-config-shared.js +56 -0
  157. package/dist/core/baseagent/baseagent-identity.js +68 -0
  158. package/dist/core/{baseagent-loader.js → baseagent/baseagent-loader.js} +89 -6
  159. package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
  160. package/dist/core/baseagent/baseagent-plugin-descriptor.js +357 -0
  161. package/dist/core/baseagent/baseagent-plugin-loader.js +367 -0
  162. package/dist/core/baseagent/baseagent.js +157 -0
  163. package/dist/{agents → core/baseagent}/runner-types.js +36 -4
  164. package/dist/core/capability/capability-manager.js +91 -33
  165. package/dist/core/capability/providers/claude-capability-provider.js +2 -154
  166. package/dist/core/capability/providers/codex-capability-provider.js +2 -136
  167. package/dist/core/{channel-loader.js → channel/channel-loader.js} +226 -38
  168. package/dist/core/{channel-runtime.js → channel/channel-runtime.js} +21 -19
  169. package/dist/core/command/agent-control.js +80 -17
  170. package/dist/core/command/agent-template-menu.js +23 -10
  171. package/dist/core/command/agentmd-menu-request.js +19 -8
  172. package/dist/core/command/agentmd-menu.js +14 -5
  173. package/dist/core/command/cli-intent-parser.js +15 -0
  174. package/dist/core/command/command-handler.js +127 -57
  175. package/dist/core/command/context-policy-menu.js +122 -0
  176. package/dist/core/command/data-root-resolver.js +157 -20
  177. package/dist/core/command/memory-slash.js +6 -6
  178. package/dist/core/command/menu-catalog.js +95 -19
  179. package/dist/core/command/menu-file-path.js +70 -0
  180. package/dist/core/command/menu-handler.js +392 -93
  181. package/dist/core/command/menu-protocol.js +47 -8
  182. package/dist/core/command/menu-query-batch.js +9 -5
  183. package/dist/core/command/private-mention-menu.js +71 -0
  184. package/dist/core/command/provider-menu.js +7 -11
  185. package/dist/core/command/role-menu.js +1 -1
  186. package/dist/core/command/skill-slash.js +17 -5
  187. package/dist/core/command/slash-gate.js +2 -4
  188. package/dist/core/command/slash-handler.js +143 -121
  189. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  190. package/dist/core/command/team-workspace-team.js +3 -3
  191. package/dist/core/command/topic-slash.js +16 -10
  192. package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -18
  193. package/dist/core/{daemon-control.js → daemon/daemon-control.js} +48 -21
  194. package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +28 -20
  195. package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +10 -5
  196. package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +101 -37
  197. package/dist/core/{lifecycle-notice.js → daemon/lifecycle-notice.js} +4 -5
  198. package/dist/core/file-integrity/store.js +1 -1
  199. package/dist/core/handoff/ipc-registration.js +3 -3
  200. package/dist/core/handoff/runtime.js +2 -2
  201. package/dist/{agents → core/inference}/request-identity.js +2 -2
  202. package/dist/core/inference/text-inference.js +4 -4
  203. package/dist/core/{bootstrap-messages.js → initialization/bootstrap-messages.js} +10 -10
  204. package/dist/core/{bootstrap-service.js → initialization/bootstrap-service.js} +24 -23
  205. package/dist/core/initialization/service.js +57 -9
  206. package/dist/core/invoke/executors/media.js +1 -1
  207. package/dist/core/invoke/executors/text.js +1 -1
  208. package/dist/core/memory/consolidation-context.js +3 -2
  209. package/dist/core/memory/consolidation-trigger.js +9 -3
  210. package/dist/core/memory/consolidation.js +39 -68
  211. package/dist/core/memory/memory-admin.js +6 -6
  212. package/dist/core/memory/memory-writer.js +1 -1
  213. package/dist/core/memory/relation-idle-monitor.js +1 -1
  214. package/dist/core/message/aun-ipc-sender.js +204 -88
  215. package/dist/core/message/aun-request-registry.js +44 -5
  216. package/dist/core/message/auto-mention-gate.js +1 -1
  217. package/dist/core/message/contact-admission.js +1 -1
  218. package/dist/core/message/im-renderer.js +19 -0
  219. package/dist/core/{interaction-router.js → message/interaction-router.js} +131 -1
  220. package/dist/core/message/items-formatter.js +5 -5
  221. package/dist/core/message/message-admission.js +1 -1
  222. package/dist/core/message/message-bridge.js +239 -59
  223. package/dist/core/message/message-log.js +8 -0
  224. package/dist/core/message/message-queue.js +88 -7
  225. package/dist/core/message/message-utils.js +1 -1
  226. package/dist/core/message/peer-mode.js +16 -5
  227. package/dist/core/message/response-engine.js +351 -152
  228. package/dist/core/message/send-options.js +44 -7
  229. package/dist/core/message/send-routing.js +55 -115
  230. package/dist/core/message/stream-idle-monitor.js +1 -1
  231. package/dist/core/{data-migration.js → migration/data-migration.js} +29 -1
  232. package/dist/core/model/catalog-service.js +29 -8
  233. package/dist/core/model/model-capabilities.js +88 -0
  234. package/dist/core/model/model-catalog.js +18 -7
  235. package/dist/core/model/model-diagnostics.js +4 -4
  236. package/dist/core/ownership/owner-resolver.js +107 -101
  237. package/dist/core/{pack-auth.js → pack/pack-auth.js} +34 -3
  238. package/dist/core/{pack-install.js → pack/pack-install.js} +95 -17
  239. package/dist/core/permission/approval-gateway.js +9 -18
  240. package/dist/core/permission/ec-command-parser.js +242 -82
  241. package/dist/core/permission/managed-file.js +234 -0
  242. package/dist/core/permission/protected-paths.js +120 -9
  243. package/dist/core/permission/sandbox-runtime.js +267 -3
  244. package/dist/core/permission/services-path-acl.js +9 -2
  245. package/dist/core/permission/session-path-grants.js +1 -1
  246. package/dist/core/permission/shell-environment.js +15 -1
  247. package/dist/core/permission/tool-policy.js +21 -9
  248. package/dist/core/plugin/plugin-lifecycle.js +442 -0
  249. package/dist/core/session/adapters/claude-session-file-adapter.js +2 -242
  250. package/dist/core/session/adapters/codex-session-file-adapter.js +2 -562
  251. package/dist/core/session/adapters/ecagent-session-file-adapter.js +2 -134
  252. package/dist/core/{background-session → session/background}/session-cleanup.js +2 -2
  253. package/dist/core/{background-session → session/background}/types.js +1 -1
  254. package/dist/core/session/session-file-health.js +2 -272
  255. package/dist/core/session/session-idle-monitor.js +1 -1
  256. package/dist/core/session/session-manager.js +76 -12
  257. package/dist/core/session/session-mapper.js +16 -0
  258. package/dist/core/session/session-terminal.js +185 -0
  259. package/dist/core/session/session-title.js +8 -11
  260. package/dist/core/{system-session → session/system}/memory.js +43 -9
  261. package/dist/core/{system-session → session/system}/registry.js +1 -1
  262. package/dist/core/{system-session → session/system}/types.js +1 -1
  263. package/dist/core/skill/index-generator.js +3 -3
  264. package/dist/core/skill/switch-resolver.js +3 -0
  265. package/dist/core/task/task-activity-store.js +112 -0
  266. package/dist/core/task/task-recovery-service.js +2 -2
  267. package/dist/core/thread/command-parser.js +4 -1
  268. package/dist/core/thread/ipc-operation.js +6 -4
  269. package/dist/core/thread/thread-operation.js +27 -11
  270. package/dist/core/thread/thread-route.js +5 -3
  271. package/dist/core/thread/thread-service.js +307 -58
  272. package/dist/core/thread/topic-id.js +52 -2
  273. package/dist/core/thread/types.js +15 -1
  274. package/dist/directory/{owner-directory-admission.js → admission.js} +3 -3
  275. package/dist/directory/{owner-directory-cache.js → cache.js} +90 -8
  276. package/dist/directory/{owner-directory-markdown.js → markdown.js} +2 -2
  277. package/dist/directory/{owner-directory-query-operation.js → query-operation.js} +83 -9
  278. package/dist/directory/{owner-directory-search.js → search.js} +50 -2
  279. package/dist/directory/{owner-directory-store.js → store.js} +2 -2
  280. package/dist/eck/kit-renderer.js +3 -2
  281. package/dist/eck/manifest-engine.js +64 -2
  282. package/dist/eck/message-renderer.js +35 -0
  283. package/dist/ecweb/basic-settings-service.js +12 -10
  284. package/dist/{contracts → ecweb/contracts}/ecweb-service-protocol.js +2 -1
  285. package/dist/ecweb/dsh-native-service.js +413 -0
  286. package/dist/ecweb/providers-service.js +5 -3
  287. package/dist/ecweb/runtime/lifecycle.js +1 -1
  288. package/dist/ecweb/runtime/supervisor.js +1 -1
  289. package/dist/event-center/center-config.js +2 -2
  290. package/dist/event-center/dispatcher.js +1 -1
  291. package/dist/event-center/ipc-operation.js +12 -3
  292. package/dist/event-center/pack-loader.js +2 -2
  293. package/dist/event-center/registry.js +6 -6
  294. package/dist/event-center/runtime.js +2 -2
  295. package/dist/index.js +181 -77
  296. package/dist/ipc.js +161 -12
  297. package/dist/outputs/authorization.js +27 -0
  298. package/dist/outputs/events.js +10 -1
  299. package/dist/outputs/panel-cards.js +960 -0
  300. package/dist/paths.js +60 -1
  301. package/dist/pay/command.js +38 -0
  302. package/dist/pay/protocol.js +136 -0
  303. package/dist/pay/runtime.js +196 -0
  304. package/dist/pay/service.js +384 -0
  305. package/dist/pay/store.js +81 -0
  306. package/dist/response-system/engines/v1/proactive-flow.js +30 -3
  307. package/dist/services/dispatcher.js +25 -7
  308. package/dist/services/host/main.js +397 -0
  309. package/dist/services/host/protocol.js +125 -0
  310. package/dist/services/host/resident.js +347 -0
  311. package/dist/services/host-client.js +398 -0
  312. package/dist/services/host-deploy.js +180 -0
  313. package/dist/services/host-launch.js +117 -0
  314. package/dist/services/host-recycle.js +208 -0
  315. package/dist/services/host-runtime.js +841 -0
  316. package/dist/services/idempotency.js +44 -86
  317. package/dist/services/index-generator.js +4 -3
  318. package/dist/services/index.js +258 -36
  319. package/dist/services/ipc-operation.js +503 -78
  320. package/dist/services/pack-manager.js +2 -2
  321. package/dist/services/router.js +43 -3
  322. package/dist/services/script-runner.js +541 -100
  323. package/dist/services/service-payload.js +28 -1
  324. package/dist/services/validation.js +136 -5
  325. package/dist/stats/context-usage.js +110 -0
  326. package/dist/stats/model-resolver.js +103 -17
  327. package/dist/stats/query.js +5 -0
  328. package/dist/trigger/application-service.js +9 -6
  329. package/dist/trigger/authorization.js +36 -33
  330. package/dist/trigger/ipc-service.js +4 -4
  331. package/dist/trigger/local-files.js +8 -166
  332. package/dist/trigger/manager.js +2 -2
  333. package/dist/trigger/parser.js +48 -0
  334. package/dist/trigger/scheduler.js +35 -13
  335. package/dist/trigger/script-executor.js +21 -0
  336. package/dist/trigger/script-sandbox.js +77 -232
  337. package/dist/trigger/system-definitions.js +25 -0
  338. package/dist/trigger/validation.js +1 -1
  339. package/dist/utils/aid-bind.js +3 -0
  340. package/dist/utils/atomic-write.js +88 -1
  341. package/dist/utils/cross-platform.js +4 -42
  342. package/dist/utils/error-dict.json +22 -1
  343. package/dist/utils/error-utils.js +193 -6
  344. package/dist/utils/evolcore-version.js +2 -2
  345. package/dist/utils/host-info.js +74 -1
  346. package/dist/utils/logger.js +5 -3
  347. package/dist/utils/media-cache.js +284 -42
  348. package/dist/utils/restart-safety.js +14 -1
  349. package/dist/utils/startup-trace.js +20 -4
  350. package/dist/utils/system-memory.js +113 -25
  351. package/dist/utils/systemd-lifecycle.js +154 -0
  352. package/dist/utils/welcome.js +64 -20
  353. package/dist/utils/windows-shell-trust.js +7 -3
  354. package/ecagent/README.md +35 -0
  355. package/ecagent/dist/agent-loop.js +80 -30
  356. package/ecagent/dist/harness/env/nodejs.d.ts +16 -0
  357. package/ecagent/dist/harness/env/nodejs.js +49 -20
  358. package/ecagent/dist/harness/messages.js +3 -2
  359. package/ecagent/dist/harness/types.d.ts +1 -0
  360. package/ecagent/dist/runtime/types.d.ts +2 -0
  361. package/ecagent/dist/runtime/utils/validation.d.ts +7 -1
  362. package/ecagent/dist/runtime/utils/validation.js +42 -0
  363. package/ecagent/dist/types.d.ts +2 -0
  364. package/kits/docs/INDEX.md +3 -2
  365. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
  366. package/kits/docs/channels/aun.md +1 -1
  367. package/kits/docs/channels/feishu.md +1 -1
  368. package/kits/docs/evolcore/INDEX.md +13 -9
  369. package/kits/docs/evolcore/agent-create.md +2 -0
  370. package/kits/docs/evolcore/agent.md +133 -11
  371. package/kits/docs/evolcore/aid.md +39 -6
  372. package/kits/docs/evolcore/config.md +95 -1
  373. package/kits/docs/evolcore/ctl.md +2 -1
  374. package/kits/docs/evolcore/ec-capabilities.md +7 -10
  375. package/kits/docs/evolcore/ecweb-lifecycle.md +5 -1
  376. package/kits/docs/evolcore/event.md +1 -1
  377. package/kits/docs/evolcore/fs.md +49 -3
  378. package/kits/docs/evolcore/group.md +5 -4
  379. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  380. package/kits/docs/evolcore/memory-tags.md +2 -0
  381. package/kits/docs/evolcore/menu-client.md +3 -3
  382. package/kits/docs/evolcore/menu-protocol.md +31 -2
  383. package/kits/docs/evolcore/model.md +12 -1
  384. package/kits/docs/evolcore/msg.md +96 -36
  385. package/kits/docs/evolcore/pay.md +22 -0
  386. package/kits/docs/evolcore/plugin.md +74 -0
  387. package/kits/docs/evolcore/provider.md +29 -2
  388. package/kits/docs/evolcore/rpc.md +2 -2
  389. package/kits/docs/evolcore/services.md +46 -18
  390. package/kits/docs/evolcore/skill.md +17 -1
  391. package/kits/docs/evolcore/stats.md +5 -0
  392. package/kits/docs/evolcore/storage.md +22 -0
  393. package/kits/docs/evolcore/thread-chain.md +20 -9
  394. package/kits/docs/evolcore/tool-authorization.md +14 -0
  395. package/kits/docs/evolcore/trigger.md +89 -13
  396. package/kits/docs/identity/AID_PROFILE_SPEC.md +1 -1
  397. package/kits/docs/venues/feishu-group.md +3 -2
  398. package/kits/docs/venues/feishu-private.md +3 -2
  399. package/kits/rules/01-overview.md +11 -32
  400. package/kits/rules/02-navigation.md +20 -6
  401. package/kits/rules/06-channel.md +20 -4
  402. package/kits/schemas/_meta.json +42 -5
  403. package/kits/schemas/agent-config.schema.21.json +974 -0
  404. package/kits/schemas/agent-config.schema.22.json +977 -0
  405. package/kits/schemas/agent-config.schema.23.json +974 -0
  406. package/kits/schemas/agent-config.schema.24.json +986 -0
  407. package/kits/schemas/agent-config.schema.25.json +986 -0
  408. package/kits/schemas/daemon.schema.10.json +373 -0
  409. package/kits/schemas/daemon.schema.11.json +487 -0
  410. package/kits/schemas/daemon.schema.12.json +505 -0
  411. package/kits/schemas/daemon.schema.9.json +12 -0
  412. package/kits/schemas/defaults.schema.7.json +472 -0
  413. package/kits/schemas/defaults.schema.8.json +484 -0
  414. package/kits/schemas/providers.schema.1.json +1 -1
  415. package/kits/schemas/providers.schema.2.json +1 -1
  416. package/kits/schemas/providers.schema.3.json +26 -4
  417. package/kits/schemas/relation-config.schema.13.json +289 -0
  418. package/kits/skills/.switches.json +17 -1
  419. package/kits/skills/ability/SKILL.md +395 -33
  420. package/kits/skills/ability/STRUCTURE.md +338 -0
  421. package/kits/skills/ability/references/cli.md +208 -0
  422. package/kits/skills/ability/references/development.md +107 -37
  423. package/kits/skills/ability/references/management.md +106 -46
  424. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  425. package/kits/skills/agent-output-cards/SKILL.md +80 -37
  426. package/kits/skills/agent-output-cards/examples/html-surface.json +11 -0
  427. package/kits/skills/agent-output-cards/examples/meeting-followups.json +16 -0
  428. package/kits/skills/agent-output-cards/examples/meeting-latest.json +24 -0
  429. package/kits/skills/agent-output-cards/examples/project-metrics.json +16 -0
  430. package/kits/skills/agent-output-cards/examples/quick-links.json +18 -0
  431. package/kits/skills/agent-output-cards/examples/surface.html +8 -0
  432. package/kits/skills/agent-template-project/SKILL.md +51 -0
  433. package/kits/skills/agent-template-project/references/01-collect-and-pack.md +174 -0
  434. package/kits/skills/agent-template-project/references/02-upload-and-share.md +109 -0
  435. package/kits/skills/agent-template-project/references/03-download-and-install.md +189 -0
  436. package/kits/skills/agent-template-project/references/04-upgrade-and-recovery.md +74 -0
  437. package/kits/skills/agent-template-project/references/05-publish-to-platform.md +62 -0
  438. package/kits/skills/ec-group/SKILL.md +8 -6
  439. package/kits/skills/ec-group/TASK.md +186 -0
  440. package/kits/skills/ec-group/WORKLOG.md +180 -0
  441. package/kits/skills/ec-group-collaboration/SKILL.md +5 -5
  442. package/kits/skills/ec-identity/SKILL.md +9 -6
  443. package/kits/skills/ec-pay/SKILL.md +223 -0
  444. package/kits/skills/ec-provider/SKILL.md +6 -6
  445. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  446. package/kits/skills/ec-service-call/SKILL.md +138 -0
  447. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  448. package/kits/skills/ec-skill/SKILL.md +25 -9
  449. package/kits/skills/ec-skill/scripts/cli.mjs +7 -7
  450. package/kits/skills/ec-skill/scripts/skill.mjs +55 -41
  451. package/kits/skills/ec-skill/scripts/template/SKILL.md.tmpl +9 -0
  452. package/kits/skills/ec-trigger/SKILL.md +3 -3
  453. package/kits/skills/personal-assistant/SKILL.md +22 -22
  454. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +1 -1
  455. package/kits/skills/scrapling-article-fetch/SKILL.md +5 -5
  456. package/kits/skills/thread-ops/SKILL.md +19 -9
  457. package/kits/skills/wechat-article-media-download/SKILL.md +2 -2
  458. package/kits/skills/wechat-article-reader/SKILL.md +2 -2
  459. package/kits/templates/memory-consolidation/notes.md +2 -2
  460. package/kits/templates/memory-consolidation/workflow.md +46 -0
  461. package/kits/templates/system-fragments/channel.md +13 -4
  462. package/kits/templates/system-fragments/commands.md +5 -4
  463. package/kits/templates/system-fragments/personal-assistant.md +2 -2
  464. package/kits/templates/system-fragments/reply.md +15 -9
  465. package/kits/templates/system-fragments/session.md +2 -2
  466. package/kits/templates/system-fragments/thread.md +30 -127
  467. package/kits/templates/system-fragments/venue.md +16 -0
  468. package/package.json +7 -7
  469. package/scripts/agent-template/index.mjs +7 -1
  470. package/scripts/agent-template/inspect.mjs +99 -39
  471. package/scripts/agent-template/overlay.mjs +126 -2
  472. package/scripts/agent-template/shared/common.mjs +49 -5
  473. package/scripts/agent-template/shared/plan.mjs +4 -2
  474. package/scripts/agent-template/shared/service-packs.mjs +104 -0
  475. package/scripts/agent-template/shared/team-schema.json +468 -39
  476. package/scripts/agent-template/shared/template-contract.mjs +93 -51
  477. package/scripts/agent-template/shared/template-package.mjs +225 -44
  478. package/scripts/agent-template/shared/template-runtime.mjs +137 -15
  479. package/scripts/agent-template/shared/template.mjs +31 -8
  480. package/scripts/agent-template/team-pack.mjs +528 -56
  481. package/scripts/agent-template/team-preview.mjs +102 -9
  482. package/scripts/aid-batch/identity-batch.mjs +1 -1
  483. package/dist/agents/baseagent-availability.js +0 -152
  484. package/dist/agents/baseagent.js +0 -750
  485. package/dist/agents/codex/catalog.js +0 -80
  486. package/dist/agents/ecagent-plugin-lazy.js +0 -41
  487. package/dist/agents/tool-time-context.js +0 -55
  488. package/dist/core/legacy-rename.js +0 -41
  489. package/dist/core/plugin-lifecycle.js +0 -137
  490. package/dist/core/rate-window.js +0 -53
  491. package/dist/core/runner-reload-transaction.js +0 -60
  492. package/dist/core/runtime-lock.js +0 -90
  493. package/dist/core/soul.js +0 -66
  494. package/dist/core/system-session/grants.js +0 -40
  495. package/dist/directory/owner-directory-agentmd-sync.js +0 -89
  496. package/dist/directory/owner-directory-request-operation.js +0 -79
  497. package/dist/directory/owner-directory-text.js +0 -60
  498. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  499. package/kits/docs/evolcore/ability.md +0 -185
  500. package/kits/skills/ability/references/calling.md +0 -56
  501. package/kits/skills/ability/references/contract-checklist.md +0 -37
  502. package/kits/skills/ability/references/recovery.md +0 -27
  503. /package/dist/{core/capability/providers/gemini-capability-provider.js → agents/gemini/capability-provider.js} +0 -0
  504. /package/dist/core/{system-channels.js → channel/system-channels.js} +0 -0
  505. /package/dist/core/{daemon-file-cache.js → daemon/daemon-file-cache.js} +0 -0
  506. /package/dist/core/{event-bus.js → event/event-bus.js} +0 -0
  507. /package/dist/core/{event-catalog.js → event/event-catalog.js} +0 -0
  508. /package/dist/core/{pack-ledger.js → pack/pack-ledger.js} +0 -0
  509. /package/dist/directory/{owner-directory-identity.js → identity.js} +0 -0
  510. /package/dist/directory/{owner-directory-policy.js → policy.js} +0 -0
  511. /package/dist/directory/{owner-directory-remarks.js → remarks.js} +0 -0
  512. /package/dist/directory/{owner-directory-scope.js → scope.js} +0 -0
  513. /package/dist/{contracts → ecweb/contracts}/ecweb-instance.js +0 -0
  514. /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
+ }