@skaile/workspaces 3.17.0 → 3.19.0

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 (273) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/dist/app-sdk/index.js +1 -1
  3. package/dist/{asset-feeds-FQT6GH24.js → asset-feeds-OO3NIRVI.js} +7 -7
  4. package/dist/{asset-feeds-FQT6GH24.js.map → asset-feeds-OO3NIRVI.js.map} +1 -1
  5. package/dist/asset-manager/catalog-deployer.js +3 -3
  6. package/dist/asset-manager/index.js +6 -6
  7. package/dist/asset-manager/installer.js +4 -4
  8. package/dist/bridge/codex-app-server.js +2 -203
  9. package/dist/bridge/codex-app-server.js.map +1 -1
  10. package/dist/bridge/drivers/claude-sdk.js +5 -5
  11. package/dist/bridge/drivers/codex.js +1238 -6
  12. package/dist/bridge/drivers/codex.js.map +1 -1
  13. package/dist/bridge/drivers/continue.js +2 -2
  14. package/dist/bridge/drivers/echo.js +2 -2
  15. package/dist/bridge/drivers/gemini.js +3 -3
  16. package/dist/bridge/drivers/goose.js +2 -2
  17. package/dist/bridge/drivers/omp.js +1 -1
  18. package/dist/bridge/drivers/opencode.js +2 -2
  19. package/dist/bridge/drivers/qwen.js +3 -3
  20. package/dist/bridge/index.js +7 -6
  21. package/dist/bridge/src/capability-dispatch.d.ts +1 -1
  22. package/dist/bridge/src/capability-dispatch.d.ts.map +1 -1
  23. package/dist/bridge/src/codex/credentials.d.ts +12 -0
  24. package/dist/bridge/src/codex/credentials.d.ts.map +1 -0
  25. package/dist/bridge/src/codex/inputs.d.ts +8 -0
  26. package/dist/bridge/src/codex/inputs.d.ts.map +1 -0
  27. package/dist/bridge/src/codex/instance-state.d.ts +16 -0
  28. package/dist/bridge/src/codex/instance-state.d.ts.map +1 -0
  29. package/dist/bridge/src/codex/managed-driver.d.ts +73 -0
  30. package/dist/bridge/src/codex/managed-driver.d.ts.map +1 -0
  31. package/dist/bridge/src/codex/native-approvals.d.ts +22 -0
  32. package/dist/bridge/src/codex/native-approvals.d.ts.map +1 -0
  33. package/dist/bridge/src/codex/native-mcp-approval.d.ts +13 -0
  34. package/dist/bridge/src/codex/native-mcp-approval.d.ts.map +1 -0
  35. package/dist/bridge/src/codex/native-policy.d.ts +38 -0
  36. package/dist/bridge/src/codex/native-policy.d.ts.map +1 -0
  37. package/dist/bridge/src/codex/native-protocol.generated.d.ts +291 -201
  38. package/dist/bridge/src/codex/native-protocol.generated.d.ts.map +1 -1
  39. package/dist/bridge/src/codex/native-state.d.ts +7 -0
  40. package/dist/bridge/src/codex/native-state.d.ts.map +1 -0
  41. package/dist/bridge/src/codex/questions.d.ts +19 -0
  42. package/dist/bridge/src/codex/questions.d.ts.map +1 -0
  43. package/dist/bridge/src/codex-app-server.d.ts +8 -1
  44. package/dist/bridge/src/codex-app-server.d.ts.map +1 -1
  45. package/dist/bridge/src/drivers/codex.d.ts +9 -1
  46. package/dist/bridge/src/drivers/codex.d.ts.map +1 -1
  47. package/dist/bridge/src/index.d.ts +1 -0
  48. package/dist/bridge/src/index.d.ts.map +1 -1
  49. package/dist/bridge/src/normalizer.d.ts.map +1 -1
  50. package/dist/bridge/src/runtime.d.ts +3 -2
  51. package/dist/bridge/src/runtime.d.ts.map +1 -1
  52. package/dist/bridge/src/types.d.ts +83 -4
  53. package/dist/bridge/src/types.d.ts.map +1 -1
  54. package/dist/{chunk-BCOGOM6F.js → chunk-23L3P7IB.js} +4 -4
  55. package/dist/{chunk-BCOGOM6F.js.map → chunk-23L3P7IB.js.map} +1 -1
  56. package/dist/{chunk-NC5YXVZF.js → chunk-2FDKUKDE.js} +3 -3
  57. package/dist/{chunk-NC5YXVZF.js.map → chunk-2FDKUKDE.js.map} +1 -1
  58. package/dist/{chunk-CMGYUF5P.js → chunk-34RUVLL6.js} +7 -7
  59. package/dist/{chunk-CMGYUF5P.js.map → chunk-34RUVLL6.js.map} +1 -1
  60. package/dist/{chunk-EXT2LNST.js → chunk-3BOWST5G.js} +125 -37
  61. package/dist/chunk-3BOWST5G.js.map +1 -0
  62. package/dist/{chunk-BUKPS4YL.js → chunk-4JDCKPTM.js} +2 -2
  63. package/dist/{chunk-BUKPS4YL.js.map → chunk-4JDCKPTM.js.map} +1 -1
  64. package/dist/{chunk-5KSIVLOX.js → chunk-5T7Y3AZU.js} +3 -3
  65. package/dist/{chunk-5KSIVLOX.js.map → chunk-5T7Y3AZU.js.map} +1 -1
  66. package/dist/{chunk-HEKLK4NG.js → chunk-5Y4RBNT2.js} +6 -6
  67. package/dist/{chunk-HEKLK4NG.js.map → chunk-5Y4RBNT2.js.map} +1 -1
  68. package/dist/{chunk-PYX4WZLJ.js → chunk-7ECAUWFU.js} +9 -9
  69. package/dist/{chunk-PYX4WZLJ.js.map → chunk-7ECAUWFU.js.map} +1 -1
  70. package/dist/{chunk-QFYEDM63.js → chunk-7J4W54DV.js} +5 -5
  71. package/dist/{chunk-QFYEDM63.js.map → chunk-7J4W54DV.js.map} +1 -1
  72. package/dist/{chunk-RRVQAE5D.js → chunk-7ZO3MUP3.js} +6 -5
  73. package/dist/chunk-7ZO3MUP3.js.map +1 -0
  74. package/dist/{chunk-HY6CIKFH.js → chunk-CP62G5PK.js} +8 -7
  75. package/dist/chunk-CP62G5PK.js.map +1 -0
  76. package/dist/{chunk-OIDFK7SG.js → chunk-DCG4UWJM.js} +3 -3
  77. package/dist/{chunk-OIDFK7SG.js.map → chunk-DCG4UWJM.js.map} +1 -1
  78. package/dist/{chunk-RTM4SFLA.js → chunk-GMKNGIIB.js} +7 -4
  79. package/dist/chunk-GMKNGIIB.js.map +1 -0
  80. package/dist/{chunk-CIPK5JMJ.js → chunk-H662SXKS.js} +4 -4
  81. package/dist/{chunk-CIPK5JMJ.js.map → chunk-H662SXKS.js.map} +1 -1
  82. package/dist/{chunk-VT4MPCRK.js → chunk-HFL3PYJ7.js} +3 -3
  83. package/dist/{chunk-VT4MPCRK.js.map → chunk-HFL3PYJ7.js.map} +1 -1
  84. package/dist/{chunk-NMAICJUA.js → chunk-IST2V7RU.js} +3 -3
  85. package/dist/{chunk-NMAICJUA.js.map → chunk-IST2V7RU.js.map} +1 -1
  86. package/dist/{chunk-ZNCZ7RUO.js → chunk-JVFZ5R7L.js} +3 -3
  87. package/dist/{chunk-ZNCZ7RUO.js.map → chunk-JVFZ5R7L.js.map} +1 -1
  88. package/dist/{chunk-FRER2PEN.js → chunk-KB2GC6YY.js} +16 -3
  89. package/dist/chunk-KB2GC6YY.js.map +1 -0
  90. package/dist/chunk-LOO5CB5M.js +12 -0
  91. package/dist/chunk-LOO5CB5M.js.map +1 -0
  92. package/dist/{chunk-AL6BU3SP.js → chunk-OJ4N4T4H.js} +12 -4
  93. package/dist/chunk-OJ4N4T4H.js.map +1 -0
  94. package/dist/{chunk-X7FJ3ES3.js → chunk-OLRKNOO2.js} +4 -4
  95. package/dist/{chunk-X7FJ3ES3.js.map → chunk-OLRKNOO2.js.map} +1 -1
  96. package/dist/chunk-PHBYB4XT.js +247 -0
  97. package/dist/chunk-PHBYB4XT.js.map +1 -0
  98. package/dist/{chunk-EO7IJY3Q.js → chunk-PWBURVRH.js} +3 -3
  99. package/dist/{chunk-EO7IJY3Q.js.map → chunk-PWBURVRH.js.map} +1 -1
  100. package/dist/chunk-QEZPFJX3.js +254 -0
  101. package/dist/chunk-QEZPFJX3.js.map +1 -0
  102. package/dist/{chunk-C4AP3XZB.js → chunk-QG2ZXU5W.js} +4 -4
  103. package/dist/{chunk-C4AP3XZB.js.map → chunk-QG2ZXU5W.js.map} +1 -1
  104. package/dist/{chunk-OZ7UNMTK.js → chunk-RPVTPVGX.js} +7 -5
  105. package/dist/chunk-RPVTPVGX.js.map +1 -0
  106. package/dist/{chunk-S4UA244H.js → chunk-S635WMXH.js} +4 -4
  107. package/dist/{chunk-S4UA244H.js.map → chunk-S635WMXH.js.map} +1 -1
  108. package/dist/{chunk-2XGFQKNJ.js → chunk-SBDTLR3Q.js} +2 -2
  109. package/dist/{chunk-2XGFQKNJ.js.map → chunk-SBDTLR3Q.js.map} +1 -1
  110. package/dist/{chunk-BQMRUH7J.js → chunk-SFCVAEJ5.js} +4 -4
  111. package/dist/{chunk-BQMRUH7J.js.map → chunk-SFCVAEJ5.js.map} +1 -1
  112. package/dist/{chunk-KCI7DAKE.js → chunk-SZ3HIMSX.js} +988 -238
  113. package/dist/chunk-SZ3HIMSX.js.map +1 -0
  114. package/dist/chunk-T3YLZQS4.js +336 -0
  115. package/dist/chunk-T3YLZQS4.js.map +1 -0
  116. package/dist/{chunk-PBRMY64S.js → chunk-WB4EWSDR.js} +31 -9
  117. package/dist/chunk-WB4EWSDR.js.map +1 -0
  118. package/dist/{chunk-SUPIVTLX.js → chunk-XL45U3C5.js} +3 -3
  119. package/dist/{chunk-SUPIVTLX.js.map → chunk-XL45U3C5.js.map} +1 -1
  120. package/dist/{chunk-AXEOG4B5.js → chunk-YCMHWNZA.js} +3 -3
  121. package/dist/{chunk-AXEOG4B5.js.map → chunk-YCMHWNZA.js.map} +1 -1
  122. package/dist/{chunk-SWUVULBU.js → chunk-YLSMYOHN.js} +7 -7
  123. package/dist/{chunk-SWUVULBU.js.map → chunk-YLSMYOHN.js.map} +1 -1
  124. package/dist/{chunk-NIQPSQFN.js → chunk-YWGL52GT.js} +4 -4
  125. package/dist/{chunk-NIQPSQFN.js.map → chunk-YWGL52GT.js.map} +1 -1
  126. package/dist/cli/index.js +75 -53
  127. package/dist/cli/index.js.map +1 -1
  128. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  129. package/dist/client/index.js +1 -1
  130. package/dist/client/src/client.d.ts +3 -2
  131. package/dist/client/src/client.d.ts.map +1 -1
  132. package/dist/connectors/config.js +4 -4
  133. package/dist/connectors/index.js +12 -11
  134. package/dist/connectors/src/connector-prompt.d.ts +11 -0
  135. package/dist/connectors/src/connector-prompt.d.ts.map +1 -1
  136. package/dist/core/index.js +3 -3
  137. package/dist/core/runtime-assets.js +2 -2
  138. package/dist/core/src/workspace-config.d.ts.map +1 -1
  139. package/dist/core/workspace-config.js +1 -1
  140. package/dist/deploy/index.js +3 -3
  141. package/dist/{ensure-sources-4GBXK6UR.js → ensure-sources-PR7YN3HV.js} +9 -9
  142. package/dist/{ensure-sources-4GBXK6UR.js.map → ensure-sources-PR7YN3HV.js.map} +1 -1
  143. package/dist/factory-assets/connectors/box.js +12 -11
  144. package/dist/factory-assets/connectors/deploy.js +12 -11
  145. package/dist/factory-assets/connectors/devserver.js +12 -11
  146. package/dist/factory-assets/connectors/flow/CONNECTOR.md +4 -5
  147. package/dist/factory-assets/connectors/flow/adapter.d.ts +8 -0
  148. package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
  149. package/dist/factory-assets/connectors/flow/adapter.js +12 -11
  150. package/dist/factory-assets/connectors/flow/contract/index.d.ts +1 -1
  151. package/dist/factory-assets/connectors/flow/contract/index.d.ts.map +1 -1
  152. package/dist/factory-assets/connectors/flow/contract/schema.d.ts +50 -17
  153. package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
  154. package/dist/factory-assets/connectors/flow/contract.js +3 -3
  155. package/dist/factory-assets/connectors/flow/engine/index.d.ts +1 -0
  156. package/dist/factory-assets/connectors/flow/engine/index.d.ts.map +1 -1
  157. package/dist/factory-assets/connectors/flow/engine.js +5 -5
  158. package/dist/factory-assets/connectors/flow/run-flow.js +13 -12
  159. package/dist/factory-assets/connectors/flow/subprompt-runner.d.ts +10 -1
  160. package/dist/factory-assets/connectors/flow/subprompt-runner.d.ts.map +1 -1
  161. package/dist/factory-assets/connectors/flow.js +12 -11
  162. package/dist/factory-assets/connectors/git.js +12 -11
  163. package/dist/factory-assets/connectors/gmail.js +12 -11
  164. package/dist/factory-assets/connectors/googledrive.js +12 -11
  165. package/dist/factory-assets/connectors/local.js +12 -11
  166. package/dist/factory-assets/connectors/mattermost.js +12 -11
  167. package/dist/factory-assets/connectors/memory.js +12 -11
  168. package/dist/factory-assets/connectors/minio.js +12 -11
  169. package/dist/factory-assets/connectors/postgres.js +12 -11
  170. package/dist/factory-assets/connectors/s3.js +12 -11
  171. package/dist/factory-assets/connectors/sharepoint.js +12 -11
  172. package/dist/factory-assets/connectors/sqlite.js +12 -11
  173. package/dist/factory-assets/connectors/static-server.js +12 -11
  174. package/dist/factory-assets/connectors/tunnel.js +12 -11
  175. package/dist/factory-assets/connectors/webdav.js +12 -11
  176. package/dist/factory-assets/connectors/xstate-store.js +12 -11
  177. package/dist/factory-assets/connectors/xstate.js +12 -11
  178. package/dist/{flows-2SUFOVVO.js → flows-COBS26MK.js} +6 -6
  179. package/dist/{flows-2SUFOVVO.js.map → flows-COBS26MK.js.map} +1 -1
  180. package/dist/{helpers-26LW4IXY.js → helpers-TFSZSWT5.js} +9 -9
  181. package/dist/{helpers-26LW4IXY.js.map → helpers-TFSZSWT5.js.map} +1 -1
  182. package/dist/library/index.js +4 -4
  183. package/dist/library/install.js +3 -3
  184. package/dist/{library-publish-IYGHOPEK.js → library-publish-WVIUUYG3.js} +14 -14
  185. package/dist/{library-publish-IYGHOPEK.js.map → library-publish-WVIUUYG3.js.map} +1 -1
  186. package/dist/{open-library-HH5LST7Z.js → open-library-2AWZGIWE.js} +12 -12
  187. package/dist/{open-library-HH5LST7Z.js.map → open-library-2AWZGIWE.js.map} +1 -1
  188. package/dist/{paths-4APA2PKT.js → paths-CZPCCBYX.js} +6 -6
  189. package/dist/{paths-4APA2PKT.js.map → paths-CZPCCBYX.js.map} +1 -1
  190. package/dist/{plugin-store-JQAIKR3R.js → plugin-store-ZEIBSNTO.js} +5 -5
  191. package/dist/{plugin-store-JQAIKR3R.js.map → plugin-store-ZEIBSNTO.js.map} +1 -1
  192. package/dist/{project-U5QRUCBN.js → project-XZDKNIRG.js} +10 -10
  193. package/dist/{project-U5QRUCBN.js.map → project-XZDKNIRG.js.map} +1 -1
  194. package/dist/resolver/index.js +3 -3
  195. package/dist/runner/index.js +25 -16
  196. package/dist/runner/src/capability-registry.d.ts +4 -0
  197. package/dist/runner/src/capability-registry.d.ts.map +1 -1
  198. package/dist/runner/src/codex-init.d.ts +2 -11
  199. package/dist/runner/src/codex-init.d.ts.map +1 -1
  200. package/dist/runner/src/codex-resource-tools.d.ts +16 -0
  201. package/dist/runner/src/codex-resource-tools.d.ts.map +1 -0
  202. package/dist/runner/src/codex-tools.d.ts +12 -0
  203. package/dist/runner/src/codex-tools.d.ts.map +1 -0
  204. package/dist/runner/src/define-capability.d.ts +2 -0
  205. package/dist/runner/src/define-capability.d.ts.map +1 -1
  206. package/dist/runner/src/external-mcp.d.ts +8 -3
  207. package/dist/runner/src/external-mcp.d.ts.map +1 -1
  208. package/dist/runner/src/index.d.ts +2 -0
  209. package/dist/runner/src/index.d.ts.map +1 -1
  210. package/dist/runner/src/managed-codex-bootstrap.d.ts +54 -0
  211. package/dist/runner/src/managed-codex-bootstrap.d.ts.map +1 -0
  212. package/dist/runner/src/resources.d.ts +1 -0
  213. package/dist/runner/src/resources.d.ts.map +1 -1
  214. package/dist/runner/src/serve.d.ts +5 -0
  215. package/dist/runner/src/serve.d.ts.map +1 -1
  216. package/dist/runner/src/session-builder.d.ts +18 -1
  217. package/dist/runner/src/session-builder.d.ts.map +1 -1
  218. package/dist/sdk/asset-manager.js +6 -6
  219. package/dist/sdk/bridge.js +7 -6
  220. package/dist/sdk/client.js +1 -1
  221. package/dist/sdk/core.js +3 -3
  222. package/dist/sdk/flow.js +5 -5
  223. package/dist/sdk/index.js +26 -17
  224. package/dist/sdk/index.js.map +1 -1
  225. package/dist/sdk/resolver.js +3 -3
  226. package/dist/sdk/runner.js +25 -16
  227. package/dist/sdk/session.js +2 -2
  228. package/dist/sdk/store.js +1 -1
  229. package/dist/sdk/types.js +1 -1
  230. package/dist/session/index.js +2 -2
  231. package/dist/{setup-XKTBHRWM.js → setup-J34TR5IR.js} +9 -8
  232. package/dist/setup-J34TR5IR.js.map +1 -0
  233. package/dist/{skills-Q7PJVB3W.js → skills-LG6IQSSN.js} +5 -5
  234. package/dist/{skills-Q7PJVB3W.js.map → skills-LG6IQSSN.js.map} +1 -1
  235. package/dist/{source-ODR4IU6R.js → source-QYINHHUP.js} +13 -13
  236. package/dist/{source-ODR4IU6R.js.map → source-QYINHHUP.js.map} +1 -1
  237. package/dist/{source-manifest-publish-WCJY3GAM.js → source-manifest-publish-3RBW5E2O.js} +15 -15
  238. package/dist/{source-manifest-publish-WCJY3GAM.js.map → source-manifest-publish-3RBW5E2O.js.map} +1 -1
  239. package/dist/store/index.js +1 -1
  240. package/dist/store/react.js +1 -1
  241. package/dist/store/react.js.map +1 -1
  242. package/dist/store/src/react.d.ts +1 -1
  243. package/dist/store/src/react.d.ts.map +1 -1
  244. package/dist/store/src/store.d.ts +2 -1
  245. package/dist/store/src/store.d.ts.map +1 -1
  246. package/dist/tui/index.js +25 -16
  247. package/dist/tui/index.js.map +1 -1
  248. package/dist/types/index.js +1 -1
  249. package/dist/types/src/events.d.ts +14 -1
  250. package/dist/types/src/events.d.ts.map +1 -1
  251. package/dist/types/src/index.d.ts +2 -2
  252. package/dist/types/src/index.d.ts.map +1 -1
  253. package/dist/types/src/protocol.d.ts +18 -0
  254. package/dist/types/src/protocol.d.ts.map +1 -1
  255. package/dist/types/src/runtime.d.ts +3 -1
  256. package/dist/types/src/runtime.d.ts.map +1 -1
  257. package/dist/types/src/version.d.ts +7 -1
  258. package/dist/types/src/version.d.ts.map +1 -1
  259. package/dist/workspace-plugin/adapters/mcp.js +9 -255
  260. package/dist/workspace-plugin/adapters/mcp.js.map +1 -1
  261. package/dist/workspace-plugin/adapters/omp.js +7 -7
  262. package/dist/workspace-plugin/index.js +1 -1
  263. package/package.json +4 -1
  264. package/dist/chunk-AL6BU3SP.js.map +0 -1
  265. package/dist/chunk-EXT2LNST.js.map +0 -1
  266. package/dist/chunk-FRER2PEN.js.map +0 -1
  267. package/dist/chunk-HY6CIKFH.js.map +0 -1
  268. package/dist/chunk-KCI7DAKE.js.map +0 -1
  269. package/dist/chunk-OZ7UNMTK.js.map +0 -1
  270. package/dist/chunk-PBRMY64S.js.map +0 -1
  271. package/dist/chunk-RRVQAE5D.js.map +0 -1
  272. package/dist/chunk-RTM4SFLA.js.map +0 -1
  273. package/dist/setup-XKTBHRWM.js.map +0 -1
@@ -1,22 +1,27 @@
1
- import { WorkspacePlugin } from './chunk-2XGFQKNJ.js';
1
+ import { buildWorkspaceToolDefs } from './chunk-QEZPFJX3.js';
2
+ import { findAiAssetsRoot } from './chunk-7IRJ4K4F.js';
3
+ import { WorkspacePlugin } from './chunk-SBDTLR3Q.js';
2
4
  import { assembleSystemPrompt, buildCapabilitiesPromptSection } from './chunk-W3UDISS2.js';
3
5
  import { WebSocketServerTransport } from './chunk-WQ7DE5UC.js';
4
- import { resolveFlowPath } from './chunk-HEKLK4NG.js';
5
- import { findAiAssetsRoot, deployCatalogEntry, undeployCatalogEntry } from './chunk-7BUZQVRR.js';
6
- import { registerBuiltinConnectors, buildConnectorPromptSection, findMissingPackages, installNpmPackages, ConnectorManager, ConnectorStartupError, buildSdkConnectorTools, driveOrchestratorTurn, SessionNodeExecutor, SessionSubpromptRunner, SessionInlineSubFlowRunner, buildSdkFlowTools } from './chunk-EXT2LNST.js';
7
- import { loadConnectorDeclarations, SecretProviderChain, PreMintedSecretProvider, InMemorySecretProvider, resolvedConfigToDeclarations, isKnownSecretRef, deriveSingleMaterializedConnectorDeclaration } from './chunk-5KSIVLOX.js';
8
- import { EventNormalizer } from './chunk-PBRMY64S.js';
6
+ import { prepareNativePolicy, codexInstanceEnvironment, parseCodexCredential, parseCodexRefreshInput, parseCodexRefreshResult } from './chunk-T3YLZQS4.js';
7
+ import { resolveFlowPath } from './chunk-5Y4RBNT2.js';
8
+ import { findAiAssetsRoot as findAiAssetsRoot$1, deployCatalogEntry, undeployCatalogEntry } from './chunk-7BUZQVRR.js';
9
+ import { registerBuiltinConnectors, buildConnectorPromptSection, findMissingPackages, installNpmPackages, ConnectorManager, ConnectorStartupError, buildSdkConnectorTools, buildConnectorToolDefs, buildFlowToolDefs, driveOrchestratorTurn, SessionNodeExecutor, SessionSubpromptRunner, SessionInlineSubFlowRunner, buildSdkFlowTools } from './chunk-3BOWST5G.js';
10
+ import { loadConnectorDeclarations, SecretProviderChain, PreMintedSecretProvider, InMemorySecretProvider, resolvedConfigToDeclarations, isKnownSecretRef, deriveSingleMaterializedConnectorDeclaration } from './chunk-5T7Y3AZU.js';
11
+ import { EventNormalizer } from './chunk-WB4EWSDR.js';
9
12
  import { SUPPORTED_CLOUDS, probeResumeTranscript, CLOUD_SECRET_ENV_KEYS } from './chunk-3NCGSSCU.js';
13
+ import { CodexNativeStateUnavailable } from './chunk-LOO5CB5M.js';
14
+ import { dispatchCapability } from './chunk-7ZO3MUP3.js';
10
15
  import { classifyClaudeSdkError } from './chunk-GAH4YRCI.js';
11
- import { createDriver } from './chunk-FRER2PEN.js';
12
- import { loadFlow } from './chunk-BQMRUH7J.js';
13
- import { parseFlowDefinition } from './chunk-HY6CIKFH.js';
16
+ import { createDriver } from './chunk-KB2GC6YY.js';
17
+ import { loadFlow } from './chunk-SFCVAEJ5.js';
18
+ import { parseFlowDefinition } from './chunk-CP62G5PK.js';
14
19
  import { renderStimulusPrompt } from './chunk-2D5BYAL6.js';
15
- import { PROTOCOL_VERSION } from './chunk-BCOGOM6F.js';
16
- import { resolveSettings, resolveApiKey, providerEnvKey } from './chunk-CIPK5JMJ.js';
20
+ import { PROTOCOL_VERSION } from './chunk-23L3P7IB.js';
21
+ import { resolveSettings, resolveApiKey, providerEnvKey } from './chunk-H662SXKS.js';
17
22
  import { resolveDriverPaths } from './chunk-K5GBV4SA.js';
18
- import { resolveRuntimeAssets } from './chunk-OIDFK7SG.js';
19
- import { resolveSkWorkspaceConfig, resolveAgentDir, cloudConfigFromProfile, stageMaterializedSkills, loadMcpServerDeclarations, COMPACTION_DEFAULTS, validateAssetRecipeAttr, deriveSingleMaterializedMcpDeclaration } from './chunk-OZ7UNMTK.js';
23
+ import { resolveRuntimeAssets } from './chunk-DCG4UWJM.js';
24
+ import { resolveSkWorkspaceConfig, resolveAgentDir, cloudConfigFromProfile, stageMaterializedSkills, loadMcpServerDeclarations, COMPACTION_DEFAULTS, validateAssetRecipeAttr, deriveSingleMaterializedMcpDeclaration } from './chunk-RPVTPVGX.js';
20
25
  import { withFsDeadline, fsDeadlineMs, FsDeadlineError, tryWithFsDeadline } from './chunk-MKZOK4JU.js';
21
26
  import { parseAssetRef } from './chunk-GEEW6SY2.js';
22
27
  import { resolveLogStoreConfig, createLogStoreFromConfig, OnLogBridgeSink, WsLogSink } from './chunk-FTG7CRFD.js';
@@ -25,15 +30,19 @@ import { __require } from './chunk-NSBPE2FW.js';
25
30
  import pc from 'picocolors';
26
31
  import { Marked } from 'marked';
27
32
  import { markedTerminal } from 'marked-terminal';
28
- import fs4, { readFile, stat, rm, unlink, mkdir, writeFile, readdir, rename } from 'fs/promises';
33
+ import fs4, { readFile, stat, rm, unlink, mkdir, writeFile, readdir, rename, realpath, mkdtemp, lstat } from 'fs/promises';
34
+ import { createHash, randomBytes, timingSafeEqual, randomUUID } from 'crypto';
29
35
  import path4, { join, resolve, relative, sep, isAbsolute, dirname, basename } from 'path';
30
- import { existsSync, readFileSync, mkdirSync, writeFileSync, watch, chmodSync, rmSync } from 'fs';
36
+ import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, writeFileSync, watch, chmodSync, accessSync, constants, rmSync } from 'fs';
31
37
  import { homedir } from 'os';
32
- import * as z6 from 'zod';
38
+ import * as z7 from 'zod';
33
39
  import { z } from 'zod';
34
- import { createHash, randomUUID } from 'crypto';
35
40
  import { execFile } from 'child_process';
36
41
  import { promisify } from 'util';
42
+ import { createServer } from 'http';
43
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
44
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
45
+ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
37
46
  import { parse } from 'yaml';
38
47
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
39
48
  import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
@@ -190,11 +199,11 @@ var MarkdownStreamer = class {
190
199
  }
191
200
  };
192
201
  function defineCapability(args) {
193
- const inputSchema = z6.toJSONSchema(args.input, {
202
+ const inputSchema = z7.toJSONSchema(args.input, {
194
203
  target: "draft-07",
195
204
  io: "input"
196
205
  });
197
- const outputSchema = args.output ? z6.toJSONSchema(args.output, {
206
+ const outputSchema = args.output ? z7.toJSONSchema(args.output, {
198
207
  target: "draft-07",
199
208
  io: "output"
200
209
  }) : void 0;
@@ -241,11 +250,11 @@ async function resolveMixin(ref, defaultKind, agentDir, repos) {
241
250
  return { content: stripFrontmatter(raw).trim(), source: entry.source };
242
251
  }
243
252
  async function resolveAgentMixins(manifest, agentDir, repos) {
244
- const resolve4 = (refs, kind) => Promise.all((refs ?? []).map((r) => resolveMixin(r, kind, agentDir, repos)));
253
+ const resolve5 = (refs, kind) => Promise.all((refs ?? []).map((r) => resolveMixin(r, kind, agentDir, repos)));
245
254
  const [personaResults, rulesResults, knowledgeResults] = await Promise.all([
246
- resolve4(manifest.persona, "persona"),
247
- resolve4(manifest.rules, "ruleset"),
248
- resolve4(manifest.knowledge, "knowledge")
255
+ resolve5(manifest.persona, "persona"),
256
+ resolve5(manifest.rules, "ruleset"),
257
+ resolve5(manifest.knowledge, "knowledge")
249
258
  ]);
250
259
  return {
251
260
  personas: personaResults.filter((r) => r !== null),
@@ -260,8 +269,8 @@ async function readFileSafe(filePath) {
260
269
  return "";
261
270
  }
262
271
  }
263
- function stripFrontmatter(text) {
264
- return text.replace(/^---\s*\n[\s\S]*?\n---\s*\n?/, "");
272
+ function stripFrontmatter(text2) {
273
+ return text2.replace(/^---\s*\n[\s\S]*?\n---\s*\n?/, "");
265
274
  }
266
275
  function parseRef(ref, defaultKind) {
267
276
  let rest = ref.trim();
@@ -545,7 +554,7 @@ function registerCompositionCapabilities(registry, entries) {
545
554
  scope: "session",
546
555
  kind: "query",
547
556
  userInvokable: false,
548
- input: z6.strictObject({}),
557
+ input: z7.strictObject({}),
549
558
  handler: async (_args, ctx) => {
550
559
  ctx.log.info("loading composed asset content", {
551
560
  ref: entry.ref,
@@ -711,6 +720,364 @@ async function buildEnvironmentSection(projectDir) {
711
720
  lines.push(`**Working directory:** ${projectDir}`);
712
721
  return lines.join("\n");
713
722
  }
723
+ async function cancellable(work, signal) {
724
+ let abort = () => {
725
+ };
726
+ try {
727
+ return await Promise.race([
728
+ work,
729
+ new Promise((_resolve, reject) => {
730
+ abort = () => reject(new Error("CODEX_TOOL_CANCELLED"));
731
+ signal.addEventListener("abort", abort, { once: true });
732
+ if (signal.aborted) abort();
733
+ })
734
+ ]);
735
+ } finally {
736
+ signal.removeEventListener("abort", abort);
737
+ }
738
+ }
739
+ async function prepareCodexTools(options) {
740
+ options.signal.throwIfAborted();
741
+ if (!options.requiredTools.length) throw new Error("CODEX_REQUIRED_TOOL_UNAVAILABLE");
742
+ const { hooks } = options;
743
+ let turnSignal;
744
+ let toolsListTotal = 0;
745
+ let toolsCallTotal = 0;
746
+ const lifetime = new AbortController();
747
+ const signal = AbortSignal.any([options.signal, lifetime.signal]);
748
+ const list = () => hooks.composeTools().filter((tool) => {
749
+ const cap = hooks.resolve(tool.name);
750
+ return cap && (cap.audience ?? ["llm", "user"]).includes("llm") && !tool.name.startsWith("host.") && !tool.name.startsWith("runner.");
751
+ });
752
+ const validate = async () => {
753
+ signal.throwIfAborted();
754
+ const names = new Set(list().map((tool) => tool.name));
755
+ if (options.requiredTools.some((name) => !names.has(name)))
756
+ throw new Error("CODEX_REQUIRED_TOOL_UNAVAILABLE");
757
+ };
758
+ await validate();
759
+ const signature = () => JSON.stringify(list());
760
+ const initialSignature = signature();
761
+ const bearer = randomBytes(32).toString("base64url");
762
+ const authorization = Buffer.from(`Bearer ${bearer}`);
763
+ const peers = /* @__PURE__ */ new Set();
764
+ const transports = /* @__PURE__ */ new Map();
765
+ let closed = false;
766
+ const http = createServer((request, response) => {
767
+ void (async () => {
768
+ const supplied = Buffer.from(request.headers.authorization ?? "");
769
+ if (closed || supplied.length !== authorization.length || !timingSafeEqual(supplied, authorization)) {
770
+ response.writeHead(401).end();
771
+ return;
772
+ }
773
+ if (request.url !== "/mcp") {
774
+ response.writeHead(404).end();
775
+ return;
776
+ }
777
+ const id = request.headers["mcp-session-id"];
778
+ let transport = typeof id === "string" ? transports.get(id) : void 0;
779
+ let allocation;
780
+ try {
781
+ if (!transport) {
782
+ if (id || request.method !== "POST") {
783
+ response.writeHead(400).end();
784
+ return;
785
+ }
786
+ if (peers.size >= 2) {
787
+ response.writeHead(429).end();
788
+ return;
789
+ }
790
+ const server = new Server(
791
+ { name: "skaile-capabilities", version: "1" },
792
+ { capabilities: { tools: { listChanged: true } } }
793
+ );
794
+ transport = new StreamableHTTPServerTransport({
795
+ sessionIdGenerator: randomUUID,
796
+ onsessioninitialized: (sessionId) => {
797
+ transports.set(sessionId, transport);
798
+ }
799
+ });
800
+ peers.add(server);
801
+ allocation = server;
802
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
803
+ toolsListTotal = Math.min(512, toolsListTotal + 1);
804
+ return {
805
+ tools: list().map((tool) => ({
806
+ name: tool.name,
807
+ description: tool.description,
808
+ inputSchema: { ...tool.parameters, type: "object" }
809
+ }))
810
+ };
811
+ });
812
+ server.setRequestHandler(CallToolRequestSchema, async (call, extra) => {
813
+ toolsCallTotal = Math.min(512, toolsCallTotal + 1);
814
+ const currentTurn = turnSignal;
815
+ const cancellation = AbortSignal.any([
816
+ signal,
817
+ extra.signal,
818
+ ...currentTurn ? [currentTurn] : []
819
+ ]);
820
+ try {
821
+ cancellation.throwIfAborted();
822
+ if (!currentTurn || currentTurn !== turnSignal)
823
+ throw new Error("CODEX_TOOL_UNAVAILABLE");
824
+ if (!list().some((tool) => tool.name === call.params.name))
825
+ throw new Error("CODEX_TOOL_UNAVAILABLE");
826
+ const { result } = await cancellable(
827
+ dispatchCapability(
828
+ hooks,
829
+ randomUUID(),
830
+ call.params.name,
831
+ call.params.arguments ?? {},
832
+ () => {
833
+ },
834
+ cancellation
835
+ ),
836
+ cancellation
837
+ );
838
+ cancellation.throwIfAborted();
839
+ if (!currentTurn || currentTurn !== turnSignal)
840
+ throw new Error("CODEX_TOOL_UNAVAILABLE");
841
+ const payload = result === void 0 ? {} : result;
842
+ const isError = typeof payload === "object" && payload !== null && ("error" in payload && typeof payload.error === "string" || "ok" in payload && payload.ok === false || "isError" in payload && payload.isError === true);
843
+ if (typeof payload === "object" && payload !== null && "content" in payload && Array.isArray(payload.content))
844
+ return { content: payload.content, isError };
845
+ return {
846
+ content: [{ type: "text", text: JSON.stringify(payload) }],
847
+ isError
848
+ };
849
+ } catch {
850
+ return {
851
+ content: [
852
+ {
853
+ type: "text",
854
+ text: cancellation.aborted ? "CODEX_TOOL_CANCELLED" : "CODEX_TOOL_FAILED"
855
+ }
856
+ ],
857
+ isError: true
858
+ };
859
+ }
860
+ });
861
+ server.onclose = () => {
862
+ peers.delete(server);
863
+ if (transport?.sessionId) transports.delete(transport.sessionId);
864
+ };
865
+ await server.connect(transport);
866
+ }
867
+ await transport.handleRequest(request, response);
868
+ } finally {
869
+ if (allocation && !transport?.sessionId) {
870
+ peers.delete(allocation);
871
+ await allocation.close();
872
+ }
873
+ }
874
+ })().catch(() => {
875
+ if (!response.headersSent) response.writeHead(500).end();
876
+ else response.destroy();
877
+ });
878
+ });
879
+ const unsubscribe = hooks.onToolsChanged?.(() => {
880
+ for (const peer of peers) void peer.sendToolListChanged().catch(() => {
881
+ });
882
+ });
883
+ let disposal;
884
+ const dispose = () => disposal ??= (async () => {
885
+ closed = true;
886
+ lifetime.abort();
887
+ unsubscribe?.();
888
+ options.signal.removeEventListener("abort", abort);
889
+ await Promise.allSettled([...peers].map((peer) => peer.close()));
890
+ http.closeAllConnections();
891
+ if (http.listening) await new Promise((resolve5) => http.close(() => resolve5()));
892
+ })();
893
+ const abort = () => {
894
+ void dispose();
895
+ };
896
+ options.signal.addEventListener("abort", abort, { once: true });
897
+ try {
898
+ signal.throwIfAborted();
899
+ await new Promise((resolve5, reject) => {
900
+ http.once("error", reject);
901
+ http.listen(0, "127.0.0.1", resolve5);
902
+ });
903
+ signal.throwIfAborted();
904
+ const address = http.address();
905
+ if (!address || typeof address === "string") throw new Error("CODEX_REQUIRED_TOOL_UNAVAILABLE");
906
+ return {
907
+ approvalServerName: "skaile-capabilities",
908
+ diagnostics: {
909
+ serverName: "skaile-capabilities",
910
+ requestCounts: () => ({ toolsListTotal, toolsCallTotal })
911
+ },
912
+ mcpServers: {
913
+ "skaile-capabilities": {
914
+ url: `http://127.0.0.1:${address.port}/mcp`,
915
+ http_headers: { Authorization: `Bearer ${bearer}` },
916
+ required: true
917
+ }
918
+ },
919
+ onServerRequest: Object.fromEntries(
920
+ Object.entries(options.approvals).filter(
921
+ ([method, handler]) => [
922
+ "item/commandExecution/requestApproval",
923
+ "item/fileChange/requestApproval",
924
+ "item/permissions/requestApproval"
925
+ ].includes(method) && typeof handler === "function"
926
+ )
927
+ ),
928
+ beginTurn: (next) => {
929
+ turnSignal = next;
930
+ },
931
+ validate,
932
+ needsReload: () => signature() !== initialSignature,
933
+ instructions: `Available Skaile MCP tools: ${list().map((tool) => tool.name).join(", ")}`,
934
+ dispose
935
+ };
936
+ } catch {
937
+ await dispose();
938
+ http.closeAllConnections();
939
+ if (http.listening) await new Promise((resolve5) => http.close(() => resolve5()));
940
+ throw new Error("CODEX_REQUIRED_TOOL_UNAVAILABLE");
941
+ }
942
+ }
943
+ function registerCodexToolDefinitions(registry, namespace, tools) {
944
+ const owned = tools.map(
945
+ (tool) => defineCapability({
946
+ name: `${namespace}.${tool.name}`,
947
+ description: tool.description,
948
+ input: z7.object(tool.inputSchema),
949
+ side: "agent",
950
+ origin: { kind: "framework" },
951
+ audience: ["llm"],
952
+ handler: async (input, ctx) => {
953
+ ctx.signal?.throwIfAborted();
954
+ return tool.handler(input);
955
+ }
956
+ })
957
+ );
958
+ if (owned.some((cap) => registry.resolve(cap.name))) throw new Error("CODEX_TOOL_CONFLICT");
959
+ for (const cap of owned) registry.register(cap, "agent");
960
+ return () => {
961
+ for (const cap of owned) if (registry.resolve(cap.name) === cap) registry.deregister(cap.name);
962
+ };
963
+ }
964
+ function contains(root, target) {
965
+ const path5 = relative(root, target);
966
+ return path5 === "" || !path5.startsWith("..") && !isAbsolute(path5);
967
+ }
968
+ async function canonical(path5) {
969
+ try {
970
+ return await realpath(path5);
971
+ } catch (error) {
972
+ if (error.code !== "ENOENT") throw error;
973
+ const parent = dirname(path5);
974
+ if (parent === path5) throw error;
975
+ return resolve(await canonical(parent), relative(parent, path5));
976
+ }
977
+ }
978
+ async function assertScopedTree(path5, root) {
979
+ let remaining = 1e4;
980
+ async function visit(entry) {
981
+ if (--remaining < 0) throw new Error("CODEX_RESOURCE_SCOPE_INVALID");
982
+ let stat3;
983
+ try {
984
+ stat3 = await lstat(entry);
985
+ } catch (error) {
986
+ if (error.code === "ENOENT") return;
987
+ throw error;
988
+ }
989
+ if (!contains(root, await realpath(entry)) || stat3.isSymbolicLink())
990
+ throw new Error("CODEX_RESOURCE_SCOPE_INVALID");
991
+ if (stat3.isDirectory())
992
+ for (const child of await readdir(entry)) await visit(join(entry, child));
993
+ }
994
+ await visit(path5);
995
+ }
996
+ async function registerCodexResourceTools(options) {
997
+ const project = await realpath(options.projectDir);
998
+ const privateRoot = await canonical(resolve(options.privateDirectory));
999
+ if (contains(project, privateRoot) || contains(privateRoot, project))
1000
+ throw new Error("CODEX_RESOURCE_SCOPE_INVALID");
1001
+ const statePath = join(project, ".skaile", "plugin-state.json");
1002
+ const assertStateScope = async () => {
1003
+ if (!contains(project, await canonical(statePath)))
1004
+ throw new Error("CODEX_RESOURCE_SCOPE_INVALID");
1005
+ };
1006
+ await assertStateScope();
1007
+ const plugin = new WorkspacePlugin({
1008
+ projectDir: options.projectDir,
1009
+ connectorManager: options.manager ?? void 0,
1010
+ driver: "codex",
1011
+ provider: "openai",
1012
+ model: options.model
1013
+ });
1014
+ await plugin.store.load();
1015
+ const removals = [];
1016
+ const protectFlow = (tools) => tools.map((tool) => ({
1017
+ ...tool,
1018
+ handler: async (input) => {
1019
+ if (tool.name === "mount_read") {
1020
+ const mount = options.manager?.listConnectors().find((entry) => entry.id === input.mount_id);
1021
+ if (!mount?.mountPath || typeof input.path !== "string")
1022
+ throw new Error("CODEX_RESOURCE_SCOPE_INVALID");
1023
+ const root = await realpath(mount.mountPath);
1024
+ const target = await realpath(resolve(root, input.path));
1025
+ if (!contains(project, root) || !contains(root, target))
1026
+ throw new Error("CODEX_RESOURCE_SCOPE_INVALID");
1027
+ }
1028
+ if (tool.name.startsWith("skill_") || ["flow_list", "flow_show", "flow_find_flow_for_session"].includes(tool.name)) {
1029
+ const assets = await findAiAssetsRoot(project);
1030
+ if (assets) await assertScopedTree(assets, project);
1031
+ }
1032
+ if (tool.name.startsWith("session_") || tool.name.includes("session"))
1033
+ await assertScopedTree(join(project, ".skaile", "sessions"), project);
1034
+ if (tool.name === "connector_exec" && options.manager && typeof input.connector_id === "string" && options.manager.listConnectors().some((entry) => entry.id === input.connector_id && entry.driver === "flow") && !buildFlowToolDefs(options.manager, input.connector_id).some(
1035
+ (operation) => operation.name === input.operation
1036
+ ))
1037
+ throw new Error("CODEX_TOOL_UNAVAILABLE");
1038
+ return tool.handler(input);
1039
+ }
1040
+ }));
1041
+ try {
1042
+ removals.push(
1043
+ registerCodexToolDefinitions(
1044
+ options.registry,
1045
+ "workspace",
1046
+ protectFlow(
1047
+ buildWorkspaceToolDefs(plugin).filter(
1048
+ (tool) => ![
1049
+ "workspace_test_secret",
1050
+ "workspace_validate",
1051
+ "workspace_reload",
1052
+ "skill_check_requirements"
1053
+ ].includes(tool.name)
1054
+ )
1055
+ )
1056
+ )
1057
+ );
1058
+ if (options.manager)
1059
+ removals.push(
1060
+ registerCodexToolDefinitions(
1061
+ options.registry,
1062
+ "connector",
1063
+ protectFlow(buildConnectorToolDefs(options.manager, { shellAccess: false }))
1064
+ )
1065
+ );
1066
+ } catch (error) {
1067
+ for (const remove of removals) remove();
1068
+ throw error;
1069
+ }
1070
+ return async () => {
1071
+ for (const remove of removals) remove();
1072
+ await assertStateScope();
1073
+ await plugin.shutdown();
1074
+ };
1075
+ }
1076
+ function registerCodexFlowTools(registry, manager, connectorId) {
1077
+ const tools = buildFlowToolDefs(manager, connectorId);
1078
+ if (!tools.length) throw new Error("CODEX_REQUIRED_TOOL_UNAVAILABLE");
1079
+ return registerCodexToolDefinitions(registry, "flow", tools);
1080
+ }
714
1081
  async function agentDefinitionExists(agentDir) {
715
1082
  try {
716
1083
  await fs4.access(path4.join(agentDir, "agent.yaml"));
@@ -1043,17 +1410,17 @@ var McpServerAlreadyRegisteredError = class extends Error {
1043
1410
  }
1044
1411
  id;
1045
1412
  };
1046
- function resolveRecordSecrets(record, secrets) {
1047
- if (!secrets) return record;
1413
+ function resolveRecordSecrets(record2, secrets) {
1414
+ if (!secrets) return record2;
1048
1415
  const resolved = {};
1049
- for (const [k, v] of Object.entries(record)) {
1416
+ for (const [k, v] of Object.entries(record2)) {
1050
1417
  resolved[k] = secrets.resolve(v) ?? v;
1051
1418
  }
1052
1419
  return resolved;
1053
1420
  }
1054
- function resolveRecordSecretsStrict(record, secrets, ctx) {
1421
+ function resolveRecordSecretsStrict(record2, secrets, ctx) {
1055
1422
  const resolved = {};
1056
- for (const [k, v] of Object.entries(record)) {
1423
+ for (const [k, v] of Object.entries(record2)) {
1057
1424
  const value = secrets?.resolve(v);
1058
1425
  if (value === void 0 && isKnownSecretRef(v)) {
1059
1426
  throw new Error(
@@ -1069,13 +1436,15 @@ var RESERVED_MCP_SERVER_IDS = /* @__PURE__ */ new Set([
1069
1436
  "skaile-workspace",
1070
1437
  "skaile-capabilities"
1071
1438
  ]);
1072
- async function resolveExternalMcpDeclarations(projectDir, sessionId) {
1439
+ async function resolveExternalMcpDeclarations(projectDir, sessionId, managedCodex = false) {
1073
1440
  const mcpLog = createLogger({
1074
1441
  kind: "mcp",
1075
1442
  subkind: "wiring",
1076
1443
  instance: sessionId ?? "no-session"
1077
1444
  });
1078
1445
  const mcpDeclarations = await loadMcpServerDeclarations(projectDir);
1446
+ if (managedCodex && mcpDeclarations.length > 0)
1447
+ throw new Error("CODEX_MANAGED_PROJECT_MCP_UNSUPPORTED");
1079
1448
  mcpLog.debug("loaded MCP declarations", { count: mcpDeclarations.length });
1080
1449
  const recipeCache = createRecipeCache();
1081
1450
  const nixFlakeRef = process.env.SKAILE_NIX_FLAKE_REF ?? "/etc/skaile/flake";
@@ -1414,37 +1783,40 @@ var ExternalMcpManager = class {
1414
1783
  inputZod: PASSTHROUGH_INPUT_ZOD,
1415
1784
  handler: async (input, ctx) => {
1416
1785
  const call = { name: tool.name, arguments: input ?? {} };
1786
+ const invoke = () => ctx.signal ? server.client.callTool(call, void 0, { signal: ctx.signal }) : server.client.callTool(call);
1417
1787
  let result;
1418
1788
  try {
1419
- result = await server.client.callTool(call);
1789
+ result = await invoke();
1420
1790
  } catch (err) {
1421
- if (isMcpAuthError(err) && await this.reauthAndReconnect(server)) {
1791
+ if (!ctx.signal?.aborted && isMcpAuthError(err) && await this.reauthAndReconnect(server)) {
1422
1792
  ctx.log.info("mcp tool retried after 401 re-mint", { tool: name });
1423
- result = await server.client.callTool(call);
1793
+ result = await invoke();
1424
1794
  } else {
1425
1795
  throw err;
1426
1796
  }
1427
1797
  }
1428
1798
  const content = result.content ?? [];
1429
- const text = content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
1799
+ const text2 = content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
1430
1800
  if (result.isError) {
1431
- throw new Error(text || `MCP tool ${name} returned an error`);
1801
+ throw new Error(text2 || `MCP tool ${name} returned an error`);
1432
1802
  }
1433
- ctx.log.debug("mcp tool ok", { tool: name, hasText: text.length > 0 });
1434
- return text.length > 0 ? text : content;
1803
+ ctx.log.debug("mcp tool ok", { tool: name, hasText: text2.length > 0 });
1804
+ return text2.length > 0 ? text2 : content;
1435
1805
  }
1436
1806
  };
1437
1807
  }
1438
1808
  /**
1439
1809
  * Deregister every tool and close every client (kills the subprocesses).
1440
- * Best-effort: a failed close on one server does not prevent the rest.
1810
+ * Best-effort by default: a failed close on one server does not prevent the rest.
1811
+ * With strict:true, report close failures after all owned cleanup attempts.
1441
1812
  *
1442
1813
  * Drains any in-flight 401 reconnect first: a `doReauthAndReconnect` resolving
1443
1814
  * after teardown would set `server.client` to a freshly-connected client that
1444
1815
  * nothing then closes (leak). Awaiting `reauthInFlight` guarantees we close the
1445
1816
  * LATEST client.
1446
1817
  */
1447
- async dispose() {
1818
+ async dispose(options = {}) {
1819
+ const failures = [];
1448
1820
  await Promise.allSettled(this.servers.map((s) => s.reauthInFlight).filter(Boolean));
1449
1821
  for (const server of this.servers) {
1450
1822
  for (const toolName of server.toolNames) {
@@ -1453,6 +1825,7 @@ var ExternalMcpManager = class {
1453
1825
  try {
1454
1826
  await server.client.close();
1455
1827
  } catch (err) {
1828
+ failures.push(err);
1456
1829
  this.log.warn("MCP server close failed", {
1457
1830
  id: server.id,
1458
1831
  error: err instanceof Error ? err.message : String(err)
@@ -1460,6 +1833,8 @@ var ExternalMcpManager = class {
1460
1833
  }
1461
1834
  }
1462
1835
  this.servers.length = 0;
1836
+ if (options.strict && failures.length > 0)
1837
+ throw new AggregateError(failures, "MCP server cleanup failed");
1463
1838
  }
1464
1839
  };
1465
1840
 
@@ -1486,6 +1861,7 @@ function buildMcpPromptSection(declarations, connected) {
1486
1861
 
1487
1862
  // runner/src/resources.ts
1488
1863
  async function buildAgentResources(projectDir, driverType, _onLog, watch, secretProvider, sessionMeta, tokenMediator, preMintedSecrets, deferFilesystemMounts, capabilityRegistry, fallbackConnectorDeclarations, extraMcpDeclarations) {
1864
+ const managedProjectMcp = sessionMeta?.managedCodex ? await resolveExternalMcpDeclarations(projectDir, sessionMeta.sessionId, true) : void 0;
1489
1865
  const resLog = createLogger({
1490
1866
  kind: "runner",
1491
1867
  subkind: "resources",
@@ -1512,7 +1888,8 @@ async function buildAgentResources(projectDir, driverType, _onLog, watch, secret
1512
1888
  for (const w of runtimeAssets.warnings) {
1513
1889
  resLog.warn("runtime asset warning", { code: w.code, message: w.message });
1514
1890
  }
1515
- await maybeInstallNpmPeerDeps(runtimeAssets, projectDir, resLog);
1891
+ if (!sessionMeta?.managedCodex)
1892
+ await maybeInstallNpmPeerDeps(runtimeAssets, projectDir, resLog);
1516
1893
  const diskDeclarations = loadConnectorDeclarations(projectDir);
1517
1894
  const connectorDeclarations = diskDeclarations.length > 0 ? diskDeclarations : fallbackConnectorDeclarations ?? [];
1518
1895
  if (diskDeclarations.length === 0 && connectorDeclarations.length > 0) {
@@ -1571,7 +1948,7 @@ async function buildAgentResources(projectDir, driverType, _onLog, watch, secret
1571
1948
  }
1572
1949
  if (capabilityRegistry) {
1573
1950
  externalMcpDeclarations = mergeExtraMcpDeclarations(
1574
- await resolveExternalMcpDeclarations(projectDir, sessionMeta?.sessionId),
1951
+ managedProjectMcp ?? await resolveExternalMcpDeclarations(projectDir, sessionMeta?.sessionId),
1575
1952
  extraMcpDeclarations
1576
1953
  );
1577
1954
  externalMcpManager = await startExternalMcpServers(
@@ -1832,6 +2209,9 @@ function toSdkMcpServerConfig(decl, secrets) {
1832
2209
 
1833
2210
  // runner/src/session-builder.ts
1834
2211
  async function createAgentSession(config) {
2212
+ const managed = config.managedCodex;
2213
+ if (managed && (config.driver !== "codex" || config.provider !== "openai" || !config.model || !config.aiProviderConfigId || !config.capabilityRegistry || !config.capabilities || config.apiKey || config.cloud && config.cloud !== "default" || config.cloudConfig || config.cloudSecrets))
2214
+ throw new Error("AI_PROFILE_INVALID");
1835
2215
  const {
1836
2216
  projectDir,
1837
2217
  cwd: cwdOverride,
@@ -1850,7 +2230,17 @@ async function createAgentSession(config) {
1850
2230
  telemetry,
1851
2231
  trace
1852
2232
  } = config;
2233
+ const managedWorkspaceConfig = managed ? wsConfigOverride ?? resolveSkWorkspaceConfig(projectDir) : void 0;
2234
+ if (managedWorkspaceConfig?.agent?.["prompt-extensions"]?.length)
2235
+ throw new Error("CODEX_MANAGED_PROMPT_EXTENSIONS_UNSUPPORTED");
1853
2236
  const agentCwd = cwdOverride ?? projectDir;
2237
+ if (managed)
2238
+ prepareNativePolicy({
2239
+ cwd: agentCwd,
2240
+ privateRoot: managed.runtime.privateRoot,
2241
+ privateDirectory: managed.runtime.privateDirectory,
2242
+ sandboxMode: managed.sandboxMode
2243
+ });
1854
2244
  const sessionLog = createLogger({
1855
2245
  kind: "runner",
1856
2246
  subkind: "session",
@@ -1861,12 +2251,12 @@ async function createAgentSession(config) {
1861
2251
  provider: providerOverride,
1862
2252
  model: modelOverride
1863
2253
  });
1864
- const driverType = settings.driver ?? "omp";
1865
- const provider = settings.provider;
1866
- const model = settings.model;
1867
- const cloud = config.cloud ?? settings.cloud ?? "default";
1868
- const cloudConfig = config.cloudConfig ?? settings.cloudConfig;
1869
- const apiKey = cloud === "bedrock" || cloud === "vertex" || cloud === "azure" ? config.apiKey : config.apiKey ?? resolveApiKey(provider ?? "anthropic", settings);
2254
+ const driverType = managed ? "codex" : settings.driver ?? "omp";
2255
+ const provider = managed ? config.provider : settings.provider;
2256
+ const model = managed ? config.model : settings.model;
2257
+ const cloud = managed ? "default" : config.cloud ?? settings.cloud ?? "default";
2258
+ const cloudConfig = managed ? void 0 : config.cloudConfig ?? settings.cloudConfig;
2259
+ const apiKey = managed ? void 0 : cloud === "bedrock" || cloud === "vertex" || cloud === "azure" ? config.apiKey : config.apiKey ?? resolveApiKey(provider ?? "anthropic", settings);
1870
2260
  const manifest = agentDir ? await loadAgentManifest(agentDir) : void 0;
1871
2261
  const {
1872
2262
  resourceManager,
@@ -1887,7 +2277,8 @@ async function createAgentSession(config) {
1887
2277
  {
1888
2278
  provider,
1889
2279
  model,
1890
- sessionId
2280
+ sessionId,
2281
+ ...managed ? { managedCodex: true } : {}
1891
2282
  },
1892
2283
  config.tokenMediator,
1893
2284
  config.preMintedSecrets,
@@ -1896,7 +2287,7 @@ async function createAgentSession(config) {
1896
2287
  config.fallbackConnectorDeclarations,
1897
2288
  config.getExtraMcpDeclarations?.()
1898
2289
  );
1899
- const wsConfig = wsConfigOverride ?? resolveSkWorkspaceConfig(projectDir);
2290
+ const wsConfig = managedWorkspaceConfig ?? wsConfigOverride ?? resolveSkWorkspaceConfig(projectDir);
1900
2291
  const contextSection = buildContextSection(wsConfig.agent?.context);
1901
2292
  const userPromptSection = wsConfig.agent?.prompt?.trim();
1902
2293
  const environmentSection = await buildEnvironmentSection(projectDir);
@@ -1912,6 +2303,20 @@ async function createAgentSession(config) {
1912
2303
  }
1913
2304
  const composition = await resolveSessionComposition(agentDir, manifest, projectDir, sessionLog);
1914
2305
  const compositionBlocks = composition?.inlineBlocks ?? [];
2306
+ const disposeManagedTools = managed ? await registerCodexResourceTools({
2307
+ registry: config.capabilityRegistry,
2308
+ manager: resourceManager,
2309
+ projectDir,
2310
+ model: config.model,
2311
+ privateDirectory: managed.runtime.privateRoot
2312
+ }) : void 0;
2313
+ const disposeSessionResources = async () => {
2314
+ try {
2315
+ await disposeManagedTools?.();
2316
+ } finally {
2317
+ await dispose();
2318
+ }
2319
+ };
1915
2320
  const additionalSections = config.additionalPromptSections ?? [];
1916
2321
  const systemPromptSections = buildSystemPromptSections({
1917
2322
  contextSection,
@@ -1935,27 +2340,39 @@ async function createAgentSession(config) {
1935
2340
  ]);
1936
2341
  logAssembledSystemPrompt(systemPrompt, sessionLog);
1937
2342
  const thinking = config.thinking ?? wsConfig.agent_config?.default?.thinking;
1938
- const effort = config.effort ?? wsConfig.agent_config?.default?.effort;
2343
+ const effort = config.effort ?? (managed ? void 0 : wsConfig.agent_config?.default?.effort);
1939
2344
  const maxTurns = maxTurnsOverride ?? manifest?.runtime?.max_turns;
1940
- const driver = await createSessionDriver({
1941
- config,
1942
- driverType,
1943
- agentCwd,
1944
- provider,
1945
- model,
1946
- cloud,
1947
- cloudConfig,
1948
- manifest,
1949
- maxTurns,
1950
- apiKey,
1951
- systemPrompt,
1952
- thinking,
1953
- effort,
1954
- sessionId,
1955
- resumeSessionId,
1956
- mcpServers,
1957
- agentDir
1958
- });
2345
+ let driver;
2346
+ try {
2347
+ driver = await createSessionDriver({
2348
+ config,
2349
+ driverType,
2350
+ agentCwd,
2351
+ provider,
2352
+ model,
2353
+ cloud,
2354
+ cloudConfig,
2355
+ manifest,
2356
+ maxTurns,
2357
+ apiKey,
2358
+ systemPrompt,
2359
+ thinking,
2360
+ effort,
2361
+ sessionId,
2362
+ resumeSessionId,
2363
+ mcpServers,
2364
+ agentDir
2365
+ });
2366
+ } catch (error) {
2367
+ try {
2368
+ await disposeSessionResources();
2369
+ } catch (cleanupError) {
2370
+ throw new AggregateError([error, cleanupError], "Session creation and cleanup failed", {
2371
+ cause: error
2372
+ });
2373
+ }
2374
+ throw error;
2375
+ }
1959
2376
  if (telemetry && trace) {
1960
2377
  driver.setTelemetry(telemetry, trace);
1961
2378
  }
@@ -1968,7 +2385,7 @@ async function createAgentSession(config) {
1968
2385
  driverType,
1969
2386
  provider,
1970
2387
  model,
1971
- dispose,
2388
+ dispose: disposeSessionResources,
1972
2389
  startWatching,
1973
2390
  getOrCreateExternalMcpManager,
1974
2391
  getExternalMcpManager,
@@ -1976,6 +2393,45 @@ async function createAgentSession(config) {
1976
2393
  systemPromptSections
1977
2394
  };
1978
2395
  }
2396
+ function createManagedCodexSubpromptDriver(config, model, cwd, privateDirectory) {
2397
+ const managed = config.managedCodex;
2398
+ if (!managed || !model || !config.sessionId || !config.aiProviderConfigId || !config.capabilities)
2399
+ return Promise.reject(new Error("AI_PROFILE_INVALID"));
2400
+ prepareNativePolicy({
2401
+ cwd,
2402
+ privateRoot: managed.runtime.privateRoot,
2403
+ privateDirectory,
2404
+ sandboxMode: managed.sandboxMode
2405
+ });
2406
+ return createDriver("codex", {
2407
+ cwd,
2408
+ provider: "openai",
2409
+ model,
2410
+ sessionId: `${config.sessionId}:subprompt:${randomUUID()}`,
2411
+ maxTurns: 1,
2412
+ aiProviderConfigId: config.aiProviderConfigId,
2413
+ driverOptions: {
2414
+ codex: {
2415
+ authSource: "managed",
2416
+ approvalPolicy: managed.approvalPolicy,
2417
+ sandboxMode: managed.sandboxMode,
2418
+ reasoningEffort: managed.reasoningEffort,
2419
+ managedRuntime: {
2420
+ ...managed.runtime,
2421
+ privateDirectory,
2422
+ nativeTurnBudget: 1,
2423
+ credential: structuredClone(managed.runtime.credential),
2424
+ prepareTools: (signal) => prepareCodexTools({
2425
+ hooks: config.capabilities,
2426
+ requiredTools: managed.requiredTools,
2427
+ approvals: managed.approvals,
2428
+ signal
2429
+ })
2430
+ }
2431
+ }
2432
+ }
2433
+ });
2434
+ }
1979
2435
  async function loadPromptExtensions(paths, projectDir, log) {
1980
2436
  if (!paths?.length) return [];
1981
2437
  const loaded = await Promise.all(
@@ -2079,6 +2535,25 @@ function createSessionDriver(args) {
2079
2535
  agentDir
2080
2536
  } = args;
2081
2537
  return createDriver(driverType, {
2538
+ ...config.managedCodex ? {
2539
+ driverOptions: {
2540
+ codex: {
2541
+ authSource: "managed",
2542
+ approvalPolicy: config.managedCodex.approvalPolicy,
2543
+ sandboxMode: config.managedCodex.sandboxMode,
2544
+ reasoningEffort: config.managedCodex.reasoningEffort,
2545
+ managedRuntime: {
2546
+ ...config.managedCodex.runtime,
2547
+ prepareTools: (signal) => prepareCodexTools({
2548
+ hooks: config.capabilities,
2549
+ requiredTools: config.managedCodex.requiredTools,
2550
+ approvals: config.managedCodex.approvals,
2551
+ signal
2552
+ })
2553
+ }
2554
+ }
2555
+ }
2556
+ } : {},
2082
2557
  cwd: agentCwd,
2083
2558
  provider,
2084
2559
  model: model ?? manifest?.model?.preferred,
@@ -2149,14 +2624,14 @@ async function runAgentChat(opts) {
2149
2624
  ${message}`;
2150
2625
  }
2151
2626
  try {
2152
- await new Promise((resolve4, reject) => {
2627
+ await new Promise((resolve5, reject) => {
2153
2628
  const onEvent = (event) => {
2154
2629
  if (event.type === "agent_end") {
2155
2630
  driver.off("agent-event", onEvent);
2156
2631
  mdStream.end();
2157
2632
  process.stdout.write("\n");
2158
2633
  driver.kill();
2159
- resolve4();
2634
+ resolve5();
2160
2635
  } else if (event.type === "error") {
2161
2636
  driver.off("agent-event", onEvent);
2162
2637
  const err = Object.assign(new Error(String(event.error)), {
@@ -2206,10 +2681,10 @@ function keywordSearch(capabilities, query, limit) {
2206
2681
  return scored.slice(0, limit).map((x) => x.cap);
2207
2682
  }
2208
2683
  function builtinCapabilities(registry) {
2209
- const listFilterSchema = z6.strictObject({
2210
- side: z6.enum(["client", "agent"]).optional(),
2211
- originKind: z6.enum(["framework", "client", "agent", "flow", "skill", "mcp", "connector", "mount"]).optional(),
2212
- scope: z6.enum(["session", "turn"]).optional()
2684
+ const listFilterSchema = z7.strictObject({
2685
+ side: z7.enum(["client", "agent"]).optional(),
2686
+ originKind: z7.enum(["framework", "client", "agent", "flow", "skill", "mcp", "connector", "mount"]).optional(),
2687
+ scope: z7.enum(["session", "turn"]).optional()
2213
2688
  });
2214
2689
  return [
2215
2690
  defineCapability({
@@ -2235,9 +2710,9 @@ function builtinCapabilities(registry) {
2235
2710
  origin: { kind: "framework" },
2236
2711
  kind: "query",
2237
2712
  userInvokable: false,
2238
- input: z6.strictObject({
2239
- query: z6.string(),
2240
- limit: z6.number().int().positive().optional()
2713
+ input: z7.strictObject({
2714
+ query: z7.string(),
2715
+ limit: z7.number().int().positive().optional()
2241
2716
  }),
2242
2717
  handler: async ({ query, limit }) => keywordSearch(registry.list(), query, limit ?? 10)
2243
2718
  }),
@@ -2249,7 +2724,7 @@ function builtinCapabilities(registry) {
2249
2724
  origin: { kind: "framework" },
2250
2725
  kind: "query",
2251
2726
  userInvokable: false,
2252
- input: z6.strictObject({ name: z6.string() }),
2727
+ input: z7.strictObject({ name: z7.string() }),
2253
2728
  handler: async ({ name }) => {
2254
2729
  const cap = registry.resolve(name);
2255
2730
  if (!cap) return null;
@@ -2293,6 +2768,22 @@ var CapabilityRegistry = class {
2293
2768
  byName = /* @__PURE__ */ new Map();
2294
2769
  logger;
2295
2770
  remoteInvoker;
2771
+ toolListeners = /* @__PURE__ */ new Set();
2772
+ /** Observe inventory changes without caching a second tool registry. */
2773
+ onToolsChanged(listener) {
2774
+ this.toolListeners.add(listener);
2775
+ return () => {
2776
+ this.toolListeners.delete(listener);
2777
+ };
2778
+ }
2779
+ toolsChanged() {
2780
+ for (const listener of this.toolListeners) {
2781
+ try {
2782
+ listener();
2783
+ } catch {
2784
+ }
2785
+ }
2786
+ }
2296
2787
  constructor(logger) {
2297
2788
  this.logger = logger ?? createLogger({ kind: "runner", subkind: "capability-registry" });
2298
2789
  }
@@ -2359,6 +2850,7 @@ var CapabilityRegistry = class {
2359
2850
  return;
2360
2851
  }
2361
2852
  this.byName.set(cap.name, cap);
2853
+ this.toolsChanged();
2362
2854
  this.logger.info("capability registered", {
2363
2855
  name: cap.name,
2364
2856
  side: cap.side,
@@ -2372,6 +2864,7 @@ var CapabilityRegistry = class {
2372
2864
  */
2373
2865
  deregister(name) {
2374
2866
  if (this.byName.delete(name)) {
2867
+ this.toolsChanged();
2375
2868
  this.logger.info("capability deregistered", { name });
2376
2869
  }
2377
2870
  }
@@ -2473,6 +2966,7 @@ var CapabilityRegistry = class {
2473
2966
  handler: HYDRATED_REJECT_HANDLER
2474
2967
  };
2475
2968
  this.byName.set(cap.name, stub);
2969
+ this.toolsChanged();
2476
2970
  hydrated++;
2477
2971
  }
2478
2972
  this.logger.info("capability registry hydrated", { count: hydrated, total: snapshot.length });
@@ -2486,6 +2980,7 @@ var CapabilityRegistry = class {
2486
2980
  * @throws when the capability is unknown or the input fails validation
2487
2981
  */
2488
2982
  async invoke(name, input, baseCtx) {
2983
+ baseCtx.signal?.throwIfAborted();
2489
2984
  const cap = this.resolve(name);
2490
2985
  if (!cap) {
2491
2986
  throw new Error(`Unknown capability: ${name}`);
@@ -2539,12 +3034,12 @@ var CapabilityRegistry = class {
2539
3034
  }
2540
3035
  };
2541
3036
  function computeCapabilitySignature(caps) {
2542
- const canonical = caps.slice().sort((a, b) => a.name.localeCompare(b.name)).map((c) => ({
3037
+ const canonical2 = caps.slice().sort((a, b) => a.name.localeCompare(b.name)).map((c) => ({
2543
3038
  name: c.name,
2544
3039
  origin: c.origin.kind,
2545
3040
  schemaSha256: sha256(JSON.stringify(c.inputSchema ?? {}))
2546
3041
  }));
2547
- return sha256(JSON.stringify(canonical));
3042
+ return sha256(JSON.stringify(canonical2));
2548
3043
  }
2549
3044
  function sha256(input) {
2550
3045
  return createHash("sha256").update(input).digest("hex");
@@ -2583,7 +3078,7 @@ function buildClientCapabilityHandler(args) {
2583
3078
  });
2584
3079
  return {};
2585
3080
  }
2586
- return new Promise((resolve4, reject) => {
3081
+ return new Promise((resolve5, reject) => {
2587
3082
  const timer = setTimeout(() => {
2588
3083
  args.pending.delete(callId);
2589
3084
  reject(
@@ -2592,7 +3087,7 @@ function buildClientCapabilityHandler(args) {
2592
3087
  )
2593
3088
  );
2594
3089
  }, timeoutMs);
2595
- args.pending.set(callId, { resolve: resolve4, reject, timer });
3090
+ args.pending.set(callId, { resolve: resolve5, reject, timer });
2596
3091
  args.emit({
2597
3092
  type: "capability_invoked",
2598
3093
  callId,
@@ -2832,38 +3327,8 @@ async function handleMountResourceRequest(command, manager, emit) {
2832
3327
  });
2833
3328
  }
2834
3329
  }
2835
- var identifier = z6.string().min(1).max(4096);
2836
- var timestamp = z6.iso.datetime({ offset: true });
2837
- var common = {
2838
- configId: identifier,
2839
- credentialVersion: z6.number().int().nonnegative().safe(),
2840
- mintedAt: timestamp
2841
- };
2842
- var subscription = z6.strictObject({
2843
- ...common,
2844
- kind: z6.literal("codex-subscription"),
2845
- accessToken: z6.string().min(1).max(65536),
2846
- chatgptAccountId: identifier,
2847
- chatgptPlanType: identifier.optional(),
2848
- expiresAt: timestamp
2849
- });
2850
- var delivery = z6.discriminatedUnion("kind", [
2851
- subscription,
2852
- z6.strictObject({
2853
- ...common,
2854
- kind: z6.literal("openai-api-key"),
2855
- apiKey: z6.string().min(1).max(65536)
2856
- })
2857
- ]);
2858
- function parseCodexCredential(value, now = Date.now()) {
2859
- const parsed = delivery.safeParse(value);
2860
- if (!parsed.success) throw new Error("Invalid managed AI credential");
2861
- const credential = parsed.data;
2862
- const mintedAt = Date.parse(credential.mintedAt);
2863
- if (mintedAt > now || credential.kind === "codex-subscription" && (Date.parse(credential.expiresAt) <= now || Date.parse(credential.expiresAt) <= mintedAt))
2864
- throw new Error("Invalid managed AI credential timestamps");
2865
- return credential;
2866
- }
3330
+
3331
+ // runner/src/codex-init.ts
2867
3332
  function validateCodexInit(cmd, supported, previous) {
2868
3333
  const requirements = cmd.requiredRuntimeFeatures;
2869
3334
  if (requirements !== void 0 && (!Array.isArray(requirements) || requirements.some((item) => typeof item !== "string" || !supported.includes(item))))
@@ -2885,6 +3350,111 @@ function validateCodexInit(cmd, supported, previous) {
2885
3350
  if (cmd.secrets && Object.keys(cmd.secrets).some((key) => /openai|codex/i.test(key)))
2886
3351
  throw new Error("Conflicting managed AI credential delivery");
2887
3352
  }
3353
+ var text = z7.string().min(1).max(4096);
3354
+ var timeout = z7.number().int().positive().max(18e5).optional();
3355
+ var zHost = z7.object({
3356
+ schemaVersion: z7.literal(1),
3357
+ sessionId: z7.string().min(1).max(128),
3358
+ runtime: z7.object({
3359
+ executable: text,
3360
+ executableArgs: z7.array(text).max(64).optional(),
3361
+ privateDirectory: text,
3362
+ privateRoot: text,
3363
+ environment: z7.record(z7.string(), z7.string()),
3364
+ instructionFiles: z7.array(text).max(64).optional(),
3365
+ skillsDirectory: text.optional(),
3366
+ requestTimeoutMs: timeout,
3367
+ turnTimeoutMs: timeout,
3368
+ interactionTimeoutMs: timeout
3369
+ }).strict(),
3370
+ requiredTools: z7.array(z7.string().min(1).max(256)).min(1).max(1024),
3371
+ approvalPolicy: z7.enum(["never", "on-request", "untrusted"]),
3372
+ sandboxMode: z7.enum(["read-only", "workspace-write"]),
3373
+ reasoningEffort: z7.enum(["minimal", "low", "medium", "high", "xhigh"]),
3374
+ subpromptModels: z7.object({
3375
+ small: text,
3376
+ deep: text,
3377
+ available: z7.array(text).min(1).max(1024)
3378
+ }).strict()
3379
+ }).strict();
3380
+ var refused = () => new Error("CODEX_MANAGED_BOOTSTRAP_INVALID");
3381
+ var overlaps = (a, b) => {
3382
+ const within = (child, parent) => {
3383
+ const rel = relative(parent, child);
3384
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
3385
+ };
3386
+ return within(a, b) || within(b, a);
3387
+ };
3388
+ var denyNativeGrants = {
3389
+ "item/commandExecution/requestApproval": async () => ({ decision: "decline" }),
3390
+ "item/fileChange/requestApproval": async () => ({ decision: "decline" }),
3391
+ "item/permissions/requestApproval": async () => ({ permissions: {}, scope: "turn" })
3392
+ };
3393
+ function validateManagedCodexHost(input, projectDir) {
3394
+ try {
3395
+ const { approvals, ...config } = input;
3396
+ const parsed = zHost.parse(config);
3397
+ const runtime = parsed.runtime;
3398
+ if (!isAbsolute(runtime.executable) || !isAbsolute(runtime.privateDirectory)) throw refused();
3399
+ prepareNativePolicy({
3400
+ cwd: projectDir,
3401
+ privateRoot: runtime.privateRoot,
3402
+ privateDirectory: runtime.privateDirectory,
3403
+ sandboxMode: parsed.sandboxMode
3404
+ });
3405
+ const state = lstatSync(runtime.privateDirectory);
3406
+ if (!state.isDirectory() || state.isSymbolicLink() || state.mode & 63) throw refused();
3407
+ if (process.getuid && state.uid !== process.getuid()) throw refused();
3408
+ if (overlaps(realpathSync(runtime.privateDirectory), realpathSync(projectDir))) throw refused();
3409
+ if (!lstatSync(realpathSync(runtime.executable)).isFile()) throw refused();
3410
+ accessSync(runtime.executable, constants.X_OK);
3411
+ codexInstanceEnvironment(runtime.environment, runtime.privateDirectory);
3412
+ for (const key of ["HTTP_PROXY", "HTTPS_PROXY"]) {
3413
+ const value = runtime.environment[key];
3414
+ if (value && (new URL(value).username || new URL(value).password)) throw refused();
3415
+ }
3416
+ return { ...parsed, approvals: { ...approvals ?? denyNativeGrants } };
3417
+ } catch {
3418
+ throw refused();
3419
+ }
3420
+ }
3421
+ function loadManagedCodexHostConfig(file, projectDir) {
3422
+ try {
3423
+ if (!isAbsolute(file)) throw refused();
3424
+ const stat3 = lstatSync(file);
3425
+ if (!stat3.isFile() || stat3.isSymbolicLink() || stat3.size > 64 * 1024 || stat3.mode & 63)
3426
+ throw refused();
3427
+ if (process.getuid && stat3.uid !== 0 && stat3.uid !== process.getuid()) throw refused();
3428
+ if (overlaps(realpathSync(file), realpathSync(projectDir))) throw refused();
3429
+ return validateManagedCodexHost(
3430
+ zHost.parse(JSON.parse(readFileSync(file, "utf8"))),
3431
+ projectDir
3432
+ );
3433
+ } catch {
3434
+ throw refused();
3435
+ }
3436
+ }
3437
+ function bindManagedCodexInit(host, cmd, refreshCredential) {
3438
+ const profile = cmd.resolvedConfig.agentConfig;
3439
+ const credential = parseCodexCredential(cmd.credentials.ai);
3440
+ if (!profile?.authMode || !["subscription", "api-key"].includes(profile.authMode) || cmd.identity.sessionId !== host.sessionId || profile?.driver !== "codex" || profile.provider !== "openai" || profile.cloud !== void 0 && profile.cloud !== "default" || profile.cloudConfig || !profile.model || !host.subpromptModels.available.includes(profile.model) || credential.configId !== cmd.resolvedConfig.aiProviderConfigId || profile.authMode === "subscription" !== (credential.kind === "codex-subscription"))
3441
+ throw refused();
3442
+ const reasoningEffort = profile.effort ?? host.reasoningEffort;
3443
+ if (!["minimal", "low", "medium", "high", "xhigh"].includes(reasoningEffort)) throw refused();
3444
+ return {
3445
+ runtime: {
3446
+ ...host.runtime,
3447
+ credential,
3448
+ ...credential.kind === "codex-subscription" ? { refreshCredential } : {}
3449
+ },
3450
+ approvals: host.approvals ?? denyNativeGrants,
3451
+ requiredTools: [...host.requiredTools],
3452
+ approvalPolicy: host.approvalPolicy,
3453
+ sandboxMode: host.sandboxMode,
3454
+ reasoningEffort,
3455
+ subpromptModels: { ...host.subpromptModels, available: [...host.subpromptModels.available] }
3456
+ };
3457
+ }
2888
3458
  var MINT_RETRY_MAX_ATTEMPTS = 3;
2889
3459
  var MINT_RETRY_BASE_DELAY_MS = 2e3;
2890
3460
  var MINT_RETRY_MAX_DELAY_MS = 5e3;
@@ -3199,8 +3769,8 @@ var CompactionGate = class {
3199
3769
  begin() {
3200
3770
  const hold = /* @__PURE__ */ Symbol("compaction");
3201
3771
  if (this.held.size === 0) {
3202
- this.opened = new Promise((resolve4) => {
3203
- this.release = resolve4;
3772
+ this.opened = new Promise((resolve5) => {
3773
+ this.release = resolve5;
3204
3774
  });
3205
3775
  }
3206
3776
  this.held.add(hold);
@@ -3253,8 +3823,8 @@ var CompactionGate = class {
3253
3823
  };
3254
3824
  async function raceDeadline(opened, ms) {
3255
3825
  let timer;
3256
- const expired = new Promise((resolve4) => {
3257
- timer = setTimeout(() => resolve4("timeout"), ms);
3826
+ const expired = new Promise((resolve5) => {
3827
+ timer = setTimeout(() => resolve5("timeout"), ms);
3258
3828
  timer.unref?.();
3259
3829
  });
3260
3830
  try {
@@ -3292,8 +3862,8 @@ var DriverSwapGate = class {
3292
3862
  */
3293
3863
  beginTurn() {
3294
3864
  let resolveTurn;
3295
- const turn = new Promise((resolve4) => {
3296
- resolveTurn = resolve4;
3865
+ const turn = new Promise((resolve5) => {
3866
+ resolveTurn = resolve5;
3297
3867
  });
3298
3868
  this.turnTail = this.turnTail.then(() => turn);
3299
3869
  let ended = false;
@@ -3481,12 +4051,12 @@ tighter prose, never from leaving material out.`;
3481
4051
  var ABORT_SETTLE_GRACE_MS = 5e3;
3482
4052
  var MAX_CARRIED_SUMMARY_CHARS = 24e3;
3483
4053
  var MAX_FAILURE_DIAGNOSTIC_CHARS = 4e3;
3484
- function truncateTo(text, max) {
3485
- if (text.length <= max) return text;
3486
- return `${text.slice(0, max)}... [truncated]`;
4054
+ function truncateTo(text2, max) {
4055
+ if (text2.length <= max) return text2;
4056
+ return `${text2.slice(0, max)}... [truncated]`;
3487
4057
  }
3488
- function truncateDiagnostic(text) {
3489
- return truncateTo(text, MAX_FAILURE_DIAGNOSTIC_CHARS);
4058
+ function truncateDiagnostic(text2) {
4059
+ return truncateTo(text2, MAX_FAILURE_DIAGNOSTIC_CHARS);
3490
4060
  }
3491
4061
  var RATE_LIMIT_TEXT_MAX_CHARS = 1500;
3492
4062
  var RATE_LIMIT_TEXT_PATTERNS = [
@@ -3510,14 +4080,14 @@ function resolveContextWindow(driverWindow, model) {
3510
4080
  }
3511
4081
  return driverWindow || DEFAULT_CONTEXT_WINDOW;
3512
4082
  }
3513
- function detectRateLimitInSummary(text) {
3514
- if (text.length > RATE_LIMIT_TEXT_MAX_CHARS) return false;
3515
- return RATE_LIMIT_TEXT_PATTERNS.some((p) => p.test(text));
4083
+ function detectRateLimitInSummary(text2) {
4084
+ if (text2.length > RATE_LIMIT_TEXT_MAX_CHARS) return false;
4085
+ return RATE_LIMIT_TEXT_PATTERNS.some((p) => p.test(text2));
3516
4086
  }
3517
- function validateCompactionOutput(text, tokensBefore, tokensAfter) {
3518
- if (!text.trim()) return { ok: false, errorCode: "empty" };
3519
- if (detectRateLimitInSummary(text)) return { ok: false, errorCode: "rate_limit" };
3520
- if (text.length < MIN_SUMMARY_CHARS) return { ok: false, errorCode: "too_short" };
4087
+ function validateCompactionOutput(text2, tokensBefore, tokensAfter) {
4088
+ if (!text2.trim()) return { ok: false, errorCode: "empty" };
4089
+ if (detectRateLimitInSummary(text2)) return { ok: false, errorCode: "rate_limit" };
4090
+ if (text2.length < MIN_SUMMARY_CHARS) return { ok: false, errorCode: "too_short" };
3521
4091
  if (tokensBefore > 0 && tokensAfter / tokensBefore > MAX_COMPRESSION_RATIO) {
3522
4092
  return { ok: false, errorCode: "poor_ratio" };
3523
4093
  }
@@ -3775,8 +4345,8 @@ var CompactionOrchestrator = class {
3775
4345
  try {
3776
4346
  this.driver.on("agent-event", captureHandler);
3777
4347
  const running = this.driver.prompt(prompt);
3778
- const expiry = new Promise((resolve4) => {
3779
- timer = setTimeout(() => resolve4("expired"), timeoutMs);
4348
+ const expiry = new Promise((resolve5) => {
4349
+ timer = setTimeout(() => resolve5("expired"), timeoutMs);
3780
4350
  });
3781
4351
  const outcome = await Promise.race([running.then(() => "settled"), expiry]);
3782
4352
  if (outcome === "expired") {
@@ -3792,8 +4362,8 @@ var CompactionOrchestrator = class {
3792
4362
  this.opts.onLog?.(`[compaction] abort after timeout failed: ${String(abortErr)}`);
3793
4363
  });
3794
4364
  let settleTimer;
3795
- const graceExpired = new Promise((resolve4) => {
3796
- settleTimer = setTimeout(resolve4, ABORT_SETTLE_GRACE_MS);
4365
+ const graceExpired = new Promise((resolve5) => {
4366
+ settleTimer = setTimeout(resolve5, ABORT_SETTLE_GRACE_MS);
3797
4367
  settleTimer.unref?.();
3798
4368
  });
3799
4369
  await Promise.race([Promise.all([aborted, settled]), graceExpired]);
@@ -4204,8 +4774,8 @@ function toPreMinted(token) {
4204
4774
  function buildSessionResourceHandlers(deps) {
4205
4775
  const { getResourceManager, getPreMintedSecrets, emitResourcesAvailable, log, getProjectDir } = deps;
4206
4776
  async function add(kind, input) {
4207
- const rm2 = getResourceManager();
4208
- if (!rm2) return { ok: false, code: "no_session", message: "session resources not ready" };
4777
+ const rm3 = getResourceManager();
4778
+ if (!rm3) return { ok: false, code: "no_session", message: "session resources not ready" };
4209
4779
  const decl = asDeclaration(input.declaration);
4210
4780
  if (!decl) {
4211
4781
  return { ok: false, code: "invalid_declaration", message: "declaration missing id/driver" };
@@ -4219,7 +4789,7 @@ function buildSessionResourceHandlers(deps) {
4219
4789
  );
4220
4790
  }
4221
4791
  try {
4222
- await rm2.connect(decl);
4792
+ await rm3.connect(decl);
4223
4793
  } catch (err) {
4224
4794
  if (input.preMintedToken) {
4225
4795
  getPreMintedSecrets()?.unset(kind, decl.id);
@@ -4256,8 +4826,8 @@ function buildSessionResourceHandlers(deps) {
4256
4826
  message: `no materialized connector at ${join(root, name)}`
4257
4827
  };
4258
4828
  }
4259
- const rm2 = getResourceManager();
4260
- if (!rm2) return { ok: false, code: "no_session", message: "session resources not ready" };
4829
+ const rm3 = getResourceManager();
4830
+ if (!rm3) return { ok: false, code: "no_session", message: "session resources not ready" };
4261
4831
  if (preMintedToken) {
4262
4832
  const ps = getPreMintedSecrets();
4263
4833
  if (ps) ps.set("connector", decl.id, toPreMinted(preMintedToken));
@@ -4267,7 +4837,7 @@ function buildSessionResourceHandlers(deps) {
4267
4837
  );
4268
4838
  }
4269
4839
  try {
4270
- await rm2.connect(decl);
4840
+ await rm3.connect(decl);
4271
4841
  } catch (err) {
4272
4842
  if (preMintedToken) {
4273
4843
  getPreMintedSecrets()?.unset("connector", decl.id);
@@ -4285,13 +4855,13 @@ function buildSessionResourceHandlers(deps) {
4285
4855
  addMount: (input) => add("mount", input),
4286
4856
  attachConnectorInstance,
4287
4857
  removeResource: async (input) => {
4288
- const rm2 = getResourceManager();
4289
- if (!rm2) return { ok: false, code: "no_session", message: "session resources not ready" };
4290
- if (!rm2.has(input.id)) {
4858
+ const rm3 = getResourceManager();
4859
+ if (!rm3) return { ok: false, code: "no_session", message: "session resources not ready" };
4860
+ if (!rm3.has(input.id)) {
4291
4861
  return { ok: false, code: "not_found", message: `no resource with id ${input.id}` };
4292
4862
  }
4293
4863
  try {
4294
- await rm2.disconnect(input.id);
4864
+ await rm3.disconnect(input.id);
4295
4865
  } catch (err) {
4296
4866
  const message = err instanceof Error ? err.message : String(err);
4297
4867
  log(`[session-resource] runner.remove_resource failed for ${input.id}: ${message}`);
@@ -4307,8 +4877,8 @@ function buildSessionResourceHandlers(deps) {
4307
4877
  updateCredential: async (input) => {
4308
4878
  const ps = getPreMintedSecrets();
4309
4879
  if (!ps) return { ok: false, code: "no_session", message: "session resources not ready" };
4310
- const rm2 = getResourceManager();
4311
- if (rm2 && !rm2.has(input.id)) {
4880
+ const rm3 = getResourceManager();
4881
+ if (rm3 && !rm3.has(input.id)) {
4312
4882
  return { ok: false, code: "not_found", message: `no resource with id ${input.id}` };
4313
4883
  }
4314
4884
  ps.set(input.kind, input.id, input.mint);
@@ -4429,54 +4999,54 @@ function notImplemented(name) {
4429
4999
  message: `${name} handler not configured`
4430
5000
  };
4431
5001
  }
4432
- var requiredUnknown = z6.unknown().refine(() => true);
4433
- var preMintedTokenSchema = z6.object({
4434
- token: z6.string(),
4435
- expiresAt: z6.string().nullable().optional()
5002
+ var requiredUnknown = z7.unknown().refine(() => true);
5003
+ var preMintedTokenSchema = z7.object({
5004
+ token: z7.string(),
5005
+ expiresAt: z7.string().nullable().optional()
4436
5006
  }).optional();
4437
- var mountDeclarationInput = z6.strictObject({
5007
+ var mountDeclarationInput = z7.strictObject({
4438
5008
  declaration: requiredUnknown,
4439
5009
  preMintedToken: preMintedTokenSchema,
4440
5010
  // The platform attaches a workspace-migration directive on add_mount; the
4441
5011
  // handler ignores it for now (replace-workspace hot-migration is a follow-up).
4442
5012
  // Accepted here so a real platform add_mount payload validates.
4443
- migration: z6.unknown().optional()
5013
+ migration: z7.unknown().optional()
4444
5014
  });
4445
- var connectorDeclarationInput = z6.strictObject({
5015
+ var connectorDeclarationInput = z7.strictObject({
4446
5016
  declaration: requiredUnknown,
4447
5017
  preMintedToken: preMintedTokenSchema
4448
5018
  });
4449
- var addMcpServerInputSchema = z6.strictObject({
5019
+ var addMcpServerInputSchema = z7.strictObject({
4450
5020
  declaration: requiredUnknown,
4451
5021
  preMintedToken: preMintedTokenSchema
4452
5022
  });
4453
- var attachInstanceInputSchema = z6.strictObject({
4454
- kind: z6.string(),
4455
- name: z6.string(),
5023
+ var attachInstanceInputSchema = z7.strictObject({
5024
+ kind: z7.string(),
5025
+ name: z7.string(),
4456
5026
  preMintedToken: preMintedTokenSchema
4457
5027
  });
4458
- var removeResourceInput = z6.strictObject({
4459
- id: z6.string()
5028
+ var removeResourceInput = z7.strictObject({
5029
+ id: z7.string()
4460
5030
  });
4461
- var updateCredentialInput = z6.strictObject({
4462
- kind: z6.enum(["mount", "connector"]),
4463
- id: z6.string(),
5031
+ var updateCredentialInput = z7.strictObject({
5032
+ kind: z7.enum(["mount", "connector"]),
5033
+ id: z7.string(),
4464
5034
  // `CredentialMint` is a discriminated union from `@skaile/workspaces/types`.
4465
5035
  // We accept it as `z.unknown()` here because Zod can't easily mirror
4466
5036
  // a discriminated TypeScript union without duplicating the schema —
4467
5037
  // the platform side has already validated the shape before sending.
4468
5038
  mint: requiredUnknown
4469
5039
  });
4470
- var setLogLevelInput = z6.strictObject({
4471
- level: z6.enum(["silent", "error", "warn", "info", "debug", "trace"])
5040
+ var setLogLevelInput = z7.strictObject({
5041
+ level: z7.enum(["silent", "error", "warn", "info", "debug", "trace"])
4472
5042
  });
4473
- var setStateInput = z6.strictObject({
4474
- store: z6.string(),
4475
- key: z6.string(),
5043
+ var setStateInput = z7.strictObject({
5044
+ store: z7.string(),
5045
+ key: z7.string(),
4476
5046
  value: requiredUnknown
4477
5047
  });
4478
- var lifecycleInput = z6.strictObject({
4479
- phase: z6.enum(["hibernate", "close", "compact"])
5048
+ var lifecycleInput = z7.strictObject({
5049
+ phase: z7.enum(["hibernate", "close", "compact"])
4480
5050
  });
4481
5051
  var VALID_LOG_STORE_LEVELS = /* @__PURE__ */ new Set(["debug", "info", "warn", "error"]);
4482
5052
  function buildRunnerCapabilities(handlers) {
@@ -4774,9 +5344,9 @@ function createSessionStimulusBus(opts) {
4774
5344
  connectorId,
4775
5345
  fragmentLength: sig.promptFragment.length
4776
5346
  });
4777
- return new Promise((resolve4, reject) => {
5347
+ return new Promise((resolve5, reject) => {
4778
5348
  const q = getQueue(connectorId);
4779
- q.pending.push({ signal: sig, resolve: resolve4, reject });
5349
+ q.pending.push({ signal: sig, resolve: resolve5, reject });
4780
5350
  startTimerIfNeeded(connectorId, q, coalesceMs);
4781
5351
  });
4782
5352
  }
@@ -4861,6 +5431,9 @@ function pickRepointedManager(next, current, disposed) {
4861
5431
  if (current !== null && current === disposed) return null;
4862
5432
  return current;
4863
5433
  }
5434
+ function supportsLiveToolUpdates(driverType, managedCodex = false) {
5435
+ return driverType !== "claude-sdk" && !(driverType === "codex" && managedCodex);
5436
+ }
4864
5437
  function buildResourcesAvailablePayload(manager, mcpManager, driverLive, bakedServerIds) {
4865
5438
  const { mounts, connectors } = splitConnectorsForWire(manager);
4866
5439
  const mcp_servers = (mcpManager?.listServers() ?? []).map((s) => ({
@@ -5106,19 +5679,19 @@ function createFlowConnectorReadiness(isReady) {
5106
5679
  wait(timeoutMs, isSatisfied) {
5107
5680
  const satisfied = isSatisfied ?? isReady;
5108
5681
  if (satisfied()) return Promise.resolve(true);
5109
- return new Promise((resolve4) => {
5682
+ return new Promise((resolve5) => {
5110
5683
  let timer;
5111
5684
  const waiter = {
5112
5685
  satisfied,
5113
5686
  release: () => {
5114
5687
  clearTimeout(timer);
5115
- resolve4(true);
5688
+ resolve5(true);
5116
5689
  }
5117
5690
  };
5118
5691
  timer = setTimeout(() => {
5119
5692
  const idx = waiters.indexOf(waiter);
5120
5693
  if (idx >= 0) waiters.splice(idx, 1);
5121
- resolve4(false);
5694
+ resolve5(false);
5122
5695
  }, timeoutMs);
5123
5696
  timer.unref?.();
5124
5697
  waiters.push(waiter);
@@ -5469,10 +6042,20 @@ function stimulusFromMetas(metas) {
5469
6042
  return { kind: "state_changed" };
5470
6043
  }
5471
6044
  async function startAgentServer(opts) {
6045
+ const managedHost = opts.managedCodex ? validateManagedCodexHost(opts.managedCodex, opts.projectDir) : void 0;
6046
+ if (managedHost && opts.sessionId && opts.sessionId !== managedHost.sessionId)
6047
+ throw new Error("CODEX_MANAGED_BOOTSTRAP_INVALID");
6048
+ const authToken = opts.authToken ?? process.env.SKAILE_WS_AUTH_TOKEN;
6049
+ if (managedHost && !opts.transport && !authToken)
6050
+ throw new Error("CODEX_MANAGED_BOOTSTRAP_INVALID");
6051
+ const supportedRuntimeFeatures = managedHost ? ["codex-app-server-v1"] : [];
6052
+ let managedBootstrapClosed = false;
5472
6053
  const port = opts.port ?? 8080;
5473
- const sessionId = opts.sessionId ?? process.env.SKAILE_SESSION_ID ?? "session-unknown";
6054
+ const sessionId = managedHost?.sessionId ?? opts.sessionId ?? process.env.SKAILE_SESSION_ID ?? "session-unknown";
5474
6055
  const resumeSessionId = opts.resumeSessionId ?? process.env.SKAILE_RESUME_SESSION_ID;
5475
6056
  const wsConfig = resolveSkWorkspaceConfig(opts.projectDir);
6057
+ if (managedHost && wsConfig.agent?.["prompt-extensions"]?.length)
6058
+ throw new Error("CODEX_MANAGED_PROMPT_EXTENSIONS_UNSUPPORTED");
5476
6059
  const { store: logStore, dispose: disposeLogStore } = bootstrapRunnerLogStore({
5477
6060
  sessionId,
5478
6061
  projectDir: opts.projectDir,
@@ -5498,7 +6081,6 @@ async function startAgentServer(opts) {
5498
6081
  } else {
5499
6082
  serverLog.warn("no agent definition found in skaile.yaml");
5500
6083
  }
5501
- const authToken = opts.authToken ?? process.env.SKAILE_WS_AUTH_TOKEN;
5502
6084
  const transport = opts.transport ?? new WebSocketServerTransport({ port, onLog: log, ...authToken ? { authToken } : {} });
5503
6085
  logStore.addSink(
5504
6086
  new WsLogSink({
@@ -5521,30 +6103,45 @@ async function startAgentServer(opts) {
5521
6103
  );
5522
6104
  bootstrapCapabilityRegistry(capabilityRegistry);
5523
6105
  const pendingCapabilityCalls = /* @__PURE__ */ new Map();
5524
- const remoteCapabilityInvoker = (name, input, timeoutMs) => {
6106
+ const remoteCapabilityInvoker = (name, input, timeoutMs, signal) => {
5525
6107
  const callId = typeof crypto?.randomUUID === "function" ? crypto.randomUUID() : `rcap-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;
5526
- return new Promise((resolve4, reject) => {
6108
+ return new Promise((resolve5, reject) => {
5527
6109
  if (!transport.connected) {
5528
6110
  reject(new Error(`Transport disconnected; cannot invoke remote capability ${name}`));
5529
6111
  return;
5530
6112
  }
5531
- const timer = setTimeout(() => {
6113
+ if (signal?.aborted) {
6114
+ reject(signal.reason);
6115
+ return;
6116
+ }
6117
+ const finish = (error, value) => {
6118
+ clearTimeout(timer);
6119
+ signal?.removeEventListener("abort", abort);
5532
6120
  pendingCapabilityCalls.delete(callId);
5533
- reject(new Error(`Remote capability ${name} (callId=${callId}) timed out`));
5534
- }, timeoutMs ?? DEFAULT_CAPABILITY_CALL_TIMEOUT_MS);
5535
- pendingCapabilityCalls.set(callId, { resolve: resolve4, reject, timer });
5536
- transport.send({
5537
- type: "capability_invoked",
5538
- callId,
5539
- name,
5540
- input,
5541
- invokedBy: "agent"
6121
+ if (error) reject(error);
6122
+ else resolve5(value);
6123
+ };
6124
+ const abort = () => finish(signal?.reason ?? new Error("Remote capability aborted"));
6125
+ const timer = setTimeout(
6126
+ () => finish(new Error(`Remote capability ${name} (callId=${callId}) timed out`)),
6127
+ timeoutMs ?? DEFAULT_CAPABILITY_CALL_TIMEOUT_MS
6128
+ );
6129
+ pendingCapabilityCalls.set(callId, {
6130
+ resolve: (value) => finish(null, value),
6131
+ reject: (error) => finish(error),
6132
+ timer
5542
6133
  });
6134
+ signal?.addEventListener("abort", abort, { once: true });
6135
+ try {
6136
+ transport.send({ type: "capability_invoked", callId, name, input, invokedBy: "agent" });
6137
+ } catch (error) {
6138
+ finish(error);
6139
+ }
5543
6140
  });
5544
6141
  };
5545
6142
  let aiProviderConfigId;
5546
- const sleep = (ms) => new Promise((resolve4) => {
5547
- const t = setTimeout(resolve4, ms);
6143
+ const sleep = (ms) => new Promise((resolve5) => {
6144
+ const t = setTimeout(resolve5, ms);
5548
6145
  t.unref?.();
5549
6146
  });
5550
6147
  async function mintAndPersistAiCredential(args) {
@@ -5695,11 +6292,12 @@ async function startAgentServer(opts) {
5695
6292
  if (!cap) return null;
5696
6293
  return capabilityRegistry.list().find((c) => c.name === name) ?? null;
5697
6294
  },
5698
- invoke: (name, input) => capabilityRegistry.invoke(name, input, { sessionId }),
6295
+ invoke: (name, input, signal) => capabilityRegistry.invoke(name, input, { sessionId, signal }),
6296
+ onToolsChanged: (listener) => capabilityRegistry.onToolsChanged(listener),
5699
6297
  emitRender: (event) => sendEvent(event),
5700
- emitText: (text) => sendEvent({
6298
+ emitText: (text2) => sendEvent({
5701
6299
  type: "text",
5702
- content: text
6300
+ content: text2
5703
6301
  })
5704
6302
  };
5705
6303
  }
@@ -5711,7 +6309,7 @@ async function startAgentServer(opts) {
5711
6309
  );
5712
6310
  }
5713
6311
  }
5714
- const secretsMode = wsConfig.secrets?.provider ?? "env";
6312
+ const secretsMode = managedHost ? "provisioned" : wsConfig.secrets?.provider ?? "env";
5715
6313
  wsConfig.secrets?.timeoutMs ?? 3e4;
5716
6314
  const rawCloud = profile?.cloud ?? "default";
5717
6315
  const effectiveCloud = SUPPORTED_CLOUDS.includes(rawCloud) ? rawCloud : "default";
@@ -5723,6 +6321,7 @@ async function startAgentServer(opts) {
5723
6321
  const effectiveCloudConfig = cloudConfigFromProfile(profile);
5724
6322
  const diskProfileHasAgentSettings = (p) => !!p && !!(p.driver || p.provider || p.model || p.cloud || p.cloud_config || p.thinking || p.effort);
5725
6323
  function resolveEffectiveCloudForSession() {
6324
+ if (managedCodex) return { cloud: "default" };
5726
6325
  if (effectiveCloud !== "default" || !wireAgentConfig) {
5727
6326
  return { cloud: effectiveCloud, cloudConfig: effectiveCloudConfig };
5728
6327
  }
@@ -5735,17 +6334,18 @@ async function startAgentServer(opts) {
5735
6334
  return {
5736
6335
  projectDir: opts.projectDir,
5737
6336
  agentDir,
5738
- driver: opts.driver ?? wireAgentConfig?.driver,
5739
- model: opts.model ?? wireAgentConfig?.model,
5740
- provider: opts.provider ?? wireAgentConfig?.provider,
6337
+ driver: managedCodex ? "codex" : opts.driver ?? wireAgentConfig?.driver,
6338
+ model: managedCodex ? wireAgentConfig?.model : opts.model ?? wireAgentConfig?.model,
6339
+ provider: managedCodex ? "openai" : opts.provider ?? wireAgentConfig?.provider,
5741
6340
  promptsDir: opts.promptsDir,
5742
6341
  sessionId,
5743
- resumeSessionId,
6342
+ resumeSessionId: managedCodex ? void 0 : resumeSessionId,
6343
+ ...managedCodex ? { managedCodex } : {},
5744
6344
  maxTurns,
5745
6345
  wsConfig,
5746
- externalPromptFile: process.env.SKAILE_SYSTEM_PROMPT_FILE,
6346
+ externalPromptFile: managedCodex ? void 0 : process.env.SKAILE_SYSTEM_PROMPT_FILE,
5747
6347
  secretProvider: secretProvider2,
5748
- onAuthError,
6348
+ onAuthError: managedCodex ? void 0 : onAuthError,
5749
6349
  onLimitBlocked,
5750
6350
  onProviderResponse,
5751
6351
  ...apiKey ? { apiKey } : {},
@@ -5830,8 +6430,8 @@ async function startAgentServer(opts) {
5830
6430
  }
5831
6431
  let resolveSessionReady;
5832
6432
  let rejectSessionReady;
5833
- const sessionReady = new Promise((resolve4, reject) => {
5834
- resolveSessionReady = resolve4;
6433
+ const sessionReady = new Promise((resolve5, reject) => {
6434
+ resolveSessionReady = resolve5;
5835
6435
  rejectSessionReady = reject;
5836
6436
  });
5837
6437
  let sessionConfig;
@@ -5841,10 +6441,14 @@ async function startAgentServer(opts) {
5841
6441
  let preMintedSecrets;
5842
6442
  const liveAttachedMcpDeclarations = /* @__PURE__ */ new Map();
5843
6443
  let wireAgentConfig;
6444
+ let managedCodex;
6445
+ let managedInitFingerprint;
6446
+ let managedInitComplete = false;
5844
6447
  let appliedWireAgentConfigKey;
5845
6448
  const stagedSkillDirs = /* @__PURE__ */ new Set();
5846
6449
  await restageMaterializedSkills(false);
5847
6450
  async function restageMaterializedSkills(allowRestart) {
6451
+ if (managedHost) return;
5848
6452
  try {
5849
6453
  const { skillsDir } = resolveDriverPaths({
5850
6454
  driver: opts.driver ?? wsConfig.agent_config?.default?.driver ?? wireAgentConfig?.driver ?? "claude-sdk"
@@ -5894,7 +6498,7 @@ async function startAgentServer(opts) {
5894
6498
  captureBakedMcpServers();
5895
6499
  }
5896
6500
  let resourceManager = secretsMode === "env" ? agentSession.resourceManager : null;
5897
- const driverPicksUpToolsLive = () => agentSession?.driverType !== "claude-sdk";
6501
+ const driverPicksUpToolsLive = () => supportsLiveToolUpdates(agentSession?.driverType, !!sessionConfig?.managedCodex);
5898
6502
  const emitResourcesAvailable = () => sendEvent(
5899
6503
  buildResourcesAvailablePayload(
5900
6504
  resourceManager,
@@ -6079,6 +6683,7 @@ async function startAgentServer(opts) {
6079
6683
  rebuildCompactionOrchestrator();
6080
6684
  }
6081
6685
  const activeFlows = /* @__PURE__ */ new Map();
6686
+ let removeCodexFlowTools;
6082
6687
  let stimulusBus = null;
6083
6688
  const FLOW_TURN_TIMEOUT_MS = 4 * 60 * 60 * 1e3;
6084
6689
  function getOnlyActiveFlow() {
@@ -6151,7 +6756,7 @@ async function startAgentServer(opts) {
6151
6756
  return stimulusBus;
6152
6757
  }
6153
6758
  function awaitFlowAgentEnd(prompt, timeoutMs) {
6154
- return new Promise((resolve4, reject) => {
6759
+ return new Promise((resolve5, reject) => {
6155
6760
  let settled = false;
6156
6761
  const onEvent = (event) => {
6157
6762
  if (event.type === "agent_end") done();
@@ -6169,7 +6774,7 @@ async function startAgentServer(opts) {
6169
6774
  onEvent
6170
6775
  ) ?? driver.removeListener("agent-event", onEvent);
6171
6776
  if (err) reject(err);
6172
- else resolve4();
6777
+ else resolve5();
6173
6778
  };
6174
6779
  const timer = setTimeout(
6175
6780
  () => done(new Error(`Flow turn timed out after ${timeoutMs / 1e3}s`)),
@@ -6202,6 +6807,8 @@ async function startAgentServer(opts) {
6202
6807
  async function createActiveFlow(flowDef, seedOrExecution) {
6203
6808
  const bus = getOrCreateStimulusBus();
6204
6809
  const nodeExecutor = new SessionNodeExecutor({ workspaceDir: opts.projectDir });
6810
+ const managedSubprompts = sessionConfig.managedCodex?.subpromptModels;
6811
+ if (sessionConfig.managedCodex && !managedSubprompts) throw new Error("AI_PROFILE_INVALID");
6205
6812
  const subpromptRunner = new SessionSubpromptRunner({
6206
6813
  driverType: agentSession.driverType,
6207
6814
  provider: agentSession.provider,
@@ -6210,7 +6817,34 @@ async function startAgentServer(opts) {
6210
6817
  apiKey: sessionConfig.apiKey,
6211
6818
  cloud: sessionConfig.cloud,
6212
6819
  cloudConfig: sessionConfig.cloudConfig,
6213
- cloudSecrets: sessionConfig.cloudSecrets
6820
+ cloudSecrets: sessionConfig.cloudSecrets,
6821
+ ...managedSubprompts ? {
6822
+ modelTierOverrides: {
6823
+ small: managedSubprompts.small,
6824
+ default: agentSession.model,
6825
+ deep: managedSubprompts.deep
6826
+ },
6827
+ availableModels: managedSubprompts.available,
6828
+ createIsolatedDriver: async (model) => {
6829
+ const parentPrivate = sessionConfig.managedCodex.runtime.privateDirectory;
6830
+ const privateDirectory = await mkdtemp(join(dirname(parentPrivate), ".subprompt-"));
6831
+ try {
6832
+ const child = await createManagedCodexSubpromptDriver(
6833
+ sessionConfig,
6834
+ model,
6835
+ opts.projectDir,
6836
+ privateDirectory
6837
+ );
6838
+ return {
6839
+ driver: child,
6840
+ dispose: () => rm(privateDirectory, { recursive: true, force: true })
6841
+ };
6842
+ } catch (error) {
6843
+ await rm(privateDirectory, { recursive: true, force: true });
6844
+ throw error;
6845
+ }
6846
+ }
6847
+ } : {}
6214
6848
  });
6215
6849
  const inlineSubFlowRunner = new SessionInlineSubFlowRunner({
6216
6850
  resolveFlow: (flowId) => loadFlow(resolveFlowPath(flowId, opts.projectDir)),
@@ -6286,6 +6920,10 @@ async function startAgentServer(opts) {
6286
6920
  log(`[serve] failed to rebuild MCP tools for flow: ${errMsg}`);
6287
6921
  }
6288
6922
  }
6923
+ if (agentSession?.driverType === "codex" && !driver.acceptsReplyAsPrompt) {
6924
+ removeCodexFlowTools?.();
6925
+ removeCodexFlowTools = registerCodexFlowTools(capabilityRegistry, manager, connectorId);
6926
+ }
6289
6927
  emitAvailability();
6290
6928
  const entry = {
6291
6929
  runId,
@@ -6351,18 +6989,20 @@ async function startAgentServer(opts) {
6351
6989
  });
6352
6990
  }
6353
6991
  async function cleanup() {
6992
+ if (managedHost) managedBootstrapClosed = true;
6354
6993
  try {
6355
6994
  await Promise.race([
6356
6995
  sessionReady,
6357
- new Promise((resolve4) => {
6358
- const t = setTimeout(resolve4, 2e3);
6996
+ new Promise((resolve5) => {
6997
+ const t = setTimeout(resolve5, 2e3);
6359
6998
  t.unref?.();
6360
6999
  })
6361
7000
  ]);
6362
7001
  } catch {
6363
7002
  }
6364
7003
  try {
6365
- driver?.kill();
7004
+ if (managedHost) await driver?.dispose();
7005
+ else driver?.kill();
6366
7006
  } catch {
6367
7007
  }
6368
7008
  aiCredentialRefreshScheduler.cancel();
@@ -6453,11 +7093,11 @@ async function startAgentServer(opts) {
6453
7093
  let apiKeyFromSecrets;
6454
7094
  let cloudSecrets;
6455
7095
  const { cloud: initCloud } = resolveEffectiveCloudForSession();
6456
- if (initCloud === "default") {
7096
+ if (!managedCodex && initCloud === "default") {
6457
7097
  const effectiveProvider = opts.provider ?? wireAgentConfig?.provider ?? "anthropic";
6458
7098
  const envKey = providerEnvKey(effectiveProvider);
6459
7099
  apiKeyFromSecrets = secrets?.[envKey];
6460
- } else {
7100
+ } else if (!managedCodex) {
6461
7101
  ({ cloudSecrets } = resolveCloudSecretBundle({
6462
7102
  cloud: initCloud,
6463
7103
  secrets,
@@ -6473,7 +7113,12 @@ async function startAgentServer(opts) {
6473
7113
  let needsWireFallbackRecreate = false;
6474
7114
  const agentSessionExistedBeforeThisInit = !!agentSession;
6475
7115
  if (!agentSession) {
7116
+ if (managedHost && managedBootstrapClosed) throw new Error("CODEX_RUNTIME_UNSUPPORTED");
6476
7117
  agentSession = await createAgentSession(sessionConfig);
7118
+ if (managedHost && managedBootstrapClosed) {
7119
+ await agentSession.dispose();
7120
+ throw new Error("CODEX_RUNTIME_UNSUPPORTED");
7121
+ }
6477
7122
  emitSystemPromptComposed(agentSession, sendEvent);
6478
7123
  resourceManager = agentSession.resourceManager;
6479
7124
  driver = agentSession.driver;
@@ -6519,8 +7164,8 @@ async function startAgentServer(opts) {
6519
7164
  async function recreateAgentSession(overrides) {
6520
7165
  let markSwapDone;
6521
7166
  driverSwapGate.beginSwap(
6522
- new Promise((resolve4) => {
6523
- markSwapDone = resolve4;
7167
+ new Promise((resolve5) => {
7168
+ markSwapDone = resolve5;
6524
7169
  })
6525
7170
  );
6526
7171
  try {
@@ -6534,8 +7179,13 @@ async function startAgentServer(opts) {
6534
7179
  const disposedManager = agentSession.resourceManager;
6535
7180
  const disposeStartedAt = Date.now();
6536
7181
  await agentSession.dispose();
7182
+ if (managedHost && managedBootstrapClosed) throw new Error("CODEX_RUNTIME_UNSUPPORTED");
6537
7183
  const createStartedAt = Date.now();
6538
7184
  agentSession = await createAgentSession({ ...sessionConfig, ...overrides });
7185
+ if (managedHost && managedBootstrapClosed) {
7186
+ await agentSession.dispose();
7187
+ throw new Error("CODEX_RUNTIME_UNSUPPORTED");
7188
+ }
6539
7189
  logPhase("session_rebuild", disposeStartedAt, {
6540
7190
  disposeMs: createStartedAt - disposeStartedAt,
6541
7191
  createMs: Date.now() - createStartedAt,
@@ -6676,7 +7326,7 @@ async function startAgentServer(opts) {
6676
7326
  log(`[serve] aiResources catalog actions: ${catalogActions.length}`);
6677
7327
  try {
6678
7328
  const skillsDir = join(sessionConfig.projectDir ?? process.cwd(), ".claude", "skills");
6679
- const assetsRoot = process.env.SKAILE_ASSETS_ROOT ?? await findAiAssetsRoot(sessionConfig.projectDir ?? process.cwd()) ?? "/app/ai-assets";
7329
+ const assetsRoot = process.env.SKAILE_ASSETS_ROOT ?? await findAiAssetsRoot$1(sessionConfig.projectDir ?? process.cwd()) ?? "/app/ai-assets";
6680
7330
  for (const res of catalogActions) {
6681
7331
  await applyCatalogAction(res, { assetsRoot, skillsDir });
6682
7332
  }
@@ -6790,7 +7440,53 @@ async function startAgentServer(opts) {
6790
7440
  return;
6791
7441
  }
6792
7442
  try {
6793
- validateCodexInit(cmd, [], runtimeIdentity ?? void 0);
7443
+ validateCodexInit(cmd, supportedRuntimeFeatures, runtimeIdentity ?? void 0);
7444
+ const wantsManaged = cmd.resolvedConfig.agentConfig?.driver === "codex";
7445
+ if (managedHost && !wantsManaged) throw new Error("AI_PROFILE_INVALID");
7446
+ if (managedHost && wantsManaged) {
7447
+ if (managedBootstrapClosed || agentSession && !managedInitFingerprint || cmd.secrets && CLAUDE_CODE_CREDENTIALS_KEY in cmd.secrets)
7448
+ throw new Error("AI_PROFILE_INVALID");
7449
+ const profile2 = cmd.resolvedConfig.agentConfig;
7450
+ if (opts.driver && opts.driver !== "codex" || opts.provider && opts.provider !== "openai" || opts.model && opts.model !== profile2.model)
7451
+ throw new Error("AI_PROFILE_INVALID");
7452
+ const initialCredential = parseCodexCredential(cmd.credentials.ai);
7453
+ const binding = bindManagedCodexInit(managedHost, cmd, async (input, signal) => {
7454
+ signal.throwIfAborted();
7455
+ if (initialCredential.kind !== "codex-subscription")
7456
+ throw new Error("AI_PROFILE_INVALID");
7457
+ const pinned = { ...initialCredential, credentialVersion: input.credentialVersion };
7458
+ const result = await remoteCapabilityInvoker(
7459
+ "host.refresh_credential",
7460
+ parseCodexRefreshInput(input, pinned),
7461
+ void 0,
7462
+ signal
7463
+ );
7464
+ signal.throwIfAborted();
7465
+ return parseCodexRefreshResult(result, pinned);
7466
+ });
7467
+ const credential = binding.runtime.credential;
7468
+ const fingerprint = JSON.stringify([
7469
+ cmd.identity,
7470
+ // A repeated init is idempotent only for the same host capability contract.
7471
+ // Keep all policy fields, not only the narrower resume signature.
7472
+ cmd.capabilities ?? [],
7473
+ profile2,
7474
+ credential.configId,
7475
+ credential.kind,
7476
+ credential.kind === "codex-subscription" ? credential.chatgptAccountId : null
7477
+ ]);
7478
+ if (managedInitFingerprint) {
7479
+ if (managedInitFingerprint !== fingerprint) throw new Error("AI_PROFILE_INVALID");
7480
+ if (managedInitComplete)
7481
+ sendEvent({
7482
+ type: "session_init_ack",
7483
+ capabilitySignature: computeCapabilitySignature(capabilityRegistry.list())
7484
+ });
7485
+ return;
7486
+ }
7487
+ managedInitFingerprint = fingerprint;
7488
+ managedCodex = binding;
7489
+ }
6794
7490
  } catch {
6795
7491
  runtimeRejected = true;
6796
7492
  sendEvent({
@@ -6821,23 +7517,29 @@ async function startAgentServer(opts) {
6821
7517
  }
6822
7518
  runtimeIdentity = cmd.identity;
6823
7519
  registerInitClientCapabilities(cmd.capabilities ?? []);
6824
- sendEvent({ type: "protocol_info", version: PROTOCOL_VERSION });
7520
+ sendEvent({
7521
+ type: "protocol_info",
7522
+ version: PROTOCOL_VERSION,
7523
+ ...managedHost ? { runtimeFeatures: supportedRuntimeFeatures } : {}
7524
+ });
6825
7525
  preMintedSecrets = new PreMintedSecretProvider(cmd.credentials);
6826
7526
  const initialAiCredentialExpiresAt = await provisionInitSecrets(cmd.secrets);
7527
+ if (managedCodex) secretsProvisioned = true;
6827
7528
  if (cmd.resolvedConfig.aiProviderConfigId) {
6828
7529
  aiProviderConfigId = cmd.resolvedConfig.aiProviderConfigId;
6829
7530
  log(`[serve] stashed aiProviderConfigId=${aiProviderConfigId}`);
6830
7531
  }
6831
- wireAgentConfig = diskProfileHasAgentSettings(profile) ? void 0 : cmd.resolvedConfig.agentConfig ?? wireAgentConfig;
6832
- if (aiProviderConfigId && initialAiCredentialExpiresAt) {
7532
+ wireAgentConfig = managedCodex ? cmd.resolvedConfig.agentConfig : diskProfileHasAgentSettings(profile) ? void 0 : cmd.resolvedConfig.agentConfig ?? wireAgentConfig;
7533
+ if (!managedCodex && aiProviderConfigId && initialAiCredentialExpiresAt) {
6833
7534
  aiCredentialRefreshScheduler.schedule(initialAiCredentialExpiresAt);
6834
7535
  }
6835
- const resumeProbe = cmd.resume?.sessionId ? await probeResumeTranscript(cmd.resume.sessionId) : void 0;
6836
- sendEvent({
6837
- type: "session_init_ack",
6838
- capabilitySignature: computeCapabilitySignature(capabilityRegistry.list()),
6839
- ...resumeProbe ? { resumeProbe } : {}
6840
- });
7536
+ const resumeProbe = !managedCodex && cmd.resume?.sessionId ? await probeResumeTranscript(cmd.resume.sessionId) : void 0;
7537
+ if (!managedCodex)
7538
+ sendEvent({
7539
+ type: "session_init_ack",
7540
+ capabilitySignature: computeCapabilitySignature(capabilityRegistry.list()),
7541
+ ...resumeProbe ? { resumeProbe } : {}
7542
+ });
6841
7543
  const buildSession = async () => {
6842
7544
  const firstBuildStartedAt = Date.now();
6843
7545
  const { needsWireFallbackRecreate, needsWireAgentConfigRecreate } = await buildSessionFromInit(cmd.secrets, resolvedConfigToDeclarations(cmd.resolvedConfig));
@@ -6855,7 +7557,7 @@ async function startAgentServer(opts) {
6855
7557
  log(
6856
7558
  `[serve] configure cfg keys=${Object.keys(cfg).join(",")} sharedState=${cfg.sharedState ? cfg.sharedState.length : "undefined"} resourceManager=${resourceManager ? "set" : "null"}`
6857
7559
  );
6858
- if (aiProviderConfigId) {
7560
+ if (!managedCodex && aiProviderConfigId) {
6859
7561
  aiCredentialRefreshScheduler.ensureArmed();
6860
7562
  }
6861
7563
  let pendingResumeSessionId;
@@ -6901,6 +7603,33 @@ async function startAgentServer(opts) {
6901
7603
  ready: true,
6902
7604
  resumeRequested: !!cmd.resume?.sessionId
6903
7605
  });
7606
+ if (managedCodex) {
7607
+ if (managedBootstrapClosed) throw new Error("CODEX_RUNTIME_UNSUPPORTED");
7608
+ try {
7609
+ await ensureDriverStarted();
7610
+ } catch (error) {
7611
+ if (!(error instanceof CodexNativeStateUnavailable) || !pendingResumeSessionId || managedBootstrapClosed)
7612
+ throw error;
7613
+ await recreateAgentSession({ resumeSessionId: void 0 });
7614
+ if (cfg.sharedState && !await applyInitSharedState(cfg.sharedState))
7615
+ throw new Error("session_init: shared-state setup failed");
7616
+ if (cfg.aiResources) await applyInitAiResources(cfg.aiResources);
7617
+ await ensureDriverStarted();
7618
+ if (managedBootstrapClosed || !driverStarted)
7619
+ throw new Error("CODEX_RUNTIME_UNSUPPORTED");
7620
+ sendEvent({
7621
+ type: "resume_failed",
7622
+ resumeSessionId: pendingResumeSessionId,
7623
+ reason: "native_state_unavailable"
7624
+ });
7625
+ }
7626
+ if (managedBootstrapClosed || !driverStarted) throw new Error("CODEX_RUNTIME_UNSUPPORTED");
7627
+ managedInitComplete = true;
7628
+ sendEvent({
7629
+ type: "session_init_ack",
7630
+ capabilitySignature: computeCapabilitySignature(capabilityRegistry.list())
7631
+ });
7632
+ }
6904
7633
  resolveSessionReady();
6905
7634
  };
6906
7635
  void buildSession().catch((err) => {
@@ -6909,6 +7638,14 @@ async function startAgentServer(opts) {
6909
7638
  log(`[serve] session_init failed to build session: ${errMsg}`);
6910
7639
  sendEvent({ type: "error", message: errMsg, fatal: true });
6911
7640
  rejectSessionReady(err instanceof Error ? err : new Error(errMsg));
7641
+ if (managedHost) {
7642
+ runtimeRejected = true;
7643
+ void cleanup().finally(async () => {
7644
+ teardownProcessHandlers();
7645
+ disposeLogStore();
7646
+ await transport.close();
7647
+ });
7648
+ }
6912
7649
  });
6913
7650
  }
6914
7651
  const awaitCompactionIdle = (what) => guardTurnAgainstCompaction({ gate: compactionGate, what, log, sendEvent });
@@ -6973,7 +7710,7 @@ async function startAgentServer(opts) {
6973
7710
  sendEvent({ type: "status", phase: "thinking" });
6974
7711
  const endTurn = driverSwapGate.beginTurn();
6975
7712
  try {
6976
- await driver.prompt(cmd.prompt);
7713
+ await driver.promptInput({ text: cmd.prompt, attachments: cmd.attachments });
6977
7714
  } catch (err) {
6978
7715
  const errMsg = err instanceof Error ? err.message : String(err);
6979
7716
  log(`[serve] prompt failed: ${errMsg}`);
@@ -6986,7 +7723,9 @@ async function startAgentServer(opts) {
6986
7723
  if (!await awaitSessionReadyOrFail()) return;
6987
7724
  log(`[serve] reply: ${cmd.answer.slice(0, 80)}...`);
6988
7725
  await driverSwapGate.awaitSwap();
6989
- if (driver.hasPendingQuestion() && driver.answerQuestion(cmd.answer, cmd.question)) return;
7726
+ if (driver.hasPendingQuestion() && driver.answerQuestion(cmd.answer, cmd.question, cmd.requestId))
7727
+ return;
7728
+ if (!driver.acceptsReplyAsPrompt) return;
6990
7729
  if (!await awaitCompactionIdle("reply")) return;
6991
7730
  const endTurn = driverSwapGate.beginTurn();
6992
7731
  try {
@@ -7229,9 +7968,10 @@ async function startAgentServer(opts) {
7229
7968
  }
7230
7969
  }
7231
7970
  async function handleCommand(cmd) {
7232
- if (runtimeRejected) return;
7971
+ if (runtimeRejected || managedHost && managedBootstrapClosed) return;
7233
7972
  const inbound = cmd;
7234
7973
  if (isCredentialRotatedSignal(cmd)) {
7974
+ if (managedCodex) return;
7235
7975
  await handleCredentialRotatedSignal({
7236
7976
  configId: readCredentialRotatedConfigId(cmd),
7237
7977
  repull: async (configId) => (await aiProviderConfigSwitcher.repull({
@@ -7322,6 +8062,14 @@ async function startAgentServer(opts) {
7322
8062
  transport.onCommand((cmd) => {
7323
8063
  void handleCommand(cmd);
7324
8064
  });
8065
+ transport.onConnect(() => {
8066
+ if (managedHost && !managedBootstrapClosed)
8067
+ sendEvent({
8068
+ type: "protocol_info",
8069
+ version: PROTOCOL_VERSION,
8070
+ runtimeFeatures: supportedRuntimeFeatures
8071
+ });
8072
+ });
7325
8073
  await transport.listen();
7326
8074
  if (secretsMode === "env" && agentSession) {
7327
8075
  agentSession.startWatching();
@@ -7346,7 +8094,9 @@ async function startAgentServer(opts) {
7346
8094
  sendEvent({ type: "commands_available", commands });
7347
8095
  }
7348
8096
  }
7349
- transport.onConnect(emitAvailability);
8097
+ transport.onConnect(() => {
8098
+ emitAvailability();
8099
+ });
7350
8100
  async function replayStoreSnapshots() {
7351
8101
  if (!resourceManager) return;
7352
8102
  for (const event of await buildStoreSnapshotReplay(resourceManager, activeFlows.values())) {
@@ -7526,6 +8276,6 @@ function touchSession(state) {
7526
8276
  return { ...state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
7527
8277
  }
7528
8278
 
7529
- export { CLAUDE_CODE_CREDENTIALS_KEY, COMPILE_MANIFEST_FILENAME, CapabilityRegistry, DEFAULT_CAPABILITY_CALL_TIMEOUT_MS, DEFAULT_COALESCE_MS, DEFAULT_FLOW_MUTATE_CONNECTOR_WAIT_MS, MOUNT_LIST_MAX_DEPTH, MOUNT_LIST_MAX_ENTRIES, MOUNT_READ_DEADLINE_FACTOR, MOUNT_TREE_OP_DEADLINE_FACTOR, MarkdownStreamer, PreInitRingSink, agentDefinitionExists, bootstrapCapabilityRegistry, bootstrapRunnerLogStore, buildAgentResources, buildClientCapabilityHandler, buildConnectorTokenMediator, buildContextSection, buildEnvironmentSection, buildResourcesAvailablePayload, buildStoreSnapshotReplay, builtinCapabilities, capabilityLogInstance, clearPreInitRingSink, clearSession, compileComposition, computeCapabilitySignature, connectorRefreshKind, createAgentSession, createFlowConnectorReadiness, createSessionStimulusBus, defineCapability, deleteSession, dispatchRunnerCapabilityInvocation, emitSystemPromptComposed, ensureClaudeSettingsDisablesConnectors, ensureGitConfigInclude, executeConnectorMutate, extractClaudeAiOauthExpiresAt, getPreInitRingSink, handleMountResourceRequest, handleResourceRequest, hasNonTerminalFlow, hostOpResumeStimulus, installPreInitRingSink, isTerminalFlowStatus, listSessions, loadAgentManifest, loadCompileManifest, loadCompileManifestFromDir, loadSession, loadSessionById, mcpAuthSecretKey, newSession, nulTailPaddingLength, pickRepointedManager, planFlowMutate, reconcilePendingDecisions, registerActiveFlow, registerCompositionCapabilities, rejectCapabilityOnApprovalDeny, resetRunnerLogStore, resolveAgentComposition, resolveAgentMixins, resolveBinding, resolveCapabilityCallTimeoutMs, resolveCapabilityResult, resolveComposition, resolveFlowMutateConnectorWaitMs, resolveMixin, runAgentChat, saveSession, setCurrentSession, setUpFlowConnector, startAgentServer, stimulusFromMetas, touchSession, validateInputResponse, writeClaudeCodeCredentialsFile };
7530
- //# sourceMappingURL=chunk-KCI7DAKE.js.map
7531
- //# sourceMappingURL=chunk-KCI7DAKE.js.map
8279
+ export { CLAUDE_CODE_CREDENTIALS_KEY, COMPILE_MANIFEST_FILENAME, CapabilityRegistry, DEFAULT_CAPABILITY_CALL_TIMEOUT_MS, DEFAULT_COALESCE_MS, DEFAULT_FLOW_MUTATE_CONNECTOR_WAIT_MS, MOUNT_LIST_MAX_DEPTH, MOUNT_LIST_MAX_ENTRIES, MOUNT_READ_DEADLINE_FACTOR, MOUNT_TREE_OP_DEADLINE_FACTOR, MarkdownStreamer, PreInitRingSink, agentDefinitionExists, bootstrapCapabilityRegistry, bootstrapRunnerLogStore, buildAgentResources, buildClientCapabilityHandler, buildConnectorTokenMediator, buildContextSection, buildEnvironmentSection, buildResourcesAvailablePayload, buildStoreSnapshotReplay, builtinCapabilities, capabilityLogInstance, clearPreInitRingSink, clearSession, compileComposition, computeCapabilitySignature, connectorRefreshKind, createAgentSession, createFlowConnectorReadiness, createManagedCodexSubpromptDriver, createSessionStimulusBus, defineCapability, deleteSession, dispatchRunnerCapabilityInvocation, emitSystemPromptComposed, ensureClaudeSettingsDisablesConnectors, ensureGitConfigInclude, executeConnectorMutate, extractClaudeAiOauthExpiresAt, getPreInitRingSink, handleMountResourceRequest, handleResourceRequest, hasNonTerminalFlow, hostOpResumeStimulus, installPreInitRingSink, isTerminalFlowStatus, listSessions, loadAgentManifest, loadCompileManifest, loadCompileManifestFromDir, loadManagedCodexHostConfig, loadSession, loadSessionById, mcpAuthSecretKey, newSession, nulTailPaddingLength, pickRepointedManager, planFlowMutate, prepareCodexTools, reconcilePendingDecisions, registerActiveFlow, registerCompositionCapabilities, rejectCapabilityOnApprovalDeny, resetRunnerLogStore, resolveAgentComposition, resolveAgentMixins, resolveBinding, resolveCapabilityCallTimeoutMs, resolveCapabilityResult, resolveComposition, resolveFlowMutateConnectorWaitMs, resolveMixin, runAgentChat, saveSession, setCurrentSession, setUpFlowConnector, startAgentServer, stimulusFromMetas, supportsLiveToolUpdates, touchSession, validateInputResponse, writeClaudeCodeCredentialsFile };
8280
+ //# sourceMappingURL=chunk-SZ3HIMSX.js.map
8281
+ //# sourceMappingURL=chunk-SZ3HIMSX.js.map