@opengeni/worker-bundle 2.0.1 → 2.0.2-canary.38789554071001

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 (379) hide show
  1. package/dist/activities/agent-run-admission.d.ts +1 -12
  2. package/dist/activities/agent-turn/admission.d.ts +88 -10
  3. package/dist/activities/agent-turn/agent-build.d.ts +14 -3
  4. package/dist/activities/agent-turn/claim.d.ts +4 -1
  5. package/dist/activities/agent-turn/claude-core.d.ts +195 -0
  6. package/dist/activities/agent-turn/code-search.d.ts +60 -0
  7. package/dist/activities/agent-turn/codex-capacity.d.ts +3 -0
  8. package/dist/activities/agent-turn/codex-core-capacity.d.ts +37 -0
  9. package/dist/activities/agent-turn/codex-core-claim.d.ts +40 -0
  10. package/dist/activities/agent-turn/codex-core-errors.d.ts +102 -0
  11. package/dist/activities/agent-turn/codex-core-failover.d.ts +15 -0
  12. package/dist/activities/agent-turn/codex-core-requests.d.ts +28 -0
  13. package/dist/activities/agent-turn/codex-core-settlement.d.ts +77 -0
  14. package/dist/activities/agent-turn/codex-credit-policy.d.ts +30 -0
  15. package/dist/activities/agent-turn/codex-plan-entitlement.d.ts +105 -0
  16. package/dist/activities/agent-turn/codex-usage-policy.d.ts +2 -0
  17. package/dist/activities/agent-turn/codex.d.ts +2 -19
  18. package/dist/activities/agent-turn/compaction-interruption.d.ts +32 -0
  19. package/dist/activities/agent-turn/compaction-prep.d.ts +30 -1
  20. package/dist/activities/agent-turn/credential-leases.d.ts +64 -37
  21. package/dist/activities/agent-turn/credential-restriction.d.ts +3 -0
  22. package/dist/activities/agent-turn/errors.d.ts +185 -26
  23. package/dist/activities/agent-turn/failure-settlement.d.ts +10 -43
  24. package/dist/activities/agent-turn/final-reply.d.ts +18 -0
  25. package/dist/activities/agent-turn/finalization-monitor.d.ts +7 -2
  26. package/dist/activities/agent-turn/finalization.d.ts +2 -0
  27. package/dist/activities/agent-turn/github-repository-bindings.d.ts +2 -0
  28. package/dist/activities/agent-turn/governance-model.d.ts +13 -1
  29. package/dist/activities/agent-turn/history-sink.d.ts +4 -1
  30. package/dist/activities/agent-turn/history.d.ts +2 -0
  31. package/dist/activities/agent-turn/input-wait-reply.d.ts +76 -0
  32. package/dist/activities/agent-turn/meaningful-output.d.ts +9 -0
  33. package/dist/activities/agent-turn/media-artifacts.d.ts +5 -3
  34. package/dist/activities/agent-turn/model-call-admission.d.ts +15 -0
  35. package/dist/activities/agent-turn/model-usage.d.ts +56 -14
  36. package/dist/activities/agent-turn/model-wire-dispatch.d.ts +15 -0
  37. package/dist/activities/agent-turn/optional-repositories.d.ts +59 -0
  38. package/dist/activities/agent-turn/prompt-tool-availability.d.ts +17 -0
  39. package/dist/activities/agent-turn/provider-dispatch-barrier.d.ts +12 -1
  40. package/dist/activities/agent-turn/provider-recovery-copy.d.ts +24 -0
  41. package/dist/activities/agent-turn/provider-recovery-metrics.d.ts +18 -0
  42. package/dist/activities/agent-turn/provider-recovery-policy.d.ts +6 -0
  43. package/dist/activities/agent-turn/quiescence.d.ts +6 -7
  44. package/dist/activities/agent-turn/recovery-warning.d.ts +6 -5
  45. package/dist/activities/agent-turn/refresh-credentials.d.ts +6 -0
  46. package/dist/activities/agent-turn/run-credentials.d.ts +9 -5
  47. package/dist/activities/agent-turn/run.d.ts +27 -2
  48. package/dist/activities/agent-turn/sandbox-establish.d.ts +1 -0
  49. package/dist/activities/agent-turn/sandbox-provision.d.ts +25 -1
  50. package/dist/activities/agent-turn/sandbox-route.d.ts +3 -0
  51. package/dist/activities/agent-turn/sandbox-runtime.d.ts +1 -1
  52. package/dist/activities/agent-turn/secret-resolver.d.ts +64 -0
  53. package/dist/activities/agent-turn/session-title.d.ts +60 -3
  54. package/dist/activities/agent-turn/session-usage-custody.d.ts +66 -0
  55. package/dist/activities/agent-turn/skill-checkout.d.ts +25 -6
  56. package/dist/activities/agent-turn/skill-read.d.ts +70 -2
  57. package/dist/activities/agent-turn/skill-search.d.ts +2 -0
  58. package/dist/activities/agent-turn/skill-tools.d.ts +41 -4
  59. package/dist/activities/agent-turn/skill-transfer.d.ts +18 -6
  60. package/dist/activities/agent-turn/stream-attempt.d.ts +6 -3
  61. package/dist/activities/agent-turn/subscription-capacity-arming.d.ts +41 -0
  62. package/dist/activities/agent-turn/subscription-core-capacity.d.ts +86 -0
  63. package/dist/activities/agent-turn/subscription-core-failover.d.ts +69 -0
  64. package/dist/activities/agent-turn/subscription-core-placed.d.ts +14 -0
  65. package/dist/activities/agent-turn/subscription-core-requests.d.ts +109 -0
  66. package/dist/activities/agent-turn/subscription-core-settlement.d.ts +112 -0
  67. package/dist/activities/agent-turn/subscription-lease.d.ts +44 -0
  68. package/dist/activities/agent-turn/subscription-serving-capacity.d.ts +6 -0
  69. package/dist/activities/agent-turn/subscription-serving-catalog.d.ts +13 -0
  70. package/dist/activities/agent-turn/subscription-serving-claim.d.ts +30 -0
  71. package/dist/activities/agent-turn/subscription-serving-providers.d.ts +2 -0
  72. package/dist/activities/agent-turn/tool-environment.d.ts +31 -6
  73. package/dist/activities/agent-turn/tool-policy.d.ts +55 -3
  74. package/dist/activities/agent-turn/turn-context.d.ts +104 -5
  75. package/dist/activities/agent-turn/web-search.d.ts +57 -0
  76. package/dist/activities/agent-turn/xai-core.d.ts +96 -0
  77. package/dist/activities/automations.d.ts +3 -1
  78. package/dist/activities/browser-deadline-checkpoint.d.ts +34 -0
  79. package/dist/activities/capabilities.d.ts +8 -20
  80. package/dist/activities/codemode-dispatcher.d.ts +20 -3
  81. package/dist/activities/codex-capacity.d.ts +1 -56
  82. package/dist/activities/codex-image-generation.d.ts +49 -3
  83. package/dist/activities/common.d.ts +3 -1
  84. package/dist/activities/context-compaction.d.ts +41 -2
  85. package/dist/activities/environment.d.ts +1 -19
  86. package/dist/activities/gmail-files.d.ts +50 -0
  87. package/dist/activities/goals.d.ts +1 -9
  88. package/dist/activities/incident-telemetry-authority.d.ts +5 -2
  89. package/dist/activities/incident-telemetry-preflight.d.ts +10 -3
  90. package/dist/activities/knowledge-indexing.d.ts +19 -0
  91. package/dist/activities/mcp-account-routes.d.ts +2 -21
  92. package/dist/activities/model-call-fact-reconciler.d.ts +34 -0
  93. package/dist/activities/open-suffix-resume.d.ts +15 -0
  94. package/dist/activities/parent-wake.d.ts +17 -12
  95. package/dist/activities/programmatic-approvals.d.ts +10 -0
  96. package/dist/activities/requester-unavailable-receipt.d.ts +8 -0
  97. package/dist/activities/retained-screenshots.d.ts +7 -2
  98. package/dist/activities/run-credential-renewal.d.ts +1 -0
  99. package/dist/activities/run-credentials.d.ts +16 -4
  100. package/dist/activities/run-input.d.ts +17 -0
  101. package/dist/activities/sandbox-lease.d.ts +132 -12
  102. package/dist/activities/scheduled-tasks.d.ts +4 -35
  103. package/dist/activities/session-archive.d.ts +58 -0
  104. package/dist/activities/session-state.d.ts +15 -3
  105. package/dist/activities/session-storage.d.ts +44 -0
  106. package/dist/activities/subscription-core-claude-waits.d.ts +2 -0
  107. package/dist/activities/subscription-core-codex-quota.d.ts +25 -0
  108. package/dist/activities/subscription-core-codex-waits.d.ts +153 -0
  109. package/dist/activities/subscription-core-image-operation.d.ts +29 -0
  110. package/dist/activities/subscription-core-usage-recheck.d.ts +49 -0
  111. package/dist/activities/subscription-core-wait-bindings.d.ts +3 -0
  112. package/dist/activities/subscription-core-xai-quota.d.ts +30 -0
  113. package/dist/activities/subscription-core-xai-waits.d.ts +2 -0
  114. package/dist/activities/types.d.ts +68 -5
  115. package/dist/activities/video-generation-admission.d.ts +2 -8
  116. package/dist/activities/video-generation-credential.d.ts +15 -12
  117. package/dist/activities/video-generation-subscription-core.d.ts +70 -0
  118. package/dist/activities/workspace-capture.d.ts +2 -0
  119. package/dist/activities/workspace-credential-provider.d.ts +47 -0
  120. package/dist/activities/xai-auth.d.ts +6 -18
  121. package/dist/activities/xai-image-generation.d.ts +22 -6
  122. package/dist/{activities-control-QA6OLRQY.js → activities-control-5IIVRXLA.js} +1569 -2883
  123. package/dist/activities-control-5IIVRXLA.js.map +1 -0
  124. package/dist/activities-control.d.ts +64 -4
  125. package/dist/{activities-turn-YVVKCGAK.js → activities-turn-FLYJOM54.js} +9300 -4403
  126. package/dist/activities-turn-FLYJOM54.js.map +1 -0
  127. package/dist/activities.d.ts +64 -4
  128. package/dist/artifact-materializer-entry.js +107 -36
  129. package/dist/artifact-materializer-entry.js.map +1 -1
  130. package/dist/artifact-outbox-entry.js +132 -61
  131. package/dist/artifact-outbox-entry.js.map +1 -1
  132. package/dist/browser-deadline-checkpoint-contract.d.ts +2 -0
  133. package/dist/{chunk-GDCLDKSH.js → chunk-24GP3BX5.js} +79 -72
  134. package/dist/chunk-24GP3BX5.js.map +1 -0
  135. package/dist/{chunk-RAMNYSAW.js → chunk-4ER3YXOT.js} +22 -4
  136. package/dist/chunk-4ER3YXOT.js.map +1 -0
  137. package/dist/{chunk-I7HKKMUJ.js → chunk-5NNS4327.js} +734 -58
  138. package/dist/chunk-5NNS4327.js.map +1 -0
  139. package/dist/chunk-MVESOYFC.js +3746 -0
  140. package/dist/chunk-MVESOYFC.js.map +1 -0
  141. package/dist/{chunk-M3NVMF2V.js → chunk-N57B3PJ5.js} +2307 -3951
  142. package/dist/chunk-N57B3PJ5.js.map +1 -0
  143. package/dist/chunk-NQDVJ6RI.js +2823 -0
  144. package/dist/chunk-NQDVJ6RI.js.map +1 -0
  145. package/dist/chunk-O7UPBWXK.js +79 -0
  146. package/dist/chunk-O7UPBWXK.js.map +1 -0
  147. package/dist/chunk-W2QSM5HR.js +414 -0
  148. package/dist/chunk-W2QSM5HR.js.map +1 -0
  149. package/dist/chunk-ZN3XJR33.js +227 -0
  150. package/dist/chunk-ZN3XJR33.js.map +1 -0
  151. package/dist/editable-artifact-outbox-dispatcher.d.ts +12 -1
  152. package/dist/editable-artifact-outbox-service.d.ts +3 -1
  153. package/dist/host-export-pump.d.ts +3 -1
  154. package/dist/host-export.d.ts +2 -2
  155. package/dist/host-export.js +1 -1
  156. package/dist/http.d.ts +1 -1
  157. package/dist/index.d.ts +49 -48
  158. package/dist/index.js +835 -256
  159. package/dist/index.js.map +1 -1
  160. package/dist/internal-maintenance.d.ts +63 -0
  161. package/dist/maintenance-cadence.d.ts +43 -0
  162. package/dist/observability-metrics.d.ts +293 -24
  163. package/dist/onepassword-vault-provider.d.ts +7 -0
  164. package/dist/parent-wake-PCLH7A3Y.js +24 -0
  165. package/dist/parent-wake-PCLH7A3Y.js.map +1 -0
  166. package/dist/personal-github-git-credentials.d.ts +1 -1
  167. package/dist/readiness-checks.d.ts +39 -0
  168. package/dist/retained-process-retry.d.ts +7 -0
  169. package/dist/sandbox-lease-BJYU72N3.js +84 -0
  170. package/dist/sandbox-lease-BJYU72N3.js.map +1 -0
  171. package/dist/sandbox-reaper-contract.d.ts +25 -0
  172. package/dist/sandbox-resume.d.ts +72 -4
  173. package/dist/sandbox-routing.d.ts +4 -2
  174. package/dist/session-event-fanout.d.ts +6 -0
  175. package/dist/site-auth-maintenance-WK3MR2PV.js +12 -0
  176. package/dist/site-auth-maintenance-WK3MR2PV.js.map +1 -0
  177. package/dist/telemetry-scheduler.d.ts +14 -0
  178. package/dist/temporal-runtime-logger.d.ts +22 -0
  179. package/dist/turn-task-queue-reader.d.ts +18 -0
  180. package/dist/turn-worker-activity-telemetry.d.ts +47 -0
  181. package/dist/worker-service-lifecycle.d.ts +12 -0
  182. package/dist/workflow-bundle.js +468 -71
  183. package/dist/workflows/activities.d.ts +1 -1
  184. package/dist/workflows/browser-deadline-checkpoint.d.ts +10 -0
  185. package/dist/workflows/sandbox-reaper.d.ts +10 -1
  186. package/dist/workflows/scheduled-tasks.d.ts +4 -0
  187. package/dist/workflows/session-storage.d.ts +2 -0
  188. package/dist/workflows/session.d.ts +36 -0
  189. package/dist/workflows/site-auth-maintenance.d.ts +2 -1
  190. package/dist/workflows/workflow-wake.d.ts +14 -3
  191. package/dist/workflows.d.ts +3 -1
  192. package/package.json +26 -20
  193. package/src/activities/agent-run-admission.ts +1 -82
  194. package/src/activities/agent-turn/admission.ts +175 -24
  195. package/src/activities/agent-turn/agent-build.ts +226 -145
  196. package/src/activities/agent-turn/claim.ts +363 -64
  197. package/src/activities/agent-turn/claude-core.ts +587 -0
  198. package/src/activities/agent-turn/code-search.ts +275 -0
  199. package/src/activities/agent-turn/codex-capacity.ts +30 -757
  200. package/src/activities/agent-turn/codex-core-capacity.ts +190 -0
  201. package/src/activities/agent-turn/codex-core-claim.ts +83 -0
  202. package/src/activities/agent-turn/codex-core-errors.ts +308 -0
  203. package/src/activities/agent-turn/codex-core-failover.ts +73 -0
  204. package/src/activities/agent-turn/codex-core-requests.ts +86 -0
  205. package/src/activities/agent-turn/codex-core-settlement.ts +263 -0
  206. package/src/activities/agent-turn/codex-credit-policy.ts +247 -0
  207. package/src/activities/agent-turn/codex-plan-entitlement.ts +254 -0
  208. package/src/activities/agent-turn/codex-usage-policy.ts +2 -0
  209. package/src/activities/agent-turn/codex.ts +8 -76
  210. package/src/activities/agent-turn/compaction-interruption.ts +56 -0
  211. package/src/activities/agent-turn/compaction-prep.ts +249 -36
  212. package/src/activities/agent-turn/credential-leases.ts +269 -214
  213. package/src/activities/agent-turn/credential-restriction.ts +14 -0
  214. package/src/activities/agent-turn/errors.ts +1152 -82
  215. package/src/activities/agent-turn/failure-settlement.ts +879 -886
  216. package/src/activities/agent-turn/final-reply.ts +46 -0
  217. package/src/activities/agent-turn/finalization-monitor.ts +17 -5
  218. package/src/activities/agent-turn/finalization.ts +107 -88
  219. package/src/activities/agent-turn/github-repository-bindings.ts +3 -1
  220. package/src/activities/agent-turn/governance-model.ts +90 -22
  221. package/src/activities/agent-turn/history-sink.ts +42 -12
  222. package/src/activities/agent-turn/history.ts +25 -5
  223. package/src/activities/agent-turn/input-wait-reply.ts +139 -0
  224. package/src/activities/agent-turn/knowledge-source-tools.ts +2 -0
  225. package/src/activities/agent-turn/meaningful-output.ts +44 -0
  226. package/src/activities/agent-turn/media-artifacts.ts +3 -1
  227. package/src/activities/agent-turn/model-call-admission.ts +114 -0
  228. package/src/activities/agent-turn/model-usage.ts +299 -233
  229. package/src/activities/agent-turn/model-wire-dispatch.ts +27 -0
  230. package/src/activities/agent-turn/optional-repositories.ts +224 -0
  231. package/src/activities/agent-turn/prompt-tool-availability.ts +27 -0
  232. package/src/activities/agent-turn/provider-dispatch-barrier.ts +22 -0
  233. package/src/activities/agent-turn/provider-recovery-copy.ts +76 -0
  234. package/src/activities/agent-turn/provider-recovery-metrics.ts +64 -0
  235. package/src/activities/agent-turn/provider-recovery-policy.ts +25 -0
  236. package/src/activities/agent-turn/quiescence.ts +7 -7
  237. package/src/activities/agent-turn/recovery-warning.ts +6 -8
  238. package/src/activities/agent-turn/refresh-credentials.ts +44 -0
  239. package/src/activities/agent-turn/run-credentials.ts +124 -76
  240. package/src/activities/agent-turn/run.ts +501 -112
  241. package/src/activities/agent-turn/sandbox-establish.ts +152 -75
  242. package/src/activities/agent-turn/sandbox-provision.ts +54 -1
  243. package/src/activities/agent-turn/sandbox-route.ts +4 -1
  244. package/src/activities/agent-turn/sandbox-runtime.ts +319 -11
  245. package/src/activities/agent-turn/secret-resolver.ts +155 -0
  246. package/src/activities/agent-turn/session-title.ts +177 -12
  247. package/src/activities/agent-turn/session-usage-custody.ts +170 -0
  248. package/src/activities/agent-turn/skill-checkout.ts +111 -24
  249. package/src/activities/agent-turn/skill-install.ts +1 -1
  250. package/src/activities/agent-turn/skill-read.ts +374 -28
  251. package/src/activities/agent-turn/skill-save.ts +35 -7
  252. package/src/activities/agent-turn/skill-search.ts +9 -0
  253. package/src/activities/agent-turn/skill-selection.ts +4 -0
  254. package/src/activities/agent-turn/skill-tools.ts +208 -21
  255. package/src/activities/agent-turn/skill-transfer.ts +68 -23
  256. package/src/activities/agent-turn/stream-attempt.ts +634 -111
  257. package/src/activities/agent-turn/subscription-capacity-arming.ts +81 -0
  258. package/src/activities/agent-turn/subscription-core-capacity.ts +439 -0
  259. package/src/activities/agent-turn/subscription-core-failover.ts +229 -0
  260. package/src/activities/agent-turn/subscription-core-placed.ts +37 -0
  261. package/src/activities/agent-turn/subscription-core-requests.ts +271 -0
  262. package/src/activities/agent-turn/subscription-core-settlement.ts +234 -0
  263. package/src/activities/agent-turn/subscription-lease.ts +140 -0
  264. package/src/activities/agent-turn/subscription-serving-capacity.ts +195 -0
  265. package/src/activities/agent-turn/subscription-serving-catalog.ts +71 -0
  266. package/src/activities/agent-turn/subscription-serving-claim.ts +178 -0
  267. package/src/activities/agent-turn/subscription-serving-providers.ts +15 -0
  268. package/src/activities/agent-turn/tool-environment.ts +384 -292
  269. package/src/activities/agent-turn/tool-policy.ts +104 -4
  270. package/src/activities/agent-turn/tool-result-spill.ts +1 -0
  271. package/src/activities/agent-turn/turn-context.ts +124 -8
  272. package/src/activities/agent-turn/web-search.ts +431 -0
  273. package/src/activities/agent-turn/xai-core.ts +301 -0
  274. package/src/activities/automations.ts +81 -6
  275. package/src/activities/browser-deadline-checkpoint.ts +297 -0
  276. package/src/activities/capabilities.ts +53 -213
  277. package/src/activities/codemode-dispatcher.ts +236 -14
  278. package/src/activities/codex-capacity.ts +27 -380
  279. package/src/activities/codex-image-generation.ts +252 -42
  280. package/src/activities/common.ts +12 -0
  281. package/src/activities/connector-attachments.ts +3 -1
  282. package/src/activities/context-compaction.ts +182 -21
  283. package/src/activities/environment.ts +18 -106
  284. package/src/activities/gmail-files.ts +108 -0
  285. package/src/activities/goals.ts +120 -204
  286. package/src/activities/image-generation-operation.ts +1 -1
  287. package/src/activities/incident-telemetry-authority.ts +80 -50
  288. package/src/activities/incident-telemetry-preflight.ts +27 -15
  289. package/src/activities/knowledge-indexing.ts +287 -17
  290. package/src/activities/knowledge-source-sync.ts +10 -0
  291. package/src/activities/mcp-account-routes.ts +2 -124
  292. package/src/activities/model-call-fact-reconciler.ts +112 -0
  293. package/src/activities/open-suffix-resume.ts +122 -88
  294. package/src/activities/parent-wake.ts +89 -21
  295. package/src/activities/programmatic-approvals.ts +26 -0
  296. package/src/activities/requester-unavailable-receipt.ts +14 -0
  297. package/src/activities/retained-screenshots.ts +135 -24
  298. package/src/activities/run-credential-renewal.ts +13 -1
  299. package/src/activities/run-credentials.ts +61 -19
  300. package/src/activities/run-input.ts +124 -9
  301. package/src/activities/sandbox-lease.ts +1615 -73
  302. package/src/activities/scheduled-tasks.ts +780 -147
  303. package/src/activities/session-archive.ts +382 -0
  304. package/src/activities/session-state.ts +219 -10
  305. package/src/activities/session-storage.ts +124 -0
  306. package/src/activities/site-auth-maintenance.ts +5 -2
  307. package/src/activities/subscription-core-claude-waits.ts +49 -0
  308. package/src/activities/subscription-core-codex-quota.ts +46 -0
  309. package/src/activities/subscription-core-codex-waits.ts +488 -0
  310. package/src/activities/subscription-core-image-operation.ts +126 -0
  311. package/src/activities/subscription-core-usage-recheck.ts +146 -0
  312. package/src/activities/subscription-core-wait-bindings.ts +12 -0
  313. package/src/activities/subscription-core-xai-quota.ts +85 -0
  314. package/src/activities/subscription-core-xai-waits.ts +48 -0
  315. package/src/activities/types.ts +85 -9
  316. package/src/activities/video-generation-admission.ts +1 -36
  317. package/src/activities/video-generation-credential.ts +38 -56
  318. package/src/activities/video-generation-reconciliation.ts +150 -131
  319. package/src/activities/video-generation-subscription-core.ts +180 -0
  320. package/src/activities/workspace-capture.ts +13 -2
  321. package/src/activities/workspace-credential-provider.ts +302 -0
  322. package/src/activities/xai-auth.ts +34 -112
  323. package/src/activities/xai-image-generation.ts +84 -36
  324. package/src/activities-control.ts +8 -0
  325. package/src/activities-turn.ts +5 -0
  326. package/src/activities.ts +17 -0
  327. package/src/activity-services.ts +29 -4
  328. package/src/browser-deadline-checkpoint-contract.ts +5 -0
  329. package/src/editable-artifact-hint-broker.ts +3 -0
  330. package/src/editable-artifact-materializer-service.ts +85 -39
  331. package/src/editable-artifact-materializer-subprocess.ts +47 -2
  332. package/src/editable-artifact-outbox-dispatcher.ts +107 -46
  333. package/src/editable-artifact-outbox-service.ts +55 -25
  334. package/src/github-rest-mcp.ts +1 -1
  335. package/src/host-export-pump.ts +26 -4
  336. package/src/host-export.ts +4 -1
  337. package/src/http.ts +4 -2
  338. package/src/index.ts +222 -282
  339. package/src/internal-maintenance.ts +347 -0
  340. package/src/maintenance-cadence.ts +156 -0
  341. package/src/observability-metrics.ts +1173 -73
  342. package/src/onepassword-vault-provider.ts +11 -0
  343. package/src/personal-github-git-credentials.ts +3 -1
  344. package/src/pr-review-credentials.ts +1 -1
  345. package/src/readiness-checks.ts +113 -0
  346. package/src/retained-process-retry.ts +36 -0
  347. package/src/sandbox-reaper-contract.ts +33 -0
  348. package/src/sandbox-resume.ts +444 -73
  349. package/src/sandbox-routing.ts +230 -75
  350. package/src/session-event-fanout.ts +23 -0
  351. package/src/telemetry-scheduler.ts +53 -0
  352. package/src/temporal-runtime-logger.ts +44 -0
  353. package/src/turn-task-queue-reader.ts +110 -0
  354. package/src/turn-worker-activity-telemetry.ts +209 -0
  355. package/src/worker-service-lifecycle.ts +54 -1
  356. package/src/workflows/activities.ts +16 -1
  357. package/src/workflows/browser-deadline-checkpoint.ts +55 -0
  358. package/src/workflows/file-upload-reaper.ts +2 -0
  359. package/src/workflows/sandbox-reaper.ts +88 -0
  360. package/src/workflows/scheduled-tasks.ts +26 -13
  361. package/src/workflows/session-storage.ts +19 -0
  362. package/src/workflows/session.ts +238 -33
  363. package/src/workflows/site-auth-maintenance.ts +2 -1
  364. package/src/workflows/workflow-wake.ts +26 -4
  365. package/src/workflows.ts +7 -0
  366. package/dist/activities/agent-turn/xai-capacity.d.ts +0 -2
  367. package/dist/activities/codex-fleet-shadow.d.ts +0 -74
  368. package/dist/activities/codex-rotation.d.ts +0 -200
  369. package/dist/activities/xai-quota.d.ts +0 -3
  370. package/dist/activities-control-QA6OLRQY.js.map +0 -1
  371. package/dist/activities-turn-YVVKCGAK.js.map +0 -1
  372. package/dist/chunk-GDCLDKSH.js.map +0 -1
  373. package/dist/chunk-I7HKKMUJ.js.map +0 -1
  374. package/dist/chunk-M3NVMF2V.js.map +0 -1
  375. package/dist/chunk-RAMNYSAW.js.map +0 -1
  376. package/src/activities/agent-turn/xai-capacity.ts +0 -257
  377. package/src/activities/codex-fleet-shadow.ts +0 -306
  378. package/src/activities/codex-rotation.ts +0 -685
  379. package/src/activities/xai-quota.ts +0 -35
@@ -1,685 +0,0 @@
1
- // Multi-account P3 — the PURE rotation ranker. Zero I/O: no provider calls, no
2
- // decrypts, no db. It consumes the already-loaded, metadata-only account list
3
- // (cached usage columns + the exhausted_until cooldown column) and returns the
4
- // account a turn should run on. The two call sites (turn-start pre-emption and
5
- // the reactive 429 catch in agent-turn.ts) feed its result into the unchanged
6
- // `selectCodexCredentialForTurn` precedence gate (pin > active). Keeping the
7
- // decision pure makes the whole rotation correctness story unit-testable in
8
- // isolation (see codex-rotation.test.ts).
9
- import type {
10
- CodexAccountStatus,
11
- CodexCredentialLeaseSelectionContext,
12
- CodexLeaseAccountStatus,
13
- CodexPinSource,
14
- } from "@opengeni/db";
15
- import { connectionModelAllowed } from "@opengeni/db";
16
-
17
- export type CodexRotationAccount = CodexAccountStatus | CodexLeaseAccountStatus;
18
-
19
- /** Capacity metadata worth an authoritative live read before/all through an idle. */
20
- export function codexAccountNeedsLiveCapacityRefresh(
21
- account: Pick<
22
- CodexAccountStatus,
23
- "primaryUsedPercent" | "secondaryUsedPercent" | "exhaustedUntil" | "exhaustedKind"
24
- >,
25
- _now: Date,
26
- ): boolean {
27
- return (
28
- (account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||
29
- (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||
30
- (account.exhaustedKind === "quota" && account.exhaustedUntil !== null)
31
- );
32
- }
33
-
34
- export type CodexRotationStrategy =
35
- | "most_remaining"
36
- | "round_robin"
37
- | "drain_then_next"
38
- | "sharded";
39
-
40
- /**
41
- * The ONE strategy rotation-enabled workspaces run: sticky-sharded. The legacy
42
- * strategies are all strictly dominated post-cache-affinity — session
43
- * stickiness is worth ~half the prompt-cache hit rate, and round_robin /
44
- * most_remaining churn accounts per turn while drain_then_next concentrates
45
- * every concurrent session on ONE account (the measured concurrency-eviction
46
- * failure sharding replaced). Stored `rotation_strategy` values are therefore
47
- * NORMALIZED here at every read site: legacy values (and any future unknown
48
- * string) behave as "sharded". The column and the legacy branch code are kept
49
- * intact for old-binary rollback safety — they are simply unreachable through
50
- * this normalization. The API accepts-but-ignores strategy writes for the same
51
- * reason (no SDK caller breaks). User-facing choice is intentionally gone: the
52
- * remaining real intents are rotation on/off, per-account allocator
53
- * include/exclude, and manual pins — not algorithm selection.
54
- */
55
- export function effectiveRotationStrategy(_stored: string): CodexRotationStrategy {
56
- return "sharded";
57
- }
58
-
59
- /**
60
- * How a session's codex pin governs THIS turn's account selection (pure). Encodes the
61
- * policy-pin LIFECYCLE rule: a 'policy' pin is meaningful ONLY while the sharded policy
62
- * is active.
63
- * • "manual" — a manual pin: honored under EVERY strategy; never moved or cleared.
64
- * • "sharded" — the sharded policy is active and the pin is non-manual: assign / keep
65
- * / re-shard the deterministic home (covers an unpinned first turn AND
66
- * an existing policy pin).
67
- * • "clearStale" — a 'policy' pin while the sharded policy is NOT active: IGNORE it
68
- * (never honor it as a sticky pin — that is the no-escape trap) and
69
- * clear it lazily so the session converges to the active strategy.
70
- * • "unpinned" — no pin (or none that applies): follow the active strategy / workspace
71
- * active pointer, unchanged.
72
- */
73
- export type CodexPinDisposition = "manual" | "sharded" | "clearStale" | "unpinned";
74
-
75
- /** Classify a session's codex pin against the active rotation regime (see {@link CodexPinDisposition}). */
76
- export function classifyCodexPin(args: {
77
- pinnedCredentialId: string | null;
78
- pinSource: CodexPinSource | null;
79
- strategy: CodexRotationStrategy;
80
- rotationEnabled: boolean;
81
- }): CodexPinDisposition {
82
- const { pinnedCredentialId, pinSource, strategy, rotationEnabled } = args;
83
- const pinned = pinnedCredentialId != null;
84
- // A manual pin is sacrosanct under every strategy — checked FIRST so sharded never
85
- // touches it. DEFENSE-IN-DEPTH (fail-safe toward sacredness): a pin whose source is
86
- // anything OTHER than the explicit 'policy' — including a NULL source (a pre-backfill
87
- // row, or any pin an unforeseen path wrote without labeling it) — is treated as
88
- // MANUAL. An unlabeled pin must NEVER be policy-moved; only an explicitly-'policy' pin
89
- // is re-shardable.
90
- if (pinned && pinSource !== "policy") {
91
- return "manual";
92
- }
93
- const shardedActive = rotationEnabled && effectiveRotationStrategy(strategy) === "sharded";
94
- if (shardedActive) {
95
- return "sharded";
96
- }
97
- // A policy pin outside the sharded regime is stale → clear it.
98
- if (pinned && pinSource === "policy") {
99
- return "clearStale";
100
- }
101
- return "unpinned";
102
- }
103
-
104
- export type RotationDecision =
105
- // The chosen account. `moved` ⇒ it differs from the current active pointer, so
106
- // the caller must persist the pointer move (and the switch is a "rotation").
107
- | { kind: "active"; credentialId: string; moved: boolean }
108
- // Every eligible account is capped/cooling: idle until the soonest instant ANY
109
- // account clears every blocking condition (the multi-account generalization of
110
- // the single-account idle-until-reset).
111
- | { kind: "allCapped"; earliestResetAt: Date }
112
- // No connected accounts at all (preserves today's relogin-fail path).
113
- | { kind: "none" };
114
-
115
- export type CodexTurnLeaseDecision =
116
- | RotationDecision
117
- // The user's manual pin or rotation-off active pointer names a connected row
118
- // that is disabled for NEW allocations. This is policy-constrained capacity,
119
- // not a disconnected-account relogin failure: the accepted turn must wait
120
- // until the row is re-enabled or the governing policy changes.
121
- | { kind: "allocatorDisabled"; credentialId: string };
122
-
123
- export type CodexTurnLeaseSelection = {
124
- credentialId: string | null;
125
- decision: CodexTurnLeaseDecision;
126
- /** Policy/manual homes never move the workspace-global legacy pointer. */
127
- advanceActivePointer?: boolean;
128
- };
129
-
130
- // Invariant 4 (NO THRASH / BOUNDED) safety floors. An all-capped idle MUST be a
131
- // positive, bounded wait — a null / elapsed / unknown reset can NEVER collapse it
132
- // into a 0 or a past instant (which the caller would turn into a 0 continueDelayMs
133
- // and a tight re-dispatch loop that hammers CPU/DB and never runs the model, so the
134
- // stale usage cache never self-heals).
135
- /** The minimum all-capped idle: continueDelayMs is clamped to at least this (never 0). */
136
- export const MIN_IDLE_MS = 60_000; // 60s
137
- /**
138
- * Cooldown applied to an exhausted account whose cached reset is null / unknown
139
- * / already-elapsed (the turn hot path never refreshes usage, so a capped window's
140
- * reset reads stale). Treating it as "available after a default cooldown" keeps
141
- * availableAt — and therefore earliestReset — ALWAYS in the future.
142
- */
143
- export const DEFAULT_RESET_COOLDOWN_MS = 60_000; // 60s
144
- /** Cached provider usage becomes unavailable only at actual exhaustion. */
145
- export const CODEX_USAGE_EXHAUSTED_PCT = 100;
146
-
147
- function effectiveWindowUsed(usedPercent: number | null, resetAt: Date | null, now: Date): number {
148
- // A completed provider window is eligible immediately even if its last cache
149
- // sample still says 100%. This is the five-hour reset boundary—not a TTL
150
- // heuristic—and avoids stranding a reset subscription while another remains
151
- // healthy. A future/unknown reset keeps the cached percentage authoritative.
152
- return resetAt && resetAt.getTime() <= now.getTime() ? 0 : (usedPercent ?? 0);
153
- }
154
-
155
- /** The worse live window: weekly binds as hard as 5h. */
156
- function bindingUsedPct(acct: CodexRotationAccount, now: Date): number {
157
- return Math.max(
158
- effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now),
159
- effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now),
160
- );
161
- }
162
-
163
- /**
164
- * Remaining quota across the binding window — the P3 rotation key. Mirrors
165
- * buildCodexUsageWindowFromCache's `remaining = 100 - percent`, taking the MIN
166
- * across both windows (the scarcer of 5h/weekly). null percent ⇒ 100 remaining.
167
- */
168
- function bindingRemaining(acct: CodexRotationAccount, now: Date): number {
169
- const primaryRemaining =
170
- 100 - effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now);
171
- const secondaryRemaining =
172
- 100 - effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now);
173
- return Math.min(primaryRemaining, secondaryRemaining);
174
- }
175
-
176
- function cooling(acct: CodexRotationAccount, now: Date): boolean {
177
- return acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > now.getTime();
178
- }
179
-
180
- /**
181
- * Healthy for an already-leased/in-flight turn = connected/usable (status
182
- * "active", excludes needs_relogin/error), not cooling, and not exhausted in
183
- * either provider window. Allocator eligibility is
184
- * deliberately separate so disabling NEW work cannot break an existing live lease.
185
- */
186
- export function isCodexCredentialHealthy(acct: CodexRotationAccount, now: Date): boolean {
187
- return (
188
- acct.status === "active" &&
189
- !cooling(acct, now) &&
190
- bindingUsedPct(acct, now) < CODEX_USAGE_EXHAUSTED_PCT
191
- );
192
- }
193
-
194
- /** New automatic allocation requires both health and explicit allocator eligibility. */
195
- export function isCodexCredentialEligible(acct: CodexRotationAccount, now: Date): boolean {
196
- return acct.allocatorEnabled && isCodexCredentialHealthy(acct, now);
197
- }
198
-
199
- /**
200
- * Public eligibility predicate (same definition as the private `eligible`): an
201
- * account is usable this turn iff it is connected/active, not cooling, and below
202
- * actual exhaustion on both windows. The worker's sharded home
203
- * health-check uses this to decide whether a session's existing policy pin is still
204
- * a valid home or must be re-sharded.
205
- */
206
- export function isCodexAccountEligible(acct: CodexRotationAccount, now: Date): boolean {
207
- return isCodexCredentialEligible(acct, now);
208
- }
209
-
210
- /** Deterministic 32-bit FNV-1a over a UTF-16 code-unit stream. Pure, allocation-free. */
211
- function fnv1a32(input: string): number {
212
- let hash = 0x811c9dc5;
213
- for (let i = 0; i < input.length; i++) {
214
- hash ^= input.charCodeAt(i);
215
- // 32-bit FNV prime multiply via Math.imul; `>>> 0` keeps it unsigned.
216
- hash = Math.imul(hash, 0x01000193);
217
- }
218
- return hash >>> 0;
219
- }
220
-
221
- /**
222
- * Session-sharded HOME account (AM-6): the deterministic account a session runs on
223
- * under the "sharded" strategy — `stableAccountList[ hash(sessionId) % N ]` over the
224
- * ELIGIBLE (connected, not cooling, not exhausted) accounts in stable created_at
225
- * order (`listCodexAccountStatuses`).
226
- *
227
- * Why deterministic hash over "least-loaded by session count" (AM-6): it needs ZERO
228
- * coordination — every worker computes the same home for a given (sessionId,
229
- * eligible-set), so a burst of concurrent first-turns can't all read the same
230
- * "least-loaded" account and stampede it (read-then-write skew), and there is no
231
- * shared round-robin cursor to contend on. It is balanced in expectation.
232
- *
233
- * Re-shard (AM-5): pass the just-capped account as already-cooling (or simply let it
234
- * fall over its threshold) and this reshuffles the SURVIVORS deterministically — the
235
- * sessions that shared a capped account spread across the remaining pool by their own
236
- * hashes instead of all re-concentrating on one first-eligible failover.
237
- *
238
- * Returns null when NO account is eligible (the caller idles until reset).
239
- */
240
- export function shardCredentialForSession(args: {
241
- sessionId: string;
242
- accounts: CodexRotationAccount[];
243
- now: Date;
244
- }): string | null {
245
- const { sessionId, accounts, now } = args;
246
- const eligibles = accounts.filter((acct) => isCodexCredentialEligible(acct, now));
247
- if (eligibles.length === 0) {
248
- return null;
249
- }
250
- const index = fnv1a32(sessionId) % eligibles.length;
251
- return eligibles[index]!.id;
252
- }
253
-
254
- /** earliestResetAt across ALL connected accounts — exported for the sharded all-capped idle. */
255
- export function earliestCodexReset(accounts: CodexRotationAccount[], now: Date): Date {
256
- return earliestReset(accounts, now);
257
- }
258
-
259
- /**
260
- * The proactive SHARDED home decision (pure — zero I/O, like {@link chooseRotationActive}).
261
- * Decides the account a session should run on THIS turn under the "sharded" strategy,
262
- * given its current POLICY pin (null on the first turn) and the accounts snapshot:
263
- *
264
- * - keepPin: the current policy pin is still ELIGIBLE → run there, no rewrite. This
265
- * is the steady-state cache-warm path (a session stays on its one home account).
266
- * - reshard: no policy pin yet (first-turn lazy assignment, AM-7) OR the policy pin
267
- * is capped/ineligible (proactive re-shard, AM-4) → deterministically shard over the
268
- * ELIGIBLE set (AM-6) and durably (re)write the pin (`rewritePin:true`, AM-3/AM-5).
269
- * - allCapped: no account is eligible → the caller idles until the earliest reset.
270
- *
271
- * A MANUAL pin is handled by the CALLER (it never reaches here); this function only
272
- * governs policy homes. Pure so the assignment/re-shard/keep logic is unit-testable
273
- * without a worker/db env; the caller wraps it with a self-heal usage refresh between
274
- * two evaluations exactly like chooseRotationActive's allCapped path.
275
- */
276
- export function chooseShardedHome(args: {
277
- sessionId: string;
278
- currentPolicyPin: string | null;
279
- accounts: CodexRotationAccount[];
280
- now: Date;
281
- }):
282
- | { kind: "home"; credentialId: string; rewritePin: boolean }
283
- | { kind: "allCapped"; earliestResetAt: Date } {
284
- const { sessionId, currentPolicyPin, accounts, now } = args;
285
- const pinRow = currentPolicyPin
286
- ? (accounts.find((acct) => acct.id === currentPolicyPin) ?? null)
287
- : null;
288
- if (pinRow && isCodexCredentialEligible(pinRow, now)) {
289
- return { kind: "home", credentialId: currentPolicyPin!, rewritePin: false };
290
- }
291
- const home = shardCredentialForSession({ sessionId, accounts, now });
292
- if (home == null) {
293
- return { kind: "allCapped", earliestResetAt: earliestReset(accounts, now) };
294
- }
295
- return { kind: "home", credentialId: home, rewritePin: true };
296
- }
297
-
298
- /**
299
- * The soonest instant `acct` clears EVERY blocking condition: its cooldown end,
300
- * and each window's reset (only when that window is at/over the threshold). The
301
- * literal multi-account generalization of #143's single-account resetsInSeconds.
302
- *
303
- * GUARANTEE (invariant 4): the result is ALWAYS in the future. A blocking window
304
- * whose cached reset is null / unknown / already-elapsed does NOT contribute a past
305
- * instant (the old EPOCH0 seed bug that made earliestReset land in 1970 → a 0
306
- * continueDelayMs → a tight idle loop). Such a window is treated as clearing after a
307
- * default cooldown (now + DEFAULT_RESET_COOLDOWN_MS), so the caller always idles a
308
- * bounded positive time and re-checks (which refreshes usage and self-heals).
309
- */
310
- export function availableAt(acct: CodexRotationAccount, now: Date): Date {
311
- const nowMs = now.getTime();
312
- // An unknown/elapsed block clears after a default cooldown, never in the past.
313
- const defaultClear = new Date(nowMs + DEFAULT_RESET_COOLDOWN_MS);
314
- const candidates: Date[] = [];
315
- // An active cooldown only blocks while it is still in the future; a past cooldown
316
- // self-clears (matches `cooling()`), so it must not pin availableAt to the past.
317
- if (acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > nowMs) {
318
- candidates.push(acct.exhaustedUntil);
319
- }
320
- const windowClear = (over: boolean, resetAt: Date | null | undefined) => {
321
- if (!over) return;
322
- // Over-threshold window: wait for its KNOWN future reset; a null/elapsed cached
323
- // reset is unknown → default cooldown (never a past instant).
324
- candidates.push(resetAt != null && resetAt.getTime() > nowMs ? resetAt : defaultClear);
325
- };
326
- windowClear(
327
- effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now) >=
328
- CODEX_USAGE_EXHAUSTED_PCT,
329
- acct.primaryResetAt,
330
- );
331
- windowClear(
332
- effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now) >=
333
- CODEX_USAGE_EXHAUSTED_PCT,
334
- acct.secondaryResetAt,
335
- );
336
- // Ineligible for a non-quota reason (needs_relogin / error) with no known block, or
337
- // a cleared cooldown: still idle a bounded cooldown before re-check — never the past.
338
- if (candidates.length === 0) {
339
- return defaultClear;
340
- }
341
- // Clears EVERY blocking condition ⇒ the MAX of the per-condition clear instants.
342
- return candidates.reduce((a, b) => (b.getTime() > a.getTime() ? b : a));
343
- }
344
-
345
- /** earliestResetAt across ALL connected accounts (min of each account's availableAt). */
346
- function earliestReset(accounts: CodexRotationAccount[], now: Date): Date {
347
- return accounts
348
- .map((acct) => availableAt(acct, now))
349
- .reduce((a, b) => (b.getTime() < a.getTime() ? b : a));
350
- }
351
-
352
- /**
353
- * Earliest provider/cooldown timestamp that is actually authoritative. The
354
- * ranker's `availableAt` deliberately synthesizes a positive default for
355
- * unknown/stale state; durable capacity waits must distinguish that bounded
356
- * refresh backoff from a real provider reset timer.
357
- */
358
- export function authoritativeCodexCapacityResetAt(
359
- accounts: CodexRotationAccount[],
360
- now: Date,
361
- ): Date | null {
362
- const future: Date[] = [];
363
- for (const account of accounts) {
364
- if (!account.allocatorEnabled || account.status !== "active") continue;
365
- if (account.exhaustedUntil && account.exhaustedUntil.getTime() > now.getTime()) {
366
- future.push(account.exhaustedUntil);
367
- }
368
- if (
369
- (account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&
370
- account.primaryResetAt &&
371
- account.primaryResetAt.getTime() > now.getTime()
372
- ) {
373
- future.push(account.primaryResetAt);
374
- }
375
- if (
376
- (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&
377
- account.secondaryResetAt &&
378
- account.secondaryResetAt.getTime() > now.getTime()
379
- ) {
380
- future.push(account.secondaryResetAt);
381
- }
382
- }
383
- if (future.length === 0) return null;
384
- return future.reduce((earliest, candidate) =>
385
- candidate.getTime() < earliest.getTime() ? candidate : earliest,
386
- );
387
- }
388
-
389
- /**
390
- * The bounded all-capped idle delay: clamp(earliestResetAt − now) into
391
- * [MIN_IDLE_MS, maxMs]. NEVER 0 and NEVER negative, so a null / elapsed / unknown
392
- * reset cannot collapse the hold into a tight re-dispatch loop (invariant 4). The two
393
- * agent-turn call sites (proactive turn-start + reactive 429) feed allCapped's
394
- * earliestResetAt through this before returning continueDelayMs.
395
- */
396
- export function computeIdleDelayMs(earliestResetAt: Date, now: Date, maxMs: number): number {
397
- const delta = earliestResetAt.getTime() - now.getTime();
398
- return Math.min(Math.max(delta, MIN_IDLE_MS), maxMs);
399
- }
400
-
401
- /**
402
- * THE pure rotation ranker. `accounts` arrives in stable created_at order
403
- * (listCodexAccountStatuses), which deterministically breaks ranking ties.
404
- */
405
- export function chooseRotationActive(args: {
406
- rotationStrategy: CodexRotationStrategy;
407
- activeCredentialId: string | null;
408
- priorCredentialId: string | null;
409
- accounts: CodexRotationAccount[];
410
- now: Date;
411
- }): RotationDecision {
412
- const { activeCredentialId, priorCredentialId, accounts, now } = args;
413
- // Normalize at the entry point: rotation-enabled ALWAYS behaves as sharded
414
- // (see effectiveRotationStrategy). args keeps the field so call sites and
415
- // tests can still express stored legacy values.
416
- const rotationStrategy = effectiveRotationStrategy(args.rotationStrategy);
417
- const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled);
418
-
419
- if (allocatableAccounts.length === 0) {
420
- return { kind: "none" };
421
- }
422
-
423
- const eligibles = allocatableAccounts.filter((acct) => isCodexCredentialEligible(acct, now));
424
-
425
- // The active pointer is a cursor/manual preference, NOT a sticky lease. In
426
- // particular, most_remaining must rank the whole eligible pool every turn;
427
- // keeping a healthy active account sticky was the production monopolization
428
- // defect fixed by credential allocator. drain_then_next remains the one explicitly sticky
429
- // strategy, and a manual pin is handled by the caller as explicit policy.
430
- const decide = (chosen: CodexRotationAccount | undefined): RotationDecision => {
431
- if (!chosen) {
432
- return {
433
- kind: "allCapped",
434
- earliestResetAt: earliestReset(allocatableAccounts, now),
435
- };
436
- }
437
- return {
438
- kind: "active",
439
- credentialId: chosen.id,
440
- moved: chosen.id !== activeCredentialId,
441
- };
442
- };
443
-
444
- if (rotationStrategy === "round_robin") {
445
- // Next eligible AFTER the prior account in list order (wrap around). When the
446
- // prior account isn't found, start from the head.
447
- if (eligibles.length === 0) {
448
- return {
449
- kind: "allCapped",
450
- earliestResetAt: earliestReset(allocatableAccounts, now),
451
- };
452
- }
453
- const priorIdx = priorCredentialId
454
- ? allocatableAccounts.findIndex((acct) => acct.id === priorCredentialId)
455
- : -1;
456
- const ordered =
457
- priorIdx >= 0
458
- ? [
459
- ...allocatableAccounts.slice(priorIdx + 1),
460
- ...allocatableAccounts.slice(0, priorIdx + 1),
461
- ]
462
- : allocatableAccounts;
463
- const chosen = ordered.find((acct) => isCodexCredentialEligible(acct, now));
464
- return decide(chosen);
465
- }
466
-
467
- if (rotationStrategy === "drain_then_next") {
468
- // Stay on the prior account while it is eligible (drain it), else first eligible.
469
- const priorRow = priorCredentialId
470
- ? accounts.find((acct) => acct.id === priorCredentialId)
471
- : undefined;
472
- if (priorRow && isCodexCredentialEligible(priorRow, now)) {
473
- return decide(priorRow);
474
- }
475
- return decide(eligibles[0]);
476
- }
477
-
478
- // most_remaining (default + the correctness path). Across the eligible set:
479
- // 1. least active leases (concurrent turns spread before quota metadata moves),
480
- // 2. most remaining binding quota,
481
- // 3. fewest historical selections,
482
- // 4. least-recently selected, then stable created_at/id input order.
483
- // Base CodexAccountStatus values (pure legacy tests/reactive rank) default the
484
- // lease/cursor metadata to zero/null, preserving deterministic stable ties.
485
- const activeLeases = (acct: CodexRotationAccount): number =>
486
- "activeLeaseCount" in acct ? acct.activeLeaseCount : 0;
487
- const selections = (acct: CodexRotationAccount): number =>
488
- "selectionCount" in acct ? acct.selectionCount : 0;
489
- const lastSelected = (acct: CodexRotationAccount): number =>
490
- "lastSelectedAt" in acct && acct.lastSelectedAt ? acct.lastSelectedAt.getTime() : 0;
491
- const chosen = eligibles.reduce<CodexRotationAccount | undefined>((best, acct) => {
492
- if (!best) {
493
- return acct;
494
- }
495
- if (activeLeases(acct) !== activeLeases(best)) {
496
- return activeLeases(acct) < activeLeases(best) ? acct : best;
497
- }
498
- if (bindingRemaining(acct, now) !== bindingRemaining(best, now)) {
499
- return bindingRemaining(acct, now) > bindingRemaining(best, now) ? acct : best;
500
- }
501
- if (selections(acct) !== selections(best)) {
502
- return selections(acct) < selections(best) ? acct : best;
503
- }
504
- return lastSelected(acct) < lastSelected(best) ? acct : best;
505
- }, undefined);
506
- return decide(chosen);
507
- }
508
-
509
- /**
510
- * Full pure policy at the transaction boundary. A live same-turn lease is
511
- * idempotent; manual and rotation-off policy preserve pin>pointer behavior; a
512
- * healthy pin wins only while eligible, so quota/auth quarantine cannot trap a
513
- * session on one subscription.
514
- */
515
- export function selectCodexCredentialLeaseForTurn<
516
- TPolicyScope = never,
517
- TUnavailableDiagnostic = never,
518
- >(args: {
519
- context: CodexCredentialLeaseSelectionContext<TPolicyScope, TUnavailableDiagnostic>;
520
- sessionId: string;
521
- sessionPinnedCredentialId: string | null;
522
- sessionPinSource: CodexPinSource | null;
523
- sessionLastCredentialId: string | null;
524
- now: Date;
525
- }): CodexTurnLeaseSelection {
526
- const { activeCredentialId, rotationEnabled, rotationStrategy, existingCredentialId } =
527
- args.context;
528
- if (args.context.failoverExhausted) {
529
- return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
530
- }
531
- const accounts = args.context.modelId
532
- ? args.context.accounts.filter((account) =>
533
- connectionModelAllowed(account.allowedModelIds, args.context.modelId!),
534
- )
535
- : args.context.accounts;
536
- const failedCredentialIds = new Set(args.context.failedCredentialIds ?? []);
537
- // Normalized: rotation-enabled always behaves as sharded (see
538
- // effectiveRotationStrategy); the stored value is only ever legacy residue.
539
- const strategy = effectiveRotationStrategy(rotationStrategy);
540
- const existing = existingCredentialId
541
- ? accounts.find((account) => account.id === existingCredentialId)
542
- : undefined;
543
- if (
544
- existing &&
545
- !failedCredentialIds.has(existing.id) &&
546
- isCodexCredentialHealthy(existing, args.now)
547
- ) {
548
- return {
549
- credentialId: existing.id,
550
- advanceActivePointer: false,
551
- decision: {
552
- kind: "active",
553
- credentialId: existing.id,
554
- moved: existing.id !== activeCredentialId,
555
- },
556
- };
557
- }
558
-
559
- const pinDisposition = classifyCodexPin({
560
- pinnedCredentialId: args.sessionPinnedCredentialId,
561
- pinSource: args.sessionPinSource,
562
- strategy,
563
- rotationEnabled,
564
- });
565
-
566
- // A manual pin is user intent, not a policy hint. Never silently fail it over.
567
- // We still reject allocator-disabled rows for a NEW turn; a healthy live
568
- // same-turn lease already returned above before this admission filter.
569
- if (pinDisposition === "manual" && args.sessionPinnedCredentialId) {
570
- const pinned = accounts.find((account) => account.id === args.sessionPinnedCredentialId);
571
- if (!pinned) {
572
- return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
573
- }
574
- if (failedCredentialIds.has(pinned.id)) {
575
- return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
576
- }
577
- if (!pinned.allocatorEnabled) {
578
- return {
579
- credentialId: null,
580
- decision: { kind: "allocatorDisabled", credentialId: pinned.id },
581
- advanceActivePointer: false,
582
- };
583
- }
584
- if (isCodexCredentialHealthy(pinned, args.now)) {
585
- return {
586
- credentialId: pinned.id,
587
- decision: { kind: "active", credentialId: pinned.id, moved: false },
588
- advanceActivePointer: false,
589
- };
590
- }
591
- return {
592
- credentialId: null,
593
- decision: {
594
- kind: "allCapped",
595
- earliestResetAt: availableAt(pinned, args.now),
596
- },
597
- advanceActivePointer: false,
598
- };
599
- }
600
-
601
- // Pin-policy homes compose with the credential allocator by sharding only the candidate list
602
- // handed to this selector. A future policy filter may therefore choose one
603
- // primary/fallback pool before this ranker runs; accounts from different pools
604
- // are never union-ranked here.
605
- if (pinDisposition === "sharded") {
606
- const unattemptedAccounts = accounts.filter((account) => !failedCredentialIds.has(account.id));
607
- if (unattemptedAccounts.length === 0) {
608
- return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
609
- }
610
- const shard = chooseShardedHome({
611
- sessionId: args.sessionId,
612
- currentPolicyPin: args.sessionPinSource === "policy" ? args.sessionPinnedCredentialId : null,
613
- accounts: unattemptedAccounts,
614
- now: args.now,
615
- });
616
- if (shard.kind === "allCapped") {
617
- return {
618
- credentialId: null,
619
- decision: shard,
620
- advanceActivePointer: false,
621
- };
622
- }
623
- return {
624
- credentialId: shard.credentialId,
625
- decision: {
626
- kind: "active",
627
- credentialId: shard.credentialId,
628
- moved: shard.credentialId !== activeCredentialId,
629
- },
630
- advanceActivePointer: false,
631
- };
632
- }
633
-
634
- // A stale policy pin is intentionally ignored here and cleared by the caller
635
- // after the atomic selection. Rotation-off/unpinned behavior otherwise keeps
636
- // the pre-lease pin > active-pointer contract. The pointer is preference, not
637
- // proof of capacity: rotation-off must wait on a capped pointer rather than
638
- // falsely admitting it or silently failing over to another subscription.
639
- if (!rotationEnabled) {
640
- const active = activeCredentialId
641
- ? accounts.find((account) => account.id === activeCredentialId)
642
- : undefined;
643
- if (!active) {
644
- return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
645
- }
646
- if (failedCredentialIds.has(active.id)) {
647
- return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
648
- }
649
- if (!active.allocatorEnabled) {
650
- return {
651
- credentialId: null,
652
- decision: { kind: "allocatorDisabled", credentialId: active.id },
653
- advanceActivePointer: false,
654
- };
655
- }
656
- if (!isCodexCredentialHealthy(active, args.now)) {
657
- return {
658
- credentialId: null,
659
- decision: { kind: "allCapped", earliestResetAt: availableAt(active, args.now) },
660
- advanceActivePointer: false,
661
- };
662
- }
663
- return {
664
- credentialId: active.id,
665
- decision: { kind: "active", credentialId: active.id, moved: false },
666
- advanceActivePointer: false,
667
- };
668
- }
669
-
670
- const priorId = args.sessionLastCredentialId ?? activeCredentialId;
671
- const unattemptedAccounts = accounts.filter((account) => !failedCredentialIds.has(account.id));
672
- const decision = chooseRotationActive({
673
- rotationStrategy: strategy,
674
- activeCredentialId,
675
- // Per-session continuity is the round-robin/drain cursor. Falling back to
676
- // the workspace pointer is only correct when this session has never run.
677
- priorCredentialId: priorId,
678
- accounts: unattemptedAccounts,
679
- now: args.now,
680
- });
681
- return {
682
- credentialId: decision.kind === "active" ? decision.credentialId : null,
683
- decision,
684
- };
685
- }