@resolveio/server-lib 22.2.33 → 22.2.34

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