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
@@ -1,50 +1,54 @@
1
- import { assertRunnerModelAllowed, getRunnerCatalog, catalogEfforts, assertCatalogSelectable } from '../core/model/model-catalog.js';
1
+ import { getCodexAppServerAvailabilityAsync } from './availability.js';
2
+ export { MIN_CODEX_CLI_VERSION, parseCodexCliVersion, isCodexCliVersionSupported, getCodexCliVersion, getCodexAppServerAvailability, isCodexAppServerAvailable, invalidateCodexAppServerAvailabilityCache, getCodexAppServerAvailabilityAsync } from './availability.js';
3
+ import { assertRunnerModelAllowed, getRunnerCatalog, catalogEfforts, assertCatalogSelectable } from '../../core/model/model-catalog.js';
2
4
  // Codex/OpenAI API 不认识 Claude Code SDK 的窗口后缀,必须传入基础模型 ID。
3
- import { parseModelId, stripContextWindowSuffix } from '../core/model/context-window-suffix.js';
4
- import { EVOLCORE_AUTO_COMPACT_WINDOW_TOKENS, evolcoreAutoCompactTokens } from '../core/model/model-capabilities.js';
5
- import { formatAsyncQuestionAnswer, hasTrustedFullAccessContext, parseAsyncUserQuestions, unsettledInterruptError, withInterruptDeadline } from './runner-types.js';
6
- import { requestDangerousCommandPermissionResult } from '../core/permission/approval-gateway.js';
7
- import { permissionFailureResult } from '../core/permission/permission-result.js';
8
- import { checkReadonly, checkDangerousCommand, evaluateToolPreflight } from '../core/permission/tool-policy.js';
9
- import { isShellToolName, normalizeFileMutation } from '../core/permission/tool-canonical.js';
10
- import { normalizeExecutionPermissionMode, normalizePermissionMode, resolvePhaseOneExecutionSandbox } from '../core/permission/mode.js';
11
- import { assertWindowsCodexFilesystemRuleBudget, buildCodexProtectedFilesystemRules, compactCodexLinuxFilesystemRules, getExistingRelationAttachmentDirs, isSameOrDescendant, resolveProtectedCandidate, } from '../core/permission/protected-paths.js';
12
- import { CODEX_THREAD_ACTIVE_WRITER, CodexAppServerClient, } from './codex/app-server-client.js';
13
- import { getSandboxInitializationFailureCounters, isNestedSandboxInitializationFailure, recordSandboxInitializationFailure, SANDBOX_INITIALIZATION_FAILED, } from '../core/permission/sandbox-runtime.js';
14
- import { resolveOpenaiConfig, resolveRuntimeBaseagentModelSelection, resolveCodexCliPath, resolveCodexPowerShellShimPath, } from './baseagent.js';
15
- import { logger } from '../utils/logger.js';
16
- import { resolveProviderService } from '../config/providers.js';
17
- import { catalogHash } from '../core/model/catalog-service.js';
18
- import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
19
- import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
20
- import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../utils/error-utils.js';
21
- import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../stats/model-resolver.js';
22
- import { renderActionAsText } from '../core/interaction-router.js';
23
- import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from '../core/message/message-utils.js';
24
- import { resolveCodexCapabilityThreadConfigForProject } from '../core/capability/capability-manager.js';
25
- import { resolveEffective } from '../config/config-manager.js';
26
- import { AGENT_DELEGATION_TOKEN_ENV, CODEX_SESSION_TOKEN_ENV, hashDelegatedCommandArgv, hashDelegatedCommandSpec, parseDelegatedExecutionSpec, } from '../core/auth/agent-delegation.js';
27
- import { sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
28
- import { classifyEvolcoreShellCommand, canonicalizeEvolcoreCommandArgv, literalShellParseRemedy, containsLiteralManagedTmpDirOutsideSendContent, containsUnresolvedManagedTmpDirReference, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCanonicalEvolcoreToolInput, serializeCanonicalEvolcoreExecutionSpec, } from '../core/permission/ec-command-parser.js';
29
- import { compareVersions } from '../utils/npm-ops.js';
30
- import { agentCodexTokenPath, getPackageRoot, resolvePaths, resolveRoot } from '../paths.js';
31
- import { CODEX_HOOK_TOKEN_ENV, MAIN_CLI_BIN } from '../product.js';
32
- import { ensureSessionRuntimeDir, ensureSessionRuntimeDirAsync, getManagedTaskTempDir } from '../cli/task-context.js';
33
- import { buildTranscriptTurns } from '../core/session/session-transcript.js';
34
- import { CodexSessionFileAdapter } from '../core/session/adapters/codex-session-file-adapter.js';
35
- import { readSessionHistoryBackward } from '../core/session/session-fs-store.js';
36
- import { repairCodexSessionProvider } from '../core/session/session-file-health.js';
5
+ import { parseModelId, stripContextWindowSuffix } from '../../core/model/context-window-suffix.js';
6
+ import { CODEX_FALLBACK_CONTEXT_TOKENS, readAgentCompactThreshold, resolveAgentContextPolicy } from '../../core/model/model-capabilities.js';
7
+ import { formatAsyncQuestionAnswer, hasTrustedFullAccessContext, parseAsyncUserQuestions, unsettledInterruptError, withInterruptDeadline } from '../../core/baseagent/runner-types.js';
8
+ import { requestDangerousCommandPermissionResult } from '../../core/permission/approval-gateway.js';
9
+ import { permissionFailureResult } from '../../core/permission/permission-result.js';
10
+ import { checkReadonly, checkDangerousCommand, evaluateToolPreflight } from '../../core/permission/tool-policy.js';
11
+ import { isShellToolName, normalizeFileMutation } from '../../core/permission/tool-canonical.js';
12
+ import { normalizeExecutionPermissionMode, normalizePermissionMode, resolvePhaseOneExecutionSandbox } from '../../core/permission/mode.js';
13
+ import { assertWindowsCodexFilesystemRuleBudget, buildCodexProtectedFilesystemRules, compactCodexLinuxFilesystemRules, getExistingCodexProjectSkillRoots, getExistingRelationAttachmentDirs, getExistingSelfAttachmentDirs, isSameOrDescendant, resolveProtectedCandidate, } from '../../core/permission/protected-paths.js';
14
+ import { CODEX_THREAD_ACTIVE_WRITER, CodexAppServerClient, } from './app-server-client.js';
15
+ import { getSandboxInitializationFailureCounters, isNestedSandboxInitializationFailure, recordSandboxInitializationFailure, SANDBOX_INITIALIZATION_FAILED, } from '../../core/permission/sandbox-runtime.js';
16
+ import { resolveOpenaiConfig } from './index.js';
17
+ import { resolveRuntimeBaseagentModelSelection } from '../../core/baseagent/baseagent.js';
18
+ import { logger } from '../../utils/logger.js';
19
+ import { resolveProviderService } from '../../config/providers.js';
20
+ import { catalogHash } from '../../core/model/catalog-service.js';
21
+ import { summarizeToolInputForAudit } from '../../utils/tool-summary.js';
22
+ import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../../core/auth/authorization-audit.js';
23
+ import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../../utils/error-utils.js';
24
+ import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../../stats/model-resolver.js';
25
+ import { renderActionAsText } from '../../core/message/interaction-router.js';
26
+ import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from '../../core/message/message-utils.js';
27
+ import { isBaseagentSkillsEnabled, resolveCodexCapabilityThreadConfigForProject } from '../../core/capability/capability-manager.js';
28
+ import { resolveEffective } from '../../config/config-manager.js';
29
+ import { AGENT_DELEGATION_TOKEN_ENV, CODEX_SESSION_TOKEN_ENV, hashDelegatedCommandArgv, hashDelegatedCommandSpec, parseDelegatedExecutionSpec, } from '../../core/auth/agent-delegation.js';
30
+ import { sanitizeShellExecutionEnvironment } from '../../core/permission/shell-environment.js';
31
+ import { classifyEvolcoreShellCommand, canonicalizeEvolcoreCommandArgv, literalShellParseRemedy, containsLiteralManagedTmpDirOutsideSendContent, containsUnresolvedManagedTmpDirReference, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCanonicalEvolcoreToolInput, serializeCanonicalEvolcoreExecutionSpec, } from '../../core/permission/ec-command-parser.js';
32
+ import { agentCodexTokenPath, getPackageRoot, resolvePaths, resolveRoot } from '../../paths.js';
33
+ import { CODEX_HOOK_TOKEN_ENV, MAIN_CLI_BIN } from '../../product.js';
34
+ import { ensureSessionRuntimeDir, ensureSessionRuntimeDirAsync, getManagedTaskTempDir } from '../../cli/task-context.js';
35
+ import { buildTranscriptTurns } from '../../core/session/session-transcript.js';
36
+ import { CodexSessionFileAdapter, repairCodexSessionProvider } from './session-file-adapter.js';
37
+ import { readSessionHistoryBackward } from '../../core/session/session-fs-store.js';
38
+ import { resolveRunInference } from '../../core/baseagent/runner-types.js';
37
39
  import { execFileSync } from 'child_process';
38
- import { probeCli, probeCliSync, CODEX_CLI_PROBE_TIMEOUT_MS, CODEX_CLI_PROBE_RETRY_TIMEOUT_MS } from '../utils/cross-platform.js';
39
40
  import { createHash, randomBytes } from 'crypto';
40
- import { buildModelRequestHeaders } from './request-identity.js';
41
- import { extractStructuredToolErrorMarker, normalizeToolErrorClassification, normalizeToolErrorCode, normalizeToolErrorDetailCode, } from '../core/permission/tool-error-code.js';
41
+ import { buildModelRequestHeaders } from '../../core/inference/request-identity.js';
42
+ import { extractStructuredToolErrorMarker, normalizeToolErrorClassification, normalizeToolErrorCode, normalizeToolErrorDetailCode, } from '../../core/permission/tool-error-code.js';
42
43
  import fs from 'fs';
43
- import { assertOwnershipAuthorization } from '../core/ownership/owner-resolver.js';
44
+ import { assertOwnershipAuthorization } from '../../core/ownership/owner-resolver.js';
44
45
  import path from 'path';
45
46
  import os from 'os';
47
+ import { cancelledMcpElicitation, collectMcpConfirmation, parseMcpConfirmation } from './mcp-elicitation.js';
46
48
  const APPROVAL_LOG_SUMMARY_MAX_LENGTH = 256;
47
49
  const CODEX_INTERRUPT_TIMEOUT_MS = 5_000;
50
+ const CODEX_STARTUP_SETTLE_TIMEOUT_MS = 10_000;
51
+ const CODEX_THREAD_OPEN_TIMEOUT_MS = 60_000;
48
52
  function toAgentErrorType(message) {
49
53
  // Forgetting the provider thread is the only remedy for a missing model.
50
54
  // classifyError must keep returning MODEL_UNAVAILABLE for it, but the runner
@@ -201,6 +205,19 @@ function waitForCodexOperation(operation, signal) {
201
205
  onAbort();
202
206
  });
203
207
  }
208
+ async function waitForCodexDelay(ms, signal) {
209
+ let timer;
210
+ try {
211
+ await waitForCodexOperation(new Promise(resolve => {
212
+ timer = setTimeout(resolve, ms);
213
+ timer.unref?.();
214
+ }), signal);
215
+ }
216
+ finally {
217
+ if (timer)
218
+ clearTimeout(timer);
219
+ }
220
+ }
204
221
  function isCodexReasoningNotification(method) {
205
222
  return method === 'item/reasoning/textDelta'
206
223
  || method === 'item/reasoning/summaryTextDelta'
@@ -213,7 +230,7 @@ const CODEX_THREAD_HANDOFF_TIMEOUT_MS = 2_000;
213
230
  * "already has an active writer"; retrying the resume — never the input — is safe
214
231
  * because the failed turn consumed nothing.
215
232
  */
216
- const CODEX_RESUME_WRITER_RETRY_DELAYS_MS = [150, 500, 1_000];
233
+ const CODEX_THREAD_WRITER_RETRY_DELAYS_MS = [500, 1_000, 3_000];
217
234
  function stableSecurityValue(value) {
218
235
  if (value === undefined)
219
236
  return 'undefined';
@@ -296,166 +313,6 @@ function isCodexActiveWriterError(error) {
296
313
  return error?.code === CODEX_THREAD_ACTIVE_WRITER
297
314
  || CODEX_ACTIVE_WRITER_RE.test(error instanceof Error ? error.message : String(error));
298
315
  }
299
- // The permission bridge is version-locked to the audited approval schema and
300
- // managed PreToolUse hook behavior used by proactive first-tool enforcement.
301
- export const MIN_CODEX_CLI_VERSION = '0.144.1';
302
- export function parseCodexCliVersion(output) {
303
- const match = output.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/);
304
- return match?.[1] ?? null;
305
- }
306
- export function isCodexCliVersionSupported(version) {
307
- return compareVersions(version, MIN_CODEX_CLI_VERSION) >= 0;
308
- }
309
- function compactCodexProbeText(value, maxLength = 600) {
310
- if (Buffer.isBuffer(value))
311
- value = value.toString('utf-8');
312
- if (typeof value !== 'string')
313
- return undefined;
314
- const text = value.replace(/\s+/gu, ' ').trim();
315
- return text.length <= maxLength ? text : `${text.slice(0, maxLength - 3).trimEnd()}...`;
316
- }
317
- function logCodexProbeFailure(args, startedAt, error, timeoutMs, launch) {
318
- const detail = error;
319
- logger.warn(`[CodexProbe] CLI probe failed: ${JSON.stringify({
320
- command: ['codex', ...args],
321
- resolvedPath: launch?.resolvedPath ?? null,
322
- launcherKind: launch?.launcherKind ?? null,
323
- launcherPath: launch?.launcherPath ?? null,
324
- path: detail?.path ?? null,
325
- spawnargs: detail?.spawnargs ?? null,
326
- elapsedMs: Date.now() - startedAt,
327
- timeoutMs,
328
- code: detail?.code ?? null,
329
- status: detail?.status ?? null,
330
- signal: detail?.signal ?? null,
331
- timedOut: detail?.code === 'ETIMEDOUT',
332
- message: compactCodexProbeText(detail?.message ?? String(error)),
333
- stdout: compactCodexProbeText(detail?.stdout),
334
- stderr: compactCodexProbeText(detail?.stderr),
335
- })}`);
336
- }
337
- function probeCodexCli(args, executable) {
338
- return probeCliSync('codex', args, {
339
- executable, onFailure: logCodexProbeFailure,
340
- validateOutput: args[0] === '--version' ? output => parseCodexCliVersion(output) !== null : undefined,
341
- });
342
- }
343
- export function getCodexCliVersion(executable) {
344
- try {
345
- return parseCodexCliVersion(probeCodexCli(['--version'], executable));
346
- }
347
- catch {
348
- return null;
349
- }
350
- }
351
- export function getCodexAppServerAvailability() {
352
- const cliPath = resolveCodexCliPath();
353
- if (!cliPath) {
354
- const powershellShim = resolveCodexPowerShellShimPath();
355
- return {
356
- available: false,
357
- reason: powershellShim
358
- ? '检测到 codex.ps1,但当前 Windows 启动路径要求 codex.exe/codex.cmd/codex.bat;请重新安装 @openai/codex 以恢复 npm shim。'
359
- : '未检测到 Codex CLI。',
360
- };
361
- }
362
- const version = getCodexCliVersion(cliPath);
363
- if (!version) {
364
- return { available: false, reason: '无法读取 Codex CLI 版本。' };
365
- }
366
- if (!isCodexCliVersionSupported(version)) {
367
- return {
368
- available: false,
369
- version,
370
- reason: `Codex CLI ${version} 低于最低要求 ${MIN_CODEX_CLI_VERSION}。请升级 Codex CLI:npm install -g @openai/codex@latest`,
371
- requiresUpgrade: true,
372
- };
373
- }
374
- try {
375
- probeCodexCli(['app-server', '--help'], cliPath);
376
- return { available: true, version };
377
- }
378
- catch (error) {
379
- if (error?.code === 'ETIMEDOUT') {
380
- return { available: false, version, reason: `Codex CLI ${version} 的 app-server 探测超时,请稍后重试。` };
381
- }
382
- return { available: false, version, reason: `Codex CLI ${version} 的 app-server 探测失败,请检查 CLI 启动日志。` };
383
- }
384
- }
385
- export function isCodexAppServerAvailable() {
386
- return getCodexAppServerAvailability().available;
387
- }
388
- /**
389
- * 启动期可用性探测结果缓存。
390
- *
391
- * 每次探测是一次完整的 Codex CLI 启动(Windows 上 0.3-0.45s)。启动时每个 codex
392
- * agent 都会调一次(21 个 agent 就是 21 次进程启动),并行创建 runner 后会同时抢
393
- * CPU,反而更慢。这里缓存整个探测的 Promise:并发调用共享同一轮探测,失败结果也
394
- * 缓存,避免热加载反复重试。
395
- *
396
- * 用 TTL 而不是永久缓存:用户可能在 daemon 运行期间升级 Codex CLI,过期的失败结论
397
- * 不应永久黏住。
398
- */
399
- const CODEX_AVAILABILITY_CACHE_TTL_MS = 60_000;
400
- let codexAvailabilityCache = null;
401
- /** 让测试与显式刷新(例如安装 Codex 后)能清掉缓存。 */
402
- export function invalidateCodexAppServerAvailabilityCache() {
403
- codexAvailabilityCache = null;
404
- }
405
- /** Daemon startup/hot reload use asynchronous probes; sync CLI callers share the cache. */
406
- export async function getCodexAppServerAvailabilityAsync() {
407
- const now = Date.now();
408
- if (codexAvailabilityCache && now - codexAvailabilityCache.at < CODEX_AVAILABILITY_CACHE_TTL_MS) {
409
- return codexAvailabilityCache.promise;
410
- }
411
- const promise = probeCodexAppServerAvailabilityAsync();
412
- codexAvailabilityCache = { at: now, promise };
413
- // 失败的 Promise 同样要能被后续调用复用,但不能产生未处理拒绝。
414
- promise.catch(() => { });
415
- return promise;
416
- }
417
- async function probeCodexAppServerAvailabilityAsync() {
418
- const cliPath = resolveCodexCliPath();
419
- const options = {
420
- timeouts: [CODEX_CLI_PROBE_TIMEOUT_MS, CODEX_CLI_PROBE_RETRY_TIMEOUT_MS],
421
- executable: cliPath ?? undefined,
422
- onFailure: logCodexProbeFailure,
423
- };
424
- if (!cliPath) {
425
- const powershellShim = resolveCodexPowerShellShimPath();
426
- return {
427
- available: false,
428
- reason: powershellShim
429
- ? '检测到 codex.ps1,但当前 Windows 启动路径要求 codex.exe/codex.cmd/codex.bat;请重新安装 @openai/codex 以恢复 npm shim。'
430
- : '未检测到 Codex CLI。',
431
- };
432
- }
433
- let version;
434
- try {
435
- // Each probe is a full Codex CLI launch (~0.3-0.45s on Windows). Run the
436
- // app-server probe concurrently; its result is only consulted after the
437
- // version gate passes, so the decision order is unchanged.
438
- const appServerProbe = probeCli('codex', ['app-server', '--help'], options);
439
- appServerProbe.catch(() => { });
440
- version = parseCodexCliVersion(await probeCli('codex', ['--version'], {
441
- ...options, validateOutput: output => parseCodexCliVersion(output) !== null,
442
- })) ?? undefined;
443
- if (!version)
444
- return { available: false, reason: '无法读取 Codex CLI 版本。' };
445
- if (!isCodexCliVersionSupported(version)) {
446
- return { available: false, version, requiresUpgrade: true,
447
- reason: `Codex CLI ${version} 低于最低要求 ${MIN_CODEX_CLI_VERSION}。请升级 Codex CLI:npm install -g @openai/codex@latest` };
448
- }
449
- await appServerProbe;
450
- return { available: true, version };
451
- }
452
- catch (error) {
453
- const detail = error;
454
- return { available: false, version, reason: detail.code === 'ETIMEDOUT' || detail.killed
455
- ? 'Codex CLI 探测超时,请稍后重试。'
456
- : `Codex CLI 探测失败:${error instanceof Error ? error.message : String(error)}` };
457
- }
458
- }
459
316
  export class CodexRunner {
460
317
  name = 'codex';
461
318
  // turn/start persists a new user turn before runQuery resolves. App-server
@@ -481,6 +338,7 @@ export class CodexRunner {
481
338
  threadExternalToolFingerprints = new Map();
482
339
  threadExternalToolBoundaries = new Map();
483
340
  trackedApprovalItems = new Map();
341
+ pendingMcpElicitations = new Map();
484
342
  pendingToolDenials = new Map();
485
343
  registeredSafeOutputCalls = new Map();
486
344
  pendingInterrupts = new Map();
@@ -496,6 +354,9 @@ export class CodexRunner {
496
354
  appServerClient = null;
497
355
  /** Trusted fullaccess calls use a separate unmasked app-server process. */
498
356
  fullAccessAppServerClient = null;
357
+ /** Executing sessions never share a process; metadata queries use the clients above. */
358
+ sessionAppServerClients = new Map();
359
+ appServerSessionOwners = new WeakMap();
499
360
  retiredProviderClients = new Set();
500
361
  providerClientRevisions = new WeakMap();
501
362
  onSessionIdUpdate;
@@ -536,7 +397,6 @@ export class CodexRunner {
536
397
  });
537
398
  this.capabilities = {
538
399
  taskRecovery: true,
539
- clear: false,
540
400
  compact: true,
541
401
  fork: true,
542
402
  forkAtTurn: true,
@@ -555,15 +415,17 @@ export class CodexRunner {
555
415
  this.onSessionIdUpdate = callbacks.onSessionIdUpdate;
556
416
  this.codexVersion = runtime?.codexVersion;
557
417
  }
558
- getAppServerClient(fullAccess = false, providerOverride) {
559
- const existing = fullAccess ? this.fullAccessAppServerClient : this.appServerClient;
418
+ getAppServerClient(fullAccess = false, providerOverride, sessionId) {
419
+ const sessionClientKey = sessionId ? JSON.stringify([sessionId, fullAccess]) : undefined;
420
+ const existing = sessionClientKey ? this.sessionAppServerClients.get(sessionClientKey)
421
+ : fullAccess ? this.fullAccessAppServerClient : this.appServerClient;
560
422
  const connection = this.currentProviderConfig(providerOverride);
561
423
  const revision = connection.providerId ? catalogHash({
562
424
  providerId: connection.providerId,
563
425
  baseUrl: connection.baseUrl, apiKey: connection.apiKey,
564
426
  headers: connection.headers, queryParams: connection.queryParams,
565
427
  }) : undefined;
566
- if (existing && (!revision || this.providerClientRevisions.get(existing) === revision))
428
+ if (existing && !existing.isClosed() && (!revision || this.providerClientRevisions.get(existing) === revision))
567
429
  return existing;
568
430
  if (existing)
569
431
  this.retiredProviderClients.add(existing);
@@ -605,7 +467,11 @@ export class CodexRunner {
605
467
  this.threadSubscriptions.set(threadId, { client, state: 'unsubscribed' });
606
468
  }
607
469
  });
608
- if (fullAccess) {
470
+ if (sessionClientKey) {
471
+ this.sessionAppServerClients.set(sessionClientKey, client);
472
+ this.appServerSessionOwners.set(client, sessionId);
473
+ }
474
+ else if (fullAccess) {
609
475
  this.fullAccessAppServerClient = client;
610
476
  }
611
477
  else {
@@ -633,7 +499,32 @@ export class CodexRunner {
633
499
  if (subscribed)
634
500
  return subscribed.client;
635
501
  const sessionId = this.findSessionKeyByThread(threadId);
636
- return this.getAppServerClient(sessionId ? this.chatModes.get(sessionId) === 'fullaccess' : false);
502
+ return this.getAppServerClient(sessionId ? this.chatModes.get(sessionId) === 'fullaccess' : false, undefined, sessionId);
503
+ }
504
+ async reclaimSessionClient(sessionId, client) {
505
+ if (this.appServerSessionOwners.get(client) !== sessionId)
506
+ throw unsettledInterruptError('Codex 运行态回收');
507
+ logger.warn(`[CodexRunner] Reclaiming session runtime: ${JSON.stringify({ sessionId, ...client.getDiagnosticContext() })}`);
508
+ const clients = new Set([client, ...this.sessionAppServerClients.values(), ...this.retiredProviderClients]
509
+ .filter(candidate => this.appServerSessionOwners.get(candidate) === sessionId));
510
+ await Promise.all([...clients].map(candidate => candidate.close()));
511
+ for (const [key, cached] of this.sessionAppServerClients) {
512
+ if (clients.has(cached))
513
+ this.sessionAppServerClients.delete(key);
514
+ }
515
+ for (const retired of clients)
516
+ this.retiredProviderClients.delete(retired);
517
+ for (const [threadId, subscription] of this.threadSubscriptions) {
518
+ if (!clients.has(subscription.client))
519
+ continue;
520
+ this.threadSubscriptions.delete(threadId);
521
+ this.unbindExternalToolBoundary(threadId);
522
+ }
523
+ for (const record of [...this.unconfirmedInterrupts.values()]) {
524
+ if (clients.has(record.client))
525
+ record.confirm('app-server:process-exited');
526
+ }
527
+ logger.info(`[CodexRunner] Session runtime reclaimed; persisted backend retained: session=${sessionId}`);
637
528
  }
638
529
  markThreadSubscribed(client, threadId) {
639
530
  const existing = this.threadSubscriptions.get(threadId);
@@ -662,12 +553,21 @@ export class CodexRunner {
662
553
  let releasePromise;
663
554
  releasePromise = Promise.resolve().then(async () => {
664
555
  let released = false;
556
+ const startedAt = Date.now();
665
557
  try {
558
+ const interrupts = [...this.unconfirmedInterrupts.values()]
559
+ .filter(record => record.threadId === threadId && record.client === client);
560
+ if (interrupts.length) {
561
+ logger.info(`[CodexRunner] Waiting for turn termination before unsubscribe: thread=${threadId} reason=${reason}`);
562
+ await withInterruptDeadline(Promise.all(interrupts.map(record => record.settled)), 'Codex termination before unsubscribe', CODEX_INTERRUPT_TIMEOUT_MS);
563
+ }
666
564
  const unsubscribe = client.threadUnsubscribe;
565
+ let status;
667
566
  if (typeof unsubscribe === 'function') {
668
567
  if (options.waitForClose && typeof client.threadUnsubscribeAndWait === 'function') {
669
568
  try {
670
- await client.threadUnsubscribeAndWait.call(client, threadId, options.timeoutMs ?? CODEX_THREAD_HANDOFF_TIMEOUT_MS);
569
+ const response = await client.threadUnsubscribeAndWait.call(client, threadId, options.timeoutMs ?? CODEX_THREAD_HANDOFF_TIMEOUT_MS);
570
+ status = response?.status;
671
571
  }
672
572
  catch (error) {
673
573
  // The unsubscribe RPC has already succeeded when this is a
@@ -675,15 +575,15 @@ export class CodexRunner {
675
575
  // target resume decide whether the archive fallback is needed.
676
576
  if (error?.code !== 'CODEX_THREAD_CLOSE_TIMEOUT')
677
577
  throw error;
678
- logger.debug(`[CodexRunner] thread/closed not observed before handoff timeout: `
578
+ logger.info(`[CodexRunner] thread/closed not observed before handoff timeout: `
679
579
  + `thread=${threadId} reason=${reason}`);
680
580
  }
681
581
  }
682
582
  else {
683
- await unsubscribe.call(client, threadId);
583
+ status = (await unsubscribe.call(client, threadId))?.status;
684
584
  }
685
585
  }
686
- logger.debug(`[CodexRunner] Released thread subscription: thread=${threadId} reason=${reason}`);
586
+ logger.info(`[CodexRunner] Thread unsubscribe acknowledged: thread=${threadId} reason=${reason} status=${String(status ?? 'unknown')} waitForClose=${!!options.waitForClose} durationMs=${Date.now() - startedAt}`);
687
587
  released = true;
688
588
  return true;
689
589
  }
@@ -711,61 +611,81 @@ export class CodexRunner {
711
611
  });
712
612
  return await releasePromise;
713
613
  }
714
- /**
715
- * Resume a thread whose previous writer may still be releasing. Unlike the
716
- * cross-client handoff, this only covers the same connection: the owner is
717
- * unsubscribed (and awaited) once before the bounded retries, and any other
718
- * active-writer rejection is released to the caller unchanged.
719
- */
720
- async resumeThreadAllowingWriterRelease(appServer, threadId, projectPath, threadOptions, previousAppServer) {
721
- try {
722
- return await appServer.threadResume(threadId, projectPath, threadOptions);
723
- }
724
- catch (error) {
725
- if (!isCodexActiveWriterError(error) || (previousAppServer && previousAppServer !== appServer))
726
- throw error;
727
- }
728
- const subscription = this.threadSubscriptions.get(threadId);
729
- if (subscription?.client === appServer && subscription.state === 'subscribed') {
730
- await this.releaseThreadSubscription(appServer, threadId, 'writer-release-wait', {
731
- waitForClose: true,
732
- timeoutMs: CODEX_THREAD_HANDOFF_TIMEOUT_MS,
733
- });
734
- }
735
- for (const delayMs of CODEX_RESUME_WRITER_RETRY_DELAYS_MS) {
736
- await new Promise(resolve => {
737
- const timer = setTimeout(resolve, delayMs);
738
- timer.unref?.();
739
- });
614
+ async retryThreadWriterOperation(threadId, operation, attempt, shouldRetry = isCodexActiveWriterError) {
615
+ for (let attemptIndex = 0;; attemptIndex++) {
740
616
  try {
741
- return await appServer.threadResume(threadId, projectPath, threadOptions);
617
+ return await attempt();
742
618
  }
743
619
  catch (error) {
744
- if (!isCodexActiveWriterError(error))
620
+ const delayMs = CODEX_THREAD_WRITER_RETRY_DELAYS_MS[attemptIndex];
621
+ if (delayMs === undefined || !shouldRetry(error))
745
622
  throw error;
746
- logger.warn(`[CodexRunner] Thread writer still active after ${delayMs}ms: thread=${threadId}`);
623
+ logger.warn(`[CodexRunner] Thread writer ${operation} retry in ${delayMs}ms: thread=${threadId} `
624
+ + `error=${error instanceof Error ? error.message : String(error)}`);
625
+ await new Promise(resolve => {
626
+ const timer = setTimeout(resolve, delayMs);
627
+ timer.unref?.();
628
+ });
747
629
  }
748
630
  }
749
- return await appServer.threadResume(threadId, projectPath, threadOptions);
750
631
  }
751
- async prepareThreadSubscription(client, threadId) {
632
+ /** With a known owner, active-writer rejection goes to the verified handoff. */
633
+ async resumeThreadAllowingWriterRelease(appServer, threadId, projectPath, threadOptions, previousAppServer, signal) {
634
+ let releaseAttempted = false;
635
+ const shouldRetry = (error) => isCodexActiveWriterError(error) && !previousAppServer;
636
+ return await this.retryThreadWriterOperation(threadId, 'resume', async () => {
637
+ signal?.throwIfAborted();
638
+ try {
639
+ return await appServer.threadResume(threadId, projectPath, threadOptions);
640
+ }
641
+ catch (error) {
642
+ signal?.throwIfAborted();
643
+ if (!releaseAttempted && shouldRetry(error)) {
644
+ releaseAttempted = true;
645
+ const subscription = this.threadSubscriptions.get(threadId);
646
+ if (subscription?.client === appServer && subscription.state === 'subscribed') {
647
+ await this.releaseThreadSubscription(appServer, threadId, 'writer-release-wait', {
648
+ waitForClose: true,
649
+ timeoutMs: CODEX_THREAD_HANDOFF_TIMEOUT_MS,
650
+ });
651
+ }
652
+ }
653
+ throw error;
654
+ }
655
+ }, shouldRetry);
656
+ }
657
+ async prepareThreadSubscription(client, threadId, signal) {
658
+ signal?.throwIfAborted();
752
659
  const existing = this.threadSubscriptions.get(threadId);
753
660
  if (!existing)
754
661
  return undefined;
755
- if (existing.client === client) {
756
- if (existing.release)
757
- await existing.release.catch(() => undefined);
662
+ if (existing.client.isRunning?.() === false) {
663
+ this.threadSubscriptions.delete(threadId);
758
664
  return undefined;
759
665
  }
760
- if (existing.state === 'subscribed') {
761
- const released = await this.releaseThreadSubscription(existing.client, threadId, 'mode-handoff', {
762
- waitForClose: true,
763
- timeoutMs: CODEX_THREAD_HANDOFF_TIMEOUT_MS,
666
+ if (existing.release)
667
+ await existing.release;
668
+ signal?.throwIfAborted();
669
+ if (this.threadSubscriptions.get(threadId)?.state === 'subscribed') {
670
+ await this.retryThreadWriterOperation(threadId, 'release', async () => {
671
+ signal?.throwIfAborted();
672
+ const released = await this.releaseThreadSubscription(existing.client, threadId, 'resume-handoff', {
673
+ waitForClose: true,
674
+ timeoutMs: CODEX_THREAD_HANDOFF_TIMEOUT_MS,
675
+ });
676
+ if (!released) {
677
+ const error = new Error(`Codex thread ${threadId} is still owned by another app-server connection`);
678
+ error.code = CODEX_THREAD_ACTIVE_WRITER;
679
+ throw error;
680
+ }
764
681
  });
765
- if (!released) {
766
- const error = new Error(`Codex thread ${threadId} is still owned by another app-server connection`);
767
- error.code = CODEX_THREAD_ACTIVE_WRITER;
768
- throw error;
682
+ }
683
+ if (typeof existing.client.threadLoadedList === 'function') {
684
+ const loaded = await existing.client.threadLoadedList();
685
+ signal?.throwIfAborted();
686
+ logger.info(`[CodexRunner] Writer handoff inspection: thread=${threadId} sameClient=${existing.client === client} loaded=${loaded.data.includes(threadId)}`);
687
+ if (loaded.data.includes(threadId)) {
688
+ await this.archiveThreadForHandoff(existing.client, client, threadId, signal);
769
689
  }
770
690
  }
771
691
  return existing.client;
@@ -809,7 +729,7 @@ export class CodexRunner {
809
729
  if ((await owner.threadLoadedList()).data.includes(threadId)) {
810
730
  // Codex can keep an unsubscribed writer alive. Its per-thread archive
811
731
  // tears down that runtime synchronously; unarchive preserves the UUID.
812
- await this.archiveThreadForHandoff(owner, owner, threadId);
732
+ await this.archiveThreadForHandoff(owner, owner, threadId, signal);
813
733
  }
814
734
  if ((await owner.threadLoadedList()).data.includes(threadId)) {
815
735
  throw new Error('Codex Provider repair could not release the thread writer');
@@ -829,7 +749,11 @@ export class CodexRunner {
829
749
  throw new Error('Codex resume did not preserve the bound thread and current Provider');
830
750
  }
831
751
  }
832
- async archiveThreadForHandoff(sourceClient, targetClient, threadId) {
752
+ async archiveThreadForHandoff(sourceClient, targetClient, threadId, signal) {
753
+ await this.retryThreadWriterOperation(threadId, 'archive-handoff', () => this.archiveThreadForHandoffOnce(sourceClient, targetClient, threadId, signal));
754
+ }
755
+ async archiveThreadForHandoffOnce(sourceClient, targetClient, threadId, signal) {
756
+ signal?.throwIfAborted();
833
757
  const existing = this.threadSubscriptions.get(threadId);
834
758
  if (existing && existing.client !== sourceClient) {
835
759
  const error = new Error(`Codex thread ${threadId} ownership changed during handoff`);
@@ -842,6 +766,13 @@ export class CodexRunner {
842
766
  error.code = CODEX_THREAD_ACTIVE_WRITER;
843
767
  throw error;
844
768
  }
769
+ await this.assertInterruptSettled(sessionId, threadId);
770
+ const status = (await sourceClient.threadRead(threadId, false, 2_000)).thread?.status?.type;
771
+ signal?.throwIfAborted();
772
+ logger.info(`[CodexRunner] Writer handoff readiness: thread=${threadId} sameClient=${sourceClient === targetClient} status=${status ?? 'unknown'}`);
773
+ if (status !== 'idle' && status !== 'notLoaded' && status !== 'systemError') {
774
+ throw unsettledInterruptError('Codex 会话交接');
775
+ }
845
776
  // Old app-server versions can acknowledge unsubscribe while retaining the
846
777
  // writer. Archive is the only per-thread operation that synchronously
847
778
  // tears down that runtime; the target client restores it before resume.
@@ -854,16 +785,18 @@ export class CodexRunner {
854
785
  }
855
786
  let archived = false;
856
787
  try {
788
+ logger.info(`[CodexRunner] Writer handoff archive begin: thread=${threadId} sameClient=${sourceClient === targetClient}`);
857
789
  await archive.call(sourceClient, threadId);
858
790
  archived = true;
859
791
  await unarchive.call(targetClient, threadId);
792
+ logger.info(`[CodexRunner] Writer handoff restored: thread=${threadId} sameClient=${sourceClient === targetClient}`);
860
793
  }
861
794
  catch (error) {
862
795
  if (archived) {
863
796
  // Do not strand the user's rollout under archived_sessions when the
864
797
  // target client fails midway through the compatibility handoff.
865
798
  try {
866
- await unarchive.call(sourceClient, threadId);
799
+ await sourceClient.threadUnarchive(threadId);
867
800
  this.threadSubscriptions.set(threadId, { client: sourceClient, state: 'subscribed' });
868
801
  }
869
802
  catch (restoreError) {
@@ -878,6 +811,7 @@ export class CodexRunner {
878
811
  throw handoffError;
879
812
  }
880
813
  this.threadSubscriptions.set(threadId, { client: targetClient, state: 'subscribed' });
814
+ signal?.throwIfAborted();
881
815
  }
882
816
  resolveCanonicalEcApproval(toolInput, managedTempDir, expectedCredentialToken) {
883
817
  const rawCommand = typeof toolInput.command === 'string' ? toolInput.command : '';
@@ -1134,11 +1068,12 @@ export class CodexRunner {
1134
1068
  this.pruneThreadOperationLocks();
1135
1069
  }
1136
1070
  resetAppServerClient() {
1137
- const clients = [...this.retiredProviderClients, this.appServerClient, this.fullAccessAppServerClient]
1071
+ const clients = [...this.retiredProviderClients, ...this.sessionAppServerClients.values(), this.appServerClient, this.fullAccessAppServerClient]
1138
1072
  .filter((client) => !!client);
1139
1073
  this.retiredProviderClients.clear();
1140
1074
  this.appServerClient = null;
1141
1075
  this.fullAccessAppServerClient = null;
1076
+ this.sessionAppServerClients.clear();
1142
1077
  this.threadSubscriptions.clear();
1143
1078
  this.threadExternalToolFingerprints.clear();
1144
1079
  this.threadExternalToolBoundaries.clear();
@@ -1158,16 +1093,23 @@ export class CodexRunner {
1158
1093
  }
1159
1094
  }
1160
1095
  /**
1161
- * Codex 自动压缩阈值:由 EvolCore 统一下发,不依赖 Codex 对模型窗口的推断。
1162
- * 窗口本身超过 550k 的模型才覆盖,其余保持 Codex 自带的默认策略。
1096
+ * Codex 的模型窗口与自动压缩阈值分开下发;未配置时阈值为 258400。
1163
1097
  */
1164
1098
  buildAutoCompactThreadConfig(model) {
1165
- if (!model)
1166
- return null;
1167
- const window = findModelSpec(resolveRoot(), model)?.context_window ?? 0;
1168
- if (!(window > EVOLCORE_AUTO_COMPACT_WINDOW_TOKENS))
1169
- return null;
1170
- return { model_auto_compact_token_limit: evolcoreAutoCompactTokens(window) };
1099
+ return model ? { model_auto_compact_token_limit: CODEX_FALLBACK_CONTEXT_TOKENS } : null;
1100
+ }
1101
+ async configuredContextPolicy(model, provider) {
1102
+ const threshold = readAgentCompactThreshold(this.resolvedConfig.agentAid, 'codex');
1103
+ let catalog;
1104
+ try {
1105
+ catalog = await getRunnerCatalog('codex', provider ? undefined : this.resolvedConfig.agentAid, this.currentProviderConfig(provider));
1106
+ }
1107
+ catch (error) {
1108
+ logger.debug('[CodexRunner] Context catalog unavailable; using 258400 fallback', error);
1109
+ }
1110
+ const policy = resolveAgentContextPolicy('codex', model, catalog, threshold);
1111
+ logger.info(`[CodexRunner] Context policy: ${JSON.stringify(policy)}`);
1112
+ return policy;
1171
1113
  }
1172
1114
  mergeThreadConfig(...configs) {
1173
1115
  const merged = {};
@@ -1191,15 +1133,7 @@ export class CodexRunner {
1191
1133
  }
1192
1134
  return Object.keys(merged).length > 0 ? merged : null;
1193
1135
  }
1194
- async resolveCapabilityThreadConfig(projectPath) {
1195
- // 每次调用按当前 effective 配置解析;构造期快照会让 capability/baseagentSkills 改动要等 runner 重建才生效。
1196
- let agentConfig = this.resolvedConfig.agentConfig;
1197
- if (this.resolvedConfig.agentAid) {
1198
- try {
1199
- agentConfig = resolveEffective({ self: this.resolvedConfig.agentAid }, { cache: true });
1200
- }
1201
- catch { }
1202
- }
1136
+ async resolveCapabilityThreadConfig(projectPath, agentConfig = this.currentEffectiveAgentConfig(), denyProjectSkills = false) {
1203
1137
  // 拿不到配置时按 baseagentSkills 缺省值(关闭)处理。
1204
1138
  const fallbackConfig = {
1205
1139
  skills: { include_instructions: false, bundled: { enabled: false }, config: [{ name: 'eclink', enabled: false }] },
@@ -1207,7 +1141,7 @@ export class CodexRunner {
1207
1141
  if (!agentConfig)
1208
1142
  return fallbackConfig;
1209
1143
  try {
1210
- const resolved = await resolveCodexCapabilityThreadConfigForProject(agentConfig, projectPath, 'codex');
1144
+ const resolved = await resolveCodexCapabilityThreadConfigForProject(agentConfig, projectPath, 'codex', denyProjectSkills ? { includeProjectSkills: false } : undefined);
1211
1145
  const skills = this.configRecord(resolved.skills);
1212
1146
  const configured = Array.isArray(skills?.config)
1213
1147
  ? skills.config.filter(entry => {
@@ -1228,6 +1162,17 @@ export class CodexRunner {
1228
1162
  return fallbackConfig;
1229
1163
  }
1230
1164
  }
1165
+ currentEffectiveAgentConfig() {
1166
+ // 每次调用按当前 effective 配置解析;构造期快照会让 capability/baseagentSkills 改动要等 runner 重建才生效。
1167
+ let agentConfig = this.resolvedConfig.agentConfig;
1168
+ if (this.resolvedConfig.agentAid) {
1169
+ try {
1170
+ agentConfig = resolveEffective({ self: this.resolvedConfig.agentAid }, { cache: true });
1171
+ }
1172
+ catch { }
1173
+ }
1174
+ return agentConfig;
1175
+ }
1231
1176
  configRecord(value) {
1232
1177
  return value && typeof value === 'object' && !Array.isArray(value)
1233
1178
  ? value
@@ -1449,7 +1394,7 @@ export class CodexRunner {
1449
1394
  // ── Permission ──
1450
1395
  currentMode = 'readonly';
1451
1396
  // per-call/per-session 权限模式:runQuery 按本次解析结果写入,审批回调(异步、按 sessionKey 路由)据此判定。
1452
- // 避免多会话共享 this.currentMode 时的并发污染(与 claude-runner 的 per-call permissionMode 同构)。
1397
+ // 避免多会话共享 this.currentMode 时的并发污染(与 Claude runner 的 per-call permissionMode 同构)。
1453
1398
  chatModes = new Map();
1454
1399
  /** 将权限模式映射为 Codex app-server 的 approvalPolicy(纯函数,无副作用,供 per-call 派生用)。 */
1455
1400
  toApprovalPolicy(mode) {
@@ -1534,7 +1479,7 @@ export class CodexRunner {
1534
1479
  }
1535
1480
  return Object.fromEntries([...paths].map(candidate => [candidate, 'write']));
1536
1481
  }
1537
- buildPermissionProfileConfig(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir) {
1482
+ buildPermissionProfileConfig(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir, disableProjectSkillDiscovery = false) {
1538
1483
  const profileName = this.permissionProfileName(sessionId);
1539
1484
  const managedTempDir = ensureSessionRuntimeDir(sessionId);
1540
1485
  const network = {
@@ -1547,6 +1492,15 @@ export class CodexRunner {
1547
1492
  onlyOtherAgents: true,
1548
1493
  }))
1549
1494
  relationAttachmentDenies[directory] = 'deny';
1495
+ const projectSkillDenies = {};
1496
+ // Windows runs each native skill probe behind a sandbox helper. Denying
1497
+ // disabled project skill roots avoids repeated walks and ACL refreshes.
1498
+ if (disableProjectSkillDiscovery) {
1499
+ for (const directory of getExistingCodexProjectSkillRoots(projectPath)) {
1500
+ projectSkillDenies[directory] = 'deny';
1501
+ projectSkillDenies[`${directory}/**`] = 'deny';
1502
+ }
1503
+ }
1550
1504
  const filesystem = compactCodexLinuxFilesystemRules({
1551
1505
  ...buildCodexProtectedFilesystemRules(resolveRoot(), {
1552
1506
  selfAid: this.resolvedConfig.agentAid,
@@ -1566,8 +1520,9 @@ export class CodexRunner {
1566
1520
  } : {}),
1567
1521
  ...(personalSoulDir ? {
1568
1522
  [path.resolve(personalSoulDir)]: mode === 'readonly' ? 'read' : 'write',
1569
- [path.join(path.resolve(personalSoulDir), '**')]: mode === 'readonly' ? 'read' : 'write',
1523
+ [`${path.resolve(personalSoulDir)}/**`]: mode === 'readonly' ? 'read' : 'write',
1570
1524
  } : {}),
1525
+ ...projectSkillDenies,
1571
1526
  ...relationAttachmentDenies,
1572
1527
  ...(mode !== 'readonly' && managedTempDir ? {
1573
1528
  [managedTempDir]: 'write',
@@ -1592,7 +1547,7 @@ export class CodexRunner {
1592
1547
  },
1593
1548
  };
1594
1549
  }
1595
- buildExecutionSandboxOptions(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir, permissionContext = this.permissionContexts.get(sessionId) ?? {}) {
1550
+ buildExecutionSandboxOptions(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir, permissionContext = this.permissionContexts.get(sessionId) ?? {}, disableProjectSkillDiscovery = false) {
1596
1551
  const decision = resolvePhaseOneExecutionSandbox(mode, permissionContext.role);
1597
1552
  // 系统会话明确声明不要沙箱:Codex 的 permission profile 以项目目录为中心,
1598
1553
  // 而系统会话的读写边界($EVOLCORE_HOME 下的批次目录与记忆目录)与 cwd 无关,
@@ -1603,7 +1558,7 @@ export class CodexRunner {
1603
1558
  decision,
1604
1559
  permissionProfileConfig: sandboxOff
1605
1560
  ? undefined
1606
- : this.buildPermissionProfileConfig(sessionId, decision.permissionMode, projectPath, bootstrapAgentMdPath, personalSoulDir),
1561
+ : this.buildPermissionProfileConfig(sessionId, decision.permissionMode, projectPath, bootstrapAgentMdPath, personalSoulDir, disableProjectSkillDiscovery),
1607
1562
  sandbox: sandboxOff ? 'danger-full-access' : undefined,
1608
1563
  sessionSandboxOff,
1609
1564
  };
@@ -2016,6 +1971,12 @@ export class CodexRunner {
2016
1971
  && !matchesCodexTask(operationTarget, target);
2017
1972
  }))
2018
1973
  return;
1974
+ // A cancelled turn/start may still return a live turn. Its startup path
1975
+ // owns the subscription until that turn has been interrupted and drained.
1976
+ if ([...(operations ?? [])].some(operation => operation.startupPending
1977
+ && operation.lockAcquired
1978
+ && (!target || matchesCodexTask(this.targetForOperation(operation), target))))
1979
+ return;
2019
1980
  const capturedController = this.activeAbortControllers.get(key);
2020
1981
  const capturedStream = this.activeStreams.get(key);
2021
1982
  const hadController = capturedController !== undefined;
@@ -2175,6 +2136,8 @@ export class CodexRunner {
2175
2136
  }
2176
2137
  async acquireThreadOperation(key, operation, signal) {
2177
2138
  signal?.throwIfAborted();
2139
+ if (key.startsWith('thread:'))
2140
+ this.assertStartupSettled(undefined, key.slice('thread:'.length));
2178
2141
  const lock = this.getThreadOperationLock(key);
2179
2142
  const previous = lock.tail;
2180
2143
  let releaseCurrent;
@@ -2222,12 +2185,34 @@ export class CodexRunner {
2222
2185
  }
2223
2186
  }
2224
2187
  // ── Core: runQuery ──
2225
- cachedThreadForTopic(sessionId, agentSessionId) {
2226
- if (!agentSessionId)
2227
- return undefined;
2228
- return this.activeSessions.get(sessionId) === agentSessionId ? agentSessionId : undefined;
2188
+ assertStartupSettled(sessionId, threadId) {
2189
+ for (const [ownerSessionId, operations] of this.queryOperations) {
2190
+ if (ownerSessionId !== sessionId && !threadId)
2191
+ continue;
2192
+ if ([...operations].some(operation => operation.lockAcquired
2193
+ && operation.startupPending && operation.controller.signal.aborted
2194
+ && (ownerSessionId === sessionId || operation.threadId === threadId))) {
2195
+ throw unsettledInterruptError('Codex 会话初始化');
2196
+ }
2197
+ }
2198
+ }
2199
+ async openThreadWithDeadline(open, diagnostics, controller) {
2200
+ controller?.signal.throwIfAborted();
2201
+ const timer = controller ? setTimeout(() => {
2202
+ logger.warn(`[CodexRunner] Thread open timed out: ${JSON.stringify({ ...diagnostics(), timeoutMs: CODEX_THREAD_OPEN_TIMEOUT_MS })}`);
2203
+ controller.abort(Object.assign(new Error('Codex 会话初始化超时;旧初始化结束前已暂停该会话的后续执行(CODEX_THREAD_OPEN_TIMEOUT)'), { code: 'CODEX_THREAD_OPEN_TIMEOUT' }));
2204
+ }, CODEX_THREAD_OPEN_TIMEOUT_MS) : undefined;
2205
+ timer?.unref?.();
2206
+ try {
2207
+ return await open();
2208
+ }
2209
+ finally {
2210
+ if (timer)
2211
+ clearTimeout(timer);
2212
+ }
2229
2213
  }
2230
- async runQuery(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv) {
2214
+ async runQuery(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, startupRecoveryAttempt = 0) {
2215
+ resolveRunInference('codex', modelOverride?.inference);
2231
2216
  const topicBinding = modelOverride?.backend?.kind === 'topic';
2232
2217
  if (topicBinding && (!modelOverride?.turn || modelOverride.turn.sessionId !== sessionId || !this.onSessionIdUpdate)) {
2233
2218
  const error = new Error('topic backend run requires an active TurnLease and binding callback');
@@ -2243,27 +2228,35 @@ export class CodexRunner {
2243
2228
  }
2244
2229
  const topicAgentSessionId = topicBinding ? modelOverride?.backend?.agentSessionId ?? null : undefined;
2245
2230
  const knownThreadId = topicBinding
2246
- ? this.cachedThreadForTopic(sessionId, topicAgentSessionId)
2231
+ ? topicAgentSessionId || undefined
2247
2232
  : initialAgentSessionId || this.activeSessions.get(sessionId);
2233
+ this.assertStartupSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId);
2248
2234
  const operationKey = this.threadOperationKey(modelOverride?.recovery?.agentSessionId || knownThreadId, sessionId);
2249
2235
  this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
2236
+ let resolveSettled;
2250
2237
  const operation = {
2251
2238
  controller: new AbortController(),
2252
2239
  taskId: modelOverride?.turn?.taskId ?? this.permissionContexts.get(sessionId)?.taskId,
2253
2240
  generation: modelOverride?.turn?.generation ?? this.permissionContexts.get(sessionId)?.turn?.generation,
2241
+ threadId: modelOverride?.recovery?.agentSessionId || knownThreadId,
2254
2242
  lockAcquired: false,
2243
+ startupPending: true,
2244
+ settled: new Promise(resolve => { resolveSettled = resolve; }),
2255
2245
  };
2256
2246
  const operationTarget = this.targetForOperation(operation);
2257
2247
  const operations = this.queryOperations.get(sessionId) ?? new Set();
2258
2248
  operations.add(operation);
2259
2249
  this.queryOperations.set(sessionId, operations);
2260
2250
  let releaseLock;
2251
+ let startup;
2261
2252
  const release = () => {
2253
+ operation.startupPending = false;
2262
2254
  operations.delete(operation);
2263
2255
  if (this.queryOperations.get(sessionId) === operations && operations.size === 0) {
2264
2256
  this.queryOperations.delete(sessionId);
2265
2257
  }
2266
2258
  releaseLock?.();
2259
+ resolveSettled();
2267
2260
  };
2268
2261
  try {
2269
2262
  if (operationTarget && this.consumePendingInterrupt(sessionId, operationTarget)) {
@@ -2272,14 +2265,50 @@ export class CodexRunner {
2272
2265
  await waitForCodexOperation(this.assertInterruptSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId), operation.controller.signal);
2273
2266
  releaseLock = await this.acquireThreadOperation(operationKey, 'thread/resume+turn/start', operation.controller.signal);
2274
2267
  operation.lockAcquired = true;
2268
+ this.assertStartupSettled(sessionId, operation.threadId);
2275
2269
  await waitForCodexOperation(this.assertInterruptSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId), operation.controller.signal);
2276
- const stream = await this.runQueryLocked(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, operation.controller);
2270
+ startup = this.runQueryLocked(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, operation.controller);
2271
+ const stream = await waitForCodexOperation(startup, operation.controller.signal);
2272
+ operation.controller.signal.throwIfAborted();
2273
+ operation.startupPending = false;
2277
2274
  this.activeOperationReleases.set(sessionId, release);
2278
2275
  this.activeOperationReleaseTargets.set(sessionId, operationTarget);
2279
2276
  return this.holdThreadOperation(stream, sessionId, release);
2280
2277
  }
2281
2278
  catch (error) {
2282
- release();
2279
+ if (startup && operation.controller.signal.aborted && !operation.inputSubmitted && operation.client
2280
+ && this.appServerSessionOwners.get(operation.client) === sessionId) {
2281
+ try {
2282
+ await this.reclaimSessionClient(sessionId, operation.client);
2283
+ }
2284
+ catch (reclaimError) {
2285
+ logger.error(`[CodexRunner] Session runtime reclamation unconfirmed: session=${sessionId} error=${String(reclaimError)}`);
2286
+ throw unsettledInterruptError('Codex 运行态回收', reclaimError);
2287
+ }
2288
+ await startup.then(async (stream) => {
2289
+ for await (const _event of stream) { /* Discard cancelled events after confirmed exit. */ }
2290
+ }).catch(() => undefined);
2291
+ release();
2292
+ if (error?.code === 'CODEX_THREAD_OPEN_TIMEOUT') {
2293
+ if (!operation.interrupted && startupRecoveryAttempt === 0) {
2294
+ logger.warn(`[CodexRunner] Retrying thread open on a fresh session runtime: session=${sessionId} thread=${operation.threadId ?? '<new>'}`);
2295
+ return this.runQuery(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, 1);
2296
+ }
2297
+ throw Object.assign(new Error('Codex 会话初始化再次超时;已回收卡住的运行态,原话题和历史保留,可稍后在原话题重试(CODEX_THREAD_OPEN_TIMEOUT)'), { code: 'CODEX_THREAD_OPEN_TIMEOUT' });
2298
+ }
2299
+ throw error;
2300
+ }
2301
+ if (startup && operation.controller.signal.aborted) {
2302
+ logger.warn(`[CodexRunner] Cancelled startup awaiting backend settlement: session=${sessionId} thread=${operation.threadId ?? '<new>'}`);
2303
+ void startup.then(async (stream) => {
2304
+ for await (const _event of stream) { /* Discard the cancelled run. */ }
2305
+ }).catch(cleanupError => {
2306
+ logger.debug(`[CodexRunner] Cancelled startup settled: session=${sessionId} error=${String(cleanupError)}`);
2307
+ }).finally(release);
2308
+ }
2309
+ else {
2310
+ release();
2311
+ }
2283
2312
  throw error;
2284
2313
  }
2285
2314
  }
@@ -2311,6 +2340,8 @@ export class CodexRunner {
2311
2340
  throw new Error('Async question reply requires its original Codex backend');
2312
2341
  }
2313
2342
  await this.assertInterruptSettled(sessionId, agentSessionId);
2343
+ this.assertStartupSettled(sessionId, agentSessionId);
2344
+ operationController?.signal.throwIfAborted();
2314
2345
  let resumingThread = !!agentSessionId;
2315
2346
  const modelContextId = modelOverride?.model || this.modelContextId;
2316
2347
  await assertRunnerModelAllowed('codex', modelContextId, this.currentProviderConfig(modelOverride?.provider));
@@ -2328,11 +2359,21 @@ export class CodexRunner {
2328
2359
  }
2329
2360
  this.chatModes.set(sessionId, callMode);
2330
2361
  const callApprovalPolicy = this.toApprovalPolicy(callMode);
2331
- const executionSandbox = this.buildExecutionSandboxOptions(sessionId, callMode, projectPath, modelOverride?.bootstrapAgentMdPath, modelOverride?.personalSoulDir, undefined);
2332
- const appServer = this.getAppServerClient(callMode === 'fullaccess', modelOverride?.provider);
2362
+ const effectiveAgentConfig = this.currentEffectiveAgentConfig();
2363
+ const disableProjectSkillDiscovery = process.platform === 'win32'
2364
+ && !isBaseagentSkillsEnabled(effectiveAgentConfig);
2365
+ const executionSandbox = this.buildExecutionSandboxOptions(sessionId, callMode, projectPath, modelOverride?.bootstrapAgentMdPath, modelOverride?.personalSoulDir, undefined, disableProjectSkillDiscovery);
2366
+ const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath, effectiveAgentConfig, disableProjectSkillDiscovery && !!executionSandbox.permissionProfileConfig);
2367
+ operationController?.signal.throwIfAborted();
2368
+ const appServer = this.getAppServerClient(callMode === 'fullaccess', modelOverride?.provider, sessionId);
2369
+ const openingOperation = [...(this.queryOperations.get(sessionId) ?? [])]
2370
+ .find(operation => operation.controller === operationController);
2371
+ if (openingOperation) {
2372
+ openingOperation.threadId = agentSessionId;
2373
+ openingOperation.client = appServer;
2374
+ }
2333
2375
  this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
2334
2376
  const effectiveApprovalPolicy = callApprovalPolicy;
2335
- const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath);
2336
2377
  const userInputConfig = { features: {
2337
2378
  default_mode_request_user_input: modelOverride?.enableRequestUserInput
2338
2379
  ?? this.resolvedConfig.enableRequestUserInput ?? true,
@@ -2343,6 +2384,7 @@ export class CodexRunner {
2343
2384
  if (callMode !== 'fullaccess')
2344
2385
  await this.assertProactiveHookAvailability(sessionId, appServer);
2345
2386
  const managedTempInstruction = this.managedTempInstruction(sessionId);
2387
+ const contextPolicy = await this.configuredContextPolicy(modelContextId, modelOverride?.provider);
2346
2388
  const developerInstructions = [systemPromptAppend, managedTempInstruction].filter(Boolean).join('\n\n') || undefined;
2347
2389
  let threadSessionToken = agentSessionId
2348
2390
  ? this.ensureThreadCredential(agentSessionId)
@@ -2363,7 +2405,7 @@ export class CodexRunner {
2363
2405
  ...(fallback
2364
2406
  ? { sandbox: 'danger-full-access' }
2365
2407
  : executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
2366
- config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(fallback ? undefined : executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, this.buildAutoCompactThreadConfig(callModel), externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
2408
+ config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(fallback ? undefined : executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, contextPolicy?.codexThreadConfig ?? this.buildAutoCompactThreadConfig(callModel), externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
2367
2409
  ...(developerInstructions ? { developerInstructions } : {}),
2368
2410
  });
2369
2411
  let threadOptions = buildThreadOptions();
@@ -2371,21 +2413,48 @@ export class CodexRunner {
2371
2413
  `role=${executionSandbox.decision.role ?? 'none'} sandbox=${executionSandbox.decision.state}`);
2372
2414
  let threadResponse;
2373
2415
  let previousAppServer;
2416
+ let openPhase = 'preparing';
2417
+ const openDiagnostics = () => ({
2418
+ ...appServer.getStartupDiagnostics(),
2419
+ sessionId,
2420
+ threadId: agentSessionId ?? null,
2421
+ taskId: openingOperation?.taskId ?? null,
2422
+ generation: openingOperation?.generation ?? null,
2423
+ mode: callMode,
2424
+ sandbox: executionSandbox.decision.state,
2425
+ innerSandboxFallback,
2426
+ phase: openPhase,
2427
+ });
2374
2428
  const openThread = async () => {
2429
+ operationController?.signal.throwIfAborted();
2430
+ logger.info(`[CodexRunner] Opening thread: ${JSON.stringify({
2431
+ sessionId, threadId: agentSessionId ?? null, mode: callMode,
2432
+ taskId: openingOperation?.taskId ?? null, generation: openingOperation?.generation ?? null,
2433
+ ...appServer.getDiagnosticContext(),
2434
+ })}`);
2375
2435
  if (agentSessionId) {
2436
+ openPhase = 'provider-preparation';
2376
2437
  await this.prepareSessionProvider(appServer, agentSessionId, operationController?.signal);
2438
+ operationController?.signal.throwIfAborted();
2377
2439
  // A thread may have been loaded by the other permission-mode client.
2378
2440
  // Release that one thread before asking this client to resume it.
2379
- previousAppServer = await this.prepareThreadSubscription(appServer, agentSessionId);
2441
+ openPhase = 'subscription-handoff';
2442
+ previousAppServer = await this.prepareThreadSubscription(appServer, agentSessionId, operationController?.signal);
2443
+ operationController?.signal.throwIfAborted();
2380
2444
  try {
2381
- return await this.resumeThreadAllowingWriterRelease(appServer, agentSessionId, projectPath, threadOptions, previousAppServer);
2445
+ openPhase = 'thread/resume';
2446
+ return await this.resumeThreadAllowingWriterRelease(appServer, agentSessionId, projectPath, threadOptions, previousAppServer, operationController?.signal);
2382
2447
  }
2383
2448
  catch (error) {
2384
- if (isCodexActiveWriterError(error) && previousAppServer && previousAppServer !== appServer) {
2449
+ operationController?.signal.throwIfAborted();
2450
+ if (isCodexActiveWriterError(error) && previousAppServer) {
2385
2451
  // Some Codex builds acknowledge unsubscribe before unloading the
2386
2452
  // runtime. Archive/unarchive is a synchronous per-thread teardown
2387
2453
  // and preserves the same persisted thread id for the retry.
2388
- await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId);
2454
+ openPhase = 'writer-handoff';
2455
+ await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId, operationController?.signal);
2456
+ operationController?.signal.throwIfAborted();
2457
+ openPhase = 'thread/resume';
2389
2458
  return appServer.threadResume(agentSessionId, projectPath, threadOptions);
2390
2459
  }
2391
2460
  // A legacy main session can retain a provider ID after its rollout was
@@ -2394,6 +2463,7 @@ export class CodexRunner {
2394
2463
  if (topicBinding || recoverySessionId || modelOverride?.asyncQuestionAnswer || !isCodexNoRolloutError(error))
2395
2464
  throw error;
2396
2465
  const missingThreadId = agentSessionId;
2466
+ openPhase = 'missing-history-recovery';
2397
2467
  if (modelOverride?.capsule) {
2398
2468
  const recovered = await modelOverride.capsule.recover(missingThreadId, prompt, systemPromptAppend);
2399
2469
  prompt = recovered.prompt;
@@ -2421,13 +2491,16 @@ export class CodexRunner {
2421
2491
  threadSessionToken = this.createThreadCredential();
2422
2492
  threadOptions = buildThreadOptions(innerSandboxFallback);
2423
2493
  logger.warn(`[CodexRunner] recovered missing rollout before input submission: session=${sessionId} thread=${missingThreadId}`);
2494
+ operationController?.signal.throwIfAborted();
2495
+ openPhase = 'thread/start';
2424
2496
  return appServer.threadStart(projectPath, threadOptions);
2425
2497
  }
2426
2498
  }
2499
+ openPhase = 'thread/start';
2427
2500
  return appServer.threadStart(projectPath, threadOptions);
2428
2501
  };
2429
2502
  try {
2430
- threadResponse = await openThread();
2503
+ threadResponse = await this.openThreadWithDeadline(openThread, openDiagnostics, operationController);
2431
2504
  }
2432
2505
  catch (error) {
2433
2506
  if (!canFallbackFromInnerSandbox || !isNestedSandboxInitializationFailure(error))
@@ -2476,13 +2549,20 @@ export class CodexRunner {
2476
2549
  logger.warn(`[CodexSandbox] inner sandbox initialization failed; retrying with outer H-class guard ` +
2477
2550
  `session=${sessionId} occurrences=${circuit.occurrences}: ${detail}`);
2478
2551
  threadOptions = buildThreadOptions(true);
2479
- threadResponse = await openThread();
2552
+ threadResponse = await this.openThreadWithDeadline(openThread, openDiagnostics, operationController);
2480
2553
  }
2481
- if (agentSessionId)
2482
- this.assertResumedProvider(appServer, threadResponse, agentSessionId);
2483
2554
  let threadId = threadResponse.thread?.id || agentSessionId;
2484
2555
  if (!threadId)
2485
2556
  throw new Error('Codex app-server did not return a thread id');
2557
+ if (openingOperation)
2558
+ openingOperation.threadId = threadId;
2559
+ if (operationController?.signal.aborted) {
2560
+ this.markThreadSubscribed(appServer, threadId);
2561
+ await this.releaseThreadSubscription(appServer, threadId, 'cancelled-thread-open');
2562
+ operationController.signal.throwIfAborted();
2563
+ }
2564
+ if (agentSessionId)
2565
+ this.assertResumedProvider(appServer, threadResponse, agentSessionId);
2486
2566
  if (recoverySessionId && threadId !== recoverySessionId) {
2487
2567
  throw new Error('Task recovery cannot replace the original Codex thread');
2488
2568
  }
@@ -2546,6 +2626,10 @@ export class CodexRunner {
2546
2626
  projectPath,
2547
2627
  model: callModel,
2548
2628
  modelContextId,
2629
+ ...(contextPolicy ? {
2630
+ modelContextWindowTokens: contextPolicy.executionContextWindowTokens,
2631
+ autoCompactTokens: contextPolicy.effectiveAutoCompactThresholdTokens,
2632
+ } : {}),
2549
2633
  committed: resumingThread,
2550
2634
  persistenceFinalized: resumingThread,
2551
2635
  streamedAgentMessageIds: new Set(),
@@ -2666,6 +2750,9 @@ export class CodexRunner {
2666
2750
  }
2667
2751
  try {
2668
2752
  operationController?.signal.throwIfAborted();
2753
+ modelOverride?.onInputSubmitted?.();
2754
+ if (openingOperation)
2755
+ openingOperation.inputSubmitted = true;
2669
2756
  const turnResponse = await appServer.turnStart(threadId, input, {
2670
2757
  cwd: projectPath,
2671
2758
  model: callModel,
@@ -2762,9 +2849,6 @@ export class CodexRunner {
2762
2849
  async interrupt(sessionKey, target) {
2763
2850
  const operations = this.queryOperations.get(sessionKey);
2764
2851
  const matchingOperations = [...(operations ?? [])].filter(operation => target ? matchesCodexTask(this.targetForOperation(operation), target) : operation.lockAcquired);
2765
- for (const operation of matchingOperations) {
2766
- operation.controller.abort(Object.assign(new Error('Codex operation interrupted'), { name: 'AbortError' }));
2767
- }
2768
2852
  const controller = this.activeAbortControllers.get(sessionKey);
2769
2853
  const activeTurn = this.activeTurns.get(sessionKey);
2770
2854
  const matchingController = controller && (!target || matchesCodexTask(this.activeAbortTargets.get(sessionKey), target))
@@ -2787,6 +2871,10 @@ export class CodexRunner {
2787
2871
  ? this.interruptAppServerTurn(matchingTurn.threadId, matchingTurn.turnId)
2788
2872
  : Promise.resolve();
2789
2873
  const interruptSubagents = this.interruptSubagentTurns(sessionKey, matchingTurn?.threadId, target);
2874
+ for (const operation of matchingOperations) {
2875
+ operation.interrupted = true;
2876
+ operation.controller.abort(Object.assign(new Error('Codex operation interrupted'), { name: 'AbortError' }));
2877
+ }
2790
2878
  // Only a task-scoped request may be retained for a runner that has not
2791
2879
  // reached its first turn yet. A session-only interrupt must never poison
2792
2880
  // a later task during this startup gap.
@@ -2810,7 +2898,13 @@ export class CodexRunner {
2810
2898
  }
2811
2899
  logger.info(`[CodexRunner] Interrupted ${target ? `task=${target.taskId} generation=${target.generation}` : 'session'}: ${sessionKey}`);
2812
2900
  }
2813
- await Promise.all([interruptTurn, interruptSubagents]);
2901
+ const startupOperations = matchingOperations.filter(operation => operation.lockAcquired && operation.startupPending);
2902
+ const startupSettlement = startupOperations.length
2903
+ ? withInterruptDeadline(Promise.all(startupOperations.map(operation => operation.settled)), 'Codex cancelled startup settlement', CODEX_STARTUP_SETTLE_TIMEOUT_MS).catch(error => {
2904
+ logger.warn(`[CodexRunner] Cancelled startup still unsettled: session=${sessionKey} error=${String(error)}`);
2905
+ })
2906
+ : Promise.resolve();
2907
+ await Promise.all([interruptTurn, interruptSubagents, startupSettlement]);
2814
2908
  }
2815
2909
  async interruptSubagentTurns(sessionId, parentThreadId, target) {
2816
2910
  const entries = [...this.activeSubagentTurns.entries()]
@@ -2858,20 +2952,37 @@ export class CodexRunner {
2858
2952
  const subscribed = this.threadSubscriptions.get(threadId);
2859
2953
  const client = subscribed
2860
2954
  ? subscribed.client
2861
- : this.getAppServerClient(sessionId ? this.chatModes.get(sessionId) === 'fullaccess' : false);
2955
+ : this.getAppServerClient(sessionId ? this.chatModes.get(sessionId) === 'fullaccess' : false, undefined, sessionId);
2862
2956
  const key = JSON.stringify([threadId, turnId]);
2863
2957
  const previous = this.unconfirmedInterrupts.get(key);
2864
- previous?.unsubscribe?.();
2865
- const record = { sessionId, threadId, turnId, client };
2866
- this.unconfirmedInterrupts.set(key, record);
2958
+ if (previous) {
2959
+ try {
2960
+ await withInterruptDeadline(previous.settled, 'Codex existing turn/interrupt', CODEX_INTERRUPT_TIMEOUT_MS);
2961
+ }
2962
+ catch (error) {
2963
+ logger.warn(`[CodexRunner] Existing interrupt still unconfirmed: thread=${threadId} turn=${turnId} error=${String(error)}`);
2964
+ }
2965
+ return;
2966
+ }
2967
+ const startedAt = Date.now();
2867
2968
  let confirm;
2969
+ let settled = false;
2868
2970
  const confirmed = new Promise(resolve => { confirm = resolve; });
2869
- const clear = () => {
2870
- if (this.unconfirmedInterrupts.get(key) === record)
2871
- this.unconfirmedInterrupts.delete(key);
2872
- record.unsubscribe?.();
2873
- confirm();
2971
+ const record = {
2972
+ sessionId, threadId, turnId, client, settled: confirmed,
2973
+ confirm: evidence => {
2974
+ if (settled)
2975
+ return;
2976
+ settled = true;
2977
+ if (this.unconfirmedInterrupts.get(key) === record)
2978
+ this.unconfirmedInterrupts.delete(key);
2979
+ record.unsubscribe?.();
2980
+ logger.info(`[CodexRunner] Interrupt confirmed: session=${sessionId} thread=${threadId} turn=${turnId} evidence=${evidence} durationMs=${Date.now() - startedAt}`);
2981
+ confirm();
2982
+ },
2874
2983
  };
2984
+ this.unconfirmedInterrupts.set(key, record);
2985
+ logger.info(`[CodexRunner] Interrupt requested: session=${sessionId} thread=${threadId} turn=${turnId}`);
2875
2986
  record.unsubscribe = client.onNotification?.(notification => {
2876
2987
  const params = notification.params ?? {};
2877
2988
  if ((params.threadId ?? params.thread_id) !== threadId)
@@ -2879,47 +2990,62 @@ export class CodexRunner {
2879
2990
  if (notification.method === 'thread/closed'
2880
2991
  || (notification.method === 'turn/completed'
2881
2992
  && (params.turn?.id ?? params.turnId ?? params.turn_id) === turnId))
2882
- clear();
2993
+ record.confirm(notification.method);
2883
2994
  });
2995
+ const polling = new AbortController();
2884
2996
  try {
2997
+ const acknowledged = client.turnInterrupt(threadId, turnId).then(accepted => {
2998
+ if (!accepted)
2999
+ throw new Error('Codex interrupt was not accepted');
3000
+ logger.info(`[CodexRunner] Interrupt acknowledged: session=${sessionId} thread=${threadId} turn=${turnId} durationMs=${Date.now() - startedAt}`);
3001
+ });
2885
3002
  await withInterruptDeadline(Promise.race([
2886
- client.turnInterrupt(threadId, turnId).then(accepted => {
2887
- if (!accepted)
2888
- throw new Error('Codex interrupt was not accepted');
2889
- }),
3003
+ acknowledged.then(() => confirmed),
2890
3004
  confirmed,
3005
+ (async () => {
3006
+ while (!polling.signal.aborted) {
3007
+ await waitForCodexDelay(250, polling.signal);
3008
+ await this.verifyInterruptRecord(key, record);
3009
+ if (settled)
3010
+ return;
3011
+ }
3012
+ })(),
2891
3013
  ]), 'Codex turn/interrupt', CODEX_INTERRUPT_TIMEOUT_MS);
2892
3014
  }
2893
3015
  catch (error) {
2894
3016
  logger.warn(`[CodexRunner] Unconfirmed interrupt: thread=${threadId} turn=${turnId} error=${String(error)}`);
2895
3017
  }
3018
+ finally {
3019
+ polling.abort();
3020
+ }
3021
+ }
3022
+ async verifyInterruptRecord(key, record) {
3023
+ if (this.unconfirmedInterrupts.get(key) !== record)
3024
+ return;
3025
+ try {
3026
+ const response = await withInterruptDeadline(record.client.threadRead(record.threadId, false, 2_000), 'Codex interrupt verification', 2_000);
3027
+ const threadStatus = response.thread?.status?.type;
3028
+ logger.debug(`[CodexRunner] Interrupt verification: session=${record.sessionId} thread=${record.threadId} turn=${record.turnId} status=${threadStatus ?? 'unknown'}`);
3029
+ if (threadStatus === 'idle' || threadStatus === 'notLoaded') {
3030
+ if (this.unconfirmedInterrupts.get(key) === record)
3031
+ record.confirm(`thread/read:${threadStatus}`);
3032
+ return;
3033
+ }
3034
+ if (threadStatus !== undefined)
3035
+ return;
3036
+ const history = await withInterruptDeadline(record.client.threadRead(record.threadId, true, 2_000), 'Codex interrupt history verification', 2_000);
3037
+ const turn = history.thread?.turns?.find(turn => turn.id === record.turnId);
3038
+ if (turn && ['completed', 'failed', 'interrupted'].includes(String(turn.status))
3039
+ && !history.thread?.turns?.some(turn => turn.status === 'inProgress')
3040
+ && this.unconfirmedInterrupts.get(key) === record) {
3041
+ record.confirm('thread/read:terminal-history');
3042
+ }
3043
+ }
3044
+ catch { /* Ambiguous execution remains fenced; report it below. */ }
2896
3045
  }
2897
3046
  async assertInterruptSettled(sessionId, threadId) {
2898
3047
  const pending = [...this.unconfirmedInterrupts.entries()].filter(([, record]) => record.sessionId === sessionId || (threadId && record.threadId === threadId));
2899
- await Promise.all(pending.map(async ([key, record]) => {
2900
- try {
2901
- const response = await withInterruptDeadline(record.client.threadRead(record.threadId, false, 2_000), 'Codex interrupt verification', 2_000);
2902
- const threadStatus = response.thread?.status?.type;
2903
- if (threadStatus === 'idle' || threadStatus === 'notLoaded') {
2904
- if (this.unconfirmedInterrupts.get(key) === record) {
2905
- this.unconfirmedInterrupts.delete(key);
2906
- record.unsubscribe?.();
2907
- }
2908
- return;
2909
- }
2910
- if (threadStatus !== undefined)
2911
- return;
2912
- const history = await withInterruptDeadline(record.client.threadRead(record.threadId, true, 2_000), 'Codex interrupt history verification', 2_000);
2913
- const turn = history.thread?.turns?.find(turn => turn.id === record.turnId);
2914
- if (turn && ['completed', 'failed', 'interrupted'].includes(String(turn.status))
2915
- && !history.thread?.turns?.some(turn => turn.status === 'inProgress')
2916
- && this.unconfirmedInterrupts.get(key) === record) {
2917
- this.unconfirmedInterrupts.delete(key);
2918
- record.unsubscribe?.();
2919
- }
2920
- }
2921
- catch { /* Ambiguous execution remains fenced; report it below. */ }
2922
- }));
3048
+ await Promise.all(pending.map(([key, record]) => this.verifyInterruptRecord(key, record)));
2923
3049
  if ([...this.unconfirmedInterrupts.values()].some(record => record.sessionId === sessionId || (threadId && record.threadId === threadId))) {
2924
3050
  throw unsettledInterruptError('Codex');
2925
3051
  }
@@ -3028,6 +3154,12 @@ export class CodexRunner {
3028
3154
  this.cleanupChildThreadsForSession(sessionId);
3029
3155
  this.activeOperationReleaseTargets.delete(sessionId);
3030
3156
  this.pruneThreadOperationLocks();
3157
+ if (!this.queryOperations.get(sessionId)?.size) {
3158
+ const client = [...this.sessionAppServerClients.values()]
3159
+ .find(candidate => this.appServerSessionOwners.get(candidate) === sessionId);
3160
+ if (client)
3161
+ await this.reclaimSessionClient(sessionId, client);
3162
+ }
3031
3163
  }
3032
3164
  }
3033
3165
  resolveSessionFile(agentSessionId, _projectPath) {
@@ -3051,29 +3183,8 @@ export class CodexRunner {
3051
3183
  };
3052
3184
  return search(sessionsDir);
3053
3185
  }
3054
- async clearSession(sessionId, _agentSessionId, _projectPath) {
3055
- // Codex: 清空会话 = 下次 runQuery 不传 resumeId,自动创建新 thread
3056
- const threadId = this.activeSessions.get(sessionId) ?? _agentSessionId;
3057
- const subscription = this.threadSubscriptions.get(threadId);
3058
- if (subscription) {
3059
- await this.releaseThreadSubscription(subscription.client, threadId, 'session-cleared');
3060
- }
3061
- this.activeSessions.delete(sessionId);
3062
- this.activeTurns.delete(sessionId);
3063
- this.activeAbortTargets.delete(sessionId);
3064
- this.activeStreamTargets.delete(sessionId);
3065
- this.activeOperationReleaseTargets.delete(sessionId);
3066
- this.activeOperationReleases.delete(sessionId);
3067
- this.steeringTails.delete(sessionId);
3068
- this.chatModes.delete(sessionId);
3069
- this.threadProjectPaths.delete(threadId);
3070
- this.unbindExternalToolBoundary(threadId);
3071
- this.clearTrackedApprovalItemsForThread(threadId);
3072
- this.pruneThreadOperationLocks();
3073
- await this.onSessionIdUpdate?.(sessionId, '');
3074
- return true;
3075
- }
3076
3186
  async compactSession(_sessionId, agentSessionId, _projectPath, modelOverride) {
3187
+ resolveRunInference('codex', modelOverride?.inference);
3077
3188
  const startedAt = Date.now();
3078
3189
  const finish = (result) => {
3079
3190
  logger.info(`[CodexRunner] Compact result: thread=${agentSessionId} ok=${result.ok} code=${result.ok ? 'ok' : result.code} durationMs=${result.durationMs}`);
@@ -3084,27 +3195,35 @@ export class CodexRunner {
3084
3195
  try {
3085
3196
  await assertRunnerModelAllowed('codex', modelOverride?.model || this.modelContextId, this.currentProviderConfig(modelOverride?.provider));
3086
3197
  const compactMode = normalizeExecutionPermissionMode(modelOverride?.permissionMode ?? this.chatModes.get(_sessionId) ?? this.currentMode);
3087
- const appServer = this.getAppServerClient(compactMode === 'fullaccess', modelOverride?.provider);
3198
+ const appServer = this.getAppServerClient(compactMode === 'fullaccess', modelOverride?.provider, _sessionId);
3088
3199
  compactAppServer = appServer;
3089
3200
  await this.prepareSessionProvider(appServer, agentSessionId);
3090
3201
  await this.prepareThreadSubscription(appServer, agentSessionId);
3091
3202
  this.onCompactStart?.(_sessionId);
3092
- try {
3093
- await this.startAndWaitForCompact(appServer, agentSessionId);
3094
- return finish({ ok: true, durationMs: Date.now() - startedAt });
3203
+ const contextPolicy = await this.configuredContextPolicy(modelOverride?.model || this.modelContextId, modelOverride?.provider);
3204
+ if (!contextPolicy) {
3205
+ try {
3206
+ await this.startAndWaitForCompact(appServer, agentSessionId);
3207
+ return finish({ ok: true, durationMs: Date.now() - startedAt });
3208
+ }
3209
+ catch (error) {
3210
+ if (!this.isThreadNotFoundError(error))
3211
+ throw error;
3212
+ }
3095
3213
  }
3096
- catch (error) {
3097
- if (!this.isThreadNotFoundError(error))
3098
- throw error;
3099
- logger.info(`[CodexRunner] Compact thread not loaded, resuming before compact: ${agentSessionId}`);
3214
+ {
3215
+ logger.info(`[CodexRunner] Resuming before compact to load thread/config: ${agentSessionId}`);
3100
3216
  await ensureSessionRuntimeDirAsync(_sessionId);
3101
3217
  const compactModel = stripContextWindowSuffix(modelOverride?.model || this.model);
3102
3218
  const compactEffort = modelOverride?.effortMode === 'model_default'
3103
3219
  ? undefined
3104
3220
  : modelOverride?.effort ?? this.effort;
3105
3221
  const compactPolicy = this.toApprovalPolicy(compactMode);
3106
- const executionSandbox = this.buildExecutionSandboxOptions(_sessionId, compactMode, _projectPath);
3107
- const capabilityConfig = await this.resolveCapabilityThreadConfig(_projectPath);
3222
+ const effectiveAgentConfig = this.currentEffectiveAgentConfig();
3223
+ const disableProjectSkillDiscovery = process.platform === 'win32'
3224
+ && !isBaseagentSkillsEnabled(effectiveAgentConfig);
3225
+ const executionSandbox = this.buildExecutionSandboxOptions(_sessionId, compactMode, _projectPath, undefined, undefined, undefined, disableProjectSkillDiscovery);
3226
+ const capabilityConfig = await this.resolveCapabilityThreadConfig(_projectPath, effectiveAgentConfig, disableProjectSkillDiscovery && !!executionSandbox.permissionProfileConfig);
3108
3227
  const externalToolConfig = compactMode === 'fullaccess'
3109
3228
  ? {}
3110
3229
  : await this.resolveExternalToolApprovalConfig(appServer, _projectPath, capabilityConfig, compactMode);
@@ -3119,7 +3238,7 @@ export class CodexRunner {
3119
3238
  approvalPolicy: compactPolicy,
3120
3239
  approvalsReviewer: 'user',
3121
3240
  ...(executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
3122
- config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, capabilityConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(_sessionId, compactSessionToken), this.buildLifecycleLockdownConfig(compactMode)), compactMode),
3241
+ config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, capabilityConfig, externalToolConfig, contextPolicy?.codexThreadConfig, this.buildEvolcoreShellEnvironmentConfig(_sessionId, compactSessionToken), this.buildLifecycleLockdownConfig(compactMode)), compactMode),
3123
3242
  });
3124
3243
  this.assertResumedProvider(appServer, resumed, agentSessionId);
3125
3244
  this.markThreadSubscribed(appServer, agentSessionId);
@@ -3424,8 +3543,11 @@ export class CodexRunner {
3424
3543
  const sessionKey = context?.sessionId ?? this.findSessionKeyByThread(agentSessionId);
3425
3544
  await ensureSessionRuntimeDirAsync(sessionKey);
3426
3545
  const mode = normalizePermissionMode(context?.permissionMode).mode;
3427
- const executionSandbox = this.buildExecutionSandboxOptions(sessionKey, mode, projectPath, undefined, undefined, context ?? {});
3428
- const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath);
3546
+ const effectiveAgentConfig = this.currentEffectiveAgentConfig();
3547
+ const disableProjectSkillDiscovery = process.platform === 'win32'
3548
+ && !isBaseagentSkillsEnabled(effectiveAgentConfig);
3549
+ const executionSandbox = this.buildExecutionSandboxOptions(sessionKey, mode, projectPath, undefined, undefined, context ?? {}, disableProjectSkillDiscovery);
3550
+ const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath, effectiveAgentConfig, disableProjectSkillDiscovery && !!executionSandbox.permissionProfileConfig);
3429
3551
  // Fork against the connection that owns the source thread. Codex keeps
3430
3552
  // normal and full-access threads on separate app-server clients; using the
3431
3553
  // default client here makes full-access forks time out or lose the thread.
@@ -3434,13 +3556,14 @@ export class CodexRunner {
3434
3556
  if (sessionKey)
3435
3557
  await this.assertProactiveHookAvailability(sessionKey, appServer);
3436
3558
  const forkSessionToken = this.createThreadCredential();
3559
+ const contextPolicy = await this.configuredContextPolicy(this.modelContextId);
3437
3560
  const response = await appServer.threadFork(agentSessionId, projectPath, title, {
3438
3561
  model: this.model,
3439
3562
  effort: this.effort,
3440
3563
  approvalPolicy: this.toApprovalPolicy(mode),
3441
3564
  approvalsReviewer: 'user',
3442
3565
  ...(executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
3443
- config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, capabilityConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionKey, forkSessionToken), this.buildLifecycleLockdownConfig(mode)), mode),
3566
+ config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, capabilityConfig, externalToolConfig, contextPolicy?.codexThreadConfig, this.buildEvolcoreShellEnvironmentConfig(sessionKey, forkSessionToken), this.buildLifecycleLockdownConfig(mode)), mode),
3444
3567
  ...(lastTurnId ? { lastTurnId } : {}),
3445
3568
  });
3446
3569
  const forkedThreadId = response.thread?.id;
@@ -3565,6 +3688,18 @@ export class CodexRunner {
3565
3688
  const threadId = this.requestThreadId(params);
3566
3689
  const turnId = params.turnId ?? params.turn_id;
3567
3690
  const key = this.approvalItemKey(threadId, turnId, itemId);
3691
+ if (threadId && ['item/completed', 'turn/completed', 'thread/closed'].includes(notification.method)) {
3692
+ const completedTurnId = turnId ?? params.turn?.id;
3693
+ for (const pending of this.pendingMcpElicitations?.values() ?? []) {
3694
+ if (pending.threadId !== threadId)
3695
+ continue;
3696
+ if (notification.method === 'item/completed' && pending.itemId !== itemId)
3697
+ continue;
3698
+ if (notification.method !== 'thread/closed' && completedTurnId && pending.turnId !== completedTurnId)
3699
+ continue;
3700
+ pending.abort.abort();
3701
+ }
3702
+ }
3568
3703
  if (notification.method === 'item/completed' && threadId && typeof itemId === 'string') {
3569
3704
  this.registeredSafeOutputCalls.delete(JSON.stringify([threadId, itemId]));
3570
3705
  }
@@ -3652,6 +3787,10 @@ export class CodexRunner {
3652
3787
  clearTrackedApprovalItemsForThread(threadId) {
3653
3788
  if (!threadId)
3654
3789
  return;
3790
+ for (const pending of this.pendingMcpElicitations?.values() ?? []) {
3791
+ if (pending.threadId === threadId)
3792
+ pending.abort.abort();
3793
+ }
3655
3794
  for (const [key, tracked] of this.trackedApprovalItems) {
3656
3795
  if (tracked.threadId === threadId)
3657
3796
  this.trackedApprovalItems.delete(key);
@@ -3727,8 +3866,7 @@ export class CodexRunner {
3727
3866
  async handleAppServerRequest(request) {
3728
3867
  const params = (request.params || {});
3729
3868
  if (request.method === 'mcpServer/elicitation/request') {
3730
- logger.warn(`[CodexRunner] MCP elicitation cancelled because EvolCore has no audited elicitation bridge: thread=${params.threadId ?? '<missing>'} server=${params.serverName ?? '<missing>'}`);
3731
- return { action: 'cancel', content: null, _meta: null };
3869
+ return this.handleMcpElicitation(request, params);
3732
3870
  }
3733
3871
  if (request.method === 'item/tool/requestUserInput') {
3734
3872
  const trackedItem = this.findTrackedApprovalItem(params);
@@ -3980,7 +4118,10 @@ export class CodexRunner {
3980
4118
  };
3981
4119
  if (managedEcIntent && !approvedCommand) {
3982
4120
  if (canonicalEcApproval?.parseFailure?.issue === 'untrusted-shell') {
3983
- return await denyInfrastructure('ec_shell_untrusted_executable', 'EC command approval denied because the shell executable failed Windows Authenticode trust validation');
4121
+ const failure = canonicalEcApproval.parseFailure.shellTrustFailure;
4122
+ logger.warn('[CodexRunner] EC shell trust validation failed', failure);
4123
+ return await denyInfrastructure('ec_shell_untrusted_executable', 'EC command approval denied because shell trust validation failed'
4124
+ + (failure ? `: ${failure.message}` : ''));
3984
4125
  }
3985
4126
  if (canonicalEcApproval?.parseFailure?.issue === 'unsupported-escape') {
3986
4127
  return await denyInfrastructure('ec_shell_unsupported_escape', canonicalEcApproval.parseFailure.dialect === 'powershell'
@@ -4301,6 +4442,125 @@ export class CodexRunner {
4301
4442
  logger.info(`[CodexRunner] unattended MCP approval denied: session=${sessionKey} tool=${toolName}`);
4302
4443
  return this.denyUntrackedExternalToolApproval(params, 'permission_mode_denied', toolName);
4303
4444
  }
4445
+ async handleMcpElicitation(request, params) {
4446
+ const threadId = this.requestThreadId(params);
4447
+ const sessionKey = this.findSessionKeyByThread(threadId);
4448
+ const context = this.permissionContexts.get(sessionKey);
4449
+ const server = typeof params.serverName === 'string' ? params.serverName : '';
4450
+ const confirmation = parseMcpConfirmation(params);
4451
+ const requestId = `codex-elicitation-${crypto.randomUUID()}`;
4452
+ const mode = this.chatModes.get(sessionKey) ?? this.currentMode;
4453
+ const toolName = `MCP:${server || 'unknown'}/elicitation`;
4454
+ const audit = (phase, response, reason) => {
4455
+ auditPermissionLifecycle({
4456
+ phase, requestId, sessionId: sessionKey,
4457
+ agentAid: context?.selfAid, agentName: context?.agentName, taskId: context?.taskId,
4458
+ permissionMode: normalizeExecutionPermissionMode(mode), role: context?.role,
4459
+ toolName, approvalMethod: request.method,
4460
+ decision: !response ? 'pending' : response.action === 'accept' ? 'allow' : 'deny',
4461
+ decisionSource: response?.action === 'cancel' ? 'infrastructure' : 'approval',
4462
+ reason, summary: JSON.stringify({ server, mode: params.mode ?? 'form' }),
4463
+ ...(response?.action !== 'cancel' && response ? {
4464
+ approverOperatorId: context?.userId,
4465
+ approverChannelKey: context?.adapter?.channelKey ?? context?.channel,
4466
+ approverPrincipalId: context?.actor?.principalId,
4467
+ } : {}),
4468
+ });
4469
+ };
4470
+ audit('request');
4471
+ const cancel = (reason) => {
4472
+ logger.warn(`[CodexRunner] MCP elicitation cancelled: thread=${threadId ?? '<missing>'} server=${server || '<missing>'} reason=${reason}`);
4473
+ const response = cancelledMcpElicitation();
4474
+ audit('response', response, reason);
4475
+ audit('final', response, reason);
4476
+ return response;
4477
+ };
4478
+ if (!confirmation || !threadId || !server)
4479
+ return cancel('unsupported_elicitation');
4480
+ if (!context || !this.isThreadOwnedBySession(sessionKey, threadId))
4481
+ return cancel('elicitation_session_unbound');
4482
+ if (context.approvalInteractionPolicy === 'deny'
4483
+ || !['request', 'bypass', 'fullaccess'].includes(mode))
4484
+ return cancel('permission_mode_denied');
4485
+ if (mode === 'fullaccess' && !this.isTrustedFullAccessSession(sessionKey))
4486
+ return cancel('fullaccess_context_untrusted');
4487
+ // MCP elicitation has no itemId in the app-server protocol. Bind only to a
4488
+ // unique live call on the same server and turn; honor tool_call_id when supplied.
4489
+ const currentTurnId = () => this.findActiveTurnId(threadId) ?? this.activeSubagentTurns.get(threadId)?.turnId;
4490
+ const activeTurnId = currentTurnId();
4491
+ const turnId = typeof params.turnId === 'string' ? params.turnId : activeTurnId;
4492
+ if (!turnId || turnId !== activeTurnId)
4493
+ return cancel('elicitation_turn_unbound');
4494
+ const callId = params._meta?.tool_call_id;
4495
+ const candidates = [...this.trackedApprovalItems.values()].filter(tracked => tracked.threadId === threadId && tracked.turnId === turnId
4496
+ && tracked.item.type === 'mcpToolCall' && tracked.item.server === server
4497
+ && typeof tracked.item.tool === 'string' && tracked.item.tool.length > 0
4498
+ && Object.prototype.hasOwnProperty.call(tracked.item, 'arguments')
4499
+ && (callId == null || tracked.itemId === callId));
4500
+ if (candidates.length !== 1)
4501
+ return cancel('elicitation_call_unbound');
4502
+ const tracked = candidates[0];
4503
+ const boundary = this.threadExternalToolBoundaries.get(threadId);
4504
+ const isAppCall = typeof tracked.item.mcpAppResourceUri === 'string'
4505
+ || (tracked.item.appContext && typeof tracked.item.appContext === 'object');
4506
+ const toolInput = { server, tool: tracked.item.tool, arguments: tracked.item.arguments };
4507
+ const isAllowed = () => {
4508
+ if (this.permissionContexts.get(sessionKey) !== context
4509
+ || (this.chatModes.get(sessionKey) ?? this.currentMode) !== mode
4510
+ || context.approvalInteractionPolicy === 'deny'
4511
+ || currentTurnId() !== turnId
4512
+ || !this.isThreadOwnedBySession(sessionKey, threadId)
4513
+ || ![...this.trackedApprovalItems.values()].includes(tracked))
4514
+ return false;
4515
+ if (mode === 'fullaccess')
4516
+ return this.isTrustedFullAccessSession(sessionKey);
4517
+ if (!this.threadExternalToolFingerprints.get(threadId)
4518
+ || this.threadExternalToolBoundaries.get(threadId) !== boundary
4519
+ || !boundary || (isAppCall ? boundary.deniedApps.has(server) : boundary.deniedMcpServers.has(server))
4520
+ || (isAppCall && !boundary.allowAnyApp && !boundary.allowedApps.has(server))
4521
+ || !this.resolvePermissionWorkspacePath({ threadId }))
4522
+ return false;
4523
+ if (context.policyHook?.(`MCP:${server}/${tracked.item.tool}`, toolInput)?.block)
4524
+ return false;
4525
+ const systemDecision = context.systemSessionCheck?.(`MCP:${server}/${tracked.item.tool}`, toolInput);
4526
+ return !systemDecision || systemDecision.allow;
4527
+ };
4528
+ if (!isAllowed())
4529
+ return cancel('elicitation_capability_denied');
4530
+ // Capture the authenticated recipient as well as the task context reference.
4531
+ const userId = context.userId;
4532
+ const channelKey = context.adapter?.channelKey ?? context.channel;
4533
+ const channelId = context.channelId;
4534
+ const taskId = context.taskId;
4535
+ const abort = new AbortController();
4536
+ const signals = [context.abortSignal, this.activeAbortControllers.get(sessionKey)?.signal].filter((signal) => !!signal);
4537
+ const onAbort = () => abort.abort();
4538
+ for (const signal of signals) {
4539
+ signal.addEventListener('abort', onAbort, { once: true });
4540
+ if (signal.aborted)
4541
+ abort.abort();
4542
+ }
4543
+ this.pendingMcpElicitations.set(requestId, { threadId, turnId, itemId: tracked.itemId, abort });
4544
+ try {
4545
+ const response = await collectMcpConfirmation({
4546
+ sessionKey, server, message: confirmation.message, context, signal: abort.signal,
4547
+ isCurrent: () => isAllowed() && context.userId === userId && context.taskId === taskId
4548
+ && context.channelId === channelId
4549
+ && (context.adapter?.channelKey ?? context.channel) === channelKey,
4550
+ });
4551
+ audit('response', response, `elicitation_${response.action}`);
4552
+ audit('final', response, `elicitation_${response.action}`);
4553
+ return response;
4554
+ }
4555
+ catch (error) {
4556
+ return cancel(error instanceof Error ? error.message : 'elicitation_failed');
4557
+ }
4558
+ finally {
4559
+ this.pendingMcpElicitations.delete(requestId);
4560
+ for (const signal of signals)
4561
+ signal.removeEventListener('abort', onAbort);
4562
+ }
4563
+ }
4304
4564
  async handleMcpToolApproval(params, trackedItem) {
4305
4565
  const questions = Array.isArray(params.questions) ? params.questions : [];
4306
4566
  if (questions.length === 0)
@@ -4685,7 +4945,12 @@ export class CodexRunner {
4685
4945
  // readonly decision. The map entry alone is stale if the directory was
4686
4946
  // replaced between preflight and the approval callback.
4687
4947
  managedTempDir: permCtx?.managedTempDir ?? this.getManagedTempDir(sessionKey),
4688
- grantedReadRoots: permCtx?.grantedReadRoots,
4948
+ grantedReadRoots: [
4949
+ ...(permCtx?.grantedReadRoots ?? []),
4950
+ ...(!permCtx?.systemSessionCheck ? getExistingSelfAttachmentDirs(resolveRoot(), {
4951
+ selfAid: this.resolvedConfig.agentAid,
4952
+ }) : []),
4953
+ ],
4689
4954
  allowReadonlySourceDiagnostics: permCtx?.allowReadonlySourceDiagnostics === true,
4690
4955
  } : undefined;
4691
4956
  if (toolName === 'Bash')
@@ -5056,7 +5321,7 @@ export class CodexRunner {
5056
5321
  resumeResponse = await appServer.threadResume(agentSessionId, projectPath);
5057
5322
  }
5058
5323
  catch (error) {
5059
- if (isCodexActiveWriterError(error) && previousAppServer && previousAppServer !== appServer) {
5324
+ if (isCodexActiveWriterError(error) && previousAppServer) {
5060
5325
  await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId);
5061
5326
  resumeResponse = await appServer.threadResume(agentSessionId, projectPath);
5062
5327
  }
@@ -6357,7 +6622,9 @@ export class CodexRunner {
6357
6622
  ...state.tokenUsage,
6358
6623
  ...(terminalTokenUsage && typeof terminalTokenUsage === 'object' ? terminalTokenUsage : {}),
6359
6624
  ...(turn.contextUsage ?? state.tokenUsage?.contextUsage ?? state.tokenUsage?.context),
6360
- }, state.modelContextId ?? state.model, this.pickNumber(state.tokenUsage?.modelContextWindow, state.tokenUsage?.model_context_window, terminalTokenUsage?.modelContextWindow, terminalTokenUsage?.model_context_window));
6625
+ }, state.modelContextId ?? state.model, state.modelContextWindowTokens ?? this.pickNumber(state.tokenUsage?.modelContextWindow, state.tokenUsage?.model_context_window, terminalTokenUsage?.modelContextWindow, terminalTokenUsage?.model_context_window));
6626
+ if (contextUsage && state.autoCompactTokens !== undefined)
6627
+ contextUsage.autoCompactTokens = state.autoCompactTokens;
6361
6628
  const modelCalls = [
6362
6629
  ...(parentTokenUsage ? [{
6363
6630
  call_index: 0,
@@ -6528,10 +6795,12 @@ export class CodexRunner {
6528
6795
  this.activeOperationReleaseTargets.clear();
6529
6796
  await Promise.all([
6530
6797
  ...[...this.retiredProviderClients].map(client => client.close()),
6798
+ ...[...this.sessionAppServerClients.values()].map(client => client.close()),
6531
6799
  this.appServerClient?.close(),
6532
6800
  this.fullAccessAppServerClient?.close(),
6533
6801
  ]);
6534
6802
  this.retiredProviderClients.clear();
6803
+ this.sessionAppServerClients.clear();
6535
6804
  this.codexSessionFileAdapter.close();
6536
6805
  this.appServerClient = null;
6537
6806
  this.fullAccessAppServerClient = null;