@resolveio/server-lib 22.3.3 → 22.3.5

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 (669) hide show
  1. package/.nodemon.json +5 -0
  2. package/.vscode/settings.json +21 -0
  3. package/AGENTS.md +188 -0
  4. package/README.md +22 -0
  5. package/build_package.sh +5 -0
  6. package/compileDTS.pl +64 -0
  7. package/docs/ai-assistant-nightly-eval.md +65 -0
  8. package/docs/ai-assistant-preflight-checklist.md +23 -0
  9. package/docs/ai-assistant-report-builder-bridge-playbook.md +115 -0
  10. package/eslint-plugin-custom/index.js +7 -0
  11. package/eslint-plugin-custom/rules/no-filter-zero-index.js +44 -0
  12. package/eslint.config.js +103 -0
  13. package/gulpfile.js +216 -0
  14. package/methodAndPublicationListGenerator.py +344 -0
  15. package/mongodbensurers.js +2 -0
  16. package/mongostop.js +3 -0
  17. package/package.json +1 -1
  18. package/scripts/cleanup-bypassed-callmethod-logs.js +616 -0
  19. package/settings.development.json +25 -0
  20. package/settings.development.redacted.json +25 -0
  21. package/src/.env +12 -0
  22. package/src/ai/assistant-core-heuristics.ts +379 -0
  23. package/src/ai/resolveio-platform-intelligence-memory-corpus.ts +185 -0
  24. package/src/ai/resolveio-platform-intelligence-memory.ts +325 -0
  25. package/{ai/resolveio-platform-intelligence-types.d.ts → src/ai/resolveio-platform-intelligence-types.ts} +20 -15
  26. package/src/ai/resolveio-platform-intelligence.ts +462 -0
  27. package/src/client-server-app.ts +12 -0
  28. package/src/collections/ai-terminal-conversation.collection.ts +91 -0
  29. package/src/collections/ai-terminal-issue-report.collection.ts +99 -0
  30. package/src/collections/ai-terminal-message.collection.ts +77 -0
  31. package/src/collections/app-setting.collection.ts +104 -0
  32. package/src/collections/app-status.collection.ts +58 -0
  33. package/src/collections/communication-metric.collection.ts +84 -0
  34. package/src/collections/counter.collection.ts +56 -0
  35. package/src/collections/cron-job-history.collection.ts +94 -0
  36. package/src/collections/cron-job.collection.ts +92 -0
  37. package/src/collections/customer-notification.collection.ts +131 -0
  38. package/src/collections/customer-portal-password.collection.ts +76 -0
  39. package/src/collections/email-history.collection.ts +127 -0
  40. package/src/collections/email-verified.collection.ts +62 -0
  41. package/src/collections/file.collection.ts +74 -0
  42. package/src/collections/flag-update.collection.ts +57 -0
  43. package/src/collections/flag.collection.ts +57 -0
  44. package/src/collections/log-method-latency.collection.ts +77 -0
  45. package/src/collections/log-subscription.collection.ts +80 -0
  46. package/src/collections/log.collection.ts +93 -0
  47. package/src/collections/logged-in-users.collection.ts +67 -0
  48. package/src/collections/monitor-cpu.collection.ts +65 -0
  49. package/src/collections/monitor-function.collection.ts +74 -0
  50. package/src/collections/monitor-memory.collection.ts +77 -0
  51. package/src/collections/monitor-mongo.collection.ts +71 -0
  52. package/src/collections/notification.collection.ts +57 -0
  53. package/src/collections/openai-usage-ledger.collection.ts +77 -0
  54. package/src/collections/report-builder-dashboard-builder.collection.ts +109 -0
  55. package/src/collections/report-builder-library.collection.ts +89 -0
  56. package/src/collections/report-builder-report.collection.ts +184 -0
  57. package/src/collections/user-group.collection.ts +89 -0
  58. package/src/collections/user-guide.collection.ts +57 -0
  59. package/src/collections/user.collection.ts +181 -0
  60. package/src/cron/cron.ts +117 -0
  61. package/src/fixtures/cron-jobs.ts +95 -0
  62. package/src/fixtures/init.ts +35 -0
  63. package/src/http/auth.ts +764 -0
  64. package/src/http/health.ts +7 -0
  65. package/src/http/home.ts +90 -0
  66. package/src/http/slow-query-publication.ts +49 -0
  67. package/src/index.ts +1 -0
  68. package/src/managers/ai-assistant-codex-manager.manager.ts +1131 -0
  69. package/src/managers/communication-metric.manager.ts +82 -0
  70. package/src/managers/cron.manager.ts +333 -0
  71. package/src/managers/customer-notification-content.manager.ts +236 -0
  72. package/src/managers/diagnostic-manager-bootstrap.ts +165 -0
  73. package/src/managers/error-auto-fix.manager.ts +2767 -0
  74. package/src/managers/local-log.manager.ts +113 -0
  75. package/src/managers/method.manager.ts +1827 -0
  76. package/src/managers/mongo.manager.ts +4575 -0
  77. package/src/managers/monitor.manager.ts +507 -0
  78. package/src/managers/openai-usage-ledger.manager.ts +116 -0
  79. package/src/managers/slow-query-verifier.manager.ts +3590 -0
  80. package/src/managers/slow-query.manager.ts +519 -0
  81. package/src/managers/subscription.manager.ts +3128 -0
  82. package/src/managers/websocket.manager.ts +746 -0
  83. package/src/managers/worker-dispatcher.manager.ts +1360 -0
  84. package/src/managers/worker-server.manager.ts +536 -0
  85. package/src/methods/accounts.ts +532 -0
  86. package/src/methods/ai-terminal.ts +22943 -0
  87. package/src/methods/app-settings.ts +114 -0
  88. package/src/methods/aws.ts +649 -0
  89. package/src/methods/collections.ts +641 -0
  90. package/src/methods/counters.ts +69 -0
  91. package/src/methods/cron-jobs.ts +2614 -0
  92. package/src/methods/customer-notifications.ts +458 -0
  93. package/src/methods/diagnostics.ts +616 -0
  94. package/src/methods/flag-updates.ts +7 -0
  95. package/src/methods/flags.ts +7 -0
  96. package/src/methods/logs.ts +657 -0
  97. package/src/methods/mongo-explorer.ts +1880 -0
  98. package/src/methods/monitor.ts +540 -0
  99. package/src/methods/pdf.ts +1236 -0
  100. package/src/methods/publications.ts +129 -0
  101. package/src/methods/report-builder.ts +3300 -0
  102. package/src/methods/support.ts +335 -0
  103. package/src/models/ai-terminal-conversation.model.ts +19 -0
  104. package/src/models/ai-terminal-issue-report.model.ts +21 -0
  105. package/src/models/ai-terminal-message.model.ts +24 -0
  106. package/src/models/app-setting.model.ts +17 -0
  107. package/{models/app-status.model.d.ts → src/models/app-status.model.ts} +3 -2
  108. package/{models/billing-logged-in-users.model.d.ts → src/models/billing-logged-in-users.model.ts} +5 -4
  109. package/src/models/collection-document.model.ts +24 -0
  110. package/src/models/communication-metric.model.ts +23 -0
  111. package/{models/counter.model.d.ts → src/models/counter.model.ts} +4 -3
  112. package/src/models/cron-job-history.model.ts +16 -0
  113. package/src/models/cron-job.model.ts +15 -0
  114. package/src/models/customer-notification.model.ts +28 -0
  115. package/src/models/customer-portal-password.model.ts +12 -0
  116. package/src/models/dialog.model.ts +25 -0
  117. package/{models/email-history.model.js → src/models/email-history.model.ts} +35 -4
  118. package/{models/email-verified.model.d.ts → src/models/email-verified.model.ts} +6 -5
  119. package/{models/file.model.d.ts → src/models/file.model.ts} +8 -7
  120. package/{models/flag-update.model.d.ts → src/models/flag-update.model.ts} +4 -3
  121. package/{models/flag.model.d.ts → src/models/flag.model.ts} +4 -3
  122. package/src/models/log-method-latency.model.ts +11 -0
  123. package/{models/log-subscription.model.d.ts → src/models/log-subscription.model.ts} +11 -9
  124. package/src/models/log.model.ts +19 -0
  125. package/{models/logged-in-users.model.d.ts → src/models/logged-in-users.model.ts} +6 -5
  126. package/{models/method-response.model.d.ts → src/models/method-response.model.ts} +7 -6
  127. package/src/models/method.model.ts +25 -0
  128. package/{models/monitor-cpu.model.d.ts → src/models/monitor-cpu.model.ts} +9 -7
  129. package/src/models/monitor-function.model.ts +16 -0
  130. package/src/models/monitor-memory.model.ts +17 -0
  131. package/src/models/monitor-mongo.model.ts +15 -0
  132. package/{models/notification.model.d.ts → src/models/notification.model.ts} +6 -4
  133. package/src/models/openai-usage-ledger.model.ts +16 -0
  134. package/src/models/pagination.model.ts +35 -0
  135. package/src/models/permission.model.ts +14 -0
  136. package/src/models/report-builder-dashboard-builder.model.ts +29 -0
  137. package/src/models/report-builder-library.model.ts +20 -0
  138. package/src/models/report-builder-report.model.ts +136 -0
  139. package/src/models/report-builder.model.ts +68 -0
  140. package/src/models/select-data-label.model.ts +9 -0
  141. package/src/models/server-message.model.ts +31 -0
  142. package/src/models/slow-query-report.model.ts +23 -0
  143. package/src/models/subscription.model.ts +73 -0
  144. package/src/models/support-ticket.model.ts +104 -0
  145. package/src/models/user-group.model.ts +24 -0
  146. package/{models/user-guide.model.d.ts → src/models/user-guide.model.ts} +5 -4
  147. package/src/models/user.model.ts +96 -0
  148. package/src/private/images/ResolveIO.png +0 -0
  149. package/src/publications/ai-terminal.ts +73 -0
  150. package/src/publications/app-settings.ts +25 -0
  151. package/src/publications/app-status.ts +13 -0
  152. package/src/publications/cron-jobs.ts +40 -0
  153. package/src/publications/customer-notifications.ts +101 -0
  154. package/src/publications/files.ts +33 -0
  155. package/src/publications/flags-update.ts +19 -0
  156. package/src/publications/flags.ts +19 -0
  157. package/src/publications/logs.ts +163 -0
  158. package/src/publications/notifications.ts +13 -0
  159. package/src/publications/report-builder-dashboard-builders.ts +39 -0
  160. package/src/publications/report-builder-libraries.ts +41 -0
  161. package/src/publications/report-builder-reports.ts +47 -0
  162. package/src/publications/super-admin.ts +13 -0
  163. package/src/publications/user-groups.ts +12 -0
  164. package/src/publications/user-guides.ts +12 -0
  165. package/src/resolveio-server-app.ts +617 -0
  166. package/src/server-app.ts +3342 -0
  167. package/src/services/codex-client.ts +1124 -0
  168. package/src/services/openai-client.ts +265 -0
  169. package/src/types/error-report.ts +26 -0
  170. package/src/types/js-tiktoken.d.ts +11 -0
  171. package/src/types/slow-query-report.ts +28 -0
  172. package/src/util/common.ts +649 -0
  173. package/src/util/customer-portal-password.ts +183 -0
  174. package/src/util/error-reporter.ts +332 -0
  175. package/src/util/error-tracking.ts +79 -0
  176. package/src/util/report-builder-unwinds.ts +180 -0
  177. package/src/util/schema-report-builder.ts +448 -0
  178. package/src/util/slow-query-reporter.ts +216 -0
  179. package/src/util/subscription-dependency-context.ts +1096 -0
  180. package/src/util/tokenizer.ts +38 -0
  181. package/src/workers/codex-runner.worker.ts +142 -0
  182. package/start_server.sh +5 -0
  183. package/tests/ai-assistant-corpus-build.ts +484 -0
  184. package/tests/ai-assistant-corpus-replay-e2e.ts +774 -0
  185. package/tests/ai-assistant-data-parity-e2e.ts +1989 -0
  186. package/tests/ai-assistant-eval-triage.ts +831 -0
  187. package/tests/ai-assistant-openai-e2e.ts +1061 -0
  188. package/tests/ai-assistant-openai-git-e2e.ts +155 -0
  189. package/tests/ai-assistant-preflight-matrix.ts +215 -0
  190. package/tests/ai-assistant-routing-eval.test.ts +560 -0
  191. package/tests/ai-assistant-snf-live-eval.ts +975 -0
  192. package/tests/ai-assistant-utils.test.ts +2860 -0
  193. package/tests/error-reporter.test.ts +145 -0
  194. package/tests/report-builder-linking.test.ts +79 -0
  195. package/tests/resolveio-platform-intelligence.test.ts +352 -0
  196. package/tests/server-app-cron-owner.test.ts +127 -0
  197. package/tests/subscription-connect-race.test.ts +158 -0
  198. package/tests/subscription-dependency-context.test.ts +324 -0
  199. package/tests/subscription-manager-collection-tracking.test.ts +86 -0
  200. package/tests/subscription-manager-invalidation.test.ts +86 -0
  201. package/tsconfig.json +34 -0
  202. package/ai/assistant-core-heuristics.d.ts +0 -11
  203. package/ai/assistant-core-heuristics.js +0 -356
  204. package/ai/assistant-core-heuristics.js.map +0 -1
  205. package/ai/resolveio-platform-intelligence-memory-corpus.d.ts +0 -3
  206. package/ai/resolveio-platform-intelligence-memory-corpus.js +0 -214
  207. package/ai/resolveio-platform-intelligence-memory-corpus.js.map +0 -1
  208. package/ai/resolveio-platform-intelligence-memory.d.ts +0 -20
  209. package/ai/resolveio-platform-intelligence-memory.js +0 -341
  210. package/ai/resolveio-platform-intelligence-memory.js.map +0 -1
  211. package/ai/resolveio-platform-intelligence-types.js +0 -4
  212. package/ai/resolveio-platform-intelligence-types.js.map +0 -1
  213. package/ai/resolveio-platform-intelligence.d.ts +0 -6
  214. package/ai/resolveio-platform-intelligence.js +0 -463
  215. package/ai/resolveio-platform-intelligence.js.map +0 -1
  216. package/client-server-app.d.ts +0 -1
  217. package/client-server-app.js +0 -68
  218. package/client-server-app.js.map +0 -1
  219. package/collections/ai-terminal-conversation.collection.d.ts +0 -2
  220. package/collections/ai-terminal-conversation.collection.js +0 -140
  221. package/collections/ai-terminal-conversation.collection.js.map +0 -1
  222. package/collections/ai-terminal-issue-report.collection.d.ts +0 -2
  223. package/collections/ai-terminal-issue-report.collection.js +0 -148
  224. package/collections/ai-terminal-issue-report.collection.js.map +0 -1
  225. package/collections/ai-terminal-message.collection.d.ts +0 -2
  226. package/collections/ai-terminal-message.collection.js +0 -121
  227. package/collections/ai-terminal-message.collection.js.map +0 -1
  228. package/collections/app-setting.collection.d.ts +0 -3
  229. package/collections/app-setting.collection.js +0 -103
  230. package/collections/app-setting.collection.js.map +0 -1
  231. package/collections/app-status.collection.d.ts +0 -3
  232. package/collections/app-status.collection.js +0 -57
  233. package/collections/app-status.collection.js.map +0 -1
  234. package/collections/communication-metric.collection.d.ts +0 -2
  235. package/collections/communication-metric.collection.js +0 -133
  236. package/collections/communication-metric.collection.js.map +0 -1
  237. package/collections/counter.collection.d.ts +0 -3
  238. package/collections/counter.collection.js +0 -56
  239. package/collections/counter.collection.js.map +0 -1
  240. package/collections/cron-job-history.collection.d.ts +0 -3
  241. package/collections/cron-job-history.collection.js +0 -137
  242. package/collections/cron-job-history.collection.js.map +0 -1
  243. package/collections/cron-job.collection.d.ts +0 -3
  244. package/collections/cron-job.collection.js +0 -92
  245. package/collections/cron-job.collection.js.map +0 -1
  246. package/collections/customer-notification.collection.d.ts +0 -3
  247. package/collections/customer-notification.collection.js +0 -130
  248. package/collections/customer-notification.collection.js.map +0 -1
  249. package/collections/customer-portal-password.collection.d.ts +0 -3
  250. package/collections/customer-portal-password.collection.js +0 -75
  251. package/collections/customer-portal-password.collection.js.map +0 -1
  252. package/collections/email-history.collection.d.ts +0 -3
  253. package/collections/email-history.collection.js +0 -127
  254. package/collections/email-history.collection.js.map +0 -1
  255. package/collections/email-verified.collection.d.ts +0 -3
  256. package/collections/email-verified.collection.js +0 -62
  257. package/collections/email-verified.collection.js.map +0 -1
  258. package/collections/file.collection.d.ts +0 -3
  259. package/collections/file.collection.js +0 -74
  260. package/collections/file.collection.js.map +0 -1
  261. package/collections/flag-update.collection.d.ts +0 -3
  262. package/collections/flag-update.collection.js +0 -57
  263. package/collections/flag-update.collection.js.map +0 -1
  264. package/collections/flag.collection.d.ts +0 -3
  265. package/collections/flag.collection.js +0 -57
  266. package/collections/flag.collection.js.map +0 -1
  267. package/collections/log-method-latency.collection.d.ts +0 -3
  268. package/collections/log-method-latency.collection.js +0 -77
  269. package/collections/log-method-latency.collection.js.map +0 -1
  270. package/collections/log-subscription.collection.d.ts +0 -3
  271. package/collections/log-subscription.collection.js +0 -80
  272. package/collections/log-subscription.collection.js.map +0 -1
  273. package/collections/log.collection.d.ts +0 -3
  274. package/collections/log.collection.js +0 -93
  275. package/collections/log.collection.js.map +0 -1
  276. package/collections/logged-in-users.collection.d.ts +0 -3
  277. package/collections/logged-in-users.collection.js +0 -67
  278. package/collections/logged-in-users.collection.js.map +0 -1
  279. package/collections/monitor-cpu.collection.d.ts +0 -3
  280. package/collections/monitor-cpu.collection.js +0 -65
  281. package/collections/monitor-cpu.collection.js.map +0 -1
  282. package/collections/monitor-function.collection.d.ts +0 -3
  283. package/collections/monitor-function.collection.js +0 -74
  284. package/collections/monitor-function.collection.js.map +0 -1
  285. package/collections/monitor-memory.collection.d.ts +0 -3
  286. package/collections/monitor-memory.collection.js +0 -77
  287. package/collections/monitor-memory.collection.js.map +0 -1
  288. package/collections/monitor-mongo.collection.d.ts +0 -3
  289. package/collections/monitor-mongo.collection.js +0 -71
  290. package/collections/monitor-mongo.collection.js.map +0 -1
  291. package/collections/notification.collection.d.ts +0 -3
  292. package/collections/notification.collection.js +0 -57
  293. package/collections/notification.collection.js.map +0 -1
  294. package/collections/openai-usage-ledger.collection.d.ts +0 -2
  295. package/collections/openai-usage-ledger.collection.js +0 -124
  296. package/collections/openai-usage-ledger.collection.js.map +0 -1
  297. package/collections/report-builder-dashboard-builder.collection.d.ts +0 -3
  298. package/collections/report-builder-dashboard-builder.collection.js +0 -109
  299. package/collections/report-builder-dashboard-builder.collection.js.map +0 -1
  300. package/collections/report-builder-library.collection.d.ts +0 -3
  301. package/collections/report-builder-library.collection.js +0 -87
  302. package/collections/report-builder-library.collection.js.map +0 -1
  303. package/collections/report-builder-report.collection.d.ts +0 -4
  304. package/collections/report-builder-report.collection.js +0 -184
  305. package/collections/report-builder-report.collection.js.map +0 -1
  306. package/collections/user-group.collection.d.ts +0 -4
  307. package/collections/user-group.collection.js +0 -89
  308. package/collections/user-group.collection.js.map +0 -1
  309. package/collections/user-guide.collection.d.ts +0 -3
  310. package/collections/user-guide.collection.js +0 -57
  311. package/collections/user-guide.collection.js.map +0 -1
  312. package/collections/user.collection.d.ts +0 -4
  313. package/collections/user.collection.js +0 -180
  314. package/collections/user.collection.js.map +0 -1
  315. package/cron/cron.d.ts +0 -14
  316. package/cron/cron.js +0 -216
  317. package/cron/cron.js.map +0 -1
  318. package/fixtures/cron-jobs.d.ts +0 -1
  319. package/fixtures/cron-jobs.js +0 -150
  320. package/fixtures/cron-jobs.js.map +0 -1
  321. package/fixtures/init.d.ts +0 -1
  322. package/fixtures/init.js +0 -91
  323. package/fixtures/init.js.map +0 -1
  324. package/http/auth.d.ts +0 -2
  325. package/http/auth.js +0 -906
  326. package/http/auth.js.map +0 -1
  327. package/http/health.d.ts +0 -1
  328. package/http/health.js +0 -11
  329. package/http/health.js.map +0 -1
  330. package/http/home.d.ts +0 -1
  331. package/http/home.js +0 -134
  332. package/http/home.js.map +0 -1
  333. package/http/slow-query-publication.d.ts +0 -2
  334. package/http/slow-query-publication.js +0 -99
  335. package/http/slow-query-publication.js.map +0 -1
  336. package/index.d.ts +0 -1
  337. package/index.js +0 -19
  338. package/index.js.map +0 -1
  339. package/managers/ai-assistant-codex-manager.manager.d.ts +0 -67
  340. package/managers/ai-assistant-codex-manager.manager.js +0 -1113
  341. package/managers/ai-assistant-codex-manager.manager.js.map +0 -1
  342. package/managers/communication-metric.manager.d.ts +0 -16
  343. package/managers/communication-metric.manager.js +0 -134
  344. package/managers/communication-metric.manager.js.map +0 -1
  345. package/managers/cron.manager.d.ts +0 -20
  346. package/managers/cron.manager.js +0 -534
  347. package/managers/cron.manager.js.map +0 -1
  348. package/managers/customer-notification-content.manager.d.ts +0 -55
  349. package/managers/customer-notification-content.manager.js +0 -158
  350. package/managers/customer-notification-content.manager.js.map +0 -1
  351. package/managers/diagnostic-manager-bootstrap.d.ts +0 -9
  352. package/managers/diagnostic-manager-bootstrap.js +0 -260
  353. package/managers/diagnostic-manager-bootstrap.js.map +0 -1
  354. package/managers/error-auto-fix.manager.d.ts +0 -149
  355. package/managers/error-auto-fix.manager.js +0 -3064
  356. package/managers/error-auto-fix.manager.js.map +0 -1
  357. package/managers/local-log.manager.d.ts +0 -18
  358. package/managers/local-log.manager.js +0 -88
  359. package/managers/local-log.manager.js.map +0 -1
  360. package/managers/method.manager.d.ts +0 -83
  361. package/managers/method.manager.js +0 -1940
  362. package/managers/method.manager.js.map +0 -1
  363. package/managers/mongo.manager.d.ts +0 -224
  364. package/managers/mongo.manager.js +0 -5000
  365. package/managers/mongo.manager.js.map +0 -1
  366. package/managers/monitor.manager.d.ts +0 -70
  367. package/managers/monitor.manager.js +0 -550
  368. package/managers/monitor.manager.js.map +0 -1
  369. package/managers/openai-usage-ledger.manager.d.ts +0 -15
  370. package/managers/openai-usage-ledger.manager.js +0 -144
  371. package/managers/openai-usage-ledger.manager.js.map +0 -1
  372. package/managers/slow-query-verifier.manager.d.ts +0 -144
  373. package/managers/slow-query-verifier.manager.js +0 -3857
  374. package/managers/slow-query-verifier.manager.js.map +0 -1
  375. package/managers/slow-query.manager.d.ts +0 -28
  376. package/managers/slow-query.manager.js +0 -468
  377. package/managers/slow-query.manager.js.map +0 -1
  378. package/managers/subscription.manager.d.ts +0 -169
  379. package/managers/subscription.manager.js +0 -3434
  380. package/managers/subscription.manager.js.map +0 -1
  381. package/managers/websocket.manager.d.ts +0 -73
  382. package/managers/websocket.manager.js +0 -673
  383. package/managers/websocket.manager.js.map +0 -1
  384. package/managers/worker-dispatcher.manager.d.ts +0 -120
  385. package/managers/worker-dispatcher.manager.js +0 -1266
  386. package/managers/worker-dispatcher.manager.js.map +0 -1
  387. package/managers/worker-server.manager.d.ts +0 -35
  388. package/managers/worker-server.manager.js +0 -582
  389. package/managers/worker-server.manager.js.map +0 -1
  390. package/methods/accounts.d.ts +0 -2
  391. package/methods/accounts.js +0 -624
  392. package/methods/accounts.js.map +0 -1
  393. package/methods/ai-terminal.d.ts +0 -322
  394. package/methods/ai-terminal.js +0 -22699
  395. package/methods/ai-terminal.js.map +0 -1
  396. package/methods/app-settings.d.ts +0 -2
  397. package/methods/app-settings.js +0 -169
  398. package/methods/app-settings.js.map +0 -1
  399. package/methods/aws.d.ts +0 -2
  400. package/methods/aws.js +0 -877
  401. package/methods/aws.js.map +0 -1
  402. package/methods/collections.d.ts +0 -2
  403. package/methods/collections.js +0 -719
  404. package/methods/collections.js.map +0 -1
  405. package/methods/counters.d.ts +0 -2
  406. package/methods/counters.js +0 -113
  407. package/methods/counters.js.map +0 -1
  408. package/methods/cron-jobs.d.ts +0 -2
  409. package/methods/cron-jobs.js +0 -2475
  410. package/methods/cron-jobs.js.map +0 -1
  411. package/methods/customer-notifications.d.ts +0 -2
  412. package/methods/customer-notifications.js +0 -528
  413. package/methods/customer-notifications.js.map +0 -1
  414. package/methods/diagnostics.d.ts +0 -2
  415. package/methods/diagnostics.js +0 -703
  416. package/methods/diagnostics.js.map +0 -1
  417. package/methods/flag-updates.d.ts +0 -2
  418. package/methods/flag-updates.js +0 -8
  419. package/methods/flag-updates.js.map +0 -1
  420. package/methods/flags.d.ts +0 -2
  421. package/methods/flags.js +0 -8
  422. package/methods/flags.js.map +0 -1
  423. package/methods/logs.d.ts +0 -2
  424. package/methods/logs.js +0 -751
  425. package/methods/logs.js.map +0 -1
  426. package/methods/mongo-explorer.d.ts +0 -2
  427. package/methods/mongo-explorer.js +0 -1808
  428. package/methods/mongo-explorer.js.map +0 -1
  429. package/methods/monitor.d.ts +0 -2
  430. package/methods/monitor.js +0 -543
  431. package/methods/monitor.js.map +0 -1
  432. package/methods/pdf.d.ts +0 -2
  433. package/methods/pdf.js +0 -1216
  434. package/methods/pdf.js.map +0 -1
  435. package/methods/publications.d.ts +0 -1
  436. package/methods/publications.js +0 -183
  437. package/methods/publications.js.map +0 -1
  438. package/methods/report-builder.d.ts +0 -2
  439. package/methods/report-builder.js +0 -3094
  440. package/methods/report-builder.js.map +0 -1
  441. package/methods/support.d.ts +0 -2
  442. package/methods/support.js +0 -430
  443. package/methods/support.js.map +0 -1
  444. package/models/ai-terminal-conversation.model.d.ts +0 -17
  445. package/models/ai-terminal-conversation.model.js +0 -4
  446. package/models/ai-terminal-conversation.model.js.map +0 -1
  447. package/models/ai-terminal-issue-report.model.d.ts +0 -19
  448. package/models/ai-terminal-issue-report.model.js +0 -4
  449. package/models/ai-terminal-issue-report.model.js.map +0 -1
  450. package/models/ai-terminal-message.model.d.ts +0 -22
  451. package/models/ai-terminal-message.model.js +0 -4
  452. package/models/ai-terminal-message.model.js.map +0 -1
  453. package/models/app-setting.model.d.ts +0 -16
  454. package/models/app-setting.model.js +0 -4
  455. package/models/app-setting.model.js.map +0 -1
  456. package/models/app-status.model.js +0 -4
  457. package/models/app-status.model.js.map +0 -1
  458. package/models/billing-logged-in-users.model.js +0 -4
  459. package/models/billing-logged-in-users.model.js.map +0 -1
  460. package/models/collection-document.model.d.ts +0 -21
  461. package/models/collection-document.model.js +0 -4
  462. package/models/collection-document.model.js.map +0 -1
  463. package/models/communication-metric.model.d.ts +0 -20
  464. package/models/communication-metric.model.js +0 -4
  465. package/models/communication-metric.model.js.map +0 -1
  466. package/models/counter.model.js +0 -4
  467. package/models/counter.model.js.map +0 -1
  468. package/models/cron-job-history.model.d.ts +0 -15
  469. package/models/cron-job-history.model.js +0 -4
  470. package/models/cron-job-history.model.js.map +0 -1
  471. package/models/cron-job.model.d.ts +0 -14
  472. package/models/cron-job.model.js +0 -4
  473. package/models/cron-job.model.js.map +0 -1
  474. package/models/customer-notification.model.d.ts +0 -26
  475. package/models/customer-notification.model.js +0 -4
  476. package/models/customer-notification.model.js.map +0 -1
  477. package/models/customer-portal-password.model.d.ts +0 -11
  478. package/models/customer-portal-password.model.js +0 -4
  479. package/models/customer-portal-password.model.js.map +0 -1
  480. package/models/dialog.model.d.ts +0 -23
  481. package/models/dialog.model.js +0 -4
  482. package/models/dialog.model.js.map +0 -1
  483. package/models/email-history.model.d.ts +0 -31
  484. package/models/email-history.model.js.map +0 -1
  485. package/models/email-verified.model.js +0 -4
  486. package/models/email-verified.model.js.map +0 -1
  487. package/models/file.model.js +0 -4
  488. package/models/file.model.js.map +0 -1
  489. package/models/flag-update.model.js +0 -4
  490. package/models/flag-update.model.js.map +0 -1
  491. package/models/flag.model.js +0 -4
  492. package/models/flag.model.js.map +0 -1
  493. package/models/log-method-latency.model.d.ts +0 -10
  494. package/models/log-method-latency.model.js +0 -4
  495. package/models/log-method-latency.model.js.map +0 -1
  496. package/models/log-subscription.model.js +0 -4
  497. package/models/log-subscription.model.js.map +0 -1
  498. package/models/log.model.d.ts +0 -17
  499. package/models/log.model.js +0 -4
  500. package/models/log.model.js.map +0 -1
  501. package/models/logged-in-users.model.js +0 -4
  502. package/models/logged-in-users.model.js.map +0 -1
  503. package/models/method-response.model.js +0 -4
  504. package/models/method-response.model.js.map +0 -1
  505. package/models/method.model.d.ts +0 -26
  506. package/models/method.model.js +0 -4
  507. package/models/method.model.js.map +0 -1
  508. package/models/monitor-cpu.model.js +0 -4
  509. package/models/monitor-cpu.model.js.map +0 -1
  510. package/models/monitor-function.model.d.ts +0 -14
  511. package/models/monitor-function.model.js +0 -4
  512. package/models/monitor-function.model.js.map +0 -1
  513. package/models/monitor-memory.model.d.ts +0 -15
  514. package/models/monitor-memory.model.js +0 -4
  515. package/models/monitor-memory.model.js.map +0 -1
  516. package/models/monitor-mongo.model.d.ts +0 -13
  517. package/models/monitor-mongo.model.js +0 -4
  518. package/models/monitor-mongo.model.js.map +0 -1
  519. package/models/notification.model.js +0 -4
  520. package/models/notification.model.js.map +0 -1
  521. package/models/openai-usage-ledger.model.d.ts +0 -15
  522. package/models/openai-usage-ledger.model.js +0 -4
  523. package/models/openai-usage-ledger.model.js.map +0 -1
  524. package/models/pagination.model.d.ts +0 -11
  525. package/models/pagination.model.js +0 -28
  526. package/models/pagination.model.js.map +0 -1
  527. package/models/permission.model.d.ts +0 -12
  528. package/models/permission.model.js +0 -4
  529. package/models/permission.model.js.map +0 -1
  530. package/models/report-builder-dashboard-builder.model.d.ts +0 -25
  531. package/models/report-builder-dashboard-builder.model.js +0 -4
  532. package/models/report-builder-dashboard-builder.model.js.map +0 -1
  533. package/models/report-builder-library.model.d.ts +0 -17
  534. package/models/report-builder-library.model.js +0 -4
  535. package/models/report-builder-library.model.js.map +0 -1
  536. package/models/report-builder-report.model.d.ts +0 -121
  537. package/models/report-builder-report.model.js +0 -4
  538. package/models/report-builder-report.model.js.map +0 -1
  539. package/models/report-builder.model.d.ts +0 -61
  540. package/models/report-builder.model.js +0 -4
  541. package/models/report-builder.model.js.map +0 -1
  542. package/models/select-data-label.model.d.ts +0 -9
  543. package/models/select-data-label.model.js +0 -4
  544. package/models/select-data-label.model.js.map +0 -1
  545. package/models/server-message.model.d.ts +0 -32
  546. package/models/server-message.model.js +0 -4
  547. package/models/server-message.model.js.map +0 -1
  548. package/models/slow-query-report.model.d.ts +0 -23
  549. package/models/slow-query-report.model.js +0 -4
  550. package/models/slow-query-report.model.js.map +0 -1
  551. package/models/subscription.model.d.ts +0 -31
  552. package/models/subscription.model.js +0 -4
  553. package/models/subscription.model.js.map +0 -1
  554. package/models/support-ticket.model.d.ts +0 -87
  555. package/models/support-ticket.model.js +0 -4
  556. package/models/support-ticket.model.js.map +0 -1
  557. package/models/user-group.model.d.ts +0 -20
  558. package/models/user-group.model.js +0 -4
  559. package/models/user-group.model.js.map +0 -1
  560. package/models/user-guide.model.js +0 -4
  561. package/models/user-guide.model.js.map +0 -1
  562. package/models/user.model.d.ts +0 -84
  563. package/models/user.model.js +0 -4
  564. package/models/user.model.js.map +0 -1
  565. package/private/images/ResolveIO.png +0 -0
  566. package/public_api.js +0 -111
  567. package/public_api.js.map +0 -1
  568. package/publications/ai-terminal.d.ts +0 -1
  569. package/publications/ai-terminal.js +0 -122
  570. package/publications/ai-terminal.js.map +0 -1
  571. package/publications/app-settings.d.ts +0 -2
  572. package/publications/app-settings.js +0 -28
  573. package/publications/app-settings.js.map +0 -1
  574. package/publications/app-status.d.ts +0 -2
  575. package/publications/app-status.js +0 -16
  576. package/publications/app-status.js.map +0 -1
  577. package/publications/cron-jobs.d.ts +0 -2
  578. package/publications/cron-jobs.js +0 -88
  579. package/publications/cron-jobs.js.map +0 -1
  580. package/publications/customer-notifications.d.ts +0 -2
  581. package/publications/customer-notifications.js +0 -161
  582. package/publications/customer-notifications.js.map +0 -1
  583. package/publications/files.d.ts +0 -2
  584. package/publications/files.js +0 -36
  585. package/publications/files.js.map +0 -1
  586. package/publications/flags-update.d.ts +0 -2
  587. package/publications/flags-update.js +0 -22
  588. package/publications/flags-update.js.map +0 -1
  589. package/publications/flags.d.ts +0 -2
  590. package/publications/flags.js +0 -22
  591. package/publications/flags.js.map +0 -1
  592. package/publications/logs.d.ts +0 -2
  593. package/publications/logs.js +0 -164
  594. package/publications/logs.js.map +0 -1
  595. package/publications/notifications.d.ts +0 -2
  596. package/publications/notifications.js +0 -16
  597. package/publications/notifications.js.map +0 -1
  598. package/publications/report-builder-dashboard-builders.d.ts +0 -2
  599. package/publications/report-builder-dashboard-builders.js +0 -42
  600. package/publications/report-builder-dashboard-builders.js.map +0 -1
  601. package/publications/report-builder-libraries.d.ts +0 -2
  602. package/publications/report-builder-libraries.js +0 -90
  603. package/publications/report-builder-libraries.js.map +0 -1
  604. package/publications/report-builder-reports.d.ts +0 -2
  605. package/publications/report-builder-reports.js +0 -50
  606. package/publications/report-builder-reports.js.map +0 -1
  607. package/publications/super-admin.d.ts +0 -2
  608. package/publications/super-admin.js +0 -16
  609. package/publications/super-admin.js.map +0 -1
  610. package/publications/user-groups.d.ts +0 -1
  611. package/publications/user-groups.js +0 -16
  612. package/publications/user-groups.js.map +0 -1
  613. package/publications/user-guides.d.ts +0 -1
  614. package/publications/user-guides.js +0 -16
  615. package/publications/user-guides.js.map +0 -1
  616. package/resolveio-server-app.d.ts +0 -70
  617. package/resolveio-server-app.js +0 -801
  618. package/resolveio-server-app.js.map +0 -1
  619. package/server-app.d.ts +0 -228
  620. package/server-app.js +0 -3549
  621. package/server-app.js.map +0 -1
  622. package/services/codex-client.d.ts +0 -118
  623. package/services/codex-client.js +0 -1475
  624. package/services/codex-client.js.map +0 -1
  625. package/services/openai-client.d.ts +0 -46
  626. package/services/openai-client.js +0 -318
  627. package/services/openai-client.js.map +0 -1
  628. package/types/error-report.d.ts +0 -25
  629. package/types/error-report.js +0 -4
  630. package/types/error-report.js.map +0 -1
  631. package/types/slow-query-report.d.ts +0 -27
  632. package/types/slow-query-report.js +0 -6
  633. package/types/slow-query-report.js.map +0 -1
  634. package/util/common.d.ts +0 -31
  635. package/util/common.js +0 -683
  636. package/util/common.js.map +0 -1
  637. package/util/customer-portal-password.d.ts +0 -13
  638. package/util/customer-portal-password.js +0 -209
  639. package/util/customer-portal-password.js.map +0 -1
  640. package/util/error-reporter.d.ts +0 -52
  641. package/util/error-reporter.js +0 -326
  642. package/util/error-reporter.js.map +0 -1
  643. package/util/error-tracking.d.ts +0 -13
  644. package/util/error-tracking.js +0 -120
  645. package/util/error-tracking.js.map +0 -1
  646. package/util/report-builder-unwinds.d.ts +0 -15
  647. package/util/report-builder-unwinds.js +0 -156
  648. package/util/report-builder-unwinds.js.map +0 -1
  649. package/util/schema-report-builder.d.ts +0 -6
  650. package/util/schema-report-builder.js +0 -481
  651. package/util/schema-report-builder.js.map +0 -1
  652. package/util/slow-query-reporter.d.ts +0 -28
  653. package/util/slow-query-reporter.js +0 -226
  654. package/util/slow-query-reporter.js.map +0 -1
  655. package/util/subscription-dependency-context.d.ts +0 -34
  656. package/util/subscription-dependency-context.js +0 -1283
  657. package/util/subscription-dependency-context.js.map +0 -1
  658. package/util/tokenizer.d.ts +0 -5
  659. package/util/tokenizer.js +0 -41
  660. package/util/tokenizer.js.map +0 -1
  661. package/workers/codex-runner.worker.d.ts +0 -1
  662. package/workers/codex-runner.worker.js +0 -192
  663. package/workers/codex-runner.worker.js.map +0 -1
  664. /package/{private → src/private}/email-templates/enrollment.html +0 -0
  665. /package/{private → src/private}/email-templates/forgot-password.html +0 -0
  666. /package/{private → src/private}/email-templates/support-ticket-deleted.html +0 -0
  667. /package/{private → src/private}/email-templates/support-ticket-modified.html +0 -0
  668. /package/{private → src/private}/email-templates/support-ticket.html +0 -0
  669. /package/{public_api.d.ts → src/public_api.ts} +0 -0
@@ -0,0 +1,1124 @@
1
+ import { promises as fs } from 'fs';
2
+ import * as os from 'os';
3
+ import * as path from 'path';
4
+ import { setTimeout as sleepTimeout } from 'timers/promises';
5
+ export interface CodexConfig {
6
+ apiKey?: string;
7
+ baseUrl?: string;
8
+ model?: string;
9
+ fallbackModel?: string;
10
+ fallbackModels?: string[];
11
+ maxRetries?: number;
12
+ retryDelayMs?: number;
13
+ }
14
+
15
+ /* eslint-disable no-unused-vars -- Function type params are required for clarity. */
16
+ type StreamEventHandler = (event: any) => void | Promise<void>;
17
+ type StreamTextHandler = (delta: string, fullText: string) => void | Promise<void>;
18
+ type AgentMessageHandler = (text: string) => void | Promise<void>;
19
+ type UsageHandler = (usage: CodexUsageSummary | null) => void | Promise<void>;
20
+ type DynamicImport = (specifier: string) => Promise<any>;
21
+ /* eslint-enable no-unused-vars */
22
+
23
+ type CodexModelFallbackPreference = {
24
+ fallbackModel: string;
25
+ expiresAt: number;
26
+ updatedAt: number;
27
+ };
28
+
29
+ export interface CodexRunOptions {
30
+ timeoutMs?: number;
31
+ threadOptions?: CodexThreadOptions;
32
+ threadKey?: string;
33
+ reuseThread?: boolean;
34
+ fallbackModels?: string[];
35
+ onStreamEvent?: StreamEventHandler;
36
+ onStreamText?: StreamTextHandler;
37
+ onUsage?: UsageHandler;
38
+ }
39
+
40
+ export interface CodexUsageSummary {
41
+ inputTokens: number;
42
+ cachedInputTokens: number;
43
+ outputTokens: number;
44
+ }
45
+
46
+ export type CodexThreadOptions = {
47
+ model?: string;
48
+ sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
49
+ workingDirectory?: string;
50
+ skipGitRepoCheck?: boolean;
51
+ modelReasoningEffort?: 'minimal' | 'none' | 'low' | 'medium' | 'high' | 'xhigh';
52
+ networkAccessEnabled?: boolean;
53
+ webSearchMode?: 'disabled' | 'cached' | 'live';
54
+ webSearchEnabled?: boolean;
55
+ approvalPolicy?: 'never' | 'on-request' | 'on-failure' | 'untrusted';
56
+ additionalDirectories?: string[];
57
+ };
58
+
59
+ export class CodexClient {
60
+ private static readonly PING_PROMPT = "Say 'pong'";
61
+ private static readonly MODEL_UNAVAILABLE_FALLBACK_FILE = path.join(os.tmpdir(), 'resolveio-codex-model-fallbacks.json');
62
+ private static readonly DEFAULT_MODEL_UNAVAILABLE_TTL_MS = 6 * 60 * 60 * 1000;
63
+ private static readonly MIN_MODEL_UNAVAILABLE_TTL_MS = 60 * 1000;
64
+ private static readonly modelFallbackPreferences = new Map<string, CodexModelFallbackPreference>();
65
+ private static modelFallbackPreferencesLoaded = false;
66
+ private static modelFallbackPreferencesLoadPromise: Promise<void> | null = null;
67
+ private codex: any | null = null;
68
+ private codexInit: Promise<void> | null = null;
69
+ private readonly threadCache = new Map<string, { thread: any; optionsKey: string; modelKey: string }>();
70
+ private readonly debugEnabled = (process.env.AI_DASHBOARD_DEBUG || '').trim().toLowerCase() === 'true';
71
+ private readonly streamEnabled = this.resolveStreamEnabled();
72
+ private readonly cleanZdotdirEnabled = this.resolveCleanZdotdirEnabled();
73
+ private zDotDir: string | null = null;
74
+ private readonly defaultTimeoutMs = this.resolveDefaultTimeoutMs();
75
+ private readonly pingEnabled = this.resolvePingEnabled();
76
+ private readonly pingTimeoutMs = this.resolvePingTimeoutMs();
77
+ private readonly modelUnavailableTtlMs = this.resolveModelUnavailableTtlMs();
78
+ private readonly config: CodexConfig;
79
+ private readonly defaultThreadOptions: CodexThreadOptions;
80
+
81
+ constructor(config: CodexConfig) {
82
+ this.config = config;
83
+ if (!this.config.apiKey) {
84
+ throw new Error('AI API key is required for AI client');
85
+ }
86
+ this.defaultThreadOptions = this.resolveDefaultThreadOptions();
87
+ }
88
+
89
+ async run(prompt: string, options?: CodexRunOptions): Promise<string> {
90
+ await this.ensureModelFallbackPreferencesLoaded();
91
+ const maxRetries = this.normalizeRetryCount(this.config.maxRetries);
92
+ const retryDelayMs = this.normalizeRetryDelay(this.config.retryDelayMs);
93
+ let lastError: unknown = null;
94
+ const modelSequence = this.resolveModelSequence(options);
95
+ for (let modelIndex = 0; modelIndex < modelSequence.length; modelIndex += 1) {
96
+ const model = modelSequence[modelIndex];
97
+ const nextModel = modelSequence[modelIndex + 1];
98
+ const modelOptions = this.applyModelOverride(options, model);
99
+ let attempt = 0;
100
+ while (attempt <= maxRetries) {
101
+ try {
102
+ this.log(`run model=${model || this.config.model || 'default'} attempt ${attempt + 1}/${maxRetries + 1}`);
103
+ if (this.pingEnabled && !this.isPingPrompt(prompt)) {
104
+ await this.runPing(modelOptions?.threadOptions);
105
+ }
106
+ if (this.streamEnabled && !this.isPingPrompt(prompt)) {
107
+ const result = await this.runStreamedOnce(prompt, modelOptions);
108
+ await this.clearModelFallbackPreference(model);
109
+ return result;
110
+ }
111
+ const result = await this.runOnce(prompt, modelOptions);
112
+ await this.clearModelFallbackPreference(model);
113
+ return result;
114
+ }
115
+ catch (error) {
116
+ lastError = error;
117
+ const message = error instanceof Error ? error.message : String(error || 'Unknown error');
118
+ this.log(`run model=${model || this.config.model || 'default'} attempt ${attempt + 1} failed: ${message}`);
119
+ if (nextModel && this.isModelAvailabilityError(error)) {
120
+ await this.rememberModelFallbackPreference(model, nextModel);
121
+ this.log(`model unavailable; retrying with fallback model ${nextModel}`);
122
+ break;
123
+ }
124
+ if (this.isCodexEnvironmentError(error)) {
125
+ this.recoverCodexEnvironment(error);
126
+ }
127
+ if (attempt >= maxRetries || !this.isRetryableError(error)) {
128
+ throw lastError;
129
+ }
130
+ const delay = retryDelayMs * Math.pow(2, attempt);
131
+ await this.sleep(delay);
132
+ attempt += 1;
133
+ }
134
+ }
135
+ }
136
+ throw lastError;
137
+ }
138
+
139
+ private async runStreamedOnce(prompt: string, options?: CodexRunOptions): Promise<string> {
140
+ const startedAt = Date.now();
141
+ this.log(`runStreamed start (promptLength=${prompt.length})`);
142
+ const thread = await this.startThread(options?.threadOptions, options?.threadKey, options?.reuseThread);
143
+ const timeoutMs = options?.timeoutMs ?? this.defaultTimeoutMs;
144
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
145
+ const timeoutId = controller
146
+ ? setTimeout(() => controller.abort(), timeoutMs)
147
+ : null;
148
+ let finalResponse = '';
149
+ let lastText = '';
150
+ let usageSummary: CodexUsageSummary | null = null;
151
+ try {
152
+ const { events } = await thread.runStreamed(prompt, controller ? { signal: controller.signal } : undefined);
153
+ for await (const event of events) {
154
+ if (event?.type === 'turn.completed') {
155
+ usageSummary = this.normalizeUsageSummary(event?.usage);
156
+ }
157
+ if (options?.onStreamEvent) {
158
+ try {
159
+ await options.onStreamEvent(event);
160
+ }
161
+ catch (error) {
162
+ const message = error instanceof Error ? error.message : String(error || 'Unknown error');
163
+ this.log(`onStreamEvent failed: ${message}`);
164
+ }
165
+ }
166
+ await this.handleStreamEvent(event, async (text: string) => {
167
+ const next = text || '';
168
+ if (!next) {
169
+ return;
170
+ }
171
+ const delta = next.startsWith(lastText) ? next.slice(lastText.length) : next;
172
+ if (delta) {
173
+ this.logStreamText(delta);
174
+ if (options?.onStreamText) {
175
+ try {
176
+ await options.onStreamText(delta, next);
177
+ }
178
+ catch (error) {
179
+ const message = error instanceof Error ? error.message : String(error || 'Unknown error');
180
+ this.log(`onStreamText failed: ${message}`);
181
+ }
182
+ }
183
+ }
184
+ lastText = next;
185
+ finalResponse = next;
186
+ });
187
+ if (event?.type === 'turn.failed') {
188
+ throw new Error(event.error?.message || 'AI run failed.');
189
+ }
190
+ if (event?.type === 'error') {
191
+ throw new Error(event.message || 'AI stream error.');
192
+ }
193
+ }
194
+ }
195
+ catch (error) {
196
+ if (controller?.signal?.aborted) {
197
+ this.log(`runStreamed timed out (durationMs=${Date.now() - startedAt})`);
198
+ throw new Error('AI request timed out.');
199
+ }
200
+ const message = error instanceof Error ? error.message : String(error || 'Unknown error');
201
+ this.log(`runStreamed failed (durationMs=${Date.now() - startedAt}): ${message}`);
202
+ throw error;
203
+ }
204
+ finally {
205
+ if (timeoutId) {
206
+ clearTimeout(timeoutId);
207
+ }
208
+ }
209
+ if (!finalResponse) {
210
+ throw new Error('AI returned no completion content.');
211
+ }
212
+ await this.emitUsageSummary(options, usageSummary);
213
+ this.log(`runStreamed complete (contentLength=${finalResponse.length}, durationMs=${Date.now() - startedAt})`);
214
+ return finalResponse.trim();
215
+ }
216
+
217
+ private async runOnce(prompt: string, options?: CodexRunOptions): Promise<string> {
218
+ const startedAt = Date.now();
219
+ this.log(`runOnce start (promptLength=${prompt.length})`);
220
+ try {
221
+ const thread = await this.startThread(options?.threadOptions, options?.threadKey, options?.reuseThread);
222
+ const runPromise = thread.run(prompt);
223
+ const timeoutMs = options?.timeoutMs ?? this.defaultTimeoutMs;
224
+ this.log(`runOnce awaiting result (timeoutMs=${timeoutMs})`);
225
+ const result: any = await this.withTimeout(runPromise, timeoutMs);
226
+ const content = this.extractContent(result);
227
+ if (!content) {
228
+ throw new Error('AI returned no completion content.');
229
+ }
230
+ await this.emitUsageSummary(options, this.normalizeUsageSummary(result?.usage));
231
+ this.log(`runOnce complete (contentLength=${content.length}, durationMs=${Date.now() - startedAt})`);
232
+ return content;
233
+ }
234
+ catch (error) {
235
+ const message = error instanceof Error ? error.message : String(error || 'Unknown error');
236
+ this.log(`runOnce failed (durationMs=${Date.now() - startedAt}): ${message}`);
237
+ throw error;
238
+ }
239
+ }
240
+
241
+ private async startThread(threadOptions?: CodexThreadOptions, threadKey?: string, reuseThread = true): Promise<any> {
242
+ await this.ensureCodex();
243
+ const mergedOptions = this.mergeThreadOptions(threadOptions);
244
+ const optionsKey = this.buildThreadOptionsKey(mergedOptions);
245
+ const effectiveModel = mergedOptions?.model || this.config.model || 'default';
246
+ const modelKey = this.normalizeOptionalString(effectiveModel).toLowerCase() || 'default';
247
+ const cacheKey = this.buildThreadCacheKey(threadKey, mergedOptions);
248
+ const explicitThreadKey = (threadKey || '').trim();
249
+ const hasExplicitThreadKey = explicitThreadKey.length > 0;
250
+ if (reuseThread && cacheKey) {
251
+ const existing = this.threadCache.get(cacheKey);
252
+ if (existing) {
253
+ const sameOptions = existing.optionsKey === optionsKey;
254
+ const sameModel = existing.modelKey === modelKey;
255
+ if (sameOptions || (hasExplicitThreadKey && sameModel)) {
256
+ if (hasExplicitThreadKey && existing.optionsKey !== optionsKey) {
257
+ this.log(`startThread reuse explicit key (${cacheKey}) despite option change`);
258
+ }
259
+ else {
260
+ this.log(`startThread reuse (${cacheKey})`);
261
+ }
262
+ return existing.thread;
263
+ }
264
+ if (hasExplicitThreadKey && !sameModel) {
265
+ this.log(`startThread explicit key (${cacheKey}) model changed (${existing.modelKey} -> ${modelKey}); creating new thread`);
266
+ }
267
+ }
268
+ }
269
+ this.log(`startThread (model=${effectiveModel})`);
270
+ if (mergedOptions?.model) {
271
+ this.log(`startThread options: ${this.formatThreadOptions(mergedOptions)}`);
272
+ const thread = this.codex.startThread(mergedOptions);
273
+ this.log('startThread created with model override');
274
+ if (cacheKey) {
275
+ this.threadCache.set(cacheKey, { thread, optionsKey, modelKey });
276
+ }
277
+ return thread;
278
+ }
279
+ if (mergedOptions && Object.keys(mergedOptions).length) {
280
+ this.log(`startThread options: ${this.formatThreadOptions(mergedOptions)}`);
281
+ }
282
+ const thread = this.codex.startThread(mergedOptions);
283
+ this.log('startThread created');
284
+ if (cacheKey) {
285
+ this.threadCache.set(cacheKey, { thread, optionsKey, modelKey });
286
+ }
287
+ return thread;
288
+ }
289
+
290
+ private extractContent(result: any): string {
291
+ if (!result) {
292
+ return '';
293
+ }
294
+ if (typeof result.finalResponse === 'string') {
295
+ return result.finalResponse.trim();
296
+ }
297
+ if (typeof result === 'string') {
298
+ return result.trim();
299
+ }
300
+ if (Array.isArray(result.items)) {
301
+ const lastMessage = [...result.items].reverse().find((item: any) => item?.type === 'agent_message' && typeof item.text === 'string');
302
+ if (lastMessage?.text) {
303
+ return lastMessage.text.trim();
304
+ }
305
+ }
306
+ if (typeof result.output_text === 'string') {
307
+ return result.output_text.trim();
308
+ }
309
+ if (typeof result.outputText === 'string') {
310
+ return result.outputText.trim();
311
+ }
312
+ if (typeof result.content === 'string') {
313
+ return result.content.trim();
314
+ }
315
+ if (typeof result.text === 'string') {
316
+ return result.text.trim();
317
+ }
318
+ if (Array.isArray(result.content)) {
319
+ const text = result.content
320
+ .map((part: any) => this.extractPartText(part))
321
+ .join('')
322
+ .trim();
323
+ if (text) {
324
+ return text;
325
+ }
326
+ }
327
+ if (Array.isArray(result.output)) {
328
+ const text = result.output
329
+ .map((item: any) => {
330
+ if (!item) {
331
+ return '';
332
+ }
333
+ if (typeof item === 'string') {
334
+ return item;
335
+ }
336
+ if (typeof item.text === 'string') {
337
+ return item.text;
338
+ }
339
+ if (typeof item.content === 'string') {
340
+ return item.content;
341
+ }
342
+ if (Array.isArray(item.content)) {
343
+ return item.content.map((part: any) => this.extractPartText(part)).join('');
344
+ }
345
+ return '';
346
+ })
347
+ .join('')
348
+ .trim();
349
+ if (text) {
350
+ return text;
351
+ }
352
+ }
353
+ return '';
354
+ }
355
+
356
+ private async handleStreamEvent(event: any, onAgentMessage: AgentMessageHandler): Promise<void> {
357
+ if (!event || !event.type) {
358
+ return;
359
+ }
360
+ switch (event.type) {
361
+ case 'thread.started':
362
+ this.log(`stream thread.started (id=${event.thread_id || 'unknown'})`);
363
+ break;
364
+ case 'turn.started':
365
+ this.log('stream turn.started');
366
+ break;
367
+ case 'turn.completed':
368
+ this.log('stream turn.completed');
369
+ break;
370
+ case 'item.started':
371
+ case 'item.updated':
372
+ case 'item.completed':
373
+ await this.handleStreamItem(event.item, onAgentMessage);
374
+ break;
375
+ default:
376
+ break;
377
+ }
378
+ }
379
+
380
+ private normalizeUsageSummary(raw: any): CodexUsageSummary | null {
381
+ if (!raw || typeof raw !== 'object') {
382
+ return null;
383
+ }
384
+ const inputTokens = this.normalizeUsageToken(raw.input_tokens ?? raw.inputTokens);
385
+ const cachedInputTokens = this.normalizeUsageToken(raw.cached_input_tokens ?? raw.cachedInputTokens);
386
+ const outputTokens = this.normalizeUsageToken(raw.output_tokens ?? raw.outputTokens);
387
+ if (inputTokens <= 0 && cachedInputTokens <= 0 && outputTokens <= 0) {
388
+ return null;
389
+ }
390
+ return {
391
+ inputTokens,
392
+ cachedInputTokens,
393
+ outputTokens
394
+ };
395
+ }
396
+
397
+ private normalizeUsageToken(value: any): number {
398
+ const parsed = Number(value);
399
+ if (!Number.isFinite(parsed) || parsed <= 0) {
400
+ return 0;
401
+ }
402
+ return Math.floor(parsed);
403
+ }
404
+
405
+ private async emitUsageSummary(options: CodexRunOptions | undefined, usage: CodexUsageSummary | null): Promise<void> {
406
+ if (!options?.onUsage) {
407
+ return;
408
+ }
409
+ try {
410
+ await options.onUsage(usage);
411
+ }
412
+ catch (error) {
413
+ const message = error instanceof Error ? error.message : String(error || 'Unknown error');
414
+ this.log(`onUsage failed: ${message}`);
415
+ }
416
+ }
417
+
418
+ private async handleStreamItem(item: any, onAgentMessage: AgentMessageHandler): Promise<void> {
419
+ if (!item || !item.type) {
420
+ return;
421
+ }
422
+ switch (item.type) {
423
+ case 'agent_message':
424
+ await onAgentMessage(item.text || '');
425
+ break;
426
+ case 'command_execution':
427
+ if (item.command) {
428
+ this.log(`stream command: ${item.command} (${item.status || 'unknown'})`);
429
+ }
430
+ if (item.aggregated_output) {
431
+ const output = item.aggregated_output.length > 800
432
+ ? `${item.aggregated_output.slice(0, 800)}...`
433
+ : item.aggregated_output;
434
+ this.log(`stream command output: ${output}`);
435
+ }
436
+ break;
437
+ case 'file_change':
438
+ if (Array.isArray(item.changes) && item.changes.length) {
439
+ const summary = item.changes.map((change: any) => `${change.kind}:${change.path}`).join(', ');
440
+ this.log(`stream file_change (${item.status || 'unknown'}): ${summary}`);
441
+ }
442
+ break;
443
+ case 'mcp_tool_call':
444
+ if (item.tool) {
445
+ this.log(`stream tool_call: ${item.tool} (${item.status || 'unknown'})`);
446
+ }
447
+ if (item.error?.message) {
448
+ this.log(`stream tool_call error: ${item.error.message}`);
449
+ }
450
+ break;
451
+ case 'web_search':
452
+ if (item.query) {
453
+ this.log(`stream web_search: ${item.query}`);
454
+ }
455
+ break;
456
+ case 'todo_list':
457
+ if (Array.isArray(item.items)) {
458
+ const total = item.items.length;
459
+ const done = item.items.filter((entry: any) => entry?.completed).length;
460
+ this.log(`stream todo_list: ${done}/${total} completed`);
461
+ }
462
+ break;
463
+ case 'reasoning':
464
+ if (item.text) {
465
+ const snippet = item.text.length > 200 ? `${item.text.slice(0, 200)}...` : item.text;
466
+ this.log(`stream reasoning: ${snippet}`);
467
+ }
468
+ break;
469
+ case 'error':
470
+ if (item.message) {
471
+ this.log(`stream error: ${item.message}`);
472
+ }
473
+ break;
474
+ default:
475
+ break;
476
+ }
477
+ }
478
+
479
+ private logStreamText(text: string): void {
480
+ if (!this.debugEnabled) {
481
+ return;
482
+ }
483
+ const lines = text.split(/\r?\n/);
484
+ for (const line of lines) {
485
+ this.log(`stream: ${line}`);
486
+ }
487
+ }
488
+
489
+ private extractPartText(part: any): string {
490
+ if (!part) {
491
+ return '';
492
+ }
493
+ if (typeof part === 'string') {
494
+ return part;
495
+ }
496
+ if (typeof part.text === 'string') {
497
+ return part.text;
498
+ }
499
+ if (typeof part.content === 'string') {
500
+ return part.content;
501
+ }
502
+ return '';
503
+ }
504
+
505
+ private async withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
506
+ let done = false;
507
+ const startedAt = Date.now();
508
+ const heartbeatMs = Math.max(10000, Math.min(30000, Math.floor(timeoutMs / 4)));
509
+ const timeoutPromise = (async (): Promise<T> => {
510
+ while (!done) {
511
+ const elapsed = Date.now() - startedAt;
512
+ if (elapsed >= timeoutMs) {
513
+ throw new Error('AI request timed out.');
514
+ }
515
+ const remaining = timeoutMs - elapsed;
516
+ await sleepTimeout(Math.min(heartbeatMs, remaining));
517
+ if (done) {
518
+ return await promise;
519
+ }
520
+ const currentElapsed = Date.now() - startedAt;
521
+ if (currentElapsed >= timeoutMs) {
522
+ throw new Error('AI request timed out.');
523
+ }
524
+ const currentRemaining = Math.max(0, timeoutMs - currentElapsed);
525
+ this.log(`runOnce waiting (elapsedMs=${currentElapsed}, remainingMs=${currentRemaining})`);
526
+ }
527
+ return await promise;
528
+ })();
529
+ try {
530
+ return await Promise.race([promise, timeoutPromise]);
531
+ }
532
+ finally {
533
+ done = true;
534
+ }
535
+ }
536
+
537
+ private normalizeRetryCount(value?: number): number {
538
+ if (typeof value !== 'number' || Number.isNaN(value)) {
539
+ return 2;
540
+ }
541
+ return Math.max(0, Math.floor(value));
542
+ }
543
+
544
+ private normalizeRetryDelay(value?: number): number {
545
+ if (typeof value !== 'number' || Number.isNaN(value)) {
546
+ return 500;
547
+ }
548
+ return Math.max(100, Math.floor(value));
549
+ }
550
+
551
+ private resolveModelSequence(options?: CodexRunOptions): string[] {
552
+ const primary = this.normalizeOptionalString(options?.threadOptions?.model || this.config.model);
553
+ const fallbackModels = this.collectFallbackModels(options?.fallbackModels);
554
+ const sequence: string[] = [];
555
+ const push = (value: any) => {
556
+ const normalized = this.normalizeOptionalString(value);
557
+ if (!normalized || sequence.includes(normalized)) {
558
+ return;
559
+ }
560
+ sequence.push(normalized);
561
+ };
562
+ const preferredFallback = this.getModelFallbackPreference(primary);
563
+ if (preferredFallback) {
564
+ push(preferredFallback);
565
+ this.log(`sticky model fallback active: ${primary} -> ${preferredFallback}`);
566
+ }
567
+ push(primary);
568
+ fallbackModels.forEach(push);
569
+ if (!sequence.length) {
570
+ sequence.push('');
571
+ }
572
+ return sequence;
573
+ }
574
+
575
+ private collectFallbackModels(runFallbackModels?: string[]): string[] {
576
+ const models: string[] = [];
577
+ const push = (value: any) => {
578
+ const normalized = this.normalizeOptionalString(value);
579
+ if (!normalized || models.includes(normalized)) {
580
+ return;
581
+ }
582
+ models.push(normalized);
583
+ };
584
+ this.normalizeModelList(runFallbackModels).forEach(push);
585
+ this.normalizeModelList(this.config.fallbackModels).forEach(push);
586
+ push(this.config.fallbackModel);
587
+ this.normalizeModelList(process.env.AI_ASSISTANT_CODEX_FALLBACK_MODELS).forEach(push);
588
+ push(process.env.AI_ASSISTANT_CODEX_FALLBACK_MODEL);
589
+ this.normalizeModelList(process.env.AI_TERMINAL_CODEX_FALLBACK_MODELS).forEach(push);
590
+ push(process.env.AI_TERMINAL_CODEX_FALLBACK_MODEL);
591
+ this.normalizeModelList(process.env.AI_DASHBOARD_CODEX_FALLBACK_MODELS).forEach(push);
592
+ push(process.env.AI_DASHBOARD_CODEX_FALLBACK_MODEL);
593
+ const primaryModel = this.normalizeOptionalString(
594
+ this.config.model
595
+ || runFallbackModels?.[0]
596
+ || ''
597
+ );
598
+ if (/^gpt-5(?:\.\d+)?-codex$/i.test(primaryModel)) {
599
+ push('gpt-5-codex');
600
+ }
601
+ if (/^gpt-5(?:-codex|\.\d+-codex)$/i.test(primaryModel)) {
602
+ push('gpt-5.5');
603
+ }
604
+ return models;
605
+ }
606
+
607
+ private normalizeModelList(value: any): string[] {
608
+ if (Array.isArray(value)) {
609
+ return value
610
+ .map(entry => this.normalizeOptionalString(entry))
611
+ .filter(Boolean);
612
+ }
613
+ const raw = this.normalizeOptionalString(value);
614
+ if (!raw) {
615
+ return [];
616
+ }
617
+ return raw
618
+ .split(',')
619
+ .map(entry => this.normalizeOptionalString(entry))
620
+ .filter(Boolean);
621
+ }
622
+
623
+ private applyModelOverride(options: CodexRunOptions | undefined, model: string): CodexRunOptions {
624
+ const nextThreadOptions: CodexThreadOptions = {
625
+ ...(options?.threadOptions || {})
626
+ };
627
+ if (model) {
628
+ nextThreadOptions.model = model;
629
+ }
630
+ else {
631
+ delete nextThreadOptions.model;
632
+ }
633
+ return {
634
+ ...(options || {}),
635
+ threadOptions: nextThreadOptions
636
+ };
637
+ }
638
+
639
+ private isModelAvailabilityError(error: unknown): boolean {
640
+ const message = error instanceof Error ? error.message : String(error || '');
641
+ const normalized = message.toLowerCase();
642
+ if (!normalized.includes('model')) {
643
+ return false;
644
+ }
645
+ if (/does not exist|not found|unknown model|invalid model|unsupported model|model_not_found|no such model/.test(normalized)) {
646
+ return true;
647
+ }
648
+ if (/not available|unavailable|not enabled|not allowed|do not have access|don't have access|insufficient permissions/.test(normalized)) {
649
+ return true;
650
+ }
651
+ return /404/.test(normalized) && /model/.test(normalized);
652
+ }
653
+
654
+ private isRetryableError(error: unknown): boolean {
655
+ const message = error instanceof Error ? error.message : String(error || '');
656
+ if (/AI returned no completion content|Codex returned no completion content/i.test(message)) {
657
+ return true;
658
+ }
659
+ if (this.isCodexEnvironmentError(error)) {
660
+ return true;
661
+ }
662
+ const statusMatch = message.match(/\\b(429|5\\d{2})\\b/);
663
+ if (statusMatch) {
664
+ return true;
665
+ }
666
+ return /ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|fetch failed|timed out|timeout/i.test(message);
667
+ }
668
+
669
+ private isCodexEnvironmentError(error: unknown): boolean {
670
+ const message = error instanceof Error ? error.message : String(error || '');
671
+ return /error finding codex home|could not update path: no such file or directory/i.test(message);
672
+ }
673
+
674
+ private recoverCodexEnvironment(error: unknown): void {
675
+ const message = error instanceof Error ? error.message : String(error || 'Unknown error');
676
+ this.log(`recovering codex environment after error: ${message}`);
677
+ this.threadCache.clear();
678
+ this.codex = null;
679
+ this.codexInit = null;
680
+ this.zDotDir = null;
681
+ }
682
+
683
+ private normalizeOptionalString(value: any): string {
684
+ return typeof value === 'string' ? value.trim() : '';
685
+ }
686
+
687
+ private resolveModelUnavailableTtlMs(): number {
688
+ const raw = Number(
689
+ process.env.AI_DASHBOARD_CODEX_MODEL_UNAVAILABLE_TTL_MS
690
+ || process.env.AI_ASSISTANT_CODEX_MODEL_UNAVAILABLE_TTL_MS
691
+ );
692
+ if (Number.isFinite(raw) && raw >= CodexClient.MIN_MODEL_UNAVAILABLE_TTL_MS) {
693
+ return Math.floor(raw);
694
+ }
695
+ return CodexClient.DEFAULT_MODEL_UNAVAILABLE_TTL_MS;
696
+ }
697
+
698
+ private async ensureModelFallbackPreferencesLoaded(): Promise<void> {
699
+ if (CodexClient.modelFallbackPreferencesLoaded) {
700
+ this.pruneModelFallbackPreferences();
701
+ return;
702
+ }
703
+ if (CodexClient.modelFallbackPreferencesLoadPromise !== null) {
704
+ await CodexClient.modelFallbackPreferencesLoadPromise;
705
+ this.pruneModelFallbackPreferences();
706
+ return;
707
+ }
708
+ CodexClient.modelFallbackPreferencesLoadPromise = (async () => {
709
+ try {
710
+ const raw = await fs.readFile(CodexClient.MODEL_UNAVAILABLE_FALLBACK_FILE, 'utf8');
711
+ const parsed = JSON.parse(raw);
712
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
713
+ return;
714
+ }
715
+ Object.entries(parsed).forEach(([model, entry]) => {
716
+ const key = this.normalizeOptionalString(model);
717
+ if (!key) {
718
+ return;
719
+ }
720
+ const fallbackModel = this.normalizeOptionalString((entry as any)?.fallbackModel);
721
+ const expiresAt = Number((entry as any)?.expiresAt);
722
+ const updatedAt = Number((entry as any)?.updatedAt);
723
+ if (!fallbackModel || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
724
+ return;
725
+ }
726
+ CodexClient.modelFallbackPreferences.set(key, {
727
+ fallbackModel,
728
+ expiresAt: Math.floor(expiresAt),
729
+ updatedAt: Number.isFinite(updatedAt) ? Math.floor(updatedAt) : Date.now()
730
+ });
731
+ });
732
+ }
733
+ catch {
734
+ // Ignore cache load errors.
735
+ }
736
+ finally {
737
+ CodexClient.modelFallbackPreferencesLoaded = true;
738
+ CodexClient.modelFallbackPreferencesLoadPromise = null;
739
+ }
740
+ })();
741
+ await CodexClient.modelFallbackPreferencesLoadPromise;
742
+ this.pruneModelFallbackPreferences();
743
+ }
744
+
745
+ private pruneModelFallbackPreferences(now = Date.now()): void {
746
+ Array.from(CodexClient.modelFallbackPreferences.entries()).forEach(([model, entry]) => {
747
+ if (!entry || !Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) {
748
+ CodexClient.modelFallbackPreferences.delete(model);
749
+ }
750
+ });
751
+ }
752
+
753
+ private getModelFallbackPreference(model: string): string {
754
+ const normalizedModel = this.normalizeOptionalString(model);
755
+ if (!normalizedModel) {
756
+ return '';
757
+ }
758
+ this.pruneModelFallbackPreferences();
759
+ const entry = CodexClient.modelFallbackPreferences.get(normalizedModel);
760
+ if (!entry || entry.expiresAt <= Date.now()) {
761
+ if (entry) {
762
+ CodexClient.modelFallbackPreferences.delete(normalizedModel);
763
+ }
764
+ return '';
765
+ }
766
+ return entry.fallbackModel;
767
+ }
768
+
769
+ private async rememberModelFallbackPreference(model: string, fallbackModel: string): Promise<void> {
770
+ const normalizedModel = this.normalizeOptionalString(model);
771
+ const normalizedFallback = this.normalizeOptionalString(fallbackModel);
772
+ if (!normalizedModel || !normalizedFallback || normalizedModel === normalizedFallback) {
773
+ return;
774
+ }
775
+ const now = Date.now();
776
+ CodexClient.modelFallbackPreferences.set(normalizedModel, {
777
+ fallbackModel: normalizedFallback,
778
+ expiresAt: now + this.modelUnavailableTtlMs,
779
+ updatedAt: now
780
+ });
781
+ this.pruneModelFallbackPreferences(now);
782
+ await this.persistModelFallbackPreferences();
783
+ }
784
+
785
+ private async clearModelFallbackPreference(model: string): Promise<void> {
786
+ const normalizedModel = this.normalizeOptionalString(model);
787
+ if (!normalizedModel) {
788
+ return;
789
+ }
790
+ if (!CodexClient.modelFallbackPreferences.has(normalizedModel)) {
791
+ return;
792
+ }
793
+ CodexClient.modelFallbackPreferences.delete(normalizedModel);
794
+ await this.persistModelFallbackPreferences();
795
+ }
796
+
797
+ private async persistModelFallbackPreferences(): Promise<void> {
798
+ this.pruneModelFallbackPreferences();
799
+ if (!CodexClient.modelFallbackPreferences.size) {
800
+ try {
801
+ await fs.unlink(CodexClient.MODEL_UNAVAILABLE_FALLBACK_FILE);
802
+ }
803
+ catch {
804
+ // Ignore file cleanup errors.
805
+ }
806
+ return;
807
+ }
808
+ const serialized: Record<string, CodexModelFallbackPreference> = {};
809
+ CodexClient.modelFallbackPreferences.forEach((entry, model) => {
810
+ serialized[model] = entry;
811
+ });
812
+ try {
813
+ await fs.writeFile(CodexClient.MODEL_UNAVAILABLE_FALLBACK_FILE, JSON.stringify(serialized), 'utf8');
814
+ }
815
+ catch {
816
+ // Ignore cache persistence errors.
817
+ }
818
+ }
819
+
820
+ private async sleep(ms: number): Promise<void> {
821
+ await sleepTimeout(ms);
822
+ }
823
+
824
+ private async ensureCodex(): Promise<void> {
825
+ if (this.codex) {
826
+ return;
827
+ }
828
+ if (this.codexInit !== null) {
829
+ await this.codexInit;
830
+ return;
831
+ }
832
+ this.codexInit = (async () => {
833
+ this.log('Loading AI SDK module...');
834
+ const importer = new Function('specifier', 'return import(specifier)') as DynamicImport;
835
+ const mod = await importer('@openai/codex-sdk');
836
+ const CodexCtor = mod?.Codex || mod?.default?.Codex || mod?.default || mod;
837
+ if (!CodexCtor) {
838
+ throw new Error('AI SDK export not found.');
839
+ }
840
+ this.log('AI SDK module loaded.');
841
+ const env = await this.buildCodexEnv();
842
+ this.codex = new CodexCtor({
843
+ apiKey: this.config.apiKey,
844
+ baseUrl: this.config.baseUrl,
845
+ model: this.config.model,
846
+ env
847
+ });
848
+ this.log('AI client initialized.');
849
+ })();
850
+ await this.codexInit;
851
+ }
852
+
853
+ private log(message: string): void {
854
+ if (!this.debugEnabled) {
855
+ return;
856
+ }
857
+ console.log(`[AI-Dashboard][AI] ${message}`);
858
+ }
859
+
860
+ private resolveDefaultTimeoutMs(): number {
861
+ const raw = Number(process.env.AI_DASHBOARD_CODEX_TIMEOUT_MS || process.env.AI_DASHBOARD_AGENT_TIMEOUT_MS);
862
+ if (Number.isFinite(raw) && raw > 0) {
863
+ return Math.floor(raw);
864
+ }
865
+ return 600000;
866
+ }
867
+
868
+ private resolveStreamEnabled(): boolean {
869
+ const raw = (process.env.AI_DASHBOARD_CODEX_STREAM || '').trim().toLowerCase();
870
+ if (!raw) {
871
+ return this.debugEnabled;
872
+ }
873
+ if (['true', '1', 'yes', 'y', 'on'].includes(raw)) {
874
+ return true;
875
+ }
876
+ if (['false', '0', 'no', 'n', 'off'].includes(raw)) {
877
+ return false;
878
+ }
879
+ return this.debugEnabled;
880
+ }
881
+
882
+ private resolveCleanZdotdirEnabled(): boolean {
883
+ const raw = (process.env.AI_DASHBOARD_CODEX_CLEAN_ZDOTDIR ?? '').trim().toLowerCase();
884
+ if (!raw) {
885
+ return true;
886
+ }
887
+ if (['false', '0', 'no', 'n', 'off'].includes(raw)) {
888
+ return false;
889
+ }
890
+ if (['true', '1', 'yes', 'y', 'on'].includes(raw)) {
891
+ return true;
892
+ }
893
+ return true;
894
+ }
895
+
896
+ private async buildCodexEnv(): Promise<Record<string, string>> {
897
+ const env: Record<string, string> = {};
898
+ for (const [key, value] of Object.entries(process.env)) {
899
+ if (typeof value === 'string') {
900
+ env[key] = value;
901
+ }
902
+ }
903
+ if (!this.normalizeOptionalString(env.HOME)) {
904
+ const fallbackHome = this.normalizeOptionalString(process.env.HOME || os.homedir());
905
+ if (fallbackHome) {
906
+ env.HOME = fallbackHome;
907
+ }
908
+ }
909
+ await this.ensureCodexHome(env);
910
+ if (this.cleanZdotdirEnabled) {
911
+ env.ZDOTDIR = await this.ensureZdotdir();
912
+ }
913
+ return env;
914
+ }
915
+
916
+ private async ensureCodexHome(env: Record<string, string>): Promise<void> {
917
+ const current = this.normalizeOptionalString(env.CODEX_HOME || process.env.CODEX_HOME);
918
+ const homeRoot = this.normalizeOptionalString(env.HOME || process.env.HOME || os.homedir());
919
+ const primary = current || (homeRoot ? path.join(homeRoot, '.codex') : path.join(os.tmpdir(), 'resolveio-codex-home'));
920
+ try {
921
+ await fs.mkdir(path.join(primary, 'sessions'), { recursive: true });
922
+ env.CODEX_HOME = primary;
923
+ process.env.CODEX_HOME = primary;
924
+ return;
925
+ }
926
+ catch {
927
+ const fallback = path.join(os.tmpdir(), 'resolveio-codex-home');
928
+ await fs.mkdir(path.join(fallback, 'sessions'), { recursive: true });
929
+ env.CODEX_HOME = fallback;
930
+ process.env.CODEX_HOME = fallback;
931
+ }
932
+ }
933
+
934
+ private async ensureZdotdir(): Promise<string> {
935
+ if (this.zDotDir) {
936
+ return this.zDotDir;
937
+ }
938
+ const override = (process.env.AI_DASHBOARD_CODEX_ZDOTDIR || '').trim();
939
+ const dir = override || path.join(os.tmpdir(), 'codex-zdotdir');
940
+ await fs.mkdir(dir, { recursive: true });
941
+ await Promise.allSettled([
942
+ fs.writeFile(path.join(dir, '.zshrc'), '', { flag: 'a' }),
943
+ fs.writeFile(path.join(dir, '.zprofile'), '', { flag: 'a' })
944
+ ]);
945
+ this.zDotDir = dir;
946
+ return dir;
947
+ }
948
+
949
+ private resolvePingEnabled(): boolean {
950
+ return this.normalizeBoolean(process.env.AI_DASHBOARD_CODEX_PING, false);
951
+ }
952
+
953
+ private resolvePingTimeoutMs(): number {
954
+ const raw = Number(process.env.AI_DASHBOARD_CODEX_PING_TIMEOUT_MS);
955
+ if (Number.isFinite(raw) && raw > 0) {
956
+ return Math.floor(raw);
957
+ }
958
+ return 10000;
959
+ }
960
+
961
+ private resolveDefaultThreadOptions(): CodexThreadOptions {
962
+ const approvalPolicy = this.normalizeApprovalPolicy(process.env.AI_DASHBOARD_CODEX_APPROVAL_POLICY);
963
+ const sandboxMode = this.normalizeSandboxMode(process.env.AI_DASHBOARD_CODEX_SANDBOX_MODE, 'workspace-write');
964
+ const skipGitRepoCheck = this.normalizeBoolean(process.env.AI_DASHBOARD_CODEX_SKIP_GIT_CHECK, true);
965
+ const webSearchMode = this.normalizeWebSearchMode(process.env.AI_DASHBOARD_CODEX_WEB_SEARCH_MODE);
966
+ const webSearchEnabled = this.normalizeBoolean(process.env.AI_DASHBOARD_CODEX_WEB_SEARCH_ENABLED, false);
967
+ const networkAccessEnabled = this.normalizeBoolean(process.env.AI_DASHBOARD_CODEX_NETWORK_ACCESS_ENABLED, false);
968
+ const modelReasoningEffort = this.normalizeModelReasoningEffort(process.env.AI_DASHBOARD_CODEX_REASONING_EFFORT);
969
+ return {
970
+ model: this.config.model,
971
+ approvalPolicy,
972
+ sandboxMode,
973
+ skipGitRepoCheck,
974
+ webSearchMode,
975
+ webSearchEnabled,
976
+ networkAccessEnabled,
977
+ modelReasoningEffort
978
+ };
979
+ }
980
+
981
+ private mergeThreadOptions(overrides?: CodexThreadOptions): CodexThreadOptions | undefined {
982
+ const merged: CodexThreadOptions = {
983
+ ...this.defaultThreadOptions,
984
+ ...(overrides || {})
985
+ };
986
+ const effectiveModel = this.normalizeOptionalString(merged.model || this.config.model);
987
+ const normalizedEffort = this.normalizeModelReasoningEffortForModel(effectiveModel, merged.modelReasoningEffort);
988
+ if (normalizedEffort && normalizedEffort !== merged.modelReasoningEffort) {
989
+ this.log(`normalized reasoning effort for model=${effectiveModel || 'default'}: ${merged.modelReasoningEffort} -> ${normalizedEffort}`);
990
+ merged.modelReasoningEffort = normalizedEffort;
991
+ }
992
+ const cleaned = Object.entries(merged).reduce((acc, [key, value]) => {
993
+ if (value === undefined || value === null || value === '') {
994
+ return acc;
995
+ }
996
+ (acc as any)[key] = value;
997
+ return acc;
998
+ }, {} as CodexThreadOptions);
999
+ return Object.keys(cleaned).length ? cleaned : undefined;
1000
+ }
1001
+
1002
+ private normalizeApprovalPolicy(value?: string): CodexThreadOptions['approvalPolicy'] {
1003
+ const normalized = (value || '').trim().toLowerCase();
1004
+ if (normalized === 'never' || normalized === 'on-request' || normalized === 'on-failure' || normalized === 'untrusted') {
1005
+ return normalized as CodexThreadOptions['approvalPolicy'];
1006
+ }
1007
+ return 'never';
1008
+ }
1009
+
1010
+ private normalizeSandboxMode(value?: string, fallback: CodexThreadOptions['sandboxMode'] = 'read-only'): CodexThreadOptions['sandboxMode'] {
1011
+ const normalized = (value || '').trim().toLowerCase();
1012
+ if (normalized === 'read-only' || normalized === 'workspace-write' || normalized === 'danger-full-access') {
1013
+ return normalized as CodexThreadOptions['sandboxMode'];
1014
+ }
1015
+ return fallback;
1016
+ }
1017
+
1018
+ private normalizeWebSearchMode(value?: string): CodexThreadOptions['webSearchMode'] | undefined {
1019
+ const normalized = (value || '').trim().toLowerCase();
1020
+ if (normalized === 'disabled' || normalized === 'cached' || normalized === 'live') {
1021
+ return normalized as CodexThreadOptions['webSearchMode'];
1022
+ }
1023
+ return undefined;
1024
+ }
1025
+
1026
+ private normalizeModelReasoningEffort(value?: string): CodexThreadOptions['modelReasoningEffort'] | undefined {
1027
+ const normalized = (value || '').trim().toLowerCase();
1028
+ if (normalized === 'minimal' || normalized === 'none' || normalized === 'low' || normalized === 'medium' || normalized === 'high' || normalized === 'xhigh') {
1029
+ return normalized as CodexThreadOptions['modelReasoningEffort'];
1030
+ }
1031
+ return undefined;
1032
+ }
1033
+
1034
+ private normalizeModelReasoningEffortForModel(
1035
+ model: string,
1036
+ effort?: CodexThreadOptions['modelReasoningEffort']
1037
+ ): CodexThreadOptions['modelReasoningEffort'] | undefined {
1038
+ if (!effort) {
1039
+ return effort;
1040
+ }
1041
+ const normalizedModel = this.normalizeOptionalString(model).toLowerCase();
1042
+ if (effort === 'minimal' && (!normalizedModel || normalizedModel.startsWith('gpt-5') || normalizedModel.includes('codex'))) {
1043
+ return 'low';
1044
+ }
1045
+ return effort;
1046
+ }
1047
+
1048
+ private normalizeBoolean(value: string | undefined, fallback: boolean): boolean {
1049
+ if (!value) {
1050
+ return fallback;
1051
+ }
1052
+ const normalized = value.trim().toLowerCase();
1053
+ if (['true', '1', 'yes', 'y', 'on'].includes(normalized)) {
1054
+ return true;
1055
+ }
1056
+ if (['false', '0', 'no', 'n', 'off'].includes(normalized)) {
1057
+ return false;
1058
+ }
1059
+ return fallback;
1060
+ }
1061
+
1062
+ private formatThreadOptions(options: CodexThreadOptions): string {
1063
+ const summary: Record<string, string> = {};
1064
+ Object.entries(options).forEach(([key, value]) => {
1065
+ if (value === undefined || value === null) {
1066
+ return;
1067
+ }
1068
+ summary[key] = String(value);
1069
+ });
1070
+ return JSON.stringify(summary);
1071
+ }
1072
+
1073
+ private buildThreadOptionsKey(options?: CodexThreadOptions): string {
1074
+ if (!options) {
1075
+ return '';
1076
+ }
1077
+ const ordered: Record<string, string> = {};
1078
+ Object.keys(options)
1079
+ .sort()
1080
+ .forEach((key) => {
1081
+ const value = (options as Record<string, unknown>)[key];
1082
+ if (value === undefined || value === null) {
1083
+ return;
1084
+ }
1085
+ ordered[key] = Array.isArray(value) ? JSON.stringify(value) : String(value);
1086
+ });
1087
+ return JSON.stringify(ordered);
1088
+ }
1089
+
1090
+ private buildThreadCacheKey(threadKey: string | undefined, options?: CodexThreadOptions): string | null {
1091
+ if (threadKey) {
1092
+ return `thread:${threadKey}`;
1093
+ }
1094
+ const model = options?.model || this.config.model;
1095
+ const workingDirectory = options?.workingDirectory;
1096
+ if (!model && !workingDirectory) {
1097
+ return null;
1098
+ }
1099
+ return `thread:auto:${model || 'default'}:${workingDirectory || 'root'}`;
1100
+ }
1101
+
1102
+ private isPingPrompt(prompt: string): boolean {
1103
+ return prompt.trim() === CodexClient.PING_PROMPT;
1104
+ }
1105
+
1106
+ private async runPing(threadOptions?: CodexThreadOptions): Promise<void> {
1107
+ this.log(`runPing start (timeoutMs=${this.pingTimeoutMs})`);
1108
+ try {
1109
+ const content = await this.runOnce(CodexClient.PING_PROMPT, {
1110
+ timeoutMs: this.pingTimeoutMs,
1111
+ threadOptions,
1112
+ reuseThread: false
1113
+ });
1114
+ const trimmed = content.trim();
1115
+ const preview = trimmed.length > 80 ? `${trimmed.slice(0, 80)}…` : trimmed;
1116
+ this.log(`runPing response: ${preview}`);
1117
+ }
1118
+ catch (error) {
1119
+ const message = error instanceof Error ? error.message : String(error || 'Unknown error');
1120
+ this.log(`runPing failed: ${message}`);
1121
+ throw error;
1122
+ }
1123
+ }
1124
+ }