@skaile/workspaces 6.9.1 → 6.10.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 (340) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/ai-sdk.js +8 -8
  3. package/dist/{asset-feeds-PANNQPEE.js → asset-feeds-UG3PG423.js} +22 -22
  4. package/dist/{asset-feeds-PANNQPEE.js.map → asset-feeds-UG3PG423.js.map} +1 -1
  5. package/dist/asset-manager/catalog-deployer.js +8 -8
  6. package/dist/asset-manager/history.js +8 -8
  7. package/dist/asset-manager/index.js +14 -14
  8. package/dist/asset-manager/installer.js +9 -9
  9. package/dist/asset-manager/renderers.js +8 -8
  10. package/dist/asset-manager/src/harness-switch-state.d.ts +30 -0
  11. package/dist/asset-manager/src/harness-switch-state.d.ts.map +1 -0
  12. package/dist/asset-manager/src/index.d.ts +49 -12
  13. package/dist/asset-manager/src/index.d.ts.map +1 -1
  14. package/dist/asset-manager/src/mcp-config.d.ts +6 -0
  15. package/dist/asset-manager/src/mcp-config.d.ts.map +1 -1
  16. package/dist/bridge/codex-app-server.js +1 -2
  17. package/dist/bridge/harnesses/claude-sdk.js +11 -11
  18. package/dist/bridge/harnesses/codex.js +15 -1926
  19. package/dist/bridge/harnesses/codex.js.map +1 -1
  20. package/dist/bridge/harnesses/continue.js +11 -11
  21. package/dist/bridge/harnesses/echo.js +3 -3
  22. package/dist/bridge/harnesses/gemini.js +6 -6
  23. package/dist/bridge/harnesses/goose.js +11 -11
  24. package/dist/bridge/harnesses/omp.js +26 -9
  25. package/dist/bridge/harnesses/omp.js.map +1 -1
  26. package/dist/bridge/harnesses/opencode.js +11 -11
  27. package/dist/bridge/harnesses/qwen.js +6 -6
  28. package/dist/bridge/index.js +17 -16
  29. package/dist/bridge/src/harness-model-check.d.ts +5 -4
  30. package/dist/bridge/src/harness-model-check.d.ts.map +1 -1
  31. package/dist/bridge/src/harnesses/codex.d.ts +13 -0
  32. package/dist/bridge/src/harnesses/codex.d.ts.map +1 -1
  33. package/dist/bridge/src/harnesses/omp.d.ts +11 -0
  34. package/dist/bridge/src/harnesses/omp.d.ts.map +1 -1
  35. package/dist/bridge/src/index.d.ts +1 -0
  36. package/dist/bridge/src/index.d.ts.map +1 -1
  37. package/dist/{chunk-SME3PK4L.js → chunk-2D6HZAO5.js} +8 -8
  38. package/dist/{chunk-SME3PK4L.js.map → chunk-2D6HZAO5.js.map} +1 -1
  39. package/dist/chunk-2MUUPRIG.js +688 -0
  40. package/dist/chunk-2MUUPRIG.js.map +1 -0
  41. package/dist/{chunk-TMQFOJ6F.js → chunk-2PVYDAFN.js} +3 -3
  42. package/dist/{chunk-TMQFOJ6F.js.map → chunk-2PVYDAFN.js.map} +1 -1
  43. package/dist/{chunk-S47KU4YB.js → chunk-2U67XYZM.js} +3 -3
  44. package/dist/{chunk-S47KU4YB.js.map → chunk-2U67XYZM.js.map} +1 -1
  45. package/dist/{chunk-PLVM6OIV.js → chunk-375HN3FD.js} +18 -14
  46. package/dist/chunk-375HN3FD.js.map +1 -0
  47. package/dist/{chunk-VEIWFS7Z.js → chunk-4I4SBOCS.js} +345 -88
  48. package/dist/chunk-4I4SBOCS.js.map +1 -0
  49. package/dist/{chunk-PBEDRYHP.js → chunk-4Z4RULWQ.js} +48 -28
  50. package/dist/{chunk-PBEDRYHP.js.map → chunk-4Z4RULWQ.js.map} +1 -1
  51. package/dist/{chunk-MPO5CQUZ.js → chunk-5JBMYZNA.js} +3 -3
  52. package/dist/{chunk-MPO5CQUZ.js.map → chunk-5JBMYZNA.js.map} +1 -1
  53. package/dist/{chunk-EMSU6L7K.js → chunk-5KQFR4D7.js} +6 -6
  54. package/dist/{chunk-EMSU6L7K.js.map → chunk-5KQFR4D7.js.map} +1 -1
  55. package/dist/{chunk-KNY356I3.js → chunk-5KSGZP3E.js} +11 -4
  56. package/dist/chunk-5KSGZP3E.js.map +1 -0
  57. package/dist/{chunk-IISEBVMA.js → chunk-5P7LTPBR.js} +5 -5
  58. package/dist/{chunk-IISEBVMA.js.map → chunk-5P7LTPBR.js.map} +1 -1
  59. package/dist/{chunk-2UKNI2HJ.js → chunk-6O7VDKX3.js} +2 -2
  60. package/dist/{chunk-2UKNI2HJ.js.map → chunk-6O7VDKX3.js.map} +1 -1
  61. package/dist/{chunk-FZTHL6SK.js → chunk-7DUOKE73.js} +27 -33
  62. package/dist/chunk-7DUOKE73.js.map +1 -0
  63. package/dist/{chunk-V5KG6CCV.js → chunk-7HRZACI4.js} +7 -2
  64. package/dist/chunk-7HRZACI4.js.map +1 -0
  65. package/dist/{chunk-U3FI4DVT.js → chunk-7K73MCI6.js} +7 -5
  66. package/dist/chunk-7K73MCI6.js.map +1 -0
  67. package/dist/{chunk-BDAXHJC5.js → chunk-BCID52M5.js} +6 -6
  68. package/dist/{chunk-BDAXHJC5.js.map → chunk-BCID52M5.js.map} +1 -1
  69. package/dist/{chunk-FZO64PLQ.js → chunk-BNLXZXZN.js} +81 -8
  70. package/dist/chunk-BNLXZXZN.js.map +1 -0
  71. package/dist/{chunk-ZUROGXJM.js → chunk-C5UKYTTD.js} +13 -23
  72. package/dist/chunk-C5UKYTTD.js.map +1 -0
  73. package/dist/{chunk-LYVLDGML.js → chunk-CG63XGVV.js} +3 -3
  74. package/dist/{chunk-LYVLDGML.js.map → chunk-CG63XGVV.js.map} +1 -1
  75. package/dist/{chunk-4ROXSQEG.js → chunk-CJO3XKO7.js} +4 -4
  76. package/dist/{chunk-4ROXSQEG.js.map → chunk-CJO3XKO7.js.map} +1 -1
  77. package/dist/{chunk-OSABUEWA.js → chunk-CVUMZTNO.js} +4 -4
  78. package/dist/{chunk-OSABUEWA.js.map → chunk-CVUMZTNO.js.map} +1 -1
  79. package/dist/{chunk-E675QKFG.js → chunk-DOMRBOJZ.js} +5 -5
  80. package/dist/{chunk-E675QKFG.js.map → chunk-DOMRBOJZ.js.map} +1 -1
  81. package/dist/{chunk-GTAHU4N4.js → chunk-EB2LKPI6.js} +4 -4
  82. package/dist/{chunk-GTAHU4N4.js.map → chunk-EB2LKPI6.js.map} +1 -1
  83. package/dist/{chunk-GZL6RN4Z.js → chunk-FXBKBOI5.js} +169 -49
  84. package/dist/chunk-FXBKBOI5.js.map +1 -0
  85. package/dist/{chunk-J45JCYS4.js → chunk-GA4GUDTL.js} +4 -4
  86. package/dist/{chunk-J45JCYS4.js.map → chunk-GA4GUDTL.js.map} +1 -1
  87. package/dist/{chunk-RZRJTCP2.js → chunk-HE3TZYNG.js} +4 -4
  88. package/dist/{chunk-RZRJTCP2.js.map → chunk-HE3TZYNG.js.map} +1 -1
  89. package/dist/chunk-HLFLET7S.js +2443 -0
  90. package/dist/chunk-HLFLET7S.js.map +1 -0
  91. package/dist/{chunk-WEPTGUR4.js → chunk-HQUF6O4B.js} +27 -56
  92. package/dist/chunk-HQUF6O4B.js.map +1 -0
  93. package/dist/{chunk-QIV7H3GJ.js → chunk-IMO4EHND.js} +5 -5
  94. package/dist/{chunk-QIV7H3GJ.js.map → chunk-IMO4EHND.js.map} +1 -1
  95. package/dist/{chunk-TUOHA6BM.js → chunk-IOXFT5D7.js} +3 -3
  96. package/dist/{chunk-TUOHA6BM.js.map → chunk-IOXFT5D7.js.map} +1 -1
  97. package/dist/{chunk-CPMLMNI5.js → chunk-JDZUQFN7.js} +4 -4
  98. package/dist/{chunk-CPMLMNI5.js.map → chunk-JDZUQFN7.js.map} +1 -1
  99. package/dist/{chunk-7TF5MNFK.js → chunk-KE5HDORU.js} +2 -2
  100. package/dist/{chunk-7TF5MNFK.js.map → chunk-KE5HDORU.js.map} +1 -1
  101. package/dist/{chunk-PTJTOPE5.js → chunk-KOI7QFDH.js} +3 -3
  102. package/dist/{chunk-PTJTOPE5.js.map → chunk-KOI7QFDH.js.map} +1 -1
  103. package/dist/{chunk-NDBHEOIA.js → chunk-KRL53RZB.js} +8 -8
  104. package/dist/{chunk-NDBHEOIA.js.map → chunk-KRL53RZB.js.map} +1 -1
  105. package/dist/{chunk-7QYBKUAS.js → chunk-LKBRBVVS.js} +3 -3
  106. package/dist/{chunk-7QYBKUAS.js.map → chunk-LKBRBVVS.js.map} +1 -1
  107. package/dist/{chunk-USSP43U3.js → chunk-LQWOU7S2.js} +3 -3
  108. package/dist/{chunk-USSP43U3.js.map → chunk-LQWOU7S2.js.map} +1 -1
  109. package/dist/{chunk-4KPQ6ILH.js → chunk-MEU2HHGV.js} +18 -9
  110. package/dist/chunk-MEU2HHGV.js.map +1 -0
  111. package/dist/{chunk-QC5BYUED.js → chunk-MS2IXLTC.js} +4 -4
  112. package/dist/{chunk-QC5BYUED.js.map → chunk-MS2IXLTC.js.map} +1 -1
  113. package/dist/{chunk-Q5SSRVD5.js → chunk-NCJSYU6A.js} +16 -14
  114. package/dist/chunk-NCJSYU6A.js.map +1 -0
  115. package/dist/{chunk-5J6N6LHL.js → chunk-NFFBYG2W.js} +3 -3
  116. package/dist/{chunk-5J6N6LHL.js.map → chunk-NFFBYG2W.js.map} +1 -1
  117. package/dist/{chunk-7UCPGQCW.js → chunk-NTFP2XF4.js} +10 -10
  118. package/dist/chunk-NTFP2XF4.js.map +1 -0
  119. package/dist/{chunk-KVTV4LT2.js → chunk-PSPFWTJI.js} +4 -4
  120. package/dist/{chunk-KVTV4LT2.js.map → chunk-PSPFWTJI.js.map} +1 -1
  121. package/dist/{chunk-YPTDPN2B.js → chunk-PTXQMTCG.js} +3 -3
  122. package/dist/{chunk-YPTDPN2B.js.map → chunk-PTXQMTCG.js.map} +1 -1
  123. package/dist/{chunk-X5SGUBUV.js → chunk-QBJQ426X.js} +3 -3
  124. package/dist/{chunk-X5SGUBUV.js.map → chunk-QBJQ426X.js.map} +1 -1
  125. package/dist/{chunk-QBUJTVMY.js → chunk-R3ZNAPBV.js} +3 -3
  126. package/dist/{chunk-QBUJTVMY.js.map → chunk-R3ZNAPBV.js.map} +1 -1
  127. package/dist/{chunk-RP3ML3QD.js → chunk-RTFH2QR2.js} +3 -3
  128. package/dist/{chunk-RP3ML3QD.js.map → chunk-RTFH2QR2.js.map} +1 -1
  129. package/dist/{chunk-5KWQMCH7.js → chunk-RZ5R6GDJ.js} +5 -5
  130. package/dist/{chunk-5KWQMCH7.js.map → chunk-RZ5R6GDJ.js.map} +1 -1
  131. package/dist/{chunk-MDCI4RSG.js → chunk-RZL4TOK3.js} +20 -6
  132. package/dist/chunk-RZL4TOK3.js.map +1 -0
  133. package/dist/{chunk-LMADWO4Q.js → chunk-SBAUZ7XH.js} +4 -4
  134. package/dist/{chunk-LMADWO4Q.js.map → chunk-SBAUZ7XH.js.map} +1 -1
  135. package/dist/{chunk-AQTAULXT.js → chunk-SKG6G4HO.js} +108 -44
  136. package/dist/chunk-SKG6G4HO.js.map +1 -0
  137. package/dist/{chunk-HQAPUPBE.js → chunk-V2VDTQ7A.js} +3 -3
  138. package/dist/{chunk-HQAPUPBE.js.map → chunk-V2VDTQ7A.js.map} +1 -1
  139. package/dist/{chunk-GNUA7XT2.js → chunk-VS6XC5JE.js} +3 -3
  140. package/dist/{chunk-GNUA7XT2.js.map → chunk-VS6XC5JE.js.map} +1 -1
  141. package/dist/{chunk-5J6JWGY4.js → chunk-WDG5IVEA.js} +3 -3
  142. package/dist/{chunk-5J6JWGY4.js.map → chunk-WDG5IVEA.js.map} +1 -1
  143. package/dist/{chunk-XB4XHGIE.js → chunk-XWCV2A2F.js} +4 -4
  144. package/dist/{chunk-XB4XHGIE.js.map → chunk-XWCV2A2F.js.map} +1 -1
  145. package/dist/{chunk-UWD7YBDR.js → chunk-ZLDAPZIX.js} +4 -4
  146. package/dist/{chunk-UWD7YBDR.js.map → chunk-ZLDAPZIX.js.map} +1 -1
  147. package/dist/{claude-code-ILZ46SLO.js → claude-code-CMFGCDMX.js} +5 -5
  148. package/dist/{claude-code-ILZ46SLO.js.map → claude-code-CMFGCDMX.js.map} +1 -1
  149. package/dist/cli/index.js +322 -196
  150. package/dist/cli/index.js.map +1 -1
  151. package/dist/cli/src/commands/asset-cmd.d.ts.map +1 -1
  152. package/dist/cli/src/commands/catalog.d.ts.map +1 -1
  153. package/dist/cli/src/commands/config.d.ts.map +1 -1
  154. package/dist/cli/src/commands/connector.d.ts.map +1 -1
  155. package/dist/cli/src/commands/harness-preflight.d.ts +3 -1
  156. package/dist/cli/src/commands/harness-preflight.d.ts.map +1 -1
  157. package/dist/cli/src/commands/harness.d.ts.map +1 -1
  158. package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
  159. package/dist/cli/src/commands/library-index.d.ts +3 -3
  160. package/dist/cli/src/commands/library-index.d.ts.map +1 -1
  161. package/dist/cli/src/commands/migrate-files.d.ts +8 -0
  162. package/dist/cli/src/commands/migrate-files.d.ts.map +1 -1
  163. package/dist/cli/src/commands/migrate-harness.d.ts.map +1 -1
  164. package/dist/cli/src/commands/migrate-providers.d.ts.map +1 -1
  165. package/dist/cli/src/commands/migrate.d.ts.map +1 -1
  166. package/dist/cli/src/commands/outdated.d.ts.map +1 -1
  167. package/dist/cli/src/commands/project.d.ts.map +1 -1
  168. package/dist/cli/src/commands/run.d.ts.map +1 -1
  169. package/dist/cli/src/commands/serve-preflight.d.ts +7 -5
  170. package/dist/cli/src/commands/serve-preflight.d.ts.map +1 -1
  171. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  172. package/dist/cli/src/commands/source.d.ts.map +1 -1
  173. package/dist/cli/src/commands/validate.d.ts.map +1 -1
  174. package/dist/cli/src/config-checks.d.ts +50 -12
  175. package/dist/cli/src/config-checks.d.ts.map +1 -1
  176. package/dist/cli/src/ensure-sources.d.ts.map +1 -1
  177. package/dist/cli/src/harness-error.d.ts +7 -0
  178. package/dist/cli/src/harness-error.d.ts.map +1 -1
  179. package/dist/cli/src/helpers.d.ts.map +1 -1
  180. package/dist/connectors/config.js +5 -5
  181. package/dist/connectors/index.js +20 -19
  182. package/dist/connectors/src/index.d.ts +1 -1
  183. package/dist/connectors/src/index.d.ts.map +1 -1
  184. package/dist/connectors/src/managed-gitconfig.d.ts +12 -0
  185. package/dist/connectors/src/managed-gitconfig.d.ts.map +1 -1
  186. package/dist/{connectors-KTRUUKWG.js → connectors-P5M2D4MH.js} +23 -22
  187. package/dist/{connectors-KTRUUKWG.js.map → connectors-P5M2D4MH.js.map} +1 -1
  188. package/dist/core/index.js +7 -7
  189. package/dist/core/logging.js +1 -1
  190. package/dist/core/manifest.js +2 -2
  191. package/dist/core/models.js +1 -1
  192. package/dist/core/publish-manifest.js +3 -3
  193. package/dist/core/ref.js +1 -1
  194. package/dist/core/runtime-assets.js +5 -5
  195. package/dist/core/src/index.d.ts +2 -2
  196. package/dist/core/src/index.d.ts.map +1 -1
  197. package/dist/core/src/lock.d.ts +7 -1
  198. package/dist/core/src/lock.d.ts.map +1 -1
  199. package/dist/core/src/models.d.ts.map +1 -1
  200. package/dist/core/src/repo-manager.d.ts +28 -0
  201. package/dist/core/src/repo-manager.d.ts.map +1 -1
  202. package/dist/core/src/run-state-ignore.d.ts +5 -3
  203. package/dist/core/src/run-state-ignore.d.ts.map +1 -1
  204. package/dist/core/src/workspace-config.d.ts.map +1 -1
  205. package/dist/core/workspace-config.js +4 -4
  206. package/dist/deploy/index.js +7 -7
  207. package/dist/discovery/index.js +4 -4
  208. package/dist/{ensure-sources-5QWKUIUD.js → ensure-sources-MOGLBEUF.js} +31 -29
  209. package/dist/ensure-sources-MOGLBEUF.js.map +1 -0
  210. package/dist/factory-assets/connectors/box.js +20 -19
  211. package/dist/factory-assets/connectors/deploy.js +20 -19
  212. package/dist/factory-assets/connectors/devserver.js +20 -19
  213. package/dist/factory-assets/connectors/flow/adapter.js +20 -19
  214. package/dist/factory-assets/connectors/flow/engine.js +8 -8
  215. package/dist/factory-assets/connectors/flow/run-flow.js +22 -21
  216. package/dist/factory-assets/connectors/flow.js +20 -19
  217. package/dist/factory-assets/connectors/git/exec.d.ts +7 -0
  218. package/dist/factory-assets/connectors/git/exec.d.ts.map +1 -1
  219. package/dist/factory-assets/connectors/git/repo.d.ts.map +1 -1
  220. package/dist/factory-assets/connectors/git.js +20 -19
  221. package/dist/factory-assets/connectors/gmail/adapter.d.ts.map +1 -1
  222. package/dist/factory-assets/connectors/gmail.js +20 -19
  223. package/dist/factory-assets/connectors/googledrive.js +20 -19
  224. package/dist/factory-assets/connectors/local.js +20 -19
  225. package/dist/factory-assets/connectors/mattermost.js +20 -19
  226. package/dist/factory-assets/connectors/memory.js +20 -19
  227. package/dist/factory-assets/connectors/minio/adapter.d.ts.map +1 -1
  228. package/dist/factory-assets/connectors/minio.js +20 -19
  229. package/dist/factory-assets/connectors/postgres/adapter.d.ts.map +1 -1
  230. package/dist/factory-assets/connectors/postgres.js +20 -19
  231. package/dist/factory-assets/connectors/s3/driver.d.ts.map +1 -1
  232. package/dist/factory-assets/connectors/s3.js +20 -19
  233. package/dist/factory-assets/connectors/sharepoint.js +20 -19
  234. package/dist/factory-assets/connectors/sqlite/adapter.d.ts.map +1 -1
  235. package/dist/factory-assets/connectors/sqlite.js +20 -19
  236. package/dist/factory-assets/connectors/static-server.js +20 -19
  237. package/dist/factory-assets/connectors/tunnel.js +20 -19
  238. package/dist/factory-assets/connectors/webdav.js +20 -19
  239. package/dist/factory-assets/connectors/xstate-store.js +20 -19
  240. package/dist/factory-assets/connectors/xstate.js +20 -19
  241. package/dist/{flows-UCP6ZUYS.js → flows-J64L5MGJ.js} +12 -12
  242. package/dist/{flows-UCP6ZUYS.js.map → flows-J64L5MGJ.js.map} +1 -1
  243. package/dist/{helpers-INS4B7OQ.js → helpers-JL5AEGDT.js} +28 -26
  244. package/dist/{helpers-INS4B7OQ.js.map → helpers-JL5AEGDT.js.map} +1 -1
  245. package/dist/library/index.js +10 -10
  246. package/dist/library/install.js +4 -4
  247. package/dist/library/src/index.d.ts +2 -2
  248. package/dist/library/src/index.d.ts.map +1 -1
  249. package/dist/library/src/library.d.ts +6 -2
  250. package/dist/library/src/library.d.ts.map +1 -1
  251. package/dist/library/src/local/db.d.ts.map +1 -1
  252. package/dist/library/src/local/library.d.ts +10 -3
  253. package/dist/library/src/local/library.d.ts.map +1 -1
  254. package/dist/library/src/local/local-catalog-source.d.ts +0 -9
  255. package/dist/library/src/local/local-catalog-source.d.ts.map +1 -1
  256. package/dist/library/src/local/schema.d.ts +27 -20
  257. package/dist/library/src/local/schema.d.ts.map +1 -1
  258. package/dist/library/src/manifest-writer.d.ts +13 -0
  259. package/dist/library/src/manifest-writer.d.ts.map +1 -1
  260. package/dist/library/src/remote/index.d.ts +1 -1
  261. package/dist/library/src/remote/index.d.ts.map +1 -1
  262. package/dist/library/src/remote/remote-catalog-source.d.ts +6 -0
  263. package/dist/library/src/remote/remote-catalog-source.d.ts.map +1 -1
  264. package/dist/library/src/sync/git-driver.d.ts.map +1 -1
  265. package/dist/{library-publish-AZTYRASL.js → library-publish-DZNNZNMB.js} +49 -50
  266. package/dist/library-publish-DZNNZNMB.js.map +1 -0
  267. package/dist/model-endpoint/index.js +10 -10
  268. package/dist/open-library-OJREQ22B.js +61 -0
  269. package/dist/{open-library-3HMXYGUF.js.map → open-library-OJREQ22B.js.map} +1 -1
  270. package/dist/{open-registry-BHBHQMBA.js → open-registry-OEU6QUK2.js} +14 -14
  271. package/dist/{open-registry-BHBHQMBA.js.map → open-registry-OEU6QUK2.js.map} +1 -1
  272. package/dist/paths-PXBWY532.js +22 -0
  273. package/dist/{paths-77PXOXZY.js.map → paths-PXBWY532.js.map} +1 -1
  274. package/dist/{plugin-store-XQP2CRYH.js → plugin-store-ZC3EGZ3D.js} +10 -10
  275. package/dist/{plugin-store-XQP2CRYH.js.map → plugin-store-ZC3EGZ3D.js.map} +1 -1
  276. package/dist/{project-HVNPK2ZF.js → project-52UABBD5.js} +45 -46
  277. package/dist/{project-HVNPK2ZF.js.map → project-52UABBD5.js.map} +1 -1
  278. package/dist/resolver/index.js +8 -8
  279. package/dist/runner/index.js +35 -35
  280. package/dist/runner/src/serve.d.ts.map +1 -1
  281. package/dist/sdk/asset-manager.js +14 -14
  282. package/dist/sdk/bridge.js +17 -16
  283. package/dist/sdk/core.js +7 -7
  284. package/dist/sdk/flow.js +8 -8
  285. package/dist/sdk/index.js +35 -35
  286. package/dist/sdk/resolver.js +8 -8
  287. package/dist/sdk/runner.js +35 -35
  288. package/dist/sdk/transport/ws/server.js +8 -8
  289. package/dist/sdk/transport/ws.js +8 -8
  290. package/dist/sdk/transport.js +8 -8
  291. package/dist/{serve-preflight-NHZOKHIC.js → serve-preflight-HOQ7CGYR.js} +30 -30
  292. package/dist/{serve-preflight-NHZOKHIC.js.map → serve-preflight-HOQ7CGYR.js.map} +1 -1
  293. package/dist/{setup-EX7Z7XRN.js → setup-JIDZ372C.js} +29 -27
  294. package/dist/setup-JIDZ372C.js.map +1 -0
  295. package/dist/{skills-DE2BDQ6G.js → skills-5D4KDVPJ.js} +13 -13
  296. package/dist/{skills-DE2BDQ6G.js.map → skills-5D4KDVPJ.js.map} +1 -1
  297. package/dist/{source-URRPRGMZ.js → source-P6ZFSSZZ.js} +47 -46
  298. package/dist/{source-URRPRGMZ.js.map → source-P6ZFSSZZ.js.map} +1 -1
  299. package/dist/{source-manifest-publish-ZWRYRJ2U.js → source-manifest-publish-Y36FHVDS.js} +49 -48
  300. package/dist/source-manifest-publish-Y36FHVDS.js.map +1 -0
  301. package/dist/transport/index.js +8 -8
  302. package/dist/transport/src/ws/server.d.ts.map +1 -1
  303. package/dist/transport/ws/server.js +8 -8
  304. package/dist/transport/ws.js +8 -8
  305. package/dist/tui/index.js +35 -35
  306. package/dist/workspace-plugin/adapters/mcp.js +27 -26
  307. package/dist/workspace-plugin/adapters/omp.js +14 -14
  308. package/dist/workspace-plugin/index.js +2 -2
  309. package/package.json +1 -1
  310. package/dist/chunk-4KPQ6ILH.js.map +0 -1
  311. package/dist/chunk-7UCPGQCW.js.map +0 -1
  312. package/dist/chunk-AQTAULXT.js.map +0 -1
  313. package/dist/chunk-BLBXOG5Q.js +0 -299
  314. package/dist/chunk-BLBXOG5Q.js.map +0 -1
  315. package/dist/chunk-C324IAXI.js +0 -160
  316. package/dist/chunk-C324IAXI.js.map +0 -1
  317. package/dist/chunk-DJSGQW2Q.js +0 -334
  318. package/dist/chunk-DJSGQW2Q.js.map +0 -1
  319. package/dist/chunk-FZO64PLQ.js.map +0 -1
  320. package/dist/chunk-FZTHL6SK.js.map +0 -1
  321. package/dist/chunk-GYPPVANR.js +0 -357
  322. package/dist/chunk-GYPPVANR.js.map +0 -1
  323. package/dist/chunk-GZL6RN4Z.js.map +0 -1
  324. package/dist/chunk-KNY356I3.js.map +0 -1
  325. package/dist/chunk-LOO5CB5M.js +0 -12
  326. package/dist/chunk-LOO5CB5M.js.map +0 -1
  327. package/dist/chunk-MDCI4RSG.js.map +0 -1
  328. package/dist/chunk-PLVM6OIV.js.map +0 -1
  329. package/dist/chunk-Q5SSRVD5.js.map +0 -1
  330. package/dist/chunk-U3FI4DVT.js.map +0 -1
  331. package/dist/chunk-V5KG6CCV.js.map +0 -1
  332. package/dist/chunk-VEIWFS7Z.js.map +0 -1
  333. package/dist/chunk-WEPTGUR4.js.map +0 -1
  334. package/dist/chunk-ZUROGXJM.js.map +0 -1
  335. package/dist/ensure-sources-5QWKUIUD.js.map +0 -1
  336. package/dist/library-publish-AZTYRASL.js.map +0 -1
  337. package/dist/open-library-3HMXYGUF.js +0 -59
  338. package/dist/paths-77PXOXZY.js +0 -22
  339. package/dist/setup-EX7Z7XRN.js.map +0 -1
  340. package/dist/source-manifest-publish-ZWRYRJ2U.js.map +0 -1
@@ -1,1943 +1,32 @@
1
- import { CodexAppServerClient } from '../../chunk-KNY356I3.js';
2
- import { freshBudget, decide, spend } from '../../chunk-7EKQDY2T.js';
3
- import { managedCodexRegistryViolation, parseCodexCredential, prepareNativePolicy, prepareCodexInstance, codexInstanceEnvironment, isNativeApprovalPolicyActive, activateNativeApprovalPolicy, parseCodexRefreshResult, allowsNativeApprovalPath } from '../../chunk-GYPPVANR.js';
4
- import { codexSessionHome, buildCodexConfigDocument, codexLoginFile, isChatgptLogin, usesCodexOwnAuth, codexProviderTableId, writeCodexConfigToml } from '../../chunk-C324IAXI.js';
5
- import { CodexNativeStateUnavailable } from '../../chunk-LOO5CB5M.js';
6
- import { fetchProviderModels } from '../../chunk-3AIEJSQR.js';
7
- import { ReconfigureLedger, stripRunnerPrivateEnv, classifyGenericErrorMessage, RUNNER_AGENT_ENV_KEYS } from '../../chunk-5DE3DGVR.js';
1
+ export { CodexHarness, checkCodexCredential, codexHarnessTarget, isManagedCodexConfig } from '../../chunk-HLFLET7S.js';
2
+ import '../../chunk-5KSGZP3E.js';
3
+ import '../../chunk-7EKQDY2T.js';
4
+ import '../../chunk-3AIEJSQR.js';
5
+ import '../../chunk-5DE3DGVR.js';
8
6
  import '../../chunk-7DN6JKP2.js';
9
- import { AgentHarness, TOOL_ALLOWLIST_UNSUPPORTED, getBridgeLogger, registryHarnessConfig } from '../../chunk-5J6N6LHL.js';
10
- import { BUILTIN_HARNESS_CATALOG, registryCredentialEnv, unresolvedProviderCredentials, entryCredentialValue } from '../../chunk-7TF5MNFK.js';
7
+ import '../../chunk-NFFBYG2W.js';
8
+ import '../../chunk-KE5HDORU.js';
11
9
  import '../../chunk-G5SUWZEU.js';
12
10
  import '../../chunk-6UP2EDFN.js';
13
11
  import '../../chunk-WS3BOCAT.js';
14
- import { loadHarnessSdk } from '../../chunk-4KPQ6ILH.js';
12
+ import '../../chunk-MEU2HHGV.js';
15
13
  import '../../chunk-4GY63JU6.js';
16
- import '../../chunk-4ROXSQEG.js';
14
+ import '../../chunk-CJO3XKO7.js';
17
15
  import '../../chunk-5KRMNUL4.js';
18
16
  import '../../chunk-C5HFK34M.js';
19
17
  import '../../chunk-MWXYN6NY.js';
20
- import '../../chunk-FZO64PLQ.js';
18
+ import '../../chunk-BNLXZXZN.js';
21
19
  import '../../chunk-L5VSIPQD.js';
22
20
  import '../../chunk-VTETQCR6.js';
23
- import '../../chunk-QC5BYUED.js';
24
- import '../../chunk-GNUA7XT2.js';
21
+ import '../../chunk-MS2IXLTC.js';
22
+ import '../../chunk-VS6XC5JE.js';
25
23
  import '../../chunk-RVRB27AN.js';
26
- import '../../chunk-V5KG6CCV.js';
24
+ import '../../chunk-7HRZACI4.js';
27
25
  import '../../chunk-VSX2G7LA.js';
28
- import { resolveEntryBaseUrl, registryEntries } from '../../chunk-RXGPFAMN.js';
29
- import '../../chunk-MDCI4RSG.js';
26
+ import '../../chunk-RXGPFAMN.js';
27
+ import '../../chunk-RZL4TOK3.js';
30
28
  import '../../chunk-C3CAXQMA.js';
31
29
  import '../../chunk-BOFL7GIF.js';
32
30
  import '../../chunk-NSBPE2FW.js';
33
- import { isAbsolute, join, dirname, relative } from 'path';
34
- import { isDeepStrictEqual } from 'util';
35
- import { rmSync, existsSync, readFileSync, mkdirSync, writeFileSync, realpathSync, statSync, symlinkSync, copyFileSync } from 'fs';
36
- import { randomUUID } from 'crypto';
37
- import * as z from 'zod';
38
-
39
- var invalid = () => new Error("CODEX_INPUT_INVALID");
40
- var inside = (root, path) => {
41
- const rel = relative(root, path);
42
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
43
- };
44
- function codexPromptInput(input, cwd, skills) {
45
- if (!input || typeof input.text !== "string" || input.text.length > 1024 * 1024 || input.attachments !== void 0 && !Array.isArray(input.attachments) || (input.attachments?.length ?? 0) > 32)
46
- throw invalid();
47
- const result = [
48
- { type: "text", text: input.text }
49
- ];
50
- for (const attachment of input.attachments ?? []) {
51
- try {
52
- if (!attachment || typeof attachment.path !== "string") throw invalid();
53
- const root = attachment.type === "skill" && skills ? realpathSync(skills.source) : realpathSync(cwd);
54
- const path = realpathSync(
55
- isAbsolute(attachment.path) ? attachment.path : join(root, attachment.path)
56
- );
57
- if (!inside(root, path) || !statSync(path).isFile()) throw invalid();
58
- if (attachment.type === "image") result.push({ type: "localImage", path });
59
- else if (attachment.type === "file" || attachment.type === "skill") {
60
- if (!attachment.name || [...attachment.name].some((char) => char.charCodeAt(0) < 32))
61
- throw invalid();
62
- if (attachment.type === "skill") {
63
- if (!skills) throw invalid();
64
- const copied = realpathSync(join(skills.target, relative(root, path)));
65
- if (!inside(realpathSync(skills.target), copied) || !statSync(copied).isFile())
66
- throw invalid();
67
- result.push({ type: "skill", name: attachment.name, path: copied });
68
- } else result.push({ type: "mention", name: attachment.name, path });
69
- } else throw invalid();
70
- } catch {
71
- throw invalid();
72
- }
73
- }
74
- return result;
75
- }
76
-
77
- // bridge/src/codex/native-approvals.ts
78
- function createCodexNativeApprovalHandlers(options) {
79
- const active = (signal, threadId) => !signal.aborted && isNativeApprovalPolicyActive(options.getPolicy(), threadId);
80
- const text2 = (value) => typeof value === "string" && value.length > 0 && value.length <= 8192;
81
- const scoped = async (path, access, signal, threadId) => active(signal, threadId) && text2(path) && allowsNativeApprovalPath(options.getPolicy(), path, access) && active(signal, threadId);
82
- const permissions = async (value, signal, threadId) => {
83
- if (value.network?.enabled || value.network != null && Object.keys(value.network).some((key) => key !== "enabled") || Object.keys(value).some((key) => !["network", "fileSystem"].includes(key)))
84
- return false;
85
- const fs = value.fileSystem;
86
- if (!fs) return true;
87
- if (fs.entries != null || fs.globScanMaxDepth != null || Object.keys(fs).some((key) => !["read", "write", "entries", "globScanMaxDepth"].includes(key)))
88
- return false;
89
- for (const access of ["read", "write"]) {
90
- const paths = fs[access];
91
- if (paths != null && (!Array.isArray(paths) || paths.length > 32)) return false;
92
- for (const path of paths ?? [])
93
- if (!await scoped(path, access, signal, threadId)) return false;
94
- }
95
- return active(signal, threadId);
96
- };
97
- const consent = async (identity, approval, signal) => {
98
- if (!active(signal, identity.threadId) || approval.details.length > 64 || approval.details.some((detail) => detail.length > 8192) || approval.details.reduce((sum, detail) => sum + detail.length, 0) > 65536)
99
- return false;
100
- try {
101
- return await options.questions.requestApproval(identity, approval, signal) && active(signal, identity.threadId);
102
- } catch {
103
- return false;
104
- }
105
- };
106
- return {
107
- "item/commandExecution/requestApproval": async (input, signal) => {
108
- const params = structuredClone(input);
109
- const allowed = async () => active(signal, params.threadId) && text2(params.command) && (params.kind == null || params.kind === "command") && !params.environmentId && !params.networkApprovalContext && (params.availableDecisions == null || params.availableDecisions.includes("accept")) && await scoped(params.cwd, "read", signal, params.threadId) && (!params.additionalPermissions || await permissions(params.additionalPermissions, signal, params.threadId));
110
- if (!await allowed()) return { decision: "decline" };
111
- const details = [`Command: ${params.command}`, `Directory: ${params.cwd}`];
112
- for (const access of ["read", "write"])
113
- for (const path of params.additionalPermissions?.fileSystem?.[access] ?? [])
114
- details.push(`${access}: ${path}`);
115
- const accepted = await consent(params, { kind: "command", details }, signal);
116
- return { decision: accepted && await allowed() ? "accept" : "decline" };
117
- },
118
- "item/fileChange/requestApproval": async (input, signal) => {
119
- const params = structuredClone(input);
120
- if (!active(signal, params.threadId)) return { decision: "decline" };
121
- const original = options.getFileChanges(params);
122
- if (!original?.length || original.length > 16) return { decision: "decline" };
123
- const changes = structuredClone(original);
124
- const snapshot = JSON.stringify(changes);
125
- const allowed = async () => {
126
- if (!active(signal, params.threadId) || snapshot !== JSON.stringify(options.getFileChanges(params)))
127
- return false;
128
- if (params.grantRoot != null && !await scoped(params.grantRoot, "write", signal, params.threadId))
129
- return false;
130
- for (const change of changes) {
131
- if (!text2(change.diff) || !await scoped(change.path, "write", signal, params.threadId))
132
- return false;
133
- if (!["add", "delete", "update"].includes(change.kind.type)) return false;
134
- if (change.kind.type === "update" && change.kind.move_path != null && !await scoped(change.kind.move_path, "write", signal, params.threadId))
135
- return false;
136
- }
137
- return active(signal, params.threadId);
138
- };
139
- if (!await allowed()) return { decision: "decline" };
140
- const details = changes.flatMap((change) => [
141
- `${change.kind.type}: ${change.path}${change.kind.type === "update" && change.kind.move_path ? ` \u2192 ${change.kind.move_path}` : ""}`,
142
- change.diff
143
- ]);
144
- const accepted = await consent(params, { kind: "file", details }, signal);
145
- return { decision: accepted && await allowed() ? "accept" : "decline" };
146
- },
147
- "item/permissions/requestApproval": async (input, signal) => {
148
- const params = structuredClone(input);
149
- const allowed = async () => active(signal, params.threadId) && !params.environmentId && await scoped(params.cwd, "read", signal, params.threadId) && await permissions(params.permissions, signal, params.threadId);
150
- if (!await allowed()) return { permissions: {}, scope: "turn" };
151
- const details = [`Directory: ${params.cwd}`];
152
- for (const access of ["read", "write"])
153
- for (const path of params.permissions.fileSystem?.[access] ?? [])
154
- details.push(`${access}: ${path}`);
155
- if (details.length === 1) return { permissions: {}, scope: "turn" };
156
- const accepted = await consent(params, { kind: "permissions", details }, signal);
157
- return {
158
- permissions: accepted && await allowed() ? params.permissions : {},
159
- scope: "turn"
160
- };
161
- }
162
- };
163
- }
164
-
165
- // bridge/src/codex/native-mcp-approval.ts
166
- var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
167
- var text = (value) => typeof value === "string" && value.length > 0 && Buffer.byteLength(value) <= 8192;
168
- function createCodexMcpApprovalHandler(options) {
169
- return async (input, signal) => {
170
- const decline = { action: "decline", content: null, _meta: null };
171
- try {
172
- const params = structuredClone(input);
173
- const active = () => !signal.aborted && options.bindingActive() && isNativeApprovalPolicyActive(options.getPolicy(), params.threadId);
174
- if (!active() || !text(options.serverName) || params.serverName !== options.serverName || !text(params.threadId) || !text(params.turnId) || params.mode !== "form" || !text(params.message) || Object.keys(params).some(
175
- (key) => ![
176
- "threadId",
177
- "turnId",
178
- "serverName",
179
- "mode",
180
- "message",
181
- "requestedSchema",
182
- "_meta"
183
- ].includes(key)
184
- ) || !record(params._meta) || params._meta.codex_approval_kind !== "mcp_tool_call" || !record(params.requestedSchema) || params.requestedSchema.type !== "object" || !record(params.requestedSchema.properties) || Object.keys(params.requestedSchema.properties).length !== 0 || Object.keys(params.requestedSchema).some(
185
- (key) => !["type", "properties", "required"].includes(key)
186
- ) || params.requestedSchema.required !== void 0 && (!Array.isArray(params.requestedSchema.required) || params.requestedSchema.required.length !== 0) || Buffer.byteLength(JSON.stringify(params._meta)) > 65536)
187
- return decline;
188
- const accepted = await options.questions.requestApproval(
189
- void 0,
190
- {
191
- kind: "mcp",
192
- details: [
193
- `Configured MCP server: ${options.serverName}`,
194
- params.message,
195
- "This is native request presentation, not an independently verified tool identity. Tool permissions are checked again when dispatched."
196
- ]
197
- },
198
- signal
199
- );
200
- return accepted && active() ? { action: "accept", content: null, _meta: null } : decline;
201
- } catch {
202
- return decline;
203
- }
204
- };
205
- }
206
- var CodexQuestions = class {
207
- constructor(emit) {
208
- this.emit = emit;
209
- }
210
- emit;
211
- pending;
212
- request = async (params, signal) => this.park(params, signal);
213
- /** Park native consent; MCP uses only local correlation because it supplies no native item ID. */
214
- async requestApproval(identity, approval, signal) {
215
- const result = await this.park(
216
- {
217
- ...identity,
218
- isBlocking: true,
219
- questions: [
220
- {
221
- id: "native-approval",
222
- header: "Approval",
223
- question: approval.kind === "permissions" ? "Allow these permissions for the current turn?" : approval.kind === "mcp" ? "Allow this native MCP request once?" : "Allow this native action once?",
224
- options: [
225
- {
226
- label: "Approve once",
227
- description: approval.kind === "permissions" ? "Allow for the current turn." : "Allow only this request."
228
- },
229
- { label: "Deny", description: "Do not allow this request." }
230
- ]
231
- }
232
- ]
233
- },
234
- signal,
235
- approval
236
- );
237
- return result.answers["native-approval"]?.answers[0] === "Approve once";
238
- }
239
- async park(params, signal, approval) {
240
- signal.throwIfAborted();
241
- if (this.pending || !params.isBlocking || !Array.isArray(params.questions) || params.questions.length === 0 || params.questions.length > 16 || params.questions.some((q) => !q.id || !q.question || q.isSecret) || new Set(params.questions.map((q) => q.id)).size !== params.questions.length || new Set(params.questions.map((q) => q.question)).size !== params.questions.length)
242
- throw new Error("CODEX_INPUT_UNSUPPORTED");
243
- params = structuredClone(params);
244
- approval = approval ? structuredClone(approval) : void 0;
245
- const id = randomUUID();
246
- const eventId = params.itemId ?? `local-consent:${id}`;
247
- return new Promise((resolve, reject) => {
248
- const abort = () => finish();
249
- const finish = (result) => {
250
- if (this.pending?.id !== id) return;
251
- this.pending = void 0;
252
- signal.removeEventListener("abort", abort);
253
- if (result && !signal.aborted) resolve(result);
254
- else reject(new Error("CODEX_INPUT_CANCELLED"));
255
- };
256
- this.pending = {
257
- id,
258
- questions: params.questions,
259
- answers: /* @__PURE__ */ Object.create(null),
260
- finish,
261
- approval
262
- };
263
- const input = {
264
- requestId: id,
265
- questions: structuredClone(params.questions),
266
- ...approval ? { approval: structuredClone(approval) } : {}
267
- };
268
- signal.addEventListener("abort", abort, { once: true });
269
- if (signal.aborted) {
270
- abort();
271
- return;
272
- }
273
- this.emit({
274
- type: "message_start",
275
- message: {
276
- role: "assistant",
277
- content: [
278
- {
279
- type: "tool_use",
280
- name: "AskUserQuestion",
281
- id: eventId,
282
- input
283
- }
284
- ]
285
- }
286
- });
287
- if (this.pending?.id !== id || signal.aborted) return;
288
- this.emit({
289
- type: "tool_call",
290
- name: "AskUserQuestion",
291
- tool: { name: "AskUserQuestion" },
292
- toolCallId: eventId,
293
- input
294
- });
295
- });
296
- }
297
- get active() {
298
- return Boolean(this.pending);
299
- }
300
- answer(answer, question, requestId) {
301
- const pending = this.pending;
302
- if (!pending || pending.id !== requestId || typeof answer !== "string") return false;
303
- if (pending.approval && (question !== pending.questions[0]?.question || !["Approve once", "Deny"].includes(answer)))
304
- return false;
305
- const q = question === void 0 ? pending.questions.find((entry) => !Object.hasOwn(pending.answers, entry.id)) : pending.questions.find((entry) => entry.question === question);
306
- if (!q || Object.hasOwn(pending.answers, q.id)) return false;
307
- pending.answers[q.id] = { answers: [answer] };
308
- if (pending.questions.every((entry) => Object.hasOwn(pending.answers, entry.id)))
309
- pending.finish({ answers: pending.answers });
310
- return true;
311
- }
312
- };
313
-
314
- // bridge/src/codex/managed-harness.ts
315
- var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
316
- var failure = (code = "CODEX_RUNTIME_UNSUPPORTED") => new Error(code);
317
- var nativeUsage = (value) => ({
318
- ...typeof value.inputTokens === "number" ? { inputTokens: value.inputTokens } : {},
319
- ...typeof value.outputTokens === "number" ? { outputTokens: value.outputTokens } : {},
320
- ...typeof value.cachedInputTokens === "number" ? { cacheReadTokens: value.cachedInputTokens } : {},
321
- ...typeof value.reasoningOutputTokens === "number" ? { reasoningTokens: value.reasoningOutputTokens } : {},
322
- ...typeof value.totalTokens === "number" ? { totalTokens: value.totalTokens } : {}
323
- });
324
- var subtractUsage = (total, baseline) => {
325
- const delta = (value, before) => value === void 0 ? void 0 : Math.max(0, value - (before ?? 0));
326
- return {
327
- ...delta(total.inputTokens, baseline?.inputTokens) !== void 0 ? { inputTokens: delta(total.inputTokens, baseline?.inputTokens) } : {},
328
- ...delta(total.outputTokens, baseline?.outputTokens) !== void 0 ? { outputTokens: delta(total.outputTokens, baseline?.outputTokens) } : {},
329
- ...delta(total.cacheReadTokens, baseline?.cacheReadTokens) !== void 0 ? {
330
- cacheReadTokens: delta(total.cacheReadTokens, baseline?.cacheReadTokens)
331
- } : {},
332
- ...delta(total.reasoningTokens, baseline?.reasoningTokens) !== void 0 ? {
333
- reasoningTokens: delta(total.reasoningTokens, baseline?.reasoningTokens)
334
- } : {},
335
- ...delta(total.totalTokens, baseline?.totalTokens) !== void 0 ? { totalTokens: delta(total.totalTokens, baseline?.totalTokens) } : {}
336
- };
337
- };
338
- var addUsage = (left, right) => {
339
- const result = {};
340
- for (const key of [
341
- "inputTokens",
342
- "outputTokens",
343
- "cacheReadTokens",
344
- "reasoningTokens",
345
- "totalTokens"
346
- ]) {
347
- if (left?.[key] !== void 0 || right[key] !== void 0)
348
- result[key] = (left?.[key] ?? 0) + (right[key] ?? 0);
349
- }
350
- return result;
351
- };
352
- var limit = (value, fallback) => {
353
- const result = value ?? fallback;
354
- if (!Number.isSafeInteger(result) || result <= 0 || result > 18e5)
355
- throw failure("AI_PROFILE_INVALID");
356
- return result;
357
- };
358
- async function bounded(work, signal, ms) {
359
- let timer;
360
- let cancel = () => {
361
- };
362
- try {
363
- return await Promise.race([
364
- work,
365
- new Promise((_, reject) => {
366
- cancel = () => reject(failure());
367
- if (signal.aborted) cancel();
368
- else signal.addEventListener("abort", cancel, { once: true });
369
- timer = setTimeout(() => reject(failure()), ms);
370
- })
371
- ]);
372
- } finally {
373
- clearTimeout(timer);
374
- signal.removeEventListener("abort", cancel);
375
- }
376
- }
377
- var ManagedCodexHarness = class extends AgentHarness {
378
- constructor(config) {
379
- super();
380
- this.config = config;
381
- this.desired = {
382
- model: config.model,
383
- modelRef: config.modelRef,
384
- thinking: config.thinking,
385
- effort: config.effort,
386
- registry: config.registry,
387
- roles: config.roles
388
- };
389
- this.reconfig = new ReconfigureLedger({
390
- config: () => this.desired,
391
- onDesired: ({ model, thinking, effort }) => {
392
- const fields = {};
393
- if (model !== void 0) fields.model = model;
394
- if (thinking !== void 0) fields.thinking = thinking;
395
- if (effort !== void 0) fields.effort = effort;
396
- this.pendingPatch = { ...this.pendingPatch, ...fields };
397
- }
398
- });
399
- }
400
- config;
401
- harnessInfo = {
402
- id: "codex",
403
- name: "OpenAI Codex",
404
- modelAgnostic: false,
405
- supportsInBandAbort: true,
406
- capabilities: BUILTIN_HARNESS_CATALOG.codex?.capabilities
407
- };
408
- client;
409
- connecting;
410
- options;
411
- credential;
412
- nativeApprovalPolicy;
413
- instance;
414
- tools;
415
- mcpStartup = "unknown";
416
- pendingMcpStartup;
417
- mcpDiagnostics = {
418
- startupBeforeTurn: "unknown",
419
- startupAtEnd: "unknown",
420
- toolsListBeforeTurn: 0,
421
- toolsListTotal: 0,
422
- toolsCallTotal: 0,
423
- nativeMcpToolItemCount: 0
424
- };
425
- controller = new AbortController();
426
- generation = 0;
427
- killed = false;
428
- broken = false;
429
- cleanupUncertain = false;
430
- unexpectedClose = false;
431
- starting;
432
- closing = Promise.resolve();
433
- threadId;
434
- lastThreadId;
435
- resetting;
436
- pendingPatch;
437
- active;
438
- threadUsageTotal;
439
- resumeUsageTurnIds = /* @__PURE__ */ new Set();
440
- queue = Promise.resolve();
441
- queued = 0;
442
- admittedTurns = 0;
443
- loginCompleted;
444
- /** Recovery budget for the connection's startup (no active turn); reset on each start. */
445
- startupRecovery = freshBudget();
446
- startupAuthAttempted = false;
447
- questions = new CodexQuestions((event) => this.event(event));
448
- get acceptsReplyAsPrompt() {
449
- return false;
450
- }
451
- hasPendingQuestion() {
452
- return this.questions.active;
453
- }
454
- answerQuestion(answer, question, requestId) {
455
- return this.questions.answer(answer, question, requestId);
456
- }
457
- /** The settings a later prompt will run on; `config` only takes them at the next turn. */
458
- desired;
459
- reconfig;
460
- get runtimeSessionId() {
461
- return this.threadId ?? this.lastThreadId;
462
- }
463
- get isRunning() {
464
- return Boolean(this.client && this.threadId && !this.killed && !this.broken);
465
- }
466
- getModel() {
467
- return this.config.model;
468
- }
469
- async start() {
470
- if (this.killed || this.broken) throw failure();
471
- if (this.threadId && this.client) return;
472
- if (this.starting) return this.starting;
473
- this.starting = this.initialize().catch(async (error) => {
474
- this.broken = true;
475
- await this.closeGeneration();
476
- if (error instanceof CodexNativeStateUnavailable && (this.cleanupUncertain || this.unexpectedClose || this.killed || this.startupAuthAttempted))
477
- throw failure();
478
- const safe = error instanceof Error && /^(AI_PROFILE_INVALID|CODEX_[A-Z_]+)$/.test(error.message) ? error : failure();
479
- throw safe;
480
- }).finally(() => {
481
- this.starting = void 0;
482
- });
483
- return this.starting;
484
- }
485
- async initialize() {
486
- await this.closing;
487
- if (this.killed) throw failure();
488
- const options = this.config.harnessOptions?.codex?.managedRuntime;
489
- const tuning = this.config.harnessOptions?.codex;
490
- if (tuning?.authSource !== "managed" || !options || typeof options.prepareTools !== "function" || !isAbsolute(options.executable) || !this.config.model || !tuning.reasoningEffort || !tuning.approvalPolicy || tuning.approvalPolicy === "on-failure" || !tuning.sandboxMode || tuning.sandboxMode === "danger-full-access" || // A managed session runs on the platform-minted credential alone: an
491
- // OpenAI key handed in through the child environment would be a second,
492
- // unaudited authority.
493
- this.config.env?.OPENAI_API_KEY || // Credential isolation, stated on the AI provider registry: one entry,
494
- // codex's own OpenAI surface, a platform-injected oauth reference. See
495
- // `managedCodexRegistryViolation`.
496
- managedCodexRegistryViolation(this.config.registry) !== void 0 || options.nativeTurnBudget !== void 0 && options.nativeTurnBudget !== 1)
497
- throw failure("AI_PROFILE_INVALID");
498
- this.options = options;
499
- const timeout = limit(options.requestTimeoutMs, 15e3);
500
- limit(options.turnTimeoutMs, 3e5);
501
- try {
502
- this.credential = parseCodexCredential(this.credential ?? options.credential);
503
- } catch {
504
- throw failure("CODEX_AUTH_UNAVAILABLE");
505
- }
506
- if (this.credential.configId !== this.config.aiProviderConfigId)
507
- throw failure("AI_PROFILE_INVALID");
508
- const privatePolicy = prepareNativePolicy({
509
- cwd: this.config.cwd,
510
- privateRoot: options.privateRoot,
511
- privateDirectory: options.privateDirectory,
512
- sandboxMode: tuning.sandboxMode
513
- });
514
- this.instance = prepareCodexInstance(this.config, options, this.credential);
515
- const generation = ++this.generation;
516
- const mcpReplies = /* @__PURE__ */ new WeakMap();
517
- this.controller = new AbortController();
518
- this.startupRecovery = freshBudget();
519
- this.startupAuthAttempted = false;
520
- const handlers = {
521
- "account/chatgptAuthTokens/refresh": async (params, signal) => {
522
- const active = this.active;
523
- if (!active && !this.starting) throw failure("CODEX_AUTH_UNAVAILABLE");
524
- if (!active) this.startupAuthAttempted = true;
525
- const cancellation = AbortSignal.any([
526
- signal,
527
- this.controller.signal,
528
- ...active ? [active.controller.signal] : []
529
- ]);
530
- try {
531
- return await this.refresh(params, cancellation);
532
- } catch {
533
- if (active && this.active === active) active.failureCode = "CODEX_AUTH_UNAVAILABLE";
534
- throw failure("CODEX_AUTH_UNAVAILABLE");
535
- }
536
- }
537
- };
538
- const authMode = this.credential.kind === "codex-subscription" ? "chatgpt" : "api";
539
- const nativePolicy = {
540
- cli_auth_credentials_store: "ephemeral",
541
- forced_login_method: authMode,
542
- model_provider: "openai",
543
- model: this.config.model,
544
- model_instructions_file: this.instance.instructionFile,
545
- shell_environment_policy: {
546
- inherit: "none",
547
- set: { PATH: options.environment.PATH ?? "/usr/bin:/bin" }
548
- },
549
- mcp_servers: {}
550
- };
551
- const overrides = Object.entries({
552
- cli_auth_credentials_store: "ephemeral",
553
- forced_login_method: authMode,
554
- model_provider: "openai",
555
- model: this.config.model,
556
- model_instructions_file: this.instance.instructionFile,
557
- "shell_environment_policy.inherit": "none",
558
- "shell_environment_policy.set.PATH": options.environment.PATH ?? "/usr/bin:/bin"
559
- }).flatMap(([key, value]) => ["-c", `${key}=${JSON.stringify(value)}`]);
560
- overrides.push("-c", "mcp_servers={}");
561
- const connecting = CodexAppServerClient.connect(
562
- {
563
- command: options.executable,
564
- args: [
565
- ...options.executableArgs ?? [],
566
- ...overrides,
567
- ...privatePolicy.cliArgs,
568
- "app-server",
569
- "--stdio"
570
- ],
571
- cwd: this.instance.root,
572
- env: codexInstanceEnvironment(options.environment, this.instance.home),
573
- clientInfo: { name: "skaile-managed-codex", version: "1" },
574
- processGroup: true,
575
- requestTimeoutMs: timeout,
576
- serverRequestTimeoutMs: Math.min(limit(options.interactionTimeoutMs, 3e5), 3e5),
577
- onServerRequest: handlers,
578
- canReplyToServerRequest: (method, params) => {
579
- if (method !== "mcpServer/elicitation/request") return true;
580
- return record2(params) && (mcpReplies.get(params)?.() ?? false);
581
- },
582
- onNotification: (method, params) => {
583
- if (generation === this.generation) this.notification(method, params);
584
- },
585
- onClose: () => {
586
- if (generation !== this.generation) return;
587
- this.unexpectedClose = true;
588
- this.broken = true;
589
- this.loginCompleted?.reject(failure());
590
- this.finishTurn("CODEX_RUNTIME_UNSUPPORTED");
591
- void this.closeGeneration();
592
- }
593
- },
594
- this.controller.signal
595
- );
596
- this.connecting = connecting;
597
- try {
598
- this.client = await connecting;
599
- } finally {
600
- if (this.connecting === connecting) this.connecting = void 0;
601
- }
602
- if (generation !== this.generation || this.killed) throw failure();
603
- await this.authenticate(timeout);
604
- const toolsPromise = options.prepareTools(this.controller.signal).then(async (tools) => {
605
- if (generation !== this.generation || this.controller.signal.aborted) {
606
- await tools.dispose().catch(() => {
607
- });
608
- throw failure();
609
- }
610
- return tools;
611
- });
612
- try {
613
- this.tools = await bounded(toolsPromise, this.controller.signal, timeout);
614
- } catch {
615
- throw failure("CODEX_REQUIRED_TOOL_UNAVAILABLE");
616
- }
617
- if (!this.tools || !record2(this.tools.mcpServers) || typeof this.tools.dispose !== "function" || Object.keys(this.tools.mcpServers).length === 0 && Object.keys(this.tools.onServerRequest ?? {}).length === 0)
618
- throw failure("CODEX_REQUIRED_TOOL_UNAVAILABLE");
619
- if (this.tools.onServerRequest?.["item/tool/requestUserInput"])
620
- throw failure("AI_PROFILE_INVALID");
621
- const nativeApprovals = createCodexNativeApprovalHandlers({
622
- questions: this.questions,
623
- getPolicy: () => tuning.approvalPolicy === "never" ? void 0 : this.nativeApprovalPolicy,
624
- getFileChanges: ({ itemId, threadId, turnId }) => {
625
- const active = this.active;
626
- if (!active || active.controller.signal.aborted || threadId !== this.threadId || turnId !== active.id)
627
- return void 0;
628
- const snapshot = active.fileChanges.get(itemId);
629
- return snapshot ? JSON.parse(snapshot) : void 0;
630
- }
631
- });
632
- const approvalTools = this.tools;
633
- const approvalServerName = approvalTools.approvalServerName;
634
- const approvalServer = approvalServerName ? approvalTools.mcpServers[approvalServerName] : void 0;
635
- const approvalServerSnapshot = structuredClone(approvalServer);
636
- const mcpBindingActive = () => this.tools === approvalTools && approvalTools.approvalServerName === approvalServerName && Boolean(approvalServerName) && Object.hasOwn(approvalTools.mcpServers, approvalServerName) && record2(approvalServer) && approvalTools.mcpServers[approvalServerName] === approvalServer && isDeepStrictEqual(approvalServer, approvalServerSnapshot);
637
- const mcpPolicy = () => tuning.approvalPolicy === "never" ? void 0 : this.nativeApprovalPolicy;
638
- const mcpApproval = createCodexMcpApprovalHandler({
639
- serverName: approvalServerName,
640
- questions: this.questions,
641
- getPolicy: mcpPolicy,
642
- bindingActive: mcpBindingActive
643
- });
644
- for (const [method, handler] of Object.entries({
645
- ...this.tools.onServerRequest,
646
- ...nativeApprovals,
647
- "item/tool/requestUserInput": this.questions.request,
648
- "mcpServer/elicitation/request": mcpApproval
649
- })) {
650
- if (method === "account/chatgptAuthTokens/refresh" || !handler)
651
- throw failure("AI_PROFILE_INVALID");
652
- handlers[method] = async (params, signal) => {
653
- const active = this.active;
654
- if (generation !== this.generation || !active || !record2(params)) throw failure();
655
- await active.ready;
656
- if (generation !== this.generation || this.active !== active || params.threadId !== this.threadId || params.turnId !== active.id)
657
- throw failure();
658
- const cancellation = AbortSignal.any([signal, active.controller.signal]);
659
- if (cancellation.aborted) throw failure();
660
- if (method === "mcpServer/elicitation/request") {
661
- mcpReplies.set(
662
- params,
663
- () => generation === this.generation && this.active === active && !cancellation.aborted && params.threadId === this.threadId && params.turnId === active.id && mcpBindingActive() && isNativeApprovalPolicyActive(mcpPolicy(), this.threadId ?? "")
664
- );
665
- }
666
- const result = await handler(params, cancellation);
667
- if (generation !== this.generation || cancellation.aborted || this.active !== active)
668
- throw failure();
669
- return result;
670
- };
671
- }
672
- if (this.tools.instructions) this.instance.setToolInstructions(this.tools.instructions);
673
- const threadParams = {
674
- model: this.config.model,
675
- modelProvider: "openai",
676
- cwd: this.instance.cwd,
677
- approvalPolicy: tuning.approvalPolicy,
678
- permissions: "managed",
679
- config: {
680
- ...nativePolicy,
681
- ...privatePolicy.config,
682
- mcp_servers: this.tools.mcpServers,
683
- model_reasoning_effort: this.config.effort ?? tuning.reasoningEffort
684
- }
685
- };
686
- const resuming = Boolean(this.config.resumeSessionId);
687
- this.threadUsageTotal = resuming ? this.threadUsageTotal ?? {} : {};
688
- this.resumeUsageTurnIds.clear();
689
- const response = resuming ? await this.client.request("thread/resume", {
690
- ...threadParams,
691
- threadId: this.config.resumeSessionId,
692
- excludeTurns: false
693
- }) : await this.client.request("thread/start", {
694
- ...threadParams,
695
- allowProviderModelFallback: false
696
- });
697
- if (!record2(response) || response.model !== this.config.model)
698
- throw failure("CODEX_MODEL_UNAVAILABLE");
699
- if (!record2(response.thread) || typeof response.thread.id !== "string" || resuming && response.thread.id !== this.config.resumeSessionId || resuming && !Array.isArray(response.thread.turns) || response.reasoningEffort !== (this.config.effort ?? tuning.reasoningEffort) || response.modelProvider !== "openai" || response.approvalPolicy !== tuning.approvalPolicy)
700
- throw failure("AI_PROFILE_INVALID");
701
- if (generation !== this.generation || this.killed) throw failure();
702
- this.resumeUsageTurnIds = new Set(
703
- resuming && Array.isArray(response.thread.turns) ? response.thread.turns.flatMap(
704
- (turn) => record2(turn) && typeof turn.id === "string" ? [turn.id] : []
705
- ) : []
706
- );
707
- this.nativeApprovalPolicy = activateNativeApprovalPolicy(
708
- privatePolicy,
709
- response,
710
- this.controller.signal
711
- );
712
- this.threadId = response.thread.id;
713
- this.mcpStartup = this.pendingMcpStartup?.threadId === this.threadId ? this.pendingMcpStartup.status : "unknown";
714
- this.pendingMcpStartup = void 0;
715
- this.lastThreadId = this.threadId;
716
- this.instance.bindThread(this.threadId);
717
- }
718
- async authenticate(timeout) {
719
- const credential = this.credential;
720
- if (credential.kind === "openai-api-key") {
721
- const result = await this.client.request("account/login/start", {
722
- type: "apiKey",
723
- apiKey: credential.apiKey
724
- });
725
- if (result.type !== "apiKey") throw failure("CODEX_AUTH_UNAVAILABLE");
726
- return;
727
- }
728
- const completion = new Promise((resolve, reject) => {
729
- this.loginCompleted = { resolve, reject };
730
- });
731
- const wait = bounded(completion, this.controller.signal, timeout);
732
- void wait.catch(() => {
733
- });
734
- try {
735
- const result = await this.client.request("account/login/start", {
736
- type: "chatgptAuthTokens",
737
- accessToken: credential.accessToken,
738
- chatgptAccountId: credential.chatgptAccountId,
739
- chatgptPlanType: credential.chatgptPlanType ?? null
740
- });
741
- if (result.type !== "chatgptAuthTokens") throw failure("CODEX_AUTH_UNAVAILABLE");
742
- await wait;
743
- } finally {
744
- this.loginCompleted = void 0;
745
- }
746
- }
747
- async refresh(params, signal) {
748
- const credential = this.credential;
749
- if (!record2(params) || params.reason !== "unauthorized" || !credential || credential.kind !== "codex-subscription" || params.previousAccountId != null && params.previousAccountId !== credential.chatgptAccountId || !this.options?.refreshCredential)
750
- throw failure("CODEX_AUTH_UNAVAILABLE");
751
- const active = this.active;
752
- const budget = active ? active.recovery : this.startupRecovery;
753
- const decision = decide(
754
- { message: "unauthorized", authError: true, limitRejected: false, queryEnded: false },
755
- budget,
756
- { onAuthError: true, onLimitBlocked: false, resumableSessionId: false }
757
- );
758
- if (!("attempt" in decision) || decision.attempt !== "auth_refresh")
759
- throw failure("CODEX_AUTH_UNAVAILABLE");
760
- const spent = spend(budget, "auth_refresh");
761
- if (active) active.recovery = spent;
762
- else this.startupRecovery = spent;
763
- const result = await this.options.refreshCredential(
764
- {
765
- kind: "codex-subscription",
766
- configId: credential.configId,
767
- credentialVersion: credential.credentialVersion,
768
- reason: "retry-401"
769
- },
770
- signal
771
- );
772
- if (signal.aborted) throw failure("CODEX_AUTH_UNAVAILABLE");
773
- let parsed;
774
- try {
775
- parsed = parseCodexRefreshResult(result, credential);
776
- } catch {
777
- throw failure("CODEX_AUTH_UNAVAILABLE");
778
- }
779
- if (!parsed.ok) throw failure("CODEX_AUTH_UNAVAILABLE");
780
- this.credential = parsed.credential;
781
- return {
782
- accessToken: parsed.credential.accessToken,
783
- chatgptAccountId: parsed.credential.chatgptAccountId,
784
- chatgptPlanType: parsed.credential.chatgptPlanType ?? null
785
- };
786
- }
787
- prompt(message) {
788
- return this.promptInput({ text: message });
789
- }
790
- promptInput(input) {
791
- if (input.toolAllowlist !== void 0)
792
- return Promise.reject(new Error(TOOL_ALLOWLIST_UNSUPPORTED));
793
- const message = structuredClone(input);
794
- const turnBudget = this.config.harnessOptions?.codex?.managedRuntime?.nativeTurnBudget;
795
- if (this.killed || this.broken || this.resetting || this.queued >= 32 || turnBudget !== void 0 && this.admittedTurns >= turnBudget)
796
- return Promise.reject(failure());
797
- if (turnBudget !== void 0) this.admittedTurns++;
798
- this.queued++;
799
- const task = this.queue.then(() => this.runTurn(message));
800
- this.queue = task.catch(() => {
801
- }).finally(() => {
802
- this.queued--;
803
- });
804
- return task;
805
- }
806
- async runTurn(message) {
807
- if (this.resetting) throw failure();
808
- await this.start();
809
- if (this.killed || this.broken || this.resetting) throw failure();
810
- if (this.pendingPatch) {
811
- this.config = { ...this.config, ...this.pendingPatch };
812
- this.pendingPatch = void 0;
813
- }
814
- if (!this.config.model) throw failure("AI_PROFILE_INVALID");
815
- await this.tools?.validate?.();
816
- if (this.tools?.needsReload?.()) {
817
- this.config = { ...this.config, resumeSessionId: this.threadId };
818
- await this.closeGeneration();
819
- await this.start();
820
- }
821
- const input = codexPromptInput(
822
- message,
823
- this.instance.cwd,
824
- this.options?.skillsDirectory ? {
825
- source: this.options.skillsDirectory,
826
- target: join(this.instance.home, "skills")
827
- } : void 0
828
- );
829
- try {
830
- parseCodexCredential(this.credential);
831
- } catch {
832
- throw failure("CODEX_AUTH_UNAVAILABLE");
833
- }
834
- let finish;
835
- let readyNow;
836
- const ready = new Promise((resolve) => {
837
- readyNow = resolve;
838
- });
839
- const done = new Promise((resolve) => {
840
- finish = resolve;
841
- });
842
- const active = {
843
- controller: new AbortController(),
844
- done,
845
- finish,
846
- ready,
847
- readyNow,
848
- timer: setTimeout(
849
- () => {
850
- this.finishTurn("CODEX_RUNTIME_UNSUPPORTED");
851
- this.broken = true;
852
- void this.closeGeneration();
853
- },
854
- limit(this.options?.turnTimeoutMs, 3e5)
855
- ),
856
- events: [],
857
- messages: /* @__PURE__ */ new Map(),
858
- fileChanges: /* @__PURE__ */ new Map(),
859
- toolResults: [],
860
- toolItems: /* @__PURE__ */ new Set(),
861
- completedToolItems: /* @__PURE__ */ new Set(),
862
- recovery: freshBudget(),
863
- usageBaseline: this.threadUsageTotal,
864
- actualModel: this.config.model
865
- };
866
- this.active = active;
867
- this.mcpDiagnostics.nativeMcpToolItemCount = 0;
868
- this.observeMcp(true);
869
- this.tools?.beginTurn?.(active.controller.signal);
870
- try {
871
- const response = await this.client.request("turn/start", {
872
- threadId: this.threadId,
873
- permissions: "managed",
874
- input,
875
- model: this.config.model,
876
- effort: this.config.effort ?? this.config.harnessOptions.codex.reasoningEffort
877
- });
878
- if (this.active !== active) return;
879
- if (!record2(response.turn) || typeof response.turn.id !== "string") throw failure();
880
- active.id = response.turn.id;
881
- active.readyNow();
882
- for (const event of active.events.splice(0)) this.notification(event.method, event.params);
883
- if (this.active === active && response.turn.status !== "inProgress")
884
- this.complete(response.turn);
885
- await done;
886
- } catch {
887
- this.finishTurn("CODEX_RUNTIME_UNSUPPORTED");
888
- }
889
- }
890
- async abort() {
891
- const active = this.active;
892
- if (!active) return;
893
- active.controller.abort();
894
- try {
895
- if (!active.id)
896
- await bounded(
897
- active.ready,
898
- this.controller.signal,
899
- limit(this.options?.requestTimeoutMs, 15e3)
900
- );
901
- if (this.active !== active) return;
902
- await this.client.request("turn/interrupt", {
903
- threadId: this.threadId,
904
- turnId: active.id
905
- });
906
- await bounded(
907
- active.done,
908
- this.controller.signal,
909
- limit(this.options?.requestTimeoutMs, 15e3)
910
- );
911
- } catch {
912
- this.finishTurn("CODEX_RUNTIME_UNSUPPORTED");
913
- this.broken = true;
914
- await this.closeGeneration();
915
- }
916
- }
917
- kill() {
918
- if (this.killed) return;
919
- this.killed = true;
920
- this.finishTurn("CODEX_RUNTIME_UNSUPPORTED");
921
- void this.closeGeneration();
922
- }
923
- async dispose() {
924
- this.kill();
925
- await this.starting?.catch(() => {
926
- });
927
- await this.closing;
928
- }
929
- async resetSession() {
930
- if (this.killed || this.broken) throw failure();
931
- if (this.resetting) return this.resetting;
932
- this.resetting = Promise.resolve().then(async () => {
933
- if (this.active) await this.abort();
934
- await this.queue;
935
- await this.starting;
936
- await this.closeGeneration();
937
- if (this.killed || this.broken) throw failure();
938
- this.config = { ...this.config, resumeSessionId: void 0 };
939
- this.lastThreadId = void 0;
940
- this.threadUsageTotal = void 0;
941
- }).finally(() => {
942
- this.resetting = void 0;
943
- });
944
- return this.resetting;
945
- }
946
- /**
947
- * Store a model / thinking / effort change; the next prompt merges it into the
948
- * config before the turn starts, and a turn in flight keeps what it began with.
949
- */
950
- reconfigure(patch) {
951
- return this.reconfig.reconfigure(patch);
952
- }
953
- closeGeneration() {
954
- const generation = ++this.generation;
955
- const finalMcp = { ...this.mcpDiagnostics };
956
- this.mcpStartup = "unknown";
957
- this.pendingMcpStartup = void 0;
958
- this.controller.abort();
959
- this.nativeApprovalPolicy = void 0;
960
- this.loginCompleted?.reject(failure());
961
- this.loginCompleted = void 0;
962
- const client = this.client;
963
- this.client = void 0;
964
- const connecting = this.connecting;
965
- this.connecting = void 0;
966
- const tools = this.tools;
967
- this.tools = void 0;
968
- const instance = this.instance;
969
- this.instance = void 0;
970
- this.threadId = void 0;
971
- this.closing = this.closing.then(async () => {
972
- try {
973
- const pendingClient = await connecting?.catch(() => void 0);
974
- await client?.dispose();
975
- if (pendingClient && pendingClient !== client) await pendingClient.dispose();
976
- if (client && !client.terminationConfirmed || pendingClient && !pendingClient.terminationConfirmed)
977
- this.cleanupUncertain = true;
978
- if (tools) {
979
- try {
980
- await bounded(
981
- Promise.resolve().then(() => tools.dispose()),
982
- new AbortController().signal,
983
- 1e3
984
- );
985
- if (generation === this.generation && !this.cleanupUncertain)
986
- this.observeClosedMcp(tools, finalMcp);
987
- } catch {
988
- this.cleanupUncertain = true;
989
- }
990
- }
991
- } finally {
992
- instance?.release();
993
- }
994
- }).catch(() => {
995
- this.cleanupUncertain = true;
996
- });
997
- return this.closing;
998
- }
999
- notification(method, params) {
1000
- if (!record2(params)) return;
1001
- if (method === "mcpServer/startupStatus/updated") {
1002
- const serverName = this.tools?.diagnostics?.serverName;
1003
- if (!serverName || params.name !== serverName || typeof params.threadId !== "string" || params.threadId.length > 512 || typeof params.status !== "string" || !["starting", "ready", "failed", "cancelled"].includes(params.status))
1004
- return;
1005
- const status = params.status;
1006
- if (this.threadId) {
1007
- if (params.threadId === this.threadId) this.mcpStartup = status;
1008
- } else this.pendingMcpStartup = { threadId: params.threadId, status };
1009
- return;
1010
- }
1011
- if (method === "account/login/completed") {
1012
- if (params.success === true && params.loginId == null) this.loginCompleted?.resolve();
1013
- else this.loginCompleted?.reject(failure("CODEX_AUTH_UNAVAILABLE"));
1014
- return;
1015
- }
1016
- const active = this.active;
1017
- if ((!active || !active.usageCursor && this.resumeUsageTurnIds.has(String(params.turnId))) && method === "thread/tokenUsage/updated" && params.threadId === (this.threadId ?? this.config.resumeSessionId) && record2(params.tokenUsage) && record2(params.tokenUsage.total)) {
1018
- this.threadUsageTotal = nativeUsage(params.tokenUsage.total);
1019
- if (active) active.usageBaseline = this.threadUsageTotal;
1020
- return;
1021
- }
1022
- if (!active || params.threadId !== this.threadId) return;
1023
- if (!active.id) {
1024
- if (active.events.length >= 256) {
1025
- this.broken = true;
1026
- this.finishTurn("CODEX_RUNTIME_UNSUPPORTED");
1027
- void this.closeGeneration();
1028
- } else active.events.push({ method, params });
1029
- return;
1030
- }
1031
- const turnId = record2(params.turn) ? params.turn.id : params.turnId;
1032
- if (turnId !== active.id) return;
1033
- if (method === "thread/tokenUsage/updated" && record2(params.tokenUsage)) {
1034
- const last = params.tokenUsage.last;
1035
- const total = params.tokenUsage.total;
1036
- const cumulativeUsage = record2(total) ? nativeUsage(total) : void 0;
1037
- if (cumulativeUsage) {
1038
- active.usageBaseline ??= {};
1039
- this.resumeUsageTurnIds.clear();
1040
- const cursor = active.usageCursor ?? active.usageBaseline;
1041
- const reset = cursor?.totalTokens !== void 0 && cumulativeUsage.totalTokens !== void 0 && cumulativeUsage.totalTokens < cursor.totalTokens;
1042
- const increment = reset ? cumulativeUsage : subtractUsage(cumulativeUsage, cursor);
1043
- if (Object.values(increment).some((value) => typeof value === "number" && value > 0))
1044
- active.usage = addUsage(active.usage, increment);
1045
- active.usageCursor = cumulativeUsage;
1046
- this.threadUsageTotal = cumulativeUsage;
1047
- }
1048
- if (record2(last)) {
1049
- if (typeof last.totalTokens === "number") active.contextTokens = last.totalTokens;
1050
- }
1051
- if (typeof params.tokenUsage.modelContextWindow === "number")
1052
- active.contextWindow = params.tokenUsage.modelContextWindow;
1053
- } else if (method === "model/rerouted") {
1054
- active.actualModel = typeof params.toModel === "string" ? params.toModel : active.actualModel;
1055
- active.failureCode = "CODEX_MODEL_UNAVAILABLE";
1056
- } else if (method === "turn/completed" && record2(params.turn)) this.complete(params.turn);
1057
- else if (method === "error" && params.willRetry !== true)
1058
- active.failureCode = this.nativeErrorCode(params.error);
1059
- else if (method === "item/agentMessage/delta" && typeof params.itemId === "string" && typeof params.delta === "string") {
1060
- const previous = active.messages.get(params.itemId);
1061
- if (previous === void 0)
1062
- this.event({
1063
- type: "message_start",
1064
- message: { role: "assistant", content: [{ type: "text", text: "" }] }
1065
- });
1066
- const text2 = (previous ?? "") + params.delta;
1067
- active.messages.set(params.itemId, text2);
1068
- this.event({
1069
- type: "message_update",
1070
- message: { role: "assistant", content: [{ type: "text", text: text2 }] },
1071
- _textDelta: params.delta
1072
- });
1073
- } else if ((method === "item/started" || method === "item/completed") && record2(params.item) && typeof params.item.id === "string") {
1074
- this.item(
1075
- params.item,
1076
- method === "item/completed"
1077
- );
1078
- }
1079
- }
1080
- item(item, completed) {
1081
- const active = this.active;
1082
- if (item.type === "fileChange") {
1083
- active.fileChanges.delete(item.id);
1084
- if (!completed && Array.isArray(item.changes) && item.changes.length <= 16 && active.fileChanges.size < 16) {
1085
- const snapshot = JSON.stringify(item.changes);
1086
- if (snapshot.length <= 65536) active.fileChanges.set(item.id, snapshot);
1087
- }
1088
- }
1089
- if (item.type === "agentMessage") {
1090
- if (completed && typeof item.text === "string") {
1091
- const previous = active.messages.get(item.id) ?? "";
1092
- if (!active.messages.has(item.id))
1093
- this.event({
1094
- type: "message_start",
1095
- message: {
1096
- role: "assistant",
1097
- content: [{ type: "text", text: "" }]
1098
- }
1099
- });
1100
- if (item.text.startsWith(previous) && item.text.length > previous.length)
1101
- this.event({
1102
- type: "message_update",
1103
- message: {
1104
- role: "assistant",
1105
- content: [{ type: "text", text: item.text }]
1106
- },
1107
- _textDelta: item.text.slice(previous.length)
1108
- });
1109
- active.messages.set(item.id, item.text);
1110
- }
1111
- return;
1112
- }
1113
- const name = item.type === "commandExecution" ? "Bash" : item.type === "fileChange" ? "ApplyPatch" : item.type === "mcpToolCall" ? `mcp__${item.server}__${item.tool}` : void 0;
1114
- if (!name) return;
1115
- if (!active.toolItems.has(item.id)) {
1116
- if (item.type === "mcpToolCall" && item.server === this.tools?.diagnostics?.serverName)
1117
- this.mcpDiagnostics.nativeMcpToolItemCount = Math.min(
1118
- 512,
1119
- this.mcpDiagnostics.nativeMcpToolItemCount + 1
1120
- );
1121
- active.toolItems.add(item.id);
1122
- this.event({
1123
- type: "tool_call",
1124
- name,
1125
- tool: { name },
1126
- toolCallId: item.id,
1127
- input: item.type === "mcpToolCall" ? item.arguments : item.type === "commandExecution" ? { command: item.command } : item.type === "fileChange" ? { changes: item.changes } : {}
1128
- });
1129
- }
1130
- if (completed && !active.completedToolItems.has(item.id)) {
1131
- active.completedToolItems.add(item.id);
1132
- active.toolResults.push({
1133
- role: "tool",
1134
- toolName: name,
1135
- content: "",
1136
- data: item.type === "mcpToolCall" ? {
1137
- content: item.result?.content,
1138
- structuredContent: item.result?.structuredContent,
1139
- status: item.status
1140
- } : item.type === "commandExecution" ? {
1141
- output: item.aggregatedOutput,
1142
- exitCode: item.exitCode,
1143
- status: item.status
1144
- } : item.type === "fileChange" ? { changes: item.changes, status: item.status } : {},
1145
- isError: "status" in item && item.status === "failed"
1146
- });
1147
- this.event({ type: "tool_execution_end", toolName: name });
1148
- }
1149
- }
1150
- complete(turn) {
1151
- if (turn.status === "completed") this.finishTurn(this.active?.failureCode);
1152
- else if (turn.status === "interrupted") this.finishTurn("CODEX_TURN_INTERRUPTED");
1153
- else if (turn.status === "failed")
1154
- this.finishTurn(this.active?.failureCode ?? this.nativeErrorCode(turn.error));
1155
- }
1156
- nativeErrorCode(error) {
1157
- const info = record2(error) ? error.codexErrorInfo : void 0;
1158
- if (info === "unauthorized") return "CODEX_RECONNECT_REQUIRED";
1159
- if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "serverOverloaded")
1160
- return "CODEX_RATE_LIMITED";
1161
- if (record2(info) && [
1162
- "httpConnectionFailed",
1163
- "responseStreamConnectionFailed",
1164
- "responseStreamDisconnected",
1165
- "responseTooManyFailedAttempts"
1166
- ].some((key) => key in info))
1167
- return "CODEX_NETWORK_UNAVAILABLE";
1168
- return "CODEX_RUNTIME_UNSUPPORTED";
1169
- }
1170
- observeMcp(beforeTurn) {
1171
- const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? Math.min(512, value) : 0;
1172
- let listed = 0;
1173
- let called = 0;
1174
- try {
1175
- const counts = this.tools?.diagnostics?.requestCounts();
1176
- listed = count(counts?.toolsListTotal);
1177
- called = count(counts?.toolsCallTotal);
1178
- } catch {
1179
- }
1180
- if (beforeTurn) {
1181
- this.mcpDiagnostics.startupBeforeTurn = this.mcpStartup;
1182
- this.mcpDiagnostics.toolsListBeforeTurn = listed;
1183
- }
1184
- this.mcpDiagnostics.startupAtEnd = this.mcpStartup;
1185
- this.mcpDiagnostics.toolsListTotal = Math.max(this.mcpDiagnostics.toolsListBeforeTurn, listed);
1186
- this.mcpDiagnostics.toolsCallTotal = beforeTurn ? called : Math.max(this.mcpDiagnostics.toolsCallTotal, called);
1187
- this.publishMcp(this.mcpDiagnostics);
1188
- }
1189
- observeClosedMcp(tools, snapshot) {
1190
- try {
1191
- const counts = tools.diagnostics?.requestCounts();
1192
- if (!counts || ![counts.toolsListTotal, counts.toolsCallTotal].every(
1193
- (value) => Number.isSafeInteger(value) && value >= 0
1194
- ))
1195
- return;
1196
- snapshot.toolsListTotal = Math.max(
1197
- snapshot.toolsListTotal,
1198
- Math.min(512, counts.toolsListTotal)
1199
- );
1200
- snapshot.toolsCallTotal = Math.max(
1201
- snapshot.toolsCallTotal,
1202
- Math.min(512, counts.toolsCallTotal)
1203
- );
1204
- this.publishMcp(snapshot);
1205
- } catch {
1206
- }
1207
- }
1208
- publishMcp(snapshot) {
1209
- try {
1210
- void Promise.resolve(
1211
- this.options?.onNativeMcpDiagnostics?.(Object.freeze({ ...snapshot }))
1212
- ).catch(() => {
1213
- });
1214
- } catch {
1215
- }
1216
- }
1217
- finishTurn(code) {
1218
- const active = this.active;
1219
- if (!active) return;
1220
- this.active = void 0;
1221
- this.observeMcp(false);
1222
- clearTimeout(active.timer);
1223
- active.controller.abort();
1224
- active.fileChanges.clear();
1225
- active.readyNow();
1226
- for (const text2 of active.messages.values())
1227
- this.event({
1228
- type: "message_end",
1229
- message: { role: "assistant", content: [{ type: "text", text: text2 }] }
1230
- });
1231
- this.event({ type: "turn_end", toolResults: active.toolResults });
1232
- const modelUsage = active.usage ? {
1233
- inputTokens: active.usage.inputTokens,
1234
- outputTokens: active.usage.outputTokens,
1235
- cacheReadTokens: active.usage.cacheReadTokens,
1236
- ...typeof active.contextWindow === "number" ? { contextWindow: active.contextWindow } : {}
1237
- } : void 0;
1238
- const usage = {
1239
- ...active.usage ? { tokens: active.usage } : {},
1240
- ...modelUsage ? { modelUsage: { [active.actualModel]: modelUsage } } : {},
1241
- ...typeof active.contextTokens === "number" ? { contextTokens: active.contextTokens } : {},
1242
- ...typeof active.contextWindow === "number" ? { contextWindow: active.contextWindow } : {}
1243
- };
1244
- if (code)
1245
- this.event({
1246
- type: "error",
1247
- error: code,
1248
- fatal: code !== "CODEX_TURN_INTERRUPTED",
1249
- detail: {
1250
- message: code,
1251
- category: code === "CODEX_TURN_INTERRUPTED" ? "process" : code === "CODEX_RATE_LIMITED" ? "rate_limit" : code === "CODEX_NETWORK_UNAVAILABLE" ? "network" : code === "CODEX_AUTH_UNAVAILABLE" || code === "CODEX_RECONNECT_REQUIRED" ? "auth" : "config",
1252
- retryable: false
1253
- },
1254
- ...usage
1255
- });
1256
- else
1257
- this.event({
1258
- type: "result",
1259
- subtype: "success",
1260
- summary: [...active.messages.values()].join("\n"),
1261
- ...usage
1262
- });
1263
- this.event({ type: "agent_end" });
1264
- active.finish();
1265
- }
1266
- event(event) {
1267
- try {
1268
- this.emit("agent-event", event);
1269
- } catch {
1270
- }
1271
- }
1272
- };
1273
-
1274
- // bridge/src/codex/friendly-error.ts
1275
- function unwrapErrorBody(raw) {
1276
- const start = raw.indexOf("{");
1277
- if (start < 0) return raw;
1278
- try {
1279
- const body = JSON.parse(raw.slice(start));
1280
- const inner = typeof body.error === "object" ? body.error?.message : body.error;
1281
- const text2 = inner ?? body.message;
1282
- if (typeof text2 === "string" && text2.length > 0) return text2;
1283
- } catch {
1284
- }
1285
- return raw;
1286
- }
1287
- function nativeCause(raw) {
1288
- const reconnecting = /^Reconnecting\.\.\.\s*\d+\/\d+\s*\(([\s\S]*)\)\s*$/.exec(raw.trim());
1289
- const reason = reconnecting ? reconnecting[1] ?? "" : unwrapErrorBody(raw);
1290
- const line = reason.split(/[{\n]/, 1)[0]?.replace(/[\s:,.]+$/, "") ?? "";
1291
- return line.length > 160 ? `${line.slice(0, 157)}...` : line;
1292
- }
1293
- function friendlyCodexError(raw, context = {}) {
1294
- const text2 = unwrapErrorBody(raw);
1295
- const chatgpt = /'([^']+)' model is not supported when using Codex with a ChatGPT account/i.exec(
1296
- text2
1297
- );
1298
- if (chatgpt) {
1299
- return {
1300
- message: `codex harness: the model '${chatgpt[1]}' is not available with a ChatGPT login.`,
1301
- category: "model",
1302
- hint: "Update @openai/codex-sdk to the 0.16x line, pass --model with a model your login allows, or set OPENAI_API_KEY."
1303
- };
1304
- }
1305
- if (/newer version of codex|requires a newer version|update codex/i.test(text2)) {
1306
- return {
1307
- message: `codex harness: the selected model needs a newer Codex than the installed @openai/codex-sdk.`,
1308
- category: "model",
1309
- hint: "Update @openai/codex-sdk to the 0.16x line (npm i @openai/codex-sdk@latest)."
1310
- };
1311
- }
1312
- if (/invalid_api_key|incorrect api key|\b401\b[^.]*unauthorized|unauthorized[^.]*\b401\b/i.test(raw)) {
1313
- if (context.chatgptLogin) {
1314
- const cause = nativeCause(raw);
1315
- return {
1316
- message: `codex harness: the codex login was rejected (401)${cause ? `: ${cause}` : ""}.`,
1317
- category: "auth",
1318
- hint: "Run `codex login` to sign in again."
1319
- };
1320
- }
1321
- return {
1322
- message: "codex harness: the API key was rejected (401).",
1323
- category: "auth",
1324
- hint: "Check OPENAI_API_KEY (or sign in again with `codex login`)."
1325
- };
1326
- }
1327
- const reconnecting = /^Reconnecting\.\.\.\s*\d+\/\d+\s*\(([\s\S]*)\)\s*$/.exec(raw.trim());
1328
- if (reconnecting) {
1329
- const reason = (reconnecting[1] ?? "").split(/[{\n]/, 1)[0]?.replace(/[\s:,]+$/, "") ?? "";
1330
- return {
1331
- message: `codex harness: could not reach the model endpoint${reason ? ` (${reason})` : ""}.`,
1332
- category: "network",
1333
- hint: "Check the network and the provider's status, then run again."
1334
- };
1335
- }
1336
- return null;
1337
- }
1338
-
1339
- // bridge/src/harnesses/codex.ts
1340
- function buildCodexChildEnv(parent, codexHome) {
1341
- const out = {};
1342
- const explicit = [
1343
- "PATH",
1344
- "HOME",
1345
- "USER",
1346
- "HOSTNAME",
1347
- "SKAILE_SESSION_ID",
1348
- ...RUNNER_AGENT_ENV_KEYS
1349
- ];
1350
- for (const key of explicit) {
1351
- const v = parent[key];
1352
- if (v !== void 0) out[key] = v;
1353
- }
1354
- for (const [key, value] of Object.entries(parent)) {
1355
- if (key.startsWith("PI_") && typeof value === "string") out[key] = value;
1356
- }
1357
- for (const key of ["OPENAI_API_KEY", "CODEX_API_KEY"]) {
1358
- const v = parent[key];
1359
- if (v) out[key] = v;
1360
- }
1361
- out.CODEX_HOME = codexHome;
1362
- return out;
1363
- }
1364
- function linkCodexLogin(codexHome, loginFile) {
1365
- const target = join(codexHome, "auth.json");
1366
- mkdirSync(codexHome, { recursive: true, mode: 448 });
1367
- rmSync(target, { force: true });
1368
- try {
1369
- symlinkSync(loginFile, target);
1370
- } catch {
1371
- copyFileSync(loginFile, target);
1372
- }
1373
- }
1374
- function missingCodexCredential(build, env, loginFile, unresolved) {
1375
- const table = build.providerId ? build.document.model_providers[codexProviderTableId(build.providerId)] : void 0;
1376
- if (table) {
1377
- if (table.requires_openai_auth) return void 0;
1378
- if (!table.env_key || env[table.env_key]) return void 0;
1379
- return `codex harness: the AI provider entry '${build.providerId}' has no credential${unresolved ? ` (${unresolved})` : ""}; export the variable its credential names (see \`skaile providers test ${build.providerId}\`)`;
1380
- }
1381
- if (env.OPENAI_API_KEY || env.CODEX_API_KEY || loginFile) return void 0;
1382
- return "codex harness needs OPENAI_API_KEY, or the codex CLI's ChatGPT login (run `codex login`; ~/.codex/auth.json), or an AI provider entry with a credential";
1383
- }
1384
- var CodexHarness = class extends AgentHarness {
1385
- harnessInfo = {
1386
- id: "codex",
1387
- name: "OpenAI Codex",
1388
- modelAgnostic: false,
1389
- supportsInBandAbort: true,
1390
- capabilities: BUILTIN_HARNESS_CATALOG.codex?.capabilities
1391
- };
1392
- log = getBridgeLogger("codex");
1393
- config;
1394
- reconfig = new ReconfigureLedger({ config: () => this.config });
1395
- thread = null;
1396
- running = false;
1397
- abortController = null;
1398
- pendingToolResults = [];
1399
- activeAssistantItemId = null;
1400
- /** The run signs in with codex's ChatGPT login, not an API key: a 401 means the login lapsed. */
1401
- chatgptLogin = false;
1402
- activeAssistantText = "";
1403
- _runtimeSessionId;
1404
- /** Token usage from the most recent completed turn. */
1405
- _lastTokens = null;
1406
- constructor(config) {
1407
- super();
1408
- if (isManagedCodexConfig(config)) throw new Error("CODEX_MANAGED_REQUIRES_FACTORY");
1409
- this.config = config;
1410
- }
1411
- get runtimeSessionId() {
1412
- return this._runtimeSessionId;
1413
- }
1414
- async dispose() {
1415
- this.kill();
1416
- }
1417
- /**
1418
- * Store a model / thinking / effort change. The SDK thread is built from
1419
- * `config` in {@link start}, so the next thread start (first prompt, or after
1420
- * `resetSession()`) uses it; a thread already running keeps its options.
1421
- */
1422
- reconfigure(patch) {
1423
- return this.reconfig.reconfigure(patch);
1424
- }
1425
- getModel() {
1426
- return this.config.model;
1427
- }
1428
- async start() {
1429
- if (this.thread) return;
1430
- let sdk;
1431
- try {
1432
- sdk = await loadHarnessSdk(
1433
- "@openai/codex-sdk",
1434
- this.config.cwd,
1435
- () => import('@openai/codex-sdk'),
1436
- "Codex SDK"
1437
- );
1438
- } catch (err) {
1439
- this.log.error("codex SDK load failed", err);
1440
- throw err;
1441
- }
1442
- const codexHome = codexSessionHome(this.config);
1443
- const build = buildCodexConfigDocument({
1444
- registry: this.config.registry,
1445
- modelRef: this.config.modelRef,
1446
- model: this.config.model,
1447
- roles: this.config.roles
1448
- });
1449
- if (build.unaddressable) {
1450
- const { id, reason } = build.unaddressable;
1451
- const message = `AI provider '${id}' cannot be used with the codex harness: ${reason}. Pick a model of another provider.`;
1452
- this.log.error("codex cannot address the selected AI provider", { provider: id, reason });
1453
- throw Object.assign(new Error(message), { category: "config", hint: message });
1454
- }
1455
- for (const warning of build.warnings) this.log.warn("codex model selection", { warning });
1456
- for (const entry of build.skipped)
1457
- this.log.debug("codex cannot address an AI provider entry", {
1458
- provider: entry.id,
1459
- reason: entry.reason
1460
- });
1461
- const env = this.config.env ? { ...this.config.env, CODEX_HOME: codexHome } : buildCodexChildEnv(process.env, codexHome);
1462
- Object.assign(
1463
- env,
1464
- registryCredentialEnv(this.config.registry ?? {}, { env: { ...process.env, ...env } })
1465
- );
1466
- stripRunnerPrivateEnv(env);
1467
- const hasKey = Boolean(env.OPENAI_API_KEY || env.CODEX_API_KEY);
1468
- const loginFile = hasKey ? void 0 : codexLoginFile({ ...process.env, ...this.config.env });
1469
- this.chatgptLogin = isChatgptLogin(loginFile);
1470
- if (usesCodexOwnAuth(build, env, loginFile)) {
1471
- delete build.document.model_provider;
1472
- delete build.document.model_providers[codexProviderTableId("openai")];
1473
- this.log.debug("codex uses its own auth: the openai entry has no credential");
1474
- }
1475
- const unresolved = build.providerId && this.config.registry ? unresolvedProviderCredentials(this.config.registry, {
1476
- env: { ...process.env, ...env },
1477
- providerId: build.providerId
1478
- })[0]?.reason : void 0;
1479
- const missing = missingCodexCredential(build, env, loginFile, unresolved);
1480
- if (missing) {
1481
- this.log.error("codex credential missing", { reason: missing });
1482
- throw Object.assign(new Error(missing), { category: "config", hint: missing });
1483
- }
1484
- writeCodexConfigToml(codexHome, build.document);
1485
- if (loginFile) linkCodexLogin(codexHome, loginFile);
1486
- else rmSync(join(codexHome, "auth.json"), { force: true });
1487
- const instructionsFile = this.writeInstructionsFile();
1488
- const client = new sdk.Codex({
1489
- apiKey: env.OPENAI_API_KEY,
1490
- env: Object.fromEntries(Object.entries(env).filter(([, value]) => value != null)),
1491
- ...instructionsFile ? { config: { model_instructions_file: instructionsFile } } : {}
1492
- });
1493
- const codexOptions = this.config.harnessOptions?.codex;
1494
- const threadOptions = {
1495
- model: build.model ?? this.config.model,
1496
- sandboxMode: codexOptions?.sandboxMode ?? "workspace-write",
1497
- workingDirectory: this.config.cwd,
1498
- skipGitRepoCheck: true,
1499
- modelReasoningEffort: codexOptions?.reasoningEffort ?? "medium",
1500
- networkAccessEnabled: codexOptions?.networkAccessEnabled,
1501
- approvalPolicy: codexOptions?.approvalPolicy ?? "never",
1502
- additionalDirectories: codexOptions?.additionalDirectories
1503
- };
1504
- this.thread = this.config.resumeSessionId ? client.resumeThread(this.config.resumeSessionId, threadOptions) : client.startThread(threadOptions);
1505
- this._runtimeSessionId = this.thread.id ?? this.config.resumeSessionId;
1506
- this.log.info("codex harness started", {
1507
- model: this.config.model,
1508
- resumed: Boolean(this.config.resumeSessionId),
1509
- sessionId: this._runtimeSessionId
1510
- });
1511
- }
1512
- async prompt(message) {
1513
- await this.start();
1514
- if (!this.thread) throw new Error("Codex thread not initialized");
1515
- if (this.running) throw new Error("Codex turn already in progress");
1516
- this.running = true;
1517
- this.pendingToolResults = [];
1518
- this.activeAssistantItemId = null;
1519
- this.activeAssistantText = "";
1520
- this._lastTokens = null;
1521
- this.abortController = new AbortController();
1522
- let turnFinished = false;
1523
- this.log.debug("prompt issued", { length: message.length });
1524
- try {
1525
- const input = message;
1526
- const { events } = await this.thread.runStreamed(input, {
1527
- signal: this.abortController.signal
1528
- });
1529
- for await (const event of events) {
1530
- turnFinished = this.handleThreadEvent(event) || turnFinished;
1531
- }
1532
- } catch (err) {
1533
- const error = err instanceof Error ? err : new Error(String(err));
1534
- if (error.name !== "AbortError") {
1535
- this.log.error("prompt failed", error);
1536
- const detail = this.classifyErrorMessage(error.message);
1537
- this.emit("agent-event", {
1538
- type: "error",
1539
- error: detail.message,
1540
- detail
1541
- });
1542
- this.emit("agent-event", { type: "agent_end" });
1543
- }
1544
- } finally {
1545
- if (!turnFinished && this.activeAssistantItemId) {
1546
- this.emit("agent-event", {
1547
- type: "message_end",
1548
- message: this.buildAssistantMessage(this.activeAssistantText)
1549
- });
1550
- }
1551
- this.activeAssistantItemId = null;
1552
- this.activeAssistantText = "";
1553
- this.abortController = null;
1554
- this.running = false;
1555
- }
1556
- }
1557
- async abort() {
1558
- this.abortController?.abort();
1559
- }
1560
- get isRunning() {
1561
- return this.running;
1562
- }
1563
- kill() {
1564
- this.abortController?.abort();
1565
- this.running = false;
1566
- this.abortController = null;
1567
- this.log.info("codex harness killed");
1568
- }
1569
- /**
1570
- * Discover models from the endpoint this session actually addresses.
1571
- *
1572
- * The registry entry codex would talk to supplies both the base URL and the
1573
- * credential, so a session pointed at a gateway lists that gateway's models
1574
- * instead of api.openai.com's. A `platform:` reference the session boundary
1575
- * already resolved is picked up from `SKAILE_AIP_<ID>_KEY` in the session
1576
- * env. Without a registry entry codex can address, an ambient
1577
- * `OPENAI_API_KEY` is the last resort.
1578
- */
1579
- async listModels() {
1580
- const selected = this.selectedProviderEntry();
1581
- const sessionEnv = { ...process.env, ...this.config.env };
1582
- const apiKey = selected ? entryCredentialValue(selected.id, selected.entry, { env: sessionEnv }) : sessionEnv.OPENAI_API_KEY;
1583
- if (!apiKey) return [];
1584
- const baseUrl = selected ? resolveEntryBaseUrl(selected.entry) : void 0;
1585
- const result = await fetchProviderModels("openai", apiKey, baseUrl ? { baseUrl } : {});
1586
- return result.ok ? result.models : [];
1587
- }
1588
- /**
1589
- * The registry entry codex addresses this session — the same selection the
1590
- * rendered `config.toml` names in `model_provider`.
1591
- */
1592
- selectedProviderEntry() {
1593
- const registry = this.config.registry;
1594
- if (!registry) return void 0;
1595
- const { providerId } = buildCodexConfigDocument({
1596
- registry,
1597
- modelRef: this.config.modelRef,
1598
- model: this.config.model,
1599
- roles: this.config.roles
1600
- });
1601
- if (!providerId) return void 0;
1602
- const match = registryEntries(registry).find(([id]) => id === providerId);
1603
- return match ? { id: match[0], entry: match[1] } : void 0;
1604
- }
1605
- async resetSession() {
1606
- this.kill();
1607
- this.config = { ...this.config, resumeSessionId: void 0 };
1608
- this.thread = null;
1609
- this._runtimeSessionId = void 0;
1610
- this._lastTokens = null;
1611
- }
1612
- getTokenUsage() {
1613
- return this._lastTokens;
1614
- }
1615
- /**
1616
- * Write a combined instructions file for Codex CLI's `model_instructions_file` config.
1617
- * Combines the agent's pre-rendered identity (`.codex/skaile-agents/<agentName>.md`, written
1618
- * by `skaile install`, one file per agent instance) with runtime context
1619
- * (resources, environment, prompt-extensions).
1620
- */
1621
- writeInstructionsFile() {
1622
- const parts = [];
1623
- if (this.config.agentDir && this.config.agentName) {
1624
- const agentFile = join(
1625
- this.config.cwd,
1626
- ".codex",
1627
- "skaile-agents",
1628
- `${this.config.agentName}.md`
1629
- );
1630
- if (existsSync(agentFile)) {
1631
- parts.push(readFileSync(agentFile, "utf-8"));
1632
- }
1633
- }
1634
- if (this.config.systemPrompt) {
1635
- parts.push(this.config.systemPrompt);
1636
- }
1637
- if (parts.length === 0) return void 0;
1638
- const instrFile = join(this.config.cwd, ".codex", "skaile-session-instructions.md");
1639
- mkdirSync(dirname(instrFile), { recursive: true });
1640
- writeFileSync(instrFile, parts.join("\n\n---\n\n"));
1641
- return instrFile;
1642
- }
1643
- handleThreadEvent(event) {
1644
- switch (event.type) {
1645
- case "thread.started":
1646
- this._runtimeSessionId = event.thread_id;
1647
- return false;
1648
- case "turn.started":
1649
- return false;
1650
- case "item.started":
1651
- case "item.updated":
1652
- case "item.completed":
1653
- this.handleThreadItem(event.item, event.type === "item.completed", event.type);
1654
- return false;
1655
- case "turn.completed": {
1656
- this.flushToolResults();
1657
- const usage = event.usage;
1658
- const tokens = usage ? {
1659
- inputTokens: usage.input_tokens,
1660
- outputTokens: usage.output_tokens,
1661
- cacheReadTokens: usage.cached_input_tokens
1662
- } : null;
1663
- this._lastTokens = tokens;
1664
- this.emit("agent-event", {
1665
- type: "result",
1666
- subtype: "success",
1667
- summary: this.activeAssistantText || "Task completed",
1668
- // Codex SDK does not report per-turn cost. `0` signals "not
1669
- // reported" — pair with `tokens` to disambiguate from "free".
1670
- costUsd: 0,
1671
- ...tokens ? { tokens } : {}
1672
- });
1673
- this.emit("agent-event", { type: "agent_end" });
1674
- return true;
1675
- }
1676
- case "turn.failed": {
1677
- this.flushToolResults();
1678
- const detail = this.classifyErrorMessage(event.error.message);
1679
- this.emit("agent-event", {
1680
- type: "error",
1681
- error: detail.message,
1682
- detail
1683
- });
1684
- this.emit("agent-event", { type: "agent_end" });
1685
- return true;
1686
- }
1687
- case "error": {
1688
- const detail = this.classifyErrorMessage(event.message);
1689
- this.emit("agent-event", {
1690
- type: "error",
1691
- error: detail.message,
1692
- detail
1693
- });
1694
- this.emit("agent-event", { type: "agent_end" });
1695
- return true;
1696
- }
1697
- }
1698
- }
1699
- handleThreadItem(item, completed, phase) {
1700
- switch (item.type) {
1701
- case "agent_message":
1702
- this.handleAgentMessage(item, completed);
1703
- break;
1704
- case "command_execution":
1705
- this.handleCommandExecution(item, completed, phase);
1706
- break;
1707
- case "mcp_tool_call":
1708
- this.handleMcpToolCall(item, completed, phase);
1709
- break;
1710
- case "file_change":
1711
- this.handleFileChange(item, completed, phase);
1712
- break;
1713
- case "web_search":
1714
- this.handleWebSearch(item, completed, phase);
1715
- break;
1716
- case "error":
1717
- if (completed) {
1718
- this.pendingToolResults.push({
1719
- role: "tool",
1720
- toolName: "CodexError",
1721
- content: "",
1722
- data: { message: item.message },
1723
- isError: true
1724
- });
1725
- }
1726
- break;
1727
- }
1728
- }
1729
- handleAgentMessage(item, completed) {
1730
- if (this.activeAssistantItemId !== item.id) {
1731
- if (this.activeAssistantItemId) {
1732
- this.emit("agent-event", {
1733
- type: "message_end",
1734
- message: this.buildAssistantMessage(this.activeAssistantText)
1735
- });
1736
- }
1737
- this.activeAssistantItemId = item.id;
1738
- this.activeAssistantText = "";
1739
- this.emit("agent-event", {
1740
- type: "message_start",
1741
- message: this.buildAssistantMessage("")
1742
- });
1743
- }
1744
- const nextText = item.text ?? "";
1745
- const delta = nextText.startsWith(this.activeAssistantText) ? nextText.slice(this.activeAssistantText.length) : nextText;
1746
- this.activeAssistantText = nextText;
1747
- if (delta) {
1748
- this.emit("agent-event", {
1749
- type: "message_update",
1750
- message: this.buildAssistantMessage(nextText),
1751
- _textDelta: delta
1752
- });
1753
- }
1754
- if (completed) {
1755
- this.emit("agent-event", {
1756
- type: "message_end",
1757
- message: this.buildAssistantMessage(nextText)
1758
- });
1759
- this.activeAssistantItemId = null;
1760
- }
1761
- }
1762
- handleCommandExecution(item, completed, phase) {
1763
- if (phase === "item.started") {
1764
- this.emit("agent-event", {
1765
- type: "tool_call",
1766
- name: "Bash",
1767
- tool: { name: "Bash" },
1768
- input: { command: item.command }
1769
- });
1770
- }
1771
- if (completed) {
1772
- this.pendingToolResults.push({
1773
- role: "tool",
1774
- toolName: "Bash",
1775
- content: "",
1776
- data: {
1777
- stdout: item.aggregated_output,
1778
- stderr: "",
1779
- exitCode: item.exit_code,
1780
- status: item.status,
1781
- command: item.command
1782
- },
1783
- isError: item.status === "failed"
1784
- });
1785
- this.emit("agent-event", {
1786
- type: "tool_execution_end",
1787
- toolName: "Bash"
1788
- });
1789
- }
1790
- }
1791
- handleMcpToolCall(item, completed, phase) {
1792
- const toolName = `mcp__${item.server}__${item.tool}`;
1793
- if (phase === "item.started") {
1794
- this.emit("agent-event", {
1795
- type: "tool_call",
1796
- name: toolName,
1797
- tool: { name: toolName },
1798
- input: this.toObject(item.arguments)
1799
- });
1800
- }
1801
- if (completed) {
1802
- this.pendingToolResults.push({
1803
- role: "tool",
1804
- toolName,
1805
- content: "",
1806
- data: {
1807
- status: item.status,
1808
- content: item.result?.content,
1809
- structuredContent: item.result?.structured_content,
1810
- error: item.error?.message
1811
- },
1812
- isError: item.status === "failed"
1813
- });
1814
- this.emit("agent-event", {
1815
- type: "tool_execution_end",
1816
- toolName
1817
- });
1818
- }
1819
- }
1820
- handleFileChange(item, completed, phase) {
1821
- if (phase === "item.started") {
1822
- this.emit("agent-event", {
1823
- type: "tool_call",
1824
- name: "ApplyPatch",
1825
- tool: { name: "ApplyPatch" },
1826
- input: { changes: item.changes }
1827
- });
1828
- }
1829
- if (completed) {
1830
- this.pendingToolResults.push({
1831
- role: "tool",
1832
- toolName: "ApplyPatch",
1833
- content: "",
1834
- data: { status: item.status, changes: item.changes },
1835
- isError: item.status === "failed"
1836
- });
1837
- this.emit("agent-event", {
1838
- type: "tool_execution_end",
1839
- toolName: "ApplyPatch"
1840
- });
1841
- }
1842
- }
1843
- handleWebSearch(item, completed, phase) {
1844
- if (phase === "item.started") {
1845
- this.emit("agent-event", {
1846
- type: "tool_call",
1847
- name: "WebSearch",
1848
- tool: { name: "WebSearch" },
1849
- input: { query: item.query }
1850
- });
1851
- }
1852
- if (completed) {
1853
- this.pendingToolResults.push({
1854
- role: "tool",
1855
- toolName: "WebSearch",
1856
- content: "",
1857
- data: { query: item.query, status: "completed" }
1858
- });
1859
- this.emit("agent-event", {
1860
- type: "tool_execution_end",
1861
- toolName: "WebSearch"
1862
- });
1863
- }
1864
- }
1865
- flushToolResults() {
1866
- if (this.pendingToolResults.length === 0) return;
1867
- this.emit("agent-event", {
1868
- type: "turn_end",
1869
- toolResults: [...this.pendingToolResults]
1870
- });
1871
- this.pendingToolResults = [];
1872
- }
1873
- buildAssistantMessage(text2) {
1874
- return {
1875
- role: "assistant",
1876
- content: [{ type: "text", text: text2 }]
1877
- };
1878
- }
1879
- toObject(value) {
1880
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
1881
- return value;
1882
- }
1883
- return { arguments: value };
1884
- }
1885
- classifyErrorMessage(rawMessage) {
1886
- const friendly = friendlyCodexError(rawMessage, { chatgptLogin: this.chatgptLogin });
1887
- if (friendly) {
1888
- return {
1889
- message: friendly.message,
1890
- category: friendly.category,
1891
- retryable: false,
1892
- hint: friendly.hint
1893
- };
1894
- }
1895
- const message = rawMessage;
1896
- const generic = classifyGenericErrorMessage(message);
1897
- if (generic) {
1898
- const hint = generic.category === "auth" ? "Check your OpenAI API key configuration in settings or environment." : generic.category === "rate_limit" ? "Codex hit an OpenAI rate limit. Wait briefly and try again." : generic.category === "model" ? "The selected Codex model is unavailable. Choose a different model." : "A network error occurred while talking to Codex.";
1899
- return { message, category: generic.category, retryable: generic.retryable, hint };
1900
- }
1901
- const lower = message.toLowerCase();
1902
- if (lower.includes("sandbox") || lower.includes("approval") || lower.includes("permission") || lower.includes("git repo")) {
1903
- return {
1904
- message,
1905
- category: "config",
1906
- retryable: false,
1907
- hint: "Check Codex sandbox, approval, and workspace configuration."
1908
- };
1909
- }
1910
- return {
1911
- message,
1912
- category: "unknown",
1913
- retryable: true,
1914
- hint: "An unexpected Codex error occurred. Try the prompt again."
1915
- };
1916
- }
1917
- };
1918
- function isManagedCodexConfig(config) {
1919
- const codex = config.harnessOptions?.codex;
1920
- return Boolean(
1921
- codex?.managedRuntime || codex?.authSource !== void 0 && codex.authSource !== "local"
1922
- );
1923
- }
1924
- var codexHarnessTarget = {
1925
- id: "codex",
1926
- displayName: BUILTIN_HARNESS_CATALOG.codex?.name ?? "OpenAI Codex",
1927
- apiVersion: 1,
1928
- // Harnesses take AgentConfig; passthrough — full schema validation is out of scope.
1929
- configSchema: z.custom(() => true),
1930
- create: async (config, _ctx) => isManagedCodexConfig(config) ? new ManagedCodexHarness(config) : new CodexHarness(config),
1931
- listModels: async (registry, options) => {
1932
- const config = {
1933
- cwd: process.cwd(),
1934
- sessionId: "model-list",
1935
- ...registryHarnessConfig(registry, options)
1936
- };
1937
- return (isManagedCodexConfig(config) ? new ManagedCodexHarness(config) : new CodexHarness(config)).listModels();
1938
- }
1939
- };
1940
-
1941
- export { CodexHarness, codexHarnessTarget, isManagedCodexConfig };
1942
31
  //# sourceMappingURL=codex.js.map
1943
32
  //# sourceMappingURL=codex.js.map